7 Commits
Author SHA1 Message Date
im0o e9e2eb555d 每路入站配一组专属策略组,换线不再改配置文件
原本换一条线要改 config.yaml、跑校验、等内核重载,几秒起步;而换线恰恰是这个工具
最高频的动作,把它放在最重的路径上方向就错了。现在每一路配一个 select 组加 AUTO、
FALLBACK 两个,入站的 proxy 永久指向 select,换线只是调一次内核接口。这样做的前提是
选中不会丢:内核把它写进 cache 文件,重启后由 patchSelectGroup 恢复,而
profile.store-selected 默认为真。

链式代理靠给来源订阅复制一份声明、挂上 override.dialer-proxy 实现,因为这个字段写在
策略组上内核只会打条日志然后忽略。副本是 type: file 读原订阅已经落盘的缓存,而不是
自己再拉一次:自己拉的话订阅地址一不可达副本就是空的,那一路入站会一条线都不剩,
表现是端口还在监听却没有任何出口。

顺带把 shared/outbound-chain.ts 里「只有 Selector 接受手动选择」那条断言删了,它是
错的(内核检查的是 SelectAble 接口,URLTest 和 Fallback 也实现了)。界面仍然只让
Selector 可点,但理由换成了另外两种的手动指定会被它们自己撤销。

完整取舍见工作区决策记录 0007。
2026-08-11 03:10:38 +08:00
im0o afe53b9790 后端补上流式透传和两个写操作,给后面几个页面铺路
原以为流量和日志要写 WebSocket 转发,实测不用:内核在没有 WebSocket 升级时把
traffic、memory、logs 退化成分块的 HTTP 流,一行一个 JSON(server.go:380-383)。
现有的透传本来就能流式传,唯一的问题是那个 15 秒超时会每隔一会儿掐断一次,
给这三个路径去掉超时即可。

写操作照旧是白名单,逐条列出:断开连接(DELETE /connections 和 /connections/{id})、
刷新订阅(PUT /providers/proxies/{名字})。两者都只改内核运行状态、不碰配置文件,
所以不走落盘那条保护链路。方法和路径都要匹配才放行,测试里有反例。
2026-08-10 19:45:31 +08:00
im0o cb8effe05b 把入站固定到某条订阅线路
订阅线路不在内核的全局名字表里,入站的 proxy 指不到它(决策记录 0005)。做法是自动建
一个只装它的策略组再指过去,用户看到的只是「这个口固定走这条线」,组是实现细节:
不出现在策略组列表里,列表和详情里都显示成线路本身的名字,没人再引用时自动删掉。

筛选条件必须做对两件事,都写了测试:转义正则元字符(线路名形如 [vmess]DMIT.LAX.Pro
里的方括号和点不转义会匹配错),以及前后加锚点(内核是部分匹配,不加锚点时「香港01」
会把「香港011」也捞进来)。线路名含反引号时表达不了——那是内核切分多个筛选条件的
分隔符——这种情况明说做不到而不是生成一个会静默匹配错的组。

实测:生成的配置 mihomo -t 通过;起一个临时内核问 /proxies,这个组解析出来的成员
恰好只有那一条线路,且确实进了名字表所以入站指得到。
2026-08-10 19:33:44 +08:00
im0o 08ab73a4f1 默认入站不再显示整块出站选择
它由配置顶层的端口字段声明,没有 proxy 字段可写,画一排点不了的卡片只会让人以为
是坏了。之前藏掉这块会让面板变空,所以留着;现在「流量去向」那一节顶上来了,
默认入站照样有内容可看——它的流量去向由规则表决定,那一节反而是它唯一相关的部分。

「默认」标记和不给删除本来就有:列表里带 tag,详情里不显示编辑和删除按钮。
2026-08-10 19:13:54 +08:00
im0o 43d410d02c 去掉解释性提示和链条上的类型标注
链条回到纯名字。类型标注和「某某组自己决定选中哪一条」那句解释是我上一版加的,
用来说明为什么那一层点不了——但不能点的东西本来就没画出来,解释一个看不见的东西
只是噪音。

默认入站那条压成一句,内核未连接那条压成四个字,没有附加规则时整行不显示而不是
显示一个破折号。shared 里跟着没人用的 autoDecidedHops 一并删掉。
2026-08-10 18:58:34 +08:00
im0o 5049879a70 可切换的那一层改成最后一个 Selector,不是最后一个有成员的组
原来的规则会落在 AUTO 上,而 AUTO 是 url-test 类型——它按延迟自己挑,手动选它没有
意义,点完会被下一轮延迟测试算回去。内核里只有 Selector 是「由人来选」的
(constant/adapters.go:240-248 列了全部五种),URLTest 挑最快、Fallback 挑第一个可用、
LoadBalance 分摊,Relay 已被移除。

链条上现在每一跳都标出类型(PROXY Selector → AUTO URLTest → 线路 Vless),并明说
自动决定的那几层不接受手动指定——不说清楚的话,用户看到链条里有个组却点不了,
只会以为是坏了。
2026-08-10 18:38:59 +08:00
im0o c5ac59ecf9 按审查结论重构:先补测试网,再搬代码
顺序是刻意的。前端一行测试都没有,直接挪代码挪坏了 bun test 不会红,所以先把纯逻辑
抽到能被测试的位置并补上用例,最后才动组件。测试从 37 条增加到 77 条。

抽出来的四块:
- shared/outbound-chain.ts  「这个端口现在走哪条线」的链路解析,带防环,9 条测试
- web/delay-test.ts          延迟测试失败时说什么,6 个分支原本一条测试都没有
- web/runtime.ts             运行时状态的模块级单例,照 prefs.ts 已有的模式
- web/components/InboundList.vue  入站列表

出站的文本原本散成四份(读一份、显示一份、写回一份、表单又抄一份),加一种出站模式
要同时改四处,漏一个就是显示与写回不一致。合并成 OUTBOUND_PRESETS 一张表。

给认证和透传白名单补了 20 条测试。两者都是安全边界、都是纯函数、都不需要内核在线,
之前却只靠需要活内核的冒烟脚本间接覆盖。其中「形似但不是健康检查的路径」几条确认了
正则没写松。

另外:配置快照不再把整份文件原文下发(前端从不读,白白让响应体积翻倍);
yaml-cosmetics 的测试改走生产路径,之前它自己拼了一遍三步流程,落盘链路漏掉其中一步
测试照样会绿。
2026-08-10 18:21:23 +08:00
28 changed files with 2666 additions and 549 deletions
+49
View File
@@ -0,0 +1,49 @@
/**
* 验证「每路一个专属代理组」和链式代理生成的配置内核真的接受。
*
* 单元测试只能证明字符串拼对了,证明不了内核认。这里走一遍真实的写回路径,
* 产物交给 mihomo -t 校验。特别要看的是订阅副本上的 dialer-proxy 引用能不能过
* `validateDialerProxies`(内核源码 config/utils.go:148-176)。
*
* 用法:bun run scripts/verify-chain.ts <源配置> <输出路径>
*/
import { readFileSync, writeFileSync } from 'node:fs'
import { openDocument } from '../vendor/config-editor/index.ts'
import type { ConfigObject } from '../vendor/config-editor/index.ts'
import { rewriteYaml } from '../server/config-store.ts'
import { applySetup, pruneGenerated } from '../shared/inbound-groups.ts'
const [src, out] = process.argv.slice(2)
if (!src || !out) {
console.error('用法:bun run scripts/verify-chain.ts <源配置> <输出路径>')
process.exit(1)
}
const source = readFileSync(src, 'utf8')
const data = JSON.parse(JSON.stringify(openDocument(source).data)) as ConfigObject
// 模拟界面上的三个动作:新增两路入站,一路直连,一路开链式代理并把入口筛到某一条线
data.listeners = [
{ name: '容器A', type: 'mixed', port: 17895 },
{ name: '容器B', type: 'mixed', port: 17896 },
]
let next = applySetup(data, '容器A', {
proxy: { sources: ['subs'], filter: null },
chain: null,
})
next = applySetup(next, '容器B', {
proxy: { sources: ['subs'], filter: null },
chain: { sources: ['subs'], filter: '(?i)DMIT' },
})
writeFileSync(out, rewriteYaml(source, pruneGenerated(next)), 'utf8')
console.log('生成的策略组:')
console.log(JSON.stringify(next['proxy-groups'], null, 2))
console.log('\n生成的订阅副本(只看结构,url 不回显):')
for (const [name, entry] of Object.entries(next['proxy-providers'] as ConfigObject)) {
if (!name.startsWith('patchbay:')) continue
const { url, ...rest } = entry as ConfigObject
console.log(name, JSON.stringify({ ...rest, url: '<同源订阅>' }))
}
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'bun:test'
import { tokenFromRequest, tokenMatches } from './auth.ts'
const TOKEN = '208ac4512b9748b9b7408ebc16ec793d'
describe('令牌比较', () => {
it('一模一样才算通过', () => {
expect(tokenMatches(TOKEN, TOKEN)).toBe(true)
})
it('差一个字符就不通过', () => {
expect(tokenMatches(TOKEN, `${TOKEN.slice(0, -1)}x`)).toBe(false)
})
it('前缀正确也不算通过', () => {
// 逐字节比较写错时最容易漏掉的一种:只比对了开头
expect(tokenMatches(TOKEN, TOKEN.slice(0, 8))).toBe(false)
})
it('更长的字符串不算通过', () => {
expect(tokenMatches(TOKEN, `${TOKEN}extra`)).toBe(false)
})
it('没带令牌不算通过', () => {
expect(tokenMatches(TOKEN, null)).toBe(false)
expect(tokenMatches(TOKEN, '')).toBe(false)
})
it('比较耗时不随匹配长度变化', () => {
// 这是常数时间比较存在的理由:如果先匹配的字符越多越慢,就能靠计时逐字节猜出令牌。
// 这里只验证行为上的对称——两个都不匹配的输入走的是同样多的比较。
const almost = `${TOKEN.slice(0, -1)}x`
const nothing = 'x'.repeat(TOKEN.length)
expect(tokenMatches(TOKEN, almost)).toBe(false)
expect(tokenMatches(TOKEN, nothing)).toBe(false)
})
})
describe('从请求里取令牌', () => {
const req = (init?: RequestInit, url = 'http://x/api/config') => new Request(url, init)
it('认 Authorization 头', () => {
expect(tokenFromRequest(req({ headers: { Authorization: `Bearer ${TOKEN}` } }))).toBe(TOKEN)
})
it('认查询参数,WebSocket 用得上——它没法自定义请求头', () => {
expect(tokenFromRequest(req(undefined, `http://x/api/logs?token=${TOKEN}`))).toBe(TOKEN)
})
it('头的格式不对时当作没带', () => {
expect(tokenFromRequest(req({ headers: { Authorization: TOKEN } }))).toBeNull()
expect(tokenFromRequest(req({ headers: { Authorization: `Basic ${TOKEN}` } }))).toBeNull()
})
it('什么都没带时返回空', () => {
expect(tokenFromRequest(req())).toBeNull()
})
})
+52 -9
View File
@@ -33,8 +33,6 @@ const KEEP_BACKUPS = 10
export interface ConfigSnapshot {
/** 解析出来的配置数据 */
data: ConfigObject
/** 文件原文 */
yaml: string
/**
* 内容指纹。客户端改完提交时要带上它,服务端据此判断这份改动
* 是不是基于最新的文件——中途有人 SSH 上去手改过就会对不上。
@@ -56,7 +54,12 @@ export type ApplyFailureStage =
| 'write' // 写文件失败
| 'reload' // 文件写进去了,但内核没能重新加载
export async function readConfig(env: Env): Promise<ConfigSnapshot> {
/** 内部用的完整读取,带原文。原文只在生成新内容时需要,不下发给前端。 */
interface ConfigDocument extends ConfigSnapshot {
yaml: string
}
async function readDocument(env: Env): Promise<ConfigDocument> {
const yaml = await readFile(env.configPath, 'utf8')
const doc = openDocument(yaml)
return {
@@ -67,6 +70,30 @@ export async function readConfig(env: Env): Promise<ConfigSnapshot> {
}
}
/**
* 读当前配置。
*
* 不含文件原文:前端从来不读它,带上只会让每次请求的响应体积翻倍。要原文的地方
* 在这个文件内部,用 readDocument。
*/
export async function readConfig(env: Env): Promise<ConfigSnapshot> {
const { yaml: _yaml, ...snapshot } = await readDocument(env)
return snapshot
}
/**
* 把新的配置数据写成 YAML 文本。
*
* 单独导出是为了让测试能走**生产用的这一条**路径。之前测试自己拼了
* 「解析 → 替换 → 还原对齐」三步,于是如果有人在落盘链路里漏掉最后那步,
* 那些专为守护它而写的测试照样全绿。
*/
export function rewriteYaml(currentYaml: string, nextData: ConfigObject): string {
const rewritten = replaceDocumentData(openDocument(currentYaml), nextData)
// 把只是丢了对齐空格的行还原成原样,否则没被改动的段落也会出现在 diff 里,见 ORIGIN.md
return restoreInlineCommentAlignment(currentYaml, rewritten.yaml)
}
/**
* 把一份新的配置数据落盘。
*
@@ -78,7 +105,7 @@ export async function applyConfig(
nextData: ConfigObject,
baseRevision?: string,
): Promise<ApplyOutcome> {
const current = await readConfig(env)
const current = await readDocument(env)
if (baseRevision !== undefined && baseRevision !== current.revision) {
return {
@@ -90,14 +117,22 @@ export async function applyConfig(
}
}
// 生成新内容。restoreInlineCommentAlignment 把只是丢了对齐空格的行还原成原样,
// 否则没被改动的段落也会出现在 diff 里,见 ORIGIN.md。
const rewritten = replaceDocumentData(openDocument(current.yaml), nextData)
const nextYaml = restoreInlineCommentAlignment(current.yaml, rewritten.yaml)
// 落盘链路有五步各自可能变慢(校验要起一个内核进程、重载要等内核跑完、备份和写盘是磁盘
// IO)。出问题时不靠猜,日志里直接给出每步耗时。
const clock = { start: Date.now(), mark: Date.now() }
const lap = (stage: string) => {
const now = Date.now()
const ms = now - clock.mark
clock.mark = now
return `${stage} ${String(ms)}ms`
}
const nextYaml = rewriteYaml(current.yaml, nextData)
// 内容没变就不要走后面那一串——不必要的备份和重载只会制造噪音。
if (nextYaml === current.yaml) {
return { ok: true, snapshot: current, reloaded: false, reloadMessage: '内容没有变化' }
const { yaml: _yaml, ...snapshot } = current
return { ok: true, snapshot, reloaded: false, reloadMessage: '内容没有变化' }
}
const problems = validateDocument(nextData).filter((d) => d.severity === 'error')
@@ -113,9 +148,11 @@ export async function applyConfig(
// 先写到临时文件交给内核校验,别碰真文件。
const tempPath = join(dirname(env.configPath), `.patchbay-check-${String(Date.now())}.yaml`)
let checkTiming = ''
try {
await writeFile(tempPath, nextYaml, 'utf8')
const checked = await validateConfigFile(env, tempPath)
checkTiming = lap('内核校验')
if (!checked.ok) {
return {
ok: false,
@@ -131,6 +168,7 @@ export async function applyConfig(
// 校验过了才动真文件。备份放在写入之前。
const backupPath = await createBackup(env)
const backupTiming = lap('备份')
try {
await writeFile(env.configPath, nextYaml, 'utf8')
} catch (error) {
@@ -143,7 +181,9 @@ export async function applyConfig(
}
}
const writeTiming = lap('写盘')
const reloaded = await reloadConfig(env, env.configPath)
const reloadTiming = lap('重载')
if (!reloaded.ok) {
// 文件已经写进去了但内核没接受。把文件还原,再让内核载回原样,
// 避免留下「文件是新的、内核跑的是旧的」这种最难排查的状态。
@@ -167,6 +207,9 @@ export async function applyConfig(
}
await pruneBackups(env)
console.log(
`[apply] 共 ${String(Date.now() - clock.start)}ms(${checkTiming},${backupTiming},${writeTiming},${reloadTiming})`,
)
return {
ok: true,
snapshot: await readConfig(env),
+3 -1
View File
@@ -8,7 +8,7 @@ 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'
import { kernelVersion, warmUpKernelBinary } from './kernel.ts'
const env = readEnv()
const { token, source } = await resolveToken(env)
@@ -29,6 +29,8 @@ try {
process.exit(1)
}
warmUpKernelBinary(env)
const kernel = await kernelVersion(env)
console.log(
kernel.online
+36 -3
View File
@@ -50,6 +50,24 @@ export async function validateConfigFile(
}
}
/**
* 启动时先把内核二进制跑一次,什么都不做。
*
* `mihomo -t` 的第一次调用要 4 秒,之后 55 毫秒(在目标机器那种规格上实测差距只会更大)。
* 差的是把这个几十兆的可执行文件读进系统文件缓存的时间,跟配置内容无关。不预热的话,
* 这 4 秒会落在用户按下的第一次保存上,而那正是他最容易以为「这个工具很慢」的时刻。
*
* 失败不用管:内核二进制不可用这件事,第一次真正校验时会带着完整错误信息报出来。
*/
export function warmUpKernelBinary(env: Env): void {
try {
const proc = Bun.spawn([env.mihomoBin, '-v'], { stdout: 'ignore', stderr: 'ignore' })
void proc.exited
} catch {
// 同上
}
}
/** 带上认证头访问管理接口。 */
async function callApi(env: Env, path: string, init?: RequestInit): Promise<Response> {
return fetch(`${env.mihomoApi}${path}`, {
@@ -119,7 +137,22 @@ export async function selectProxy(
}
}
/** 透传一个管理接口的 GET 请求,用于运行时数据(线路、连接、日志等)。 */
export async function proxyGet(env: Env, path: string): Promise<Response> {
return callApi(env, path, { signal: AbortSignal.timeout(15_000) })
/**
* 透传一个管理接口的 GET 请求。
*
* `stream` 为真时不设超时:流量、内存、日志这三个接口不升级 WebSocket 时会退化成
* 持续吐 JSON 的分块流(内核源码 hub/route/server.go:380-383),给它们设超时等于
* 每隔一会儿就把连接掐断一次。
*/
export async function proxyGet(env: Env, path: string, stream = false): Promise<Response> {
return callApi(env, path, stream ? {} : { signal: AbortSignal.timeout(15_000) })
}
/** 透传一个写操作。目前只有断开连接和刷新订阅两处。 */
export async function proxyWrite(
env: Env,
method: 'PUT' | 'DELETE',
path: string,
): Promise<Response> {
return callApi(env, path, { method, signal: AbortSignal.timeout(30_000) })
}
+130
View File
@@ -0,0 +1,130 @@
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('写操作的白名单', () => {
const write = (method: string, path: string) =>
handle(
new Request(`http://127.0.0.1:7580/api/kernel${path}`, {
method,
headers: { Authorization: `Bearer ${TOKEN}` },
}),
)
it('放行断开连接和刷新订阅', async () => {
expect((await write('DELETE', '/connections')).status).not.toBe(403)
expect((await write('DELETE', '/connections/abc-123')).status).not.toBe(403)
expect((await write('PUT', '/providers/proxies/subs')).status).not.toBe(403)
})
it('挡住没列出来的写操作', async () => {
// 重启内核、切换配置这类动作不该从这里走
expect((await write('PUT', '/configs')).status).toBe(403)
expect((await write('DELETE', '/cache/fakeip/flush')).status).toBe(403)
expect((await write('PUT', '/providers/proxies/subs/healthcheck')).status).toBe(403)
})
it('方法对不上也挡住', async () => {
// 断开连接是 DELETE,刷新订阅是 PUT,反过来都不行
expect((await write('PUT', '/connections')).status).toBe(403)
expect((await write('DELETE', '/providers/proxies/subs')).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<string, unknown> }
expect(Object.keys(body.types).length).toBeGreaterThan(0)
})
it('前端页面不要令牌——它只是空壳,数据都要带令牌才拿得到', async () => {
expect((await get('/', null)).status).not.toBe(401)
})
})
+32 -2
View File
@@ -11,7 +11,7 @@
*/
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 { kernelVersion, proxyGet, proxyWrite, 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'
@@ -30,6 +30,25 @@ const DELAY_PATH = /^\/(proxies|group)\/.+\/delay$/
*/
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\/[^/]+$/ },
]
/** 允许透传的管理接口路径。白名单而不是黑名单——多开一个口子要有意为之。 */
const READABLE_KERNEL_PATHS = new Set([
'/version',
@@ -175,6 +194,17 @@ function makeRoute(env: Env, token: string) {
: json({ message: upstream.message || '内核拒绝了这次切换' }, 422)
}
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 =
@@ -182,7 +212,7 @@ function makeRoute(env: Env, token: string) {
if (!allowed) {
return json({ message: `不允许访问该路径:${target}` }, 403)
}
const upstream = await proxyGet(env, target + url.search)
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' },
+321
View File
@@ -0,0 +1,321 @@
import { describe, expect, it } from 'bun:test'
import {
applySetup,
chainGroupName,
chainProviderName,
panelGroups,
syncGenerated,
isGenerated,
linesMatching,
proxyGroupName,
pruneGenerated,
readSetup,
} from './inbound-groups.ts'
import type { OutboundSetup } from './inbound-groups.ts'
import { collectInbounds } from './inbounds.ts'
import type { ConfigObject } from '../vendor/config-editor/index.ts'
const URL = 'http://127.0.0.1:3001/token/download/V2House'
/** 一份最小但完整的配置:一个订阅、一路入站,还没被 Patchbay 接管过。 */
function base(): ConfigObject {
return {
'proxy-providers': {
subs: { type: 'http', url: URL, path: './providers/subs.yaml', interval: 86400 },
},
listeners: [{ name: 'test1', type: 'mixed', port: 7778 }],
}
}
const plain: OutboundSetup = { proxy: { sources: ['subs'], filter: null }, chain: null }
const chained: OutboundSetup = {
proxy: { sources: ['subs'], filter: null },
chain: { sources: ['subs'], filter: '(?i)DMIT' },
}
describe('名字', () => {
it('三种生成物都带前缀', () => {
// 前缀是识别它们的唯一可靠标记,注释会被配置改写引擎丢掉(决策记录 0002)
expect(isGenerated(proxyGroupName('test1'))).toBe(true)
expect(isGenerated(chainGroupName('test1'))).toBe(true)
expect(isGenerated(chainProviderName('test1', 'subs'))).toBe(true)
})
it('用户自己建的组不会被认成生成的', () => {
expect(isGenerated('PROXY')).toBe(false)
})
it('不同的「入站 × 来源」组合不撞名', () => {
// proxy-providers 是个映射,撞名会让其中一份被静默丢掉,
// 表现是链式代理挂到了别的入站上
const names = new Set([
chainProviderName('a', 'b c'),
chainProviderName('a b', 'c'),
chainProviderName('a', 'b'),
])
expect(names.size).toBe(3)
})
})
describe('筛选预览', () => {
const lines = ['[vmess]DMIT.LAX.Pro.MTYQ', '[vless]Gomami.SIN Secret', '香港01', '香港011']
it('没写筛选条件就是全要', () => {
expect(linesMatching(null, lines)).toEqual(lines)
})
it('部分匹配,不自动加锚点', () => {
// 内核的筛选就是部分匹配,界面预览必须跟它一致,否则预览的数字骗人
expect(linesMatching('香港01', lines)).toEqual(['香港01', '香港011'])
})
it('反引号切成多条正则,取并集', () => {
expect(linesMatching('DMIT`Gomami', lines)).toEqual([
'[vmess]DMIT.LAX.Pro.MTYQ',
'[vless]Gomami.SIN Secret',
])
})
it('写法有误时返回空,让界面提示而不是显示一个错的数字', () => {
expect(linesMatching('[未闭合', lines)).toBeNull()
})
})
describe('一路入站的三个组', () => {
it('SELECT 的成员是 DIRECT 加另外两个组,加上订阅', () => {
// 这三种挑法是所有 clash 配置里固定的那几种,让用户从零拼一遍没有意义
const groups = applySetup(base(), 'test1', plain)['proxy-groups'] as ConfigObject[]
expect(groups[0]).toEqual({
name: 'patchbay:test1',
type: 'select',
proxies: ['DIRECT', 'patchbay:test1 AUTO', 'patchbay:test1 FALLBACK'],
use: ['subs'],
})
})
it('AUTO 是 url-test,FALLBACK 是 fallback,都带测速地址', () => {
// 不写测速地址时内核会去借来源订阅的健康检查配置,那依赖订阅写了它,不能指望
const groups = applySetup(base(), 'test1', plain)['proxy-groups'] as ConfigObject[]
expect(groups[1]).toEqual({
name: 'patchbay:test1 AUTO',
type: 'url-test',
use: ['subs'],
url: 'https://www.gstatic.com/generate_204',
interval: 300,
})
expect((groups[2] as ConfigObject).type).toBe('fallback')
})
it('tab 的顺序是 SELECT、AUTO、FALLBACK,只有 SELECT 能点', () => {
// 另外两个自己决定用哪条,手动指定会被它们自己撤销,见 outbound-chain.ts
const data = applySetup(base(), 'test1', plain)
const runtime = {
'patchbay:test1': { type: 'Selector' },
'patchbay:test1 AUTO': { type: 'URLTest' },
'patchbay:test1 FALLBACK': { type: 'Fallback' },
}
const inbound = collectInbounds(data)[0]!
const panel = panelGroups(data, runtime, inbound)
expect(panel.shared).toBe(false)
expect(panel.groups.map((g) => g.label)).toEqual(['SELECT', 'AUTO', 'FALLBACK'])
expect(panel.groups.map((g) => g.pickable)).toEqual([true, false, false])
expect(panel.groups[0]!.uses).toEqual(['subs'])
})
it('内核里还没有的组不出现在 tab 上', () => {
// 保存完到内核重载完之间会有这么一小段,画一个点不出东西的 tab 只会让人以为坏了
const data = applySetup(base(), 'test1', plain)
const inbound = collectInbounds(data)[0]!
expect(panelGroups(data, {}, inbound).groups).toEqual([])
})
it('没接管的入站落到它顺着规则表走到的那个手动选择组,并标为共用', () => {
const data: ConfigObject = {
...base(),
rules: ['MATCH,PROXY'],
'proxy-groups': [{ name: 'PROXY', type: 'select', use: ['subs'] }],
}
const runtime = { PROXY: { type: 'Selector', now: 'A', all: ['A'] } }
const panel = panelGroups(data, runtime, collectInbounds(data)[0]!)
expect(panel.shared).toBe(true)
expect(panel.groups).toEqual([
{ name: 'PROXY', label: 'PROXY', uses: ['subs'], pickable: true },
])
})
it('筛选条件三个组共用一份', () => {
const groups = applySetup(base(), 'test1', {
proxy: { sources: ['subs'], filter: '(?i)hk' },
chain: null,
})['proxy-groups'] as ConfigObject[]
for (const g of groups) expect((g as ConfigObject).filter).toBe('(?i)hk')
})
})
describe('重建成当前形状', () => {
it('旧形状的生成组会被补齐成三个', () => {
// 改过生成规则之后,早先建的那些停在旧形状上,界面按新形状去找就静默少一块
const stale: ConfigObject = {
...base(),
'proxy-groups': [{ name: 'patchbay:test1', type: 'select', use: ['subs'] }],
listeners: [{ name: 'test1', type: 'mixed', port: 7778, proxy: 'patchbay:test1' }],
}
const fixed = syncGenerated(stale, collectInbounds(stale))
const names = (fixed['proxy-groups'] as ConfigObject[]).map((g) => (g as ConfigObject).name)
expect(names).toEqual(['patchbay:test1', 'patchbay:test1 AUTO', 'patchbay:test1 FALLBACK'])
})
it('没接管的入站不碰', () => {
const data = base()
expect(syncGenerated(data, collectInbounds(data))).toBe(data)
})
})
describe('读取设置', () => {
it('没有代理组时返回空,表示这一路由别的方式决定去向', () => {
expect(readSetup(base(), 'test1')).toBeNull()
})
it('没开链式代理时,来源就是代理组的 use', () => {
const setup: OutboundSetup = { proxy: { sources: ['subs'], filter: '(?i)hk' }, chain: null }
expect(readSetup(applySetup(base(), 'test1', setup), 'test1')).toEqual(setup)
})
it('开了链式代理时,来源从副本的 url 还原', () => {
// 代理组的 use 这时指向副本,用户选的订阅只能靠 url 相同认回来
const data = applySetup(base(), 'test1', chained)
expect(readSetup(data, 'test1')).toEqual(chained)
})
})
describe('写回设置', () => {
it('开链式代理时建入口组,三个组一起改用副本', () => {
const groups = applySetup(base(), 'test1', chained)['proxy-groups'] as ConfigObject[]
const copyName = chainProviderName('test1', 'subs')
// 只有副本挂着 dialer-proxy,自动测速和故障转移也得走副本,否则那两条路绕过了中转
for (const g of groups.slice(0, 3)) expect((g as ConfigObject).use).toEqual([copyName])
expect(groups[3]).toEqual({
name: 'patchbay:test1 链式',
type: 'select',
use: ['subs'],
filter: '(?i)DMIT',
})
})
it('副本读原订阅的缓存文件,自己不联网', () => {
// 副本要是自己去拉,订阅地址一不可达它就是空的,那一路入站的线路会全部消失,
// 表现是端口还在监听却一条线都没有
const data = applySetup(base(), 'test1', chained)
const copy = (data['proxy-providers'] as ConfigObject)[
chainProviderName('test1', 'subs')
] as ConfigObject
expect(copy.type).toBe('file')
expect(copy.path).toBe('./providers/subs.yaml')
expect(copy.url).toBeUndefined()
expect(copy.interval).toBeUndefined()
expect(copy.override).toEqual({ 'dialer-proxy': 'patchbay:test1 链式' })
})
it('原订阅没写 path 时给它补一个,否则副本认不到该读哪个文件', () => {
// 内核会按 url 哈希自己生成缓存路径,那个路径 Patchbay 算不出来
const data = base()
delete ((data['proxy-providers'] as ConfigObject).subs as ConfigObject).path
const next = applySetup(data, 'test1', chained)
const providers = next['proxy-providers'] as ConfigObject
expect((providers.subs as ConfigObject).path).toBe('./providers/subs.yaml')
expect(readSetup(next, 'test1')).toEqual(chained)
})
it('源订阅原有的 override 保留,不被覆盖', () => {
const data = base()
;((data['proxy-providers'] as ConfigObject).subs as ConfigObject).override = { udp: true }
const next = applySetup(data, 'test1', chained)
const copy = (next['proxy-providers'] as ConfigObject)[
chainProviderName('test1', 'subs')
] as ConfigObject
expect(copy.override).toEqual({ udp: true, 'dialer-proxy': 'patchbay:test1 链式' })
})
it('关掉链式代理时,入口组和副本一起消失', () => {
const off = applySetup(applySetup(base(), 'test1', chained), 'test1', plain)
const names = (off['proxy-groups'] as ConfigObject[]).map((g) => (g as ConfigObject).name)
expect(names).not.toContain('patchbay:test1 链式')
expect(Object.keys(off['proxy-providers'] as ConfigObject)).toEqual(['subs'])
})
it('换来源时旧副本立刻消失', () => {
// 留着的话就是一份没人引用、却还在按 interval 定时联网的订阅
const data = base()
const providers = data['proxy-providers'] as ConfigObject
providers.other = { type: 'http', url: 'http://other.example/x', path: './providers/o.yaml' }
const first = applySetup(data, 'test1', chained)
const second = applySetup(first, 'test1', {
proxy: { sources: ['other'], filter: null },
chain: { sources: ['subs'], filter: null },
})
const names = Object.keys(second['proxy-providers'] as ConfigObject)
expect(names).toContain(chainProviderName('test1', 'other'))
expect(names).not.toContain(chainProviderName('test1', 'subs'))
})
it('两路入站各自的副本互不干扰', () => {
const data = base()
;(data.listeners as ConfigObject[]).push({ name: 'test2', type: 'mixed', port: 7779 })
const next = applySetup(applySetup(data, 'test1', chained), 'test2', chained)
const providers = next['proxy-providers'] as ConfigObject
expect(Object.keys(providers)).toHaveLength(3)
expect(readSetup(next, 'test1')).toEqual(chained)
expect(readSetup(next, 'test2')).toEqual(chained)
})
})
describe('清理', () => {
it('删掉入站之后,几个组和副本连锁消失', () => {
// 链式引用:SELECT 引 AUTO 和 FALLBACK,三者引副本,副本引入口组,要反复扫才清得干净
const withInbound = applySetup(base(), 'test1', chained)
const removed: ConfigObject = { ...withInbound, listeners: [] }
const cleaned = pruneGenerated(removed)
expect(cleaned['proxy-groups']).toBeUndefined()
expect(Object.keys(cleaned['proxy-providers'] as ConfigObject)).toEqual(['subs'])
})
it('入站还在就一个都不删', () => {
const data = applySetup(base(), 'test1', chained)
expect(pruneGenerated(data)).toBe(data)
})
it('用户自己建的组和订阅一律不碰,哪怕真的没人引用', () => {
const data: ConfigObject = {
'proxy-groups': [{ name: '我建的组', type: 'select', use: ['subs'] }],
'proxy-providers': { subs: { type: 'http', url: URL } },
}
expect(pruneGenerated(data)).toBe(data)
})
it('没有可删的时候原样返回,不制造无谓的改动', () => {
// 返回同一个对象,落盘链路才看得出「内容没变」而跳过备份和重载
const data: ConfigObject = { 'proxy-groups': [{ name: 'PROXY' }] }
expect(pruneGenerated(data)).toBe(data)
})
it('被规则引用的生成组不删,连它引用的两个组一起留下', () => {
const data = applySetup(base(), 'test1', plain)
const orphaned: ConfigObject = { ...data, listeners: [], rules: ['MATCH,patchbay:test1'] }
expect((pruneGenerated(orphaned)['proxy-groups'] as ConfigObject[]).length).toBe(3)
})
})
+501
View File
@@ -0,0 +1,501 @@
/**
* 每一路入站的专属策略组。
*
* 一路入站配三个组,入站的 `proxy:` 指向其中的 SELECT,换线是换那个组的当前选中,
* 不改配置文件(决策记录 0007):
* SELECT 手动选。它的成员是 DIRECT、下面两个组,加上订阅里的线路
* AUTO url-test,自动挑延迟最低的
* FALLBACK fallback,按顺序挑第一个测得通的
* 界面上这三个是并排的 tab。做成三个而不是让用户自己配,是因为它们就是所有 clash 配置
* 里那三种固定的挑法,让人从零拼一遍没有意义。
*
* 开了链式代理时再多一个入口组,以及若干份订阅声明的副本——`dialer-proxy` 写不到策略组
* 上,只能挂在整个订阅上(内核源码 adapter/outboundgroup/parser.go:68-70)。
*
* 配置里的东西属于谁全靠三条线索还原,不靠解析名字:
* 四个组 名字由入站名推出来
* 订阅副本 override.dialer-proxy 指向哪一路的入口组
* 副本的来源 url 和哪个用户订阅相同
*/
import type { ConfigObject } from '../vendor/config-editor/index.ts'
import { resolveDestination } from './inbounds.ts'
import type { Inbound } from './inbounds.ts'
import { lastSwitchableGroup, resolveChain } from './outbound-chain.ts'
import type { RuntimeNode } from './outbound-chain.ts'
/**
* Patchbay 自动创建的策略组和订阅的名字前缀。
*
* 名字是识别它们的唯一可靠标记。注释靠不住——配置改写引擎重建整个被碰到的顶层段落,
* 段落内的注释会丢(决策记录 0002)。改这个前缀会让已有配置里的组失去标记,别改。
*/
export const GENERATED_PREFIX = 'patchbay:'
export function isGenerated(name: string): boolean {
return name.startsWith(GENERATED_PREFIX)
}
/** 手动选的那个组。入站的 `proxy:` 指向它,它的当前选中决定这一路走哪。 */
export function proxyGroupName(inbound: string): string {
return `${GENERATED_PREFIX}${inbound}`
}
/** 自动测速组,作为 SELECT 的一个成员出现。 */
export function autoGroupName(inbound: string): string {
return `${GENERATED_PREFIX}${inbound} AUTO`
}
/** 故障转移组,同上。 */
export function fallbackGroupName(inbound: string): string {
return `${GENERATED_PREFIX}${inbound} FALLBACK`
}
/** 链式代理的入口组。订阅副本的 `dialer-proxy` 指向它。 */
export function chainGroupName(inbound: string): string {
return `${GENERATED_PREFIX}${inbound} 链式`
}
/**
* 一个出站在界面上叫什么。
*
* 生成的组要去掉 `patchbay:` 前缀和入站名。用户从没建过这些组,让他在卡片和链条上读到
* `patchbay:test1 FALLBACK` 只是噪音——那一屏本来就是这一路入站的详情,名字里再重复
* 一遍入站名不增加任何信息。
*/
export function displayName(name: string): string {
if (!isGenerated(name)) return name
const rest = name.slice(GENERATED_PREFIX.length)
for (const [suffix, label] of [
[' AUTO', 'AUTO'],
[' FALLBACK', 'FALLBACK'],
[' 链式', '链式代理'],
] as const) {
if (rest.endsWith(suffix)) return label
}
return rest
}
/** 这一路的三个组,按界面上的显示顺序。 */
function ownGroups(inbound: string): Array<{ name: string; label: string }> {
return [
{ name: proxyGroupName(inbound), label: 'SELECT' },
{ name: autoGroupName(inbound), label: 'AUTO' },
{ name: fallbackGroupName(inbound), label: 'FALLBACK' },
]
}
/** FNV-1a。只用来给名字和文件名去重,不是安全用途,所以不引哈希库,浏览器端也要能算。 */
function shortHash(text: string): string {
let h = 0x811c9dc5
for (let i = 0; i < text.length; i += 1) {
h ^= text.charCodeAt(i)
h = Math.imul(h, 0x01000193) >>> 0
}
return h.toString(16).padStart(8, '0')
}
const pairKey = (inbound: string, source: string) => `${inbound} ${source}`
/**
* 「某一路入站 × 某个来源订阅」这个组合对应的订阅副本叫什么。
*
* 名字里带哈希是因为 `proxy-providers` 是个映射,两个组合撞名会让其中一个被静默丢掉,
* 表现是链式代理挂到了别的入站上。带上入站名只是为了翻配置文件时读得懂。
*/
export function chainProviderName(inbound: string, source: string): string {
return `${GENERATED_PREFIX}chain ${inbound} ${shortHash(pairKey(inbound, source))}`
}
/**
* 一个订阅的缓存文件落在哪。
*
* 内核把拉回来的内容写在这里(内核源码 component/resource/vehicle.go:42-47)。没写
* `path:` 时它按 url 哈希自己生成一个(adapter/provider/parser.go:87),那个路径 Patchbay
* 算不出来,所以缺的时候补一个确定的进去。
*/
export function providerCachePath(name: string): string {
const safe = name.replace(/[^\p{L}\p{N}_-]+/gu, '-').replace(/^-+|-+$/g, '')
return `./providers/${safe || shortHash(name)}.yaml`
}
/** 一组线路从哪来、要哪些。三个组共用同一份,它们只是挑法不同。 */
export interface GroupSpec {
/** 成员来自哪几个订阅,写进组的 `use:` */
sources: string[]
/** 只要名字匹配这个正则的线路。null 表示全要 */
filter: string | null
}
/** 一路入站的出站设置。 */
export interface OutboundSetup {
proxy: GroupSpec
/** 链式代理的入口。null 表示没开 */
chain: GroupSpec | null
}
function isPlainObject(value: unknown): value is ConfigObject {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function groupsOf(data: ConfigObject): ConfigObject[] {
return (Array.isArray(data['proxy-groups']) ? data['proxy-groups'] : []).filter(isPlainObject)
}
function providersOf(data: ConfigObject): ConfigObject {
return isPlainObject(data['proxy-providers']) ? data['proxy-providers'] : {}
}
function findGroup(data: ConfigObject, name: string): ConfigObject | null {
return groupsOf(data).find((g) => g.name === name) ?? null
}
function stringList(value: unknown): string[] {
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
}
function specOf(group: ConfigObject): GroupSpec {
return {
sources: stringList(group.use),
filter: typeof group.filter === 'string' && group.filter ? group.filter : null,
}
}
/** 用户自己配的订阅,不含 Patchbay 生成的副本。界面上「来源」能选的就是这些。 */
export function userProviders(data: ConfigObject): string[] {
return Object.keys(providersOf(data)).filter((name) => !isGenerated(name))
}
/** 某个策略组从哪几个订阅取成员。组不存在时返回 null。 */
export function groupUses(data: ConfigObject, name: string): string[] | null {
const group = findGroup(data, name)
return group ? stringList(group.use) : null
}
/** 这个订阅副本是哪一路入站的。不是副本、或者认不出归属时返回 null。 */
function chainOwnerOf(provider: unknown): string | null {
if (!isPlainObject(provider)) return null
const override = provider.override
if (!isPlainObject(override)) return null
const target = override['dialer-proxy']
if (typeof target !== 'string' || !isGenerated(target)) return null
const suffix = ' 链式'
if (!target.endsWith(suffix)) return null
return target.slice(GENERATED_PREFIX.length, target.length - suffix.length)
}
/** 副本的来源订阅叫什么。靠读同一个缓存文件来认,因为名字不可靠解析。 */
function sourceOfCopy(data: ConfigObject, copy: ConfigObject): string | null {
if (typeof copy.path !== 'string') return null
for (const [name, entry] of Object.entries(providersOf(data))) {
if (isGenerated(name) || !isPlainObject(entry)) continue
if (entry.path === copy.path) return name
}
return null
}
/**
* 读出这一路入站当前的出站设置。
*
* 返回 null 表示它还没在专属组模式下,可能是走规则表、直连,或者指向用户自己建的组。
*/
export function readSetup(data: ConfigObject, inbound: string): OutboundSetup | null {
const proxyGroup = findGroup(data, proxyGroupName(inbound))
if (!proxyGroup) return null
const spec = specOf(proxyGroup)
const providers = providersOf(data)
const copies = spec.sources.filter((name) => chainOwnerOf(providers[name]) === inbound)
if (copies.length === 0) return { proxy: spec, chain: null }
const chainGroup = findGroup(data, chainGroupName(inbound))
const sources = copies
.map((name) => sourceOfCopy(data, providers[name] as ConfigObject))
.filter((name): name is string => name !== null)
return {
proxy: { sources, filter: spec.filter },
chain: chainGroup ? specOf(chainGroup) : { sources: [], filter: null },
}
}
function makeGroup(
name: string,
type: string,
use: string[],
filter: string | null,
members: string[] = [],
): ConfigObject {
const group: ConfigObject = { name, type }
if (members.length > 0) group.proxies = members
if (use.length > 0) group.use = use
if (filter) group.filter = filter
// url-test 和 fallback 要有测速地址才知道谁快谁通。不写的话内核会借用来源订阅自己的
// 健康检查地址(adapter/outboundgroup/parser.go:139-148),但那依赖订阅写了它,
// 不能指望;写死一个和内核默认一致的更稳。
if (type !== 'select') {
group.url = 'https://www.gstatic.com/generate_204'
group.interval = 300
}
return group
}
function upsert(list: ConfigObject[], entry: ConfigObject): ConfigObject[] {
const at = list.findIndex((item) => item.name === entry.name)
if (at < 0) return [...list, entry]
const next = [...list]
next[at] = entry
return next
}
/**
* 照着一个用户订阅做出带 `dialer-proxy` 的那一份。
*
* 副本是 `type: file`,读的正是原订阅那个缓存文件,自己不联网。这一点是硬性的:副本要是
* 自己去拉,订阅地址一不可达它就是空的,而这一路入站的线路全部来自它,结果是端口还在
* 监听却一条线都没有。派生自原订阅已经落盘的内容,原订阅有什么副本就有什么。
*
* 内核对 file 类型的 provider 自带文件监视(component/resource/fetcher.go:212-228),
* 原订阅刷新写盘之后副本自动跟着更新,不需要 Patchbay 做任何事。
*
* `filter` 这些影响「这个订阅里有哪些线路」的字段照抄,`url` 和 `interval` 去掉,
* 它们只对 http 类型有意义。
*/
function makeChainProvider(source: ConfigObject, inbound: string, cachePath: string): ConfigObject {
const override = isPlainObject(source.override) ? { ...source.override } : {}
override['dialer-proxy'] = chainGroupName(inbound)
const { url: _url, interval: _interval, ...rest } = source
return { ...rest, type: 'file', path: cachePath, override }
}
/**
* 把一路入站的出站设置写回配置。
*
* 开了链式代理时,三个组的成员都改从订阅副本里取,因为只有副本挂着 `dialer-proxy`。
* 用户选的来源订阅仍然可以从副本的 `url` 还原出来,所以配置文件之外不需要另存状态。
*/
export function applySetup(data: ConfigObject, inbound: string, setup: OutboundSetup): ConfigObject {
const next = { ...data }
const chained = setup.chain !== null
const providers = { ...providersOf(next) }
// 先清掉这一路原有的副本,再按新的来源重建。改来源时旧的副本必须消失,
// 否则代理组不再引用它,它就成了一份没人用却还在定时拉取的订阅。
for (const [name, entry] of Object.entries(providers)) {
if (chainOwnerOf(entry) === inbound) delete providers[name]
}
const use: string[] = []
if (chained) {
for (const sourceName of setup.proxy.sources) {
const source = providers[sourceName]
if (!isPlainObject(source)) continue
// 副本靠「读同一个缓存文件」认亲。原订阅没写 path 时内核按 url 哈希自己生成一个,
// 那个路径这边算不出来,所以先给原订阅补一个确定的。
const cachePath =
typeof source.path === 'string' && source.path ? source.path : providerCachePath(sourceName)
providers[sourceName] = { ...source, path: cachePath }
const copyName = chainProviderName(inbound, sourceName)
providers[copyName] = makeChainProvider(providers[sourceName], inbound, cachePath)
use.push(copyName)
}
} else {
use.push(...setup.proxy.sources)
}
const { filter } = setup.proxy
let groups = groupsOf(next)
groups = upsert(
groups,
makeGroup(proxyGroupName(inbound), 'select', use, filter, [
'DIRECT',
autoGroupName(inbound),
fallbackGroupName(inbound),
]),
)
groups = upsert(groups, makeGroup(autoGroupName(inbound), 'url-test', use, filter))
groups = upsert(groups, makeGroup(fallbackGroupName(inbound), 'fallback', use, filter))
if (chained) {
groups = upsert(
groups,
makeGroup(chainGroupName(inbound), 'select', setup.chain!.sources, setup.chain!.filter),
)
} else {
groups = groups.filter((g) => g.name !== chainGroupName(inbound))
}
next['proxy-groups'] = groups
if (Object.keys(providers).length === 0) delete next['proxy-providers']
else next['proxy-providers'] = providers
const listeners = (Array.isArray(next.listeners) ? next.listeners : []).map((entry) =>
isPlainObject(entry) && entry.name === inbound
? { ...entry, proxy: proxyGroupName(inbound) }
: entry,
)
if (listeners.length > 0) next.listeners = listeners
return next
}
/** 配置里指向某个名字的地方有几处。用来判断生成的东西还有没有人在用。 */
function referencesTo(data: ConfigObject, name: string): number {
let count = 0
for (const entry of Array.isArray(data.listeners) ? data.listeners : []) {
if (isPlainObject(entry) && entry.proxy === name) count += 1
}
for (const group of groupsOf(data)) {
if (stringList(group.proxies).includes(name)) count += 1
if (stringList(group.use).includes(name)) count += 1
}
for (const entry of Object.values(providersOf(data))) {
if (!isPlainObject(entry) || !isPlainObject(entry.override)) continue
if (entry.override['dialer-proxy'] === name) count += 1
}
for (const rule of Array.isArray(data.rules) ? data.rules : []) {
// 规则是逗号分隔的,目标出站是其中一段,形如 MATCH,目标 或 DOMAIN,x,目标
if (typeof rule === 'string' && rule.split(',').some((part) => part.trim() === name)) count += 1
}
return count
}
/**
* 删掉没人再引用的生成组和订阅副本。
*
* 每次改完配置都跑一遍。删一路入站之后,它的几个组和几份副本会先后变成孤儿,不清理的话
* 文件里就攒下一堆用户从没主动建过的东西,而副本还在按 interval 定时联网。
*
* 要反复扫:AUTO 和 FALLBACK 被 SELECT 引用,入口组被副本引用,副本被那三个组引用,
* 所以删掉 SELECT 之后下一轮才轮到它们。只动带前缀的,用户自己建的一律不碰。
*/
export function pruneGenerated(data: ConfigObject): ConfigObject {
const groups = Array.isArray(data['proxy-groups']) ? data['proxy-groups'] : []
const keptGroups = groups.filter((group) => {
if (!isPlainObject(group)) return true
const name = group.name
if (typeof name !== 'string' || !isGenerated(name)) return true
return referencesTo(data, name) > 0
})
const providers = providersOf(data)
const keptProviders = Object.entries(providers).filter(
([name]) => !isGenerated(name) || referencesTo(data, name) > 0,
)
const providersChanged = keptProviders.length !== Object.keys(providers).length
if (keptGroups.length === groups.length && !providersChanged) return data
const next = { ...data }
if (keptGroups.length === 0) delete next['proxy-groups']
else next['proxy-groups'] = keptGroups
if (providersChanged) {
if (keptProviders.length === 0) delete next['proxy-providers']
else next['proxy-providers'] = Object.fromEntries(keptProviders)
}
return pruneGenerated(next)
}
/**
* 把所有已接管入站的生成组按当前的生成规则重建一遍。
*
* 每次写配置前跑。生成的东西必须永远和生成它的代码一致,否则改过生成规则之后,早先建的
* 那些就停在旧形状上,界面按新形状去找,找不到就静默少一块——tab 少了两个正是这么来的。
* `applySetup` 幂等,形状没变时返回的内容一样,落盘链路会看出内容没变而跳过重载。
*/
export function syncGenerated(data: ConfigObject, inbounds: Inbound[]): ConfigObject {
let next = data
for (const inbound of inbounds) {
const setup = readSetup(next, inbound.name)
const mode = inbound.outbound
if (!setup || mode.kind !== 'named' || mode.name !== proxyGroupName(inbound.name)) continue
next = applySetup(next, inbound.name, setup)
}
return next
}
/** 面板上一个 tab 对应的策略组。 */
export interface PanelGroup {
name: string
/** tab 上显示什么。自己的组显示挑法,共用的组显示它自己的名字 */
label: string
/** 它从哪几个订阅取成员。测延迟要顺着来源找,见 web/runtime.ts 的 membersOf */
uses: string[]
/** 能不能点成员换选中 */
pickable: boolean
}
/**
* 这一路入站的面板上能操作哪些策略组。
*
* 只此一处回答这个问题。之前它散在四个地方(页面算一次能不能点、组件再算一次、
* 共用与否又各算一次),加一种情况就要同时改四处,漏一处就是界面和实际操作对不上。
*
* 两种情况:接管过的入站是它自己那三个组;没接管的(比如 `mixed-port`,配置顶层的端口
* 字段没有 `proxy` 可写)落到它顺着规则表走到的那个手动选择组上,那个组是共用的。
*/
export function panelGroups(
data: ConfigObject,
runtime: Record<string, RuntimeNode>,
inbound: Inbound,
): { groups: PanelGroup[]; shared: boolean } {
const mode = inbound.outbound
const managed = mode.kind === 'named' && mode.name === proxyGroupName(inbound.name)
if (managed) {
return {
shared: false,
groups: ownGroups(inbound.name)
// 保存完到内核重载完之间,组已经在配置里但运行时还没有,这时先不显示那个 tab
.filter((g) => runtime[g.name])
.map((g) => ({
...g,
uses: groupUses(data, g.name) ?? [],
// 只有手动选的那个能点。另外两个自己决定用哪条,理由见 outbound-chain.ts
pickable: runtime[g.name]?.type === 'Selector',
})),
}
}
const chain = resolveChain(runtime, resolveDestination(data, inbound))
const fallback = lastSwitchableGroup(runtime, chain)
if (!fallback) return { groups: [], shared: false }
return {
shared: true,
groups: [
{
name: fallback.group,
label: fallback.group,
uses: groupUses(data, fallback.group) ?? [],
pickable: true,
},
],
}
}
/**
* 筛选条件会留下哪些线路。界面上用来在保存前当场告诉用户「匹配到几条」。
*
* 照着内核的规则算(`adapter/outboundgroup/groupbase.go:72-76, 168-195`):反引号把
* 条件切成多条独立正则,取并集;每条都是部分匹配,不自动加锚点。
*
* 内核用的是支持前后向查找的 .NET 风味引擎,浏览器只有 JS 的,所以复杂写法这里算出来的
* 数字可能和内核不一致。写法有误时返回 null,界面据此提示而不是显示一个错的数字。
*/
export function linesMatching(filter: string | null, lines: string[]): string[] | null {
if (!filter) return lines
let regexps: RegExp[]
try {
regexps = filter.split('`').map((part) => new RegExp(part))
} catch {
return null
}
return lines.filter((line) => regexps.some((re) => re.test(line)))
}
+34
View File
@@ -6,7 +6,10 @@ import {
collectInbounds,
collectOutboundNames,
fallbackTarget,
isUnsetOutbound,
outboundLabel,
outboundToProxyField,
OUTBOUND_PRESETS,
resolveDestination,
} from './inbounds.ts'
@@ -145,3 +148,34 @@ describe('流量最终去哪', () => {
expect(fallbackTarget({})).toBeNull()
})
})
describe('出站预设表是读写显示三者的唯一约定', () => {
it('每种预设的字段值和标签一一对应', () => {
expect(OUTBOUND_PRESETS.map((p) => [p.mode.kind, p.field, p.label])).toEqual([
['rules', undefined, 'RULE'],
['direct', 'DIRECT', 'DIRECT'],
['global', 'GLOBAL', 'GLOBAL'],
])
})
it('从配置读出来再写回去,值不变', () => {
// 这条是防止「显示的」和「写进文件的」跑偏:任何一种模式转一圈都要回到原值
for (const preset of OUTBOUND_PRESETS) {
expect(outboundToProxyField(preset.mode)).toBe(preset.field)
}
expect(outboundToProxyField({ kind: 'named', name: 'AUTO' })).toBe('AUTO')
})
it('界面上的名字用配置里的原词', () => {
expect(outboundLabel({ kind: 'rules' })).toBe('RULE')
expect(outboundLabel({ kind: 'direct' })).toBe('DIRECT')
expect(outboundLabel({ kind: 'global' })).toBe('GLOBAL')
expect(outboundLabel({ kind: 'named', name: '固定-Gomami' })).toBe('固定-Gomami')
})
it('只有 RULE 算「没明确指定」,界面据此弱化显示', () => {
expect(isUnsetOutbound({ kind: 'rules' })).toBe(true)
expect(isUnsetOutbound({ kind: 'direct' })).toBe(false)
expect(isUnsetOutbound({ kind: 'named', name: 'AUTO' })).toBe(false)
})
})
+45 -11
View File
@@ -55,23 +55,59 @@ export interface Inbound {
legacyKey: string | null
/** 在 listeners 数组里的下标,用于写回。旧写法为 null */
listenerIndex: number | null
/** 给人看的一句话说明,主要是给默认入站解释它为什么不能改出站 */
note: string | null
}
/**
* 不用指名道姓的那几种出站,以及它们各自对应配置里的什么值。
*
* 这张表是「读配置 → 界面 → 写回配置」三者的唯一约定来源。之前它被拆成四份散在
* 各处(读一份、显示一份、写回一份、表单里又抄了一份),加一种出站模式就要同时改
* 四个地方,漏一个就是「界面显示的」和「实际写进文件的」对不上。
*
* `field` 为 undefined 表示配置里**不写** proxy 这个字段——「没有这个键」和
* 「这个键是空字符串」在 YAML 里是两回事。
*/
export const OUTBOUND_PRESETS: Array<{
mode: OutboundMode
field: string | undefined
label: string
}> = [
{ mode: { kind: 'rules' }, field: undefined, label: 'RULE' },
{ mode: { kind: 'direct' }, field: 'DIRECT', label: 'DIRECT' },
{ mode: { kind: 'global' }, field: 'GLOBAL', label: 'GLOBAL' },
]
function outboundOf(proxy: unknown): OutboundMode {
if (typeof proxy !== 'string' || proxy === '') return { kind: 'rules' }
if (proxy === 'DIRECT') return { kind: 'direct' }
if (proxy === 'GLOBAL') return { kind: 'global' }
return { kind: 'named', name: proxy }
const preset = OUTBOUND_PRESETS.find((p) => p.field === proxy)
return preset ? preset.mode : { kind: 'named', name: proxy }
}
/** 把出站去向写回成配置里 proxy 字段该有的值。返回 undefined 表示不写这个字段。 */
export function outboundToProxyField(mode: OutboundMode): string | undefined {
if (mode.kind === 'rules') return undefined
if (mode.kind === 'direct') return 'DIRECT'
if (mode.kind === 'global') return 'GLOBAL'
return mode.name
if (mode.kind === 'named') return mode.name
return OUTBOUND_PRESETS.find((p) => p.mode.kind === mode.kind)?.field
}
/** 出站在界面上的名字。指名道姓的就是它自己的名字,其余用配置里的原词。 */
export function outboundLabel(mode: OutboundMode): string {
if (mode.kind === 'named') return mode.name
return OUTBOUND_PRESETS.find((p) => p.mode.kind === mode.kind)?.label ?? mode.kind
}
/**
* 是不是「没有明确指定」那种状态。
*
* 界面上用来决定要不要弱化显示:RULE 是不写 proxy 字段时的默认结果,不是用户做出的
* 选择,跟他明确选了 DIRECT 是两回事,不该长得一样。
*/
export function isUnsetOutbound(mode: OutboundMode): boolean {
return mode.kind === 'rules'
}
/** 入站类型在界面上怎么念。以配置里的原词为准,不另造描述。 */
export function inboundTypeLabel(type: string): string {
return type === '' ? '—' : type
}
/**
@@ -112,7 +148,6 @@ export function collectInbounds(data: ConfigObject): Inbound[] {
isDefault: true,
legacyKey: key,
listenerIndex: null,
note: `由配置文件顶层的 ${key} 声明。这种写法没法单独指定出站,流量一律走分流规则。想让这个端口固定走某个出站,要把它改成命名入站。`,
})
}
@@ -131,7 +166,6 @@ export function collectInbounds(data: ConfigObject): Inbound[] {
isDefault: false,
legacyKey: null,
listenerIndex: index,
note: null,
})
})
+85
View File
@@ -0,0 +1,85 @@
import { describe, expect, it } from 'bun:test'
import { lastSwitchableGroup, resolveChain } from './outbound-chain.ts'
import type { RuntimeNode } from './outbound-chain.ts'
/**
* 仿照真实那台机器:PROXY 手动选,它选中了按延迟自动挑的 AUTO,AUTO 挑了一条订阅线路。
* PROXY 的成员是手写的 AUTO、DIRECT 加上订阅带进来的两条线路。
*/
const runtime: Record<string, RuntimeNode> = {
PROXY: { type: 'Selector', now: 'AUTO', all: ['AUTO', 'DIRECT', '[vmess]DMIT', '[vless]Gomami'] },
AUTO: { type: 'URLTest', now: '[vless]Gomami', all: ['[vmess]DMIT', '[vless]Gomami'] },
'[vless]Gomami': { type: 'Vless' },
'[vmess]DMIT': { type: 'Vmess' },
DIRECT: { type: 'Direct' },
}
describe('解析流量最终走到哪条线', () => {
it('一路跟着当前选中走到底', () => {
expect(resolveChain(runtime, 'PROXY')).toEqual(['PROXY', 'AUTO', '[vless]Gomami'])
})
it('起点就是线路时链条只有它自己', () => {
expect(resolveChain(runtime, '[vless]Gomami')).toEqual(['[vless]Gomami'])
})
it('没有落脚点时是空链条', () => {
expect(resolveChain(runtime, null)).toEqual([])
})
it('落脚在一个内核不认识的名字上时也只返回它自己', () => {
// 配置引用了一个不存在的出站时会走到这里,界面要能显示而不是崩掉
expect(resolveChain(runtime, '不存在的组')).toEqual(['不存在的组'])
})
it('策略组互相引用成环时停下来,不会转死', () => {
const looped: Record<string, RuntimeNode> = {
A: { type: 'Selector', now: 'B', all: ['B'] },
B: { type: 'Selector', now: 'A', all: ['A'] },
}
expect(resolveChain(looped, 'A')).toEqual(['A', 'B'])
})
})
describe('找出用户能换选中的那一层', () => {
it('跳过自动决定的组,落在最后一个 Selector 上', () => {
// 链条是 PROXY(Selector) → AUTO(URLTest) → 线路。能点的是 PROXY 不是 AUTO:
// 内核对 URLTest 也接受手动指定,但那条线测不通时指定会临时让位,
// 和「选了就一直是它」不是一回事,摆成同一个控件会骗人。
const chain = resolveChain(runtime, 'PROXY')
expect(lastSwitchableGroup(runtime, chain)).toEqual({
group: 'PROXY',
members: ['AUTO', 'DIRECT', '[vmess]DMIT', '[vless]Gomami'],
now: 'AUTO',
})
})
it('有多个 Selector 时取最靠近线路的那个', () => {
// 越靠近线路越接近「换线路」这个意图;前面的层换的是「走哪套策略」
const nested: Record<string, RuntimeNode> = {
外层: { type: 'Selector', now: '内层', all: ['内层'] },
内层: { type: 'Selector', now: '线路A', all: ['线路A', '线路B'] },
线路A: { type: 'Vmess' },
}
expect(lastSwitchableGroup(nested, resolveChain(nested, '外层'))?.group).toBe('内层')
})
it('整条链都不是 Selector 时返回空', () => {
const auto: Record<string, RuntimeNode> = {
AUTO: { type: 'URLTest', now: '线路A', all: ['线路A'] },
线路A: { type: 'Vmess' },
}
expect(lastSwitchableGroup(auto, resolveChain(auto, 'AUTO'))).toBeNull()
})
it('链条上一个策略组都没有时返回空', () => {
expect(lastSwitchableGroup(runtime, ['[vless]Gomami'])).toBeNull()
expect(lastSwitchableGroup(runtime, [])).toBeNull()
})
it('Selector 存在但成员是空的,不算可切换', () => {
// 筛选条件没匹配到任何线路时会出现这种组,给出一个点不动的列表只会让人困惑
expect(lastSwitchableGroup({ 空组: { type: 'Selector', all: [], now: '' } }, ['空组'])).toBeNull()
})
})
+72
View File
@@ -0,0 +1,72 @@
/**
* 「这个端口现在到底走哪条线」——这个工具要回答的核心问题。
*
* 答案往往不是一跳能到的:一路入站落在 `PROXY` 组上,`PROXY` 选中了 `AUTO`,
* `AUTO` 又按延迟挑了某条线路。只显示第一层等于没回答。
*
* 这里只做纯计算,输入是内核报上来的运行时状态,输出是名字数组。放在 shared 里
* 是为了能被 `bun test` 覆盖——它带防环处理,而防环这种事写在组件的 computed 里
* 就再也没人测得到。
*/
/** 运行时状态里跟解析链路有关的部分。完整定义在 web/api.ts。 */
export interface RuntimeNode {
/** 出站类型。策略组是 Selector / URLTest / Fallback / LoadBalance 之一 */
type?: string
/** 策略组当前选中的成员。不是策略组就没有这个字段 */
now?: string
/** 策略组的成员列表 */
all?: string[]
}
/**
* 从落脚的出站一路跟着「当前选中」往下走。
*
* 返回的数组第一项是起点,最后一项是走到头的那个名字。起点为 null 时返回空数组。
* 策略组理论上可以互相引用成环,遇到重复的名字就停下——内核自己会拒绝这种配置,
* 但界面不能因为一份坏配置就转到卡死。
*/
export function resolveChain(
runtime: Record<string, RuntimeNode>,
start: string | null,
): string[] {
const hops: string[] = []
let cursor = start
while (cursor && !hops.includes(cursor)) {
hops.push(cursor)
cursor = runtime[cursor]?.now ?? null
}
return hops
}
export interface SwitchableGroup {
group: string
members: string[]
now: string
}
/**
* 链条上最后一个 `Selector` 组。这一路入站没被 Patchbay 接管时,界面上能点的就是它。
*
* 取最后一个而不是第一个,是因为越靠近线路的那一层越接近「换线路」这个意图;
* 前面的层换的是「走哪套策略」,那是另一回事。
*
* 只认 `Selector`,尽管内核对 `URLTest` 和 `Fallback` 也接受手动指定
* (hub/route/proxies.go:85-90 检查的是 `SelectAble` 接口,不是类型)。原因是那两种的
* 手动指定会自己失效:`URLTest` 选中的线路测不通时临时让位给最快的
* (adapter/outboundgroup/urltest.go:103-116),`Fallback` 更狠,测不通一次就把手动指定
* 永久清掉(fallback.go:117)。把它们和「选了就一直是它」摆成同一个控件会骗人。
*/
export function lastSwitchableGroup(
runtime: Record<string, RuntimeNode>,
chain: string[],
): SwitchableGroup | null {
for (let i = chain.length - 1; i >= 0; i -= 1) {
const name = chain[i]!
const node = runtime[name]
if (!node?.all?.length || node.type !== 'Selector') continue
return { group: name, members: node.all, now: node.now ?? '' }
}
return null
}
+8 -5
View File
@@ -1,8 +1,9 @@
import { describe, expect, it } from 'bun:test'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { openDocument, replaceDocumentData } from '../vendor/config-editor/index.ts'
import { openDocument } from '../vendor/config-editor/index.ts'
import type { ConfigObject } from '../vendor/config-editor/index.ts'
import { rewriteYaml } from '../server/config-store.ts'
import { restoreInlineCommentAlignment } from './yaml-cosmetics.ts'
const fixture = readFileSync(
@@ -12,12 +13,14 @@ const fixture = readFileSync(
const clone = (v: unknown) => JSON.parse(JSON.stringify(v)) as ConfigObject
/** 走一遍真实的写回链路:解析 → 改 → 写回 → 修复格式。 */
/**
* 走**生产用的那一条**写回路径,而不是在测试里重拼一遍。
* 自己拼的话,落盘链路里漏掉其中一步这些测试照样会绿——那就白写了。
*/
function roundtrip(source: string, mutate: (draft: ConfigObject) => void): string {
const doc = openDocument(source)
const draft = clone(doc.data)
const draft = clone(openDocument(source).data)
mutate(draft)
return restoreInlineCommentAlignment(source, replaceDocumentData(doc, draft).yaml)
return rewriteYaml(source, draft)
}
describe('写回一份带注释的配置', () => {
+1 -3
View File
@@ -21,9 +21,7 @@
"jsx": "preserve",
"baseUrl": ".",
"paths": {
"~/*": ["./web/*"],
"@shared/*": ["./shared/*"],
"@config-editor": ["./vendor/config-editor/index.ts"]
"@shared/*": ["./shared/*"]
}
},
"include": [
-1
View File
@@ -18,7 +18,6 @@ export default defineConfig({
],
resolve: {
alias: {
'~': fileURLToPath(new URL('./web', import.meta.url)),
'@shared': fileURLToPath(new URL('./shared', import.meta.url)),
},
},
+18 -86
View File
@@ -1,46 +1,39 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { ApiError, api, getToken, setToken } from './api'
import type { ConfigSnapshot, ProxyInfo } from './api'
import { ApiError, api, clearToken, getToken, setToken } from './api'
import type { ConfigSnapshot } from './api'
import { NAV } from './nav'
import { density, toggleDensity } from './prefs'
import { kernel, reloadRuntime } from './runtime'
import RouterPage from './views/RouterPage.vue'
import TokenGate from './views/TokenGate.vue'
import IconFold from '~icons/ri/sidebar-fold-line'
import IconUnfold from '~icons/ri/sidebar-unfold-line'
const snapshot = ref<ConfigSnapshot | null>(null)
const kernel = ref<{ online: boolean; version?: string }>({ online: false })
const providerLines = ref<string[]>([])
/** 订阅线路 → 它所属的订阅名。测延迟时要用它选对接口 */
const lineProvider = ref<Record<string, string>>({})
const runtime = ref<Record<string, ProxyInfo>>({})
const needsToken = ref(!getToken())
const loadError = ref('')
const booted = ref(false)
const refreshing = ref(false)
const active = ref('router')
const active = ref('dashboard')
/**
* 重新读一遍状态。
*
* 关键在于**不能把页面拆掉重建**:之前每次刷新都会先切到「读取中」,
* 于是路由页被卸载、选中的那一路入站丢失,改完一个设置还要重新找回原来的位置。
* 所以只有首次加载显示占位,之后都是原地更新。
* 关键在于**不能把页面拆掉重建**:之前每次刷新都会先切到「读取中」,于是路由页被卸载、
* 选中的那一路入站丢失,改完一个设置还要重新找回原来的位置。所以只有首次加载显示占位,
* 之后都是原地更新。
*/
async function load() {
refreshing.value = true
loadError.value = ''
try {
const [config, status] = await Promise.all([api.readConfig(), api.kernel()])
snapshot.value = config
kernel.value = status
snapshot.value = await api.readConfig()
needsToken.value = false
// 订阅里有哪些线路只有运行中的内核知道,配置文件里只有一个订阅地址。
// 拿不到不算错误——界面照常能编辑,只是订阅线路那一档不可选。
runtime.value = status.online ? await readRuntime() : {}
await reloadRuntime()
} catch (error) {
if (error instanceof ApiError && error.unauthorized) {
clearToken()
needsToken.value = true
} else {
loadError.value = error instanceof Error ? error.message : String(error)
@@ -51,69 +44,6 @@ async function load() {
}
}
/**
* 出站的运行时状态:协议类型、策略组当前选中了谁、最近一次延迟。
*
* 要读两处。/proxies 只包含内核全局名字表里的东西——内置出站、自有线路、策略组;
* 订阅线路不在那张表上,它们的类型和延迟只能从 /providers/proxies 拿。
* 两边合成一张表,界面上就不用关心某个名字是从哪来的了。
*
* 顺带记下每条订阅线路属于哪个订阅:测它的延迟必须从所属订阅进去。
*/
async function readRuntime(): Promise<Record<string, ProxyInfo>> {
const merged: Record<string, ProxyInfo> = {}
const lines: string[] = []
const owner: Record<string, string> = {}
try {
Object.assign(merged, (await api.proxies()).proxies)
} catch {
// 拿不到就当没有,界面照常显示,只是没有延迟数字
}
try {
const { providers } = await api.providers()
for (const [name, provider] of Object.entries(providers)) {
// 内核会给每个用了 proxies 的策略组造一个内部 provider,那些不是订阅
if (provider.vehicleType === 'Compatible') continue
for (const line of provider.proxies) {
merged[line.name] = line
lines.push(line.name)
owner[line.name] = name
}
}
} catch {
// 同上
}
providerLines.value = lines
lineProvider.value = owner
return merged
}
/**
* 切换策略组时先在本地改掉,不等内核回话。
*
* 这一步不写配置文件,失败率极低;而等一个往返再更新会让点击感觉发木。
* 真失败了随后的刷新会把状态纠正回来。
*/
function optimisticSelect(group: string, member: string) {
const info = runtime.value[group]
if (info) info.now = member
}
/**
* 只重读运行时状态,不碰配置文件。
*
* 切换策略组、测一条线路的延迟,改变的只是内核的运行状态。走完整的 load() 会让服务端
* 重读整份配置、重新解析、再跑一遍引用校验,外加两个多余的往返——最便宜的动作触发了
* 最贵的操作。
*/
async function reloadRuntime() {
if (!kernel.value.online) return
runtime.value = await readRuntime()
}
function submitToken(value: string) {
setToken(value)
void load()
@@ -192,13 +122,7 @@ const current = computed(() => NAV.find((n) => n.key === active.value))
v-if="active === 'router'"
:data="snapshot.data"
:revision="snapshot.revision"
:kernel-online="kernel.online"
:provider-lines="providerLines"
:line-provider="lineProvider"
:runtime="runtime"
@saved="load"
@optimistic-select="optimisticSelect"
@runtime-changed="reloadRuntime"
/>
<div v-else class="note">
@@ -222,7 +146,15 @@ const current = computed(() => NAV.find((n) => n.key === active.value))
}
/* ── 侧栏 ───────────────────────────────────── */
/*
* 钉在视口里。不加 sticky 的话它会被网格行撑到和主区一样高,页面一长,
* 导航就跟着滚出屏幕外,而它是全局导航,任何时候都该够得着。
*/
.side {
position: sticky;
top: 0;
align-self: start;
height: 100vh;
display: flex;
flex-direction: column;
gap: var(--s-5);
-9
View File
@@ -69,7 +69,6 @@ async function request<T>(method: string, path: string, body?: unknown): Promise
export interface ConfigSnapshot {
data: ConfigObject
yaml: string
revision: string
diagnostics: ConfigDiagnostic[]
}
@@ -81,14 +80,6 @@ export interface ApplySuccess {
reloadMessage: string
}
export interface ApplyFailure {
ok: false
stage: 'stale' | 'self-check' | 'kernel-check' | 'write' | 'reload'
message: string
hint: string
restored: boolean
}
export interface ProxyInfo {
/** 出站的名字。/proxies 用键名标识,provider 里的线路则带在对象上 */
name: string
+124
View File
@@ -0,0 +1,124 @@
<script setup lang="ts">
/**
* 入站列表。每行一路入站:端口、类型、名字、它落在哪个出站上。
*
* 只管显示和选中,不碰任何数据。
*/
import { inboundTypeLabel, isUnsetOutbound, outboundLabel } from '@shared/inbounds.ts'
import { displayName, isGenerated } from '@shared/inbound-groups.ts'
import type { Inbound } from '@shared/inbounds.ts'
import { runtime } from '../runtime'
defineProps<{ inbounds: Inbound[] }>()
const selected = defineModel<string | null>('selected', { required: true })
/**
* 这一行右侧显示什么。
*
* 指向 Patchbay 自动创建的代理组时显示那个组当前选中的线路,而不是组名——组名是
* 「patchbay:」加入站名,和左边的名字列完全重复,等于一列没有信息。
*/
function outboundOf(inbound: Inbound): string {
const mode = inbound.outbound
if (mode.kind !== 'named' || !isGenerated(mode.name)) return outboundLabel(mode)
return displayName(runtime.value[mode.name]?.now ?? '') || '未选择'
}
</script>
<template>
<ol class="rows">
<li v-for="inbound in inbounds" :key="inbound.id">
<button
type="button"
:class="['line', selected === inbound.id && 'is-on']"
@click="selected = inbound.id"
>
<span class="port mono">{{ inbound.port }}</span>
<span class="type mono">{{ inboundTypeLabel(inbound.type) }}</span>
<span class="name">
{{ inbound.name }}
<span v-if="inbound.isDefault" class="tag">默认</span>
</span>
<span :class="['out mono', isUnsetOutbound(inbound.outbound) && 'is-muted']">
{{ outboundOf(inbound) }}
</span>
</button>
</li>
</ol>
</template>
<style scoped>
.rows {
list-style: none;
margin: 0;
padding: 0;
border: 1px solid var(--c-border);
border-radius: var(--r-md);
background: var(--c-surface);
overflow: hidden;
}
.rows li + li {
border-top: 1px solid var(--c-border);
}
.line {
width: 100%;
display: grid;
grid-template-columns: 4.5rem 5rem 1fr minmax(5rem, auto);
align-items: center;
gap: var(--s-3);
padding: var(--s-3) var(--s-4);
border: none;
background: none;
cursor: pointer;
text-align: left;
}
.line:hover {
background: var(--c-surface-sunken);
}
.line.is-on {
background: var(--c-accent-soft);
}
.port {
font-size: var(--t-lg);
font-variant-numeric: tabular-nums;
}
.type {
font-size: var(--t-xs);
color: var(--c-text-faint);
}
.name {
display: flex;
align-items: center;
gap: var(--s-2);
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag {
flex: none;
padding: 0 var(--s-2);
border: 1px solid var(--c-border-strong);
border-radius: 999px;
font-size: var(--t-xs);
color: var(--c-text-soft);
line-height: 1.6;
}
.out {
font-size: var(--t-sm);
text-align: right;
}
.out.is-muted {
color: var(--c-text-faint);
}
</style>
+28 -6
View File
@@ -23,6 +23,11 @@ defineProps<{
testing?: boolean
/** 能不能测延迟。内置出站没得测 */
testable?: boolean
/**
* 选中态用哪一组颜色。同一屏上有两种「当前选中」,一种是流量最后从哪出去,
* 一种是流量先经过哪,不区分颜色就分不清哪张卡属于哪一件事。
*/
tone?: 'proxy' | 'chain'
}>()
const emit = defineEmits<{ pick: []; test: [] }>()
@@ -36,7 +41,15 @@ function delayClass(ms: number | null): string {
</script>
<template>
<div :class="['card', selected && 'is-on', disabledReason && 'is-off', pending && 'is-pending']">
<div
:class="[
'card',
tone === 'chain' && 'tone-chain',
selected && 'is-on',
disabledReason && 'is-off',
pending && 'is-pending',
]"
>
<button
type="button"
class="hit"
@@ -70,6 +83,9 @@ function delayClass(ms: number | null): string {
<style scoped>
.card {
--tone: var(--c-accent);
--tone-soft: var(--c-accent-soft);
--tone-text: var(--c-accent-text);
display: flex;
flex-direction: column;
min-width: 0;
@@ -78,13 +94,19 @@ function delayClass(ms: number | null): string {
background: var(--c-surface-sunken);
}
.card.tone-chain {
--tone: var(--c-chain);
--tone-soft: var(--c-chain-soft);
--tone-text: var(--c-chain-text);
}
.card.is-on {
border-color: var(--c-accent);
background: var(--c-accent-soft);
border-color: var(--tone);
background: var(--tone-soft);
}
.card:not(.is-off):hover {
border-color: var(--c-accent);
border-color: var(--tone);
}
.card.is-off {
@@ -120,7 +142,7 @@ function delayClass(ms: number | null): string {
}
.card.is-on .name {
color: var(--c-accent-text);
color: var(--tone-text);
}
.sub {
@@ -157,7 +179,7 @@ function delayClass(ms: number | null): string {
.delay:hover:not(:disabled) {
background: var(--c-surface);
color: var(--c-accent-text);
color: var(--tone-text);
}
.delay:disabled {
+157
View File
@@ -0,0 +1,157 @@
<script setup lang="ts">
/**
* 挑几个订阅。已选的是一排 tag,末尾一个加号,点开是还没选的那些。
*
* 不用原生 select:它在已选项旁边显示的是「当前值」,而这里要表达的是「已经选了这几个」,
* 两种语义。之前用 select 拼出来的那版,加号和 tag 的对齐、宽度、选中后的复位都得单独调,
* 全是在跟控件本身的默认行为较劲。
*/
import { ref } from 'vue'
import IconAdd from '~icons/ri/add-line'
import IconRemove from '~icons/ri/close-line'
defineProps<{ options: string[] }>()
const chosen = defineModel<string[]>({ required: true })
const open = ref(false)
const root = ref<HTMLElement | null>(null)
function add(name: string) {
chosen.value = [...chosen.value, name]
open.value = false
}
function remove(name: string) {
chosen.value = chosen.value.filter((item) => item !== name)
}
/** 焦点离开整块时收起。判断新焦点还在不在里面,否则点列表里的按钮会先把自己关掉。 */
function onFocusOut(event: FocusEvent) {
const next = event.relatedTarget
if (next instanceof Node && root.value?.contains(next)) return
open.value = false
}
</script>
<template>
<div ref="root" class="picker" @focusout="onFocusOut">
<span v-for="name in chosen" :key="name" class="tag">
{{ name }}
<button type="button" :title="`移除 ${name}`" @click="remove(name)">
<IconRemove />
</button>
</span>
<div v-if="options.some((o) => !chosen.includes(o))" class="add">
<button type="button" class="plus" title="添加订阅" @click="open = !open">
<IconAdd />
</button>
<ul v-if="open" class="menu">
<template v-for="name in options" :key="name">
<li v-if="!chosen.includes(name)">
<button type="button" @click="add(name)">{{ name }}</button>
</li>
</template>
</ul>
</div>
<span v-else-if="chosen.length === 0" class="empty">没有可选的订阅</span>
</div>
</template>
<style scoped>
.picker {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--s-2);
}
.tag {
display: inline-flex;
align-items: center;
gap: var(--s-1);
height: 34px;
padding: 0 var(--s-1) 0 var(--s-3);
border: 1px solid var(--c-border-strong);
border-radius: var(--r-sm);
background: var(--c-surface-sunken);
font-size: var(--t-sm);
}
.tag button {
display: grid;
place-items: center;
width: 22px;
height: 22px;
border: none;
border-radius: var(--r-sm);
background: none;
color: var(--c-text-faint);
cursor: pointer;
}
.tag button:hover {
background: var(--c-surface);
color: var(--c-danger);
}
.add {
position: relative;
}
.plus {
display: grid;
place-items: center;
width: 34px;
height: 34px;
border: 1px dashed var(--c-border-strong);
border-radius: var(--r-sm);
background: none;
color: var(--c-text-faint);
cursor: pointer;
}
.plus:hover {
border-style: solid;
border-color: var(--c-accent);
color: var(--c-accent-text);
}
/* 浮在上面,不能把下面几行顶下去 */
.menu {
position: absolute;
z-index: 1;
top: calc(34px + var(--s-1));
left: 0;
min-width: 10em;
list-style: none;
margin: 0;
padding: var(--s-1);
border: 1px solid var(--c-border-strong);
border-radius: var(--r-md);
background: var(--c-surface);
}
.menu button {
width: 100%;
padding: var(--s-2) var(--s-3);
border: none;
border-radius: var(--r-sm);
background: none;
text-align: left;
font-size: var(--t-sm);
white-space: nowrap;
cursor: pointer;
}
.menu button:hover {
background: var(--c-surface-sunken);
}
.empty {
color: var(--c-text-faint);
font-size: var(--t-sm);
}
</style>
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from 'bun:test'
import { ApiError } from './api'
import { describeTestFailure } from './delay-test'
const LINE = '[vless]Gomami.SIN Secret'
describe('延迟测试失败时告诉用户什么', () => {
it('超时说明是几秒内没完成', () => {
// 只说「超时」,用户不知道是等了 1 秒还是 60 秒,也就不知道该不该重试
expect(describeTestFailure(LINE, new ApiError(504, {}), 5000)).toBe(
`${LINE} 延迟测试超时,5 秒内没有取到测试地址`,
)
})
it('找不到这个名字时指出该从订阅进去测', () => {
// 订阅线路不在内核的全局出站表里,这是本项目最容易踩的一条约束
expect(describeTestFailure(LINE, new ApiError(404, { message: 'Resource not found' }))).toContain(
'不在内核的出站表里',
)
})
it('连接失败且内核没给具体原因时,给出能指导排查的话', () => {
const generic = new ApiError(503, { message: 'An error occurred in the delay test' })
expect(describeTestFailure(LINE, generic)).toBe(
`${LINE} 无法建立连接,线路可能已失效,或本机到该服务器的网络不通`,
)
})
it('内核给了具体原因就原样带上', () => {
const specific = new ApiError(503, { message: 'dial tcp: i/o timeout' })
expect(describeTestFailure(LINE, specific)).toBe(`${LINE} 无法建立连接:dial tcp: i/o timeout`)
})
it('没见过的状态码带上状态码和内核原话', () => {
expect(describeTestFailure(LINE, new ApiError(500, { message: 'boom' }))).toBe(
`${LINE} 延迟测试失败(HTTP 500):boom`,
)
})
it('状态码没见过且内核没说话时不留一个空冒号', () => {
expect(describeTestFailure(LINE, new ApiError(500, {}))).toBe(
`${LINE} 延迟测试失败(HTTP 500)`,
)
})
it('不是接口错误时也要说出是什么', () => {
// 网络断了、代码抛了异常,都会走到这里,不能显示成 [object Object]
expect(describeTestFailure(LINE, new TypeError('Failed to fetch'))).toBe(
`${LINE} 延迟测试失败:TypeError: Failed to fetch`,
)
})
})
+74
View File
@@ -0,0 +1,74 @@
/**
* 线路延迟测试。
*
* 单独成一个模块,是因为「测失败了该跟用户说什么」有六个分支,而它原本写在组件里,
* 一条测试都加不了。这些话是用户唯一能看到的诊断信息,值得测。
*/
import { ref } from 'vue'
import { ApiError, api } from './api'
/** 超时,毫秒。文案里会用到它,所以不能让接口和文案各写一个数。 */
export const TEST_TIMEOUT_MS = 5000
/**
* 把内核的延迟测试结果翻译成一句说明原因的话。
*
* 内核对这件事的回答是精确的(内核源码 hub/route/proxies.go:122-145):
* 504 在给定超时内没有完成
* 503 连接建立失败,或者测得的延迟为 0
* 404 这个名字不在内核的全局出站表里
* 笼统说一句「测不通」会把它们混在一起,而这三种要查的地方完全不一样。
*/
export function describeTestFailure(
name: string,
error: unknown,
timeoutMs = TEST_TIMEOUT_MS,
): string {
if (!(error instanceof ApiError)) return `${name} 延迟测试失败:${String(error)}`
if (error.status === 504) {
return `${name} 延迟测试超时,${String(timeoutMs / 1000)} 秒内没有取到测试地址`
}
if (error.status === 404) {
return `${name} 不在内核的出站表里,无法测试。订阅线路需要从所属订阅进去测。`
}
const detail = String(error.payload.message ?? '')
// 内核对连接失败给的是一句没有信息量的通用英文,替换成能指导排查的话
const generic = detail === '' || detail === 'An error occurred in the delay test'
if (error.status === 503) {
return generic
? `${name} 无法建立连接,线路可能已失效,或本机到该服务器的网络不通`
: `${name} 无法建立连接:${detail}`
}
return `${name} 延迟测试失败(HTTP ${String(error.status)})${generic ? '' : `:${detail}`}`
}
/**
* 管理「哪几条线路正在测」。
*
* 测延迟是纯读操作,不影响配置也不影响别的线路,所以它只标记自己那一条忙碌,
* 不禁用界面上的任何其它东西。
*/
export function useDelayTest(onFinished: () => void, onFailure: (message: string) => void) {
const testing = ref<string[]>([])
async function test(name: string, provider?: string) {
if (testing.value.includes(name)) return
testing.value = [...testing.value, name]
try {
await api.testLine(name, provider, TEST_TIMEOUT_MS)
onFinished()
} catch (error) {
// 测不通是关于线路的结论,不是 Patchbay 出了故障
onFailure(describeTestFailure(name, error))
} finally {
testing.value = testing.value.filter((n) => n !== name)
}
}
return { testing, test }
}
+5 -7
View File
@@ -15,15 +15,13 @@ export interface NavItem {
key: string
label: string
icon: Component
/** 还没做的页面标 true,导航上显示但点进去是占位 */
pending?: boolean
}
export const NAV: NavItem[] = [
{ key: 'dashboard', label: '仪表盘', icon: IconDashboard, pending: true },
{ key: 'dashboard', label: '仪表盘', icon: IconDashboard },
{ key: 'router', label: '路由', icon: IconRoute },
{ key: 'config', label: '配置', icon: IconConfig, pending: true },
{ key: 'requests', label: '请求', icon: IconRequests, pending: true },
{ key: 'connections', label: '连接', icon: IconConnections, pending: true },
{ key: 'settings', label: '设置', icon: IconSettings, pending: true },
{ key: 'config', label: '配置', icon: IconConfig },
{ key: 'requests', label: '请求', icon: IconRequests },
{ key: 'connections', label: '连接', icon: IconConnections },
{ key: 'settings', label: '设置', icon: IconSettings },
]
+163
View File
@@ -0,0 +1,163 @@
/**
* 内核的运行时状态:有哪些出站、每个是什么协议、策略组当前选中谁、最近一次延迟。
*
* 这些数据配置文件里没有,只有运行中的内核知道;而且界面上有三层组件要用它。
* 原本它住在根组件里靠 props 一层层往下传,中间有两层完全不碰它、纯粹为了转发而
* 声明了参数。做成模块级单例之后那两层就不用再知道它的存在了。
*
* 用的是 web/prefs.ts 已有的模式(模块级 ref),不是新抽象。
*/
import { ref } from 'vue'
import { api } from './api'
import type { ProxyInfo } from './api'
import { isGenerated } from '@shared/inbound-groups.ts'
/**
* 出站名字 → 运行时信息。内核没连接时是空的。
*
* 合并了内核全局名字表和用户订阅里的线路。Patchbay 自己生成的订阅副本**不并进来**:
* 副本里的线路和原版同名(决策记录 0007 里那套复制订阅声明的做法),并进来只会互相
* 覆盖。要看副本里那一份,用下面的 `providers`。
*/
export const runtime = ref<Record<string, ProxyInfo>>({})
/** 订阅名 → 它当前提供的线路。含 Patchbay 生成的副本,按订阅隔开所以不会撞。 */
export const providers = ref<Record<string, ProxyInfo[]>>({})
/** 用户自己的订阅带来的线路,按订阅返回的顺序。不含生成的副本。 */
export const providerLines = ref<string[]>([])
/** 订阅线路 → 它所属的订阅名。测它的延迟必须从所属订阅进去。 */
export const lineProvider = ref<Record<string, string>>({})
export const kernel = ref<{ online: boolean; version?: string }>({ online: false })
/**
* 重新读一遍运行时状态。
*
* 要读两处:`/proxies` 只包含内核全局名字表里的东西(内置出站、自有线路、策略组),
* 订阅线路不在那张表上,它们的协议和延迟只能从 `/providers/proxies` 拿。
*
* 任何一处取不到都不算错误——界面照常显示,只是少了延迟数字。内核没起来的时候正是
* 最需要这个界面的时候。
*/
export async function reloadRuntime(): Promise<void> {
kernel.value = await api.kernel().catch(() => ({ online: false }))
if (!kernel.value.online) {
runtime.value = {}
providers.value = {}
providerLines.value = []
lineProvider.value = {}
return
}
const merged: Record<string, ProxyInfo> = {}
try {
Object.assign(merged, (await api.proxies()).proxies)
} catch {
// 拿不到就当没有
}
const byProvider: Record<string, ProxyInfo[]> = {}
const lines: string[] = []
const owner: Record<string, string> = {}
try {
const result = await api.providers()
for (const [name, provider] of Object.entries(result.providers)) {
// 内核会给每个用了 proxies 的策略组造一个内部 provider,那些不是订阅
if (provider.vehicleType === 'Compatible') continue
byProvider[name] = provider.proxies
if (isGenerated(name)) continue
for (const line of provider.proxies) {
merged[line.name] = line
lines.push(line.name)
owner[line.name] = name
}
}
} catch {
// 同上
}
runtime.value = merged
providers.value = byProvider
providerLines.value = lines
lineProvider.value = owner
}
/**
* 界面渲染一个策略组需要知道的最少信息。
*
* `uses` 来自配置文件,`now` 来自内核,两边缺一不可:光有名字查不到它从哪取成员,
* 而开了链式代理之后同名线路有两份,不知道来源就分不清该显示哪一份。
*/
export interface GroupView {
name: string
uses: string[]
}
/** 一条线路在界面上要显示的样子,外加测它的延迟该从哪个订阅进去。 */
export interface LineEntry {
name: string
/** 它来自哪个订阅。测延迟必须带上 */
provider: string
info: ProxyInfo | undefined
}
/**
* 这条线路是不是来自 Patchbay 生成的订阅副本。
*
* 副本整份挂着 `dialer-proxy`,所以来自副本就一定经过入口。点名加进组里的成员
* (`DIRECT`、AUTO 和 FALLBACK 那两个组)不属于任何订阅,不在副本里。
*/
export function isChainedLine(name: string): boolean {
return Object.entries(providers.value).some(
([provider, lines]) => isGenerated(provider) && lines.some((line) => line.name === name),
)
}
/**
* 这几个订阅里一共有哪些线路。
*
* 只给高级配置里那个「匹配到几条」的预览用:那时用户选的来源还没保存,内核也还不知道
* 有这么个组,只能自己按来源算一遍。已经存在的组要用下面的 `membersOf`。
*/
export function linesFrom(uses: string[]): string[] {
const seen = new Set<string>()
for (const provider of uses) {
for (const line of providers.value[provider] ?? []) seen.add(line.name)
}
return [...seen]
}
/**
* 一个策略组的成员,按内核给的顺序。
*
* 成员名单直接用内核算好的(`/proxies` 里那个 `all`),不自己从来源订阅里推——组上的
* `filter` 已经在内核那边生效过了,重推一遍就是把同一条规则实现两次,两边一旦不一致
* 界面显示的就是假的。
*
* 每个成员还要标出它来自哪个订阅,因为测延迟得从所属订阅进去。顺着组自己的 `use:` 找而
* 不是全局按名字查:开了链式代理之后同一个线路名在原订阅和副本里各有一份,只有顺着来源
* 才知道该用哪一份。副本那份挂着 `dialer-proxy`,测出来是走完两跳的延迟,这正是这一路
* 真实的延迟。点名加进来的成员(DIRECT、别的策略组)不属于任何订阅,`provider` 是空串。
*/
export function membersOf(view: GroupView): LineEntry[] {
return (runtime.value[view.name]?.all ?? []).map((name) => {
for (const provider of view.uses) {
const line = (providers.value[provider] ?? []).find((item) => item.name === name)
if (line) return { name, provider, info: line }
}
return { name, provider: '', info: runtime.value[name] }
})
}
/**
* 切换策略组选中谁时先在本地改掉,不等内核回话。
*
* 这一步不写配置文件、失败率极低,而等一个往返再更新会让点击感觉发木。
* 真失败了随后的刷新会把状态纠正回来。
*/
export function optimisticSelect(group: string, member: string): void {
const node = runtime.value[group]
if (node) node.now = member
}
+13
View File
@@ -8,6 +8,10 @@
*
* 颜色只留一个强调色,用在「当前选中」和「主要操作」上。状态色(成功/警告/危险)
* 只在真的表示状态时用,不拿来装饰。
*
* 唯一的例外是链式代理那一组色(--c-chain-*)。同一屏上有两种「当前选中」——流量最后
* 从哪出去,和流量先经过哪——它们必须一眼分得开,这是含义不是装饰。挑靛蓝是因为它在
* 这套色板里不表示任何状态,红绿琥珀都被状态占了。别把它当成通用的第二强调色。
*/
:root {
@@ -27,6 +31,11 @@
--c-accent-soft: #e6f2f1;
--c-accent-text: #1f5c5a;
/* 链式代理的「当前选中」。靛蓝,和强调色的青绿色相拉得够开 */
--c-chain: #5145cd;
--c-chain-soft: #eeedfb;
--c-chain-text: #4038a8;
--c-danger: #b3261e;
--c-danger-soft: #fdedec;
--c-warn: #8a6100;
@@ -78,6 +87,10 @@
--c-accent-soft: #1b3330;
--c-accent-text: #7fd4cb;
--c-chain: #8b83f0;
--c-chain-soft: #241f4a;
--c-chain-text: #a9a2f7;
--c-danger: #f2b8b5;
--c-danger-soft: #3a1f1e;
--c-warn: #e8c37a;
+509 -184
View File
@@ -2,94 +2,145 @@
/**
* 选中那一路入站的详情。
*
* 分两块,因为它们是两种不同性质的动作,不该长得一样也不该给一样的反馈:
* 流量去向 —— 换策略组当前选中谁。不写配置文件,点了立刻变。日常点的就是这个。
* 出站 —— 换这路入站指向哪个出站。要改配置文件,走校验和重载,要等几秒。
* 上下两半,界限就是高级配置上面那条分割线:
* 上半 点卡片立刻生效。换的是策略组当前选中谁,不写配置文件(决策记录 0007)
* 下半 高级配置。改的是组从哪些订阅取成员,写配置文件,要校验和重载
*
* 两半的反馈方式必须不一样。它们长得一样的时候,用户分不清哪个动作要等、哪个不用。
*/
import { computed } from 'vue'
import type { Inbound, OutboundMode } from '@shared/inbounds.ts'
import { computed, ref, watch } from 'vue'
import type { Inbound } from '@shared/inbounds.ts'
import { displayName, linesMatching } from '@shared/inbound-groups.ts'
import type { OutboundSetup, PanelGroup } from '@shared/inbound-groups.ts'
import { resolveChain } from '@shared/outbound-chain.ts'
import { latestDelay } from '../api'
import type { ProxyInfo } from '../api'
import type { GroupView } from '../runtime'
import { isChainedLine, kernel, linesFrom, membersOf, runtime } from '../runtime'
import OutboundCard from '../components/OutboundCard.vue'
import IconOffline from '~icons/ri/cloud-off-line'
import SourcePicker from '../components/SourcePicker.vue'
import IconEdit from '~icons/ri/edit-line'
import IconDelete from '~icons/ri/delete-bin-line'
import IconDown from '~icons/ri/arrow-down-s-line'
import IconUp from '~icons/ri/arrow-up-s-line'
import IconOffline from '~icons/ri/cloud-off-line'
const props = defineProps<{
inbound: Inbound
groups: string[]
ownProxies: string[]
providerLines: string[]
runtime: Record<string, ProxyInfo>
/** 流量最终交给哪个出站。走规则的入站要查到规则表末尾的 MATCH */
destination: string | null
kernelOnline: boolean
/** 正在提交的那个出站的名字。只有它显示忙碌,其余照常能点 */
pendingOutbound: string | null
/** 能操作哪些策略组、各自能不能点。groups 为空表示这一路没有能点的组 */
panel: { groups: PanelGroup[]; shared: boolean }
/** 链式代理的入口组。null 表示没开 */
chain: GroupView | null
/** 配置里定义过的订阅,高级配置里从这里挑来源 */
subscriptions: string[]
/** 当前的来源和筛选,高级配置的表单初值 */
setup: OutboundSetup | null
/** 正在测延迟的线路 */
testing: string[]
/** 高级配置正在保存 */
saving: boolean
}>()
const emit = defineEmits<{
pick: [mode: OutboundMode]
edit: []
remove: []
/** 切换某个策略组当前选中谁 */
select: [group: string, member: string]
test: [name: string]
test: [name: string, provider: string]
/** 保存高级配置 */
save: [setup: OutboundSetup]
/** 把这一路改成专属代理组模式 */
adopt: []
}>()
/** 默认入站没有 proxy 字段可写,「出站」那一块对它是只读的。 */
/** 默认入站由配置顶层的端口字段声明,没有 proxy 字段可写,也不能删。 */
const locked = computed(() => props.inbound.isDefault)
function describe(name: string): string {
const info = props.runtime[name]
if (!info) return ''
return info.now ? `${info.type}(${info.now})` : info.type
}
const activeTab = ref('')
watch(
() => props.panel.groups,
(list) => {
if (!list.some((t) => t.name === activeTab.value)) activeTab.value = list[0]?.name ?? ''
},
{ immediate: true },
)
const delayOf = (name: string) => latestDelay(props.runtime[name])
const activeGroup = computed(
() => props.panel.groups.find((g) => g.name === activeTab.value) ?? null,
)
/**
* 表单里开了链式代理但还没保存。
*
* 这时内核里还没有入口组,卡片点不了,但候选线路是知道的,先按只读画出来。开关拨完
* 一片空白、要按了保存才看得见东西,会让人以为开关没生效。
*/
const chainPreview = computed(() =>
props.chain === null && form.value.chain ? linesFrom(form.value.chain.sources) : [],
)
const proxyLines = computed(() => (activeGroup.value ? membersOf(activeGroup.value) : []))
const chainLines = computed(() => (props.chain ? membersOf(props.chain) : []))
const nowOf = (group: { name: string } | null) =>
group ? (runtime.value[group.name]?.now ?? '') : ''
const isTesting = (name: string) => props.testing.includes(name)
/**
* 从落脚的出站一路跟着「当前选中」往下走,直到走到一条真正的线路。
* 流量最终走到哪。
*
* 策略组可以选中另一个策略组,所以「这个端口现在走哪条线」往往要跳好几层。
* 只显示第一层等于没回答问题。
* 从代理组当前选中的那个开始一路跟着「当前选中」查下去。选中的是一条线路就到此为止,
* 选中的是 `AUTO` 这种自动测速组就还要再查一层,否则只显示一个组名等于没回答。
*/
const chain = computed(() => {
const hops: string[] = []
let cursor = props.destination
while (cursor && !hops.includes(cursor)) {
hops.push(cursor)
cursor = props.runtime[cursor]?.now ?? null
}
return hops
const exitChain = computed(() =>
resolveChain(runtime.value, nowOf(props.panel.groups[0] ?? null) || null),
)
/**
* 这一路当前这条出口是不是真的经过入口。
*
* 开了链式代理不等于每条出口都走中转:`DIRECT` 是点名加进代理组的成员,不属于任何订阅,
* 身上没有 `dialer-proxy`,选中它就是直连。这时画一跳入口是在骗人。
*/
const throughChain = computed(() => {
const exit = exitChain.value.at(-1)
return exit !== undefined && props.chain !== null && isChainedLine(exit)
})
/** 链条上最后一个还是策略组的环节——用户能在这里换选中。 */
const switchable = computed(() => {
for (let i = chain.value.length - 1; i >= 0; i -= 1) {
const name = chain.value[i]!
const info = props.runtime[name]
if (info?.all?.length) return { group: name, members: info.all, now: info.now ?? '' }
// ── 高级配置 ────────────────────────────────────────────────
const open = ref(false)
const form = ref<OutboundSetup>({ proxy: { sources: [], filter: null }, chain: null })
function reset() {
form.value = props.setup
? (JSON.parse(JSON.stringify(props.setup)) as OutboundSetup)
: { proxy: { sources: [...props.subscriptions], filter: null }, chain: null }
}
return null
// 切到别的入站时表单要跟着换,否则会把上一路的设置保存到这一路上
watch(() => [props.inbound.id, props.setup], reset, { immediate: true, deep: true })
const chainOn = computed({
get: () => form.value.chain !== null,
set: (on: boolean) => {
form.value.chain = on ? { sources: [...props.subscriptions], filter: null } : null
},
})
function isCurrentOutbound(mode: OutboundMode): boolean {
const now = props.inbound.outbound
if (now.kind !== mode.kind) return false
return now.kind !== 'named' || now.name === (mode as { name: string }).name
/** 当前筛选条件会留下几条线路。写错了 kept 是 null,界面据此提示而不是显示错的数字。 */
function preview(spec: { sources: string[]; filter: string | null }) {
const names = linesFrom(spec.sources)
return { total: names.length, kept: linesMatching(spec.filter, names)?.length ?? null }
}
const BUILTINS: Array<{ mode: OutboundMode; label: string; sub: string }> = [
{ mode: { kind: 'rules' }, label: 'RULE', sub: '由规则决定' },
{ mode: { kind: 'direct' }, label: 'DIRECT', sub: '直接连接' },
{ mode: { kind: 'global' }, label: 'GLOBAL', sub: '跟随 GLOBAL 组' },
]
const LINE_LOCKED = '订阅线路无法被入站直接引用,需要通过筛选组间接引入。该功能尚未实现。'
const NO_PROXY_FIELD = '该入站没有 proxy 字段'
const dirty = computed(() => JSON.stringify(form.value) !== JSON.stringify(props.setup))
/**
* 至少要选一个订阅。AUTO 和 FALLBACK 只有 `use:` 没有点名成员,一个订阅都不选就是空组,
* 内核会直接拒绝整份配置(内核源码 adapter/outboundgroup/parser.go:117-119)。
* 在这里拦住,比让用户按下保存再读一段内核报错好。
*/
const filled = (spec: { sources: string[] }) => spec.sources.length > 0
const complete = computed(
() => filled(form.value.proxy) && (form.value.chain === null || filled(form.value.chain)),
)
</script>
<template>
@@ -98,11 +149,12 @@ const NO_PROXY_FIELD = '该入站没有 proxy 字段'
<div class="title">
<span class="port mono">{{ inbound.port }}</span>
<span class="name">{{ inbound.name }}</span>
</div>
<div v-if="!locked" class="acts">
<button type="button" @click="emit('edit')"><IconEdit /> 编辑</button>
<button type="button" class="danger" @click="emit('remove')"><IconDelete /> 删除</button>
<button type="button" class="danger" @click="emit('remove')">
<IconDelete /> 删除
</button>
</div>
</div>
<dl class="facts">
@@ -110,121 +162,202 @@ const NO_PROXY_FIELD = '该入站没有 proxy 字段'
<dd class="mono">{{ inbound.type }}</dd>
<dt>监听</dt>
<dd class="mono">{{ inbound.listen ?? '0.0.0.0' }}</dd>
<template v-if="inbound.ruleSet">
<dt>附加规则</dt>
<dd class="mono">{{ inbound.ruleSet ?? '—' }}</dd>
<dd class="mono">{{ inbound.ruleSet }}</dd>
</template>
<template v-if="exitChain.length">
<dt>流量去向</dt>
<dd class="flow mono">
<template v-if="throughChain">
<span class="hop is-chain">{{ displayName(nowOf(chain)) || '未选择' }}</span>
<span class="arrow">→</span>
</template>
<template v-for="(hop, i) in exitChain" :key="hop">
<span v-if="i" class="arrow">→</span>
<span :class="['hop', i === exitChain.length - 1 && 'is-proxy']">{{
displayName(hop)
}}</span>
</template>
</dd>
</template>
</dl>
</header>
<!-- 运行时:换线路。不写文件,点了立刻变 -->
<section v-if="chain.length" class="block">
<h3>流量去向</h3>
<p class="chain mono">
<template v-for="(hop, i) in chain" :key="hop">
<span v-if="i" class="arrow">→</span>
<span :class="i === chain.length - 1 && 'tail'">{{ hop }}</span>
</template>
</p>
<template v-if="switchable">
<h4>{{ switchable.group }} 的当前选中</h4>
<div class="grid">
<OutboundCard
v-for="m in switchable.members"
:key="m"
:name="m"
:sub="describe(m)"
:delay="delayOf(m)"
:selected="m === switchable.now"
:testing="isTesting(m)"
testable
@pick="emit('select', switchable.group, m)"
@test="emit('test', m)"
/>
</div>
</template>
<!-- 链条上一个能点的组都没有:只能说明现状 -->
<section v-if="panel.groups.length === 0" class="block">
<p class="hint">没有可切换的策略组。</p>
<button v-if="!locked" type="button" class="adopt" :disabled="saving" @click="emit('adopt')">
改成逐条选线路
</button>
</section>
<!-- 配置:换这路入站指向谁。要写文件、要校验 -->
<template v-else>
<section class="block">
<h3>出站</h3>
<p v-if="locked" class="hint">
由 <code>{{ inbound.legacyKey }}</code> 声明。该写法没有 proxy 字段,出站固定为 RULE。
</p>
<h3>
代理
<span
v-if="panel.shared"
class="tag"
:title="`换的是 ${panel.groups[0]?.name},所有走分流规则的入站共用它`"
>共用</span
>
</h3>
<div v-if="!locked" class="grid">
<OutboundCard
v-for="b in BUILTINS"
:key="b.label"
:name="b.label"
:sub="b.sub"
:delay="null"
:selected="isCurrentOutbound(b.mode)"
:pending="pendingOutbound === b.label"
@pick="emit('pick', b.mode)"
/>
<div v-if="panel.groups.length > 1" class="tabs">
<button
v-for="t in panel.groups"
:key="t.name"
type="button"
:class="['tab', activeTab === t.name && 'is-on']"
@click="activeTab = t.name"
>
{{ t.label }}
</button>
</div>
<template v-if="groups.length">
<h4 :class="locked && 'is-dim'">策略组</h4>
<div class="grid">
<OutboundCard
v-for="g in groups"
:key="g"
:name="g"
:sub="describe(g)"
:delay="delayOf(g)"
:selected="isCurrentOutbound({ kind: 'named', name: g })"
:disabled-reason="locked ? NO_PROXY_FIELD : undefined"
:pending="pendingOutbound === g"
:testing="isTesting(g)"
testable
@pick="emit('pick', { kind: 'named', name: g })"
@test="emit('test', g)"
/>
</div>
</template>
<template v-if="ownProxies.length">
<h4 :class="locked && 'is-dim'">自有线路</h4>
<div class="grid">
<OutboundCard
v-for="p in ownProxies"
:key="p"
:name="p"
:sub="describe(p)"
:delay="delayOf(p)"
:selected="isCurrentOutbound({ kind: 'named', name: p })"
:disabled-reason="locked ? NO_PROXY_FIELD : undefined"
:pending="pendingOutbound === p"
:testing="isTesting(p)"
testable
@pick="emit('pick', { kind: 'named', name: p })"
@test="emit('test', p)"
/>
</div>
</template>
<h4 :class="locked && 'is-dim'">订阅线路</h4>
<p v-if="!kernelOnline" class="hint">
<IconOffline />
内核未连接,无法获取订阅线路
</p>
<p v-else-if="providerLines.length === 0" class="hint">订阅中没有线路</p>
<p v-if="!kernel.online" class="hint"><IconOffline /> 内核未连接</p>
<p v-else-if="proxyLines.length === 0" class="hint">这个策略组现在没有成员</p>
<div v-else class="grid">
<OutboundCard
v-for="line in providerLines"
:key="line"
:name="line"
:sub="describe(line)"
:delay="delayOf(line)"
:selected="false"
:disabled-reason="LINE_LOCKED"
:testing="isTesting(line)"
v-for="line in proxyLines"
:key="line.name"
:name="displayName(line.name)"
:sub="line.info?.type ?? ''"
:delay="latestDelay(line.info)"
:selected="line.name === nowOf(activeGroup)"
:disabled-reason="activeGroup?.pickable ? undefined : '这个组自己决定用哪条'"
:testing="isTesting(line.name)"
testable
@test="emit('test', line)"
tone="proxy"
@pick="emit('select', activeTab, line.name)"
@test="emit('test', line.name, line.provider)"
/>
</div>
</section>
<section v-if="chain || chainPreview.length" class="block">
<h3>
链式代理
<span v-if="!chain" class="tag">未保存</span>
</h3>
<div v-if="!chain" class="grid">
<OutboundCard
v-for="name in chainPreview"
:key="name"
:name="name"
sub=""
:delay="null"
:selected="false"
disabled-reason="保存之后才能选"
tone="chain"
/>
</div>
<div v-else class="grid">
<OutboundCard
v-for="line in chainLines"
:key="line.name"
:name="line.name"
:sub="line.info?.type ?? ''"
:delay="latestDelay(line.info)"
:selected="line.name === nowOf(chain)"
:testing="isTesting(line.name)"
testable
tone="chain"
@pick="emit('select', chain.name, line.name)"
@test="emit('test', line.name, line.provider)"
/>
</div>
</section>
<!-- 共用的组只能换选中,改不了它的成员来源:那是别人的组 -->
<section v-if="panel.shared && !locked" class="block">
<button type="button" class="adopt" :disabled="saving" @click="emit('adopt')">
改成逐条选线路
</button>
</section>
<section v-if="!panel.shared" class="block advanced">
<button type="button" class="toggle" @click="open = !open">
<span>高级配置</span>
<component :is="open ? IconUp : IconDown" />
</button>
<div v-if="open" class="form">
<h4>代理</h4>
<div class="row">
<span class="label">订阅</span>
<SourcePicker v-model="form.proxy.sources" :options="subscriptions" />
</div>
<div class="row">
<span class="label">筛选</span>
<div class="field">
<input v-model="form.proxy.filter" placeholder="正则,留空表示全部保留" />
<p class="count">
<template v-if="preview(form.proxy).kept === null">筛选条件写法有误</template>
<template v-else>
{{ preview(form.proxy).total }} 条线路里匹配到 {{ preview(form.proxy).kept }} 条
</template>
</p>
</div>
</div>
<div class="row">
<span class="label">链式代理</span>
<div class="field">
<button
type="button"
role="switch"
:aria-checked="chainOn"
:class="['switch', chainOn && 'is-on']"
@click="chainOn = !chainOn"
>
<span class="knob"></span>
</button>
</div>
</div>
<template v-if="form.chain">
<h4>链式代理</h4>
<div class="row">
<span class="label">订阅</span>
<SourcePicker v-model="form.chain!.sources" :options="subscriptions" />
</div>
<div class="row">
<span class="label">筛选</span>
<div class="field">
<input v-model="form.chain.filter" placeholder="正则,建议筛到作为中转的那一条" />
<p class="count">
<template v-if="preview(form.chain).kept === null">筛选条件写法有误</template>
<template v-else>
{{ preview(form.chain).total }} 条线路里匹配到
{{ preview(form.chain).kept }} 条
</template>
</p>
</div>
</div>
</template>
<div class="form-acts">
<button type="button" :disabled="!dirty || saving" @click="reset">取消</button>
<button
type="button"
class="primary"
:disabled="!dirty || !complete || saving"
@click="emit('save', form)"
>
{{ saving ? '保存中' : '保存' }}
</button>
</div>
</div>
</section>
</template>
</aside>
</template>
@@ -267,7 +400,7 @@ const NO_PROXY_FIELD = '该入站没有 proxy 字段'
.acts {
display: flex;
gap: var(--s-2);
margin-bottom: var(--s-3);
margin-left: auto;
}
.acts button {
@@ -306,6 +439,33 @@ const NO_PROXY_FIELD = '该入站没有 proxy 字段'
.facts dd {
margin: 0;
min-width: 0;
}
.flow {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--s-2);
}
.arrow {
color: var(--c-text-faint);
}
.hop {
color: var(--c-text-soft);
}
/* 两跳用两种颜色,和下面卡片的选中态对得上 */
.hop.is-proxy {
color: var(--c-accent-text);
font-weight: 500;
}
.hop.is-chain {
color: var(--c-chain-text);
font-weight: 500;
}
.block {
@@ -318,36 +478,50 @@ const NO_PROXY_FIELD = '该入站没有 proxy 字段'
}
h3 {
font-size: var(--t-sm);
font-weight: 600;
color: var(--c-text-soft);
margin-bottom: var(--s-3);
}
h4 {
font-size: var(--t-xs);
font-weight: 500;
color: var(--c-text-faint);
margin: var(--s-5) 0 var(--s-2);
}
.chain {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--s-2);
font-size: var(--t-sm);
color: var(--c-text-soft);
margin-bottom: var(--s-2);
font-weight: 600;
color: var(--c-text);
letter-spacing: 0.02em;
margin-bottom: var(--s-4);
}
.chain .arrow {
.tag {
padding: 0 var(--s-2);
border: 1px solid var(--c-border-strong);
border-radius: 999px;
font-size: var(--t-xs);
font-weight: 400;
color: var(--c-text-faint);
cursor: help;
}
.chain .tail {
color: var(--c-accent-text);
font-weight: 500;
.tabs {
display: flex;
gap: var(--s-4);
margin-bottom: var(--s-4);
}
/* 选中态是一条离文字有距离的下划线,不画边框 */
.tab {
padding: 0 0 var(--s-2);
border: none;
border-bottom: 2px solid transparent;
background: none;
color: var(--c-text-faint);
font-size: var(--t-sm);
cursor: pointer;
}
.tab:hover {
color: var(--c-text-soft);
}
.tab.is-on {
border-bottom-color: var(--c-accent);
color: var(--c-text);
}
.grid {
@@ -365,11 +539,162 @@ h4 {
line-height: 1.6;
}
.hint code {
color: var(--c-text-soft);
.adopt {
padding: var(--s-1) var(--s-4);
border: 1px solid var(--c-border-strong);
border-radius: var(--r-sm);
background: var(--c-surface);
font-size: var(--t-sm);
cursor: pointer;
}
.is-dim {
opacity: 0.6;
.adopt:hover:not(:disabled) {
border-color: var(--c-accent);
color: var(--c-accent-text);
}
.adopt:disabled {
color: var(--c-text-faint);
cursor: not-allowed;
}
/* ── 高级配置 ───────────────────────────────── */
.toggle {
display: flex;
align-items: center;
gap: var(--s-2);
padding: 0;
border: none;
background: none;
color: var(--c-text-soft);
font-size: var(--t-sm);
font-weight: 600;
cursor: pointer;
}
.toggle:hover {
color: var(--c-text);
}
/* 表单不套盒子,靠小标题和一条分割线分段(设计基调第 2 条:不要卡片套卡片) */
.form {
display: flex;
flex-direction: column;
gap: var(--s-3);
margin-top: var(--s-4);
}
.form h4 {
font-size: var(--t-xs);
font-weight: 600;
letter-spacing: 0.04em;
color: var(--c-text-faint);
}
.form h4:not(:first-child) {
margin-top: var(--s-4);
}
.row {
display: grid;
grid-template-columns: 4.5em minmax(0, 1fr);
align-items: start;
gap: var(--s-3);
}
/* 标签和第一行控件对齐。控件本身高 34px,所以标签也按 34px 居中 */
.label {
display: flex;
align-items: center;
min-height: 34px;
color: var(--c-text-faint);
font-size: var(--t-sm);
}
.field {
display: flex;
min-height: 34px;
flex-direction: column;
justify-content: center;
}
select,
input {
height: 34px;
padding: 0 var(--s-3);
border: 1px solid var(--c-border-strong);
border-radius: var(--r-sm);
background: var(--c-surface);
font-size: var(--t-base);
}
input {
width: 100%;
font-family: var(--f-mono);
}
.count {
margin-top: var(--s-1);
color: var(--c-text-faint);
font-size: var(--t-xs);
}
.switch {
flex: none;
align-self: flex-start;
width: 38px;
height: 22px;
padding: 2px;
border: 1px solid var(--c-border-strong);
border-radius: 999px;
background: var(--c-surface-sunken);
cursor: pointer;
}
.switch .knob {
display: block;
width: 16px;
height: 16px;
border-radius: 50%;
background: var(--c-text-faint);
transition:
transform 0.15s ease,
background 0.15s ease;
}
.switch.is-on {
border-color: var(--c-chain);
background: var(--c-chain-soft);
}
.switch.is-on .knob {
background: var(--c-chain);
transform: translateX(16px);
}
.form-acts {
display: flex;
justify-content: flex-end;
gap: var(--s-2);
}
.form-acts button {
padding: var(--s-1) var(--s-4);
border: 1px solid var(--c-border-strong);
border-radius: var(--r-sm);
background: var(--c-surface);
font-size: var(--t-sm);
cursor: pointer;
}
.form-acts button:disabled {
color: var(--c-text-faint);
cursor: not-allowed;
}
.form-acts .primary:not(:disabled) {
border-color: var(--c-accent);
background: var(--c-accent-soft);
color: var(--c-accent-text);
}
</style>
+93 -219
View File
@@ -1,40 +1,50 @@
<script setup lang="ts">
/**
* 路由页:一张「端口 → 出站」的表,加上选中那一路的详情。
*
* 这里只做编排——把配置数据、运行时状态和三个子组件接起来,并守住一条:
* 所有改配置文件的动作都从 commit() 走,失败时按停在哪一步说不同的话。
* 运行时动作(切换选中、测延迟)不经过它,因为它们不写文件也不需要校验。
*/
import { computed, onMounted, ref, watch } from 'vue'
import { collectInbounds } from '@shared/inbounds.ts'
import type { Inbound } from '@shared/inbounds.ts'
import {
collectInbounds,
collectOutboundNames,
outboundToProxyField,
resolveDestination,
} from '@shared/inbounds.ts'
import type { Inbound, OutboundMode } from '@shared/inbounds.ts'
applySetup,
chainGroupName,
groupUses,
panelGroups,
pruneGenerated,
syncGenerated,
readSetup,
userProviders,
} from '@shared/inbound-groups.ts'
import type { OutboundSetup } from '@shared/inbound-groups.ts'
import type { ConfigObject } from '../../vendor/config-editor/index.ts'
import { ApiError, api } from '../api'
import type { ListenerFields, ProxyInfo } from '../api'
import type { ListenerFields } from '../api'
import type { GroupView } from '../runtime'
import { optimisticSelect, providerLines, reloadRuntime, runtime } from '../runtime'
import { useDelayTest } from '../delay-test'
import { density } from '../prefs'
import InboundList from '../components/InboundList.vue'
import InboundDetail from './InboundDetail.vue'
import InboundForm from './InboundForm.vue'
import IconAdd from '~icons/ri/add-line'
const props = defineProps<{
data: ConfigObject
revision: string
kernelOnline: boolean
providerLines: string[]
/** 订阅线路 → 所属订阅 */
lineProvider: Record<string, string>
runtime: Record<string, ProxyInfo>
}>()
const props = defineProps<{ data: ConfigObject; revision: string }>()
const emit = defineEmits<{
/** 配置文件变了,需要重读整份配置 */
saved: []
/** 只有内核的运行时状态变了,不用重读配置 */
runtimeChanged: []
optimisticSelect: [group: string, member: string]
}>()
/** 配置文件变了,需要重读整份配置。运行时的变化不走这里。 */
const emit = defineEmits<{ saved: [] }>()
const inbounds = computed(() => collectInbounds(props.data))
const outbounds = computed(() => collectOutboundNames(props.data))
const subscriptions = computed(() => userProviders(props.data))
/** 刚接管一路入站时给它什么:订阅全给上,不筛。三个组由 applySetup 一并建出来。 */
const defaultSetup = (): OutboundSetup => ({
proxy: { sources: [...subscriptions.value], filter: null },
chain: null,
})
const selectedId = ref<string | null>(null)
const saving = ref(false)
@@ -46,10 +56,13 @@ const notice = ref('')
const fields = ref<ListenerFields | null>(null)
const formOpen = ref(false)
const formEditing = ref<Inbound | null>(null)
/** 正在提交的那个出站的名字。只有它显示忙碌,其余卡片照常能点 */
const pendingOutbound = ref<string | null>(null)
/** 正在测延迟的线路 */
const testing = ref<string[]>([])
const { testing, test } = useDelayTest(
() => void reloadRuntime(),
(message) => {
notice.value = message
},
)
onMounted(async () => {
try {
@@ -71,29 +84,32 @@ watch(
const selected = computed(() => inbounds.value.find((i) => i.id === selectedId.value) ?? null)
const takenNames = computed(() => inbounds.value.map((i) => i.name))
const TYPE_LABEL: Record<string, string> = {
mixed: 'HTTP + SOCKS5',
http: 'HTTP',
socks: 'SOCKS5',
redir: 'REDIR',
tproxy: 'TPROXY',
}
/** 面板上能操作哪些策略组、各自能不能点。这个问题只在 panelGroups 里回答一次。 */
const panel = computed(() =>
selected.value
? panelGroups(props.data, runtime.value, selected.value)
: { groups: [], shared: false },
)
function typeLabel(inbound: Inbound): string {
return TYPE_LABEL[inbound.type] ?? inbound.type.toUpperCase()
}
/** 共用的组是别人的,改不了它的来源,所以高级配置也不给。 */
const setup = computed<OutboundSetup | null>(() =>
selected.value && !panel.value.shared ? readSetup(props.data, selected.value.name) : null,
)
function outboundLabel(mode: OutboundMode): { text: string; muted: boolean } {
if (mode.kind === 'rules') return { text: 'RULE', muted: true }
if (mode.kind === 'direct') return { text: 'DIRECT', muted: false }
if (mode.kind === 'global') return { text: 'GLOBAL', muted: false }
return { text: mode.name, muted: false }
}
const chainView = computed<GroupView | null>(() => {
const target = selected.value
if (!target || !setup.value?.chain) return null
const name = chainGroupName(target.name)
return { name, uses: groupUses(props.data, name) ?? [] }
})
const clone = () => JSON.parse(JSON.stringify(props.data)) as ConfigObject
/** 所有改动都走这一条路:落盘失败时按停在哪一步说不同的话。 */
async function commit(next: ConfigObject, success: string) {
/** 所有改配置文件的动作都从这里走。 */
async function commit(raw: ConfigObject, success: string) {
// 先把生成的东西按当前规则重建一遍,再清掉没人再引用的。不清理的话,改几次文件里就
// 攒下一堆用户从没主动建过的东西,而没人用的订阅副本还会按 interval 继续联网。
const next = pruneGenerated(syncGenerated(raw, collectInbounds(raw)))
saving.value = true
failure.value = null
done.value = ''
@@ -112,23 +128,18 @@ async function commit(next: ConfigObject, success: string) {
}
}
async function pickOutbound(mode: OutboundMode) {
/** 保存高级配置:改的是这一路的组从哪些订阅取成员、筛掉哪些。 */
async function saveSetup(next: OutboundSetup) {
const target = selected.value
if (!target || target.listenerIndex === null || pendingOutbound.value) return
pendingOutbound.value = outboundLabel(mode).text
const next = clone()
const entry = (next.listeners as ConfigObject[])[target.listenerIndex]!
const proxy = outboundToProxyField(mode)
// RULE 是「没有这个字段」而不是「字段为空」,所以是删掉而不是置空。
if (proxy === undefined) delete entry.proxy
else entry.proxy = proxy
try {
await commit(next, `${target.name} 的出站已设为 ${outboundLabel(mode).text}`)
} finally {
pendingOutbound.value = null
if (!target || saving.value) return
await commit(applySetup(clone(), target.name, next), `${target.name} 的代理配置已保存`)
}
/** 把一路还没接管的入站改成专属代理组模式。 */
async function adopt() {
const target = selected.value
if (!target || saving.value) return
await commit(applySetup(clone(), target.name, defaultSetup()), `${target.name} 已改为逐条选线路`)
}
function openAdd() {
@@ -136,7 +147,6 @@ function openAdd() {
formOpen.value = true
}
function openEdit() {
if (!selected.value || selected.value.isDefault) return
formEditing.value = selected.value
@@ -152,24 +162,28 @@ async function submitForm(entry: ConfigObject) {
else listeners[editingIndex] = entry
next.listeners = listeners
await commit(next, editingIndex === null ? `已新增 ${String(entry.name)}` : '已保存')
// 新增的入站直接进专属组模式。否则新建完看到的是一块「这一路不由 Patchbay 管理」
// 的提示,还得再点一次才能用。
const name = String(entry.name)
const withGroup = editingIndex === null ? applySetup(next, name, defaultSetup()) : next
await commit(withGroup, editingIndex === null ? `已新增 ${name}` : '已保存')
// 失败时不能关对话框——关了再打开就是空表单,用户填的名称、端口、类型全没了
if (failure.value) return
formOpen.value = false
if (editingIndex === null) selectedId.value = `listener:${String(listeners.length - 1)}`
}
/** 切换策略组当前选中谁。运行时动作,不写配置文件,所以不走那条落盘链路。 */
/** 切换策略组当前选中谁。运行时动作,不写配置文件,所以不走 commit()。 */
async function selectMember(group: string, member: string) {
if (saving.value) return
// 先本地改掉,别让点击等一个往返。失败了随后的刷新会纠正回来。
emit('optimisticSelect', group, member)
optimisticSelect(group, member)
failure.value = null
done.value = ''
notice.value = ''
try {
await api.selectProxy(group, member)
emit('runtimeChanged')
await reloadRuntime()
} catch (error) {
failure.value = {
message: error instanceof ApiError ? error.message : String(error),
@@ -178,52 +192,6 @@ async function selectMember(group: string, member: string) {
}
}
/** 延迟测试用的超时,毫秒。也用在失败提示里,让「超时」这个词有具体含义。 */
const TEST_TIMEOUT_MS = 5000
/**
* 把内核的延迟测试结果翻译成一句说明原因的话。
*
* 内核的语义是精确的(hub/route/proxies.go:122-145):
* 504 在给定超时内没有完成
* 503 连接建立失败,或者测得的延迟为 0
* 笼统说一句「测不通」会把这两种情况混在一起,而它们要查的地方不一样。
*/
function describeTestFailure(name: string, error: unknown): string {
if (!(error instanceof ApiError)) return `${name} 延迟测试失败:${String(error)}`
const seconds = String(TEST_TIMEOUT_MS / 1000)
if (error.status === 504) return `${name} 延迟测试超时,${seconds} 秒内没有取到测试地址`
const detail = String(error.payload.message ?? '')
const generic = detail === '' || detail === 'An error occurred in the delay test'
if (error.status === 404) {
return `${name} 不在内核的出站表里,无法测试。订阅线路需要从所属订阅进去测。`
}
if (error.status === 503) {
return generic
? `${name} 无法建立连接,线路可能已失效,或本机到该服务器的网络不通`
: `${name} 无法建立连接:${detail}`
}
return `${name} 延迟测试失败(HTTP ${String(error.status)})${generic ? '' : `:${detail}`}`
}
/** 测一条线路的延迟。纯读操作,不影响任何配置,所以不禁用任何东西。 */
async function testLine(name: string) {
if (testing.value.includes(name)) return
testing.value = [...testing.value, name]
try {
await api.testLine(name, props.lineProvider[name], TEST_TIMEOUT_MS)
emit('runtimeChanged')
} catch (error) {
// 测不通是关于线路的结论,不是 Patchbay 出了故障。既不该用错误框,
// 也不该用成功的绿色——它需要第三种中性的样子。
notice.value = describeTestFailure(name, error)
} finally {
testing.value = testing.value.filter((n) => n !== name)
}
}
async function removeSelected() {
const target = selected.value
if (!target || target.listenerIndex === null || saving.value) return
@@ -249,8 +217,8 @@ async function removeSelected() {
<span class="sum-k">入站</span>
</div>
<div class="sum">
<span class="sum-n">{{ outbounds.groups.length }}</span>
<span class="sum-k">策略组</span>
<span class="sum-n">{{ subscriptions.length }}</span>
<span class="sum-k">订阅</span>
</div>
<div class="sum">
<span class="sum-n">{{ providerLines.length }}</span>
@@ -272,42 +240,23 @@ async function removeSelected() {
<p v-else-if="notice" class="notice">{{ notice }}</p>
<div class="split">
<ol class="rows">
<li v-for="inbound in inbounds" :key="inbound.id">
<button
type="button"
:class="['line', selectedId === inbound.id && 'is-on']"
@click="selectedId = inbound.id"
>
<span class="port mono">{{ inbound.port }}</span>
<span class="type">{{ typeLabel(inbound) }}</span>
<span class="name">
{{ inbound.name }}
<span v-if="inbound.isDefault" class="tag">默认</span>
</span>
<span :class="['out', outboundLabel(inbound.outbound).muted && 'is-muted']">
{{ outboundLabel(inbound.outbound).text }}
</span>
</button>
</li>
</ol>
<InboundList v-model:selected="selectedId" :inbounds="inbounds" />
<InboundDetail
v-if="selected"
:inbound="selected"
:groups="outbounds.groups"
:own-proxies="outbounds.ownProxies"
:provider-lines="providerLines"
:destination="resolveDestination(data, selected)"
:runtime="runtime"
:kernel-online="kernelOnline"
@pick="pickOutbound"
:panel="panel"
:chain="chainView"
:subscriptions="subscriptions"
:setup="setup"
:testing="testing"
:saving="saving"
@edit="openEdit"
@remove="removeSelected"
@select="selectMember"
@test="testLine"
:testing="testing"
:pending-outbound="pendingOutbound"
@test="test"
@save="saveSetup"
@adopt="adopt"
/>
</div>
@@ -414,81 +363,6 @@ async function removeSelected() {
}
}
.rows {
list-style: none;
margin: 0;
padding: 0;
border: 1px solid var(--c-border);
border-radius: var(--r-md);
background: var(--c-surface);
overflow: hidden;
}
.rows li + li {
border-top: 1px solid var(--c-border);
}
.line {
width: 100%;
display: grid;
grid-template-columns: 4.5rem 6.5rem 1fr minmax(5rem, auto);
align-items: center;
gap: var(--s-3);
padding: var(--s-3) var(--s-4);
border: none;
background: none;
cursor: pointer;
text-align: left;
}
.line:hover {
background: var(--c-surface-sunken);
}
.line.is-on {
background: var(--c-accent-soft);
}
.port {
font-size: var(--t-lg);
font-variant-numeric: tabular-nums;
}
.type {
font-size: var(--t-xs);
color: var(--c-text-faint);
}
.name {
display: flex;
align-items: center;
gap: var(--s-2);
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag {
flex: none;
padding: 0 var(--s-2);
border: 1px solid var(--c-border-strong);
border-radius: 999px;
font-size: var(--t-xs);
color: var(--c-text-soft);
line-height: 1.6;
}
.out {
font-family: var(--f-mono);
font-size: var(--t-sm);
text-align: right;
}
.out.is-muted {
color: var(--c-text-faint);
}
.empty {
color: var(--c-text-faint);
font-size: var(--t-sm);