fix(image-annotate): loadImage 不再 fetch(dataURL)(宿主 CSP connect-src 不含 data:)

带 CSP 的真站 e2e 抓出:编辑器 loadImage 用 fetch(dataURL) 转 blob URL,被
connect-src 'self' https: … 拦下 → 每次打开编辑器都产生一次 CSP 违规
(靠上游 catch 回退才没坏,功能正常、只在控制台报错)。mock 页无 CSP,永远测不出。

改为纯本地解码 atob → Uint8Array → Blob → blobURL,行为与上游一致(同样拿到
blob URL、同样载入后 revoke),且不依赖 CSP/网络。这是相对上游编辑器唯一的移植改动。

版本 1.0.0 → 1.0.1(产物字节已变,按语义升版并已在 KV 重新发布)。

顺带:
- 新增 tools/e2e-site.mjs:带 CSP 真站端到端(真 KV + 浏览器 SRI + 漂浮菜单 →
  编辑器 → 覆盖/新建)。开发用,不进 CI(CI 仍只跑 npm run validate)。
- README:写清唯一的移植改动与原因;发布段补实测踩到的坑——发布器用传入文件
  「重建」清单,必须把所有插件文件一起传,否则别的插件会被挤掉。
This commit is contained in:
qiqi committed 2026-10-19 14:13:44 +08:00
1 parent d99173321e
commit 320cd6e4d0
5 files changed
+227 -7

No files matched your search

+22 -2
View File
@@ -5,9 +5,16 @@
编辑器**移植自** `iwb-plaus` 仓库的 `iwb-cutout-extension`(纯 Canvas 2D、零第三方库):
- 源:`/Users/qiqi/open/github/iwb-plaus/iwb-cutout-extension/src/editor/`(11 个模块)+ `src/shared/{image-math,layer-logic}.js`
- 差异:只有「宿主胶水」(`plugin/glue.js`、`plugin/entry.js`)是新写的;编辑器模块与样式**逐字移植**,便于日后回灌上游。
- 差异:只有「宿主胶水」(`plugin/glue.js`、`plugin/entry.js`)是新写的;编辑器模块与样式**逐字移植**,便于日后回灌上游 —— **唯一例外见下**。
- 原扩展的 CSS 由 `manifest.json` 的 `content_scripts.css` 注入;插件没有 manifest,改为构建时以字符串内联、运行时注入 `<style>`。
### 移植改动(唯一一处)
`plugin/editor/dom.js` 的 `loadImage()`:上游用 `fetch(dataURL)` 把 dataURL 转成 blob URL(避免 `img.src` 在整个编辑会话里
持有几十 MB 的 base64 字符串)。但宿主 CSP 是 `connect-src 'self' https: …`,**不含 `data:`** ⇒ `fetch(data:)` 必被浏览器拦,
每次打开编辑器都产生一次 CSP 违规(上游的 `catch` 回退让它「还能用」,所以功能看起来正常、只在控制台报错)。
现改为**纯本地解码**(`atob` → `Uint8Array` → `Blob` → blob URL),与上游行为一致(同样拿到 blob URL),且不依赖 CSP/网络。
> 这类问题**只有带 CSP 的真站能测出来**(无 CSP 的 mock 页永远绿)。真实站点用例见 `image-annotate/tools/e2e-site.mjs`。
## 入口
- **节点漂浮菜单**「标注 / 修图」(`ref` / `out` / `gen` / `layer` 节点)
- 右键菜单「插件命令 → 标注 / 修图:选中节点」
@@ -43,6 +50,19 @@ npm run validate # 契约校验
```bash
cd /Users/qiqi/open/github/image-workbench-web
cp /Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js /tmp/plugin-image-annotate.js
node scripts/plugins-publish.mjs /tmp/plugin-image-annotate.js --upload --version image-annotate=1.0.0
# ⚠️ 必须把所有插件文件一起传入:发布器用「传入的文件」重建清单,不做合并。
# 只传自己 → 别的插件会从 plugins/index.json 里消失(已实测踩到,靠 git checkout 复原)。
cp /Users/qiqi/open/github/iwb-plugins/xianyi-cutout/src/index.js /tmp/plugin-xianyi-cutout.js
node scripts/plugins-publish.mjs /tmp/plugin-image-annotate.js /tmp/plugin-xianyi-cutout.js \
--version image-annotate=1.0.1 # 默认 dry-run,检查 diff 后再加 --upload
```
发布后刷新即生效(KV 为测试站/正式站共享;新插件在插件管理里**默认未启用**,需手动开启)。
## 验证(可选,开发用)
`tools/e2e-site.mjs`:**带 CSP 的真实站点**端到端(真 KV 加载 + 浏览器 SRI + 漂浮菜单 → 编辑器 → 覆盖/新建)。
需要 Playwright(可从宿主仓 `node_modules` 或全局解析),**不进 CI**(本仓 CI 只跑 `npm run validate`,不联网、无依赖)。
```bash
IWB_BASE_URL=https://test.image-workbench-web.pages.dev node image-annotate/tools/e2e-site.mjs
```
> 为什么值得留着:mock 页没有 CSP,`connect-src` 类问题(如 `fetch(dataURL)`)在 mock 下永远绿,只有真站能抓出来。
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@iwb-plugin/image-annotate",
"private": true,
"version": "1.0.0",
"version": "1.0.1",
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
"ibwPlugin": {
"id": "image-annotate",
+23 -2
View File
@@ -179,6 +179,26 @@ import { bindEvents } from './events.js'
}
// ============ 图片加载 ============
/**
* 把 base64 dataURL 本地解码成 Blob(不经过 fetch)。
*
* [插件移植改动] 上游用 `fetch(dataURL)` 转 blob URL,但宿主 CSP 是
* `connect-src 'self' https: http://127.0.0.1:30092 http://localhost:30092` —— 不含 `data:`,
* 于是每次 loadImage 都会触发一次 CSP 违规(上游的 catch 回退让它「还能用」,但控制台每次都报错)。
* 这里改为纯本地解码,行为与上游一致(同样拿到 blob URL),且不依赖网络/CSP。
*/
function dataUrlToBlob(dataUrl) {
const comma = dataUrl.indexOf(',')
if (comma < 0) return null
const meta = dataUrl.slice(0, comma)
if (!/;base64/i.test(meta)) return null
const mime = (/^data:([^;,]+)/.exec(meta) || [])[1] || 'image/png'
const bin = atob(dataUrl.slice(comma + 1))
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
return new Blob([bytes], { type: mime })
}
/**
* dataURL 一律先转 blob URL 再喂给 Image:img.src 直接挂 dataURL 会让
* 元素在整个编辑会话期间持有一份几十 MB 的字符串(4K 源图 ≈44MB),而
@@ -190,10 +210,11 @@ import { bindEvents } from './events.js'
let revokeUrl = null
if (typeof src === 'string' && src.slice(0, 5) === 'data:') {
try {
const blob = await (await fetch(src)).blob()
const blob = dataUrlToBlob(src)
if (!blob) throw new Error('dataURL 不是 base64')
useSrc = URL.createObjectURL(blob)
revokeUrl = useSrc
} catch (e) { useSrc = src } // fetch 不可用/失败:回落原 dataURL
} catch (e) { useSrc = src } // 解码不可用/失败:回落原 dataURL
}
try {
return await new Promise((resolve, reject) => {
+14 -2
View File
@@ -9,7 +9,7 @@
var __IWB_ANNOTATE_MANIFEST__ = {
id: 'image-annotate',
name: '标注 / 修图',
version: '1.0.0',
version: '1.0.1',
apiVersion: 1,
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
}
@@ -1211,12 +1211,24 @@ var __IWB_ANNOTATE_MANIFEST__ = {
S.overlayCtx = S.overlayCanvas.getContext("2d");
bindEvents();
}
function dataUrlToBlob(dataUrl) {
const comma = dataUrl.indexOf(",");
if (comma < 0) return null;
const meta = dataUrl.slice(0, comma);
if (!/;base64/i.test(meta)) return null;
const mime = (/^data:([^;,]+)/.exec(meta) || [])[1] || "image/png";
const bin = atob(dataUrl.slice(comma + 1));
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return new Blob([bytes], { type: mime });
}
async function loadImage(src) {
let useSrc = src;
let revokeUrl = null;
if (typeof src === "string" && src.slice(0, 5) === "data:") {
try {
const blob = await (await fetch(src)).blob();
const blob = dataUrlToBlob(src);
if (!blob) throw new Error("dataURL 不是 base64");
useSrc = URL.createObjectURL(blob);
revokeUrl = useSrc;
} catch (e) {
+167
View File
@@ -0,0 +1,167 @@
// 真实站点端到端(开发用,不进 CI)。
//
// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被
// `connect-src 'self' https: …` 拦掉)在 mock 下永远绿,只有带 CSP 的真站能抓出来。
// 它不 mock /plugins/*:走真实 KV + 浏览器 SRI 校验 + 真实画布桥。
//
// 运行:
// node image-annotate/tools/e2e-site.mjs
// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-annotate/tools/e2e-site.mjs
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/image-annotate/tools
const REPO = path.resolve(HERE, '../..') // <repo>
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:')
console.error(' npm i -D playwright # 本仓或宿主仓皆可')
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node image-annotate/tools/e2e-site.mjs')
process.exit(2)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-annotate/package.json'), 'utf8')).version
const CFG = { providers: [], canvas: {} }
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const poll = async (fn, timeout = 25000, step = 250) => {
const end = Date.now() + timeout
for (;;) {
let v
try { v = await fn() } catch { v = false }
if (v) return v
if (Date.now() > end) return false
await new Promise((r) => setTimeout(r, step))
}
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } })
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
// 造一张真实的 96x64 PNG 作为节点图片
await page.goto('about:blank')
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 96; c.height = 64
const x = c.getContext('2d')
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 96, 64)
x.fillStyle = '#ffffff'; x.fillRect(20, 12, 56, 40)
return c.toDataURL('image/png')
})
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
const ws = JSON.parse(JSON.stringify(d.ws))
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
localStorage.setItem('iwb_plugins', JSON.stringify({ 'image-annotate': { enabled: true, settings: {}, data: {} } }))
}, { cfg: CFG, ws: WS, png: PNG })
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
// ---------- 1) 真实 KV 加载 + SRI + 启用 ----------
const active = await poll(async () => page.evaluate(() => {
const p = window.IWBPluginHost.list().find((x) => x.id === 'image-annotate')
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
}))
check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active))
check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' })))
check('插件脚本用 SRI(sha256) 加载', scripts.some((s) => /plugin-image-annotate\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
// ---------- 2) 打开工作区 + 节点存在 ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
// ---------- 3) 入口:节点漂浮菜单(回落右键插件命令)----------
const openEditor = async () => {
await page.locator('.iwb-node[data-node-id="r1"]').click()
const btn = page.locator('.iwb-node-floatbar button[title="标注 / 修图"]')
if (await btn.count()) { await btn.click(); return '漂浮菜单' }
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '标注 / 修图:选中节点' }).click()
return '右键命令'
}
const entry = await openEditor()
check('节点入口可触发(漂浮菜单或右键命令)', true, entry)
// ---------- 4) 编辑器打开(真实 CSP 下注入样式)----------
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 })
const opened = await page.evaluate(() => {
const el = document.querySelector('#iwb-editor-overlay')
const style = document.getElementById('iwb-annotate-style')
return {
display: getComputedStyle(el).display,
position: getComputedStyle(el).position,
zIndex: getComputedStyle(el).zIndex,
bg: getComputedStyle(el).backgroundColor,
styleInjected: Boolean(style && style.textContent.includes('.iwb-editor-')),
}
})
check('编辑器浮层可见', opened.display === 'flex' && opened.position === 'fixed')
check('样式注入生效(CSP unsafe-inline)', opened.styleInjected)
check('浮层压住宿主 UI', Number(opened.zIndex) >= 999998, 'z=' + opened.zIndex + ' bg=' + opened.bg)
// ---------- 5) 覆盖:回写真机画布 ----------
await page.mouse.move(400, 300)
await page.mouse.down()
await page.mouse.move(760, 520, { steps: 8 })
await page.mouse.up()
await page.locator('[data-action="replace"]').click()
const replaced = await poll(async () => page.evaluate((orig) => {
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
const n = (ws.nodes || []).find((x) => x.id === 'r1')
if (!n) return false
const v = n.data && (typeof n.data.data === 'string' ? n.data.data : (n.data.data && (n.data.data.__blob || JSON.stringify(n.data.data))))
return (ws.nodes.length === 1 && v && v !== orig) ? { nodes: ws.nodes.length, changed: true } : false
}, PNG))
check('「覆盖」写回原节点(节点数不变、内容已变)', Boolean(replaced), JSON.stringify(replaced))
check('编辑器导出后关闭', (await page.locator('#iwb-editor-overlay').isVisible().catch(() => false)) === false)
// ---------- 6) 新建:真机画布新增节点 ----------
await openEditor()
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 })
await page.locator('[data-action="newNode"]').click()
const created = await poll(async () => page.evaluate(() => {
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
return (ws.nodes || []).length === 2 ? { nodes: 2 } : false
}))
check('「新建」在真机画布新增节点', Boolean(created), JSON.stringify(created))
await page.locator('.iwb-canvas').waitFor({ state: 'visible' })
check('画布渲染出 2 个节点', (await page.locator('.iwb-node').count()) === 2)
// ---------- 7) 无 CSP / 运行时错误 ----------
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)