Files
mihomo-patchbay/server/routes.ts
T
im0o ada547adf7 加上 HTTP 接口层和令牌认证
接口分三类:配置读写走保护链路,内核状态和只读透传,静态字段表。
透传用白名单而不是黑名单——写操作属于运行时面板,等做到那步再单独开,
现在不留一个什么都能转发的口子。

令牌即便在只监听本机时也强制校验:同一台机器上跑着容器和别的服务,
「只监听 127.0.0.1」不等于「只有你能访问」。比较用常数时间,避免靠响应耗时猜。

scripts/api-smoke.ts 对着真服务和真内核跑 17 项检查,端到端确认过
改配置之后内核会重载、新端口真的被监听起来。
2026-08-10 03:37:49 +08:00

107 lines
4.3 KiB
TypeScript

/**
* 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<Response> {
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)
}
}