Files
image-workbench-desktop/scripts/plugins-publish.mjs
T

298 lines
15 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.
// A2 插件发布:为每个插件文件算 SHA-256(SRI integrity)→ 以内容寻址名 plugin-<id>.<hash12>.js 入库 → 写 plugins/index.json →(可选)上传 KV。
//
// 用法:
// node scripts/plugins-publish.mjs <plugin-<id>.js ...> [--out plugins/index.json] [--kv-id <namespaceId>] [--version <id>=<ver>] [--upload] [--prune]
// node scripts/plugins-publish.mjs --gc [--delete] [--keep <id>] # 列出(并删除)KV 里线上清单不再引用的陈旧插件键
// --keep 用于「归档保留」的插件(如 ai-chat:移出清单但字节留 KV 待启用),可重复。
//
// 默认 **dry-run**:只写本地清单并打印计划;只有显式 --upload 才会写线上 KV。
//
// 上传走 **Cloudflare REST API**(2026-11-03 起),不再 spawn `npx wrangler`:
// PUT /accounts/<acct>/storage/kv/namespaces/<ns>/values/<urlenc key>
// GET /accounts/<acct>/storage/kv/namespaces/<ns>/values/<urlenc key>
// GET /accounts/<acct>/storage/kv/namespaces/<ns>/keys?prefix=plugins/
// DELETE /accounts/<acct>/storage/kv/namespaces/<ns>/bulk (body = key 数组)
// 原因:wrangler v3/v4 的子命令名不同(`kv:key put` / `kv key put`),靠 spawnSync 传参数永远踩版本坑。
// 凭据:CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID;macOS 上缺失时自动回退读钥匙串
// (服务名 CLOUDFLARE_PAGES_TOKEN / CLOUDFLARE_ACCOUNT_ID)。token 需 **Account → Workers KV Storage → Edit**。
//
// version 默认从既有 --out 清单里按 id 保留;要改版本用 --version <id>=<ver>。
// 清单**默认与既有清单合并**:本次未传入的插件原样保留(同 id 覆盖)。要缩减清单必须显式 --prune
// (2026-11-03:旧版只按命令行文件重建 ⇒ 单发 style-source 就把另外 5 个抹掉,插件管理页只剩 1 个)。
// 运行时宿主读 /plugins/index.json 的 integrity,用 <script integrity> 交给浏览器强制校验(不符即拒绝执行)。
//
// 存储名为内容寻址:storedNameOf(id, bytes) = plugin-<id>.<sha256前12位hex>.js。同字节 ⇒ 同名(幂等);内容变 ⇒ 名变。
// 因此 Pages Function 可对带哈希文件名发 `cache-control: public, max-age=31536000, immutable`。
// 内容变化后 KV 会同时保留**新旧哈希键**(旧键不再被清单引用)⇒ 用 --gc 清理(默认只列出,加 --delete 才删)。
import { createHash } from 'node:crypto'
import { spawnSync } from 'node:child_process'
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'
import { basename, dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const CF_API = 'https://api.cloudflare.com/client/v4'
const REQ_TIMEOUT_MS = 30000
export const integrityOf = (buffer) => 'sha256-' + createHash('sha256').update(buffer).digest('base64')
export const idFromFile = (file) => {
const base = basename(String(file))
const m = /^plugin-([a-z][a-z0-9-]{2,31})\.js$/.exec(base)
return m ? m[1] : ''
}
// 内容寻址存储名:同 id + 同字节 ⇒ 同名(幂等);字节变 ⇒ 名变 ⇒ 客户端永不拿到陈旧缓存
export const storedNameOf = (id, buffer) => {
if (!/^[a-z][a-z0-9-]{2,31}$/.test(String(id))) throw new Error('非法插件 id:' + id)
return 'plugin-' + id + '.' + createHash('sha256').update(buffer).digest('hex').slice(0, 12) + '.js'
}
export const buildIndex = (entries) => {
const seen = new Set()
const out = []
for (const e of entries) {
if (!e || !e.id || !e.file || !e.integrity) throw new Error('清单项缺字段:' + JSON.stringify(e))
if (seen.has(e.id)) throw new Error('插件 id 重复:' + e.id)
seen.add(e.id)
out.push({ id: e.id, file: e.file, version: e.version || '', integrity: e.integrity })
}
return out.sort((a, b) => a.id.localeCompare(b.id))
}
// 并入既有清单:本次**未提供**文件的插件予以保留(incoming 同 id 覆盖旧的)。
// 2026-11-03 事故:旧版只拿命令行文件重建清单 ⇒ 单发一个插件就把另外 5 个从清单里抹掉
// (字节还在 KV,但插件管理页只剩 1 个)。默认必须合并;确要缩减清单走 --prune。
export const mergeIndexes = (existing, incoming) => {
const incomingIds = new Set(incoming.map((e) => e.id))
const kept = (Array.isArray(existing) ? existing : []).filter((e) => e && e.id && e.file && e.integrity && !incomingIds.has(e.id))
return buildIndex([...incoming, ...kept])
}
// 陈旧键 = KV 里 plugins/ 下、但**线上清单不再引用**的键(清单自身永远保留)。
// keep 可传插件 id 或完整键(如 'ai-chat' / 'plugins/plugin-ai-chat.824397a8e54b.js'),用于**归档保留**的插件:
// ai-chat 就是「移出清单但字节留在 KV 等启用」的形态,不加 keep 会被当成垃圾。
// 纯函数便于单测;调用方必须以线上清单为准,不能用本地文件(否则本地落后时会误删)。
export const staleKeys = (keys, index, keep = []) => {
const keepSet = new Set(['plugins/index.json'])
for (const e of Array.isArray(index) ? index : []) if (e && e.file) keepSet.add('plugins/' + e.file)
const keeps = (Array.isArray(keep) ? keep : []).map(String).filter(Boolean)
const kept = (key) => keeps.some((p) => key === p || key === 'plugins/' + p || key.startsWith('plugins/plugin-' + p + '.'))
return (Array.isArray(keys) ? keys : [])
.map(String)
.filter((k) => k.startsWith('plugins/') && !keepSet.has(k) && !kept(k))
.sort()
}
const readKvId = () => {
try {
const toml = readFileSync(join(ROOT, 'wrangler.toml'), 'utf8')
const i = toml.indexOf('binding = "PLUGINS"')
if (i < 0) return ''
const m = /id = "([^"]+)"/.exec(toml.slice(i))
return m ? m[1] : ''
} catch (e) { return '' }
}
const readEntries = (outPath) => {
try {
const parsed = JSON.parse(readFileSync(outPath, 'utf8'))
const list = Array.isArray(parsed) ? parsed : (parsed && Array.isArray(parsed.plugins) ? parsed.plugins : [])
return list.filter((e) => e && e.id && e.file && e.integrity)
} catch (e) { return [] }
}
const readVersions = (outPath) => {
const map = new Map()
for (const e of readEntries(outPath)) map.set(String(e.id), String(e.version || ''))
return map
}
// —— 凭据:env 优先,macOS 回退钥匙串(本机 token 就存在那儿)——
const keychain = (service) => {
try {
const r = spawnSync('security', ['find-generic-password', '-s', service, '-w'], { encoding: 'utf8' })
return r.status === 0 ? String(r.stdout || '').trim() : ''
} catch (e) { return '' }
}
const resolveCreds = () => {
let token = String(process.env.CLOUDFLARE_API_TOKEN || '').trim()
let account = String(process.env.CLOUDFLARE_ACCOUNT_ID || '').trim()
if (!token && process.platform === 'darwin') token = keychain('CLOUDFLARE_PAGES_TOKEN')
if (!account && process.platform === 'darwin') account = keychain('CLOUDFLARE_ACCOUNT_ID')
if (!token) throw new Error('缺少 CLOUDFLARE_API_TOKEN(该 token 需 Account → Workers KV Storage → Edit)')
if (!account) throw new Error('缺少 CLOUDFLARE_ACCOUNT_ID')
return { token, account }
}
const kvBase = (creds, kvId) => CF_API + '/accounts/' + creds.account + '/storage/kv/namespaces/' + kvId
const kvValueUrl = (creds, kvId, key) => kvBase(creds, kvId) + '/values/' + encodeURIComponent(key)
const cfJson = async (creds, url, init) => {
const r = await fetch(url, Object.assign({
headers: Object.assign({ Authorization: 'Bearer ' + creds.token }, (init && init.contentType) ? { 'content-type': init.contentType } : {}),
signal: AbortSignal.timeout(REQ_TIMEOUT_MS),
}, init ? { method: init.method, body: init.body } : {}))
const text = await r.text()
let json = null
try { json = JSON.parse(text) } catch (e) { /* 非 JSON 响应 */ }
if (!r.ok || (json && json.success === false)) {
const detail = (json && json.errors && json.errors[0] && json.errors[0].message) || text.slice(0, 200) || '(空响应)'
throw new Error('Cloudflare API ' + r.status + ':' + detail)
}
return json
}
const kvPut = async (creds, kvId, key, body) => {
await cfJson(creds, kvValueUrl(creds, kvId, key), { method: 'PUT', body, contentType: 'text/plain; charset=utf-8' })
}
const kvGetText = async (creds, kvId, key) => {
const r = await fetch(kvValueUrl(creds, kvId, key), {
headers: { Authorization: 'Bearer ' + creds.token },
signal: AbortSignal.timeout(REQ_TIMEOUT_MS),
})
if (!r.ok) throw new Error('读取 KV 失败 ' + r.status + ':' + key)
return await r.text()
}
const kvListPluginKeys = async (creds, kvId) => {
const out = []
let cursor = ''
for (;;) {
const url = kvBase(creds, kvId) + '/keys?limit=1000&prefix=' + encodeURIComponent('plugins/') + (cursor ? '&cursor=' + encodeURIComponent(cursor) : '')
const json = await cfJson(creds, url)
for (const k of (json && json.result) || []) out.push(String(k.name))
cursor = String((json && json.result_info && json.result_info.cursor) || '')
if (!cursor) break
}
return out
}
const kvDeleteKeys = async (creds, kvId, keys) => {
if (!keys.length) return
await cfJson(creds, kvBase(creds, kvId) + '/bulk', { method: 'DELETE', body: JSON.stringify(keys), contentType: 'application/json' })
}
const main = async () => {
const argv = process.argv.slice(2)
const files = []
let outPath = join(ROOT, 'plugins', 'index.json')
let kvId = ''
let upload = false
let prune = false
let gc = false
let del = false
const keeps = []
const overrides = new Map()
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
if (a === '--upload') upload = true
else if (a === '--prune') prune = true
else if (a === '--gc') gc = true
else if (a === '--delete') del = true
else if (a === '--keep') keeps.push(String(argv[++i] || ''))
else if (a === '--out') outPath = resolve(argv[++i] || '')
else if (a === '--kv-id') kvId = String(argv[++i] || '')
else if (a === '--version') { const kv = String(argv[++i] || ''); const eq = kv.indexOf('='); if (eq > 0) overrides.set(kv.slice(0, eq), kv.slice(eq + 1)) }
else if (a.startsWith('--')) throw new Error('未知参数:' + a)
else files.push(a)
}
if (!files.length && !gc) throw new Error('至少给一个 plugin-<id>.js 文件(只想清理陈旧键用 --gc)')
if ((upload || gc) && !kvId) kvId = readKvId()
if (del && !gc) throw new Error('--delete 只能与 --gc 一起用(避免误删)')
const creds = (upload || gc) ? resolveCreds() : null
if ((upload || gc) && !kvId) throw new Error('未找到 KV namespace id:用 --kv-id 指定,或在 wrangler.toml 里确认 binding = "PLUGINS"')
let index = readEntries(outPath)
let entries = []
if (files.length) {
const versions = readVersions(outPath)
entries = files.map((f) => {
const abs = resolve(f)
if (!existsSync(abs)) throw new Error('文件不存在:' + abs)
const id = idFromFile(abs)
if (!id) throw new Error('文件名须为 plugin-<id>.js(id 须 ^[a-z][a-z0-9-]{2,31}$):' + basename(abs))
const bytes = readFileSync(abs)
return { id, file: storedNameOf(id, bytes), version: overrides.get(id) || versions.get(id) || '', integrity: integrityOf(bytes), abs }
})
// 默认合并:未在本次传入的插件原样保留(同 id 由新条目覆盖)
const prev = prune ? [] : readEntries(outPath)
index = mergeIndexes(prev, entries)
const kept = index.length - entries.length
mkdirSync(dirname(outPath), { recursive: true })
writeFileSync(outPath, JSON.stringify(index, null, 2) + '\n')
console.log('[plugins-publish] 已写清单 ' + outPath + '(共 ' + index.length + ' 个,本次发布 ' + entries.length + ' 个' + (kept > 0 ? ',保留既有 ' + kept + ' 个' : '') + ')')
for (const e of index) console.log(' ' + e.id + ' ' + e.file + ' ' + e.integrity)
}
const plan = () => {
console.log('[plugins-publish] 将写 KV(REST,' + kvId + '):')
for (const e of entries) console.log(' PUT plugins/' + e.file + ' (' + e.abs + ')')
if (files.length) console.log(' PUT plugins/index.json (' + outPath + ')')
}
if (!upload && !gc) {
console.log('[plugins-publish] dry-run(未上传)。加 --upload 才会写 KV:')
plan()
return
}
if (upload) {
// 只上传本次传入的插件字节(保留项已在 KV 里,无需重传)
for (const e of entries) await kvPut(creds, kvId, 'plugins/' + e.file, readFileSync(e.abs))
if (files.length) await kvPut(creds, kvId, 'plugins/index.json', readFileSync(outPath))
// 回读校验:写成功 ≠ 内容对(曾经清单被覆写成 1 条就是这么发生的)
if (files.length) {
const remote = JSON.parse(await kvGetText(creds, kvId, 'plugins/index.json'))
const a = JSON.stringify(remote)
const b = JSON.stringify(readEntries(outPath))
if (a !== b) throw new Error('回读校验失败:KV 里的 plugins/index.json 与本地清单不一致')
console.log('[plugins-publish] 回读校验通过(线上清单 ' + remote.length + ' 条与本地一致)')
}
console.log('[plugins-publish] 已上传 ' + entries.length + ' 个插件' + (files.length ? ' + 清单' : '') + ' 到 KV ' + kvId)
}
if (gc) await runGc(creds, kvId, del, keeps)
}
const runGc = async (creds, kvId, del, keeps = []) => {
// 以**线上清单**为准判定引用关系(本地清单可能落后于线上)
let online = []
try {
online = JSON.parse(await kvGetText(creds, kvId, 'plugins/index.json'))
} catch (e) {
throw new Error('GC 中止:读不到线上 plugins/index.json(' + ((e && e.message) || e) + ')——不能用本地清单猜,否则会误删')
}
const keys = await kvListPluginKeys(creds, kvId)
const stale = staleKeys(keys, online, keeps)
console.log('[plugins-publish] KV 共 ' + keys.length + ' 个 plugins/ 键,线上清单引用 ' + online.length + ' 个,陈旧 ' + stale.length + ' 个' + (keeps.length ? '(保留 ' + keeps.join(', ') + ')' : ''))
for (const k of stale) console.log(' 陈旧 ' + k)
if (!stale.length) return
const archived = stale.filter((k) => /plugin-ai-chat\./.test(k))
if (archived.length) {
console.log('[plugins-publish] ⚠️ ' + archived.join('、') + ' 属「归档但保留待启用」的插件(移出清单、字节留 KV),')
console.log(' 删掉后要重新上传字节才能再启用。要保留就加 --keep ai-chat。')
}
if (!del) {
console.log('[plugins-publish] 仅列出(未删除)。确认无误后加 --delete 真正删除:node scripts/plugins-publish.mjs --gc --delete [--keep ai-chat]')
return
}
await kvDeleteKeys(creds, kvId, stale)
console.log('[plugins-publish] 已删除 ' + stale.length + ' 个陈旧键')
}
if (process.argv[1] && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url))) {
main().catch((e) => {
console.error('[plugins-publish] ' + ((e && e.message) || e))
process.exit(1)
})
}