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 } expect(Object.keys(body.types).length).toBeGreaterThan(0) }) it('前端页面不要令牌——它只是空壳,数据都要带令牌才拿得到', async () => { expect((await get('/', null)).status).not.toBe(401) }) })