From 412b90712696402894a36e993a91c95982a5f007 Mon Sep 17 00:00:00 2001 From: qiqi Date: Sun, 22 Nov 2026 16:09:56 +0800 Subject: [PATCH] =?UTF-8?q?feat(plugins):=20zip=20=E6=89=93=E5=8C=85/?= =?UTF-8?q?=E8=A7=A3=E5=8C=85=E6=A8=A1=E5=9D=97=EF=BC=88=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95=20+=20=E4=B8=8A=E9=99=90=20+=20?= =?UTF-8?q?=E9=87=8D=E5=90=8D=E6=8B=92=E7=BB=9D=EF=BC=89+=20=E6=B5=8B?= =?UTF-8?q?=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CONTRIBUTING.md | 2 +- docs/standards/architecture-current-state.md | 8 +- package.json | 2 +- scripts/build.js | 1 + src/plugin-archive.js | 206 +++++++++++++++++ tests/fixtures/iwb-source-modules-order.json | 1 + tests/plugin-archive-test.js | 226 +++++++++++++++++++ 7 files changed, 440 insertions(+), 6 deletions(-) create mode 100644 src/plugin-archive.js create mode 100644 tests/plugin-archive-test.js diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1072249..f1b77db 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,7 +41,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序 node --check app.js 与 dist/app.js 语法 check-dist.js 产物体检 lint ESLint(src/ + app.js,正确性规则) -test:unit 115 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) +test:unit 116 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) test relay-task-graph-fixture + iwb-v32-web-test test:facts 事实基线守门(见 §5) typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js) diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index 649f99e..5425a65 100644 --- a/docs/standards/architecture-current-state.md +++ b/docs/standards/architecture-current-state.md @@ -22,7 +22,7 @@ - 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob__`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。 - 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。 - 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。 -- `app.js` = 单 IIFE **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **106** 个模块 / 14,607 行,`sourceModules` 106 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 +- `app.js` = 单 IIFE **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **107** 个模块 / 14,607 行,`sourceModules` 107 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 - 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。 ## 2. 门禁与环境现状 @@ -167,7 +167,7 @@ - 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。 - **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。 - **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A) - - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**106 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 + - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**107 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 - **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。) - **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。 - **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。 @@ -183,7 +183,7 @@ | `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 | | `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 | | `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) | - - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**86** 项)与 `sourceModules` 顺序(**106** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 + - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**86** 项)与 `sourceModules` 顺序(**107** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 ## 12. 易踩的坑 @@ -254,7 +254,7 @@ **信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。 -**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**86** 项)与 `sourceModules` 顺序(**106** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 +**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**86** 项)与 `sourceModules` 顺序(**107** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 **关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。 diff --git a/package.json b/package.json index 077cd0e..ac6ba0d 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "app:build": "tauri build", "lint": "eslint src app.js", "test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js", - "test:unit": "node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js", + "test:unit": "node tests/plugin-archive-test.js && node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js", "test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js", "test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js", "plugins:gc": "node scripts/plugins-publish.mjs --gc", diff --git a/scripts/build.js b/scripts/build.js index 980dd6d..44dc948 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -69,6 +69,7 @@ const sourceModules = [ 'storage-outputs.js', 'storage-backup.js', 'storage-zip.js', + 'plugin-archive.js', 'runtime-constants.js', 'canvas-store.js', 'generation-scheduler.js', diff --git a/src/plugin-archive.js b/src/plugin-archive.js new file mode 100644 index 0000000..fd562bb --- /dev/null +++ b/src/plugin-archive.js @@ -0,0 +1,206 @@ +/* plugin-archive.js —— 插件包 ZIP 打包/解包(浏览器侧) + * + * 为什么要有这一层: + * - 插件包是**外部输入**:ZIP 里可能藏 ../、绝对路径、反斜杠、超限条目(zip 炸弹)。 + * 直接把它交给 storage-zip 读写,会把「能不能解」和「该不该解」混在一起; + * 本模块只做准入判断,ZIP 编解码仍全部复用 src/storage-zip.js。 + * - 打包与解包共用同一套校验,避免「写的时候放行、读的时候才拦」造成半成品包。 + * + * 插件包布局(只允许这几种路径): + * - data.json / meta.json 顶层元数据 + * - images/.(jpg|jpeg|png|webp) 图片资源(images/ 下不再允许子目录) + * + * ⚠️ 重名检测不能只看 wOpenZipBlob 的 files 映射:它是普通对象,同名条目会被 + * 后一个静默覆盖。所以先用 wZipParseEntries 读中央目录做名字/声明大小/重名预检, + * 再用 wOpenZipBlob 逐条读字节并复核**实际**大小(声明大小可伪造,不能当唯一防线)。 + */ +;(function (global) { + 'use strict' + + const MAX_FILES = 500 + const MAX_FILE_BYTES = 16 * 1024 * 1024 + const MAX_TOTAL_BYTES = 64 * 1024 * 1024 + // 名字过长会写坏 ZIP 的 16 位名称长度字段,也超出常见文件系统上限,直接拒绝。 + // 名字被白名单限制为 ASCII,所以字符数即字节数。 + const MAX_NAME_LENGTH = 255 + const SAFE_NAME_RE = /^[A-Za-z0-9._/-]+$/ + const IMAGE_EXT_RE = /\.(?:jpe?g|png|webp)$/i + const IMAGE_DIR = 'images/' + const TOP_FILES = ['data.json', 'meta.json'] + + // 上限必须可被调用方/测试读取:这些数字就是信任边界,散落在函数里容易被改错。 + const limits = Object.freeze({ + maxFiles: MAX_FILES, + maxFileBytes: MAX_FILE_BYTES, + maxTotalBytes: MAX_TOTAL_BYTES, + }) + + function isDirectory (name) { + return name.charAt(name.length - 1) === '/' + } + + // 名字是唯一进入 ZIP 的路径,按「明显穿越 → 字符 → 路径段 → 白名单前缀」顺序校验。 + // 顺序是刻意的:先报「反斜杠 / .. / 绝对路径」,错误消息才能指向真正原因, + // 而不是笼统地报一句"含非法字符"。 + function validateName (name) { + if (typeof name !== 'string' || name.length === 0) throw new Error('文件名必须是非空字符串') + if (name.indexOf('\\') !== -1) throw new Error('文件名不能包含反斜杠:' + name) + for (let i = 0; i < name.length; i++) { + const code = name.charCodeAt(i) + if (code < 0x20 || code === 0x7f) throw new Error('文件名不能包含控制字符:' + JSON.stringify(name)) + } + if (name.charAt(0) === '/') throw new Error('文件名不能是绝对路径:' + name) + if (!SAFE_NAME_RE.test(name)) throw new Error('文件名含非法字符(只允许字母数字、-、_、.、/):' + name) + if (name.length > MAX_NAME_LENGTH) { + throw new Error('文件名过长(最多 ' + MAX_NAME_LENGTH + ' 个字符):' + name.slice(0, 64) + '...') + } + const dir = isDirectory(name) + const body = dir ? name.slice(0, -1) : name + if (body.length === 0) throw new Error('文件名不能为空:' + name) + for (const part of body.split('/')) { + if (part === '..') throw new Error('文件名不能包含 .. 路径段:' + name) + if (part === '.' || part === '') throw new Error('文件名包含非法路径段:' + name) + } + if (dir) { + // 只接受 images/ 这一种目录条目;其余目录没有业务含义,放行只会扩大攻击面。 + if (body !== 'images') throw new Error('ZIP 只允许 images/ 目录条目:' + name) + return { name, dir: true } + } + if (TOP_FILES.indexOf(name) !== -1) return { name, dir: false } + if (name.indexOf(IMAGE_DIR) !== 0) throw new Error('文件名不在允许的路径内(仅 data.json、meta.json、images/):' + name) + const rest = name.slice(IMAGE_DIR.length) + if (rest.indexOf('/') !== -1) throw new Error('images/ 下不允许再建子目录:' + name) + if (!IMAGE_EXT_RE.test(rest)) throw new Error('图片只允许 .jpg/.jpeg/.png/.webp 后缀:' + name) + return { name, dir: false } + } + + function encodeData (data, name) { + if (typeof data === 'string') return new global.TextEncoder().encode(data) + // 用 brand check 而不是 instanceof:模块可能被放在 iframe/vm 等不同 realm 里, + // 跨 realm 的 Uint8Array 用 instanceof 判断会误杀正常输入。 + if (Object.prototype.toString.call(data) === '[object Uint8Array]') { + return new global.Uint8Array(data.buffer, data.byteOffset, data.byteLength) + } + throw new Error('文件内容必须是 Uint8Array 或 string:' + name) + } + + function storage () { + const S = global.IWBStorageZip + if (!S) throw new Error('ZIP 能力不可用(IWBStorageZip 未加载)') + return S + } + + function assertBlob (blob) { + if (!blob || typeof blob.arrayBuffer !== 'function' || typeof blob.size !== 'number') { + throw new Error('解包输入必须是 Blob') + } + } + + async function zip (files) { + if (!Array.isArray(files)) throw new Error('打包输入必须是文件数组') + if (files.length > MAX_FILES) throw new Error('文件数超过上限(最多 ' + MAX_FILES + ' 个):' + files.length) + const seen = new Set() + const items = [] + let total = 0 + // 先把整批文件校验完再动写入器:校验失败时不要留下写了一半的 ZIP。 + for (const f of files) { + if (!f || typeof f !== 'object') throw new Error('文件项必须是 { name, data } 对象') + const checked = validateName(f.name) + if (checked.dir) throw new Error('打包列表不能包含目录条目:' + checked.name) + if (seen.has(checked.name)) throw new Error('ZIP 中存在重名条目:' + checked.name) + seen.add(checked.name) + const bytes = encodeData(f.data, checked.name) + if (bytes.byteLength > MAX_FILE_BYTES) throw new Error('单个文件超过上限(16MB):' + checked.name) + total += bytes.byteLength + if (total > MAX_TOTAL_BYTES) throw new Error('文件总大小超过上限(64MB):' + checked.name) + items.push({ name: checked.name, bytes }) + } + const S = storage() + if (typeof S.wCreateStoreZip !== 'function') throw new Error('ZIP 写入能力不可用(IWBStorageZip.wCreateStoreZip 缺失)') + const zw = S.wCreateStoreZip() + if (!zw || typeof zw.add !== 'function' || typeof zw.finish !== 'function') throw new Error('ZIP 写入器不可用') + for (const item of items) { + // 每个文件单独一个 Blob:storage-zip 会把 Blob 原样作为 ZIP part,字节不必堆进 JS 堆。 + await zw.add(item.name, new global.Blob([item.bytes])) + } + const blob = zw.finish() + if (!blob || typeof blob.arrayBuffer !== 'function') throw new Error('ZIP 写入失败:没有产出 Blob') + return blob + } + + // 中央目录预检。返回 null 表示当前客户端没有 wZipParseEntries —— + // 此时只能退化为 files 映射校验(该映射会吞掉重名,属于已知降级)。 + async function scanEntries (S, blob) { + if (typeof S.wZipParseEntries !== 'function') return null + let parsed + try { + parsed = S.wZipParseEntries(await blob.arrayBuffer()) + } catch (e) { + throw new Error('ZIP 解析失败:' + ((e && e.message) || e)) + } + const entries = (parsed && parsed.entries) || [] + if (entries.length > MAX_FILES) { + throw new Error('ZIP 条目数超过上限(最多 ' + MAX_FILES + ' 个):' + entries.length) + } + const names = [] + const seen = new Set() + let declaredTotal = 0 + for (const e of entries) { + const checked = validateName(e && e.name) + if (checked.dir) continue + // 声明大小先卡一道:明显超限的炸弹包不必等读出全部字节才报错。 + const rawSize = Number(e.rawSize) || 0 + if (rawSize > MAX_FILE_BYTES) throw new Error('解包后单个文件超过上限(16MB):' + checked.name) + declaredTotal += rawSize + if (declaredTotal > MAX_TOTAL_BYTES) throw new Error('解包后总大小超过上限(64MB):' + checked.name) + if (seen.has(checked.name)) throw new Error('ZIP 中存在重名条目:' + checked.name) + seen.add(checked.name) + names.push(checked.name) + } + return names + } + + async function unzip (blob) { + assertBlob(blob) + const S = storage() + if (typeof S.wOpenZipBlob !== 'function') throw new Error('ZIP 读取能力不可用(IWBStorageZip.wOpenZipBlob 缺失)') + const parsedNames = await scanEntries(S, blob) + let opened + try { + opened = await S.wOpenZipBlob(blob) + } catch (e) { + throw new Error('ZIP 解析失败:' + ((e && e.message) || e)) + } + const map = opened && opened.files + if (!map || typeof map !== 'object') throw new Error('ZIP 打开失败:没有文件表') + let names = parsedNames + if (!names) { + // 降级路径:没有中央目录解析能力时,只能按 files 映射的键校验。 + names = Object.keys(map) + if (names.length > MAX_FILES) throw new Error('ZIP 条目数超过上限(最多 ' + MAX_FILES + ' 个):' + names.length) + for (const name of names) validateName(name) + } + const out = [] + let total = 0 + for (const name of names) { + const entry = (typeof opened.file === 'function') ? opened.file(name) : map[name] + if (!entry || typeof entry.async !== 'function') throw new Error('ZIP 条目读取失败:' + name) + let bytes + try { + bytes = await entry.async('uint8array') + } catch (e) { + throw new Error('ZIP 条目解压失败(' + name + '):' + ((e && e.message) || e)) + } + if (!bytes || typeof bytes.byteLength !== 'number') throw new Error('ZIP 条目内容非法:' + name) + // 中央目录里的 rawSize 可以伪造,真实字节数必须再复核一次(zip 炸弹的最终防线)。 + if (bytes.byteLength > MAX_FILE_BYTES) throw new Error('解包后单个文件超过上限(16MB):' + name) + total += bytes.byteLength + if (total > MAX_TOTAL_BYTES) throw new Error('解包后总大小超过上限(64MB):' + name) + // 复制一份再交付,避免返回值与 ZIP 内部大 buffer 长期共享(也防止调用方改写源字节)。 + out.push({ name, data: new global.Uint8Array(bytes) }) + } + return out + } + + global.IWBPluginArchive = Object.freeze({ zip, unzip, limits }) +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/tests/fixtures/iwb-source-modules-order.json b/tests/fixtures/iwb-source-modules-order.json index 17d557f..9fe9c41 100644 --- a/tests/fixtures/iwb-source-modules-order.json +++ b/tests/fixtures/iwb-source-modules-order.json @@ -41,6 +41,7 @@ "storage-outputs.js", "storage-backup.js", "storage-zip.js", + "plugin-archive.js", "runtime-constants.js", "canvas-store.js", "generation-scheduler.js", diff --git a/tests/plugin-archive-test.js b/tests/plugin-archive-test.js new file mode 100644 index 0000000..7237053 --- /dev/null +++ b/tests/plugin-archive-test.js @@ -0,0 +1,226 @@ +'use strict' + +// src/plugin-archive.js 的行为测试。 +// +// 为什么测试要这么细:插件包来自外部,ZIP 解包是这个功能的**信任边界**。 +// 路径穿越、非法后缀、重名条目、超限条目(zip 炸弹)只要漏一个, +// 用户点一次"导入插件"就可能把文件写到插件目录之外,或把内存/磁盘打爆。 +// +// 用 vm 加载真实模块(IIFE 挂 window),并先加载 src/storage-zip.js —— +// 测试不 mock ZIP 编解码,测的就是线上真实走的那条链路。 +// ⚠️ 跨 realm:模块在 vm 里创建对象/数组,原型与本文件不同, +// 所以内容比较统一走 JSON,不能用 deepStrictEqual。 + +const assert = require('assert') +const fs = require('fs') +const path = require('path') +const vm = require('vm') +const root = path.resolve(__dirname, '..') + +const sandbox = { + console: { log() {}, warn() {}, error() {} }, + TextEncoder, TextDecoder, Blob, DataView, Uint8Array, Uint32Array, + Response, DecompressionStream, Date, Error, Math, String, Number, Array, Object, JSON, Promise, Set, Map, Boolean, isNaN, parseInt, +} +vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'storage-zip.js'), 'utf8'), sandbox) +vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'plugin-archive.js'), 'utf8'), sandbox) + +const Z = sandbox.IWBStorageZip +const A = sandbox.IWBPluginArchive +assert.ok(Z, '应加载 IWBStorageZip(storage-zip.js 是被测模块的真实依赖)') +assert.ok(A, '应导出 IWBPluginArchive') + +const eqJson = (a, b, msg) => assert.strictEqual(JSON.stringify(a), JSON.stringify(b), msg) +const eqBytes = (a, b, msg) => eqJson(Array.from(a), Array.from(b), msg) + +// 绕过 IWBPluginArchive.zip 的校验,直接用底层写入器造"恶意 ZIP": +// 只有这样才能验证 unzip 自身的防线(真实攻击者也不会经过我们的 zip())。 +const rawZip = async (entries) => { + const w = Z.wCreateStoreZip() + for (const [name, data] of entries) await w.add(name, new Blob([data])) + return w.finish() +} + +const expectReject = async (fn, pattern, label) => { + let err = null + try { await fn() } catch (e) { err = e } + assert.ok(err, label + ':应 reject,实际却成功了') + assert.ok(pattern.test(String(err && err.message)), + label + ':错误消息应匹配 ' + pattern + ',实际:' + (err && err.message)) +} + +// 篡改中央目录里的"原始大小"字段:用一个几字节的小 ZIP 模拟声明 16MB/64MB 的炸弹包。 +// 这类包不需要真的把大字节读进内存,正好用来单独验证上限判断。 +const patchCentralRawSize = async (blob, size) => { + const buf = await blob.arrayBuffer() + const dv = new DataView(buf) + const u8 = new Uint8Array(buf) + const eocd = u8.length - 22 + const count = dv.getUint16(eocd + 10, true) + let p = dv.getUint32(eocd + 16, true) + for (let i = 0; i < count; i++) { + assert.strictEqual(dv.getUint32(p, true), 0x02014b50, '中央目录签名应正确') + dv.setUint32(p + 24, size, true) // 中央目录条目 +24 = 原始大小 + const nameLen = dv.getUint16(p + 28, true) + const extraLen = dv.getUint16(p + 30, true) + const commentLen = dv.getUint16(p + 32, true) + p += 46 + nameLen + extraLen + commentLen + } + return new Blob([buf]) +} + +;(async () => { + // ── 1. 导出面与上限常量 ──────────────────────────────────────────────── + { + assert.strictEqual(typeof A.zip, 'function', '应导出 zip') + assert.strictEqual(typeof A.unzip, 'function', '应导出 unzip') + assert.ok(A.limits && Object.isFrozen(A.limits), 'limits 应是冻结对象,防止运行期被改松') + assert.strictEqual(A.limits.maxFiles, 500, '条目上限应为 500') + assert.strictEqual(A.limits.maxFileBytes, 16 * 1024 * 1024, '单文件上限应为 16MB') + assert.strictEqual(A.limits.maxTotalBytes, 64 * 1024 * 1024, '总大小上限应为 64MB') + } + + // ── 2. 往返:zip → unzip,字节逐一致(含中文内容)──────────────────── + { + const binary = new Uint8Array(256) + for (let i = 0; i < binary.length; i++) binary[i] = i + const blob = await A.zip([ + { name: 'data.json', data: JSON.stringify({ title: '中文标题', n: 1 }) }, + { name: 'meta.json', data: '{"version":1}' }, + { name: 'images/a.jpg', data: binary }, + ]) + assert.ok(blob && typeof blob.arrayBuffer === 'function', '应产出 Blob') + assert.strictEqual(blob.type, 'application/zip', 'ZIP 的 MIME 应为 application/zip') + + const out = await A.unzip(blob) + eqJson(out.map((x) => x.name), ['data.json', 'meta.json', 'images/a.jpg'], '条目名与顺序应保持') + assert.strictEqual(new TextDecoder().decode(out[0].data), '{"title":"中文标题","n":1}', + '字符串内容按 UTF-8 写入、应原样读回(中文不能乱码)') + eqBytes(out[2].data, binary, '二进制内容应逐字节一致') + assert.strictEqual(Object.prototype.toString.call(out[0].data), '[object Uint8Array]', 'data 应是 Uint8Array') + } + + // ── 3. 路径穿越 / 绝对路径 / 反斜杠:打包与解包都必须拒绝 ───────────── + { + const cases = [ + ['../evil.js', /\.\.|路径段/], + ['/abs', /绝对路径/], + ['images/../../x', /\.\.|路径段/], + ['images\\a.jpg', /反斜杠/], + ] + for (const [name, pattern] of cases) { + await expectReject( + () => A.zip([{ name, data: new Uint8Array([1]) }]), + pattern, 'zip 应拒绝 ' + name + ) + await expectReject( + async () => A.unzip(await rawZip([[name, new Uint8Array([1])]])), + pattern, 'unzip 应拒绝 ' + name + ) + } + } + + // ── 4. 非法后缀 / 非白名单路径 / 中文文件名 ─────────────────────────── + // 白名单只允许 ASCII 字母数字与 - _ . /,所以中文文件名也应被拒绝 + // (中文可以出现在 data.json 的**内容**里,但不能出现在路径里)。 + { + await expectReject( + () => A.zip([{ name: 'images/a.gif', data: new Uint8Array([1]) }]), + /后缀.*images\/a\.gif/, 'zip 应拒绝 .gif' + ) + await expectReject( + async () => A.unzip(await rawZip([['images/a.gif', new Uint8Array([1])]])), + /后缀.*images\/a\.gif/, 'unzip 应拒绝 .gif' + ) + for (const name of ['other/a.jpg', 'data.json.bak', 'images/nested/a.jpg', 'images/中文.jpg', 'images/a']) { + await expectReject( + () => A.zip([{ name, data: new Uint8Array([1]) }]), + /允许的|子目录|后缀|非法字符/, 'zip 应拒绝白名单外名字 ' + name + ) + } + } + + // ── 5. 重名条目:不能让后一个静默覆盖前一个 ─────────────────────────── + // wOpenZipBlob 内部用普通对象存 files,重名会覆盖;所以 unzip 必须先用 + // 中央目录预检。这条测试就是防止以后有人把预检"优化"掉。 + { + await expectReject( + () => A.zip([ + { name: 'images/dup.jpg', data: new Uint8Array([1]) }, + { name: 'images/dup.jpg', data: new Uint8Array([2]) }, + ]), + /重名.*images\/dup\.jpg/, 'zip 应拒绝重名' + ) + const dup = await rawZip([ + ['images/dup.jpg', new Uint8Array([1])], + ['images/dup.jpg', new Uint8Array([2])], + ]) + await expectReject(() => A.unzip(dup), /重名.*images\/dup\.jpg/, 'unzip 应拒绝重名条目') + } + + // ── 6. 条目数 > 500(打包与解包)────────────────────────────────────── + { + const tooMany = [] + for (let i = 0; i < 501; i++) tooMany.push({ name: 'images/n' + i + '.jpg', data: new Uint8Array([1]) }) + await expectReject(() => A.zip(tooMany), /500|文件数/, 'zip 应拒绝 501 个文件') + + const tooManyRaw = [] + for (let i = 0; i < 501; i++) tooManyRaw.push(['images/n' + i + '.jpg', new Uint8Array([1])]) + await expectReject( + async () => A.unzip(await rawZip(tooManyRaw)), + /条目数.*500/, 'unzip 应拒绝 501 个条目' + ) + } + + // ── 7. 单文件 > 16MB:打包侧用真实长度;解包侧用伪造的声明长度 ───────── + { + const oversized = new Uint8Array(A.limits.maxFileBytes + 1) + await expectReject( + () => A.zip([{ name: 'images/big.jpg', data: oversized }]), + /16MB.*images\/big\.jpg/, 'zip 应拒绝 >16MB 的单文件' + ) + + const one = await rawZip([['images/a.jpg', new Uint8Array([1, 2, 3])]]) + const fakeSingle = await patchCentralRawSize(one, A.limits.maxFileBytes + 1) + await expectReject( + async () => A.unzip(fakeSingle), + /16MB.*images\/a\.jpg/, 'unzip 应按声明大小拒绝 >16MB 的单条目(防 zip 炸弹)' + ) + } + + // ── 8. 总解压 > 64MB(声明值伪造,避免测试真的分配 64MB)───────────── + { + const five = [] + for (let i = 0; i < 5; i++) five.push(['images/t' + i + '.jpg', new Uint8Array([1])]) + const blob = await rawZip(five) + // 5 × 13MB = 65MB:每个都在 16MB 以内,只有总和超限 → 专门打总大小那条判断。 + const fakeTotal = await patchCentralRawSize(blob, 13 * 1024 * 1024) + await expectReject(() => A.unzip(fakeTotal), /总大小.*64MB/, 'unzip 应拒绝解压后总大小 >64MB') + } + + // ── 9. 合法目录条目被跳过;非法输入/类型要显式报错 ─────────────────── + { + const withDir = await rawZip([ + ['images/', new Uint8Array(0)], + ['images/a.png', new Uint8Array([7, 8])], + ]) + const out = await A.unzip(withDir) + eqJson(out.map((x) => x.name), ['images/a.png'], 'images/ 目录条目应被跳过,不计入文件') + eqBytes(out[0].data, new Uint8Array([7, 8]), '目录后的文件内容应正常读出') + + await expectReject(() => A.zip('not-an-array'), /数组/, 'zip 应拒绝非数组输入') + await expectReject( + () => A.zip([{ name: 'data.json', data: 123 }]), + /Uint8Array 或 string/, 'zip 应拒绝非 Uint8Array/string 的内容' + ) + await expectReject(() => A.unzip('not-a-blob'), /Blob/, 'unzip 应拒绝非 Blob 输入') + await expectReject(() => A.unzip(new Blob([new Uint8Array(32)])), /ZIP/, 'unzip 应拒绝非 ZIP 字节') + } + + console.log('plugin archive checks passed(往返 + 路径穿越 + 白名单后缀 + 重名 + 条目数/单文件/总大小上限)') + // ⚠️ 显式退出:vm/Blob 可能让事件循环挂着(沿用 storage-zip-test 的处理)。 + process.exit(0) +})().catch((e) => { + console.error('plugin archive checks FAILED:', e && e.message) + process.exit(1) +})