Initial team BPM workspace with managed connections, scanning and mail templates

This commit is contained in:
abaishu0730 committed 2026-10-16 22:34:11 +08:00
commit 34770ed338
101 files changed
+6499

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
* text=auto
*.cjs text eol=lf
*.js text eol=lf
*.json text eol=lf
*.md text eol=lf
*.html text eol=lf
*.css text eol=lf
*.yaml text eol=lf
*.cmd text eol=crlf
+37
View File
@@ -0,0 +1,37 @@
node_modules/
output/
config.json
extension/local-config.js
*.log
# Local credentials, authentication state and databases
.env
.env.*
!.env.example
*.sqlite
*.sqlite-*
*.db
*.db-*
*.enc
*.pem
*.key
*.pfx
*.p12
state.json
local-config.js
# Business exports and mail payloads
*.pdf
*.eml
*.msg
*.har
downloads/
backups/
playwright-report/
test-results/
# Editor and operating-system files
.vscode/
.idea/
Thumbs.db
.DS_Store
+109
View File
@@ -0,0 +1,109 @@
# 订单通知自动化工作台
面向团队的 BPM 订单工作台,提供业务日历、异常待办与转交、连接管理和运行监管配置;保留 Chrome 已登录订单页导出本地 PDF 的能力。
**项目最终目标**:无人值守识别匹配订单、按模板整理、上传 210、按产品线群组每天两次自动发送邮件。当前实现团队工作台与 BPM Web 登录、会话保存,订单处理规则后续确定;BPM 知会不自动处理。已接入新版门户只读扫描;上传、ZCode 和业务自动通知仍待接入。完整流程背景见 [无人值守系统设计](docs/unattended-system-design.md),登录实现见 [BPM 登录设计](docs/superpowers/specs/2026-10-16-bpm-login-design.md)。
## 设计与部署入口
- [设计要求(当前基准)](docs/design-requirements.md):功能范围、架构、数据存储、权限、验收和实施顺序。
- [部署说明](docs/deployment.md):安装、HTTPS、状态目录及备份。
- [扫描验证记录](docs/bpm-scan-verification-2026-10-16.md):最近验证及实际范围。
## Web 看板
1. 启动工具后,在部署机打开 http://127.0.0.1:18766 ,自行创建管理员账号(至少 12 位密码)。没有默认账号或默认密码。
2. 管理员在“团队账号”中创建同事账号;同事使用启动窗口打印的局域网地址访问。默认监听 0.0.0.0:18766,能否跨机器访问取决于路由和 Windows 防火墙;本工具不自动修改防火墙。
3. 业务日历支持月历、公司工作日/休息日/停发覆盖,采集与发送分别设置;可恢复每周默认规则,并预览发送时段。保存配置不会执行采集或发送。
4. 异常待办支持创建、认领、转交、提交验证、填写人工核验依据后关闭和重新打开;显示负责人和流转记录,防止多人同时覆盖。operator 可处理异常,viewer 只读,admin 可管理全部配置。
5. BPM 连接支持创建、账号托管、网页登录、检查保存、重启复用和停用。每个连接独立保存会话,由负责人或管理员操作。运行监管目前保存默认负责人、通知方式和重试上限草稿,不调用 ZCode、不执行恢复、不发送通知。
6. 邮箱管理支持公司 SMTP / IMAP、模板邮件收取、预览确认和历史版本;原 PDF 记录、每日两次时间、产品线群组、团队账号和操作记录继续可用。新版 BPM 扫描结果按流程到达日期分区;自动批量发信等待业务规则联调。
界面复用 [Tabler](https://tabler.io/admin-template) 免费开源版(@tabler/core 1.6.1),CSS/JS 全部在本机提供;MIT 原文见 licenses/Tabler-MIT.txt。青龙已有独立部署准备和 CLI,尚未接通业务,本次不启动它或复制其内部源码。
工作台账号、群组设置和原 PDF 记录保存在 `%LOCALAPPDATA%\OrderNotificationAutomation\dashboard\state.json`;业务日历、异常、连接与监管草稿保存在同级 `workspace` 目录的 SQLite 数据库中。邮箱、模板版本、原邮件、收信游标和测试发送记录保存在 `mail\mail.sqlite`,密码、原邮件和完整正文附件加密保存。BPM 会话加密保存在 `bpm-sessions`,主密钥经 Windows 当前运行用户 DPAPI 保护。数据留在运行机本地磁盘,不放项目所在的 Z: 共享盘。备份前停止服务并保护整个本地状态目录。工作台登录有效期为 30 天,每日活动自动续期;令牌哈希保存在 `dashboard\auth.sqlite`,服务重启后继续有效,退出登录立即撤销。已保存的 BPM 会话在同一 Windows 运行账号下恢复。
## 邮箱与邮件模板
1. 管理员进入 **邮箱管理 → 添加邮箱**,填写邮箱地址、SMTP / IMAP 服务器、端口、加密方式、登录账号和密码或授权码。支持 SSL/TLS 和必须升级加密的 STARTTLS,证书正常校验;不会猜测公司服务器参数。新邮箱默认暂停收信。
2. 填写 **允许提交模板的发件人**,保存后点击 **检查连接**。此操作验证 SMTP、IMAP 及 INBOX 访问,不发送邮件。确认正常后在管理邮箱中开启 **模板收信**,服务每分钟检查;也可点击 **立即收信**。
3. 从名单内的邮箱新建邮件发送到托管邮箱,主题为 `[模板][海外运营]订单通知 {{日期}}`;正文和附件作为对应产品线模板。`[模板]订单通知` 表示默认模板。回复/转发主题、范围标记不完整、未授权发件人和超出 10 MB 的邮件不导入。首次及邮箱 UID 变化只处理近 7 天邮件,保留该日期边界和 UID 游标;只读访问,不标记已读、不移动或删除邮件。
4. 打开 **模板与收件群组 → 预览并确认**,核对来源、发信标题、产品线、表格、图片和附件后点击 **确认生效**。可调整标题和产品线,或切换为纯文本编辑正文。旧版本留作历史;多人确认发生冲突时不覆盖新版本。名单控制导入,管理员确认后才生效。
5. 支持明确变量 `{{产品线}}`、`{{订单号}}`、`{{日期}}`、`{{订单列表}}`,不执行模板表达式。HTML 预览隔离,阻断脚本及外链图片;保留原 EML,管理员可下载原邮件与附件。邮件中的 To/Cc 不会修改业务收件群组。
6. 已生效模板可点击 **发送测试到本邮箱** 并确认目标。使用真实 SMTP 发送到托管邮箱自身,先记录发送任务,不自动重试不确定结果。此操作不会发给产品线群组。批量订单发信在后续业务规则接入。
旧模板草稿首次启动迁为待确认版本,确认时选择实际托管邮箱。邮箱维护须从部署机回环地址或已配置的 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,版本已锁定。公司邮箱真实连接需管理员录入参数后检查。
## BPM 登录
### 自动扫描与流程到达记录
在 **订单与导出记录 → 流程到达记录** 查看,每个到达日期单独一个分区,按北京时间倒序展示,可按连接及关键字查询、折叠日期、加载更早日期。PDF 导出记录保留在同页另一标签。
默认每 5 分钟通过新版门户列表 API 扫描已连接账号,遵循业务日历的“采集”开关。管理员可在“扫描设置”调整间隔、暂停或开启;管理员和连接负责人可“立即扫描”,手动扫描不受日历限制。当前待阅列表作为临时采集来源,保留真实流程名,后续按业务表格配置流程范围,不标记已阅或审批。
按接口的“收到时间”划分日期,不使用扫描时间、发起日期或流水号日期。正常扫描直接复用服务端 Cookie,认证失效时调用现有续登。全部分页读取成功才提交;按连接、来源、任务标识去重,历史记录保留。记录、扫描设置及最近运行结果保存在本机 `bpm-scan\scan.sqlite`,不随网页关闭或服务重启丢失。
1. 在正式工作台打开 **BPM 连接**,创建连接并指定负责人。
2. 点击 **开启自动续登**,录入 BPM 账号和托管密码,点击 **保存账号**。账号输入完成后检查是否已托管,保存时以数据库唯一约束再次检查;忽略首尾空格和大小写,同一账号只能在一条连接中开启。保存后自动检查现有会话,Cookie 有效时直接复用;确认失效后,使用已托管账号在已识别的新 SSO 表单自动续登。开启后可从 **管理账号** 更新密码或 **关闭自动续登**;关闭自动续登保留有效 Cookie。
3. 只有需要验证码或额外验证时,点击 **远程登录**,在页面显示的 BPM 画面中完成验证。有托管账号会自动填入对应入口,也可点击 **填入托管账号**;不复制其他浏览器的 Cookie。
4. 完成新版门户登录后点击 **检查并保存**。新版账号验证通过即显示“已连接”;只维护新版 BPM,不提供旧版入口或检查。
5. 服务启动及每 5 分钟自动恢复检查并保存有效的刷新 Cookie,无须一直打开工作台。错误密码自动重试间隔至少 15 分钟,网络故障不触发密码提交,正在人工登录的连接暂不接管。需要人工处理时建立去重待办;重复失败合并为同一未关闭待办。BPM 服务端的强制到期或注销不能靠修改本地 Cookie 期限延长,届时由自动续登恢复,验证码仍需人工完成。
6. 管理员可先 **停用连接**,再点击已停用卡片上的 **删除**。确认后清理该连接的托管账号和已保存 Cookie,并移除连接;历史审计保留。正在使用的连接需要先停用。
7. 关闭登录画面会释放操作权,其他负责人可继续操作;停用连接会关闭对应浏览器并清除保存的会话与托管账号。每个连接同时只允许一个工作台会话操作。
部署机可直接通过 `http://127.0.0.1:18766` 操作登录。其他电脑操作 BPM 登录须使用 HTTPS 工作台:可使用公司已有反向代理,代理在部署机本地连接 `127.0.0.1:18766` 并设置 `X-Forwarded-Proto: https`,再在 `config.json` 设置 `dashboard.trustedProxy: true`。仅信任本机代理;远端直接传入此头不会启用登录。代理需保留公开 Host,工作台的同源检查会比对该 Host 与 Origin。示例见 `deploy/bpm-login.Caddyfile`。
托管账号登记在 `%LOCALAPPDATA%\OrderNotificationAutomation\bpm-sessions\accounts.sqlite`。账号和密码以 AES-GCM 加密后写入数据库,账号唯一键使用带密钥的摘要,主密钥由 Windows 当前服务账号 DPAPI 保护;账号接口只返回用户名和更新时间,已保存密码不回传。服务启动先将原加密账号文件事务迁移到数据库,迁移成功再移除原条目;发现旧账号重复则回滚并保留源文件,避免覆盖。远程画面输入不会另行记录,也不保存截图文件。状态检查只访问新版门户,不执行已阅、审批、知会或通知操作。
## PDF 扩展首次使用
1. 双击本目录的 **启动工具.cmd**,或运行 `npm start`。保持服务窗口打开。本机已有 Node.js、Chrome 和依赖,可直接启动。换电脑使用时,安装 Node.js 22.13+(建议 Node.js 24)和 Chrome,然后在项目目录运行 `npm install`。框架使用 Node 内置 SQLite,部分 Node 版本会打印实验性 API 提示。
2. 在 Chrome 地址栏打开 `chrome://extensions`,启用“开发者模式”,点击“加载已解压的扩展程序”。
3. 选择服务窗口给出的本机目录:`%LOCALAPPDATA%\OrderNotificationAutomation\extension`。**不要选择项目内的 extension 源码目录**:启动时会把源码和本机配对配置一起准备到上述目录。
4. 在 Chrome 扩展菜单中固定“订单通知书 PDF”。在你已登录的 BPM 中打开订单详情,点击扩展,再点击 **导出当前订单**。
5. 面板显示保存位置后,在本目录 `output\pdf` 查看结果。导出在后台继续,关闭面板不会取消;可再次点击扩展查看结果。
Chrome 加载扩展只需做一次。修改扩展源码、重新配对或变更端口后,先重启本地工具,再到扩展管理页点击刷新。
内置浏览器无法安装这份 Chrome 扩展。使用独立工具时,在原有 Chrome 的已登录页面操作;若该 Chrome 尚未登录,需要在该 Chrome 中登录一次。工具不复制其他浏览器的登录状态。
## 命名和重复导出
规则:`订单号_项目编号_产品型号_通知书编号.pdf`。
虚构示例:`900001_DEMO-PROJECT-001_DEMO-MODEL_DEMO-CHANGE-001.pdf`。
四项来自表单 `xdatabind`:`OrderNum`、`ProductNum`、`ProductModelNEW`、`SN`,不依赖示例订单值。缺少任一项时停止并提示;非法文件名字符替换为下划线。同名文件追加 ` (2)`、` (3)`,不覆盖旧文件。
## 设置
复制 `config.example.json` 为 `config.json`,可更改 `outputDir`、本地服务 `port`、PDF 缩放 `scale`。默认 A4 纵向,缩放 0.59,与本次验证样稿采用相同参数。`outputDir` 可以是相对项目路径,也可以是 Windows 绝对路径。
扩展桥接服务仅监听 `127.0.0.1:18765`;Web 看板默认监听 `0.0.0.0:18766`,可用 `dashboard.host` 改为 `127.0.0.1`。配对密钥只用于本机扩展和本机程序通信,不是 BPM 登录凭据。不要分享 `%LOCALAPPDATA%\OrderNotificationAutomation` 中的配对配置。
## 能力范围
- 扩展直接读取当前浏览器页的显示值、CSS 和图片,复用该 Chrome 的登录状态;不启动远程调试端口。
- 本地程序使用隔离的无界面 Chrome 排版,禁用页面脚本和网络;保存后关闭该排版进程,不影响你正在使用的 Chrome。
- 不导出密码、隐藏控件、ViewState、讨论输入和操作按钮,不提交或修改 BPM 订单。
- **输出是页面导出样稿,不是服务器原版 PDF,也不保证与 XForm 原生打印完全一致。** 不支持的图片、资源读取失败会在扩展中提示。网页内的附件只显示名称,不会自动合并附件。
- 本版包含 PDF 导出、团队协作、BPM 托管、SMTP / IMAP 邮箱与模板审核及明确操作的测试发信。上传 210、业务规则匹配、按批次自动发信及 ZCode 监管尚未接入;不会自动处理知会或修改 BPM 审批。
## 故障处理
- 无法连接本地工具:确认启动窗口仍在运行;端口或配对变更后刷新扩展。
- 端口占用:先关闭重复启动的工具窗口;也可在 `config.json` 修改端口,重启并刷新扩展。
- 缺少字段:进入“海外运营订单更改评审 V7”实际订单详情;其他表单的绑定不同,需要增加映射。
- 缺少排版依赖:在项目目录运行 `npm install`。
- 启动入口直接运行 Node,不需要 PowerShell 脚本,也不修改系统执行策略。
## 开发和验证
`npm test` 运行命名、重名保留、真实 PDF、可见字段采集和回环 API 访问控制测试。运行时优先使用本项目安装的 `playwright-core`,本机也兼容 Codex 提供的依赖目录;Chrome 路径可用 `ORDER_CHROME_PATH` 指定。
运行本地快照回归:`node scripts/export-snapshot.cjs --snapshot <snapshot.json> --assets <assets.json>`。该入口仅用于已有离线快照;日常使用扩展按钮。
验证记录见 `docs/verification.md`。浏览器扩展需要在 Chrome 中加载后才能完成真实会话的整体验证。
+6
View File
@@ -0,0 +1,6 @@
{
"port": 18765,
"outputDir": "output/pdf",
"scale": 0.59,
"dashboard": { "host": "0.0.0.0", "port": 18766, "trustedProxy": false }
}
+8
View File
@@ -0,0 +1,8 @@
# Replace the host with the company-assigned HTTPS name and use an approved certificate.
# config.json: "dashboard": {"host":"127.0.0.1","port":18766,"trustedProxy":true}
orders.company.example {
reverse_proxy 127.0.0.1:18766 {
header_up Host {hostport}
header_up X-Forwarded-Proto https
}
}
+31
View File
@@ -0,0 +1,31 @@
# 青龙部署
直接使用官方青龙面板、调度器、任务启停、运行日志和 OpenAPI。订单程序保留浏览器及业务处理;原工作台的发送时间配置不会自动同步至青龙。
## 启动
1. 准备可运行 Linux 容器的 Docker Engine。Windows 使用 Docker Desktop 和 WSL 2。
2. 双击项目根目录 `启动青龙.cmd`,打开 http://127.0.0.1:5700 ,自行完成管理员初始化。
3. 需要局域网访问时,先完成账号初始化,再设置环境变量 `QL_LISTEN_ADDRESS=0.0.0.0`,重新启动;同事通过部署机 IP:5700 访问。端口可用 `QL_PANEL_PORT` 修改。工具不改防火墙。
状态保存在 Docker 命名卷 `order-notification-qinglong_qinglong-data`,不放在 VirtualBox 共享目录。不运行 `down -v`,否则会删除账号、任务和日志。
## 管理
优先使用青龙原生 Web 页面。项目内安装官方 `@whyour/qinglong-cli@0.1.2`;根目录 `青龙CLI.cmd` 直接转发参数到该 CLI,没有另写一套任务管理实现。
```powershell
.\青龙CLI.cmd --help
.\青龙CLI.cmd task list --json
.\青龙CLI.cmd task logs 任务ID --json
```
CLI 认证按官方说明配置。现阶段不自动生成账号、保存凭据、创建业务任务或启用邮件;BPM 执行端尚需对接。部署文件可验证不代表容器已经运行。
## 来源
- https://github.com/whyour/qinglong
- https://github.com/whyour/qinglong/blob/develop/docker/docker-compose.yml
- https://github.com/whyour/qinglong/blob/develop/cli/README.md
- 镜像:whyour/qinglong:debian,2026-10-16 核对 Docker Hub 后固定摘要。
- 官方代码采用 Apache-2.0;项目安装的 CLI 保留其随包许可证。未复制或修改青龙源代码。
+15
View File
@@ -0,0 +1,15 @@
name: order-notification-qinglong
services:
qinglong:
# Official Debian image; digest verified against Docker Hub on 2026-10-16.
image: whyour/qinglong:debian@sha256:43abc2d370dc21176d995d0b1ee45585372e6760159dfd40de1cd8ede62908a9
restart: unless-stopped
ports:
- "${QL_LISTEN_ADDRESS:-127.0.0.1}:${QL_PANEL_PORT:-5700}:5700"
environment:
TZ: Asia/Shanghai
QlBaseUrl: /
volumes:
- qinglong-data:/ql/data
volumes:
qinglong-data:
+21
View File
@@ -0,0 +1,21 @@
# BPM 扫描验证记录
## 接口与生产数据
- 使用服务端已保存会话读取新版门户客户端认证信息,再 GET 两个新版门户列表 API;没有打开流程详情,也没有调用已阅、审批或发送接口。
- 实际读取 7 条流程:2026-10-15 到达 6 条,2026-09-03 到达 1 条。保留原流程名称,包括采购流程,未提前按未提供的业务表格筛选。
- 正式工作台实际点击“立即扫描”:本次 7 条,新增 0 条,总数仍为 7;之后后台定时扫描成功,页面自动更新最近完成时间。
- 实际验证关键字“海外运营”返回 3 条;清空恢复 7 条。PDF 导出记录标签、日期折叠按钮可用。
- 正式页面截图:`output/verification/bpm-arrivals-2026-10-16.png`。
## 自动验证
- 专项包括真实本地 HTTP 分页、Bearer、认证失效续登、禁止跳转、收到日期、缺失日期、SQLite 去重/重启/事务回滚、日历暂停、并发与负责人权限。
- 浏览器测试包括日期分区、关键字查询、立即扫描、后台新增自动出现、PDF 标签,以及扫描接口不可用时 PDF 仍可访问。
- 完整运行结果见 `output/verification/bpm-scan-full-test-2026-10-16.log`。
- 限制测试文件并发为 2,避免同时创建大量 Chromium 和 Windows 凭据保护进程产生资源争用。
- 本轮完整回归 111 项:105 项直接通过,包括全部 7 项新增扫描测试。6 项旧用例失败后分别复测通过:远程输入/关闭测试改为等待真实请求,PDF 测试的完成等待改为最多 60 秒;4 项 Windows 会话加密存储用例在独立运行中通过。复测记录为 `output/verification/bpm-scan-recheck-2026-10-16.log`(6/6 通过)。
## 审查
独立只读代码审查发现并修正两处问题:扫描不可用时 PDF 入口被阻断、空闲记录页不刷新后台新增。修复后复查无新增阻断问题。
+36
View File
@@ -0,0 +1,36 @@
# 部署与维护
## 安装启动
1. 准备常驻 Windows 机器、Node.js 22.13+(建议 24)及 Chrome,确认可访问新版 BPM、SSO 和公司邮箱。
2. 克隆私有仓库,进入项目执行 `npm ci`。
3. 按需复制 `config.example.json` 为 `config.json`,调整监听端口、PDF 输出目录与代理设置。实际配置不提交 Git。
4. 执行 `npm start` 或双击 `启动工具.cmd`。浏览器访问 `http://127.0.0.1:18766/`,首次自行创建管理员,无默认密码。
5. 管理员创建团队账号,配置 BPM 连接及邮箱。账号密码在 Web 中录入,不写源码、命令行或文档。
服务进程需持续运行,网页可以关闭。当前启动入口不自动安装 Windows 服务或开机任务;常驻运行时使用固定 Windows 账号,另行配置并验证开机启动与失败重启。不要同时启动多个实例访问同一状态目录。
## 多人访问与 HTTPS
Web 默认监听 `0.0.0.0:18766`,PDF 扩展桥接仅监听 `127.0.0.1:18765`。局域网访问需部署环境允许相应路由及防火墙。
敏感设置和远程 BPM 登录,部署机可用回环 HTTP;其他电脑使用 HTTPS。优先使用公司反向代理,参考 [Caddy 示例](../deploy/bpm-login.Caddyfile)。代理应在部署机回环连接后端,保留公开 Host,设置 `X-Forwarded-Proto: https`,并在实际配置启用 `dashboard.trustedProxy`。仅本机代理获得信任,不能把该配置当作允许任意远端伪造代理头。
上线需在另一台电脑验收登录、远程画面点击与中文输入、会话保存、权限及长时间运行。反向代理、证书和公司邮箱连通性依部署环境确认。
## 数据与备份
状态目录:`%LOCALAPPDATA%\OrderNotificationAutomation`,由实际运行账号决定。数据库清单见 [设计要求](design-requirements.md#8-数据保密与部署)。PDF 输出默认在项目 `output/pdf`,若需跨版本保存建议在 config.json 配置独立输出目录。
备份先停止服务,再备份整个状态目录及业务输出目录;SQLite 的 WAL 文件与数据库必须保持一致。备份包含敏感数据,需限制访问及加密保存。密钥由 Windows DPAPI 绑定运行身份,单独复制 SQLite 或加密文件无法保证跨机器恢复;迁移前验证恢复条件,必要时重新登录及录入渠道凭据。
升级前备份,安装锁定依赖后再启动。Git 仓库不含运行数据库、凭据、Cookie、日志或业务输出,克隆源码不会同步这些数据,也不会恢复已有登录状态。`scripts/preview.cjs` 仅供隔离开发验证,正式启动使用 `npm start`。
## 开发与发布检查
- `npm ci`:安装 package-lock.json 锁定版本。
- `npm test`:运行回归,包含真实本地浏览器与 SQLite/DPAPI 夹具,需要 Chrome 和可用 Windows 运行环境。
- 新提交先检查 `git status` 和暂存文件,禁止加入 config.json、extension/local-config.js、output、状态库及密钥。
- 使用 HTTPS 与 Git Credential Manager 访问私有仓库,不把密码或令牌写进远端 URL。
最新扫描验证范围及历史测试结果见 [扫描验证](bpm-scan-verification-2026-10-16.md) 和 [验证历史](verification.md)。
+135
View File
@@ -0,0 +1,135 @@
# 订单通知自动化:设计要求
更新日期:2026-10-16。本文为当前设计要求入口;与早期调研或阶段计划冲突时,以本文及对应模块最新设计为准。业务规则的调整需要同步本文、实现与验收记录。
## 1. 产品目标与运行方式
团队成员在各自电脑访问同一台常驻服务器,通过 Web 管理 BPM 连接、流程到达记录、业务日历、异常、邮件模板和收件群组。正式工作台使用真实持久数据,不预置演示账号或虚构订单,不提供默认管理员密码。
最终业务链路:发现符合规则的订单 → 提取字段及生成 PDF → 归档并上传 210 → 按产品线选择模板与群组 → 每日两个约定时段发送 → 保存结果并处理异常。
当前阶段优先保证账号托管、只读扫描、日期视图与邮件模板维护。业务匹配规则由后续表格确定;在规则确认前,不将知会状态等同于可处理订单,不自动已阅、审批或发送业务通知。
## 2. 功能范围与现状
| 模块 | 当前实现 | 后续要求 |
|---|---|---|
| 团队工作台 | 首次创建管理员、团队账号、角色权限、持久登录、审计 | 常驻部署与异机 HTTPS 验收 |
| BPM 连接 | 新版门户、远程交互登录、加密会话、账号托管与续登、唯一性、停用后删除 | 按上游认证变化维护适配 |
| 流程扫描 | 新版列表 API、分页、去重、定时和手动扫描、按到达日分区 | 按用户业务表格配置范围及字段映射 |
| 业务日历 | 周规则、工作日/休息日覆盖、采集与发送独立开关 | 接入正式发送调度 |
| 异常待办 | 创建、认领、转交、提交核验、关闭、重开及流转记录 | 业务执行失败自动建单与通知接口人 |
| 邮箱渠道 | 公司 SMTP/IMAP、加密凭据、连接检查、定时收信 | 公司真实邮箱连通性验收 |
| 邮件模板 | 模板邮件解析、预览确认、版本、HTML/CID/附件、自发测试 | 接入正式订单数据渲染与发送批次 |
| PDF | Chrome 扩展手动采集、离线生成、四字段命名、重名保留 | 按业务表单适配无人值守详情与导出 |
| 210 上传 | 尚未接入 | 确认协议、路径、权限与结果校验 |
| 自动业务邮件 | 已有时间与群组配置,未接通业务执行 | 批次持久化、去重、恢复、结果核验 |
| ZCode 监管 | 方向预留,未接入 | 确认 GLM ZCode 接口、诊断范围及通知渠道 |
| 青龙 | 保留部署准备及 CLI | 暂停部署,不作为当前服务启动依赖 |
## 3. 架构与模块职责
```mermaid
flowchart LR
U[团队浏览器] --> W[Web 工作台 :18766]
W --> A[认证、权限与业务 API]
A --> B[BPM 登录与会话托管]
A --> S[只读扫描与日期查询]
A --> M[邮件渠道与模板审核]
A --> D[(服务端本地状态与 SQLite)]
B --> P[新版 BPM / SSO]
S --> P
M --> E[公司 IMAP / SMTP]
X[Chrome 扩展] --> L[本机桥接 :18765]
L --> F[离线 PDF 排版]
```
采用 Node.js 单服务与模块化代码,前端复用 Tabler,浏览器执行使用 Playwright Core。邮件复用 Nodemailer、ImapFlow、MailParser 与 sanitize-html;依赖锁定在 package-lock.json。源码按功能拆分,避免将外部系统调用写入页面渲染逻辑。
| 代码位置 | 职责 |
|---|---|
| `src/server.cjs`、`src/dashboard*.cjs` | 启动、桥接、Web 路由、工作台身份与设置 |
| `src/workspace-*.cjs` | 日历、异常、连接、监管配置与审计 |
| `src/bpm-*.cjs` | 会话加密、远程输入、续登、列表读取、扫描存储与 API |
| `src/mail-*.cjs` | 邮箱存储、收发服务、模板解析与审核 API |
| `src/exporter.cjs`、`extension/` | 可见字段采集、静态快照、PDF 输出 |
| `web/` | 工作台页面及交互 |
| `tests/` | 隔离数据、HTTP、浏览器与存储回归 |
## 4. 角色、连接与登录
管理员管理团队、邮箱与全局设置;操作员处理授权业务及异常;只读成员查看记录。连接敏感操作还需检查管理员身份或连接负责人权限,不能只隐藏按钮。写入操作进行同源校验;多人修改使用版本校验,冲突时拒绝覆盖。
仅维护新版门户 `https://bpmn.skyworthdigital.com/` 及所需 `https://sso.skyworthdigital.com/`。历史调研中的旧网站路径不构成旧版兼容要求。
远程登录必须直接在画面上点击、键盘输入、Tab、粘贴与中文输入,不在画面下方另放替代输入框。每个连接同时只有一个交互租约;人工操作期间后台托管让出控制权。登录成功检查后保存服务端会话,关闭画面释放操作权。
有效 Cookie 优先复用,服务重启后继续恢复。确认认证失效才提交托管账号;网络故障不触发重复密码登录。错误凭据至少冷却 15 分钟;验证码或额外验证生成去重待办,由人完成。
工作台登录有效期为 30 天,活动时续期;BPM 的上游有效期由公司认证系统控制,通过会话复用及自动续登维持长期托管,不改写 Cookie 到期值冒充上游续期。
账号规范化采用去除首尾空格、忽略大小写,以带密钥摘要及数据库唯一约束防止重复托管,页面提前查重不能替代保存事务约束。更换密码保留仍有效会话;更换账号清理原身份会话。连接须先停用再删除,删除清除凭据和 Cookie、保留审计。
## 5. BPM 扫描与日期视图
- 默认每 5 分钟扫描,遵循业务日历采集开关;管理员可调整或暂停,管理员及连接负责人可立即扫描。
- 从新版门户获取客户端认证信息,在内存使用 Bearer 调用 `/bpm/worklist/informlist` 和 `/skyworth/todo/v2/workflow/get_process_of_inform_v4`。后一个是新版门户聚合来源,不单独维护旧站登录。
- 处理 `total/children` 及 `page/start/limit`,全部来源全部分页成功后事务提交;失败记录运行结果,不把半次扫描写成成功。
- 去重键为连接、来源、任务标识;保存原流程名与业务收到时间,首次发现及最近扫描时间分别记录。
- 按接口 `startTime` 对应的收到时间,以 Asia/Shanghai 划分“到达我们这边”的日期。缺失日期显式保留未知状态,不回填扫描时间。
- 一天一个可折叠分区,支持连接筛选、关键字查询和加载更早日期;后台新增自动刷新,扫描故障不阻断 PDF 记录。
- 当前待阅/知会仅为临时采集来源;不打开详情、不标已阅、不审批。保留不匹配流程,等待后续表格定义筛选。
后续业务表格至少需明确流程名称与版本、触发节点、产品线、字段映射、通知类型、新单/更改单范围、模板和收件群组。字段不完整、范围不明或映射冲突进入待办,不猜测处理。
## 6. 邮箱与模板
支持公司 SMTP/IMAP,服务器、端口、TLS 方式与登录身份由管理员维护。证书正常校验,连接检查不发信。新邮箱默认暂停收信,开启后后台每分钟检查,也支持立即收信。
仅接收允许发件人提交的模板。主题 `[模板][产品线]发信标题` 指定产品线;`[模板]发信标题` 为默认模板。回复、转发、无效范围及超 10 MB 邮件不导入。按邮箱、UIDVALIDITY 和 UID 去重,首次及 UID 变化只查近 7 天;只读访问,不标记已读、移动或删除。
解析正文、HTML、CID 图片、附件和原 EML;模板必须在 Web 预览并确认后生效。保留版本和来源,多人确认冲突不覆盖新版本。HTML 预览隔离、清理脚本并阻断外链图片,内嵌资源限制展开大小。
变量只替换 `{{产品线}}`、`{{订单号}}`、`{{日期}}`、`{{订单列表}}`,不执行代码。原邮件 To/Cc 不修改业务收件群组。显式测试只发到托管邮箱自身,记录任务;不确定发送结果不自动重发。
## 7. 日历、异常与后续执行
业务时间统一为 Asia/Shanghai。日历区分采集与发送,支持周规则、公司工作日、休息日、停发覆盖;每天两个发送时段必须不同。保存配置不会立即发送。
异常需包含连接或任务引用、失败步骤、负责人、状态、时间和流转记录,支持认领及转交。核验关闭保存操作人和核验依据;自动步骤的结果来自实际执行回执。产品页面只呈现必要的业务操作、状态、数据和结果。
后续执行链路必须持久化订单版本、导出、上传、待发、发送结果及批次;重启可恢复,同一版本不重复通知。缺少群组、上传失败或发送结果不明时停在对应步骤。上线前明确历史补发、漏过时段补发、空批次和更改单策略。
ZCode 后续用于有限诊断与修复建议;任务状态、重试上限和外部结果判定由确定性程序维护。接入前明确接口人及通知渠道,不向模型发送密码、Cookie 或完整业务表单。
## 8. 数据、保密与部署
运行状态位于部署机 `%LOCALAPPDATA%\OrderNotificationAutomation`,不写项目共享盘。
| 位置 | 数据 |
|---|---|
| `dashboard/state.json`、`dashboard/auth.sqlite` | 工作台账号哈希、配置、PDF 记录、登录令牌哈希 |
| `workspace/workspace.sqlite` | 连接、日历、异常、审计与监管配置 |
| `bpm-sessions/accounts.sqlite`、加密会话文件 | 托管账号、密码、冷却信息及会话 |
| `bpm-keys/` | Windows DPAPI 保护的主密钥 |
| `mail/mail.sqlite` | 邮箱、模板、原邮件、游标及测试发送记录 |
| `bpm-scan/scan.sqlite` | 流程到达记录、扫描设置与运行结果 |
敏感载荷使用 AES-GCM 加密,主密钥绑定 Windows 运行身份。账号 API 不返回已保存密码,客户端不取得 BPM Cookie。远程画面不录制,输入不写日志;导出快照移除密码及隐藏数据。
代码仓库只包含源码、锁定依赖、测试、示例配置和设计文档。排除 node_modules、output、实际 config.json、配对配置、数据库、密钥、Cookie、原邮件、业务文件及日志。测试样例使用虚构标识。备份应停服务后备份整个状态目录,并保护密钥恢复条件;跨 Windows 用户或主机迁移需单独验证 DPAPI 恢复或重新授权。
要求 Windows、Node.js 22.13+(建议 24)、Chrome 及到 BPM/邮箱的网络连通性。`npm ci` 后 `npm start`;首次创建管理员。桥接仅监听 127.0.0.1:18765,Web 默认 0.0.0.0:18766。多人敏感操作通过 HTTPS 反向代理,仅信任部署机回环代理,示例见 `deploy/bpm-login.Caddyfile`。开机常驻、防火墙、DNS、证书与备份由部署环境配置并验收。
## 9. 验收与实施顺序
1. 登录与托管:重启复用、失效续登、验证码待办、账号并发查重、停用删除、远程画面直接输入、权限与租约。
2. 扫描与日期:跨页完整、重复不新增、失败不半提交、收到日期跨日正确、后台新增刷新、日历暂停与手动覆盖。
3. 邮件模板:中文 MIME、HTML/CID/附件、白名单、UID 重置、预览隔离、确认后生效、版本冲突、只向自身测试。
4. 业务表格接入:确认流程范围、订单标识及字段映射,先核对候选清单,再连接自动详情和 PDF。
5. 210 与自动发送:确认上传参数、模板群组及两个时段,验证批次去重、重启恢复、结果不明处理,再启用正式群组。
6. 运维监管:完成异机 HTTPS、常驻、备份恢复,再按实际需求接入通知接口人与 ZCode。
自动验证入口为 `npm test`。不同阶段记录有各自范围,不能把隔离夹具测试当成公司真实系统的端到端验收。最近扫描验证详情见 [BPM 扫描验证记录](bpm-scan-verification-2026-10-16.md),其他阶段见 [验证历史](verification.md)。
相关模块设计:[框架](superpowers/specs/2026-10-16-application-framework-design.md)、[BPM 登录](superpowers/specs/2026-10-16-bpm-login-design.md)、[扫描](superpowers/specs/2026-10-16-bpm-scan-design.md)、[邮件](superpowers/specs/2026-10-16-mail-design.md)。
@@ -0,0 +1,403 @@
# 当前项目架构分析与模块复用调研
> 历史调研或分阶段记录;当前能力与设计要求见 [设计要求](design-requirements.md)。本文件中的订单标识样例已替换为虚构值,旧站点记录不构成兼容要求。
日期:2026-10-16,Asia/Shanghai。
后续状态:用户已决定先实现并运行应用框架,知会不自动处理,具体处理规则以后再定。实际首版范围和已实现边界以 [框架设计](superpowers/specs/2026-10-16-application-framework-design.md) 与项目 README 为准;本文保留调研时的建议及观察,不代表全部功能已经落地。
本文是基于当前代码、网上官方资料和实际 BPM 页面查看的设计建议,不是已批准的实施规格。2026-10-16 用户自行登录新版 BPM 后,本次查看了待阅列表及五类订单详情;未主动执行审批、已阅、转交、上传 210 或发送邮件,也没有启动、部署或修改青龙。业务代码、依赖和已有配置未修改;打开详情是否存在自动阅读副作用仍需专项验证。
## 1. 推荐结论
保留当前 **Node.js + Tabler + Playwright PDF** 基础,补成“业务工作台 + 持久业务账本 + Windows 浏览器执行端”,调度优先接已有部署准备的青龙。
复用青龙完整服务及 OpenAPI,不移植其内部调度源码;订单识别、版本判定、归档、分组和邮件发送记录属于本项目。先把业务内核做成可被调度器调用的任务,再决定正式启用青龙或轻量本机调度。
补充用户方向:引入智谱/Z.ai 的 ZCode 参与运行监管与故障分析,执行异常按配置通知对应接口人。用户已选择 B“有限自动恢复”;采用独立规则监测与通知作为基础,ZCode 负责诊断并调用经约束的恢复动作,详见第 10 节;该部分尚未安装或接通。用户另已明确需要业务日历、异常待办与转交,并要求以新版 BPM 为主、支持通过 Web 人工登录并保存会话,详见第 11、12 节。此处恢复方案 B 与第 3 节部署路线 B 是不同维度。
推荐的初期运行假设是一台常驻 Windows 主机、一个业务数据库、一个 BPM 登录执行端、局域网多人查看。实际订单量和处理时长尚无测量,不能据此承诺吞吐量或设定扩容阈值。
## 2. 项目现状:已经做好的与实际缺口
| 模块 | 当前代码证据 | 判断与处理 |
|---|---|---|
| 页面采集 | `extension/capture.js` 的 `captureOrder()` | 当前固定使用海外表单的四个 xdatabind;移除隐藏及操作内容的能力可复用,但多表单适配及 LABEL 空 value 问题需修正,见 11.4 |
| CSS、图片采集 | `extension/worker.js` 的 `collectAssets()` | 有来源限制、大小限制、CSS 顺序和警告;复用规则,浏览器端与扩展端分别实现资源读取 |
| PDF 排版 | `src/exporter.cjs` 的 `renderSnapshot()` | 静态输入、禁网络、禁页面脚本、文件命名与重名保留已实现;继续使用 |
| 本机扩展桥接 | `src/server.cjs` | 回环监听、配对鉴权、异步任务与轮询;适合手动导出,不能直接充当无人值守队列 |
| 团队看板 | `src/dashboard.cjs`、`web/app.js` | 已有账号角色、PDF 下载、配置与审计;沿用 Tabler,不另起前端工程 |
| 存储 | `src/dashboard-store.cjs` | JSON 临时文件后替换、配置版本校验适合当前规模;缺少业务事务、任务领取与长期去重记录 |
| 调度 | `src/schedule.cjs` | 只算下一时段,没有实际执行器,不能视为已实现自动发送 |
| 青龙 | `deploy/qinglong/compose.yaml`、官方 CLI 依赖及启动脚本 | 已有部署准备,尚无调用业务执行端的集成;本次未确认容器运行情况 |
| BPM 列表、规则表、210、邮件 | 设计文档和看板占位 | 未完成连接器;必须分别接通并验证 |
本次在 Node.js v24.19.0 执行 `node --test tests/*.test.cjs`,17/17 通过,包括实际无界面 Chrome 的 PDF 测试。它证明现有导出与看板基础可用,不证明真实登录会话、无人值守、上传或邮件链路已经通过验收。
有一处文档已不同步:根目录 README 写“青龙仅作参考、不在本阶段部署”,而 `deploy/qinglong/README.md` 已提供官方镜像、CLI 和部署入口。准确表述应是“有部署准备,尚未接通业务”,不能只按其中一份文档判断现状。
### 从手动工具到常驻系统必须补的三项能力
1. **可重启恢复的任务状态**:当前扩展 API 的任务 Map 最多 20 条、进程内 `busy` 只保护当前实例;看板中的持久任务不等于可恢复执行队列。`recoverJobs()` 只将任务改为 interrupted。
2. **独立的业务去重账本**:现有 PDF 记录只保留 5000 条、审计只保留 2000 条。若拿这些列表判断“是否发送过”,清理后可能再次发送历史订单。
3. **明确的自动采集入口**:当前链路从用户点击扩展、指定标签页开始。页面采集能力可复用,但现有 MV3 worker 不是常驻浏览器执行器。
## 3. 三条设计路线
| 路线 | 组成 | 优点 | 代价与适用条件 |
|---|---|---|---|
| **A:青龙 + 本项目业务内核,优先考虑** | 青龙调度/运维,本项目处理订单、PDF、上传和邮件,Windows 执行浏览器 | 利用已有部署准备,直接使用任务启停、调度管理、日志;不重写通用运维面板 | 需要稳定的 Linux Docker 环境,以及容器到 Windows 执行端的连接和状态回传 |
| **B:纯 Windows 轻量版** | 现有看板 + node-cron + 持久任务表 + Windows 执行端 | 服务组件少,适合一台机器、固定每日两次发送 | 定时器不提供持久业务恢复;任务日志、补跑和锁仍需本项目实现 |
| **C:n8n 工作流平台** | n8n 编排 + 本项目提供浏览器/PDF 能力 | 适合以后由业务人员经常调整多系统流程和节点 | BPM 登录、页面采集、版本去重依然需要专用模块;增加流程平台、权限与许可边界 |
建议先实现 A/B 共用的业务内核。正式运行机能够稳定运行青龙时选 A;若 Docker/WSL 不适合该机器,则选 B。不要同时启用青龙和 node-cron 两套发送触发器。现阶段没有必要为了固定链路迁入整套 n8n。
## 4. 可以复用哪些项目,复用到哪一层
以下项目来自本次在线读取的官方仓库、文档和部分源码。没有通过下载第三方未知脚本来拼装业务流程。
| 项目 | 可用模块/功能 | 本项目落点 | 建议及边界 |
|---|---|---|---|
| [Tabler](https://github.com/tabler/tabler),MIT | 表格、卡片、筛选、表单、状态标签和后台布局 | 继续扩展现有业务看板 | **继续直接使用**。增加订单池、待发批次和异常页,不更换 React/Vue 全家桶 |
| [青龙](https://github.com/whyour/qinglong),Apache-2.0 | 定时、启停、任务运行、日志、OpenAPI、官方远程 CLI | 调度适配器、运维入口 | **优先复用完整服务**。不复制依赖其内部数据模型和容器环境的 `back/services/cron.ts` |
| [Playwright](https://github.com/microsoft/playwright),Apache-2.0 | 持久浏览器上下文、Locator 等待、请求与响应观察、文件下载 | BPM 浏览器执行端;现有 PDF 排版 | **直接使用现有依赖**。采集浏览器与禁网络 PDF 排版浏览器分开 |
| [node-cron](https://github.com/node-cron/node-cron),ISC | 时区、定时、运行控制、noOverlap、执行事件 | 路线 B 的调度触发器 | **青龙的备选**。不能代替数据库任务表、补跑及跨进程业务防重 |
| [Nodemailer](https://github.com/nodemailer/nodemailer),MIT No Attribution | SMTP、附件、连接与发送结果 | `MailGateway` 适配器 | **邮件渠道确认为 SMTP 后使用**。企业 HTTP 邮件接口则另写同一接口的适配器 |
| [Handlebars](https://github.com/handlebars-lang/handlebars.js),MIT | 模板变量、循环、条件、partials | 邮件标题/正文、产品线汇总表 | **直接使用**。限制可用变量和 helper,不把任意代码执行能力给模板 |
| [ExcelJS](https://github.com/exceljs/exceljs),MIT | XLSX/CSV 工作簿和单元格解析 | 规则表导入和列映射 | **拿到实际样表后接入**。保留编号前导零,显示逐行错误;它不是 Excel 公式计算引擎,也不覆盖旧 `.xls` |
| [MJML](https://github.com/mjmlio/mjml),MIT | 邮件专用布局转 HTML | 邮件正文样式 | **按模板需要选用**。简单通知表格可先用 HTML + Handlebars;Tabler 网页 CSS 不直接当邮件样式 |
| [ssh2-sftp-client](https://github.com/theophilusx/ssh2-sftp-client),Apache-2.0 | SFTP 上传、查询、重命名 | `ArchiveGateway` 的 SFTP 实现 | **仅在 210 确认为 SFTP 时使用**。SMB 走 UNC 文件接口,HTTP 走相应上传 API |
| [Crawlee](https://github.com/apify/crawlee),Apache-2.0 | 请求队列、失败重试、路由、持久抓取状态、浏览器管理 | BPM 扫描器的结构参考 | **先参考,后按需引入**。一个企业站点和单登录会话,直接 Playwright 更容易控制;不需要代理轮换 |
| [BullMQ](https://github.com/taskforcesh/bullmq),MIT | 持久队列、重试、并发、父子任务 | 未来执行队列 | **扩容时再评估**。当前经典 Redis 方案会多一个服务;产品线聚合仍由业务批次完成,不默认依赖 Pro 的 Groups/Batches |
| [Sidequest](https://github.com/sidequestjs/sidequest),LGPL-3.0-or-later | 数据库任务队列、重试、唯一任务、生命周期 | 队列模型参考 | **暂不选**。官方 README 将 SQLite 定位为开发测试、不推荐生产,不能作为免评估的 SQLite 生产队列方案 |
| [n8n](https://github.com/n8n-io/n8n) | 可视化工作流、节点编排、执行记录 | 路线 C 或后续编排参考 | **参考流程和失败处理交互**。核心许可为 Sustainable Use,企业代码另有许可,不能按 MIT/Apache 随意抽取 |
本阶段只需要优先增加业务状态库、邮件/模板/规则表所需的小模块,不需要一次安装表里所有项目。上游主分支会变化,真正接入时应锁定正式版本,再验证与现有 CJS、Node、Windows 和许可证的兼容性。
## 5. 推荐组件划分与执行链路
```mermaid
flowchart TD
Q[青龙:扫描与每日两次触发] --> A[调度适配器:固定动作和业务 runId]
U[Tabler 工作台:配置/预览/人工补偿] --> C[业务服务]
A --> C
C <--> D[(本机 SQLite:订单/版本/任务/发件箱)]
C --> W[Windows 浏览器执行端]
W --> B[BPM:已核实接口或页面]
W --> S[字段与静态快照]
S --> P[现有 PDF 排版模块]
P --> F[本机归档与 210 上传]
F --> O[冻结待发批次]
O --> M[邮件渠道]
M --> D
```
### 5.1 BPM 连接器:接口优先,浏览器兼容
- 定义 `listOrders(cursor)`、`readOrder(id)`、`captureSnapshot(id)` 等明确接口,业务规则不依赖某个按钮或 ExtJS 控件名称。
- 以新版 `https://bpmn.skyworthdigital.com/` 的“流程 → 待阅 → BPMV4”为已实地查看的候选来源,详情仍跨至 `https://bpm.skyworthdigital.com/`。继续核实可见范围、分页、已读历史和更新时间。`docs/web-structure-discovery.md` 中的新旧资源路径都只是线索,不能直接当成已联调 API。
- 有经过核实的只读接口就用它读取列表;详情渲染、页面字段或下载仍可使用 Playwright。资源读取必须使用执行端自己的合法登录会话,不能直接把扩展的 fetch 原样搬成未鉴权 Node 请求。
- 采用更新时间游标、稳定次排序和重叠回查;若 BPM 没有可靠更新时间,则用可解释的扫描窗口和周期对账,不假设分页号能长期防漏。
- 登录过期进入 `login_required`,停止该站点采集并提示续登。SSO 是否支持无人介入续期,需实际验证。
### 5.2 浏览器执行端:独立配置,不接管日常 Chrome
使用 Playwright 的专用持久用户目录,例如部署机 `%LOCALAPPDATA%/OrderNotificationAutomation/browser-profile`。首次人工完成合法登录,随后执行任务。官方文档明确不支持直接自动化日常 Chrome 默认用户目录,也不能让两个浏览器实例同时使用同一个目录。
采集器用 Locator、字段出现、目标订单 ID 和加载完成条件判断页面就绪,不使用固定 sleep 猜测,也不只等 networkidle。保留当前 Chrome 扩展,作为手动导出和异常补救入口。
Windows 交互用户、系统服务和 Docker 容器属于不同运行环境。若 BPM 必须在可交互桌面完成登录,浏览器执行端应在对应用户会话运行;后端可以独立常驻。是否支持注销后、重启后完全无需人工,须单独验收,不能由“设置开机启动”推导出来。
### 5.3 持久状态:业务账本与运行日志分开
当前 JSON 存储可暂时保留账号和设置,但自动处理订单前应建立 SQLite Repository 层及迁移机制。推荐的最小数据模型是:
| 数据表/概念 | 保存内容 | 关键约束 |
|---|---|---|
| orders / order_versions | BPM 来源 ID、业务版本、字段、业务更新时间 | 来源系统 + 来源 ID + 已定义的业务版本唯一 |
| processing_jobs | 处理步骤、尝试次数、下次尝试、领取者、租约、错误 | 同一业务版本的同一步骤不能并行领取 |
| artifacts | PDF/附件路径、摘要、排版版本、上传状态和远端位置 | 任务恢复时可核对产物,而不只信进程状态 |
| notification_intents | 应通知的订单版本、通知类型、产品线目标 | 独立防重账本,不随看板列表清理 |
| delivery_batches / batch_items | 时段、截止时间、冻结的通知项、模板及收件人快照 | 同一通知项不能被两个有效批次重复消费 |
| delivery_attempts | Message-ID/渠道请求 ID、各收件人结果、异常阶段 | 区分明确失败、服务器接受和结果不明 |
| scan_checkpoints / config_versions | 扫描水位、规则、模板、群组版本 | 成功记录发现结果后再推进扫描水位 |
主键不能只用文件名。现有重名加 `(2)` 是“不覆盖文件”,不能防止同一订单多次发送。业务版本优先采用 BPM 的可靠版本或变更标识;没有时先定义稳定业务字段的摘要,排除时间戳、讨论内容和纯排版变化。
群组或模板改变不应自动让全部历史订单变成“新通知”。重新通知是一种明确的业务操作,需要单独记录原因和范围。
### 5.4 上传和邮件:按外部副作用设计恢复
上传先写临时目标,核对文件长度及远端支持的校验信息,再提交正式位置并记账。不同协议的重命名、覆盖和原子性能力需要验证,不能统一假设。
“210 文件存储路径”和“同事可打开的访问链接”应分别保存;SFTP 路径本身不一定能作为邮件下载链接。链接/附件方式、附件大小上限及收件人权限由真实环境决定。
邮件发送前,在同一数据库事务中冻结批次和发件箱记录:包括订单版本、文件摘要、产品线、收件人/抄送和模板版本。发送过程中不再追随配置修改。
发送结果需要区分:
- 明确未被发送方接受的失败:按错误类别决定能否自动重试。
- SMTP/邮件服务已接受:记录渠道响应,不能将其标成每位收件人都已收到或已阅读。
- 部分收件人接受、部分拒绝:按收件人记录,不能对完整群组盲目重发。
- 提交之后超时、进程崩溃或响应丢失:进入 `delivery_unknown`,查渠道记录后处理。稳定 Message-ID 有助核查,但不能假设 SMTP 用它自动去重。
数据库事务、青龙防重叠和队列去重,都不能单独保证外部邮件严格 exactly-once。有正式幂等键的邮件 HTTP API,可在确认其契约后进一步收敛这一风险。
## 6. 青龙与本项目怎么接,避免两个系统互相误导
青龙负责“何时触发、是否启用、脚本级运行与日志”;本项目负责“本批次有哪些订单、到哪一步、哪些收件人被接受、失败后怎么办”。两种记录用本项目生成的业务 `runId` 关联。
建议只提供固定业务动作:`scan`、`process-pending`、`dispatch-mail`、`reconcile`,不提供远程任意命令执行。青龙脚本调用认证的业务接口或经过约束的任务入口。
几个现有代码没有解决的集成点:
1. **调度唯一来源**:选择青龙后,先将现有看板发送时间改为只读展示青龙实际配置;以后需要统一入口时再通过 OpenAPI 写入,显示应用成功或失败。不能保留两个互不关联的可编辑计划。
2. **容器网络**:青龙容器里的 `127.0.0.1` 是容器自身,访问不了 Windows 的 18765。该接口还要求扩展 Origin 和配对密钥,不应伪装成扩展调用。应设计独立的服务鉴权入口;Docker Desktop 的 `host.docker.internal` 可作宿主机候选地址,具体监听和连通性需实测。
3. **完成状态回传**:业务接口返回 202 只说明任务已接收。青龙脚本需按 runId 等待/查询最终状态,明确失败时非零退出。官方远程 CLI 的 `task run` 也只保证接受,不保证完成。
4. **取消语义**:停止青龙脚本不会天然停止 Windows 任务。取消必须显式传递;邮件进入提交阶段后,不承诺可撤回。
5. **补跑与防重**:每日两次发件按持久批次标识处理,手动运行和定时运行走同一领取/去重逻辑。停机错过时段按设置合并到下一个窗口或跳过;不自动创建一串历史补发批次。
6. **职责分离**:扫描与 PDF/上传不必等到发送时刻才开始;发送时从符合条件、已准备好的通知项中截取批次。尚未准备好的项显示延迟并进入后续策略,避免静默漏掉。
如果走纯 Windows 路线,node-cron 只替换以上“触发来源”,业务接口、账本和恢复逻辑保持相同。初期浏览器采集按单执行端串行处理;PDF、上传并发须根据资源测量再调节。
## 7. 目录与看板怎么演进
建议采用模块化单体,不拆微服务。以下是职责示意,不要求为了目录整齐立即重构所有现有文件:
```text
src/
domain/ 订单版本、匹配规则、通知策略、批次规则
application/ 扫描、准备、上传、发件、对账用例
connectors/
bpm/ BPM 列表/详情及浏览器实现
archive/ 210 的实际协议适配器
mail/ SMTP 或企业邮件 API
scheduling/ 青龙;或二选一的本机调度
persistence/ Repository、SQLite、迁移、租约和发件箱
workers/ 浏览器执行与任务领取
exporter.cjs 保留现有 PDF 核心
dashboard.cjs 逐步整理业务 API
web/ 保留 Tabler 业务看板
extension/ 保留手动入口
```
看板建议围绕业务补齐六个页面:订单池、规则导入与匹配预览、处理任务、待发批次预览、发送记录、异常中心。现有 PDF 记录、模板/群组设置、账号和审计继续复用。青龙完整任务运维保留原生页面,本项目展示业务摘要和关联 runId。
接入表格时采用“上传 → 选工作表 → 列映射 → 逐行校验 → 匹配预览 → 发布规则版本”。按实际样表确定订单号、项目、产品线、触发条件和冲突优先级;不能写一个猜测的固定表头就视为完成匹配。
## 8. 部署约束与实施优先级
本次核实 Z: 映射到 `\\VBoxSvr\Tools`。代码可以保留在共享目录,数据库、浏览器 profile、执行中的临时文件应放在部署机本地磁盘;PDF 输出是否继续直接写共享盘取决于可靠性要求,常驻版建议先落本机再发布到共享目标。
目前账号设置本来就保存在 LOCALAPPDATA,应延续这一做法。备份任务账本与关联文件时要保证一致性,不能只复制一个正在写入的数据库文件。当前目录没有 Git 仓库,正式开发前应建立版本管理和数据排除规则。
| 顺序 | 工作 | 可以观察的验收结果 |
|---|---|---|
| 1 | 核实实际 BPM 列表与规则样表,做只读扫描及匹配预览 | 同一来源范围可解释地列出应处理与不处理的订单,重叠扫描不重复建业务版本 |
| 2 | 持久订单/任务/产物账本 + Playwright 执行端 | 不逐单点击即可导出;处理中重启后能核对产物并继续,不重复建通知项 |
| 3 | 模板、产品线映射、210 协议适配 | 上传结果可核对;预览能显示本批订单、收件人、附件/链接和正式邮件内容 |
| 4 | 实际邮件渠道和持久发件箱 | 测试渠道验证正常、明确失败、部分拒绝及提交后结果不明;按记录处理而非统一重试 |
| 5 | 接通青龙或本机定时,启用正式目标 | 两个真实时段执行;验证停机错过、重复触发、登录过期和缺映射,不靠聊天提醒驱动 |
实施前最影响设计的真实资料是:BPM 列表和触发状态、实际规则表、邮件模板/群组、210 完整地址与协议、邮件渠道,以及运行机与登录有效期。资料未齐时可以完成模块边界和本地假服务验证,但不能宣称业务联调完成。
## 9. 主要网上证据入口
- 青龙官方 [README](https://github.com/whyour/qinglong/blob/develop/README.md)、[远程 CLI 说明](https://github.com/whyour/qinglong/blob/develop/cli/README.md)、[cron 服务源码](https://github.com/whyour/qinglong/blob/develop/back/services/cron.ts):核实其运维能力、OpenAPI 与 CLI 的接受/完成语义,以及内部实现依赖。
- Playwright [launchPersistentContext](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context)、[认证文档](https://playwright.dev/docs/auth):核实持久会话与独立用户目录的约束。
- node-cron [官方 README](https://github.com/node-cron/node-cron/blob/main/README.md):核实 noOverlap、时区、运行控制,以及调度器不持久化任务状态的边界。
- Nodemailer [README](https://github.com/nodemailer/nodemailer/blob/master/README.md)、[SMTP transport](https://github.com/nodemailer/nodemailer/blob/master/src/smtp-transport/index.ts)、[许可证](https://github.com/nodemailer/nodemailer/blob/master/LICENSE):核实 CJS/ESM、SMTP 响应字段及当前许可。
- [ExcelJS README](https://github.com/exceljs/exceljs/blob/master/README.md)、[Handlebars README](https://github.com/handlebars-lang/handlebars.js/blob/master/README.md)、[MJML README](https://github.com/mjmlio/mjml/blob/master/README.md):核实表格读取及邮件模板能力。
- [ssh2-sftp-client README](https://github.com/theophilusx/ssh2-sftp-client/blob/master/README.md):核实上传、重命名及服务端能力差异。
- [Crawlee README](https://github.com/apify/crawlee/blob/master/README.md)、[BullMQ](https://github.com/taskforcesh/bullmq)、[幂等任务设计](https://docs.bullmq.io/patterns/idempotent-jobs)、[失败重试](https://docs.bullmq.io/guide/retrying-failing-jobs):比较抓取框架与队列职责。
- [Sidequest README](https://github.com/sidequestjs/sidequest/blob/master/README.md)、[n8n LICENSE](https://github.com/n8n-io/n8n/blob/master/LICENSE.md):排除不适合直接照搬的生产后端组合与许可假设。
在线资料是调研时的主分支快照,所列能力不是已经安装或联调的承诺。部分 SQLite 官网和 Nodemailer 文档入口请求超时或未返回有效正文;相关判断没有依赖搜索摘要替代核实,Nodemailer 改读官方仓库及源码。
## 10. 补充设计:ZCode 监管与接口人通知
### 10.1 本次确认的产品与接入能力
用户已确认指智谱/GLM 家的 ZCode。在线核对的官方项目是 [zai-org/ZCode](https://github.com/zai-org/ZCode),官网入口为 [zcode.z.ai](https://zcode.z.ai/)。官方仓库包含桌面、Web、CLI、Agent 运行时和 MCP/插件能力,采用 Apache-2.0 许可。
本次读取官方主分支的 README、CLI README、运行入口及流式输出测试,确认以下接入基础:
- CLI 支持 `--prompt` 非交互运行,以及 `--output-format json` / `stream-json`。这是进程输出格式,不能推定模型回复天然符合本项目的诊断 schema。
- MCP 支持 stdio、HTTP、SSE,可将本项目的查询或固定处置动作暴露给 ZCode。第一阶段仅暴露诊断所需的只读查询。
- 主配置支持生命周期 Hooks,包括工具失败与会话结束。它们反映 Agent 会话事件,不会自动发现本项目在会话外的服务崩溃、漏跑或主机失联。
- 当前 CLI 源码的非交互 prompt 默认权限模式为 yolo。监管调用必须显式选择适当模式,并通过工具暴露范围、运行账号和接口鉴权限制能力;不能把 plan 模式或工作目录当成操作系统沙箱。
这些属于源码层面的能力确认。本机当前 PATH 中未发现 zcode 命令;本次未安装、登录、调用模型或验证发行版行为。正式接入先选定版本,再核实该版本帮助和实际运行输出。
### 10.2 三层监管,告警不等待模型
```mermaid
flowchart TD
T[业务任务:步骤、心跳、预期时段] --> W[独立 Watchdog:规则检查]
W --> E[(持久故障事件与通知发件箱)]
E --> N[按接口人映射发送基础告警]
E --> Z[ZCode:分析脱敏诊断包]
Z --> R[诊断结论、证据、处理建议]
R --> E
N --> P[接口人:认领、处理、升级]
P --> E
```
1. **确定性监测层**:检查任务失败、心跳过期、扫描水位停滞、预期发送批次缺失、积压增长、登录失效、上传失败和邮件结果不明。必须能区分“没有新订单”和“任务根本没有运行”。
2. **ZCode 诊断层**:读取故障事件、相关 runId、有限日志、连接器健康状态与配置版本,整理可能原因、证据、影响范围及建议。模型结论单独标注,不替代渠道回执或业务状态。
3. **通知和处置层**:通过持久通知发件箱将基础告警发给预先配置的接口人;诊断后可补充同一事件。ZCode 不可用、超时或额度不足时仍发送基础故障事实。
Watchdog 必须独立于业务进程运行,否则业务进程退出时无法报警。本机独立进程可检测服务失败,但不能保证检测整台主机关机、断电或网络隔离;若要覆盖这些故障,需要另一台主机或外部服务接收心跳并执行超时告警。
### 10.3 哪些异常通知谁,哪些可以自动重试
以下是待配置的路由建议,不代表已有真实联系人或渠道:
| 异常 | 系统先做什么 | 接口人路由建议 |
|---|---|---|
| BPM 登录失效/权限不足 | 暂停对应采集,保留待处理任务;提示续登,不循环提交登录 | BPM 账号负责人 |
| 表单变化、必填字段缺失 | 保存失败阶段及脱敏定位信息,隔离该订单或该表单 | 工具维护人;涉及业务字段时加对应产品线接口人 |
| 规则表冲突、缺产品线映射、缺收件群组 | 进入待配置,展示具体缺项,停止该项发送 | 对应产品线接口人;无法路由则转默认负责人 |
| PDF 排版进程退出 | 按产物和任务记录核对后有限重试 | 多次失败转工具维护人 |
| 210 连接/权限/空间异常 | 按协议核对临时与正式文件,再决定重试 | 210 存储负责人 |
| 邮件鉴权失败/部分拒绝 | 记录发送方响应及收件人级结果,不对已接受群组整体重发 | 邮件管理员或产品线接口人 |
| 邮件提交后结果不明 | 标记 delivery_unknown,查询渠道记录,停止盲目重发 | 邮件接口人及该批业务负责人 |
| 服务失联、应有批次未执行 | 由独立监测层生成事件,按补跑策略处理 | 工具运行维护人 |
只允许对预先定义、具备幂等或可核对结果的步骤有限重试。重发业务邮件、更改收件群组、修改业务规则、删除数据或自动改生产代码不属于第一阶段自动处置范围。以后若开放自动恢复,应通过固定动作接口、前置条件与审计实现,不让模型任意拼接 Shell 命令。
### 10.4 接口人配置与告警生命周期
新增 owners / escalation_policies 概念,与正常订单邮件收件群组分开。至少保存产品线或故障组件、主接口人、备用接口人、渠道目标、通知级别和升级规则。没有匹配时转已配置的默认负责人,不能猜测联系人,也不能静默丢弃。
故障事件按“组件 + 错误类型 + 受影响业务范围”聚合;单个订单特有问题保留订单版本标识。连续相同故障更新同一事件,记录首次/最近发生时间、次数及影响任务,避免每次扫描都重复发送。通知发送本身记录渠道结果、重试及最终失败。
事件流转为 open → acknowledged → resolved,超时未认领或影响扩大时按配置升级;恢复后发送一次恢复通知。acknowledged 只表示有人认领,不表示业务任务已成功。ZCode 不能仅凭自己的文字回复关闭故障;关闭需健康检查、实际任务/渠道结果或有记录的人工确认。
若故障恰好是业务邮件渠道不可用,告警优先走独立的企业微信/飞书等已配置渠道;只有 SMTP 时,应明确渠道失效期间通知能力的限制,并在看板保留失败记录。第一阶段先接一种实际可用渠道。
### 10.5 最小接入方式与验收
建议事件触发、每个事件受限调用一次 ZCode,必要时再补充诊断,避免持续让 Agent 轮询所有订单。超时、并发及模型调用预算由适配器控制。
诊断包只提供错误码、步骤、耗时、有限脱敏日志、版本与任务引用;BPM Cookie、邮箱密钥和完整业务表单不放进模型提示。ZCode 的模型请求可能进入所配置服务端,本地运行 CLI 不等于本地推理。
模型返回内容需解析、校验并存档。通知路由由已配置的负责人表决定,不能采用模型临时生成的邮箱或群 ID。通知模板至少包含:事件编号、失败步骤、影响范围、已自动尝试的动作、当前状态、建议处理和工作台链接。
实施顺序:先独立监测和规则告警,再接 ZCode 诊断,最后按需要开放有限自动恢复。验收应注入服务退出、登录失效、上传失败、缺群组、邮件结果不明、ZCode 超时和通知接口失败,验证事件合并、正确路由、通知重试、恢复通知,以及模型不可用时基础告警仍能发出。
主要官方证据:[根 README](https://github.com/zai-org/ZCode/blob/main/README.md)、[CLI 与 MCP/Hooks 说明](https://github.com/zai-org/ZCode/blob/main/apps/zcode-cli/README.md)、[CLI 运行入口](https://github.com/zai-org/ZCode/blob/main/apps/zcode-cli/packages/cli/src/run.ts)、[流式输出测试](https://github.com/zai-org/ZCode/blob/main/apps/zcode-cli/packages/cli/tests/output-format-stream-json.test.ts)、[权限实现](https://github.com/zai-org/ZCode/blob/main/apps/zcode-cli/packages/core/src/permission/service.ts)、[项目声明](https://github.com/zai-org/ZCode/blob/main/NOTICE.md)。
## 11. 已选功能与新版 BPM“知会”实地观察
本节记录用户已选择的功能方向,具体规则仍为设计建议,不表示已实现。2026-10-16 最初旧入口停在验证码登录页,用户随后自行登录新版门户,并明确新版为主。本次已查看新版待阅列表及五类订单详情,没有提取或复制该浏览器的 Cookie。
### 11.1 业务日历
在现有“每天两次 + 是否周末”的设置之上,增加有版本的工作日历。建议支持普通工作日/休息日、调休工作日、法定假日,以及公司临时上班、放假、停发和特殊发送时段。
- 日期的显式公司设置优先于导入日历,导入日历优先于每周默认规则;发布时展示冲突日期、变更原因及未来实际运行时段。
- 初期支持人工维护与表格导入,不把未经确认的第三方节假日 API 当公司最终安排;每年日历需要有来源和维护责任人。
- 扫描/归档日历与邮件发送日历分别设置。休息日可以继续采集并积累待发项;发送是否顺延、跳过或采用临时时段由规则决定。
- 日历修改只影响后续计划,已经冻结或正在提交的邮件批次不随配置变动重写;待发积压按新的有效窗口处理,避免恢复上班后大量历史时段各自补发。
- 界面提供月历、工作/休息/停发标识、两个实际时段及下次执行说明,审计记录谁在何时修改了哪个日期。
### 11.2 异常待办与转交
先在本工具实现异常待办,并保留对应 BPM 流程/订单链接。工具内部异常与 BPM 自身的流程待办分开记录;在没有明确接口与业务规则前,不向 BPM 创建流程任务或自动改变审批状态。
待办建议包含:异常编号、关联订单/批次、失败阶段、优先级、首次/最近发生时间、责任人、处理期限、已执行的恢复动作及证据。
- 状态:待认领 → 处理中 → 待验证 → 已解决;必要时另设暂缓。认领和转交不能代表业务恢复。
- 转交时记录原负责人、新负责人、原因及时间;区分“立即转移责任”与“待对方接受”,界面始终显示当前实际负责人,不能出现双方都认为已交出的空档。
- 同一异常由版本校验或原子认领防止多人同时处理;等待人工操作时暂停相冲突的自动恢复动作。
- 接口人按组件、产品线或明确映射分派;BPM 申请人、当前审批人、知会发送人不直接等同于故障负责人,需业务确认。
- 处理期限使用业务日历;重大服务失联等持续影响故障可另按自然时间升级,避免假期内完全无人收到紧急问题。
- 人工处理后执行针对性验证:登录状态、文件存在及一致性、上传回执或发送方记录等;验证通过才关闭,并保留完整转交和处置记录。
### 11.3 实际入口、五类样本与跨域详情
新版门户为 `https://bpmn.skyworthdigital.com/#`,标题“创维数字流程门户”。本次入口为“流程 → 待阅 → BPMV4 (6)”,其中五条订单、一条采购申请;普通“待阅 (1)”中另有一条采购申请。不能把待阅记录数直接当订单数。
以下五条订单的列表接收日期均为 2026-10-15,列表状态均为“知会”:
| 订单流程 | 通知书/流程编号 | 订单号 | 已打开表单 |
|---|---|---|---|
| 零售订单评审 | DEMO-RETAIL-001 | 900002 | 零售产品部订单评审 V12 |
| 备损订单评审 | DEMO-SPARE-001 | 900003 | 备损订单评审 V5 |
| 宽带事业订单评审 | DEMO-BROADBAND-001 | 900004 | 宽带事业订单评审 V16 |
| 海外运营订单更改评审 | DEMO-CHANGE-001 | 900001 | 海外运营订单更改评审 V7 |
| 海外运营订单评审 | DEMO-ORDER-001 | 900005 | 海外运营订单评审 V13 |
五个详情都打开在旧域名 `bpm.skyworthdigital.com` 的 `/YZSoft/Forms/XForm/.../*.aspx`,路由含 `tid` 和 `pid`。这是“新版门户承接列表、既有表单承接详情”的实际结构;不能因为优先新版就丢掉旧域名的会话支持。参数含义和唯一性需结合接口确认,不能仅凭名称认定为业务主键。
“知会”描述当前列表任务的状态,不足以证明整个审批流程已结束。自动通知的业务触发点仍需确认,不能把所有知会一律当作审批完成。宽带样本的摘要还出现 `HA900004` 及另一公司/订单信息块,业务关系尚未核实;模型应允许一条来源记录关联多个订单标识。
本次没有点击“批量已阅”“已阅”“知会”“发送提醒邮件”、讨论或审批按钮。查看后列表计数仍为 6,但这不能单独证明打开详情完全没有自动阅读副作用。
### 11.4 表单适配:共用采集内核,分别映射字段
| 表单 | 已见订单号与编号绑定 | 已见产品/项目字段 | 对设计的影响 |
|---|---|---|---|
| 零售 V12 | `OFR_LSCP_Applicant.OrderNum` / `.SN` | `OFR_LSCP_BInfo.ProductModel` | 不能套用海外命名空间;业务分类还有选择项 |
| 备损 V5 | `OFR_BS_Applicant.OrderNum` / `.SN` | `OFR_BS_Applicant.ProductLine` | 有明确产品线;当前查看未确认项目及产品型号的等价字段 |
| 宽带 V16 | `OFR_KD_Applicant.OrderNum` / `.SN` | `OFR_KD_BInfo.ProductModel`;另见 `OrderNum_Original` | 区分当前/原始订单;项目绑定待核实 |
| 海外更改 V7 / 新单 V13 | `OFR_WY_Applicant.OrderNum` / `.SN` | `OFR_WY_BInfo.ProductNum`、`.ProductModel`、`.ProductModelNEW` | 两类共用命名空间,但完整型号与较短型号不同,需按业务语义保存 |
建议建立“流程类型 + 表单版本 → 适配器”,输出统一订单对象和字段证据。保留来源原始订单号、关联订单标识、流程编号、项目、完整型号、短型号、产品线、原始订单、知会时间与详情引用;缺字段显式标为待核实,不从标题猜出后静默发送。命名规则是否继续采用短型号,也应由业务确定。
存在一个具体兼容问题:实页编号控件是 `LABEL`,其 `.value` 为空字符串,而 `.textContent` 有正确编号。现有 `el.value ?? el.textContent` 不会在空字符串时回退,并且 `querySelector` 只选一个绑定元素。应按控件类型读取、处理重复绑定并校验非空值;现有模拟测试通过不代表这些真实表单已经可用。本次仅记录问题,未修改采集代码。
零售表单可见 `.xls` BOM 对比附件,其链接 `href` 为 `###`,不能当直接下载地址或使用 ExcelJS 直接读取;附件处理需核实实际点击/下载链路,且不默认将所有附件纳入通知邮件。
### 11.5 来源范围与尚需确认的业务规则
采集设计不应仅依赖“未读”状态:人工查看可能导致订单不再出现在未读列表。优先覆盖经过确认的时间范围和已读历史,使用业务标识、版本账本及重叠扫描去重;工具处理状态独立于 BPM 已读状态。
后续需确认已读/历史范围、筛选分页和稳定排序、账号可见权限、知会 ID 与流程 ID 的关系、重复知会的版本语义,以及知会时间/业务更新时间/流程完成时间的区别。五类样本是结构覆盖的起点,不是全部表单或所有通知条件已核实的证明。
## 12. 新增要求:Web 人工登录与持久 BPM 会话
用户明确要求后续 Web 支持像本次一样由人登录,然后记录 Cookie。实现目标应定义为“保存可供执行端复用的登录会话”,包括所需 Cookie 和站点存储;不能承诺复制一串 Cookie 就能覆盖现有 SSO。
### 12.1 推荐交互
```text
工作台 → BPM 连接 → 新建连接/重新登录
→ 在执行端创建或打开该连接专用的浏览器
→ 用户在真实 BPM 页面输入账号、密码、验证码并完成 SSO
→ 用户点击工作台的“检查登录”
→ 检查新版门户身份 + 旧域名订单详情的实际访问
→ 显示连接账号、授权范围、最后验证时间和会话状态
→ 后台任务按该连接复用会话
```
用户输入发生在 BPM 页面,工作台无需收集密码或代填验证码。初次连接需显示并确认实际账号,防止操作者登录成与预期不同的账号。只打开门户首页或没有出现登录框,不足以标记连接成功;无法访问详情时显示部分可用和原因。
### 12.2 同机与远程登录是两种部署能力
| 场景 | 实现选择 | 边界 |
|---|---|---|
| 用户与执行端在同一台 Windows 主机 | Web 请求执行端打开专用浏览器,用户在该窗口登录 | 实现较轻;后台服务账号和交互桌面必须可用,Windows 服务不能天然弹出用户可操作窗口 |
| 同事从不同电脑访问集中部署的 Web | 提供绑定该连接的远程浏览器画面和输入通道;执行端保存会话 | 用户在 Web 内操作运行机浏览器;需要独立会话、短期访问票据及加密通道 |
| 用户必须在自己电脑的浏览器登录 | 本机配套执行器或经专门授权的扩展配对,再设计凭据移交 | 作为备选路线评估,不默认把个人浏览器会话复制到服务器 |
用户已确认“多人在各自电脑访问同一台服务器”,因此以第二种作为正式方案;远程登录画面是首版连接能力的一部分,不能只交付运行机本地弹窗。第一种可供运行机管理员排障。远程画面的具体实现库尚未选定,需先验证 Windows 执行端兼容性、并发隔离、会话授权与维护成本。
普通链接把 BPM 打开在同事自己的浏览器里,服务器不会因此获得该会话。跨域限制和 HttpOnly 等机制也意味着不能通过普通 iframe 或 `document.cookie` 实现上述能力。远程浏览器应是隔离的登录会话,并限制到已确认的 BPM/SSO 目的地,不做通用远程桌面。
### 12.3 会话存储与执行隔离
- 使用独立浏览器用户目录或经验证的认证状态持久化方案,覆盖 `bpmn.skyworthdigital.com` 与 `bpm.skyworthdigital.com` 以及真实 SSO 所需范围;不复用个人日常浏览器目录。具体存储机制取决于站点实际使用的 Cookie、LocalStorage、IndexedDB 或 SessionStorage,不能假定一种导出方式全覆盖。
- 浏览器 profile 放部署机本地磁盘,不放 Z: 共享目录、仓库或 PDF 输出目录。凭据文件按部署账号隔离并保护,敏感状态文件加密或使用系统保护;浏览器 profile 仍需依赖本机访问控制,不能假设整体天然加密。
- Web、业务任务只引用不透明 connectionId,不向普通客户端返回 Cookie;日志、诊断包、邮件和 ZCode 提示均不包含会话内容。远程登录画面不录制,不保留密码或验证码输入日志。
- 连接有所有者、可使用者和管理者权限。不能将登录工具账号自动等同于有权使用任意 BPM 账号;多人共享同一连接时必须显式授权,所有操作保留执行连接与实际操作者。
- 同一 profile 同时由一个浏览器进程持有。人工重新登录期间暂停对应自动采集、等待在途操作结束并取得连接租约;PDF 静态排版使用另一独立浏览器。
### 12.4 失效、通知与验收
连接状态建议为未连接、登录中、已连接、部分可用、需重新登录、已停用。分别记录最近一次检查和失败原因;会话有效期可能受服务端撤销影响,不显示未经验证的永久有效或精确到期承诺。
检测重定向登录页、访问拒绝或实际身份变化后,暂停对应采集并创建“BPM 续登”异常待办,按既定负责人通知;避免每条订单各报警一次。重新登录后验证两个入口,并从持久水位/待处理任务恢复,不依赖剩余未读数。停用本工具连接时清理本地会话;是否注销 BPM 服务端会话由单独明确动作控制,避免影响用户其他会话。
最小验收包括:人工验证码登录;执行端/服务重启后仍可访问列表及详情;仅门户有效时显示部分可用;过期后一次告警和可续登;多人连接互不串用;重新登录与扫描不争用同一 profile;停止连接后任务无法继续使用旧会话。当前没有实现或验收上述 Web 登录功能,也没有将本次浏览器会话导入项目。
@@ -0,0 +1,12 @@
# 首次代码发布检查
日期:2026-10-16。
- 整理当前设计要求与部署维护说明;README 链接统一入口。历史调研保留阶段说明,避免把旧结论当成当前能力。
- 文档与测试中的真实订单标识替换为虚构值,生产数据库和业务输出未修改。
- 检查提交文件,排除 node_modules、output、实际配置、配对配置、状态库、加密会话、密钥、原邮件、PDF 及日志;验证 Git 忽略规则。
- 源码扫描未发现私钥、JWT、常见服务令牌或带凭据 URL。凭据字面量命中为隔离测试数据,以及登录表单的 `#password` 选择器;不代表真实凭据。
- 全部提交中的 `.js` / `.cjs` 通过 `node --check`,Markdown 本地文件链接存在,`git diff --cached --check` 通过。
- 替换样例涉及的回归:`node --test --test-concurrency=1 tests/core.test.cjs tests/capture.test.cjs tests/dashboard-store.test.cjs tests/server.test.cjs`,12/12 通过,0 失败、0 跳过,包括真实本地 PDF 输出。
本次未重新运行完整测试集。最近完整扫描阶段的结果及失败复测见 [扫描验证记录](bpm-scan-verification-2026-10-16.md),不能将本次发布检查表述为完整业务端到端验收。
@@ -0,0 +1,40 @@
# PDF Export Tool Implementation Plan
> **For agentic workers:** Execute inline using executing-plans. No delegation required.
**Goal:** Reuse a logged-in Chrome order tab to export a named PDF without a print dialog.
**Architecture:** MV3 extension captures a static visible form and permitted assets, then POSTs it to a paired loopback Node service. An isolated offline Chromium process renders the PDF, with exclusive filename reservation preventing overwrite.
**Tech Stack:** Node.js 22+, playwright-core, Chrome MV3, node:test.
**Spec:** docs/tool-design.md
## Global Constraints
- No remote debugging port or account credential persistence.
- Only user-triggered captures of https://bpm.skyworthdigital.com/.
- Local helper listens on 127.0.0.1:18765; requests need extension Origin and random pairing token.
- Four naming fields required; existing files preserved.
- Browser renderer has scripts and network disabled.
## Task 1: Export core
- [x] Write tests for missing fields, Windows-safe names, collision preservation and real PDF bytes.
- [x] Run `node --test tests/core.test.cjs` and confirm missing functionality fails.
- [x] Implement `src/exporter.cjs`: `buildFilename(metadata)`, `renderSnapshot(snapshot, options)` and offline browser lifecycle.
- [x] Run tests using installed Chrome and local fixture markup.
## Task 2: Browser capture and bridge
- [x] Write DOM fixture tests for `captureOrder()` bindings, live values and hidden secrets removal; write HTTP tests for origin, token and size checks.
- [x] Confirm tests fail before implementation.
- [x] Implement extension capture, asset bundling and popup; implement `src/server.cjs` with authenticated POST `/export` and GET `/health`.
- [x] Run tests; malformed submissions must never start a renderer or write a file.
## Task 3: Packaging and acceptance
- [x] Add direct Node Windows command launcher, configuration example, dependency setup and Chinese README.
- [x] Run full tests and real captured-page regression, render the resulting PDF and inspect pages.
- [x] Check extension manifest and scripts; document that live extension loading requires user action and is not yet verified.
- [x] Deliver startup and extension-loading paths, output naming and exact verification limits.
@@ -0,0 +1,62 @@
# Application Framework Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. Steps use checkbox syntax for tracking.
**Goal:** 搭建可运行、可演示的多人订单工作台框架,暂不执行订单处理规则。
**Architecture:** 既有 dashboard 账号认证保护新增 workspace API。SQLite 保存业务日历、异常和连接元数据;独立浏览器模块渲染新增页面;隔离演示服务提供可查看的样例。
**Tech Stack:** Node.js >=22.13、CJS、node:sqlite、Tabler 1.6.1、原生浏览器 JS。
**Spec:** docs/superpowers/specs/2026-10-16-application-framework-design.md
## Global Constraints
- 知会不自动处理,业务规则后续确定;自动发送永远关闭。
- 新 BPM 主站 bpmn.skyworthdigital.com,详情 bpm.skyworthdigital.com。
- 没有 Git 仓库,直接在已指定工作目录开发;不虚构提交或分支。
- 真实登录画面、凭据存储、ZCode 和通知本次只保留接入边界,不能显示已成功连接。
- 不写入或提取用户当前 BPM 会话。
## 接口合同
`GET /api/workspace` 返回 `{calendar:{version,overrides},exceptions,connections,supervisor:{version,defaultOwner,notifyChannel,maxAttempts},audit,members,capabilities:{remoteLogin:false,zcode:false,automaticProcessing:false},stats}`。
`POST /api/calendar` 管理员保存 `{version,overrides:[{date,kind,scan,send,note}]}`,kind 为 workday/restday/pause,返回 calendar。
`POST /api/exceptions` 操作员/管理员提交 `{title,component,priority,description,owner}`,返回 exception。component 为 bpm/pdf/archive/mail/system/rules;priority 为 normal/high/critical。
`POST /api/exceptions/:id/action` 提交 `{version,action,owner?,note?}`,action 为 claim/transfer/verify/resolve/reopen,返回 exception。owner 使用 username。
`POST /api/connections` 管理员创建 `{name,owner}`,返回 connection,status 固定 disconnected;`POST /api/connections/:id/disable` 停用;不提供伪造登录态接口。
`POST /api/supervisor` 管理员保存 `{version,defaultOwner,notifyChannel,maxAttempts}`,渠道 none/manual,次数 0–3,均为策略草稿;返回 supervisor。GET 中 members 为 `{username,role}` 列表。
### Task 1: Backend workspace ledger and protected APIs
Files: src/workspace-store.cjs, src/workspace-api.cjs, src/dashboard.cjs, src/schedule.cjs, tests/workspace.test.cjs, tests/workspace-http.test.cjs.
- [x] 先写并运行持久化、日期覆盖、并发认领、权限和同源测试,确认缺失行为失败。
- [x] 实现 SQLite 事务、有效值校验、版本冲突、独立审计。构造 `new WorkspaceStore(dir)`,提供 `snapshot(members)`、`saveCalendar(input,actor)`、`createException(input,actor,members)`、`actOnException(id,input,actor,members)`、`createConnection(input,actor,members)`、`disableConnection(id,actor)`、`saveSupervisor(input,actor,members)`、`close()`。
- [x] dashboard 允许 `{workspace,previewUserId}` 选项;`GET /api/bootstrap/status` 额外返回 preview 布尔值;预览登录仅在配置 previewUserId 且 loopback 时由同源 `POST /api/preview-login` 签入该用户。正式实例没有此捷径。
- [x] `nextSlots(schedule,from,count,overrides=[])` 使用 send 覆盖,另导出 dayPolicy(date,schedule,overrides) 返回 `{scan,send,kind,note}`。
- [x] 运行新增与原测试,交付更改清单和测试证据。
### Task 2: Functional workspace UI
Files: web/workspace.js, web/app.js, web/index.html, web/app.css.
- [x] 复用当前认证与视图路由,独立 `window.WorkspaceViews` 提供 overview/calendar/exceptions/bpm/supervisor 渲染器,调用 `configure({api,esc,formatDate,notify,user})`,每个渲染器接受 `(container,isActive)`,防止过期响应覆盖。
- [x] 新总览展示能力状态、日历、异常、连接及最近活动,示例数据显式标识;保留 PDF 列表入口。calendar 月历可翻月、选日期、编辑公司覆盖、恢复默认并保存。
- [x] 异常建立/搜索筛选/认领/转交/提交验证/填写核验依据关闭,显示历史和负责人。连接创建/停用可用,远程登录按钮禁用并解释接入状态。监管可保存草稿,无真实 AI/通知开关。
- [x] 首页保留普通账号登录;仅 preview=true 时提供“进入演示空间”按钮调用 preview-login。
- [x] 原导航测试与浏览器表单回归。
### Task 3: Runtime, isolated preview and verification
Files: src/server.cjs, scripts/preview.cjs, package.json, README.md, 启动看板预览.cmd.
- [x] 正式服务本地数据目录初始化 WorkspaceStore 并注入,退出时释放;新增 npm run preview。
- [x] 演示数据独立目录,生成随机预览账号密码,不输出凭据;只在演示进程注入 previewUserId,绑定 loopback,预置虚构异常和连接,显式示例。
- [x] 运行全套 node tests 和 JS 语法检查,启动正式和演示服务,浏览器验证日历保存及异常流转,截图并打开成品。
- [x] 更新 README 的能力范围、端口、运行方法和未接入边界。
@@ -0,0 +1,22 @@
# SDD ledger — plan: docs/superpowers/plans/2026-10-16-bpm-credentials.md
Authorization: user explicitly said '可以的,账号也需要托管。' after first real login deployment.
Ruling: extend encrypted vault to host BPM account/password; previous no-password-persistence stance is superseded by this explicit request. Password never returned/logged or captured implicitly from remote typing.
Ruling (superseded): initial fill-only restriction replaced by explicit user requirement for automatic custody and no repeated login. Cookie-first ensure, verified SSO auto-submit, challenge-only manual intervention; business processing remains later scope.
Ruling: current designated non-Git workspace is implementation destination; no worktree/commits.
| Interface/task | Check | Outcome |
|---|---|---|
| 1 ↔ 2 | account GET/POST, clear and fill verbs/shapes | exact shared contract above |
| 1 ↔ 3 | no secret metadata/audit, restart/disable lifecycle | explicit tests and review |
| Task 1 | reuse vault no plaintext credential storage | consistent |
| Task 2 | write-only password form, stale-page guards | consistent |
| Task 3 | production user enters credentials | no need agent account access |
Existing deployed first-step baseline: 54/54 tests, actual service PID42884 ports18765/18766, no preview listener, one real admin and BPM主连接 preserved; pending actual user login.
Parent implementation: dashboard-sessions.cjs persists hashed workbench tokens for 30 sliding days and revocation across restarts; RED missing module/restart401 -> GREEN2/2. bpm-custodian.cjs startup and 5-minute sequential ensure, no overlap, interactive/disabled skip, stop waits; RED absent -> GREEN2/2. Runtime lifecycle integrated. Backend/UI independent tasks implement credential encryption, safe metadata, exact forms, automatic reuse/cooldown, interface password clearing and navigation lifecycle. Full regression/review/deployment pending.
Final: all three implementation tasks and independent review complete. Full final suite 76/76 PASS; syntax38/38 PASS; backend focused27/27 PASS. Review P2 partial portal state loss reproduced and fixed; repeated ensure/restart now retains portal without repeated password submission. Whole UI+server+real local browser integration covers account save after manual login, positive cookie reuse, no secret metadata/password DOM return. Actual production restarted once after all checks: PID23632 ports18765/18766, required=false/preview=false, stderr empty. Original user and connection kept; no real managed credential entered by agent, actual BPM authenticated renewal/30 elapsed days not claimed. User only needs initial account entry in product; no repeated permission/login prompts introduced.
Latest user ruling: only new BPM, no legacy maintenance. Removed legacy auth origin/form/probe/navigation/UI/check and partial results. Portal positive identity alone is connected. Added transactional connection metadata migration preserving owner/identity/lastConnectedAt and stripping old fields. RED portal-only/detail rejection/old-origin regressions -> GREEN; final complete suite79/79, syntax39/39, independent delta review29/29 approved. Production PID18800 ports18765/18766 healthy, stderr empty, one existing user and one connection retained, no legacy fields. Cookie custody/automatic checks/30-day workbench sessions retained. No real credentials or business mutations.
@@ -0,0 +1,58 @@
# BPM Account Custody Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task.
**Goal:** 为实际 BPM 连接增加加密账号托管、Cookie 复用、自动保活/续登及持久 30 天工作台登录。
**Architecture:** 复用 AES-GCM/DPAPI vault 的独立 account:id 条目,API 只返回账号元数据,远程浏览器只在已验证登录控件填入。
**Tech Stack:** Existing Node CJS/Playwright/Tabler/vault.
**Spec:** docs/superpowers/specs/2026-10-16-bpm-login-design.md 已授权的账号托管补充。
**最新范围(取代下文旧版/双入口描述)**:用户明确只维护新版 BPM。仅 bpmn.skyworthdigital.com 与其 sso 登录跳转;移除旧版域名白名单、表单、导航、检查与 UI,portal 正向验证即 connected,checks 仅 portal,不再 partial。现有连接迁移去除旧字段,保留负责人、会话和业务数据。新版托管、30 天工作台会话、5 分钟保活与验证码人工介入继续适用。
## Global Constraints
- 用户已明确要求账号托管;不创建、重置或显示真实密码;用户在产品页面自行输入。
- 不记录密码或截图;按用户后续明确要求自动托管,仅在正向确认需登录的已验证 SSO 表单提交凭据;不代解验证码,不修改 BPM 业务。
- 继续保留正式管理员/主连接;不得动现有用户浏览器 Cookie。
- 在当前非 Git 工作区工作,先有失败测试再实现;产品页面不出现设计思考文案。
## Task 1: Managed account backend and fill
Files: src/bpm-session-manager.cjs, src/bpm-api.cjs, tests/bpm-account.test.cjs, tests/bpm-http.test.cjs (add tests, preserve existing).
Interfaces: manager.account(connection,principal) -> {configured,username,updatedAt}; manager.saveAccount(connection,principal,{username,password}) -> metadata; manager.clearAccount(connection,principal) -> {configured:false,username:'',updatedAt:null}; manager.fillAccount(connection,principal) -> {filled:boolean,message:string}. Same owner/admin authorization and perconnection serialization; save validates strict keys username nonempty<=150 chars/password nonempty<=256 chars, no trim of password. account:id vault entry stores username/password/updatedAt; return no password. manager.disable also removes account entry. save/clear don't require active browser; fill requires current session lease and drains queue. Production fill selectors only exact https://sso.skyworthdigital.com #username/#password and https://bpm.skyworthdigital.com #_txtUserId/#_txtPassword (allow injected fixture selectors through known-host constructor testing configuration only, never API). Fill only visible text/password input expected types, bounded wait, NEVER click submit. create/navigate internally attempt saved fill, unknown form no-op. When no account fill returns concise actionable error. Do not write back browser-field edits into account vault implicitly.
API: /api/connections/:id/account GET metadata, POST username/password save; /account/clear POST empty; /login/fill-account POST empty. Same role, same-origin POST and secureBpmTransport guards. GET metadata only authorized owner/admin. Only username metadata returned; no raw vault errors. Record audit save/clear using connection name (no password). Existing routes must remain unchanged.
- [ ] Write failing persistence/auth/unknown-host/DOM-type/submit-never-called tests.
- [ ] Implement methods and API routes.
- [ ] Verify ciphertext contains neither username nor password, restart metadata/fill works, disable removes both, no secret response/audit.
- [ ] Run focused tests and self-review.
## Task 2: Account UI
Files: web/bpm.js, web/app.css, tests/bpm-ui.test.cjs.
Add 管理账号 to authorized connection cards. GET /connections/:id/account to show configured username or 未托管; an inline editor asks BPM账号 and 托管密码 (password type, autocomplete new-password, never prefilled stored value). 保存账号 POST same route; clear fields after success. Existing configured account updating requires entering a new password; placeholder 输入新密码以更新. 清除托管 POST account/clear; no account controls for viewers/unrelated operator/disabled connections. Remote toolbar offers 填入托管账号 when metadata says configured; serialize after input queue, track operation for disposal, standard busy/error controls. UI copy concise user actions only; no technical/internal disclaimers. Preserve all current input/lifecycle/CSP behavior.
- [ ] Add meaningful failing UI tests for permissions, password handling and API body.
- [ ] Implement form, metadata and fill action.
- [ ] Verify no saved-password DOM value, no password in cards/localStorage, stale forms do not mount after navigation; run existing UI tests.
## Task 3: Review, regression and deployment
Files: README.md, docs/verification.md, this plan ledger.
- [ ] Independent read-only security/correctness review of account backend + UI.
- [ ] Full suite and syntax pass; restart only verified project process and preserve existing data.
- [ ] Show actual account management page. User enters actual account/password once; automatic checks and renewal operate thereafter, challenge handling remains in remote window. No test users in production.
## Subsequent authorized scope: automatic custody and thirty days
用户明确要求“不要每一次都登入”“至少要30天有效”。以下规则取代前述任务中仅填入而不提交的限制:
- manager.ensure 先验证已有 Cookie,健康时持久保存刷新状态,不提交凭据。只有正向确认登录页才尝试受限自动提交。网络失败、身份冲突、未知表单、验证码均不盲目重登;提交前持久化 15 分钟冷却。
- 首次托管/同一托管账号更新密码保留有效会话;更换已托管用户名清除旧身份与会话。清除账号只删除托管凭据;停用删除会话与凭据。
- 新增 BpmCustodian:启动即检查,每 5 分钟顺序检查,跳过人工操作租约和停用连接,关闭服务等待检查结束。没有业务动作或外部通知。
- 新增 SessionStore:SQLite 仅持久 token 哈希,30 天滑动有效期,每日活动续期,重启可恢复,退出撤销。隔离演示/正式空间。
- 外部 BPM 服务端有权撤销/强制过期,不伪造 Cookie 期限;使用保活和自动续登达到持续托管。实际 30 天运行尚需时间验证。
@@ -0,0 +1,35 @@
# SDD ledger — plan: docs/superpowers/plans/2026-10-16-bpm-login.md
User authorization: first real BPM login step approved; admin creation confirmed by user.
Ruling: use designated non-Git workspace and document progress here — no repository exists, so commits/worktree helper do not apply.
Ruling: keep dev-only preview fixture for existing regression tests, stop its service and remove product/demo entry plus root preview launcher — preserve all user data.
Ruling: verify old portal login separately but do not open old orders automatically — individual detail permission belongs to the later collection task.
| Pair/task | Interface/content check | Outcome |
|---|---|---|
| 1 ↔ 2 | manager signatures + principal session identity | exact shared contract above |
| 2 ↔ 3 | route verbs, JSON and JPEG | exact shared contract above |
| 1 ↔ 4 | constructor stateDir + shutdown | local protected storage and graceful close |
| 3 ↔ 4 | static asset /bpm.js | integrator verifies route registration |
| Task 1 | browser auth fixtures test isolation and restart | consistent |
| Task 2 | metadata not trusted from request; role + transport tests | consistent |
| Task 3 | frame stream disposal and ordered input | consistent |
| Task 4 | deployment preserves administrator/data | consistent |
Preview service PID 3284 verified project scripts/preview.cjs and stopped; demo tab closed. Existing formal tab confirms admin signed in.
Ruling: include exact HTTPS sso.skyworthdigital.com — dedicated new browser observed bpmn redirect to company SSO with username/password controls; required for already-authorized primary portal login. No wildcard hosts.
Ruling: private in-process CDP request guard may enforce all redirect hops; no CDP endpoint exposed — Playwright routes alone miss redirected browser requests.
Task 2: complete — HTTP/store/role/transport/restart focused checks 16/16 passed. Cross-layer review dispatched.
Task 4 integration: real formal-dashboard-to-isolated-BPM-fixture test passed under production CSP; exercised typed login, JPEG display, save, close, reload, restored check. Runtime restart/admin preservation test passed in Task 2 focused run.
TDD runtime red: main export absent; implemented isolated startup/stop and manager wiring.
Task 1: complete initial implementation — 9/9 focused checks; actual new dedicated browser reached SSO username/password and legacy username/password/captcha fields with JPEG output, no credentials entered. Review fixes under execution.
Task 3: complete initial implementation — 9/9 UI/navigation checks. Final review found pending-open unload cleanup skipped close; implementer reproduced real unload and is fixing synchronous keepalive cleanup.
Task 2 review: API approved after partial task fix — initial partial creates none, previously connected partial creates a check task, repeated partial/login_required dedup, wording does not assert network failure means expired. Focused re-review10/10 passed.
Ruling: partial after previous connected warrants owner attention, title 'BPM 连接需要检查' rather than an expiry claim — correct prior brief to match plan's attention requirement and avoid false statuses.
Task 1 review: parent whole UI integration exposed immediate save racing login reload; reviewer reproduced both read-only verification navigations interrupted by login navigation. Implementer added CDP lifecycle settling and bounded interrupted-navigation retry, no replay of login submissions.
Final first-step regression: 54/54 passed, 0 skipped/failures; all changed JS syntax checks passed. Independent API/UI and browser/vault/runtime reviewers approved after fixes. Formal service restarted as verified PID42884, 18765 localhost + 18766 shared dashboard, no18776 listener. Production bootstrap required=false; existing one admin and BPM主连接 preserved. Formal browser tab reloaded to normal login screen; user asked to self-login/check/save. User instead added account托管 requirement, continued under docs/superpowers/plans/2026-10-16-bpm-credentials.md.
@@ -0,0 +1,55 @@
# BPM Login Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task.
**Goal:** 在正式工作台完成独立 BPM 登录、加密保存、恢复及续登。
**Architecture:** 独立浏览器会话管理器 + 鉴权路由 + JPEG 远程登录界面。
**Tech Stack:** Node CJS、node:sqlite、Playwright、Windows DPAPI、原生 Web。
**Spec:** docs/superpowers/specs/2026-10-16-bpm-login-design.md
## Global Constraints
- 保留已有管理员及业务数据;不发送通知或修改 BPM 流程。
- 产品页面不出现设计思考、内部免责声明。
- 无 Git 仓库,在当前指定工作区修改,不提交。
- 所有新行为先写测试,观察缺失行为失败,再实现;最后完整测试与审查。
## Task 1: Browser manager and encrypted vault
Files: src/bpm-session-manager.cjs, src/bpm-vault.cjs, tests/bpm-session.test.cjs, tests/bpm-vault.test.cjs.
Interface: BpmSessionManager({stateDir, browserFactory?, urls?, allowedOrigins?, probe?}) supports async open(connection,principal), frame(id,principal), input(id,principal,action), navigate(id,principal,{target}), save(connection,principal), check(connection,principal), close(id,principal), releaseSession(sessionId), disable(id), shutdown(). principal={user:{id,username,role},sessionId}. open/frame/input require exclusive session, TTL 10min, 3 slots max. open returns {active:true,viewport:{width:1280,height:800},expiresAt,host}. frame returns JPEG Buffer. input types click{x,y}, text{text}, key{key}, scroll{deltaX,deltaY}. key allowlist supports Tab/Enter/Backspace/Delete/arrows/Home/End/Escape/Control+A; text max 2000. navigate target main/detail/reload/back, no arbitrary URL. save/check return {status,identity,checkedAt,checks:{portal:{ok,message},detail:{ok,message}}}. statuses connected/partial/login_required/error. Failed verification must not replace previously saved auth state. Errors safe status-coded without secrets. Only exact BPM HTTPS origins by default; injected localhost origins for tests only. vault authenticated encryption atomic writes and Windows DPAPI-protected key. Browser tests use local fixture, demonstrate save, manager shutdown/restart/recheck, isolated connections, expired lease, malicious navigation/input, encryption corruption.
- [ ] Write failing tests and record red result.
- [ ] Implement manager/vault against interfaces.
- [ ] Run focused tests; report API deviations and pass evidence.
## Task 2: Authenticated API and persisted metadata
Files: src/bpm-api.cjs, src/dashboard.cjs, src/workspace-api.cjs, src/workspace-store.cjs, tests/bpm-http.test.cjs, tests/workspace.test.cjs.
Consumes manager Task1 interface. createDashboard receives optional bpmSessions and trustedProxy boolean; async bpmApi runs after auth before workspaceApi. Routes /api/connections/:id/login/{open,frame,input,navigate,save,close} and /api/connections/:id/check; GET frame JPEG, others POST. /disable closes manager before Store metadata. Authorize admin or exact owner operator; block viewer and unrelated operator. principal.sessionId is dashboard token, never response. Check/save persist manager result via internal WorkspaceStore updateConnectionSession(id,result,actor), not user-supplied status. Internal getConnection and startup markSessionChecksPending reset connected/partial to unchecked while preserving safe last-check metadata. snapshot capability remoteLogin true only with active manager wiring. Deduplicated expiry exception for connection from partial/login_required check when previous saved connected; check failure doesn't auto-close task. Release manager on logout. Remote credentials endpoints only encrypted socket, loopback Host+remoteAddress, or configured local proxy with X-Forwarded-Proto:https. Do not trust arbitrary proxy headers.
- [ ] Write failing HTTP tests for owner/session/origin/transport and persistence.
- [ ] Implement authenticated routes and metadata, preserve original tests.
- [ ] Run focused tests and provide review notes.
## Task 3: Actual BPM remote login UI
Files: web/bpm.js, web/workspace.js, web/app.js, web/index.html, web/app.css, tests/bpm-ui.test.cjs.
Expose window.BpmLogin.mount(container,{api,esc,formatDate,notify,user,isActive}) and .dispose(). WorkspaceViews.bpm delegates mount. API routes Task2; API helper supports JSON POST/GET; GET frame fetched separately as blob. Connection cards show statuses disconnected/unchecked/login_required/partial/connected/disabled/error; only admin or owner operator has login/check actions; create admin only. Remote login image frame with click scaling, ordered keyboard/text/paste/IME input, scroll. Preserve password secrecy (no localStorage/logging), no persistent screenshot. Navigation buttons 新版门户/旧版入口/刷新; 检查并保存/关闭. Poll with no overlap; dispose releases remote lease and objectURLs, stops timers and stale navigation. Disable refresh/navigation while save in progress as needed. Proper concise statuses and errors; no claims unverified. Remove demo UI entry and branding from formal app; legacy dev preview fixture may remain test-only. Adapt overview login summary. Product must stay usable at narrow viewport.
- [ ] Write focused meaningful lifecycle/coordinate/input tests before implementation.
- [ ] Implement page and remote login controls.
- [ ] Run syntax/UI tests and report completion.
## Task 4: Integration, real deployment, review
Files: src/server.cjs, README.md, docs/verification.md, config.example.json and plan ledger.
- [ ] Instantiate manager in local stateDir/bpm-sessions, reset stale metadata; close it on shutdown/error.
- [ ] Stop existing preview process only; remove user-facing preview launch emphasis.
- [ ] Full test suite, syntax checks, independent read-only code review and fixes.
- [ ] Restart verified formal project process, preserve data, inspect actual Web and BPM login screen.
- [ ] Report running URL, completed behavior and any real login still requiring user interaction.
@@ -0,0 +1,7 @@
# 实施计划
1. 测试先行:本地 HTTP 列表模拟、日期解析与 SQLite 去重/持久化/原子性。
2. 新门户只读 API 适配器与 BpmSessionManager 互斥接入,会话失效使用既有续登。
3. 扫描数据库、生命周期、日历调度、手动扫描与权限路由。
4. 每日分区视图与真实接入状态,保留 PDF 记录。
5. 专项和全量测试、代码审查、重启正式服务、真实扫描和浏览器验证。
@@ -0,0 +1,21 @@
# SDD ledger — plan: docs/superpowers/plans/2026-10-16-application-framework.md
Ruling: 用户已明确要求先实现并运行框架,继续本会话执行 — 不重复询问设计批准 — 规则变动仍可后续调整。
Ruling: 非 Git 工作目录直接开发,不创建仓库或 worktree — 保持用户指定启动目录 — 需依赖文件和测试审查。
Ruling: Web 远程登录本轮提供诚实接入边界,先交付可运行管理框架 — 用户明确先框架 — 实际远程登录另需联调。
| 任务/接口 | 检查结论 |
|---|---|
| Task1/Task2 workspace API | 共享接口如计划合同,前端不依赖数据库细节 |
| Task1/Task3 dashboard 参数 | workspace、previewUserId 注入,正式启动不配置预览用户 |
| Task2/Task3 示例标识 | bootstrap/status.preview 驱动,示例数据与正式独立 |
| Task1 内部 | 事务/版本、权限、日历测试分别覆盖 |
| Task2 内部 | 独立模块、当前页面检查、功能与禁用边界一致 |
| Task3 内部 | loopback 预览与正式 LAN 服务分开,文档如实说明 |
Task 1: complete — SQLite/API、权限/同源、日期与版本冲突已测试;后端独立审查通过。
Task 2: complete — 五个实际工作页面与表单、角色限制、审计、示例标识;前端独立审查通过。
Task 3: complete — 正式服务及 loopback 演示已启动;27/27 回归与语法检查通过;浏览器保存/转交/关闭/重启保留验证通过;README 与验证记录更新。
Ruling: 演示与正式空间 Cookie 使用不同名字 — 浏览器 Cookie 不按端口隔离,原同名会互相覆盖 — 回归已覆盖。
Ruling: 目录不是 Git 仓库,finishing 分支/合并菜单不适用 — 交付运行文件和可访问页面,不创建虚构提交。
@@ -0,0 +1,10 @@
# 邮件接入实施计划
1. 测试驱动 MIME 解析:中文、HTML/CID、附件、指令主题、来源授权、大小限制。
2. 测试驱动 SQLite 邮箱/游标/模板版本/发送记录:密文、唯一邮箱、配置版本、幂等、人工确认冲突、历史。
3. 实现 SMTP 验证、IMAP 只读收信、每分钟轮询、停止释放,以及明确操作的测试发信。
4. 接入登录/同源/角色约束的 API;服务生命周期与总览读取真实状态。
5. 新增邮箱管理与模板审核 UI,保留收件群组,迁移旧草稿;浏览器操作验证。
6. 执行全部测试、依赖审计、更新说明,重启并核验正式服务。
工作区无 Git;直接在现有目录实施,凭据仅由用户在 Web 配置。
@@ -0,0 +1,18 @@
# Web Dashboard Implementation Plan
> Execute inline. Reuse Tabler UI; preserve the existing extension bridge.
**Goal:** Deploy a shared authenticated LAN dashboard with persistent settings and export records.
**Spec:** docs/web-dashboard-design.md
**Architecture:** Separate dashboard HTTP server, local persistent store, existing loopback exporter with record callback; locally hosted Tabler assets.
- [x] Write and run failing store tests: defaults, two times validation, optimistic concurrency, user roles and password hashing, persistent job records.
- [x] Implement `src/dashboard-store.cjs` and `src/schedule.cjs`; run store tests.
- [x] Write and run failing HTTP tests: loopback-only bootstrap, sessions, authorization, same-origin mutation, configuration restart persistence and PDF download containment.
- [x] Implement `src/dashboard.cjs`, connect export status callbacks in `src/server.cjs`.
- [x] Install pinned `@tabler/core`; adapt existing Tabler sidebar/cards/tables/forms in `web/`, preserve license.
- [x] Add login/bootstrap, overview, export records, sending plan, templates/groups, users and audit pages with real API bindings.
- [x] Verify full test suite, launch local dashboard, inspect desktop layout and actual save/reload via browser. Narrow viewport override did not change the IAB dimensions; mobile acceptance remains pending.
- [x] Document LAN host/port, deployment-machine setup and pending table/template integration. Do not enable mail sending.
@@ -0,0 +1,15 @@
# 订单通知中心应用框架
用户已授权先搭建运行框架,处理规则后续确定;知会不自动处理。沿用 Node.js/CJS、Tabler 和既有账号/PDF 能力。
本次交付:可运行的工作台;持久业务日历;异常建立、认领、转交、待验证、人工确认关闭;BPM 连接元数据管理;监管策略草稿;本机独立演示空间。真实 BPM 远程浏览器、Cookie 保存、自动扫描、ZCode 调用、对外通知和邮件发送保留接口边界,界面明确尚未接入,不制造成功状态。
多人通过同一服务器访问。viewer 只读,operator 处理异常,admin 管理连接、日历与监管配置。沿用登录、同源校验和审计。连接主站固定新版 bpmn.skyworthdigital.com,详情 bpm.skyworthdigital.com;元数据不接收密码、Cookie 或任意站点 URL。
新增业务框架使用本机 SQLite,既有用户/模板/PDF JSON 保留兼容。日历与监管配置有版本号,异常流转使用版本校验和事务,拒绝并发覆盖。日期必须真实存在;公司显式日期覆盖每周默认规则,采集和发送分别计算;实际发送始终关闭。
异常 status 为 open/in_progress/verifying/resolved。认领仅限未认领,转交须有效团队账号及原因;处理者或管理员提交验证,待验证后以记录人工核验依据关闭;记录每次流转。人工核验只代表工具内记录,不声称对外系统结果已自动验证。
Web 增加工作总览、业务日历、异常待办、BPM 连接、运行监管。保留导出、模板、团队和审计。演示空间绑定 127.0.0.1 独立端口 18776,显著标识示例数据,使用独立本地数据目录和预置虚构数据,不连接业务系统;正式服务仍使用 18766 和账号登录。
验收:日历跨周末覆盖和停发预览;异常重启持久、重复认领冲突、转交审计、只读限制;连接不能伪造已登录;监管设置不能开启实际自动执行;原测试回归;浏览器查看页面及表单提交,截图交付。
@@ -0,0 +1,21 @@
# BPM Web 登录与会话
用户已确认多人在各自电脑访问一台服务器,并明确只维护新版 BPM。唯一业务入口为 https://bpmn.skyworthdigital.com,登录跳转为 https://sso.skyworthdigital.com;不访问、不检查、不提供旧版入口。账号密码由用户在工作台托管表单输入,验证码在远程登录画面完成,不导入现有浏览器 Cookie。
每个连接使用独立 Playwright context,工作台通过受鉴权的 JPEG 帧和有限输入事件控制服务器浏览器。仅连接负责人及管理员可登录或检查。同一连接一次只允许一个工作台登录会话控制,空闲 10 分钟关闭,最多同时 3 个;退出工作台释放其控制。不得暴露 CDP、任意脚本执行、任意网址或 Cookie 接口。生产仅允许新版门户和 SSO 两个 HTTPS 域名,禁止下载和文件上传。
使用 AES-256-GCM 加密 Playwright storageState(含 IndexedDB)和相关 sessionStorage;Windows 主密钥使用当前服务用户的 DPAPI 加密,文件存放本机 LOCALAPPDATA,限制目录权限。远程输入不写入日志、审计、截图文件或连接记录。截图不持久化。恢复会话后必须重新检查。
用户点击“检查并保存”后以新版可观察的已登录账号控件作正向验证,新版验证成功即 connected;没有足够证据显示待登录或检查失败,不存在双入口的 partial 状态。检查不自动点击知会、已阅、审批、发送等动作。需要人工验证建立去重待办,不发送外部通知。旧连接元数据自动去除 detailUrl/checks.detail,旧 partial 转 unchecked,保留负责人、身份及其他业务数据。
远程登录仅允许本机访问或经过明确配置的本机 HTTPS 反向代理,防止通过局域网明文输入密码。普通工作台仍可局域网访问。界面只包含用户操作、状态和简短错误,不展示设计思考或免责声明。
演示服务停止,正式入口继续为 18766,保留已有管理员和业务数据,不创建或重置用户密码。
## 已授权的账号托管补充
用户在正式登录功能部署后明确要求“账号也需要托管”。新增每个连接的 BPM 用户名/密码托管表单,只允许负责人和管理员在本机或可信 HTTPS 访问。用户名、密码整体加密存于独立 vault 条目,不混入会话状态或 SQLite。接口可返回是否配置、用户名和更新时间,绝不返回已保存密码。保存与清除记审计,但不记录密码。
打开登录时,有托管账号则填入已验证的 SSO #username/#password;也提供“填入托管账号”按钮。禁止向其他域名/未知表单填入凭据。停用连接同时关闭浏览器并清除会话和托管账号。
用户随后明确要求无需重复登录与至少 30 天的持续托管。工作台登录改为 30 天持久会话,服务重启继续有效,每日活动续期,退出立即撤销。BPM 由后台启动即检查并每 5 分钟保活,优先恢复有效 Cookie 并保存刷新状态。只有已确认登录过期、可识别且无验证码的正式 SSO 表单才自动提交托管凭据;网络错误或身份冲突不重登。自动提交前持久化 15 分钟冷却,验证码或额外验证转人工窗口;不自动解验证码。新 SSO 实测表单为 #kc-form-login、POST 同源 /realms/skyworthdigital/login-actions/authenticate、button[type="submit"]。外部服务端强制会话期限不可由本工具延长;通过 Cookie 复用及失效续登持续运行。
@@ -0,0 +1,13 @@
# BPM 自动扫描与到达日期视图
日期口径:流程到达当前账号的 startTime,按 Asia/Shanghai 分日。不得用发起日期、流水号中的日期或扫描时间替代。缺失日期拒绝本次扫描,不制造日期。
新版门户公开列表模块经认证实测:GET /skyworth/todo/v2/workflow/get_process_of_inform_v4 与 GET /bpm/worklist/informlist,page/start/limit 分页,响应 total/children。两者均属于新版门户入口,不增加旧网站支持。门户 HTML 提供当前客户端 Bearer,使用服务端加密 Cookie 取回,只在内存使用。
当前待阅仅为临时来源,存储 source 与真实 processName 分开;不预设订单类型过滤,后续用业务表格配置正式范围。扫描仅查询列表,不打开详情、不标记已阅、不审批、不发送邮件。
SQLite 保存到达记录、扫描设置及运行结果。每连接扫描全部分页成功后一次事务入库,连接/source/taskId 唯一;失败不提交半批数据,不删除列表已消失的历史记录。默认每 5 分钟,按业务日历允许扫描的日期运行。允许管理员配置,管理员及连接负责人手动扫描,只读成员查看。连接操作与现有托管互斥;有效 Cookie 优先,仅认证失效才调用既有续登。
订单记录页新增每日分区、到达时间、流水号、流程、当前节点、标题、发起人和连接。日期降序,支持连接/文字过滤、分页加载日期。PDF 导出记录独立保留。显示扫描状态、最近成功、失败原因,不把扫描成功等同业务处理完成。
验证覆盖真实 HTTP 分页/认证/禁止跨域跳转,日期与去重、重启恢复、失败原子性、并发与权限、调度日历;完成后回归全部测试、正式服务扫描与浏览器点击验证。
@@ -0,0 +1,21 @@
# 公司邮箱与邮件模板
用户已指定公司邮箱 SMTP/IMAP;模板必须先解析预览,在 Web 确认后生效。
## 流程
服务接入维护多个邮箱,各自配置 SMTP、IMAP、TLS、登录账号和授权密码、模板发件人白名单。密码加密,状态持久化到部署机 SQLite。检查连接只验证 SMTP/IMAP,不发送邮件。后台每分钟检查启用邮箱;手动检查同样复用去重游标。首次及 UIDVALIDITY 变化只扫描近 7 天,普通邮件保持原状,不标记已读。
主题 `[模板][产品线]发信标题` 导入指定产品线;`[模板]发信标题` 导入默认模板。只接受完整标记、直接发送而非回复/转发、单一授权发件人、投递到本邮箱的邮件。主题去除指令标记,MIME 解码得到正文和附件。HTML 消毒、阻断远程资源,CID 图片本地化;保留原始 EML。每封上限 10 MB,每轮最多 50 封,逐 UID 提交游标,失败可重试且不重复导入。
模板导入为待确认版本,展示标题、范围、正文、图片、附件、来源;管理员可以修改标题、范围和纯文本正文、确认或忽略。确认按相同邮箱和范围归档旧版,保留历史。确认使用导入时的活动版本进行冲突检查,避免多人或旧邮件覆盖新版本。正文调整将切换到纯文本并保留附件。无 AI 自动推断产品线或收件人,模板邮件里的 To/Cc 不会变成业务收件群组。
保留现有产品线群组;旧模板草稿一次性迁入待确认列表。发送接口只使用已确认版本,变量为明确的 `{{产品线}}`、`{{订单号}}`、`{{日期}}`、`{{订单列表}}`,不执行表达式。提供明确点击的发送测试到本邮箱,发送前落库,不自动重试不确定结果。订单批量发送仍由后续业务规则接入。
## 实现
采用 Nodemailer(SMTP)、ImapFlow(IMAP)、MailParser(MIME)、sanitize-html。独立 MailStore/ MailService/ mail API,接入现有认证、同源保护、管理员配置权限和服务启动停止。密钥复用现有 DPAPI/AES-GCM vault 编解码,邮箱和原文内容独立数据库。定时器不重入;邮箱配置修改后检查/收信结果不得写入新版本配置。
## 验证
先写失败测试覆盖 MIME、附件、HTML、授权、去重、确认冲突、密文、重启游标、SMTP 本地实际传输、API 权限。全量回归后部署正式服务,并通过浏览器验证邮箱表单、模板列表及预览操作。真实公司邮箱连接需要用户在网页填写参数后验证。
+13
View File
@@ -0,0 +1,13 @@
# 订单通知书 PDF 工具
> 历史调研或分阶段记录;当前能力与设计要求见 [设计要求](design-requirements.md)。本文件中的订单标识样例已替换为虚构值,旧站点记录不构成兼容要求。
本次范围是将已验证的页面导出步骤固化,生成本地 PDF 并自动命名。Chrome 扩展读取用户主动选择的已登录订单标签页;本地 Node.js 程序负责离线排版和保存。用户只需启动本地程序、在订单页点击扩展导出按钮。暂不加入上传、邮件、审批。
浏览器采用扩展连接,避免启动远程调试端口。扩展权限限制到 BPM 站点、当前标签页和 localhost。读取 DOM、当前控件值、已加载 CSS 与图片,不导出 Cookie、Token、密码、隐藏控件。静态副本通过带随机配对密钥的本机回环接口传给本地程序。程序仅监听 127.0.0.1,离线渲染禁止网络,生成完立即关闭排版浏览器。
按 xdatabind 的 OrderNum、ProductNum、ProductModelNEW、SN 提取订单号、项目编号、产品型号、通知书编号;四项缺失则提示用户检查,不猜测。命名规则为 `订单号_项目编号_型号_通知书编号.pdf`,清理非法文件字符,重名追加序号,不覆盖。输出目录为工作区 `output/pdf`,可配置。页面导出与 XForm 原生打印一致性不作保证。
导出请求立即返回任务编号,本地后台排版,扩展用短请求轮询结果;这样可关闭面板继续处理,扩展重启后也可查询任务状态。本机服务仅保留最近 20 个任务状态,重启后不保留状态,已生成的文件保留。
验收:字段提取、隐藏数据移除、危险文件名、重名保留、鉴权与跨域拒绝有自动化测试;用已采集页面进行真实离线 PDF 回归,并渲染检查。Chrome 扩展首次加载由用户完成,无法替内置浏览器安装扩展。交付时分别说明实际验证与尚待用户加载扩展验证的部分。
+58
View File
@@ -0,0 +1,58 @@
# 订单通知书无人值守系统:目标与实施边界
> 历史调研或分阶段记录;当前能力与设计要求见 [设计要求](design-requirements.md)。本文件中的订单标识样例已替换为虚构值,旧站点记录不构成兼容要求。
更新:2026-10-16(Asia/Shanghai)。本文件根据用户明确的最终目标及原始需求图整理,是下一阶段设计;不表示下列功能已经实现或已启用发送。
## 最终验收目标
工具常驻运行,自动发现符合业务规则的订单,按模板整理通知书、归档并上传 210 服务器,按产品线选择收件群组,每天在两个约定时间自动发送邮件。日常运行不要求用户逐张打开订单、点击扩展或确认打印。保留浏览器操作能力,以兼容 BPM 页面和接口。
现有版本只实现了 PDF 导出基础模块和手动触发的 Chrome 扩展,不满足完整无人值守验收。当前接口记录只有 URL 和部分参数线索,订单列表的权限范围、过滤方式、HTTP 请求和响应尚未联调,不能当作已可用的订单发现接口。
## 完整处理链路
1. **扫描与识别**:按配置访问实际业务列表,分页读取候选订单;按流程类型、完成状态、产品线等规则筛选。区分扫描发现时间和业务更新时间,保存扫描位置并回查一段重叠窗口,避免分页变化或延迟造成漏单。
2. **详情与导出**:浏览器自动进入匹配订单详情,读取命名和模板字段,调用现有静态 PDF 排版模块;不再依赖 activeTab 或用户点击。经过核实的接口可辅助获取列表与数据,浏览器操作作为兼容路径。
3. **整理与归档**:按订单号、项目编号、型号、通知书编号命名;保存结构化字段及模板版本。附件是否下载、是否合并 PDF 由业务规则决定,不能默认把附件条目当作已归档文件。
4. **上传**:通过确认的协议写入 210 服务器指定目录,核实上传结果后记录地址。服务器完整地址、协议、目录和访问方式需要配置。
5. **匹配模板与群组**:根据产品线映射发件配置、收件人/抄送和标题正文模板;缺少映射的订单进入待处理列表,不发送到猜测的群组。
6. **每天两次发送**:调度采用 Asia/Shanghai。按约定时间截取本批次待发订单,按产品线汇总或逐单发送;记录批次、订单版本、收件群组、模板版本与发送结果。
7. **恢复与异常**:进程重启后从持久记录继续。登录失效时提示重新登录;失败任务可重试。邮件超时或连接断开导致结果不明确时标记“待核实”,查询发送方记录或人工核实后再决定是否重发,不承诺邮件链路的严格 exactly-once。
## 运行架构
- **常驻本地程序**:负责周期扫描、任务状态、模板、归档、上传、发送调度及日志。调度属于本工具,不能以对话中的提醒代替实际业务运行。
- **浏览器执行端**:保持可访问 BPM 的浏览器会话,按任务自动打开/检查订单标签页。现有扩展需要增加后台任务入口与就绪判断,不能把手动导出扩展宣称为无人值守版本。
- **持久状态库**:以任务标识与业务版本识别订单,分别记录发现、导出、上传、待发、发送成功、失败、结果待核实。现有内存中最近 20 个导出任务仅适用于手动版,不能充当无人值守状态库。
- **配置与运行面板**:编辑筛选条件、两个发送时间、模板、产品线群组、服务器和邮件渠道;查看当前登录状态、上次扫描、待发量、发送记录及异常。运行账户与敏感配置不写入源码或普通日志。
- **常驻条件**:需要一台在发送时段运行且可访问 BPM、210 服务器和邮件服务的机器。若使用浏览器会话,还需明确公司登录过期策略;没有合法自动续期方式时,不能保证永久不需人工登录。
## 去重与发送语义
- 已处理的同一订单版本不重复加入待发队列。更改单是否作为新通知由业务规则决定。
- 默认首次部署不补发全部历史订单,先预览候选范围,再设置起始时间。
- 多次启动和定时触发通过互斥锁/批次记录防止并行重复处理。
- 正常失败可按限制退避重试;发送结果不明确时停止自动重发该项。
- 停机后是否补发错过的时段、无新增时是否发送空报,均须在调度规则中明确。
## 尚需确认的业务配置
| 配置 | 所需信息 |
|---|---|
| 订单识别 | 实际 BPM 列表入口、流程/产品线、通知触发状态、新单/更改单范围 |
| 两次发送 | 两个北京时间、周末规则、按产品线汇总还是逐单、错过时段的补发策略 |
| 整理模板 | 现成模板路径或示例、必需字段、附件与链接形式 |
| 收件群组 | 产品线对应收件人/抄送,以及没有匹配项时的处理人 |
| 210 上传 | 完整地址、协议、归档目录、文件命名/权限和访问方式 |
| 邮件渠道 | 企业邮箱/SMTP/邮件接口等实际渠道、发件身份与允许的鉴权方式 |
| 运行环境 | 常驻机器、网络访问、开机启动、浏览器登录有效期 |
## 推荐实施顺序
1. 核实业务列表和筛选规则,做只读自动扫描,输出“会处理哪些订单”的清单。
2. 将浏览器自动进入详情、字段采集、现有 PDF 排版接成无需逐单点击的流程,建立持久去重与恢复。
3. 按确认的模板整理并对接 210;生成完整待发邮件预览,验证产品线群组映射。
4. 对接实际邮件渠道及本工具的两个每日时段,验证测试邮件、失败恢复和去重,再启用目标群组的正式自动发送。
用户已经明确要求最终自动发送邮件;当前还缺少实际模板、目标群组和邮件渠道,因此目前不向任何猜测的邮箱发送,也未创建正式发送计划。
+98
View File
@@ -0,0 +1,98 @@
# 验证记录
> 历史调研或分阶段记录;当前能力与设计要求见 [设计要求](design-requirements.md)。本文件中的订单标识样例已替换为虚构值,旧站点记录不构成兼容要求。
## 自动续登设置与托管账号数据库唯一性(2026-10-16,当前版本)
- 页面将“未托管”改为“自动续登未开启”,未配置时提供“开启自动续登”入口;保存账号开启,管理账号可更新密码或关闭。账号字段失焦时只提交用户名查重,提交表单前再检查;过时的检查结果不能覆盖新输入,检查重复时不会发送密码。
- 托管账号写入本机 bpm-sessions/accounts.sqlite,连接 ID 为主键,规范化账号(去除首尾空格、转小写)的 HMAC 摘要有 UNIQUE 约束;账号/密码/重试冷却信息使用原 AES-GCM 封装加密为 BLOB,密钥继续由 DPAPI 保护。两条连接并发保存同一账号仅一条成功;更换为重复账号时,原凭据与 Cookie 保持。原会话文件继续加密保存。
- 服务监听前事务迁移旧账号加密文件,提交后才移除源文件。旧文件存在重复时整批回滚,源文件保留;测试覆盖迁移后的冷却信息、账号读取和唯一性。停用/删除清理数据库账号条目,关闭自动续登释放账号唯一占用并保留有效会话。
- 新增数据库并发/重启/密文、迁移、管理器权限与无损冲突、API 查重和安全返回、页面重复阻止和恢复输入回归,均先复现缺失行为后实现。真实本地 BPM 全栈测试覆盖开启续登后,另一连接查重失败、跳过页面检查直接保存也返回 409、原连接保留登录。
- 全量 `npm test`:89/89 通过,0 失败,0 跳过。初轮暴露旧测试先移除临时目录再关闭重启管理器的问题,已将所有重启实例纳入统一清理,重新运行全量通过。生产修改的五个 JS 文件语法检查通过。
- 正式服务 PID43456,bootstrap required=false/preview=false,stderr 为空。只读检查确认账号数据库和唯一索引建立,当前托管账号数为 0。现有两个活动连接保持已连接;实际页面已打开第一条连接的自动续登表单,账号密码留用户自行录入,尚未将其标为已开启。未保存任何虚构正式账号,未进行 BPM 业务操作。
- 页面截图:output/verification/bpm-auto-renew-setup-2026-10-16.png。此前阶段记录保留如下。
## 直接在画面输入与停用后删除(2026-10-16,当前版本)
- 按用户要求移除画面下方的可见键盘输入区。直接点击远端控件后输入;IME 捕获控件位于点击位置、透明且不拦截鼠标,不增加额外布局。保留远端插入光标,点击不再高亮整个外框;键盘访问画面时仍有焦点提示。处理嵌套事件冒泡,避免普通按键、编辑键和粘贴发送两次。
- 新回归先失败,修正后确认无下方输入框、画面直接物理按键、点击后连续输入、Tab、中文输入,以及既有 IME/粘贴/缩放事件顺序正确。真实本地 BPM 登录全栈测试确认立即保存并在重载后复用 Cookie,符合正式 CSP。
- 已停用连接仅管理员显示“删除”。用户确认后先调用会话管理器的停用清理路径,清除托管账号与 Cookie,再在数据库事务内删除连接并记录审计。未停用、非管理员、跨站、额外参数均拒绝;清理失败保留卡片,以便重试。服务不可用时拒绝删除,避免遗留认证数据。
- 删除存储/API/页面的回归先失败后通过,覆盖取消、确认、权限、前置状态、清理失败、重启后不恢复连接和历史审计保留。使用隔离临时数据,未删除任何正式连接。
- `node --test tests/workspace.test.cjs tests/bpm-http.test.cjs tests/bpm-account.test.cjs tests/bpm-ui.test.cjs tests/bpm-integration.test.cjs`:45/45 通过,0 失败、0 跳过。此前输入修正定向测试(含 bpm-session)27/27 通过。修改的三个 JavaScript 文件语法检查通过。
- 正式服务核实后从 PID32900 更新为 PID35908,18765/18766 监听正常,bootstrap required=false/preview=false,stderr 为空。工作台登录跨服务更新保留。实际打开已保存连接的 BPM 远程画面,直接恢复到已登录的新版门户,确认下方没有输入区;关闭远程窗口后确认两张停用卡片显示删除按钮,未触发删除。
- 页面截图:output/verification/bpm-native-remote-2026-10-16.png;output/verification/bpm-disabled-delete-2026-10-16.png。以下章节保留此前阶段的实现和验证历史。
## 远程画面焦点与键盘输入修正(2026-10-16)
- 用户反馈远程登录只能看到外框聚焦、无法输入。原实现依赖 1px 隐藏 textarea 的 input 事件,画面本身不处理键盘,截图默认隐藏插入光标。新增真实按键回归先失败(画面聚焦后 Ab-1/Backspace 无任何远程输入),修正后通过。
- 参考 noVNC rfb.js 的画面聚焦和键盘事件转发方式,画面增加键盘焦点、普通按键和编辑键转发;鼠标按下即定位远端并获得键盘焦点。保留 IME、粘贴和程序输入的 input 路径,preventDefault 避免重复字符。隐藏 textarea 改为正常尺寸的可见键盘输入区,支持直接点击键入;远程截图保留实际插入光标。
- 定向回归 `node --test tests/bpm-ui.test.cjs tests/bpm-integration.test.cjs tests/bpm-session.test.cjs`:27/27,通过且无跳过。覆盖画面本身的真实物理键盘、可见输入区、中文和粘贴、缩放、密码不留本地、输入顺序、真实本地登录全栈、Cookie/权限/租约/导航边界。修改 JavaScript 语法检查通过。
- 实际连到真实新版 BPM 的独立空会话,在完整工作台宽屏和 616px 窄窗口点击账号框并输入测试文字;修正后逐个发送 q/w/e 原生按键,Tab 切到密码框输入两位虚构测试文字,远端分别显示字符及掩码。未提交 BPM 登录、未使用任何真实账号密码。截图为 output/verification/bpm-remote-input-2026-10-16.png。
- 正式服务 PID32900 已加载新版本,18765/18766 正常,bootstrap required=false/preview=false,新脚本提供可见键盘区和 pointerdown 处理,stderr 为空。工作台账号和业务数据保留。
- 参考源码:https://github.com/novnc/noVNC/blob/master/core/rfb.js 。采用事件处理方式,未引入 VNC 服务或复制 noVNC 源码。
## 新版 BPM 单入口(2026-10-16,当前版本)
- 按用户最新要求仅维护新版 BPM。生产只允许 bpmn.skyworthdigital.com 与 SSO;旧版域名、登录表单、检查、导航、UI 和 partial 状态均移除。新版正向账号验证通过即 connected,checks 仅 portal。
- 先失败后通过回归:新版无需第二入口就 connected、不请求旧版、detail 导航拒绝。连接迁移删除 detailUrl/checks.detail,旧 partial 转 unchecked,保留负责人、身份、历史成功时间及其他数据。原 Cookie 复用、自动续登、冷却、30 天工作台会话测试继续通过。
- 最终 `npm test`:79/79 通过,0 失败,退出 0;39 个 JavaScript 文件语法检查全部通过。独立 delta 审查及 29 项定向验证通过,无阻断问题。
- 正式服务更新为 PID18800,18765 回环桥接及 18766 正式工作台正常,无 18776 演示监听;bootstrap required=false/preview=false,已提供移除旧版控件的新脚本,stderr 0 字节。实际状态保留 1 个用户和 1 个连接,旧版字段已全部迁移移除,工作台持久会话库存在。
- 真实 BPM 账号尚待用户首次在产品托管表单录入;未触碰现有浏览器凭据,未执行任何 BPM 业务动作。长期运行边界同下述记录。
## 正式 BPM 自动账号托管与长期会话(2026-10-16)
- 最终完整回归 `npm test`:76/76 通过,0 失败,退出 0;`node --check` 覆盖 src/web/tests/scripts 共 38 个 JavaScript 文件,均通过。
- 实际 Chrome 本地登录夹具验证:托管账号自动登录一次、后续检查及管理器重启复用 Cookie、同账号保存保留会话、失效自动续登、15 分钟冷却跨重启保留、验证码/未知表单/不安全表单不提交、网络故障不重复提交。密码不出现在返回元数据、审计或存储明文中。
- 独立审查发现门户成功但旧版待验证码时丢弃门户 Cookie,已先复现后修复。新增连续检查及重启回归确认门户只提交一次;网络不确定或身份冲突保留旧加密快照。实际生产 SSO 的表单、控件、POST action 在独立空浏览器中确认,未输入真实凭据。
- 全栈隔离夹具验证正式 CSP 下远程输入/立即保存、首次托管复用已登录 Cookie、账号保存响应不含密码、刷新后管理表单密码仍为空;浏览器无脚本错误或 CSP 拒绝。
- 工作台 token 哈希持久化至 SQLite,验证 30 天到期、29 天活动续期、注销撤销、服务重启同一 Cookie 仍返回 /api/me 200。后台托管启动检查、每 5 分钟检查、交互租约/停用排除、无重叠和停止等待均有回归。
- 通过独立代码审查,未留阻断问题。正式进程从已核实的 PID42884 更新为 PID23632,监听 18765 回环桥接及 18766 正式工作台,无 18776 演示监听。bootstrap/status 为 required=false、preview=false;新前端已提供,stderr 为空,保留原管理员与 BPM 主连接。
- 尚未录入真实托管凭据,因此未证明真实 BPM 的认证续登与长期运行。30 天工作台期限通过时钟场景测试,未等待实际 30 天;外部 BPM 的强制到期依靠续登恢复,不能改写其服务端期限。未执行知会、审批、已阅、订单处理或外部通知。
## 应用框架(2026-10-16)
- 最终完整回归 `node --test tests/*.test.cjs`:27/27 通过,退出码 0;包含原真实 Chrome PDF/扩展回归、新 SQLite 持久化、事务认领冲突、异常转交权限与核验依据、日历日期/时段、只读和同源限制、演示空间隔离测试。
- 对 src/workspace-store.cjs、workspace-api.cjs、dashboard.cjs、schedule.cjs、server.cjs、scripts/preview.cjs、web/workspace.js、app.js 执行 `node --check`,均退出 0。
- 独立审查发现演示与正式空间使用同名 Cookie 会相互覆盖。已改用独立 `order_preview_session`,回归确认两个空间可同时登录、退出演示不影响正式登录;修复经过先失败后通过验证。
- 浏览器实际操作隔离演示空间:进入演示;2026-10-17 从周末默认改为补班并保存,页面重载后保留;认领虚构 BPM 异常并转交 colleague,负责人和历史正确;虚构 PDF 异常提交验证、填写人工核验依据并关闭;新建虚构连接保持未连接;监管负责人及重试次数草稿保存成功。服务重启后异常状态和历史仍保留。
- 现场页面为窄侧栏浏览器,菜单按钮、卡片、月历及详情可用;没有将此记录当作所有桌面/手机尺寸的完整验收。完整页面截图能力不可用,保存了正常视口截图 `output/verification/framework-overview-2026-10-16.png`。
- 正式进程运行于 18765 回环桥接 + 18766 局域网工作台,演示仅监听 127.0.0.1:18776。正式 bootstrap/status 返回 preview=false、required=true,管理员留用户自行设置。演示 preview=true,独立用户和数据。运行日志 stderr 为空。
- 没有从另一台电脑实测局域网访问,没有设置开机自启或修改防火墙。远程 BPM 浏览器登录、Cookie 持久化、ZCode、实际告警、自动处理规则及发送尚未接入。
以下保留此前阶段的历史验证记录。
日期:2026-10-15。环境:Windows,Node.js 24.19.0,Chrome 154,playwright-core 1.62.1。
## 已验证
- `node --test tests/*.test.cjs`:11 项测试通过。覆盖四字段命名、缺字段阻止导出、Windows 非法文件名、真实 PDF 字节、同名文件保留、真实浏览器 DOM 采集、隐藏/密码/操作元素移除、CSS 异步资源按源顺序合并、本地 HTTP 鉴权/跨域/大小限制、异步任务到真实 PDF 的集成、启动准备失败不占用端口,以及扩展重启后的任务恢复。
- 最初 6 项功能测试在实现前均失败;CSS 顺序测试先复现错误,再修正。新增 HTTP 集成使用真实本地服务器和实际 Chrome 排版。
- `npm install --ignore-scripts --no-audit --no-fund` 成功,已生成依赖锁文件。
- JS 语法检查通过。
- 独立代码审查发现并修复了两项问题:扩展准备失败后的端口残留、MV3 长请求导致状态卡住。扩展准备改在监听前完成;导出接口改为立即返回任务编号,扩展短请求轮询进度,面板重开时恢复状态。
- 实际调用 `启动工具.cmd` 已启动回环服务,并生成本机配对配置和本机扩展目录。发现 PowerShell 执行策略禁止脚本后,已改成直接运行 Node,未更改系统策略。
- `node scripts/export-snapshot.cjs --snapshot <先前采集的 snapshot.json> --assets <assets.json> --output output/verification` 实际生成当前订单 PDF:331144 字节,2 页 A4,无 PDF 脚本。已渲染并逐页检查,内容到“订单评审参考资料”。
## 验证边界
- Chrome 扩展尚未在用户 Chrome 里加载,真实登录会话下的扩展点击、权限提示、CSS/图片读取和本机连接仍需加载后验收。测试没有向 BPM 提交或重放请求,没有复制内置浏览器登录状态。
- 页面导出仍是样稿,不能作为 XForm 原生打印一致性证明。软件特性要求/配置表图片区域保留了页面占位;附件仅显示条目,未合并附件文件。
- 当前字段绑定只针对已探查的海外运营订单更改评审 V7 表单。其他订单表单未经验证。
本文件不保存浏览器认证数据。测试快照与回归输出只在本机使用。
## Web 看板(2026-10-16)
- node --test tests/*.test.cjs:17/17 通过。新增持久化/版本冲突、密码哈希/角色、任务记录、上海时区/周末、HTTP 登录与权限、跨站拒绝、PDF 路径限制、旧请求不覆盖新页面测试。
- 独立审查的慢请求覆盖与启动异常端口残留已修复;前者有先失败后通过的回归。浏览器检查发现 Tabler 1.6.1 顶栏 class 导致侧栏隐藏,已按布局规则修正并现场确认。
- 隔离测试服务 127.0.0.1:18767 使用临时测试数据;浏览器登录、侧栏导航和修改时间为 10:30/16:30 后重载保留已确认。测试配置不写入正式数据库。控制台无错误/警告。窄屏覆盖未实际生效,未宣称手机布局验收通过。
- 实际启动工具后,正式看板 127.0.0.1:18766 和原桥接服务 18765 已启动;首次管理员留给用户自行设置。未测试另一台局域网电脑的连通性,未修改防火墙。
- 尚未实现 BPM 无人值守扫描、业务表格匹配、210 上传和邮件发送;没有发送真实邮件或上传业务文件。青龙仅完成官方资料参考。
## 公司 SMTP / IMAP 邮箱与模板审核(2026-10-16)
- 最终 `npm test`:104/104 通过,0 失败、0 跳过,退出 0;日志 `output/verification/mail-full-test-2026-10-16.log`。其中 15 项邮件专项测试覆盖 MIME 中文/HTML/CID/附件、未授权来源、错误主题、加密与唯一邮箱、版本冲突、历史和旧草稿、重启游标与去重、后台不重入、连接验证不发信、真实本地 SMTP 发送、API 权限和正式 CSP 下的浏览器审核流程。
- 8 个新增/修改业务 JS 文件 `node --check` 通过;`npm audit`(含开发依赖)报告 0 漏洞。依赖版本固定到 package-lock.json。
- 独立审查发现并修复:首次空搜索丢失七天边界、范围正则回溯误识别默认模板、轮询反复解密完整历史邮件、CID 重复展开无界内存。分别增加边界回归;列表改读 SQLite 摘要,内嵌图片展开累计限制 12 MB。发信图片使用 CID 附件。
- 隔离真实浏览器操作:填写 SMTP/IMAP 配置并保存、解析 HTML 模板、在隔离 iframe 展示表格、修改发信标题并确认、确认前仍为 pending、390 px 页面无横向溢出。无浏览器脚本错误。
- 正式服务 PID43456 更新为 PID15984,监听 18765 回环桥接及 18766 团队工作台。bootstrap/status:required=false、preview=false。stderr 为空;原工作台登录会话保留。正式页实测“添加邮箱”按钮打开表单、名称输入响应、模板状态筛选及群组入口正常;没有写入测试邮箱或模板。
- 邮件数据库在部署机 `%LOCALAPPDATA%\OrderNotificationAutomation\mail\mail.sqlite`,邮箱密码与完整邮件载荷加密;测试源与接收服务均为隔离本地夹具。公司真实邮箱参数尚未录入,因此未验证其实际 SMTP/IMAP 连通性,没有发送真实公司邮件。
+39
View File
@@ -0,0 +1,39 @@
# 局域网 Web 看板(2026-10-16)
用户已明确:本地部署供局域网同事使用;订单匹配依据后续提供的表格,邮件模板与产品线群组后续提供;每日两次时间和发送方式可设置。界面使用现成开源 UI,不自行设计组件体系。
## UI 选型
实际检索并核对官方资料:
| 方案 | 官方来源 | 适用取舍 |
|---|---|---|
| Tabler | https://tabler.io/admin-template 、 https://preview.tabler.io/ 、 https://github.com/tabler/tabler | MIT 开源版提供 Bootstrap 5 后台布局、卡片、表格、设置页;可直接接入现有 Node 程序,采用此方案 |
| Ant Design Pro | https://github.com/ant-design/ant-design-pro | MIT,React 企业后台完整模板,适合大型前端工程;本项目当前不需要引入整套 Umi 构建工具链 |
| Vben Admin | https://doc.vben.pro/ | MIT,Vue 企业管理框架,可选多种 UI,当前项目接入成本高于 Tabler |
使用 npm 分发的 `@tabler/core`,保留许可证和归属信息,不购买或复制 Pro 专属素材。资源全部从本机提供,不使用远端 CDN、在线字体或演示业务数据。沿用现成 Tabler 页面布局和组件,仅替换中文业务字段和数据绑定。
## 本阶段可交付功能
- 独立 Web 服务(默认 18766,与扩展回环服务 18765 分开),可配置局域网监听。
- 首次从部署机创建管理员,后续账号登录;管理员创建操作员/只读账号。普通浏览访问不含扩展配对密钥。
- 看板显示真实 PDF 导出记录、任务状态、接入缺项、计划时间;不添加虚构订单和发送成功记录。
- 每日两次时间、周末、逐单/产品线汇总、错过时段策略可保存;时区 Asia/Shanghai,未接通业务与邮件服务时明确未启用发送。
- 模板草稿和产品线收件群组可编辑保存,表格映射待真实样表后接入。
- 持久化设置、用户、导出记录和操作记录,重启保留;并发修改使用版本校验防止静默覆盖。
- 保留现有扩展导出,成功/失败状态同步到 Web 记录,并可在登录后下载已完成 PDF。
## 本阶段不假定的内容
订单扫描/匹配、210 上传、邮件发送不能在表格、模板和渠道未提供时伪造实现或启用。看板显示配置就绪程度,现有配置表单是后续连接器的输入,不代表连接器已联调。后续依据样表补充导入、列映射和匹配预览。
## 验证
先写测试验证持久化、配置验证、版本冲突、账号权限、首次设置限制、跨站请求拒绝和 PDF 记录/下载;通过后使用浏览器检查桌面与窄屏看板、设置保存和非管理员界面。保留原 PDF 回归测试。
## 调度参考:青龙面板
2026-10-16 按用户要求核对 https://github.com/whyour/qinglong 。官方 README 列出任务日志、秒级定时、通知、移动端与内置 API;演示入口跳至登录页,未进入其受保护功能。当前仅作架构和交互参考,不声称已部署或集成青龙。
后续调度按“任务定义 → 执行批次 → 日志”组织:任务名、时间/cron、启停状态、上次结果、下次时间;提供手动运行、日志与失败重试。日常使用保留每天两次的简单设置,cron 作为高级模式。BPM 采集、PDF 整理、210 归档、邮件批次划分步骤;同一任务防重叠,邮件按订单/版本/收件组记录发送状态,避免重启或重试重复发送。上述执行器功能尚未实现。
+141
View File
@@ -0,0 +1,141 @@
# BPM Web 结构与接口线索
> 历史调研或分阶段记录;当前能力与设计要求见 [设计要求](design-requirements.md)。本文件中的订单标识样例已替换为虚构值,旧站点记录不构成兼容要求。
首次采集:2026-10-15(Asia/Shanghai),旧站点:https://bpm.skyworthdigital.com/ 。2026-10-16 已补充新版门户实地观察,后续以新版 `https://bpmn.skyworthdigital.com/` 为主;旧域名仍承接已观察的订单详情。
范围:登录后的首页及用户提供的海外运营订单更改评审 V7 页面。仅分析技术结构,不以业务表单内容作为接口文档;未调用审批、已阅、讨论、发送邮件或上传操作。
## 证据等级
- **加载记录**:内置浏览器 pageAssets 资源清单实际列出了该请求 URL;不代表已经核实 HTTP 方法、状态码、请求体、响应格式或接口权限。
- **源码线索**:当前页面 DOM 中的内联脚本或控件属性引用该入口;不代表当前页面执行过该分支。
- 当前浏览器工具未提供完整 Network 请求体和响应体,因此不能把以下路径作为已经完成联调的 API。
## Web 结构
```text
BPM 首页(ASP.NET / ExtJS)
├─ /BPM/MainWindow.js 与 YZSoft/Frame/Classic/Scripts/Frame.js
├─ 导航树:MainModuleTree.ashx、BPMModuleTree.ashx
├─ 历史任务模块:HistoryTask*Panel.js / HistoryTaskStore.js / HistoryTaskGrid.js
│ └─ /YZSoft/BPM/StoreDataService/HistoryTask.ashx
└─ 业务表单:/YZSoft/Forms/XForm/.../*.aspx
├─ XFormCore.js / XFormAgent.js / XForm.js
├─ XMLService/DataProvider.ashx
├─ ProcessStep.ashx
└─ Attachment/GetAttachment.ashx 与自定义附件处理器
```
可确认是 ASP.NET Web Forms 风格(`.aspx`、`WebResource.axd`、表单 POST),前端为 ExtJS、jQuery、YZSoft XForm。表单内联变量声明 `XFormAgentVer = "3.1.0.5"`;该值不能当作整个 BPM 产品的版本号。页面有 `xdatabind` 数据绑定属性。站点同时存在 `.ashx` 处理器及少量 `/api/` 路由,不能据此断定所有服务都是 REST API。
## 入口清单
以下以站点根路径为基准,忽略 `_dc`、`r` 等时间戳或随机参数。
| 路径 | 已见参数 | 用途及证据 |
|---|---|---|
| `/BPM/MainModuleTree.ashx` | `_dc` | 首页导航入口;加载记录 |
| `/BPM/BPMModuleTree.ashx` | `node=root` | 流程模块导航;加载记录 |
| `/YZSoft/BPM/StoreDataService/HistoryTask.ashx` | `start`、`limit`、`HistoryTaskType=MyRequest`、`SpecProcessName`、`byYear=1`、`Year` | 历史流程列表;加载记录。待确认订单流程过滤与权限范围 |
| `/YZSoft/BPM/XMLService/DataProvider.ashx` | URL 仅见 `_dc` | 表单数据服务候选;加载记录。真正的操作类型和业务参数可能在请求体,尚未采集 |
| `/YZSoft/BPM/ProcessStep.ashx` | `TaskID`、`r` | 流程步骤;加载记录 |
| `/YZSoft/Attachment/GetAttachment.ashx` | URL 仅见 `_dc` | 附件相关服务;加载记录。不能仅凭名称断言它直接返回文件二进制 |
| `/ASHX/YZAttachmentInfo.ashx` | `fids`,逗号分隔 | 附件信息服务候选;加载记录 |
| `/ashx/OrderReview/RevertRecordModifyHandle.ashx` | `TaskID`、`Field` | 订单变更记录相关;加载记录。仅观察,未重放,修改性需另核实 |
| `/ashx/BPMOwnerPosition.ashx` | `tid` | 归属/岗位相关服务候选;加载记录 |
| `/MyApp/Demo/TaskComment/MyData.ashx` | `TaskId`、`ParentId`、`AppName`、`AppKey`、`curindex` | 讨论数据相关;加载记录 |
| `/api/PLM/MyTask` | `uid` | 首页 PLM 任务对接;加载记录,与订单接口不能混同 |
| `/sso/KeycloakAuth.ashx` | `action=check` | SSO 状态检查候选;加载记录。未读取或保存认证内容 |
| `/ASHX/MasterData/POExportExcelHandler.ashx` | `Action=HWDetail`、`TaskID` | 页面 `downMatDetail()` 通过 `location.href` 导航,属于物料 Excel 导出源码线索,不能当作通知书 PDF 接口 |
| `http://172.28.17.108/api/sdt-rdm/product/bpmGetOne` | `projNo`、`r` | 页面 `$.ajax` 源码线索。未声明 `type/method`,按 jQuery 默认语义为 GET;回调引用 `re.data`,但未实测返回、内网可达性或跨域行为 |
## 打印与 PDF
打印控件 `#XPrintButton1` 的 DOM 属性为:
```javascript
XFormPrint(this, 'ori=v;zm=60;ml=2;mt=20;mr=2;mb=10;ph=;pf=', true);
```
这证明页面通过 XForm 打印函数进入打印链路。点击时浏览器工具超时;随后未观察到新标签、JavaScript 对话框或新增资源 URL。因此本次不能确认打印已成功,更不能确认存在服务端 PDF 下载接口。
后续需核实 `XFormPrint` 实现、是否打开打印预览、是否依赖客户端组件,以及打印样式、页码、签名和分页的输出效果。
## 后续工具要求
用户明确要求最终工具能直接操作浏览器。设计时应保留浏览器控制能力,包括启动或连接、人工登录后继续、导航、点击、等待及文件下载;接口调用可作为提高效率的手段。端口连接和独立浏览器配置的最终方案尚未确定。
以上为旧入口阶段的后续方向。2026-10-16 起优先核实新版待阅/知会列表的范围、分页与只读接口,再结合既有详情核实 DataProvider、附件和 PDF 链路;不再默认旧 HistoryTask 是正式列表来源。不要重放审批、已阅、讨论、邮件或上传请求。
本记录不包含密码、Cookie、Token 或完整业务表单数据。
## 本地 PDF 导出实验
2026-10-15:内置浏览器原生打印弹窗未通过现有控制能力完成。为交付样稿,提取已登录页面的静态 DOM、可见控件值、已加载 CSS 与 logo,在禁止网络访问的本地排版进程中生成 PDF,无需人工点保存。移除了脚本、隐藏字段、讨论输入和流程操作控件;未执行提交、审批、邮件或上传操作。
输出:`output/pdf/900001_DEMO-PROJECT-001_DEMO-MODEL_DEMO-CHANGE-001.pdf`。命名规则为 `订单号_项目编号_产品型号_通知书编号.pdf`。最终文件为两页 A4、331560 字节;已逐页渲染检查,并核对四个命名标识和正文末端的参考资料标题。
该文件是页面导出样稿,不是已联调的服务器 PDF 下载结果。图片区域、窄控件和分页经过本地处理,尚未验证与 XForm 原生打印一致;不能据此认定 PDF 接口或原生打印自动化已打通。
## 2026-10-16:新版门户与“知会”样本
用户自行登录新版门户,并要求后续以新版为主。当前已登录入口为 `https://bpmn.skyworthdigital.com/#`,标题“创维数字流程门户”。本次仅查看列表和必要订单样本,没有复制 Cookie,也没有点击已阅、知会、讨论、审批或发送提醒邮件按钮。
### 已验证的导航与跨域结构
```text
新版门户 bpmn.skyworthdigital.com
└─ 流程 → 待阅
├─ 普通待阅 (1):一条采购申请
└─ BPMV4 (6):五条订单 + 一条采购申请
└─ 订单详情仍在 bpm.skyworthdigital.com
/YZSoft/Forms/XForm/.../*.aspx?tid=...&pid=...
```
列表编号链接为 `a.yz-worklist-sn`,`href="#"`;实际点击后才能取得详情路由,不能仅收集锚点 href。当次查看后列表计数仍为 6,但不能据此证明打开详情无自动阅读副作用。
| 表单类型 | 样本编号 | 订单号 | 详情 tid / pid |
|---|---|---|---|
| 零售产品部订单评审 V12 | DEMO-RETAIL-001 | 900002 | 800001 / 700001 |
| 备损订单评审 V5 | DEMO-SPARE-001 | 900003 | 800002 / 700002 |
| 宽带事业订单评审 V16 | DEMO-BROADBAND-001 | 900004 | 800003 / 700003 |
| 海外运营订单更改评审 V7 | DEMO-CHANGE-001 | 900001 | 800004 / 700004 |
| 海外运营订单评审 V13 | DEMO-ORDER-001 | 900005 | 800005 / 700005 |
以上列表接收日期均为 2026-10-15,状态均显示“知会”。此状态不能直接作为流程全部审批完成的证据。宽带记录摘要还出现 `HA900004` 及另一个公司/订单信息块,尚未核实关联语义;不能强制一条来源记录对应一个业务订单。
### 已加载的新门户资源线索
以下来自 pageAssets 清单,已去除查询字符串;仍不代表已核实方法、响应体或用途:
| 路径 | 可支持的观察与边界 |
|---|---|
| `/bpm/account/info` | 账号信息候选;没有读取认证值或响应结构 |
| `/bpm/worklist/counts`、`/bpm/worklist`、`/navigator/bpm/worklist` | 工作列表及计数相关候选;未确认哪个专门返回 BPMV4 知会、筛选及分页参数 |
| `/Yzsc/features/web/override/Yiez/workflow/worklist/Informlist.js` | 知会列表模块资源线索 |
| `/Skyworth/Portal/src/component/Informlist.js` | 门户知会组件资源线索 |
| `/Skyworth/ToDoV2/panel/WorklistV4Panel.js`、`WorklistV8Panel.js` | 新旧代际工作列表面板资源线索 |
| `/portal/calendar/dates`、`/portal/calendar` | 门户日历候选;可见日历包含会议/备忘/用车,不能视为公司工作日历接口 |
| `/hubs/system/negotiate`、`/hubs/notice/negotiate` | 实时通道协商资源线索;不能据此认定完整事件协议或漏消息恢复能力 |
本次没有重放这些请求。下一步如实现接口采集,需在合法执行会话内另核实请求/响应和只读性。
### 字段适配的实际差异
- 零售:`OFR_LSCP_Applicant.OrderNum`、`.SN`,型号 `OFR_LSCP_BInfo.ProductModel`。
- 备损:`OFR_BS_Applicant.OrderNum`、`.SN`、`.ProductLine`;项目及型号的等价字段尚未确认。
- 宽带:`OFR_KD_Applicant.OrderNum`、`.SN`、`.OrderNum_Original`,型号 `OFR_KD_BInfo.ProductModel`;项目的确切绑定尚未确认。
- 海外 V7/V13:`OFR_WY_Applicant.OrderNum`、`.SN`,项目 `OFR_WY_BInfo.ProductNum`,完整型号 `.ProductModel` 与短型号 `.ProductModelNEW` 均存在,不能混用。
实际编号 LABEL 控件可出现 `.value` 为空而 `.textContent` 非空;当前 `extension/capture.js` 使用 `value ?? textContent` 会忽略这种回退。还需处理同一绑定出现在多个控件上的情况。建议按表单类型和版本注册适配器,按控件类型读取并校验必填项。本次仅记录兼容问题,未修改代码。
零售样本可见 `.xls` BOM 对比附件,锚点 href 为 `###`。这证明存在附件入口,不证明有直接下载 URL,也不证明附件应随通知发送。
### 会话设计要求与剩余问题
用户已确认 Web 面向“多人在各自电脑访问同一台服务器”。正式方案应在 Web 中提供服务器专用浏览器的交互登录画面,由人完成 BPM 登录和验证码;会话保存在执行端,并验证新版门户与旧域名详情均可访问。普通跳转到同事本机浏览器无法把登录态自动交给服务器,跨域 iframe 读取 Cookie 也不可作为实现方案。
不提取本次会话;后续使用隔离 profile/认证状态、连接级权限和本地凭据保护。登录失效接入异常待办与续登,续登期间暂停同一连接的自动采集。完整设计见 [架构调研第 12 节](project-architecture-research-2026-10-16.md#12-新增要求web-人工登录与持久-bpm-会话)。
仍需明确:历史/已读来源范围、分页与排序;知会与业务触发条件;来源 ID/流程 ID/订单版本关系;多订单标识含义;各表单产品线/项目字段;自动阅读副作用;会话跨重启与过期行为。上述五类样本不能替代完整联调。
+46
View File
@@ -0,0 +1,46 @@
// Self-contained function: injected only after the user clicks Export.
function captureOrder() {
const source = document.querySelector('form');
if (!source) throw new Error('当前页面没有订单表单,请进入 BPM 订单详情。');
const bindings = { order:'OFR_WY_Applicant.OrderNum', project:'OFR_WY_BInfo.ProductNum', model:'OFR_WY_BInfo.ProductModelNEW', serial:'OFR_WY_Applicant.SN' };
const labels = { order:'订单号', project:'项目编号', model:'产品型号', serial:'通知书编号' };
const metadata = {};
for (const [key, binding] of Object.entries(bindings)) {
const el = source.querySelector(`[xdatabind="${binding}"]`);
metadata[key] = (el?.value ?? el?.textContent ?? '').trim();
}
const clone = source.cloneNode(true);
const originals = [source, ...source.querySelectorAll('*')];
const copies = [clone, ...clone.querySelectorAll('*')];
for (let index = originals.length - 1; index >= 0; index--) {
const original = originals[index], copy = copies[index];
const style = getComputedStyle(original);
const type = (original.getAttribute('type') || '').toLowerCase();
const tag = original.tagName.toLowerCase();
if (['script','iframe','object','embed','button','link','meta'].includes(tag) || ['hidden','password','button','submit','reset','file'].includes(type) || style.display === 'none' || style.visibility === 'hidden' || original.hidden || original.getAttribute('printout') === 'false') {
copy.remove(); continue;
}
if (['input','textarea','select'].includes(tag)) {
const span = document.createElement('span');
span.className = original.className;
span.style.cssText = 'display:inline-block;max-width:100%;white-space:pre-wrap;overflow-wrap:break-word;min-height:1em;';
span.textContent = ['checkbox','radio'].includes(type) ? (original.checked ? '☑' : '☐') : tag === 'select' ? [...original.selectedOptions].map(option => option.textContent).join('、') : original.value;
copy.replaceWith(span);
} else {
for (const attribute of [...copy.attributes]) {
if (/^on/i.test(attribute.name) || ['action','srcdoc','srcset','formaction','value'].includes(attribute.name.toLowerCase())) copy.removeAttribute(attribute.name);
}
if (tag === 'img') copy.setAttribute('src', original.src);
}
}
for (const id of ['taskCommentForm','TaskCommentCount']) {
const el = clone.querySelector('#'+id);
if (el) el.remove();
}
const styles = [...document.querySelectorAll('style')].map(el => el.textContent);
const stylesheetUrls = [...document.querySelectorAll('link[rel="stylesheet"][href]')].map(el => el.href);
const styleSources = [...document.querySelectorAll('style,link[rel="stylesheet"][href]')].map(el => el.tagName.toLowerCase() === 'style' ? {text:el.textContent} : {url:el.href});
const imageUrls = [...clone.querySelectorAll('img[src]')].map(el => el.getAttribute('src'));
return { metadata, html:clone.outerHTML, styles, styleSources, stylesheetUrls, imageUrls:[...new Set(imageUrls)], width:1264, missing:Object.keys(bindings).filter(key => !metadata[key]).map(key => labels[key]), warnings:[] };
}
if (typeof module !== 'undefined') module.exports = { captureOrder };
+10
View File
@@ -0,0 +1,10 @@
{
"manifest_version": 3,
"name": "订单通知书 PDF",
"version": "0.1.0",
"description": "将当前已登录的 BPM 订单页面导出为自动命名的本地 PDF。",
"permissions": ["activeTab", "scripting", "storage"],
"host_permissions": ["https://bpm.skyworthdigital.com/*", "http://127.0.0.1/*"],
"background": { "service_worker": "worker.js" },
"action": { "default_popup": "popup.html", "default_title": "导出订单通知书" }
}
+1
View File
@@ -0,0 +1 @@
*{box-sizing:border-box}body{margin:0;width:360px;padding:24px;background:#f6f7f5;color:#1e302b;font:14px/1.6 "Microsoft YaHei",sans-serif}.eyebrow{color:#557269;font-size:11px;letter-spacing:1px}h1{font-size:24px;line-height:1.4;margin:7px 0 12px}.intro{color:#52665e;margin:0 0 22px}button{width:100%;border:0;border-radius:8px;background:#17684f;color:white;padding:12px;font:600 14px "Microsoft YaHei",sans-serif;cursor:pointer}button:hover{background:#10563f}button:disabled{opacity:.65;cursor:wait}section{margin-top:20px;padding:14px;background:white;border:1px solid #dce4df;border-radius:8px;overflow-wrap:anywhere}.label{font-size:11px;color:#698075}section p{margin:6px 0 0;white-space:pre-wrap}.error{color:#a73d2b}.success{color:#13765b}.hint{font-size:11px;color:#6b7c74;margin:16px 0 0}
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>订单通知书</title><link rel="stylesheet" href="popup.css"></head>
<body>
<div class="eyebrow">BPM · 本地归档</div>
<h1>订单通知书</h1>
<p class="intro">将当前订单页面保存为 PDF,自动按订单和项目命名。</p>
<button id="export">导出当前订单</button>
<section id="status" aria-live="polite"><span class="label">使用方式</span><p>先启动本地工具,再打开已登录的订单详情页。</p></section>
<p class="hint">导出在后台继续,可关闭此面板。文件保存在本地输出目录。</p>
<script src="popup.js"></script>
</body>
</html>
+23
View File
@@ -0,0 +1,23 @@
const button = document.querySelector('#export');
const status = document.querySelector('#status');
function show(value) {
if (!value) return;
button.disabled = value.status === 'running';
status.replaceChildren();
const label = document.createElement('span'); label.className='label'; label.textContent=value.status==='success'?'导出完成':value.status==='error'?'需要处理':'导出进度';
const text = document.createElement('p'); text.className=value.status; text.textContent=value.message;
if (value.filename) text.textContent+='\n'+value.filename+'\n'+value.path;
if (value.warnings?.length) text.textContent+='\n\n'+value.warnings.join('\n');
status.append(label,text);
}
chrome.storage.session.get('lastExport').then(data=>show(data.lastExport));
chrome.runtime.sendMessage({type:'status'}).then(result=>{if(result.ok)show(result.value);},error=>show({status:'error',message:error.message}));
chrome.storage.onChanged.addListener((changes,area)=>{if(area==='session' && changes.lastExport)show(changes.lastExport.newValue);});
button.addEventListener('click',async()=>{
button.disabled=true;
try {
const [tab] = await chrome.tabs.query({active:true,currentWindow:true});
const result = await chrome.runtime.sendMessage({type:'export',tabId:tab.id});
if (!result.ok) show({status:'error',message:result.error});
} catch(error) {show({status:'error',message:error.message});}
});
+117
View File
@@ -0,0 +1,117 @@
importScripts('local-config.js', 'capture.js');
const config = globalThis.ORDER_LOCAL_CONFIG;
const state = value => chrome.storage.session.set({ lastExport:value });
let running = false;
async function requestLocal(route, body) {
const response = await fetch(config.endpoint + route, {
method: body ? 'POST' : 'GET',
headers: { 'Content-Type':'application/json', 'X-Order-Token':config.token },
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(10000)
});
const result = await response.json();
if (!response.ok) throw new Error(result.error || '本地导出服务返回错误。');
return result;
}
async function collectAssets(snapshot) {
const allowed = 'https://bpm.skyworthdigital.com';
snapshot.images = [];
const jobs = [
...[...new Set(snapshot.stylesheetUrls || [])].map(url => ({url,kind:'css'})),
...(snapshot.imageUrls || []).map(url => ({url,kind:'image'}))
];
if (jobs.length > 100) throw new Error('页面资源过多,请确认当前标签页是单个订单详情。');
let total = 0;
const collected = await Promise.all(jobs.map(async ({url,kind}) => {
try {
if (kind === 'image' && /^data:image\/(png|jpeg|gif|webp);base64,/i.test(url)) { snapshot.images.push({url,data:url}); return; }
if (new URL(url).origin !== allowed) throw new Error('不属于 BPM 站点');
const response = await fetch(url,{credentials:'include',redirect:'error',signal:AbortSignal.timeout(15000)});
if (!response.ok) throw new Error('读取失败');
const bytes = new Uint8Array(await response.arrayBuffer());
total += bytes.length;
if (bytes.length > 3*1024*1024 || total > 12*1024*1024) throw new Error('资源超过大小限制');
const mime = (response.headers.get('content-type') || '').split(';')[0];
if (kind === 'css') {
if (!/text\/css/i.test(mime)) throw new Error('样式资源格式不匹配');
return {url,css:new TextDecoder('utf-8').decode(bytes)};
} else {
if (!/^image\/(png|jpeg|gif|webp)$/i.test(mime)) throw new Error('图片格式暂不支持');
let binary = '';
for (let i=0;i<bytes.length;i+=32768) binary += String.fromCharCode(...bytes.subarray(i,i+32768));
snapshot.images.push({url,data:`data:${mime};base64,${btoa(binary)}`});
}
} catch {
snapshot.warnings.push(kind === 'css' ? '有一项页面样式未能嵌入,请核对输出排版。' : '有一张图片未能嵌入,请核对图片区域。');
}
}));
const cssByUrl = new Map(collected.filter(Boolean).map(item=>[item.url,item.css]));
snapshot.styles = snapshot.styleSources ? snapshot.styleSources.map(item=>item.url ? cssByUrl.get(item.url) || '' : item.text || '') : [
...(snapshot.stylesheetUrls || []).map(url=>cssByUrl.get(url) || ''), ...snapshot.styles
];
delete snapshot.styleSources;
delete snapshot.stylesheetUrls;
delete snapshot.imageUrls;
snapshot.warnings = [...new Set(snapshot.warnings)];
return snapshot;
}
async function exportTab(tabId) {
if (running) throw new Error('正在导出,请稍候。');
running = true;
try {
await state({status:'running',message:'正在连接本地工具…'});
await requestLocal('/health');
const tab = await chrome.tabs.get(tabId);
if (!tab.url || new URL(tab.url).origin !== 'https://bpm.skyworthdigital.com') throw new Error('请先切换到 BPM 订单详情标签页。');
const results = await chrome.scripting.executeScript({target:{tabId},func:captureOrder});
const snapshot = results[0]?.result;
if (!snapshot) throw new Error('未采集到订单页面,请刷新订单后再试。');
if (snapshot.missing.length) throw new Error('缺少'+snapshot.missing.join('、')+'。请检查是否进入正确的订单详情页。');
await state({status:'running',message:'正在生成 '+snapshot.metadata.order+' 的 PDF…'});
const accepted = await requestLocal('/export', await collectAssets(snapshot));
await state({status:'running',jobId:accepted.jobId,message:'正在排版 '+snapshot.metadata.order+' 的 PDF…'});
let result;
const deadline=Date.now()+120000;
while (Date.now()<deadline) {
result=await requestLocal('/jobs/'+accepted.jobId);
if (result.status!=='running') break;
await new Promise(resolve=>setTimeout(resolve,750));
}
if (!result || result.status==='running') throw new Error('排版用时较长,请检查输出目录,稍后重试。');
if (result.status==='error') throw new Error(result.error);
await state({status:'success',message:'已保存',...result});
await chrome.action.setBadgeText({text:'✓'});
await chrome.action.setBadgeBackgroundColor({color:'#13765b'});
return result;
} catch(error) {
const message = /Failed to fetch|fetch failed|NetworkError/i.test(error.message) ? '无法连接本地工具。请先双击“启动工具.cmd”,保持窗口运行。' : error.message;
await state({status:'error',message});
await chrome.action.setBadgeText({text:'!'});
await chrome.action.setBadgeBackgroundColor({color:'#b44334'});
throw new Error(message);
} finally { running = false; }
}
async function currentState() {
let value=(await chrome.storage.session.get('lastExport')).lastExport;
if (value?.status==='running' && !running) {
try {
if (!value.jobId) throw new Error('上次采集被中断,请检查输出目录后重试。');
const job=await requestLocal('/jobs/'+value.jobId);
if (job.status==='success') value={...job,message:'已保存'};
else if (job.status==='error') value={status:'error',message:job.error};
} catch(error) {value={status:'error',message:error.message};}
await state(value);
}
return value;
}
chrome.runtime.onMessage.addListener((message,sender,sendResponse) => {
if (sender.id !== chrome.runtime.id) return;
if (message.type==='status') {currentState().then(value=>sendResponse({ok:true,value}),error=>sendResponse({ok:false,error:error.message}));return true;}
if (message.type !== 'export') return;
exportTab(message.tabId).then(result=>sendResponse({ok:true,result}),error=>sendResponse({ok:false,error:error.message}));
return true;
});
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-2026 The Tabler Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+860
View File
@@ -0,0 +1,860 @@
{
"name": "order-notification-pdf-tool",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "order-notification-pdf-tool",
"version": "0.1.0",
"dependencies": {
"@tabler/core": "1.6.1",
"@whyour/qinglong-cli": "0.1.2",
"imapflow": "2.4.3",
"mailparser": "3.9.39",
"nodemailer": "10.1.1",
"playwright-core": "1.62.1",
"sanitize-html": "2.18.1"
},
"devDependencies": {
"smtp-server": "3.19.22"
},
"engines": {
"node": ">=22.13"
}
},
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
"integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==",
"license": "MIT"
},
"node_modules/@popperjs/core": {
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
"integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@selderee/plugin-htmlparser2": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/@selderee/plugin-htmlparser2/-/plugin-htmlparser2-0.12.0.tgz",
"integrity": "sha512-oELmoyA6ML9jDRMV3kgcMQFKxUfBU0yFVn6yTctVaLT5ygXnxH52I3TZEgV9EhXJC68/uFvE5Daj1/25c0Xa/A==",
"license": "MIT",
"dependencies": {
"domelementtype": "~2.3.0",
"domhandler": "~5.0.3"
},
"funding": {
"url": "https://github.com/sponsors/KillyMXI"
},
"peerDependencies": {
"selderee": "~0.12.0"
}
},
"node_modules/@tabler/core": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/@tabler/core/-/core-1.6.1.tgz",
"integrity": "sha512-lgmR9gcxRp5JlLxcmRi9Rz85JrEvH6Bz71KnlcPVSa97wtwQNjgSs3g3fxwbAlulHyRMghhIV04QUuW3pqDsIg==",
"license": "MIT",
"dependencies": {
"@popperjs/core": "^2.11.8"
},
"engines": {
"node": ">=20"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/codecalm"
},
"peerDependencies": {
"vanilla-calendar-pro": "^3.3.2"
},
"peerDependenciesMeta": {
"vanilla-calendar-pro": {
"optional": true
}
}
},
"node_modules/@whyour/qinglong-cli": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/@whyour/qinglong-cli/-/qinglong-cli-0.1.2.tgz",
"integrity": "sha512-G9b74lDagwBvHV0POSBAlXh1vcccm5B14t8xGsnPFgA7RWfHLOxMvEaTvemrkv4gaXJccSarHjyfodgN5duWQA==",
"license": "Apache-2.0",
"bin": {
"ql": "dist/npm/ql.js"
},
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/@zone-eu/mailsplit": {
"version": "5.4.21",
"resolved": "https://registry.npmjs.org/@zone-eu/mailsplit/-/mailsplit-5.4.21.tgz",
"integrity": "sha512-a7DjD8zysu77OeLuAZRTMC6NDALc3smuKkaZv1QTJkq2kMa5CbEgVQuC7Nfd9LfMO92bkjxT41t8L3mkWDZe1Q==",
"license": "(MIT OR EUPL-1.1+)",
"dependencies": {
"libbase64": "1.3.3",
"libmime": "5.4.8",
"libqp": "2.1.2"
}
},
"node_modules/atomic-sleep": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
"integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",
"license": "MIT",
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/dayjs": {
"version": "1.11.23",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
"integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==",
"license": "MIT"
},
"node_modules/deepmerge-ts": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-8.0.2.tgz",
"integrity": "sha512-uqbvqLUMrc6p0MO+WBRtTxY55hmyh94WRwI5a++PZe54X+bfVh59FSN7uWCBCW1CCVjzjnrwzfI8zidE2obMMw==",
"funding": [
{
"type": "ko-fi",
"url": "https://ko-fi.com/rebeccastevens"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/deepmerge-ts"
}
],
"license": "BSD-3-Clause",
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/dom-serializer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
"integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
"license": "MIT",
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.2",
"entities": "^4.2.0"
},
"funding": {
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
}
},
"node_modules/domelementtype": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
"integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause"
},
"node_modules/domhandler": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
"integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^2.3.0"
},
"engines": {
"node": ">= 4"
},
"funding": {
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/domutils": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
"integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
"license": "BSD-2-Clause",
"dependencies": {
"dom-serializer": "^2.0.0",
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3"
},
"funding": {
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/encoding-japanese": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/encoding-japanese/-/encoding-japanese-2.4.0.tgz",
"integrity": "sha512-PE0KjlsDy9JSsoU4C2Q8NXb1kC4c+bZRac9ZvHXUE4q1Ht63gScKMdEy9jst9+Fi3M4eDkqzkEhBZvix4blP2A==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/escape-string-regexp": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
"integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/he": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz",
"integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==",
"license": "MIT",
"bin": {
"he": "bin/he"
}
},
"node_modules/html-to-text": {
"version": "10.0.1",
"resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-10.0.1.tgz",
"integrity": "sha512-GiVhRI1BatGARSCmlXWNCjDT0cWrwBWoeduLoV0WSKAgaV/wa+hUWy5LiQLUs4UwiUrE52ZCMfBGiKD87TDPrg==",
"license": "MIT",
"dependencies": {
"@selderee/plugin-htmlparser2": "~0.12.0",
"deepmerge-ts": "^8.0.1",
"dom-serializer": "^2.0.0",
"htmlparser2": "^10.1.0",
"selderee": "~0.12.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"url": "https://github.com/sponsors/KillyMXI"
}
},
"node_modules/htmlparser2": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
"integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==",
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "MIT",
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3",
"domutils": "^3.2.2",
"entities": "^7.0.1"
}
},
"node_modules/htmlparser2/node_modules/entities": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
"integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/iconv-lite": {
"version": "0.7.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
"integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
"engines": {
"node": ">=0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/imapflow": {
"version": "2.4.3",
"resolved": "https://registry.npmjs.org/imapflow/-/imapflow-2.4.3.tgz",
"integrity": "sha512-n9JLurmTDHRYacQXvi7zlNIuyeG7sjsKAXI1nyJ1cFqd1fHwqVXf1UOnmTL/GwnFURvDnQ6H0akuwltyffxyUA==",
"license": "MIT",
"dependencies": {
"@zone-eu/mailsplit": "5.4.21",
"encoding-japanese": "2.4.0",
"iconv-lite": "0.7.3",
"libbase64": "1.3.3",
"libmime": "5.4.8",
"libqp": "2.1.2",
"pino": "10.3.1",
"socks": "2.8.10"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/ip-address": {
"version": "10.7.4",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz",
"integrity": "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==",
"license": "MIT",
"engines": {
"node": ">= 12"
}
},
"node_modules/ipv6-normalize": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/ipv6-normalize/-/ipv6-normalize-1.0.1.tgz",
"integrity": "sha512-Bm6H79i01DjgGTCWjUuCjJ6QDo1HB96PT/xCYuyJUP9WFbVDrLSbG4EZCvOCun2rNswZb0c3e4Jt/ws795esHA==",
"dev": true,
"license": "MIT"
},
"node_modules/is-plain-object": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.1.0.tgz",
"integrity": "sha512-bUi/yjmtKYcRVUtWRGr0UA6xEFh2I6zWUwMrUXB3s7bmYCaZ8a+0ZsTRkrawh/mzlSD1Y0Ph8bp/U+TvBpWDNw==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/launder": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/launder/-/launder-1.7.2.tgz",
"integrity": "sha512-DLg3HPnHUfBi5/MxMLmJD12dmlMpFEC2HgMW6vkZ/9JR0RU00kXoRGvDxAvFmdO0o610OA77i4FgNTLucmhDVg==",
"license": "MIT",
"dependencies": {
"dayjs": "^1.11.23"
}
},
"node_modules/leac": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/leac/-/leac-0.7.0.tgz",
"integrity": "sha512-qMrZeyEekgdRQ9o6a4NAB2EQZrv827GJdn1vnapwSJ90hWRB4TzUSunvacPkxQ2TnNqHNI1/zSt0hlo0crG8Jw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/KillyMXI"
}
},
"node_modules/libbase64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/libbase64/-/libbase64-1.3.3.tgz",
"integrity": "sha512-6n4p3TUeQPimN4ANBTYQ5P4IpFx8p6cdanknnOBfw05XGtaG/k1LAtTSu79w7S07D1esy4qUfM8G4qvQncDWcw==",
"license": "MIT"
},
"node_modules/libmime": {
"version": "5.4.8",
"resolved": "https://registry.npmjs.org/libmime/-/libmime-5.4.8.tgz",
"integrity": "sha512-nsBApAZkontkOI4Kmg/7GyctCRraQ9Yxn7vZnzpHSOfqCmkt5/WTXpu5jk7a14REzW8OghKcbTY4bxx6rR9wSQ==",
"license": "MIT",
"dependencies": {
"encoding-japanese": "2.4.0",
"iconv-lite": "0.7.3",
"libbase64": "1.3.3",
"libqp": "2.1.2"
}
},
"node_modules/libqp": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/libqp/-/libqp-2.1.2.tgz",
"integrity": "sha512-rp+U80tl9Os4K7GnVbPzPRmghPu6eqB8rcF+ontvNAnoga0JhMFG/bkTD/reC8yoznKMgOc5/ttZHJasiWeFPw==",
"license": "MIT"
},
"node_modules/linkify-it": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.2.tgz",
"integrity": "sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/puzrin"
},
{
"type": "github",
"url": "https://github.com/sponsors/markdown-it"
}
],
"license": "MIT",
"dependencies": {
"uc.micro": "^2.0.0"
}
},
"node_modules/mailparser": {
"version": "3.9.39",
"resolved": "https://registry.npmjs.org/mailparser/-/mailparser-3.9.39.tgz",
"integrity": "sha512-tFIEhwsNR4Xs5aq/8oBtd8aQZv42oLoDGWrne6rT/b3e0hN+o/k1KjaedWLh1NydVK35FiDaOTmGg9ZFhIsfYw==",
"license": "MIT",
"dependencies": {
"@zone-eu/mailsplit": "5.4.21",
"encoding-japanese": "2.4.0",
"he": "1.2.0",
"html-to-text": "10.0.1",
"iconv-lite": "0.7.3",
"libmime": "5.4.8",
"linkify-it": "5.0.2",
"nodemailer": "10.1.1",
"punycode.js": "2.3.1",
"tlds": "1.261.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/nanoid": {
"version": "3.3.20",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
"integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/nodemailer": {
"version": "10.1.1",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.1.tgz",
"integrity": "sha512-pbqZRoeYUO+1E8TJ/11WeY4D2EVujj1hsYjz3qff/vUFDtGnmi7p3iqzTFslYOfQ6PnjVcWxx/CIUSHCSrO/QA==",
"license": "MIT-0",
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/on-exit-leak-free": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
"integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/parse-srcset": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/parse-srcset/-/parse-srcset-1.0.2.tgz",
"integrity": "sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==",
"license": "MIT"
},
"node_modules/parseley": {
"version": "0.13.1",
"resolved": "https://registry.npmjs.org/parseley/-/parseley-0.13.1.tgz",
"integrity": "sha512-uNBJZzmb60l6p6VWLTmevizNAGnE0xoSf1n0B4q3ntegDNzcS68NRCcBDZTcyXHxt2XhBChsCuqj4M+nChvE/A==",
"license": "MIT",
"dependencies": {
"leac": "^0.7.0",
"peberminta": "^0.10.0"
},
"funding": {
"url": "https://github.com/sponsors/KillyMXI"
}
},
"node_modules/peberminta": {
"version": "0.10.0",
"resolved": "https://registry.npmjs.org/peberminta/-/peberminta-0.10.0.tgz",
"integrity": "sha512-80B2AsU+I4Qdb0ZAPSfe9UwvGzwkM37IKIFEvdS3D/3Ndgv2bsuJ0bfG1+iEYO+l7Gfd4EUJmuRyq7efLgRMzQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/KillyMXI"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"license": "ISC"
},
"node_modules/pino": {
"version": "10.3.1",
"resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz",
"integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==",
"license": "MIT",
"dependencies": {
"@pinojs/redact": "^0.4.0",
"atomic-sleep": "^1.0.0",
"on-exit-leak-free": "^2.1.0",
"pino-abstract-transport": "^3.0.0",
"pino-std-serializers": "^7.0.0",
"process-warning": "^5.0.0",
"quick-format-unescaped": "^4.0.3",
"real-require": "^0.2.0",
"safe-stable-stringify": "^2.3.1",
"sonic-boom": "^4.0.1",
"thread-stream": "^4.0.0"
},
"bin": {
"pino": "bin.js"
}
},
"node_modules/pino-abstract-transport": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz",
"integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==",
"license": "MIT",
"dependencies": {
"split2": "^4.0.0"
}
},
"node_modules/pino-std-serializers": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz",
"integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==",
"license": "MIT"
},
"node_modules/playwright-core": {
"version": "1.62.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",
"integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/postcss": {
"version": "8.5.30",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz",
"integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.20",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.2"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/process-warning": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz",
"integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"license": "MIT"
},
"node_modules/punycode.js": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz",
"integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/quick-format-unescaped": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
"integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",
"license": "MIT"
},
"node_modules/real-require": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
"integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",
"license": "MIT",
"engines": {
"node": ">= 12.13.0"
}
},
"node_modules/safe-stable-stringify": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
"integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/sanitize-html": {
"version": "2.18.1",
"resolved": "https://registry.npmjs.org/sanitize-html/-/sanitize-html-2.18.1.tgz",
"integrity": "sha512-2X5lC8fYla8YaT8g73Nj+HcLWXan5dLyCWLgVvaOmfw7JI78IRsyNtIDytTHdn7hBQbIkCah7Zbmd5jabzeDig==",
"license": "MIT",
"dependencies": {
"escape-string-regexp": "^4.0.0",
"htmlparser2": "^12.0.0",
"is-plain-object": "^5.1.0",
"launder": "^1.7.2",
"parse-srcset": "^1.0.2",
"postcss": "^8.5.27"
},
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/sanitize-html/node_modules/dom-serializer": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
"integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==",
"license": "MIT",
"dependencies": {
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0",
"entities": "^8.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
}
},
"node_modules/sanitize-html/node_modules/domelementtype": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz",
"integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/sanitize-html/node_modules/domhandler": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz",
"integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==",
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^3.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/sanitize-html/node_modules/domutils": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz",
"integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==",
"license": "BSD-2-Clause",
"dependencies": {
"dom-serializer": "^3.0.0",
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0"
},
"engines": {
"node": ">=20.19.0"
},
"funding": {
"type": "github",
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/sanitize-html/node_modules/entities": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",
"integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/sanitize-html/node_modules/htmlparser2": {
"version": "12.0.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-12.0.0.tgz",
"integrity": "sha512-Tz7u1i95/g2x2jz81+x0FBVhBhY5aRTvD3tXXdFaljuNdzDLJ8UGNRrTcj2cgQvAg3iW/h77Fz15nLW0L0CrZw==",
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "MIT",
"dependencies": {
"domelementtype": "^3.0.0",
"domhandler": "^6.0.0",
"domutils": "^4.0.2",
"entities": "^8.0.0"
},
"engines": {
"node": ">=20.19.0"
}
},
"node_modules/selderee": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/selderee/-/selderee-0.12.0.tgz",
"integrity": "sha512-b1YMh3+DHZp59DLna3qVwQ5iOla/nrI6mLBNW02XxU77M3046Df6VLkoaJyFz20VsGIG5kkp+FK0kg4K4HnUFw==",
"license": "MIT",
"dependencies": {
"parseley": "~0.13.1"
},
"funding": {
"url": "https://github.com/sponsors/KillyMXI"
}
},
"node_modules/smart-buffer": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
"integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
"license": "MIT",
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
}
},
"node_modules/smtp-server": {
"version": "3.19.22",
"resolved": "https://registry.npmjs.org/smtp-server/-/smtp-server-3.19.22.tgz",
"integrity": "sha512-tFAL2UmSPDvxSIpH809XcZ61Pri2uM/8/EmGO4ptf8fAsoOrHbCeyv5jWAVE21zKQk/OEzEQHgJYjfUQF8lFxw==",
"dev": true,
"license": "MIT-0",
"dependencies": {
"ipv6-normalize": "1.0.1",
"nodemailer": "10.1.1",
"punycode.js": "2.3.1"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/socks": {
"version": "2.8.10",
"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz",
"integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==",
"license": "MIT",
"dependencies": {
"ip-address": "^10.1.1",
"smart-buffer": "^4.2.0"
},
"engines": {
"node": ">= 10.0.0",
"npm": ">= 3.0.0"
}
},
"node_modules/sonic-boom": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz",
"integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==",
"license": "MIT",
"dependencies": {
"atomic-sleep": "^1.0.0"
}
},
"node_modules/source-map-js": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"license": "ISC",
"engines": {
"node": ">= 10.x"
}
},
"node_modules/thread-stream": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",
"integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==",
"license": "MIT",
"dependencies": {
"real-require": "^1.0.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/thread-stream/node_modules/real-require": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz",
"integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",
"license": "MIT"
},
"node_modules/tlds": {
"version": "1.261.0",
"resolved": "https://registry.npmjs.org/tlds/-/tlds-1.261.0.tgz",
"integrity": "sha512-QXqwfEl9ddlGBaRFXIvNKK6OhipSiLXuRuLJX5DErz0o0Q0rYxulWLdFryTkV5PkdZct5iMInwYEGe/eR++1AA==",
"license": "MIT",
"bin": {
"tlds": "bin.js"
}
},
"node_modules/uc.micro": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz",
"integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==",
"license": "MIT"
}
}
}
+26
View File
@@ -0,0 +1,26 @@
{
"name": "order-notification-pdf-tool",
"version": "0.1.0",
"private": true,
"description": "Team workspace for BPM connections, business calendars, exceptions and order PDF export",
"scripts": {
"start": "node src/server.cjs",
"test": "node --test --test-concurrency=2 tests/*.test.cjs",
"preview": "node scripts/preview.cjs"
},
"engines": {
"node": ">=22.13"
},
"dependencies": {
"@tabler/core": "1.6.1",
"@whyour/qinglong-cli": "0.1.2",
"imapflow": "2.4.3",
"mailparser": "3.9.39",
"nodemailer": "10.1.1",
"playwright-core": "1.62.1",
"sanitize-html": "2.18.1"
},
"devDependencies": {
"smtp-server": "3.19.22"
}
}
+32
View File
@@ -0,0 +1,32 @@
// Regression/import entry point for offline captures. Never contacts BPM.
const fs = require('node:fs/promises');
const path = require('node:path');
const { renderSnapshot } = require('../src/exporter.cjs');
async function main() {
const args = process.argv.slice(2);
const value = flag => { const index=args.indexOf(flag); return index < 0 ? undefined : args[index+1]; };
const input = value('--snapshot');
if (!input) throw new Error('用法:node scripts/export-snapshot.cjs --snapshot <snapshot.json> [--assets <assets.json>] [--output <directory>]');
const captured = JSON.parse(await fs.readFile(input,'utf8'));
const snapshot = { ...captured, metadata: captured.metadata || { order:captured.order,project:captured.project,model:captured.model,serial:captured.serial }, images:[], warnings:[] };
if (value('--assets')) {
const assets = JSON.parse(await fs.readFile(value('--assets'),'utf8'));
const external = [];
for (const asset of assets.assets || []) {
if (asset.kind === 'stylesheet') external.push(await fs.readFile(asset.path,'utf8'));
if (asset.kind === 'image') {
const bytes = await fs.readFile(asset.path);
const data = `data:${asset.contentType || 'image/gif'};base64,${bytes.toString('base64')}`;
snapshot.images.push({url:asset.url,data});
const url = new URL(asset.url);
snapshot.images.push({url:url.pathname+url.search,data});
}
}
snapshot.styles = [...external,...(snapshot.styles || [])];
}
// Legacy capture used by the original probe already contains visible-value spans.
const result = await renderSnapshot(snapshot,{outputDir:value('--output') && path.resolve(value('--output'))});
console.log(JSON.stringify(result,null,2));
}
main().catch(error=>{console.error(error.message);process.exitCode=1;});
+43
View File
@@ -0,0 +1,43 @@
// Explicit, loopback-only demonstration space. Never opens BPM or sends messages.
const crypto=require('node:crypto');
const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
const {Store}=require('../src/dashboard-store.cjs');
const {WorkspaceStore}=require('../src/workspace-store.cjs');
const {createDashboard}=require('../src/dashboard.cjs');
async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation','preview'),port=18776}={}) {
fs.mkdirSync(stateDir,{recursive:true});
const store=new Store(path.join(stateDir,'accounts'));
if(!store.users().length) {
store.bootstrap('preview',crypto.randomBytes(32).toString('hex'));
store.addUser({username:'colleague',password:crypto.randomBytes(32).toString('hex'),role:'operator'},'演示初始化');
}
const admin=store.users().find(user=>user.role==='admin');
if(!admin)throw Error('演示空间缺少管理员,请检查独立演示数据目录。');
const workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
try {
const snapshot=workspace.snapshot(store.users());
if(!snapshot.exceptions.length) {
for(const item of [
{title:'演示:BPM 连接等待人工登录',component:'bpm',priority:'high',description:'这是虚构的续登待办,用于体验认领、转交和验证。没有检查或使用真实 BPM 登录态。',owner:''},
{title:'演示:归档目录待确认',component:'archive',priority:'normal',description:'这是虚构的接入任务。可转交给演示同事,并查看责任流转记录。',owner:'colleague'},
{title:'演示:PDF 排版等待核验',component:'pdf',priority:'normal',description:'这是虚构的人工核验任务。提交验证后填写核验依据即可体验关闭流程。',owner:admin.username}
])workspace.createException(item,admin,store.users());
}
if(!snapshot.connections.length)workspace.createConnection({name:'演示 BPM 连接',owner:admin.username},admin,store.users());
const server=createDashboard({store,workspace,outputDir:path.join(stateDir,'pdf'),previewUserId:admin.id});
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});
let closed=false;
return {server,store,workspace,async close(){if(closed)return;closed=true;await new Promise(resolve=>server.close(resolve));workspace.close();}};
} catch(error) { workspace.close();throw error; }
}
if(require.main===module)startPreview().then(runtime=>{
console.log(`订单通知中心演示空间:http://127.0.0.1:${runtime.server.address().port}\n页面点击“进入演示空间”,数据与正式空间独立。\n此服务仅监听本机,不访问 BPM,不发送通知。`);
const stop=()=>runtime.close().then(()=>process.exit(0));
process.once('SIGINT',stop);process.once('SIGTERM',stop);
}).catch(error=>{console.error('预览启动失败:'+error.message);process.exitCode=1;});
module.exports={startPreview};
+73
View File
@@ -0,0 +1,73 @@
const fail=(status,message)=>{throw Object.assign(new Error(message),{status});};
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
function secureBpmTransport(request,trustedProxy=false){
if(request.socket.encrypted)return true;
if(!isLoopback(request.socket.remoteAddress))return false;
if(trustedProxy && request.headers['x-forwarded-proto']==='https')return true;
try{const host=new URL('http://'+request.headers.host);return ['localhost','127.0.0.1','[::1]'].includes(host.hostname) && !host.username && !host.password && host.pathname==='/' && !host.search && !host.hash;}catch{return false;}
}
function authorizeConnection(connection,user){
if(user?.role!=='admin' && !(user?.role==='operator' && connection.owner===user.username))fail(403,'仅连接负责人或管理员可以操作此连接。');
}
function emptyBody(body){if(!body || Object.keys(body).length)fail(400,'此操作不接受额外数据。');}
async function managerCall(work){
try{return await work();}catch(error){
if(error?.status===409&&error.code==='BPM_ACCOUNT_DUPLICATE')fail(409,'该 BPM 账号已开启自动续登,请使用已有连接或先解除原账号托管。');
const messages={400:'登录操作数据不正确。',403:'没有操作此登录会话的权限。',404:'登录会话不存在,请重新打开。',409:'登录会话正被使用或不可操作,请刷新后重试。',410:'登录会话已过期,请重新打开。',429:'登录窗口已达到上限,请稍后重试。',503:'BPM 登录服务暂不可用,请稍后重试。'};
const status=messages[error?.status]?error.status:502;fail(status,messages[status] || 'BPM 暂时无法连接,请稍后重试。');
}
}
async function bpmApi({workspace,bpmSessions,user,sessionId,route,method,body,request,response,reply,trustedProxy=false}){
const match=/^\/api\/connections\/([\w-]+)\/(?:login\/(open|frame|input|navigate|save|close|fill-account)|(check|disable|delete)|(account)(\/(?:clear|check))?)$/.exec(route);
if(!match || !workspace)return false;
const [,id,login,other,account,suffix]=match;const action=login || other || (suffix==='/clear'?'clear-account':suffix==='/check'?'check-account':account);
if(action==='account'?!['GET','POST'].includes(method):method!==(action==='frame'?'GET':'POST'))fail(405,'此操作不支持当前请求方式。');
const connection=workspace.getConnection(id);authorizeConnection(connection,user);
if(action==='delete'){
if(user.role!=='admin')fail(403,'仅管理员可以删除连接。');emptyBody(body);
if(connection.status!=='disabled')fail(409,'请先停用连接再删除。');
if(!bpmSessions)fail(503,'BPM 登录服务暂不可用,请稍后重试。');
await managerCall(()=>bpmSessions.disable(id));reply(200,workspace.deleteConnection(id,user));return true;
}
if(action==='disable'){
if(user.role!=='admin')fail(403,'仅管理员可以停用连接。');emptyBody(body);
if(bpmSessions)await managerCall(()=>bpmSessions.disable(id));reply(200,workspace.disableConnection(id,user));return true;
}
if(connection.status==='disabled')fail(409,'此连接已停用。');
if(!secureBpmTransport(request,trustedProxy))fail(403,'请在部署机本地或 HTTPS 页面中登录 BPM。');
if(!bpmSessions)fail(503,'BPM 登录服务暂不可用。');
const principal={user,sessionId};
if(action==='check-account'){
const value=await managerCall(()=>bpmSessions.checkAccount(connection,principal,body));reply(200,{available:value.available===true});return true;
}
if(!['frame','input','navigate','account'].includes(action))emptyBody(body);
if(action==='account' || action==='clear-account'){
const saving=action==='account' && method==='POST';
const previous=saving?await managerCall(()=>bpmSessions.account(connection,principal)):null;
const value=await managerCall(()=>bpmSessions[action==='clear-account'?'clearAccount':saving?'saveAccount':'account'](connection,principal,body));
let checked;
if(saving && previous.configured && previous.username!==value.username)workspace.resetConnectionSession(id,user);
if(saving || action==='clear-account')workspace.record(user,saving?'bpm.account.save':'bpm.account.clear',connection.name);
if(saving){
try{const result=await managerCall(()=>bpmSessions.ensure(workspace.getConnection(id),principal));checked=workspace.updateConnectionSession(id,result,user);}
catch(error){if(error.status!==409)throw error;checked=workspace.getConnection(id);}
}
reply(200,{configured:value.configured===true,username:typeof value.username==='string'?value.username:'',updatedAt:typeof value.updatedAt==='string'?value.updatedAt:null,...(saving?{connection:checked}:{})});return true;
}
if(action==='fill-account'){
const value=await managerCall(()=>bpmSessions.fillAccount(connection,principal));reply(200,{filled:value.filled===true,message:typeof value.message==='string'?value.message:''});return true;
}
if(action==='frame'){
const bytes=await managerCall(()=>bpmSessions.frame(id,principal));
if(!Buffer.isBuffer(bytes))fail(502,'登录画面暂不可用。');
response.writeHead(200,{'Content-Type':'image/jpeg'});response.end(bytes);return true;
}
if(action==='save' || action==='check'){
const result=await managerCall(()=>bpmSessions[action](connection,principal));reply(200,workspace.updateConnectionSession(id,result,user));return true;
}
const value=await managerCall(()=>bpmSessions[action](action==='open'?connection:id,principal,body));
if(action==='open')reply(200,{active:value.active===true,viewport:{width:value.viewport?.width,height:value.viewport?.height},expiresAt:value.expiresAt,host:value.host});
else reply(200,{ok:true});
return true;
}
module.exports={bpmApi,secureBpmTransport};
+34
View File
@@ -0,0 +1,34 @@
const crypto=require('node:crypto');
class BpmCustodian {
constructor({workspace,manager,intervalMs=5*60*1000}){
this.workspace=workspace;this.manager=manager;this.intervalMs=intervalMs;this.stopped=false;this.running=null;
this.principal={user:{id:'bpm-custodian',username:'系统托管',role:'admin'},sessionId:'custodian:'+crypto.randomBytes(24).toString('hex')};
}
start(){if(this.timer || this.stopped)return;this.timer=setInterval(()=>{this.tick().catch(()=>{});},this.intervalMs);this.timer.unref?.();this.tick().catch(()=>{});}
tick(){
if(this.stopped || this.running)return Promise.resolve();
this.running=this.checkAll().finally(()=>{this.running=null;});return this.running;
}
async checkAll(){
const connections=this.workspace.snapshot().connections;
for(const candidate of connections){
if(this.stopped)break;
if(candidate.status==='disabled')continue;
try{
const connection=this.workspace.getConnection(candidate.id);
if(connection.status==='disabled')continue;
const account=await this.manager.account(connection,this.principal);
if(!account.configured && !connection.lastConnectedAt && !['connected','unchecked','login_required'].includes(connection.status))continue;
const result=await this.manager.ensure(connection,this.principal);
// The connection can be disabled while its remote check is in flight.
if(this.workspace.getConnection(connection.id).status!=='disabled')this.workspace.updateConnectionSession(connection.id,result,this.principal.user);
}catch(cause){
// Interactive leases and transient browser failures are retried on the next cycle.
// The manager returns checked upstream failures as structured results.
if(![403,404,409,429].includes(cause.status))this.lastErrorAt=new Date().toISOString();
}
}
}
async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await this.running;}
}
module.exports={BpmCustodian};
+57
View File
@@ -0,0 +1,57 @@
'use strict';
const sanitize=require('sanitize-html');
const {loadPlaywright}=require('./runtime.cjs');
const fail=(message,status=502)=>Object.assign(new Error(message),{status});
const SOURCES=[['portal-v8','bpm/worklist/informlist'],['portal-v4','skyworth/todo/v2/workflow/get_process_of_inform_v4']];
function plain(value,max=8000){
const text=sanitize(String(value??''),{allowedTags:[],allowedAttributes:{}}).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(m,key)=>{
if(key[0]==='#'){const n=key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):+key.slice(1);return n>0&&n<=0x10ffff?String.fromCodePoint(n):'';}
return {amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:' '}[key.toLowerCase()];
});return text.replace(/\s+/g,' ').trim().slice(0,max);
}
function normalizeArrival(row,source){
if(!row||typeof row!=='object'||!['string','number'].includes(typeof row.taskId)||!String(row.taskId)||String(row.taskId).length>200)throw fail('BPM 列表缺少有效的任务标识。');
const raw=row.startTime;
if(typeof raw!=='string'||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?$/.test(raw))throw fail('BPM 列表缺少有效的流程到达时间。');
const day=raw.slice(0,10),valid=new Date(day+'T00:00:00Z');
if(Number.isNaN(+valid)||valid.toISOString().slice(0,10)!==day)throw fail('BPM 流程到达日期无效。');
const date=new Date(/(?:Z|[+-]\d{2}:\d{2})$/.test(raw)?raw:raw+'+08:00');
if(Number.isNaN(+date))throw fail('BPM 流程到达时间无效。');
const arrivedAt=date.toISOString(),arrivalDay=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date);
return {source,taskId:String(row.taskId),serialNum:plain(row.serialNum,250),processName:plain(row.processName,250),activityName:plain(row.activityName,250),subject:plain(row.processInstanceSubject),initiator:plain(row.processInstanceInitiatorShortName||row.processInstanceInitiator,250),arrivedAt,arrivalDay};
}
class BpmListClient{
constructor({baseURL='https://bpmn.skyworthdigital.com/',pageSize=100,allowLocal=false}={}){
const u=new URL(baseURL);if(u.href!=='https://bpmn.skyworthdigital.com/'&&!(allowLocal&&['127.0.0.1','localhost','[::1]'].includes(u.hostname)&&['http:','https:'].includes(u.protocol)&&u.pathname==='/'&&!u.username&&!u.password&&!u.search&&!u.hash))throw fail('BPM 地址不受支持。',400);
this.baseURL=u.href;this.pageSize=pageSize;
}
async scan(storageState){
if(!storageState)throw fail('BPM 会话需要续登。',401);
const request=await loadPlaywright().request.newContext({baseURL:this.baseURL,storageState,timeout:20000});
const get=async(route,options={})=>{
let response;try{response=await request.get(route,{...options,maxRedirects:0});}catch{throw fail('BPM 查询连接失败,请稍后重试。');}
const status=response.status();if(status>=300&&status<400)throw fail('BPM 查询发生登录跳转,需要续登。',401);
if([401,403].includes(status))throw fail('BPM 会话需要续登。',401);
if(status!==200)throw fail('BPM 查询失败,请稍后重试。');
const body=await response.body();if(body.length>10*1024*1024)throw fail('BPM 查询响应过大。');return body.toString('utf8');
};
try{
const html=await get('/'),token=/Yiez\.clientId\s*=\s*['"]([^'"\s<>]{1,16000})['"]/.exec(html)?.[1];
if(!token)throw fail('BPM 会话需要续登。',401);
const rows=[];
for(const [source,route]of SOURCES){
let total=null;const seen=new Set();
for(let page=1;page<=100;page++){
let data;try{data=JSON.parse(await get(route,{params:{page,start:(page-1)*this.pageSize,limit:this.pageSize},headers:{Authorization:'Bearer '+token}}));}catch(cause){if(cause.status)throw cause;throw fail('BPM 列表数据格式不正确。');}
if(!Array.isArray(data.children)||!Number.isSafeInteger(data.total)||data.total<0||data.total>10000||data.success===false)throw fail('BPM 列表分页数据不完整。');
if(total!==null&&total!==data.total)throw fail('BPM 列表正在变化,请重新扫描。');total=data.total;
for(const raw of data.children){const row=normalizeArrival(raw,source);if(seen.has(row.taskId))throw fail('BPM 列表分页重复,请重新扫描。');seen.add(row.taskId);rows.push(row);}
if(seen.size===total)break;
if(!data.children.length||data.children.length>this.pageSize||seen.size>total||page===100)throw fail('BPM 列表分页不完整,请重新扫描。');
}
}
return rows;
}finally{await request.dispose();}
}
}
module.exports={BpmListClient,normalizeArrival};
+23
View File
@@ -0,0 +1,23 @@
'use strict';
async function bpmScanApi({scanner,workspace,user,sessionId,url,route,method,body,reply}){
if(!route.startsWith('/api/bpm-scan')&&route!=='/api/arrivals')return false;
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
if(!scanner)fail('BPM 扫描暂不可用。',503);
if(route==='/api/arrivals'&&method==='GET'){
const filters={connectionId:url.searchParams.get('connectionId')||'',q:url.searchParams.get('q')||'',before:url.searchParams.get('before')||'',days:Number(url.searchParams.get('days')||7)};
reply(200,scanner.store.list(filters));return true;
}
if(route==='/api/bpm-scan'&&method==='GET'){reply(200,{...scanner.store.status(),connections:workspace.snapshot().connections.map(({id,name,status,owner})=>({id,name,status,owner}))});return true;}
if(route==='/api/bpm-scan/config'&&method==='POST'){
if(user.role!=='admin')fail('仅管理员可以配置自动扫描。',403);
const config=scanner.store.saveConfig(body);workspace.record(user,'保存自动扫描',`${config.enabled?'开启':'暂停'},间隔 ${config.intervalMinutes} 分钟`);reply(200,config);return true;
}
if(route==='/api/bpm-scan/run'&&method==='POST'){
if(!body||Object.keys(body).some(k=>k!=='connectionId')||typeof body.connectionId!=='string')fail('请选择 BPM 连接。');
// A scan may span many pages. The UI polls the durable run instead of holding a request open.
const {promise,runId}=scanner.startScan(body.connectionId,{user,sessionId});
promise.catch(()=>{});reply(202,{runId});return true;
}
return false;
}
module.exports={bpmScanApi};
+36
View File
@@ -0,0 +1,36 @@
'use strict';
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');
const invalid=message=>Object.assign(new Error(message),{status:400});
class BpmScanStore{
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'scan.sqlite'));this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO config VALUES(1,'{"enabled":true,"intervalMinutes":5}');
CREATE TABLE IF NOT EXISTS arrivals(connection_id TEXT NOT NULL,source TEXT NOT NULL,task_id TEXT NOT NULL,day TEXT NOT NULL,value TEXT NOT NULL,first_seen TEXT NOT NULL,last_seen TEXT NOT NULL,PRIMARY KEY(connection_id,source,task_id));
CREATE INDEX IF NOT EXISTS arrivals_day ON arrivals(day DESC);
CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,actor TEXT NOT NULL,started_at TEXT NOT NULL,finished_at TEXT,status TEXT NOT NULL,seen INTEGER,added INTEGER,message TEXT);
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);}
transaction(fn){this.db.exec('BEGIN IMMEDIATE');try{const r=fn();this.db.exec('COMMIT');return r;}catch(e){this.db.exec('ROLLBACK');throw e;}}
config(){return JSON.parse(this.db.prepare('SELECT value FROM config WHERE id=1').get().value);}
saveConfig(input){if(!input||Object.keys(input).some(k=>!['enabled','intervalMinutes'].includes(k))||typeof input.enabled!=='boolean'||!Number.isInteger(input.intervalMinutes)||input.intervalMinutes<1||input.intervalMinutes>1440)throw invalid('扫描间隔需为 1–1440 分钟。');this.db.prepare('UPDATE config SET value=? WHERE id=1').run(JSON.stringify(input));return this.config();}
begin(connectionId,actor){const id=crypto.randomUUID();this.db.prepare('INSERT INTO runs(id,connection_id,actor,started_at,status) VALUES(?,?,?,?,?)').run(id,connectionId,actor,new Date().toISOString(),'running');return id;}
complete(id,connectionId,rows){return this.transaction(()=>{
let added=0;const now=new Date().toISOString();
const insert=this.db.prepare('INSERT OR IGNORE INTO arrivals VALUES(?,?,?,?,?,?,?)');const update=this.db.prepare('UPDATE arrivals SET day=?,value=?,last_seen=? WHERE connection_id=? AND source=? AND task_id=?');
for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const value=JSON.stringify(row);added+=Number(insert.run(connectionId,row.source,row.taskId,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,row.taskId);}
this.db.prepare('UPDATE runs SET status=?,finished_at=?,seen=?,added=?,message=? WHERE id=? AND status=?').run('success',now,rows.length,added,'',id,'running');this.prune();return {seen:rows.length,added};
});}
fail(id,message){this.db.prepare('UPDATE runs SET status=?,finished_at=?,message=? WHERE id=?').run('error',new Date().toISOString(),message,id);this.prune();}
prune(){this.db.exec("DELETE FROM runs WHERE status!='running' AND id NOT IN(SELECT id FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 200)");}
status(){return {config:this.config(),total:this.db.prepare('SELECT COUNT(*) n FROM arrivals').get().n,runs:this.db.prepare('SELECT id,connection_id AS connectionId,actor,started_at AS startedAt,finished_at AS finishedAt,status,seen,added,message FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 30').all()};}
list({connectionId='',q='',before='',days=7}={}){
if(typeof q!=='string'||q.length>200||typeof connectionId!=='string'||connectionId.length>200||typeof before!=='string'||(before&&!/^\d{4}-\d{2}-\d{2}$/.test(before))||!Number.isInteger(days)||days<1||days>31)throw invalid('查询条件无效。');
const conditions=[],args=[];if(connectionId){conditions.push('connection_id=?');args.push(connectionId);}if(q){conditions.push("value LIKE ? ESCAPE '\\'");args.push('%'+q.replace(/[\\%_]/g,'\\$&')+'%');}
const where=conditions.length?' WHERE '+conditions.join(' AND '):'';const total=this.db.prepare('SELECT COUNT(*) n FROM arrivals'+where).get(...args).n;
if(before){conditions.push('day<?');args.push(before);}const filtered=conditions.length?' WHERE '+conditions.join(' AND '):'';
const dates=this.db.prepare('SELECT DISTINCT day FROM arrivals'+filtered+' ORDER BY day DESC LIMIT ?').all(...args,days+1).map(r=>r.day);const shown=dates.slice(0,days);
const groups=shown.map(day=>({day,items:this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt,last_seen AS lastSeenAt FROM arrivals'+(filtered?filtered+' AND ':' WHERE ')+'day=? ORDER BY json_extract(value,\'$.arrivedAt\') DESC,task_id').all(...args,day).map(({value,...rest})=>({...JSON.parse(value),...rest}))}));
return {total,groups,nextBefore:dates.length>days?shown.at(-1):null};
}
close(){this.db.close();}
}
module.exports={BpmScanStore};
+28
View File
@@ -0,0 +1,28 @@
'use strict';
const crypto=require('node:crypto');const {dayPolicy}=require('./schedule.cjs');
const fail=(message,status)=>Object.assign(new Error(message),{status});
class BpmScanner{
constructor({store,workspace,manager,settings,clock=()=>new Date()}){Object.assign(this,{store,workspace,manager,settings,clock});this.pending=new Map();this.stopped=false;this.lastTick=0;this.principal={user:{username:'系统扫描',role:'admin'},sessionId:'scan:'+crypto.randomUUID()};}
start(){if(this.timer||this.stopped)return;this.timer=setInterval(()=>this.tick().catch(()=>{}),15000);this.timer.unref?.();this.tick().catch(()=>{});}
async scan(id,principal){return this.startScan(id,principal).promise;}
startScan(id,principal){
if(this.stopped)throw fail('扫描服务正在关闭。',503);const connection=this.workspace.getConnection(id);
if(!principal?.sessionId||!['admin','operator'].includes(principal.user?.role)||(principal.user.role!=='admin'&&connection.owner!==principal.user.username))throw fail('只有连接负责人或管理员可以扫描。',403);
if(connection.status==='disabled')throw fail('此 BPM 连接已停用。',409);
if(this.pending.has(id))throw fail('此连接正在扫描,请稍后查看结果。',409);
const runId=this.store.begin(id,principal.user.username);
const operation=Promise.resolve().then(async()=>{
try{const rows=await this.manager.scanArrivals(connection,principal);if(this.workspace.getConnection(id).status==='disabled')throw fail('此 BPM 连接已停用。',409);return {...this.store.complete(runId,id,rows),runId};}
catch(cause){this.store.fail(runId,cause.status?cause.message:'BPM 扫描失败,请稍后重试。');throw cause;}
}).finally(()=>this.pending.delete(id));this.pending.set(id,operation);return {promise:operation,runId};
}
tick(){if(this.stopped||this.ticking)return Promise.resolve();this.ticking=this.checkAll().finally(()=>{this.ticking=null;});return this.ticking;}
async checkAll(){
const config=this.store.config(),now=this.clock();if(!config.enabled||+now-this.lastTick<config.intervalMinutes*60000)return;
const snapshot=this.workspace.snapshot();if(!dayPolicy(now,this.settings().schedule,snapshot.calendar.overrides).scan)return;
this.lastTick=+now;
for(const connection of snapshot.connections){if(this.stopped)break;if(connection.status==='disabled'||(!connection.lastConnectedAt&&connection.status!=='connected')||this.pending.has(connection.id))continue;try{await this.scan(connection.id,this.principal);}catch{}}
}
async stop(){this.stopped=true;clearInterval(this.timer);await this.ticking;await Promise.allSettled([...this.pending.values()]);}
}
module.exports={BpmScanner};
+417
View File
@@ -0,0 +1,417 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const { BpmVault } = require('./bpm-vault.cjs');
const { loadPlaywright, browserOptions } = require('./runtime.cjs');
const { BpmListClient } = require('./bpm-list-client.cjs');
const DEFAULT_URLS = { main: 'https://bpmn.skyworthdigital.com/' };
const LOGIN_FORMS = {
'https://sso.skyworthdigital.com': { username:'#username', password:'#password', submit:'#kc-form-login button[type="submit"]', form:'#kc-form-login', actionPath:'/realms/skyworthdigital/login-actions/authenticate' }
};
const TTL = 10 * 60 * 1000;
const KEYS = new Set(['Tab','Enter','Backspace','Delete','ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Home','End','Escape','Control+A']);
const error = (message, status = 400) => Object.assign(new Error(message), { status });
const safe = cause => cause?.status ? cause : error('BPM 浏览器暂不可用,请重试。', 503);
const object = (value, fields) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every(key => fields.includes(key));
class BpmSessionManager {
constructor({ stateDir, browserFactory, urls, allowedOrigins, probe, loginForms } = {}) {
this.stateDir = path.resolve(stateDir); fs.mkdirSync(this.stateDir, { recursive: true });
if (urls!==undefined && !object(urls,['main'])) throw error('BPM 地址配置无效。');
this.urls = { ...DEFAULT_URLS, ...urls };
this.allowedOrigins = new Set(Object.values(DEFAULT_URLS).map(url => new URL(url).origin));
this.allowedOrigins.add('https://sso.skyworthdigital.com');
if (allowedOrigins) {
// Injection exists only for local integration fixtures; it cannot widen production's external allowlist.
for (const origin of allowedOrigins) {
const parsed = new URL(origin);
if (!['localhost','127.0.0.1','[::1]'].includes(parsed.hostname) || !['http:','https:'].includes(parsed.protocol) || parsed.origin !== origin) throw error('测试域名必须为本机地址。');
this.allowedOrigins.add(origin);
}
}
for (const target of Object.values(this.urls)) if (!this.allowed(target)) throw error('BPM 地址不在允许范围内。',403);
this.loginForms = { ...LOGIN_FORMS };
// Only local fixtures may register additional forms; callers cannot replace company forms.
for (const [origin,form] of Object.entries(loginForms || {})) {
const parsed = new URL(origin);
if (!['localhost','127.0.0.1','[::1]'].includes(parsed.hostname) || !this.allowedOrigins.has(origin) || parsed.origin!==origin || !object(form,['username','password','submit']) || !['username','password'].every(key=>typeof form[key]==='string' && /^#[a-zA-Z_][\w-]*$/.test(form[key])) || (form.submit!==undefined && !/^#[a-zA-Z_][\w-]*$/.test(form.submit))) throw error('测试登录表单无效。');
this.loginForms[origin] = { ...form };
}
this.browserFactory = browserFactory || (() => loadPlaywright().chromium.launch(browserOptions()));
this.probe = probe || this.defaultProbe.bind(this);
this.sessions = new Map(); this.operations = new Map(); this.disabled = new Set(); this.stopped = false;
}
allowed(url) { try { const parsed = new URL(url); return !parsed.username && !parsed.password && this.allowedOrigins.has(parsed.origin); } catch { return false; } }
vault() { return this._vault ||= new BpmVault({ stateDir: this.stateDir }); }
accountMetadata(stored) { return stored ? {configured:true,username:stored.username,updatedAt:stored.updatedAt} : {configured:false,username:'',updatedAt:null}; }
async migrateAccounts(connections) { await this.vault().migrateAccounts(connections.map(connection=>connection.id)); }
async checkAccount(connection,principal,input) {
return this.run(connection?.id,async()=>{this.authorize(connection,principal);if(!object(input,['username'])||typeof input.username!=='string'||!input.username.trim()||input.username.length>150)throw error('请输入有效的 BPM 账号。');return this.vault().accountAvailability(connection.id,input.username);});
}
async account(connection,principal) {
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); return this.accountMetadata(await this.vault().read('account:'+connection.id)); });
}
async saveAccount(connection,principal,credentials) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
if (!object(credentials,['username','password']) || typeof credentials.username!=='string' || !credentials.username.trim() || credentials.username.length>150 || typeof credentials.password!=='string' || !credentials.password || credentials.password.length>256) throw error('请输入有效的 BPM 账号和密码。');
const lease=this.sessions.get(connection.id);
if (lease && lease.sessionId!==principal.sessionId) throw error('此连接正在另一登录窗口中使用。',409);
const stored={username:credentials.username.trim(),password:credentials.password,updatedAt:new Date().toISOString()};
const previous=await this.vault().read('account:'+connection.id);
// A password rotation retains valid cookies. Only an actual account change revokes
// authentication; first custody can reuse a user's already saved manual login.
await this.vault().write('account:'+connection.id,stored);
if (previous && previous.username.trim().toLowerCase()!==stored.username.toLowerCase()) {
try{await this.vault().remove(connection.id);await this.closeLease(connection.id);}
catch(cause){await this.vault().write('account:'+connection.id,previous);throw cause;}
}
return this.accountMetadata(stored);
});
}
async clearAccount(connection,principal) {
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); await this.vault().remove('account:'+connection.id); return this.accountMetadata(null); });
}
async fillSavedAccount(lease) {
const stored=await this.vault().read('account:'+lease.id);
if (!stored) return {filled:false,message:'请先保存托管账号。'};
const origin=new URL(lease.page.url()).origin, form=this.loginForms[origin];
if (!form || lease.blocked) return {filled:false,message:'请打开支持的 BPM 登录页面。'};
try {
await Promise.all([lease.page.locator(form.username).waitFor({state:'visible',timeout:1500}),lease.page.locator(form.password).waitFor({state:'visible',timeout:1500})]);
// Validate and set both values in one browser task: a navigation or DOM replacement
// between separate locator.fill calls must never redirect a secret to another field.
const filled=await lease.page.evaluate(({origin,form,username,password})=>{
if (location.origin!==origin || window!==window.top) return false;
const user=document.querySelector(form.username), secret=document.querySelector(form.password);
const usable=(node,type)=>node instanceof HTMLInputElement && node.type===type && !node.disabled && !node.readOnly && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none';
if (!usable(user,'text') || !usable(secret,'password') || user===secret) return false;
const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;
set.call(user,username);set.call(secret,password);
for (const node of [user,secret]) { node.dispatchEvent(new Event('input',{bubbles:true})); node.dispatchEvent(new Event('change',{bubbles:true})); }
return true;
},{origin,form,username:stored.username,password:stored.password});
return {filled,message:filled?'已填入托管账号,请完成登录。':'请打开支持的 BPM 登录表单。'};
} catch { return {filled:false,message:'请等待登录表单显示后重试。'}; }
}
async fillAccount(connection,principal) {
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true); await this.settleNavigation(lease); return this.fillSavedAccount(lease); });
}
async automaticSubmit(lease,stored,submit=false) {
const origin=new URL(lease.page.url()).origin, form=this.loginForms[origin];
if (!form?.submit || lease.blocked) return false;
return lease.page.evaluate(({origin,form,stored,submit})=>{
if (location.origin!==origin || window!==window.top) return false;
const visible=node=>!!node && node.getClientRects().length>0 && getComputedStyle(node).visibility==='visible' && getComputedStyle(node).display!=='none';
const user=document.querySelector(form.username),secret=document.querySelector(form.password),button=document.querySelector(form.submit);
if (!(user instanceof HTMLInputElement) || user.type!=='text' || !visible(user) || user.disabled || user.readOnly || !(secret instanceof HTMLInputElement) || secret.type!=='password' || !visible(secret) || secret.disabled || secret.readOnly || !visible(button) || button.disabled || button.type!=='submit') return false;
const login=user.form;
if (!login || secret.form!==login || button.form!==login || login.method.toLowerCase()!=='post' || (form.form && !login.matches(form.form))) return false;
if ((button.getAttribute('formmethod') || login.method).toLowerCase()!=='post' || !['','_self'].includes(button.getAttribute('formtarget') || login.target)) return false;
const action=new URL(button.getAttribute('formaction') || login.action,location.href);
if (action.origin!==origin || (form.actionPath && action.pathname!==form.actionPath)) return false;
// Any additional visible field or challenge requires the user's intervention.
const challenge=/captcha|recaptcha|hcaptcha|turnstile|otp|one.?time|totp|verification|verify.?code/i;
if (Array.from(document.querySelectorAll('input,iframe,img,[id],[class]')).some(node=>visible(node) && challenge.test([node.id,node.className,node.getAttribute('name'),node.getAttribute('autocomplete'),node.getAttribute('src'),node.getAttribute('title')].join(' ')))) return false;
if (Array.from(login.elements).some(node=>visible(node) && node!==user && node!==secret && !['submit','button','hidden','reset'].includes(node.type))) return false;
if (submit) {
const set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;
set.call(user,stored.username);set.call(secret,stored.password);
button.click();
}
return true;
},{origin,form,stored:{username:stored.username,password:stored.password},submit}).catch(()=>false);
}
async persistLease(lease) {
await this.captureSessions(lease);
const storageState=await lease.context.storageState({indexedDB:true});
await this.vault().write(lease.id,{storageState,sessionStorage:lease.sessionStorage});
}
canPersistVerified(result) {
return result.status==='connected' && result.checks.portal.ok;
}
async ensure(connection,principal) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
if (this.sessions.has(connection.id)) throw error('此连接正在登录窗口中使用。',409);
const lease=await this.create(connection,principal);
try {
let result=await this.verify(lease);
this.authorize(connection,principal);
if (this.canPersistVerified(result)) await this.persistLease(lease);
if (result.status==='connected') return result;
// Network failures and a healthy portal never justify submitting credentials again.
if (result.status!=='login_required' || result.checks.portal.message!=='请在此入口完成登录。' || lease.blocked) return result;
const stored=await this.vault().read('account:'+connection.id);
if (!stored) return result;
const manual=message=>{ if (!result.checks.portal.ok) result.checks.portal.message=message; return result; };
if (Date.parse(stored.nextAttemptAt)>Date.now()) return manual('自动登录暂缓,请稍后重试或更新托管账号。');
await this.readOnlyGoto(lease,this.urls.main);
if (lease.blocked || !this.allowed(lease.page.url())) return manual('请人工检查 BPM 登录页面。');
if (!await this.automaticSubmit(lease,stored)) return manual('需要人工完成验证码或登录验证。');
// Persist before a request to avoid repeated retries after a crash or failed password.
await this.vault().write('account:'+connection.id,{...stored,nextAttemptAt:new Date(Date.now()+15*60*1000).toISOString()});
if (!await this.automaticSubmit(lease,stored,true)) return manual('需要人工完成登录验证。');
await this.settleNavigation(lease);
result=await this.verify(lease);this.authorize(connection,principal);
if (this.canPersistVerified(result)) {
await this.persistLease(lease);delete stored.nextAttemptAt;await this.vault().write('account:'+connection.id,stored);
} else if (!result.checks.portal.ok) result.checks.portal.message='自动登录未完成,请检查托管账号或人工完成验证;稍后重试。';
return result;
} finally { await this.closeLease(connection.id); }
});
}
async scanArrivals(connection,principal) {
const query=()=>this.run(connection?.id,async()=>{
this.authorize(connection,principal);
if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用,请关闭后扫描。',409);
const saved=await this.vault().read(connection.id);
const rows=await (this.listClient ||= new BpmListClient()).scan(saved?.storageState);
this.authorize(connection,principal);return rows;
});
try{return await query();}catch(cause){if(cause.status!==401)throw cause;}
// Renewal takes the same per-connection lock, so it must run after query releases it.
const renewed=await this.ensure(connection,principal);
if(renewed.status!=='connected')throw error(renewed.checks?.portal?.message||'请在 BPM 连接中完成登录。',401);
return query();
}
authorize(connection, principal) {
if (!connection || typeof connection.id !== 'string' || !connection.id || connection.id.length > 200) throw error('连接标识无效。');
if (!principal?.sessionId || !principal.user || !['admin','operator'].includes(principal.user.role) || (principal.user.role !== 'admin' && connection.owner !== principal.user.username)) throw error('只有连接负责人或管理员可以操作。',403);
if (this.stopped) throw error('BPM 服务正在关闭。',503);
if (connection.status === 'disabled' || this.disabled.has(connection.id)) throw error('此 BPM 连接已停用。',409);
}
run(id, work) {
const before = this.operations.get(id) || Promise.resolve();
const operation = before.catch(()=>{}).then(work).catch(cause=>{ throw safe(cause); });
this.operations.set(id, operation);
operation.finally(()=>{ if (this.operations.get(id) === operation) this.operations.delete(id); }).catch(()=>{});
return operation;
}
touch(lease) {
lease.expiresAt = Date.now() + TTL; clearTimeout(lease.timer);
lease.timer = setTimeout(()=>this.run(lease.id, async()=>{ if (lease.expiresAt <= Date.now()) await this.closeLease(lease.id); }).catch(()=>{}), TTL + 10);
lease.timer.unref?.();
}
async getLease(id, principal, touch = false, closing = false) {
const lease = this.sessions.get(id);
if (!lease) throw error('登录窗口已关闭,请重新打开。',410);
this.authorize(lease.connection,principal);
if (lease.sessionId !== principal.sessionId) throw error('此连接正在另一登录窗口中使用。',409);
if (lease.expiresAt <= Date.now()) { await this.closeLease(id); throw error('登录窗口已过期,请重新打开。',410); }
if (!closing && (lease.blocked || !this.allowed(lease.page.url()))) throw error('已阻止离开允许的 BPM 域名,请重新打开登录窗口。',403);
if (touch) this.touch(lease);
return lease;
}
async browser() {
if (this.stopped) throw error('BPM 服务正在关闭。',503);
if (!this.browserPromise) this.browserPromise = Promise.resolve().then(()=>this.browserFactory()).catch(cause=>{ this.browserPromise=null; throw cause; });
return this.browserPromise;
}
async create(connection, principal) {
this.authorize(connection,principal);
if (this.sessions.size >= 3) throw error('同时登录窗口已达上限,请先关闭其他窗口。',429);
const lease = { id:connection.id, connection:{...connection}, sessionId:principal.sessionId, context:null, page:null, blocked:false, sessionStorage:{} };
this.sessions.set(connection.id,lease); this.touch(lease);
try {
const stored = await this.vault().read(connection.id);
lease.sessionStorage = stored?.sessionStorage || {};
const browser = await this.browser();
this.authorize(connection,principal);
lease.context = await browser.newContext({ viewport:{width:1280,height:800}, acceptDownloads:false, serviceWorkers:'block', permissions:[], storageState:stored?.storageState });
await lease.context.route('**/*', async route => {
try {
// A popup is never a remote-control surface. Block its first navigation,
// before even an allowed host can redirect it elsewhere.
if (route.request().isNavigationRequest() && route.request().frame().page()!==lease.page) return route.abort('blockedbyclient');
if (this.allowed(route.request().url())) {
// route.continue follows redirects without re-entering the route handler.
// Inspect each redirect before Chromium receives it, including resource redirects.
const response=await route.fetch({maxRedirects:0,timeout:25000});
const location=response.headers().location;
if (location && response.status()>=300 && response.status()<400 && !this.allowed(new URL(location,route.request().url()).href)) {
if (route.request().isNavigationRequest() && !route.request().frame().parentFrame()) lease.blocked=true;
return route.abort('blockedbyclient');
}
if (/attachment/i.test(response.headers()['content-disposition']||'')) return route.abort('blockedbyclient');
return route.fulfill({response});
}
if (route.request().isNavigationRequest() && !route.request().frame().parentFrame()) lease.blocked = true;
await route.abort('blockedbyclient');
} catch { await route.abort('failed').catch(()=>{}); }
});
if (lease.context.routeWebSocket) await lease.context.routeWebSocket(/.*/, socket => {
const url=socket.url().replace(/^ws:/,'http:').replace(/^wss:/,'https:');
if (this.allowed(url)) socket.connectToServer(); else socket.close();
});
await lease.context.addInitScript(({ sessions }) => {
try { if (sessionStorage.length===0) for (const [key,value] of Object.entries(sessions[location.origin] || {})) sessionStorage.setItem(key,value); } catch {}
// Native file pickers are not part of remote login and must never reach the service desktop.
const disable = () => document.querySelectorAll('input[type=file]').forEach(input=>{ input.disabled=true; });
new MutationObserver(disable).observe(document,{childList:true,subtree:true});
document.addEventListener('click', event => { if (event.target.closest?.('input[type=file],a[download]')) { event.preventDefault(); event.stopImmediatePropagation(); } },true);
}, { sessions:lease.sessionStorage });
lease.page = await lease.context.newPage();
// Playwright routes omit redirected requests. A private Chromium request-stage
// guard sees every hop before any network access, including redirect chains.
lease.network = await lease.context.newCDPSession(lease.page);
lease.mainFrameId=(await lease.network.send('Page.getFrameTree')).frameTree.frame.id;
// Raw mouse/keyboard input returns before a form-triggered navigation commits.
// Track main-frame navigation independently so verification never races it.
const started=event=>{
if (event.frameId!==lease.mainFrameId || lease.pendingNavigation) return;
lease.pendingNavigation=new Promise(resolve=>{lease.finishNavigation=resolve;});
};
lease.network.on('Page.frameRequestedNavigation',started);
lease.network.on('Page.frameStartedLoading',started);
lease.network.on('Page.frameStoppedLoading',event=>{
if (event.frameId!==lease.mainFrameId) return;
lease.finishNavigation?.(); lease.pendingNavigation=null; lease.finishNavigation=null;
});
await lease.network.send('Page.enable');
lease.network.on('Fetch.requestPaused', async event => {
try {
if (this.allowed(event.request.url)) await lease.network.send('Fetch.continueRequest',{requestId:event.requestId});
else {
if (event.resourceType==='Document' && event.frameId===lease.mainFrameId) lease.blocked=true;
await lease.network.send('Fetch.failRequest',{requestId:event.requestId,errorReason:'BlockedByClient'});
}
} catch {}
});
await lease.network.send('Fetch.enable',{patterns:[{urlPattern:'*',requestStage:'Request'}]});
lease.context.on('page', page=>{ if (page !== lease.page) page.close().catch(()=>{}); });
lease.page.on('download', download=>download.cancel().catch(()=>{}));
lease.page.on('dialog', dialog=>dialog.dismiss().catch(()=>{}));
await lease.page.goto(this.urls.main,{waitUntil:'domcontentloaded',timeout:30000});
this.authorize(connection,principal);
if (lease.blocked || !this.allowed(lease.page.url())) throw error('已阻止离开允许的 BPM 域名。',403);
await this.fillSavedAccount(lease);
return lease;
} catch (cause) { await this.closeLease(connection.id); throw safe(cause); }
}
async open(connection, principal) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
const lease=this.sessions.has(connection.id) ? await this.getLease(connection.id,principal,true) : await this.create(connection,principal);
return { active:true,viewport:{width:1280,height:800},expiresAt:new Date(lease.expiresAt).toISOString(),host:new URL(lease.page.url()).host };
});
}
async frame(id,principal) { return this.run(id,async()=>{ const lease=await this.getLease(id,principal); return lease.page.screenshot({type:'jpeg',quality:75,caret:'initial',timeout:10000}); }); }
async input(id,principal,action) {
return this.run(id,async()=>{
if (!object(action,['type','x','y','text','key','deltaX','deltaY'])) throw error('输入操作无效。');
const type=action.type;
if (type==='click') { if (!Number.isFinite(action.x)||!Number.isFinite(action.y)||action.x<0||action.x>=1280||action.y<0||action.y>=800) throw error('点击位置无效。'); }
else if (type==='text') { if (typeof action.text!=='string'||action.text.length>2000) throw error('输入文字过长或无效。'); }
else if (type==='key') { if (!KEYS.has(action.key)) throw error('不支持此按键。'); }
else if (type==='scroll') { if (![action.deltaX,action.deltaY].every(value=>Number.isFinite(value)&&Math.abs(value)<=10000)) throw error('滚动距离无效。'); }
else throw error('输入操作无效。');
const lease=await this.getLease(id,principal,true);
if (type==='click') await lease.page.mouse.click(action.x,action.y);
if (type==='text') await lease.page.keyboard.insertText(action.text);
if (type==='key') await lease.page.keyboard.press(action.key);
if (type==='scroll') await lease.page.mouse.wheel(action.deltaX,action.deltaY);
return {ok:true};
});
}
async navigate(id,principal,action) {
return this.run(id,async()=>{
if (!object(action,['target']) || !['main','reload','back'].includes(action.target)) throw error('导航目标无效。');
const lease=await this.getLease(id,principal,true), options={waitUntil:'domcontentloaded',timeout:30000};
if (action.target==='reload') await lease.page.reload(options);
else if (action.target==='back') await lease.page.goBack(options);
else await lease.page.goto(this.urls[action.target],options);
if (lease.blocked || !this.allowed(lease.page.url())) throw error('已阻止离开允许的 BPM 域名。',403);
await this.fillSavedAccount(lease);
return {ok:true,host:new URL(lease.page.url()).host};
});
}
async defaultProbe(page) {
const marker=page.locator('a.yz-btn-signinuser .x-btn-inner').first();
await marker.waitFor({state:'visible',timeout:4000}).catch(()=>{});
if (!await marker.isVisible().catch(()=>false)) return {ok:false};
const identity=(await marker.innerText()).trim();
return {ok:!!identity && !/^(登录|请登录|未登录|sign\s*in|login)$/i.test(identity),identity};
}
async captureSessions(lease) {
for (const frame of lease.page.frames()) {
if (!this.allowed(frame.url())) continue;
const item=await frame.evaluate(()=>({origin:location.origin,values:Object.fromEntries(Object.entries(sessionStorage))})).catch(()=>null);
if (item) lease.sessionStorage[item.origin]=item.values;
}
}
async settleNavigation(lease) {
// A protocol round trip lets an input-triggered navigation notification arrive;
// the wait itself follows lifecycle events, with a deadline rather than a sleep.
await lease.network.send('Page.getFrameTree');
const pending=lease.pendingNavigation;
if (pending) {
let timeout;
try { await Promise.race([pending,new Promise((_,reject)=>{timeout=setTimeout(()=>reject(error('BPM 页面仍在加载,请稍后重试。',503)),15000);})]); }
finally { clearTimeout(timeout); }
}
await lease.page.waitForLoadState('domcontentloaded',{timeout:15000});
}
async readOnlyGoto(lease,url) {
await this.settleNavigation(lease);
for (let attempt=0;attempt<2;attempt++) {
try { return await lease.page.goto(url,{waitUntil:'domcontentloaded',timeout:25000}); }
catch (cause) {
// Retry only our read-only verification GET, never the user's login action.
if (attempt || lease.blocked || !/interrupted by another navigation|ERR_ABORTED/i.test(cause.message||'')) throw cause;
await this.settleNavigation(lease);
}
}
}
async verify(lease) {
const checkedAt=new Date().toISOString();
try {
await this.settleNavigation(lease);await this.captureSessions(lease);
lease.blocked=false;
const response=await this.readOnlyGoto(lease,this.urls.main);
if (lease.blocked || !this.allowed(lease.page.url())) throw error('域名被阻止。',403);
if (response && response.status()>=400) throw error('BPM 暂时无法连接。',503);
const result=await this.probe(lease.page,'portal');
const ok=result?.ok===true && typeof result.identity==='string' && !!result.identity.trim();
await this.captureSessions(lease);
return {status:ok?'connected':'login_required',identity:ok?result.identity.trim().slice(0,150):'',checkedAt,checks:{portal:{ok,message:ok?'已验证登录账号。':'请在此入口完成登录。'}}};
} catch {
return {status:'error',identity:'',checkedAt,checks:{portal:{ok:false,message:lease.blocked?'已阻止离开允许的 BPM 域名。':'暂时无法验证此入口。'}}};
}
}
async save(connection,principal) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true);
const result=await this.verify(lease);
this.authorize(connection,principal);
// Failed verification never replaces a previously working credential snapshot.
if (this.canPersistVerified(result)) await this.persistLease(lease);
return result;
});
}
async check(connection,principal) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
const transient=!this.sessions.has(connection.id);
const lease=transient ? await this.create(connection,principal) : await this.getLease(connection.id,principal,true);
try { const result=await this.verify(lease); this.authorize(connection,principal); if(this.canPersistVerified(result))await this.persistLease(lease); return result; }
finally { if (transient) await this.closeLease(connection.id); }
});
}
async closeLease(id) {
const lease=this.sessions.get(id); if (!lease) return;
clearTimeout(lease.timer); this.sessions.delete(id);
await lease.context?.close().catch(()=>{});
}
async close(id,principal) { return this.run(id,async()=>{ if (!this.sessions.has(id)) return {active:false}; await this.getLease(id,principal,false,true); await this.closeLease(id); return {active:false}; }); }
async releaseSession(sessionId) { await Promise.all([...this.sessions.values()].filter(lease=>lease.sessionId===sessionId).map(lease=>this.run(lease.id,()=>this.closeLease(lease.id)))); }
async disable(id) { this.disabled.add(id); await this.run(id,async()=>{ await this.closeLease(id); await this.vault().remove(id); await this.vault().remove('account:'+id); }); }
async shutdown() {
this.stopped=true;
await Promise.allSettled([...this.operations.values()]);
await Promise.all([...this.sessions.keys()].map(id=>this.closeLease(id)));
if (this.browserPromise) await (await this.browserPromise.catch(()=>null))?.close().catch(()=>{});
this._vault?.destroy();
}
}
module.exports={BpmSessionManager};
+123
View File
@@ -0,0 +1,123 @@
'use strict';
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const path = require('node:path');
const crypto = require('node:crypto');
const { execFileSync } = require('node:child_process');
const { DatabaseSync } = require('node:sqlite');
const fail = () => Object.assign(new Error('BPM 会话存储不可用,请重新登录或联系管理员。'), { status: 503 });
const duplicate = () => Object.assign(new Error('该 BPM 账号已开启自动续登,请使用已有连接或先解除原账号托管。'), { status: 409, code: 'BPM_ACCOUNT_DUPLICATE' });
const digest = value => crypto.createHash('sha256').update(value).digest('hex');
function powershell(script, input) {
return execFileSync('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script], {
input, encoding: 'utf8', windowsHide: true, timeout: 15000, stdio: ['pipe', 'pipe', 'pipe']
}).trim();
}
function secureDirectory(dir) {
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
if (process.platform === 'win32') {
powershell('$ErrorActionPreference="Stop"; $p=[Console]::In.ReadToEnd(); $s=[System.Security.Principal.WindowsIdentity]::GetCurrent().User; $a=New-Object System.Security.AccessControl.DirectorySecurity; $a.SetAccessRuleProtection($true,$false); $a.SetOwner($s); $r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow"); $a.AddAccessRule($r); [System.IO.Directory]::SetAccessControl($p,$a)', dir);
} else fs.chmodSync(dir, 0o700);
}
function dpapi(value, decrypt = false) {
const operation = decrypt ? 'Unprotect' : 'Protect';
return Buffer.from(powershell(`$ErrorActionPreference="Stop"; Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd()); $r=[System.Security.Cryptography.ProtectedData]::${operation}($b,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Out.Write([Convert]::ToBase64String($r))`, value.toString('base64')), 'base64');
}
class BpmVault {
constructor({ stateDir }) {
try {
this.stateDir = path.resolve(stateDir);
secureDirectory(this.stateDir);
} catch { throw fail(); }
}
ensureKey() {
if (this.key) return this.key;
try {
// The key always stays on the service user's local disk, even when project code is on a shared drive.
const keyDir = process.platform === 'win32'
? path.join(process.env.LOCALAPPDATA, 'OrderNotificationAutomation', 'bpm-keys')
: path.join(this.stateDir, '.keys');
secureDirectory(keyDir);
const keyFile = path.join(keyDir, digest(this.stateDir.toLowerCase()) + '.key');
if (!fs.existsSync(keyFile)) {
const raw = crypto.randomBytes(32);
const protectedKey = process.platform === 'win32' ? dpapi(raw) : raw;
try { fs.writeFileSync(keyFile, protectedKey, { flag: 'wx', mode: 0o600 }); }
catch (error) { if (error.code !== 'EEXIST') throw error; }
finally { raw.fill(0); }
}
const protectedKey = fs.readFileSync(keyFile);
this.key = process.platform === 'win32' ? dpapi(protectedKey, true) : protectedKey;
if (this.key.length !== 32) throw fail();
return this.key;
} catch { throw fail(); }
}
filename(id) {
if (typeof id !== 'string' || !id || id.length > 200) throw Object.assign(new Error('连接标识无效。'), { status: 400 });
return path.join(this.stateDir, digest(id) + '.enc');
}
accounts() {
if(this.db)return this.db;
const db=new DatabaseSync(path.join(this.stateDir,'accounts.sqlite'));
try{db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS accounts(connection_id TEXT PRIMARY KEY,username_key TEXT NOT NULL UNIQUE,payload BLOB NOT NULL);`);this.db=db;return db;}
catch{db.close();throw fail();}
}
accountKey(username) {
if(typeof username!=='string'||!username.trim()||username.length>150)throw Object.assign(new Error('请输入有效的 BPM 账号。'),{status:400});
return crypto.createHmac('sha256',this.ensureKey()).update(username.trim().toLowerCase()).digest('hex');
}
encode(id,state) {
const iv=crypto.randomBytes(12),cipher=crypto.createCipheriv('aes-256-gcm',this.ensureKey(),iv);cipher.setAAD(Buffer.from(id));
const encrypted=Buffer.concat([cipher.update(JSON.stringify(state),'utf8'),cipher.final()]);
return Buffer.concat([Buffer.from('BPM1'),iv,cipher.getAuthTag(),encrypted]);
}
decode(id,bytes) {
const data=Buffer.from(bytes);
if(data.length<33||data.subarray(0,4).toString()!=='BPM1')throw fail();
const decipher=crypto.createDecipheriv('aes-256-gcm',this.ensureKey(),data.subarray(4,16));
decipher.setAAD(Buffer.from(id));decipher.setAuthTag(data.subarray(16,32));
return JSON.parse(Buffer.concat([decipher.update(data.subarray(32)),decipher.final()]).toString('utf8'));
}
putAccount(id,state) {
try{this.accounts().prepare('INSERT INTO accounts(connection_id,username_key,payload) VALUES(?,?,?) ON CONFLICT(connection_id) DO UPDATE SET username_key=excluded.username_key,payload=excluded.payload').run(id.slice(8),this.accountKey(state.username),this.encode(id,state));}
catch(cause){if(cause.errcode===2067)throw duplicate();if(cause.status)throw cause;throw fail();}
}
async accountAvailability(connectionId,username) {
try{const row=this.accounts().prepare('SELECT connection_id FROM accounts WHERE username_key=?').get(this.accountKey(username));return {available:!row||row.connection_id===connectionId};}
catch(cause){if(cause.status)throw cause;throw fail();}
}
async migrateAccounts(connectionIds) {
const db=this.accounts(),legacy=[];
try{
for(const connectionId of connectionIds){const id='account:'+connectionId;if(db.prepare('SELECT 1 FROM accounts WHERE connection_id=?').get(connectionId))continue;try{const payload=await fsp.readFile(this.filename(id));legacy.push({id,state:this.decode(id,payload)});}catch(cause){if(cause.code!=='ENOENT')throw cause;}}
db.exec('BEGIN IMMEDIATE');
try{for(const item of legacy)this.putAccount(item.id,item.state);db.exec('COMMIT');}catch(cause){db.exec('ROLLBACK');throw cause;}
// Committed database rows become authoritative before legacy ciphertext is removed.
for(const item of legacy)await fsp.rm(this.filename(item.id),{force:true});
}catch(cause){if(cause.status)throw cause;throw fail();}
}
async read(id) {
const filename = this.filename(id);
try {
if(id.startsWith('account:')){const row=this.accounts().prepare('SELECT payload FROM accounts WHERE connection_id=?').get(id.slice(8));if(row)return this.decode(id,row.payload);}
const state=this.decode(id,await fsp.readFile(filename));
if(id.startsWith('account:')){this.putAccount(id,state);await fsp.rm(filename,{force:true});}
return state;
} catch (error) { if (error.code === 'ENOENT') return null;if(error.code==='BPM_ACCOUNT_DUPLICATE')throw error;throw fail(); }
}
async write(id, state) {
const filename = this.filename(id), temp = filename + '.' + crypto.randomUUID() + '.tmp';
if(id.startsWith('account:')){this.putAccount(id,state);await fsp.rm(filename,{force:true}).catch(()=>{});return;}
try {
await fsp.writeFile(temp, this.encode(id,state), { flag: 'wx', mode: 0o600 });
await fsp.rename(temp, filename);
} catch { throw fail(); }
finally { await fsp.rm(temp, { force: true }).catch(() => {}); }
}
async remove(id) { try { await fsp.rm(this.filename(id), { force: true });if(id.startsWith('account:'))this.accounts().prepare('DELETE FROM accounts WHERE connection_id=?').run(id.slice(8)); } catch { throw fail(); } }
destroy() { this.db?.close();this.db=null;this.key?.fill(0);this.key=null; }
}
module.exports = { BpmVault };
+32
View File
@@ -0,0 +1,32 @@
const fs=require('node:fs');
const path=require('node:path');
const crypto=require('node:crypto');
const {DatabaseSync}=require('node:sqlite');
const DAY=86400000;
const SESSION_MS=30*DAY;
const digest=token=>crypto.createHash('sha256').update(token).digest('hex');
class SessionStore {
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'auth.sqlite'));
this.db.exec('PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL);');
}
issue(userId,now=Date.now()){
this.db.prepare('DELETE FROM sessions WHERE expires<=?').run(now);
this.db.exec('DELETE FROM sessions WHERE hash IN (SELECT hash FROM sessions ORDER BY renewedAt DESC LIMIT -1 OFFSET 999)');
const token=crypto.randomBytes(32).toString('hex'),expires=now+SESSION_MS;
this.db.prepare('INSERT INTO sessions(hash,userId,expires,renewedAt) VALUES(?,?,?,?)').run(digest(token),userId,expires,now);
return {token,expires};
}
lookup(token,now=Date.now()){
if(typeof token!=='string' || !/^[a-f0-9]{64}$/.test(token))return null;
const hash=digest(token),row=this.db.prepare('SELECT userId,expires,renewedAt FROM sessions WHERE hash=?').get(hash);
if(!row)return null;
if(row.expires<=now){this.db.prepare('DELETE FROM sessions WHERE hash=?').run(hash);return null;}
const renewed=now-row.renewedAt>=DAY;
if(renewed){row.expires=now+SESSION_MS;this.db.prepare('UPDATE sessions SET expires=?,renewedAt=? WHERE hash=?').run(row.expires,now,hash);}
return {userId:row.userId,expires:row.expires,renewed};
}
revoke(token){if(typeof token==='string' && /^[a-f0-9]{64}$/.test(token))this.db.prepare('DELETE FROM sessions WHERE hash=?').run(digest(token));}
close(){if(this.db){this.db.close();this.db=null;}}
}
module.exports={SessionStore,SESSION_MS};
+99
View File
@@ -0,0 +1,99 @@
const fs=require('node:fs');
const path=require('node:path');
const crypto=require('node:crypto');
const copy=value=>structuredClone(value);
const safeUser=({id,username,role,createdAt})=>({id,username,role,createdAt});
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
function validateSettings(settings) {
const schedule=settings.schedule;
if(!schedule || !Array.isArray(schedule.times) || schedule.times.length!==2 || new Set(schedule.times).size!==2)fail('请设置两个不同的发送时间。');
if(schedule.times.some(time=>typeof time!=='string' || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(time)))fail('时间必须为有效的 HH:MM。');
if(typeof schedule.weekends!=='boolean' || !['product_line','order'].includes(schedule.mode) || !['next_window','skip'].includes(schedule.missed))fail('发送计划选项不正确。');
if(schedule.timezone!=='Asia/Shanghai')fail('时区必须为 Asia/Shanghai。');
if(!settings.templates || typeof settings.templates.subject!=='string' || typeof settings.templates.body!=='string' || settings.templates.subject.length>300 || settings.templates.body.length>20000)fail('模板标题最多 300 字,正文最多 20000 字。');
if(!Array.isArray(settings.groups) || settings.groups.length>100)fail('收件群组格式不正确。');
const names=new Set();
for(const group of settings.groups) {
if(!group || typeof group.productLine!=='string' || !group.productLine.trim() || group.productLine.length>100 || names.has(group.productLine.trim()))fail('产品线名称不能为空或重复。');
names.add(group.productLine.trim());
for(const field of ['to','cc']) {
if(!Array.isArray(group[field]) || group[field].length>50 || group[field].some(email=>typeof email!=='string' || email.length>254 || !/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)))fail('请填写有效的收件邮箱,使用逗号分隔。');
}
if(group.to.length===0)fail('每个产品线至少需要一个收件人。');
}
}
class Store {
constructor(dir) {
fs.mkdirSync(dir,{recursive:true});this.file=path.join(dir,'state.json');
try {this.data=JSON.parse(fs.readFileSync(this.file,'utf8'));if(this.data.schema!==1)fail('状态文件版本不支持。',500);}
catch(error) {if(error.code!=='ENOENT')throw error;this.data={schema:1,users:[],settings:{version:1,schedule:{times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:false,mode:'product_line',missed:'next_window'},templates:{subject:'',body:''},groups:[]},jobs:[],audit:[]};}
}
commit(mutator) {
const draft=copy(this.data);const result=mutator(draft);
const temp=this.file+'.'+crypto.randomBytes(6).toString('hex')+'.tmp';
try {fs.writeFileSync(temp,JSON.stringify(draft,null,2),{mode:0o600});fs.renameSync(temp,this.file);}
catch(error){try{fs.unlinkSync(temp);}catch{}throw error;}
this.data=draft;return copy(result);
}
addAudit(draft,actor,action,detail='') {draft.audit.unshift({id:crypto.randomUUID(),at:new Date().toISOString(),actor,action,detail});draft.audit=draft.audit.slice(0,2000);}
settings(){return copy(this.data.settings);}
saveSettings(patch,version,actor) {
return this.commit(draft=>{
if(version!==draft.settings.version)fail('配置已被其他人更新,请刷新后重试。',409);
const updated={...draft.settings};
for(const key of ['schedule','templates','groups'])if(Object.hasOwn(patch,key))updated[key]=copy(patch[key]);
validateSettings(updated);
updated.schedule={times:[...updated.schedule.times].sort(),timezone:'Asia/Shanghai',weekends:updated.schedule.weekends,mode:updated.schedule.mode,missed:updated.schedule.missed};
updated.templates={subject:updated.templates.subject,body:updated.templates.body};
updated.groups=updated.groups.map(group=>({productLine:group.productLine.trim(),to:group.to,cc:group.cc}));
updated.version++;draft.settings=updated;
this.addAudit(draft,actor,'保存配置','发送计划 / 模板 / 产品线群组');return updated;
});
}
users(){return this.data.users.map(safeUser);}
user(id){const user=this.data.users.find(user=>user.id===id);return user?safeUser(user):null;}
makeUser(username,password,role) {
if(typeof username!=='string' || !/^[a-zA-Z0-9_.-]{3,40}$/.test(username))fail('账号需为 3–40 位英文、数字、点、下划线或短横线。');
if(typeof password!=='string' || password.length<12 || password.length>128)fail('密码长度需为 12–128 位。');
if(!['admin','operator','viewer'].includes(role))fail('账号角色不正确。');
if(this.data.users.some(user=>user.username.toLowerCase()===username.toLowerCase()))fail('账号已存在。',409);
const salt=crypto.randomBytes(16).toString('hex');
return {id:crypto.randomUUID(),username,role,createdAt:new Date().toISOString(),passwordHash:salt+':'+crypto.scryptSync(password,salt,32).toString('hex')};
}
bootstrap(username,password) {
if(this.data.users.length)fail('管理员已经创建,请登录。',409);
const user=this.makeUser(username,password,'admin');
return this.commit(draft=>{draft.users.push(user);this.addAudit(draft,username,'创建管理员');return safeUser(user);});
}
addUser(input,actor) {
const user=this.makeUser(input.username,input.password,input.role);
return this.commit(draft=>{draft.users.push(user);this.addAudit(draft,actor,'创建账号',user.username+' / '+user.role);return safeUser(user);});
}
authenticate(username,password) {
if(typeof username!=='string' || typeof password!=='string' || password.length>128)return null;
const user=this.data.users.find(user=>user.username.toLowerCase()===username.toLowerCase());
const [salt,hash]=(user?.passwordHash || '00000000000000000000000000000000:'+ '0'.repeat(64)).split(':');
const actual=crypto.scryptSync(password,salt,32);
if(!crypto.timingSafeEqual(actual,Buffer.from(hash,'hex')) || !user)return null;
return safeUser(user);
}
recordJob(record) {
return this.commit(draft=>{
const index=draft.jobs.findIndex(job=>job.jobId===record.jobId);
const prior=index>=0?draft.jobs[index]:{createdAt:new Date().toISOString()};
const saved={...prior,...copy(record),updatedAt:new Date().toISOString()};
if(index>=0)draft.jobs.splice(index,1);draft.jobs.unshift(saved);draft.jobs=draft.jobs.slice(0,5000);
if(record.status!=='running')this.addAudit(draft,'浏览器导出',record.status==='success'?'PDF 导出完成':'PDF 导出失败',record.filename || record.error || '');
return saved;
});
}
jobs(){return copy(this.data.jobs);}
audit(){return copy(this.data.audit);}
recoverJobs() {
if(!this.data.jobs.some(job=>job.status==='running'))return;
this.commit(draft=>{for(const job of draft.jobs)if(job.status==='running'){job.status='interrupted';job.error='服务重启,请核对输出文件后重新导出。';}return null;});
}
}
module.exports={Store};
+121
View File
@@ -0,0 +1,121 @@
const http=require('node:http');const fs=require('node:fs');const path=require('node:path');
const {nextSlots}=require('./schedule.cjs');
const {workspaceApi}=require('./workspace-api.cjs');
const {bpmApi}=require('./bpm-api.cjs');
const {mailApi}=require('./mail-api.cjs');
const {bpmScanApi}=require('./bpm-scan-api.cjs');
const {SessionStore,SESSION_MS}=require('./dashboard-sessions.cjs');
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'});
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,trustedProxy=false}) {
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map();
const sessionCookieName=previewUserId?'order_preview_session':'order_session';
const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)');
const webRoot=path.resolve(__dirname,'../web');
const assets={
'/':{path:path.join(webRoot,'index.html'),type:'text/html'},
'/app.js':{path:path.join(webRoot,'app.js'),type:'text/javascript'},
'/workspace.js':{path:path.join(webRoot,'workspace.js'),type:'text/javascript'},
'/bpm.js':{path:path.join(webRoot,'bpm.js'),type:'text/javascript'},
'/mail.js':{path:path.join(webRoot,'mail.js'),type:'text/javascript'},
'/orders.js':{path:path.join(webRoot,'orders.js'),type:'text/javascript'},
'/app.css':{path:path.join(webRoot,'app.css'),type:'text/css'},
'/vendor/tabler.css':{path:require.resolve('@tabler/core/dist/css/tabler.min.css'),type:'text/css'},
'/vendor/tabler.js':{path:require.resolve('@tabler/core/dist/js/tabler.min.js'),type:'text/javascript'}
};
const server=http.createServer(async(request,response)=>{
const encryptedTransport=Boolean(request.socket.encrypted || (trustedProxy && isLoopback(request.socket.remoteAddress) && request.headers['x-forwarded-proto']==='https'));
response.setHeader('X-Content-Type-Options','nosniff');response.setHeader('Referrer-Policy','same-origin');
response.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
response.setHeader('Cache-Control','no-store');
const reply=(status,body)=>{response.writeHead(status,{'Content-Type':'application/json; charset=utf-8'});response.end(JSON.stringify(body));};
const fail=(status,message)=>{throw Object.assign(new Error(message),{status});};
try {
const url=new URL(request.url,'http://localhost');const route=url.pathname;
const asset=assets[route];
if(request.method==='GET' && asset) {
const bytes=await fs.promises.readFile(asset.path);response.writeHead(200,{'Content-Type':asset.type+'; charset=utf-8'});response.end(bytes);return;
}
const sameOrigin=request.headers.origin===`http://${request.headers.host}` || request.headers.origin===`https://${request.headers.host}`;
if(!['GET','HEAD'].includes(request.method) && !sameOrigin)fail(403,'请在看板页面中执行操作。');
let body;
if(request.method==='POST') {
if(!/^application\/json(?:;|$)/i.test(request.headers['content-type'] || ''))fail(415,'需要 JSON 数据。');
if(Number(request.headers['content-length'] || 0)>128*1024){request.resume();fail(413,'提交内容过大。');}
const chunks=[];let size=0;
for await(const chunk of request){size+=chunk.length;if(size>128*1024)fail(413,'提交内容过大。');chunks.push(chunk);}
try{body=JSON.parse(Buffer.concat(chunks).toString('utf8'));if(!body || Array.isArray(body) || typeof body!=='object')throw new Error();}catch{fail(400,'数据格式不正确。');}
}
const host=(request.headers.host || '').split(':')[0];
const canSetup=isLoopback(request.socket.remoteAddress) && ['localhost','127.0.0.1'].includes(host);
const preview=Boolean(previewUserId && canSetup && store.user(previewUserId));
if(route==='/api/bootstrap/status' && request.method==='GET')return reply(200,{required:store.users().length===0,canSetup,preview});
function signIn(user) {
const {token}=sessions.issue(user.id);
response.setHeader('Set-Cookie',`${sessionCookieName}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS/1000}${encryptedTransport?'; Secure':''}`);
return user;
}
if(route==='/api/bootstrap' && request.method==='POST') {
if(!canSetup)fail(403,'请在部署机访问 http://127.0.0.1:18766 创建管理员。');
return reply(201,{user:signIn(store.bootstrap(body.username,body.password))});
}
if(route==='/api/preview-login' && request.method==='POST') {
if(!previewUserId)fail(404,'没有找到此页面或操作。');
if(!preview)fail(403,'演示登录仅允许在部署机本地访问。');
return reply(200,{user:signIn(store.user(previewUserId)),preview:true});
}
if(route==='/api/login' && request.method==='POST') {
const address=request.socket.remoteAddress;const now=Date.now();
for(const [key,value] of failures)if(now-value.since>900000)failures.delete(key);
if(failures.get(address)?.count>=10)fail(429,'登录失败次数过多,请 15 分钟后重试。');
const user=store.authenticate(body.username,body.password);
if(!user){if(failures.size>1000)failures.clear();const previous=failures.get(address);failures.set(address,{since:previous?.since || now,count:(previous?.count || 0)+1});fail(401,'账号或密码不正确。');}
failures.delete(address);return reply(200,{user:signIn(user)});
}
const token=sessionCookiePattern.exec(request.headers.cookie || '')?.[1];
const session=sessions.lookup(token);const user=session?store.user(session.userId):null;
if(!user)fail(401,'请先登录。');
if(session.renewed)response.setHeader('Set-Cookie',`${sessionCookieName}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS/1000}${encryptedTransport?'; Secure':''}`);
if(route==='/api/me' && request.method==='GET')return reply(200,{user,preview});
if(route==='/api/logout' && request.method==='POST'){sessions.revoke(token);response.setHeader('Set-Cookie',`${sessionCookieName}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0${encryptedTransport?'; Secure':''}`);if(bpmSessions)try{await bpmSessions.releaseSession(token);}catch{fail(502,'登录窗口关闭失败,请稍后重试。');}return reply(200,{ok:true});}
if(await bpmApi({workspace,bpmSessions,user,sessionId:token,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await mailApi({mail,workspace,user,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await bpmScanApi({scanner,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return;
if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return;
if(route==='/api/overview' && request.method==='GET') {
const jobs=store.jobs();const settings=store.settings();const mailChannels=mail?.store.channels()||[];const mailTemplates=mail?.store.templates()||[];
const today=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date());
const todayJobs=jobs.filter(job=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(job.updatedAt))===today);
const scan=scanner?.store.status();
return reply(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation:{enabled:false,reason:'待接入订单规则表和归档目录,业务自动处理尚未启用。'},connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'订单规则表',ready:false,detail:'等待提供表格,随后配置列映射与筛选'},{name:'BPM 自动扫描',ready:!!scan?.runs.some(r=>r.status==='success'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'扫描服务未启动'},{name:'210 服务器',ready:false,detail:'等待完整地址、协议和归档目录'},{name:'邮件渠道',ready:mailChannels.some(c=>c.state.smtp&&c.state.imap),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认`},{name:'产品线群组',ready:settings.groups.length>0,detail:`已配置 ${settings.groups.length} 个产品线`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)});
}
if(route==='/api/settings') {
if(request.method==='GET')return reply(200,store.settings());
if(request.method==='POST'){if(user.role!=='admin')fail(403,'仅管理员可以修改配置。');return reply(200,store.saveSettings(body,body.version,user.username));}
}
if(route==='/api/jobs' && request.method==='GET')return reply(200,{jobs:store.jobs().map(publicJob)});
if(route==='/api/audit' && request.method==='GET')return reply(200,{audit:store.audit()});
if(route==='/api/users') {
if(user.role!=='admin')fail(403,'仅管理员可以管理账号。');
if(request.method==='GET')return reply(200,{users:store.users()});
if(request.method==='POST')return reply(201,{user:store.addUser(body,user.username)});
}
const download=/^\/api\/jobs\/([\w-]+)\/file$/.exec(route);
if(download && request.method==='GET') {
const job=store.jobs().find(job=>job.jobId===download[1]);
if(!job || job.status!=='success' || !job.path)fail(404,'文件不可用。');
let realRoot,realFile;
try{[realRoot,realFile]=await Promise.all([fs.promises.realpath(outputDir),fs.promises.realpath(job.path)]);}catch{fail(404,'文件不存在。');}
const relative=path.relative(realRoot,realFile);
if(!relative || relative.startsWith('..'+path.sep) || relative==='..' || path.isAbsolute(relative) || path.extname(realFile).toLowerCase()!=='.pdf')fail(404,'文件不可用。');
const bytes=await fs.promises.readFile(realFile);
response.writeHead(200,{'Content-Type':'application/pdf','Content-Disposition':`attachment; filename*=UTF-8''${encodeURIComponent(path.basename(realFile))}`});response.end(bytes);return;
}
fail(404,'没有找到此页面或操作。');
}catch(error){if(!response.headersSent){if(!error.status)console.error('看板处理失败:',error.message);reply(error.status || 500,{error:error.status?error.message:'处理失败,请检查服务日志。'});}else response.end();}
});
server.once('close',()=>sessions.close());server.once('error',()=>{if(!server.listening)sessions.close();});
return server;
}
module.exports={createDashboard};
+90
View File
@@ -0,0 +1,90 @@
const fs = require('node:fs/promises');
const path = require('node:path');
const { loadPlaywright, browserOptions } = require('./runtime.cjs');
const fields = { order: '订单号', project: '项目编号', model: '产品型号', serial: '通知书编号' };
function buildFilename(metadata = {}) {
const parts = Object.entries(fields).map(([key, label]) => {
if (typeof metadata[key] !== 'string' || !metadata[key].trim()) throw new Error(`缺少${label},请在订单页检查。`);
const value = metadata[key].trim().replace(/[<>:"/\\|?*\x00-\x1f\x7f]/g, '_').replace(/[. ]+$/g, '').slice(0, 45);
if (!value || !/[^._ ]/.test(value)) throw new Error(`${label}不能用于文件名。`);
return value;
});
return parts.join('_') + '.pdf';
}
function validateSnapshot(snapshot) {
if (!snapshot || typeof snapshot.html !== 'string' || !snapshot.html.trim() || snapshot.html.length > 12_000_000) throw new Error('页面内容为空或超过大小限制。');
buildFilename(snapshot.metadata);
if (snapshot.styles !== undefined && (!Array.isArray(snapshot.styles) || snapshot.styles.some(s => typeof s !== 'string'))) throw new Error('页面样式格式不正确。');
if (snapshot.images !== undefined && (!Array.isArray(snapshot.images) || snapshot.images.length > 200)) throw new Error('页面图片格式不正确。');
}
async function reserveFile(outputDir, filename) {
await fs.mkdir(outputDir, { recursive: true });
for (let index = 1; index <= 9999; index++) {
const suffix = index === 1 ? '' : ` (${index})`;
const target = path.join(outputDir, filename.slice(0, -4) + suffix + '.pdf');
try { const handle = await fs.open(target, 'wx'); return { target, handle }; }
catch (error) { if (error.code !== 'EEXIST') throw error; }
}
throw new Error('同名文件过多,请更换输出目录。');
}
async function renderSnapshot(snapshot, options = {}) {
validateSnapshot(snapshot);
const filename = buildFilename(snapshot.metadata);
const outputDir = path.resolve(options.outputDir || path.join(__dirname, '../output/pdf'));
const scale = options.scale ?? 0.59;
if (typeof scale !== 'number' || scale < 0.1 || scale > 2) throw new Error('scale 必须在 0.1 到 2 之间。');
const browser = await loadPlaywright().chromium.launch(browserOptions());
let reservation;
try {
const context = await browser.newContext({ javaScriptEnabled: false, serviceWorkers: 'block', viewport: { width: 1280, height: 1000 } });
await context.route('**/*', route => route.abort());
const page = await context.newPage();
await page.goto('about:blank');
// Only static markup enters the document. Network and page scripts stay disabled.
const content = await page.evaluate(({ html, styles, images, width }) => {
const doc = new DOMParser().parseFromString(html, 'text/html');
doc.querySelectorAll('script,iframe,object,embed,link,base,meta,input,button,textarea,select,[printout="false"],#taskCommentForm').forEach(el => el.remove());
doc.querySelectorAll('*').forEach(el => {
for (const attribute of [...el.attributes]) {
if (/^on/i.test(attribute.name) || ['action','srcdoc','srcset','formaction','href','poster','background'].includes(attribute.name.toLowerCase())) el.removeAttribute(attribute.name);
}
if (el.hidden || /display\s*:\s*none/i.test(el.getAttribute('style') || '')) el.remove();
});
const supplied = new Map((images || []).filter(image => image && typeof image.url === 'string' && /^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/=\r\n]+$/i.test(image.data || '')).map(image => [image.url, image.data]));
doc.querySelectorAll('img').forEach(el => {
const value = supplied.get(el.getAttribute('src')) || el.getAttribute('src') || '';
if (/^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/=\r\n]+$/i.test(value)) el.setAttribute('src', value); else el.remove();
});
const cleanCSS = css => css.replace(/@import\s+[^;]+;/gi, '').replace(/url\([^)]*\)/gi, 'none').replace(/<\/style/gi, '');
const css = (styles || []).map(cleanCSS).join('\n');
doc.querySelectorAll('style').forEach(el => el.remove());
const style = doc.createElement('style');
const pageWidth = Math.min(1264, Math.max(800, Number(width) || 1264));
style.textContent = css + `\nhtml,body{margin:0;padding:0;background:white}body,form{width:${pageWidth}px;font-family:Arial,"Microsoft YaHei",sans-serif}table{max-width:100%}tr{break-inside:avoid;page-break-inside:avoid}td{overflow-wrap:anywhere}a{color:inherit;text-decoration:none}span.TextBox,span.TextBoxPink{height:auto!important;min-height:16px}@media print{html,body{-webkit-print-color-adjust:exact;print-color-adjust:exact}}`;
doc.head.append(style);
doc.querySelectorAll('.yz-inp-cnt').forEach(el => {
const match = (el.getAttribute('style') || '').match(/width\s*:\s*([\d.]+)px/);
const text = el.textContent.trim();
if (match && Number(match[1]) <= 50 && text) el.style.width = Math.max(50, Math.min(120, text.length * 8)) + 'px';
});
return '<!doctype html>' + doc.documentElement.outerHTML;
}, snapshot);
await page.setContent(content, { waitUntil: 'load', timeout: 30000 });
await page.evaluate(() => document.fonts.ready);
const pdf = await page.pdf({ format: 'A4', scale, printBackground: true, displayHeaderFooter: false, margin: { top: '8mm', right: '6mm', bottom: '8mm', left: '6mm' } });
if (pdf.subarray(0, 5).toString() !== '%PDF-') throw new Error('PDF 生成失败。');
reservation = await reserveFile(outputDir, filename);
await reservation.handle.writeFile(pdf);
await reservation.handle.close();
return { path: reservation.target, filename: path.basename(reservation.target), bytes: pdf.length, warnings: snapshot.warnings || [] };
} catch (error) {
if (reservation) { await reservation.handle.close().catch(() => {}); await fs.unlink(reservation.target).catch(() => {}); }
throw error;
} finally { await browser.close(); }
}
module.exports = { buildFilename, validateSnapshot, renderSnapshot };
+32
View File
@@ -0,0 +1,32 @@
'use strict';
const {secureBpmTransport}=require('./bpm-api.cjs');const {escape}=require('./mail-parser.cjs');
const fail=(message,status)=>{throw Object.assign(new Error(message),{status});};
async function mailApi({mail,workspace,user,route,method,body,request,response,reply,trustedProxy}){
if(!route.startsWith('/api/mail'))return false;if(!mail)fail('邮件服务暂不可用。',503);const store=mail.store;
if(method==='POST'&&user.role!=='admin')fail('仅管理员可以维护邮箱和确认模板。',403);
if(route==='/api/mail'&&method==='GET'){reply(200,{channels:store.channels(),templates:store.templates(),receipts:store.receipts(),sends:store.sends()});return true;}
const audit=(action,detail)=>workspace?.record(user,action,detail);
if(route==='/api/mail/channels'&&method==='POST'){
if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护邮箱账号。',403);
if(body?.id&&mail.busy(body.id))fail('此邮箱正在执行操作,请稍后保存。',409);const saved=store.saveChannel(body);audit('mail.channel.save',saved.name);reply(body.id?200:201,saved);return true;
}
let match=/^\/api\/mail\/channels\/([\w-]+)\/(verify|poll|test)$/.exec(route);
if(match&&method==='POST'){const [,id,action]=match;let result;if(action==='test'){if(typeof body.templateId!=='string')fail('请选择已生效模板。',400);result=await mail.sendTest(id,body.templateId);}else result=await mail[action](id);audit('mail.'+action,store.publicChannel(id).name);reply(200,result);return true;}
match=/^\/api\/mail\/templates\/([\w-]+)(?:\/(confirm|reject|preview|source|attachments\/([0-9]+)))?$/.exec(route);
if(match){const [,id,action,index]=match;const template=store.template(id);
if(method==='GET'&&!action){const {raw,attachments,...detail}=template;reply(200,{...detail,attachments:attachments.map(({content,...a})=>a)});return true;}
if(method==='GET'&&action==='preview'){
response.setHeader('Content-Security-Policy',"default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox; base-uri 'none'; form-action 'none'");
response.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});response.end('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><style>body{font:14px/1.7 system-ui,sans-serif;padding:16px;color:#182433;overflow-wrap:anywhere}img{max-width:100%;height:auto}table{border-collapse:collapse;max-width:100%}td,th{padding:6px;border:1px solid #ddd}pre{white-space:pre-wrap}</style><body>'+(template.html||'<pre>'+escape(template.text)+'</pre>')+'</body></html>');return true;
}
if(method==='GET'&&(action==='source'||action?.startsWith('attachments/'))){
if(user.role!=='admin')fail('仅管理员可以下载原邮件和附件。',403);let bytes,name;
if(action==='source'){bytes=store.source(id);name='template.eml';}else{const a=template.attachments[Number(index)];if(!a)fail('附件不存在。',404);bytes=Buffer.from(a.content,'base64');name=a.filename;}
response.writeHead(200,{'Content-Type':'application/octet-stream','Content-Disposition':"attachment; filename*=UTF-8''"+encodeURIComponent(name)});response.end(bytes);return true;
}
if(method==='POST'&&action==='confirm'){const saved=store.confirm(id,body,user.username);audit('mail.template.confirm',saved.subject);reply(200,{id:saved.id,status:saved.status,version:saved.version});return true;}
if(method==='POST'&&action==='reject'){store.reject(id,body.version);audit('mail.template.reject',template.subject);reply(200,{ok:true});return true;}
}
fail('没有找到此邮件操作。',404);
}
module.exports={mailApi};
+37
View File
@@ -0,0 +1,37 @@
'use strict';
const {simpleParser}=require('mailparser');const sanitize=require('sanitize-html');
const MAX_MAIL=10*1024*1024;
const fail=message=>{throw Object.assign(new Error(message),{status:400});};
const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const VARIABLES=['产品线','订单号','日期','订单列表'];
function validateVariables(...parts){for(const part of parts)for(const token of String(part||'').matchAll(/{{([\s\S]*?)}}/g))if(!VARIABLES.includes(token[1].trim()))fail('模板含有不支持的变量,请使用:'+VARIABLES.map(x=>'{{'+x+'}}').join('、'));}
function cleanHtml(html,attachments=[]){
let expandedBytes=Buffer.byteLength(html||'');
const inline=new Map(attachments.filter(a=>a.cid && /^image\/(png|jpeg|gif|webp)$/.test(a.contentType)).map(a=>[a.cid,'data:'+a.contentType+';base64,'+a.content]));
return sanitize(html||'',{allowedTags:['p','br','div','span','b','strong','i','em','u','s','ul','ol','li','blockquote','pre','code','h1','h2','h3','h4','table','thead','tbody','tfoot','tr','th','td','hr','img'],allowedAttributes:{'*':['style'],td:['colspan','rowspan','style'],th:['colspan','rowspan','style'],img:['src','alt','width','height']},allowedStyles:{'*':{'color':[/^#[0-9a-f]{3,8}$/i,/^[a-z]+$/i],'background-color':[/^#[0-9a-f]{3,8}$/i,/^[a-z]+$/i],'text-align':[/^(left|right|center)$/],'font-weight':[/^(bold|normal|[1-9]00)$/],'font-size':[/^\d{1,2}(px|pt)$/],'border':[/^\dpx solid #[0-9a-f]{3,6}$/i],'padding':[/^\d{1,2}px$/]}},allowedSchemes:['data'],allowedSchemesByTag:{img:['data']},transformTags:{img:(tag,attrs)=>{const src=attrs.src?.startsWith('cid:')?(inline.get(attrs.src.slice(4))||''):attrs.src||'';expandedBytes+=src.length;if(expandedBytes>12*1024*1024)fail('内嵌图片展开超过 12 MB,请减少重复图片后重新发送。');return {tagName:'img',attribs:{...attrs,src}};}},exclusiveFilter:frame=>frame.tag==='img'&&!/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/=]+$/.test(frame.attribs.src||'')});
}
async function parseTemplate(raw,channel){
if(!Buffer.isBuffer(raw)||raw.length>MAX_MAIL)fail('邮件超过 10 MB 限制。');
const mail=await simpleParser(raw,{skipImageLinks:true,skipTextToHtml:true,maxHtmlLengthToParse:1024*1024,maxInlinedImagesSize:MAX_MAIL});
const sourceSubject=(mail.subject||'').trim();if(!sourceSubject.startsWith('[模板]'))return null;
let title=sourceSubject.slice(4).trim(),scope='';
if(title.startsWith('[')){const scoped=/^\[([^\[\]\r\n]{1,80})\]\s*(.+)$/u.exec(title);if(!scoped||!scoped[1].trim())fail('模板主题范围或标题不完整。');scope=scoped[1].trim();title=scoped[2].trim();}
if(!title)fail('模板主题缺少发信标题。');
if(mail.inReplyTo || mail.references?.length)fail('回复邮件不作为模板,请新建邮件发送。');
const senders=mail.from?.value||[];const sender=senders[0]?.address?.toLowerCase();
if(senders.length!==1||!(channel.senders||[]).map(x=>x.toLowerCase()).includes(sender))fail('模板发件人不在允许名单中。');
const recipients=[...(mail.to?.value||[]),...(mail.cc?.value||[])].map(x=>x.address?.toLowerCase());if(!recipients.includes(channel.email.toLowerCase()))fail('模板邮件收件人不包含此托管邮箱。');
const subject=title;if(subject.length>300||!subject)fail('发信标题应为 1–300 字。');
if((mail.html||'').length>1024*1024||(mail.text||'').length>200000)fail('模板正文过大。');
const attachments=mail.attachments.map(a=>({filename:(a.filename||'附件').replace(/[\\/\x00-\x1f]/g,'_').slice(0,150),contentType:a.contentType,content:a.content.toString('base64'),cid:a.contentId?.replace(/^<|>$/g,''),size:a.content.length,inline:a.contentDisposition==='inline'}));
const text=mail.text||'',html=cleanHtml(mail.html||'',attachments);if(!text.trim()&&!html.trim())fail('模板正文为空。');validateVariables(subject,text,html);
return {subject,scope,text,html,sender,sourceSubject:mail.subject,messageId:mail.messageId||'',date:mail.date?.toISOString()||'',attachments,notes:[...(html?'': ['纯文本邮件']),...(/(^|\n)\s*(On .+wrote:|发件人[::]|-----Original Message-----|在.+写道[::])/im.test(text)?['正文包含引用内容,请核对后确认。']:[])]};
}
function renderTemplate(template,values){
validateVariables(template.subject,template.text,template.html);
const replace=(input,html)=>String(input||'').replace(/{{\s*(产品线|订单号|日期|订单列表)\s*}}/g,(_,key)=>{if(values[key]===undefined)fail('缺少模板变量:'+key);return html?escape(values[key]).replace(/\r?\n/g,'<br>'):String(values[key]);});
let html=template.html?replace(template.html,true):undefined;
for(const a of template.attachments||[])if(html&&a.cid&&/^[A-Za-z0-9._@+-]{1,200}$/.test(a.cid))html=html.replaceAll('src="data:'+a.contentType+';base64,'+a.content+'"','src="cid:'+a.cid+'"');
return {subject:replace(template.subject,false).replace(/[\r\n]/g,' '),text:replace(template.text,false),html};
}
module.exports={parseTemplate,renderTemplate,cleanHtml,validateVariables,escape,MAX_MAIL};
+29
View File
@@ -0,0 +1,29 @@
'use strict';
const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');const {parseTemplate,renderTemplate,MAX_MAIL}=require('./mail-parser.cjs');
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;}
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 withImap(config,work){const client=this.imapFactory(config);client.on?.('error',()=>{});this.clients.add(client);try{await client.connect();return await work(client);}finally{try{await client.logout();}catch{}client.close?.();this.clients.delete(client);}}
verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);let smtp=false,imap=false,message='SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});try{const epoch=String(client.mailbox.uidValidity),cursor=this.store.cursor(id);const sameEpoch=cursor.epoch===epoch;const last=sameEpoch?(cursor.uid||0):0;const query={since:new Date(sameEpoch&&cursor.since?cursor.since:Date.now()-7*86400000),...(last?{uid:(last+1)+':*'}:{})};const found=await client.search(query,{uid:true});const uids=(found||[]).filter(uid=>uid>last).sort((a,b)=>a-b).slice(0,50);
for(const uid of uids){if(this.stopped)break;this.store.guard(id,c.version);const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info){this.store.skip(id,epoch,uid,'skipped','邮件已移除',c.version);continue;}
if(!/^\[模板\]/.test((info.envelope?.subject||'').trim())){this.store.transaction(()=>{this.store.guard(id,c.version);this.store.advance(id,epoch,uid);});continue;}
if(!Number.isFinite(info.size)||info.size>MAX_MAIL){this.store.skip(id,epoch,uid,'rejected','邮件超过 10 MB 限制',c.version);rejected++;continue;}
const source=await client.fetchOne(uid,{source:true},{uid:true});if(!source){this.store.skip(id,epoch,uid,'skipped','邮件已移除',c.version);continue;}
let parsed;try{parsed=await parseTemplate(source.source,c);}catch(e){this.store.skip(id,epoch,uid,'rejected',e.status===400?e.message:'邮件格式无法解析,请重新发送模板。',c.version);rejected++;continue;}
if(parsed){const result=this.store.ingest(id,epoch,uid,parsed,source.source,c.version);if(result.created)imported++;}else this.store.skip(id,epoch,uid,'skipped','未包含模板指令',c.version);
}
// Persist an empty mailbox epoch too, without skipping future messages.
if(!uids.length&&!sameEpoch)this.store.transaction(()=>{this.store.guard(id,c.version);this.store.advance(id,epoch,0);});
}finally{lock.release();}});
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);}});}
sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id),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'};const rendered=renderTemplate(t,values);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);}});}
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(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()]);}
}
module.exports={MailService};
+66
View File
@@ -0,0 +1,66 @@
'use strict';
const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('./bpm-vault.cjs');const {validateVariables}=require('./mail-parser.cjs');
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
const email=value=>{if(typeof value!=='string'||value.length>254||!/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?\.[A-Za-z]{2,63}$/.test(value.trim()))fail('请输入有效的邮箱地址。');return value.trim().toLowerCase();};
const text=(v,label,max=200)=>{if(typeof v!=='string'||!v.trim()||v.length>max||/[\x00-\x1f]/.test(v))fail(label+'格式不正确。');return v.trim();};
const at=()=>new Date().toISOString();const hash=raw=>crypto.createHash('sha256').update(raw).digest('hex');
class MailStore{
constructor(dir){this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'mail.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS channels(id TEXT PRIMARY KEY,email TEXT NOT NULL UNIQUE,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL,cursor TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS templates(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,source_key TEXT NOT NULL,scope TEXT NOT NULL,status TEXT NOT NULL,version INTEGER NOT NULL,base_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL,UNIQUE(channel_id,source_key));
CREATE UNIQUE INDEX IF NOT EXISTS active_template ON templates(channel_id,scope) WHERE status='active';
CREATE TABLE IF NOT EXISTS receipts(id INTEGER PRIMARY KEY,channel_id TEXT NOT NULL,epoch TEXT NOT NULL,uid INTEGER NOT NULL,status TEXT NOT NULL,detail TEXT NOT NULL,at TEXT NOT NULL,UNIQUE(channel_id,epoch,uid));
CREATE TABLE IF NOT EXISTS sends(id TEXT PRIMARY KEY,channel_id TEXT NOT NULL,template_id TEXT NOT NULL,status TEXT NOT NULL,at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);`);
if(!this.db.prepare('PRAGMA table_info(templates)').all().some(c=>c.name==='summary'))this.db.exec("ALTER TABLE templates ADD COLUMN summary TEXT NOT NULL DEFAULT '{}'");
for(const r of this.db.prepare("SELECT id,payload FROM templates WHERE summary='{}'").all()){const p=this.decode(r.id,r.payload);this.db.prepare('UPDATE templates SET summary=? WHERE id=?').run(this.summary(p),r.id);}
}
summary(p){return JSON.stringify({subject:p.subject,sender:p.sender,attachmentCount:p.attachments.length});}
recoverSends(){this.db.prepare("UPDATE sends SET status='unknown' WHERE status='sending'").run();}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
encode(id,value){try{return this.vault.encode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
decode(id,value){try{return this.vault.decode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
row(id){const row=this.db.prepare('SELECT * FROM channels WHERE id=?').get(id);if(!row)fail('邮箱不存在。',404);return row;}
channelSecret(id){const row=this.row(id);return {...this.decode(id,row.payload),id,version:row.version};}
publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap.password},state};}
channels(){return this.db.prepare('SELECT id FROM channels ORDER BY rowid').all().map(r=>this.publicChannel(r.id));}
saveChannel(input){return this.transaction(()=>{
if(!input||typeof input!=='object')fail('邮箱配置无效。');const old=input.id?this.channelSecret(input.id):null;if(old&&old.version!==input.version)fail('邮箱已被修改,请刷新后重试。',409);
const id=old?.id||crypto.randomUUID(),address=email(input.email);const existing=this.db.prepare('SELECT id FROM channels WHERE email=?').get(address);if(existing&&existing.id!==id)fail('此邮箱已托管,请使用已有邮箱。',409);
if(typeof input.enabled!=='boolean'||!Array.isArray(input.senders)||!input.senders.length||input.senders.length>100)fail('请填写模板发件人名单,并选择是否启用收信。');
const endpoint=kind=>{const v=input[kind];if(!v||!['tls','starttls'].includes(v.security)||!Number.isInteger(v.port)||v.port<1||v.port>65535)fail(kind.toUpperCase()+' 端口或加密方式无效。');const host=text(v.host,'服务器地址',253);if(!/^[a-zA-Z0-9.:-]+$/.test(host)||host.startsWith('-'))fail('服务器地址只填写主机名或 IP。');const password=v.password===''&&old?old[kind].password:v.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 '+kind.toUpperCase()+' 密码或授权码。');const user=text(v.user,'登录账号',254);if(old&&v.password===''&&(old.email!==address||old[kind].user!==user||old[kind].host!==host))fail('更换邮箱、服务器或登录账号时,请重新填写密码。');return {host,port:v.port,security:v.security,user,password};};
const saved={name:text(input.name,'邮箱名称',80),email:address,smtp:endpoint('smtp'),imap:endpoint('imap'),senders:[...new Set(input.senders.map(email))],enabled:input.enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
const reset=!old||old.email!==address||JSON.stringify(old.imap)!==JSON.stringify(saved.imap);const oldrow=old?this.row(id):null;
const changed=reset||JSON.stringify(old?.smtp)!==JSON.stringify(saved.smtp);const state=changed?{checkedAt:null,smtp:false,imap:false,pollAt:null,message:'待检查连接'}:JSON.parse(oldrow.state);
this.db.prepare('INSERT INTO channels VALUES(?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET email=excluded.email,version=excluded.version,payload=excluded.payload,state=excluded.state,cursor=excluded.cursor').run(id,address,(old?.version||0)+1,this.encode(id,saved),JSON.stringify(state),reset?'{}':oldrow.cursor);return this.publicChannel(id);
});}
guard(id,version){if(this.row(id).version!==version)fail('邮箱配置已变化,请重试。',409);}
setState(id,version,patch){this.guard(id,version);this.db.prepare('UPDATE channels SET state=? WHERE id=?').run(JSON.stringify({...JSON.parse(this.row(id).state),...patch}),id);}
cursor(id){return JSON.parse(this.row(id).cursor);}
advance(id,epoch,uid){const prior=this.cursor(id);this.db.prepare('UPDATE channels SET cursor=? WHERE id=?').run(JSON.stringify({epoch:String(epoch),uid,since:prior.epoch===String(epoch)&&prior.since?prior.since:new Date(Date.now()-7*86400000).toISOString()}),id);}
receipt(id,epoch,uid,status,detail){this.db.prepare('INSERT OR IGNORE INTO receipts(channel_id,epoch,uid,status,detail,at) VALUES(?,?,?,?,?,?)').run(id,String(epoch),uid,status,detail,at());this.db.prepare('DELETE FROM receipts WHERE channel_id=? AND id NOT IN (SELECT id FROM receipts WHERE channel_id=? ORDER BY id DESC LIMIT 500)').run(id,id);}
skip(id,epoch,uid,status,detail,version){return this.transaction(()=>{this.guard(id,version);this.receipt(id,epoch,uid,status,detail);this.advance(id,epoch,uid);});}
receipts(){return this.db.prepare('SELECT * FROM receipts ORDER BY id DESC LIMIT 100').all();}
ingest(channelId,epoch,uid,parsed,raw,configVersion){return this.transaction(()=>{
this.guard(channelId,configVersion);const key=parsed.messageId?hash(parsed.messageId+'\0'+hash(raw)):hash(raw);const old=this.db.prepare('SELECT id FROM templates WHERE channel_id=? AND source_key=?').get(channelId,key);
let id=old?.id;if(!id){id=crypto.randomUUID();const payload={...parsed,raw:raw.toString('base64')};const base=this.activeId(channelId,parsed.scope);this.db.prepare('INSERT INTO templates VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,channelId,key,parsed.scope,'pending',1,base,this.encode(id,payload),at(),this.summary(parsed));}
this.receipt(channelId,epoch,uid,old?'duplicate':'pending',old?'已识别,未重复导入':'待确认模板');this.advance(channelId,epoch,uid);return {...this.template(id),created:!old};
});}
template(id){const r=this.db.prepare('SELECT * FROM templates WHERE id=?').get(id);if(!r)fail('模板不存在。',404);return {...this.decode(id,r.payload),id:r.id,channelId:r.channel_id,scope:r.scope,status:r.status,version:r.version,baseId:r.base_id,createdAt:r.created_at};}
templates(){return ['pending','active','archived','rejected'].flatMap(status=>this.db.prepare('SELECT id,channel_id,scope,status,version,created_at,summary FROM templates WHERE status=? ORDER BY created_at DESC,rowid DESC LIMIT 200').all(status).map(r=>({...JSON.parse(r.summary),id:r.id,channelId:r.channel_id,scope:r.scope,status:r.status,version:r.version,createdAt:r.created_at})));}
stats(){return Object.fromEntries(this.db.prepare('SELECT status,COUNT(*) AS count FROM templates GROUP BY status').all().map(r=>[r.status,r.count]));}
activeId(channelId,scope){return this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND status='active'").get(channelId,scope)?.id||null;}
active(channelId,scope){const r=this.db.prepare("SELECT id FROM templates WHERE channel_id=? AND scope=? AND status='active'").get(channelId,scope);return r?this.template(r.id):null;}
confirm(id,input,actor){return this.transaction(()=>{const t=this.template(id);if(t.status!=='pending'||input.version!==t.version)fail('模板状态已变化,请刷新。',409);if(t.channelId==='legacy'){this.row(input.channelId);t.channelId=input.channelId;}const subject=text(input.subject,'邮件标题',300);if(typeof input.scope!=='string'||input.scope.length>80||/[\[\]\x00-\x1f]/.test(input.scope))fail('产品线格式无效。');const scope=input.scope.trim(),current=this.activeId(t.channelId,scope);if(current!==(scope===t.scope?t.baseId:null))fail('该范围已有更新的模板,请重新导入后确认。',409);
if(typeof input.useText!=='boolean')fail('正文模式无效。');if(input.useText){if(typeof input.text!=='string'||!input.text.trim()||input.text.length>200000)fail('正文应为 1–200000 字。');t.text=input.text;t.html='';}
validateVariables(subject,t.text,t.html);const payload={...t,subject,scope,confirmedBy:actor,confirmedAt:at()};delete payload.id;this.db.prepare("UPDATE templates SET status='archived',version=version+1 WHERE channel_id=? AND scope=? AND status='active'").run(t.channelId,scope);this.db.prepare("UPDATE templates SET channel_id=?,scope=?,status='active',version=version+1,payload=?,summary=? WHERE id=?").run(t.channelId,scope,this.encode(id,payload),this.summary(payload),id);return this.template(id);
});}
reject(id,version){const t=this.template(id);if(t.status!=='pending'||t.version!==version)fail('模板状态已变化。',409);this.db.prepare("UPDATE templates SET status='rejected',version=version+1 WHERE id=?").run(id);}
source(id){return Buffer.from(this.template(id).raw||'','base64');}
migrateLegacy(legacy){if(this.db.prepare("SELECT 1 FROM meta WHERE key='legacy'").get())return;this.transaction(()=>{if(legacy?.subject?.trim()&&legacy?.body?.trim()){const id=crypto.randomUUID(),payload={subject:legacy.subject,text:legacy.body,html:'',sender:'工作台旧草稿',sourceSubject:legacy.subject,attachments:[],notes:['从原模板草稿迁入,请选择托管邮箱后确认。']};this.db.prepare('INSERT INTO templates VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,'legacy','legacy','','pending',1,null,this.encode(id,payload),at(),this.summary(payload));}this.db.prepare("INSERT INTO meta VALUES('legacy','1')").run();});}
beginSend(channelId,templateId){const id=crypto.randomUUID();this.db.prepare('INSERT INTO sends VALUES(?,?,?,?,?)').run(id,channelId,templateId,'sending',at());return id;}
finishSend(id,status){this.db.prepare('UPDATE sends SET status=? WHERE id=?').run(status,id);}
sends(){return this.db.prepare('SELECT * FROM sends ORDER BY at DESC LIMIT 50').all();}
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
}
module.exports={MailStore,email};
+24
View File
@@ -0,0 +1,24 @@
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
function loadPlaywright() {
const candidates = [
'playwright-core',
process.env.ORDER_PLAYWRIGHT_MODULE,
path.join(os.homedir(), '.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright-core')
].filter(Boolean);
for (const candidate of candidates) {
try { return require(candidate); } catch (error) { if (error.code !== 'MODULE_NOT_FOUND') throw error; }
}
throw new Error('缺少 playwright-core,请先运行 npm install。');
}
function browserOptions() {
const candidates = [process.env.ORDER_CHROME_PATH,
process.env.PROGRAMFILES && path.join(process.env.PROGRAMFILES, 'Google/Chrome/Application/chrome.exe'),
process.env['PROGRAMFILES(X86)'] && path.join(process.env['PROGRAMFILES(X86)'], 'Google/Chrome/Application/chrome.exe'),
process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Google/Chrome/Application/chrome.exe')].filter(Boolean);
const executablePath = candidates.find(candidate => fs.existsSync(candidate));
return executablePath ? { executablePath, headless: true } : { channel: 'chrome', headless: true };
}
module.exports = { loadPlaywright, browserOptions };
+25
View File
@@ -0,0 +1,25 @@
// Plan calculation only. A mail connector must exist before execution is enabled.
function dayPolicy(date,schedule,overrides=[]) {
const key=typeof date==='string'?date:new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date);
const override=overrides.find(item=>item.date===key);
if(override)return {scan:override.kind==='pause'?false:override.scan,send:override.kind==='pause'?false:override.send,kind:override.kind,note:override.note || ''};
const working=schedule.weekends || ![0,6].includes(new Date(key+'T00:00:00Z').getUTCDay());
return {scan:working,send:working,kind:working?'workday':'restday',note:''};
}
function nextSlots(schedule, from=new Date(), count=2, overrides=[]) {
const shifted=new Date(from.getTime()+8*3600000);
const midnight=Date.UTC(shifted.getUTCFullYear(),shifted.getUTCMonth(),shifted.getUTCDate());
const slots=[];
for(let day=0;day<370 && slots.length<count;day++) {
const date=new Date(midnight+day*86400000);
if(!dayPolicy(date.toISOString().slice(0,10),schedule,overrides).send)continue;
for(const time of [...schedule.times].sort()) {
const [hour,minute]=time.split(':').map(Number);
const utc=date.getTime()+hour*3600000+minute*60000-8*3600000;
if(utc>from.getTime())slots.push(new Date(utc).toISOString());
if(slots.length>=count)break;
}
}
return slots;
}
module.exports={nextSlots,dayPolicy};
+140
View File
@@ -0,0 +1,140 @@
const http = require('node:http');
const crypto = require('node:crypto');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { renderSnapshot, validateSnapshot } = require('./exporter.cjs');
const { Store } = require('./dashboard-store.cjs');
const { createDashboard } = require('./dashboard.cjs');
const { WorkspaceStore } = require('./workspace-store.cjs');
const { BpmSessionManager } = require('./bpm-session-manager.cjs');
const { BpmCustodian } = require('./bpm-custodian.cjs');
const { MailStore } = require('./mail-store.cjs');
const { MailService } = require('./mail-service.cjs');
const { BpmScanStore } = require('./bpm-scan-store.cjs');
const { BpmScanner } = require('./bpm-scanner.cjs');
function createServer(options) {
let busy = false;
const jobs = new Map();
const maxBytes = options.maxBodyBytes || 20 * 1024 * 1024;
return http.createServer(async (request, response) => {
const reply = (status, body) => { response.writeHead(status, { 'Content-Type':'application/json; charset=utf-8', 'Cache-Control':'no-store' }); response.end(JSON.stringify(body)); };
const origin = request.headers.origin || '';
if (!/^chrome-extension:\/\/[a-p]{32}$/.test(origin)) return reply(403, {error:'仅接受已配对的浏览器扩展。'});
response.setHeader('Access-Control-Allow-Origin', origin);
response.setHeader('Vary', 'Origin');
if (request.method === 'OPTIONS') {
response.setHeader('Access-Control-Allow-Methods','GET, POST, OPTIONS');
response.setHeader('Access-Control-Allow-Headers','Content-Type, X-Order-Token');
response.setHeader('Access-Control-Allow-Private-Network','true');
response.writeHead(204); response.end(); return;
}
const supplied = Buffer.from(String(request.headers['x-order-token'] || ''));
const expected = Buffer.from(options.token);
if (supplied.length !== expected.length || !crypto.timingSafeEqual(supplied, expected)) return reply(401, {error:'配对失效,请重新加载扩展。'});
if (request.method === 'GET' && request.url === '/health') return reply(200, {ok:true,version:'0.1.0',busy});
const jobRoute = /^\/jobs\/([a-f0-9]{32})$/.exec(request.url);
if (request.method === 'GET' && jobRoute) return jobs.has(jobRoute[1]) ? reply(200,jobs.get(jobRoute[1])) : reply(404,{error:'任务已过期,请检查输出目录后重试。'});
if (request.method !== 'POST' || request.url !== '/export') return reply(404, {error:'未知操作。'});
if (!/^application\/json(?:;|$)/i.test(request.headers['content-type'] || '')) return reply(415, {error:'需要 JSON 数据。'});
if (Number(request.headers['content-length'] || 0) > maxBytes) { request.resume(); return reply(413, {error:'页面超过 20 MB 限制。'}); }
if (busy) return reply(409, {error:'正在导出其他订单,请稍后重试。'});
try {
const raw = await new Promise((resolve, reject) => {
const chunks = []; let total = 0; let overflow = false;
request.on('data', chunk => { total += chunk.length; if (total > maxBytes) { if (!overflow) { overflow=true; reject(Object.assign(new Error('页面过大。'),{status:413})); } } else if (!overflow) chunks.push(chunk); });
request.on('end', () => { if (!overflow) resolve(Buffer.concat(chunks).toString('utf8')); });
request.on('error', reject);
});
let snapshot;
try { snapshot = JSON.parse(raw); validateSnapshot(snapshot); } catch(error) { return reply(400, {error:error instanceof SyntaxError ? '页面数据不是有效 JSON。' : error.message}); }
if (busy) return reply(409,{error:'正在导出其他订单,请稍后重试。'});
busy = true;
const jobId = crypto.randomBytes(16).toString('hex');
if (jobs.size >= 20) jobs.delete(jobs.keys().next().value);
jobs.set(jobId,{status:'running',jobId});
try { options.store?.recordJob({jobId,status:'running',metadata:snapshot.metadata}); }
catch(error) {busy=false;jobs.delete(jobId);throw error;}
reply(202,{status:'running',jobId});
renderSnapshot(snapshot, options).then(result => {
options.store?.recordJob({status:'success',jobId,...result});
jobs.set(jobId,{status:'success',jobId,...result});
console.log(`已保存:${result.filename} (${result.bytes} bytes)`);
}).catch(error=>{const failed={status:'error',jobId,error:error.message || '导出失败。'};jobs.set(jobId,failed);try{options.store?.recordJob(failed);}catch(storeError){console.error('保存任务状态失败:'+storeError.message);}}).finally(()=>{busy=false;});
} catch(error) { if (!response.writableEnded) reply(error.status || 500,{error:error.message || '导出失败。'}); }
});
}
async function startService(options) {
// Complete file preparation before opening a socket: failed startup must exit cleanly.
await fs.mkdir(options.installedExtension,{recursive:true});
await fs.cp(options.extensionSourceDir,options.installedExtension,{recursive:true,filter:source => path.basename(source) !== 'local-config.js'});
await fs.writeFile(path.join(options.installedExtension,'local-config.js'),'globalThis.ORDER_LOCAL_CONFIG = '+JSON.stringify({endpoint:`http://127.0.0.1:${options.port}`,token:options.token})+';\n');
const server = createServer(options);
await new Promise((resolve,reject) => { server.once('error',reject); server.listen(options.port,'127.0.0.1',resolve); });
return server;
}
async function main(options = {}) {
const root = path.resolve(__dirname,'..');
let config = options.config;
if(!config){
config={};
try { config = JSON.parse(await fs.readFile(path.join(root,'config.json'),'utf8')); } catch(error) { if(error.code !== 'ENOENT') throw error; }
}
const port = config.port || 18765;
if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error('端口需为 1024–65535。');
const stateDir = options.stateDir || path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation');
await fs.mkdir(stateDir,{recursive:true});
const tokenPath = path.join(stateDir,'pairing.key');
let token;
try { token = (await fs.readFile(tokenPath,'utf8')).trim(); } catch(error) { if(error.code !== 'ENOENT') throw error; token=crypto.randomBytes(32).toString('hex'); await fs.writeFile(tokenPath,token,{mode:0o600}); }
if (!/^[a-f0-9]{64}$/.test(token)) throw new Error('本地配对文件损坏,请删除 pairing.key 后重启。');
const outputDir = path.resolve(root,config.outputDir || 'output/pdf');
const installedExtension = path.join(stateDir,'extension');
const dashboardConfig=config.dashboard || {};
const dashboardPort=dashboardConfig.port ?? 18766;
const dashboardHost=dashboardConfig.host || '0.0.0.0';
if(!Number.isInteger(dashboardPort) || dashboardPort<1024 || dashboardPort>65535 || dashboardPort===port)throw new Error('Web 看板端口需为 1024–65535,且不能与扩展服务相同。');
if(!['0.0.0.0','127.0.0.1'].includes(dashboardHost))throw new Error('Web 看板 host 请设置为 0.0.0.0(局域网)或 127.0.0.1(仅本机)。');
if(dashboardConfig.trustedProxy!==undefined && typeof dashboardConfig.trustedProxy!=='boolean')throw new Error('dashboard.trustedProxy 必须为布尔值。');
const store=new Store(path.join(stateDir,'dashboard'));
const workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
const bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions')});
const custodian=new BpmCustodian({workspace,manager:bpmSessions});
let server;
let dashboard;
let mailStore,mail,scanStore,scanner;
try {
mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore});
mailStore.migrateLegacy(store.settings().templates);
scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()});
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
workspace.markSessionChecksPending();
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,trustedProxy:dashboardConfig.trustedProxy===true});
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();
}
catch(error){if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
if(!options.quiet){
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
console.log(`Web 看板:http://127.0.0.1:${dashboardPort}\n${store.users().length?'使用已创建的工作台账号登录。':'首次请在部署机创建管理员。'}`);
if(dashboardHost==='0.0.0.0')for(const list of Object.values(os.networkInterfaces()))for(const address of list || [])if(address.family==='IPv4' && !address.internal)console.log(`局域网地址:http://${address.address}:${dashboardPort}`);
}
let stopping;
const stop=()=>stopping ||= (async()=>{
await scanner.stop();await mail.stop();await custodian.stop();await bpmSessions.shutdown();
await Promise.all([dashboard,server].map(socket=>new Promise((resolve,reject)=>socket.close(error=>error?reject(error):resolve()))));
workspace.close();
mailStore.close();
scanStore.close();
})();
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,stop};
}
if (require.main === module) main().then(app=>{
const stop=()=>app.stop().then(()=>process.exit(0),()=>process.exit(1));
process.once('SIGINT',stop);process.once('SIGTERM',stop);
}).catch(error => { console.error('启动失败:'+error.message); process.exitCode=1; });
module.exports = { createServer, startService, main };
+15
View File
@@ -0,0 +1,15 @@
// This router is called only after dashboard authentication and same-origin validation.
function workspaceApi({workspace,store,user,route,method,body,reply,bpmSessions}){
if(!workspace)return false;
const members=()=>store.users();
if(route==='/api/workspace' && method==='GET'){const snapshot=workspace.snapshot(members());snapshot.capabilities.remoteLogin=Boolean(bpmSessions);reply(200,snapshot);return true;}
if(method!=='POST')return false;
if(route==='/api/calendar'){reply(200,workspace.saveCalendar(body,user));return true;}
if(route==='/api/exceptions'){reply(201,workspace.createException(body,user,members()));return true;}
const action=/^\/api\/exceptions\/([\w-]+)\/action$/.exec(route);if(action){reply(200,workspace.actOnException(action[1],body,user,members()));return true;}
if(route==='/api/connections'){reply(201,workspace.createConnection(body,user,members()));return true;}
const disable=/^\/api\/connections\/([\w-]+)\/disable$/.exec(route);if(disable){if(Object.keys(body).length)throw Object.assign(new Error('停用连接不接受额外数据。'),{status:400});reply(200,workspace.disableConnection(disable[1],user));return true;}
if(route==='/api/supervisor'){reply(200,workspace.saveSupervisor(body,user,members()));return true;}
return false;
}
module.exports={workspaceApi};
+130
View File
@@ -0,0 +1,130 @@
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
const object=(input,keys)=>{if(!input || Array.isArray(input) || typeof input!=='object' || Object.keys(input).some(key=>!keys.includes(key)))fail('数据格式不正确或包含不支持的字段。');};
const text=(value,label,max,required=false)=>{if(typeof value!=='string' || value.length>max || (required && !value.trim()))fail(`${label}格式不正确。`);return value.trim();};
const version=value=>{if(!Number.isSafeInteger(value) || value<1)fail('版本号不正确。');};
const authorize=(actor,roles)=>{if(!actor || typeof actor.username!=='string' || !roles.includes(actor.role))fail('当前账号没有执行此操作的权限。',403);};
const owner=(value,members,required=false)=>{const name=text(value,'负责人',40,required);if(name && !members?.some(user=>user.username===name && ['admin','operator'].includes(user.role)))fail('请选择有效的管理员或操作员作为负责人。');return name;};
const validDate=date=>typeof date==='string' && /^\d{4}-\d{2}-\d{2}$/.test(date) && date>='0001-01-01' && date<='9999-12-31' && !Number.isNaN(Date.parse(date+'T00:00:00Z')) && new Date(date+'T00:00:00Z').toISOString().slice(0,10)===date;
class WorkspaceStore {
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'workspace.sqlite'));
this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS exceptions(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS connections(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS audit(seq INTEGER PRIMARY KEY AUTOINCREMENT,value TEXT NOT NULL);`);
const insert=this.db.prepare('INSERT OR IGNORE INTO metadata(key,value) VALUES(?,?)');
insert.run('calendar',JSON.stringify({version:1,overrides:[]}));insert.run('supervisor',JSON.stringify({version:1,defaultOwner:'',notifyChannel:'none',maxAttempts:0}));
this.transaction(()=>{for(const row of this.db.prepare('SELECT id,value FROM connections').all()){
const item=JSON.parse(row.value);if(!('detailUrl' in item) && !item.checks?.detail && item.status!=='partial')continue;
delete item.detailUrl;if(item.checks)delete item.checks.detail;if(item.status==='partial')item.status='unchecked';
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);
}});
}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(error){this.db.exec('ROLLBACK');throw error;}}
meta(key){return JSON.parse(this.db.prepare('SELECT value FROM metadata WHERE key=?').get(key).value);}
setMeta(key,value){this.db.prepare('UPDATE metadata SET value=? WHERE key=?').run(JSON.stringify(value),key);}
record(actor,action,detail){this.db.prepare('INSERT INTO audit(value) VALUES(?)').run(JSON.stringify({id:crypto.randomUUID(),at:new Date().toISOString(),actor:actor.username,action,detail}));this.db.exec('DELETE FROM audit WHERE seq <= (SELECT COALESCE(MAX(seq),0)-2000 FROM audit)');}
snapshot(members=[]){
return this.transaction(()=>{
const calendar=this.meta('calendar'),supervisor=this.meta('supervisor');
const exceptions=this.db.prepare('SELECT value FROM exceptions ORDER BY rowid DESC').all().map(row=>JSON.parse(row.value));
const connections=this.db.prepare('SELECT value FROM connections ORDER BY rowid DESC').all().map(row=>JSON.parse(row.value));
const audit=this.db.prepare('SELECT value FROM audit ORDER BY seq DESC LIMIT 2000').all().map(row=>JSON.parse(row.value));
return {calendar,exceptions,connections,supervisor,audit,members:members.map(({username,role})=>({username,role})),capabilities:{remoteLogin:false,zcode:false,automaticProcessing:false},stats:{open:exceptions.filter(e=>e.status==='open').length,inProgress:exceptions.filter(e=>e.status==='in_progress').length,verifying:exceptions.filter(e=>e.status==='verifying').length,resolved:exceptions.filter(e=>e.status==='resolved').length,connections:connections.filter(c=>c.status!=='disabled').length,overrides:calendar.overrides.length}};
});
}
saveCalendar(input,actor){
authorize(actor,['admin']);object(input,['version','overrides']);version(input.version);
if(!Array.isArray(input.overrides) || input.overrides.length>1500)fail('日期覆盖格式不正确,最多保存 1500 天。');
const dates=new Set();const overrides=input.overrides.map(item=>{object(item,['date','kind','scan','send','note']);if(!validDate(item.date) || dates.has(item.date))fail('日期不存在或重复。');dates.add(item.date);if(!['workday','restday','pause'].includes(item.kind) || typeof item.scan!=='boolean' || typeof item.send!=='boolean')fail('日历选项不正确。');if(item.kind==='pause' && (item.scan || item.send))fail('暂停日期必须同时停止采集和发送。');return {date:item.date,kind:item.kind,scan:item.scan,send:item.send,note:text(item.note,'备注',1000)};}).sort((a,b)=>a.date.localeCompare(b.date));
return this.transaction(()=>{const previous=this.meta('calendar');if(previous.version!==input.version)fail('日历已被其他人更新,请刷新后重试。',409);const saved={version:previous.version+1,overrides};this.setMeta('calendar',saved);this.record(actor,'保存业务日历',`${overrides.length} 个日期覆盖`);return saved;});
}
createException(input,actor,members){
authorize(actor,['admin','operator']);object(input,['title','component','priority','description','owner']);
const title=text(input.title,'标题',200,true),description=text(input.description,'说明',10000),assigned=owner(input.owner,members);
if(!['bpm','pdf','archive','mail','system','rules'].includes(input.component) || !['normal','high','critical'].includes(input.priority))fail('异常组件或优先级不正确。');
return this.transaction(()=>{const at=new Date().toISOString();const item={id:crypto.randomUUID(),title,description,component:input.component,priority:input.priority,owner:assigned,status:assigned?'in_progress':'open',version:1,createdAt:at,updatedAt:at,history:[{at,actor:actor.username,action:'create',note:description,toOwner:assigned}]};this.db.prepare('INSERT INTO exceptions(id,value) VALUES(?,?)').run(item.id,JSON.stringify(item));this.record(actor,'建立异常',title);return item;});
}
actOnException(id,input,actor,members){
authorize(actor,['admin','operator']);object(input,['version','action','owner','note']);version(input.version);
if(!['claim','transfer','verify','resolve','reopen'].includes(input.action))fail('异常操作不正确。');
const note=input.note===undefined?'':text(input.note,'处理记录',5000);
if(['transfer','resolve','reopen'].includes(input.action) && !note)fail('请填写交接原因或人工核验依据。');
const assigned=input.action==='transfer'?owner(input.owner,members,true):undefined;
if(input.action!=='transfer' && input.owner!==undefined)fail('此操作不接受指定负责人。');
return this.transaction(()=>{
const row=this.db.prepare('SELECT value FROM exceptions WHERE id=?').get(id);if(!row)fail('没有找到此异常。',404);const item=JSON.parse(row.value);
if(item.version!==input.version)fail('异常已被其他人更新,请刷新后重试。',409);
if(input.action==='claim'){
if(item.status!=='open' || item.owner)fail('此异常已被认领或不允许认领。',409);
owner(actor.username,members,true);item.owner=actor.username;item.status='in_progress';
}else {
if(actor.role!=='admin' && item.owner!==actor.username)fail('只有负责人或管理员可以处理此异常。',403);
if(input.action==='transfer'){
if(!['open','in_progress','verifying'].includes(item.status))fail('已关闭异常需先重新打开。',409);
if(assigned===item.owner)fail('新负责人必须与当前负责人不同。');
}else if(input.action==='verify'){
if(item.status!=='in_progress')fail('只有处理中的异常可以提交验证。',409);item.status='verifying';
}else if(input.action==='resolve'){
if(item.status!=='verifying')fail('异常需要先提交验证,再记录人工核验依据关闭。',409);item.status='resolved';
}else if(input.action==='reopen'){
if(item.status!=='resolved')fail('只有已关闭异常可以重新打开。',409);item.status='open';
}
}
const at=new Date().toISOString();const history={at,actor:actor.username,action:input.action,note};
if(input.action==='transfer'){history.fromOwner=item.owner;history.toOwner=assigned;item.owner=assigned;item.status='in_progress';}
if(input.action==='reopen'){history.fromOwner=item.owner;history.toOwner='';item.owner='';}
item.updatedAt=at;item.version++;item.history.push(history);this.db.prepare('UPDATE exceptions SET value=? WHERE id=?').run(JSON.stringify(item),id);this.record(actor,({claim:'认领异常',transfer:'转交异常',verify:'提交异常验证',resolve:'人工核验关闭异常',reopen:'重新打开异常'})[input.action],item.title+(note?':'+note:''));return item;
});
}
createConnection(input,actor,members){
authorize(actor,['admin']);object(input,['name','owner']);const name=text(input.name,'连接名称',100,true),assigned=owner(input.owner,members,true);
return this.transaction(()=>{const at=new Date().toISOString();const item={id:crypto.randomUUID(),name,owner:assigned,status:'disconnected',mainUrl:'https://bpmn.skyworthdigital.com',createdAt:at,updatedAt:at};this.db.prepare('INSERT INTO connections(id,value) VALUES(?,?)').run(item.id,JSON.stringify(item));this.record(actor,'创建连接',name);return item;});
}
getConnection(id){const row=this.db.prepare('SELECT value FROM connections WHERE id=?').get(id);if(!row)fail('没有找到此连接。',404);return JSON.parse(row.value);}
resetConnectionSession(id,actor){
authorize(actor,['admin','operator']);return this.transaction(()=>{
const item=this.getConnection(id);if(actor.role!=='admin' && item.owner!==actor.username)fail('仅连接负责人或管理员可以操作此连接。',403);if(item.status==='disabled')fail('此连接已停用。',409);
item.status='disconnected';for(const key of ['identity','checks','checkedAt','lastConnectedAt','savedAt'])delete item[key];item.updatedAt=new Date().toISOString();
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);return item;
});
}
markSessionChecksPending(){
return this.transaction(()=>{let count=0;for(const row of this.db.prepare('SELECT id,value FROM connections').all()){const item=JSON.parse(row.value);if(item.status!=='connected')continue;item.status='unchecked';this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);count++;}return count;});
}
updateConnectionSession(id,result,actor){
authorize(actor,['admin','operator']);object(result,['status','identity','checkedAt','checks']);
if(!['connected','login_required','error'].includes(result.status))fail('连接检查状态不正确。');
const identity=text(result.identity,'BPM 账号',200);
if(typeof result.checkedAt!=='string' || !/^\d{4}-\d{2}-\d{2}T/.test(result.checkedAt) || !Number.isFinite(Date.parse(result.checkedAt)))fail('连接检查时间不正确。');
object(result.checks,['portal']);const checks={};
const check=result.checks.portal;object(check,['ok','message']);if(typeof check.ok!=='boolean')fail('连接检查结果不正确。');checks.portal={ok:check.ok,message:text(check.message,'检查说明',500)};
if((result.status==='connected')!==checks.portal.ok)fail('连接检查结果不完整。');
return this.transaction(()=>{
const item=this.getConnection(id);if(actor.role!=='admin' && item.owner!==actor.username)fail('仅连接负责人或管理员可以操作此连接。',403);if(item.status==='disabled')fail('此连接已停用。',409);
const at=new Date().toISOString();Object.assign(item,{status:result.status,identity,checkedAt:result.checkedAt,checks,updatedAt:at});if(item.status==='connected')item.lastConnectedAt=result.checkedAt;
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);
if(['error','login_required'].includes(item.status) && item.lastConnectedAt){
const existing=this.db.prepare('SELECT value FROM exceptions').all().map(row=>JSON.parse(row.value)).some(entry=>entry.connectionId===id && entry.kind==='bpm_login' && entry.status!=='resolved');
if(!existing){const unavailable=item.status==='error',title=unavailable?'BPM 连接需要检查:'+item.name:item.name+' 需要登录验证',description=unavailable?'新版 BPM 暂时无法连接,请检查网络和连接状态。':'BPM 自动续登未完成,请连接负责人检查托管账号或完成登录验证。';const task={id:crypto.randomUUID(),title,description,component:'bpm',priority:'high',owner:item.owner,status:'in_progress',version:1,kind:'bpm_login',connectionId:id,createdAt:at,updatedAt:at,history:[{at,actor:actor.username,action:'create',note:unavailable?'连接检查未通过':'连接检查需要登录验证'}]};this.db.prepare('INSERT INTO exceptions(id,value) VALUES(?,?)').run(task.id,JSON.stringify(task));this.record(actor,unavailable?'创建 BPM 连接检查待办':'创建 BPM 续登待办',item.name);}
}
this.record(actor,'检查 BPM 连接',item.name+':'+item.status);return item;
});
}
disableConnection(id,actor){
authorize(actor,['admin']);return this.transaction(()=>{const item=this.getConnection(id);if(item.status==='disabled')return item;item.status='disabled';for(const key of ['identity','checks','checkedAt','lastConnectedAt','savedAt'])delete item[key];item.updatedAt=new Date().toISOString();this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);this.record(actor,'停用连接',item.name);return item;});
}
deleteConnection(id,actor){
authorize(actor,['admin']);return this.transaction(()=>{const item=this.getConnection(id);if(item.status!=='disabled')fail('请先停用连接再删除。',409);this.db.prepare('DELETE FROM connections WHERE id=?').run(id);this.record(actor,'删除连接',item.name);return {id,deleted:true};});
}
saveSupervisor(input,actor,members){
authorize(actor,['admin']);object(input,['version','defaultOwner','notifyChannel','maxAttempts']);version(input.version);const defaultOwner=owner(input.defaultOwner,members);
if(!['none','manual'].includes(input.notifyChannel) || !Number.isInteger(input.maxAttempts) || input.maxAttempts<0 || input.maxAttempts>3)fail('监管草稿渠道或尝试次数不正确。');
return this.transaction(()=>{const previous=this.meta('supervisor');if(previous.version!==input.version)fail('监管草稿已被其他人更新,请刷新后重试。',409);const saved={version:previous.version+1,defaultOwner,notifyChannel:input.notifyChannel,maxAttempts:input.maxAttempts};this.setMeta('supervisor',saved);this.record(actor,'保存监管策略草稿','仅保存草稿,不执行自动处理或通知');return saved;});
}
close(){if(this.db){this.db.close();this.db=null;}}
}
module.exports={WorkspaceStore};
+21
View File
@@ -0,0 +1,21 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const vm = require('node:vm');
test('asset collection keeps source CSS order even when network completion order differs', async () => {
const worker = await fs.readFile(require.resolve('../extension/worker.js'),'utf8');
const responses = {
'https://bpm.skyworthdigital.com/first.css': {delay:30,text:'body{color:red}'},
'https://bpm.skyworthdigital.com/second.css': {delay:0,text:'body{color:blue}'}
};
const context = vm.createContext({
importScripts:()=>{}, ORDER_LOCAL_CONFIG:{},
chrome:{runtime:{onMessage:{addListener:()=>{}}}},
URL, AbortSignal, TextDecoder, Uint8Array,
fetch:async url=>{const response=responses[url];await new Promise(resolve=>setTimeout(resolve,response.delay));return {ok:true,headers:{get:()=> 'text/css; charset=utf-8'},arrayBuffer:async()=>new TextEncoder().encode(response.text).buffer};}
});
vm.runInContext(worker,context);
const actual = await context.collectAssets({styles:['body{color:green}'],stylesheetUrls:Object.keys(responses),imageUrls:[],warnings:[]});
assert.deepEqual(Array.from(actual.styles),['body{color:red}','body{color:blue}','body{color:green}']);
});
+183
View File
@@ -0,0 +1,183 @@
'use strict';
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs/promises');
const os=require('node:os');
const path=require('node:path');
const http=require('node:http');
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
const principal={user:{username:'owner',role:'operator'},sessionId:'session-one'};
const connection={id:'account-test',owner:'owner',status:'disconnected'};
const credentials={username:'Fixture User',password:' Fixture-password-123 '};
const empty={configured:false,username:'',updatedAt:null};
test('account availability enforces scope and duplicate saves preserve old credentials and cookies',async t=>{
const {manager}=await fixture(t);const other={...connection,id:'other'};
await manager.saveAccount(connection,principal,credentials);
await manager.saveAccount(other,principal,{username:'different',password:'original-password'});
await manager.vault().write(other.id,{storageState:{cookies:[{name:'keep',value:'unchanged'}],origins:[]}});
assert.deepEqual(await manager.checkAccount(other,principal,{username:' fixture USER '}),{available:false});
await assert.rejects(manager.saveAccount(other,principal,{username:'fixture user',password:'replacement'}),e=>e.status===409&&e.code==='BPM_ACCOUNT_DUPLICATE');
assert.equal((await manager.account(other,principal)).username,'different');assert.ok(await manager.vault().read(other.id));
for(const user of [{username:'unrelated',role:'operator'},{username:'owner',role:'viewer'}])await assert.rejects(manager.checkAccount(other,{...principal,user},{username:'anything'}),e=>e.status===403);
for(const body of [null,{},[],{username:' '},{username:'x',password:'secret'}])await assert.rejects(manager.checkAccount(other,principal,body),e=>e.status===400);
});
async function fixture(t,{browser=false,known=true}={}){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-account-'));
const server=http.createServer((req,res)=>{
const type=req.url==='/malicious'?'text':'password';
const hidden=req.url==='/hidden'?'style="display:none"':'';
res.setHeader('content-type','text/html');
res.end(`<form onsubmit="event.preventDefault();window.submitted++"><input id="username" type="text"><input id="password" type="${type}" ${hidden}><button type="submit">Login</button><input id="captcha"></form><script>window.submitted=0</script>`);
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const origin='http://127.0.0.1:'+server.address().port;
const options={stateDir:dir,urls:{main:origin+'/login'},allowedOrigins:[origin],...(known?{loginForms:{[origin]:{username:'#username',password:'#password'}}}:{})};
if(browser)options.browserFactory=async()=>loadPlaywright().chromium.launch(browserOptions());
else options.browserFactory=async()=>{throw new Error('browser must not launch for account CRUD');};
const manager=new BpmSessionManager(options);
const managers=[manager],make=()=>{const next=new BpmSessionManager(options);managers.push(next);return next;};
t.after(async()=>{for(const item of managers)await item.shutdown();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));await fs.rm(dir,{recursive:true,force:true});});
return {manager,dir,options,origin,make};
}
test('account saves encrypted credentials without browser, returns safe metadata and survives restart',async t=>{
const {manager,dir,make}=await fixture(t);
assert.deepEqual(await manager.account(connection,principal),empty);
const saved=await manager.saveAccount(connection,principal,credentials);
assert.equal(saved.configured,true);assert.equal(saved.username,'Fixture User');assert.ok(Date.parse(saved.updatedAt));
assert.deepEqual(Object.keys(saved).sort(),['configured','updatedAt','username']);
assert.equal((await manager.vault().read('account:account-test')).password,credentials.password);
assert.equal(await manager.vault().read(connection.id),null);
for(const filename of await fs.readdir(dir))if(filename.endsWith('.enc')){
const bytes=await fs.readFile(path.join(dir,filename));
assert.equal(bytes.includes(Buffer.from(credentials.username)),false);assert.equal(bytes.includes(Buffer.from(credentials.password)),false);
}
await manager.shutdown();const restarted=make();
assert.deepEqual(await restarted.account(connection,principal),saved);
assert.deepEqual(await restarted.clearAccount(connection,principal),empty);
assert.equal(await restarted.vault().read('account:account-test'),null);
});
test('account enforces owner and admin, strict payload bounds and disabled deletion',async t=>{
const {manager}=await fixture(t);
for(const user of [{username:'other',role:'operator'},{username:'owner',role:'viewer'}])for(const method of ['account','saveAccount','clearAccount','fillAccount'])await assert.rejects(manager[method](connection,{...principal,user},credentials),e=>e.status===403);
for(const body of [null,[],{}, {...credentials,extra:true},{...credentials,username:' '},{...credentials,username:'x'.repeat(151)},{...credentials,password:''},{...credentials,password:'x'.repeat(257)}])await assert.rejects(manager.saveAccount(connection,principal,body),e=>e.status===400);
const admin={...principal,user:{username:'admin',role:'admin'}};
await manager.saveAccount(connection,admin,credentials);assert.equal((await manager.account(connection,principal)).configured,true);
await manager.vault().write(connection.id,{storageState:{cookies:[],origins:[]}});
await manager.disable(connection.id);
assert.equal(await manager.vault().read(connection.id),null);assert.equal(await manager.vault().read('account:account-test'),null);
await assert.rejects(manager.account(connection,principal),e=>e.status===409);
});
test('saved account fills real known form on open and navigate without submission, captcha changes or field writeback',async t=>{
const {manager,make}=await fixture(t,{browser:true});
await manager.saveAccount(connection,principal,credentials);await manager.shutdown();
const restarted=make();
await restarted.open(connection,principal);const page=restarted.sessions.get(connection.id).page;
assert.equal(await page.locator('#username').inputValue(),credentials.username);assert.equal(await page.locator('#password').inputValue(),credentials.password);
assert.equal(await page.locator('#captcha').inputValue(),'');assert.equal(await page.evaluate(()=>window.submitted),0);
await page.locator('#password').fill('Browser edit');assert.equal((await restarted.vault().read('account:account-test')).password,credentials.password);
await restarted.navigate(connection.id,principal,{target:'main'});assert.equal(await page.locator('#password').inputValue(),credentials.password);
assert.equal((await restarted.fillAccount(connection,principal)).filled,true);
assert.equal(await page.evaluate(()=>window.submitted),0);
await assert.rejects(restarted.fillAccount(connection,{...principal,sessionId:'second-session'}),e=>e.status===409);
await restarted.clearAccount(connection,principal);const absent=await restarted.fillAccount(connection,principal);assert.equal(absent.filled,false);assert.match(absent.message,/托管|保存/);
});
test('unknown origins and unsafe or hidden form fields never receive any saved credentials',async t=>{
const unknown=await fixture(t,{browser:true,known:false});await unknown.manager.saveAccount(connection,principal,credentials);await unknown.manager.open(connection,principal);
const unknownPage=unknown.manager.sessions.get(connection.id).page;assert.equal(await unknownPage.locator('#username').inputValue(),'');assert.equal(await unknownPage.locator('#password').inputValue(),'');
assert.equal((await unknown.manager.fillAccount(connection,principal)).filled,false);assert.equal(await unknownPage.evaluate(()=>window.submitted),0);
const known=await fixture(t,{browser:true});await known.manager.saveAccount(connection,principal,credentials);await known.manager.open(connection,principal);const page=known.manager.sessions.get(connection.id).page;
for(const target of ['/malicious','/hidden']){await page.goto(known.origin+target);assert.equal((await known.manager.fillAccount(connection,principal)).filled,false);assert.equal(await page.locator('#username').inputValue(),'');assert.equal(await page.locator('#password').inputValue(),'');assert.equal(await page.evaluate(()=>window.submitted),0);}
await assert.rejects(known.manager.fillAccount({...connection,id:'unopened'},principal),e=>e.status===410);
});
test('saving a managed account invalidates previous authentication and refuses another dashboard lease',async t=>{
const {manager}=await fixture(t,{browser:true});
await manager.saveAccount(connection,principal,credentials);
await manager.vault().write(connection.id,{storageState:{cookies:[],origins:[]},sessionStorage:{old:'authentication'}});
await manager.open(connection,principal);
await manager.saveAccount(connection,principal,{...credentials,password:'Updated password'});
assert.ok(await manager.vault().read(connection.id));assert.equal(manager.sessions.has(connection.id),true);
await assert.rejects(manager.saveAccount(connection,{...principal,sessionId:'other-session'},{username:'New User',password:'New password'}),e=>e.status===409);
assert.equal((await manager.account(connection,principal)).username,credentials.username);
assert.ok(await manager.vault().read(connection.id));
await assert.rejects(manager.saveAccount(connection,principal,{username:'New User',password:''}),e=>e.status===400);
assert.ok(await manager.vault().read(connection.id));assert.equal(manager.sessions.has(connection.id),true);
await manager.saveAccount(connection,principal,{username:'New User',password:'New password'});
assert.equal(await manager.vault().read(connection.id),null);assert.equal(manager.sessions.has(connection.id),false);
assert.equal((await manager.account(connection,principal)).username,'New User');
});
async function automaticFixture(t,{challenge=false,wrong=false,unknown=false,unsafe=false,portalFailure=false,getSubmit=false}={}){
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-automatic-'));let submissions=0,verificationMode='';
const server=http.createServer((req,res)=>{
res.setHeader('content-type','text/html');
if(req.url.startsWith('/authenticate') && req.method!=='POST'){submissions++;res.end('Unsafe GET submission');return;}
if(req.url==='/authenticate' && req.method==='POST'){
submissions++;let body='';req.on('data',chunk=>body+=chunk);req.on('end',()=>{
const params=new URLSearchParams(body);if(!wrong && params.get('username')===credentials.username && params.get('password')===credentials.password)res.setHeader('Set-Cookie','auth=valid; HttpOnly; Path=/');
res.writeHead(302,{Location:'/main'});res.end();
});return;
}
if((req.headers.cookie||'').includes('auth=valid'))res.end('<div id="identity">Fixture User</div>');
else res.end(`<form method="POST" action="/authenticate"><input id="username" name="username" type="text"><input id="password" name="password" type="${unsafe?'text':'password'}">${challenge?'<input id="otp" name="otp" type="text" placeholder="One time code">':''}<button id="kc-login" type="submit" ${getSubmit?'formmethod="GET"':''}>Sign In</button></form>`);
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const origin='http://127.0.0.1:'+server.address().port;
const options={stateDir:dir,urls:{main:origin+'/main'},allowedOrigins:[origin],...(!unknown?{loginForms:{[origin]:{username:'#username',password:'#password',submit:'#kc-login'}}}:{}),browserFactory:async()=>loadPlaywright().chromium.launch(browserOptions())};
// Avoid a locator timeout when no identity exists; positive evidence remains required.
options.probe=async(page,kind)=>{assert.equal(kind,'portal');if(portalFailure || verificationMode==='network')throw new Error('fixture connection interrupted');const marker=page.locator('#identity');return {ok:await marker.count()===1,identity:await marker.count()?await marker.textContent():''};};
const managers=[];const make=()=>{const manager=new BpmSessionManager(options);managers.push(manager);return manager;};
t.after(async()=>{for(const manager of managers)await manager.shutdown();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));await fs.rm(dir,{recursive:true,force:true});});
return {manager:make(),make,origin,submissions:()=>submissions,setVerificationMode:mode=>verificationMode=mode};
}
test('automatic custody authenticates once, restores cookies after restart and renews expired authentication',async t=>{
const {manager,make,submissions}=await automaticFixture(t);
assert.equal(typeof manager.ensure,'function');await manager.saveAccount(connection,principal,credentials);
assert.equal((await manager.ensure(connection,principal)).status,'connected');assert.equal(submissions(),1);assert.equal(manager.sessions.size,0);assert.ok(await manager.vault().read(connection.id));
await manager.shutdown();const restarted=make();
assert.equal((await restarted.ensure(connection,principal)).status,'connected');assert.equal(submissions(),1);
await restarted.saveAccount(connection,principal,credentials);assert.equal((await restarted.ensure(connection,principal)).status,'connected');assert.equal(submissions(),1);
await restarted.vault().remove(connection.id);assert.equal((await restarted.ensure(connection,principal)).status,'connected');assert.equal(submissions(),2);
await restarted.clearAccount(connection,principal);await restarted.saveAccount(connection,principal,credentials);assert.equal((await restarted.ensure(connection,principal)).status,'connected');assert.equal(submissions(),2);
});
test('automatic custody defers CAPTCHA or unsafe and unknown forms without submitting',async t=>{
for(const options of [{challenge:true},{unknown:true},{unsafe:true}]){
const {manager,submissions}=await automaticFixture(t,options);assert.equal(typeof manager.ensure,'function');await manager.saveAccount(connection,principal,credentials);
const checked=await manager.ensure(connection,principal);assert.equal(checked.status,'login_required');assert.match(checked.checks.portal.message,/人工|验证|登录/);assert.equal(submissions(),0);assert.equal(manager.sessions.size,0);
}
});
test('failed automatic credentials use persisted cooldown and background ensure never takes over an active lease',async t=>{
const {manager,make,submissions}=await automaticFixture(t,{wrong:true});assert.equal(typeof manager.ensure,'function');await manager.saveAccount(connection,principal,credentials);
assert.equal((await manager.ensure(connection,principal)).status,'login_required');assert.equal(submissions(),1);
const cooldown=await manager.ensure(connection,principal);assert.equal(cooldown.status,'login_required');assert.match(cooldown.checks.portal.message,/稍后|更新|重试/);assert.equal(submissions(),1);
await manager.shutdown();const restarted=make();assert.equal((await restarted.ensure(connection,principal)).status,'login_required');assert.equal(submissions(),1);
await restarted.open(connection,principal);await assert.rejects(restarted.ensure(connection,{...principal,sessionId:'background'}),e=>e.status===409);assert.equal(restarted.sessions.size,1);assert.equal(submissions(),1);
});
test('portal network failure never triggers another credential submission',async t=>{
const {manager,submissions}=await automaticFixture(t,{portalFailure:true});await manager.saveAccount(connection,principal,credentials);
const checked=await manager.ensure(connection,principal);assert.equal(checked.status,'error');assert.equal(checked.checks.portal.ok,false);assert.deepEqual(Object.keys(checked.checks),['portal']);assert.equal(submissions(),0);
});
test('positive check persists refreshed authenticated cookies instead of discarding them',async t=>{
const {manager,origin,submissions}=await automaticFixture(t);await manager.saveAccount(connection,principal,credentials);await manager.ensure(connection,principal);
await manager.open(connection,principal);await manager.sessions.get(connection.id).context.addCookies([{name:'rotated',value:'refresh-value',url:origin}]);
assert.equal((await manager.check(connection,principal)).status,'connected');assert.equal(submissions(),1);
const state=await manager.vault().read(connection.id);assert.equal(state.storageState.cookies.find(cookie=>cookie.name==='rotated')?.value,'refresh-value');
});
test('a submit control cannot override POST and leak managed credentials into a GET URL',async t=>{
const {manager,submissions}=await automaticFixture(t,{getSubmit:true});await manager.saveAccount(connection,principal,credentials);
assert.equal((await manager.ensure(connection,principal)).status,'login_required');assert.equal(submissions(),0);
});
test('new portal authentication is sufficient for connected checks and cookie reuse across restart',async t=>{
const {manager,make,submissions}=await automaticFixture(t);await manager.saveAccount(connection,principal,credentials);
const checked=await manager.ensure(connection,principal);assert.equal(checked.status,'connected');assert.equal(checked.checks.portal.ok,true);assert.deepEqual(Object.keys(checked.checks),['portal']);assert.equal(submissions(),1);
assert.ok(await manager.vault().read(connection.id));
const account=await manager.vault().read('account:'+connection.id);account.nextAttemptAt='2020-01-01T00:00:00.000Z';await manager.vault().write('account:'+connection.id,account);
assert.equal((await manager.check(connection,principal)).status,'connected');assert.equal((await manager.ensure(connection,principal)).status,'connected');assert.equal(submissions(),1);
await manager.shutdown();const restarted=make();assert.equal((await restarted.ensure(connection,principal)).status,'connected');assert.equal(submissions(),1);
});
test('network uncertainty preserves the prior good encrypted snapshot without another login attempt',async t=>{
const {manager,submissions,setVerificationMode}=await automaticFixture(t);await manager.saveAccount(connection,principal,credentials);await manager.ensure(connection,principal);
const filename=manager.vault().filename(connection.id),lastGood=await fs.readFile(filename);
setVerificationMode('network');const checked=await manager.ensure(connection,principal);assert.equal(checked.status,'error');assert.equal(checked.checks.portal.ok,false);
assert.deepEqual(await fs.readFile(filename),lastGood);assert.equal(submissions(),1);
});
+31
View File
@@ -0,0 +1,31 @@
const {test}=require('node:test');const assert=require('node:assert/strict');
const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {WorkspaceStore}=require('../src/workspace-store.cjs');
test('custodian restores managed or saved sessions, skips busy/disabled connections and never overlaps',async t=>{
let BpmCustodian;try{({BpmCustodian}=require('../src/bpm-custodian.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
assert.equal(typeof BpmCustodian,'function');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'custodian-'));const workspace=new WorkspaceStore(dir);
t.after(()=>{workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
const actor={username:'admin',role:'admin'},members=[actor];
const managed=workspace.createConnection({name:'managed',owner:'admin'},actor,members);
const busy=workspace.createConnection({name:'busy',owner:'admin'},actor,members);
const disabled=workspace.createConnection({name:'disabled',owner:'admin'},actor,members);workspace.disableConnection(disabled.id,actor);
workspace.createConnection({name:'unconfigured',owner:'admin'},actor,members);
let release;const gate=new Promise(resolve=>release=resolve),calls=[];
const result={status:'connected',identity:'Fixture User',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'ok'}}};
const manager={account:async c=>({configured:c.id!==disabled.id && c.name!=='unconfigured'}),ensure:async(c,p)=>{calls.push(c.id);assert.equal(p.user.role,'admin');if(c.id===busy.id)throw Object.assign(new Error('busy'),{status:409});await gate;return result;}};
const custodian=new BpmCustodian({workspace,manager,intervalMs:999999});
const first=custodian.tick();await new Promise(resolve=>setImmediate(resolve));await custodian.tick();
assert.equal(calls.filter(id=>id===managed.id).length,1);release();await first;
assert.equal(workspace.getConnection(managed.id).status,'connected');assert.equal(workspace.getConnection(busy.id).status,'disconnected');
assert.equal(calls.includes(disabled.id),false);assert.equal(calls.length,2);
const stopped=custodian.stop();await stopped;await custodian.tick();assert.equal(calls.length,2);
});
test('custodian start restores saved state without managed credentials and stop waits for running check',async()=>{
const {BpmCustodian}=require('../src/bpm-custodian.cjs');let finish,started;const active=new Promise(r=>started=r),gate=new Promise(r=>finish=r);let updates=0;
const connection={id:'saved',status:'unchecked',lastConnectedAt:'2026-10-16T00:00:00Z'};
const workspace={snapshot:()=>({connections:[connection]}),getConnection:()=>connection,updateConnectionSession:()=>updates++};
const manager={account:async()=>({configured:false}),ensure:async()=>{started();await gate;return {};}};
const custodian=new BpmCustodian({workspace,manager,intervalMs:999999});custodian.start();await active;
let stopped=false;const stopping=custodian.stop().then(()=>stopped=true);await new Promise(r=>setImmediate(r));assert.equal(stopped,false);finish();await stopping;assert.equal(updates,1);
});
+125
View File
@@ -0,0 +1,125 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const http=require('node:http');
const {Store}=require('../src/dashboard-store.cjs');const {WorkspaceStore}=require('../src/workspace-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');
const result=(status='connected')=>({status,identity:'alice@bpm',checkedAt:'2026-10-16T01:00:00.000Z',checks:{portal:{ok:status==='connected',message:'门户检查'}}});
async function setup(t,options={}){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-http-'));const store=new Store(path.join(dir,'users'));const admin=store.bootstrap('admin','Test-password-123');for(const [username,role] of [['alice','operator'],['bob','operator'],['reader','viewer']])store.addUser({username,password:'Test-password-123',role},'admin');const workspace=new WorkspaceStore(path.join(dir,'workspace'));let lease;let next=result();let disabled=0,released=0;const jpg=Buffer.from([255,216,255,217]);
const manager={open:async(connection,principal)=>{if(lease && lease!==principal.sessionId)throw Object.assign(new Error('占用'),{status:409});lease=principal.sessionId;return {active:true,viewport:{width:1280,height:800},expiresAt:'2026-10-16T02:00:00.000Z',host:'bpmn.skyworthdigital.com'};},frame:async(id,p)=>{assert.ok(id);if(lease!==p.sessionId)throw Object.assign(new Error('占用'),{status:409});return jpg;},input:async(id,p,action)=>{assert.equal(action.type,'text');return {ok:true};},navigate:async(id,p,action)=>({target:action.target}),save:async()=>next,check:async()=>next,close:async(id,p)=>{if(lease && lease!==p.sessionId)throw Object.assign(new Error('占用'),{status:409});lease=null;return {ok:true};},releaseSession:async(token)=>{if(lease===token)lease=null;released++;},disable:async()=>{disabled++;lease=null;}};
const server=createDashboard({store,workspace,outputDir:dir,...(options.noManager?{}:{bpmSessions:manager}),trustedProxy:options.trustedProxy});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));t.after(async()=>{await new Promise(resolve=>server.close(resolve));workspace.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;
function call(route,body,cookie,extra={}){return new Promise((resolve,reject)=>{const host=extra.host||'127.0.0.1:'+server.address().port;const request=http.request(base+route,{method:body===undefined?'GET':'POST',headers:{Host:host,...(body===undefined?{}:{Origin:extra.origin||'http://'+host,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{}),...(extra.headers||{})}},response=>{const chunks=[];response.on('data',x=>chunks.push(x));response.on('end',()=>{const bytes=Buffer.concat(chunks);resolve({status:response.statusCode,headers:response.headers,bytes,json:()=>JSON.parse(bytes.toString())});});});request.on('error',reject);request.end(body===undefined?undefined:JSON.stringify(body));});}
const login=async(username)=>(await call('/api/login',{username,password:'Test-password-123'})).headers['set-cookie'][0].split(';')[0];const cookie=await login('admin');const connection=(await call('/api/connections',{name:'BPM',owner:'alice'},cookie)).json();const route='/api/connections/'+connection.id;
return {call,login,cookie,workspace,store,manager,connection,route,setResult:value=>{next=value;},counts:()=>({disabled,released}),jpg};
}
test('deleting a disabled connection enforces admin, cleans custody first, and preserves the entry on cleanup failure',async t=>{
const s=await setup(t);const endpoint=s.route+'/delete';
assert.equal((await s.call(endpoint,{},s.cookie)).status,409);
assert.equal(s.counts().disabled,0);
await s.call(s.route+'/disable',{},s.cookie);
for(const username of ['alice','bob','reader'])assert.equal((await s.call(endpoint,{},await s.login(username))).status,403);
assert.equal((await s.call(endpoint,{extra:true},s.cookie)).status,400);
assert.equal((await s.call(endpoint,{},s.cookie,{origin:'https://evil.example'})).status,403);
s.manager.disable=async()=>{throw new Error('cookie=PRIVATE');};
const failed=await s.call(endpoint,{},s.cookie);assert.equal(failed.status,502);assert.ok(!failed.bytes.toString().includes('PRIVATE'));
assert.equal(s.workspace.getConnection(s.connection.id).status,'disabled');
let cleaned=false;s.manager.disable=async id=>{assert.equal(id,s.connection.id);assert.equal(s.workspace.getConnection(id).status,'disabled');cleaned=true;};
const deleted=await s.call(endpoint,{},s.cookie);assert.equal(deleted.status,200);assert.equal(cleaned,true);
assert.deepEqual(deleted.json(),{id:s.connection.id,deleted:true});
assert.equal((await s.call(s.route+'/login/open',{},s.cookie)).status,404);
assert.equal((await s.call('/api/workspace',undefined,s.cookie)).json().connections.length,0);
const unavailable=await setup(t,{noManager:true});unavailable.workspace.disableConnection(unavailable.connection.id,unavailable.store.users().find(u=>u.role==='admin'));
assert.equal((await unavailable.call(unavailable.route+'/delete',{},unavailable.cookie)).status,503);
});
test('remote login authenticates owner and dashboard session, serves private JPEG and releases control on logout',async t=>{
const s=await setup(t);const alice=await s.login('alice'),other=await s.login('alice'),bob=await s.login('bob'),reader=await s.login('reader');const open=s.route+'/login/open',frame=s.route+'/login/frame';
assert.equal((await s.call(open,{})).status,401);for(const cookie of [bob,reader])assert.equal((await s.call(open,{},cookie)).status,403);
const opened=await s.call(open,{},alice);assert.equal(opened.status,200);assert.equal(opened.json().active,true);assert.ok(!opened.bytes.includes(Buffer.from(alice.split('=')[1])));
assert.match(opened.headers['content-security-policy'],/img-src[^;]*blob:/);
assert.equal((await s.call(frame)).status,401);assert.equal((await s.call(frame,undefined,bob)).status,403);assert.equal((await s.call(frame,undefined,other)).status,409);
const image=await s.call(frame,undefined,alice);assert.equal(image.status,200);assert.equal(image.headers['content-type'],'image/jpeg');assert.equal(image.headers['cache-control'],'no-store');assert.deepEqual(image.bytes,s.jpg);
assert.equal((await s.call(s.route+'/login/input',{type:'text',text:'Sensitive-password'},alice)).status,200);assert.ok(!JSON.stringify(s.workspace.snapshot()).includes('Sensitive-password'));
assert.equal((await s.call(s.route+'/login/navigate',{target:'main'},alice)).status,200);
assert.equal((await s.call('/api/logout',{},alice)).status,200);assert.equal(s.counts().released,1);assert.equal((await s.call(open,{},other)).status,200);
});
test('remote credentials require local host or explicit local HTTPS proxy and reject cross-origin and forged state',async t=>{
const s=await setup(t);const alice=await s.login('alice');const route=s.route+'/login/open';
assert.equal((await s.call(route,{},alice,{origin:'https://evil.example'})).status,403);
assert.equal((await s.call(route,{},alice,{host:'lan.example'})).status,403);
assert.equal((await s.call(route,{},alice,{host:'lan.example',headers:{'X-Forwarded-Proto':'https'}})).status,403);
assert.equal((await s.call(s.route+'/login/save',{status:'connected',cookies:['forged']},alice)).status,400);
assert.equal((await s.call(s.route+'/check',{status:'connected'},alice)).status,400);
const trusted=await setup(t,{trustedProxy:true});const proxy={host:'workspace.example',origin:'https://workspace.example',headers:{'X-Forwarded-Proto':'https'}};const proxyLogin=await trusted.call('/api/login',{username:'alice',password:'Test-password-123'},undefined,proxy);assert.match(proxyLogin.headers['set-cookie'][0],/; Secure(?:;|$)/);const owner=proxyLogin.headers['set-cookie'][0].split(';')[0];assert.equal((await trusted.call(trusted.route+'/login/open',{},owner,proxy)).status,200);
});
test('transport never trusts remote LAN address with local Host or forwarded HTTPS, but accepts TLS and configured loopback proxy',()=>{
const {secureBpmTransport}=require('../src/bpm-api.cjs');
const request=(host,remoteAddress,encrypted=false,proto)=>({socket:{remoteAddress,encrypted},headers:{host,'x-forwarded-proto':proto}});
for(const trusted of [false,true]){
assert.equal(secureBpmTransport(request('localhost','192.168.1.10',false,'https'),trusted),false);
assert.equal(secureBpmTransport(request('127.0.0.1','192.168.1.10'),trusted),false);
assert.equal(secureBpmTransport(request('workspace.example','192.168.1.10',true),trusted),true);
}
assert.equal(secureBpmTransport(request('[::1]:18766','::1')),true);
assert.equal(secureBpmTransport(request('localhost.evil','127.0.0.1')),false);
assert.equal(secureBpmTransport(request('workspace.example','127.0.0.1',false,'https,http'),true),false);
assert.equal(secureBpmTransport(request('workspace.example','127.0.0.1',false,'https'),true),true);
});
test('manager errors do not leak browser secrets and failed disable leaves persisted connection enabled',async t=>{
const s=await setup(t);s.manager.open=async()=>{throw new Error('password=NEVER-EXPOSE cookie=PRIVATE');};
const failed=await s.call(s.route+'/login/open',{},s.cookie);assert.equal(failed.status,502);assert.ok(!failed.bytes.toString().includes('NEVER-EXPOSE'));
s.manager.disable=async()=>{throw new Error('cookie=PRIVATE');};const disabled=await s.call(s.route+'/disable',{},s.cookie);assert.equal(disabled.status,502);assert.equal(s.workspace.getConnection(s.connection.id).status,'disconnected');
});
test('portal metadata persists safely, unavailable and login tasks deduplicate, and restart clears readiness',async t=>{
const s=await setup(t);const alice=await s.login('alice');assert.equal((await s.call('/api/workspace',undefined,alice)).json().capabilities.remoteLogin,true);
s.setResult(result('error'));assert.equal((await s.call(s.route+'/check',{},alice)).status,200);assert.equal(s.workspace.snapshot().exceptions.length,0);
s.setResult(result());
assert.equal((await s.call(s.route+'/login/save',{},alice)).status,200);assert.equal(s.workspace.getConnection(s.connection.id).status,'connected');
s.setResult(result('error'));let checked=await s.call(s.route+'/check',{},alice);assert.equal(checked.json().checks.portal.ok,false);assert.equal(checked.json().checks.detail,undefined);const attention=s.workspace.snapshot().exceptions;assert.equal(attention.length,1);assert.equal(attention[0].title,'BPM 连接需要检查:BPM');assert.equal(attention[0].description,'新版 BPM 暂时无法连接,请检查网络和连接状态。');assert.equal(attention[0].owner,'alice');const attentionId=attention[0].id;
assert.equal((await s.call(s.route+'/check',{},alice)).status,200);
s.setResult(result('login_required'));for(let n=0;n<2;n++)assert.equal((await s.call(s.route+'/check',{},alice)).status,200);assert.equal(s.workspace.snapshot().exceptions.length,1);assert.equal(s.workspace.snapshot().exceptions[0].component,'bpm');assert.equal(s.workspace.snapshot().exceptions[0].id,attentionId);
s.setResult({...result(),cookies:[{value:'PRIVATE_COOKIE'}],password:'PRIVATE_PASSWORD'});assert.equal((await s.call(s.route+'/check',{},alice)).status,400);assert.ok(!JSON.stringify(s.workspace.snapshot()).includes('PRIVATE_'));
s.setResult(result());await s.call(s.route+'/check',{},alice);s.workspace.markSessionChecksPending();const after=s.workspace.getConnection(s.connection.id);assert.equal(after.status,'unchecked');assert.equal(after.identity,'alice@bpm');assert.equal(after.checkedAt,'2026-10-16T01:00:00.000Z');
assert.equal((await s.call(s.route+'/disable',{},alice)).status,403);assert.equal(s.counts().disabled,0);assert.equal((await s.call(s.route+'/disable',{},s.cookie)).status,200);assert.equal(s.counts().disabled,1);assert.equal((await s.call(s.route+'/login/open',{},alice)).status,409);
const noManager=await setup(t,{noManager:true});assert.equal((await noManager.call('/api/workspace',undefined,noManager.cookie)).json().capabilities.remoteLogin,false);assert.equal((await noManager.call(noManager.route+'/login/open',{},noManager.cookie)).status,503);
});
test('account API protects metadata and mutations, redacts responses and audits connection names only',async t=>{
const s=await setup(t);const owner=await s.login('alice'),unrelated=await s.login('bob'),viewer=await s.login('reader');
const account=s.route+'/account',clear=account+'/clear',fill=s.route+'/login/fill-account';
let saved=false;const secret='Never-return-this-password';
const meta=()=>({configured:saved,username:saved?'BPM User':'',updatedAt:saved?'2026-10-16T02:00:00.000Z':null,password:secret,cookies:['PRIVATE']});
s.manager.account=async()=>meta();
s.manager.saveAccount=async(connection,p,body)=>{assert.equal(connection.id,s.connection.id);assert.equal(p.user.username,'alice');assert.deepEqual(body,{username:'BPM User',password:secret});saved=true;return meta();};
s.manager.clearAccount=async()=>{saved=false;return meta();};
s.manager.ensure=async()=>({...result('login_required'),identity:''});
s.manager.fillAccount=async()=>({filled:true,message:'已填入托管账号。',password:secret});
assert.equal((await s.call(account)).status,401);
for(const cookie of [unrelated,viewer]){assert.equal((await s.call(account,undefined,cookie)).status,403);assert.equal((await s.call(account,{username:'BPM User',password:secret},cookie)).status,403);assert.equal((await s.call(clear,{},cookie)).status,403);assert.equal((await s.call(fill,{},cookie)).status,403);}
assert.deepEqual((await s.call(account,undefined,owner)).json(),{configured:false,username:'',updatedAt:null});
assert.equal((await s.call(account,undefined,owner,{host:'lan.example'})).status,403);
assert.equal((await s.call(account,{username:'BPM User',password:secret},owner,{origin:'https://evil.example'})).status,403);
assert.equal((await s.call(account,{username:'BPM User',password:secret},owner,{host:'lan.example'})).status,403);
await s.call(s.route+'/login/save',{},owner);assert.equal(s.workspace.getConnection(s.connection.id).status,'connected');
s.manager.account=async()=>({configured:true,username:'Previous User',updatedAt:'2026-10-16T01:00:00.000Z'});
const stored=await s.call(account,{username:'BPM User',password:secret},owner);assert.equal(stored.status,200);assert.equal(stored.json().configured,true);assert.equal(stored.json().username,'BPM User');assert.equal(stored.json().updatedAt,'2026-10-16T02:00:00.000Z');assert.equal(stored.json().connection.status,'login_required');assert.equal(stored.bytes.includes(Buffer.from(secret)),false);
const reset=s.workspace.getConnection(s.connection.id);assert.equal(reset.status,'login_required');assert.equal(reset.identity,'');assert.equal(reset.lastConnectedAt,undefined);assert.equal(reset.checks.portal.ok,false);
assert.equal((await s.call(account,undefined,s.cookie)).json().configured,true);
const filled=await s.call(fill,{},owner);assert.equal(filled.status,200);assert.deepEqual(filled.json(),{filled:true,message:'已填入托管账号。'});
for(const route of [fill,clear])assert.equal((await s.call(route,{url:'https://evil.example',selector:'input'},owner)).status,400);
assert.deepEqual((await s.call(clear,{},owner)).json(),{configured:false,username:'',updatedAt:null});
const audit=s.workspace.snapshot().audit;assert.equal(audit.filter(row=>row.action==='bpm.account.save').length,1);assert.equal(audit.filter(row=>row.action==='bpm.account.clear').length,1);
assert.equal(audit.find(row=>row.action==='bpm.account.save').detail,'BPM');assert.equal(audit.find(row=>row.action==='bpm.account.clear').detail,'BPM');
assert.equal(JSON.stringify(s.workspace.snapshot()).includes(secret),false);assert.equal(JSON.stringify(s.workspace.snapshot()).includes('BPM User'),false);
s.manager.account=async()=>{throw new Error('password='+secret);};const failed=await s.call(account,undefined,owner);assert.equal(failed.status,502);assert.equal(failed.bytes.includes(Buffer.from(secret)),false);
});
test('account availability is authenticated, owner scoped, strict and duplicate errors are actionable without secrets',async t=>{
const s=await setup(t);const owner=await s.login('alice'),other=await s.login('bob'),viewer=await s.login('reader');
const endpoint=s.route+'/account/check';s.manager.checkAccount=async(c,p,input)=>{assert.equal(c.id,s.connection.id);assert.equal(p.user.username,'alice');assert.deepEqual(input,{username:'existing'});return {available:false,password:'DO-NOT-RETURN',connectionId:'private-other-id'};};
assert.equal((await s.call(endpoint,{})).status,401);
for(const cookie of [other,viewer])assert.equal((await s.call(endpoint,{username:'existing'},cookie)).status,403);
assert.equal((await s.call(endpoint,{username:'existing'},owner,{origin:'https://evil.example'})).status,403);
assert.deepEqual((await s.call(endpoint,{username:'existing'},owner)).json(),{available:false});
s.manager.account=async()=>({configured:false,username:'',updatedAt:null});
s.manager.saveAccount=async()=>{throw Object.assign(new Error('PRIVATE'),{status:409,code:'BPM_ACCOUNT_DUPLICATE'});};
const failed=await s.call(s.route+'/account',{username:'existing',password:'SECRET'},owner);
assert.equal(failed.status,409);assert.match(failed.json().error,/账号.*已/);assert.equal(failed.bytes.includes(Buffer.from('PRIVATE')),false);
});
+88
View File
@@ -0,0 +1,88 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs/promises');
const os=require('node:os');
const path=require('node:path');
const http=require('node:http');
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
test('formal dashboard remote screen signs into an isolated BPM fixture under production CSP',async t=>{
const {Store}=require('../src/dashboard-store.cjs');
const {WorkspaceStore}=require('../src/workspace-store.cjs');
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
const {createDashboard}=require('../src/dashboard.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-full-ui-'));
const site=http.createServer((req,res)=>{
res.setHeader('Content-Type','text/html; charset=utf-8');
res.end(`<!doctype html><meta charset="utf-8"><style>input{position:absolute;left:10px;width:200px;height:30px}#name{top:10px}#password{top:60px}button{position:absolute;top:110px;left:10px}</style>
${req.headers.cookie?.includes('fixture_auth=yes')?'<div data-authenticated>Fixture User</div>':`<form onsubmit="event.preventDefault();if(document.querySelector('#name').value==='fixture-user'&&document.querySelector('#password').value==='fixture-password'){document.cookie='fixture_auth=yes; path=/';location.reload()}"><input id="name" autocomplete="off"><input id="password" type="password" autocomplete="off"><button>Login</button></form>`}`);
});
await new Promise(resolve=>site.listen(0,'127.0.0.1',resolve));
const bpmOrigin=`http://127.0.0.1:${site.address().port}`;
const store=new Store(path.join(dir,'dashboard'));
const admin=store.bootstrap('integration-admin','Integration-password-123');
const workspace=new WorkspaceStore(path.join(dir,'workspace'));
const connection=workspace.createConnection({name:'Fixture BPM',owner:admin.username},admin,store.users());
const sessions=new BpmSessionManager({stateDir:path.join(dir,'sessions'),urls:{main:bpmOrigin+'/main'},allowedOrigins:[bpmOrigin],probe:async page=>{
const marker=page.locator('[data-authenticated]');
await marker.waitFor({state:'visible',timeout:1000}).catch(()=>{});
return {ok:await marker.isVisible(),identity:await marker.isVisible()?await marker.textContent():''};
}});
const server=createDashboard({store,workspace,bpmSessions:sessions,outputDir:path.join(dir,'output')});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const base=`http://127.0.0.1:${server.address().port}`;
const browser=await loadPlaywright().chromium.launch(browserOptions());
t.after(async()=>{await browser.close();await sessions.shutdown();await new Promise(resolve=>server.close(resolve));workspace.close();await new Promise(resolve=>site.close(resolve));await fs.rm(dir,{recursive:true,force:true});});
const page=await browser.newPage({viewport:{width:1440,height:1000}});
const errors=[];page.on('pageerror',error=>errors.push(error.message));
await page.addInitScript(()=>{window.cspFailures=[];document.addEventListener('securitypolicyviolation',event=>window.cspFailures.push(event.violatedDirective));});
await page.goto(base+'/#bpm');
await page.getByLabel('账号',{exact:true}).fill('integration-admin');
await page.getByLabel('密码',{exact:true}).fill('Integration-password-123');
await page.getByRole('button',{name:'登录',exact:true}).click();
await page.getByRole('button',{name:'远程登录',exact:true}).click();
const image=page.locator('[data-bpm-frame]');
await page.waitForFunction(()=>{const el=document.querySelector('[data-bpm-frame]');return el&&!el.hidden&&el.complete&&el.naturalWidth===1280;});
const bounds=await image.boundingBox();
assert.ok(bounds.width>300);
await image.click({position:{x:50*bounds.width/1280,y:25*bounds.height/800}});
await page.keyboard.type('fixture-user');
await page.keyboard.press('Tab');
await page.keyboard.type('fixture-password');
await page.keyboard.press('Enter');
await page.getByRole('button',{name:'检查并保存',exact:true}).click();
await page.waitForFunction(()=>document.querySelector('#bpm-list')?.textContent.includes('已连接'));
const saved=workspace.getConnection(connection.id);
assert.equal(saved.status,'connected');assert.equal(saved.identity,'Fixture User');
assert.deepEqual(await page.evaluate(()=>window.cspFailures),[]);
assert.deepEqual(errors,[]);
await page.getByRole('button',{name:'关闭',exact:true}).click();
await page.waitForFunction(()=>!document.querySelector('[data-bpm-frame]'));
assert.equal(sessions.sessions.size,0);
await page.reload();
await page.getByRole('button',{name:'检查连接',exact:true}).click();
await page.getByText('连接状态已更新。',{exact:true}).first().waitFor();
assert.equal(workspace.getConnection(connection.id).status,'connected');
// Initial custody reuses the authenticated remote session and saves no password in UI metadata.
await page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();
await page.getByLabel('BPM 账号',{exact:true}).fill('fixture-user');
await page.getByLabel('托管密码',{exact:true}).fill('fixture-password');
const accountResponse=page.waitForResponse(response=>response.url().endsWith('/account') && response.request().method()==='POST');
await page.getByRole('button',{name:'保存账号',exact:true}).click();
const metadata=await (await accountResponse).json();
assert.equal(metadata.configured,true);assert.equal(metadata.connection.status,'connected');
assert.equal(JSON.stringify(metadata).includes('fixture-password'),false);
await page.getByText('自动续登已开启,BPM 已连接。',{exact:true}).first().waitFor();
await page.reload();await page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();
assert.equal(await page.getByLabel('BPM 账号',{exact:true}).inputValue(),'fixture-user');
assert.equal(await page.getByLabel('托管密码',{exact:true}).inputValue(),'');
assert.equal(workspace.getConnection(connection.id).status,'connected');
assert.deepEqual(await page.evaluate(()=>window.cspFailures),[]);assert.deepEqual(errors,[]);
const another=workspace.createConnection({name:'Another Fixture BPM',owner:admin.username},admin,store.users());
const check=await page.request.post(base+'/api/connections/'+another.id+'/account/check',{headers:{Origin:base},data:{username:' FIXTURE-USER '}});
assert.deepEqual(await check.json(),{available:false});
const duplicate=await page.request.post(base+'/api/connections/'+another.id+'/account',{headers:{Origin:base},data:{username:'FIXTURE-USER',password:'must-not-be-saved'}});
assert.equal(duplicate.status(),409);assert.match((await duplicate.json()).error,/账号.*已/);
assert.equal((await sessions.account(another,{user:admin,sessionId:'isolated-check'})).configured,false);
assert.equal(workspace.getConnection(connection.id).status,'connected');
});
+13
View File
@@ -0,0 +1,13 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {WorkspaceStore}=require('../src/workspace-store.cjs');
test('new BPM portal alone marks connected and legacy connection metadata migrates without losing ownership',t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-portal-'));let store=new WorkspaceStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
const actor={username:'owner',role:'admin'},c=store.createConnection({name:'BPM',owner:'owner'},actor,[actor]);
assert.equal(c.detailUrl,undefined);
const result={status:'connected',identity:'Owner',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'已登录'}}};
assert.equal(store.updateConnectionSession(c.id,result,actor).status,'connected');
assert.throws(()=>store.updateConnectionSession(c.id,{...result,checks:{...result.checks,detail:{ok:false,message:'not needed'}}},actor));
const saved=store.getConnection(c.id);store.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify({...saved,status:'partial',detailUrl:'https://bpm.skyworthdigital.com',checks:{...saved.checks,detail:{ok:false,message:'old'}}}),c.id);
store.close();store=new WorkspaceStore(dir);const migrated=store.getConnection(c.id);
assert.equal(migrated.detailUrl,undefined);assert.equal(migrated.checks.detail,undefined);assert.equal(migrated.status,'unchecked');assert.equal(migrated.owner,'owner');assert.equal(migrated.identity,'Owner');assert.equal(migrated.lastConnectedAt,saved.lastConnectedAt);
});
+34
View File
@@ -0,0 +1,34 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
const net=require('node:net');
async function freePort(){const server=net.createServer();await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const port=server.address().port;await new Promise(resolve=>server.close(resolve));return port;}
test('formal runtime wires BPM sessions and preserves users across restart',async t=>{
const {main}=require('../src/server.cjs');
assert.equal(typeof main,'function','formal runtime must support isolated startup and shutdown');
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'order-runtime-'));
let app;
t.after(async()=>{if(app)await app.stop();fs.rmSync(stateDir,{recursive:true,force:true});});
const config={port:await freePort(),dashboard:{host:'127.0.0.1',port:await freePort()}};
app=await main({stateDir,config,quiet:true});
const base=`http://127.0.0.1:${config.dashboard.port}`;
const post=(route,body,cookie)=>fetch(base+route,{method:'POST',headers:{Origin:base,'Content-Type':'application/json',...(cookie?{Cookie:cookie}:{})},body:JSON.stringify(body)});
const bootstrap=await post('/api/bootstrap',{username:'runtime-admin',password:'Runtime-test-password-123'});
assert.equal(bootstrap.status,201);
let cookie=bootstrap.headers.get('set-cookie').split(';')[0];
const snapshot=await (await fetch(base+'/api/workspace',{headers:{Cookie:cookie}})).json();
assert.equal(snapshot.capabilities.remoteLogin,true);
assert.equal(snapshot.members[0].username,'runtime-admin');
await app.stop();app=null;
app=await main({stateDir,config,quiet:true});
assert.equal((await (await fetch(base+'/api/bootstrap/status')).json()).required,false);
assert.equal((await fetch(base+'/api/me',{headers:{Cookie:cookie}})).status,200);
const login=await post('/api/login',{username:'runtime-admin',password:'Runtime-test-password-123'});
assert.equal(login.status,200);cookie=login.headers.get('set-cookie').split(';')[0];
assert.equal((await fetch(base+'/api/workspace',{headers:{Cookie:cookie}})).status,200);
assert.equal(fs.existsSync(path.join(stateDir,'bpm-sessions')),true);
});
+34
View File
@@ -0,0 +1,34 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {Store}=require('../src/dashboard-store.cjs');const {WorkspaceStore}=require('../src/workspace-store.cjs');const {BpmScanStore}=require('../src/bpm-scan-store.cjs');const {BpmScanner}=require('../src/bpm-scanner.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {normalizeArrival}=require('../src/bpm-list-client.cjs');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
async function setup(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'scan-http-')),store=new Store(path.join(dir,'users')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scanStore=new BpmScanStore(path.join(dir,'scan'));
store.bootstrap('admin','Test-password-123');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');store.addUser({username:'other',password:'Test-password-123',role:'operator'},'admin');
const connection={id:'fixture',name:'测试连接',owner:'admin',status:'connected',lastConnectedAt:new Date().toISOString()};workspace.db.prepare('INSERT INTO connections VALUES(?,?)').run(connection.id,JSON.stringify(connection));
const rows=['2026-10-15T16:33:58','2026-10-14T10:00:00'].map((date,i)=>normalizeArrival({taskId:String(i),serialNum:'TEST-'+i,processName:'测试流程',startTime:date,processInstanceSubject:i?'昨天的流程':'<script>bad()</script>订单号:123'},'portal-v8'));
const scanner=new BpmScanner({store:scanStore,workspace,manager:{scanArrivals:async()=>rows},settings:()=>store.settings()});
const server=createDashboard({store,workspace,scanner,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));
t.after(async()=>{await scanner.stop();await new Promise(r=>server.close(r));scanStore.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port,call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});
const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {base,call,login,scanner,scanStore};
}
test('scan API enforces owner, role and origin; scan results and overview reflect database',async t=>{
const {call,login,scanner}=await setup(t);assert.equal((await call('/api/arrivals')).status,401);const admin=await login('admin'),reader=await login('reader'),other=await login('other');
for(const cookie of [reader,other])assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture'},cookie)).status,403);
assert.equal((await call('/api/bpm-scan/config',{enabled:false,intervalMinutes:5},reader)).status,403);
assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture'},admin,'http://evil.test')).status,403);
assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture'},admin)).status,202);await Promise.all([...scanner.pending.values()]);
const page=await (await call('/api/arrivals',undefined,reader)).json();assert.equal(page.groups.length,2);assert.equal(page.groups[0].day,'2026-10-15');assert.equal(page.groups[0].items[0].subject,'订单号:123');
const overview=await (await call('/api/overview',undefined,reader)).json();assert.equal(overview.scan.total,2);assert.equal(overview.connections.find(c=>c.name==='BPM 自动扫描').ready,true);
});
test('browser displays separate arrival days, searches, scans and preserves PDF entry',async t=>{
const {base,scanner,scanStore}=await setup(t);await scanner.scan('fixture',{user:{username:'admin',role:'admin'},sessionId:'fixture'});
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.goto(base+'/#records');await page.locator('#username').fill('admin');await page.locator('#password').fill('Test-password-123');await page.locator('#login-form button').click();
await page.locator('[data-arrival-day="2026-10-15"]').waitFor();assert.equal(await page.locator('[data-arrival-day]').count(),2);
const background=normalizeArrival({taskId:'background',serialNum:'BG-1',processName:'新增流程',startTime:'2026-10-16T12:00:00',processInstanceSubject:'后台扫描新增'},'portal-v8');scanStore.complete(scanStore.begin('fixture','系统扫描'),'fixture',[background]);
await page.getByText('后台扫描新增',{exact:true}).waitFor({timeout:20000});
await page.getByLabel('搜索流程记录',{exact:true}).fill('昨天');await page.getByRole('button',{name:'查询',exact:true}).click();await page.getByText('昨天的流程',{exact:true}).waitFor();assert.equal(await page.locator('[data-arrival-day]').count(),1);
await page.getByRole('button',{name:'立即扫描',exact:true}).click();await page.getByText(/扫描完成/).waitFor();
await page.getByRole('button',{name:'PDF 导出记录',exact:true}).click();await page.locator('#record-search').waitFor();assert.equal(await page.locator('#record-search').isVisible(),true);
await page.route('**/api/bpm-scan',route=>route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:'扫描暂不可用'})}));
await page.getByRole('link',{name:'工作总览',exact:true}).click();await page.getByRole('link',{name:'订单与导出记录',exact:true}).click();await page.locator('#pdf-fallback').waitFor();await page.locator('#pdf-fallback').click();await page.locator('#record-search').waitFor();
});
+51
View File
@@ -0,0 +1,51 @@
const test=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const http=require('node:http');
const {BpmListClient,normalizeArrival}=require('../src/bpm-list-client.cjs');
const {BpmScanStore}=require('../src/bpm-scan-store.cjs');
const {BpmScanner}=require('../src/bpm-scanner.cjs');
const {BpmSessionManager}=require('../src/bpm-session-manager.cjs');
const row=(id,date='2026-10-15T16:33:58')=>({taskId:id,serialNum:'SN-'+id,processName:'订单评审',activityName:'知会',startTime:date,processInstanceSubject:'<b>订单号:</b>123 &amp; 456',processInstanceInitiatorShortName:'甲'});
test('arrival uses received time in Shanghai, strips HTML, never substitutes scan time',()=>{
const a=normalizeArrival(row('1'),'portal-v4');assert.equal(a.arrivalDay,'2026-10-15');assert.equal(a.arrivedAt,'2026-10-15T08:33:58.000Z');assert.equal(a.subject,'订单号:123 & 456');
assert.equal(normalizeArrival(row('2','2026-10-15T18:30:00Z'),'portal-v8').arrivalDay,'2026-10-16');
assert.throws(()=>normalizeArrival(row('3',''),'portal-v4'));assert.throws(()=>normalizeArrival(row('3','2026-02-30T01:00:00'),'portal-v4'));
});
test('session scanning reuses cookies, renews only authentication failures, and respects interactive lock',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'scan-manager-'));const manager=new BpmSessionManager({stateDir:dir,browserFactory:()=>{throw Error('unexpected browser');}});
const saved={storageState:{cookies:[],origins:[]}};manager._vault={read:async()=>saved,destroy(){}};
t.after(async()=>{manager.sessions.clear();await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});
const connection={id:'c',status:'connected',owner:'甲'},principal={user:{username:'甲',role:'operator'},sessionId:'test'};let renewals=0,calls=0,mode='ok';
manager.ensure=async()=>{renewals++;mode='ok';return {status:'connected'};};manager.listClient={scan:async state=>{assert.equal(state,saved.storageState);calls++;if(mode==='auth')throw Object.assign(Error('expired'),{status:401});if(mode==='network')throw Object.assign(Error('network'),{status:502});return [];}};
await manager.scanArrivals(connection,principal);assert.equal(renewals,0);
mode='auth';await manager.scanArrivals(connection,principal);assert.equal(renewals,1);assert.equal(calls,3);
mode='network';await assert.rejects(manager.scanArrivals(connection,principal));assert.equal(renewals,1);
manager.sessions.set('c',{});await assert.rejects(manager.scanArrivals(connection,principal),e=>e.status===409);manager.sessions.clear();
await assert.rejects(manager.scanArrivals(connection,{...principal,user:{username:'乙',role:'operator'}}),e=>e.status===403);
});
test('scanner respects calendar, rejects unauthorized owners, deduplicates concurrent calls and records failures',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-service-')),store=new BpmScanStore(dir);let calls=0,release,broken=false;
const connection={id:'c',name:'BPM',owner:'甲',status:'connected',lastConnectedAt:new Date().toISOString()};
const workspace={snapshot:()=>({connections:[connection],calendar:{overrides:[{date:'2026-10-16',kind:'pause',scan:false}]}}),getConnection:()=>connection,record:()=>{}};
const manager={scanArrivals:async()=>{calls++;if(broken)throw Object.assign(Error('查询失败'),{status:502});await new Promise(r=>release=r);return [normalizeArrival(row('1'),'portal-v4')];}};
const scanner=new BpmScanner({store,workspace,manager,settings:()=>({schedule:{weekends:true}}),clock:()=>new Date('2026-10-16T12:00:00+08:00')});t.after(async()=>{await scanner.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});
await scanner.tick();assert.equal(calls,0);
const principal={user:{username:'甲',role:'operator'},sessionId:'x'};
await assert.rejects(scanner.scan('c',{...principal,user:{username:'乙',role:'operator'}}),e=>e.status===403);
const first=scanner.scan('c',principal);await new Promise(r=>setImmediate(r));await assert.rejects(scanner.scan('c',principal),e=>e.status===409);release();assert.equal((await first).added,1);
broken=true;await assert.rejects(scanner.scan('c',principal));assert.equal(store.status().runs[0].status,'error');assert.equal(store.list().total,1);
});
test('API authenticates from portal, follows all pages, rejects redirects and incomplete scans',async t=>{
let mode='ok',calls=[];const server=http.createServer((req,res)=>{calls.push(req.url);if(req.url==='/'){res.end('<script>Yiez.clientId = "fixture-token";</script>');return;}if(mode==='redirect'){res.writeHead(302,{Location:'https://example.com/'});res.end();return;}if(req.headers.authorization!=='Bearer fixture-token'){res.writeHead(401);res.end();return;}const u=new URL(req.url,'http://localhost');const start=+u.searchParams.get('start');res.setHeader('Content-Type','application/json');res.end(JSON.stringify({total:3,children:mode==='incomplete'?[]:[row(String(start)),...(start===0?[row('1')]:[])]}));});
await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));const baseURL=`http://127.0.0.1:${server.address().port}/`;
const client=new BpmListClient({baseURL,pageSize:2,allowLocal:true});const result=await client.scan({cookies:[],origins:[]});assert.equal(result.length,6);assert.ok(calls.some(u=>u.includes('start=2')));
mode='incomplete';await assert.rejects(client.scan({cookies:[],origins:[]}),/分页|完整/);
mode='redirect';await assert.rejects(client.scan({cookies:[],origins:[]}),/跳转/);
});
test('SQLite keeps history across rescan and restart, daily pagination and search are stable',t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-scan-'));let store=new BpmScanStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
const rows=[normalizeArrival(row('1'),'portal-v4'),normalizeArrival(row('2','2026-10-14T10:00:00'),'portal-v8')];
const run=store.begin('c','甲');assert.equal(store.complete(run,'c',rows).added,2);assert.equal(store.complete(store.begin('c','甲'),'c',rows).added,0);
store.close();store=new BpmScanStore(dir);let page=store.list({days:1});assert.equal(page.total,2);assert.equal(page.groups[0].day,'2026-10-15');assert.equal(page.nextBefore,'2026-10-15');assert.equal(store.list({before:page.nextBefore}).groups[0].day,'2026-10-14');
assert.equal(store.list({q:'不存在'}).total,0);assert.equal(store.list({connectionId:'other'}).total,0);
const bad=store.begin('c','甲');assert.throws(()=>store.complete(bad,'c',[rows[0],{...rows[1],arrivalDay:null}]));assert.equal(store.list().total,2);store.fail(bad,'扫描失败');assert.equal(store.status().runs[0].status,'error');
store.saveConfig({enabled:false,intervalMinutes:10},'甲');assert.equal(store.status().config.enabled,false);
});
+161
View File
@@ -0,0 +1,161 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const { loadPlaywright, browserOptions } = require('../src/runtime.cjs');
const principal = { user: { id: '1', username: 'owner', role: 'operator' }, sessionId: 'dashboard-session' };
const connection = { id: 'a', owner: 'owner', status: 'disconnected' };
const other = { user: { id: '2', username: 'intruder', role: 'operator' }, sessionId: 'other-session' };
const html = `<!doctype html><meta charset="utf-8"><input id="name" style="position:absolute;left:10px;top:10px;width:200px;height:30px"><button style="position:absolute;left:10px;top:60px" onclick="login()">登录</button><div id="status"></div><script>
const dbp=new Promise((resolve,reject)=>{const r=indexedDB.open('auth',1);r.onupgradeneeded=()=>r.result.createObjectStore('tokens');r.onsuccess=()=>resolve(r.result);r.onerror=reject});
async function login(){const db=await dbp;await new Promise(r=>{const t=db.transaction('tokens','readwrite');t.objectStore('tokens').put('idb-token','token');t.oncomplete=r});document.cookie='auth=yes; path=/';localStorage.setItem('auth','local-token');sessionStorage.setItem('auth','session-token');location.reload()}
(async()=>{const db=await dbp;const token=await new Promise(r=>{const q=db.transaction('tokens').objectStore('tokens').get('token');q.onsuccess=()=>r(q.result)});if(document.cookie.includes('auth=yes')&&localStorage.getItem('auth')==='local-token'&&sessionStorage.getItem('auth')==='session-token'&&token==='idb-token'){document.querySelector('#status').innerHTML='<a class="yz-btn-signinuser"><span class="x-btn-inner">Fixture User</span></a>'}})();
</script>`;
async function fixture(t) {
const { BpmSessionManager } = require('../src/bpm-session-manager.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-browser-'));
let blockedHits = 0;const requests=[];
const forbidden = http.createServer((req,res) => { blockedHits++; res.end('forbidden'); });
await new Promise(resolve => forbidden.listen(0, '127.0.0.1', resolve));
const badOrigin = `http://127.0.0.1:${forbidden.address().port}`;
const server = http.createServer((req,res) => {
requests.push(req.url);
if (req.url === '/escape-chain') { res.writeHead(302, { Location: '/escape' }); res.end(); return; }
if (req.url === '/escape') { res.writeHead(302, { Location: badOrigin }); res.end(); return; }
res.setHeader('content-type','text/html; charset=utf-8'); res.end(html+(req.url==='/iframe'?`<iframe src="${badOrigin}/tracking"></iframe>`:''));
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const origin = `http://127.0.0.1:${server.address().port}`;
const browser = await loadPlaywright().chromium.launch(browserOptions());
const options = { stateDir: dir, browserFactory: async () => browser, urls: { main: origin + '/main' }, allowedOrigins: [origin],
probe: async page => { const marker = page.locator('a.yz-btn-signinuser .x-btn-inner'); await marker.waitFor({timeout:1000}).catch(()=>{}); return { ok: await marker.count() > 0, identity: (await marker.allTextContents())[0] || '' }; } };
const manager = new BpmSessionManager(options);
const managers=[manager],make=overrides=>{const next=new BpmSessionManager({...options,...overrides});managers.push(next);return next;};
t.after(async () => { for(const item of managers)await item.shutdown(); await browser.close(); await Promise.all([new Promise(r=>server.close(r)),new Promise(r=>forbidden.close(r))]); await fs.rm(dir,{recursive:true,force:true}); });
return { manager, options, make, browser, origin, badOrigin, requests, blockedHits:()=>blockedHits };
}
test('real browser login saves encrypted full state, restores after shutdown and isolates connections', async t => {
const { manager, make } = await fixture(t);
const opened = await manager.open(connection,principal);
assert.equal(opened.active,true); assert.deepEqual(opened.viewport,{width:1280,height:800});
const jpeg = await manager.frame('a',principal); assert.equal(jpeg.readUInt16BE(0),0xffd8);
assert.equal((await manager.save(connection,principal)).status,'login_required');
await manager.input('a',principal,{type:'click',x:50,y:25});
await manager.input('a',principal,{type:'text',text:'Not persisted password'});
await manager.input('a',principal,{type:'click',x:30,y:70});
await new Promise(r=>setTimeout(r,300));
const saved = await manager.save(connection,principal);
assert.equal(saved.status,'connected'); assert.equal(saved.identity,'Fixture User');
assert.equal(saved.checks.portal.ok,true); assert.deepEqual(Object.keys(saved.checks),['portal']);
await manager.open({...connection,id:'b'},principal);
assert.equal((await manager.check({...connection,id:'b'},principal)).status,'login_required');
// An unsuccessful verification must leave the last good encrypted state intact.
const lease = manager.sessions.get('a'); await lease.context.clearCookies();
assert.equal((await manager.save(connection,principal)).status,'login_required');
await manager.shutdown();
const restarted = make({browserFactory:undefined});
assert.equal((await restarted.check(connection,principal)).status,'connected');
});
test('session lease enforces owner, dashboard exclusivity, limits, TTL and logout cleanup', async t => {
const { manager } = await fixture(t);
await assert.rejects(manager.open(connection,other),e=>e.status===403);
await manager.open(connection,principal);
await assert.rejects(manager.frame('a',{...principal,sessionId:'different-login'}),e=>e.status===409);
await assert.rejects(manager.frame('a',other),e=>e.status===403);
await manager.open({...connection,id:'b'},principal); await manager.open({...connection,id:'c'},principal);
await assert.rejects(manager.open({...connection,id:'d'},principal),e=>e.status===429);
manager.sessions.get('a').expiresAt=Date.now()-1;
await assert.rejects(manager.frame('a',principal),e=>e.status===410);
assert.equal(manager.sessions.has('a'),false);
await manager.releaseSession(principal.sessionId); assert.equal(manager.sessions.size,0);
});
test('bounded inputs and navigation reject arbitrary origins and scripts before any request', async t => {
const { manager, origin, blockedHits } = await fixture(t);
await manager.open(connection,principal);
for (const action of [{type:'text',text:'x'.repeat(2001)},{type:'key',key:'Control+L'},{type:'click',x:-1,y:2},{type:'scroll',deltaY:Infinity,deltaX:0},{type:'evaluate',script:'alert(1)'}]) {
await assert.rejects(manager.input('a',principal,action),e=>e.status===400);
}
await assert.rejects(manager.navigate('a',principal,{target:'https://example.com'}),e=>e.status===400);
const lease=manager.sessions.get('a');
await lease.page.goto(origin+'/escape-chain').catch(()=>{});
assert.equal(blockedHits(),0);
await assert.rejects(manager.frame('a',principal),e=>e.status===403);
await manager.close('a',principal);
assert.equal(manager.sessions.has('a'),false);
});
test('positive new BPM login alone reports connected and never requests a legacy entry', async t => {
const { manager, origin, requests } = await fixture(t);
await manager.open(connection,principal);
await manager.sessions.get('a').page.route(origin+'/main',route=>route.fulfill({contentType:'text/html',body:'<a class="yz-btn-signinuser"><span class="x-btn-inner">Fixture User</span></a>'}));
const result=await manager.save(connection,principal);
assert.equal(result.status,'connected');
assert.equal(result.checks.portal.ok,true);
assert.deepEqual(Object.keys(result.checks),['portal']);
assert.equal(requests.includes('/detail'),false);
assert.ok(await manager.vault().read('a'));
});
test('legacy detail navigation is rejected before any request',async t=>{
const {manager,requests}=await fixture(t);await manager.open(connection,principal);
await assert.rejects(manager.navigate('a',principal,{target:'detail'}),error=>error.status===400);
assert.equal(requests.includes('/detail'),false);
});
test('production origin policy permits verified company SSO but rejects lookalikes and arbitrary injections', async t => {
const { BpmSessionManager } = require('../src/bpm-session-manager.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-origin-'));
t.after(()=>fs.rm(dir,{recursive:true,force:true}));
const manager=new BpmSessionManager({stateDir:dir}); t.after(()=>manager.shutdown());
assert.equal(manager.allowed('https://sso.skyworthdigital.com/realms/skyworth/protocol/openid-connect/auth'),true);
for (const url of ['https://bpm.skyworthdigital.com/','http://sso.skyworthdigital.com/','https://sso.skyworthdigital.com.evil.example/','https://evil.example/','file:///C:/Windows/win.ini']) assert.equal(manager.allowed(url),false);
assert.throws(()=>new BpmSessionManager({stateDir:dir,allowedOrigins:['https://evil.example']}),e=>e.status===400);
assert.throws(()=>new BpmSessionManager({stateDir:dir,urls:{main:'https://bpmn.skyworthdigital.com/',detail:'https://bpm.skyworthdigital.com/'}}),e=>e.status===400);
});
test('blocked external iframe and popup make no external request and preserve usable login frame', async t => {
const {manager,origin,blockedHits}=await fixture(t);
await manager.open(connection,principal);
const lease=manager.sessions.get('a');
await lease.page.goto(origin+'/iframe',{waitUntil:'domcontentloaded'});
await lease.page.evaluate(url=>window.open(url,'_blank'),origin+'/escape-chain');
await new Promise(resolve=>setTimeout(resolve,200));
assert.equal(blockedHits(),0);
assert.equal((await manager.frame('a',principal)).readUInt16BE(0),0xffd8);
assert.equal((await manager.check(connection,principal)).status,'login_required');
});
test('concurrent startup never exceeds three contexts and disabling in flight closes and prevents reopening', async t => {
const {manager,browser}=await fixture(t);
const results=await Promise.allSettled(['a','b','c','d','e'].map(id=>manager.open({...connection,id},principal)));
assert.equal(results.filter(result=>result.status==='fulfilled').length,3);
assert.equal(browser.contexts().length,3);
await manager.releaseSession(principal.sessionId);
assert.equal(browser.contexts().length,0);
const opening=manager.open(connection,principal);
const disabling=manager.disable('a');
await Promise.allSettled([opening,disabling]);
assert.equal(browser.contexts().length,0);
await assert.rejects(manager.open(connection,principal),e=>e.status===409);
await manager.shutdown();
await assert.rejects(manager.open({...connection,id:'b'},principal),e=>e.status===503);
});
test('immediate save after remote login Enter waits for pending login navigation and verifies the portal', async t => {
const {manager,origin}=await fixture(t);
await manager.open(connection,principal);
const lease=manager.sessions.get('a');
await lease.page.route(origin+'/pending-login',async route=>{
await route.fulfill({contentType:'text/html',body:`<form onsubmit="event.preventDefault();document.cookie='auth=yes; path=/';localStorage.setItem('auth','local-token');sessionStorage.setItem('auth','session-token');location.href='/main'"><input autofocus><button>Login</button></form><script>const r=indexedDB.open('auth',1);r.onupgradeneeded=()=>r.result.createObjectStore('tokens');r.onsuccess=()=>{const t=r.result.transaction('tokens','readwrite');t.objectStore('tokens').put('idb-token','token')};</script>`});
});
await lease.page.goto(origin+'/pending-login');
await lease.page.locator('input').focus();
await manager.input('a',principal,{type:'key',key:'Enter'});
assert.equal((await manager.save(connection,principal)).status,'connected');
});
+304
View File
@@ -0,0 +1,304 @@
const {test,before,after}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const http=require('node:http');
const path=require('node:path');
const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
const {setTimeout:delay}=require('node:timers/promises');
async function waitUntil(predicate){const deadline=Date.now()+10000;while(!predicate()){assert.ok(Date.now()<deadline,'expected browser request did not arrive');await delay(25);}}
let browser,server,base,jpeg;
const source=path.join(__dirname,'../web/bpm.js');
before(async()=>{
browser=await loadPlaywright().chromium.launch(browserOptions());
const page=await browser.newPage({viewport:{width:1280,height:800}});jpeg=await page.screenshot({type:'jpeg'});await page.close();
server=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html');res.end('<div id="root"></div>');});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));base=`http://127.0.0.1:${server.address().port}`;
});
after(async()=>{await browser?.close();await new Promise(resolve=>server?.close(resolve));});
async function fixture(t,{user={username:'alice',role:'operator'},connections,account={configured:false,username:'',updatedAt:null},savedAccountConnection,holdAccount=false,holdAccountSave=false,holdFill=false,holdOpen=false,holdInput=false,holdFrame=false,holdSave=false}={}){
const page=await browser.newPage();t.after(()=>page.close());
const calls=[];let releaseOpen,releaseInput,releaseFrame,releaseSave,releaseAccount,releaseFill,releaseAccountSave;
const accountSaveGate=holdAccountSave?new Promise(r=>releaseAccountSave=r):Promise.resolve();
const accountGate=holdAccount?new Promise(r=>releaseAccount=r):Promise.resolve();
const fillGate=holdFill?new Promise(r=>releaseFill=r):Promise.resolve();
const openGate=holdOpen?new Promise(r=>releaseOpen=r):Promise.resolve();
const inputGate=holdInput?new Promise(r=>releaseInput=r):Promise.resolve();
const frameGate=holdFrame?new Promise(r=>releaseFrame=r):Promise.resolve();
const saveGate=holdSave?new Promise(r=>releaseSave=r):Promise.resolve();
let frameActive=0,maxFrames=0;
await page.route('**/api/**',async route=>{
const url=new URL(route.request().url()),body=route.request().postDataJSON();calls.push({path:url.pathname,body});
if(url.pathname.endsWith('/frame')){frameActive++;maxFrames=Math.max(maxFrames,frameActive);await frameGate;frameActive--;return route.fulfill({contentType:'image/jpeg',body:jpeg});}
let result={};
if(url.pathname.endsWith('/account')){await accountGate;if(body){await accountSaveGate;account={configured:true,username:body.username,updatedAt:'2026-10-16T00:00:00.000Z'};}result=body&&savedAccountConnection?{...account,connection:savedAccountConnection}:account;}
if(url.pathname.endsWith('/account/clear'))result=account={configured:false,username:'',updatedAt:null};
if(url.pathname.endsWith('/fill-account')){await fillGate;result={filled:true,message:'账号已填入。'};}
if(url.pathname==='/api/workspace')result={members:[{username:'alice',role:'operator'}],capabilities:{remoteLogin:true},connections:connections||[{id:'one',name:'业务连接',owner:'alice',status:'disconnected'}]};
if(url.pathname.endsWith('/open')){await openGate;result={active:true,viewport:{width:1280,height:800},expiresAt:new Date(Date.now()+600000).toISOString(),host:'bpmn.skyworthdigital.com'};}
if(url.pathname.endsWith('/input'))await inputGate;
if(url.pathname.endsWith('/save'))await saveGate;
if(url.pathname.endsWith('/save')||url.pathname.endsWith('/check'))result={connection:{id:'one',name:'业务连接',owner:'alice',status:'connected',identity:'Alice',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'已登录'}}}};
if(url.pathname.endsWith('/account/check'))result={available:body?.username!=='already-used'};
await route.fulfill({json:result});
});
await page.goto(base);
await page.addStyleTag({path:path.join(__dirname,'../web/app.css')});
if(fs.existsSync(source))await page.addScriptTag({path:source});
assert.equal(await page.evaluate(()=>typeof window.BpmLogin?.mount),'function','BPM page exposes a working mount function');
await page.evaluate(async user=>{
const api=async(route,body)=>{const r=await fetch('/api'+route,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});return r.json();};
await window.BpmLogin.mount(document.querySelector('#root'),{api,esc:v=>String(v??'').replaceAll('<','&lt;'),formatDate:v=>v||'—',notify:()=>{},user,isActive:()=>true});
},user);
return {page,calls,releaseOpen,releaseInput,releaseFrame,releaseSave,releaseAccount,releaseFill,releaseAccountSave,maxFrames:()=>maxFrames};
}
test('admin can delete only disabled connections after explicit confirmation',async t=>{
const connections=[{id:'one',name:'已停用账号',owner:'alice',status:'disabled'},{id:'active',name:'使用中账号',owner:'alice',status:'connected'}];
const f=await fixture(t,{connections,user:{username:'boss',role:'admin'}});
const remove=f.page.getByRole('button',{name:'删除',exact:true});assert.equal(await remove.count(),1);
f.page.once('dialog',dialog=>dialog.dismiss());await remove.click();
assert.equal(f.calls.some(c=>c.path.endsWith('/delete')),false);
f.page.once('dialog',async dialog=>{assert.match(dialog.message(),/已停用账号/);assert.match(dialog.message(),/Cookie/);await dialog.accept();});
await remove.click();await f.page.getByText('连接已删除。',{exact:true}).waitFor();
assert.equal(await f.page.getByRole('heading',{name:'已停用账号',exact:true}).count(),0);
assert.equal(await f.page.getByRole('heading',{name:'使用中账号',exact:true}).count(),1);
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/delete')).map(c=>c.body),[{}]);
for(const role of ['operator','viewer']){const other=await fixture(t,{connections,user:{username:'alice',role}});assert.equal(await other.page.getByRole('button',{name:'删除',exact:true}).count(),0);}
});
test('auto-renew setup rejects a duplicate username before sending credentials and clears stale checks',async t=>{
const f=await fixture(t);
await f.page.getByRole('button',{name:'开启自动续登',exact:true}).click();
const username=f.page.getByLabel('BPM 账号',{exact:true}),password=f.page.getByLabel('托管密码',{exact:true});
await username.fill('already-used');await password.fill('not-submitted');
await f.page.getByText('该账号已开启自动续登,请使用已有连接。',{exact:true}).waitFor();
assert.equal(await username.evaluate(el=>el.validity.valid),false);
assert.equal(f.calls.some(c=>c.path.endsWith('/account')&&c.body),false);
await username.fill('available-user');await password.fill('new-secret');
await f.page.getByRole('button',{name:'保存账号',exact:true}).click();
await f.page.getByText('自动续登已开启。',{exact:true}).waitFor();
assert.equal(f.calls.filter(c=>c.path.endsWith('/account')&&c.body).length,1);
assert.equal(await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).count(),1);
});
test('portal login displays one portal check and saves connected without legacy controls',async t=>{
const f=await fixture(t,{connections:[{id:'one',name:'新版 BPM',owner:'alice',status:'connected',checks:{portal:{ok:true,message:'新版已登录'}}}]});
assert.equal(await f.page.getByText('旧版入口',{exact:true}).count(),0);
assert.equal(await f.page.getByText('bpm.skyworthdigital.com',{exact:true}).count(),0);
assert.equal(await f.page.locator('.bpm-checks>div').count(),1);
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
assert.equal(await f.page.getByRole('button',{name:'旧版入口',exact:true}).count(),0);
await f.page.getByRole('button',{name:'新版门户',exact:true}).click();
await f.page.getByRole('button',{name:'刷新',exact:true}).click();
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();
await f.page.getByText('连接已检查并保存。',{exact:true}).waitFor();
assert.equal(await f.page.getByText('已连接',{exact:true}).count(),1);
assert.equal(await f.page.locator('.bpm-checks>div').count(),1);
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/navigate')).map(c=>c.body),[{target:'main'},{target:'reload'}]);
});
test('account management loads metadata only for enabled owner or admin connections',async t=>{
const connections=[{id:'mine',name:'我的连接',owner:'alice',status:'unchecked'},{id:'other',name:'其他连接',owner:'bob',status:'connected'},{id:'off',name:'停用连接',owner:'alice',status:'disabled'}];
const f=await fixture(t,{connections});
assert.equal(await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).count(),1);
await f.page.getByText('自动续登未开启',{exact:true}).waitFor();
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/account')).map(c=>c.path),['/api/connections/mine/account']);
const viewer=await fixture(t,{connections,user:{username:'alice',role:'viewer'}});
assert.equal(await viewer.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).count(),0);
assert.equal(viewer.calls.some(c=>c.path.endsWith('/account')),false);
const admin=await fixture(t,{connections,user:{username:'boss',role:'admin'}});
assert.equal(await admin.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).count(),2);
});
test('account editor saves exact credentials, clears secret input, requires fresh password and explicitly clears custody',async t=>{
const f=await fixture(t,{account:{configured:true,username:'saved-user',updatedAt:'2026-10-16T00:00:00.000Z'}});
await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();
const username=f.page.getByLabel('BPM 账号',{exact:true}),password=f.page.getByLabel('托管密码',{exact:true});
await username.waitFor();assert.equal(await username.inputValue(),'saved-user');
assert.equal(await password.getAttribute('type'),'password');assert.equal(await password.getAttribute('autocomplete'),'new-password');assert.equal(await password.inputValue(),'');
await username.fill('new-user');await f.page.getByRole('button',{name:'保存账号',exact:true}).click();
assert.equal(f.calls.filter(c=>c.path.endsWith('/account')&&c.body).length,0);
await password.fill(' secret-value ');await f.page.getByRole('button',{name:'保存账号',exact:true}).click();
await f.page.getByText('自动续登已开启。',{exact:true}).waitFor();
assert.deepEqual(f.calls.find(c=>c.path.endsWith('/account')&&c.body).body,{username:'new-user',password:' secret-value '});
assert.equal(await f.page.locator('input[type=password]').evaluateAll(inputs=>inputs.some(input=>input.value!=='')),false);
assert.equal(await f.page.locator('#root').textContent().then(s=>s.includes('secret-value')),false);
assert.equal(await f.page.evaluate(()=>localStorage.length),0);
await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();
assert.equal(await password.inputValue(),'');assert.equal(await password.getAttribute('placeholder'),'输入新密码以更新');
await f.page.getByRole('button',{name:'关闭自动续登',exact:true}).click();await f.page.getByText('自动续登未开启',{exact:true}).waitFor();
assert.deepEqual(f.calls.find(c=>c.path.endsWith('/account/clear')).body,{});
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
assert.equal(await f.page.getByRole('button',{name:'填入托管账号',exact:true}).count(),0);
});
test('saving a replacement account blocks new remote control and shows the automatically connected identity',async t=>{
const f=await fixture(t,{holdAccountSave:true,savedAccountConnection:{id:'one',name:'业务连接',owner:'alice',status:'connected',identity:'replacement',checkedAt:'2026-10-16T01:00:00.000Z',checks:{portal:{ok:true,message:'已登录'}}},connections:[{id:'one',name:'业务连接',owner:'alice',status:'connected',identity:'old-user',checkedAt:'2026-10-15T00:00:00.000Z',checks:{portal:{ok:true,message:'已登录'}}}]});
await f.page.setViewportSize({width:360,height:800});await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();
await f.page.getByLabel('BPM 账号',{exact:true}).fill('replacement');await f.page.getByLabel('托管密码',{exact:true}).fill('replacement-secret');
assert.equal(await f.page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth),true);
await f.page.getByRole('button',{name:'保存账号',exact:true}).click();
assert.equal(await f.page.getByRole('button',{name:'远程登录',exact:true}).isDisabled(),true);
await f.page.locator('[data-account-form]').evaluate(form=>form.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true})));
await f.page.waitForTimeout(50);assert.equal(f.calls.filter(c=>c.path.endsWith('/account')&&c.body).length,1);
f.releaseAccountSave();await f.page.getByText('登录账号 replacement',{exact:true}).waitFor();
assert.equal(await f.page.getByText('已连接',{exact:true}).count(),1);
assert.equal(await f.page.getByText('登录账号 old-user',{exact:true}).count(),0);
assert.equal(await f.page.getByText('上次检查 2026-10-15T00:00:00.000Z',{exact:true}).count(),0);
assert.equal(await f.page.getByRole('button',{name:'远程登录',exact:true}).isEnabled(),true);
await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();await f.page.getByLabel('托管密码',{exact:true}).fill('unsaved');
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
assert.equal(await f.page.getByRole('button',{name:'保存账号',exact:true}).count(),0);
assert.equal(await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).isDisabled(),true);
});
test('account fill drains queued input and disposal waits for its operation before closing',async t=>{
const f=await fixture(t,{holdInput:true,holdFill:true,account:{configured:true,username:'saved-user',updatedAt:'2026-10-16T00:00:00.000Z'}});
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
await f.page.locator('[data-bpm-input]').evaluate(el=>el.dispatchEvent(new InputEvent('input',{data:'x',bubbles:true})));
await f.page.getByRole('button',{name:'填入托管账号',exact:true}).click();
assert.equal(f.calls.some(c=>c.path.endsWith('/fill-account')),false);
assert.equal(await f.page.getByRole('button',{name:'检查并保存',exact:true}).isDisabled(),true);
f.releaseInput();await f.page.waitForFunction(()=>document.querySelector('[data-bpm-input]').disabled);await waitUntil(()=>f.calls.some(c=>c.path.endsWith('/fill-account')));
assert.deepEqual(f.calls.find(c=>c.path.endsWith('/fill-account'))?.body,{});
await f.page.evaluate(()=>{window.BpmLogin.dispose();});
assert.equal(f.calls.some(c=>c.path.endsWith('/close')),false);
f.releaseFill();await waitUntil(()=>f.calls.some(c=>c.path.endsWith('/close')));
assert.equal(f.calls.filter(c=>c.path.endsWith('/close')).length,1);
});
test('late account metadata cannot mount an editor after leaving the BPM page',async t=>{
const f=await fixture(t,{holdAccount:true});await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();
await f.page.evaluate(()=>{window.BpmLogin.dispose();document.querySelector('#root').innerHTML='<p>其他页面</p>';});
f.releaseAccount();await f.page.waitForTimeout(100);
assert.equal(await f.page.getByLabel('托管密码',{exact:true}).count(),0);assert.equal(await f.page.locator('#root').textContent(),'其他页面');
});
test('scaled clicks, IME, paste and editing keys reach the remote browser in order before save',async t=>{
const f=await fixture(t,{holdInput:true});await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
const image=f.page.locator('[data-bpm-frame]');await image.waitFor({state:'visible'});
await image.evaluate(el=>{el.style.width='640px';el.style.height='400px';});
await image.click({position:{x:320,y:200}});
await f.page.locator('[data-bpm-input]').evaluate(el=>{
el.dispatchEvent(new CompositionEvent('compositionstart',{bubbles:true}));
el.value='中文';el.dispatchEvent(new InputEvent('input',{data:'中文',inputType:'insertCompositionText',isComposing:true,bubbles:true}));
el.dispatchEvent(new CompositionEvent('compositionend',{data:'中文',bubbles:true}));
el.dispatchEvent(new InputEvent('input',{data:'中文',inputType:'insertText',bubbles:true}));
const clipboardData=new DataTransfer();clipboardData.setData('text/plain','paste secret');el.dispatchEvent(new ClipboardEvent('paste',{clipboardData,bubbles:true,cancelable:true}));
el.dispatchEvent(new KeyboardEvent('keydown',{key:'Backspace',bubbles:true,cancelable:true}));
el.dispatchEvent(new KeyboardEvent('keydown',{key:'Tab',bubbles:true,cancelable:true}));
});
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();
assert.equal(f.calls.filter(c=>c.path.endsWith('/input')).length,1);
assert.equal(f.calls.some(c=>c.path.endsWith('/save')),false);
f.releaseInput();await f.page.getByText('已连接',{exact:true}).waitFor();
const actions=f.calls.filter(c=>c.path.endsWith('/input')).map(c=>c.body);
// Browser click coordinates round to whole CSS pixels: at half scale, allow two remote pixels.
assert.equal(actions[0].type,'click');assert.ok(Math.abs(actions[0].x-640)<=2,JSON.stringify(actions[0]));assert.ok(Math.abs(actions[0].y-400)<=2,JSON.stringify(actions[0]));
assert.deepEqual(actions.slice(1),[{type:'text',text:'中文'},{type:'text',text:'paste secret'},{type:'key',key:'Backspace'},{type:'key',key:'Tab'}]);
assert.ok(f.calls.findIndex(c=>c.path.endsWith('/save'))>f.calls.map(c=>c.path).lastIndexOf('/api/connections/one/login/input'));
assert.equal(await f.page.locator('[data-bpm-input]').inputValue(),'');
assert.equal(await f.page.evaluate(()=>localStorage.length),0);
});
test('remote surface forwards physical keyboard events without relying on a hidden editable element',async t=>{
const f=await fixture(t);await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
await f.page.locator('[data-bpm-frame]').waitFor({state:'visible'});
const surface=f.page.locator('.bpm-screen');
await surface.focus();await f.page.keyboard.type('Ab-1');await f.page.keyboard.press('Backspace');
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();await f.page.getByText('连接已检查并保存。',{exact:true}).waitFor();
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/input')).map(c=>c.body),[{type:'text',text:'A'},{type:'text',text:'b'},{type:'text',text:'-'},{type:'text',text:'1'},{type:'key',key:'Backspace'}]);
const keyboard=f.page.getByLabel('远程登录输入',{exact:true});
const screenBounds=await surface.boundingBox(),bounds=await keyboard.boundingBox();
assert.ok(bounds.y>=screenBounds.y && bounds.y+bounds.height<=screenBounds.y+screenBounds.height,'IME capture stays inside the remote picture, with no input field below it');
assert.equal(await keyboard.evaluate(el=>getComputedStyle(el).opacity),'0','typing must not expose a second editor');
await f.page.locator('[data-bpm-frame]').click({position:{x:110,y:90}});
await f.page.keyboard.type('xy');await f.page.keyboard.press('Tab');await f.page.keyboard.insertText('中文输入');
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();
await f.page.waitForFunction(()=>document.querySelector('[data-bpm-input]')?.value==='');
assert.equal(f.calls.filter(c=>c.body?.type==='text'&&c.body.text==='中文输入').length,1);
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/input')).slice(6).map(c=>c.body),[{type:'text',text:'x'},{type:'text',text:'y'},{type:'key',key:'Tab'},{type:'text',text:'中文输入'}]);
});
test('disposal during a pending open closes the late lease without mounting a frame',async t=>{
const f=await fixture(t,{holdOpen:true});await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
await f.page.waitForFunction(()=>document.querySelector('button[data-login]')?.disabled);
await f.page.evaluate(()=>{window.BpmLogin.dispose();});f.releaseOpen();
await f.page.waitForTimeout(150);
assert.equal(f.calls.filter(c=>c.path.endsWith('/close')).length,1);
assert.equal(f.calls.filter(c=>c.path.endsWith('/frame')).length,0);
});
test('frame polling never overlaps and disposal stops polling and revokes the displayed URL',async t=>{
const f=await fixture(t,{holdFrame:true});
await f.page.evaluate(()=>{window.revoked=[];const revoke=URL.revokeObjectURL.bind(URL);URL.revokeObjectURL=u=>{window.revoked.push(u);revoke(u);};});
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();await f.page.waitForTimeout(1200);
assert.equal(f.calls.filter(c=>c.path.endsWith('/frame')).length,1);assert.equal(f.maxFrames(),1);
f.releaseFrame();await f.page.waitForFunction(()=>document.querySelector('[data-bpm-frame]')?.src.startsWith('blob:'));
await f.page.evaluate(()=>window.BpmLogin.dispose());const count=f.calls.filter(c=>c.path.endsWith('/frame')).length;
await f.page.waitForTimeout(800);assert.equal(f.calls.filter(c=>c.path.endsWith('/frame')).length,count);
assert.ok((await f.page.evaluate(()=>window.revoked)).length>=1);
});
test('only the connection owner operator can login and check; admin creation remains separate',async t=>{
const connections=[{id:'mine',name:'我的连接',owner:'alice',status:'unchecked'},{id:'other',name:'其他连接',owner:'bob',status:'connected'},{id:'off',name:'停用连接',owner:'alice',status:'disabled'}];
const f=await fixture(t,{connections});
assert.equal(await f.page.getByRole('button',{name:'远程登录',exact:true}).count(),1);
assert.equal(await f.page.getByRole('button',{name:'检查连接',exact:true}).count(),1);
assert.equal(await f.page.getByRole('button',{name:'创建连接',exact:true}).count(),0);
assert.equal(await f.page.getByRole('button',{name:'停用连接',exact:true}).count(),0);
const viewer=await fixture(t,{connections,user:{username:'alice',role:'viewer'}});
assert.equal(await viewer.page.getByRole('button',{name:'远程登录',exact:true}).count(),0);
});
test('leaving during save waits for verification before releasing the browser',async t=>{
const f=await fixture(t,{holdSave:true});await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();
await f.page.waitForTimeout(70);await f.page.evaluate(()=>{window.BpmLogin.dispose();});
await f.page.waitForTimeout(100);assert.equal(f.calls.filter(c=>c.path.endsWith('/close')).length,0);
f.releaseSave();await f.page.waitForTimeout(150);assert.equal(f.calls.filter(c=>c.path.endsWith('/close')).length,1);
});
test('narrow screens keep the frame inside the page and native typing forwards text once',async t=>{
const f=await fixture(t);await f.page.setViewportSize({width:360,height:800});
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
const frame=f.page.locator('[data-bpm-frame]');await frame.waitFor({state:'visible'});await frame.click({position:{x:50,y:50}});
await f.page.keyboard.type('abc');await f.page.keyboard.press('Backspace');await f.page.keyboard.press('Tab');
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();await f.page.getByText('已连接',{exact:true}).waitFor();
assert.deepEqual(f.calls.filter(c=>c.body?.type==='text').map(c=>c.body.text),['a','b','c']);
assert.ok(await f.page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth));
});
test('refresh and logout release BPM control before rendering or dropping authentication',async()=>{
const vm=require('node:vm'),events=[],elements=new Map();
const element=id=>{if(!elements.has(id))elements.set(id,{innerHTML:'',textContent:'',classList:{remove(){}},querySelector(){return {disabled:false};}});return elements.get(id);};
const context=vm.createContext({Intl,setTimeout,clearInterval,location:{hash:'#overview'},document:{querySelector:element,querySelectorAll:()=>[]},window:{addEventListener(){},BpmLogin:{dispose:async()=>events.push('release')},WorkspaceViews:{overview:async()=>events.push('render')}}});
const source=fs.readFileSync(path.join(__dirname,'../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
vm.runInContext(source,context);
await vm.runInContext("currentUser={username:'alice',role:'admin'};renderView()",context);
assert.deepEqual(events,['release','render']);events.length=0;
vm.runInContext("shell();api=async route=>events.push(route);boot=async()=>{}",Object.assign(context,{events}));
await element('#logout').onclick();assert.deepEqual(events,['release','/logout']);
});
test('an expired login request rejects without waiting on its own remote cleanup',async()=>{
const vm=require('node:vm'),events=[];
const context=vm.createContext({Intl,setTimeout,fetch:async()=>({status:401,ok:false,json:async()=>({error:'请重新登录。'})}),document:{querySelector:()=>({})},window:{addEventListener(){},BpmLogin:{dispose:()=>new Promise(()=>{})}},events});
const source=fs.readFileSync(path.join(__dirname,'../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');vm.runInContext(source,context);
const pending=vm.runInContext("currentUser={username:'alice',role:'operator'};boot=async()=>events.push('login');api('/connections/one/login/open',{}).then(()=> 'resolved',()=> 'rejected')",context);
assert.equal(await Promise.race([pending,new Promise(resolve=>setTimeout(()=>resolve('pending'),100))]),'rejected');assert.deepEqual(events,['login']);
});
for(const pendingAction of ['open','save'])test(`document unload sends authenticated close while ${pendingAction} is pending`,async t=>{
const calls=[];let finishPending=()=>{},pendingStarted;
const started=new Promise(resolve=>pendingStarted=resolve);
const appSource=fs.readFileSync(path.join(__dirname,'../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
const fixtureServer=http.createServer(async(req,res)=>{
const requestPath=new URL(req.url,'http://localhost').pathname;
if(requestPath==='/bpm.js'||requestPath==='/app.js'){res.setHeader('Content-Type','application/javascript; charset=utf-8');return res.end(requestPath==='/bpm.js'?fs.readFileSync(source):appSource);}
if(!requestPath.startsWith('/api/')){res.setHeader('Content-Type','text/html; charset=utf-8');return res.end('<div id="app"></div><div id="root"></div><script src="/bpm.js"></script><script src="/app.js"></script>');}
let body='';for await(const chunk of req)body+=chunk;
calls.push({path:requestPath,body,cookie:req.headers.cookie,origin:req.headers.origin});
res.setHeader('Content-Type','application/json');
if(requestPath.endsWith('/'+pendingAction)){finishPending=()=>res.end('{}');pendingStarted();return;}
if(requestPath.endsWith('/frame')){res.setHeader('Content-Type','image/jpeg');return res.end(jpeg);}
if(requestPath.endsWith('/open'))return res.end(JSON.stringify({active:true,viewport:{width:1280,height:800},expiresAt:new Date(Date.now()+600000).toISOString(),host:'bpmn.skyworthdigital.com'}));
if(requestPath==='/api/workspace')return res.end(JSON.stringify({members:[],capabilities:{remoteLogin:true},connections:[{id:'one',name:'业务连接',owner:'alice',status:'disconnected'}]}));
res.end('{}');
});
await new Promise(resolve=>fixtureServer.listen(0,'127.0.0.1',resolve));
const fixtureBase=`http://127.0.0.1:${fixtureServer.address().port}`;
const page=await browser.newPage();t.after(async()=>{finishPending();await page.close();fixtureServer.closeAllConnections();await new Promise(resolve=>fixtureServer.close(resolve));});
await page.context().addCookies([{name:'session',value:'fixture-session',url:fixtureBase}]);await page.goto(fixtureBase);
await page.evaluate(async()=>window.BpmLogin.mount(document.querySelector('#root'),{api,esc:v=>String(v??''),formatDate:v=>v||'—',notify:()=>{},user:{username:'alice',role:'operator'},isActive:()=>true}));
await page.getByRole('button',{name:'远程登录',exact:true}).click();
if(pendingAction==='save')await page.getByRole('button',{name:'检查并保存',exact:true}).click();
await started;await page.goto(fixtureBase+'/exit');
const deadline=Date.now()+700;while(!calls.some(c=>c.path.endsWith('/close'))&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,20));
const close=calls.find(c=>c.path.endsWith('/close'));assert.ok(close,'unload must dispatch close before the held request completes');
assert.equal(close.body,'{}');assert.match(close.cookie,/session=fixture-session/);assert.equal(close.origin,fixtureBase);
});
+84
View File
@@ -0,0 +1,84 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
test('managed accounts use an encrypted SQLite registry with uniqueness across connections and restarts',async t=>{
const {BpmVault}=require('../src/bpm-vault.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-accounts-db-'));
const vault=new BpmVault({stateDir:dir}),second=new BpmVault({stateDir:dir});
t.after(async()=>{vault.destroy();second.destroy();await fs.rm(dir,{recursive:true,force:true});});
await vault.write('account:a',{username:' Fixture.User ',password:'Secret-first-value',updatedAt:'2026-10-16T00:00:00Z'});
await assert.rejects(second.write('account:b',{username:'fixture.USER',password:'Secret-second-value'}),e=>e.status===409&&e.code==='BPM_ACCOUNT_DUPLICATE');
assert.equal(await second.read('account:b'),null);
assert.equal((await second.read('account:a')).password,'Secret-first-value');
const {DatabaseSync}=require('node:sqlite');const db=new DatabaseSync(path.join(dir,'accounts.sqlite'),{readOnly:true});
try{assert.equal(db.prepare('SELECT count(*) AS n FROM accounts').get().n,1);}finally{db.close();}
for(const file of await fs.readdir(dir))if(/sqlite/.test(file)){const bytes=await fs.readFile(path.join(dir,file));assert.equal(bytes.includes(Buffer.from('Secret-first-value')),false);assert.equal(bytes.includes(Buffer.from('Fixture.User')),false);}
await vault.write('account:a',{username:'fixture.user',password:'Updated-secret'});
assert.deepEqual(await second.accountAvailability('b',' FIXTURE.USER '),{available:false});
assert.deepEqual(await second.accountAvailability('a','FIXTURE.USER'),{available:true});
await vault.remove('account:a');await second.write('account:b',{username:'fixture.user',password:'Now-available'});
second.destroy();const restarted=new BpmVault({stateDir:dir});
try{assert.equal((await restarted.read('account:b')).password,'Now-available');await assert.rejects(restarted.write('account:c',{username:'Fixture.User',password:'Duplicate'}),e=>e.status===409);}finally{restarted.destroy();}
});
test('simultaneous account saves admit only one normalized username and preserve other records',async t=>{
const {BpmVault}=require('../src/bpm-vault.cjs');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-unique-'));
const vault=new BpmVault({stateDir:dir}),other=new BpmVault({stateDir:dir});
t.after(async()=>{vault.destroy();other.destroy();await fs.rm(dir,{recursive:true,force:true});});
await vault.write('account:existing',{username:'different',password:'keep-this'});
const results=await Promise.allSettled([vault.write('account:a',{username:'Same.User',password:'one'}),other.write('account:b',{username:' same.user ',password:'two'})]);
assert.equal(results.filter(r=>r.status==='fulfilled').length,1);assert.equal(results.find(r=>r.status==='rejected').reason.status,409);
await assert.rejects(vault.write('account:existing',{username:'SAME.USER',password:'replacement'}),e=>e.status===409);
assert.equal((await vault.read('account:existing')).password,'keep-this');
});
test('legacy encrypted account files migrate atomically and conflicting legacy files are retained',async t=>{
const {BpmVault}=require('../src/bpm-vault.cjs'),crypto=require('node:crypto');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'bpm-legacy-'));
const vault=new BpmVault({stateDir:dir});t.after(async()=>{vault.destroy();await fs.rm(dir,{recursive:true,force:true});});
const legacy=async(id,username)=>{const key='account:'+id,iv=crypto.randomBytes(12),cipher=crypto.createCipheriv('aes-256-gcm',vault.ensureKey(),iv);cipher.setAAD(Buffer.from(key));const data=Buffer.concat([cipher.update(JSON.stringify({username,password:'legacy-secret',nextAttemptAt:'2030-01-01T00:00:00Z'})),cipher.final()]);await fs.writeFile(vault.filename(key),Buffer.concat([Buffer.from('BPM1'),iv,cipher.getAuthTag(),data]));};
await legacy('one','First.User');await legacy('two','first.user');
await assert.rejects(vault.migrateAccounts(['one','two']),e=>e.status===409);
assert.equal((await fs.stat(vault.filename('account:one'))).isFile(),true);assert.equal((await fs.stat(vault.filename('account:two'))).isFile(),true);
assert.deepEqual(await vault.accountAvailability('other','FIRST.USER'),{available:true},'failed batch must not partially claim the account');
await legacy('two','Second.User');await vault.migrateAccounts(['one','two']);
assert.equal((await vault.read('account:one')).nextAttemptAt,'2030-01-01T00:00:00Z');assert.equal((await vault.read('account:two')).password,'legacy-secret');
await assert.rejects(fs.stat(vault.filename('account:one')),e=>e.code==='ENOENT');
assert.deepEqual(await vault.accountAvailability('third','second.user'),{available:false});
});
test('vault encrypts state, survives restart, rejects corruption and keeps connection isolation', async t => {
const { BpmVault } = require('../src/bpm-vault.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-vault-'));
t.after(() => fs.rm(dir, { recursive: true, force: true }));
const vault = new BpmVault({ stateDir: dir });
const state = { cookies: [{ name: 'session', value: 'private-cookie-value' }], sessionStorage: { 'https://bpm.example': { account: 'secret-user' } } };
await vault.write('connection-a', state);
assert.deepEqual(await new BpmVault({ stateDir: dir }).read('connection-a'), state);
assert.equal(await vault.read('connection-b'), null);
const filename = (await fs.readdir(dir)).find(file => file.endsWith('.enc'));
const encrypted = await fs.readFile(path.join(dir, filename));
assert.equal(encrypted.includes(Buffer.from('private-cookie-value')), false);
assert.equal(encrypted.includes(Buffer.from('secret-user')), false);
encrypted[encrypted.length - 1] ^= 1;
await fs.writeFile(path.join(dir, filename), encrypted);
await assert.rejects(vault.read('connection-a'), error => error.status === 503 && !error.message.includes('private-cookie'));
await vault.remove('connection-a');
assert.equal(await vault.read('connection-a'), null);
});
test('vault binds ciphertext to connection identity and never leaves plaintext temporary files', async t => {
const { BpmVault } = require('../src/bpm-vault.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'bpm-vault-'));
t.after(() => fs.rm(dir, { recursive: true, force: true }));
const vault = new BpmVault({ stateDir: dir });
await vault.write('a', { secret: 'alpha' });
await vault.write('b', { secret: 'bravo' });
const crypto = require('node:crypto');
const filename = id => path.join(dir, crypto.createHash('sha256').update(id).digest('hex') + '.enc');
await fs.copyFile(filename('a'), filename('b'));
await assert.rejects(vault.read('b'), error => error.status === 503);
assert.equal((await fs.readdir(dir)).some(file => file.endsWith('.tmp')), false);
});
+25
View File
@@ -0,0 +1,25 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const load = () => { try { return require('../extension/capture.js'); } catch(e) { if(e.code === 'MODULE_NOT_FOUND') return {}; throw e; } };
test('capture keeps live values and names while excluding hidden secrets and actions', async () => {
const { captureOrder } = load();
assert.equal(typeof captureOrder, 'function', 'browser capture is not implemented');
const { loadPlaywright, browserOptions } = require('../src/runtime.cjs');
const browser = await loadPlaywright().chromium.launch(browserOptions());
try {
const page = await browser.newPage();
await page.setContent(`<form><input type="hidden" value="SECRET_VIEWSTATE"><input style="display:none" value="SECRET_HIDDEN"><div style="display:none">SECRET_PARENT<input value="SECRET_CHILD"></div>
<input xdatabind="OFR_WY_Applicant.OrderNum" value="900001"><input xdatabind="OFR_WY_BInfo.ProductNum" value="DEMO-PROJECT-001"><input xdatabind="OFR_WY_BInfo.ProductModelNEW" value="DEMO-MODEL"><input xdatabind="OFR_WY_Applicant.SN" value="DEMO-CHANGE-001">
<textarea id="notes">original</textarea><input type="password" value="SECRET_PASSWORD"><button onclick="alert(1)">提交</button><input type="checkbox" checked><script>window.fixture=1</script><div printout="false">工作流操作</div><iframe src="about:blank"></iframe></form>`);
await page.locator('#notes').fill('最新备注 <数量20>');
const captured = await page.evaluate(captureOrder);
assert.deepEqual(captured.metadata, { order:'900001', project:'DEMO-PROJECT-001', model:'DEMO-MODEL', serial:'DEMO-CHANGE-001' });
assert.match(captured.html, /最新备注 &lt;数量20&gt;/);
assert.match(captured.html, /☑/);
assert.doesNotMatch(captured.html, /SECRET_|<script|<iframe|onclick|工作流操作|提交/);
assert.equal(captured.missing.length, 0);
await page.locator('[xdatabind$="ProductNum"]').fill('');
assert.deepEqual((await page.evaluate(captureOrder)).missing, ['项目编号']);
} finally { await browser.close(); }
});
+38
View File
@@ -0,0 +1,38 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const core = (() => { try { return require('../src/exporter.cjs'); } catch (e) { if (e.code === 'MODULE_NOT_FOUND') return {}; throw e; } })();
const metadata = { order: '900001', project: 'DEMO-PROJECT-001', model: 'DEMO-MODEL', serial: 'DEMO-CHANGE-001' };
test('filename uses all four identifiers in the agreed order', () => {
assert.equal(typeof core.buildFilename, 'function', 'export core is not implemented');
assert.equal(core.buildFilename(metadata), '900001_DEMO-PROJECT-001_DEMO-MODEL_DEMO-CHANGE-001.pdf');
});
test('missing identifiers stop export instead of silently guessing', () => {
assert.equal(typeof core.buildFilename, 'function');
assert.throws(() => core.buildFilename({ ...metadata, project: ' ' }), /项目/);
});
test('filename cannot escape output directory or exceed Windows limits', () => {
assert.equal(typeof core.buildFilename, 'function');
const filename = core.buildFilename({ ...metadata, order: '../../900:001', project: 'A'.repeat(300) });
assert.equal(path.basename(filename), filename);
assert.ok(!/[<>:"/\\|?*\x00-\x1f]/.test(filename));
assert.ok(filename.length <= 200);
assert.ok(filename.endsWith('_DEMO-MODEL_DEMO-CHANGE-001.pdf'));
});
test('offline rendering creates PDF bytes and repeated exports preserve previous file', async () => {
assert.equal(typeof core.renderSnapshot, 'function');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'order-tool-test-'));
try {
const snapshot = { metadata, html: '<form><h1>订单通知书 900001</h1><p>DEMO-PROJECT-001</p><script>location.href="https://example.com"</script><img src="https://example.com/private.png"></form>', styles: ['body{font-size:16px}'], width: 1264 };
const first = await core.renderSnapshot(snapshot, { outputDir: dir });
const original = await fs.readFile(first.path);
assert.equal(original.subarray(0, 5).toString(), '%PDF-');
const second = await core.renderSnapshot(snapshot, { outputDir: dir });
assert.equal(path.basename(second.path), '900001_DEMO-PROJECT-001_DEMO-MODEL_DEMO-CHANGE-001 (2).pdf');
assert.deepEqual(await fs.readFile(first.path), original);
assert.ok(first.bytes > 1000);
} finally { await fs.rm(dir, { recursive: true, force: true }); }
});
+31
View File
@@ -0,0 +1,31 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
let createDashboard;try{({createDashboard}=require('../src/dashboard.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
test('dashboard requires login, persists settings and enforces viewer and same-origin restrictions',async t=>{
assert.equal(typeof createDashboard,'function','web dashboard server not implemented');
const {Store}=require('../src/dashboard-store.cjs');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'dashboard-http-'));const store=new Store(path.join(dir,'data'));
const outputDir=path.join(dir,'pdf');fs.mkdirSync(outputDir);fs.writeFileSync(path.join(outputDir,'ok.pdf'),'%PDF-test');fs.writeFileSync(path.join(dir,'secret.pdf'),'%PDF-private');
const server=createDashboard({store,outputDir});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
t.after(async()=>{await new Promise(resolve=>server.close(resolve));fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port;
const call=(url,body,cookie,origin=base)=>fetch(base+url,{method:body?'POST':'GET',headers:{...(body?{'Content-Type':'application/json',Origin:origin}:{}),...(cookie?{Cookie:cookie}:{})},body:body?JSON.stringify(body):undefined});
assert.equal((await call('/api/overview')).status,401);
assert.equal((await call('/api/bootstrap',{username:'admin',password:'Test-password-123'},null,'https://evil.example')).status,403);
const setup=await call('/api/bootstrap',{username:'admin',password:'Test-password-123'});assert.equal(setup.status,201);const cookie=setup.headers.get('set-cookie').split(';')[0];
const overview=await (await call('/api/overview',null,cookie)).json();assert.equal(overview.automation.enabled,false);assert.equal(overview.stats.total,0);
const original=await (await call('/api/settings',null,cookie)).json();
assert.equal((await call('/api/settings',{version:original.version,schedule:{...original.schedule,times:['10:00','16:00']}},cookie)).status,200);
assert.deepEqual(new Store(path.join(dir,'data')).settings().schedule.times,['10:00','16:00']);
assert.equal((await call('/api/settings',{version:original.version,schedule:original.schedule},cookie)).status,409);
assert.equal((await call('/api/users',{username:'viewer',password:'Viewer-password-123',role:'viewer'},cookie)).status,201);
const login=await call('/api/login',{username:'viewer',password:'Viewer-password-123'});const reader=login.headers.get('set-cookie').split(';')[0];
assert.equal((await call('/api/settings',{version:2},reader)).status,403);
assert.equal((await call('/api/settings',{version:2},cookie,'https://evil.example')).status,403);
assert.equal((await call('/api/users',null,reader)).status,403);
store.recordJob({jobId:'inside',status:'success',path:path.join(outputDir,'ok.pdf'),filename:'ok.pdf'});
store.recordJob({jobId:'outside',status:'success',path:path.join(dir,'secret.pdf'),filename:'secret.pdf'});
assert.equal((await call('/api/jobs/inside/file',null,reader)).status,200);
assert.equal((await call('/api/jobs/outside/file',null,reader)).status,404);
assert.ok(!(await (await call('/api/jobs',null,reader)).text()).includes(dir.replaceAll('\\','\\\\')));
assert.equal((await call('/vendor/tabler.css')).status,200);
});
+17
View File
@@ -0,0 +1,17 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const vm=require('node:vm');
test('late overview response cannot overwrite a newly opened settings form',async()=>{
let resolve;
const container={innerHTML:'unsaved template draft'};
const context=vm.createContext({document:{querySelector:()=>({})},Intl,setTimeout,window:{addEventListener(){}},fetch(){throw Error('unexpected fetch');}});
const source=fs.readFileSync(require.resolve('../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
vm.runInContext(source,context);
context.pending=new Promise(r=>{resolve=r;});context.container=container;
vm.runInContext("api=()=>pending;currentUser={role:'admin'};",context);
const work=vm.runInContext('viewOverview(container,()=>false)',context);
resolve({stats:{total:0,completed:0,today:0,running:0,failed:0},connections:[],schedule:{times:[]},nextSlots:[],jobs:[],audit:[]});
await work;
assert.equal(container.innerHTML,'unsaved template draft');
});
+22
View File
@@ -0,0 +1,22 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
test('workbench sessions persist for thirty days, renew with activity and revoke without storing raw tokens',t=>{
let SessionStore;try{({SessionStore}=require('../src/dashboard-sessions.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
assert.equal(typeof SessionStore,'function','persistent workbench sessions missing');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'workbench-auth-'));let store;
t.after(()=>{store?.close();fs.rmSync(dir,{recursive:true,force:true});});
const day=86400000,now=Date.now();
store=new SessionStore(dir);const issued=store.issue('test-user',now);
assert.equal(issued.expires,now+30*day);assert.match(issued.token,/^[a-f0-9]{64}$/);
store.close();
assert.equal(fs.readFileSync(path.join(dir,'auth.sqlite')).includes(Buffer.from(issued.token)),false);
store=new SessionStore(dir);
const recovered=store.lookup(issued.token,now+29*day);
assert.equal(recovered.userId,'test-user');assert.equal(recovered.expires,now+59*day);assert.equal(recovered.renewed,true);
assert.equal(store.lookup('x'.repeat(64)),null);assert.equal(store.lookup(undefined),null);
store.revoke(issued.token);assert.equal(store.lookup(issued.token),null);
const expired=store.issue('test-user',now);assert.equal(store.lookup(expired.token,now+31*day),null);
});
+45
View File
@@ -0,0 +1,45 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
let Store, nextSlots;
try { ({Store}=require('../src/dashboard-store.cjs')); ({nextSlots}=require('../src/schedule.cjs')); } catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
function fixture(t){assert.equal(typeof Store,'function','dashboard store not implemented');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'dashboard-store-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));return {dir,store:new Store(dir)};}
test('configuration is persisted and stale edits cannot overwrite another colleague',t=>{
const {dir,store}=fixture(t);
const original=store.settings();
assert.equal(original.schedule.timezone,'Asia/Shanghai');
const updated=store.saveSettings({schedule:{...original.schedule,times:['10:30','16:45'],weekends:false}},original.version,'admin');
assert.deepEqual(new Store(dir).settings().schedule.times,['10:30','16:45']);
assert.throws(()=>store.saveSettings({schedule:original.schedule},original.version,'admin'),/已被其他人/);
assert.throws(()=>store.saveSettings({schedule:{...updated.schedule,times:['25:00','16:00']}},updated.version,'admin'),/时间/);
assert.throws(()=>store.saveSettings({schedule:{...updated.schedule,times:['09:00','09:00']}},updated.version,'admin'),/两个不同/);
});
test('admin bootstrap is one-time and credentials are hashed with usable roles',t=>{
const {dir,store}=fixture(t);
const admin=store.bootstrap('admin','Test-password-123');
assert.equal(admin.role,'admin');
assert.equal(store.authenticate('admin','wrong'),null);
assert.equal(store.authenticate('admin','Test-password-123').id,admin.id);
assert.throws(()=>store.bootstrap('second','Test-password-123'),/管理员/);
const reader=store.addUser({username:'reader',password:'Reader-password-123',role:'viewer'},admin.username);
assert.equal(reader.role,'viewer');
assert.ok(!JSON.stringify(reader).includes('passwordHash'));
assert.ok(!fs.readFileSync(path.join(dir,'state.json'),'utf8').includes('Test-password-123'));
});
test('export job records update in place and remain visible after restart',t=>{
const {dir,store}=fixture(t);
store.recordJob({jobId:'abc',status:'running',metadata:{order:'900001',project:'DEMO-PROJECT-001'}});
store.recordJob({jobId:'abc',status:'success',filename:'order.pdf',path:'C:/output/order.pdf',bytes:1234});
const jobs=new Store(dir).jobs();
assert.equal(jobs.length,1);
assert.equal(jobs[0].metadata.order,'900001');
assert.equal(jobs[0].status,'success');
});
test('next slots follow Shanghai time, weekend policy and exact slot boundary',()=>{
assert.equal(typeof nextSlots,'function','schedule calculation not implemented');
const schedule={times:['09:00','17:00'],weekends:false};
assert.deepEqual(nextSlots(schedule,new Date('2026-10-16T09:00:00Z'),2),['2026-10-19T01:00:00.000Z','2026-10-19T09:00:00.000Z']);
assert.deepEqual(nextSlots({...schedule,weekends:true},new Date('2026-10-16T08:59:00Z'),2),['2026-10-16T09:00:00.000Z','2026-10-17T01:00:00.000Z']);
});
+8
View File
@@ -0,0 +1,8 @@
// Local test fixture, never used by the production launcher. No BPM/mail access.
const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {Store}=require('../../src/dashboard-store.cjs');const {createDashboard}=require('../../src/dashboard.cjs');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-dashboard-ui-'));const store=new Store(dir);
store.bootstrap('preview','Preview-only-test-2026');
const server=createDashboard({store,outputDir:dir});
server.listen(18767,'127.0.0.1',()=>console.log('Isolated UI verification server: http://127.0.0.1:18767 (no business connectors)'));
process.once('SIGINT',()=>server.close(()=>{fs.rmSync(dir,{recursive:true,force:true});process.exit(0);}));
+15
View File
@@ -0,0 +1,15 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {Store}=require('../src/dashboard-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');const {parseTemplate}=require('../src/mail-parser.cjs');
const config={name:'邮箱',email:'orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
async function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-http-'));const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');const mailStore=new MailStore(path.join(dir,'mail'));const mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;const call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {mail,mailStore,call,login};}
test('mail API uses authentication, roles, same origin, redacted config and actual overview status',async t=>{
const {mailStore,call,login}=await setup(t);assert.equal((await call('/api/mail')).status,401);const admin=await login('admin'),reader=await login('reader');assert.equal((await call('/api/mail/channels',config,reader)).status,403);assert.equal((await call('/api/mail/channels',config,admin,'https://evil.test')).status,403);
const save=await call('/api/mail/channels',config,admin);assert.equal(save.status,201);const c=await save.json();assert.equal(c.smtp.password,undefined);assert.equal(c.smtp.hasPassword,true);const snapshot=await (await call('/api/mail',undefined,reader)).json();assert.equal(snapshot.channels.length,1);assert.doesNotMatch(JSON.stringify(snapshot),/Secret-mail/);assert.equal((await call('/api/mail/channels',config,admin)).status,409);
mailStore.setState(c.id,1,{smtp:true,imap:true});const overview=await (await call('/api/overview',undefined,admin)).json();assert.equal(overview.connections.find(x=>x.name==='邮件渠道').ready,true);
});
test('template preview is isolated, source attachments downloadable and confirmation requires admin',async t=>{
const {mailStore,call,login}=await setup(t);const c=mailStore.saveChannel(config);const raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n<table><tr><td>Hello</td></tr></table>');const d=mailStore.ingest(c.id,'1',1,await parseTemplate(raw,config),raw,1);const admin=await login('admin'),reader=await login('reader');
const view=await call('/api/mail/templates/'+d.id+'/preview',undefined,reader);assert.equal(view.status,200);assert.match(view.headers.get('content-security-policy'),/sandbox/);assert.match(await view.text(),/<table>/);const detail=await (await call('/api/mail/templates/'+d.id,undefined,admin)).json();assert.equal(detail.raw,undefined);
assert.equal((await call('/api/mail/templates/'+d.id+'/confirm',{version:1,subject:d.subject,scope:'',useText:false},reader)).status,403);assert.equal((await call('/api/mail/templates/'+d.id+'/confirm',{version:1,subject:d.subject,scope:'',useText:false},admin)).status,200);assert.equal(mailStore.active(c.id,'').id,d.id);
assert.equal((await call('/api/mail/templates/'+d.id+'/source',undefined,reader)).status,403);const source=await call('/api/mail/templates/'+d.id+'/source',undefined,admin);assert.equal(await source.text(),raw.toString());
});
+19
View File
@@ -0,0 +1,19 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const path=require('node:path');const os=require('node:os');const {SMTPServer}=require('smtp-server');const {simpleParser}=require('mailparser');
const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');
const config={name:'邮箱',email:'orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
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};}
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(){}};
const {store,service}=await fixture(t,{imapFactory:()=>client});const c=store.saveChannel(config);await service.poll(c.id);await service.poll(c.id);assert.equal(downloads,2);assert.equal(locks,0);assert.equal(store.templates().length,1);assert.equal(store.cursor(c.id).uid,3);assert.equal(store.receipts()[0].status,'rejected');
});
test('failed download does not advance cursor and overlapping polls are blocked; provider error never exposes secret',async t=>{
let release;const wait=new Promise(r=>release=r);const client={mailbox:{uidValidity:1n},on(){},async connect(){await wait;},async getMailboxLock(){return {release(){}};},async search(){return [9];},async fetchOne(uid,q){if(q.source)throw new Error(config.imap.password);return {size:100,envelope:{subject:'[模板]Notice'}};},async logout(){},close(){}};
const {store,service}=await fixture(t,{imapFactory:()=>client});const c=store.saveChannel(config);const first=service.poll(c.id);await assert.rejects(service.poll(c.id),e=>e.status===409);release();await assert.rejects(first,e=>!e.message.includes(config.imap.password));assert.deepEqual(store.cursor(c.id),{});assert.doesNotMatch(JSON.stringify(store.channels()),/Secret-mail/);
});
test('initial empty seven-day scan retains date boundary on future polls',async t=>{const queries=[];const client={mailbox:{uidValidity:1n},on(){},async connect(){},async getMailboxLock(){return {release(){}};},async search(q){queries.push(q);return [];},async logout(){},close(){}};const {store,service}=await fixture(t,{imapFactory:()=>client});const c=store.saveChannel(config);await service.poll(c.id);await service.poll(c.id);assert.ok(queries[0].since instanceof Date);assert.ok(queries[1].since instanceof Date);assert.ok(Math.abs(queries[0].since-queries[1].since)<5000);});
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/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');
});
+8
View File
@@ -0,0 +1,8 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');const {Store}=require('../src/dashboard-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');const {parseTemplate}=require('../src/mail-parser.cjs');
test('mail management saves a real config, previews template under CSP and confirms after review; narrow layout stays inside viewport',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const mailStore=new MailStore(path.join(dir,'mail')),mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});let browser;
t.after(async()=>{await browser?.close();await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1360,height:950}});const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/#mail');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加邮箱',exact:true}).click({timeout:5000});
await page.getByLabel('邮箱名称',{exact:true}).fill('通知邮箱');await page.getByLabel('邮箱地址',{exact:true}).fill('orders@company.test');for(const type of ['SMTP','IMAP']){await page.getByLabel(type+' 服务器',{exact:true}).fill(type.toLowerCase()+'.company.test');await page.getByLabel(type+' 登录账号',{exact:true}).fill('orders');await page.getByLabel(type+' 密码 / 授权码',{exact:true}).fill('Secret-mail-123');}await page.getByLabel('允许提交模板的发件人',{exact:true}).fill('author@company.test');await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('通知邮箱',{exact:true}).waitFor();assert.equal(mailStore.channels().length,1);
const c=mailStore.channels()[0],raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n<table><tr><td>Template body</td></tr></table><img src="https://tracker.test/1">');const draft=mailStore.ingest(c.id,'1',1,await parseTemplate(raw,c),raw,1);await page.getByRole('link',{name:'模板与收件群组',exact:true}).click();await page.getByRole('button',{name:'预览并确认',exact:true}).click();await page.frameLocator('iframe[title="邮件正文预览"]').getByText('Template body',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'pending');await page.getByLabel('发信标题',{exact:true}).fill('Confirmed notice');await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText('模板已确认生效。',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'active');
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
});
+46
View File
@@ -0,0 +1,46 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {parseTemplate,renderTemplate}=require('../src/mail-parser.cjs');
const {MailStore}=require('../src/mail-store.cjs');
const config={name:'通知邮箱',email:'Orders@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'orders',password:'Secret-mail-123'},imap:{host:'imap.company.test',port:993,security:'tls',user:'orders',password:'Secret-mail-123'},senders:['author@company.test'],enabled:true};
const eml=(subject='[模板][海外运营]订单 {{订单号}}',body='你好,{{产品线}}\r\n{{订单列表}}',from='author@company.test')=>Buffer.from(`From: ${from}\r\nTo: orders@company.test\r\nSubject: =?UTF-8?B?${Buffer.from(subject).toString('base64')}?=\r\nMessage-ID: <test1@company.test>\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n${body}`);
async function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-'));const store=new MailStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,store};}
test('template MIME decoding and subject scope use explicit command, not replies',async()=>{
const p=await parseTemplate(eml(),config);assert.equal(p.scope,'海外运营');assert.equal(p.subject,'订单 {{订单号}}');assert.match(p.text,/你好/);assert.equal(p.sender,'author@company.test');
assert.equal(await parseTemplate(eml('Re: [模板]订单'),config),null);assert.equal(await parseTemplate(eml('普通订单'),config),null);
await assert.rejects(parseTemplate(eml('[模板]订单','正文','stranger@company.test'),config),/发件人/);
await assert.rejects(parseTemplate(eml('[模板]订单','正文','author@company.test, stranger@company.test'),config),/发件人/);
await assert.rejects(parseTemplate(eml('[模板]订单 {{unknown}}'),config),/变量/);
for(const subject of ['[模板][]Notice','[模板][海外运营]','[模板][海外运营','[模板][ ]Notice'])await assert.rejects(parseTemplate(eml(subject),config),/主题|范围/);
await assert.rejects(parseTemplate(Buffer.alloc(10*1024*1024+1),config),/10 MB/);
});
test('HTML tables and inline images survive while scripts and remote tracking are removed; attachments retain bytes',async()=>{
const raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]HTML\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=x\r\n\r\n--x\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<table><tr><td>{{产品线}}</td></tr></table><script>alert(1)</script><img src="https://tracker.test/x"><img src="cid:logo"><a href="javascript:alert(1)">bad</a>\r\n--x\r\nContent-Type: image/png\r\nContent-ID: <logo>\r\nContent-Disposition: inline; filename="logo.png"\r\nContent-Transfer-Encoding: base64\r\n\r\naGVsbG8=\r\n--x\r\nContent-Type: application/pdf\r\nContent-Disposition: attachment; filename="notice.pdf"\r\nContent-Transfer-Encoding: base64\r\n\r\ncGRm\r\n--x--');
const p=await parseTemplate(raw,config);assert.match(p.html,/<table>/);assert.match(p.html,/data:image\/png;base64,aGVsbG8=/);assert.doesNotMatch(p.html,/tracker|script|javascript/i);assert.equal(p.attachments.length,2);assert.equal(p.attachments[1].content,'cGRm');
const r=renderTemplate(p,{'产品线':'<海外>','订单号':'1','日期':'2026-10-16','订单列表':'A\nB'});assert.match(r.html,/&lt;海外&gt;/);
});
test('mailbox secrets encrypted, identity unique, versions checked, blank secrets preserve existing value',async t=>{
const {dir,store}=await fixture(t);const c=store.saveChannel(config);assert.equal(c.email,'orders@company.test');assert.equal(c.smtp.hasPassword,true);assert.equal(c.smtp.password,undefined);
assert.throws(()=>store.saveChannel({...config,email:' ORDERS@company.test '}),e=>e.status===409);
const updated=store.saveChannel({...config,id:c.id,version:c.version,smtp:{...config.smtp,password:''},imap:{...config.imap,password:''}});assert.equal(store.channelSecret(c.id).smtp.password,config.smtp.password);
assert.throws(()=>store.saveChannel({...config,id:c.id,version:1}),e=>e.status===409);
for(const file of fs.readdirSync(dir).filter(f=>f.startsWith('mail.sqlite')))assert.equal(fs.readFileSync(path.join(dir,file)).includes(Buffer.from(config.smtp.password)),false);
assert.equal(updated.version,2);
store.setState(c.id,2,{smtp:true,imap:true});const toggled=store.saveChannel({...config,id:c.id,version:2,enabled:false});assert.equal(toggled.state.smtp,true);assert.equal(toggled.state.imap,true);
});
test('ingestion deduplicates restart and confirmation preserves active/history with stale-draft conflict',async t=>{
const {dir,store}=await fixture(t);const c=store.saveChannel(config);const p=await parseTemplate(eml(),config);
const d=store.ingest(c.id,'1',4,p,eml(),c.version);assert.equal(store.ingest(c.id,'1',4,p,eml(),c.version).id,d.id);assert.equal(store.cursor(c.id).uid,4);assert.equal(store.active(c.id,'海外运营'),null);
const active=store.confirm(d.id,{version:1,subject:p.subject,scope:p.scope,text:p.text,useText:false},'admin');assert.equal(active.status,'active');
const p2=await parseTemplate(eml('[模板][海外运营]新标题'),config);p2.messageId='<two@test>';
const d2=store.ingest(c.id,'1',5,p2,eml(),c.version);p2.messageId='<three@test>';const d3=store.ingest(c.id,'1',6,p2,eml(),c.version);
store.confirm(d2.id,{version:1,subject:p2.subject,scope:p2.scope,text:p2.text,useText:false},'admin');assert.throws(()=>store.confirm(d3.id,{version:1,subject:p2.subject,scope:p2.scope,text:p2.text,useText:false},'admin'),e=>e.status===409);
assert.equal(store.template(d.id).status,'archived');store.close();const reopened=new MailStore(dir);try{assert.equal(reopened.cursor(c.id).uid,6);assert.equal(reopened.templates().length,3);assert.equal(reopened.channelSecret(c.id).smtp.password,config.smtp.password);}finally{reopened.close();}
});
test('source message duplicates under new UID and epoch never generate new version; changed config rejects old poll commits',async t=>{
const {store}=await fixture(t);const c=store.saveChannel(config),p=await parseTemplate(eml(),config);const first=store.ingest(c.id,'1',3,p,eml(),1);assert.equal(store.ingest(c.id,'2',99,p,eml(),1).id,first.id);assert.equal(store.templates().length,1);
store.saveChannel({...config,id:c.id,version:1,enabled:false});assert.throws(()=>store.ingest(c.id,'2',100,p,eml(),1),e=>e.status===409);assert.equal(store.cursor(c.id).uid,99);
});
module.exports={config,eml};
test('repeated CID references are rejected before expanding to unbounded HTML',()=>{const {cleanHtml}=require('../src/mail-parser.cjs');assert.throws(()=>cleanHtml('<img src="cid:logo">'.repeat(200),[{cid:'logo',contentType:'image/png',content:Buffer.alloc(100000).toString('base64')}]),e=>e.status===400&&/内嵌图片/.test(e.message));});
test('outgoing embedded images use MIME content IDs and template lists never decode raw messages',async t=>{const {store}=await fixture(t);const c=store.saveChannel(config);const parsed={subject:'Notice',scope:'',text:'Image',html:'<img src="data:image/png;base64,aGVsbG8=">',sender:'author@company.test',attachments:[{filename:'a.png',cid:'logo',contentType:'image/png',content:'aGVsbG8=',inline:true,size:5}]};const d=store.ingest(c.id,'1',1,parsed,Buffer.from('raw'),1);assert.match(renderTemplate(parsed,{}).html,/src="cid:logo"/);const decode=store.decode;store.decode=()=>{throw new Error('must not decode payload');};try{assert.equal(store.templates()[0].id,d.id);}finally{store.decode=decode;}});
test('legacy draft can be assigned once to a real mailbox without losing body',async t=>{const {store}=await fixture(t);const c=store.saveChannel(config);store.migrateLegacy({subject:'旧草稿',body:'保留正文'});const d=store.templates()[0];const saved=store.confirm(d.id,{version:1,channelId:c.id,subject:'正式标题',scope:'',useText:false},'admin');assert.equal(saved.channelId,c.id);assert.equal(saved.text,'保留正文');assert.equal(store.active(c.id,'').id,d.id);store.migrateLegacy({subject:'旧草稿',body:'保留正文'});assert.equal(store.templates().length,1);});
+35
View File
@@ -0,0 +1,35 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const os=require('node:os');
const path=require('node:path');
let startPreview;
try { ({startPreview}=require('../scripts/preview.cjs')); } catch(error) { if(error.code!=='MODULE_NOT_FOUND')throw error; }
test('isolated preview signs in locally with fictional workspace data and survives restart',async t=>{
assert.equal(typeof startPreview,'function','isolated preview runtime not implemented');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'framework-preview-'));
let runtime;
t.after(async()=>{if(runtime)await runtime.close();fs.rmSync(dir,{recursive:true,force:true});});
runtime=await startPreview({stateDir:dir,port:0});
assert.equal(runtime.server.address().address,'127.0.0.1');
const base='http://127.0.0.1:'+runtime.server.address().port;
const status=await (await fetch(base+'/api/bootstrap/status')).json();
assert.equal(status.preview,true);
const login=await fetch(base+'/api/preview-login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:'{}'});
assert.equal(login.status,200);
const cookie=login.headers.get('set-cookie').split(';')[0];
const response=await fetch(base+'/api/workspace',{headers:{Cookie:cookie}});
assert.equal(response.status,200);
const data=await response.json();
assert.ok(data.exceptions.length>=2);
assert.ok(data.exceptions.every(item=>item.title.includes('演示')));
assert.equal(data.capabilities.automaticProcessing,false);
assert.equal(data.capabilities.remoteLogin,false);
assert.equal(data.connections[0].status,'disconnected');
assert.ok(!JSON.stringify(data).includes('passwordHash'));
const ids=data.exceptions.map(item=>item.id);
await runtime.close();runtime=null;
runtime=await startPreview({stateDir:dir,port:0});
assert.deepEqual(runtime.workspace.snapshot(runtime.store.users()).exceptions.map(item=>item.id),ids);
});
+66
View File
@@ -0,0 +1,66 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const net = require('node:net');
const serverModule = (() => { try { return require('../src/server.cjs'); } catch(e) { if(e.code === 'MODULE_NOT_FOUND') return {}; throw e; } })();
const origin = 'chrome-extension://' + 'a'.repeat(32);
test('loopback API rejects web origins, unpaired callers and oversized bodies', async () => {
assert.equal(typeof serverModule.createServer, 'function', 'local API is not implemented');
const server = serverModule.createServer({ token: 'test-pairing-key', maxBodyBytes: 1024, outputDir: 'unused' });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const url = `http://127.0.0.1:${server.address().port}`;
try {
assert.equal((await fetch(url+'/health', {headers:{Origin:'https://evil.example','X-Order-Token':'test-pairing-key'}})).status, 403);
assert.equal((await fetch(url+'/health', {headers:{Origin:origin}})).status, 401);
const headers = { Origin:origin,'X-Order-Token':'test-pairing-key','Content-Type':'application/json' };
const good = await fetch(url+'/health', {headers});
assert.equal(good.status, 200);
assert.equal(good.headers.get('access-control-allow-origin'),origin);
assert.equal((await fetch(url+'/export',{method:'POST',headers,body:'x'.repeat(1025)})).status,413);
assert.equal((await fetch(url+'/export',{method:'POST',headers,body:'invalid json'})).status,400);
assert.equal((await fetch(url+'/export',{method:'POST',headers,body:JSON.stringify({html:'<p>x</p>'})})).status,400);
} finally { await new Promise(resolve=>server.close(resolve)); }
});
test('paired HTTP export returns a readable PDF saved to the configured directory', async () => {
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-http-test-'));
const server=serverModule.createServer({token:'test-pairing-key',outputDir:dir});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
try {
const response=await fetch(`http://127.0.0.1:${server.address().port}/export`,{method:'POST',headers:{Origin:origin,'X-Order-Token':'test-pairing-key','Content-Type':'application/json'},body:JSON.stringify({metadata:{order:'900001',project:'DEMO-PROJECT-001',model:'DEMO-MODEL',serial:'DEMO-CHANGE-001'},html:'<form><p>订单通知书测试</p></form>',styles:[]})});
assert.equal(response.status,202);
const accepted=await response.json();
assert.match(accepted.jobId,/^[a-f0-9]{32}$/);
let result;
const deadline=Date.now()+60000;
while (Date.now()<deadline) {
const status=await fetch(`http://127.0.0.1:${server.address().port}/jobs/${accepted.jobId}`,{headers:{Origin:origin,'X-Order-Token':'test-pairing-key'}});
result=await status.json();
if (result.status !== 'running') break;
await new Promise(resolve=>setTimeout(resolve,100));
}
assert.equal(result.status,'success');
assert.equal(result.filename,'900001_DEMO-PROJECT-001_DEMO-MODEL_DEMO-CHANGE-001.pdf');
assert.equal(path.dirname(result.path),dir);
assert.equal((await fs.readFile(result.path)).subarray(0,5).toString(),'%PDF-');
} finally {await new Promise(resolve=>server.close(resolve));await fs.rm(dir,{recursive:true,force:true});}
});
test('extension setup failure leaves no listening service behind', async () => {
assert.equal(typeof serverModule.startService,'function','startup failure cleanup is not implemented');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-start-test-'));
const probe=net.createServer();
await new Promise(resolve=>probe.listen(0,'127.0.0.1',resolve));
const port=probe.address().port;
await new Promise(resolve=>probe.close(resolve));
try {
const invalid=path.join(dir,'extension');
await fs.writeFile(invalid,'not a directory');
await assert.rejects(serverModule.startService({port,token:'test-key',outputDir:dir,extensionSourceDir:path.resolve(__dirname,'../extension'),installedExtension:invalid}));
const free=net.createServer();
await new Promise((resolve,reject)=>{free.once('error',reject);free.listen(port,'127.0.0.1',resolve);});
await new Promise(resolve=>free.close(resolve));
} finally {await fs.rm(dir,{recursive:true,force:true});}
});
+27
View File
@@ -0,0 +1,27 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const vm=require('node:vm');
const fs=require('node:fs/promises');
async function workerContext(saved) {
const storage={lastExport:saved};
const context=vm.createContext({
importScripts:()=>{},ORDER_LOCAL_CONFIG:{endpoint:'http://127.0.0.1:18765',token:'test'},AbortSignal,
chrome:{runtime:{onMessage:{addListener:()=>{}}},storage:{session:{get:async()=>storage,set:async value=>Object.assign(storage,value)}}},
fetch:async()=>({ok:true,json:async()=>({status:'success',filename:'saved.pdf',path:'output/saved.pdf',bytes:1000})})
});
vm.runInContext(await fs.readFile(require.resolve('../extension/worker.js'),'utf8'),context);
return context;
}
test('reopening popup after worker restart recovers a completed local job',async()=>{
const context=await workerContext({status:'running',jobId:'a'.repeat(32),message:'处理中'});
const result=await context.currentState();
assert.equal(result.status,'success');
assert.equal(result.filename,'saved.pdf');
});
test('interrupted capture without a job does not leave export permanently disabled',async()=>{
const context=await workerContext({status:'running',message:'处理中'});
const result=await context.currentState();
assert.equal(result.status,'error');
assert.match(result.message,/中断/);
});
+39
View File
@@ -0,0 +1,39 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
const {Store}=require('../src/dashboard-store.cjs');const {createDashboard}=require('../src/dashboard.cjs');let WorkspaceStore;try{({WorkspaceStore}=require('../src/workspace-store.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
const http=require('node:http');
function hostCall(base,route,host,body){return new Promise((resolve,reject)=>{const request=http.request(base+route,{method:body===undefined?'GET':'POST',headers:{Host:host,...(body===undefined?{}:{Origin:'http://'+host,'Content-Type':'application/json'})}},response=>{const chunks=[];response.on('data',chunk=>chunks.push(chunk));response.on('end',()=>resolve({status:response.statusCode,json:()=>JSON.parse(Buffer.concat(chunks).toString())}));});request.on('error',reject);request.end(body===undefined?undefined:JSON.stringify(body));});}
async function setup(t,preview=true){assert.equal(typeof WorkspaceStore,'function','workspace ledger is missing');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'workspace-http-'));const store=new Store(path.join(dir,'users'));const admin=store.bootstrap('admin','Test-password-123');store.addUser({username:'operator',password:'Test-password-123',role:'operator'},'admin');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');const workspace=new WorkspaceStore(path.join(dir,'workspace'));const server=createDashboard({store,workspace,outputDir:dir,...(preview?{previewUserId:admin.id}:{})});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));t.after(async()=>{await new Promise(resolve=>server.close(resolve));workspace.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;const call=(route,body,cookie,origin=base,host)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{}),...(host?{Host:host}:{})},body:body===undefined?undefined:JSON.stringify(body)});return {store,workspace,server,base,call};}
test('workspace API requires authentication and roles and preserves same-origin enforcement',async t=>{
const {call}=await setup(t);assert.equal((await call('/api/workspace')).status,401);assert.equal((await call('/api/preview-login',{},null,'https://evil.example')).status,403);
const login=await call('/api/preview-login',{});assert.equal(login.status,200);const cookie=login.headers.get('set-cookie').split(';')[0];
assert.equal((await (await call('/api/bootstrap/status')).json()).preview,true);assert.equal((await (await call('/api/me',undefined,cookie)).json()).preview,true);
const snapshot=await (await call('/api/workspace',undefined,cookie)).json();assert.deepEqual(snapshot.members.map(m=>m.username),['admin','operator','reader']);
assert.equal((await call('/api/calendar',{version:1,overrides:[]},cookie,'https://evil.example')).status,403);
assert.equal((await call('/api/calendar',{version:1,overrides:[]},cookie)).status,200);
const readerLogin=await call('/api/login',{username:'reader',password:'Test-password-123'});const reader=readerLogin.headers.get('set-cookie').split(';')[0];
assert.equal((await call('/api/workspace',undefined,reader)).status,200);assert.equal((await call('/api/exceptions',{title:'示例',component:'pdf',priority:'normal',description:'',owner:''},reader)).status,403);
const opLogin=await call('/api/login',{username:'operator',password:'Test-password-123'});const operator=opLogin.headers.get('set-cookie').split(';')[0];
assert.equal((await call('/api/connections',{name:'示例连接',owner:'operator'},operator)).status,403);assert.equal((await call('/api/supervisor',{version:1,defaultOwner:'operator',notifyChannel:'manual',maxAttempts:1},operator)).status,403);
const made=await call('/api/exceptions',{title:'示例',component:'pdf',priority:'normal',description:'',owner:''},operator);assert.equal(made.status,201);const item=await made.json();const claimed=await call('/api/exceptions/'+item.id+'/action',{version:1,action:'claim'},operator);assert.equal(claimed.status,200);assert.equal((await claimed.json()).owner,'operator');
assert.equal((await call('/api/connections',{name:'示例连接',owner:'operator'},cookie)).status,201);assert.equal((await call('/workspace.js')).status,200);
});
test('production dashboard cannot preview-login and preview rejects nonlocal Host even on loopback',async t=>{
const production=await setup(t,false);assert.equal((await (await production.call('/api/bootstrap/status')).json()).preview,false);assert.equal((await production.call('/api/preview-login',{})).status,404);
const preview=await setup(t);const host='attacker.example:'+preview.server.address().port;assert.equal((await hostCall(preview.base,'/api/bootstrap/status',host)).json().preview,false);assert.equal((await hostCall(preview.base,'/api/preview-login',host,{})).status,403);
});
test('existing overview slot preview honors saved pause dates without enabling execution',async t=>{
const {call}=await setup(t);const login=await call('/api/preview-login',{});const cookie=login.headers.get('set-cookie').split(';')[0];
const start=new Date();const overrides=[];for(let offset=0;offset<21;offset++){const date=new Date(start.getTime()+offset*86400000);overrides.push({date:new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date),kind:'pause',scan:false,send:false,note:'示例停发'});}
assert.equal((await call('/api/calendar',{version:1,overrides},cookie)).status,200);const overview=await (await call('/api/overview',undefined,cookie)).json();assert.equal(overview.automation.enabled,false);assert.ok(new Date(overview.nextSlots[0]).getTime()>start.getTime()+19*86400000,'overview ignored saved calendar pauses');
});
test('preview and production sessions coexist on one host and preview logout clears only its cookie',async t=>{
const production=await setup(t,false),preview=await setup(t);
const formalLogin=await production.call('/api/login',{username:'admin',password:'Test-password-123'});const formalCookie=formalLogin.headers.get('set-cookie').split(';')[0];
const previewLogin=await preview.call('/api/preview-login',{});const previewCookie=previewLogin.headers.get('set-cookie').split(';')[0];
assert.match(formalCookie,/^order_session=/);assert.match(previewCookie,/^order_preview_session=/);
const combined=formalCookie+'; '+previewCookie;
assert.equal((await production.call('/api/me',undefined,combined)).status,200);assert.equal((await preview.call('/api/me',undefined,combined)).status,200);
assert.equal((await preview.call('/api/me',undefined,formalCookie)).status,401);assert.equal((await production.call('/api/me',undefined,previewCookie)).status,401);
const logout=await preview.call('/api/logout',{},combined);assert.equal(logout.status,200);assert.match(logout.headers.get('set-cookie'),/^order_preview_session=;/);assert.match(logout.headers.get('set-cookie'),/Max-Age=0/);
assert.equal((await preview.call('/api/me',undefined,combined)).status,401);assert.equal((await production.call('/api/me',undefined,formalCookie)).status,200);
});
+69
View File
@@ -0,0 +1,69 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
let WorkspaceStore;try{({WorkspaceStore}=require('../src/workspace-store.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
const admin={id:'a',username:'admin',role:'admin'},alice={id:'b',username:'alice',role:'operator'},bob={id:'c',username:'bob',role:'operator'},viewer={id:'d',username:'reader',role:'viewer'};const members=[admin,alice,bob,viewer];
function setup(t){assert.equal(typeof WorkspaceStore,'function','workspace ledger is missing');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'workspace-'));let store=new WorkspaceStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,store};}
const exception={title:'虚构订单 PDF 缺失',component:'pdf',priority:'high',description:'示例核对事项',owner:''};
const bad=(fn,status=400)=>assert.throws(fn,error=>error.status===status);
test('only an admin can delete a disabled connection and deletion survives restart with audit intact',t=>{
const {store,dir}=setup(t);const item=store.createConnection({name:'待删除连接',owner:'alice'},admin,members);
bad(()=>store.deleteConnection(item.id,admin),409);
store.disableConnection(item.id,admin);
for(const actor of [alice,viewer])bad(()=>store.deleteConnection(item.id,actor),403);
assert.deepEqual(store.deleteConnection(item.id,admin),{id:item.id,deleted:true});
bad(()=>store.getConnection(item.id),404);
const reopened=new WorkspaceStore(dir);t.after(()=>reopened.close());
assert.equal(reopened.snapshot(members).connections.length,0);
assert.ok(reopened.snapshot(members).audit.some(row=>row.action==='删除连接'));
reopened.close();
});
test('workspace saves calendar and supervisor atomically across restart without leaking member credentials',t=>{
const {store,dir}=setup(t);const before=store.snapshot(members);assert.equal(before.calendar.version,1);
const saved=store.saveCalendar({version:1,overrides:[{date:'2026-10-17',kind:'workday',scan:true,send:true,note:'示例补班'}]},admin);assert.equal(saved.version,2);
bad(()=>store.saveCalendar({version:1,overrides:[]},admin),409);
for(const date of ['2026-02-30','2026-13-01','2026-1-01'])bad(()=>store.saveCalendar({version:2,overrides:[{date,kind:'pause',scan:false,send:false,note:''}]},admin));
bad(()=>store.saveCalendar({version:2,overrides:[null]},admin));bad(()=>store.saveCalendar({version:2,overrides:[{date:'2026-10-18',kind:'pause',scan:true,send:true,note:''}]},admin));
const policy=store.saveSupervisor({version:1,defaultOwner:'alice',notifyChannel:'manual',maxAttempts:2},admin,members);assert.equal(policy.version,2);
bad(()=>store.saveSupervisor({version:2,defaultOwner:'missing',notifyChannel:'manual',maxAttempts:2},admin,members));
bad(()=>store.saveSupervisor({version:2,defaultOwner:'alice',notifyChannel:'email',maxAttempts:2},admin,members));
bad(()=>store.saveSupervisor({version:2,defaultOwner:'alice',notifyChannel:'none',maxAttempts:4},admin,members));
const reopened=new WorkspaceStore(dir);t.after(()=>reopened.close());const snapshot=reopened.snapshot([...members.map(m=>({...m,passwordHash:'SENSITIVE',cookie:'COOKIE'}))]);
assert.deepEqual(snapshot.calendar,saved);assert.deepEqual(snapshot.supervisor,policy);assert.ok(snapshot.audit.length>=2);assert.ok(!JSON.stringify(snapshot).includes('SENSITIVE'));assert.ok(!JSON.stringify(snapshot).includes('COOKIE'));assert.deepEqual(snapshot.members[1],{username:'alice',role:'operator'});assert.deepEqual(snapshot.capabilities,{remoteLogin:false,zcode:false,automaticProcessing:false});reopened.close();
});
test('exception claims are atomic, ownership is enforced and resolution requires recorded evidence',t=>{
const {store,dir}=setup(t);const item=store.createException(exception,alice,members);const second=new WorkspaceStore(dir);t.after(()=>second.close());
const claimed=store.actOnException(item.id,{version:1,action:'claim'},alice,members);assert.equal(claimed.owner,'alice');assert.equal(claimed.status,'in_progress');
bad(()=>second.actOnException(item.id,{version:1,action:'claim'},bob,members),409);
bad(()=>store.actOnException(item.id,{version:2,action:'verify'},bob,members),403);
bad(()=>store.actOnException(item.id,{version:2,action:'transfer',owner:'bob',note:''},alice,members));
bad(()=>store.actOnException(item.id,{version:2,action:'transfer',owner:'reader',note:'交接'},alice,members));
const moved=store.actOnException(item.id,{version:2,action:'transfer',owner:'bob',note:'请核验导出'},alice,members);assert.equal(moved.owner,'bob');assert.equal(moved.history.at(-1).fromOwner,'alice');assert.equal(moved.history.at(-1).toOwner,'bob');
bad(()=>store.actOnException(item.id,{version:3,action:'resolve',note:'检查完成'},bob,members),409);
const verifying=store.actOnException(item.id,{version:3,action:'verify',note:'已补齐'},bob,members);assert.equal(verifying.status,'verifying');
bad(()=>store.actOnException(item.id,{version:4,action:'resolve',note:' '},bob,members));
const done=store.actOnException(item.id,{version:4,action:'resolve',note:'人工打开 PDF 确认内容完整'},bob,members);assert.equal(done.status,'resolved');assert.equal(done.history.at(-1).actor,'bob');
assert.equal(second.snapshot(members).exceptions[0].status,'resolved');
const reopened=store.actOnException(item.id,{version:5,action:'reopen',note:'发现新问题'},admin,members);assert.equal(reopened.status,'open');assert.equal(reopened.owner,'');second.close();
});
test('ledger rejects malformed input, invalid roles, unknown owners and forged connected state',t=>{
const {store}=setup(t);
bad(()=>store.saveCalendar({version:1,overrides:[]},alice),403);bad(()=>store.createException(exception,viewer,members),403);
for(const input of [null,[],{...exception,owner:'missing'},{...exception,owner:'reader'},{...exception,priority:'urgent'},{...exception,title:''}])bad(()=>store.createException(input,alice,members));
const item=store.createException(exception,alice,members);for(const version of [undefined,'1',0,-1,1.5])bad(()=>store.actOnException(item.id,{version,action:'claim'},alice,members));
bad(()=>store.createConnection({name:'示例连接',owner:'alice',status:'connected'},admin,members));bad(()=>store.createConnection({name:'示例连接',owner:'alice',url:'https://evil.example'},admin,members));
bad(()=>store.createConnection({name:'示例连接',owner:'alice'},alice,members),403);
const connection=store.createConnection({name:'示例连接',owner:'alice'},admin,members);assert.equal(connection.status,'disconnected');assert.equal(connection.mainUrl,'https://bpmn.skyworthdigital.com');assert.equal(connection.detailUrl,undefined);
assert.equal(store.disableConnection(connection.id,admin).status,'disabled');assert.ok(store.snapshot(members).audit.some(entry=>entry.action==='停用连接'));
});
test('calendar day overrides independently control scan and send and slots skip paused workdays',()=>{
const {nextSlots,dayPolicy}=require('../src/schedule.cjs');assert.equal(typeof dayPolicy,'function','day policy missing');
const schedule={times:['09:00','17:00'],weekends:false};const overrides=[{date:'2026-10-17',kind:'workday',scan:true,send:true,note:'补班'},{date:'2026-10-19',kind:'restday',scan:true,send:false,note:'只采集'}];
assert.deepEqual(dayPolicy('2026-10-18',schedule,overrides),{scan:false,send:false,kind:'restday',note:''});assert.deepEqual(dayPolicy('2026-10-19',schedule,overrides),{scan:true,send:false,kind:'restday',note:'只采集'});
assert.deepEqual(nextSlots(schedule,new Date('2026-10-16T10:00:00Z'),3,overrides),['2026-10-17T01:00:00.000Z','2026-10-17T09:00:00.000Z','2026-10-20T01:00:00.000Z']);
});
test('calendar accepts real Gregorian dates beyond the current century and rejects invalid century leap days',t=>{
const {store}=setup(t);const overrides=[{date:'2400-02-29',kind:'workday',scan:true,send:false,note:'未来业务日期'}];
assert.equal(store.saveCalendar({version:1,overrides},admin).overrides[0].date,'2400-02-29');
bad(()=>store.saveCalendar({version:2,overrides:[{...overrides[0],date:'2100-02-29'}]},admin));
assert.equal(store.snapshot(members).calendar.version,2);
});
+15
View File
@@ -0,0 +1,15 @@
:root{--tblr-font-sans-serif:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif}body{font-family:var(--tblr-font-sans-serif)}.navbar-brand{font-size:1.1rem;gap:.65rem}.brand-mark{width:32px;height:32px;display:grid;place-items:center;border-radius:8px;background:var(--tblr-primary);color:white;font-weight:700}.page-title{letter-spacing:.01em}.nav-link-icon{font-size:1.1rem}.form-hint{line-height:1.7}.empty-state{padding:3rem 1.5rem;text-align:center}.empty-state p{max-width:420px;margin:.6rem auto}.table td{vertical-align:middle}.audit-detail{max-width:350px;overflow-wrap:anywhere}.account-name{max-width:150px;overflow:hidden;text-overflow:ellipsis}.connection-item{min-height:82px}.time-value{font-size:2.4rem;font-weight:600;letter-spacing:.02em}.footer{margin-top:auto}.file-name{max-width:330px;overflow-wrap:anywhere}.form-label.required:after{content:" *";color:var(--tblr-danger)}.login-note{max-width:380px;margin:auto}.card-header .badge{margin-left:auto}#flash{position:fixed;right:24px;top:20px;max-width:min(480px,calc(100vw - 48px));z-index:1100}.group-table input{min-width:150px}.group-table .product-input{min-width:120px}.status-note{border-left:3px solid var(--tblr-warning)}.schedule-time{max-width:240px}.settings-width{max-width:1040px}.mobile-title{font-size:1rem}@media(max-width:767px){.time-value{font-size:1.8rem}.page-header{margin-top:1rem}.card-body{padding:1rem}.file-name{max-width:220px}.container-xl{--tblr-gutter-x:1.5rem}.connection-item{min-height:auto}.navbar-brand{font-size:1rem}}
:root{--tblr-primary:#25745b;--tblr-primary-rgb:37,116,91;--tblr-body-bg:#f5f7f8;--tblr-body-color:#25384a;--tblr-border-color:#e7ecef;--tblr-border-radius:12px;--tblr-link-color:#25745b}body{background:#f5f7f8}.navbar-vertical{background:#fff;border-right:1px solid #e5ebee}.navbar-brand{padding:1.55rem 1.1rem 1.15rem!important;color:#243e3a}.brand-mark{background:#28745b;border-radius:10px}.navbar-vertical .navbar-nav .nav-link{margin:.15rem .7rem;border-radius:8px;min-height:43px;color:#667684;font-size:.88rem}.navbar-vertical .navbar-nav .nav-link.active{background:#eaf4ee;color:#24634e;font-weight:600}.navbar-vertical .navbar-nav .nav-link:hover{background:#f4f7f5}.navbar-vertical .nav-link-icon{color:inherit;opacity:.85}.navbar:not(.navbar-vertical){box-shadow:none;border-bottom:1px solid #e5ebee;min-height:70px}.page-pretitle{color:#87939b;font-size:.67rem;letter-spacing:.12em}.page-title{font-size:1.65rem;font-weight:650;color:#25384a}.page-header{margin-top:1.8rem}.page-header #view-description{font-size:.85rem}.page-body{margin-top:1.5rem}.card{border:1px solid #e5ebee;border-radius:12px;box-shadow:0 2px 5px #243e3a03;overflow:hidden}.card-header{min-height:65px;padding:1.15rem 1.4rem;border-color:#edf0f2}.card-title{font-size:1rem;font-weight:600}.card-body{padding:1.4rem}.card-footer{background:#fbfcfc;border-color:#edf0f2}.btn{border-radius:7px;box-shadow:none}.btn-primary{background:#28745b;border-color:#28745b;color:#fff}.btn-primary:hover,.btn-primary:focus{background:#1f604a;border-color:#1f604a}.btn-outline-primary{color:#28745b;border-color:#28745b}.form-control,.form-select{border-radius:7px;border-color:#dfe6eb}.form-control:focus,.form-select:focus{border-color:#73a591;box-shadow:0 0 0 .2rem #28745b12}.form-check-input:checked{background-color:#28745b;border-color:#28745b}.badge{font-weight:500;letter-spacing:0;font-size:.72rem;padding:.4rem .55rem}.text-secondary{color:#7b8994!important}.sidebar-status{display:flex;align-items:center;gap:6px;font-size:.68rem;margin-top:7px}.sidebar-status i{width:6px;height:6px;border-radius:50%;background:#54a17f}.footer{font-size:.75rem;padding:1.4rem 0}.workspace-welcome{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:.5rem 0 1.8rem}.workspace-eyebrow{font-size:.66rem;letter-spacing:.13em;font-weight:600;color:#7a958b;margin-bottom:.8rem}.workspace-welcome h2{font-size:1.35rem;line-height:1.5;font-weight:600;margin-bottom:.5rem}.workspace-welcome p{color:#829097;font-size:.85rem;margin:0}.workspace-welcome .btn{white-space:nowrap;gap:.8rem}.workspace-metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:1.15rem;margin-bottom:1.4rem}.metric-card{text-decoration:none;color:inherit;position:relative;transition:transform .15s,border-color .15s}.metric-card:hover{color:inherit;text-decoration:none;transform:translateY(-2px);border-color:#bdd6c9}.metric-card .card-body{padding:1.35rem}.metric-card .subheader{font-weight:500;color:#657b81;font-size:.78rem;letter-spacing:0}.metric-number{font-size:2.2rem;font-weight:600;line-height:1.3;margin:.65rem 0 .45rem;color:#29473c}.metric-number span{font-size:.78rem;margin-left:.55rem;color:#93a09b;font-weight:400}.metric-word{font-size:1.7rem;font-weight:600;line-height:1.7;margin:.35rem 0;color:#335e4c}.metric-symbol{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;float:right;font-size:1.2rem}.metric-blue{background:linear-gradient(135deg,#fff 25%,#f1f8ff)}.metric-blue .metric-symbol{color:#5b89bb;background:#e8f1fb}.metric-green{background:linear-gradient(135deg,#fff 25%,#eff7f1)}.metric-green .metric-symbol{color:#4f9171;background:#e6f2e9}.workspace-grid{display:grid;grid-template-columns:minmax(0,1.65fr) minmax(280px,1fr);gap:1.4rem;align-items:start}.workspace-text-link{color:#4e806e;font-size:.78rem;font-weight:500;text-decoration:none}.workspace-text-link:hover{text-decoration:underline}.workspace-task{display:flex;align-items:center;gap:1rem;padding:1.1rem 1.4rem;color:inherit}.workspace-task strong{font-size:.86rem;font-weight:500}.task-priority{display:inline-block;flex-shrink:0;width:7px;height:7px;border-radius:50%;background:#8ab5d3;margin-top:6px}.priority-high{background:#daa661}.priority-critical{background:#d87775}.capability-row{display:flex;gap:.85rem;align-items:flex-start;margin-bottom:1.4rem}.capability-row .status-dot{margin-top:.45rem;flex-shrink:0}.capability-row strong{font-size:.85rem;font-weight:550}.capability-row .small{line-height:1.7;margin-top:.2rem}.workspace-note{border:1px solid #dfeae5;background:#f1f7f3;color:#6e8378;border-radius:8px;padding:1rem 1.1rem;font-size:.78rem;line-height:1.8}.workspace-empty{padding:2.7rem 1.4rem;text-align:center}.workspace-empty>span{width:42px;height:42px;background:#edf4f1;color:#7f9b8e;border-radius:12px;display:grid;place-items:center;font-size:1.8rem;margin:0 auto 1rem}.workspace-empty h3{font-size:.95rem;font-weight:500}.workspace-empty p{font-size:.8rem;max-width:3Line truncated
@media(min-width:992px){.navbar-vertical.navbar-expand-lg{width:232px}.navbar-vertical.navbar-expand-lg~.page-wrapper,.navbar-vertical.navbar-expand-lg~.navbar{margin-left:232px}.container-xl{max-width:1440px;padding-left:2rem;padding-right:2rem}.navbar-vertical.navbar-expand-lg .navbar-collapse{align-items:stretch}.navbar-vertical.navbar-expand-lg .navbar-nav{padding-top:0!important}.navbar-vertical.navbar-expand-lg .navbar-nav .nav-link-icon{margin-right:.7rem}.navbar-vertical .nav-item.mt-3{margin-top:.8rem!important}.navbar-vertical .nav-item.mt-3>.nav-link{font-size:.65rem;min-height:20px;padding-bottom:.2rem;padding-top:.2rem;letter-spacing:.08em}}
@media(max-width:1199px){.workspace-metrics{gap:.7rem}.metric-card .card-body{padding:1.1rem}.calendar-layout{grid-template-columns:minmax(0,1fr) 280px}.day-policy{font-size:.54rem}.calendar-day{padding:.5rem;min-height:86px}.workspace-grid{grid-template-columns:minmax(0,1.4fr) minmax(260px,1fr)}}
@media(max-width:767px){.workspace-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.workspace-welcome{align-items:flex-start;flex-direction:column;padding-bottom:1.3rem}.workspace-welcome h2{font-size:1.15rem}.workspace-grid,.calendar-layout,.exception-layout,.connection-layout{grid-template-columns:minmax(0,1fr)}.exceptions-toolbar{flex-direction:column}.exceptions-toolbar .d-flex{flex-wrap:nowrap!important}.exceptions-toolbar input{width:100%;min-width:0}.exceptions-toolbar select{width:120px;flex-shrink:0}.exceptions-toolbar>button{align-self:flex-start}.calendar-body{padding:.65rem}.calendar-day{padding:.4rem;min-height:85px}.day-number{font-size:.9rem}.day-policy{font-size:.5rem;letter-spacing:-.04em}.calendar-grid{gap:3px}.calendar-legend{gap:.65rem}.workspace-welcome p{font-size:.78rem}.page-title{font-size:1.4rem}.metric-number{font-size:1.8rem}.metric-word{font-size:1.4rem}.metric-card .small{font-size:.68rem}.metric-symbol{width:28px;height:28px;font-size:1rem}.card-header{padding:1rem}.card-body{padding:1rem}.workspace-note{padding:.8rem}.navbar:not(.navbar-vertical){min-height:62px}.activity-list{padding:1.1rem}.workspace-task{padding:1rem}.connection-url{font-size:.72rem}.brand-mark{width:28px;height:28px}.navbar-brand{padding:.8rem .5rem!important}.navbar-vertical .navbar-nav .nav-link{margin:0 .5rem}}
.planned-slots{margin-top:1.2rem;padding:1rem;border:1px solid #dfe9e0;border-radius:8px;background:#ffffff80}.planned-slots>div{font-size:.84rem;color:#527865;margin:.35rem 0}.planned-slots>span{display:block;line-height:1.7}
.bpm-layout:has(>div:only-child){grid-template-columns:minmax(0,1fr)}.bpm-remote-pane{margin-top:1.25rem}.bpm-screen{aspect-ratio:1280/800;position:relative;background:#f3f5f7;border:1px solid #dfe6eb;border-radius:8px;overflow:hidden;max-width:1280px;margin:auto}.bpm-screen img{display:block;width:100%;height:auto;cursor:text;touch-action:manipulation;user-select:none}.bpm-screen img[hidden]{display:none}.bpm-input{position:absolute;left:0;top:0;width:2px;height:24px;min-height:0;margin:0;padding:0;border:0;resize:none;overflow:hidden;opacity:0;pointer-events:none;font-size:16px}.bpm-screen:focus{outline:none}.bpm-screen:focus-visible{outline:2px solid #73a591;outline-offset:2px}.bpm-loading{position:absolute;inset:0;display:grid;place-items:center;color:#7b8994;font-size:.85rem}.bpm-loading[hidden]{display:none}.bpm-checks>div{display:flex;gap:.75rem;flex-wrap:wrap;align-items:center;margin-top:.65rem}.bpm-remote-pane .btn-list{flex-wrap:wrap}.bpm-layout .card-header>div{min-width:0}.bpm-layout .card-title,.bpm-checks{overflow-wrap:anywhere}@media(max-width:767px){.bpm-remote-pane .card-body{padding:.75rem}.bpm-remote-pane .card-header{padding:.85rem}.bpm-remote-pane .btn{padding:.45rem .65rem}.bpm-layout .connection-avatar{display:none}.bpm-screen{border-radius:4px}}
.bpm-account-summary{padding:.75rem 1.4rem;overflow-wrap:anywhere}.bpm-account-panel{padding:0 1.4rem 1.4rem}.bpm-account-form{display:grid;gap:1rem;min-width:0;padding-top:.5rem}.bpm-account-form .form-label{display:grid;gap:.4rem;min-width:0;margin:0}.bpm-account-form .form-control{width:100%;min-width:0;box-sizing:border-box}.bpm-account-actions{display:flex;flex-wrap:wrap;gap:.5rem}.bpm-layout>div{min-width:0}@media(max-width:767px){.bpm-account-summary{padding:.75rem 1rem}.bpm-account-panel{padding:0 1rem 1rem}}
/* Keep email documents in their own scrollable preview. */
.mail-preview{display:block;width:100%;height:400px;border:1px solid var(--tblr-border-color,#dce1e7);border-radius:6px;background:#fff}
#mail-editor .form-fieldset{min-width:0;margin-bottom:0}
#mail-template-detail{scroll-margin-top:20px}
.scan-interval{width:6rem}.arrival-date{font-weight:700;font-size:1.05rem;font-variant-numeric:tabular-nums}.arrival-day>summary{cursor:pointer;list-style:none}.arrival-day>summary::-webkit-details-marker{display:none}.arrival-day>summary:before{content:"▾";margin-right:.8rem;color:#64748b}.arrival-day:not([open])>summary:before{content:"▸"}.arrival-table th:first-child{min-width:175px}.arrival-table th:nth-child(2){min-width:170px}.arrival-subject{min-width:250px;white-space:normal;overflow-wrap:anywhere;max-width:600px}.arrival-table td:last-child{min-width:115px}
+92
View File
@@ -0,0 +1,92 @@
'use strict';
const root=document.querySelector('#app');
const esc=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const formatDate=value=>{const date=new Date(value);return value&&!Number.isNaN(date.getTime())?new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',dateStyle:'short',timeStyle:'medium',hour12:false}).format(date):'—';};
const roles={admin:'管理员',operator:'操作员',viewer:'只读成员'};
const statusMap={running:['处理中','blue'],success:['已完成','green'],error:['失败','red'],interrupted:['已中断','orange']};
let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0;
const views={overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['订单匹配规则','管理订单筛选和匹配条件'],schedule:['发送计划','设置每日两个发送时间和批次整理方式'],templates:['模板与收件群组','预览确认发信模板,维护产品线收件群组'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
async function api(route,body) {
const response=await fetch('/api'+route,{credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:body===undefined?'GET':'POST',headers:body?{'Content-Type':'application/json'}:{},body:body?JSON.stringify(body):undefined});
const result=await response.json();
if(!response.ok){if(response.status===401 && currentUser){currentUser=null;++viewGeneration;window.BpmLogin?.dispose();await boot();}throw new Error(result.error || '操作失败,请重试。');}
return result;
}
function notify(message,type='success') {
document.querySelector('#flash')?.remove();
const flash=document.createElement('div');flash.id='flash';flash.className='alert alert-'+type+' shadow';flash.setAttribute('role','alert');flash.textContent=message;document.body.append(flash);setTimeout(()=>flash.remove(),6500);
}
function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `<span class="badge bg-${color}-lt">${label}</span>`;}
function navItem(id,symbol){return `<li class="nav-item"><a class="nav-link ${currentView===id?'active':''}" href="#${id}" data-view="${id}"><span class="nav-link-icon" aria-hidden="true">${symbol}</span><span class="nav-link-title">${views[id][0]}</span></a></li>`;}
function shell() {
root.innerHTML=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${navItem('overview','▦')}${navItem('calendar','▣')}${navItem('exceptions','☷')}${navItem('bpm','⇄')}${navItem('supervisor','◎')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">订单与通知</span></li>${navItem('records','≡')}${navItem('rules','⌕')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">通知配置</span></li>${navItem('schedule','◷')}${navItem('templates','✉')}${navItem('mail','@')}${navItem('connections','⇄')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">团队管理</span></li>${currentUser.role==='admin'?navItem('users','♙'):''}${navItem('audit','☷')}</ul><div class="mt-auto p-3 text-secondary small d-none d-lg-block">团队共享工作台<br><span class="sidebar-status"><i></i> 本地运行 · 北京时间</span></div></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><span class="badge bg-yellow-lt">自动处理未启用</span></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><div class="page-pretitle">订单通知自动化</div><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl" id="content"></div></div><footer class="footer footer-transparent d-print-none"><div class="container-xl"><div class="row text-secondary align-items-center"><div class="col">订单通知中心 · 局域网工作台</div><div class="col-auto">UI 基于 <a href="https://tabler.io" target="_blank" rel="noreferrer">Tabler</a> · MIT</div></div></div></footer></div></div>`;
document.querySelector('#logout').onclick=async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});currentUser=null;clearInterval(refreshTimer);await boot();};
document.querySelector('#refresh').onclick=()=>renderView().catch(error=>notify(error.message,'danger'));
document.querySelectorAll('[data-view]').forEach(link=>link.onclick=()=>{document.querySelector('#sidebar-menu').classList.remove('show');});
}
function empty(title,text){return `<div class="empty-state"><div class="avatar avatar-lg bg-blue-lt mb-3">▤</div><h3>${title}</h3><p class="text-secondary">${text}</p></div>`;}
function readOnlyNote(){return currentUser.role==='admin'?'':`<div class="alert alert-info">当前账号可查看配置。修改配置请联系管理员。</div>`;}
function jobRows(jobs){return jobs.map(job=>`<tr><td><div class="fw-medium">${esc(job.metadata?.order || '未记录订单号')}</div><div class="small text-secondary">${esc(job.metadata?.serial || '')}</div></td><td>${esc(job.metadata?.project || '—')}<div class="small text-secondary">${esc(job.metadata?.model || '')}</div></td><td>${badge(job.status)}${job.error?`<div class="small text-danger mt-1">${esc(job.error)}</div>`:''}</td><td class="text-secondary small">${formatDate(job.updatedAt)}</td><td>${job.downloadable?`<a class="btn btn-sm" href="/api/jobs/${encodeURIComponent(job.jobId)}/file">下载 PDF</a>`:'—'}</td></tr>`).join('');}
function jobTable(jobs){return `<div class="table-responsive"><table class="table table-vcenter card-table"><thead><tr><th>订单 / 通知书编号</th><th>项目 / 型号</th><th>状态</th><th>更新时间</th><th></th></tr></thead><tbody>${jobRows(jobs)}</tbody></table></div>`;}
async function viewOverview(container,isActive=()=>true) {
if(window.WorkspaceViews)return window.WorkspaceViews.overview(container,isActive);
await api('/workspace');if(!isActive())return;
container.innerHTML=empty('工作台模块未加载','请刷新页面后重试。');
}
async function viewRecords(container,isActive=()=>true) {
return window.OrderViews.records(container,isActive,viewPdfRecords);
}
async function viewPdfRecords(container,isActive=()=>true) {
const {jobs}=await api('/jobs');if(!isActive())return;
container.innerHTML=`<div class="card"><div class="card-header gap-3 flex-wrap"><h2 class="card-title">导出记录 <span class="text-secondary">${jobs.length}</span></h2><div class="ms-auto d-flex gap-2"><input class="form-control" id="record-search" placeholder="搜索订单号、项目或型号" aria-label="搜索订单"><select class="form-select" id="record-status" aria-label="任务状态"><option value="">全部状态</option><option value="success">已完成</option><option value="running">处理中</option><option value="error">失败</option><option value="interrupted">已中断</option></select></div></div><div id="records-body"></div><div class="card-footer d-flex align-items-center"><span class="text-secondary" id="records-count"></span><div class="btn-list ms-auto"><button class="btn btn-sm" id="prev-page">上一页</button><button class="btn btn-sm" id="next-page">下一页</button></div></div></div>`;
let page=0;
function render(){const search=document.querySelector('#record-search').value.toLowerCase().trim();const status=document.querySelector('#record-status').value;const filtered=jobs.filter(job=>(!status || job.status===status) && (!search || [job.metadata?.order,job.metadata?.project,job.metadata?.model,job.metadata?.serial,job.filename].join(' ').toLowerCase().includes(search)));page=Math.max(0,Math.min(page,Math.ceil(filtered.length/25)-1));const selected=filtered.slice(page*25,page*25+25);document.querySelector('#records-body').innerHTML=selected.length?jobTable(selected):empty('暂无匹配记录','调整搜索条件,或先从订单页面导出一份通知书。');document.querySelector('#records-count').textContent=`共 ${filtered.length} 条 · 第 ${page+1} 页`;document.querySelector('#prev-page').disabled=page===0;document.querySelector('#next-page').disabled=(page+1)*25>=filtered.length;}
document.querySelector('#record-search').oninput=()=>{page=0;render();};document.querySelector('#record-status').onchange=()=>{page=0;render();};document.querySelector('#prev-page').onclick=()=>{page--;render();};document.querySelector('#next-page').onclick=()=>{page++;render();};render();
}
async function viewSchedule(container,isActive=()=>true) {
const loaded=await api('/settings');if(!isActive())return;settings=loaded;const s=settings.schedule;const disabled=currentUser.role!=='admin'?'disabled':'';
container.innerHTML=`<div class="settings-width">${readOnlyNote()}<div class="alert alert-info">自动发送未启用</div><form id="schedule-form"><div class="card"><div class="card-header"><h2 class="card-title">每日两次通知</h2><span class="badge bg-blue-lt">北京时间</span></div><div class="card-body"><div class="row g-4"><div class="col-sm-6"><label class="form-label required" for="time-first">第一个发送时间</label><input class="form-control schedule-time" id="time-first" type="time" value="${s.times[0]}" required ${disabled}></div><div class="col-sm-6"><label class="form-label required" for="time-second">第二个发送时间</label><input class="form-control schedule-time" id="time-second" type="time" value="${s.times[1]}" required ${disabled}></div><div class="col-12"><label class="form-check form-switch"><input class="form-check-input" type="checkbox" id="weekends" ${s.weekends?'checked':''} ${disabled}><span class="form-check-label">周六、周日照常发送</span></label><div class="form-hint">关闭后仅在周一至周五发送;公司调休与暂停安排可在 <a href="#calendar">业务日历</a> 中按日期覆盖。</div></div><div class="col-sm-6"><label class="form-label" for="send-mode">邮件整理方式</label><select class="form-select" id="send-mode" ${disabled}><option value="product_line" ${s.mode==='product_line'?'selected':''}>按产品线汇总为一封邮件</option><option value="order" ${s.mode==='order'?'selected':''}>每个订单单独发送一封</option></select></div><div class="col-sm-6"><label class="form-label" for="missed">停机错过时段后</label><select class="form-select" id="missed" ${disabled}><option value="next_window" ${s.missed==='next_window'?'selected':''}>保留待发订单,下一时段合并处理</option><option value="skip" ${s.missed==='skip'?'selected':''}>跳过错过时段,继续正常计划</option></select></div></div></div><div class="card-footer d-flex align-items-center"><span class="text-secondary small">配置供整个团队共用</span>${currentUser.role==='admin'?'<button class="btn btn-primary ms-auto" type="submit">保存发送计划</button>':''}</div></div></form></div>`;
document.querySelector('#schedule-form').onsubmit=async event=>{event.preventDefault();try{const updated=await api('/settings',{version:settings.version,schedule:{times:[document.querySelector('#time-first').value,document.querySelector('#time-second').value],timezone:'Asia/Shanghai',weekends:document.querySelector('#weekends').checked,mode:document.querySelector('#send-mode').value,missed:document.querySelector('#missed').value}});settings=updated;notify('发送计划已保存。');}catch(error){notify(error.message,'danger');}};
}
async function viewTemplates(container,isActive=()=>true) {
const loaded=await api('/settings');if(!isActive())return;settings=loaded;const admin=currentUser.role==='admin';const disabled=admin?'':'disabled';
container.innerHTML=`<div class="settings-width">${readOnlyNote()}<div class="row row-cards"><div class="col-12" id="mail-templates"></div><div class="col-12"><div class="card"><div class="card-header"><h2 class="card-title">产品线与收件群组</h2>${admin?'<button class="btn btn-sm ms-auto" id="add-group">添加产品线</button>':''}</div><div id="group-editor"></div><div class="card-footer d-flex"><span class="text-secondary small">多个邮箱用英文逗号分隔</span>${admin?'<button class="btn btn-primary ms-auto" id="save-groups">保存群组</button>':''}</div></div></div></div></div>`;
let groups=structuredClone(settings.groups);
const split=value=>value.split(/[,;,;\n]/).map(item=>item.trim()).filter(Boolean);
const readGroups=()=>[...document.querySelectorAll('[data-group]')].map(row=>({productLine:row.querySelector('[name="productLine"]').value.trim(),to:split(row.querySelector('[name="to"]').value),cc:split(row.querySelector('[name="cc"]').value)}));
function draw(){document.querySelector('#group-editor').innerHTML=groups.length?`<div class="table-responsive"><table class="table card-table group-table"><thead><tr><th>产品线</th><th>收件人</th><th>抄送</th>${admin?'<th></th>':''}</tr></thead><tbody>${groups.map((group,index)=>`<tr data-group="${index}"><td><input class="form-control product-input" name="productLine" aria-label="产品线 ${index+1}" value="${esc(group.productLine)}" ${disabled}></td><td><input class="form-control" name="to" aria-label="收件人 ${index+1}" value="${esc(group.to.join(', '))}" ${disabled}></td><td><input class="form-control" name="cc" aria-label="抄送 ${index+1}" value="${esc(group.cc.join(', '))}" ${disabled}></td>${admin?`<td><button class="btn btn-sm btn-outline-danger" data-remove="${index}">移除</button></td>`:''}</tr>`).join('')}</tbody></table></div>`:empty('尚未配置收件群组','添加产品线及收件邮箱。');document.querySelectorAll('[data-remove]').forEach(button=>button.onclick=()=>{groups=readGroups();groups.splice(Number(button.dataset.remove),1);draw();});}
draw();
if(admin){document.querySelector('#add-group').onclick=()=>{groups=readGroups();groups.push({productLine:'',to:[],cc:[]});draw();};document.querySelector('#save-groups').onclick=async()=>{try{settings=await api('/settings',{version:settings.version,groups:readGroups()});groups=structuredClone(settings.groups);draw();notify('产品线收件群组已保存。');}catch(error){notify(error.message,'danger');}};}
await window.MailViews.templates(container.querySelector('#mail-templates'),isActive);
}
async function viewConnections(container,isActive=()=>true) {
const data=await api('/overview');if(!isActive())return;container.innerHTML=`<div class="mb-3 btn-list"><a class="btn btn-primary" href="#mail">邮箱管理</a><a class="btn" href="#bpm">BPM 连接</a></div><div class="row row-cards">${data.connections.map(item=>`<div class="col-md-6"><div class="card"><div class="card-body"><div class="d-flex align-items-center mb-2"><h3 class="card-title mb-0">${esc(item.name)}</h3><span class="badge bg-${item.ready?'green':'yellow'}-lt ms-auto">${item.ready?'已就绪':'待接入'}</span></div><div class="text-secondary">${esc(item.detail)}</div></div></div></div>`).join('')}</div>`;
}
async function viewUsers(container,isActive=()=>true) {
const {users}=await api('/users');if(!isActive())return;container.innerHTML=`<div class="row row-cards"><div class="col-lg-7"><div class="card"><div class="card-header"><h2 class="card-title">团队账号</h2></div><div class="table-responsive"><table class="table card-table"><thead><tr><th>账号</th><th>角色</th><th>创建时间</th></tr></thead><tbody>${users.map(user=>`<tr><td>${esc(user.username)}</td><td><span class="badge bg-${user.role==='admin'?'blue':'secondary'}-lt">${roles[user.role]}</span></td><td class="text-secondary small">${formatDate(user.createdAt)}</td></tr>`).join('')}</tbody></table></div></div></div><div class="col-lg-5"><form class="card" id="user-form"><div class="card-header"><h2 class="card-title">添加同事</h2></div><div class="card-body"><div class="mb-3"><label class="form-label required" for="new-username">登录账号</label><input class="form-control" id="new-username" autocomplete="off" required minlength="3" maxlength="40" pattern="[a-zA-Z0-9_.-]+"><div class="form-hint">英文、数字、点、下划线或短横线</div></div><div class="mb-3"><label class="form-label required" for="new-password">初始密码</label><input class="form-control" id="new-password" type="password" autocomplete="new-password" required minlength="12" maxlength="128"></div><div><label class="form-label" for="new-role">角色</label><select class="form-select" id="new-role"><option value="viewer">只读成员</option><option value="operator">操作员</option><option value="admin">管理员</option></select><div class="form-hint">管理员管理配置和账号;操作员处理异常;只读成员查看和下载。</div></div></div><div class="card-footer text-end"><button class="btn btn-primary" type="submit">创建账号</button></div></form></div></div>`;
document.querySelector('#user-form').onsubmit=async event=>{event.preventDefault();try{await api('/users',{username:document.querySelector('#new-username').value,password:document.querySelector('#new-password').value,role:document.querySelector('#new-role').value});notify('账号已创建。');await viewUsers(container,isActive);}catch(error){notify(error.message,'danger');}};
}
async function viewAudit(container,isActive=()=>true){const [legacy,workspace]=await Promise.all([api('/audit'),api('/workspace')]);if(!isActive())return;const audit=[...legacy.audit,...workspace.audit].sort((a,b)=>new Date(b.at)-new Date(a.at));container.innerHTML=`<div class="card"><div class="card-header"><h2 class="card-title">最近操作记录</h2><span class="text-secondary ms-auto">按时间展示最近 200 条</span></div>${audit.length?`<div class="table-responsive"><table class="table card-table"><thead><tr><th>时间(北京时间)</th><th>操作人</th><th>操作</th><th>详情</th></tr></thead><tbody>${audit.slice(0,200).map(item=>`<tr><td class="small text-secondary">${formatDate(item.at)}</td><td>${esc(item.actor)}</td><td>${esc(window.WorkspaceViews.activityText(item.action))}</td><td class="audit-detail text-secondary">${esc(item.detail)}</td></tr>`).join('')}</tbody></table></div>`:empty('暂无操作记录','保存设置或导出订单后,可在这里查看。')}</div>`;}
function viewRules(container){container.innerHTML=`<div class="card"><div class="card-header"><h2 class="card-title">订单识别与匹配</h2><span class="badge bg-yellow-lt">等待业务表格</span></div><div class="card-body"><div class="steps steps-counter steps-blue mb-5"><span class="step-item active">提供业务表格</span><span class="step-item">确认字段对应</span><span class="step-item">预览匹配订单</span><span class="step-item">启用自动处理</span></div>${empty('依据你的表格识别订单','暂无匹配规则')}</div></div>`;}
async function renderView() {
if(!currentUser)return;
const generation=++viewGeneration;const isActive=()=>generation===viewGeneration && !!currentUser;
await window.BpmLogin?.dispose();if(!isActive())return;
const requested=location.hash.slice(1) || 'overview';currentView=views[requested]?requested:'overview';
if(currentView==='users' && currentUser.role!=='admin')currentView='overview';
document.querySelectorAll('[data-view]').forEach(link=>link.classList.toggle('active',link.dataset.view===currentView));
document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1];
const container=document.querySelector('#content');container.innerHTML='<div class="card"><div class="card-body text-secondary">正在加载…</div></div>';
const fn={overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:viewUsers,audit:viewAudit,rules:viewRules}[currentView];
try{await fn(container,isActive);}catch(error){if(isActive())container.innerHTML=`<div class="alert alert-danger">${esc(error.message)}</div>`;}
}
async function authScreen() {
const setup=await api('/bootstrap/status');const initialize=setup.required && setup.canSetup;
root.innerHTML=`<div class="page page-center"><div class="container-tight py-4"><div class="text-center mb-4"><span class="avatar bg-blue text-white mb-3">单</span><h1 class="h2">订单通知中心</h1><div class="text-secondary">团队协同工作台</div></div><form class="card card-md" id="login-form"><div class="card-body"><h2 class="h2 text-center mb-4">${initialize?'创建管理员账号':'登录工作台'}</h2>${setup.required && !setup.canSetup?'<div class="alert alert-info">请先由部署机在本机地址创建管理员,再为团队开通账号。</div>':''}<div class="mb-3"><label class="form-label" for="username">账号</label><input class="form-control" id="username" autocomplete="username" required ${initialize?'minlength="3" maxlength="40" pattern="[a-zA-Z0-9_.-]+"':''}></div><div class="mb-3"><label class="form-label" for="password">密码</label><input class="form-control" type="password" id="password" autocomplete="${initialize?'new-password':'current-password'}" required ${initialize?'minlength="12" maxlength="128"':''}>${initialize?'<div class="form-hint">设置至少 12 位密码,后续可在看板中创建同事账号。</div>':''}</div><div class="text-danger mb-3" id="auth-error" role="alert"></div><div class="form-footer"><button class="btn btn-primary w-100" type="submit" ${setup.required && !setup.canSetup?'disabled':''}>${initialize?'创建账号并进入':'登录'}</button></div></div></form><p class="text-center text-secondary small mt-4 login-note">${initialize?'首次设置仅允许从部署机访问。':'使用管理员分配的账号访问。'}<br>界面基于 Tabler 开源模板</p></div></div>`;
document.querySelector('#login-form').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type="submit"]');button.disabled=true;try{const result=await api(initialize?'/bootstrap':'/login',{username:document.querySelector('#username').value,password:document.querySelector('#password').value});currentUser=result.user;enter();}catch(error){document.querySelector('#auth-error').textContent=error.message;}finally{button.disabled=false;}};
}
function enter(){window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);}
async function boot(){try{const setup=await api('/bootstrap/status');currentUser=(await api('/me')).user;enter();}catch{await authScreen();}}
window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});});
window.addEventListener('hashchange',()=>{if(currentUser)renderView();});
boot().catch(error=>{root.innerHTML=`<div class="container-tight py-5"><div class="alert alert-danger">${esc(error.message)}</div></div>`;});
+162
View File
@@ -0,0 +1,162 @@
'use strict';
window.BpmLogin=(()=>{
let active=null,releasing=null,releasePending=Promise.resolve();
const statuses={disconnected:['未连接','secondary'],unchecked:['待检查','yellow'],login_required:['待登录','yellow'],connected:['已连接','green'],disabled:['已停用','secondary'],error:['检查失败','red']};
function dispose(options={}){const previous=active||releasing;active=null;if(previous){releasing=previous;releasePending=previous.dispose(options);releasePending.finally(()=>{if(releasing===previous)releasing=null;});}return releasePending;}
async function mount(container,{api,esc,formatDate,notify,user,isActive=()=>true}){
await dispose();
if(!isActive())return;
let disposed=false,remote=null,accountBusy=false,data,connections=[];
const accounts=new Map(),accountRequests=new Map();
const live=()=>!disposed&&isActive();
const $=selector=>container.querySelector(selector);
const authorized=c=>user.role==='admin'||(user.role==='operator'&&c.owner===user.username);
const route=(id,action)=>`/connections/${encodeURIComponent(id)}/${action}`;
const status=c=>{const [label,color]=statuses[c.status]||statuses.error;return `<span class="badge bg-${color}-lt">${label}</span>`;};
function feedback(message,type='danger'){if(!live())return;const el=$('[data-bpm-feedback]');if(el){el.hidden=false;el.className=`alert alert-${type}`;el.textContent=message;}notify(message,type);}
function release(r,{unload=false}={}){
r.closed=true;clearTimeout(r.timer);r.controller?.abort();if(r.url){URL.revokeObjectURL(r.url);r.url=null;}
if(unload){if(!r.closeRequest)r.closeRequest=fetch('/api'+route(r.id,'login/close'),{method:'POST',credentials:'same-origin',keepalive:true,headers:{'Content-Type':'application/json'},body:'{}'}).then(()=>{}).catch(()=>{});return r.closeRequest;}
if(r.release)return r.release;
r.release=(async()=>{await r.opening.catch(()=>{});await r.queue.catch(()=>{});await r.operation?.catch(()=>{});if(!r.closeRequest)r.closeRequest=api(route(r.id,'login/close'),{}).catch(()=>{});await r.closeRequest;})();return r.release;
}
const handle={dispose(options){disposed=true;container.querySelectorAll('[data-account-form]').forEach(form=>form.reset());return remote?release(remote,options):Promise.resolve();}};
active=handle;
const valid=r=>live()&&remote===r&&!r.closed;
function controls(r){if(!valid(r))return;container.querySelectorAll('[data-bpm-control]').forEach(el=>el.disabled=!!r.busy);const input=$('[data-bpm-input]');if(input)input.disabled=!!r.busy;}
function enqueue(r,action){
if(!valid(r)||r.busy)return;
r.queue=r.queue.then(()=>{if(valid(r)&&!r.failed)return api(route(r.id,'login/input'),action);}).catch(()=>{if(valid(r)){r.failed=true;feedback('输入未送达,请关闭后重新打开登录窗口。');}});
}
function update(result,id){const saved=result.connection||result;connections=connections.map(c=>c.id===id?{...c,...saved,id}:c);drawCards();}
function rememberAccount(id,result){const metadata={configured:result.configured===true,username:typeof result.username==='string'?result.username:'',updatedAt:result.updatedAt||null};accounts.set(id,metadata);return metadata;}
function loadAccount(id){
if(accounts.has(id))return Promise.resolve(accounts.get(id));
if(!accountRequests.has(id))accountRequests.set(id,api(route(id,'account')).then(result=>rememberAccount(id,result)).finally(()=>accountRequests.delete(id)));
return accountRequests.get(id);
}
function accountSummary(c){const account=accounts.get(c.id);return account?(account.configured?`自动续登已开启 · ${account.username} · 每 5 分钟检查`:'自动续登未开启'):'正在加载账号…';}
function refreshAccountSummary(){if(live()){container.querySelectorAll('[data-account-summary]').forEach(el=>{const c=connections.find(c=>c.id===el.dataset.accountSummary);if(c)el.textContent=accountSummary(c);});container.querySelectorAll('[data-account]').forEach(button=>button.textContent=accounts.get(button.dataset.account)?.configured?'管理账号':'开启自动续登');}}
function accountControls(busy){accountBusy=busy;if(live())container.querySelectorAll('[data-login],[data-check],[data-disable],[data-delete],[data-account]').forEach(el=>el.disabled=busy||!!remote);}
async function editAccount(button){
const id=button.dataset.account;
if(remote||accountBusy||!live())return;
button.disabled=true;
try{
const account=await loadAccount(id);if(!live()||!button.isConnected||remote)return;
const panel=button.closest('article').querySelector('[data-account-panel]');
panel.innerHTML=`<form class="bpm-account-form" data-account-form autocomplete="off"><h4 class="card-title">${account.configured?'管理自动续登账号':'开启自动续登'}</h4><label class="form-label">BPM 账号<input class="form-control" name="username" autocomplete="username" maxlength="150" required aria-describedby="bpm-account-availability"></label><div class="small" id="bpm-account-availability" data-account-availability role="status" hidden></div><label class="form-label">托管密码<input class="form-control" name="password" type="password" autocomplete="new-password" maxlength="256" required placeholder="${account.configured?'输入新密码以更新':'输入托管密码'}"></label><div class="bpm-account-actions"><button class="btn btn-primary" type="submit">保存账号</button>${account.configured?'<button class="btn btn-outline-danger" type="button" data-account-clear>关闭自动续登</button>':''}<button class="btn" type="button" data-account-cancel>取消</button></div></form>`;
const form=panel.querySelector('form'),username=form.elements.username,password=form.elements.password;
username.value=account.username;panel.hidden=false;
panel.scrollIntoView({block:'nearest'});username.focus({preventScroll:true});
form.querySelector('[data-account-cancel]').onclick=()=>{form.reset();panel.innerHTML='';panel.hidden=true;};
const busy=value=>{accountControls(value);form.querySelectorAll('input,button').forEach(el=>el.disabled=value);};
let checkVersion=0;
const availability=form.querySelector('[data-account-availability]');
const checkUsername=async()=>{
const value=username.value.trim(),version=++checkVersion;
if(!value)return false;
const result=await api(route(id,'account/check'),{username:value});
if(!live()||!form.isConnected||version!==checkVersion||value!==username.value.trim())return false;
const available=result.available===true,message=available?'该账号可以使用。':'该账号已开启自动续登,请使用已有连接。';
username.setCustomValidity(available?'':message);availability.hidden=false;availability.textContent=message;availability.className='small '+(available?'text-success':'text-danger');
return available;
};
username.oninput=()=>{checkVersion++;username.setCustomValidity('');availability.hidden=true;};
username.onblur=()=>{if(username.value.trim()&&!accountBusy)checkUsername().catch(()=>{if(live()&&form.isConnected){availability.hidden=false;availability.className='small text-danger';availability.textContent='账号检查失败,请保存时重试。';}});};
form.onsubmit=async event=>{
event.preventDefault();if(!live()||remote||accountBusy||!form.isConnected||!form.reportValidity()||!username.value.trim())return;
const body={username:username.value.trim(),password:password.value};busy(true);
try{if(!await checkUsername()){password.value='';return;}const result=await api(route(id,'account'),body);password.value='';if(!live()||!form.isConnected)return;rememberAccount(id,result);form.reset();accountControls(false);if(result.connection)update(result,id);else drawCards();const state=result.connection?.status;feedback(state==='connected'?'自动续登已开启,BPM 已连接。':state==='login_required'?'自动续登已开启,请完成登录验证。':state==='error'?'自动续登已开启,连接检查失败。':'自动续登已开启。',['login_required','error'].includes(state)?'warning':'success');}
catch(error){password.value='';feedback(error.message);}finally{busy(false);}
};
const clear=form.querySelector('[data-account-clear]');if(clear)clear.onclick=async()=>{
if(!live()||remote||accountBusy||!form.isConnected)return;busy(true);try{const result=await api(route(id,'account/clear'),{});password.value='';if(!live()||!form.isConnected)return;rememberAccount(id,result);form.reset();accountControls(false);drawCards();feedback('自动续登已关闭。','success');}catch(error){feedback(error.message);}finally{busy(false);}
};
}catch(error){feedback(error.message);}finally{if(live()&&button.isConnected)button.disabled=false;}
}
function drawCards(){
if(!live())return;
container.querySelectorAll('[data-account-form]').forEach(form=>form.reset());
$('#bpm-list').innerHTML=connections.length?connections.map(c=>`<article class="card mb-3"><div class="card-header"><span class="connection-avatar" aria-hidden="true">B</span><div class="flex-fill"><h3 class="card-title mb-1">${esc(c.name)}</h3><span class="text-secondary small">负责人 ${esc(c.owner||'未分配')}</span></div>${status(c)}</div><div class="card-body"><div class="connection-url"><span class="text-secondary">新版门户</span><span>bpmn.skyworthdigital.com</span></div>${c.identity?`<div class="small mt-2">登录账号 ${esc(c.identity)}</div>`:''}${c.checkedAt?`<div class="small text-secondary mt-2">上次检查 ${esc(formatDate(c.checkedAt))}</div>`:''}${c.checks?`<div class="bpm-checks mt-3">${[['portal','新版门户']].map(([key,label])=>`<div><span class="badge bg-${c.checks[key]?.ok?'green':'yellow'}-lt">${label} · ${c.checks[key]?.ok?'已登录':'待登录'}</span><span class="small text-secondary">${esc(c.checks[key]?.message||'待检查')}</span></div>`).join('')}</div>`:''}</div>${c.status!=='disabled'&&authorized(c)?`<div class="card-footer d-flex gap-2 flex-wrap">${data.capabilities?.remoteLogin?`<button class="btn btn-primary" data-login="${esc(c.id)}" ${remote?'disabled':''}>远程登录</button><button class="btn" data-check="${esc(c.id)}" ${remote?'disabled':''}>检查连接</button>`:'<span class="text-secondary small">远程登录未启用</span>'}<button class="btn" data-account="${esc(c.id)}" ${remote?'disabled':''}>${accounts.get(c.id)?.configured?'管理账号':'开启自动续登'}</button>${user.role==='admin'?`<button class="btn btn-outline-danger ms-auto" data-disable="${esc(c.id)}" ${remote?'disabled':''}>停用连接</button>`:''}</div><div class="bpm-account-summary small text-secondary" data-account-summary="${esc(c.id)}">${esc(accountSummary(c))}</div><div class="bpm-account-panel" data-account-panel hidden></div>`:c.status==='disabled'&&user.role==='admin'?`<div class="card-footer text-end"><button class="btn btn-outline-danger" data-delete="${esc(c.id)}" ${remote?'disabled':''}>删除</button></div>`:''}</article>`).join(''):'<div class="card"><div class="workspace-empty"><h3>还没有 BPM 连接</h3><p class="text-secondary mb-0">请管理员添加连接并指定负责人。</p></div></div>';
container.querySelectorAll('[data-account]').forEach(button=>button.onclick=()=>editAccount(button));
container.querySelectorAll('[data-login]').forEach(button=>button.onclick=()=>open(button.dataset.login));
container.querySelectorAll('[data-check]').forEach(button=>button.onclick=()=>mutate(button,'check','连接状态已更新。'));
container.querySelectorAll('[data-disable]').forEach(button=>button.onclick=()=>mutate(button,'disable','连接已停用。'));
container.querySelectorAll('[data-delete]').forEach(button=>button.onclick=()=>removeConnection(button));
}
async function removeConnection(button){
if(remote||accountBusy||!live())return;
const id=button.dataset.delete,connection=connections.find(c=>c.id===id);
if(!connection||connection.status!=='disabled'||user.role!=='admin')return;
if(!window.confirm('删除“'+connection.name+'”?该连接的托管账号和 Cookie 将一并清除,删除后无法恢复。'))return;
accountControls(true);
try{await api(route(id,'delete'),{});if(!live())return;connections=connections.filter(c=>c.id!==id);accounts.delete(id);drawCards();feedback('连接已删除。','success');}
catch(error){feedback(error.message);}finally{accountControls(false);}
}
async function mutate(button,action,message){button.disabled=true;try{const result=await api(route(button.dataset[action],action),{});if(!live())return;update(result,button.dataset[action]);feedback(message,'success');}catch(error){feedback(error.message);}finally{if(live())button.disabled=false;}}
async function frame(r){
if(!valid(r))return;
try{
r.controller=new AbortController();
const response=await fetch('/api'+route(r.id,'login/frame'),{credentials:'same-origin',cache:'no-store',signal:r.controller.signal});
if(!response.ok){let message='登录画面加载失败,请重新打开窗口。';try{message=(await response.json()).error||message;}catch{}throw new Error(message);}
const blob=await response.blob();if(!valid(r))return;
const url=URL.createObjectURL(blob),old=r.url;r.url=url;const image=$('[data-bpm-frame]');image.src=url;image.hidden=false;const loading=$('[data-bpm-loading]');if(loading)loading.hidden=true;if(old)URL.revokeObjectURL(old);
}catch(error){if(valid(r)&&error.name!=='AbortError'){feedback(error.message);await close(r);return;}}
if(valid(r))r.timer=setTimeout(()=>frame(r),650);
}
async function close(r){if(remote===r)remote=null;await release(r);if(live()){$('#bpm-remote').innerHTML='';drawCards();}}
async function open(id){
if(remote||accountBusy||!live())return;
const r={id,closed:false,queue:Promise.resolve(),busy:false,failed:false,url:null,timer:null};remote=r;drawCards();
r.opening=api(route(id,'login/open'),{});
try{
const session=await r.opening;if(!valid(r)){await release(r);return;}
await loadAccount(id).catch(error=>feedback(error.message));if(!valid(r)){await release(r);return;}
r.viewport=session.viewport;
$('#bpm-remote').innerHTML=`<section class="card bpm-remote-pane"><div class="card-header gap-2 flex-wrap"><h2 class="card-title">BPM 登录</h2><span class="text-secondary small">${esc(session.host||'')}</span><button class="btn btn-sm ms-auto" data-bpm-close>关闭</button></div><div class="card-body"><div class="btn-list mb-3"><button class="btn btn-sm" data-bpm-control data-target="main">新版门户</button><button class="btn btn-sm" data-bpm-control data-target="reload">刷新</button>${accounts.get(id)?.configured?'<button class="btn btn-sm" data-bpm-control data-bpm-fill-account>填入托管账号</button>':''}</div><p class="text-secondary small">直接点击画面中的输入框即可输入。</p><div class="bpm-screen" tabindex="0" role="group" aria-label="BPM 远程画面"><div class="bpm-loading" data-bpm-loading>正在加载登录画面…</div><img data-bpm-frame alt="BPM 登录画面" width="${Number(r.viewport.width)}" height="${Number(r.viewport.height)}" hidden draggable="false"><textarea data-bpm-input class="bpm-input" rows="1" tabindex="-1" aria-label="远程登录输入" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false"></textarea></div><div class="small text-secondary mt-2" data-bpm-session>10 分钟未操作自动关闭</div></div><div class="card-footer d-flex align-items-center gap-2 flex-wrap"><span class="small text-secondary" data-bpm-save-state>完成登录后保存连接</span><button class="btn btn-primary ms-auto" data-bpm-control data-bpm-save>检查并保存</button></div></section>`;
bindInput(r);$('[data-bpm-close]').onclick=()=>{if(!r.busy)close(r);};
container.querySelectorAll('[data-target]').forEach(button=>button.onclick=async()=>{if(!valid(r)||r.busy)return;r.busy=true;controls(r);try{await r.queue;if(r.failed)throw Error('输入未送达,请重新打开登录窗口。');if(valid(r)){r.operation=api(route(id,'login/navigate'),{target:button.dataset.target});await r.operation;}}catch(error){feedback(error.message);}finally{r.busy=false;controls(r);}});
const fill=$('[data-bpm-fill-account]');if(fill)fill.onclick=async()=>{
if(!valid(r)||r.busy)return;r.busy=true;controls(r);
try{await r.queue;if(!valid(r))return;if(r.failed)throw Error('输入未送达,请关闭后重新打开登录窗口。');r.operation=api(route(id,'login/fill-account'),{});const result=await r.operation;if(valid(r))feedback(result.message,result.filled?'success':'warning');}
catch(error){feedback(error.message);}finally{r.busy=false;controls(r);}
};
$('[data-bpm-save]').onclick=async()=>{
if(!valid(r)||r.busy)return;r.busy=true;controls(r);$('[data-bpm-close]').disabled=true;$('[data-bpm-save-state]').textContent='正在检查连接…';
try{await r.queue;if(!valid(r))return;if(r.failed)throw Error('输入未送达,请关闭后重新打开登录窗口。');r.operation=api(route(id,'login/save'),{});const result=await r.operation;if(!valid(r))return;update(result,id);const saved=result.connection||result;feedback(saved.status==='connected'?'连接已检查并保存。':'请完成登录后再次检查。',saved.status==='connected'?'success':'warning');}
catch(error){feedback(error.message);}finally{r.busy=false;if(valid(r)){controls(r);$('[data-bpm-close]').disabled=false;$('[data-bpm-save-state]').textContent='完成登录后保存连接';}}
};
frame(r);
}catch(error){if(valid(r)){remote=null;drawCards();feedback(error.message);}}
}
function bindInput(r){
const image=$('[data-bpm-frame]'),input=$('[data-bpm-input]'),surface=image.closest('.bpm-screen');let composing=false,committed='';
const text=value=>{if(!value)return;for(let i=0;i<value.length;i+=2000)enqueue(r,{type:'text',text:value.slice(i,i+2000)});};
image.onpointerdown=event=>{if(!valid(r)||r.busy||event.button!==0)return;event.preventDefault();const rect=image.getBoundingClientRect();if(!rect.width||!rect.height)return;enqueue(r,{type:'click',x:Math.max(0,Math.min(r.viewport.width-1,Math.round((event.clientX-rect.left)*r.viewport.width/rect.width))),y:Math.max(0,Math.min(r.viewport.height-1,Math.round((event.clientY-rect.top)*r.viewport.height/rect.height)))});input.style.left=`${Math.max(0,Math.min(surface.clientWidth-2,event.clientX-rect.left))}px`;input.style.top=`${Math.max(0,Math.min(surface.clientHeight-24,event.clientY-rect.top))}px`;input.focus({preventScroll:true});};
image.addEventListener('wheel',event=>{event.preventDefault();const multiplier=event.deltaMode===1?16:event.deltaMode===2?r.viewport.height:1;enqueue(r,{type:'scroll',deltaX:Math.max(-2000,Math.min(2000,Math.round(event.deltaX*multiplier))),deltaY:Math.max(-2000,Math.min(2000,Math.round(event.deltaY*multiplier)))});},{passive:false});
input.oncompositionstart=()=>{composing=true;committed='';};
input.oncompositionend=event=>{composing=false;committed=event.data||input.value;text(committed);input.value='';};
input.oninput=event=>{if(composing||event.isComposing)return;const value=event.data??input.value;if(committed&&value===committed){committed='';input.value='';return;}committed='';text(value);input.value='';};
input.onpaste=event=>{event.preventDefault();committed='';text(event.clipboardData?.getData('text/plain')||'');input.value='';};
const keydown=event=>{
if(event.isComposing||composing||event.keyCode===229)return;
const keys=['Tab','Enter','Backspace','Delete','ArrowLeft','ArrowRight','ArrowUp','ArrowDown','Home','End','Escape'];
if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==='v')return;
let key=keys.includes(event.key)?event.key:null;
if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==='a')key='Control+A';
if(key){event.preventDefault();committed='';enqueue(r,{type:'key',key});input.value='';}else if(event.ctrlKey||event.metaKey||event.altKey)event.preventDefault();else if(event.key.length===1){event.preventDefault();committed='';text(event.key);input.value='';}
};
input.onkeydown=keydown;surface.onkeydown=event=>{if(event.target!==input)keydown(event);};surface.onpaste=event=>{if(event.target!==input)input.onpaste(event);};
}
try{
data=await api('/workspace');if(!live())return;connections=data.connections||[];
container.innerHTML=`<div data-bpm-feedback hidden role="alert"></div><div class="connection-layout bpm-layout"><div><div id="bpm-list"></div></div>${user.role==='admin'?`<form class="card" id="connection-create"><div class="card-header"><h2 class="card-title">添加 BPM 连接</h2></div><div class="card-body"><div class="mb-3"><label class="form-label required" for="connection-name">连接名称</label><input class="form-control" id="connection-name" required maxlength="100" placeholder="例如:业务团队 BPM"></div><div><label class="form-label required" for="connection-owner">负责人</label><select class="form-select" id="connection-owner" required><option value="">请选择负责人</option>${(data.members||[]).filter(m=>m.role!=='viewer').map(m=>`<option value="${esc(m.username)}">${esc(m.username)}</option>`).join('')}</select></div></div><div class="card-footer text-end"><button class="btn btn-primary" type="submit">创建连接</button></div></form>`:''}</div><div id="bpm-remote" aria-live="polite"></div>`;
if(user.role==='admin')$('#connection-create').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type=submit]');button.disabled=true;try{const result=await api('/connections',{name:$('#connection-name').value.trim(),owner:$('#connection-owner').value});if(!live())return;connections.unshift(result.connection||result);event.target.reset();drawCards();feedback('连接已创建。','success');}catch(error){feedback(error.message);}finally{if(live())button.disabled=false;}};
drawCards();
connections.filter(c=>c.status!=='disabled'&&authorized(c)).forEach(c=>loadAccount(c.id).then(refreshAccountSummary).catch(error=>feedback(error.message)));
}catch(error){if(live())throw error;}
}
return {mount,dispose};
})();
+3
View File
@@ -0,0 +1,3 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>订单通知中心</title><link href="/vendor/tabler.css" rel="stylesheet"><link href="/app.css" rel="stylesheet"></head>
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/bpm.js" defer></script><script src="/workspace.js" defer></script><script src="/mail.js" defer></script><script src="/orders.js" defer></script><script src="/app.js" defer></script></body></html>
+30
View File
@@ -0,0 +1,30 @@
'use strict';
window.MailViews=(()=>{
let api,esc,formatDate,notify,user;
const labels={pending:'待确认',active:'已生效',archived:'历史版本',rejected:'已忽略'};
const colors={pending:'yellow',active:'green',archived:'secondary',rejected:'secondary'};
const split=v=>v.split(/[,;,;\s]+/).map(x=>x.trim()).filter(Boolean);
const stateBadge=t=>`<span class="badge bg-${colors[t.status]||'secondary'}-lt">${labels[t.status]||esc(t.status)}</span>`;
async function action(button,work){const label=button.textContent;button.disabled=true;button.textContent='处理中…';try{await work();}catch(e){notify(e.message,'danger');}finally{if(button.isConnected){button.disabled=false;button.textContent=label;}}}
function configure(options){({api,esc,formatDate,notify,user}=options);}
async function accounts(container,isActive=()=>true){
const data=await api('/mail');if(!isActive())return;const admin=user.role==='admin';
container.innerHTML=`<div class="card mb-3"><div class="card-body d-flex flex-wrap align-items-center gap-3"><div><h2 class="card-title mb-1">托管邮箱</h2><div class="text-secondary">SMTP 发信 · IMAP 收信 · 每分钟检查模板邮件</div></div>${admin?'<button class="btn btn-primary ms-auto" id="mail-add">添加邮箱</button>':''}</div></div><div id="mail-editor"></div><div class="row row-cards">${data.channels.map(c=>`<div class="col-lg-6"><div class="card h-100"><div class="card-header"><h3 class="card-title">${esc(c.name)}</h3><span class="badge bg-${c.enabled?'blue':'secondary'}-lt ms-auto">${c.enabled?'收信已开启':'收信已暂停'}</span></div><div class="card-body"><div class="fw-medium mb-3">${esc(c.email)}</div><div class="d-flex gap-2 flex-wrap mb-3"><span class="badge bg-${c.state.smtp?'green':'yellow'}-lt">SMTP ${c.state.smtp?'已连接':'待检查'}</span><span class="badge bg-${c.state.imap?'green':'yellow'}-lt">IMAP ${c.state.imap?'已连接':'待检查'}</span></div><div class="text-secondary">${esc(c.state.message)}</div><div class="small text-secondary mt-2">上次检查:${formatDate(c.state.checkedAt)}<br>上次收信:${formatDate(c.state.pollAt)}</div><div class="small mt-3 text-secondary">模板发件人:${esc(c.senders.join('、'))}</div></div>${admin?`<div class="card-footer btn-list"><button class="btn btn-sm" data-edit="${c.id}">管理邮箱</button><button class="btn btn-sm" data-verify="${c.id}">检查连接</button><button class="btn btn-sm btn-primary" data-poll="${c.id}" ${c.enabled?'':'disabled'}>立即收信</button><a class="btn btn-sm" href="#templates">查看模板</a></div>`:''}</div></div>`).join('')||'<div class="col-12"><div class="card card-body text-center text-secondary py-5">尚未添加托管邮箱</div></div>'}</div><div class="card mt-3"><div class="card-body"><h3 class="card-title">用邮件提交模板</h3><p>新建邮件发送到托管邮箱,主题填写 <code>[模板][产品线]发信标题</code>,正文及附件作为模板。省略产品线时使用默认模板。</p><div class="text-secondary">发件人须在允许名单中。首次收取近 7 天邮件,新模板在“模板与收件群组”中预览确认后生效。</div></div></div><details class="card mt-3"><summary class="card-body cursor-pointer">最近收信记录(${data.receipts.length})</summary><div class="table-responsive"><table class="table card-table"><thead><tr><th>时间 / 邮箱</th><th>结果</th></tr></thead><tbody>${data.receipts.map(r=>`<tr><td class="small">${formatDate(r.at)}<div class="text-secondary">${esc(data.channels.find(c=>c.id===r.channel_id)?.name||'—')}</div></td><td>${esc(r.detail)}</td></tr>`).join('')||'<tr><td colspan="2" class="text-secondary">暂无收信记录</td></tr>'}</tbody></table></div></details>${data.sends.length?`<details class="card mt-3"><summary class="card-body cursor-pointer">测试发信记录</summary><div class="table-responsive"><table class="table card-table"><tbody>${data.sends.map(s=>`<tr><td>${formatDate(s.at)}</td><td>${esc(data.channels.find(c=>c.id===s.channel_id)?.email||'—')}</td><td>${({sent:'已提交至邮件服务器',unknown:'结果待核对',sending:'发送中'})[s.status]||esc(s.status)}</td></tr>`).join('')}</tbody></table></div></details>`:''}`;
if(!admin)return;container.querySelector('#mail-add').onclick=()=>editor();
container.querySelectorAll('[data-edit]').forEach(b=>b.onclick=()=>editor(data.channels.find(c=>c.id===b.dataset.edit)));
for(const type of ['verify','poll'])container.querySelectorAll(`[data-${type}]`).forEach(b=>b.onclick=()=>action(b,async()=>{await api(`/mail/channels/${b.dataset[type]}/${type}`,{});if(isActive()){await accounts(container,isActive);notify(type==='verify'?'连接检查完成。':'收信检查完成。');}}));
function editor(c){const endpoint=(kind,port)=>{const v=c?.[kind.toLowerCase()]||{host:'',port,security:'tls',user:''};return `<div class="col-lg-6"><fieldset class="form-fieldset"><legend class="float-none w-auto fs-4">${kind}</legend><div class="mb-3"><label class="form-label required" for="${kind}-host">${kind} 服务器</label><input id="${kind}-host" class="form-control" required maxlength="253" placeholder="${kind.toLowerCase()}.company.com" value="${esc(v.host)}"></div><div class="row mb-3"><div class="col-5"><label class="form-label required" for="${kind}-port">${kind} 端口</label><input type="number" min="1" max="65535" id="${kind}-port" class="form-control" required value="${v.port}"></div><div class="col-7"><label class="form-label" for="${kind}-security">${kind} 加密方式</label><select class="form-select" id="${kind}-security"><option value="tls" ${v.security==='tls'?'selected':''}>SSL / TLS</option><option value="starttls" ${v.security==='starttls'?'selected':''}>STARTTLS</option></select></div></div><div class="mb-3"><label class="form-label required" for="${kind}-user">${kind} 登录账号</label><input id="${kind}-user" class="form-control" required maxlength="254" autocomplete="off" value="${esc(v.user)}"></div><div><label class="form-label ${c?'':'required'}" for="${kind}-password">${kind} 密码 / 授权码</label><input id="${kind}-password" type="password" class="form-control" maxlength="2048" autocomplete="new-password" ${c?'':'required'} placeholder="${c?'留空保留已保存密码':'填写邮箱密码或授权码'}"></div></fieldset></div>`;};const host=container.querySelector('#mail-editor');host.innerHTML=`<form class="card mb-3" id="mail-form" autocomplete="off"><div class="card-header"><h3 class="card-title">${c?'管理邮箱':'添加邮箱'}</h3><button class="btn btn-sm ms-auto" type="button" id="mail-cancel">取消</button></div><div class="card-body"><div class="row g-3"><div class="col-md-6"><label class="form-label required" for="mail-name">邮箱名称</label><input id="mail-name" class="form-control" required maxlength="80" value="${esc(c?.name||'')}"></div><div class="col-md-6"><label class="form-label required" for="mail-address">邮箱地址</label><input id="mail-address" type="email" class="form-control" required maxlength="254" value="${esc(c?.email||'')}"></div>${endpoint('SMTP',465)}${endpoint('IMAP',993)}<div class="col-12"><label class="form-label required" for="mail-senders">允许提交模板的发件人</label><textarea id="mail-senders" class="form-control" rows="2" required placeholder="同事邮箱,多个地址用逗号或换行分隔">${esc(c?.senders.join('\n')||'')}</textarea></div><div class="col-12"><label class="form-check form-switch"><input id="mail-enabled" class="form-check-input" type="checkbox" ${c?.enabled?'checked':''}><span class="form-check-label">启用模板收信</span></label><div class="form-hint">可先保存并检查连接,再开启定时收信。公司邮箱需已开通 SMTP 和 IMAP。</div></div></div><div class="text-danger mt-3" id="mail-save-error" role="alert"></div></div><div class="card-footer text-end"><button class="btn btn-primary" type="submit">保存邮箱</button></div></form>`;
host.querySelector('#mail-cancel').onclick=()=>host.replaceChildren();host.scrollIntoView({block:'start',behavior:'smooth'});host.querySelector('#mail-form').onsubmit=async event=>{event.preventDefault();const button=event.submitter;button.disabled=true;host.querySelector('#mail-save-error').textContent='';try{const read=id=>host.querySelector('#'+id).value;const connection=kind=>({host:read(kind+'-host'),port:Number(read(kind+'-port')),security:read(kind+'-security'),user:read(kind+'-user'),password:read(kind+'-password')});await api('/mail/channels',{...(c?{id:c.id,version:c.version}:{}),name:read('mail-name'),email:read('mail-address'),smtp:connection('SMTP'),imap:connection('IMAP'),senders:split(read('mail-senders')),enabled:host.querySelector('#mail-enabled').checked});host.querySelectorAll('[type="password"]').forEach(e=>e.value='');if(isActive()){await accounts(container,isActive);notify('邮箱已保存。');}}catch(e){if(isActive())host.querySelector('#mail-save-error').textContent=e.message;}finally{if(button.isConnected)button.disabled=false;}};
}
}
async function templates(container,isActive=()=>true){
const data=await api('/mail');if(!isActive())return;const admin=user.role==='admin';let filter='pending';
container.innerHTML=`<div class="card mb-3"><div class="card-header flex-wrap gap-3"><h2 class="card-title">发信模板</h2><div class="ms-auto"><a class="btn btn-sm" href="#mail">邮箱管理</a></div></div><div class="card-body"><p class="mb-2">向托管邮箱发送 <code>[模板][产品线]发信标题</code>,新版本将在这里等待确认。未填写产品线时作为默认模板。</p><div class="small text-secondary">可用变量:<code>{{产品线}}</code>、<code>{{订单号}}</code>、<code>{{日期}}</code>、<code>{{订单列表}}</code></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||'默认模板')} · ${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=()=>action(b,()=>detail(b.dataset.template)));};draw();container.querySelector('#template-filter').onchange=event=>{filter=event.target.value;draw();};
async function detail(id){const t=await api('/mail/templates/'+id);if(!isActive())return;const pending=t.status==='pending',host=container.querySelector('#mail-template-detail');host.innerHTML=`<form class="card mb-3" id="template-review"><div class="card-header gap-2"><h3 class="card-title">模板预览</h3>${stateBadge(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.map(c=>`<option value="${c.id}">${esc(c.name)}</option>`).join('')}</select></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.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>':''}${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=()=>host.replaceChildren();
if(pending&&admin){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,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()){await templates(container,isActive);notify('模板已确认生效。');}}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()){await templates(container,isActive);notify('模板已忽略。');}});}
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('测试邮件已提交至邮件服务器。');});});
}
}
return {configure,accounts,templates};
})();
+52
View File
@@ -0,0 +1,52 @@
'use strict';
window.OrderViews=(()=>{
let api,esc,formatDate,notify,user,filters={q:'',connectionId:''};
const configure=options=>{if(user?.username!==options.user.username)filters={q:'',connectionId:''};({api,esc,formatDate,notify,user}=options);};
async function records(container,isActive,renderPdf){
let initial;
try{initial=await api('/bpm-scan');}catch(cause){
if(!isActive())return;
container.innerHTML=`<div class="alert alert-warning">${esc(cause.message)}</div><button class="btn mb-3" id="pdf-fallback">PDF 导出记录</button><div id="pdf-fallback-panel"></div>`;
container.querySelector('#pdf-fallback').onclick=()=>renderPdf(container.querySelector('#pdf-fallback-panel'),isActive).catch(e=>notify(e.message,'danger'));return;
}
if(!isActive())return;
let mode='arrivals',before='',loading=false,revision=0,watching=false,lastSignature='',status=initial;
const names=new Map(initial.connections.map(c=>[c.id,c.name]));
const nodeLabel=value=>value==='sysInform'?'知会':value||'—';
container.innerHTML=`<div class="btn-list mb-3"><button class="btn btn-primary" id="arrivals-tab">流程到达记录</button><button class="btn" id="pdf-tab">PDF 导出记录</button></div><div id="order-panel"></div>`;
const panel=container.querySelector('#order-panel');
const active=()=>isActive()&&mode==='arrivals';
function toolbar(){panel.innerHTML=`<section class="card mb-4"><div class="card-header flex-wrap gap-3"><div><h2 class="card-title mb-1">BPM 自动扫描</h2><div class="text-secondary small" id="scan-summary"></div></div><div class="ms-auto btn-list"><a class="btn" href="#bpm">管理连接</a>${user.role!=='viewer'?'<button class="btn btn-primary" id="scan-now">立即扫描</button>':''}</div></div><div class="card-body"><form id="arrival-filter" class="row g-3 align-items-end"><div class="col-md-6"><label class="form-label" for="arrival-query">搜索流程记录</label><input class="form-control" id="arrival-query" value="${esc(filters.q)}" placeholder="流水号、流程名、标题或发起人" maxlength="200"></div><div class="col-md-4"><label class="form-label" for="arrival-connection">BPM 连接</label><select class="form-select" id="arrival-connection"><option value="">全部连接</option>${initial.connections.map(c=>`<option value="${esc(c.id)}" ${c.id===filters.connectionId?'selected':''}>${esc(c.name)}${c.status==='disabled'?'(已停用)':''}</option>`).join('')}</select></div><div class="col-md-2"><button class="btn w-100" type="submit">查询</button></div></form><div id="scan-result" class="small mt-3" role="status"></div>${user.role==='admin'?`<details class="mt-3"><summary class="text-secondary">扫描设置</summary><form id="scan-config" class="d-flex flex-wrap align-items-center gap-3 mt-3"><label class="form-check form-switch mb-0"><input id="scan-enabled" class="form-check-input" type="checkbox" ${status.config.enabled?'checked':''}><span class="form-check-label">自动扫描</span></label><label class="d-flex align-items-center gap-2">间隔(分钟)<input id="scan-interval" class="form-control scan-interval" type="number" min="1" max="1440" required value="${status.config.intervalMinutes}"></label><button class="btn" type="submit">保存设置</button><a href="#calendar" class="small">业务日历</a></form></details>`:''}</div></section><div class="d-flex align-items-center mb-3"><h2 class="h3 m-0">按到达日期</h2><span class="text-secondary small ms-auto" id="arrival-count"></span></div><div id="arrival-groups"></div><div class="text-center mt-3"><button id="arrival-more" class="btn" hidden>加载更早日期</button></div>`;
panel.querySelector('#arrival-filter').onsubmit=event=>{event.preventDefault();filters={q:panel.querySelector('#arrival-query').value.trim(),connectionId:panel.querySelector('#arrival-connection').value};load(false).catch(showError);};
panel.querySelector('#arrival-more').onclick=()=>load(true).catch(showError);
panel.querySelector('#scan-config')?.addEventListener('submit',async event=>{event.preventDefault();const button=event.target.querySelector('button');button.disabled=true;try{status.config=await api('/bpm-scan/config',{enabled:panel.querySelector('#scan-enabled').checked,intervalMinutes:Number(panel.querySelector('#scan-interval').value)});if(active()){summary();notify('扫描设置已保存。');}}catch(e){showError(e);}finally{button.disabled=false;}});
panel.querySelector('#scan-now')?.addEventListener('click',async()=>{
const button=panel.querySelector('#scan-now');button.disabled=true;
try{const selected=panel.querySelector('#arrival-connection').value,connections=status.connections.filter(c=>c.status!=='disabled'&&(!selected||c.id===selected)&&(user.role==='admin'||c.owner===user.username));if(!connections.length)throw Error('没有可扫描的连接,请先在 BPM 连接中完成登录。');
for(const c of connections)await api('/bpm-scan/run',{connectionId:c.id});if(active()){panel.querySelector('#scan-result').textContent='正在扫描…';await refresh();watch();}
}catch(e){showError(e);}finally{if(active())button.disabled=false;}
});summary();
}
function showError(e){if(active())notify(e.message,'danger');}
function summary(){
if(!active())return;panel.querySelector('#scan-summary').textContent=`${status.config.enabled?'已开启':'已暂停'} · 每 ${status.config.intervalMinutes} 分钟 · 按业务日历运行`;
const latest=status.runs[0],ok=status.runs.find(r=>r.status==='success');
const el=panel.querySelector('#scan-result');el.className='small mt-3 '+(latest?.status==='error'?'text-danger':'text-secondary');
el.textContent=latest?.status==='running'?'正在扫描…':latest?.status==='error'?`${names.get(latest.connectionId)||'BPM'}:${latest.message}`:ok?`扫描完成 · ${formatDate(ok.finishedAt)} · 本次 ${ok.seen} 条,新增 ${ok.added} 条`:'尚无扫描记录';
}
function groupHtml(group){return `<details open class="card arrival-day mb-4" data-arrival-day="${esc(group.day)}"><summary class="card-header"><span class="arrival-date">${esc(group.day)}</span><span class="badge bg-blue-lt ms-3">${group.items.length} 条</span><span class="small text-secondary ms-auto">到达时间 · 北京时间</span></summary><div class="table-responsive"><table class="table table-vcenter card-table arrival-table"><thead><tr><th>到达时间 / 连接</th><th>流水号 / 流程</th><th>标题</th><th>发起人 / 节点</th></tr></thead><tbody>${group.items.map(row=>`<tr><td class="text-secondary small">${formatDate(row.arrivedAt)}<div class="mt-1">${esc(names.get(row.connectionId)||'已删除连接')}</div></td><td><strong>${esc(row.serialNum||'—')}</strong><div class="text-secondary small mt-1">${esc(row.processName||'—')}</div></td><td class="arrival-subject">${esc(row.subject||'—')}</td><td>${esc(row.initiator||'—')}<div class="text-secondary small mt-1">${esc(nodeLabel(row.activityName))}</div></td></tr>`).join('')}</tbody></table></div></details>`;}
async function load(append=false){
if(loading&&append)return;loading=true;const request=++revision;
try{const params=new URLSearchParams({...filters,...(append&&before?{before}:{} )});const result=await api('/arrivals?'+params);if(!active()||request!==revision)return;
const groups=panel.querySelector('#arrival-groups'),html=result.groups.map(groupHtml).join('');if(append)groups.insertAdjacentHTML('beforeend',html);else groups.innerHTML=html||'<div class="card"><div class="card-body text-center text-secondary py-5">暂无匹配的流程记录</div></div>';
before=result.nextBefore;panel.querySelector('#arrival-more').hidden=!before;panel.querySelector('#arrival-count').textContent=`共 ${result.total} 条流程`;
}finally{if(request===revision)loading=false;}
}
async function refresh(){const next=await api('/bpm-scan');if(!active())return;status=next;summary();const signature=JSON.stringify(status.runs.map(r=>[r.id,r.status]));if(lastSignature&&signature!==lastSignature)await load(false);lastSignature=signature;}
function watch(){if(watching||!active())return;watching=true;setTimeout(async()=>{watching=false;if(!active())return;try{await refresh();}catch(e){showError(e);}if(active())watch();},status.runs.some(r=>r.status==='running')?1500:10000);}
container.querySelector('#pdf-tab').onclick=async()=>{mode='pdf';++revision;container.querySelector('#pdf-tab').classList.add('btn-primary');container.querySelector('#arrivals-tab').classList.remove('btn-primary');try{await renderPdf(panel,()=>isActive()&&mode==='pdf');}catch(e){if(isActive())notify(e.message,'danger');}};
container.querySelector('#arrivals-tab').onclick=async()=>{mode='arrivals';container.querySelector('#arrivals-tab').classList.add('btn-primary');container.querySelector('#pdf-tab').classList.remove('btn-primary');toolbar();try{await load();await refresh();watch();}catch(e){showError(e);}};
toolbar();await load();await refresh();watch();
}
return {configure,records};
})();
+74
View File
@@ -0,0 +1,74 @@
'use strict';
window.WorkspaceViews=(()=>{
let api,esc,formatDate,notify,user;
const components={bpm:'BPM',pdf:'PDF 导出',archive:'归档',mail:'邮件',system:'系统',rules:'业务规则'};
const states={open:['待认领','blue'],in_progress:['处理中','orange'],verifying:['待验证','purple'],resolved:['已关闭','green']};
const priorities={normal:'普通',high:'高',critical:'紧急'};
const activityText=value=>String(value??'').replaceAll('保存监管策略草稿','保存监管设置').replaceAll('仅保存草稿,不执行自动处理或通知','更新负责人、通知方式和重试上限').replaceAll('(尚未接入登录)','');
const actions={create:'建立异常',claim:'认领',transfer:'转交',verify:'提交验证',resolve:'核验关闭',reopen:'重新打开'};
const dateKey=date=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai',year:'numeric',month:'2-digit',day:'2-digit'}).format(date);
const today=()=>dateKey(new Date());
const admin=()=>user.role==='admin';
const operator=()=>user.role==='admin'||user.role==='operator';
const lock=allowed=>allowed?'':'disabled';
const empty=(title,text)=>`<div class="workspace-empty"><span aria-hidden="true">◌</span><h3>${esc(title)}</h3><p class="text-secondary mb-0">${esc(text)}</p></div>`;
const badge=item=>`<span class="badge bg-${(states[item.status]||states.open)[1]}-lt">${(states[item.status]||states.open)[0]}</span>`;
const memberOptions=(members,selected='',blank='未分配')=>`<option value="">${esc(blank)}</option>`+members.filter(m=>m.role!=='viewer').map(m=>`<option value="${esc(m.username)}" ${m.username===selected?'selected':''}>${esc(m.username)}</option>`).join('');
const readonly=allowed=>allowed?'':`<div class="alert alert-info">当前账号可查看本页记录。此页面的变更操作需要相应管理或操作权限,请联系管理员。</div>`;
const feedback=(container,message,type='danger')=>{const el=container.querySelector('[data-feedback]');if(el){el.className=`alert alert-${type}`;el.textContent=message;el.hidden=false;}notify(message,type);};
const policy=(key,schedule,overrides)=>{const override=overrides.find(item=>item.date===key);if(override)return override;const day=new Date(key+'T12:00:00Z').getUTCDay();const work=schedule.weekends||![0,6].includes(day);return {kind:work?'workday':'restday',scan:work,send:work,note:''};};
function configure(options){({api,esc,formatDate,notify,user}=options);}
async function overview(container,isActive=()=>true){
const [data,settings,pdf]=await Promise.all([api('/workspace'),api('/settings'),api('/overview')]);if(!isActive())return;
const exceptions=data.exceptions||[],connections=data.connections||[],active=exceptions.filter(e=>e.status!=='resolved'),mine=active.filter(e=>e.owner===user.username);
const day=policy(today(),settings.schedule,data.calendar.overrides);
const activity=(data.audit||[]).slice(0,5);
container.innerHTML=`${pdf.scan?`<a href="#records" class="card mb-3 text-reset text-decoration-none"><div class="card-body d-flex align-items-center flex-wrap gap-3"><span class="badge bg-${pdf.scan.config.enabled?'green':'secondary'}-lt">扫描${pdf.scan.config.enabled?'已开启':'已暂停'}</span><strong>BPM 流程到达记录</strong><span class="text-secondary">已收录 ${pdf.scan.total} 条 · 按到达日期查看</span><span class="ms-auto">查看记录 →</span></div></a>`:''}<div class="workspace-welcome"><div><div class="workspace-eyebrow">WORKSPACE / 团队协作</div><h2>让每一项工作,都有清晰的去向。</h2><p>安排业务日期、协同处理异常,逐步准备订单通知流程。</p></div><a href="#exceptions" class="btn btn-primary">查看异常待办 <span aria-hidden="true">↗</span></a></div>
<div class="workspace-metrics"><a href="#exceptions" class="card metric-card metric-blue"><div class="card-body"><span class="metric-symbol" aria-hidden="true">☷</span><div class="subheader">待处理异常</div><div class="metric-number">${active.length}<span>项</span></div><div class="small text-secondary">其中 ${mine.length} 项由我负责</div></div></a><a href="#calendar" class="card metric-card metric-green"><div class="card-body"><span class="metric-symbol" aria-hidden="true">▦</span><div class="subheader">今日业务安排</div><div class="metric-word">${day.kind==='pause'?'暂停日':day.kind==='restday'?'休息日':'工作日'}</div><div class="small text-secondary">采集${day.scan?'允许':'暂停'} · 发送计划${day.send?'允许':'暂停'}</div></div></a><a href="#bpm" class="card metric-card metric-blue"><div class="card-body"><span class="metric-symbol" aria-hidden="true">⇄</span><div class="subheader">BPM 连接档案</div><div class="metric-number">${connections.filter(c=>c.status!=='disabled').length}<span>个</span></div><div class="small text-secondary">${connections.filter(c=>c.status==='connected').length} 个已连接 · ${connections.filter(c=>['unchecked','login_required','error'].includes(c.status)).length} 个待处理</div></div></a><a href="#records" class="card metric-card metric-green"><div class="card-body"><span class="metric-symbol" aria-hidden="true">▤</span><div class="subheader">已完成 PDF</div><div class="metric-number">${Number(pdf.stats?.completed)||0}<span>份</span></div><div class="small text-secondary">查看导出记录与下载文件</div></div></a></div>
<div class="workspace-grid"><section class="card"><div class="card-header"><h3 class="card-title">需要关注</h3><a class="workspace-text-link ms-auto" href="#exceptions">全部异常 →</a></div>${active.length?`<div class="list-group list-group-flush">${active.slice(0,5).map(e=>`<a class="list-group-item workspace-task" href="#exceptions"><span class="task-priority priority-${esc(e.priority)}"></span><div class="flex-fill"><strong>${esc(e.title)}</strong><div class="small text-secondary mt-1">${esc(components[e.component]||e.component)} · ${esc(e.owner||'未分配')} · ${formatDate(e.updatedAt)}</div></div>${badge(e)}</a>`).join('')}</div>`:empty('当前没有待处理异常','遇到流程或文件问题时,可建立异常并交给团队处理。')}</section><section class="card"><div class="card-header"><h3 class="card-title">业务自动处理</h3><span class="badge bg-yellow-lt ms-auto">未启用</span></div><div class="card-body"><div class="capability-row"><span class="status-dot status-green"></span><div><strong>团队工作台</strong><div class="text-secondary small">日历、异常协作与操作留痕已可用</div></div></div><div class="capability-row"><span class="status-dot status-blue"></span><div><strong>自动处理未启用</strong></div></div><div class="capability-row"><span class="status-dot status-yellow"></span><div><strong>服务连接</strong><div class="text-secondary small">查看连接状态</div></div></div></div></section><section class="card"><div class="card-header"><h3 class="card-title">最近活动</h3><a class="workspace-text-link ms-auto" href="#audit">操作记录 →</a></div>${activity.length?`<div class="card-body activity-list">${activity.map(a=>`<div class="activity-item"><span class="activity-dot"></span><div><strong>${esc(activityText(actions[a.action]||a.action))}</strong><p class="small text-secondary mb-1">${esc(activityText(typeof a.detail==='object'?JSON.stringify(a.detail):a.detail||a.note||''))}</p><div class="small text-secondary">${esc(a.actor)} · ${formatDate(a.at)}</div></div></div>`).join('')}</div>`:empty('工作台已就绪','团队保存日历或处理异常后,活动会显示在这里。')}</section><section class="card overview-guide"><div class="card-body"><div class="workspace-eyebrow">下一步</div><h3>从安排工作日开始</h3><p class="text-secondary">设置公司调休与暂停日期,再为异常指定负责人。</p><a class="btn" href="#calendar">打开业务日历 →</a><div class="planned-slots"><span class="text-secondary small">下两个计划发送时段 · 北京时间</span>${(pdf.nextSlots||[]).map(slot=>`<div>${formatDate(slot)}</div>`).join('')}</div><hr><a class="workspace-text-link" href="#records">查看现有订单与 PDF 导出记录 →</a></div></section></div>`;
}
async function calendar(container,isActive=()=>true){
const [data,settings]=await Promise.all([api('/workspace'),api('/settings')]);if(!isActive())return;
let version=data.calendar.version,overrides=structuredClone(data.calendar.overrides),selected=today(),month=selected.slice(0,7),dirty=false,busy=false;
const schedule=settings.schedule;
container.innerHTML=`${readonly(admin())}<div class="workspace-note mb-4">公司安排优先于每周默认设置。</div><div data-feedback hidden role="alert"></div><div class="calendar-layout"><section class="card"><div class="card-header flex-wrap gap-2"><div class="btn-list"><button class="btn btn-icon" id="calendar-prev" aria-label="上个月">‹</button><button class="btn btn-icon" id="calendar-next" aria-label="下个月">›</button></div><h2 class="card-title" id="calendar-month"></h2><button class="btn btn-sm ms-auto" id="calendar-today">回到今天</button></div><div class="card-body calendar-body"><div class="calendar-weekdays">${['一','二','三','四','五','六','日'].map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid" id="calendar-grid"></div><div class="calendar-legend"><span><i class="legend-dot legend-work"></i>工作日</span><span><i class="legend-dot legend-rest"></i>休息日</span><span><i class="legend-dot legend-override"></i>公司覆盖</span></div></div><div class="card-footer d-flex align-items-center gap-2 flex-wrap"><span class="text-secondary small" id="calendar-save-state">所有更改已保存</span><button class="btn btn-primary ms-auto" id="calendar-save" ${lock(admin())}>保存日历</button></div></section><div><form class="card" id="day-form"><div class="card-header"><h3 class="card-title" id="selected-date"></h3></div><div class="card-body"><div id="day-source" class="mb-3"></div><fieldset ${lock(admin())}><div class="mb-3"><label for="day-kind" class="form-label">日期类型</label><select id="day-kind" class="form-select"><option value="workday">工作日 / 调休上班</option><option value="restday">休息日 / 公司假期</option><option value="pause">暂停日</option></select></div><label class="form-check form-switch mb-3"><input type="checkbox" class="form-check-input" id="day-scan"><span class="form-check-label">允许计划采集</span></label><label class="form-check form-switch mb-3"><input type="checkbox" class="form-check-input" id="day-send"><span class="form-check-label">允许计划发送</span></label><div><label for="day-note" class="form-label">安排说明</label><textarea id="day-note" class="form-control" rows="3" maxlength="500" placeholder="例如:公司调休、系统维护"></textarea></div></fieldset></div><div class="card-footer d-flex gap-2 flex-wrap"><button type="button" class="btn" id="day-reset" ${lock(admin())}>恢复每周默认</button><button type="submit" class="btn btn-primary ms-auto" ${lock(admin())}>应用到此日期</button></div></form><section class="card mt-3"><div class="card-body"><h3 class="card-title">每周默认</h3><p class="text-secondary mb-2">${schedule.weekends?'周一至周日':'周一至周五'}允许计划采集、发送</p><div class="schedule-pills">${(schedule.times||[]).map(t=>`<span>${esc(t)}</span>`).join('')}</div><a class="workspace-text-link d-block mt-3" href="#schedule">编辑默认发送计划 →</a></div></section></div></div>`;
const $=selector=>container.querySelector(selector);
function draw(){if(!isActive())return;const [year,m]=month.split('-').map(Number),start=(new Date(year,m-1,1).getDay()+6)%7,days=new Date(year,m,0).getDate();$('#calendar-month').textContent=`${year} 年 ${m} 月`;$('#calendar-save-state').textContent=dirty?'有未保存的日历更改':'所有更改已保存';$('#calendar-save').disabled=!admin()||!dirty||busy;$('#day-form').querySelector('fieldset').disabled=!admin()||busy;$('#day-form').querySelector('button[type=submit]').disabled=!admin()||busy;$('#day-reset').disabled=!admin()||busy;
$('#calendar-grid').innerHTML=Array.from({length:start},()=>'<div class="calendar-blank"></div>').join('')+Array.from({length:days},(_,i)=>{const key=`${month}-${String(i+1).padStart(2,'0')}`,p=policy(key,schedule,overrides),override=overrides.some(o=>o.date===key);return `<button class="calendar-day ${p.kind==='workday'?'is-work':'is-rest'} ${override?'is-override':''} ${selected===key?'is-selected':''} ${today()===key?'is-today':''}" data-date="${key}" aria-pressed="${selected===key}" aria-label="${key} ${p.kind==='workday'?'工作日':p.kind==='pause'?'暂停日':'休息日'}"><span class="day-number">${i+1}${today()===key?'<i>今</i>':''}</span><span class="day-kind">${p.kind==='workday'?'工作':p.kind==='pause'?'暂停':'休息'}</span><span class="day-policy">采${p.scan?' ✓':' —'} · 发${p.send?' ✓':' —'}</span>${override?'<span class="override-mark" aria-label="公司覆盖"></span>':''}</button>`;}).join('');
container.querySelectorAll('[data-date]').forEach(button=>button.onclick=()=>{selected=button.dataset.date;draw();});const p=policy(selected,schedule,overrides);$('#selected-date').textContent=selected;$('#day-source').innerHTML=`<span class="badge bg-${overrides.some(o=>o.date===selected)?'blue':'secondary'}-lt">${overrides.some(o=>o.date===selected)?'公司日期覆盖':'跟随每周默认'}</span>`;$('#day-kind').value=p.kind;$('#day-scan').checked=p.scan;$('#day-send').checked=p.send;$('#day-note').value=p.note||'';$('#day-scan').disabled=!admin()||busy||p.kind==='pause';$('#day-send').disabled=!admin()||busy||p.kind==='pause';
}
function move(delta){const [y,m]=month.split('-').map(Number),d=new Date(y,m-1+delta,1);month=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}`;draw();}
$('#calendar-prev').onclick=()=>move(-1);$('#calendar-next').onclick=()=>move(1);$('#calendar-today').onclick=()=>{selected=today();month=selected.slice(0,7);draw();};
$('#day-kind').onchange=()=>{const work=$('#day-kind').value==='workday';$('#day-scan').checked=work;$('#day-send').checked=work;$('#day-scan').disabled=$('#day-kind').value==='pause';$('#day-send').disabled=$('#day-kind').value==='pause';};
$('#day-form').onsubmit=e=>{e.preventDefault();if(!admin())return;overrides=overrides.filter(o=>o.date!==selected);overrides.push({date:selected,kind:$('#day-kind').value,scan:$('#day-scan').checked,send:$('#day-send').checked,note:$('#day-note').value.trim()});dirty=true;draw();};
$('#day-reset').onclick=()=>{if(!admin())return;overrides=overrides.filter(o=>o.date!==selected);dirty=true;draw();};
$('#calendar-save').onclick=async()=>{busy=true;draw();try{const result=await api('/calendar',{version,overrides});if(!isActive())return;const saved=result.calendar||result;version=saved.version;overrides=structuredClone(saved.overrides);dirty=false;feedback(container,'业务日历已保存。','success');}catch(error){if(isActive())feedback(container,error.message);}finally{busy=false;if(isActive())draw();}};draw();
}
async function exceptions(container,isActive=()=>true){
let data=await api('/workspace');if(!isActive())return;let selectedId=null,search='',filter='',list=data.exceptions||[];
container.innerHTML=`${readonly(operator())}<div data-feedback hidden role="alert"></div><div class="exceptions-toolbar"><div class="d-flex gap-2 flex-wrap"><input class="form-control" id="exception-search" aria-label="搜索异常" placeholder="搜索标题、说明或负责人"><select class="form-select" id="exception-filter" aria-label="筛选异常状态"><option value="">全部状态</option>${Object.entries(states).map(([key,value])=>`<option value="${key}">${value[0]}</option>`).join('')}</select></div><button class="btn btn-primary" id="exception-new" ${lock(operator())}>+ 建立异常</button></div><div class="exception-layout"><section class="card"><div class="card-header"><h2 class="card-title">异常工作队列</h2><span class="badge bg-blue-lt" id="exception-count"></span></div><div id="exception-list"></div></section><div id="exception-detail"></div></div>`;
const $=selector=>container.querySelector(selector);
function drawList(){if(!isActive())return;const visible=list.filter(e=>(!filter||e.status===filter)&&(!search||[e.title,e.description,e.owner,components[e.component]].join(' ').toLowerCase().includes(search)));$('#exception-count').textContent=`${visible.length} 项`;$('#exception-list').innerHTML=visible.length?`<div class="list-group list-group-flush">${visible.map(e=>`<button class="list-group-item list-group-item-action exception-item ${e.id===selectedId?'selected':''}" data-exception="${esc(e.id)}"><div class="d-flex gap-2 align-items-start"><span class="task-priority priority-${esc(e.priority)}"></span><strong class="flex-fill">${esc(e.title)}</strong>${badge(e)}</div><div class="text-secondary small mt-2">${esc(components[e.component])} · ${esc(priorities[e.priority])} · ${esc(e.owner||'未分配')}</div><div class="text-secondary small mt-1">${formatDate(e.updatedAt)}</div></button>`).join('')}</div>`:empty('没有匹配的异常','可调整搜索条件,或建立新的异常待办。');container.querySelectorAll('[data-exception]').forEach(button=>button.onclick=()=>{selectedId=button.dataset.exception;drawList();drawDetail();});}
function drawCreate(){selectedId=null;drawList();$('#exception-detail').innerHTML=`<form class="card" id="exception-create"><div class="card-header"><h3 class="card-title">建立异常</h3></div><div class="card-body"><fieldset ${lock(operator())}><div class="mb-3"><label class="form-label required" for="exception-title">异常标题</label><input class="form-control" id="exception-title" required maxlength="200" placeholder="用一句话描述需要处理的问题"></div><div class="row g-3 mb-3"><div class="col-sm-6"><label class="form-label" for="exception-component">所属环节</label><select class="form-select" id="exception-component">${Object.entries(components).map(([k,v])=>`<option value="${k}">${v}</option>`).join('')}</select></div><div class="col-sm-6"><label class="form-label" for="exception-priority">优先级</label><select class="form-select" id="exception-priority">${Object.entries(priorities).map(([k,v])=>`<option value="${k}">${v}</option>`).join('')}</select></div></div><div class="mb-3"><label class="form-label" for="exception-owner">负责人</label><select class="form-select" id="exception-owner">${memberOptions(data.members)}</select></div><div><label class="form-label required" for="exception-description">问题说明</label><textarea class="form-control" id="exception-description" rows="5" maxlength="5000" required placeholder="记录现象、影响范围与需要协助的事项"></textarea></div></fieldset></div><div class="card-footer text-end"><button class="btn btn-primary" type="submit" ${lock(operator())}>保存异常</button></div></form>`;
$('#exception-create').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type=submit]');button.disabled=true;try{const result=await api('/exceptions',{title:$('#exception-title').value.trim(),component:$('#exception-component').value,priority:$('#exception-priority').value,description:$('#exception-description').value.trim(),owner:$('#exception-owner').value});if(!isActive())return;const exception=result.exception||result;list.unshift(exception);selectedId=exception.id;drawList();drawDetail();feedback(container,'异常已建立。','success');}catch(error){if(isActive())feedback(container,error.message);}finally{if(isActive())button.disabled=false;}};
}
function drawDetail(){const item=list.find(e=>e.id===selectedId);if(!item){$('#exception-detail').innerHTML=`<section class="card">${empty('选择一项异常','在左侧查看队列,或建立一项需要团队处理的异常。')}</section>`;return;}const mine=item.owner===user.username||admin(),canManage=operator()&&mine;
const available=[];if(operator()&&!item.owner&&item.status==='open')available.push('claim');if(canManage&&item.status!=='resolved')available.push('transfer');if(canManage&&item.status==='in_progress')available.push('verify');if(canManage&&item.status==='verifying')available.push('resolve');if(canManage&&item.status==='resolved')available.push('reopen');
$('#exception-detail').innerHTML=`<section class="card"><div class="card-header gap-2"><h3 class="card-title">异常详情</h3>${badge(item)}</div><div class="card-body"><h3 class="exception-title">${esc(item.title)}</h3><div class="text-secondary small mb-3">${esc(components[item.component])} · ${esc(priorities[item.priority])}优先级 · 负责人 ${esc(item.owner||'未分配')}</div><p class="exception-description">${esc(item.description||'暂无问题说明')}</p><div class="text-secondary small">建立于 ${formatDate(item.createdAt)}<br>更新于 ${formatDate(item.updatedAt)}</div>${available.length?`<hr><form id="exception-action"><div class="mb-3"><label class="form-label" for="action-kind">处理操作</label><select class="form-select" id="action-kind">${available.map(a=>`<option value="${a}">${actions[a]}</option>`).join('')}</select></div><div id="transfer-owner-wrap" class="mb-3" hidden><label class="form-label required" for="transfer-owner">转交给</label><select class="form-select" id="transfer-owner">${memberOptions(data.members.filter(m=>m.username!==item.owner),'','请选择负责人')}</select></div><div class="mb-3"><label class="form-label" id="action-note-label" for="action-note">处理说明</label><textarea class="form-control" id="action-note" rows="3" maxlength="3000" placeholder="填写处理说明"></textarea><div class="form-hint" id="action-hint">操作将记入此异常的流转历史。</div></div><button class="btn btn-primary" type="submit">确认操作</button></form>`:'<div class="workspace-note mt-3">当前为只读状态,或此异常需要由负责人 / 管理员继续处理。</div>'}</div><div class="card-header border-top"><h3 class="card-title">流转历史</h3></div><div class="card-body activity-list">${(item.history||[]).length?item.history.map(h=>`<div class="activity-item"><span class="activity-dot"></span><div><strong>${esc(actions[h.action]||h.action)}</strong><div class="small text-secondary">${esc(h.actor)} · ${formatDate(h.at)}</div>${h.toOwner?`<div class="small mt-1">转交给 ${esc(h.toOwner)}</div>`:''}${h.note?`<p class="history-note mb-0 mt-2">${esc(h.note)}</p>`:''}</div></div>`).join(''):'<p class="text-secondary mb-0">暂无流转记录</p>'}</div></section>`;
if(available.length){const update=()=>{const kind=$('#action-kind').value;$('#transfer-owner-wrap').hidden=kind!=='transfer';$('#transfer-owner').required=kind==='transfer';$('#action-note').required=['transfer','verify','resolve','reopen'].includes(kind);$('#action-note-label').textContent=kind==='resolve'?'核验结果(必填)':'处理说明'+($('#action-note').required?'(必填)':'');$('#action-hint').textContent=kind==='resolve'?'请填写核验结果。':'操作将记入此异常的流转历史。';};$('#action-kind').onchange=update;update();$('#exception-action').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button');button.disabled=true;try{const result=await api(`/exceptions/${encodeURIComponent(item.id)}/action`,{version:item.version,action:$('#action-kind').value,owner:$('#action-kind').value==='transfer'?$('#transfer-owner').value:undefined,note:$('#action-note').value.trim()});if(!isActive())return;const updated=result.exception||result;list=list.map(e=>e.id===item.id?updated:e);drawList();drawDetail();feedback(container,'异常状态已更新。','success');}catch(error){if(isActive())feedback(container,error.message+' 如有并发变更,请刷新后重试。');}finally{if(isActive())button.disabled=false;}};}
}
$('#exception-search').oninput=e=>{search=e.target.value.trim().toLowerCase();drawList();};$('#exception-filter').onchange=e=>{filter=e.target.value;drawList();};$('#exception-new').onclick=drawCreate;drawList();if(list.length){selectedId=list.find(e=>e.status!=='resolved')?.id||list[0].id;drawList();}drawDetail();
}
async function bpm(container,isActive=()=>true){return window.BpmLogin.mount(container,{api,esc,formatDate,notify,user,isActive});}
async function supervisor(container,isActive=()=>true){
const data=await api('/workspace');if(!isActive())return;let draft=data.supervisor;
container.innerHTML=`${readonly(admin())}<div data-feedback hidden role="alert"></div><div class="workspace-grid"><form class="card" id="supervisor-form"><div class="card-header"><h2 class="card-title">监管设置</h2><span class="badge bg-blue-lt ms-auto">未启用</span></div><div class="card-body"><fieldset ${lock(admin())}><div class="mb-3"><label class="form-label" for="supervisor-owner">默认负责人</label><select class="form-select" id="supervisor-owner">${memberOptions(data.members,draft.defaultOwner)}</select></div><div class="mb-3"><label class="form-label" for="supervisor-channel">通知方式</label><select class="form-select" id="supervisor-channel"><option value="none" ${draft.notifyChannel==='none'?'selected':''}>不通知</option><option value="manual" ${draft.notifyChannel==='manual'?'selected':''}>人工通知</option></select></div><div><label class="form-label" for="supervisor-attempts">重试上限</label><select class="form-select" id="supervisor-attempts">${[0,1,2,3].map(n=>`<option value="${n}" ${draft.maxAttempts===n?'selected':''}>${n} 次${n===0?'(不重试)':''}</option>`).join('')}</select></div></fieldset></div><div class="card-footer d-flex align-items-center"><span class="text-secondary small">整个团队共用</span><button class="btn btn-primary ms-auto" type="submit" ${lock(admin())}>保存设置</button></div></form><div><section class="card"><div class="card-header"><h3 class="card-title">业务自动处理</h3></div><div class="card-body"><div class="capability-row"><span class="status-dot status-green"></span><div><strong>异常管理</strong><div class="small text-secondary">认领、转交与处理记录</div></div></div><div class="capability-row"><span class="status-dot status-yellow"></span><div><strong>ZCode · 未连接</strong></div></div><div class="capability-row"><span class="status-dot status-yellow"></span><div><strong>自动通知 · 未启用</strong></div></div></div></section></div></div>`;
container.querySelector('#supervisor-form').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type=submit]');button.disabled=true;try{const result=await api('/supervisor',{version:draft.version,defaultOwner:container.querySelector('#supervisor-owner').value,notifyChannel:container.querySelector('#supervisor-channel').value,maxAttempts:Number(container.querySelector('#supervisor-attempts').value)});if(!isActive())return;draft=result.supervisor||result;feedback(container,'设置已保存。','success');}catch(error){if(isActive())feedback(container,error.message);}finally{if(isActive())button.disabled=!admin();}};
}
return {configure,overview,calendar,exceptions,bpm,supervisor,activityText};
})();
+17
View File
@@ -0,0 +1,17 @@
@echo off
setlocal
where node.exe >nul 2>nul
if errorlevel 1 goto bundled
node.exe "%~dp0src\server.cjs"
goto finished
:bundled
set "ORDER_NODE=%USERPROFILE%\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe"
if not exist "%ORDER_NODE%" goto missing
"%ORDER_NODE%" "%~dp0src\server.cjs"
goto finished
:missing
echo Node.js 22+ is required. Install from https://nodejs.org
pause
exit /b 1
:finished
if errorlevel 1 pause
+19
View File
@@ -0,0 +1,19 @@
@echo off
setlocal
docker version --format "{{.Server.Version}}" >nul 2>nul
if errorlevel 1 goto engine
docker compose -f "%~dp0deploy\qinglong\compose.yaml" up -d
if errorlevel 1 goto failed
echo QingLong: http://127.0.0.1:5700
echo Complete first-time account setup in the panel.
pause
exit /b 0
:engine
echo Docker Linux engine is unavailable. Start Docker Desktop first.
echo If WSL 2 is missing, complete the Docker Desktop environment setup.
pause
exit /b 1
:failed
echo QingLong startup failed. See Docker output above.
pause
exit /b 1
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more