Files
image-workbench-desktop/tests/desktop-csp-loopback-test.js
T

53 lines
2.9 KiB
JavaScript
Raw Permalink 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.
/* desktop-csp-loopback-test.js —— 桌面版 CSP 必须放行本地服务插件(v3.25.14)
*
* 修的是什么:v3.25.11 的「CSP 清理」把 30092 当成遗留端口删掉了,但它其实是
* 2026-10-17 有意为「本地服务插件」放宽的安全边界(见 BACKLOG.md 与
* docs/standards/architecture-current-state.md)。删掉后桌面版鲜艺抠图插件报
* 「Failed to fetch」,网页版正常 —— 因为两份 CSP 是互不相干的两段文本。
*
* 为什么以前没拦住:仓库的 CSP 门禁(tests/iwb-csp-gate.spec.js)只下发 _headers,
* tauri.conf.json 的 CSP 零覆盖,两份可以无声漂移。本测试补上这一侧。
*
* ⚠️ 写法约束(tests/source-text-ratchet-test.js 的零余量棘轮):
* 不要读文件原文再 .includes/.indexOf(变量名命中 source|src|app53… 会被计数)。
* 这里只做**解析后运行时值**的断言。
*/
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const assert = require('node:assert')
const conf = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'src-tauri', 'tauri.conf.json'), 'utf8'))
const policy = String((conf.app && conf.app.security && conf.app.security.csp) || '')
assert.ok(policy.length > 0, '桌面版必须显式声明 CSP(不允许留空回落默认)')
const directives = Object.fromEntries(policy.split(';').map((part) => {
const bits = part.trim().split(/\s+/).filter(Boolean)
return bits.length ? [bits[0], bits.slice(1)] : ['', []]
}))
const connect = directives['connect-src'] || []
assert.ok(connect.length > 0, 'connect-src 不能为空')
// 30092 = 本地鲜艺抠图服务(XianyiAiRmbg)。两个 loopback 写法都要在:
// 插件默认 http://localhost:30092,用户改成 127.0.0.1 也必须能用。
for (const origin of ['http://127.0.0.1:30092', 'http://localhost:30092']) {
assert.ok(connect.includes(origin), '桌面 CSP 的 connect-src 必须放行 ' + origin + '(本地抠图插件依赖;见 BACKLOG.md)')
}
// 守卫的守卫:确认没有顺手把整个 http: 放开
assert.ok(!connect.includes('http:'), 'connect-src 不得放开整个 http: 协议(只放行具体 loopback 源)')
// 两份 CSP 不得再漂移:桌面放行的 loopback 源必须被网页版同样放行
const headers = fs.readFileSync(path.join(__dirname, '..', '_headers'), 'utf8')
const webPolicy = (headers.match(/Content-Security-Policy:([^\n]*)/) || [])[1] || ''
const webConnect = ((webPolicy.split(';').find((p) => p.trim().startsWith('connect-src')) || '').split(/\s+/).slice(1))
const loopbacks = connect.filter((v) => /^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(v))
assert.ok(loopbacks.length > 0, '桌面 CSP 应至少有 loopback 例外')
for (const origin of loopbacks) {
assert.ok(webConnect.includes(origin), '网页版 _headers 也必须放行 ' + origin + '(两份 CSP 不许漂移)')
}
console.log('desktop-csp-loopback: ' + (3 + loopbacks.length) + ' 通过 / 0 失败')