Files
image-workbench-desktop/src/runtime-plugin-market.js
T
qiqi e08fdb6271 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 两组测试(含覆盖升级与拒绝路径)
2026-11-20 10:20:09 +08:00

211 lines
9.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* runtime-plugin-market.js —— 插件市场(下载 / 校验 / 安装 / 卸载)
*
* 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) {
const T = (global.__TAURI__ && global.__TAURI__.http) ? global.__TAURI__.http : null
let nativeErr = ''
if (T && typeof T.fetch === 'function') {
try { return await T.fetch(url) } catch (e) { nativeErr = String((e && e.message) || e) }
}
try {
return await global.fetch(url, { cache: 'no-store' })
} catch (e2) {
const webErr = String((e2 && e2.message) || e2)
throw new Error('无法访问 ' + url + (nativeErr ? ('(原生 HTTP:' + nativeErr + ')') : '') + '(网页请求:' + webErr + ')')
}
}
// 本地缓存:上次成功拉到的市场列表(毫秒级出图,后台再刷新)
const CACHE_KEY = 'iwb_market_cache'
function localStore () {
const L = global.IWBStorageLocal || null
return (L && typeof L.getStore === 'function') ? L.getStore() : null
}
function cached () {
try {
const st = localStore()
if (!st) return null
const v = st.get(CACHE_KEY)
return (Array.isArray(v) && v.length) ? v : null
} catch (e) { return null }
}
function saveCache (list) {
try { const st = localStore(); if (st && Array.isArray(list) && list.length) st.set(CACHE_KEY, list) } catch (e) { /* ignore */ }
}
async function list () {
const resp = await marketFetch(MARKET_URL)
if (!resp.ok) throw new Error('市场不可达:HTTP ' + resp.status)
const j = await resp.json()
const items = Array.isArray(j && j.plugins) ? j.plugins : []
saveCache(items)
return items
}
async function installed () {
const s = store()
if (!s) return []
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 s = store()
if (!s) return { ok: false, error: '外部插件目录不可用' }
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) } }
}
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.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,
_internals: { safeEntryName: safeEntryName, MAX_FILES: MAX_FILES, MAX_FILE_BYTES: MAX_FILE_BYTES, MAX_TOTAL_BYTES: MAX_TOTAL_BYTES },
}
})(typeof window !== 'undefined' ? window : globalThis)