404 不是 bug。内核的 /proxies 只返回全局名字表(内置出站、自有线路、策略组),
订阅线路不在里面——跟「订阅线路不能被入站直接引用」是同一条约束,我没想到它同样
适用于运行时接口。所以 /proxies/{订阅线路}/delay 一律 404,而订阅线路的卡片也一直
没有协议和延迟,因为那些数据同样查不到。
现在运行时状态从两处合成:/proxies 给内置出站和策略组,/providers/proxies 给订阅线路
(它返回的线路本来就带完整的协议和延迟历史)。测速按线路归属选接口,订阅线路走
{订阅}/{线路}/healthcheck。实测该接口对同一条线路返回 200 和 325 毫秒。
155 lines
6.7 KiB
TypeScript
155 lines
6.7 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, selectProxy } from './kernel.ts'
|
|
import { tokenFromRequest, tokenMatches } from './auth.ts'
|
|
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
|
import type { Env } from './env.ts'
|
|
|
|
/**
|
|
* 延迟测试。名字里可能有斜杠和中文,所以按前缀匹配而不是列进上面那个精确白名单。
|
|
* 它是 GET 但会真的发起网络连接,属于「读」里比较重的一类,单独列出来提醒这一点。
|
|
*/
|
|
const DELAY_PATH = /^\/(proxies|group)\/.+\/delay$/
|
|
|
|
/**
|
|
* 订阅线路的健康检查。
|
|
*
|
|
* 订阅线路不在内核的全局名字表里,所以 /proxies/{名字}/delay 对它们一律 404——
|
|
* 要测只能从它所属的订阅进去。整条订阅测用 {订阅}/healthcheck,单条用 {订阅}/{线路}/healthcheck。
|
|
*/
|
|
const HEALTHCHECK_PATH = /^\/providers\/proxies\/[^/]+(\/[^/]+)?\/healthcheck$/
|
|
|
|
/** 允许透传的管理接口路径。白名单而不是黑名单——多开一个口子要有意为之。 */
|
|
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:服务端或内核的问题
|
|
}
|
|
|
|
/** 打包后的前端。开发时前端由 Vite 提供并把 /api 转发过来,走不到这里。 */
|
|
const WEB_DIST = new URL('../web-dist/', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')
|
|
|
|
/**
|
|
* 静态文件不需要令牌——它们只是一个空壳,所有数据都要带令牌才拿得到。
|
|
* 单页应用的路由由前端接管,所以找不到的路径一律回 index.html。
|
|
*/
|
|
async function serveStatic(path: string): Promise<Response> {
|
|
const target = Bun.file(WEB_DIST + (path === '/' ? 'index.html' : path.slice(1)))
|
|
if (await target.exists()) return new Response(target)
|
|
|
|
const shell = Bun.file(`${WEB_DIST}index.html`)
|
|
if (await shell.exists()) return new Response(shell)
|
|
return new Response('前端还没打包。先运行 bun run build,或者开发时用 bun run dev:web。', {
|
|
status: 404,
|
|
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
|
})
|
|
}
|
|
|
|
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 serveStatic(path)
|
|
|
|
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))
|
|
}
|
|
|
|
// 切换某个策略组当前选中哪个成员。这是白名单里唯一的写操作,单独开而不是放开整个透传:
|
|
// 它只改内核的运行时状态,不碰配置文件,而且是这个工具最日常的动作。
|
|
const selectMatch = /^\/api\/kernel\/proxies\/([^/]+)$/.exec(path)
|
|
if (selectMatch && req.method === 'PUT') {
|
|
const group = decodeURIComponent(selectMatch[1]!)
|
|
const body = (await req.json()) as { name?: string }
|
|
if (!body.name) return json({ error: '请求里没有 name 字段' }, 400)
|
|
const upstream = await selectProxy(env, group, body.name)
|
|
return upstream.ok
|
|
? json({ ok: true })
|
|
: json({ error: upstream.message || `内核拒绝了这次切换` }, 422)
|
|
}
|
|
|
|
if (path.startsWith('/api/kernel/') && req.method === 'GET') {
|
|
const target = path.slice('/api/kernel'.length)
|
|
const allowed =
|
|
READABLE_KERNEL_PATHS.has(target) || DELAY_PATH.test(target) || HEALTHCHECK_PATH.test(target)
|
|
if (!allowed) {
|
|
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)
|
|
}
|
|
}
|