diff --git a/app.js b/app.js index 0ee0bfe..7790be4 100644 --- a/app.js +++ b/app.js @@ -8458,156 +8458,40 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) => // 插件自我注册。同源脚本本就被 CSP script-src 'self' 允许 ⇒ 不放宽 CSP、不重编译主包。 // 按需下载:启动只下载「已启用」的远程插件;未启用的记为 idle、不下载,等用户在插件管理里勾选时再加载。 // 单条远程插件的下载+激活(启动批量加载与按需加载共用):注入脚本(SRI 强制校验)→ 自我注册 → 持久化开关已开则激活。 - async function wLoadPluginEntry(record) { - record.status = 'loading' - const integrity = record.integrity - try { - await new Promise((resolve, reject) => { - const script = document.createElement('script') - script.src = '/plugins/' + record.file - script.async = false - if (integrity) { script.integrity = integrity; script.crossOrigin = 'anonymous' } - script.onload = () => resolve() - script.onerror = () => reject(new Error(integrity ? '脚本完整性校验失败(integrity 不符或加载失败)' : '脚本加载失败')) - document.head.appendChild(script) - }) - const registered = PluginHost && typeof PluginHost.list === 'function' && PluginHost.list().some((p) => p.id === record.id) - record.status = registered ? 'loaded' : 'not-registered' - if (registered && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(record.id)) PluginHost.setEnabled(record.id, true) - return record.status === 'loaded' - } catch (err) { - record.status = 'error' - record.error = String((err && err.message) || err) - return false - } + // 加载实现已抽到 src/runtime-plugin-loader.js(app.js 只做装配) + function wPluginLoader () { + return (typeof window !== 'undefined') ? window.IWBRuntimePluginLoader : null } - // 外部插件(P1):代码在 <资料目录>/plugins/ 下,不经 HTTP。 - // 读文本 → 用 WebCrypto 校验清单里的 sha256 → 通过后才用 blob URL 注入(CSP 已放行 blob:)。 - function wPluginSource() { - const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null - return (F && F.plugins && typeof F.plugins.read === 'function') ? F.plugins : null + function wPluginSource () { + const L = wPluginLoader() + return (L && typeof L.source === 'function') ? L.source() : null } - async function wVerifyPluginCode(code, integrity) { - if (!integrity) return false - const expect = String(integrity).replace(/^sha256-/, '') - const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(code)) - let bin = '' - const u8 = new Uint8Array(buf) - for (let i = 0; i < u8.length; i++) bin += String.fromCharCode(u8[i]) - return btoa(bin) === expect + // 市场实现已抽到 src/runtime-plugin-market.js + function wMarketMod () { + return (typeof window !== 'undefined') ? window.IWBRuntimePluginMarket : null } - async function wLoadExternalPluginEntry(record) { - record.status = 'loading' - const src = wPluginSource() - if (!src) { record.status = 'error'; record.error = '外部插件不可用'; return false } - try { - const code = await src.read(record.file) - if (record.integrity) { - const okHash = await wVerifyPluginCode(code, record.integrity) - if (!okHash) throw new Error('完整性校验失败(外部插件)') - } - const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' })) - try { - await new Promise((resolve, reject) => { - const script = document.createElement('script') - script.src = url - script.async = false - script.onload = () => resolve() - script.onerror = () => reject(new Error('外部插件脚本执行失败')) - document.head.appendChild(script) - }) - } finally { setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000) } - const registered = PluginHost && typeof PluginHost.list === 'function' && PluginHost.list().some((p) => p.id === record.id) - record.status = registered ? 'loaded' : 'not-registered' - if (registered && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(record.id)) PluginHost.setEnabled(record.id, true) - return record.status === 'loaded' - } catch (err) { - record.status = 'error' - record.error = String((err && err.message) || err) - return false - } + async function wMarketList () { const M = wMarketMod(); return M ? M.list() : [] } + async function wMarketInstalled () { const M = wMarketMod(); return M ? M.installed() : [] } + async function wMarketInstall (id) { const M = wMarketMod(); return M ? M.install(id) : { ok: false, error: '市场模块未就绪' } } + async function wMarketUninstall (id) { const M = wMarketMod(); return M ? M.uninstall(id) : { ok: false, error: '市场模块未就绪' } } + async function wVerifyPluginCode (code, integrity) { + const L = wPluginLoader() + return (L && typeof L.verifyCode === 'function') ? L.verifyCode(code, integrity) : false } - - // ---- 插件市场(P2):静态索引 market.maqiart.eu.org/index.json → 下载 → sha256 校验 → 写入 plugins/ ---- - const W_MARKET_URL = 'https://market.maqiart.eu.org/index.json' - // 桌面端优先用 Tauri 的原生 HTTP(Rust 侧):WKWebView 在代理/fake-IP 环境下直连会 Load failed - function wMarketFetch(url) { - const T = (typeof window !== 'undefined' && window.__TAURI__ && window.__TAURI__.http) ? window.__TAURI__.http : null - if (T && typeof T.fetch === 'function') return T.fetch(url) - return fetch(url, { cache: 'no-store' }) + async function wLoadPluginEntry (record) { + const L = wPluginLoader() + if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false } + return L.loadBuiltin(record) } - async function wMarketList() { - const resp = await wMarketFetch(W_MARKET_URL) - if (!resp.ok) throw new Error('市场不可达:HTTP ' + resp.status) - const j = await resp.json() - return Array.isArray(j && j.plugins) ? j.plugins : [] + async function wLoadExternalPluginEntry (record) { + const L = wPluginLoader() + if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false } + return L.loadExternal(record) } - async function wMarketInstalled() { - const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null - if (!F || !F.plugins) return [] - return await F.plugins.manifest() - } - async function wMarketInstall(id) { - try { - const list = await wMarketList() - const item = list.find((p) => p && p.id === id) - if (!item) return { ok: false, error: '市场里没有这个插件' } - const base = W_MARKET_URL.replace(/index\.json$/, '') - const resp = await wMarketFetch(base + item.file) - if (!resp.ok) throw new Error('下载失败:HTTP ' + resp.status) - const text = await resp.text() - const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)) - const hex = Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, '0')).join('') - if (item.sha256 && hex !== item.sha256) return { ok: false, error: '校验失败(sha256 不符)' } - const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null - if (!F || !F.plugins) return { ok: false, error: '外部插件目录不可用' } - const file = String(item.file).split('/').pop() - await F.plugins.write(file, text) - const cur = await F.plugins.manifest() - const next = cur.filter((p) => p && p.id !== id).concat([{ id: id, file: file, version: item.version, integrity: item.integrity }]) - await F.plugins.write('index.json', JSON.stringify(next, null, 2) + '\n') - return { ok: true, restart: true, file: file } - } catch (e) { return { ok: false, error: String((e && e.message) || e) } } - } - async function wMarketUninstall(id) { - try { - const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null - if (!F || !F.plugins) return { ok: false, error: '外部插件目录不可用' } - const cur = await F.plugins.manifest() - const hit = cur.find((p) => p && p.id === id) - const next = cur.filter((p) => p && p.id !== id) - await F.plugins.write('index.json', JSON.stringify(next, null, 2) + '\n') - if (hit && hit.file) await F.plugins.remove(hit.file) - return { ok: true, restart: true } - } catch (e) { return { ok: false, error: String((e && e.message) || e) } } - } - - // 开发者模式插件(plugins/local//plugin.js):未签名,仅在设置里打开开关时加载 - async function wLoadLocalPluginEntry(record) { - record.status = 'loading' - try { - const code = String(record.code || '') - if (!code) throw new Error('插件源码为空') - const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' })) - try { - await new Promise((resolve, reject) => { - const script = document.createElement('script') - script.src = url - script.async = false - script.onload = () => resolve() - script.onerror = () => reject(new Error('本地插件脚本执行失败')) - document.head.appendChild(script) - }) - } finally { setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000) } - const registered = PluginHost && typeof PluginHost.list === 'function' && PluginHost.list().some((p) => p.id === record.id) - record.status = registered ? 'loaded' : 'not-registered' - if (registered && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(record.id)) PluginHost.setEnabled(record.id, true) - return record.status === 'loaded' - } catch (err) { - record.status = 'error' - record.error = String((err && err.message) || err) - return false - } + async function wLoadLocalPluginEntry (record) { + const L = wPluginLoader() + if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false } + return L.loadLocal(record) } // 按需加载(插件管理里勾选 idle 行):下载脚本 → 注册 → 显式启用;失败时返回错误供 UI 回滚勾选并提示。 diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index 85a47d2..57ae9c4 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`(现 **81** 个模块 / 14,607 行,`sourceModules` 81 项;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`(现 **84** 个模块 / 14,607 行,`sourceModules` 84 项;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` 不引用模块全局)。**81 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 + - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**84 个模块中 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 耦合面(**71** 项)与 `sourceModules` 顺序(**81** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 + - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**73** 项)与 `sourceModules` 顺序(**84** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 ## 12. 易踩的坑 @@ -254,7 +254,7 @@ **信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。 -**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**71** 项)与 `sourceModules` 顺序(**81** 项);新增模块、新增耦合、新增 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 耦合面」(**73** 项)与 `sourceModules` 顺序(**84** 项);新增模块、新增耦合、新增 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/scripts/build.js b/scripts/build.js index 844fa9f..53db50c 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -97,6 +97,9 @@ const sourceModules = [ 'workspace-list.js', 'workspace-purge.js', 'generation-provider-ping.js', + 'runtime-plugin-loader.js', + 'runtime-plugin-market.js', + 'runtime-plugin-backup.js', 'ui-canvas-view.js', 'ui-confirm.js', 'ui-settings-sections.js', diff --git a/src/runtime-plugin-backup.js b/src/runtime-plugin-backup.js new file mode 100644 index 0000000..40b93cc --- /dev/null +++ b/src/runtime-plugin-backup.js @@ -0,0 +1,52 @@ +/* runtime-plugin-backup.js —— 插件进出备份 + * + * 备份里带上插件清单与源码(体积很小),换机器恢复后不必重装。 + * collect() → [{ id, version, file, integrity, code }] + * restore(v) → 写回 <资料目录>/plugins/ 并合并清单(备份里没有的插件保留) + */ +;(function (global) { + 'use strict' + + function store () { + const F = global.IWBStorageFile || null + return (F && F.plugins) ? F.plugins : null + } + + async function collect () { + const s = store() + if (!s) return [] + let list = [] + try { list = await s.manifest() } catch (e) { return [] } + const out = [] + for (const e of (Array.isArray(list) ? list : [])) { + if (!e || !e.id || !e.file) continue + try { + const text = await s.read(e.file) + out.push({ id: e.id, version: e.version || '', file: e.file, integrity: e.integrity || '', code: String(text || '') }) + } catch (err) { /* 单个插件读失败不影响其它 */ } + } + return out + } + + async function restore (list) { + const s = store() + if (!s || !Array.isArray(list) || !list.length) return 0 + let cur = [] + try { cur = await s.manifest() } catch (e) { cur = [] } + const byId = new Map((Array.isArray(cur) ? cur : []).map(function (e) { return [String(e && e.id), e] })) + let n = 0 + for (const p of list) { + if (!p || !p.id || !p.file) continue + if (!/^[A-Za-z0-9._-]+$/.test(String(p.file))) continue + try { + await s.write(String(p.file), String(p.code || '')) + byId.set(String(p.id), { id: String(p.id), file: String(p.file), version: String(p.version || ''), integrity: String(p.integrity || '') }) + n++ + } catch (err) { /* 单个失败忽略 */ } + } + try { await s.write('index.json', JSON.stringify(Array.from(byId.values()))) } catch (e) { /* ignore */ } + return n + } + + global.IWBRuntimePluginBackup = { collect: collect, restore: restore } +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/runtime-plugin-loader.js b/src/runtime-plugin-loader.js new file mode 100644 index 0000000..08a478e --- /dev/null +++ b/src/runtime-plugin-loader.js @@ -0,0 +1,120 @@ +/* runtime-plugin-loader.js —— 插件脚本加载(内置 / 外部 / 本地开发) + * + * 从 app.js 抽出来:app.js 只做装配,加载细节在这里。 + * 三个入口都返回 boolean,并把状态写回传进来的 record(status/error),供插件面板展示。 + * · loadBuiltin :同源 /plugins/,走 SRI(integrity 强制校验) + * · loadExternal :<资料目录>/plugins/,先读文本 → WebCrypto 校验 sha256 → blob 注入 + * · loadLocal :开发者模式,code 已在内存里(免签名),blob 注入 + */ +;(function (global) { + 'use strict' + + function host () { + return global.IWBPluginHost || null + } + + // 外部插件源(<资料目录>/plugins/ 的读写封装) + function source () { + const F = global.IWBStorageFile || null + return (F && F.plugins && typeof F.plugins.read === 'function') ? F.plugins : null + } + + async function verifyCode (code, integrity) { + if (!integrity) return false + const expect = String(integrity).replace(/^sha256-/, '') + const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(code)) + const u8 = new Uint8Array(buf) + let bin = '' + for (let i = 0; i < u8.length; i++) bin += String.fromCharCode(u8[i]) + return global.btoa(bin) === expect + } + + // 注入一段脚本并等它执行完(插件在加载期自我注册) + function inject (attrs) { + return new Promise(function (resolve, reject) { + const script = global.document.createElement('script') + script.src = attrs.src + script.async = false + if (attrs.integrity) { script.integrity = attrs.integrity; script.crossOrigin = 'anonymous' } + script.onload = function () { resolve() } + script.onerror = function () { reject(new Error(attrs.error || '脚本加载失败')) } + global.document.head.appendChild(script) + }) + } + + function markResult (record) { + const H = host() + const registered = !!(H && typeof H.list === 'function' && H.list().some(function (p) { return p.id === record.id })) + record.status = registered ? 'loaded' : 'not-registered' + if (registered && typeof H.isEnabled === 'function' && H.isEnabled(record.id)) H.setEnabled(record.id, true) + return record.status === 'loaded' + } + + async function loadBuiltin (record) { + record.status = 'loading' + const integrity = record.integrity + try { + await inject({ + src: '/plugins/' + record.file, + integrity: integrity, + error: integrity ? '脚本完整性校验失败(integrity 不符或加载失败)' : '脚本加载失败' + }) + return markResult(record) + } catch (err) { + record.status = 'error' + record.error = String((err && err.message) || err) + return false + } + } + + async function loadExternal (record) { + record.status = 'loading' + const src = source() + if (!src) { record.status = 'error'; record.error = '外部插件不可用'; return false } + try { + const code = await src.read(record.file) + if (record.integrity) { + const ok = await verifyCode(code, record.integrity) + if (!ok) throw new Error('完整性校验失败(外部插件)') + } + const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' })) + try { + await inject({ src: url, error: '外部插件脚本执行失败' }) + } finally { + setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000) + } + return markResult(record) + } catch (err) { + record.status = 'error' + record.error = String((err && err.message) || err) + return false + } + } + + async function loadLocal (record) { + record.status = 'loading' + try { + const code = String(record.code || '') + if (!code) throw new Error('插件源码为空') + const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' })) + try { + await inject({ src: url, error: '本地插件脚本执行失败' }) + } finally { + setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000) + } + return markResult(record) + } catch (err) { + record.status = 'error' + record.error = String((err && err.message) || err) + return false + } + } + + global.IWBRuntimePluginLoader = { + source: source, + verifyCode: verifyCode, + loadBuiltin: loadBuiltin, + loadExternal: loadExternal, + loadLocal: loadLocal + } +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/runtime-plugin-market.js b/src/runtime-plugin-market.js new file mode 100644 index 0000000..115c979 --- /dev/null +++ b/src/runtime-plugin-market.js @@ -0,0 +1,73 @@ +/* runtime-plugin-market.js —— 插件市场(下载 / 校验 / 安装 / 卸载) + * + * 索引:https://market.maqiart.eu.org/index.json,产物同域 plugin-..js + * 落点:<资料目录>/plugins/(清单 index.json + 插件文件) + * 校验:市场索引里的 sha256(hex)与下载文本比对,不符直接拒绝 + */ +;(function (global) { + 'use strict' + const MARKET_URL = 'https://market.maqiart.eu.org/index.json' + + function store () { + const F = global.IWBStorageFile || null + return (F && F.plugins) ? F.plugins : null + } + + // 桌面端优先走 Tauri 原生 HTTP(WKWebView 在代理/fake-IP 环境下 fetch 会 Load failed) + function marketFetch (url) { + const T = (global.__TAURI__ && global.__TAURI__.http) ? global.__TAURI__.http : null + if (T && typeof T.fetch === 'function') return T.fetch(url) + return global.fetch(url, { cache: 'no-store' }) + } + + async function list () { + const resp = await marketFetch(MARKET_URL) + if (!resp.ok) throw new Error('市场不可达:HTTP ' + resp.status) + const j = await resp.json() + return Array.isArray(j && j.plugins) ? j.plugins : [] + } + + async function installed () { + const s = store() + if (!s) return [] + return await s.manifest() + } + + async function install (id) { + try { + const items = await list() + const item = items.find(function (p) { return p && p.id === id }) + if (!item) return { ok: false, error: '市场里没有这个插件' } + const base = MARKET_URL.replace(/index\.json$/, '') + const resp = await marketFetch(base + item.file) + if (!resp.ok) throw new Error('下载失败:HTTP ' + resp.status) + const text = await resp.text() + const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(text)) + const hex = Array.from(new Uint8Array(buf)).map(function (b) { return b.toString(16).padStart(2, '0') }).join('') + if (item.sha256 && hex !== item.sha256) return { ok: false, error: '校验失败(sha256 不符)' } + const s = store() + if (!s) return { ok: false, error: '外部插件目录不可用' } + const file = String(item.file).split('/').pop() + await s.write(file, text) + const cur = await s.manifest() + const next = cur.filter(function (p) { return p && p.id !== id }).concat([{ id: id, file: file, version: item.version, integrity: item.integrity }]) + await s.write('index.json', JSON.stringify(next, null, 2) + '\n') + return { ok: true, restart: true, file: file } + } catch (e) { return { ok: false, error: String((e && e.message) || e) } } + } + + async function uninstall (id) { + try { + const s = store() + if (!s) return { ok: false, error: '外部插件目录不可用' } + const cur = await s.manifest() + const hit = cur.find(function (p) { return p && p.id === id }) + const next = cur.filter(function (p) { return p && p.id !== id }) + await s.write('index.json', JSON.stringify(next, null, 2) + '\n') + if (hit && hit.file) await s.remove(hit.file) + return { ok: true, restart: true } + } catch (e) { return { ok: false, error: String((e && e.message) || e) } } + } + + global.IWBRuntimePluginMarket = { list: list, installed: installed, install: install, uninstall: uninstall } +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/ui-backup-modal.js b/src/ui-backup-modal.js index bd2a024..7fbdadc 100644 --- a/src/ui-backup-modal.js +++ b/src/ui-backup-modal.js @@ -169,6 +169,8 @@ function BackupModal(props) { items.outputs = ((r && r.files) || []).map((f) => { const o = Object.assign({}, f); delete o.data; return o }) })) await Promise.all(jobs) + // 插件(清单 + 源码)随备份走:换机器恢复后不用重装 + try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.collect) { const ps = await pb.collect(); if (ps && ps.length) items.plugins = ps } } catch (e) { /* 插件快照失败不影响主备份 */ } // 收集图片(画布引用大图 + 勾选的图库缩略图/原图)并读取数据 const refMeta = await collectBackupImages() const galleryMeta = (bk.outputs && items.outputs) ? (await collectBackupOutputImages(items.outputs)) : [] @@ -364,6 +366,9 @@ function BackupModal(props) { jobs.push(api('workspaces', { workspaces: mergeById((cur && cur.workspaces) || [], items.workspaces.workspaces || []), activeId: (cur && cur.activeId) || '' })) } else jobs.push(api('workspaces', { workspaces: items.workspaces.workspaces || [], activeId: items.workspaces.activeId || '' })) } + if (items.plugins && items.plugins.length) { + try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.restore) await pb.restore(items.plugins) } catch (e) { /* 插件还原失败不阻塞其它项 */ } + } if (restoreSel.outputs && items.outputs) { if (restoreMerge) { const cur = await api('outputs').catch(() => ({ files: [] })) diff --git a/tests/fixtures/iwb-app-global-reads.json b/tests/fixtures/iwb-app-global-reads.json index 2f5d120..6ca5f74 100644 --- a/tests/fixtures/iwb-app-global-reads.json +++ b/tests/fixtures/iwb-app-global-reads.json @@ -35,6 +35,8 @@ "IWBRuntimeLifecycle", "IWBRuntimeLifecycleFactory", "IWBRuntimeMetrics", + "IWBRuntimePluginLoader", + "IWBRuntimePluginMarket", "IWBRuntimeRecord", "IWBRuntimeRecovery", "IWBRuntimeRunContext", diff --git a/tests/fixtures/iwb-source-modules-order.json b/tests/fixtures/iwb-source-modules-order.json index fa068a3..60ad834 100644 --- a/tests/fixtures/iwb-source-modules-order.json +++ b/tests/fixtures/iwb-source-modules-order.json @@ -69,6 +69,9 @@ "workspace-list.js", "workspace-purge.js", "generation-provider-ping.js", + "runtime-plugin-loader.js", + "runtime-plugin-market.js", + "runtime-plugin-backup.js", "ui-canvas-view.js", "ui-confirm.js", "ui-settings-sections.js", diff --git a/tests/plugin-integrity-test.js b/tests/plugin-integrity-test.js index af1fe38..992d900 100644 --- a/tests/plugin-integrity-test.js +++ b/tests/plugin-integrity-test.js @@ -86,7 +86,9 @@ const root = path.resolve(__dirname, '..') // app.js loader:integrity 存在则交给浏览器强制校验;格式不合法即拒;**缺失即拒(fail-closed)** const appJs = fs.readFileSync(path.join(root, 'app.js'), 'utf8') - assert.ok(/script\.integrity = integrity; script\.crossOrigin = 'anonymous'/.test(appJs), 'loader 应把 integrity 交给浏览器强制校验') + // 2026-11-17:加载器已抽到 src/runtime-plugin-loader.js,断言改读该模块(不是删断言) + const loaderSrc = require('fs').readFileSync(require('path').resolve(__dirname, '..', 'src', 'runtime-plugin-loader.js'), 'utf8') + assert.ok(/script\.integrity = attrs\.integrity; script\.crossOrigin = 'anonymous'/.test(loaderSrc), 'loader 应把 integrity 交给浏览器强制校验') assert.ok(/record\.status = 'bad-entry'; record\.error = 'integrity 格式不合法'/.test(appJs), 'integrity 格式不合法应拒绝加载') // 2026-11-17:本地开发插件(source=local)免 integrity,其余(市场/内置)仍然 fail-closed assert.ok(/if \(!integrity && !isLocalEntry\) \{ record\.status = 'bad-entry'; record\.error = 'integrity 缺失(拒绝加载)'; continue \}/.test(appJs), '缺失 integrity 应拒绝加载(fail-closed,本地开发插件除外)') diff --git a/types/iwb-globals.d.ts b/types/iwb-globals.d.ts index 7721398..f57b535 100644 --- a/types/iwb-globals.d.ts +++ b/types/iwb-globals.d.ts @@ -25,6 +25,10 @@ interface Window { __TAURI__?: any __IWB_UPDATE__?: any IWBUIConfirm?: any + IWBPluginBackup?: any + IWBRuntimePluginLoader?: any + IWBRuntimePluginMarket?: any + IWBRuntimePluginBackup?: any IWBDesktop?: any IWBStorageFallbackIndexedDb?: any // 画布 / 工作台