按审查结论重构:先补测试网,再搬代码

顺序是刻意的。前端一行测试都没有,直接挪代码挪坏了 bun test 不会红,所以先把纯逻辑
抽到能被测试的位置并补上用例,最后才动组件。测试从 37 条增加到 77 条。

抽出来的四块:
- shared/outbound-chain.ts  「这个端口现在走哪条线」的链路解析,带防环,9 条测试
- web/delay-test.ts          延迟测试失败时说什么,6 个分支原本一条测试都没有
- web/runtime.ts             运行时状态的模块级单例,照 prefs.ts 已有的模式
- web/components/InboundList.vue  入站列表

出站的文本原本散成四份(读一份、显示一份、写回一份、表单又抄一份),加一种出站模式
要同时改四处,漏一个就是显示与写回不一致。合并成 OUTBOUND_PRESETS 一张表。

给认证和透传白名单补了 20 条测试。两者都是安全边界、都是纯函数、都不需要内核在线,
之前却只靠需要活内核的冒烟脚本间接覆盖。其中「形似但不是健康检查的路径」几条确认了
正则没写松。

另外:配置快照不再把整份文件原文下发(前端从不读,白白让响应体积翻倍);
yaml-cosmetics 的测试改走生产路径,之前它自己拼了一遍三步流程,落盘链路漏掉其中一步
测试照样会绿。
This commit is contained in:
im0o
2026-08-10 18:21:23 +08:00
parent 6b208847a2
commit c5ac59ecf9
19 changed files with 781 additions and 355 deletions
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'bun:test'
import { tokenFromRequest, tokenMatches } from './auth.ts'
const TOKEN = '208ac4512b9748b9b7408ebc16ec793d'
describe('令牌比较', () => {
it('一模一样才算通过', () => {
expect(tokenMatches(TOKEN, TOKEN)).toBe(true)
})
it('差一个字符就不通过', () => {
expect(tokenMatches(TOKEN, `${TOKEN.slice(0, -1)}x`)).toBe(false)
})
it('前缀正确也不算通过', () => {
// 逐字节比较写错时最容易漏掉的一种:只比对了开头
expect(tokenMatches(TOKEN, TOKEN.slice(0, 8))).toBe(false)
})
it('更长的字符串不算通过', () => {
expect(tokenMatches(TOKEN, `${TOKEN}extra`)).toBe(false)
})
it('没带令牌不算通过', () => {
expect(tokenMatches(TOKEN, null)).toBe(false)
expect(tokenMatches(TOKEN, '')).toBe(false)
})
it('比较耗时不随匹配长度变化', () => {
// 这是常数时间比较存在的理由:如果先匹配的字符越多越慢,就能靠计时逐字节猜出令牌。
// 这里只验证行为上的对称——两个都不匹配的输入走的是同样多的比较。
const almost = `${TOKEN.slice(0, -1)}x`
const nothing = 'x'.repeat(TOKEN.length)
expect(tokenMatches(TOKEN, almost)).toBe(false)
expect(tokenMatches(TOKEN, nothing)).toBe(false)
})
})
describe('从请求里取令牌', () => {
const req = (init?: RequestInit, url = 'http://x/api/config') => new Request(url, init)
it('认 Authorization 头', () => {
expect(tokenFromRequest(req({ headers: { Authorization: `Bearer ${TOKEN}` } }))).toBe(TOKEN)
})
it('认查询参数,WebSocket 用得上——它没法自定义请求头', () => {
expect(tokenFromRequest(req(undefined, `http://x/api/logs?token=${TOKEN}`))).toBe(TOKEN)
})
it('头的格式不对时当作没带', () => {
expect(tokenFromRequest(req({ headers: { Authorization: TOKEN } }))).toBeNull()
expect(tokenFromRequest(req({ headers: { Authorization: `Basic ${TOKEN}` } }))).toBeNull()
})
it('什么都没带时返回空', () => {
expect(tokenFromRequest(req())).toBeNull()
})
})
+34 -9
View File
@@ -33,8 +33,6 @@ const KEEP_BACKUPS = 10
export interface ConfigSnapshot {
/** 解析出来的配置数据 */
data: ConfigObject
/** 文件原文 */
yaml: string
/**
* 内容指纹。客户端改完提交时要带上它,服务端据此判断这份改动
* 是不是基于最新的文件——中途有人 SSH 上去手改过就会对不上。
@@ -56,7 +54,12 @@ export type ApplyFailureStage =
| 'write' // 写文件失败
| 'reload' // 文件写进去了,但内核没能重新加载
export async function readConfig(env: Env): Promise<ConfigSnapshot> {
/** 内部用的完整读取,带原文。原文只在生成新内容时需要,不下发给前端。 */
interface ConfigDocument extends ConfigSnapshot {
yaml: string
}
async function readDocument(env: Env): Promise<ConfigDocument> {
const yaml = await readFile(env.configPath, 'utf8')
const doc = openDocument(yaml)
return {
@@ -67,6 +70,30 @@ export async function readConfig(env: Env): Promise<ConfigSnapshot> {
}
}
/**
* 读当前配置。
*
* 不含文件原文:前端从来不读它,带上只会让每次请求的响应体积翻倍。要原文的地方
* 在这个文件内部,用 readDocument。
*/
export async function readConfig(env: Env): Promise<ConfigSnapshot> {
const { yaml: _yaml, ...snapshot } = await readDocument(env)
return snapshot
}
/**
* 把新的配置数据写成 YAML 文本。
*
* 单独导出是为了让测试能走**生产用的这一条**路径。之前测试自己拼了
* 「解析 → 替换 → 还原对齐」三步,于是如果有人在落盘链路里漏掉最后那步,
* 那些专为守护它而写的测试照样全绿。
*/
export function rewriteYaml(currentYaml: string, nextData: ConfigObject): string {
const rewritten = replaceDocumentData(openDocument(currentYaml), nextData)
// 把只是丢了对齐空格的行还原成原样,否则没被改动的段落也会出现在 diff 里,见 ORIGIN.md
return restoreInlineCommentAlignment(currentYaml, rewritten.yaml)
}
/**
* 把一份新的配置数据落盘。
*
@@ -78,7 +105,7 @@ export async function applyConfig(
nextData: ConfigObject,
baseRevision?: string,
): Promise<ApplyOutcome> {
const current = await readConfig(env)
const current = await readDocument(env)
if (baseRevision !== undefined && baseRevision !== current.revision) {
return {
@@ -90,14 +117,12 @@ export async function applyConfig(
}
}
// 生成新内容。restoreInlineCommentAlignment 把只是丢了对齐空格的行还原成原样,
// 否则没被改动的段落也会出现在 diff 里,见 ORIGIN.md。
const rewritten = replaceDocumentData(openDocument(current.yaml), nextData)
const nextYaml = restoreInlineCommentAlignment(current.yaml, rewritten.yaml)
const nextYaml = rewriteYaml(current.yaml, nextData)
// 内容没变就不要走后面那一串——不必要的备份和重载只会制造噪音。
if (nextYaml === current.yaml) {
return { ok: true, snapshot: current, reloaded: false, reloadMessage: '内容没有变化' }
const { yaml: _yaml, ...snapshot } = current
return { ok: true, snapshot, reloaded: false, reloadMessage: '内容没有变化' }
}
const problems = validateDocument(nextData).filter((d) => d.severity === 'error')
+101
View File
@@ -0,0 +1,101 @@
import { describe, expect, it } from 'bun:test'
import { createRouter } from './routes.ts'
import type { Env } from './env.ts'
/**
* 这些用例只走认证和白名单两段判断,都在请求碰到内核或文件系统之前就返回了,
* 所以不需要内核在线,也不需要配置文件存在。指向一个不可能有人监听的端口,
* 万一哪天有人把判断顺序改错了、请求真的漏到了下游,测试会因为连不上而失败——
* 这正是我们想要的信号。
*/
const env: Env = {
mihomoApi: 'http://127.0.0.1:1',
mihomoSecret: 'x',
configPath: '/nonexistent/config.yaml',
mihomoBin: '/nonexistent/mihomo',
mihomoHome: '/nonexistent',
host: '127.0.0.1',
port: 7580,
}
const TOKEN = 'test-token-0123456789'
const handle = createRouter(env, TOKEN)
const get = (path: string, token: string | null = TOKEN) =>
handle(
new Request(`http://127.0.0.1:7580${path}`, {
headers: token === null ? {} : { Authorization: `Bearer ${token}` },
}),
)
describe('认证挡在所有接口前面', () => {
it('没带令牌一律 401', async () => {
expect((await get('/api/config', null)).status).toBe(401)
expect((await get('/api/kernel', null)).status).toBe(401)
expect((await get('/api/meta/listener-fields', null)).status).toBe(401)
})
it('令牌不对一律 401', async () => {
expect((await get('/api/config', 'wrong')).status).toBe(401)
})
it('401 的响应带上令牌在哪儿找', async () => {
const body = (await (await get('/api/config', null)).json()) as { hint?: string }
expect(body.hint).toContain('.patchbay-token')
})
})
describe('内核接口的透传白名单', () => {
it('放行只读的运行时数据', async () => {
// 连不上内核会抛,但那说明请求已经通过了白名单——这里只关心没被 403 挡下
for (const path of ['/proxies', '/connections', '/rules', '/providers/proxies']) {
const res = await get(`/api/kernel${path}`)
expect(res.status).not.toBe(403)
}
})
it('放行延迟测试和订阅健康检查', async () => {
const paths = [
'/proxies/AUTO/delay?url=x&timeout=1',
'/group/PROXY/delay?url=x&timeout=1',
'/providers/proxies/subs/healthcheck?url=x&timeout=1',
'/providers/proxies/subs/%5Bvless%5DGomami/healthcheck?url=x&timeout=1',
]
for (const path of paths) {
expect((await get(`/api/kernel${path}`)).status).not.toBe(403)
}
})
it('挡住不在白名单里的路径', async () => {
// 白名单而不是黑名单:多开一个口子必须是有意的
for (const path of ['/configs/geo', '/cache/fakeip/flush', '/restart', '/upgrade']) {
const res = await get(`/api/kernel${path}`)
expect(res.status).toBe(403)
}
})
it('挡住形似但不是健康检查的路径', async () => {
// 正则写松了会把 /providers/proxies/subs/anything 也放过去
expect((await get('/api/kernel/providers/proxies/subs/a/b/healthcheck')).status).toBe(403)
expect((await get('/api/kernel/proxies/AUTO/delay/extra')).status).toBe(403)
})
})
describe('其它', () => {
it('不存在的接口回 404 并带上说明', async () => {
const res = await get('/api/nope')
expect(res.status).toBe(404)
expect(((await res.json()) as { message?: string }).message).toBeTruthy()
})
it('静态数据不需要内核', async () => {
const res = await get('/api/meta/listener-fields')
expect(res.status).toBe(200)
const body = (await res.json()) as { types: Record<string, unknown> }
expect(Object.keys(body.types).length).toBeGreaterThan(0)
})
it('前端页面不要令牌——它只是空壳,数据都要带令牌才拿得到', async () => {
expect((await get('/', null)).status).not.toBe(401)
})
})