/* 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 } // 版本比较(v3.25.44):外置插件不再无条件覆盖内置 —— 高版本胜,同版本外置胜(允许本地打补丁)。 // 否则用户资料目录里残留的旧外置插件会永久盖住随包升级后的内置插件(browser 1.6.0 盖 1.7.0 的真实案例)。 function compareVersions (a, b) { const pa = String(a || '0').split('.').map(function (x) { return parseInt(x, 10) || 0 }) const pb = String(b || '0').split('.').map(function (x) { return parseInt(x, 10) || 0 }) const n = Math.max(pa.length, pb.length) for (let i = 0; i < n; i++) { const x = pa[i] || 0 const y = pb[i] || 0 if (x !== y) return x > y ? 1 : -1 } return 0 } async function sha256Hex (text) { const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(String(text))) return Array.from(new Uint8Array(buf)).map(function (b) { return b.toString(16).padStart(2, '0') }).join('') } // 目录插件(v3.25.41 / M1):一个插件一个目录 // <内置>/plugins//{manifest.json,main.js,styles.css} // <资料目录>/plugins//{同} // 与单文件插件共用同一套「自注册」契约,区别只是多读一个 manifest 和可选 styles.css。 const styleNodes = {} const pendingStyles = {} function applyStyle (id, css) { if (!css) return try { const doc = global.document if (!doc) return if (styleNodes[id] && styleNodes[id].parentNode) styleNodes[id].parentNode.removeChild(styleNodes[id]) const node = doc.createElement('style') node.setAttribute('data-plugin', String(id)) node.textContent = String(css) doc.head.appendChild(node) styleNodes[id] = node } catch (e) { /* 样式失败不影响脚本 */ } } function applyStyleFor (id) { const css = pendingStyles[id] if (css) applyStyle(id, css) } function removeStyle (id) { try { const n = styleNodes[id]; if (n && n.parentNode) n.parentNode.removeChild(n); delete styleNodes[id] } catch (e) { /* ignore */ } } async function readFolderFile (record, name) { if (record.source === 'external') { const src = source() if (!src || typeof src.readFile !== 'function') throw new Error('外部插件目录不可用') return await src.readFile(record.dir + '/' + name) } const resp = await global.fetch('/plugins/' + record.dir + '/' + name, { cache: 'no-store' }) if (!resp.ok) throw new Error('读取插件文件失败:' + name + '(HTTP ' + resp.status + ')') return await resp.text() } // 扫描 <资料目录>/plugins/*/manifest.json(无索引也能识别手工放入的目录插件) async function listFolderEntries () { const src = source() if (!src || typeof src.listDirs !== 'function') return [] const out = [] let dirs = [] try { dirs = await src.listDirs() } catch (e) { return [] } for (const d of dirs) { const id = String((d && d.id) || '') if (!id) continue try { const m = JSON.parse(await src.readFile(id + '/manifest.json')) if (!m || String(m.id || '') !== id) continue out.push({ id: id, dir: id, main: m.main || 'main.js', style: m.style || '', version: m.version || '', files: m.files || null, source: 'external' }) } catch (e) { /* 不是插件目录 */ } } return out } async function loadFolder (record) { record.status = 'loading' try { // 目录里的 manifest.json 是入口/样式的真源:内置索引只带 hash,字段缺省时向 manifest 补 if (record.source !== 'external') { try { const m = JSON.parse(await readFolderFile(record, 'manifest.json')) if (m && typeof m === 'object') { if (typeof m.main === 'string' && m.main) record.main = m.main if (typeof m.style === 'string' && m.style) record.style = m.style if (!record.version && m.version) record.version = String(m.version) } } catch (e) { /* 无 manifest 时按索引里的 main */ } } const main = String(record.main || 'main.js') const code = await readFolderFile(record, main) // 逐文件 sha256:内置以随包 index.json 的值为准(外部/市场安装同理),不一致直接拒载 const expect = record.hashes && record.hashes[main] if (expect) { const actual = await sha256Hex(code) if (actual !== String(expect).toLowerCase()) throw new Error('完整性校验失败(' + main + ' 的 sha256 不符)') } if (record.style) { // 只在插件**激活**时注入样式(停用状态不该污染宿主 UI);文本先暂存,激活由宿主触发 try { pendingStyles[record.id] = await readFolderFile(record, String(record.style)) } catch (e) { /* 样式缺失不阻断 */ } } const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' })) try { await inject({ src: url, error: '插件脚本执行失败(' + record.id + ')' }) } 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 } } // 注入一段脚本并等它执行完(插件在加载期自我注册) 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' // 不在加载阶段写启用状态:否则会把用户关掉的插件又打开 // (启用/停用由 app.js 加载完成后按持久化状态统一应用) 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, sha256Hex: sha256Hex, compareVersions: compareVersions, loadBuiltin: loadBuiltin, loadExternal: loadExternal, loadLocal: loadLocal, loadFolder: loadFolder, listFolderEntries: listFolderEntries, applyStyleFor: applyStyleFor, removeStyle: removeStyle } })(typeof window !== 'undefined' ? window : globalThis)