proxylang 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -6
- package/dist/cli.js +1 -1
- package/dist/{host-Cw60hFyr.js → host-BvBQxdmA.js} +448 -379
- package/dist/index.d.ts +70 -1
- package/dist/index.js +132 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -21,7 +21,16 @@ proxylang 把这些关系直接写进代码:
|
|
|
21
21
|
|
|
22
22
|
## 快速开始
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
需要 **Node.js 24(最低 24.11.0)**。安装 npm 包:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npm install --save-exact proxylang@0.1.2
|
|
28
|
+
npx proxylang --help
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
将下面的 Usage 示例保存为 `proxy.config.ts`,即可执行 `npx proxylang check proxy.config.ts`。
|
|
32
|
+
|
|
33
|
+
若要运行仓库里的完整示例,另需 **Vite+ 1.3.0**:
|
|
25
34
|
|
|
26
35
|
```sh
|
|
27
36
|
git clone https://github.com/CorrectRoadH/proxylang.git
|
|
@@ -40,7 +49,7 @@ DEMO_PASSWORD=example-only vp exec node dist/cli.js build examples/clients.ts --
|
|
|
40
49
|
|
|
41
50
|
## Usage
|
|
42
51
|
|
|
43
|
-
将下面三个 TypeScript
|
|
52
|
+
将下面三个 TypeScript 代码块按顺序保存为项目中的 `proxy.config.ts`。
|
|
44
53
|
|
|
45
54
|
### 1. 组合规则,给出口留一个位置
|
|
46
55
|
|
|
@@ -165,14 +174,14 @@ export default defineConfig({
|
|
|
165
174
|
|
|
166
175
|
```sh
|
|
167
176
|
# 检查所有目标和请求案例
|
|
168
|
-
|
|
177
|
+
npx proxylang check proxy.config.ts
|
|
169
178
|
|
|
170
179
|
# 查看请求命中了哪条规则,以及规则来自哪个模板
|
|
171
|
-
|
|
180
|
+
npx proxylang explain proxy.config.ts --target backup \
|
|
172
181
|
--request '{"network":"tcp","domain":"github.com","port":443}'
|
|
173
182
|
|
|
174
183
|
# 用测试密码构建;实际使用时由环境提供真实凭据
|
|
175
|
-
PROXY_PASSWORD=example-only
|
|
184
|
+
PROXY_PASSWORD=example-only npx proxylang build proxy.config.ts --out out
|
|
176
185
|
```
|
|
177
186
|
|
|
178
187
|
`explain` 展示条件匹配与逻辑出口,不模拟节点测速或网络连通性。`build` 生成原生配置,整批成功后更新 `out/active.json`,其中列出各目标文件路径;一个目标失败不会替换上一批结果。
|
|
@@ -244,6 +253,41 @@ TLS 的 `serverName` 是证书身份,WebSocket 的 `host` 是 HTTP Host,二
|
|
|
244
253
|
|
|
245
254
|
这些是当前已实现的有限组合:WebSocket 只接受普通路径,不接受查询参数或百分号转义;Reality、XTLS/flow、gRPC、SS2022 和插件尚未实现,传入会报错。VLESS 目前只编码到 sing-box 和 Mihomo。
|
|
246
255
|
|
|
256
|
+
### 链式声明与已有配置迁移
|
|
257
|
+
|
|
258
|
+
`proxy.builder(node)` 提供不可变的链式写法,最后 `.build()` 得到普通节点数据。`.via("relay")` 表示通过 relay 连接这个节点;重复调用会替换依赖,不会追加一跳。
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
import { proxy, secret, compileProxyNodes, renderProxyNodes } from "proxylang";
|
|
262
|
+
|
|
263
|
+
const exit = proxy
|
|
264
|
+
.builder(
|
|
265
|
+
proxy.http({
|
|
266
|
+
id: "exit",
|
|
267
|
+
server: "proxy.example.com",
|
|
268
|
+
port: 8080,
|
|
269
|
+
username: secret("PROXY_USER"),
|
|
270
|
+
password: secret("PROXY_PASSWORD"),
|
|
271
|
+
}),
|
|
272
|
+
)
|
|
273
|
+
.via("relay")
|
|
274
|
+
.build();
|
|
275
|
+
|
|
276
|
+
const compiled = compileProxyNodes({
|
|
277
|
+
target: { engine: "surge", platform: "macos", version: "6.10.0" },
|
|
278
|
+
nodes: [exit],
|
|
279
|
+
names: { exit: "🇭🇰 我的出口" },
|
|
280
|
+
externals: [{ id: "relay", nativeName: "已有代理组", kind: "group" }],
|
|
281
|
+
});
|
|
282
|
+
if (!compiled.ok) throw new Error("节点编译失败");
|
|
283
|
+
const artifact = renderProxyNodes(compiled, (token) => process.env[token.name]);
|
|
284
|
+
// artifact.entries 提供每个节点的 id 和原生行,可按 provider 分文件。
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
节点片段目前仅支持 Surge macOS 6.10.0,允许域名服务器地址。它保留输入顺序,通过 `names` 映射原生名称;`label` 仍是元数据。外部组由已有配置提供,SDK 返回 `requirements` 并发出 warning;组装方必须逐设备检查实际包含的符号、种类及完整依赖图。片段不会生成占位组。
|
|
288
|
+
|
|
289
|
+
Surge 节点可显式声明 `tcpFastOpen`,Trojan/AnyTLS 可声明 `skipCertVerify` 和 `surge: { udpRelay: true }`。其它目标暂拒绝这些新选项。SS 可用 `surge: { udpRelay: false, blockQuic: "auto" }` 关闭 UDP 并保留原生 QUIC 策略;关闭 UDP 的约束会沿组与拨号链传播。详见[节点片段契约](docs/engineering/proxy-node-fragments/README.md)。
|
|
290
|
+
|
|
247
291
|
### Tailscale:有状态的网络端点
|
|
248
292
|
|
|
249
293
|
Tailscale 需要持久身份和引导解析,使用独立的 `endpoints` 声明。规则仍通过 `route(id)` 或 policy 的出口槽位引用它:
|
|
@@ -294,7 +338,7 @@ DEMO_PASSWORD=example-only DEMO_UUID=11111111-2222-4333-8444-555555555555 \
|
|
|
294
338
|
|
|
295
339
|
支持域名、IP、端口、网络类型与逻辑条件,节点协议包括 Trojan、HTTP、AnyTLS、Shadowsocks、VMess、VLESS,具体能力按目标版本检查。未知版本和影响路由行为的不支持项报错;可省略的展示信息报 warning,可用 `warningsAsErrors` 提升为错误。
|
|
296
340
|
|
|
297
|
-
Stash 当前拒绝来源 IP/端口、端口范围和组级 URLTest
|
|
341
|
+
Stash 当前拒绝来源 IP/端口、端口范围和组级 URLTest。完整配置的节点地址暂限 IP,独立 Surge 节点片段支持域名。HTTP、VMess、VLESS 及经过它们的代理链按 TCP-only 检查;AnyTLS 目前仅在 Surge 放行 UDP。远程节点订阅、MAC/进程匹配和 TUN 尚未实现。完整限制见 [SDK 细则](docs/implementation-v0.md)和 [Mihomo / Stash 转换边界](docs/engineering/clash-backends/README.md)。
|
|
298
342
|
|
|
299
343
|
配置文件是可信的 TypeScript 代码;构建产物包含密码,旧构建也会保留。凭据与产物管理见[构建契约](docs/feature/artifact-publication/use-case/publish-generation.md)。
|
|
300
344
|
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { R as requestSchema, a as explain, i as compile, l as targetCatalog, p as StaticRuleSetUnknownError, t as buildToDirectory } from "./host-BvBQxdmA.js";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
5
|
import { tsImport } from "tsx/esm/api";
|
|
@@ -1,266 +1,10 @@
|
|
|
1
|
-
import ipaddr from "ipaddr.js";
|
|
2
1
|
import { z } from "zod";
|
|
3
2
|
import { isIP } from "node:net";
|
|
3
|
+
import ipaddr from "ipaddr.js";
|
|
4
4
|
import { stringify } from "yaml";
|
|
5
5
|
import { lstat, mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
6
6
|
import { join, resolve } from "node:path";
|
|
7
7
|
import { randomUUID } from "node:crypto";
|
|
8
|
-
//#region src/dsl.ts
|
|
9
|
-
const ruleSet = (definition) => ({
|
|
10
|
-
...definition,
|
|
11
|
-
type: "ruleSet"
|
|
12
|
-
});
|
|
13
|
-
const match = {
|
|
14
|
-
ruleSet: (set) => set,
|
|
15
|
-
domain: (value) => ({
|
|
16
|
-
type: "domain",
|
|
17
|
-
value
|
|
18
|
-
}),
|
|
19
|
-
domainSuffix: (value) => ({
|
|
20
|
-
type: "domainSuffix",
|
|
21
|
-
value
|
|
22
|
-
}),
|
|
23
|
-
ipCidr: (value) => ({
|
|
24
|
-
type: "ipCidr",
|
|
25
|
-
value
|
|
26
|
-
}),
|
|
27
|
-
sourceIp: (value) => ({
|
|
28
|
-
type: "sourceIp",
|
|
29
|
-
value
|
|
30
|
-
}),
|
|
31
|
-
port: (from, to = from) => ({
|
|
32
|
-
type: "port",
|
|
33
|
-
from,
|
|
34
|
-
to
|
|
35
|
-
}),
|
|
36
|
-
sourcePort: (from, to = from) => ({
|
|
37
|
-
type: "sourcePort",
|
|
38
|
-
from,
|
|
39
|
-
to
|
|
40
|
-
}),
|
|
41
|
-
network: (value) => ({
|
|
42
|
-
type: "network",
|
|
43
|
-
value
|
|
44
|
-
}),
|
|
45
|
-
all: (...conditions) => ({
|
|
46
|
-
type: "all",
|
|
47
|
-
conditions
|
|
48
|
-
}),
|
|
49
|
-
any: (...conditions) => ({
|
|
50
|
-
type: "any",
|
|
51
|
-
conditions
|
|
52
|
-
}),
|
|
53
|
-
not: (condition) => ({
|
|
54
|
-
type: "not",
|
|
55
|
-
condition
|
|
56
|
-
})
|
|
57
|
-
};
|
|
58
|
-
const direct = () => ({ type: "direct" });
|
|
59
|
-
const reject = () => ({ type: "reject" });
|
|
60
|
-
const route = (to) => ({
|
|
61
|
-
type: "route",
|
|
62
|
-
to
|
|
63
|
-
});
|
|
64
|
-
const slot = (name) => ({
|
|
65
|
-
type: "slot",
|
|
66
|
-
name
|
|
67
|
-
});
|
|
68
|
-
const secret = (name) => ({
|
|
69
|
-
type: "env",
|
|
70
|
-
name
|
|
71
|
-
});
|
|
72
|
-
const rule = (id, when, then) => ({
|
|
73
|
-
type: "rule",
|
|
74
|
-
id,
|
|
75
|
-
when,
|
|
76
|
-
then
|
|
77
|
-
});
|
|
78
|
-
const block = (id, rules, when) => ({
|
|
79
|
-
type: "block",
|
|
80
|
-
id,
|
|
81
|
-
rules,
|
|
82
|
-
...when ? { when } : {}
|
|
83
|
-
});
|
|
84
|
-
const policy$1 = (definition) => ({
|
|
85
|
-
type: "policy",
|
|
86
|
-
...definition
|
|
87
|
-
});
|
|
88
|
-
const use = (definition, options) => ({
|
|
89
|
-
type: "use",
|
|
90
|
-
id: options.id,
|
|
91
|
-
policy: definition,
|
|
92
|
-
bindings: options.bindings
|
|
93
|
-
});
|
|
94
|
-
const sequence = (...parts) => parts.flatMap((part) => Array.isArray(part) ? part : [part]);
|
|
95
|
-
const defineConfig = (config) => config;
|
|
96
|
-
/** Filtering is stable: catalogue order determines initial selector order. */
|
|
97
|
-
function selectNodes(nodes, query = {}) {
|
|
98
|
-
return nodes.filter((node) => (!query.regions || node.region !== void 0 && query.regions.includes(node.region)) && (!query.providers || node.provider !== void 0 && query.providers.includes(node.provider)) && (!query.tags || query.tags.every((tag) => node.tags?.includes(tag)))).map((node) => node.id);
|
|
99
|
-
}
|
|
100
|
-
/** A shared strategy explicitly chooses an algorithm for each engine. */
|
|
101
|
-
const strategy = (definition) => ({
|
|
102
|
-
type: "strategy",
|
|
103
|
-
...definition
|
|
104
|
-
});
|
|
105
|
-
const group = {
|
|
106
|
-
select: () => ({ type: "select" }),
|
|
107
|
-
urltest: (options) => ({
|
|
108
|
-
type: "urltest",
|
|
109
|
-
...options
|
|
110
|
-
})
|
|
111
|
-
};
|
|
112
|
-
const surge$1 = {
|
|
113
|
-
smart: () => ({ type: "surge-smart" }),
|
|
114
|
-
ruleSet: (options) => ({
|
|
115
|
-
format: "rule-set",
|
|
116
|
-
...options,
|
|
117
|
-
type: "nativeRuleSet",
|
|
118
|
-
engine: "surge"
|
|
119
|
-
})
|
|
120
|
-
};
|
|
121
|
-
const mihomo = { ruleProvider: (options) => ({
|
|
122
|
-
...options,
|
|
123
|
-
type: "nativeRuleSet",
|
|
124
|
-
engine: "mihomo"
|
|
125
|
-
}) };
|
|
126
|
-
/** Protocol constructors keep credentials and options specific to their protocol. */
|
|
127
|
-
function nodeConstructor(type) {
|
|
128
|
-
return (options) => ({
|
|
129
|
-
...options,
|
|
130
|
-
type
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
const proxy = {
|
|
134
|
-
http: nodeConstructor("http"),
|
|
135
|
-
trojan: nodeConstructor("trojan"),
|
|
136
|
-
anytls: nodeConstructor("anytls"),
|
|
137
|
-
shadowsocks: nodeConstructor("shadowsocks"),
|
|
138
|
-
vmess: nodeConstructor("vmess"),
|
|
139
|
-
vless: nodeConstructor("vless")
|
|
140
|
-
};
|
|
141
|
-
const singbox$1 = {
|
|
142
|
-
ruleSet: (options) => ({
|
|
143
|
-
...options,
|
|
144
|
-
type: "nativeRuleSet",
|
|
145
|
-
engine: "sing-box"
|
|
146
|
-
}),
|
|
147
|
-
tailscale: (options) => ({
|
|
148
|
-
...options,
|
|
149
|
-
type: "sing-box-tailscale"
|
|
150
|
-
})
|
|
151
|
-
};
|
|
152
|
-
//#endregion
|
|
153
|
-
//#region src/rulesets.ts
|
|
154
|
-
function canonical(value) {
|
|
155
|
-
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
156
|
-
if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
|
|
157
|
-
return JSON.stringify(value);
|
|
158
|
-
}
|
|
159
|
-
function validateRuleSets(entries, engine, diagnostics, path) {
|
|
160
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
161
|
-
const urls = /* @__PURE__ */ new Map();
|
|
162
|
-
const error = (code) => diagnostics.push({
|
|
163
|
-
severity: "error",
|
|
164
|
-
code,
|
|
165
|
-
path,
|
|
166
|
-
message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
|
|
167
|
-
});
|
|
168
|
-
const visit = (m) => {
|
|
169
|
-
if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
|
|
170
|
-
const key = canonical(m);
|
|
171
|
-
if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
|
|
172
|
-
definitions.set(m.id, key);
|
|
173
|
-
if (m.type === "ruleSet") visit(m.when);
|
|
174
|
-
else {
|
|
175
|
-
if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
|
|
176
|
-
if (m.engine === "surge") {
|
|
177
|
-
const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
|
|
178
|
-
const url = new URL(m.url).href;
|
|
179
|
-
if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
|
|
180
|
-
urls.set(url, settings);
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
} else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
|
|
184
|
-
else if (m.type === "not") visit(m.condition);
|
|
185
|
-
};
|
|
186
|
-
const walk = (items) => {
|
|
187
|
-
for (const item of items) if (item.type === "rule") visit(item.when);
|
|
188
|
-
else if (item.type === "block") {
|
|
189
|
-
if (item.when) visit(item.when);
|
|
190
|
-
walk(item.rules);
|
|
191
|
-
} else walk(item.policy.rules);
|
|
192
|
-
};
|
|
193
|
-
walk(entries);
|
|
194
|
-
}
|
|
195
|
-
function lowerRuleSets(rules, diagnostics, path) {
|
|
196
|
-
let count = 0;
|
|
197
|
-
let origins = 0;
|
|
198
|
-
const lower = (m, origin, depth) => {
|
|
199
|
-
if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
|
|
200
|
-
if (m.type === "ruleSet") {
|
|
201
|
-
origin.push(`rule-set:${m.id}`);
|
|
202
|
-
return lower(m.when, origin, depth + 1);
|
|
203
|
-
}
|
|
204
|
-
if (m.type === "all" || m.type === "any") return {
|
|
205
|
-
...m,
|
|
206
|
-
conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
|
|
207
|
-
};
|
|
208
|
-
if (m.type === "not") return {
|
|
209
|
-
...m,
|
|
210
|
-
condition: lower(m.condition, origin, depth + 1)
|
|
211
|
-
};
|
|
212
|
-
return m;
|
|
213
|
-
};
|
|
214
|
-
try {
|
|
215
|
-
if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
|
|
216
|
-
return rules.map((r) => {
|
|
217
|
-
const origin = [...r.origin];
|
|
218
|
-
const when = lower(r.when, origin, 0);
|
|
219
|
-
origins += origin.length;
|
|
220
|
-
if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
|
|
221
|
-
return {
|
|
222
|
-
...r,
|
|
223
|
-
when,
|
|
224
|
-
origin
|
|
225
|
-
};
|
|
226
|
-
});
|
|
227
|
-
} catch {
|
|
228
|
-
diagnostics.push({
|
|
229
|
-
severity: "error",
|
|
230
|
-
code: "EXPANSION_LIMIT",
|
|
231
|
-
path,
|
|
232
|
-
message: "展开规则、条件或来源超过预算"
|
|
233
|
-
});
|
|
234
|
-
return [];
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
function collectNativeRuleSets(rules, target, diagnostics) {
|
|
238
|
-
const found = /* @__PURE__ */ new Map();
|
|
239
|
-
const visit = (m, nested) => {
|
|
240
|
-
if (m.type === "nativeRuleSet") {
|
|
241
|
-
found.set(m.id, m);
|
|
242
|
-
if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
|
|
243
|
-
severity: "error",
|
|
244
|
-
code: "RULESET_COMPOSITION_UNSUPPORTED",
|
|
245
|
-
target: target.id,
|
|
246
|
-
path: `targets.${target.id}.ruleSets.${m.id}`,
|
|
247
|
-
message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
|
|
248
|
-
});
|
|
249
|
-
} else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
|
|
250
|
-
else if (m.type === "not") visit(m.condition, true);
|
|
251
|
-
else if (m.type === "ruleSet") visit(m.when, nested);
|
|
252
|
-
};
|
|
253
|
-
rules.forEach((r) => visit(r.when, false));
|
|
254
|
-
for (const r of found.values()) diagnostics.push({
|
|
255
|
-
severity: "warning",
|
|
256
|
-
code: "EXTERNAL_RULESET_UNVERIFIED",
|
|
257
|
-
target: target.id,
|
|
258
|
-
path: `targets.${target.id}.ruleSets.${r.id}`,
|
|
259
|
-
message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
|
|
260
|
-
});
|
|
261
|
-
return [...found.values()];
|
|
262
|
-
}
|
|
263
|
-
//#endregion
|
|
264
8
|
//#region src/schema.ts
|
|
265
9
|
const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
|
|
266
10
|
const domain = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/);
|
|
@@ -395,9 +139,10 @@ const secretSchema = z.strictObject({
|
|
|
395
139
|
});
|
|
396
140
|
const nodeBase = {
|
|
397
141
|
id: idSchema,
|
|
398
|
-
server: ip,
|
|
142
|
+
server: z.union([ip, domain]),
|
|
399
143
|
port,
|
|
400
144
|
via: idSchema.optional(),
|
|
145
|
+
tcpFastOpen: z.boolean().optional(),
|
|
401
146
|
label: z.string().min(1).max(256).optional(),
|
|
402
147
|
region: z.string().regex(/^[A-Z]{2}$/).optional(),
|
|
403
148
|
provider: idSchema.optional(),
|
|
@@ -405,6 +150,7 @@ const nodeBase = {
|
|
|
405
150
|
};
|
|
406
151
|
const tlsSchema = z.strictObject({
|
|
407
152
|
serverName: domain,
|
|
153
|
+
skipCertVerify: z.boolean().optional(),
|
|
408
154
|
alpn: z.array(z.string().min(1).refine((x) => !/\p{C}/u.test(x) && Buffer.byteLength(x) <= 255)).min(1).refine(unique).optional()
|
|
409
155
|
});
|
|
410
156
|
const transportSchema = z.strictObject({
|
|
@@ -418,18 +164,33 @@ const uuidNode = {
|
|
|
418
164
|
tls: tlsSchema.optional(),
|
|
419
165
|
transport: transportSchema.optional()
|
|
420
166
|
};
|
|
167
|
+
const surgeOptions = { blockQuic: z.enum([
|
|
168
|
+
"auto",
|
|
169
|
+
"on",
|
|
170
|
+
"off"
|
|
171
|
+
]).optional() };
|
|
421
172
|
const nodeSchema = z.discriminatedUnion("type", [
|
|
422
173
|
z.strictObject({
|
|
423
174
|
...nodeBase,
|
|
424
175
|
type: z.literal("trojan"),
|
|
425
176
|
password: secretSchema,
|
|
426
|
-
serverName: domain.optional()
|
|
177
|
+
serverName: domain.optional(),
|
|
178
|
+
skipCertVerify: z.boolean().optional(),
|
|
179
|
+
surge: z.strictObject({
|
|
180
|
+
...surgeOptions,
|
|
181
|
+
udpRelay: z.literal(true).optional()
|
|
182
|
+
}).optional()
|
|
427
183
|
}),
|
|
428
184
|
z.strictObject({
|
|
429
185
|
...nodeBase,
|
|
430
186
|
type: z.literal("anytls"),
|
|
431
187
|
password: secretSchema,
|
|
432
|
-
serverName: domain.optional()
|
|
188
|
+
serverName: domain.optional(),
|
|
189
|
+
skipCertVerify: z.boolean().optional(),
|
|
190
|
+
surge: z.strictObject({
|
|
191
|
+
...surgeOptions,
|
|
192
|
+
udpRelay: z.literal(true).optional()
|
|
193
|
+
}).optional()
|
|
433
194
|
}),
|
|
434
195
|
z.strictObject({
|
|
435
196
|
...nodeBase,
|
|
@@ -441,6 +202,10 @@ const nodeSchema = z.discriminatedUnion("type", [
|
|
|
441
202
|
z.strictObject({
|
|
442
203
|
...nodeBase,
|
|
443
204
|
type: z.literal("shadowsocks"),
|
|
205
|
+
surge: z.strictObject({
|
|
206
|
+
...surgeOptions,
|
|
207
|
+
udpRelay: z.boolean().optional()
|
|
208
|
+
}).optional(),
|
|
444
209
|
method: z.enum([
|
|
445
210
|
"aes-128-gcm",
|
|
446
211
|
"aes-256-gcm",
|
|
@@ -450,7 +215,8 @@ const nodeSchema = z.discriminatedUnion("type", [
|
|
|
450
215
|
}),
|
|
451
216
|
z.strictObject({
|
|
452
217
|
...uuidNode,
|
|
453
|
-
type: z.literal("vmess")
|
|
218
|
+
type: z.literal("vmess"),
|
|
219
|
+
surge: z.strictObject(surgeOptions).optional()
|
|
454
220
|
}),
|
|
455
221
|
z.strictObject({
|
|
456
222
|
...uuidNode,
|
|
@@ -501,93 +267,367 @@ const groupSchema = z.union([
|
|
|
501
267
|
id: idSchema,
|
|
502
268
|
members
|
|
503
269
|
}),
|
|
504
|
-
z.strictObject({
|
|
505
|
-
type: z.literal("urltest"),
|
|
506
|
-
id: idSchema,
|
|
507
|
-
members,
|
|
508
|
-
url,
|
|
509
|
-
intervalSeconds: z.number().int().min(1).max(86400).default(180),
|
|
510
|
-
toleranceMs: z.number().int().min(0).max(6e4).default(50)
|
|
270
|
+
z.strictObject({
|
|
271
|
+
type: z.literal("urltest"),
|
|
272
|
+
id: idSchema,
|
|
273
|
+
members,
|
|
274
|
+
url,
|
|
275
|
+
intervalSeconds: z.number().int().min(1).max(86400).default(180),
|
|
276
|
+
toleranceMs: z.number().int().min(0).max(6e4).default(50)
|
|
277
|
+
})
|
|
278
|
+
]);
|
|
279
|
+
const requestSchema = z.strictObject({
|
|
280
|
+
network,
|
|
281
|
+
domain: domain.optional(),
|
|
282
|
+
ip: ip.optional(),
|
|
283
|
+
sourceIp: ip.optional(),
|
|
284
|
+
port: port.optional(),
|
|
285
|
+
sourcePort: port.optional()
|
|
286
|
+
});
|
|
287
|
+
const configSchema = z.strictObject({
|
|
288
|
+
programs: z.record(idSchema, z.strictObject({
|
|
289
|
+
engine: z.enum([
|
|
290
|
+
"surge",
|
|
291
|
+
"sing-box",
|
|
292
|
+
"mihomo",
|
|
293
|
+
"stash"
|
|
294
|
+
]),
|
|
295
|
+
nodes: z.array(nodeSchema),
|
|
296
|
+
endpoints: z.array(endpointSchema).max(1e3).optional(),
|
|
297
|
+
groups: z.array(groupSchema),
|
|
298
|
+
routing: z.array(entrySchema),
|
|
299
|
+
fallback: actionSchema,
|
|
300
|
+
listener: z.strictObject({
|
|
301
|
+
port,
|
|
302
|
+
resolver: ip
|
|
303
|
+
}).optional()
|
|
304
|
+
})),
|
|
305
|
+
targets: z.array(z.strictObject({
|
|
306
|
+
id: idSchema,
|
|
307
|
+
program: idSchema,
|
|
308
|
+
engine: z.enum([
|
|
309
|
+
"surge",
|
|
310
|
+
"sing-box",
|
|
311
|
+
"mihomo",
|
|
312
|
+
"stash"
|
|
313
|
+
]),
|
|
314
|
+
platform: z.enum(["macos", "linux"]),
|
|
315
|
+
version: z.string().regex(/^\d+\.\d+\.\d+$/),
|
|
316
|
+
mode: z.enum(["fragment", "standalone"]).default("fragment")
|
|
317
|
+
})).min(1),
|
|
318
|
+
cases: z.array(z.strictObject({
|
|
319
|
+
id: idSchema,
|
|
320
|
+
program: idSchema,
|
|
321
|
+
request: requestSchema,
|
|
322
|
+
expect: z.strictObject({
|
|
323
|
+
rule: z.string().min(1).optional(),
|
|
324
|
+
action: actionSchema
|
|
325
|
+
})
|
|
326
|
+
})).optional(),
|
|
327
|
+
warningsAsErrors: z.boolean().optional()
|
|
328
|
+
});
|
|
329
|
+
/** Reject cycles, executable values and excessive expansion before recursive schema parsing. */
|
|
330
|
+
function assertData(value) {
|
|
331
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
332
|
+
let count = 0;
|
|
333
|
+
const visit = (v, depth) => {
|
|
334
|
+
if (++count > 1e5 || depth > 64) throw new Error("INPUT_LIMIT");
|
|
335
|
+
if (v === void 0 || v === null || [
|
|
336
|
+
"string",
|
|
337
|
+
"number",
|
|
338
|
+
"boolean"
|
|
339
|
+
].includes(typeof v)) return;
|
|
340
|
+
if (typeof v !== "object" || ancestors.has(v)) throw new Error("INPUT_GRAPH");
|
|
341
|
+
if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) throw new Error("INPUT_OBJECT");
|
|
342
|
+
ancestors.add(v);
|
|
343
|
+
for (const descriptor of Object.values(Object.getOwnPropertyDescriptors(v))) {
|
|
344
|
+
if (descriptor.get || descriptor.set) throw new Error("INPUT_ACCESSOR");
|
|
345
|
+
visit(descriptor.value, depth + 1);
|
|
346
|
+
}
|
|
347
|
+
ancestors.delete(v);
|
|
348
|
+
};
|
|
349
|
+
visit(value, 0);
|
|
350
|
+
}
|
|
351
|
+
function deepFreeze(value) {
|
|
352
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
353
|
+
Object.freeze(value);
|
|
354
|
+
for (const item of Object.values(value)) deepFreeze(item);
|
|
355
|
+
}
|
|
356
|
+
return value;
|
|
357
|
+
}
|
|
358
|
+
//#endregion
|
|
359
|
+
//#region src/proxy-builder.ts
|
|
360
|
+
/** Fluent construction is separate from the plain-data node consumed by the compiler. */
|
|
361
|
+
function proxyBuilder(node) {
|
|
362
|
+
assertData(node);
|
|
363
|
+
const copy = deepFreeze(structuredClone(node));
|
|
364
|
+
const fork = (patch) => proxyBuilder({
|
|
365
|
+
...copy,
|
|
366
|
+
...patch
|
|
367
|
+
});
|
|
368
|
+
return Object.freeze({
|
|
369
|
+
via: (id) => fork({ via: id }),
|
|
370
|
+
label: (text) => fork({ label: text }),
|
|
371
|
+
tcpFastOpen: (enabled) => fork({ tcpFastOpen: enabled }),
|
|
372
|
+
build: () => deepFreeze(structuredClone(copy))
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
//#endregion
|
|
376
|
+
//#region src/dsl.ts
|
|
377
|
+
const ruleSet = (definition) => ({
|
|
378
|
+
...definition,
|
|
379
|
+
type: "ruleSet"
|
|
380
|
+
});
|
|
381
|
+
const match = {
|
|
382
|
+
ruleSet: (set) => set,
|
|
383
|
+
domain: (value) => ({
|
|
384
|
+
type: "domain",
|
|
385
|
+
value
|
|
386
|
+
}),
|
|
387
|
+
domainSuffix: (value) => ({
|
|
388
|
+
type: "domainSuffix",
|
|
389
|
+
value
|
|
390
|
+
}),
|
|
391
|
+
ipCidr: (value) => ({
|
|
392
|
+
type: "ipCidr",
|
|
393
|
+
value
|
|
394
|
+
}),
|
|
395
|
+
sourceIp: (value) => ({
|
|
396
|
+
type: "sourceIp",
|
|
397
|
+
value
|
|
398
|
+
}),
|
|
399
|
+
port: (from, to = from) => ({
|
|
400
|
+
type: "port",
|
|
401
|
+
from,
|
|
402
|
+
to
|
|
403
|
+
}),
|
|
404
|
+
sourcePort: (from, to = from) => ({
|
|
405
|
+
type: "sourcePort",
|
|
406
|
+
from,
|
|
407
|
+
to
|
|
408
|
+
}),
|
|
409
|
+
network: (value) => ({
|
|
410
|
+
type: "network",
|
|
411
|
+
value
|
|
412
|
+
}),
|
|
413
|
+
all: (...conditions) => ({
|
|
414
|
+
type: "all",
|
|
415
|
+
conditions
|
|
416
|
+
}),
|
|
417
|
+
any: (...conditions) => ({
|
|
418
|
+
type: "any",
|
|
419
|
+
conditions
|
|
420
|
+
}),
|
|
421
|
+
not: (condition) => ({
|
|
422
|
+
type: "not",
|
|
423
|
+
condition
|
|
424
|
+
})
|
|
425
|
+
};
|
|
426
|
+
const direct = () => ({ type: "direct" });
|
|
427
|
+
const reject = () => ({ type: "reject" });
|
|
428
|
+
const route = (to) => ({
|
|
429
|
+
type: "route",
|
|
430
|
+
to
|
|
431
|
+
});
|
|
432
|
+
const slot = (name) => ({
|
|
433
|
+
type: "slot",
|
|
434
|
+
name
|
|
435
|
+
});
|
|
436
|
+
const secret = (name) => ({
|
|
437
|
+
type: "env",
|
|
438
|
+
name
|
|
439
|
+
});
|
|
440
|
+
const rule = (id, when, then) => ({
|
|
441
|
+
type: "rule",
|
|
442
|
+
id,
|
|
443
|
+
when,
|
|
444
|
+
then
|
|
445
|
+
});
|
|
446
|
+
const block = (id, rules, when) => ({
|
|
447
|
+
type: "block",
|
|
448
|
+
id,
|
|
449
|
+
rules,
|
|
450
|
+
...when ? { when } : {}
|
|
451
|
+
});
|
|
452
|
+
const policy$1 = (definition) => ({
|
|
453
|
+
type: "policy",
|
|
454
|
+
...definition
|
|
455
|
+
});
|
|
456
|
+
const use = (definition, options) => ({
|
|
457
|
+
type: "use",
|
|
458
|
+
id: options.id,
|
|
459
|
+
policy: definition,
|
|
460
|
+
bindings: options.bindings
|
|
461
|
+
});
|
|
462
|
+
const sequence = (...parts) => parts.flatMap((part) => Array.isArray(part) ? part : [part]);
|
|
463
|
+
const defineConfig = (config) => config;
|
|
464
|
+
/** Filtering is stable: catalogue order determines initial selector order. */
|
|
465
|
+
function selectNodes(nodes, query = {}) {
|
|
466
|
+
return nodes.filter((node) => (!query.regions || node.region !== void 0 && query.regions.includes(node.region)) && (!query.providers || node.provider !== void 0 && query.providers.includes(node.provider)) && (!query.tags || query.tags.every((tag) => node.tags?.includes(tag)))).map((node) => node.id);
|
|
467
|
+
}
|
|
468
|
+
/** A shared strategy explicitly chooses an algorithm for each engine. */
|
|
469
|
+
const strategy = (definition) => ({
|
|
470
|
+
type: "strategy",
|
|
471
|
+
...definition
|
|
472
|
+
});
|
|
473
|
+
const group = {
|
|
474
|
+
select: () => ({ type: "select" }),
|
|
475
|
+
urltest: (options) => ({
|
|
476
|
+
type: "urltest",
|
|
477
|
+
...options
|
|
478
|
+
})
|
|
479
|
+
};
|
|
480
|
+
const surge$1 = {
|
|
481
|
+
smart: () => ({ type: "surge-smart" }),
|
|
482
|
+
ruleSet: (options) => ({
|
|
483
|
+
format: "rule-set",
|
|
484
|
+
...options,
|
|
485
|
+
type: "nativeRuleSet",
|
|
486
|
+
engine: "surge"
|
|
487
|
+
})
|
|
488
|
+
};
|
|
489
|
+
const mihomo = { ruleProvider: (options) => ({
|
|
490
|
+
...options,
|
|
491
|
+
type: "nativeRuleSet",
|
|
492
|
+
engine: "mihomo"
|
|
493
|
+
}) };
|
|
494
|
+
/** Protocol constructors keep credentials and options specific to their protocol. */
|
|
495
|
+
function nodeConstructor(type) {
|
|
496
|
+
return (options) => ({
|
|
497
|
+
...options,
|
|
498
|
+
type
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
const proxy = {
|
|
502
|
+
builder: proxyBuilder,
|
|
503
|
+
http: nodeConstructor("http"),
|
|
504
|
+
trojan: nodeConstructor("trojan"),
|
|
505
|
+
anytls: nodeConstructor("anytls"),
|
|
506
|
+
shadowsocks: nodeConstructor("shadowsocks"),
|
|
507
|
+
vmess: nodeConstructor("vmess"),
|
|
508
|
+
vless: nodeConstructor("vless")
|
|
509
|
+
};
|
|
510
|
+
const singbox$1 = {
|
|
511
|
+
ruleSet: (options) => ({
|
|
512
|
+
...options,
|
|
513
|
+
type: "nativeRuleSet",
|
|
514
|
+
engine: "sing-box"
|
|
515
|
+
}),
|
|
516
|
+
tailscale: (options) => ({
|
|
517
|
+
...options,
|
|
518
|
+
type: "sing-box-tailscale"
|
|
511
519
|
})
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
const
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
rule: z.string().min(1).optional(),
|
|
558
|
-
action: actionSchema
|
|
559
|
-
})
|
|
560
|
-
})).optional(),
|
|
561
|
-
warningsAsErrors: z.boolean().optional()
|
|
562
|
-
});
|
|
563
|
-
/** Reject cycles, executable values and excessive expansion before recursive schema parsing. */
|
|
564
|
-
function assertData(value) {
|
|
565
|
-
const ancestors = /* @__PURE__ */ new Set();
|
|
520
|
+
};
|
|
521
|
+
//#endregion
|
|
522
|
+
//#region src/rulesets.ts
|
|
523
|
+
function canonical(value) {
|
|
524
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
525
|
+
if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
|
|
526
|
+
return JSON.stringify(value);
|
|
527
|
+
}
|
|
528
|
+
function validateRuleSets(entries, engine, diagnostics, path) {
|
|
529
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
530
|
+
const urls = /* @__PURE__ */ new Map();
|
|
531
|
+
const error = (code) => diagnostics.push({
|
|
532
|
+
severity: "error",
|
|
533
|
+
code,
|
|
534
|
+
path,
|
|
535
|
+
message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
|
|
536
|
+
});
|
|
537
|
+
const visit = (m) => {
|
|
538
|
+
if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
|
|
539
|
+
const key = canonical(m);
|
|
540
|
+
if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
|
|
541
|
+
definitions.set(m.id, key);
|
|
542
|
+
if (m.type === "ruleSet") visit(m.when);
|
|
543
|
+
else {
|
|
544
|
+
if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
|
|
545
|
+
if (m.engine === "surge") {
|
|
546
|
+
const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
|
|
547
|
+
const url = new URL(m.url).href;
|
|
548
|
+
if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
|
|
549
|
+
urls.set(url, settings);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
} else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
|
|
553
|
+
else if (m.type === "not") visit(m.condition);
|
|
554
|
+
};
|
|
555
|
+
const walk = (items) => {
|
|
556
|
+
for (const item of items) if (item.type === "rule") visit(item.when);
|
|
557
|
+
else if (item.type === "block") {
|
|
558
|
+
if (item.when) visit(item.when);
|
|
559
|
+
walk(item.rules);
|
|
560
|
+
} else walk(item.policy.rules);
|
|
561
|
+
};
|
|
562
|
+
walk(entries);
|
|
563
|
+
}
|
|
564
|
+
function lowerRuleSets(rules, diagnostics, path) {
|
|
566
565
|
let count = 0;
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
if (
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
].includes(typeof v)) return;
|
|
574
|
-
if (typeof v !== "object" || ancestors.has(v)) throw new Error("INPUT_GRAPH");
|
|
575
|
-
if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) throw new Error("INPUT_OBJECT");
|
|
576
|
-
ancestors.add(v);
|
|
577
|
-
for (const descriptor of Object.values(Object.getOwnPropertyDescriptors(v))) {
|
|
578
|
-
if (descriptor.get || descriptor.set) throw new Error("INPUT_ACCESSOR");
|
|
579
|
-
visit(descriptor.value, depth + 1);
|
|
566
|
+
let origins = 0;
|
|
567
|
+
const lower = (m, origin, depth) => {
|
|
568
|
+
if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
|
|
569
|
+
if (m.type === "ruleSet") {
|
|
570
|
+
origin.push(`rule-set:${m.id}`);
|
|
571
|
+
return lower(m.when, origin, depth + 1);
|
|
580
572
|
}
|
|
581
|
-
|
|
573
|
+
if (m.type === "all" || m.type === "any") return {
|
|
574
|
+
...m,
|
|
575
|
+
conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
|
|
576
|
+
};
|
|
577
|
+
if (m.type === "not") return {
|
|
578
|
+
...m,
|
|
579
|
+
condition: lower(m.condition, origin, depth + 1)
|
|
580
|
+
};
|
|
581
|
+
return m;
|
|
582
582
|
};
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
583
|
+
try {
|
|
584
|
+
if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
|
|
585
|
+
return rules.map((r) => {
|
|
586
|
+
const origin = [...r.origin];
|
|
587
|
+
const when = lower(r.when, origin, 0);
|
|
588
|
+
origins += origin.length;
|
|
589
|
+
if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
|
|
590
|
+
return {
|
|
591
|
+
...r,
|
|
592
|
+
when,
|
|
593
|
+
origin
|
|
594
|
+
};
|
|
595
|
+
});
|
|
596
|
+
} catch {
|
|
597
|
+
diagnostics.push({
|
|
598
|
+
severity: "error",
|
|
599
|
+
code: "EXPANSION_LIMIT",
|
|
600
|
+
path,
|
|
601
|
+
message: "展开规则、条件或来源超过预算"
|
|
602
|
+
});
|
|
603
|
+
return [];
|
|
589
604
|
}
|
|
590
|
-
|
|
605
|
+
}
|
|
606
|
+
function collectNativeRuleSets(rules, target, diagnostics) {
|
|
607
|
+
const found = /* @__PURE__ */ new Map();
|
|
608
|
+
const visit = (m, nested) => {
|
|
609
|
+
if (m.type === "nativeRuleSet") {
|
|
610
|
+
found.set(m.id, m);
|
|
611
|
+
if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
|
|
612
|
+
severity: "error",
|
|
613
|
+
code: "RULESET_COMPOSITION_UNSUPPORTED",
|
|
614
|
+
target: target.id,
|
|
615
|
+
path: `targets.${target.id}.ruleSets.${m.id}`,
|
|
616
|
+
message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
|
|
617
|
+
});
|
|
618
|
+
} else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
|
|
619
|
+
else if (m.type === "not") visit(m.condition, true);
|
|
620
|
+
else if (m.type === "ruleSet") visit(m.when, nested);
|
|
621
|
+
};
|
|
622
|
+
rules.forEach((r) => visit(r.when, false));
|
|
623
|
+
for (const r of found.values()) diagnostics.push({
|
|
624
|
+
severity: "warning",
|
|
625
|
+
code: "EXTERNAL_RULESET_UNVERIFIED",
|
|
626
|
+
target: target.id,
|
|
627
|
+
path: `targets.${target.id}.ruleSets.${r.id}`,
|
|
628
|
+
message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
|
|
629
|
+
});
|
|
630
|
+
return [...found.values()];
|
|
591
631
|
}
|
|
592
632
|
//#endregion
|
|
593
633
|
//#region src/rules.ts
|
|
@@ -797,12 +837,21 @@ var RenderError = class extends Error {
|
|
|
797
837
|
function pathsOverlap(a, b) {
|
|
798
838
|
return a === b || a.startsWith(b.endsWith("/") ? b : `${b}/`) || b.startsWith(a.endsWith("/") ? a : `${a}/`);
|
|
799
839
|
}
|
|
800
|
-
function nodeIsTcpOnly(node) {
|
|
801
|
-
return node.type === "http" || node.type === "anytls" || node.type === "vmess" || node.type === "vless";
|
|
840
|
+
function nodeIsTcpOnly(node, engine) {
|
|
841
|
+
return node.type === "http" || node.type === "anytls" && engine !== "surge" || node.type === "vmess" || node.type === "vless" || engine === "surge" && node.type === "shadowsocks" && node.surge?.udpRelay === false;
|
|
802
842
|
}
|
|
803
843
|
function validateProxyOptions(node, target, diagnostics) {
|
|
804
|
-
if (target.engine !== "surge") return;
|
|
805
844
|
const tls = "tls" in node ? node.tls : void 0;
|
|
845
|
+
if (target.engine !== "surge") {
|
|
846
|
+
if (node.tcpFastOpen !== void 0 || "skipCertVerify" in node && node.skipCertVerify !== void 0 || tls?.skipCertVerify !== void 0 || "surge" in node && node.surge !== void 0) diagnostics.push({
|
|
847
|
+
severity: "error",
|
|
848
|
+
code: "PROXY_OPTION_UNSUPPORTED",
|
|
849
|
+
target: target.id,
|
|
850
|
+
path: `targets.${target.id}.nodes.${node.id}`,
|
|
851
|
+
message: "显式节点选项尚未实现此精确目标的编码"
|
|
852
|
+
});
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
806
855
|
if (("serverName" in node ? node.serverName : tls?.serverName) === "off" || tls?.alpn !== void 0) diagnostics.push({
|
|
807
856
|
severity: "error",
|
|
808
857
|
code: "PROXY_OPTION_UNSUPPORTED",
|
|
@@ -910,13 +959,13 @@ function clashProxy(node, engine, secret) {
|
|
|
910
959
|
}
|
|
911
960
|
return result;
|
|
912
961
|
}
|
|
913
|
-
function surgeProxy(node, secret) {
|
|
962
|
+
function surgeProxy(node, secret, name = (id) => id) {
|
|
914
963
|
const atom = (value) => {
|
|
915
964
|
if (!/^[A-Za-z0-9_./:@+%-]+$/.test(value)) throw new RenderError("SURGE_VALUE_UNREPRESENTABLE");
|
|
916
965
|
return value;
|
|
917
966
|
};
|
|
918
967
|
const params = [
|
|
919
|
-
`${node.id} = ${node.type === "shadowsocks" ? "ss" : node.type}`,
|
|
968
|
+
`${name(node.id)} = ${node.type === "shadowsocks" ? "ss" : node.type}`,
|
|
920
969
|
node.server,
|
|
921
970
|
String(node.port)
|
|
922
971
|
];
|
|
@@ -929,14 +978,15 @@ function surgeProxy(node, secret) {
|
|
|
929
978
|
case "anytls":
|
|
930
979
|
params.push(`password=${atom(secret(node.password))}`);
|
|
931
980
|
if (node.serverName) params.push(`sni=${node.serverName}`);
|
|
932
|
-
if (node.
|
|
981
|
+
if (node.skipCertVerify !== void 0) params.push(`skip-cert-verify=${node.skipCertVerify}`);
|
|
933
982
|
break;
|
|
934
983
|
case "shadowsocks":
|
|
935
|
-
params.push(`encrypt-method=${node.method}`, `password=${atom(secret(node.password))}
|
|
984
|
+
params.push(`encrypt-method=${node.method}`, `password=${atom(secret(node.password))}`);
|
|
936
985
|
break;
|
|
937
986
|
case "vmess":
|
|
938
987
|
params.push(`username=${uuid(node.uuid, secret)}`, "vmess-aead=true", "encrypt-method=aes-128-gcm", `tls=${!!node.tls}`);
|
|
939
988
|
if (node.tls) params.push(`sni=${node.tls.serverName}`);
|
|
989
|
+
if (node.tls?.skipCertVerify !== void 0) params.push(`skip-cert-verify=${node.tls.skipCertVerify}`);
|
|
940
990
|
if (node.transport) {
|
|
941
991
|
params.push("ws=true", `ws-path=${node.transport.path}`);
|
|
942
992
|
if (node.transport.host) params.push(`ws-headers=Host:${node.transport.host}`);
|
|
@@ -944,7 +994,11 @@ function surgeProxy(node, secret) {
|
|
|
944
994
|
break;
|
|
945
995
|
case "vless": throw new RenderError("PROTOCOL_UNSUPPORTED");
|
|
946
996
|
}
|
|
947
|
-
if (node.
|
|
997
|
+
if (node.tcpFastOpen !== void 0) params.push(`tfo=${node.tcpFastOpen}`);
|
|
998
|
+
if (node.type === "trojan" || node.type === "anytls" && node.surge?.udpRelay) params.push("udp-relay=true");
|
|
999
|
+
if (node.type === "shadowsocks") params.push(`udp-relay=${node.surge?.udpRelay ?? true}`, `block-quic=${node.surge?.blockQuic ?? "off"}`);
|
|
1000
|
+
if (node.type !== "shadowsocks" && "surge" in node && node.surge?.blockQuic !== void 0) params.push(`block-quic=${node.surge.blockQuic}`);
|
|
1001
|
+
if (node.via) params.push(`underlying-proxy=${name(node.via)}`);
|
|
948
1002
|
return params.join(", ");
|
|
949
1003
|
}
|
|
950
1004
|
//#endregion
|
|
@@ -1129,6 +1183,27 @@ const targetCatalog = deepFreeze([
|
|
|
1129
1183
|
}
|
|
1130
1184
|
]);
|
|
1131
1185
|
//#endregion
|
|
1186
|
+
//#region src/native-names.ts
|
|
1187
|
+
const nativeNameSchema = z.string().min(1).max(256).refine((value) => value.trim() === value && !/[\p{C}\p{Zl}\p{Zp},=[\]()#;]/u.test(value) && !["DIRECT", "REJECT"].includes(value.toUpperCase()) && !value.toLowerCase().startsWith("pl-"));
|
|
1188
|
+
function isReservedNativeName(name, engine) {
|
|
1189
|
+
return (engine === "surge" ? [
|
|
1190
|
+
"REJECT-DROP",
|
|
1191
|
+
"REJECT-NO-DROP",
|
|
1192
|
+
"REJECT-TINYGIF"
|
|
1193
|
+
] : engine === "mihomo" ? [
|
|
1194
|
+
"GLOBAL",
|
|
1195
|
+
"PASS",
|
|
1196
|
+
"COMPATIBLE",
|
|
1197
|
+
"REJECT-DROP",
|
|
1198
|
+
"PASS-RULE"
|
|
1199
|
+
] : engine === "stash" ? [
|
|
1200
|
+
"GLOBAL",
|
|
1201
|
+
"PASS",
|
|
1202
|
+
"COMPATIBLE",
|
|
1203
|
+
"REJECT-DROP"
|
|
1204
|
+
] : []).includes(name.toUpperCase());
|
|
1205
|
+
}
|
|
1206
|
+
//#endregion
|
|
1132
1207
|
//#region src/strategies.ts
|
|
1133
1208
|
function lowerStrategies(groups, engine, diagnostics, path) {
|
|
1134
1209
|
const selected = [];
|
|
@@ -1197,7 +1272,6 @@ function singboxGroup(group, name = (id) => id) {
|
|
|
1197
1272
|
interrupt_exist_connections: false
|
|
1198
1273
|
};
|
|
1199
1274
|
}
|
|
1200
|
-
const nameSchema = z.string().min(1).max(256).refine((value) => value.trim() === value && !/[\p{C}\p{Zl}\p{Zp},=[\]()#;]/u.test(value) && !["DIRECT", "REJECT"].includes(value.toUpperCase()) && !value.toLowerCase().startsWith("pl-"));
|
|
1201
1275
|
const inputSchema = z.strictObject({
|
|
1202
1276
|
target: z.strictObject({
|
|
1203
1277
|
engine: z.enum([
|
|
@@ -1211,10 +1285,10 @@ const inputSchema = z.strictObject({
|
|
|
1211
1285
|
}),
|
|
1212
1286
|
nodes: z.array(z.strictObject({
|
|
1213
1287
|
id: idSchema,
|
|
1214
|
-
nativeName:
|
|
1288
|
+
nativeName: nativeNameSchema
|
|
1215
1289
|
})).max(1e3),
|
|
1216
1290
|
strategies: z.array(strategySchema).max(1e3),
|
|
1217
|
-
names: z.record(idSchema,
|
|
1291
|
+
names: z.record(idSchema, nativeNameSchema).optional()
|
|
1218
1292
|
});
|
|
1219
1293
|
/** Only group topology/encoding is checked here; nodes, via, protocols and routes remain consumer-owned. */
|
|
1220
1294
|
function compileStrategyGroups(input) {
|
|
@@ -1252,21 +1326,9 @@ function compileStrategyGroups(input) {
|
|
|
1252
1326
|
const ids = [...nodes.map((n) => n.id), ...strategies.map((s) => s.id)];
|
|
1253
1327
|
if (new Set(ids).size !== ids.length || ids.length > 1e3) error("DUPLICATE_RESOURCE", "$", "资源 ID 必须唯一且总数不超过 1000");
|
|
1254
1328
|
if (Object.keys(names).some((id) => !strategies.some((s) => s.id === id))) error("UNKNOWN_NAME_MAPPING", "names", "只能映射已声明策略 ID");
|
|
1255
|
-
const nativeNames = new Map([...nodes.map((n) => [n.id, n.nativeName]), ...strategies.map((s) => [s.id, names[s.id]
|
|
1256
|
-
if ([...nativeNames.values()].some((name) => !
|
|
1257
|
-
|
|
1258
|
-
"GLOBAL",
|
|
1259
|
-
"PASS",
|
|
1260
|
-
"COMPATIBLE",
|
|
1261
|
-
"REJECT-DROP",
|
|
1262
|
-
"PASS-RULE"
|
|
1263
|
-
] : target.engine === "stash" ? [
|
|
1264
|
-
"GLOBAL",
|
|
1265
|
-
"PASS",
|
|
1266
|
-
"COMPATIBLE",
|
|
1267
|
-
"REJECT-DROP"
|
|
1268
|
-
] : [];
|
|
1269
|
-
if ([...nativeNames.values()].some((value) => reserved.includes(value.toUpperCase()))) error("INVALID_NATIVE_NAME", "names", "最终名称与目标内建策略冲突");
|
|
1329
|
+
const nativeNames = new Map([...nodes.map((n) => [n.id, n.nativeName]), ...strategies.map((s) => [s.id, Object.hasOwn(names, s.id) ? names[s.id] : s.id])]);
|
|
1330
|
+
if ([...nativeNames.values()].some((name) => !nativeNameSchema.safeParse(name).success)) error("INVALID_NATIVE_NAME", "names", "最终名称不符合原生名称约束");
|
|
1331
|
+
if ([...nativeNames.values()].some((value) => isReservedNativeName(value, target.engine))) error("INVALID_NATIVE_NAME", "names", "最终名称与目标内建策略冲突");
|
|
1270
1332
|
if (new Set(nativeNames.values()).size !== nativeNames.size) error("DUPLICATE_NATIVE_NAME", "names", "最终节点和策略名称必须唯一");
|
|
1271
1333
|
const { groups, selections } = lowerStrategies(strategies, target.engine, diagnostics, "$");
|
|
1272
1334
|
const all = new Set(ids);
|
|
@@ -1337,6 +1399,7 @@ function compile(input) {
|
|
|
1337
1399
|
if (Object.keys(config.programs).length === 0) error("EMPTY_PROGRAMS", "programs", "至少需要一个程序");
|
|
1338
1400
|
for (const [name, program] of Object.entries(config.programs)) {
|
|
1339
1401
|
const path = `programs.${name}`;
|
|
1402
|
+
for (const node of program.nodes) if (!isIP(node.server)) error("PROXY_HOSTNAME_MODE_UNSUPPORTED", `${path}.nodes.${node.id}`, "域名代理地址目前仅允许节点片段入口");
|
|
1340
1403
|
validateRuleSets(program.routing, program.engine, diagnostics, path);
|
|
1341
1404
|
const rules = lowerRuleSets(expandRules(program.routing, diagnostics, name), diagnostics, path);
|
|
1342
1405
|
expanded.set(name, rules);
|
|
@@ -1362,7 +1425,7 @@ function compile(input) {
|
|
|
1362
1425
|
if (states.get(id) === 2) return tcpOnly.get(id) ?? false;
|
|
1363
1426
|
states.set(id, 1);
|
|
1364
1427
|
const item = byId.get(id);
|
|
1365
|
-
let limited = !!item && "server" in item && nodeIsTcpOnly(item);
|
|
1428
|
+
let limited = !!item && "server" in item && nodeIsTcpOnly(item, program.engine);
|
|
1366
1429
|
for (const ref of edges.get(id) ?? []) limited = visit(ref) || limited;
|
|
1367
1430
|
states.set(id, 2);
|
|
1368
1431
|
tcpOnly.set(id, limited);
|
|
@@ -1519,15 +1582,11 @@ function explain(compilation, target, request) {
|
|
|
1519
1582
|
return explainRules(plan.rules, plan.program.fallback, request);
|
|
1520
1583
|
}
|
|
1521
1584
|
//#endregion
|
|
1522
|
-
//#region src/
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
const actionTag = (action) => action.type === "route" ? action.to : action.type === "direct" ? DIRECT : "pl-reject";
|
|
1526
|
-
/** Secret resolution is once per token per batch, including across providers. */
|
|
1527
|
-
function render(compilation, resolveSecret) {
|
|
1528
|
-
if (!compilation.ok) throw new RenderError("COMPILATION_FAILED");
|
|
1585
|
+
//#region src/secrets.ts
|
|
1586
|
+
/** One reader per rendering batch; exceptions and missing values never disclose credentials. */
|
|
1587
|
+
function secretReader(resolveSecret) {
|
|
1529
1588
|
const values = /* @__PURE__ */ new Map();
|
|
1530
|
-
|
|
1589
|
+
return (token) => {
|
|
1531
1590
|
if (values.has(token.name)) return values.get(token.name);
|
|
1532
1591
|
let value;
|
|
1533
1592
|
try {
|
|
@@ -1539,6 +1598,16 @@ function render(compilation, resolveSecret) {
|
|
|
1539
1598
|
values.set(token.name, value);
|
|
1540
1599
|
return value;
|
|
1541
1600
|
};
|
|
1601
|
+
}
|
|
1602
|
+
//#endregion
|
|
1603
|
+
//#region src/render.ts
|
|
1604
|
+
const DIRECT = "pl-direct";
|
|
1605
|
+
const DNS = "pl-dns";
|
|
1606
|
+
const actionTag = (action) => action.type === "route" ? action.to : action.type === "direct" ? DIRECT : "pl-reject";
|
|
1607
|
+
/** Secret resolution is once per token per batch, including across providers. */
|
|
1608
|
+
function render(compilation, resolveSecret) {
|
|
1609
|
+
if (!compilation.ok) throw new RenderError("COMPILATION_FAILED");
|
|
1610
|
+
const secret = secretReader(resolveSecret);
|
|
1542
1611
|
return compilation.plans.map((plan) => ({
|
|
1543
1612
|
target: plan.target.id,
|
|
1544
1613
|
filename: `${plan.target.id}.${plan.target.engine === "surge" ? "conf" : plan.target.engine === "sing-box" ? "json" : "yaml"}`,
|
|
@@ -1820,4 +1889,4 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1820
1889
|
};
|
|
1821
1890
|
}
|
|
1822
1891
|
//#endregion
|
|
1823
|
-
export {
|
|
1892
|
+
export { slot as A, route as C, selectNodes as D, secret as E, deepFreeze as F, idSchema as I, nodeSchema as L, surge$1 as M, use as N, sequence as O, assertData as P, requestSchema as R, reject as S, ruleSet as T, group as _, explain as a, policy$1 as b, nativeNameSchema as c, surgeProxy as d, validateProxyOptions as f, direct as g, defineConfig as h, compile as i, strategy as j, singbox$1 as k, targetCatalog as l, block as m, render as n, compileStrategyGroups as o, StaticRuleSetUnknownError as p, secretReader as r, isReservedNativeName as s, buildToDirectory as t, RenderError as u, match as v, rule as w, proxy as x, mihomo as y };
|
package/dist/index.d.ts
CHANGED
|
@@ -84,6 +84,7 @@ export type ProxyBase = {
|
|
|
84
84
|
readonly server: string;
|
|
85
85
|
readonly port: number;
|
|
86
86
|
readonly via?: string;
|
|
87
|
+
readonly tcpFastOpen?: boolean;
|
|
87
88
|
readonly label?: string;
|
|
88
89
|
readonly region?: string;
|
|
89
90
|
readonly provider?: string;
|
|
@@ -92,6 +93,14 @@ export type ProxyBase = {
|
|
|
92
93
|
export type ProxyTLS = {
|
|
93
94
|
readonly serverName: string;
|
|
94
95
|
readonly alpn?: readonly string[];
|
|
96
|
+
readonly skipCertVerify?: boolean;
|
|
97
|
+
};
|
|
98
|
+
export type SurgeProxyOptions = {
|
|
99
|
+
readonly udpRelay?: boolean;
|
|
100
|
+
readonly blockQuic?: "auto" | "on" | "off";
|
|
101
|
+
};
|
|
102
|
+
type SurgeAutomaticUdpOptions = Omit<SurgeProxyOptions, "udpRelay"> & {
|
|
103
|
+
readonly udpRelay?: true;
|
|
95
104
|
};
|
|
96
105
|
export type WebSocketTransport = {
|
|
97
106
|
readonly type: "ws";
|
|
@@ -102,11 +111,15 @@ export type TrojanNode = ProxyBase & {
|
|
|
102
111
|
readonly type: "trojan";
|
|
103
112
|
readonly password: Secret;
|
|
104
113
|
readonly serverName?: string;
|
|
114
|
+
readonly skipCertVerify?: boolean;
|
|
115
|
+
readonly surge?: SurgeAutomaticUdpOptions;
|
|
105
116
|
};
|
|
106
117
|
export type AnyTLSNode = ProxyBase & {
|
|
107
118
|
readonly type: "anytls";
|
|
108
119
|
readonly password: Secret;
|
|
109
120
|
readonly serverName?: string;
|
|
121
|
+
readonly skipCertVerify?: boolean;
|
|
122
|
+
readonly surge?: SurgeAutomaticUdpOptions;
|
|
110
123
|
};
|
|
111
124
|
export type HttpNode = ProxyBase & {
|
|
112
125
|
readonly type: "http";
|
|
@@ -118,12 +131,14 @@ export type ShadowsocksNode = ProxyBase & {
|
|
|
118
131
|
readonly type: "shadowsocks";
|
|
119
132
|
readonly method: "aes-128-gcm" | "aes-256-gcm" | "chacha20-ietf-poly1305";
|
|
120
133
|
readonly password: Secret;
|
|
134
|
+
readonly surge?: SurgeProxyOptions;
|
|
121
135
|
};
|
|
122
136
|
export type VMessNode = ProxyBase & {
|
|
123
137
|
readonly type: "vmess";
|
|
124
138
|
readonly uuid: Secret;
|
|
125
139
|
readonly tls?: ProxyTLS;
|
|
126
140
|
readonly transport?: WebSocketTransport;
|
|
141
|
+
readonly surge?: Pick<SurgeProxyOptions, "blockQuic">;
|
|
127
142
|
};
|
|
128
143
|
export type VLESSNode = ProxyBase & {
|
|
129
144
|
readonly type: "vless";
|
|
@@ -267,6 +282,18 @@ export type Explanation = {
|
|
|
267
282
|
}[];
|
|
268
283
|
};
|
|
269
284
|
//#endregion
|
|
285
|
+
//#region src/proxy-builder.d.ts
|
|
286
|
+
type ProxyBuilder<N extends ProxyNode> = {
|
|
287
|
+
readonly via: (id: string) => ProxyBuilder<N>;
|
|
288
|
+
readonly label: (text: string) => ProxyBuilder<N>;
|
|
289
|
+
readonly tcpFastOpen: (enabled: boolean) => ProxyBuilder<N>;
|
|
290
|
+
readonly build: () => N;
|
|
291
|
+
};
|
|
292
|
+
/** Fluent construction is separate from the plain-data node consumed by the compiler. */
|
|
293
|
+
declare function proxyBuilder<N extends ProxyNode>(node: N): ProxyBuilder<Extract<ProxyNode, {
|
|
294
|
+
type: N["type"];
|
|
295
|
+
}>>;
|
|
296
|
+
//#endregion
|
|
270
297
|
//#region src/dsl.d.ts
|
|
271
298
|
export declare const ruleSet: (definition: Omit<NamedRuleSet, "type">) => NamedRuleSet;
|
|
272
299
|
export declare const match: {
|
|
@@ -324,6 +351,7 @@ export declare const mihomo: {
|
|
|
324
351
|
}>, "type" | "engine">) => NativeRuleSet;
|
|
325
352
|
};
|
|
326
353
|
export declare const proxy: {
|
|
354
|
+
builder: typeof proxyBuilder;
|
|
327
355
|
http: (options: Omit<HttpNode, "type">) => HttpNode;
|
|
328
356
|
trojan: (options: Omit<TrojanNode, "type">) => TrojanNode;
|
|
329
357
|
anytls: (options: Omit<AnyTLSNode, "type">) => AnyTLSNode;
|
|
@@ -479,4 +507,45 @@ export declare class StaticRuleSetUnknownError extends Error {
|
|
|
479
507
|
constructor();
|
|
480
508
|
}
|
|
481
509
|
//#endregion
|
|
482
|
-
|
|
510
|
+
//#region src/proxy-fragments.d.ts
|
|
511
|
+
type ProxyNodeInput = {
|
|
512
|
+
readonly target: {
|
|
513
|
+
readonly engine: "surge";
|
|
514
|
+
readonly platform: "macos";
|
|
515
|
+
readonly version: "6.10.0";
|
|
516
|
+
};
|
|
517
|
+
readonly nodes: readonly ProxyNode[];
|
|
518
|
+
readonly names?: Readonly<Record<string, string>>;
|
|
519
|
+
readonly externals?: readonly {
|
|
520
|
+
readonly id: string;
|
|
521
|
+
readonly nativeName: string;
|
|
522
|
+
readonly kind: "proxy" | "group";
|
|
523
|
+
}[];
|
|
524
|
+
};
|
|
525
|
+
type ProxyNodeCompilation = {
|
|
526
|
+
readonly ok: boolean;
|
|
527
|
+
readonly artifactKind: "proxy-nodes";
|
|
528
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
529
|
+
readonly bindings: readonly {
|
|
530
|
+
readonly id: string;
|
|
531
|
+
readonly nativeName: string;
|
|
532
|
+
}[];
|
|
533
|
+
readonly requirements: readonly {
|
|
534
|
+
readonly id: string;
|
|
535
|
+
readonly nativeName: string;
|
|
536
|
+
readonly kind: "proxy" | "group";
|
|
537
|
+
readonly usedBy: readonly string[];
|
|
538
|
+
}[];
|
|
539
|
+
};
|
|
540
|
+
type ProxyNodeArtifact = {
|
|
541
|
+
readonly artifactKind: "proxy-nodes";
|
|
542
|
+
readonly content: string;
|
|
543
|
+
readonly entries: readonly {
|
|
544
|
+
readonly id: string;
|
|
545
|
+
readonly content: string;
|
|
546
|
+
}[];
|
|
547
|
+
};
|
|
548
|
+
export declare function compileProxyNodes(input: unknown): ProxyNodeCompilation;
|
|
549
|
+
export declare function renderProxyNodes(compilation: ProxyNodeCompilation, resolveSecret: (token: Secret) => string | undefined): ProxyNodeArtifact;
|
|
550
|
+
//#endregion
|
|
551
|
+
export type { Artifact, BuildResult, CaseResult, Compilation, ProxyBuilder, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, StrategyGroupCompilation, StrategyGroupInput, TargetPlan };
|
package/dist/index.js
CHANGED
|
@@ -1 +1,132 @@
|
|
|
1
|
-
|
|
1
|
+
import { A as slot, C as route, D as selectNodes, E as secret, F as deepFreeze, I as idSchema, L as nodeSchema, M as surge, N as use, O as sequence, P as assertData, S as reject, T as ruleSet, _ as group, a as explain, b as policy, c as nativeNameSchema, d as surgeProxy, f as validateProxyOptions, g as direct, h as defineConfig, i as compile, j as strategy, k as singbox, l as targetCatalog, m as block, n as render, o as compileStrategyGroups, p as StaticRuleSetUnknownError, r as secretReader, s as isReservedNativeName, t as buildToDirectory, u as RenderError, v as match, w as rule, x as proxy, y as mihomo } from "./host-BvBQxdmA.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
//#region src/proxy-fragments.ts
|
|
4
|
+
const inputSchema = z.strictObject({
|
|
5
|
+
target: z.strictObject({
|
|
6
|
+
engine: z.string(),
|
|
7
|
+
platform: z.string(),
|
|
8
|
+
version: z.string()
|
|
9
|
+
}),
|
|
10
|
+
nodes: z.array(nodeSchema).max(1e3),
|
|
11
|
+
names: z.record(idSchema, nativeNameSchema).optional(),
|
|
12
|
+
externals: z.array(z.strictObject({
|
|
13
|
+
id: idSchema,
|
|
14
|
+
nativeName: nativeNameSchema,
|
|
15
|
+
kind: z.enum(["proxy", "group"])
|
|
16
|
+
})).max(1e3).optional()
|
|
17
|
+
});
|
|
18
|
+
const plans = /* @__PURE__ */ new WeakMap();
|
|
19
|
+
function compileProxyNodes(input) {
|
|
20
|
+
const diagnostics = [];
|
|
21
|
+
const error = (code, path, message) => diagnostics.push({
|
|
22
|
+
severity: "error",
|
|
23
|
+
code,
|
|
24
|
+
path,
|
|
25
|
+
message
|
|
26
|
+
});
|
|
27
|
+
const failure = () => deepFreeze({
|
|
28
|
+
ok: false,
|
|
29
|
+
artifactKind: "proxy-nodes",
|
|
30
|
+
diagnostics,
|
|
31
|
+
bindings: [],
|
|
32
|
+
requirements: []
|
|
33
|
+
});
|
|
34
|
+
try {
|
|
35
|
+
assertData(input);
|
|
36
|
+
} catch {
|
|
37
|
+
error("INVALID_INPUT_GRAPH", "$", "输入必须是有限纯数据,不接受 builder 或访问器");
|
|
38
|
+
return failure();
|
|
39
|
+
}
|
|
40
|
+
const parsed = inputSchema.safeParse(input);
|
|
41
|
+
if (!parsed.success) {
|
|
42
|
+
error("INVALID_SCHEMA", "$", "节点、名字或外部声明不符合严格 schema");
|
|
43
|
+
return failure();
|
|
44
|
+
}
|
|
45
|
+
const { target, nodes, names = {}, externals = [] } = deepFreeze(parsed.data);
|
|
46
|
+
const ids = [...nodes.map((n) => n.id), ...externals.map((e) => e.id)];
|
|
47
|
+
if (ids.length > 1e3) error("RESOURCE_LIMIT", "$", "节点和外部声明总数最多1000");
|
|
48
|
+
if (new Set(ids).size !== ids.length) error("DUPLICATE_RESOURCE", "$", "节点与外部声明 ID 必须唯一");
|
|
49
|
+
const nodeIds = new Set(nodes.map((n) => n.id));
|
|
50
|
+
if (Object.keys(names).some((id) => !nodeIds.has(id))) error("UNKNOWN_NAME_MAPPING", "names", "名字映射只能引用输入节点");
|
|
51
|
+
const bindings = nodes.map((node) => ({
|
|
52
|
+
id: node.id,
|
|
53
|
+
nativeName: Object.hasOwn(names, node.id) ? names[node.id] : node.id
|
|
54
|
+
}));
|
|
55
|
+
const symbols = [...bindings, ...externals];
|
|
56
|
+
if (symbols.some((s) => !nativeNameSchema.safeParse(s.nativeName).success || isReservedNativeName(s.nativeName, "surge"))) error("INVALID_NATIVE_NAME", "names", "原生名不合法或与目标内建策略冲突");
|
|
57
|
+
if (new Set(symbols.map((s) => s.nativeName)).size !== symbols.length) error("DUPLICATE_NATIVE_NAME", "names", "节点和外部符号的原生名必须唯一");
|
|
58
|
+
const allIds = new Set(ids);
|
|
59
|
+
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
60
|
+
for (const node of nodes) if (node.via && !allIds.has(node.via)) error("MISSING_REFERENCE", `nodes.${node.id}.via`, "拨号依赖未声明");
|
|
61
|
+
const states = /* @__PURE__ */ new Map();
|
|
62
|
+
const visit = (id) => {
|
|
63
|
+
if (states.get(id) === 1) {
|
|
64
|
+
error("RESOURCE_CYCLE", `nodes.${id}.via`, "内部拨号依赖形成循环");
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (states.get(id) === 2) return;
|
|
68
|
+
states.set(id, 1);
|
|
69
|
+
const via = byId.get(id)?.via;
|
|
70
|
+
if (via && byId.has(via)) visit(via);
|
|
71
|
+
states.set(id, 2);
|
|
72
|
+
};
|
|
73
|
+
if (ids.length <= 1e3) for (const id of byId.keys()) visit(id);
|
|
74
|
+
if (diagnostics.length) return failure();
|
|
75
|
+
if (target.engine !== "surge" || target.platform !== "macos" || target.version !== "6.10.0") {
|
|
76
|
+
error("UNKNOWN_TARGET", "target", "节点片段仅支持 Surge macOS 6.10.0");
|
|
77
|
+
return failure();
|
|
78
|
+
}
|
|
79
|
+
const descriptor = targetCatalog.find((t) => t.engine === "surge" && t.version === target.version);
|
|
80
|
+
for (const node of nodes) {
|
|
81
|
+
if (!descriptor.protocols.includes(node.type)) error("PROTOCOL_UNSUPPORTED", `nodes.${node.id}`, "精确目标不支持该节点协议");
|
|
82
|
+
validateProxyOptions(node, {
|
|
83
|
+
id: "nodes",
|
|
84
|
+
program: "nodes",
|
|
85
|
+
engine: "surge",
|
|
86
|
+
platform: "macos",
|
|
87
|
+
version: target.version
|
|
88
|
+
}, diagnostics);
|
|
89
|
+
}
|
|
90
|
+
if (diagnostics.some((d) => d.severity === "error")) return failure();
|
|
91
|
+
const requirements = externals.flatMap((external) => {
|
|
92
|
+
const usedBy = nodes.filter((node) => node.via === external.id).map((node) => node.id);
|
|
93
|
+
return usedBy.length ? [{
|
|
94
|
+
...external,
|
|
95
|
+
usedBy
|
|
96
|
+
}] : [];
|
|
97
|
+
});
|
|
98
|
+
if (requirements.length) diagnostics.push({
|
|
99
|
+
severity: "warning",
|
|
100
|
+
code: "EXTERNAL_REFERENCE_UNVERIFIED",
|
|
101
|
+
path: "externals",
|
|
102
|
+
message: "必须逐设备验证原生符号、include 闭包及完整依赖图;未知动态组须拒绝"
|
|
103
|
+
});
|
|
104
|
+
const compilation = deepFreeze({
|
|
105
|
+
ok: true,
|
|
106
|
+
artifactKind: "proxy-nodes",
|
|
107
|
+
diagnostics,
|
|
108
|
+
bindings,
|
|
109
|
+
requirements
|
|
110
|
+
});
|
|
111
|
+
plans.set(compilation, deepFreeze({
|
|
112
|
+
nodes,
|
|
113
|
+
names: Object.fromEntries(symbols.map((s) => [s.id, s.nativeName]))
|
|
114
|
+
}));
|
|
115
|
+
return compilation;
|
|
116
|
+
}
|
|
117
|
+
function renderProxyNodes(compilation, resolveSecret) {
|
|
118
|
+
const plan = plans.get(compilation);
|
|
119
|
+
if (!plan) throw new RenderError("COMPILATION_FAILED");
|
|
120
|
+
const secret = secretReader(resolveSecret);
|
|
121
|
+
const entries = plan.nodes.map((node) => ({
|
|
122
|
+
id: node.id,
|
|
123
|
+
content: surgeProxy(node, secret, (id) => plan.names[id]) + "\n"
|
|
124
|
+
}));
|
|
125
|
+
return deepFreeze({
|
|
126
|
+
artifactKind: "proxy-nodes",
|
|
127
|
+
content: entries.map((e) => e.content).join(""),
|
|
128
|
+
entries
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
//#endregion
|
|
132
|
+
export { RenderError, StaticRuleSetUnknownError, block, buildToDirectory, compile, compileProxyNodes, compileStrategyGroups, defineConfig, direct, explain, group, match, mihomo, policy, proxy, reject, render, renderProxyNodes, route, rule, ruleSet, secret, selectNodes, sequence, singbox, slot, strategy, surge, targetCatalog, use };
|
package/package.json
CHANGED