diff --git a/.gitattributes b/.gitattributes index 2996ec1e..f97328e3 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,6 +4,7 @@ *.png binary *.jpg binary *.ico binary +docs/companion-a-b-evidence/*.tap binary tests/fixtures/legacy-workbench-0.1/dist-server/server.mjs binary docs/workers-*.tap binary docs/workers-*.log binary diff --git a/AGENTS.md b/AGENTS.md index c1ddda20..535b564f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,7 @@ # Agent Workbench项目执行规范 +1.16在feat/mobile-companion-1.16实施;A/B默认关闭HTTPS网关、Windows DPAPI证书、单次配对/设备授权与脱敏投影已通过54/54本地专项及关联回归,见docs/QA-1.16.md。手机C界面、D真实原Runtime竞争、E断线/撤销和F真实iPhone/独立发行仍分别验收,不能把390px/协议夹具写成真实手机交付。正式1.15宿主保持;新增开发仅使用自有项目/数据/端口,不读取原模型Key。手机根证书需用户手动信任,不自动改OS信任或防火墙。 + ## 范围与目标 本仓库专注AI编程与能力研究工作台。其他项目不纳入本项目计划或代码。用户确定的研究对象为Codex、Claude Code、Cursor、DeepSeek Harness、WorkBuddy及DSH-purge;目标是将有证据的机制独立开发成自有Harness内置能力。 diff --git a/docs/PLAN-1.16.md b/docs/PLAN-1.16.md index 3df2b747..981b51d6 100644 --- a/docs/PLAN-1.16.md +++ b/docs/PLAN-1.16.md @@ -1,6 +1,6 @@ # 1.16 手机伴随端执行方案 -2026-10-31记录。前置[1.15](PLAN-1.15.md)已完成F独立发行、正式桌面安装与保留状态部署;本文为下一阶段计划,手机功能尚未实施。 +2026-10-31开始实施。从06c9fac/正式1.15.0在feat/mobile-companion-1.16推进。用户选择iPhone,可配合证书信任;Windows提供HTTPS服务,iPhone Safari/PWA通过同Wi-Fi联调。各切片状态以[实际验收](QA-1.16.md)为准,未通过的能力不能计为交付。 ## 用户成果 diff --git a/docs/QA-1.16.md b/docs/QA-1.16.md new file mode 100644 index 00000000..6b5349b0 --- /dev/null +++ b/docs/QA-1.16.md @@ -0,0 +1,15 @@ +# 1.16 手机伴随端验收 + +2026-10-31从06c9fac/正式1.15.0接续。A–F按PLAN-1.16实施,当前尚未完成手机交付。用户指定iPhone,可配合手动证书信任。自有项目、数据和端口用于开发;正式宿主、Provider与已有数据保持,真实模型请求为0。 + +## A/B:网关与权限(本地通过,手机设备仍待验) + +验收须覆盖实际受信TLS、原宿主/用户/网关身份、错误/过期/重复/并发消费、设备事务、关闭监听不结束任务,以及不泄露原管理token。默认关闭远程监听。 + +16项新增专项通过:实际TLS链/IP SAN、根证书指纹、加密块重开、真实Windows CurrentUser DPAPI、120秒/单次/并发配对、事务失败可恢复、项目/操作权限、轮换/到期/撤销、原宿主变化、原事件seq分页、数据投影和限速。与API、Runtime、桌面宿主和各热升级回归合并,最终54/54通过、0跳过。原TAP见[切片证据](companion-a-b-evidence/final.tap)。手机未知结果原登记不重放和审批请求幂等已作协议夹具检查,实际原Runtime竞争与界面另在D验收。 + +保留首轮14/16失败原因和首轮关联30/38及修复后36/38原日志:两项夹具身份/TLS目标问题已修正;qrcode CommonJS在ESM发行中动态require失败已补createRequire;新增网关变量命名与旧升级定位源码标记冲突已消除,旧定位契约不放宽。最终54项包含直接启动与0.1旧宿主两次真实升级。正式4318未操作;不以本地通过宣称真实iPhone完成。 + +## C–F:实施中及待验收 + +设备权限、独立手机界面、审批/停止、事件恢复、真实iPhone与独立发行分别记录。手机界面和浏览器模拟结果不能代替真实设备步骤;没有设备结果时不记完整交付。 diff --git a/docs/RETROSPECTIVE-1.16.md b/docs/RETROSPECTIVE-1.16.md new file mode 100644 index 00000000..bfad4efe --- /dev/null +++ b/docs/RETROSPECTIVE-1.16.md @@ -0,0 +1,13 @@ +# 1.16 手机伴随端切片回顾 + +## 开始前核对 + +06c9fac已完成1.15,工作区干净。继承既有正式安装及数据,原候选及失败证据不改写。1.16以Windows为执行宿主,iPhone Safari/PWA通过同Wi-Fi和受信HTTPS联调,不依赖原生iOS构建链。 + +按A–F推进,每个切片记录观察、问题、修正、验证和本地提交。先实现TLS与权限契约,再用真实原任务完成手机流程,最终由真实iPhone和独立发行结果判断交付。 + +## A/B本地回顾 + +原Store只保留桌面update observer;手机采用授权项目SQL分页和短轮询,不新增需跨热升级迁移的观察者。网关使用原宿主/用户/目录身份,默认关闭,升级前必须关闭独立监听;关闭手机网关不调用Runtime.stop。新的手机授权仅保留摘要和脱敏审计。TLS私钥通过原CurrentUser DPAPI保护,未读取Provider凭据。 + +首轮未经过bundle执行而只看源码会漏掉二维码库CommonJS依赖;实际API/热升级回归及时揭示了问题。修复发行require后又发现源码定位标记冲突,保持原管理处理器唯一标记并对旧版连续升级复验。最终54/54通过,原失败与最终日志分别保存。接下来独立手机entry、设备管理和任务详情进入C;审批/停止的真实原Runtime竞争、断线及实际iPhone分别验收。 diff --git a/docs/companion-a-b-evidence/final.tap b/docs/companion-a-b-evidence/final.tap new file mode 100644 index 00000000..6563423b --- /dev/null +++ b/docs/companion-a-b-evidence/final.tap @@ -0,0 +1,334 @@ +TAP version 13 +# Subtest: the bundled local service enforces host, origin, token and JSON object contracts +ok 1 - the bundled local service enforces host, origin, token and JSON object contracts + --- + duration_ms: 2196.4388 + type: 'test' + ... +# Subtest: an in-flight connection probe prevents configuration changes and another probe until its actual result returns +ok 2 - an in-flight connection probe prevents configuration changes and another probe until its actual result returns + --- + duration_ms: 2349.1248 + type: 'test' + ... +# Subtest: API review applies verified content, detects conflicts, exports sessions and keeps keys in memory +ok 3 - API review applies verified content, detects conflicts, exports sessions and keeps keys in memory + --- + duration_ms: 4792.0407 + type: 'test' + ... +# Subtest: a real bundle restart preserves proposals, interrupts old approvals and requests fresh consent on resume +ok 4 - a real bundle restart preserves proposals, interrupts old approvals and requests fresh consent on resume + --- + duration_ms: 10638.2515 + type: 'test' + ... +# Subtest: runtime diagnostics and model-response validation use actual records and preserve the saved connection +ok 5 - runtime diagnostics and model-response validation use actual records and preserve the saved connection + --- + duration_ms: 2092.0017 + type: 'test' + ... +# Subtest: persistent event replay is read-only and keeps run/artifact identity across reconnects +ok 6 - persistent event replay is read-only and keeps run/artifact identity across reconnects + --- + duration_ms: 8166.6453 + type: 'test' + ... +# Subtest: pairing is short lived, single-use, generation-bound and validates exact permissions +ok 7 - pairing is short lived, single-use, generation-bound and validates exact permissions + --- + duration_ms: 927.8145 + type: 'test' + ... +# Subtest: device transaction failure neither consumes the ticket nor leaves a credential +ok 8 - device transaction failure neither consumes the ticket nor leaves a credential + --- + duration_ms: 600.8998 + type: 'test' + ... +# Subtest: devices have project and action boundaries; rotation, expiration, revocation and host changes reject old authority +ok 9 - devices have project and action boundaries; rotation, expiration, revocation and host changes reject old authority + --- + duration_ms: 866.5426 + type: 'test' + ... +# Subtest: persistent registry stores hashes and a bounded audit, never raw credentials +ok 10 - persistent registry stores hashes and a bounded audit, never raw credentials + --- + duration_ms: 719.0345 + type: 'test' + ... +# Subtest: real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint +ok 11 - real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint + --- + duration_ms: 876.1836 + type: 'test' + ... +# Subtest: TLS sealing failure leaves listener closed and no plaintext or successful TLS registration +ok 12 - TLS sealing failure leaves listener closed and no plaintext or successful TLS registration + --- + duration_ms: 810.7035 + type: 'test' + ... +# Subtest: HTTP pairing is concurrent single-use; secure cookie and strict origin/host checks +ok 13 - HTTP pairing is concurrent single-use; secure cookie and strict origin/host checks + --- + duration_ms: 880.9565 + type: 'test' + ... +# Subtest: gateway never exposes management routes, arbitrary assets or unpaired project data +ok 14 - gateway never exposes management routes, arbitrary assets or unpaired project data + --- + duration_ms: 801.8095 + type: 'test' + ... +# Subtest: authorized project events paginate from original seq without leaking other project events or payloads +ok 15 - authorized project events paginate from original seq without leaking other project events or payloads + --- + duration_ms: 1443.8762 + type: 'test' + ... +# Subtest: remote task projection excludes raw model history, host configuration, tool input and credentials +ok 16 - remote task projection excludes raw model history, host configuration, tool input and credentials + --- + duration_ms: 652.4081 + type: 'test' + ... +# Subtest: permission checks apply to direct remote mutation, not only UI controls +ok 17 - permission checks apply to direct remote mutation, not only UI controls + --- + duration_ms: 1052.8996 + type: 'test' + ... +# Subtest: approval fingerprint and exact task/revision are bound; duplicate requests never execute twice +ok 18 - approval fingerprint and exact task/revision are bound; duplicate requests never execute twice + --- + duration_ms: 1080.0886 + type: 'test' + ... +# Subtest: unknown original operation is recorded and never replayed after response failure +ok 19 - unknown original operation is recorded and never replayed after response failure + --- + duration_ms: 1025.2881 + type: 'test' + ... +# Subtest: revocation and gateway closure reject old access without invoking runtime stop +ok 20 - revocation and gateway closure reject old access without invoking runtime stop + --- + duration_ms: 1049.2047 + type: 'test' + ... +# Subtest: rate limits reject pairing brute force and do not persist candidate secrets +ok 21 - rate limits reject pairing brute force and do not persist candidate secrets + --- + duration_ms: 1015.942 + type: 'test' + ... +# Subtest: real Windows CurrentUser DPAPI persists only a sealed CA and reopens it +ok 22 - real Windows CurrentUser DPAPI persists only a sealed CA and reopens it + --- + duration_ms: 1911.906 + type: 'test' + ... +# Subtest: a rebuilt source archive binds actual generated client assets and retains its original running identity after disk changes +ok 23 - a rebuilt source archive binds actual generated client assets and retains its original running identity after disk changes + --- + duration_ms: 1582.7944 + type: 'test' + ... +# Subtest: host challenge proof rejects a stale challenge, changed identity and changed signature +ok 24 - host challenge proof rejects a stale challenge, changed identity and changed signature + --- + duration_ms: 0.7783 + type: 'test' + ... +# Subtest: stop confirmation binds the original instance, creation and loaded runtime +ok 25 - stop confirmation binds the original instance, creation and loaded runtime + --- + duration_ms: 0.192 + type: 'test' + ... +# Subtest: state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON +ok 26 - state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON + --- + duration_ms: 1026.9164 + type: 'test' + ... +# Subtest: failed registration publishes no initialized memory and can complete after its actual inputs are supplied +ok 27 - failed registration publishes no initialized memory and can complete after its actual inputs are supplied + --- + duration_ms: 2405.8429 + type: 'test' + ... +# Subtest: host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered +ok 28 - host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered + --- + duration_ms: 1.63 + type: 'test' + ... +# Subtest: host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts +ok 29 - host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts + --- + duration_ms: 582.57 + type: 'test' + ... +# Subtest: a stop from the event loop interrupts immediate model replies before later tools +ok 30 - a stop from the event loop interrupts immediate model replies before later tools + --- + duration_ms: 1490.7039 + type: 'test' + ... +# Subtest: a stop after the first tool preserves a complete interrupted multi-call protocol group +ok 31 - a stop after the first tool preserves a complete interrupted multi-call protocol group + --- + duration_ms: 2160.1239 + type: 'test' + ... +# Subtest: the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands +ok 32 - the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands + --- + duration_ms: 5765.214 + type: 'test' + ... +# Subtest: denial prevents command execution and produces a paired denied result +ok 33 - denial prevents command execution and produces a paired denied result + --- + duration_ms: 1884.7637 + type: 'test' + ... +# Subtest: stopping during approval interrupts pending calls without executing or replaying them +ok 34 - stopping during approval interrupts pending calls without executing or replaying them + --- + duration_ms: 1521.9807 + type: 'test' + ... +# Subtest: stopping a running fixture command terminates its own process tree and retains uncertain state +ok 35 - stopping a running fixture command terminates its own process tree and retains uncertain state + --- + duration_ms: 2139.324 + type: 'test' + ... +# Subtest: command output decodes split UTF-8 and excludes the workbench key from child environment +ok 36 - command output decodes split UTF-8 and excludes the workbench key from child environment + --- + duration_ms: 1063.4353 + type: 'test' + ... +# Subtest: model-list testing uses a tentative key without changing the saved connection and redacts service errors +ok 37 - model-list testing uses a tentative key without changing the saved connection and redacts service errors + --- + duration_ms: 6.12 + type: 'test' + ... +# Subtest: truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities +ok 38 - truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities + --- + duration_ms: 3405.7791 + type: 'test' + ... +# Subtest: request projection keeps exact tool pairs and complete recent user instructions while preserving disk history +ok 39 - request projection keeps exact tool pairs and complete recent user instructions while preserving disk history + --- + duration_ms: 1371.9415 + type: 'test' + ... +# Subtest: a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes +ok 40 - a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes + --- + duration_ms: 4716.2931 + type: 'test' + ... +# Subtest: failed upgrade restores the original artifact object, provider and request handler +ok 41 - failed upgrade restores the original artifact object, provider and request handler + --- + duration_ms: 1794.2995 + type: 'test' + ... +# Subtest: claiming the same runtime owner twice preserves its original metadata and every database row +ok 42 - claiming the same runtime owner twice preserves its original metadata and every database row + --- + duration_ms: 762.0886 + type: 'test' + ... +# Subtest: sessions without controlled-engine history retain their prior export shape and never expose another session record +ok 43 - sessions without controlled-engine history retain their prior export shape and never expose another session record + --- + duration_ms: 1058.0759 + type: 'test' + ... +# Subtest: live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows +ok 44 - live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows + --- + duration_ms: 715.689 + type: 'test' + ... +# Subtest: an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects +ok 45 - an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects + --- + duration_ms: 947.9357 + type: 'test' + ... +# Subtest: an installation failure restores old managers, original record maps, handlers and all existing database rows +ok 46 - an installation failure restores old managers, original record maps, handlers and all existing database rows + --- + duration_ms: 1712.04 + type: 'test' + ... +# Subtest: the owned controlled driver remains an active session and project even after outer task activity has ended +ok 47 - the owned controlled driver remains an active session and project even after outer task activity has ended + --- + duration_ms: 846.4857 + type: 'test' + ... +# Subtest: release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory +ok 48 - release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory + --- + duration_ms: 909.3419 + type: 'test' + ... +# Subtest: hot upgrade adopts a retained virtual data root without reopening SQLite or changing rows, Provider or routing +ok 49 - hot upgrade adopts a retained virtual data root without reopening SQLite or changing rows, Provider or routing + --- + duration_ms: 1360.8202 + type: 'test' + ... +# Subtest: failed adoption restores the original virtual data-root name and original open database +ok 50 - failed adoption restores the original virtual data-root name and original open database + --- + duration_ms: 798.2686 + type: 'test' + ... +# Subtest: hot upgrade refreshes retained model and importer methods while preserving credential and routing objects +ok 51 - hot upgrade refreshes retained model and importer methods while preserving credential and routing objects + --- + duration_ms: 562.0017 + type: 'test' + ... +# Subtest: hot upgrade refuses active probes and restores retained model methods if installation fails +ok 52 - hot upgrade refuses active probes and restores retained model methods if installation fails + --- + duration_ms: 474.5689 + type: 'test' + ... +# Subtest: a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider +ok 53 - a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider + --- + duration_ms: 3312.8041 + type: 'test' + ... +# Subtest: the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection +ok 54 - the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection + --- + duration_ms: 6009.7972 + type: 'test' + ... +1..54 +# tests 54 +# suites 0 +# pass 54 +# fail 0 +# cancelled 0 +# skipped 0 +# todo 0 +# duration_ms 53648.534 diff --git a/docs/companion-a-b-evidence/first-bundle-failure.tap b/docs/companion-a-b-evidence/first-bundle-failure.tap new file mode 100644 index 00000000..7ca55836 --- /dev/null +++ b/docs/companion-a-b-evidence/first-bundle-failure.tap @@ -0,0 +1,556 @@ +TAP version 13 +# Subtest: the bundled local service enforces host, origin, token and JSON object contracts +not ok 1 - the bundled local service enforces host, origin, token and JSON object contracts + --- + duration_ms: 1003.4786 + type: 'test' + location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\api.test.mjs:8:1' + failureType: 'testCodeFailure' + error: |- + Workbench launch failed: file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11 + throw Error('Dynamic require of "' + x + '" is not supported'); + ^ + + Error: Dynamic require of "fs" is not supported + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + at node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + at ModuleJob.run (node:internal/modules/esm/module_job:561:25) + at async node:internal/modules/esm/loader:647:26 + + Node.js v24.22.1 + + code: 'ERR_ASSERTION' + name: 'AssertionError' + expected: true + actual: '' + operator: '==' + stack: |- + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + ModuleJob.run (node:internal/modules/esm/module_job:561:25) + async node:internal/modules/esm/loader:647:26 + launchWorkbench (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/helpers.mjs:94:10) + async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/api.test.mjs:9:34) + async Test.run (node:internal/test_runner/test:1409:7) + async startSubtestAfterBootstrap (node:internal/test_runner/harness:387:3) + ... +# Subtest: an in-flight connection probe prevents configuration changes and another probe until its actual result returns +not ok 2 - an in-flight connection probe prevents configuration changes and another probe until its actual result returns + --- + duration_ms: 725.1588 + type: 'test' + location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\api.test.mjs:27:1' + failureType: 'testCodeFailure' + error: |- + Workbench launch failed: file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11 + throw Error('Dynamic require of "' + x + '" is not supported'); + ^ + + Error: Dynamic require of "fs" is not supported + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + at node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + at ModuleJob.run (node:internal/modules/esm/module_job:561:25) + at async node:internal/modules/esm/loader:647:26 + + Node.js v24.22.1 + + code: 'ERR_ASSERTION' + name: 'AssertionError' + expected: true + actual: '' + operator: '==' + stack: |- + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + ModuleJob.run (node:internal/modules/esm/module_job:561:25) + async node:internal/modules/esm/loader:647:26 + launchWorkbench (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/helpers.mjs:94:10) + async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/api.test.mjs:28:32) + async Test.run (node:internal/test_runner/test:1409:7) + async Test.processPendingSubtests (node:internal/test_runner/test:974:7) + ... +# Subtest: API review applies verified content, detects conflicts, exports sessions and keeps keys in memory +not ok 3 - API review applies verified content, detects conflicts, exports sessions and keeps keys in memory + --- + duration_ms: 877.0347 + type: 'test' + location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\api.test.mjs:42:1' + failureType: 'testCodeFailure' + error: |- + Workbench launch failed: file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11 + throw Error('Dynamic require of "' + x + '" is not supported'); + ^ + + Error: Dynamic require of "fs" is not supported + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + at node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + at ModuleJob.run (node:internal/modules/esm/module_job:561:25) + at async node:internal/modules/esm/loader:647:26 + + Node.js v24.22.1 + + code: 'ERR_ASSERTION' + name: 'AssertionError' + expected: true + actual: '' + operator: '==' + stack: |- + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + ModuleJob.run (node:internal/modules/esm/module_job:561:25) + async node:internal/modules/esm/loader:647:26 + launchWorkbench (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/helpers.mjs:94:10) + async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/api.test.mjs:43:34) + async Test.run (node:internal/test_runner/test:1409:7) + async Test.processPendingSubtests (node:internal/test_runner/test:974:7) + ... +# Subtest: a real bundle restart preserves proposals, interrupts old approvals and requests fresh consent on resume +not ok 4 - a real bundle restart preserves proposals, interrupts old approvals and requests fresh consent on resume + --- + duration_ms: 959.4322 + type: 'test' + location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\api.test.mjs:76:1' + failureType: 'testCodeFailure' + error: |- + Workbench launch failed: file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11 + throw Error('Dynamic require of "' + x + '" is not supported'); + ^ + + Error: Dynamic require of "fs" is not supported + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + at node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + at ModuleJob.run (node:internal/modules/esm/module_job:561:25) + at async node:internal/modules/esm/loader:647:26 + + Node.js v24.22.1 + + code: 'ERR_ASSERTION' + name: 'AssertionError' + expected: true + actual: '' + operator: '==' + stack: |- + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + ModuleJob.run (node:internal/modules/esm/module_job:561:25) + async node:internal/modules/esm/loader:647:26 + launchWorkbench (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/helpers.mjs:94:10) + async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/api.test.mjs:77:34) + async Test.run (node:internal/test_runner/test:1409:7) + async Test.processPendingSubtests (node:internal/test_runner/test:974:7) + ... +# Subtest: runtime diagnostics and model-response validation use actual records and preserve the saved connection +not ok 5 - runtime diagnostics and model-response validation use actual records and preserve the saved connection + --- + duration_ms: 874.5208 + type: 'test' + location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\api.test.mjs:105:1' + failureType: 'testCodeFailure' + error: |- + Workbench launch failed: file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11 + throw Error('Dynamic require of "' + x + '" is not supported'); + ^ + + Error: Dynamic require of "fs" is not supported + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + at node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + at ModuleJob.run (node:internal/modules/esm/module_job:561:25) + at async node:internal/modules/esm/loader:647:26 + + Node.js v24.22.1 + + code: 'ERR_ASSERTION' + name: 'AssertionError' + expected: true + actual: '' + operator: '==' + stack: |- + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + ModuleJob.run (node:internal/modules/esm/module_job:561:25) + async node:internal/modules/esm/loader:647:26 + launchWorkbench (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/helpers.mjs:94:10) + async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/api.test.mjs:106:34) + async Test.run (node:internal/test_runner/test:1409:7) + async Test.processPendingSubtests (node:internal/test_runner/test:974:7) + ... +# Subtest: persistent event replay is read-only and keeps run/artifact identity across reconnects +not ok 6 - persistent event replay is read-only and keeps run/artifact identity across reconnects + --- + duration_ms: 707.8704 + type: 'test' + location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\api.test.mjs:122:1' + failureType: 'testCodeFailure' + error: |- + Workbench launch failed: file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11 + throw Error('Dynamic require of "' + x + '" is not supported'); + ^ + + Error: Dynamic require of "fs" is not supported + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + at node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + at ModuleJob.run (node:internal/modules/esm/module_job:561:25) + at async node:internal/modules/esm/loader:647:26 + + Node.js v24.22.1 + + code: 'ERR_ASSERTION' + name: 'AssertionError' + expected: true + actual: '' + operator: '==' + stack: |- + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + ModuleJob.run (node:internal/modules/esm/module_job:561:25) + async node:internal/modules/esm/loader:647:26 + launchWorkbench (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/helpers.mjs:94:10) + async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/api.test.mjs:123:34) + async Test.run (node:internal/test_runner/test:1409:7) + async Test.processPendingSubtests (node:internal/test_runner/test:974:7) + ... +# Subtest: a rebuilt source archive binds actual generated client assets and retains its original running identity after disk changes +ok 7 - a rebuilt source archive binds actual generated client assets and retains its original running identity after disk changes + --- + duration_ms: 1987.8439 + type: 'test' + ... +# Subtest: host challenge proof rejects a stale challenge, changed identity and changed signature +ok 8 - host challenge proof rejects a stale challenge, changed identity and changed signature + --- + duration_ms: 0.7577 + type: 'test' + ... +# Subtest: stop confirmation binds the original instance, creation and loaded runtime +ok 9 - stop confirmation binds the original instance, creation and loaded runtime + --- + duration_ms: 0.1309 + type: 'test' + ... +# Subtest: state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON +ok 10 - state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON + --- + duration_ms: 1286.9472 + type: 'test' + ... +# Subtest: failed registration publishes no initialized memory and can complete after its actual inputs are supplied +ok 11 - failed registration publishes no initialized memory and can complete after its actual inputs are supplied + --- + duration_ms: 2538.2104 + type: 'test' + ... +# Subtest: host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered +ok 12 - host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered + --- + duration_ms: 1.175 + type: 'test' + ... +# Subtest: host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts +ok 13 - host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts + --- + duration_ms: 936.5359 + type: 'test' + ... +# Subtest: a stop from the event loop interrupts immediate model replies before later tools +ok 14 - a stop from the event loop interrupts immediate model replies before later tools + --- + duration_ms: 1649.8051 + type: 'test' + ... +# Subtest: a stop after the first tool preserves a complete interrupted multi-call protocol group +ok 15 - a stop after the first tool preserves a complete interrupted multi-call protocol group + --- + duration_ms: 1918.1817 + type: 'test' + ... +# Subtest: the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands +ok 16 - the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands + --- + duration_ms: 4352.8588 + type: 'test' + ... +# Subtest: denial prevents command execution and produces a paired denied result +ok 17 - denial prevents command execution and produces a paired denied result + --- + duration_ms: 2118.9445 + type: 'test' + ... +# Subtest: stopping during approval interrupts pending calls without executing or replaying them +ok 18 - stopping during approval interrupts pending calls without executing or replaying them + --- + duration_ms: 1961.9679 + type: 'test' + ... +# Subtest: stopping a running fixture command terminates its own process tree and retains uncertain state +ok 19 - stopping a running fixture command terminates its own process tree and retains uncertain state + --- + duration_ms: 2129.2296 + type: 'test' + ... +# Subtest: command output decodes split UTF-8 and excludes the workbench key from child environment +ok 20 - command output decodes split UTF-8 and excludes the workbench key from child environment + --- + duration_ms: 1312.7886 + type: 'test' + ... +# Subtest: model-list testing uses a tentative key without changing the saved connection and redacts service errors +ok 21 - model-list testing uses a tentative key without changing the saved connection and redacts service errors + --- + duration_ms: 5.9883 + type: 'test' + ... +# Subtest: truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities +ok 22 - truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities + --- + duration_ms: 2884.9196 + type: 'test' + ... +# Subtest: request projection keeps exact tool pairs and complete recent user instructions while preserving disk history +ok 23 - request projection keeps exact tool pairs and complete recent user instructions while preserving disk history + --- + duration_ms: 1693.0511 + type: 'test' + ... +# Subtest: a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes +ok 24 - a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes + --- + duration_ms: 4525.4854 + type: 'test' + ... +# Subtest: failed upgrade restores the original artifact object, provider and request handler +ok 25 - failed upgrade restores the original artifact object, provider and request handler + --- + duration_ms: 1630.4765 + type: 'test' + ... +# Subtest: claiming the same runtime owner twice preserves its original metadata and every database row +ok 26 - claiming the same runtime owner twice preserves its original metadata and every database row + --- + duration_ms: 851.2513 + type: 'test' + ... +# Subtest: sessions without controlled-engine history retain their prior export shape and never expose another session record +ok 27 - sessions without controlled-engine history retain their prior export shape and never expose another session record + --- + duration_ms: 835.2472 + type: 'test' + ... +# Subtest: live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows +ok 28 - live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows + --- + duration_ms: 1006.5435 + type: 'test' + ... +# Subtest: an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects +ok 29 - an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects + --- + duration_ms: 898.6232 + type: 'test' + ... +# Subtest: an installation failure restores old managers, original record maps, handlers and all existing database rows +ok 30 - an installation failure restores old managers, original record maps, handlers and all existing database rows + --- + duration_ms: 1678.8204 + type: 'test' + ... +# Subtest: the owned controlled driver remains an active session and project even after outer task activity has ended +ok 31 - the owned controlled driver remains an active session and project even after outer task activity has ended + --- + duration_ms: 841.1664 + type: 'test' + ... +# Subtest: release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory +ok 32 - release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory + --- + duration_ms: 1075.3137 + type: 'test' + ... +# Subtest: hot upgrade adopts a retained virtual data root without reopening SQLite or changing rows, Provider or routing +ok 33 - hot upgrade adopts a retained virtual data root without reopening SQLite or changing rows, Provider or routing + --- + duration_ms: 1494.1818 + type: 'test' + ... +# Subtest: failed adoption restores the original virtual data-root name and original open database +ok 34 - failed adoption restores the original virtual data-root name and original open database + --- + duration_ms: 784.762 + type: 'test' + ... +# Subtest: hot upgrade refreshes retained model and importer methods while preserving credential and routing objects +ok 35 - hot upgrade refreshes retained model and importer methods while preserving credential and routing objects + --- + duration_ms: 958.6187 + type: 'test' + ... +# Subtest: hot upgrade refuses active probes and restores retained model methods if installation fails +ok 36 - hot upgrade refuses active probes and restores retained model methods if installation fails + --- + duration_ms: 871.3889 + type: 'test' + ... +# Subtest: a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider +not ok 37 - a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider + --- + duration_ms: 733.5798 + type: 'test' + location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\upgrade.test.mjs:10:1' + failureType: 'testCodeFailure' + error: |- + Workbench launch failed: file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11 + throw Error('Dynamic require of "' + x + '" is not supported'); + ^ + + Error: Dynamic require of "fs" is not supported + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + at node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + at ModuleJob.run (node:internal/modules/esm/module_job:561:25) + at async node:internal/modules/esm/loader:647:26 + + Node.js v24.22.1 + + code: 'ERR_ASSERTION' + name: 'AssertionError' + expected: true + actual: '' + operator: '==' + stack: |- + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:11:9 + node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:18654:16) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19085:23) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:19203:22) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:17:50) + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/server.mjs:38674:29 + ModuleJob.run (node:internal/modules/esm/module_job:561:25) + async node:internal/modules/esm/loader:647:26 + launchWorkbench (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/helpers.mjs:94:10) + async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/upgrade.test.mjs:11:32) + async Test.run (node:internal/test_runner/test:1409:7) + async startSubtestAfterBootstrap (node:internal/test_runner/harness:387:3) + ... +# Subtest: the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection +not ok 38 - the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection + --- + duration_ms: 2294.5523 + type: 'test' + location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\upgrade.test.mjs:38:1' + failureType: 'testCodeFailure' + error: |- + Runtime upgrade failed: Error: Dynamic require of "fs" is not supported + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:11:9 + at node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:18654:16) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:17:50) + at node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:19085:23) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:17:50) + at node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:19203:22) + at __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:17:50) + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:38675:29 + at ModuleJobSync.runSync (node:internal/modules/esm/module_job:665:37) + at ModuleLoader.importSyncForRequire (node:internal/modules/esm/loader:347:47) + code: 'ERR_TEST_FAILURE' + stack: |- + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:11:9 + node_modules/qrcode/lib/renderer/png.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:18654:16) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:17:50) + node_modules/qrcode/lib/server.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:19085:23) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:17:50) + node_modules/qrcode/lib/index.js (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:19203:22) + __require2 (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:17:50) + file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/dist-server/hot-upgrade.mjs:38675:29 + ModuleJobSync.runSync (node:internal/modules/esm/module_job:665:37) + ModuleLoader.importSyncForRequire (node:internal/modules/esm/loader:347:47) + upgradeRunning (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/upgrade-running.mjs:129:42) + process.processTicksAndRejections (node:internal/process/task_queues:104:5) + async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/upgrade.test.mjs:70:18) + async Test.run (node:internal/test_runner/test:1409:7) + async Test.processPendingSubtests (node:internal/test_runner/test:974:7) + ... +1..38 +# tests 38 +# suites 0 +# pass 30 +# fail 8 +# cancelled 0 +# skipped 0 +# todo 0 +# duration_ms 28091.1508 diff --git a/docs/companion-a-b-evidence/second-upgrade-failure.tap b/docs/companion-a-b-evidence/second-upgrade-failure.tap new file mode 100644 index 00000000..687163f7 --- /dev/null +++ b/docs/companion-a-b-evidence/second-upgrade-failure.tap @@ -0,0 +1,258 @@ +TAP version 13 +# Subtest: the bundled local service enforces host, origin, token and JSON object contracts +ok 1 - the bundled local service enforces host, origin, token and JSON object contracts + --- + duration_ms: 2398.5298 + type: 'test' + ... +# Subtest: an in-flight connection probe prevents configuration changes and another probe until its actual result returns +ok 2 - an in-flight connection probe prevents configuration changes and another probe until its actual result returns + --- + duration_ms: 2309.2915 + type: 'test' + ... +# Subtest: API review applies verified content, detects conflicts, exports sessions and keeps keys in memory +ok 3 - API review applies verified content, detects conflicts, exports sessions and keeps keys in memory + --- + duration_ms: 4303.8204 + type: 'test' + ... +# Subtest: a real bundle restart preserves proposals, interrupts old approvals and requests fresh consent on resume +ok 4 - a real bundle restart preserves proposals, interrupts old approvals and requests fresh consent on resume + --- + duration_ms: 10552.0269 + type: 'test' + ... +# Subtest: runtime diagnostics and model-response validation use actual records and preserve the saved connection +ok 5 - runtime diagnostics and model-response validation use actual records and preserve the saved connection + --- + duration_ms: 2035.1003 + type: 'test' + ... +# Subtest: persistent event replay is read-only and keeps run/artifact identity across reconnects +ok 6 - persistent event replay is read-only and keeps run/artifact identity across reconnects + --- + duration_ms: 7131.3767 + type: 'test' + ... +# Subtest: a rebuilt source archive binds actual generated client assets and retains its original running identity after disk changes +ok 7 - a rebuilt source archive binds actual generated client assets and retains its original running identity after disk changes + --- + duration_ms: 2018.4278 + type: 'test' + ... +# Subtest: host challenge proof rejects a stale challenge, changed identity and changed signature +ok 8 - host challenge proof rejects a stale challenge, changed identity and changed signature + --- + duration_ms: 0.6999 + type: 'test' + ... +# Subtest: stop confirmation binds the original instance, creation and loaded runtime +ok 9 - stop confirmation binds the original instance, creation and loaded runtime + --- + duration_ms: 0.1341 + type: 'test' + ... +# Subtest: state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON +ok 10 - state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON + --- + duration_ms: 1034.1621 + type: 'test' + ... +# Subtest: failed registration publishes no initialized memory and can complete after its actual inputs are supplied +ok 11 - failed registration publishes no initialized memory and can complete after its actual inputs are supplied + --- + duration_ms: 2269.7603 + type: 'test' + ... +# Subtest: host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered +ok 12 - host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered + --- + duration_ms: 1.0627 + type: 'test' + ... +# Subtest: host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts +ok 13 - host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts + --- + duration_ms: 715.8724 + type: 'test' + ... +# Subtest: a stop from the event loop interrupts immediate model replies before later tools +ok 14 - a stop from the event loop interrupts immediate model replies before later tools + --- + duration_ms: 1335.7391 + type: 'test' + ... +# Subtest: a stop after the first tool preserves a complete interrupted multi-call protocol group +ok 15 - a stop after the first tool preserves a complete interrupted multi-call protocol group + --- + duration_ms: 1918.681 + type: 'test' + ... +# Subtest: the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands +ok 16 - the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands + --- + duration_ms: 5023.739 + type: 'test' + ... +# Subtest: denial prevents command execution and produces a paired denied result +ok 17 - denial prevents command execution and produces a paired denied result + --- + duration_ms: 1862.7343 + type: 'test' + ... +# Subtest: stopping during approval interrupts pending calls without executing or replaying them +ok 18 - stopping during approval interrupts pending calls without executing or replaying them + --- + duration_ms: 1841.5925 + type: 'test' + ... +# Subtest: stopping a running fixture command terminates its own process tree and retains uncertain state +ok 19 - stopping a running fixture command terminates its own process tree and retains uncertain state + --- + duration_ms: 2199.5374 + type: 'test' + ... +# Subtest: command output decodes split UTF-8 and excludes the workbench key from child environment +ok 20 - command output decodes split UTF-8 and excludes the workbench key from child environment + --- + duration_ms: 1064.2569 + type: 'test' + ... +# Subtest: model-list testing uses a tentative key without changing the saved connection and redacts service errors +ok 21 - model-list testing uses a tentative key without changing the saved connection and redacts service errors + --- + duration_ms: 5.5337 + type: 'test' + ... +# Subtest: truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities +ok 22 - truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities + --- + duration_ms: 2544.29 + type: 'test' + ... +# Subtest: request projection keeps exact tool pairs and complete recent user instructions while preserving disk history +ok 23 - request projection keeps exact tool pairs and complete recent user instructions while preserving disk history + --- + duration_ms: 1579.8632 + type: 'test' + ... +# Subtest: a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes +ok 24 - a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes + --- + duration_ms: 4314.0651 + type: 'test' + ... +# Subtest: failed upgrade restores the original artifact object, provider and request handler +ok 25 - failed upgrade restores the original artifact object, provider and request handler + --- + duration_ms: 1941.2982 + type: 'test' + ... +# Subtest: claiming the same runtime owner twice preserves its original metadata and every database row +ok 26 - claiming the same runtime owner twice preserves its original metadata and every database row + --- + duration_ms: 844.3569 + type: 'test' + ... +# Subtest: sessions without controlled-engine history retain their prior export shape and never expose another session record +ok 27 - sessions without controlled-engine history retain their prior export shape and never expose another session record + --- + duration_ms: 1017.7445 + type: 'test' + ... +# Subtest: live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows +ok 28 - live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows + --- + duration_ms: 727.4079 + type: 'test' + ... +# Subtest: an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects +ok 29 - an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects + --- + duration_ms: 836.2491 + type: 'test' + ... +# Subtest: an installation failure restores old managers, original record maps, handlers and all existing database rows +ok 30 - an installation failure restores old managers, original record maps, handlers and all existing database rows + --- + duration_ms: 1697.5218 + type: 'test' + ... +# Subtest: the owned controlled driver remains an active session and project even after outer task activity has ended +ok 31 - the owned controlled driver remains an active session and project even after outer task activity has ended + --- + duration_ms: 1082.1289 + type: 'test' + ... +# Subtest: release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory +ok 32 - release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory + --- + duration_ms: 1070.3313 + type: 'test' + ... +# Subtest: hot upgrade adopts a retained virtual data root without reopening SQLite or changing rows, Provider or routing +ok 33 - hot upgrade adopts a retained virtual data root without reopening SQLite or changing rows, Provider or routing + --- + duration_ms: 1552.9529 + type: 'test' + ... +# Subtest: failed adoption restores the original virtual data-root name and original open database +ok 34 - failed adoption restores the original virtual data-root name and original open database + --- + duration_ms: 827.2672 + type: 'test' + ... +# Subtest: hot upgrade refreshes retained model and importer methods while preserving credential and routing objects +ok 35 - hot upgrade refreshes retained model and importer methods while preserving credential and routing objects + --- + duration_ms: 889.0345 + type: 'test' + ... +# Subtest: hot upgrade refuses active probes and restores retained model methods if installation fails +ok 36 - hot upgrade refuses active probes and restores retained model methods if installation fails + --- + duration_ms: 837.2508 + type: 'test' + ... +# Subtest: a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider +not ok 37 - a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider + --- + duration_ms: 2307.8727 + type: 'test' + location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\upgrade.test.mjs:10:1' + failureType: 'testCodeFailure' + error: 'The existing request handler could not be identified uniquely.' + code: 'ERR_TEST_FAILURE' + stack: |- + upgradeRunning (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/upgrade-running.mjs:103:41) + process.processTicksAndRejections (node:internal/process/task_queues:104:5) + async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/upgrade.test.mjs:24:20) + async Test.run (node:internal/test_runner/test:1409:7) + async startSubtestAfterBootstrap (node:internal/test_runner/harness:387:3) + ... +# Subtest: the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection +not ok 38 - the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection + --- + duration_ms: 4785.5103 + type: 'test' + location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\upgrade.test.mjs:38:1' + failureType: 'testCodeFailure' + error: 'The existing request handler could not be identified uniquely.' + code: 'ERR_TEST_FAILURE' + stack: |- + upgradeRunning (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/upgrade-running.mjs:103:41) + process.processTicksAndRejections (node:internal/process/task_queues:104:5) + async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/upgrade.test.mjs:90:18) + async Test.run (node:internal/test_runner/test:1409:7) + async Test.processPendingSubtests (node:internal/test_runner/test:974:7) + ... +1..38 +# tests 38 +# suites 0 +# pass 36 +# fail 2 +# cancelled 0 +# skipped 0 +# todo 0 +# duration_ms 43498.0512 diff --git a/findings.md b/findings.md index 722de05b..0b87e6e0 100644 --- a/findings.md +++ b/findings.md @@ -677,3 +677,16 @@ A–E已提交并保留原证据。F源码包必须对实际重新生成的客 ## 1.15最终发行与正式安装结论 最终20261031071202956包含85e0f0e/138adcf存储修复及新server构建,client/desktop/依赖/许可证/基准原字节保持;限定差异核对后,全新495项独立源码、同载荷隔离安装、便携和正式数据保留各自验证。495/495独立源码、23类179组历史UI、真实窗口7/原生UI9/三工程16节点、父8/8、9/9、10/10、同载荷安装/重启/卸载7组(隔离测试登记,正式产品安装器另行stage)、正式18页、1446条工件记录和1357个去重文件核对通过;当前2连接配置/1池、17项目/29全部会话/2567记录/4599事件,正式纠正升级前后每行/全导出/全部工件原字节保持(相对初始16项目,用户启动新增1个示例并将原列表顺移;体验期间另新增1个空白idle会话及对应1事件,全部原28会话/记录/工件保持);旧PID23172已在恢复检查前退出,用户体验时手动启动1.14/PID36552,随后保留这个进程/Provider升级;旧内存Key不可恢复,需在界面重新填写,原Node SHA保持,9229关闭。实际来源检测在C盘安装可定位原D盘SDK/Purge,提示实验继续默认关闭。原unknown/来源attention按巡检页保留;未执行原真实模型Key的探测或推理。下一真实手机按已记录PLAN-1.16独立实施。 + + +## 2026-10-31 1.16手机伴随端开始 + +从06c9fac/正式1.15接续,分支feat/mobile-companion-1.16。用户选定iPhone并可配合证书信任;Windows可提供HTTPS给同Wi-Fi的Safari/PWA,真实设备操作另留证据。独立监听默认关闭,原执行宿主保持loopback,手机仅取得授权项目的固定操作;每个切片验收、回顾和本地Git。首轮猜测文件路径及计划补丁标题锚点失败已记录,无产品修改。 + +1.16实现依据:实际管理入口src/server/app.mjs、Runtime原审批waiters/decide与stop、SQLite metadata事务和events全局seq已核对。新增独立HTTPS监听及固定手机投影,不复用完整管理API或原SSE;使用项目过滤SQL分页原seq,读取事件不携带内部payload。手机仅保存Secure/HttpOnly/SameSite=Strict cookie,配对随机值位于fragment且登记仅存摘要。TLS使用@peculiar/x5093.1.0/reflect-metadata0.2.2,二维码qrcode1.5.4;npm依赖审计0漏洞。证书私钥默认仅使用Windows CurrentUser DPAPI,无生产明文回退。正式宿主未操作、真实模型0请求。 + +开工读取纠错:npm依赖尚在安装时读取其README不存在;安装完成后按实际文件读取。两次探索rg使用不存在的core/changes与core/delivery路径,实际分别server/files.mjs与core/delivery-report.mjs,均仅只读失败无副作用。后续不复用猜测路径。规划技能session-catchup无待恢复输出,原计划和Git差异已接续。 + +1.16 A/B专项首轮14/16:两项测试夹具问题分别为重启身份回调每次生成新UUID、错误Host测试被Node TLS提前拒绝。修正夹具为固定重启身份、SNI空值仍校验目标IP后16/16通过(.qa/companion-a-b-rerun.tap),含真实DPAPI。关联38项首轮30/38,8项因qrcode CommonJS在ESM bundle中动态require fs失败;补createRequire后36/38,剩余2项热升级处理器唯一定位待修。失败日志独立保留,没有部署正式宿主。 + +手机UI结构比较:桌面缩小复制会保留大量编辑区/配置,任务队列→详情能把待审批/unknown/进展放在首屏;多面板仪表盘弱化同一Task归属。选择任务队列与独立详情,保留现有深蓝/冷灰/绿色状态语言,触控至少44px、中文系统字体、安全区、无额外动效。桌面只增加连接管理模态,手机不加载桌面入口或管理令牌。按product-ui-ux/frontend-design完成流程和实际宽窄屏验收。 diff --git a/package-lock.json b/package-lock.json index 2a04a875..6f8fb1db 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,11 +9,14 @@ "version": "1.15.0", "dependencies": { "@babel/parser": "7.29.11", + "@peculiar/x509": "3.1.0", "diff": "^8.0.2", "lucide-react": "^0.548.0", "playwright": "1.64.1", + "qrcode": "1.5.4", "react": "^19.2.0", "react-dom": "^19.2.0", + "reflect-metadata": "0.2.2", "smol-toml": "1.9.1" }, "devDependencies": { @@ -862,6 +865,229 @@ "node": "^22.20 || ^24.12 || >=25" } }, + "node_modules/@peculiar/asn1-asym-key": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-asym-key/-/asn1-asym-key-3.0.0.tgz", + "integrity": "sha512-zq7C4L3mGT+Ax8RN2ss8uIGx6OyDjxgKCywCV5pQjGRRtndPXWgWHJAoZxjDc1aAlX9f2/TqU09TPOyLkfSUXg==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-pkcs8": "^3.0.0", + "@peculiar/asn1-x509": "^3.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, + "node_modules/@peculiar/asn1-cms": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-3.0.0.tgz", + "integrity": "sha512-pIhjg30MC6hDpUWWrhPv/CEkAL/gwHrgDpOXQKkgoEDn+j47ZhKOlSGHGDIMinZrBaorKnRfQpE8CiJtnF46OA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-x509": "^3.0.0", + "@peculiar/asn1-x509-attr": "^3.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, + "node_modules/@peculiar/asn1-csr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-3.0.0.tgz", + "integrity": "sha512-tNNPwiY1AB5DqzNF/wkP9HpCUeodUXm4onsmzzKtrZ5kegMVshYJXCkrZu4WJspPi53nGHYL1kbhE2MS06eddg==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-x509": "^3.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, + "node_modules/@peculiar/asn1-ecc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-3.0.0.tgz", + "integrity": "sha512-CxBF5rMaLycKDo4fBvEnhDF0OD4BjwHbTCKBZKsmtI5R+//gZSZcEryosDAyrW/GDEygVxyjrHhURIKam8vsIw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-x509": "^3.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, + "node_modules/@peculiar/asn1-pfx": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-3.0.0.tgz", + "integrity": "sha512-5341Q2VHPaf2k4UblHRKIeDSLNUyUA9lekVFXAFWy/P9dPq2NAK2DeaQiYcHK+RBBUmZdNRZWzQNfiQ72bxIZg==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^3.0.0", + "@peculiar/asn1-pkcs8": "^3.0.0", + "@peculiar/asn1-rsa": "^3.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, + "node_modules/@peculiar/asn1-pkcs8": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-3.0.0.tgz", + "integrity": "sha512-bWNih5cHY7uIsF50GgXRbhb89PBXJqRZ7irp58Rk9dRWNauVNTiJtJbkyTcHo/wVdvbkPV02SsvhvRGMB4C+jA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-x509": "^3.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, + "node_modules/@peculiar/asn1-pkcs9": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-3.0.0.tgz", + "integrity": "sha512-a2zEw7xhDhGgVSKRzZV/+ylH5thRf/Muo569fELnWsM7MIvYw/lbExHv5xoaMd9oTHaJyq8+AkXVKTPwoy1bHw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^3.0.0", + "@peculiar/asn1-pfx": "^3.0.0", + "@peculiar/asn1-pkcs8": "^3.0.0", + "@peculiar/asn1-x509": "^3.0.0", + "@peculiar/asn1-x509-attr": "^3.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, + "node_modules/@peculiar/asn1-rsa": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-3.0.0.tgz", + "integrity": "sha512-ZWIfDZx1hEPTdv5BiIJ3f1DZkX4ggs7PtIdL2Hj1NwRstXxfJw2AEfbfh+Un8p1rMZmWGCupi8ePmE1qTphmmw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-x509": "^3.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, + "node_modules/@peculiar/asn1-schema": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-3.0.0.tgz", + "integrity": "sha512-VQgBSyf3teIp7219Y0rHFruJUVY/teYkKvvvObuwtwx6+jOt1f1+jvZoTBRua370H0a8eYpnUWoe0G6GqV0yaA==", + "license": "MIT", + "peer": true, + "dependencies": { + "@peculiar/utils": "^4.1.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "asn1js": "^4.0.0" + } + }, + "node_modules/@peculiar/asn1-x509": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-3.0.0.tgz", + "integrity": "sha512-2SiGmnk+qDtRfifIaGAShAIYJYXRU2DkInPzd+io8GiL9MIyf9RyGj/kcuWVOsdEEPDRm5xfNMVXCu9EQStzgA==", + "license": "MIT", + "dependencies": { + "@peculiar/utils": "^4.1.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0", + "asn1js": "^4.0.0" + } + }, + "node_modules/@peculiar/asn1-x509-attr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-3.0.0.tgz", + "integrity": "sha512-5aLS6ICUdDB42Y3tGfCFAvUzw8SppVGsRogyc1ic4QOBlt358p7iInON4YQP+/V6wzFDWYAN/jfw9gQ/oSG6sg==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-x509": "^3.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, + "node_modules/@peculiar/asn1-x509-post-quantum": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-post-quantum/-/asn1-x509-post-quantum-3.0.0.tgz", + "integrity": "sha512-CxGAoQ5Md/LIqZyQsgWCCMJo2/T+XYrHDyRPVyN8MGpi7p/05iSilQYrxA25dYqX1sgxoSsaKxVCNJRghz28Qw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-asym-key": "^3.0.0", + "@peculiar/asn1-x509": "^3.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, + "node_modules/@peculiar/utils": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-4.1.0.tgz", + "integrity": "sha512-y2oDqAwp+VPZMUYFGFFMYlXM8xinwb7ehb69+2EhbEL+n7KsykCQX5F0u3/B+BFHxCkwTyft3T1id0ugyzNHVQ==", + "license": "MIT", + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@peculiar/x509": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-3.1.0.tgz", + "integrity": "sha512-wjrnCx9lwiRyusHZcNuujCDQ5hplsVyH0j8KMkVGWYb+UwfbgS/0vfDnE72OpUMRJ5/Snz2Tz75LjqvZF8+tWw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^3.0.0", + "@peculiar/asn1-csr": "^3.0.0", + "@peculiar/asn1-ecc": "^3.0.0", + "@peculiar/asn1-pkcs9": "^3.0.0", + "@peculiar/asn1-rsa": "^3.0.0", + "@peculiar/asn1-x509": "^3.0.0", + "@peculiar/asn1-x509-post-quantum": "^3.0.0", + "@peculiar/utils": "^4.1.0", + "tsyringe": "^4.10.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@peculiar/asn1-schema": "^3.0.0" + } + }, "node_modules/@rolldown/pluginutils": { "version": "1.0.0-rc.3", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz", @@ -1361,6 +1587,43 @@ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/asn1js": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-4.0.0.tgz", + "integrity": "sha512-81NlooYbXCbBWL2+p1/ivGyT4AR2+bnfKYlPq/3rCoIPJSuLbdS8G70XYt561wOJnbaYfBS2HQDMENaX5hM2vA==", + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "@peculiar/utils": "^4.1.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, "node_modules/baseline-browser-mapping": { "version": "2.11.34", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.34.tgz", @@ -1408,6 +1671,15 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/caniuse-lite": { "version": "1.0.30001819", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001819.tgz", @@ -1429,6 +1701,35 @@ ], "license": "CC-BY-4.0" }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -1461,6 +1762,15 @@ } } }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/diff": { "version": "8.0.4", "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", @@ -1470,6 +1780,12 @@ "node": ">=0.3.1" } }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, "node_modules/electron": { "version": "45.2.0", "resolved": "https://registry.npmjs.org/electron/-/electron-45.2.0.tgz", @@ -1496,6 +1812,12 @@ "dev": true, "license": "ISC" }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, "node_modules/env-paths": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", @@ -1579,6 +1901,19 @@ } } }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -1604,6 +1939,15 @@ "node": ">=6.9.0" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", @@ -1623,6 +1967,15 @@ "node": ">= 0.8.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -1656,6 +2009,18 @@ "node": ">=6" } }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -1711,6 +2076,51 @@ "node": ">=18" } }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -1758,6 +2168,15 @@ "node": ">=20" } }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/postcss": { "version": "8.5.32", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", @@ -1797,6 +2216,23 @@ "node": ">=0.4.0" } }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/react": { "version": "19.3.1", "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", @@ -1828,6 +2264,27 @@ "node": ">=0.10.0" } }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0" + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, "node_modules/rollup": { "version": "4.66.0", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.66.0.tgz", @@ -1890,6 +2347,12 @@ "semver": "bin/semver.js" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, "node_modules/smol-toml": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz", @@ -1912,6 +2375,32 @@ "node": ">=0.10.0" } }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/sumchecker": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz", @@ -1942,6 +2431,24 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, + "node_modules/tsyringe": { + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz", + "integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==", + "license": "MIT", + "dependencies": { + "tslib": "^1.9.3" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -2564,12 +3071,73 @@ "@esbuild/win32-x64": "0.28.2" } }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", "dev": true, "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } } } } diff --git a/package.json b/package.json index 6643abcc..06a23853 100644 --- a/package.json +++ b/package.json @@ -41,11 +41,14 @@ }, "dependencies": { "@babel/parser": "7.29.11", + "@peculiar/x509": "3.1.0", "diff": "^8.0.2", "lucide-react": "^0.548.0", "playwright": "1.64.1", + "qrcode": "1.5.4", "react": "^19.2.0", "react-dom": "^19.2.0", + "reflect-metadata": "0.2.2", "smol-toml": "1.9.1" }, "devDependencies": { diff --git a/progress.md b/progress.md index 79ecd92d..e71ebb6a 100644 --- a/progress.md +++ b/progress.md @@ -751,3 +751,14 @@ F最终说明包首次全字节对照拒绝REA运行清单的builtAt时间变化 最终封存首轮预检拒绝“360个输入全部为Git文件”的错误假设,且未创建证据输出;第二次因四个文本的Git换行规范化拒绝,也未创建输出,两次原脚本/诊断和第二次实际工具输出分别保留。一次性核对全部360输入:351个与Git原始blob完全一致,4个仅CRLF/LF差异,完整缓冲区去掉CRLF中的CR后与Git字节严格相同,另封存冻结原文件;5个是.gitignore明确忽略的示例构建结果,四个模块逐字节等于已提交src,package.json逐字节等于已提交build.mjs的固定输出。所有360输入/12构建/40基准的原SHA保持,5份生成结果和构建器另封存。没有跳过任意缺失文件、更改冻结源码或强制提交生成目录,不宣称全部Git原始字节相同,也没有重复运行产品验收。 第三次最终封存外部日志预检拒绝且未创建输出;随后一次性核对36个外部引用,三份卸载日志原SHA都严格对应完整日志前缀,分别仅追加199字节的“卸载成功/移除完成/无需重启/日志关闭”终结行。保留原收据与原SHA,按散列证明分别封存原前缀和完整日志,第三次实际工具失败/当时脚本亦保留。其余外部引用SHA一致,没有把变化日志写成原字节相同或重新执行卸载、安装和升级。 + + +## 2026-10-31 1.16手机伴随端开始 + +从06c9fac/正式1.15接续,分支feat/mobile-companion-1.16。用户选定iPhone并可配合证书信任;Windows可提供HTTPS给同Wi-Fi的Safari/PWA,真实设备操作另留证据。独立监听默认关闭,原执行宿主保持loopback,手机仅取得授权项目的固定操作;每个切片验收、回顾和本地Git。首轮猜测文件路径及计划补丁标题锚点失败已记录,无产品修改。 + +1.16 A/B首次实现已写入:设备登记、256位/120秒/单次配对、项目与观察/审批/停止权限、会话轮换、撤销/到期、固定Origin/Host和限速;Windows DPAPI根证书与IP SAN叶证书;独立网关默认关闭及宿主关闭/升级守卫。原任务投影、原seq分页及审批幂等初步接入,正在执行真实TLS和边界专项。尚未标为验收通过,手机界面与真实iPhone仍待开发/验证。 + +A/B完成:16新增专项与38项API/桌面/Runtime/升级关联合并54/54通过,失败日志和最终原TAP封存在docs/companion-a-b-evidence。新增网关变量撞到旧管理处理器Debugger定位字符串,改为mobileUrl保持原定位契约,直接启动和旧0.1宿主连续升级通过。TLS套接字登记补充close清理和10秒握手超时。C界面已写入但尚未验收。一次状态补丁因计划原句不完全一致整批拒绝,无写入;读取原句后正确应用。 + +A/B封存检查发现原失败TAP保留了空白行缩进,git diff --check据此报空格;不重写原日志。按仓库既有证据策略将这一目录的TAP标记binary,保留原字节,再做代码/文档检查。原失败和该检查结果已记录。 diff --git a/scripts/build-server.mjs b/scripts/build-server.mjs index 5cc1791c..7362f3d5 100644 --- a/scripts/build-server.mjs +++ b/scripts/build-server.mjs @@ -1,10 +1,12 @@ import { build } from 'esbuild'; import fs from 'node:fs'; +// Bundled CommonJS dependencies (QR PNG encoder) still import Node builtins. +const nodeRequire = { js: "import { createRequire as __awbCreateRequire } from 'node:module'; const require = __awbCreateRequire(import.meta.url);" }; fs.mkdirSync('dist-server', { recursive: true }); await build({ entryPoints: ['src/server/index.mjs'], outfile: 'dist-server/server.mjs', bundle: true, - platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' }); + platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof', banner: nodeRequire }); await build({ entryPoints: ['src/server/hot-upgrade.mjs'], outfile: 'dist-server/hot-upgrade.mjs', bundle: true, - platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' }); + platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof', banner: nodeRequire }); await build({ entryPoints: ['src/desktop/host-cli.mjs'], outfile: 'dist-server/host-launcher.mjs', bundle: true, platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' }); await build({ entryPoints: ['src/desktop/install-cli.mjs'], outfile: 'dist-server/install-manager.mjs', bundle: true, diff --git a/src/core/companion/device-registry.mjs b/src/core/companion/device-registry.mjs new file mode 100644 index 00000000..b7f0edd5 --- /dev/null +++ b/src/core/companion/device-registry.mjs @@ -0,0 +1,127 @@ +import fs from 'node:fs'; +import { randomBytes, randomUUID } from 'node:crypto'; +import { companionError, companionHash, companionName, deviceGrant, COMPANION_SCHEMA } from '../../shared/contracts/companion.mjs'; +import { assertLocalTree } from '../desktop/file-state.mjs'; + +const key = 'mobileCompanion'; +const instant = value => new Date(value).toISOString(); +const secret = () => randomBytes(32).toString('base64url'); +export class DeviceRegistry { + constructor(store, identity, { clock = Date.now } = {}) { + this.store = store; this.identity = identity; this.clock = clock; this.pairings = new Map(); + assertLocalTree(store.directory); + const host = identity(); + if (!host?.instanceId || !host?.userSid || !host?.ownerId) throw companionError('手机连接需要已登记的Windows执行宿主。', 409); + this.host = structuredClone(host); + this.binding = companionHash(JSON.stringify({ userSid: host.userSid, directory: fs.realpathSync.native(store.directory).toLowerCase() })); + this.read(); + } + assertHost() { + const host = this.identity(); + if (!host || ['instanceId', 'ownerId', 'userSid', 'pid', 'createdAt'].some(key => host[key] !== this.host[key])) throw companionError('原执行宿主已变化,请在电脑上重新开启手机连接。', 409); + } + read() { + const state = this.store.storage.meta(key); + if (state && (state.schema !== COMPANION_SCHEMA || state.binding !== this.binding || !Number.isSafeInteger(state.revision) + || !state.devices || Array.isArray(state.devices) || Object.keys(state.devices).length > 128 || !Array.isArray(state.audit) + || !state.operations || Array.isArray(state.operations))) throw companionError('原手机登记无法核对;请保留数据并检查原Windows用户和目录。', 409); + return state ?? { schema: COMPANION_SCHEMA, binding: this.binding, gatewayId: randomUUID(), revision: 0, devices: {}, audit: [], operations: {} }; + } + mutate(action) { + this.assertHost(); + return this.store.storage.transaction(() => { + const state = this.read(), result = action(state); + state.revision++; this.store.storage.setMeta(key, state); return result; + }); + } + audit(state, action, deviceId, status, extra = {}) { + state.audit.push({ id: randomUUID(), at: instant(this.clock()), deviceId, action, status, ...extra }); + state.audit = state.audit.slice(-500); + } + initialize() { return this.mutate(state => ({ gatewayId: state.gatewayId })); } + view() { + const state = this.read(); + return { gatewayId: state.gatewayId, revision: state.revision, devices: Object.values(state.devices).map(({ credentialHash, ...device }) => ({ ...device, + status: device.revokedAt ? 'revoked' : Date.parse(device.expiresAt) <= this.clock() ? 'expired' : credentialHash ? 'active' : 'reconnect_required' })), audit: state.audit.slice(-50).reverse() }; + } + pair(grant, generation) { + this.assertHost(); deviceGrant(this.store, grant); + const token = secret(), hash = companionHash(token), expiresAt = this.clock() + 120000; + this.pairings.clear(); this.pairings.set(hash, { grant: structuredClone(grant), generation, expiresAt }); + return { token, expiresAt: instant(expiresAt) }; + } + consume(token, name, generation) { + this.assertHost(); name = companionName(name); + if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw companionError('配对码无效或已过期。', 401); + const hash = companionHash(token), pairing = this.pairings.get(hash); + if (!pairing || pairing.generation !== generation || pairing.expiresAt <= this.clock()) throw companionError('配对码无效或已过期,请在电脑重新生成。', 401); + deviceGrant(this.store, pairing.grant); + const tokenValue = secret(); + const device = this.mutate(state => { + if (Object.keys(state.devices).length >= 128) throw companionError('设备登记达到128条上限,请保留原审计并检查设备登记。', 409); + const at = this.clock(), device = { id: randomUUID(), name, projectIds: pairing.grant.projectIds, permissions: pairing.grant.permissions, + revision: 1, createdAt: instant(at), expiresAt: instant(at + pairing.grant.expiresInHours * 3600000), revokedAt: null, + credentialHash: companionHash(tokenValue) }; + state.devices[device.id] = device; this.audit(state, 'pair', device.id, 'completed'); + const { credentialHash, ...view } = device; return view; + }); + this.pairings.delete(hash); + return { device, token: tokenValue }; + } + authenticate(token) { + this.assertHost(); + if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw companionError('请在电脑生成配对码,重新连接此设备。', 401); + const hash = companionHash(token), device = Object.values(this.read().devices).find(value => value.credentialHash === hash); + if (!device || device.revokedAt || Date.parse(device.expiresAt) <= this.clock()) throw companionError('设备已撤销、到期或会话已轮换,请重新配对。', 401); + return structuredClone(device); + } + authorize(device, projectId, permission = 'observe') { + const current = this.read().devices[device.id]; + if (!current || current.revision !== device.revision || current.credentialHash !== device.credentialHash || current.revokedAt || Date.parse(current.expiresAt) <= this.clock()) throw companionError('设备授权已变化,请重新连接。', 401); + if (!current.projectIds.includes(projectId) || current.permissions[permission] !== true) throw companionError('此设备没有当前项目或操作权限。', 403); + return current; + } + revoke(id, revision) { + this.pairings.clear(); + return this.mutate(state => { + const device = state.devices[id]; + if (!device || device.revision !== revision) throw companionError('设备登记已变化,请刷新列表。', 409); + device.revokedAt = instant(this.clock()); device.credentialHash = null; device.revision++; + this.audit(state, 'revoke', id, 'completed'); return { revoked: true }; + }); + } + rotate(device) { + const token = secret(); + this.mutate(state => { + this.authorize(device, device.projectIds[0]); + const current = state.devices[device.id]; current.credentialHash = companionHash(token); current.revision++; + current.rotatedAt = instant(this.clock()); this.audit(state, 'rotate', device.id, 'completed'); + }); + return token; + } + reserve(device, action, session, input) { + const hash = companionHash(JSON.stringify({ action, sessionId: session.id, input })), id = device.id + ':' + input.requestId; + return this.mutate(state => { + const existing = state.operations[id]; + if (existing) { + if (existing.hash !== hash) throw companionError('同一请求ID不能更换操作或输入。', 409); + return { ...existing, duplicate: true }; + } + if (Object.keys(state.operations).length >= 2000) throw companionError('手机操作账本达到上限,请在电脑处理。', 409); + const operation = { hash, deviceId: device.id, requestId: input.requestId, action, sessionId: session.id, + taskId: session.taskId, runId: session.runId, projectId: session.projectId, status: 'pending', createdAt: instant(this.clock()) }; + state.operations[id] = operation; + this.audit(state, action, device.id, 'pending', { requestId: input.requestId, projectId: session.projectId, taskId: session.taskId, runId: session.runId }); + return operation; + }); + } + finish(device, input, status) { + return this.mutate(state => { + const operation = state.operations[device.id + ':' + input.requestId]; + if (!operation) throw companionError('原手机操作登记丢失,请在电脑核对。', 409); + operation.status = status; operation.finishedAt = instant(this.clock()); + this.audit(state, operation.action, device.id, status, { requestId: input.requestId, projectId: operation.projectId, taskId: operation.taskId, runId: operation.runId }); + return structuredClone(operation); + }); + } +} diff --git a/src/core/companion/projection.mjs b/src/core/companion/projection.mjs new file mode 100644 index 00000000..2dbf7030 --- /dev/null +++ b/src/core/companion/projection.mjs @@ -0,0 +1,33 @@ +import { approvalBinding } from '../../shared/contracts/companion.mjs'; + +export const pick = (value, names) => Object.fromEntries(names.filter(key => value?.[key] !== undefined).map(key => [key, structuredClone(value[key])])); +export const reportKinds = new Set(['delivery-report', 'delivery-report-markdown']); +export const sessionBrief = (session, redact = String) => ({ ...pick(session, ['id', 'projectId', 'taskId', 'runId', 'status', 'revision', 'eventSeq', 'updatedAt']), title: redact(String(session.title).slice(0, 240)) }); +export function mobileSession(store, runtime, session, redact = String) { + const task = store.core.task.get(session.taskId), run = store.core.run.get(session.runId); + const tools = [...store.core.tool.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId); + const checks = [...store.core.check_job.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId); + const result = { + ...sessionBrief(session, redact), + task: task ? { ...pick(task, ['id', 'status', 'budget', 'usage', 'verification']), goal: String(task.goal).slice(0, 12000) } : null, + run: run ? pick(run, ['id', 'taskId', 'status', 'budget', 'usage', 'steps', 'toolCalls', 'stopReason', 'startedAt', 'finishedAt']) : null, + progress: { total: tools.length, completed: tools.filter(value => value.state === 'completed').length, + unknown: tools.filter(value => value.requiresVerification).map(value => pick(value, ['id', 'tool', 'state', 'runId'])) }, + events: session.events.slice(-60).map(value => ({ ...pick(value, ['id', 'kind', 'phase', 'taskId', 'runId', 'createdAt', 'exitCode', 'durationMs']), + label: String(value.label ?? value.tool ?? '').slice(0, 240), output: String(value.output ?? '').slice(-4000) })), + messages: session.messages.filter(value => ['assistant', 'system'].includes(value.role)).slice(-8).map(value => ({ ...pick(value, ['id', 'role', 'createdAt']), content: String(value.content).slice(0, 12000) })), + approvals: session.approvals.filter(value => value.status === 'pending' && value.taskId === session.taskId && value.runId === session.runId).map(value => ({ + ...pick(value, ['id', 'taskId', 'runId', 'projectId', 'command', 'reason', 'shell', 'createdAt']), + fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })), + changes: session.changes.filter(value => value.taskId === session.taskId).slice(-100).map(value => pick(value, ['id', 'path', 'reason', 'status', 'sha256', 'baseSha256', 'additions', 'deletions'])), + checks: checks.slice(-12).map(value => ({ ...pick(value, ['id', 'status', 'summary', 'requiresVerification', 'createdAt', 'finishedAt']), + results: (value.results ?? []).map(item => pick(item, ['name', 'status', 'exitCode', 'counts', 'durationMs'])) })), + reports: [...store.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && reportKinds.has(value.kind)) + .slice(-10).map(value => pick(value, ['id', 'kind', 'sha256', 'bytes', 'createdAt', 'taskId', 'runId'])), + }; + // Only this explicit projection crosses the remote boundary. Never expose + // providerMessages, model configuration, tool input, host paths or full exports. + const clean = value => typeof value === 'string' ? redact(value) : Array.isArray(value) ? value.map(clean) + : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, clean(entry)])) : value; + return clean(result); +} diff --git a/src/core/companion/tls-authority.mjs b/src/core/companion/tls-authority.mjs new file mode 100644 index 00000000..8c47893e --- /dev/null +++ b/src/core/companion/tls-authority.mjs @@ -0,0 +1,63 @@ +import 'reflect-metadata'; +import { webcrypto, createPrivateKey, X509Certificate as NativeCertificate } from 'node:crypto'; +import { X509CertificateGenerator, BasicConstraintsExtension, KeyUsagesExtension, KeyUsageFlags, + ExtendedKeyUsageExtension, ExtendedKeyUsage, SubjectAlternativeNameExtension, SubjectKeyIdentifierExtension, AuthorityKeyIdentifierExtension } from '@peculiar/x509'; +import { protectCredential, unprotectCredential } from '../desktop/windows-dpapi.mjs'; +import { companionError, companionHash } from '../../shared/contracts/companion.mjs'; + +const algorithm = { name: 'ECDSA', namedCurve: 'P-256', hash: 'SHA-256' }; +const signing = { name: 'ECDSA', hash: 'SHA-256' }; +const day = 86400000; +export class CompanionTLS { + constructor(registry, { protect = protectCredential, unprotect = unprotectCredential } = {}) { + this.registry = registry; this.protect = protect; this.unprotect = unprotect; + } + publicCertificate() { + const tls = this.registry.read().tls; + if (!tls) throw companionError('请先在电脑开启手机连接以生成证书。', 409); + const cert = new NativeCertificate(tls.certificate); + if (companionHash(cert.raw) !== tls.sha256) throw companionError('手机证书登记校验失败。', 409); + return { bytes: cert.raw, sha256: tls.sha256, expiresAt: tls.expiresAt }; + } + async material(address) { + const registry = this.registry, entropy = Buffer.from(companionHash('companion-tls:' + registry.binding), 'hex'); + let record = registry.read().tls, privateBytes, keys, certificate; + try { + if (record) { + const cert = new NativeCertificate(record.certificate); + if (companionHash(cert.raw) !== record.sha256 || Date.parse(cert.validTo) <= Date.now() + day) throw companionError('原手机根证书已变化或即将到期,请在电脑处理证书更新。', 409); + privateBytes = this.unprotect(Buffer.from(record.ciphertext, 'base64'), entropy); + const payload = JSON.parse(privateBytes.toString('utf8')); + if (payload.binding !== registry.binding || payload.sha256 !== record.sha256) throw companionError('手机TLS私钥不属于当前Windows用户和数据目录。', 409); + const privateKey = await webcrypto.subtle.importKey('pkcs8', Buffer.from(payload.pkcs8, 'base64'), algorithm, false, ['sign']); + if (!cert.checkPrivateKey(createPrivateKey({ key: Buffer.from(payload.pkcs8, 'base64'), format: 'der', type: 'pkcs8' }))) throw companionError('手机证书与私钥不匹配。', 409); + keys = { privateKey }; certificate = record.certificate; + } else { + keys = await webcrypto.subtle.generateKey(algorithm, true, ['sign', 'verify']); + const ca = await X509CertificateGenerator.createSelfSigned({ name: 'CN=Agent Workbench Mobile ' + registry.read().gatewayId, + keys, signingAlgorithm: signing, notBefore: new Date(Date.now() - 300000), notAfter: new Date(Date.now() + 730 * day), + extensions: [new BasicConstraintsExtension(true, 0, true), new KeyUsagesExtension(KeyUsageFlags.keyCertSign | KeyUsageFlags.cRLSign, true), + await SubjectKeyIdentifierExtension.create(keys.publicKey)] }, webcrypto); + certificate = ca.toString('pem'); + const pkcs8 = Buffer.from(await webcrypto.subtle.exportKey('pkcs8', keys.privateKey)); + let encrypted; + try { + privateBytes = Buffer.from(JSON.stringify({ binding: registry.binding, sha256: companionHash(new NativeCertificate(certificate).raw), pkcs8: pkcs8.toString('base64') })); + encrypted = this.protect(privateBytes, entropy); + record = { certificate, sha256: companionHash(new NativeCertificate(certificate).raw), expiresAt: ca.notAfter.toISOString(), ciphertext: encrypted.toString('base64') }; + registry.mutate(state => { if (state.tls) throw companionError('证书已由另一操作生成,请刷新。', 409); state.tls = record; }); + } finally { pkcs8.fill(0); encrypted?.fill(0); } + } + const leafKeys = await webcrypto.subtle.generateKey(algorithm, true, ['sign', 'verify']); + const leaf = await X509CertificateGenerator.create({ subject: 'CN=Agent Workbench Companion', issuer: new NativeCertificate(certificate).subject, + publicKey: leafKeys.publicKey, signingKey: keys.privateKey, signingAlgorithm: signing, + notBefore: new Date(Date.now() - 300000), notAfter: new Date(Date.now() + 90 * day), + extensions: [new BasicConstraintsExtension(false, undefined, true), new KeyUsagesExtension(KeyUsageFlags.digitalSignature, true), + new ExtendedKeyUsageExtension([ExtendedKeyUsage.serverAuth]), new SubjectAlternativeNameExtension([{ type: 'ip', value: address }]), + await SubjectKeyIdentifierExtension.create(leafKeys.publicKey), await AuthorityKeyIdentifierExtension.create(new NativeCertificate(certificate).publicKey.export({ type: 'spki', format: 'der' }))] }, webcrypto); + const der = Buffer.from(await webcrypto.subtle.exportKey('pkcs8', leafKeys.privateKey)); + try { return { key: createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }).export({ format: 'pem', type: 'pkcs8' }), cert: leaf.toString('pem') + '\n' + certificate, ca: certificate }; } + finally { der.fill(0); } + } finally { privateBytes?.fill(0); entropy.fill(0); } + } +} diff --git a/src/server/app.mjs b/src/server/app.mjs index 08d4a677..ddb53fab 100644 --- a/src/server/app.mjs +++ b/src/server/app.mjs @@ -14,6 +14,7 @@ import { ConfigImporter } from '../core/models/config-import.mjs'; import { ProjectMemoryManager } from '../core/memory/project-memory.mjs'; import { workerForProject, workerConflict, assertWorkersResolved } from '../shared/contracts/workers.mjs'; import { hostAuthority } from '../core/desktop/host-authority.mjs'; +import { companionGateway } from './companion-gateway.mjs'; import { inspectOperations } from './operations.mjs'; export function createSessionPublisher(clients) { @@ -85,6 +86,25 @@ return async (request, response) => { const method = request.method; const route = url.pathname; if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: server?.workbenchReady !== false, uptimeMs: Date.now() - started }); + if (route.startsWith('/api/companion')) { + const gateway = companionGateway({ appDirectory, server, store, provider, runtime }); + if (method === 'GET' && route === '/api/companion') return json(response, gateway.status()); + if (method === 'POST' && route === '/api/companion/start') return json(response, await gateway.start(await body(request))); + if (method === 'POST' && route === '/api/companion/close') { const value = await body(request); if (Object.keys(value).length) throw Object.assign(new Error('关闭手机连接不接受额外字段。'), { status: 400 }); return json(response, await gateway.close()); } + if (method === 'POST' && route === '/api/companion/pair') return json(response, await gateway.pairing(await body(request))); + const revoke = route.match(/^\/api\/companion\/devices\/([a-f0-9-]+)\/revoke$/); + if (method === 'POST' && revoke) { + const value = await body(request); + if (Object.keys(value).length !== 1 || !Number.isSafeInteger(value.revision)) throw Object.assign(new Error('设备撤销需要原登记修订。'), { status: 400 }); + return json(response, gateway.revoke(revoke[1], value.revision)); + } + if (method === 'GET' && route === '/api/companion/certificate') { + const certificate = gateway.tls.publicCertificate(); + response.writeHead(200, { 'Content-Type': 'application/pkix-cert', 'Content-Disposition': 'attachment; filename="Agent-Workbench-Mobile-CA.cer"', 'Cache-Control': 'no-store' }); + return response.end(certificate.bytes); + } + return json(response, { error: '手机连接管理操作不存在。' }, 404); + } if (method === 'GET' && route === '/api/host/identity') return json(response, host().attest(url.searchParams.get('challenge'))); if (method === 'GET' && route === '/api/host/status') return json(response, host().status()); if (method === 'POST' && route === '/api/host/windows/register') return json(response, host().registerWindow(await body(request))); diff --git a/src/server/companion-gateway.mjs b/src/server/companion-gateway.mjs new file mode 100644 index 00000000..d84b3aa1 --- /dev/null +++ b/src/server/companion-gateway.mjs @@ -0,0 +1,258 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import https from 'node:https'; +import { randomUUID } from 'node:crypto'; +import QRCode from 'qrcode'; +import { DeviceRegistry } from '../core/companion/device-registry.mjs'; +import { CompanionTLS } from '../core/companion/tls-authority.mjs'; +import { fields, companionError, companionHash, approvalBinding, operationInput } from '../shared/contracts/companion.mjs'; +import { isId } from '../shared/contracts/execution.mjs'; +import { mobileSession, sessionBrief, reportKinds } from '../core/companion/projection.mjs'; +import { hostAuthority } from '../core/desktop/host-authority.mjs'; + +export function companionGateway(context) { + if (!context.server.workbenchCompanion) { + const authority = hostAuthority(context); authority.initialize(); + const identity = () => { + const registration = context.server.listening ? context.server.workbenchHostAuthority?.registration : null; + return registration ? Object.fromEntries(['instanceId', 'ownerId', 'userSid', 'pid', 'createdAt'].map(key => [key, registration[key]])) : null; + }; + context.server.workbenchCompanion = new CompanionGateway({ ...context, identity, redact: value => context.provider.redact(value) }); + if (!context.server.workbenchCompanionCloseHook) { + context.server.workbenchCompanionCloseHook = () => context.server.workbenchCompanion?.dispose(); + context.server.on('close', context.server.workbenchCompanionCloseHook); + } + } + return context.server.workbenchCompanion; +} + +const cookieName = '__Host-Workbench-Device'; +const privateV4 = value => /^10\./.test(value) || /^192\.168\./.test(value) || /^172\.(1[6-9]|2\d|3[01])\./.test(value); +export function companionAddresses() { + return Object.entries(os.networkInterfaces()).flatMap(([name, entries]) => (entries ?? []).filter(entry => entry.family === 'IPv4' && !entry.internal && privateV4(entry.address)) + .map(entry => ({ name, address: entry.address }))); +} +function reply(response, data, status = 200) { + response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); response.end(JSON.stringify(data)); +} +async function input(request) { + if (!/^application\/json(?:;|$)/i.test(request.headers['content-type'] ?? '')) throw companionError('手机操作需要JSON请求。', 415); + const chunks = []; let length = 0; + for await (const chunk of request) { + length += chunk.length; + if (length > 16384) { request.resume(); throw companionError('手机请求超过16KB。', 413); } + chunks.push(chunk); + } + let value; try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw companionError('手机请求JSON无效。'); } + if (!value || typeof value !== 'object' || Array.isArray(value)) throw companionError('手机请求需要JSON对象。'); + return value; +} +const cookie = request => { + const values = String(request.headers.cookie ?? '').split(';').map(value => value.trim()).filter(value => value.startsWith(cookieName + '=')); + return values.length === 1 ? values[0].slice(cookieName.length + 1) : ''; +}; +function setCookie(response, token, expiresAt) { + const seconds = Math.max(0, Math.floor((Date.parse(expiresAt) - Date.now()) / 1000)); + response.setHeader('Set-Cookie', cookieName + '=' + token + '; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=' + seconds); +} +const cursor = value => { + if (!/^\d+$/.test(value ?? '') || !Number.isSafeInteger(Number(value))) throw companionError('手机事件游标无效。'); + return Number(value); +}; + +export class CompanionGateway { + constructor({ store, runtime, appDirectory, identity, redact = String }, { registryOptions, tlsOptions, allowLoopback = false } = {}) { + this.store = store; this.runtime = runtime; this.appDirectory = appDirectory; this.redact = redact; + this.registry = new DeviceRegistry(store, identity, registryOptions); this.tls = new CompanionTLS(this.registry, tlsOptions); + this.allowLoopback = allowLoopback; this.server = null; this.busy = false; this.generation = null; this.origin = null; + this.rates = new Map(); this.sockets = new Map(); + } + status() { + return { enabled: !!this.server?.listening, busy: this.busy, origin: this.origin, addresses: companionAddresses(), ...this.registry.view(), + certificate: this.registry.read().tls ? { sha256: this.tls.publicCertificate().sha256, expiresAt: this.tls.publicCertificate().expiresAt } : null }; + } + async start(options) { + fields(options, ['address', 'port']); + if (this.disposed || this.busy || this.server) throw companionError('手机网关正在开启、已开启或原宿主已关闭。', 409); + if (!companionAddresses().some(value => value.address === options.address) && !(this.allowLoopback && options.address === '127.0.0.1')) throw companionError('请选择本机已连接的局域网IPv4地址。'); + if (!Number.isInteger(options.port) || options.port < (this.allowLoopback ? 0 : 1024) || options.port > 65535) throw companionError('手机端口需要1024至65535。'); + this.busy = true; + try { + this.registry.initialize(); const material = await this.tls.material(options.address); + this.registry.assertHost(); + if (this.disposed) throw companionError('原宿主已关闭。', 409); + const server = https.createServer({ key: material.key, cert: material.cert, minVersion: 'TLSv1.2', maxHeaderSize: 16384, handshakeTimeout: 10000 }, (request, response) => void this.handle(request, response)); + server.requestTimeout = 15000; server.headersTimeout = 10000; server.keepAliveTimeout = 5000; server.maxConnections = 64; + server.on('connection', socket => { this.sockets.set(socket, null); socket.on('close', () => this.sockets.delete(socket)); }); + server.on('clientError', (_error, socket) => socket.destroy()); + try { await new Promise((resolve, reject) => { server.once('error', reject); server.listen(options.port, options.address, resolve); }); } + catch (error) { server.close(); for (const socket of this.sockets.keys()) socket.destroy(); throw error; } + if (this.disposed) { server.close(); throw companionError('原宿主已关闭。', 409); } + server.removeAllListeners('error'); server.on('error', () => this.dispose()); + this.server = server; this.origin = 'https://' + options.address + ':' + server.address().port; + this.generation = randomUUID(); this.rates.clear(); + return this.status(); + } catch (error) { + if (error.companion) throw error; + throw companionError(error.code === 'EADDRINUSE' ? '手机端口已占用,请换一个端口。' : '手机HTTPS启动失败,请核对证书、Windows用户及网络地址。', 409); + } finally { this.busy = false; } + } + async close() { + if (this.busy) throw companionError('网关正在启动,请等待完成后再关闭。', 409); + const server = this.server; this.server = null; this.origin = null; this.generation = null; this.registry.pairings.clear(); + for (const socket of this.sockets.keys()) socket.destroy(); this.sockets.clear(); + if (server) await new Promise(resolve => server.close(resolve)); + return { enabled: false }; + } + dispose() { + this.disposed = true; + for (const socket of this.sockets.keys()) socket.destroy(); + this.server?.close(); this.server = null; this.origin = null; this.generation = null; this.registry.pairings.clear(); + } + async pairing(grant) { + if (!this.server?.listening || !this.origin) throw companionError('请先开启手机HTTPS连接。', 409); + const generation = this.generation, origin = this.origin, pair = this.registry.pair(grant, generation), url = origin + '/#pair=' + pair.token; + const qr = await QRCode.toDataURL(url, { errorCorrectionLevel: 'M', margin: 2, width: 256 }); + if (generation !== this.generation) throw companionError('网关已变化,请重新生成配对码。', 409); + return { url, qr, expiresAt: pair.expiresAt }; + } + revoke(id, revision) { + const result = this.registry.revoke(id, revision); + for (const [socket, deviceId] of this.sockets) if (deviceId === id) socket.destroy(); + return result; + } + limit(key, maximum) { + const at = Date.now(), existing = this.rates.get(key), entry = existing?.until > at ? existing : { count: 0, until: at + 60000 }; + if (++entry.count > maximum) throw companionError('手机请求过于频繁,请稍后重试。', 429); + if (!existing && this.rates.size >= 2048) { + for (const [id, value] of this.rates) if (value.until <= at) this.rates.delete(id); + if (this.rates.size >= 2048) throw companionError('手机连接繁忙,请稍后重试。', 429); + } + this.rates.set(key, entry); + } + session(device, id, permission = 'observe') { + if (!isId(id)) throw companionError('手机任务不存在。', 404); + const session = this.store.sessions.get(id); + if (!session) throw companionError('手机任务不存在。', 404); + this.registry.authorize(device, session.projectId, permission); return session; + } + events(device, after, limit = 100) { + const projects = device.projectIds.filter(id => this.store.projects.some(project => project.id === id)); + if (!projects.length) return { events: [], nextCursor: after, hasMore: false }; + const rows = this.store.storage.database.prepare('SELECT seq,id,session_id,project_id,task_id,run_id,type,revision,created_at FROM events WHERE seq>? AND project_id IN (' + projects.map(() => '?').join(',') + ') ORDER BY seq LIMIT ?').all(after, ...projects, limit + 1); + const events = rows.slice(0, limit).map(row => ({ seq: row.seq, id: row.id, sessionId: row.session_id, projectId: row.project_id, taskId: row.task_id, runId: row.run_id, type: row.type, revision: row.revision, createdAt: row.created_at })); + return { events, nextCursor: events.at(-1)?.seq ?? after, hasMore: rows.length > limit }; + } + async operate(device, sessionId, action, value) { + const approve = action === 'approve'; operationInput(value, approve); + const session = this.session(device, sessionId, approve ? 'approve' : 'stop'); + // Look up idempotency before checking the now-changed session revision. + const prior = this.registry.read().operations[device.id + ':' + value.requestId]; + if (prior) { + if (prior.hash !== companionHash(JSON.stringify({ action, sessionId, input: value }))) throw companionError('同一请求ID不能更换操作或输入。', 409); + return { requestId: value.requestId, status: prior.status === 'pending' ? 'unknown' : prior.status, duplicate: true }; + } + if (session.taskId !== value.taskId || session.runId !== value.runId || session.revision !== value.revision) throw companionError('原任务或修订已变化,请刷新后核对。', 409); + if (approve) { + const approval = session.approvals.find(item => item.id === value.approvalId); + if (!approval || approval.status !== 'pending' || approvalBinding(session, approval) !== value.fingerprint + || this.runtime.waiters.get(approval.id)?.runId !== session.runId) throw companionError('原审批已变化或过期,请在电脑核对。', 409); + } + this.registry.reserve(device, action, session, value); + try { + if (approve) this.runtime.decide(session.id, value.approvalId, value.allow); + else await this.runtime.stop(session.id, { taskId: value.taskId, runId: value.runId }); + this.registry.finish(device, value, 'completed'); + } catch { + // A durable pending record is intentionally not replayable, even when + // the process or response fails between the original effect and receipt. + try { this.registry.finish(device, value, 'unknown'); } catch {} + throw companionError('原操作结果需要在电脑核对;不会自动重放。', 409); + } + this.registry.authorize(device, session.projectId, approve ? 'approve' : 'stop'); + return { requestId: value.requestId, status: 'completed', taskId: value.taskId, runId: value.runId }; + } + async handle(request, response) { + response.setHeader('Cache-Control', 'no-store'); response.setHeader('X-Content-Type-Options', 'nosniff'); + response.setHeader('Referrer-Policy', 'no-referrer'); response.setHeader('X-Frame-Options', 'DENY'); + response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'"); + try { + this.registry.assertHost(); + if (!this.server?.listening || !this.origin || request.headers.host !== new URL(this.origin).host) throw companionError('手机网关地址已变化,请重新连接。', 421); + this.limit('all', 1200); this.limit('ip:' + request.socket.remoteAddress, 400); + const mobileUrl = new URL(request.url, this.origin), route = mobileUrl.pathname, method = request.method; + if (mobileUrl.origin !== this.origin || request.headers.origin && request.headers.origin !== this.origin) throw companionError('请求来源不属于当前手机网关。', 403); + if (method === 'POST' && request.headers.origin !== this.origin) throw companionError('手机操作需要来自当前HTTPS页面。', 403); + if (mobileUrl.search && route !== '/mobile-api/events' && !/^\/mobile-api\/sessions\/[a-f0-9-]+\/changes\/[a-f0-9-]+$/.test(route)) throw companionError('手机接口不接受额外查询字段。'); + if (method === 'POST' && route === '/mobile-api/pair') { + this.limit('pair:' + request.socket.remoteAddress, 8); + const value = await input(request); fields(value, ['token', 'name']); + // The gateway may have closed while receiving a request body. + if (!this.server?.listening) throw companionError('手机网关已关闭。', 409); + const paired = this.registry.consume(value.token, value.name, this.generation); + setCookie(response, paired.token, paired.device.expiresAt); return reply(response, { device: paired.device }, 201); + } + if (route.startsWith('/mobile-api/')) { + const device = this.registry.authenticate(cookie(request)); this.limit('device:' + device.id, 240); + if (!this.sockets.has(request.socket)) request.socket.once('close', () => this.sockets.delete(request.socket)); + this.sockets.set(request.socket, device.id); + if (method === 'GET' && route === '/mobile-api/me') return reply(response, { device: { id: device.id, name: device.name, projectIds: device.projectIds, permissions: device.permissions, expiresAt: device.expiresAt, revision: device.revision }, gatewayId: this.registry.read().gatewayId }); + if (method === 'POST' && route === '/mobile-api/rotate') { + fields(await input(request), []); const token = this.registry.rotate(device); setCookie(response, token, device.expiresAt); return reply(response, { rotated: true }); + } + if (method === 'POST' && route === '/mobile-api/logout') { + fields(await input(request), []); this.registry.revoke(device.id, device.revision); setCookie(response, '', new Date(0).toISOString()); return reply(response, { revoked: true }); + } + if (method === 'GET' && route === '/mobile-api/projects') return reply(response, this.store.projects.filter(value => device.projectIds.includes(value.id)).map(value => ({ id: value.id, name: this.redact(value.name) }))); + if (method === 'GET' && route === '/mobile-api/sessions') return reply(response, [...this.store.sessions.values()].filter(value => device.projectIds.includes(value.projectId) && !value.archived).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, 200).map(value => sessionBrief(value, this.redact))); + if (method === 'GET' && route === '/mobile-api/events') { + if ([...mobileUrl.searchParams.keys()].some(key => !['after', 'limit'].includes(key)) || mobileUrl.searchParams.getAll('after').length > 1 || mobileUrl.searchParams.getAll('limit').length > 1) throw companionError('手机事件分页参数无效。'); + const after = cursor(mobileUrl.searchParams.get('after') ?? '0'), limit = cursor(mobileUrl.searchParams.get('limit') ?? '100'); + if (limit < 1 || limit > 200) throw companionError('手机事件每页需要1至200条。'); + return reply(response, this.events(device, after, limit)); + } + const match = route.match(/^\/mobile-api\/sessions\/([a-f0-9-]+)(?:\/(approve|stop|changes\/([a-f0-9-]+)|reports\/([a-f0-9-]+)))?$/); + if (match) { + const session = this.session(device, match[1]); + if (method === 'GET' && !match[2]) return reply(response, mobileSession(this.store, this.runtime, session, this.redact)); + if (method === 'POST' && ['approve', 'stop'].includes(match[2])) return reply(response, await this.operate(this.registry.authenticate(cookie(request)), session.id, match[2], await input(request))); + if (method === 'GET' && match[3]) { + const change = session.changes.find(value => value.id === match[3] && value.taskId === session.taskId); + if (!change) throw companionError('当前任务没有这项文件差异。', 404); + if ([...mobileUrl.searchParams.keys()].some(key => key !== 'offset') || mobileUrl.searchParams.getAll('offset').length > 1) throw companionError('文件差异分页参数无效。'); + const offset = cursor(mobileUrl.searchParams.get('offset') ?? '0'); + const text = this.redact(change.diff.map(part => part.value.split(/(?<=\n)/).map(line => (part.added ? '+' : part.removed ? '-' : ' ') + line).join('')).join('')); + if (offset > text.length) throw companionError('文件差异游标超出范围。'); + return reply(response, { id: change.id, path: this.redact(change.path), sourceSha256: change.sha256, baseSha256: change.baseSha256, + sha256: companionHash(text), text: text.slice(offset, offset + 48000), offset, nextOffset: Math.min(offset + 48000, text.length), hasMore: offset + 48000 < text.length }); + } + if (method === 'GET' && match[4]) { + const artifact = this.store.core.artifact.get(match[4]); + if (!artifact || artifact.sessionId !== session.id || artifact.projectId !== session.projectId || artifact.taskId !== session.taskId || !reportKinds.has(artifact.kind)) throw companionError('当前任务没有这份报告。', 404); + const bytes = this.store.artifactStore.readBytes(artifact), text = this.redact(bytes.toString('utf8')); + return reply(response, { id: artifact.id, sourceSha256: artifact.sha256, sha256: companionHash(text), redacted: text !== bytes.toString('utf8'), text }); + } + } + throw companionError('手机端没有这项操作,请回电脑工作台处理。', 404); + } + if (method !== 'GET' && method !== 'HEAD') throw companionError('手机端没有这项操作。', 404); + // Mobile HTML and its build-time asset list are separate from the desktop + // entry. Do not serve arbitrary paths, source files or management assets. + const root = path.join(this.appDirectory, 'dist-client'); + let file, type; + if (route === '/') { file = path.join(root, 'mobile.html'); type = 'text/html; charset=utf-8'; } + else if (['/mobile.webmanifest', '/mobile-sw.js', '/mobile-icon.svg', '/mobile-touch-icon.png'].includes(route)) { + file = path.join(root, route.slice(1)); type = route.endsWith('.js') ? 'text/javascript' : route.endsWith('.svg') ? 'image/svg+xml' : route.endsWith('.png') ? 'image/png' : 'application/manifest+json'; + } else { + const manifest = JSON.parse(fs.readFileSync(path.join(root, 'mobile-assets.json'), 'utf8')); + if (!manifest.includes(route) || !/^\/assets\/[A-Za-z0-9_.-]+\.(js|css)$/.test(route)) throw companionError('手机页面不存在。', 404); + file = path.join(root, route.slice(1)); type = route.endsWith('.js') ? 'text/javascript' : 'text/css'; + } + const bytes = fs.readFileSync(file); response.writeHead(200, { 'Content-Type': type }); response.end(method === 'HEAD' ? undefined : bytes); + } catch (error) { + if (!response.destroyed && !response.headersSent) reply(response, { error: error.companion ? error.message : '手机请求未完成,请在电脑核对当前任务和连接。' }, error.companion ? error.status : 500); + else if (!response.destroyed) response.destroy(); + } + } +} diff --git a/src/server/hot-upgrade.mjs b/src/server/hot-upgrade.mjs index 9d0e77d9..4224389c 100644 --- a/src/server/hot-upgrade.mjs +++ b/src/server/hot-upgrade.mjs @@ -17,12 +17,14 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true const { server, store, provider, runtime, token, clients, started, exampleProject, shutdown } = context; if (!server?.listening || !store || !provider || !runtime || !clients || !token) throw new Error('The existing Workbench context is incomplete.'); if (server.workbenchHostAuthority?.stopping) throw new Error('Wait for the original host stop operation before upgrading.'); + if (server.workbenchCompanion?.server || server.workbenchCompanion?.busy) throw new Error('Close the mobile companion gateway before upgrading; original tasks remain on the host.'); if (server.workbenchHostAuthority?.desktopWindows?.().count) throw new Error('Close the registered desktop windows before upgrading; the execution host remains running.'); if (runtime.active.size || runtime.waiters.size || runtime.workers?.active.size || runtime.controlledEngines?.drivers.size || runtime.mcp?.active.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size || runtime.engines?.active.size || runtime.browser?.active.size || runtime.taskPlans?.active.size) throw new Error('Wait for active tasks, workers, controlled engines, MCP operations, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.'); if (provider.activeRequests || provider.hub?.waiting || [...(provider.hub?.leases.values() ?? [])].some(count => count > 0)) throw new Error('Wait for active model requests and probes before upgrading.'); const root = fs.realpathSync.native(path.resolve(appDirectory)); if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.'); const oldHandlers = server.listeners('request'); + const oldCompanion = server.workbenchCompanion; const oldAuthority = server.workbenchHostAuthority, oldAuthorityProperties = oldAuthority ? { ...oldAuthority } : null; const oldAuthorityPrototype = oldAuthority ? Object.getPrototypeOf(oldAuthority) : null; const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)]; @@ -46,6 +48,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true if (provider.hub.credentialVault) Object.setPrototypeOf(provider.hub.credentialVault, CredentialVault.prototype); } runtime.appDirectory = root; runtime.workers = null; runtime.controlledEngines = null; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null; + delete server.workbenchCompanion; store.ensureStorage(); // A SQLite host can retain an artifact object from an earlier bundle. // Reopen the same blobs through the new API without mutating that object; @@ -61,6 +64,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true } return { version: APP_VERSION, pid: process.pid, hasKey: provider.hasKey(), projects: store.projects.length, sessions: store.sessions.size, appDirectory: root }; } catch (error) { + if (oldCompanion) server.workbenchCompanion = oldCompanion; else delete server.workbenchCompanion; if (oldAuthority) { for (const key of Object.keys(oldAuthority)) if (!Object.hasOwn(oldAuthorityProperties, key)) delete oldAuthority[key]; Object.assign(oldAuthority, oldAuthorityProperties); Object.setPrototypeOf(oldAuthority, oldAuthorityPrototype); diff --git a/src/server/index.mjs b/src/server/index.mjs index 54801955..8bdaace9 100644 --- a/src/server/index.mjs +++ b/src/server/index.mjs @@ -48,6 +48,8 @@ server.on('request', createRequestHandler({ appDirectory, server, store, provide async function shutdown() { if (closing) return; closing = true; clearInterval(modelImportSync); + try { await server.workbenchCompanion?.close(); } + catch { closing = false; console.error('Workbench shutdown rejected while companion gateway is starting.'); return; } try { await Promise.all([provider.abortRequests(), runtime.stopAll()]); } catch (cause) { closing = false; provider.resumeRequests(); console.error('Workbench shutdown remains unverified: ' + provider.redact(cause.message)); return; } for (const response of clients) response.end(); diff --git a/src/server/runtime.mjs b/src/server/runtime.mjs index 9d27ffe2..95e0710c 100644 --- a/src/server/runtime.mjs +++ b/src/server/runtime.mjs @@ -652,8 +652,18 @@ export class Runtime { if (signal.aborted) terminate(); }); } - async stop(sessionId) { + async stop(sessionId, expected = null) { + const original = this.active.get(sessionId); + const assertOriginal = () => { + if (!expected) return; + const session = this.store.session(sessionId); + if (session.taskId !== expected.taskId || session.runId !== expected.runId || this.active.get(sessionId) && this.active.get(sessionId) !== original) { + throw Object.assign(new Error('原停止请求的任务或运行已变化。'), { status: 409 }); + } + }; + assertOriginal(); await this.workers?.stopParent(sessionId); + assertOriginal(); const run = this.active.get(sessionId); if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); await this.workspaces?.stop(sessionId); await this.research?.stop(sessionId); await this.engines?.stop(sessionId); await this.browser?.stop(sessionId); await this.mcp?.stop(sessionId); await this.taskPlans?.settle(sessionId); return; } const session = this.store.session(sessionId); diff --git a/src/shared/contracts/companion.mjs b/src/shared/contracts/companion.mjs new file mode 100644 index 00000000..8d2d6587 --- /dev/null +++ b/src/shared/contracts/companion.mjs @@ -0,0 +1,38 @@ +import { createHash } from 'node:crypto'; +import { isId } from './execution.mjs'; + +export const COMPANION_SCHEMA = 1; +export const companionHash = value => createHash('sha256').update(value).digest('hex'); +export const companionError = (message, status = 400) => Object.assign(new Error(message), { status, companion: true }); +export function fields(input, allowed, required = allowed) { + if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !allowed.includes(key)) + || required.some(key => !Object.hasOwn(input, key))) throw companionError('请求字段不符合手机连接契约。'); + return input; +} +export function deviceGrant(store, input) { + fields(input, ['projectIds', 'permissions', 'expiresInHours']); + if (!Array.isArray(input.projectIds) || !input.projectIds.length || input.projectIds.length > 16 + || new Set(input.projectIds).size !== input.projectIds.length || input.projectIds.some(id => !isId(id) || !store.projects.some(project => project.id === id))) { + throw companionError('请选择1至16个已打开的项目。'); + } + fields(input.permissions, ['observe', 'approve', 'stop']); + if (input.permissions.observe !== true || typeof input.permissions.approve !== 'boolean' || typeof input.permissions.stop !== 'boolean') throw companionError('观察权限必选,审批和停止权限需要明确选择。'); + if (!Number.isInteger(input.expiresInHours) || input.expiresInHours < 1 || input.expiresInHours > 720) throw companionError('设备有效期应为1至720小时。'); + return structuredClone(input); +} +export function companionName(value) { + if (typeof value !== 'string' || !value.trim() || value.trim().length > 60 || /[\x00-\x1f\x7f]/.test(value)) throw companionError('设备名称需要1至60个可见字符。'); + return value.trim(); +} +export function approvalBinding(session, approval) { + // Every execution-relevant approval field participates; no caller-supplied + // command, path or tool arguments are accepted by the gateway. + const { status, decidedAt, ...input } = approval; + return companionHash(JSON.stringify({ sessionId: session.id, taskId: session.taskId, runId: session.runId, input })); +} +export function operationInput(input, approve) { + fields(input, ['requestId', 'taskId', 'runId', 'revision', ...(approve ? ['approvalId', 'fingerprint', 'allow'] : [])]); + if (![input.requestId, input.taskId, input.runId, ...(approve ? [input.approvalId] : [])].every(isId) + || !Number.isSafeInteger(input.revision) || input.revision < 0 || approve && (!/^[a-f0-9]{64}$/.test(input.fingerprint) || typeof input.allow !== 'boolean')) throw companionError('原任务、运行或审批依据无效。'); + return input; +} diff --git a/task_plan.md b/task_plan.md index 0cd1fc44..80d450f2 100644 --- a/task_plan.md +++ b/task_plan.md @@ -1,6 +1,19 @@ # Agent Workbench:核心代理能力研究与产品计划 -## 2026-10-31 当前任务:1.15 Windows桌面宿主与持久连接 +## 2026-10-31 当前任务:1.16 手机伴随端 + +用户授权全阶段开发并及时回顾。以06c9fac/正式1.15.0为基线,在feat/mobile-companion-1.16实施PLAN-1.16六个切片。用户选择iPhone,可配合手机证书信任;Windows提供HTTPS服务,同Wi-Fi的iPhone Safari/PWA实际联调。开发使用自有数据/端口/凭据,保留正式宿主与Provider;不读取真实Key、不发送真实模型请求,不新建代理/goal/automation/chat。 + +1. [complete] A:默认关闭的独立HTTPS监听、宿主/用户/网关绑定、256位短效单次配对与原子设备登记;实际受信TLS、Windows DPAPI和54项关联检查通过,正式宿主未操作。 +2. [complete] B:项目范围、观察/审批/停止权限、会话轮换、撤销/到期、速率限制与脱敏审计;越权/直调/事务回滚通过。C–E新增流程继续独立验收。 +3. [in_progress] C:桌面连接管理与独立手机PWA,复用原Task/Run、进展/差异/检查/预算/unknown与报告;界面已写入,实际宽窄屏尚待构建与观察。 +4. [pending] D:原审批ID/Task/Run/输入指纹/修订绑定、幂等与同一原任务停止;实际竞争和未知结果检查。 +5. [pending] E:授权项目原seq分页、断线补发/去重、工件SHA与撤销活动连接;原结果不重放。 +6. [pending] F:全量源码/历史UI/独立发行及保留状态部署;真实iPhone配对、证书信任、后台/切网/撤销由设备结果判定,不用390px模拟代替。 + +初读纠错:实际入口为src/server/index.mjs和src/server/runtime.mjs,一次猜测路径读取失败无副作用。首次计划批量补丁因findings标题锚点错误整批拒绝,未写入;移除错误锚点后重试。后续按实际文件定位。 + +## 2026-10-31 已交付:1.15 Windows桌面宿主与持久连接 当前最终候选20261031071202956:A–F完整交付。495/495独立源码、23类179组历史UI、真实窗口7/原生UI9/三工程16节点、父8/8、9/9、10/10、同载荷安装/重启/卸载7组(隔离测试登记,正式产品安装器另行stage)、正式18页、1446条工件记录和1357个去重文件核对通过;纠正升级、实际原生窗口和所有持久数据核对均完成,正式PID36552保持。下一PLAN-1.16仍仅计划。 diff --git a/tests/companion.test.mjs b/tests/companion.test.mjs new file mode 100644 index 00000000..9988ce90 --- /dev/null +++ b/tests/companion.test.mjs @@ -0,0 +1,223 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import https from 'node:https'; +import fs from 'node:fs'; +import path from 'node:path'; +import { randomBytes, randomUUID, createCipheriv, createDecipheriv, X509Certificate } from 'node:crypto'; +import { fixture } from './helpers.mjs'; +import { CompanionGateway } from '../src/server/companion-gateway.mjs'; +import { DeviceRegistry } from '../src/core/companion/device-registry.mjs'; +import { CompanionTLS } from '../src/core/companion/tls-authority.mjs'; +import { approvalBinding, companionHash } from '../src/shared/contracts/companion.mjs'; + +function setup(t) { + const value = fixture(t), host = { instanceId: randomUUID(), ownerId: randomUUID(), userSid: 'fixture-current-user', pid: process.pid, createdAt: new Date().toISOString() }; + let clock = Date.now(); + const registry = new DeviceRegistry(value.store, () => host, { clock: () => clock }); + const grant = { projectIds: [value.project.id], permissions: { observe: true, approve: false, stop: false }, expiresInHours: 24 }; + registry.initialize(); + return { ...value, registry, grant, host, advance: ms => { clock += ms; } }; +} +function testSealing() { + // This explicit dependency is confined to tests. Product code always uses + // Windows CurrentUser DPAPI and has no plaintext/non-Windows fallback. + const key = randomBytes(32); + return { protect: (bytes, entropy) => { + const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', key, iv); cipher.setAAD(entropy); + const encrypted = Buffer.concat([cipher.update(bytes), cipher.final()]); return Buffer.concat([iv, cipher.getAuthTag(), encrypted]); + }, unprotect: (bytes, entropy) => { + const decipher = createDecipheriv('aes-256-gcm', key, bytes.subarray(0, 12)); decipher.setAuthTag(bytes.subarray(12, 28)); decipher.setAAD(entropy); + return Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]); + } }; +} +async function running(t) { + const f = setup(t), runtime = { waiters: new Map(), decide() { throw new Error('No approval'); }, async stop() {} }; + const appDirectory = path.join(f.root, 'app'); fs.mkdirSync(path.join(appDirectory, 'dist-client'), { recursive: true }); + fs.writeFileSync(path.join(appDirectory, 'dist-client', 'mobile.html'), 'Test mobile entry'); + fs.writeFileSync(path.join(appDirectory, 'dist-client', 'mobile-assets.json'), '[]'); + const gateway = new CompanionGateway({ store: f.store, runtime, appDirectory, identity: () => f.host, redact: value => String(value).replaceAll('fixture-secret', '[REDACTED]') }, + { tlsOptions: testSealing(), allowLoopback: true }); + f.onCleanup(() => gateway.close()); + assert.equal(gateway.status().enabled, false); + await gateway.start({ address: '127.0.0.1', port: 0 }); + const ca = gateway.registry.read().tls.certificate; + const request = (route, data, { cookie = '', origin = gateway.origin, headers = {} } = {}) => new Promise((resolve, reject) => { + const req = https.request(gateway.origin + route, { ca, servername: '', method: data === undefined ? 'GET' : 'POST', headers: { + ...(cookie ? { Cookie: cookie } : {}), ...(origin ? { Origin: origin } : {}), ...(data === undefined ? {} : { 'Content-Type': 'application/json' }), Connection: 'close', ...headers } }, res => { + const chunks = []; res.on('data', chunk => chunks.push(chunk)); res.on('end', () => { + const text = Buffer.concat(chunks).toString('utf8'); let body; try { body = JSON.parse(text); } catch { body = text; } + resolve({ status: res.statusCode, headers: res.headers, body }); + }); + }); req.on('error', reject); req.end(data === undefined ? undefined : JSON.stringify(data)); + }); + async function pair(grant = f.grant) { + const ticket = await gateway.pairing(grant), token = new URLSearchParams(new URL(ticket.url).hash.slice(1)).get('pair'); + const result = await request('/mobile-api/pair', { token, name: '测试iPhone' }); + assert.equal(result.status, 201, JSON.stringify(result.body)); + const cookie = result.headers['set-cookie'][0].split(';')[0]; return { ticket, token, cookie, device: result.body.device }; + } + return { ...f, gateway, runtime, request, pair }; +} + +test('pairing is short lived, single-use, generation-bound and validates exact permissions', t => { + const f = setup(t), pair = f.registry.pair(f.grant, 'generation'); + assert.match(pair.token, /^[A-Za-z0-9_-]{43}$/); + assert.throws(() => f.registry.consume(pair.token, 'phone', 'other'), /无效/); + const accepted = f.registry.consume(pair.token, 'phone', 'generation'); + assert.equal(f.registry.authenticate(accepted.token).id, accepted.device.id); + assert.throws(() => f.registry.consume(pair.token, 'phone', 'generation'), /无效/); + const next = f.registry.pair(f.grant, 'generation'); f.advance(120001); + assert.throws(() => f.registry.consume(next.token, 'phone', 'generation'), /过期/); + assert.throws(() => f.registry.pair({ ...f.grant, permissions: { ...f.grant.permissions, execute: true } }, 'g'), /字段/); + assert.throws(() => f.registry.pair({ ...f.grant, projectIds: [randomUUID()] }, 'g'), /项目/); +}); + +test('device transaction failure neither consumes the ticket nor leaves a credential', t => { + const f = setup(t), pair = f.registry.pair(f.grant, 'g'); + f.store.storage.faultInjector = () => { throw new Error('disk fixture'); }; + assert.throws(() => f.registry.consume(pair.token, 'phone', 'g'), /disk fixture/); + assert.equal(f.registry.view().devices.length, 0); + f.store.storage.faultInjector = null; + assert.equal(f.registry.consume(pair.token, 'phone', 'g').device.name, 'phone'); +}); + +test('devices have project and action boundaries; rotation, expiration, revocation and host changes reject old authority', t => { + const f = setup(t), pair = f.registry.pair(f.grant, 'g'), accepted = f.registry.consume(pair.token, 'phone', 'g'); + const device = f.registry.authenticate(accepted.token); + assert.throws(() => f.registry.authorize(device, randomUUID()), /权限/); + assert.throws(() => f.registry.authorize(device, f.project.id, 'stop'), /权限/); + const rotated = f.registry.rotate(device); + assert.throws(() => f.registry.authenticate(accepted.token), /轮换/); + const current = f.registry.authenticate(rotated); f.registry.revoke(current.id, current.revision); + assert.throws(() => f.registry.authenticate(rotated), /撤销/); + const fresh = f.registry.consume(f.registry.pair(f.grant, 'g').token, 'other', 'g'); f.advance(25 * 3600000); + assert.throws(() => f.registry.authenticate(fresh.token), /到期/); + f.host.instanceId = randomUUID(); assert.throws(() => f.registry.authenticate(fresh.token), /宿主/); +}); + +test('persistent registry stores hashes and a bounded audit, never raw credentials', t => { + const f = setup(t), ticket = f.registry.pair(f.grant, 'g'), accepted = f.registry.consume(ticket.token, 'iPhone', 'g'); + const text = JSON.stringify(f.store.storage.meta('mobileCompanion')); + assert.ok(!text.includes(ticket.token) && !text.includes(accepted.token)); + const nextHost = { ...f.host, instanceId: randomUUID() }; + const registry = new DeviceRegistry(f.store, () => nextHost); + assert.equal(registry.authenticate(accepted.token).name, 'iPhone'); + assert.ok(!JSON.stringify(registry.view()).includes('credentialHash')); +}); + +test('real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint', async t => { + const f = await running(t), first = f.gateway.tls.publicCertificate(); + assert.equal(new X509Certificate(first.bytes).ca, true); + assert.equal(companionHash(first.bytes), first.sha256); + assert.equal((await f.request('/')).status, 200); + const record = f.gateway.registry.read().tls; + assert.ok(!Buffer.from(record.ciphertext, 'base64').toString('utf8').includes('pkcs8')); + const origin = f.gateway.origin; await f.gateway.close(); + await f.gateway.start({ address: '127.0.0.1', port: Number(new URL(origin).port) }); + assert.equal(f.gateway.tls.publicCertificate().sha256, first.sha256); + assert.equal((await f.request('/')).status, 200); +}); + +test('TLS sealing failure leaves listener closed and no plaintext or successful TLS registration', async t => { + const f = setup(t), tls = new CompanionTLS(f.registry, { protect() { throw new Error('fixture encryption failure'); } }); + await assert.rejects(tls.material('127.0.0.1'), /encryption/); + assert.equal(f.registry.read().tls, undefined); +}); + +test('HTTP pairing is concurrent single-use; secure cookie and strict origin/host checks', async t => { + const f = await running(t), ticket = await f.gateway.pairing(f.grant), token = new URLSearchParams(new URL(ticket.url).hash.slice(1)).get('pair'); + assert.match(ticket.qr, /^data:image\/png;base64,/); + const attempts = await Promise.all([f.request('/mobile-api/pair', { token, name: 'first' }), f.request('/mobile-api/pair', { token, name: 'second' })]); + assert.deepEqual(attempts.map(value => value.status).sort(), [201, 401]); + const accepted = attempts.find(value => value.status === 201); + assert.match(accepted.headers['set-cookie'][0], /; Secure; HttpOnly; SameSite=Strict/); + assert.equal((await f.request('/mobile-api/pair', { token, name: 'third' }, { origin: 'https://unrelated.invalid' })).status, 403); + assert.equal((await f.request('/', undefined, { headers: { Host: 'localhost:443' } })).status, 421); +}); + +test('gateway never exposes management routes, arbitrary assets or unpaired project data', async t => { + const f = await running(t); + assert.equal((await f.request('/mobile-api/projects')).status, 401); + const { cookie } = await f.pair(); + for (const route of ['/api/bootstrap', '/api/config', '/index.html', '/assets/desktop.js', '/src/server/index.mjs', '/mobile-api/config', '/mobile-api/projects?expand=all']) { + const result = await f.request(route, undefined, { cookie }); assert.ok(result.status >= 400, route); + assert.ok(!JSON.stringify(result.body).includes('Workbench-Token')); + } +}); + +test('authorized project events paginate from original seq without leaking other project events or payloads', async t => { + const f = await running(t), otherRoot = path.join(f.root, 'other'); fs.mkdirSync(otherRoot); + const otherProject = f.store.addProject(otherRoot), other = f.store.createSession(otherProject.id); + for (let i = 0; i < 7; i++) { f.store.save(other, { detail: { secret: 'fixture-secret' } }); f.store.save(f.session); } + const { cookie } = await f.pair(); let after = 0, events = []; + for (let i = 0; i < 20; i++) { + const page = await f.request('/mobile-api/events?after=' + after + '&limit=2', undefined, { cookie }); assert.equal(page.status, 200); + events.push(...page.body.events); after = page.body.nextCursor; + if (!page.body.hasMore) break; + } + assert.ok(events.length >= 8); assert.equal(new Set(events.map(event => event.seq)).size, events.length); + assert.ok(events.every(event => event.projectId === f.project.id && !Object.hasOwn(event, 'payload'))); + assert.equal((await f.request('/mobile-api/sessions/' + other.id, undefined, { cookie })).status, 403); + const projects = await f.request('/mobile-api/projects', undefined, { cookie }); + assert.equal(projects.body.length, 1); assert.equal(projects.body[0].root, undefined); +}); + +test('remote task projection excludes raw model history, host configuration, tool input and credentials', async t => { + const f = await running(t); f.session.providerMessages.push({ role: 'system', content: 'private-model-history' }); + f.session.events.push({ id: randomUUID(), label: 'check', input: { token: 'private-input' }, output: 'fixture-secret' }); f.store.save(f.session); + const { cookie } = await f.pair(), result = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie }); + assert.equal(result.status, 200); const text = JSON.stringify(result.body); + assert.ok(!text.includes('private-model-history') && !text.includes('private-input') && !text.includes('fixture-secret')); + assert.equal(result.body.events.at(-1).output, '[REDACTED]'); +}); + +test('permission checks apply to direct remote mutation, not only UI controls', async t => { + const f = await running(t), { cookie } = await f.pair(); + f.session.taskId = randomUUID(); f.session.runId = randomUUID(); f.store.save(f.session); + const result = await f.request('/mobile-api/sessions/' + f.session.id + '/stop', { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision }, { cookie }); + assert.equal(result.status, 403); +}); + +test('approval fingerprint and exact task/revision are bound; duplicate requests never execute twice', async t => { + const f = await running(t), grant = { ...f.grant, permissions: { observe: true, approve: true, stop: true } }, { cookie } = await f.pair(grant); + f.session.taskId = randomUUID(); f.session.runId = randomUUID(); + const approval = { id: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, projectId: f.project.id, command: 'echo owned', reason: 'fixture', status: 'pending' }; + f.session.approvals.push(approval); f.runtime.waiters.set(approval.id, { sessionId: f.session.id, runId: f.session.runId }); f.store.save(f.session); + let calls = 0; + f.runtime.decide = (_session, _approval, allow) => { calls++; assert.equal(allow, true); approval.status = 'approved'; f.runtime.waiters.delete(approval.id); f.store.save(f.session); }; + const value = { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision, approvalId: approval.id, fingerprint: approvalBinding(f.session, approval), allow: true }; + const route = '/mobile-api/sessions/' + f.session.id + '/approve'; + assert.equal((await f.request(route, { ...value, fingerprint: '0'.repeat(64) }, { cookie })).status, 409); + const results = await Promise.all([f.request(route, value, { cookie }), f.request(route, value, { cookie })]); + assert.ok(results.every(result => result.status === 200)); assert.equal(calls, 1); + assert.equal((await f.request(route, { ...value, allow: false }, { cookie })).status, 409); +}); + +test('unknown original operation is recorded and never replayed after response failure', async t => { + const f = await running(t), { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: false, stop: true } }); + f.session.taskId = randomUUID(); f.session.runId = randomUUID(); f.store.save(f.session); + let calls = 0; f.runtime.stop = async () => { calls++; throw new Error('fixture interrupted receipt'); }; + const value = { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision }, route = '/mobile-api/sessions/' + f.session.id + '/stop'; + assert.equal((await f.request(route, value, { cookie })).status, 409); + const retry = await f.request(route, value, { cookie }); assert.equal(retry.body.status, 'unknown'); assert.equal(calls, 1); +}); + +test('revocation and gateway closure reject old access without invoking runtime stop', async t => { + const f = await running(t), { cookie, device } = await f.pair(); let stopped = 0; f.runtime.stop = () => { stopped++; }; + f.gateway.revoke(device.id, device.revision); + assert.equal((await f.request('/mobile-api/projects', undefined, { cookie })).status, 401); + await f.gateway.close(); assert.equal(stopped, 0); assert.equal(f.gateway.status().enabled, false); +}); + +test('rate limits reject pairing brute force and do not persist candidate secrets', async t => { + const f = await running(t); let last; + for (let i = 0; i < 9; i++) last = await f.request('/mobile-api/pair', { token: randomBytes(32).toString('base64url'), name: 'phone' }); + assert.equal(last.status, 429); assert.equal(f.gateway.registry.view().devices.length, 0); +}); + +test('real Windows CurrentUser DPAPI persists only a sealed CA and reopens it', { skip: process.platform !== 'win32' }, async t => { + const f = setup(t), tls = new CompanionTLS(f.registry); + await tls.material('127.0.0.1'); const hash = tls.publicCertificate().sha256; + await new CompanionTLS(f.registry).material('127.0.0.1'); + assert.equal(tls.publicCertificate().sha256, hash); +});