diff --git a/scripts/api-smoke.ts b/scripts/api-smoke.ts new file mode 100644 index 0000000..a5f7fe4 --- /dev/null +++ b/scripts/api-smoke.ts @@ -0,0 +1,104 @@ +/** + * 接口冒烟测试:对着真的服务和真的内核,把每类响应走一遍。 + * + * 重点在认证和边界——这两块出错的后果比功能不好用严重得多:令牌校验写歪了等于没有认证, + * 透传白名单漏了等于把内核的全部接口暴露出去。 + * + * 前置条件: + * 1. 本地测试内核在跑(见 .env.example) + * 2. Patchbay 在跑:bun run server/index.ts + * + * 用法:bun run scripts/api-smoke.ts [令牌] + * 不给令牌就从配置文件旁边的 .patchbay-token 读。 + */ +import { readFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { readEnv } from '../server/env.ts' +import type { ConfigObject } from '../vendor/config-editor/index.ts' + +const env = readEnv() +const base = `http://${env.host}:${String(env.port)}` +const token = + process.argv[2] ?? + (await readFile(join(dirname(env.configPath), '.patchbay-token'), 'utf8')).trim() + +let failures = 0 +function check(name: string, actual: unknown, expected: unknown) { + if (JSON.stringify(actual) === JSON.stringify(expected)) { + console.log(`✓ ${name}`) + } else { + failures += 1 + console.log(`✗ ${name}\n 期望 ${JSON.stringify(expected)},实际 ${JSON.stringify(actual)}`) + } +} + +async function call(method: string, path: string, body?: unknown, auth = true) { + const res = await fetch(base + path, { + method, + headers: { + ...(auth ? { Authorization: `Bearer ${token}` } : {}), + 'Content-Type': 'application/json', + }, + body: body === undefined ? undefined : JSON.stringify(body), + }) + const text = await res.text() + return { status: res.status, body: text ? (JSON.parse(text) as Record) : null } +} + +const clone = (v: unknown) => JSON.parse(JSON.stringify(v)) as ConfigObject + +// ── 认证与边界 ────────────────────────────────────────── +check('没带令牌被拒', (await call('GET', '/api/config', undefined, false)).status, 401) +check( + '令牌不对被拒', + (await fetch(`${base}/api/config`, { headers: { Authorization: 'Bearer wrong' } })).status, + 401, +) +check('白名单外的透传被拒', (await call('GET', '/api/kernel/configs/geo')).status, 403) +check('不存在的接口', (await call('GET', '/api/nope')).status, 404) +check('非 api 路径', (await call('GET', '/index.html')).status, 404) + +// ── 配置读写 ──────────────────────────────────────────── +const snapshot = await call('GET', '/api/config') +check('读配置', snapshot.status, 200) +const data = snapshot.body!.data as ConfigObject +const revision = snapshot.body!.revision as string + +const stale = clone(data) +stale.mode = 'global' +check( + '基准过时被拒', + (await call('PUT', '/api/config', { data: stale, baseRevision: '过时的指纹' })).status, + 409, +) + +const dangling = clone(data) +dangling.listeners = [{ name: '冒烟-断引用', type: 'mixed', port: 17899, proxy: '不存在的出站' }] +const danglingResult = await call('PUT', '/api/config', { data: dangling, baseRevision: revision }) +check('断引用被自己的检查拦下', danglingResult.status, 422) +check('拦在 self-check 这一步', danglingResult.body?.stage, 'self-check') + +const badType = clone(data) +badType.listeners = [{ name: '冒烟-怪类型', type: '不是合法类型', port: 17898 }] +const badTypeResult = await call('PUT', '/api/config', { data: badType, baseRevision: revision }) +check('非法类型被内核拦下', badTypeResult.status, 422) +check('拦在 kernel-check 这一步', badTypeResult.body?.stage, 'kernel-check') + +const good = clone(data) +good.listeners = [{ name: '冒烟-正常', type: 'mixed', port: 17896, proxy: 'PROXY' }] +const goodResult = await call('PUT', '/api/config', { data: good, baseRevision: revision }) +check('正常写入', goodResult.status, 200) +check('内核已重载', goodResult.body?.reloaded, true) + +// ── 其余 ──────────────────────────────────────────────── +check('备份列表可读', (await call('GET', '/api/config/backups')).status, 200) +check('内核状态可读', (await call('GET', '/api/kernel')).body?.online, true) +check('内核透传可用', (await call('GET', '/api/kernel/version')).status, 200) +check( + '字段表可读', + Object.keys(((await call('GET', '/api/meta/listener-fields')).body?.types ?? {}) as object).length, + 20, +) + +console.log(failures === 0 ? '\n全部通过' : `\n${String(failures)} 项没通过`) +process.exit(failures === 0 ? 0 : 1) diff --git a/server/auth.ts b/server/auth.ts new file mode 100644 index 0000000..6c1206e --- /dev/null +++ b/server/auth.ts @@ -0,0 +1,52 @@ +/** + * 访问令牌。 + * + * Patchbay 默认只监听 127.0.0.1,远程访问走 SSH 隧道。即便如此仍然要认证—— + * 同一台机器上跑着别的服务(比如容器里的进程)时,「只监听本机」并不等于「只有你能访问」。 + * + * 令牌可以用环境变量 PATCHBAY_TOKEN 指定;没指定就在首次启动时生成一个, + * 存到配置文件旁边的 .patchbay-token 里,并打印在控制台上。 + */ +import { chmod, readFile, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import type { Env } from './env.ts' + +export async function resolveToken(env: Env): Promise<{ token: string; source: string }> { + const fromEnv = Bun.env.PATCHBAY_TOKEN + if (fromEnv) return { token: fromEnv, source: '环境变量 PATCHBAY_TOKEN' } + + const path = join(dirname(env.configPath), '.patchbay-token') + try { + const saved = (await readFile(path, 'utf8')).trim() + if (saved) return { token: saved, source: path } + } catch { + // 文件不存在,往下走去生成一个 + } + + const token = crypto.randomUUID().replaceAll('-', '') + await writeFile(path, `${token}\n`, 'utf8') + // 令牌等同于密码,不该让同机器上的其他用户读到。Windows 上 chmod 基本无效,失败就算了。 + await chmod(path, 0o600).catch(() => {}) + return { token, source: `${path}(新生成)` } +} + +/** + * 常数时间比较,避免通过响应耗时逐字节猜出令牌。 + * + * 长度不同直接返回 false 会泄漏长度,但令牌长度本来就是固定且公开的,无所谓。 + */ +export function tokenMatches(expected: string, given: string | null): boolean { + if (!given || given.length !== expected.length) return false + let diff = 0 + for (let i = 0; i < expected.length; i += 1) { + diff |= expected.charCodeAt(i) ^ given.charCodeAt(i) + } + return diff === 0 +} + +/** 从请求里取令牌,支持 Authorization 头和查询参数(后者给 WebSocket 用)。 */ +export function tokenFromRequest(req: Request): string | null { + const header = req.headers.get('Authorization') + if (header?.startsWith('Bearer ')) return header.slice(7) + return new URL(req.url).searchParams.get('token') +} diff --git a/server/index.ts b/server/index.ts new file mode 100644 index 0000000..0525023 --- /dev/null +++ b/server/index.ts @@ -0,0 +1,54 @@ +/** + * 启动入口。 + * + * 启动时把该报的问题一次报清楚:环境变量缺没缺、配置文件读不读得到、内核在不在线。 + * 配置类工具最糟糕的失败方式是界面能打开、点了保存才发现根本连不上。 + */ +import { readEnv } from './env.ts' +import { resolveToken } from './auth.ts' +import { createRouter } from './routes.ts' +import { readConfig } from './config-store.ts' +import { kernelVersion } from './kernel.ts' + +const env = readEnv() +const { token, source } = await resolveToken(env) + +// 先确认配置文件读得到、解析得动。读不到就没必要往下走了。 +try { + const snapshot = await readConfig(env) + const errors = snapshot.diagnostics.filter((d) => d.severity === 'error') + console.log(`配置文件 ${env.configPath}`) + if (errors.length > 0) { + console.log(` 解析出 ${String(errors.length)} 个问题,界面上会标出来:`) + for (const e of errors) console.log(` ${e.path.join('.')}:${e.message}`) + } +} catch (error) { + console.error(`读不到配置文件 ${env.configPath}`) + console.error(String(error)) + console.error('检查 .env 里的 PATCHBAY_CONFIG 指对了没有,以及这个进程有没有读权限。') + process.exit(1) +} + +const kernel = await kernelVersion(env) +console.log( + kernel.online + ? `内核 在线 ${kernel.version ?? ''}(${env.mihomoApi})` + : `内核 连不上 ${env.mihomoApi}——界面仍然能编辑配置,但看不到订阅里的线路,也无法重载`, +) + +const handle = createRouter(env, token) +const server = Bun.serve({ + hostname: env.host, + port: env.port, + fetch: handle, +}) + +console.log(`令牌 ${token}`) +console.log(` 来自 ${source}`) +console.log(`Patchbay http://${server.hostname}:${String(server.port)}`) +if (env.host === '127.0.0.1') { + console.log(` 只监听本机。从别的机器访问请开隧道:`) + console.log(` ssh -N -L ${String(env.port)}:127.0.0.1:${String(env.port)} 用户名@这台机器`) +} else { + console.log(` ⚠ 监听在 ${env.host},本机之外也能访问。确认这是你要的。`) +} diff --git a/server/routes.ts b/server/routes.ts new file mode 100644 index 0000000..7fbb71c --- /dev/null +++ b/server/routes.ts @@ -0,0 +1,106 @@ +/** + * HTTP 接口。 + * + * 分成三类: + * /api/config* 配置文件的读写,走 config-store 那条保护链路 + * /api/kernel/* 内核状态,以及对管理接口的只读透传 + * /api/meta/* 静态数据,比如入站类型的字段表 + * + * 透传只开放 GET。写操作(切换节点、关连接)属于运行时面板的功能,等做到那一步再单独开, + * 现在不留一个「什么都能转发」的口子。 + */ +import listenerFields from '../shared/listener-fields.json' with { type: 'json' } +import { applyConfig, listBackups, readConfig, restoreBackup } from './config-store.ts' +import { kernelVersion, proxyGet } from './kernel.ts' +import { tokenFromRequest, tokenMatches } from './auth.ts' +import type { ConfigObject } from '../vendor/config-editor/index.ts' +import type { Env } from './env.ts' + +/** 允许透传的管理接口路径。白名单而不是黑名单——多开一个口子要有意为之。 */ +const READABLE_KERNEL_PATHS = new Set([ + '/version', + '/configs', + '/proxies', + '/providers/proxies', + '/rules', + '/providers/rules', + '/connections', + '/memory', +]) + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }) +} + +/** 把落盘失败的结果翻译成 HTTP 响应。状态码按「谁的问题」分。 */ +function applyFailureStatus(stage: string): number { + if (stage === 'stale') return 409 // 冲突,客户端该刷新重来 + if (stage === 'self-check' || stage === 'kernel-check') return 422 // 内容不合法 + return 500 // write / reload:服务端或内核的问题 +} + +export function createRouter(env: Env, token: string) { + return async function handle(req: Request): Promise { + const url = new URL(req.url) + const path = url.pathname + + if (!path.startsWith('/api/')) return json({ error: '没有这个接口' }, 404) + + if (!tokenMatches(token, tokenFromRequest(req))) { + return json({ error: '令牌不对。它在配置文件旁边的 .patchbay-token 里。' }, 401) + } + + // ── 配置 ──────────────────────────────────────────── + if (path === '/api/config' && req.method === 'GET') { + const snapshot = await readConfig(env) + return json(snapshot) + } + + if (path === '/api/config' && req.method === 'PUT') { + const body = (await req.json()) as { data?: ConfigObject; baseRevision?: string } + if (!body.data || typeof body.data !== 'object') { + return json({ error: '请求里没有 data 字段' }, 400) + } + const result = await applyConfig(env, body.data, body.baseRevision) + return result.ok ? json(result) : json(result, applyFailureStatus(result.stage)) + } + + if (path === '/api/config/backups' && req.method === 'GET') { + return json({ backups: await listBackups(env) }) + } + + const restoreMatch = /^\/api\/config\/backups\/([^/]+)\/restore$/.exec(path) + if (restoreMatch && req.method === 'POST') { + const name = decodeURIComponent(restoreMatch[1]!) + const result = await restoreBackup(env, name) + return result.ok ? json(result) : json(result, applyFailureStatus(result.stage)) + } + + // ── 内核 ──────────────────────────────────────────── + if (path === '/api/kernel' && req.method === 'GET') { + return json(await kernelVersion(env)) + } + + if (path.startsWith('/api/kernel/') && req.method === 'GET') { + const target = path.slice('/api/kernel'.length) + if (!READABLE_KERNEL_PATHS.has(target)) { + return json({ error: `不允许透传这个路径:${target}` }, 403) + } + const upstream = await proxyGet(env, target + url.search) + return new Response(upstream.body, { + status: upstream.status, + headers: { 'Content-Type': upstream.headers.get('Content-Type') ?? 'application/json' }, + }) + } + + // ── 静态数据 ──────────────────────────────────────── + if (path === '/api/meta/listener-fields' && req.method === 'GET') { + return json(listenerFields) + } + + return json({ error: '没有这个接口' }, 404) + } +}