chore: 彻底转桌面客户端,删除网页版部署面(_headers/functions/wrangler + 相关 spec);更新清单平台解耦(v3.25.15)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m33s

This commit is contained in:
qiqi committed 2026-11-18 15:35:13 +08:00
1 parent 3fcc003738
commit cb6dcd1813
27 files changed
+160 -3808

No files matched your search

-1
View File
@@ -170,7 +170,6 @@ const minifiedCss = transformSync(fs.readFileSync(path.join(root, 'style.css'),
fs.writeFileSync(path.join(dist, 'style.css'), minifiedCss)
fs.copyFileSync(path.join(root, 'favicon.svg'), path.join(dist, 'favicon.svg'))
fs.copyFileSync(path.join(root, '_headers'), path.join(dist, '_headers'))
// PWA(2026-11-07):可安装 —— manifest + 图标(iOS 额外要 apple-touch-icon 的 PNG)
for (const f of ['manifest.webmanifest', 'icon-192.png', 'icon-512.png', 'apple-touch-icon.png']) {
fs.copyFileSync(path.join(root, f), path.join(dist, f))
+14 -15
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env bash
# 发布 Windows 更新:对 Windows 侧构建好的 *-setup.exe 重新签名(用本机正式私钥),
# 上传到 NAS,并把 windows-x86_64 条目合并进 updates/latest.json。
# 上传到 NAS,并写入 **独立** 的 updates/latest-windows.json(v3.25.15 起平台解耦:
# mac 的 latest.json 与 Windows 的 latest-windows.json 互不影响)。
#
# 用法:./scripts/publish-windows-update.sh "/path/to/image-workbench_3.25.3_x64-setup.exe"
#
@@ -38,27 +39,25 @@ echo "== 3/4 上传到 NAS"
ssh -i "$SSH_KEY" -o BatchMode=yes "$NAS_HOST" "mkdir -p $NAS_DIR/updates/windows-x86_64"
$SCP "$OUT" "$SIG_FILE" "$NAS_HOST:$NAS_DIR/updates/windows-x86_64/"
echo "== 4/4 合并 latest.json"
echo "== 4/4 写 latest-windows.json(平台独立)"
SIG=$(cat "$SIG_FILE")
URL="https://download.maqiart.eu.org/updates/windows-x86_64/image-workbench_${V}_x64-setup.exe"
export SIG URL APP_VERSION="$V"
curl -s -m 20 https://download.maqiart.eu.org/updates/latest.json -o "$WORK/latest.json" || echo '{}' > "$WORK/latest.json"
node -e '
const fs = require("fs")
const p = process.argv[1]
let cur = {}
try { cur = JSON.parse(fs.readFileSync(p, "utf8")) } catch (e) { cur = {} }
cur.version = process.env.APP_VERSION
cur.notes = cur.notes || "在线更新"
cur.pub_date = new Date().toISOString()
cur.platforms = cur.platforms || {}
cur.platforms["windows-x86_64"] = { signature: process.env.SIG, url: process.env.URL }
fs.writeFileSync(p, JSON.stringify(cur, null, 2))
console.log(" platforms:", Object.keys(cur.platforms).join(", "))
' "$WORK/latest.json"
$SCP "$WORK/latest.json" "$NAS_HOST:$NAS_DIR/updates/latest.json"
const doc = {
version: process.env.APP_VERSION,
notes: process.env.NOTES || "在线更新",
pub_date: new Date().toISOString(),
platforms: { "windows-x86_64": { signature: process.env.SIG, url: process.env.URL } },
}
fs.writeFileSync(p, JSON.stringify(doc, null, 2))
console.log(" version", doc.version)
' "$WORK/latest-windows.json"
$SCP "$WORK/latest-windows.json" "$NAS_HOST:$NAS_DIR/updates/latest-windows.json"
ssh -i "$SSH_KEY" -o BatchMode=yes "$NAS_HOST" "chmod -R a+rX $NAS_DIR"
echo "== 完成"
curl -s -m 20 https://download.maqiart.eu.org/updates/latest.json | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const j=JSON.parse(s);console.log("version",j.version);for(const k of Object.keys(j.platforms))console.log(" -",k,"sig",(j.platforms[k].signature||"").length,"bytes")})'
curl -s -m 20 https://download.maqiart.eu.org/updates/latest-windows.json | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const j=JSON.parse(s);console.log("version",j.version);for(const k of Object.keys(j.platforms))console.log(" -",k,"sig",(j.platforms[k].signature||"").length,"bytes")})'
curl -s -o /dev/null -m 60 -w "exe:%{http_code} size:%{size_download}\n" "$URL"
+52 -225
View File
@@ -1,238 +1,65 @@
/* serve-test.js —— e2e 用的本地静态服务器(v3.25.15 起脱离网页部署)
*
* 历史:本项目早期同时发布网页版(Cloudflare Pages),这个脚本会解析 `_headers` 下发 CSP、
* 并模拟 Pages Functions(/api/img、/plugins/*)。**现在是桌面客户端项目**,那些部署面已删除,
* 因此这里只保留「能跑 e2e」的最小职责:把 dist/ 当静态目录伺服。
*
* 桌面端的 CSP 由 src-tauri/tauri.conf.json 决定,e2e 不模拟 webview 的 CSP(要验就装真包)。
* 用法:node scripts/serve-test.js(IWB_LOCAL_PORT 可改端口,默认 8787)
*/
'use strict'
const http = require('http')
const fs = require('fs')
const path = require('path')
const cp = require('child_process')
const http = require('node:http')
const fs = require('node:fs')
const path = require('node:path')
const root = path.resolve(__dirname, '..')
const dist = path.join(root, 'dist')
const port = Number(process.env.IWB_LOCAL_PORT || 8787)
const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml' }
// ---------- _headers → 响应头(本地 e2e 与 Cloudflare Pages 保持一致) ----------
// 动机:线上 CSP 是 connect-src 'self' https:,会拦掉 fetch(data:...) / CDN <script> / blob: Worker。
// 本地服务器原先不解析 _headers,这类「本地过、线上挂」的缺陷永远抓不到。这里把 _headers 的
// 路径分组按 Cloudflare Pages 语义应用到响应头(/* 组作用于所有响应,其它组按前缀/通配匹配)。
// 健壮性:_headers 缺失或解析不出任何分组时**不注入**并打印一行提示,绝不让服务器启动失败。
function parseHeaderGroups(text) {
const groups = []
let current = null
for (const raw of String(text == null ? '' : text).split(/\r?\n/)) {
const line = raw.replace(/\s+$/, '')
if (!line.trim() || /^\s*#/.test(line)) continue
if (/^\s/.test(line)) {
if (!current) continue // 缩进行但没有归属路径 → 忽略
const i = line.indexOf(':')
if (i <= 0) continue
const name = line.slice(0, i).trim()
const value = line.slice(i + 1).trim().replace(/[\r\n]+/g, ' ') // 防响应头注入
if (name) current.headers.push([name, value])
continue
}
current = { path: line.trim(), headers: [] }
groups.push(current)
}
return groups
}
// Cloudflare Pages 匹配规则(够用即可):/* 与 * 全局;/a/* 前缀;其余精确匹配。
function headerGroupMatches(pattern, pathname) {
const p = String(pattern || '').trim()
if (!p || p === '*' || p === '/*') return true
if (p.endsWith('*')) return pathname.indexOf(p.slice(0, -1)) === 0
return p === pathname
}
function loadHeaderGroups() {
const candidates = [path.join(root, '_headers'), path.join(dist, '_headers')]
for (const file of candidates) {
try {
if (!fs.existsSync(file)) continue
const groups = parseHeaderGroups(fs.readFileSync(file, 'utf8')).filter((g) => g.headers.length)
if (groups.length) return { groups, file }
} catch (e) { /* 换下一个候选 */ }
}
return null
}
const loaded = loadHeaderGroups()
const headerGroups = loaded ? loaded.groups : []
const cspApplied = headerGroups.some((g) => g.headers.some(([n]) => n.toLowerCase() === 'content-security-policy'))
if (loaded) {
console.log(`[serve-test] 已从 ${path.relative(root, loaded.file) || '_headers'} 注入响应头分组 ${headerGroups.length} 个${cspApplied ? '(含 Content-Security-Policy,本地与线上 CSP 一致)' : '(未解析到 CSP)'}`)
} else {
console.log('[serve-test] 未找到/无法解析 _headers:本次不注入任何安全响应头(本地环境与线上不一致,CSP 类缺陷不会被拦住)')
}
function securityHeadersFor(pathname, base) {
const out = Object.assign({}, base)
for (const group of headerGroups) {
if (!headerGroupMatches(group.path, pathname)) continue
for (const [name, value] of group.headers) out[name] = value // 后匹配的覆盖先匹配的(与 Pages 的后者优先一致)
}
return out
}
// ---------- Pages Functions 本地模拟(2026-10-20 加,审计 H1 的护栏) ----------
//
// 动机:Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
// (https://developers.cloudflare.com/pages/configuration/headers/)—— 静态资源有 CSP/nosniff,
// 而 `/api/*` 与 `/plugins/*`(Pages Functions)**一个安全头都没有**,此前线上与本地都测不到。
// 本文件原先只服务 dist/ 静态资源 ⇒ 「本地过、线上挂」这一类缺陷**无法被 e2e 发现**。
//
// 忠实度原则(重要):Function 响应**只带 Function 自己返回的 header**,
// **绝不叠加 `_headers`** —— 线上就是这样,本地若"好心"加上 CSP 就永远测不出真实差异。
// 测试 tests/iwb-functions-headers.spec.js 用反向断言把这一点钉死。
//
// 模拟范围刻意最小:只做「Cloudflare context 形状」+「Response → Node 响应」两件事,
// 不模拟 Pages 的路由匹配、缓存、边缘网络等 —— 那些不属于本项目能控的范围。
const FUNCTION_ROUTES = [
{ prefix: '/api/img', file: 'functions/api/img.js', entry: 'onRequest' },
{ prefix: '/plugins', file: 'functions/plugins/[[path]].js', entry: 'onRequestGet' },
]
// 上游 mock(默认开):/api/img 会真的去请求外部图床(豆包/阿里云…),
// 那会让 e2e 变慢且依赖外部可达性 ⇒ 默认把上游 fetch 换成本地假图片。
// 关闭:IWB_MOCK_UPSTREAM=0(需要真连上游时用)。
const MOCK_UPSTREAM = process.env.IWB_MOCK_UPSTREAM !== '0'
// 插件 KV 的本地替身:内存 Map,内容寻址的插件文件用可预测的假字节。
const MOCK_PLUGIN_BYTES = '/* mock plugin */\n'
function mockKv() {
const store = new Map([
['plugins/index.json', JSON.stringify([{ id: 'mock-plugin', file: 'plugin-mock-plugin.0123456789ab.js', version: '1.0.0', integrity: 'sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' }])],
['plugins/plugin-mock-plugin.0123456789ab.js', MOCK_PLUGIN_BYTES],
])
return { get: async (key) => (store.has(key) ? store.get(key) : null) }
}
async function readRequestBody(req) {
if (req.method === 'GET' || req.method === 'HEAD') return undefined
const chunks = []
for await (const c of req) chunks.push(c)
return Buffer.concat(chunks)
}
const functionModules = new Map()
async function loadFunctionModule(file) {
if (functionModules.has(file)) return functionModules.get(file)
const mod = await import(path.join(root, file))
functionModules.set(file, mod)
return mod
}
// Function 响应 → Node 响应:**只透传 Function 自己的 header**(不叠加 _headers,见上方忠实度原则)
async function sendFunctionResponse(res, fnRes) {
const headers = {}
for (const [name, value] of fnRes.headers.entries()) headers[name] = value
const body = fnRes.status === 204 || fnRes.status === 304 ? Buffer.alloc(0) : Buffer.from(await fnRes.arrayBuffer())
res.writeHead(fnRes.status, headers)
res.end(body)
}
async function handleFunction(req, res, pathname) {
const route = FUNCTION_ROUTES.find((r) => pathname === r.prefix || pathname.indexOf(r.prefix + '/') === 0)
if (!route) return false
try {
const mod = await loadFunctionModule(route.file)
const fn = mod[route.entry]
if (typeof fn !== 'function') throw new Error('入口未导出: ' + route.entry)
// 构造 Request(POST 需要 body)
const url = new URL(req.url, 'http://127.0.0.1')
const body = await readRequestBody(req)
const request = new Request(url.toString(), {
method: req.method,
headers: Object.entries(req.headers).reduce((acc, [k, v]) => { if (typeof v === 'string') acc[k] = v; return acc }, {}),
body: body && body.length ? body : undefined,
})
const ctx = {
params: { path: pathname.slice(route.prefix.length).split('/').filter(Boolean) },
env: { PLUGINS: mockKv() },
request,
}
// 上游 mock:把 Function 内部的 fetch 换成本地假响应(仅 /api/img 会用到)
const fnRes = await withMockedUpstream(async () => {
return await fn(ctx)
})
await sendFunctionResponse(res, fnRes)
} catch (e) {
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
res.end('function error: ' + String((e && e.message) || e))
}
return true
}
// 上游 mock 实现:把 fetch 指向白名单图床的请求替换为一张 1x1 PNG。
// 仅在 MOCK_UPSTREAM 开启时生效;不影响真实部署(线上跑的是 Cloudflare Functions)。
async function withMockedUpstream(fn) {
if (!MOCK_UPSTREAM) return fn()
const realFetch = globalThis.fetch
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
globalThis.fetch = async (input, init) => {
const u = String(typeof input === 'string' ? input : (input && input.url) || input)
// 非上游请求(如本地自取)放行
if (!/^https?:\/\//i.test(u)) return realFetch(input, init)
return new Response(PNG, { status: 200, headers: { 'Content-Type': 'image/png', 'Content-Length': String(PNG.length) } })
}
try {
return await fn()
} finally {
globalThis.fetch = realFetch
}
const mime = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.map': 'application/json; charset=utf-8',
}
const server = http.createServer((req, res) => {
const clean = decodeURIComponent((req.url || '/').split('?')[0])
// Pages Functions 优先(/api/* 与 /plugins/*):它们**不套用 _headers**,与线上一致
handleFunction(req, res, clean).then((handled) => {
if (handled) return
const file = path.resolve(dist, clean === '/' ? 'index.html' : '.' + clean)
if (!file.startsWith(dist + path.sep)) { res.writeHead(403, securityHeadersFor(clean, {})); return res.end('forbidden') }
fs.readFile(file, (err, data) => {
if (err) { res.writeHead(404, securityHeadersFor(clean, {})); return res.end('not found') }
const headers = securityHeadersFor(clean, { 'content-type': mime[path.extname(file)] || 'application/octet-stream' })
res.writeHead(200, headers)
res.end(data)
})
}).catch(() => {
if (!res.headersSent) { res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }) }
res.end('server error')
})
})
server.listen(port, '127.0.0.1', () => {
const cli = require.resolve('@playwright/test/cli')
// iwb-csp-gate.spec.js 是 CSP 门禁:它依赖本服务器下发的 _headers(尤其 Content-Security-Policy),
// 覆盖「blob: 源复制」与「大图压缩落库」两条真实链路,必须留在门禁里。
// 默认跑全部门禁 spec;调试时可用 IWB_E2E_SPECS(逗号分隔)只跑指定文件,避免每次都全量。
// iwb-import-4k.spec.js = 「导入图片(粘贴/拖放/上传)」路径契约(4K 导入 ⇒ 立即引用化 + 压缩到显示尺寸),
// 用户实测的真实缺陷驱动,必须留在门禁里(否则该路径会再次退化成"原图 base64 直入节点")。
// iwb-backup-config.spec.js = 「备份/还原里的设置完整性与往返一致」契约(用户实测:设置还原不回来),
// 覆盖导出源必须是真实设置、withKeys 两个方向、__KEEP__ 语义与未知字段保留,必须留在门禁里。
// iwb-duplicate-ws.spec.js = 「创建副本不丢连线 + 副本名唯一」契约(用户实测:复制画布丢连线、连续复制同名),
// 覆盖 画布→连线→回库→复制→打开副本 的真实链路,必须留在门禁里。
// iwb-resume-reload.spec.js = 「生图中刷新不丢需求」契约(用户实测:刷新后续跑横幅不出现),
// 覆盖 在途请求→刷新被标 failed→启动过滤 failed→recoverable→横幅→点继续重新发起 的链路,必须留在门禁里。
// iwb-tab-dot.spec.js = 「标签条圆点状态色」契约(用户需求:生成完成=绿、失败=红、切到画布清除)。
// iwb-resume-scope.spec.js = 「续跑范围不放大」契约(用户实测:单任务中断刷新后其他未启动任务也被新建→计划外计费)。
// iwb-resume-variants.spec.js = 「多变体只补缺张」契约(用户实测:4 变体完成 2 张后整任务被跳过,缺张永不补;继续只补缺失变体)。
const specOverride = String(process.env.IWB_E2E_SPECS || '').split(',').map((x) => x.trim()).filter(Boolean)
// 门禁 spec 不再手工维护:交给 scripts/list-e2e-specs.js 自动发现 tests/*.spec.js。
// 排除规则只有一条——下划线前缀(_*.spec.js = dev 探针),且该探针必须自带 iwb-dev-probe 标记,
// 否则 discoverSpecs 会抛错。"忘了把新 spec 加进清单"这种静默漏跑从此不可能发生。
let specs = specOverride
if (specs.length) {
console.log(`[serve-test] 使用 IWB_E2E_SPECS 覆盖:${specs.length} 个 spec`)
} else {
const discovered = require('./list-e2e-specs').discoverSpecs(path.join(root, 'tests'))
specs = discovered.specs
console.log(`[serve-test] 自动发现门禁 spec ${specs.length} 个${discovered.excluded.length ? `(排除 dev 探针 ${discovered.excluded.length}:${discovered.excluded.map((f) => path.basename(f)).join('、')})` : ''}`)
let pathname = '/'
try { pathname = decodeURIComponent(new URL(req.url, 'http://127.0.0.1').pathname) } catch (e) { pathname = '/' }
if (pathname.endsWith('/')) pathname += 'index.html'
let file = path.join(dist, pathname)
// 目录穿越防护:只允许 servicedir 内的文件
if (!file.startsWith(dist + path.sep)) {
res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })
res.end('forbidden')
return
}
const child = cp.spawn(process.execPath, [cli, 'test'].concat(specs), {
cwd: root,
stdio: 'inherit',
env: { ...process.env, IWB_BASE_URL: `http://127.0.0.1:${port}` },
fs.stat(file, (err, st) => {
if (err || !st.isFile()) {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
res.end('not found')
return
}
res.writeHead(200, {
'content-type': mime[path.extname(file)] || 'application/octet-stream',
'cache-control': 'no-store',
})
fs.createReadStream(file).pipe(res)
})
child.on('exit', (code) => { server.close(() => process.exit(code == null ? 1 : code)) })
})
server.listen(port, () => {
console.log('[serve-test] serving ' + path.relative(process.cwd(), dist) + ' at http://127.0.0.1:' + port)
console.log('[serve-test] 纯静态:不再注入 _headers / 不再模拟 Pages Functions(项目已转为桌面客户端)')
})