From 0489d94461c59c960aa5a7ae5df0055b1f3d91a2 Mon Sep 17 00:00:00 2001 From: qiqi Date: Sun, 22 Nov 2026 16:07:58 +0800 Subject: [PATCH] =?UTF-8?q?feat(plugins):=20=E6=96=B0=E5=A2=9E=20files=20?= =?UTF-8?q?=E8=83=BD=E5=8A=9B=EF=BC=88plugin-data//files=20=E6=B2=99?= =?UTF-8?q?=E7=AE=B1=20+=20=E7=99=BD=E5=90=8D=E5=8D=95/=E9=85=8D=E9=A2=9D?= =?UTF-8?q?=E7=AD=96=E7=95=A5=20+=20=E6=B5=8B=E8=AF=95=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CONTRIBUTING.md | 2 +- app.js | 13 +++ docs/standards/architecture-current-state.md | 8 +- package.json | 2 +- scripts/build.js | 1 + src/plugin-files-policy.js | 40 +++++++++ src/plugin-host.js | 4 +- src/storage-file.js | 88 +++++++++++++++++++- tests/fixtures/iwb-source-modules-order.json | 1 + tests/plugin-files-policy-test.js | 34 ++++++++ tests/plugin-host-test.js | 2 +- 11 files changed, 185 insertions(+), 10 deletions(-) create mode 100644 src/plugin-files-policy.js create mode 100644 tests/plugin-files-policy-test.js diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 79b8b00..1072249 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 114 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) +test:unit 115 个单测文件(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/app.js b/app.js index 59616f1..68d8f55 100644 --- a/app.js +++ b/app.js @@ -8867,6 +8867,19 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) => gallery: () => ((typeof window !== 'undefined' && window.IWBPluginGallery) ? window.IWBPluginGallery.api() : {}), grouplib: () => ((typeof window !== 'undefined' && window.IWBPluginGroupLib) ? window.IWBPluginGroupLib.api() : {}), promptlib: () => ((typeof window !== 'undefined' && window.IWBPluginPromptLib) ? window.IWBPluginPromptLib.api() : {}), + // 插件文件能力(v3.26.36):沙箱目录 plugin-data//files,供插件自持图片 + files: (ctx) => { + const F = (typeof window !== 'undefined' && window.IWBStorageFile) ? window.IWBStorageFile.pluginFiles : null + const need = () => { if (!F) throw new Error('文件能力未就绪(资料目录尚未初始化)'); return F } + return { + put: (name, dataUrl) => need().put(ctx.id, name, dataUrl), + get: (name) => need().get(ctx.id, name), + list: () => need().list(ctx.id), + remove: (name) => need().remove(ctx.id, name), + stat: () => need().stat(ctx.id), + dir: () => need().dir(ctx.id), + } + }, commands: (ctx) => { const owned = [] return { diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index e131c3a..649f99e 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`(现 **105** 个模块 / 14,607 行,`sourceModules` 105 项;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`(现 **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 行)。 - 门禁:`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` 不引用模块全局)。**105 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 + - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**106 个模块中 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` 顺序(**105** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 + - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**86** 项)与 `sourceModules` 顺序(**106** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 ## 12. 易踩的坑 @@ -254,7 +254,7 @@ **信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。 -**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**86** 项)与 `sourceModules` 顺序(**105** 项);新增模块、新增耦合、新增 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` 顺序(**106** 项);新增模块、新增耦合、新增 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 6665865..077cd0e 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/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-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 2bf22f3..980dd6d 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -131,6 +131,7 @@ const sourceModules = [ 'ui-connect-menu.js', 'ui-gen-config-panel.js', 'canvas-webview.js', + 'plugin-files-policy.js', 'image-prompt-cover.js', ] diff --git a/src/plugin-files-policy.js b/src/plugin-files-policy.js new file mode 100644 index 0000000..97cb645 --- /dev/null +++ b/src/plugin-files-policy.js @@ -0,0 +1,40 @@ +/* plugin-files-policy.js —— 插件文件能力的纯策略(v3.26.36) + * + * 为什么单独成模块:文件名白名单与配额是安全边界,必须能在 Node 里单测; + * storage-file 里只留 IO,策略在这里,避免「安全靠人工」。 + */ +;(function (global) { + 'use strict' + + var LIMITS = Object.freeze({ + FILE_MAX: 8 * 1024 * 1024, // 单文件 8MB(640px 封面约 40~90KB,留足余量) + TOTAL_MAX: 64 * 1024 * 1024, // 单插件总量 64MB + }) + var NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}\.(jpg|jpeg|png|webp)$/i + + // 文件名只允许:字母数字 / - / _ + 图片后缀;禁止路径分隔、点段与控制字符。 + function fileOk (name) { + var s = String(name == null ? '' : name) + if (!s || s.length > 72) return false + if (!NAME_RE.test(s)) return false + if (s.indexOf('..') >= 0) return false + if (s.indexOf('/') >= 0) return false + if (s.indexOf(String.fromCharCode(92)) >= 0) return false + for (var i = 0; i < s.length; i++) { if (s.charCodeAt(i) < 32) return false } + return true + } + + // 配额:total 为现有总量;replacing 为同名旧文件大小(覆盖时不重复计)。 + function quotaOk (total, incoming, replacing, limits) { + var L = limits || LIMITS + var inc = Number(incoming) || 0 + var rep = Number(replacing) || 0 + var cur = Math.max(0, Number(total) || 0) + if (inc <= 0) return { ok: false, reason: 'empty' } + if (inc > L.FILE_MAX) return { ok: false, reason: 'file-too-large', limit: L.FILE_MAX } + if (cur - rep + inc > L.TOTAL_MAX) return { ok: false, reason: 'total-too-large', limit: L.TOTAL_MAX } + return { ok: true } + } + + global.IWBPluginFilesPolicy = { LIMITS: LIMITS, fileOk: fileOk, quotaOk: quotaOk } +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/plugin-host.js b/src/plugin-host.js index a726930..3d7d19e 100644 --- a/src/plugin-host.js +++ b/src/plugin-host.js @@ -4,8 +4,8 @@ const API_VERSION = 1 const ID_PATTERN = /^[a-z][a-z0-9-]{2,31}$/ const REQUIRED_FIELDS = ['id', 'name', 'version', 'apiVersion', 'capabilities'] - const CAPABILITIES = ['panels', 'commands', 'nodeTypes', 'generationHooks', 'providers', 'canvas', 'canvasWrite', 'nodeActions', 'gallery', 'grouplib', 'promptlib'] - const CAPABILITY_API_KEYS = { panels: 'ui', commands: 'commands', nodeTypes: 'nodes', generationHooks: 'generation', providers: 'providers', canvas: 'canvas', canvasWrite: 'canvas', nodeActions: 'nodeActions', gallery: 'gallery', grouplib: 'grouplib', promptlib: 'promptlib' } + const CAPABILITIES = ['panels', 'commands', 'nodeTypes', 'generationHooks', 'providers', 'canvas', 'canvasWrite', 'nodeActions', 'gallery', 'grouplib', 'promptlib', 'files'] + const CAPABILITY_API_KEYS = { panels: 'ui', commands: 'commands', nodeTypes: 'nodes', generationHooks: 'generation', providers: 'providers', canvas: 'canvas', canvasWrite: 'canvas', nodeActions: 'nodeActions', gallery: 'gallery', grouplib: 'grouplib', promptlib: 'promptlib' , files: 'files'} function createPluginHost(options) { const opt = options || {} diff --git a/src/storage-file.js b/src/storage-file.js index b7f1349..c8de92e 100644 --- a/src/storage-file.js +++ b/src/storage-file.js @@ -571,6 +571,91 @@ } catch (e) { return [] } } + // ---- 插件文件(v3.26.36):<资料目录>/plugin-data//files/ ---- + // 与插件 JSON 数据分离:文件放目录、JSON 只存文件名(内容哈希命名)。 + // 安全:文件名白名单(禁路径分隔/点段)、单文件 8MB、单插件总量 64MB、原子写。 + const PFILE_DIR = 'files' + const PFILE_MAX = 8 * 1024 * 1024 + const PFILE_TOTAL = 64 * 1024 * 1024 + const PFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}\.(jpg|jpeg|png|webp)$/i + function pluginFileNameOk (name) { + const P = global.IWBPluginFilesPolicy + if (P && typeof P.fileOk === 'function') return P.fileOk(name) + const s0 = String(name || '') + if (!PFILE_NAME_RE.test(s0)) return false + if (s0.indexOf('..') >= 0 || s0.indexOf('/') >= 0 || s0.indexOf(String.fromCharCode(92)) >= 0) return false + return true + } + async function pluginFilesDir (id) { + const p = await join(await pluginDataDir(), safePluginId(id), PFILE_DIR) + try { await fs().mkdir(p, { recursive: true }) } catch (e) { /* 已存在 */ } + return p + } + async function pluginFilePut (id, name, dataUrl) { + try { + if (!pluginFileNameOk(name)) return { ok: false, error: '非法文件名(只允许小写字母/数字/-/_ + jpg/png/webp)' } + const bytes = dataUrlToBytes(String(dataUrl || '')) + if (!bytes || !bytes.length) return { ok: false, error: '图片数据为空' } + const stat = await pluginFileStat(id) + const existing = stat.files.find((f) => f.name === name) + const P = global.IWBPluginFilesPolicy + const q = P ? P.quotaOk(stat.bytes, bytes.length, existing ? existing.size : 0) : null + if (q && !q.ok) { + if (q.reason === 'file-too-large') return { ok: false, error: '单张图片超过 8MB' } + if (q.reason === 'total-too-large') return { ok: false, error: '插件数据总量超过 64MB,请先清理' } + return { ok: false, error: '图片数据为空' } + } + if (!P) { + if (bytes.length > PFILE_MAX) return { ok: false, error: '单张图片超过 8MB' } + if (stat.bytes - (existing ? existing.size : 0) + bytes.length > PFILE_TOTAL) return { ok: false, error: '插件数据总量超过 64MB,请先清理' } + } + const dir0 = await pluginFilesDir(id) + const target = await join(dir0, name) + const tmp = target + '.tmp' + await fs().writeFile(tmp, bytes) + try { await fs().rename(tmp, target) } catch (e) { + try { await fs().remove(target) } catch (e2) { /* ignore */ } + await fs().rename(tmp, target) + } + return { ok: true, name: name, size: bytes.length } + } catch (e) { return { ok: false, error: String((e && e.message) || e) } } + } + async function pluginFileGet (id, name) { + try { + if (!pluginFileNameOk(name)) return { ok: false, error: '非法文件名' } + const u8 = await fs().readFile(await join(await pluginFilesDir(id), name)) + if (!u8 || !u8.length) return { ok: false, error: '文件不存在' } + return { ok: true, url: bytesToDataUrl(sniffMime(u8) || 'image/jpeg', u8), size: u8.length } + } catch (e) { return { ok: false, error: '文件不存在' } } + } + async function pluginFileList (id) { + try { + const entries = await fs().readDir(await pluginFilesDir(id)) + const out = [] + for (const e of entries) { + if (!e || e.isDirectory || !pluginFileNameOk(e.name)) continue + let size = 0 + try { const u8 = await fs().readFile(await join(await pluginFilesDir(id), e.name)); size = u8 ? u8.length : 0 } catch (err) { size = 0 } + out.push({ name: e.name, size: size }) + } + out.sort((a, b) => a.name.localeCompare(b.name)) + return out + } catch (e) { return [] } + } + async function pluginFileRemove (id, name) { + try { + if (!pluginFileNameOk(name)) return { ok: false, error: '非法文件名' } + await fs().remove(await join(await pluginFilesDir(id), name)) + return { ok: true } + } catch (e) { return { ok: false, error: '删除失败' } } + } + async function pluginFileStat (id) { + try { + const files = await pluginFileList(id) + return { ok: true, files: files, bytes: files.reduce((n, f) => n + (f.size || 0), 0), count: files.length } + } catch (e) { return { ok: false, files: [], bytes: 0, count: 0 } } + } + async function loadInto() { // data.json 不存在 ⇒ 把当前 WebView 里的数据迁过去(只做一次) const target = await join(dir, DATA_FILE) @@ -1160,12 +1245,13 @@ enabled, ready: init, flush, runtime, pickDir, switchTo, migrateTo, gcImages, rotateTrash, galleryThumb, readDisplayThumb, readDisplayThumbUrl, writeDisplayThumb, writeDisplayThumbBlob, pruneThumbs, cleanupLegacy, maintain, plugins: { manifest: pluginManifest, read: pluginRead, write: pluginWrite, remove: pluginRemove, dir: pluginDir, listLocal: pluginListLocal, listDirs: pluginListDirs, readFile: pluginReadFile, writeFile: pluginWriteFile, writeBinary: pluginWriteBinary, mkdir: pluginMkdir, removeDir: pluginRemoveDir, renameDir: pluginRenameDir, existsDir: pluginExistsDir }, pluginData: { read: pluginDataRead, write: pluginDataWrite, remove: pluginDataRemove, list: pluginDataList }, + pluginFiles: { put: pluginFilePut, get: pluginFileGet, list: pluginFileList, remove: pluginFileRemove, stat: pluginFileStat, dir: pluginFilesDir }, storage: () => storage, kv: () => kv, dir: () => dir, setDir: async (next) => { dir = String(next || ''); await flush();}, stats: () => ({ dir, keys: Object.keys(mem).length, images: Object.keys(assets).length }), - __internals: { snapshot, loadInto, sha16, extOf, dataUrlToBytes, bytesToDataUrl }, + __internals: { snapshot, loadInto, sha16, extOf, dataUrlToBytes, bytesToDataUrl, pluginFileNameOk }, } // 关窗/收托盘前强制刷盘(beforeunload 在桌面端不保证,但能救一次是一次) // 落盘兜底:桌面端点关闭是「收进托盘」,beforeunload 不一定触发; diff --git a/tests/fixtures/iwb-source-modules-order.json b/tests/fixtures/iwb-source-modules-order.json index e0225ed..17d557f 100644 --- a/tests/fixtures/iwb-source-modules-order.json +++ b/tests/fixtures/iwb-source-modules-order.json @@ -103,5 +103,6 @@ "ui-connect-menu.js", "ui-gen-config-panel.js", "canvas-webview.js", + "plugin-files-policy.js", "image-prompt-cover.js" ] diff --git a/tests/plugin-files-policy-test.js b/tests/plugin-files-policy-test.js new file mode 100644 index 0000000..1558491 --- /dev/null +++ b/tests/plugin-files-policy-test.js @@ -0,0 +1,34 @@ +// 插件文件能力的安全策略(v3.26.36):文件名白名单 + 配额。 +// 这两条是安全边界,破坏即等于允许路径穿越或塞满磁盘,必须由 CI 守住。 +const assert = require('assert') +const path = require('path') + +const sandbox = {} +new Function('window', require('fs').readFileSync(path.join(__dirname, '..', 'src', 'plugin-files-policy.js'), 'utf8'))(sandbox) +const P = sandbox.IWBPluginFilesPolicy +assert.ok(P && typeof P.fileOk === 'function', '应导出 fileOk') + +// ---- 文件名白名单 ---- +for (const ok of ['a.jpg', 'a1b2c3.jpg', 'cover_2026-11-22.png', 'x.webp', 'A.JPEG']) { + assert.strictEqual(P.fileOk(ok), true, '应允许:' + ok) +} +for (const bad of [ + '', '.jpg', 'a.gif', 'a.txt', 'a.jpg/png', '../x.jpg', 'a/b.jpg', '../../etc/passwd', + 'a' + String.fromCharCode(92) + 'b.jpg', 'a.jpg ', ' a.jpg', 'a.jpg' + String.fromCharCode(0), + 'a'.repeat(80) + '.jpg', 'x.jpg?1', 'x.jpg#a', '图片.jpg', +]) { + assert.strictEqual(P.fileOk(bad), false, '应拒绝:' + JSON.stringify(bad)) +} + +// ---- 配额 ---- +const L = P.LIMITS +assert.ok(L.FILE_MAX > 0 && L.TOTAL_MAX >= L.FILE_MAX) +assert.deepStrictEqual(P.quotaOk(0, 1024), { ok: true }) +assert.strictEqual(P.quotaOk(0, 0).ok, false, '空文件应拒绝') +assert.strictEqual(P.quotaOk(0, L.FILE_MAX + 1).reason, 'file-too-large') +assert.strictEqual(P.quotaOk(L.TOTAL_MAX - 10, 1024).reason, 'total-too-large') +// 覆盖同名文件:旧大小不重复计 +assert.strictEqual(P.quotaOk(L.TOTAL_MAX - 100, 1024, 4096).ok, true) +assert.strictEqual(P.quotaOk(L.TOTAL_MAX - 100, 1024, 0).ok, false) + +console.log('plugin files policy checks passed(白名单/路径穿越/配额/覆盖计费)') diff --git a/tests/plugin-host-test.js b/tests/plugin-host-test.js index 7734425..6de3e4d 100644 --- a/tests/plugin-host-test.js +++ b/tests/plugin-host-test.js @@ -13,7 +13,7 @@ vm.runInNewContext(source, sandbox) const host0 = sandbox.IWBPluginHost assert.ok(Number.isInteger(host0.apiVersion) && host0.apiVersion >= 1, 'apiVersion 必须是正整数') assert.ok(Array.isArray(host0.capabilities) && host0.capabilities.length >= 7, '能力清单应非空') -assert.strictEqual(host0.capabilities.slice().sort().join(','), 'canvas,canvasWrite,commands,gallery,generationHooks,grouplib,nodeActions,nodeTypes,panels,promptlib,providers') +assert.strictEqual(host0.capabilities.slice().sort().join(','), 'canvas,canvasWrite,commands,files,gallery,generationHooks,grouplib,nodeActions,nodeTypes,panels,promptlib,providers') const manifest = (over) => Object.assign({ id: 'demo-plugin', name: 'Demo', version: '1.0.0', apiVersion: 1, capabilities: [] }, over) const stateOf = (ids) => {