feat(market): M3 zip 整包安装 + 逐文件 sha256 + 原子换位 v3.25.46

- gen-market 产出 <id>-<version>.zip(STORE)+ bundle/bundleSize/bundleSha256/files[];保留单文件兼容
- 安装器:下载→整包校验→解包→逐文件 sha256→路径白名单→体积/数量上限→.new→.old→rename→清理(失败回滚)
- storage-file 增 renameDir/existsDir;卸载目录插件保留 plugin-data
- 新增 scripts/plugin-zip.js 与 plugin-bundle / plugin-install 两组测试(含覆盖升级与拒绝路径)
This commit is contained in:
qiqi committed 2026-11-20 10:20:09 +08:00
1 parent 56e64decd3
commit e08fdb6271
8 files changed
+532 -45

No files matched your search

+13
View File
@@ -14,6 +14,19 @@
> 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。
> 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。
## v3.25.46(2026-11-20)插件市场 M3:zip 整包 + 逐文件 sha256 + 桌面解包安装
- 市场产物升级:每个插件同时产出 `plugins/<id>-<version>.zip`(STORE 不压缩),条目新增 `bundle / bundleSize / bundleSha256 / files[]`;
旧的单文件 `file + integrity` 保留一个版本,老客户端照常可装。
- 桌面安装器改走 zip:下载(30s)→ 整包 sha256 → 解包(复用 `src/storage-zip.js`)→ **逐文件 sha256** → 路径白名单
(只允许 `manifest.json / main.js / styles.css / assets/*`)→ 体积/数量上限(≤200 文件、单文件 ≤2MB、总 ≤10MB)→
`.new` 落地 → 旧目录改名 `.old` → rename 就位 → 删 `.old`(失败回滚,Windows 覆盖不再报错)。
- 新增 `plugins.renameDir / existsDir`;卸载目录插件走 `removeDir`,**插件数据(plugin-data)默认保留**。
- 新增 `scripts/plugin-zip.js`(Node STORE 写入器)与两组测试:
`tests/plugin-bundle-test.js`(写入↔解包往返、路径白名单、上限常量)、
`tests/plugin-install-test.js`(首装 / 覆盖升级 / 逐文件校验拒绝 / manifest id 校验 / 卸载)。
- 关键取舍:包统一 STORE —— 客户端 DEFLATE 依赖 `DecompressionStream`,旧 macOS(<13)WKWebView 没有该 API。
## v3.25.45(2026-11-20)纠正:插件只能来自市场(桌面包不内置插件)
- 事实纠正:`beforeBuildCommand` 跑 `scripts/strip-plugins.js`,打包前把 `dist/plugins` 移出 —— **桌面包里没有任何内置插件**;
+1 -1
View File
@@ -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/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/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/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-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/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-test.js",
"test:unit": "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/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/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-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/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-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",
+95 -23
View File
@@ -1,36 +1,108 @@
#!/usr/bin/env node
'use strict'
// 生成插件市场索引:plugins/index.json + plugins/meta.json → market/index.json + market/plugins/*
// 产物用于 market.maqiart.eu.org(纯静态)。
// 生成插件市场索引(M3):plugins/index.json + plugins/meta.json(+ 目录插件)→ market/
//
// 产物(纯静态,供 market.maqiart.eu.org 与桌面端安装器共用):
// market/index.json 市场条目:bundle(zip) + files[逐文件 sha256] + 兼容字段 file
// market/plugins/<id>-<version>.zip 目录插件包:manifest.json + main.js [+ styles.css / assets]
// market/plugins/plugin-<id>.<hash>.js 单文件产物(旧客户端仍可安装,保持向后兼容)
//
// 包里统一用 STORE(不压缩):客户端 src/storage-zip.js 对 DEFLATE 依赖 DecompressionStream,
// 旧 macOS 的 WKWebView 没有该 API;插件包只有几十 KB,不压缩没有实际损失。
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const { zipStore } = require('./plugin-zip')
const root = path.resolve(__dirname, '..')
const man = JSON.parse(fs.readFileSync(path.join(root, 'plugins', 'index.json'), 'utf8'))
const meta = JSON.parse(fs.readFileSync(path.join(root, 'plugins', 'meta.json'), 'utf8'))
const out = path.join(root, 'market')
fs.mkdirSync(path.join(out, 'plugins'), { recursive: true })
const sha = (buf) => crypto.createHash('sha256').update(buf)
const plugins = []
let skipped = 0
for (const e of man) {
// 目录插件(v3.25.41):市场打包(zip)在 M3 落地,这一版先跳过,避免生成缺 bundle 的条目
if (e.dir) { skipped++; console.warn('跳过目录插件(待 M3 打包):' + e.id); continue }
const src = path.join(root, 'plugins', 'runtime', e.file)
if (!fs.existsSync(src)) { console.warn('缺少产物:' + e.file); continue }
const buf = fs.readFileSync(src)
fs.writeFileSync(path.join(out, 'plugins', e.file), buf)
const m = meta[e.id] || {}
plugins.push({
id: e.id, name: m.name || e.id, desc: m.desc || '', author: m.author || 'official', icon: m.icon || '', color: m.color || '', tags: Array.isArray(m.tags) ? m.tags : [],
version: e.version, apiVersion: 1,
file: 'plugins/' + e.file,
size: buf.length,
sha256: sha(buf).digest('hex'),
integrity: 'sha256-' + sha(buf).digest('base64'),
})
const shaHex = (buf) => sha(buf).digest('hex')
function readFolderFiles (id) {
// 目录插件:manifest.json + main.js + 可选 styles.css + assets/**(限两级)
const dir = path.join(root, 'plugins', id)
const files = []
const manifestPath = path.join(dir, 'manifest.json')
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
files.push({ name: 'manifest.json', data: fs.readFileSync(manifestPath) })
const main = String(manifest.main || 'main.js')
files.push({ name: main, data: fs.readFileSync(path.join(dir, main)) })
if (manifest.style && fs.existsSync(path.join(dir, manifest.style))) files.push({ name: String(manifest.style), data: fs.readFileSync(path.join(dir, String(manifest.style))) })
const assetsDir = path.join(dir, 'assets')
if (fs.existsSync(assetsDir)) {
for (const name of fs.readdirSync(assetsDir)) {
const abs = path.join(assetsDir, name)
if (fs.statSync(abs).isFile()) files.push({ name: 'assets/' + name, data: fs.readFileSync(abs) })
}
}
return { files, manifest }
}
const index = { version: 1, updatedAt: new Date().toISOString(), plugins: plugins }
const plugins = []
let zipped = 0
for (const e of man) {
const m = meta[e.id] || {}
const base = {
id: e.id, name: m.name || e.id, desc: m.desc || '', author: m.author || 'official',
icon: m.icon || '', color: m.color || '', tags: Array.isArray(m.tags) ? m.tags : [],
version: e.version, apiVersion: 1,
}
// ---- 目录形态:打包 manifest + main(+style/assets) ----
let files = null
if (e.dir) {
const got = readFolderFiles(e.dir)
files = got.files
} else {
const src = path.join(root, 'plugins', 'runtime', e.file)
if (!fs.existsSync(src)) { console.warn('缺少产物:' + e.file); continue }
const js = fs.readFileSync(src)
// 单文件插件也打成目录包:manifest.json 由市场索引生成,main.js 就是原产物
// manifest 里带 files(main.js 的 sha256):手工把 zip 解到 <plugins>/<id>/ 时,
// 加载器扫描目录也能校验入口文件(manifest 自身不参与,避免自引用)。
const manifestJson = {
id: e.id, name: base.name, version: e.version, apiVersion: 1, main: 'main.js',
description: base.desc, author: base.author, icon: base.icon, tags: base.tags,
files: { 'main.js': shaHex(js) },
}
files = [
{ name: 'manifest.json', data: Buffer.from(JSON.stringify(manifestJson, null, 2) + '\n', 'utf8') },
{ name: 'main.js', data: js },
]
}
const fileList = files.map((f) => ({ path: f.name, sha256: shaHex(f.data), size: f.data.length }))
const zip = zipStore(files)
const zipName = e.id + '-' + e.version + '.zip'
fs.writeFileSync(path.join(out, 'plugins', zipName), zip)
zipped++
const item = Object.assign({}, base, {
bundle: 'plugins/' + zipName,
bundleSize: zip.length,
bundleSha256: shaHex(zip),
files: fileList,
})
// 兼容:单文件插件继续提供裸 .js(旧客户端 install 只认 file/integrity)
if (!e.dir) {
const src = path.join(root, 'plugins', 'runtime', e.file)
const buf = fs.readFileSync(src)
fs.writeFileSync(path.join(out, 'plugins', e.file), buf)
item.file = 'plugins/' + e.file
item.size = buf.length
item.sha256 = shaHex(buf)
item.integrity = 'sha256-' + sha(buf).digest('base64')
}
plugins.push(item)
}
const index = { version: 2, updatedAt: new Date().toISOString(), plugins: plugins }
fs.writeFileSync(path.join(out, 'index.json'), JSON.stringify(index, null, 2) + '\n')
console.log('market/index.json:' + plugins.length + ' 个插件' + (skipped ? '(跳过 ' + skipped + ' 个目录插件)' : ''))
for (const p of plugins) console.log(' ' + p.id.padEnd(16) + p.version.padEnd(8) + (p.size + ' B'))
console.log('market/index.json:' + plugins.length + ' 个插件 / ' + zipped + ' 个 zip 包')
for (const p of plugins) console.log(' ' + p.id.padEnd(16) + String(p.version).padEnd(8) + (p.bundleSize + ' B zip'))
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env node
'use strict'
// 插件包 ZIP 写入器(M3,2026-11-20)
//
// 为什么自己写:插件包很小(几十 KB),只需要 STORE(不压缩);
// 而客户端解包走 src/storage-zip.js —— 它对 DEFLATE 依赖 DecompressionStream,
// 旧 macOS(<13)的 WKWebView 没有该 API。用 STORE 可以彻底绕开这个兼容坑。
//
// 输出:标准 ZIP(local header + central directory + EOCD),UTF-8 文件名(flag 0x0800)。
const CRC_TABLE = (() => {
const t = new Uint32Array(256)
for (let i = 0; i < 256; i++) {
let c = i
for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)
t[i] = c >>> 0
}
return t
})()
function crc32 (buf) {
let c = 0xFFFFFFFF
for (let i = 0; i < buf.length; i++) c = (CRC_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >>> 8)) >>> 0
return (c ^ 0xFFFFFFFF) >>> 0
}
// files: [{ name: string, data: Buffer|string }]
function zipStore (files) {
const locals = []
const centrals = []
let offset = 0
const DOS_TIME = 0
const DOS_DATE = 0x21 // 1980-01-01
for (const f of files || []) {
const name = String(f.name || '')
if (!name || name.indexOf('..') >= 0 || name.charAt(0) === '/') throw new Error('非法文件名:' + name)
const nameBuf = Buffer.from(name, 'utf8')
const data = Buffer.isBuffer(f.data) ? f.data : Buffer.from(String(f.data == null ? '' : f.data), 'utf8')
const crc = crc32(data)
const local = Buffer.alloc(30)
local.writeUInt32LE(0x04034b50, 0)
local.writeUInt16LE(20, 4) // version needed
local.writeUInt16LE(0x0800, 6) // UTF-8 文件名
local.writeUInt16LE(0, 8) // method = STORE
local.writeUInt16LE(DOS_TIME, 10)
local.writeUInt16LE(DOS_DATE, 12)
local.writeUInt32LE(crc, 14)
local.writeUInt32LE(data.length, 18)
local.writeUInt32LE(data.length, 22)
local.writeUInt16LE(nameBuf.length, 26)
local.writeUInt16LE(0, 28)
locals.push(local, nameBuf, data)
const cd = Buffer.alloc(46)
cd.writeUInt32LE(0x02014b50, 0)
cd.writeUInt16LE(20, 4) // made by
cd.writeUInt16LE(20, 6) // version needed
cd.writeUInt16LE(0x0800, 8)
cd.writeUInt16LE(0, 10) // method
cd.writeUInt16LE(DOS_TIME, 12)
cd.writeUInt16LE(DOS_DATE, 14)
cd.writeUInt32LE(crc, 16)
cd.writeUInt32LE(data.length, 20)
cd.writeUInt32LE(data.length, 24)
cd.writeUInt16LE(nameBuf.length, 28)
cd.writeUInt16LE(0, 30) // extra len
cd.writeUInt16LE(0, 32) // comment len
cd.writeUInt16LE(0, 34) // disk start
cd.writeUInt16LE(0, 36) // internal attrs
cd.writeUInt32LE(0, 38) // external attrs
cd.writeUInt32LE(offset, 42) // local header offset
centrals.push(cd, nameBuf)
offset += local.length + nameBuf.length + data.length
}
const cdBuf = Buffer.concat(centrals)
const end = Buffer.alloc(22)
end.writeUInt32LE(0x06054b50, 0)
end.writeUInt16LE(0, 4)
end.writeUInt16LE(0, 6)
end.writeUInt16LE(files.length, 8)
end.writeUInt16LE(files.length, 10)
end.writeUInt32LE(cdBuf.length, 12)
end.writeUInt32LE(offset, 16)
end.writeUInt16LE(0, 20)
return Buffer.concat(locals.concat([cdBuf, end]))
}
module.exports = { zipStore, crc32 }
+129 -20
View File
@@ -1,18 +1,40 @@
/* runtime-plugin-market.js —— 插件市场(下载 / 校验 / 安装 / 卸载)
*
* 索引:https://market.maqiart.eu.org/index.json,产物同域 plugin-<id>.<hash>.js
* 落点:<资料目录>/plugins/(清单 index.json + 插件文件)
* 校验:市场索引里的 sha256(hex)与下载文本比对,不符直接拒绝
* v3.25.46(M3):支持**目录插件 zip 整包**安装
* 索引:https://market.maqiart.eu.org/index.json
* 包: plugins/<id>-<version>.zip(STORE 不压缩;manifest.json + main.js [+ styles.css / assets])
* 落点:<资料目录>/plugins/<id>/(+ index.json 目录条目)
* 校验:zip 整体 sha256(bundleSha256)+ **逐文件 sha256**(files[])+ 路径白名单 + 体积/数量上限
*
* 兼容:没有 bundle 的旧条目仍走「单文件」安装(写到 <plugins>/plugin-<id>.<hash>.js)。
* 原子性:先解到 <id>.new → 旧目录改名 <id>.old → rename 就位 → 删 .old;失败回滚。
*/
;(function (global) {
'use strict'
const MARKET_URL = 'https://market.maqiart.eu.org/index.json'
const MAX_FILES = 200
const MAX_FILE_BYTES = 2 * 1024 * 1024
const MAX_TOTAL_BYTES = 10 * 1024 * 1024
// 只允许这些路径:清单/入口/样式 + 一级 assets(防止包里塞脚本目录或路径穿越)
const ENTRY_RE = /^(manifest\.json|main\.js|styles\.css|assets\/[A-Za-z0-9._-]{1,80})$/
function store () {
const F = global.IWBStorageFile || null
return (F && F.plugins) ? F.plugins : null
}
function safeEntryName (name) {
const s = String(name || '')
if (!s || s.length > 120) return false
if (s.charAt(0) === '/' || s.indexOf('\\') >= 0 || s.indexOf('..') >= 0) return false
return ENTRY_RE.test(s)
}
async function sha256Hex (bytes) {
const buf = await global.crypto.subtle.digest('SHA-256', bytes)
return Array.from(new Uint8Array(buf)).map(function (b) { return b.toString(16).padStart(2, '0') }).join('')
}
// 桌面端优先走 Tauri 原生 HTTP(WKWebView 在代理/fake-IP 环境下 fetch 会 Load failed);
// 原生失败时再退回 WebView fetch(有些 Windows 公司网络/代理只放行后者),两个错误都带上,便于定位。
async function marketFetch (url) {
@@ -62,26 +84,106 @@
return await s.manifest()
}
async function writeIndex (s, id, entry) {
const cur = await s.manifest()
const next = cur.filter(function (p) { return p && p.id !== id }).concat([entry])
await s.write('index.json', JSON.stringify(next, null, 2) + '\n')
return next
}
// 目录插件:下载 zip → 整体/逐文件校验 → .new → 换位 → 写索引
async function installBundle (item, s) {
const zipMod = global.IWBStorageZip
if (!zipMod || typeof zipMod.wZipParseEntries !== 'function' || typeof zipMod.wZipReadEntry !== 'function') {
throw new Error('解包模块不可用(客户端版本过旧)')
}
const base = MARKET_URL.replace(/index\.json$/, '')
const resp = await marketFetch(base + item.bundle)
if (!resp.ok) throw new Error('下载失败:HTTP ' + resp.status)
const ab = await resp.arrayBuffer()
if (item.bundleSha256 && (await sha256Hex(new Uint8Array(ab))) !== String(item.bundleSha256).toLowerCase()) {
throw new Error('安装包校验失败(sha256 不符)')
}
let zip
try { zip = zipMod.wZipParseEntries(ab) } catch (e) { throw new Error('安装包不是有效的 ZIP:' + ((e && e.message) || e)) }
const entries = (zip.entries || []).filter(function (e) { return e && e.name && e.name.charAt(e.name.length - 1) !== '/' })
if (!entries.length) throw new Error('安装包是空的')
if (entries.length > MAX_FILES) throw new Error('安装包文件过多(>' + MAX_FILES + ')')
const expectByPath = {}
for (const f of (item.files || [])) if (f && f.path) expectByPath[String(f.path)] = String(f.sha256 || '').toLowerCase()
let total = 0
const files = []
for (const ent of entries) {
if (!safeEntryName(ent.name)) throw new Error('安装包含非法路径:' + ent.name)
if (Number(ent.rawSize) > MAX_FILE_BYTES) throw new Error('安装包单文件过大:' + ent.name)
total += Number(ent.rawSize) || 0
if (total > MAX_TOTAL_BYTES) throw new Error('安装包解压后过大(>' + Math.round(MAX_TOTAL_BYTES / 1048576) + 'MB)')
const bytes = await zipMod.wZipReadEntry(zip, ent)
const hex = await sha256Hex(bytes)
const expect = expectByPath[ent.name]
if (expect && hex !== expect) throw new Error('校验失败:' + ent.name)
files.push({ name: ent.name, bytes: bytes, sha256: hex })
}
const manFile = files.filter(function (f) { return f.name === 'manifest.json' })[0]
if (!manFile) throw new Error('安装包缺少 manifest.json')
let man = null
try { man = JSON.parse(new global.TextDecoder().decode(manFile.bytes)) } catch (e) { throw new Error('manifest.json 解析失败') }
if (!man || String(man.id || '') !== String(item.id)) throw new Error('manifest 的 id 与市场条目不一致')
const mainName = String(man.main || 'main.js')
if (!files.some(function (f) { return f.name === mainName })) throw new Error('安装包缺少入口文件 ' + mainName)
const id = String(item.id)
const tmp = id + '.new'
const bak = id + '.old'
try { await s.removeDir(tmp) } catch (e) { /* 不存在 */ }
await s.mkdir(tmp)
for (const f of files) await s.writeBinary(tmp + '/' + f.name, f.bytes)
try { await s.removeDir(bak) } catch (e) { /* 不存在 */ }
let hadOld = false
try {
if (await s.existsDir(id)) { await s.renameDir(id, bak); hadOld = true }
} catch (e) { hadOld = false }
try {
await s.renameDir(tmp, id)
} catch (e) {
if (hadOld) { try { await s.renameDir(bak, id) } catch (e2) { /* 回滚尽力而为 */ } }
throw new Error('替换插件目录失败:' + ((e && e.message) || e))
}
if (hadOld) { try { await s.removeDir(bak) } catch (e) { /* 遗留 .old 不影响加载 */ } }
const filesMap = {}
for (const f of files) filesMap[f.name] = f.sha256
await writeIndex(s, id, { id: id, dir: id, main: mainName, style: String(man.style || ''), version: String(item.version || ''), files: filesMap })
return { ok: true, restart: true, dir: id, version: item.version, files: files.length }
}
// 旧条目:单文件安装(保持向后兼容)
async function installSingle (item, s) {
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 hex = await sha256Hex(new global.TextEncoder().encode(text))
if (item.sha256 && hex !== String(item.sha256).toLowerCase()) return { ok: false, error: '校验失败(sha256 不符)' }
const file = String(item.file).split('/').pop()
await s.write(file, text)
await writeIndex(s, item.id, { id: item.id, file: file, version: item.version, integrity: item.integrity })
return { ok: true, restart: true, file: file }
}
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 }
if (item.bundle) return await installBundle(item, s)
if (!item.file) return { ok: false, error: '市场条目缺少安装包' }
return await installSingle(item, s)
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
@@ -93,10 +195,17 @@
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 }
if (hit && hit.dir) {
try { await s.removeDir(String(hit.dir)) } catch (e) { /* 目录已不在 */ }
} else if (hit && hit.file) {
await s.remove(hit.file)
}
return { ok: true, restart: true, keptData: true }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
global.IWBRuntimePluginMarket = { list: list, cached: cached, installed: installed, install: install, uninstall: uninstall }
})(typeof window !== 'undefined' ? window : globalThis)
global.IWBRuntimePluginMarket = {
list: list, cached: cached, installed: installed, install: install, uninstall: uninstall,
_internals: { safeEntryName: safeEntryName, MAX_FILES: MAX_FILES, MAX_FILE_BYTES: MAX_FILE_BYTES, MAX_TOTAL_BYTES: MAX_TOTAL_BYTES },
}
})(typeof window !== 'undefined' ? window : globalThis)
+13 -1
View File
@@ -514,6 +514,18 @@
await fs().mkdir(abs, { recursive: true })
return true
}
// 重命名插件目录(单级,用于安装时的原子替换)
async function pluginRenameDir(fromId, toId) {
const a = safePluginRel(fromId)
const b = safePluginRel(toId)
if (a.indexOf('/') >= 0 || b.indexOf('/') >= 0) throw new Error('只允许重命名一级插件目录')
await fs().rename(await join(await pluginRoot(), a), await join(await pluginRoot(), b))
return true
}
async function pluginExistsDir(id) {
try { return await fs().exists(await join(await pluginRoot(), safePluginRel(id))) } catch (e) { return false }
}
// 删除插件目录(递归)。只允许一级 <id>,避免误删 plugins 根或上级目录。
async function pluginRemoveDir(id) {
const seg = safePluginRel(id)
@@ -994,7 +1006,7 @@
global.IWBStorageFile = {
enabled, ready: init, flush, runtime, pickDir, switchTo, migrateTo, gcImages, rotateTrash, galleryThumb, readDisplayThumb, writeDisplayThumb,
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 },
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 },
storage: () => storage,
kv: () => kv,
+56
View File
@@ -0,0 +1,56 @@
'use strict'
// 插件安装包(M3)行为测试
//
// 覆盖两件最容易出错、且出错就等于「装了个坏插件 / 被路径穿越」的事:
// ① Node 侧 STORE zip 写入器 ↔ 客户端解包器(src/storage-zip.js)必须互通;
// ② 安装包的路径白名单(只允许 manifest.json / main.js / styles.css / assets/*)。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const root = path.resolve(__dirname, '..')
const { zipStore } = require(path.join(root, 'scripts', 'plugin-zip'))
// ---- ① zip 往返 ----
const zipBuf = zipStore([
{ name: 'manifest.json', data: '{"id":"demo","version":"1.0.0","main":"main.js"}' },
{ name: 'main.js', data: 'global.x = 1\n' },
])
const zipSandbox = { TextDecoder }
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'storage-zip.js'), 'utf8'), zipSandbox)
const Zip = zipSandbox.IWBStorageZip
const ab = zipBuf.buffer.slice(zipBuf.byteOffset, zipBuf.byteOffset + zipBuf.byteLength)
const parsed = Zip.wZipParseEntries(ab)
assert.strictEqual(parsed.entries.length, 2, '应解析出 2 个条目')
for (const e of parsed.entries) {
assert.strictEqual(e.method, 0, '必须是 STORE(method=0),否则旧 macOS 无 DecompressionStream 会失败')
assert.ok(e.rawSize > 0)
}
;(async () => {
const texts = {}
for (const e of parsed.entries) texts[e.name] = new TextDecoder().decode(await Zip.wZipReadEntry(parsed, e))
assert.strictEqual(texts['main.js'], 'global.x = 1\n', '解出的内容必须与写入一致')
assert.ok(texts['manifest.json'].indexOf('"id":"demo"') > 0)
// ---- ② 路径白名单 ----
const sandbox = { crypto: require('crypto').webcrypto, TextDecoder, TextEncoder }
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'runtime-plugin-market.js'), 'utf8'), sandbox)
const M = sandbox.IWBRuntimePluginMarket
assert.ok(M && M._internals, '市场模块应导出 _internals 供测试')
const ok = M._internals.safeEntryName
;['manifest.json', 'main.js', 'styles.css', 'assets/icon.png', 'assets/a-b_c.svg'].forEach((n) => {
assert.strictEqual(ok(n), true, '应允许:' + n)
})
;['../evil.js', '/etc/passwd', 'assets/../../x.js', 'sub/main.js', 'main.js.bak', 'assets/a/b.png', '', 'assets/' + 'x'.repeat(100)].forEach((n) => {
assert.strictEqual(ok(n), false, '应拒绝:' + n)
})
assert.ok(M._internals.MAX_FILES >= 50 && M._internals.MAX_TOTAL_BYTES >= 5 * 1024 * 1024, '体积/数量上限应存在且合理')
// zip 写入器本身也要拒绝穿越路径
assert.throws(() => zipStore([{ name: '../x.js', data: '1' }]), '写入器应拒绝 ..')
assert.throws(() => zipStore([{ name: '/abs.js', data: '1' }]), '写入器应拒绝绝对路径')
console.log('plugin-bundle checks passed(STORE 往返 / 路径白名单 / 上限常量)')
})().catch((e) => { console.error(e); process.exit(1) })
+136
View File
@@ -0,0 +1,136 @@
'use strict'
// 目录插件安装(M3)端到端测试:真实 zip → 假 FS → 断言落盘/索引/失败回滚
//
// 不依赖 Tauri:用 fs 临时目录实现 IWBStorageFile.plugins 的同名契约,
// 用 vm 加载真实的 src/storage-zip.js 与 src/runtime-plugin-market.js。
const assert = require('assert')
const fs = require('fs')
const os = require('os')
const path = require('path')
const vm = require('vm')
const root = path.resolve(__dirname, '..')
const { zipStore } = require(path.join(root, 'scripts', 'plugin-zip'))
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'iwb-install-'))
const pluginsDir = path.join(work, 'plugins')
function p (rel) { return path.join(pluginsDir, rel) }
const fakePlugins = {
async manifest () {
try { return JSON.parse(fs.readFileSync(p('index.json'), 'utf8')) } catch (e) { return [] }
},
async read (f) { return fs.readFileSync(p(f), 'utf8') },
async write (f, text) { fs.mkdirSync(path.dirname(p(f)), { recursive: true }); fs.writeFileSync(p(f), text) },
async remove (f) { try { fs.unlinkSync(p(f)) } catch (e) { /* ignore */ } },
async mkdir (rel) { fs.mkdirSync(p(rel), { recursive: true }) },
async writeBinary (rel, bytes) { fs.mkdirSync(path.dirname(p(rel)), { recursive: true }); fs.writeFileSync(p(rel), Buffer.from(bytes)) },
async removeDir (rel) { fs.rmSync(p(rel), { recursive: true, force: true }) },
async renameDir (a, b) { fs.renameSync(p(a), p(b)) },
async existsDir (rel) { return fs.existsSync(p(rel)) },
async listDirs () { return [] },
}
const mainCode = 'global.__demoLoaded = 1\n'
const manifest = { id: 'demo', name: '演示', version: '1.0.0', apiVersion: 1, main: 'main.js' }
function buildZip (over) {
const man = Object.assign({}, manifest, over || {})
const main = (over && over.__main) || mainCode
return zipStore([
{ name: 'manifest.json', data: JSON.stringify(man) },
{ name: 'main.js', data: main },
])
}
const sha = (buf) => require('crypto').createHash('sha256').update(buf).digest('hex')
;(async () => {
// 真实解包在下面由 install 走异步路径;这里改用同步手工解析避免测试辅助复杂化
const sb = { TextDecoder }
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'storage-zip.js'), 'utf8'), sb)
const Z = sb.IWBStorageZip
async function contents (buf) {
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
const parsed = Z.wZipParseEntries(ab)
const out = {}
for (const e of parsed.entries) out[e.name] = Buffer.from(await Z.wZipReadEntry(parsed, e)).toString('utf8')
return out
}
const zip1 = buildZip()
const files1 = await contents(zip1)
const item = {
id: 'demo', version: '1.0.0', bundle: 'plugins/demo-1.0.0.zip',
bundleSha256: sha(zip1),
files: Object.keys(files1).map((n) => ({ path: n, sha256: sha(Buffer.from(files1[n])), size: Buffer.byteLength(files1[n]) })),
}
const sandbox = {
crypto: require('crypto').webcrypto, TextDecoder, TextEncoder,
IWBStorageFile: { plugins: fakePlugins },
IWBStorageLocal: { getStore: () => ({ get: () => null, set: () => true }) },
fetch: async (url) => {
if (String(url).indexOf('index.json') >= 0) return { ok: true, json: async () => ({ plugins: [item] }) }
return { ok: true, arrayBuffer: async () => zip1.buffer.slice(zip1.byteOffset, zip1.byteOffset + zip1.byteLength) }
},
}
sandbox.__TAURI__ = null
sandbox.global = sandbox
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'storage-zip.js'), 'utf8'), sandbox)
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'runtime-plugin-market.js'), 'utf8'), sandbox)
const M = sandbox.IWBRuntimePluginMarket
const r1 = await M.install('demo')
assert.ok(r1.ok, '首次安装应成功:' + JSON.stringify(r1))
assert.strictEqual(fs.readFileSync(p('demo/main.js'), 'utf8'), mainCode, 'main.js 应落盘且内容一致')
const idx1 = JSON.parse(fs.readFileSync(p('index.json'), 'utf8'))
const e1 = idx1.find((x) => x.id === 'demo')
assert.ok(e1 && e1.dir === 'demo' && e1.main === 'main.js', '索引应写入目录条目')
assert.strictEqual(e1.files['main.js'], sha(Buffer.from(mainCode)), '索引应记录逐文件 sha256')
// 覆盖安装(升级):旧目录必须被替换,且不残留 .old/.new
const zip2 = buildZip({ __main: 'global.__demoLoaded = 2\n' })
const files2 = await contents(zip2)
const item2 = Object.assign({}, item, {
version: '1.0.1', bundleSha256: sha(zip2),
files: Object.keys(files2).map((n) => ({ path: n, sha256: sha(Buffer.from(files2[n])), size: Buffer.byteLength(files2[n]) })),
})
sandbox.fetch = async (url) => {
if (String(url).indexOf('index.json') >= 0) return { ok: true, json: async () => ({ plugins: [item2] }) }
return { ok: true, arrayBuffer: async () => zip2.buffer.slice(zip2.byteOffset, zip2.byteOffset + zip2.byteLength) }
}
const r2 = await M.install('demo')
assert.ok(r2.ok, '覆盖安装应成功:' + JSON.stringify(r2))
assert.strictEqual(fs.readFileSync(p('demo/main.js'), 'utf8'), 'global.__demoLoaded = 2\n', '升级后应是新内容')
assert.ok(!fs.existsSync(p('demo.old')), '不应残留 .old')
assert.ok(!fs.existsSync(p('demo.new')), '不应残留 .new')
// 逐文件 sha256 不符 → 拒绝,且旧版本不受影响
const bad = Object.assign({}, item2, { files: [{ path: 'manifest.json', sha256: 'deadbeef', size: 1 }] })
sandbox.fetch = async (url) => {
if (String(url).indexOf('index.json') >= 0) return { ok: true, json: async () => ({ plugins: [bad] }) }
return { ok: true, arrayBuffer: async () => zip2.buffer.slice(zip2.byteOffset, zip2.byteOffset + zip2.byteLength) }
}
const r3 = await M.install('demo')
assert.ok(!r3.ok && /校验失败/.test(r3.error), '逐文件 sha256 不符必须拒绝:' + JSON.stringify(r3))
assert.strictEqual(fs.readFileSync(p('demo/main.js'), 'utf8'), 'global.__demoLoaded = 2\n', '拒绝安装不得破坏已装版本')
// manifest id 不一致 → 拒绝
const wrongId = buildZip({ id: 'other' })
const wrongFiles = await contents(wrongId)
const item4 = Object.assign({}, item2, {
bundleSha256: sha(wrongId),
files: Object.keys(wrongFiles).map((n) => ({ path: n, sha256: sha(Buffer.from(wrongFiles[n])), size: Buffer.byteLength(wrongFiles[n]) })),
})
sandbox.fetch = async (url) => {
if (String(url).indexOf('index.json') >= 0) return { ok: true, json: async () => ({ plugins: [item4] }) }
return { ok: true, arrayBuffer: async () => wrongId.buffer.slice(wrongId.byteOffset, wrongId.byteOffset + wrongId.byteLength) }
}
const r4 = await M.install('demo')
assert.ok(!r4.ok && /id 与市场条目不一致/.test(r4.error), 'manifest id 不一致必须拒绝:' + JSON.stringify(r4))
// 卸载:目录删除,索引移除
const r5 = await M.uninstall('demo')
assert.ok(r5.ok, '卸载应成功')
assert.ok(!fs.existsSync(p('demo')), '卸载应删除插件目录')
assert.strictEqual((JSON.parse(fs.readFileSync(p('index.json'), 'utf8')) || []).filter((x) => x.id === 'demo').length, 0, '索引条目应移除')
fs.rmSync(work, { recursive: true, force: true })
console.log('plugin-install checks passed(首装 / 覆盖升级 / 逐文件校验拒绝 / id 校验 / 卸载)')
})().catch((e) => { try { fs.rmSync(work, { recursive: true, force: true }) } catch (e2) { /* ignore */ } console.error(e); process.exit(1) })