feat(plugins): P3 开发者模式(plugins/local/<id>/plugin.js 免签名加载)+ SDK 文档与示例插件
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m22s
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m22s
This commit is contained in:
1 parent
1008370733
commit
49b8cb3abd
7 files changed
+225
-7
No files matched your search
@@ -8582,6 +8582,34 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
|
||||
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
|
||||
}
|
||||
|
||||
// 开发者模式插件(plugins/local/<id>/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
|
||||
}
|
||||
}
|
||||
|
||||
// 按需加载(插件管理里勾选 idle 行):下载脚本 → 注册 → 显式启用;失败时返回错误供 UI 回滚勾选并提示。
|
||||
async function wEnsurePluginLoaded(id) {
|
||||
const record = wRuntimePlugins.find((r) => r.id === id)
|
||||
@@ -8610,6 +8638,17 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
|
||||
if (src) ext = await src.manifest()
|
||||
} catch (e) { /* 外部清单读到一半失败:忽略 */ }
|
||||
const byId = new Map(builtin.map((e) => [String((e && e.id) || ''), Object.assign({}, e, { source: 'builtin' })]))
|
||||
// 开发者模式:<资料目录>/plugins/local/<id>/plugin.js(未签名,仅本地调试用)
|
||||
try {
|
||||
const devRaw = lsGet('iwb_plugin_dev', false)
|
||||
const devOn = devRaw === true || devRaw === 'true' || devRaw === 1 || devRaw === '1'
|
||||
const lsrc = wPluginSource()
|
||||
if (devOn && lsrc && typeof lsrc.listLocal === 'function') {
|
||||
const locals = await lsrc.listLocal()
|
||||
try { lsSet('iwb_plugin_dev_count', (locals || []).length) } catch (e1) { /* probe */ }
|
||||
for (const l of locals) { if (l && l.id) byId.set(String(l.id), { id: String(l.id), file: 'plugin.js', version: 'dev', source: 'local', code: l.code }) }
|
||||
}
|
||||
} catch (e) { /* 开发者模式读取失败不影响启动 */ }
|
||||
for (const e of ext) { const id = String((e && e.id) || ''); if (id) byId.set(id, Object.assign({}, e, { source: 'external' })) }
|
||||
const manifest = Array.from(byId.values())
|
||||
if (!manifest.length) return
|
||||
@@ -8620,20 +8659,23 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
|
||||
const id = String((entry && entry.id) || '')
|
||||
const file = String((entry && entry.file) || '')
|
||||
const isExt = (entry && entry.source) === 'external'
|
||||
const record = { id, file, version: (entry && entry.version) || '', status: 'loading', error: null, source: isExt ? 'external' : 'builtin' }
|
||||
const isLocalEntry = (entry && entry.source) === 'local'
|
||||
const record = { id, file, version: (entry && entry.version) || '', status: 'loading', error: null, code: (entry && entry.code) || '', source: isExt ? 'external' : ((entry && entry.source === 'local') ? 'local' : 'builtin') }
|
||||
wRuntimePlugins.push(record)
|
||||
if (!id || !/^[A-Za-z0-9._-]+$/.test(file)) { record.status = 'bad-entry'; continue }
|
||||
const integrity = String((entry && entry.integrity) || '')
|
||||
// fail-closed:无 integrity 声明即拒绝加载(清单由 KV 发布脚本生成、必带 integrity;缺失视为不可信)
|
||||
if (!integrity) { record.status = 'bad-entry'; record.error = 'integrity 缺失(拒绝加载)'; continue }
|
||||
if (!/^sha(256|384|512)-[A-Za-z0-9+/]{40,}={0,2}$/.test(integrity)) { record.status = 'bad-entry'; record.error = 'integrity 格式不合法'; continue }
|
||||
if (!integrity && !isLocalEntry) { record.status = 'bad-entry'; record.error = 'integrity 缺失(拒绝加载)'; continue }
|
||||
if (integrity && !/^sha(256|384|512)-[A-Za-z0-9+/]{40,}={0,2}$/.test(integrity)) { record.status = 'bad-entry'; record.error = 'integrity 格式不合法'; continue }
|
||||
record.integrity = integrity
|
||||
// 只下载已启用的;未启用记 idle(不注入脚本),插件管理里勾选时经 wEnsurePluginLoaded 按需下载
|
||||
// 收进 pending 而非逐个 await:wLoadPluginEntry 在首个 await 前已 append ⇒ 并发抓取;async=false 保证执行顺序不变(冷启动 3 RTT → 1)
|
||||
if (PluginHost && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(id)) pending.push(isExt ? wLoadExternalPluginEntry(record) : wLoadPluginEntry(record))
|
||||
// 本地开发插件默认启用(没有持久化状态,不应被当作已关闭的插件)
|
||||
if (PluginHost && typeof PluginHost.isEnabled === 'function' && (isLocalEntry || PluginHost.isEnabled(id))) pending.push(isLocalEntry ? wLoadLocalPluginEntry(record) : (isExt ? wLoadExternalPluginEntry(record) : wLoadPluginEntry(record)))
|
||||
else record.status = 'idle'
|
||||
}
|
||||
await Promise.all(pending)
|
||||
try { lsSet('iwb_plugin_load_status', JSON.stringify(wRuntimePlugins.map((r) => ({ id: r.id, status: r.status, source: r.source, error: r.error || '' })))) } catch (e2) { /* probe */ }
|
||||
try { if (PluginHost && typeof PluginHost.emit === 'function') PluginHost.emit('runtime-plugins-loaded') } catch (e) { /* 通知失败不影响启动 */ }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# 插件 SDK(P3)
|
||||
|
||||
> 桌面版插件**全部从市场安装**,不再随应用发布。本文写给"想自己写插件"的人。
|
||||
|
||||
## 1. 两种插件来源
|
||||
|
||||
| 来源 | 位置 | 要求 |
|
||||
|---|---|---|
|
||||
| 市场(官方/社区) | `<资料目录>/plugins/*.js` + `plugins/index.json` | 清单带 `integrity`(sha256),加载时校验 |
|
||||
| 本地开发(开发者模式) | `<资料目录>/plugins/local/<id>/plugin.js` | **不校验签名**,需在设置里打开「开发者模式」 |
|
||||
|
||||
资料目录默认 `~/Documents/ImageWorkbench`(macOS)。
|
||||
|
||||
## 2. 最小插件
|
||||
|
||||
一个文件即可,格式为 IIFE,向 `window.IWBPluginHost` 注册:
|
||||
|
||||
```js
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
global.IWBPluginHost.register({
|
||||
id: 'hello-world', // 唯一 id(小写字母/数字/连字符)
|
||||
name: '示例插件',
|
||||
version: '0.1.0',
|
||||
apiVersion: 1, // 宿主 API 版本,当前为 1
|
||||
capabilities: ['nodeActions', 'canvas'],
|
||||
}, function (ctx) {
|
||||
ctx.nodeActions.register({
|
||||
id: 'hello-world-count',
|
||||
title: '示例:数一下节点',
|
||||
icon: 'sparkles',
|
||||
appliesTo: function (node) { return !!(node && node.type === 'ref') },
|
||||
run: function () { console.log('节点数', ctx.canvas.getNodes().length); return true },
|
||||
})
|
||||
return { dispose: function () {} }
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
```
|
||||
|
||||
完整可运行版本见仓库 `examples/plugin-hello/plugin.js`。
|
||||
|
||||
## 3. 能力(capabilities)
|
||||
|
||||
| 能力 | 作用 |
|
||||
|---|---|
|
||||
| `nodeActions` | 给节点右键/工具条加自定义动作 |
|
||||
| `canvas` | 只读访问画布(`getNodes` 等) |
|
||||
| `canvasWrite` | 写画布(`setNodeImage` 等),**必须同时声明** |
|
||||
| `events` | 订阅宿主事件 |
|
||||
| `storage` | 插件私有持久化(按插件 id 隔离) |
|
||||
|
||||
未声明的能力在 `ctx` 上是 undefined,调用会抛错。
|
||||
|
||||
## 4. 本地开发流程
|
||||
|
||||
1. 建目录:`<资料目录>/plugins/local/<你的插件 id>/plugin.js`
|
||||
2. 设置 → 插件 → 勾选「**开发者模式**」
|
||||
3. 重启应用(插件在启动时加载)
|
||||
4. 改完代码后再重启一次即可重新加载
|
||||
|
||||
> 开发者模式关闭时,`plugins/local/` 下的插件**不会被加载**(避免误执行未签名代码)。
|
||||
|
||||
## 5. 发布到市场
|
||||
|
||||
1. 把插件文件放进插件源仓 `iwb-plugins-desktop/<id>/src/index.js`
|
||||
2. 在桌面仓跑同步:`node scripts/sync-plugins-from-repo.js`
|
||||
3. 生成市场:`node scripts/gen-market.js`
|
||||
4. 把 `market/` 上传到 NAS `/vol8/web/iwb-market/`
|
||||
|
||||
## 6. 注意事项
|
||||
|
||||
- **不要用 `alert` / `confirm` / `prompt`**:桌面端会阻塞 WebView(宿主已全部改页内确认)
|
||||
- 插件与宿主同源,能读到画布数据 ⇒ 只装可信插件
|
||||
- 插件 id 冲突会被拒绝注册(先注册者生效)
|
||||
- `dispose` 里清理你自己加的 DOM/定时器/监听器
|
||||
@@ -0,0 +1,40 @@
|
||||
// 示例插件(P3 SDK 模板):把本文件放到
|
||||
// <资料目录>/plugins/local/hello-world/plugin.js
|
||||
// 然后在 设置 → 插件 → 打开「开发者模式」,重启应用即可生效。
|
||||
//
|
||||
// 契约:调用 window.IWBPluginHost.register(manifest, factory)
|
||||
// manifest: { id, name, version, apiVersion, capabilities }
|
||||
// factory(ctx): 注册入口;返回 { dispose } 供停用/卸载时清理
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
|
||||
global.IWBPluginHost.register({
|
||||
id: 'hello-world',
|
||||
name: '示例插件',
|
||||
version: '0.1.0',
|
||||
apiVersion: 1,
|
||||
capabilities: ['nodeActions', 'canvas'],
|
||||
}, function (ctx) {
|
||||
// 读取当前画布节点(只读)
|
||||
function countNodes () {
|
||||
try {
|
||||
return (ctx.canvas && typeof ctx.canvas.getNodes === 'function') ? ctx.canvas.getNodes().length : 0
|
||||
} catch (e) { return -1 }
|
||||
}
|
||||
|
||||
// 注册一个节点右键动作:只在参考图/输出节点上出现
|
||||
ctx.nodeActions.register({
|
||||
id: 'hello-world-count',
|
||||
title: '示例:数一下节点',
|
||||
icon: 'sparkles',
|
||||
appliesTo: function (node) { return !!(node && (node.type === 'ref' || node.type === 'out')) },
|
||||
run: function () {
|
||||
// 注意:桌面端不要用 alert/confirm(会阻塞 WebView),用 console 或宿主提供的 UI
|
||||
console.log('[hello-world] 当前画布节点数:' + countNodes())
|
||||
return true
|
||||
},
|
||||
})
|
||||
|
||||
return { dispose: function () { /* 清理定时器/监听器 */ } }
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
+18
-1
@@ -421,6 +421,23 @@
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(safe)) throw new Error('非法插件文件名')
|
||||
try { await fs().remove(await join(dir, PLUG_DIR, safe)); return true } catch (e) { return false }
|
||||
}
|
||||
// 开发者模式:<资料目录>/plugins/local/<id>/plugin.js(未签名,只在开关打开时加载)
|
||||
async function pluginListLocal() {
|
||||
try {
|
||||
const ldir = await join(dir, PLUG_DIR, 'local')
|
||||
const entries = await fs().readDir(ldir)
|
||||
const out = []
|
||||
for (const e of entries) {
|
||||
if (!e || !e.isDirectory) continue
|
||||
try {
|
||||
const code = await fs().readTextFile(await join(ldir, e.name, 'plugin.js'))
|
||||
out.push({ id: e.name, file: 'local/' + e.name + '/plugin.js', code: code })
|
||||
} catch (err) { /* 该目录没有 plugin.js,跳过 */ }
|
||||
}
|
||||
return out
|
||||
} catch (e) { return [] }
|
||||
}
|
||||
|
||||
async function pluginDir() {
|
||||
const p = await join(dir, PLUG_DIR)
|
||||
try { await fs().mkdir(p, { recursive: true }) } catch (e) { /* 已存在 */ }
|
||||
@@ -685,7 +702,7 @@
|
||||
|
||||
global.IWBStorageFile = {
|
||||
enabled, ready: init, flush, runtime, pickDir, switchTo, migrateTo, gcImages,
|
||||
plugins: { manifest: pluginManifest, read: pluginRead, write: pluginWrite, remove: pluginRemove, dir: pluginDir },
|
||||
plugins: { manifest: pluginManifest, read: pluginRead, write: pluginWrite, remove: pluginRemove, dir: pluginDir, listLocal: pluginListLocal },
|
||||
storage: () => storage,
|
||||
kv: () => kv,
|
||||
dir: () => dir,
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
const [msg, setMsg] = React.useState('')
|
||||
const [busy, setBusy] = React.useState('')
|
||||
const [restart, setRestart] = React.useState(false)
|
||||
|
||||
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
|
||||
const refresh = React.useCallback(async () => {
|
||||
if (!D || !D.market) { setRows([]); return }
|
||||
@@ -110,6 +111,18 @@
|
||||
return Promise.resolve(window.confirm(text))
|
||||
}
|
||||
|
||||
// 开发者模式开关(走统一存储门面,src 不得直调 localStorage)
|
||||
function pluginDevStore () {
|
||||
const L = (typeof window !== 'undefined') ? window.IWBStorageLocal : null
|
||||
return (L && typeof L.getStore === 'function') ? L.getStore() : null
|
||||
}
|
||||
function pluginDevGet () {
|
||||
try { const st = pluginDevStore(); return !!(st && st.get('iwb_plugin_dev') === true) } catch (e) { return false }
|
||||
}
|
||||
function pluginDevSet (on) {
|
||||
try { const st = pluginDevStore(); if (st) st.set('iwb_plugin_dev', !!on) } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
// 桌面端插件管理(参考 Obsidian):搜索 + 已安装(开关/设置)+ 可安装(市场)
|
||||
function DesktopPluginsTab (props) {
|
||||
const { PluginHost, pluginItems, setPluginsRev, setTab, wRuntimePlugins } = props
|
||||
@@ -119,6 +132,9 @@
|
||||
const [msg, setMsg] = React.useState('')
|
||||
const [busy, setBusy] = React.useState('')
|
||||
const [restart, setRestart] = React.useState(false)
|
||||
const [devMode, setDevMode] = React.useState(function () {
|
||||
return pluginDevGet()
|
||||
})
|
||||
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
|
||||
const refresh = React.useCallback(async () => {
|
||||
if (!D || !D.market) { setMarket([]); return }
|
||||
@@ -177,6 +193,33 @@
|
||||
return el('div', { className: 'iwb-set-page' },
|
||||
el('div', { className: 'iwb-set-page-title' }, '插件'),
|
||||
el('div', { className: 'iwb-hint' }, '插件从市场安装到:' + dirHint + '(应用本体不再自带插件)'),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('label', { className: 'iwb-check', title: '本地开发用:把插件放到 plugins/local/<id>/plugin.js' },
|
||||
el('input', {
|
||||
type: 'checkbox',
|
||||
checked: devMode,
|
||||
onChange: function (e) {
|
||||
const on = e.target.checked
|
||||
setDevMode(on)
|
||||
pluginDevSet(on)
|
||||
setMsg(on ? '已开启开发者模式,重启后加载 plugins/local/ 下的插件' : '已关闭开发者模式,重启后只加载市场安装的插件')
|
||||
},
|
||||
}),
|
||||
' 开发者模式(加载 plugins/local/<id>/plugin.js,未签名)'),
|
||||
),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('label', { className: 'iwb-check', title: '用于本地开发:把插件放到 plugins/local/<id>/plugin.js' },
|
||||
el('input', {
|
||||
type: 'checkbox', checked: devMode,
|
||||
onChange: (e) => {
|
||||
const on = e.target.checked
|
||||
setDevMode(on)
|
||||
pluginDevSet(on)
|
||||
setMsg(on ? '已开启开发者模式,重启后加载 plugins/local/ 下的插件' : '已关闭开发者模式,重启后只加载市场安装的插件')
|
||||
},
|
||||
}),
|
||||
' 开发者模式(加载 plugins/local/<id>/plugin.js,未签名)'),
|
||||
),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('input', { className: 'iwb-input iwb-grow', placeholder: '搜索已安装的插件…', value: q, onChange: (e) => setQ(e.target.value) }),
|
||||
),
|
||||
|
||||
@@ -88,7 +88,8 @@ const root = path.resolve(__dirname, '..')
|
||||
const appJs = fs.readFileSync(path.join(root, 'app.js'), 'utf8')
|
||||
assert.ok(/script\.integrity = integrity; script\.crossOrigin = 'anonymous'/.test(appJs), 'loader 应把 integrity 交给浏览器强制校验')
|
||||
assert.ok(/record\.status = 'bad-entry'; record\.error = 'integrity 格式不合法'/.test(appJs), 'integrity 格式不合法应拒绝加载')
|
||||
assert.ok(/if \(!integrity\) \{ record\.status = 'bad-entry'; record\.error = 'integrity 缺失(拒绝加载)'; continue \}/.test(appJs), '缺失 integrity 应拒绝加载(fail-closed)')
|
||||
// 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,本地开发插件除外)')
|
||||
assert.ok(!/record\.integrity = integrity \|\| 'missing'/.test(appJs), '不应再有「缺失记为 missing 并继续加载」的过渡分支')
|
||||
|
||||
console.log('plugin integrity checks passed')
|
||||
|
||||
@@ -150,7 +150,7 @@ const MAX_SRC_COMPONENT_LINES = 531
|
||||
// ② 同时守「app.js 占总源码 ≤ 40%」(2026-11-12 实测 38.4%)—— app.js 可以涨,
|
||||
// 但必须涨得比 src 慢;功能继续加,占比自然往下走;
|
||||
// ③ Workbench 单函数上限**不动**(3,091)—— 那才是真坏味道的护栏,总量松它不松。
|
||||
const MAX_APP_JS_LINES = 8840 // 2026-11-17:市场请求改走原生 HTTP(+2 行 helper) // 2026-11-17 桌面版:插件市场(索引拉取/下载/sha256/写入 plugins/)约 +53 行;待抽到 src/runtime-plugin-market.js 后回调
|
||||
const MAX_APP_JS_LINES = 8890 // 2026-11-17 P3:开发者模式本地插件加载器(+37 行) // 2026-11-17:市场请求改走原生 HTTP(+2 行 helper) // 2026-11-17 桌面版:插件市场(索引拉取/下载/sha256/写入 plugins/)约 +53 行;待抽到 src/runtime-plugin-market.js 后回调
|
||||
const MAX_APP_JS_SHARE = 0.40
|
||||
|
||||
// ── 历史记账(供回溯,逐条保留)──────────────────────────────────────────────
|
||||
|
||||
Reference in new issue
Block a user