备份存的是「改动前」,所以一条记录的 diff 两端是它自己和更新一份的 状态(最新一条对比当前文件)。行级 diff 先掐公共前后缀再做 LCS,一次 改动通常只碰几行,表撑得住;大面积不同时退化成整段删增。 合并窗做在服务端而不是前端防抖:普通保存(opts.merge)发现最新备份 还在窗内就不新建,连点删除共享一条历史、一步撤回。窗锚定在这一串的 第一下,不滚雪球;还原、导入、撤回重做不合并,各占一条。合并时没有 备份文件,重载失败的还原改用刚读出的原文写回。顺带消除了备份名只精 确到秒、同秒保存互相覆盖的隐患。
384 lines
17 KiB
TypeScript
384 lines
17 KiB
TypeScript
/**
|
|
* HTTP 接口。
|
|
*
|
|
* 分成三类:
|
|
* /api/config* 配置文件的读写,走 config-store 那条保护链路
|
|
* /api/kernel/* 内核状态,以及对管理接口的只读透传
|
|
* /api/meta/* 静态数据,比如入站类型的字段表
|
|
*
|
|
* 透传只开放 GET。写操作(切换节点、关连接)属于运行时面板的功能,等做到那一步再单独开,
|
|
* 现在不留一个「什么都能转发」的口子。
|
|
*/
|
|
import { resolve, sep } from 'node:path'
|
|
import listenerFields from '../shared/listener-fields.json' with { type: 'json' }
|
|
import { isProviderFilePath } from '../shared/provider-files.ts'
|
|
import {
|
|
applyConfig,
|
|
backupDiff,
|
|
importConfig,
|
|
listBackups,
|
|
listRedo,
|
|
readConfig,
|
|
redoConfig,
|
|
restoreBackup,
|
|
undoConfig,
|
|
} from './config-store.ts'
|
|
import { geoStatus, syncGeoFile } from './geo.ts'
|
|
import { hostInfo, probeExit } from './host.ts'
|
|
import {
|
|
kernelVersion,
|
|
proxyGet,
|
|
proxyWrite,
|
|
reloadConfig,
|
|
restartKernel,
|
|
selectProxy,
|
|
updateGeoDatabases,
|
|
} 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$/
|
|
|
|
/**
|
|
* 会持续吐数据的接口。透传它们时不能设超时。
|
|
* 内核在没有 WebSocket 升级时把这三个退化成分块的 HTTP 流,一行一个 JSON。
|
|
*/
|
|
const STREAM_PATHS = new Set(['/traffic', '/memory', '/logs'])
|
|
|
|
/**
|
|
* 允许透传的写操作。
|
|
*
|
|
* 每一条都是「只改内核运行状态、不碰配置文件」的动作,所以不走落盘那条保护链路。
|
|
* 仍然是白名单:能写的东西必须一条条列出来。
|
|
*/
|
|
const WRITABLE: Array<{ method: 'PUT' | 'DELETE'; pattern: RegExp }> = [
|
|
// 断开某条连接,或者全部断开
|
|
{ method: 'DELETE', pattern: /^\/connections(\/[^/]+)?$/ },
|
|
// 让内核重新拉取某个订阅
|
|
{ method: 'PUT', pattern: /^\/providers\/proxies\/[^/]+$/ },
|
|
// 让内核重新拉取某个规则组
|
|
{ method: 'PUT', pattern: /^\/providers\/rules\/[^/]+$/ },
|
|
]
|
|
|
|
/** 允许透传的管理接口路径。白名单而不是黑名单——多开一个口子要有意为之。 */
|
|
const READABLE_KERNEL_PATHS = new Set([
|
|
'/version',
|
|
'/configs',
|
|
'/proxies',
|
|
'/providers/proxies',
|
|
'/rules',
|
|
'/providers/rules',
|
|
'/connections',
|
|
'/memory',
|
|
'/traffic',
|
|
'/logs',
|
|
])
|
|
|
|
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。但这条**不能**用在
|
|
* 带扩展名的路径上:资源文件是带哈希的,每次打包都换名字,浏览器要是缓存了旧的
|
|
* index.html,它引用的那个 .js 就已经不存在了。这时候回 index.html 等于把一份 HTML
|
|
* 当作 JavaScript 交给浏览器,报出来的是「MIME 类型不对」——一句完全指不到病根的错误。
|
|
* 老老实实回 404,浏览器才会重新去取 index.html。
|
|
*/
|
|
const HAS_EXTENSION = /\.[a-z0-9]+$/i
|
|
|
|
async function serveStatic(path: string): Promise<Response> {
|
|
const shellHeaders = {
|
|
'Content-Type': 'text/html; charset=utf-8',
|
|
// 空壳不缓存,否则打包后旧的 index.html 会一直引用已经不存在的资源
|
|
'Cache-Control': 'no-cache',
|
|
}
|
|
|
|
const target = Bun.file(WEB_DIST + (path === '/' ? 'index.html' : path.slice(1)))
|
|
if (await target.exists()) {
|
|
return path === '/' ? new Response(target, { headers: shellHeaders }) : new Response(target)
|
|
}
|
|
|
|
if (HAS_EXTENSION.test(path)) {
|
|
return new Response(`找不到 ${path}`, {
|
|
status: 404,
|
|
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
|
})
|
|
}
|
|
|
|
const shell = Bun.file(`${WEB_DIST}index.html`)
|
|
if (await shell.exists()) return new Response(shell, { headers: shellHeaders })
|
|
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) {
|
|
const route = makeRoute(env, token)
|
|
|
|
/**
|
|
* 兜底。没有它的话,请求体不是合法 JSON、或者配置文件在运行中被删,都会抛出一个
|
|
* 没有响应体的 500,前端只能显示「请求失败(HTTP 500)」——这条链路的全部立意是
|
|
* 出事时把用户救回来,而出事时给出的偏偏是最没信息量的一句话。
|
|
*/
|
|
return async function handle(req: Request): Promise<Response> {
|
|
try {
|
|
return await route(req)
|
|
} catch (error) {
|
|
return json(
|
|
{
|
|
message: String(error),
|
|
hint: '这是 Patchbay 自身的故障,配置文件没有被改动。',
|
|
},
|
|
500,
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
function makeRoute(env: Env, token: string) {
|
|
return async function route(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({ message: '令牌不正确', hint: '它在服务端配置文件的同级目录 .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({ message: '请求缺少 data 字段' }, 400)
|
|
}
|
|
// merge:界面上的连续保存在时间窗内合并成一条历史。还原、导入不走这里
|
|
const result = await applyConfig(env, body.data, body.baseRevision, { merge: true })
|
|
return result.ok ? json(result) : json(result, applyFailureStatus(result.stage))
|
|
}
|
|
|
|
if (path === '/api/config/backups' && req.method === 'GET') {
|
|
// redo 是重做栈深度,侧栏用它决定重做按钮亮不亮
|
|
return json({ backups: await listBackups(env), redo: (await listRedo(env)).length })
|
|
}
|
|
|
|
// 撤回/重做。走 config-store 的保护链路,备份链的进出由它们自己管
|
|
if (path === '/api/config/undo' && req.method === 'POST') {
|
|
const result = await undoConfig(env)
|
|
return result.ok ? json(result) : json(result, applyFailureStatus(result.stage))
|
|
}
|
|
|
|
if (path === '/api/config/redo' && req.method === 'POST') {
|
|
const result = await redoConfig(env)
|
|
return result.ok ? json(result) : json(result, applyFailureStatus(result.stage))
|
|
}
|
|
|
|
// 配置文件原文,给「下载当前配置」用。带 attachment 让浏览器按下载处理
|
|
if (path === '/api/config/raw' && req.method === 'GET') {
|
|
const file = Bun.file(env.configPath)
|
|
return new Response(file, {
|
|
headers: {
|
|
'Content-Type': 'text/yaml; charset=utf-8',
|
|
'Content-Disposition': 'attachment; filename="config.yaml"',
|
|
},
|
|
})
|
|
}
|
|
|
|
// 上传的 YAML 替换当前配置(mode=override 整份,compatible 只搬接管段落)。
|
|
// 走 config-store 完整的保护链路
|
|
if (path === '/api/config/import' && req.method === 'POST') {
|
|
const body = (await req.json()) as { content?: string; mode?: string }
|
|
if (typeof body.content !== 'string' || body.content.trim() === '') {
|
|
return json({ message: '请求缺少 content 字段' }, 400)
|
|
}
|
|
if (body.mode !== 'override' && body.mode !== 'compatible') {
|
|
return json({ message: 'mode 必须是 override 或 compatible' }, 400)
|
|
}
|
|
const result = await importConfig(env, body.content, body.mode)
|
|
return result.ok ? json(result) : json(result, applyFailureStatus(result.stage))
|
|
}
|
|
|
|
// 一条历史记录的对比原文:这份备份(改动前)和它之后的状态(改动后)
|
|
const diffMatch = /^\/api\/config\/backups\/([^/]+)\/diff$/.exec(path)
|
|
if (diffMatch && req.method === 'GET') {
|
|
const pair = await backupDiff(env, decodeURIComponent(diffMatch[1]!))
|
|
if (!pair) return json({ message: '没有这个备份', hint: '刷新一下历史记录再试。' }, 404)
|
|
return json(pair)
|
|
}
|
|
|
|
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))
|
|
}
|
|
|
|
// ── 清单文件 ────────────────────────────────────────
|
|
// 从界面上传的订阅/规则清单,写进内核工作目录的 providers/ 下。
|
|
// 路径白名单校验 + 解析后确认没出工作目录,两道都过才落盘
|
|
if (path === '/api/provider-files' && req.method === 'POST') {
|
|
const body = (await req.json()) as { path?: string; content?: string }
|
|
if (typeof body.path !== 'string' || typeof body.content !== 'string') {
|
|
return json({ message: '请求缺少 path 或 content 字段' }, 400)
|
|
}
|
|
if (!isProviderFilePath(body.path)) {
|
|
return json({ message: `不允许写入该路径:${body.path}` }, 400)
|
|
}
|
|
const home = resolve(env.mihomoHome)
|
|
const target = resolve(home, body.path)
|
|
if (!target.startsWith(home + sep)) {
|
|
return json({ message: `不允许写入该路径:${body.path}` }, 400)
|
|
}
|
|
await Bun.write(target, body.content)
|
|
return json({ ok: true })
|
|
}
|
|
|
|
// ── 主机 ────────────────────────────────────────────
|
|
// 服务端和内核在同一台机器上,所以主机指标由 Patchbay 自己代答
|
|
if (path === '/api/host' && req.method === 'GET') {
|
|
return json(await hostInfo())
|
|
}
|
|
|
|
// 经由某个入站端口探测公网 IP。GET 但会发起真实的外网请求,和延迟测试同一类
|
|
if (path === '/api/host/exit' && req.method === 'GET') {
|
|
const port = Number(url.searchParams.get('port'))
|
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
return json({ message: 'port 参数必须是 1-65535 的端口号' }, 400)
|
|
}
|
|
return json(await probeExit(port))
|
|
}
|
|
|
|
// ── 内核 ────────────────────────────────────────────
|
|
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({ message: '请求缺少 name 字段' }, 400)
|
|
const upstream = await selectProxy(env, group, body.name)
|
|
return upstream.ok
|
|
? json({ ok: true })
|
|
: json({ message: upstream.message || '内核拒绝了这次切换' }, 422)
|
|
}
|
|
|
|
// 让内核重新加载磁盘上的配置文件。给 SSH 手改过配置的场景用;运行时动作
|
|
if (path === '/api/kernel/reload' && req.method === 'POST') {
|
|
const upstream = await reloadConfig(env, env.configPath)
|
|
return upstream.ok
|
|
? json({ ok: true })
|
|
: json({ message: upstream.message || '内核重载失败' }, 502)
|
|
}
|
|
|
|
// GEO 数据库文件的本地状态(大小、更新时间)和生效中的下载地址
|
|
if (path === '/api/geo' && req.method === 'GET') {
|
|
const snapshot = await readConfig(env)
|
|
const geox = (snapshot.data['geox-url'] ?? {}) as Record<string, unknown>
|
|
return json({ files: await geoStatus(env, geox) })
|
|
}
|
|
|
|
// 单个 GEO 文件的下载。服务端自己下(内核只有全量更新的口子),重启后生效
|
|
if (path === '/api/geo/sync' && req.method === 'POST') {
|
|
const body = (await req.json()) as { key?: string }
|
|
if (typeof body.key !== 'string') return json({ message: '请求缺少 key 字段' }, 400)
|
|
const snapshot = await readConfig(env)
|
|
const geox = (snapshot.data['geox-url'] ?? {}) as Record<string, unknown>
|
|
// 内核在线且开着老式 http 入口时借它的通路下载,直连 GitHub 不一定通
|
|
const port = [snapshot.data['mixed-port'], snapshot.data.port].find(
|
|
(p): p is number => typeof p === 'number' && p > 0,
|
|
)
|
|
const kernelUp = port !== undefined && (await kernelVersion(env)).online
|
|
const proxy = kernelUp ? `http://127.0.0.1:${String(port)}` : null
|
|
const result = await syncGeoFile(env, body.key, geox, proxy)
|
|
return result.ok ? json({ ok: true }) : json({ message: result.message }, 502)
|
|
}
|
|
|
|
// 更新 GEO 数据库。运行时动作;同步接口,透传层给了长超时
|
|
if (path === '/api/kernel/geo' && req.method === 'POST') {
|
|
const upstream = await updateGeoDatabases(env)
|
|
return upstream.ok
|
|
? json({ ok: true })
|
|
: json({ message: upstream.message || '内核更新 GEO 数据库失败' }, 502)
|
|
}
|
|
|
|
// 重启内核进程。运行时动作,不碰配置文件;和其它写操作一样单独点名,不开通用口子
|
|
if (path === '/api/kernel/restart' && req.method === 'POST') {
|
|
const upstream = await restartKernel(env)
|
|
return upstream.ok
|
|
? json({ ok: true })
|
|
: json({ message: upstream.message || '内核拒绝了重启请求' }, 502)
|
|
}
|
|
|
|
if (path.startsWith('/api/kernel/') && (req.method === 'PUT' || req.method === 'DELETE')) {
|
|
const target = path.slice('/api/kernel'.length)
|
|
const rule = WRITABLE.find((w) => w.method === req.method && w.pattern.test(target))
|
|
if (!rule) return json({ message: `不允许写入该路径:${target}` }, 403)
|
|
const upstream = await proxyWrite(env, rule.method, target + url.search)
|
|
return new Response(upstream.body, {
|
|
status: upstream.status,
|
|
headers: { 'Content-Type': upstream.headers.get('Content-Type') ?? 'application/json' },
|
|
})
|
|
}
|
|
|
|
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({ message: `不允许访问该路径:${target}` }, 403)
|
|
}
|
|
const upstream = await proxyGet(env, target + url.search, STREAM_PATHS.has(target))
|
|
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({ message: '没有这个接口' }, 404)
|
|
}
|
|
}
|