239 lines
13 KiB
JavaScript
239 lines
13 KiB
JavaScript
'use strict'
|
||
|
||
const http = require('http')
|
||
const fs = require('fs')
|
||
const path = require('path')
|
||
const cp = require('child_process')
|
||
|
||
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 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('、')})` : ''}`)
|
||
}
|
||
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}` },
|
||
})
|
||
child.on('exit', (code) => { server.close(() => process.exit(code == null ? 1 : code)) })
|
||
})
|