proxylang 0.1.2 → 0.1.3
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 +4 -0
- package/dist/cli.js +32 -3
- package/dist/{host-BvBQxdmA.js → host-CB08cTs0.js} +20 -6
- package/dist/index.d.ts +227 -19
- package/dist/index.js +459 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -107,6 +107,8 @@ const routing = sequence(
|
|
|
107
107
|
|
|
108
108
|
`slot("proxy")` 让模板不依赖具体节点名称。换一台设备时,可以把同一个 `work` 模板绑定到别的出口;规则正文不用复制。`sequence` 保留原始顺序,不排序、不去重,最终未匹配的流量交给程序的 `fallback`。
|
|
109
109
|
|
|
110
|
+
`slot` 是普通 TypeScript 函数,表示模板的出口参数;`route` 引用具体节点或组。编辑器会检查字面量槽位名称、缺失或多余的绑定,并沿嵌套块与模板保留提示。`defineConfig` 也会检查目标与案例引用的程序名称。动态输入仍由 `check` 验证。
|
|
111
|
+
|
|
110
112
|
### 2. 一个出口,显式选择平台策略
|
|
111
113
|
|
|
112
114
|
规则引用 `adaptive`,节点成员与出口名称可以共用,具体选路算法由每个平台独立声明。
|
|
@@ -186,6 +188,8 @@ PROXY_PASSWORD=example-only npx proxylang build proxy.config.ts --out out
|
|
|
186
188
|
|
|
187
189
|
`explain` 展示条件匹配与逻辑出口,不模拟节点测速或网络连通性。`build` 生成原生配置,整批成功后更新 `out/active.json`,其中列出各目标文件路径;一个目标失败不会替换上一批结果。
|
|
188
190
|
|
|
191
|
+
配置错误提供字段路径和约束提示,例如端口越界会定位到对应规则的条件字段。加载失败会说明是模块缺失、权限不足、语法错误还是执行失败;诊断不会回显原始异常或配置中的秘密。
|
|
192
|
+
|
|
189
193
|
默认输出是包含节点、策略组和规则的 **fragment**,需要与客户端的入口、DNS 等配置组合。可选 `standalone` 提供本机显式代理配置;生成文件不等于部署或系统接管。
|
|
190
194
|
|
|
191
195
|
## 组合规则集与原生能力
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { R as requestSchema, a as explain, i as compile, l as targetCatalog, p as StaticRuleSetUnknownError, t as buildToDirectory } from "./host-
|
|
2
|
+
import { R as requestSchema, a as explain, i as compile, l as targetCatalog, p as StaticRuleSetUnknownError, t as buildToDirectory } from "./host-CB08cTs0.js";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
5
|
import { tsImport } from "tsx/esm/api";
|
|
@@ -12,6 +12,35 @@ const failure = (code) => {
|
|
|
12
12
|
});
|
|
13
13
|
return 1;
|
|
14
14
|
};
|
|
15
|
+
function loadFailure(cause) {
|
|
16
|
+
let code;
|
|
17
|
+
let name;
|
|
18
|
+
try {
|
|
19
|
+
if (cause && typeof cause === "object") {
|
|
20
|
+
code = Object.getOwnPropertyDescriptor(cause, "code")?.value;
|
|
21
|
+
name = Object.getOwnPropertyDescriptor(cause, "name")?.value;
|
|
22
|
+
if (cause instanceof SyntaxError) name = "SyntaxError";
|
|
23
|
+
}
|
|
24
|
+
} catch {}
|
|
25
|
+
print({
|
|
26
|
+
ok: false,
|
|
27
|
+
code: "CONFIG_LOAD_FAILED",
|
|
28
|
+
...code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || code === "ENOENT" ? {
|
|
29
|
+
reason: "MODULE_NOT_FOUND",
|
|
30
|
+
hint: "检查配置文件和 import 路径,并安装所需依赖"
|
|
31
|
+
} : code === "EACCES" || code === "EPERM" ? {
|
|
32
|
+
reason: "ACCESS_DENIED",
|
|
33
|
+
hint: "检查配置及导入文件的读取权限"
|
|
34
|
+
} : name === "TransformError" || name === "SyntaxError" ? {
|
|
35
|
+
reason: "INVALID_SYNTAX",
|
|
36
|
+
hint: "使用 TypeScript 检查配置与导入文件的语法"
|
|
37
|
+
} : {
|
|
38
|
+
reason: "EXECUTION_FAILED",
|
|
39
|
+
hint: "检查默认导出、导入依赖和配置顶层执行逻辑"
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
return 1;
|
|
43
|
+
}
|
|
15
44
|
async function main(args) {
|
|
16
45
|
const [command, file, ...rest] = args;
|
|
17
46
|
if (command === "targets" && args.length === 1) {
|
|
@@ -48,8 +77,8 @@ async function main(args) {
|
|
|
48
77
|
try {
|
|
49
78
|
const loaded = await tsImport(pathToFileURL(resolve(file)).href, import.meta.url);
|
|
50
79
|
config = loaded.default?.__esModule === true ? loaded.default.default : loaded.default;
|
|
51
|
-
} catch {
|
|
52
|
-
return
|
|
80
|
+
} catch (cause) {
|
|
81
|
+
return loadFailure(cause);
|
|
53
82
|
}
|
|
54
83
|
const result = compile(config);
|
|
55
84
|
if (!result.ok) {
|
|
@@ -38,7 +38,7 @@ const remoteBase = {
|
|
|
38
38
|
})
|
|
39
39
|
};
|
|
40
40
|
const updateInterval = z.number().int().min(60).max(2147483647);
|
|
41
|
-
const nativeRuleSetSchema = z.
|
|
41
|
+
const nativeRuleSetSchema = z.discriminatedUnion("engine", [
|
|
42
42
|
z.strictObject({
|
|
43
43
|
...remoteBase,
|
|
44
44
|
engine: z.literal("surge"),
|
|
@@ -63,7 +63,7 @@ const nativeRuleSetSchema = z.union([
|
|
|
63
63
|
intervalSeconds: updateInterval
|
|
64
64
|
})
|
|
65
65
|
]);
|
|
66
|
-
const matchSchema = z.lazy(() => z.
|
|
66
|
+
const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
|
|
67
67
|
nativeRuleSetSchema,
|
|
68
68
|
z.strictObject({
|
|
69
69
|
type: z.literal("ruleSet"),
|
|
@@ -97,7 +97,7 @@ const matchSchema = z.lazy(() => z.union([
|
|
|
97
97
|
condition: matchSchema
|
|
98
98
|
})
|
|
99
99
|
]));
|
|
100
|
-
const actionSchema = z.
|
|
100
|
+
const actionSchema = z.discriminatedUnion("type", [z.strictObject({ type: z.enum(["direct", "reject"]) }), z.strictObject({
|
|
101
101
|
type: z.literal("route"),
|
|
102
102
|
to: idSchema
|
|
103
103
|
})]);
|
|
@@ -105,7 +105,7 @@ const slotSchema = z.strictObject({
|
|
|
105
105
|
type: z.literal("slot"),
|
|
106
106
|
name: idSchema
|
|
107
107
|
});
|
|
108
|
-
const ruleAction = z.
|
|
108
|
+
const ruleAction = z.discriminatedUnion("type", [actionSchema, slotSchema]);
|
|
109
109
|
const unique = (items) => new Set(items).size === items.length;
|
|
110
110
|
const policySchema = z.lazy(() => z.strictObject({
|
|
111
111
|
type: z.literal("policy"),
|
|
@@ -113,7 +113,7 @@ const policySchema = z.lazy(() => z.strictObject({
|
|
|
113
113
|
exits: z.array(idSchema).refine(unique),
|
|
114
114
|
rules: z.array(entrySchema).min(1)
|
|
115
115
|
}));
|
|
116
|
-
const entrySchema = z.lazy(() => z.
|
|
116
|
+
const entrySchema = z.lazy(() => z.discriminatedUnion("type", [
|
|
117
117
|
z.strictObject({
|
|
118
118
|
type: z.literal("rule"),
|
|
119
119
|
id: idSchema,
|
|
@@ -326,6 +326,19 @@ const configSchema = z.strictObject({
|
|
|
326
326
|
})).optional(),
|
|
327
327
|
warningsAsErrors: z.boolean().optional()
|
|
328
328
|
});
|
|
329
|
+
/** Only schema-owned constraints are rendered; Zod messages can contain input values. */
|
|
330
|
+
function schemaIssueMessage(issue) {
|
|
331
|
+
switch (issue.code) {
|
|
332
|
+
case "invalid_type": return `字段类型错误或缺失;需要 ${issue.expected}`;
|
|
333
|
+
case "too_small": return `字段低于下限;${issue.origin} 的最小值或长度为 ${issue.minimum}`;
|
|
334
|
+
case "too_big": return `字段超过上限;${issue.origin} 的最大值或长度为 ${issue.maximum}`;
|
|
335
|
+
case "invalid_value": return `字段必须使用声明的枚举值:${issue.values.map(String).join("、")}`;
|
|
336
|
+
case "invalid_format": return "字段格式不符合约束;检查域名、标识符或路径格式";
|
|
337
|
+
case "unrecognized_keys": return "对象包含当前声明不支持的字段;请删除额外字段";
|
|
338
|
+
case "invalid_union": return "声明不符合任何支持的分支;检查 type、engine 及对应必填字段";
|
|
339
|
+
default: return "字段不满足语义约束;检查地址、范围顺序、重复项或相关字段组合";
|
|
340
|
+
}
|
|
341
|
+
}
|
|
329
342
|
/** Reject cycles, executable values and excessive expansion before recursive schema parsing. */
|
|
330
343
|
function assertData(value) {
|
|
331
344
|
const ancestors = /* @__PURE__ */ new Set();
|
|
@@ -429,6 +442,7 @@ const route = (to) => ({
|
|
|
429
442
|
type: "route",
|
|
430
443
|
to
|
|
431
444
|
});
|
|
445
|
+
/** An exit parameter declared by policy.exits and resolved by use.bindings. */
|
|
432
446
|
const slot = (name) => ({
|
|
433
447
|
type: "slot",
|
|
434
448
|
name
|
|
@@ -1386,7 +1400,7 @@ function compile(input) {
|
|
|
1386
1400
|
}
|
|
1387
1401
|
const parsed = configSchema.safeParse(input);
|
|
1388
1402
|
if (!parsed.success) {
|
|
1389
|
-
for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$",
|
|
1403
|
+
for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
|
|
1390
1404
|
return deepFreeze({
|
|
1391
1405
|
ok: false,
|
|
1392
1406
|
diagnostics,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
1
2
|
//#region src/types.d.ts
|
|
2
3
|
export type Network = "tcp" | "udp";
|
|
3
4
|
export type NamedRuleSet = {
|
|
@@ -46,20 +47,20 @@ export type Action = {
|
|
|
46
47
|
readonly type: "route";
|
|
47
48
|
readonly to: string;
|
|
48
49
|
};
|
|
49
|
-
export type Slot = {
|
|
50
|
+
export type Slot<S extends string = string> = {
|
|
50
51
|
readonly type: "slot";
|
|
51
|
-
readonly name:
|
|
52
|
+
readonly name: S;
|
|
52
53
|
};
|
|
53
|
-
export type Rule = {
|
|
54
|
+
export type Rule<S extends string = string> = {
|
|
54
55
|
readonly type: "rule";
|
|
55
56
|
readonly id: string;
|
|
56
57
|
readonly when: Match;
|
|
57
|
-
readonly then: Action | Slot
|
|
58
|
+
readonly then: Action | Slot<S>;
|
|
58
59
|
};
|
|
59
|
-
export type Block = {
|
|
60
|
+
export type Block<S extends string = string> = {
|
|
60
61
|
readonly type: "block";
|
|
61
62
|
readonly id: string;
|
|
62
|
-
readonly rules: readonly Entry[];
|
|
63
|
+
readonly rules: readonly Entry<S>[];
|
|
63
64
|
readonly when?: Match;
|
|
64
65
|
};
|
|
65
66
|
export type Policy<S extends string = string> = {
|
|
@@ -68,13 +69,13 @@ export type Policy<S extends string = string> = {
|
|
|
68
69
|
readonly exits: readonly S[];
|
|
69
70
|
readonly rules: readonly Entry[];
|
|
70
71
|
};
|
|
71
|
-
export type Use = {
|
|
72
|
+
export type Use<S extends string = string> = {
|
|
72
73
|
readonly type: "use";
|
|
73
74
|
readonly id: string;
|
|
74
75
|
readonly policy: Policy;
|
|
75
|
-
readonly bindings: Readonly<Record<string, Action | Slot
|
|
76
|
+
readonly bindings: Readonly<Record<string, Action | Slot<S>>>;
|
|
76
77
|
};
|
|
77
|
-
export type Entry = Rule | Block | Use
|
|
78
|
+
export type Entry<S extends string = string> = Rule<S> | Block<S> | Use<S>;
|
|
78
79
|
export type Secret = {
|
|
79
80
|
readonly type: "env";
|
|
80
81
|
readonly name: string;
|
|
@@ -312,17 +313,28 @@ export declare const match: {
|
|
|
312
313
|
export declare const direct: () => Action;
|
|
313
314
|
export declare const reject: () => Action;
|
|
314
315
|
export declare const route: (to: string) => Action;
|
|
315
|
-
|
|
316
|
+
/** An exit parameter declared by policy.exits and resolved by use.bindings. */
|
|
317
|
+
export declare const slot: <const S extends string>(name: S) => Slot<S>;
|
|
316
318
|
export declare const secret: (name: string) => Secret;
|
|
317
|
-
export declare const rule: (id: string, when: Match, then: Action | Slot) => Rule
|
|
318
|
-
export declare const block: (id: string, rules: readonly Entry[], when?: Match) => Block
|
|
319
|
-
|
|
320
|
-
export declare const
|
|
319
|
+
export declare const rule: <const S extends string = never>(id: string, when: Match, then: Action | Slot<S>) => Rule<S>;
|
|
320
|
+
export declare const block: <const S extends string = never>(id: string, rules: readonly Entry<S>[], when?: Match) => Block<S>;
|
|
321
|
+
type CheckedEntries<S extends string, R extends readonly Entry[]> = R & (string extends (R[number] extends Entry<infer Used> ? Used : never) ? unknown : readonly Entry<S>[]);
|
|
322
|
+
export declare const policy: <const S extends string, const R extends readonly Entry[] = readonly Entry<S>[]>(definition: Omit<Policy<S>, "type" | "rules"> & {
|
|
323
|
+
readonly rules: CheckedEntries<NoInfer<S>, R>;
|
|
324
|
+
}) => Policy<S>;
|
|
325
|
+
export declare const use: <S extends string, const B extends Record<NoInfer<S>, Action | Slot>>(definition: Policy<S>, options: {
|
|
321
326
|
id: string;
|
|
322
|
-
bindings: Record<
|
|
323
|
-
}) => Use
|
|
324
|
-
export declare const sequence: (...parts: readonly (Entry | readonly Entry[])[]) => Entry[];
|
|
325
|
-
export declare const defineConfig: <T extends Config>(config: T
|
|
327
|
+
bindings: B & Record<Exclude<keyof B, S>, never>;
|
|
328
|
+
}) => Use<Extract<B[keyof B], Slot>["name"]>;
|
|
329
|
+
export declare const sequence: <const S extends string = never>(...parts: readonly (Entry<S> | readonly Entry<S>[])[]) => Entry<S>[];
|
|
330
|
+
export declare const defineConfig: <const T extends Config>(config: T & {
|
|
331
|
+
readonly targets: readonly (Config["targets"][number] & {
|
|
332
|
+
readonly program: string extends NoInfer<T>["targets"][number]["program"] ? string : keyof NoInfer<T>["programs"] & string;
|
|
333
|
+
})[];
|
|
334
|
+
readonly cases?: readonly (NonNullable<Config["cases"]>[number] & {
|
|
335
|
+
readonly program: string extends NonNullable<NoInfer<T>["cases"]>[number]["program"] ? string : keyof NoInfer<T>["programs"] & string;
|
|
336
|
+
})[];
|
|
337
|
+
}) => T;
|
|
326
338
|
/** Filtering is stable: catalogue order determines initial selector order. */
|
|
327
339
|
export declare function selectNodes(nodes: readonly ProxyNode[], query?: {
|
|
328
340
|
regions?: readonly string[];
|
|
@@ -548,4 +560,200 @@ type ProxyNodeArtifact = {
|
|
|
548
560
|
export declare function compileProxyNodes(input: unknown): ProxyNodeCompilation;
|
|
549
561
|
export declare function renderProxyNodes(compilation: ProxyNodeCompilation, resolveSecret: (token: Secret) => string | undefined): ProxyNodeArtifact;
|
|
550
562
|
//#endregion
|
|
551
|
-
|
|
563
|
+
//#region src/surge-profile.d.ts
|
|
564
|
+
declare const policy$1: z.ZodUnion<readonly [z.ZodObject<{
|
|
565
|
+
ref: z.ZodString;
|
|
566
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
567
|
+
builtin: z.ZodEnum<{
|
|
568
|
+
DIRECT: "DIRECT";
|
|
569
|
+
REJECT: "REJECT";
|
|
570
|
+
"REJECT-DROP": "REJECT-DROP";
|
|
571
|
+
"REJECT-NO-DROP": "REJECT-NO-DROP";
|
|
572
|
+
"REJECT-TINYGIF": "REJECT-TINYGIF";
|
|
573
|
+
}>;
|
|
574
|
+
}, z.core.$strict>]>;
|
|
575
|
+
type SurgePolicy = z.infer<typeof policy$1>;
|
|
576
|
+
declare const generalSchema: z.ZodObject<{
|
|
577
|
+
loglevel: z.ZodOptional<z.ZodEnum<{
|
|
578
|
+
info: "info";
|
|
579
|
+
notify: "notify";
|
|
580
|
+
verbose: "verbose";
|
|
581
|
+
warning: "warning";
|
|
582
|
+
}>>;
|
|
583
|
+
"dns-server": z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
584
|
+
"encrypted-dns-server": z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
585
|
+
"show-error-page-for-reject": z.ZodOptional<z.ZodBoolean>;
|
|
586
|
+
"exclude-simple-hostnames": z.ZodOptional<z.ZodBoolean>;
|
|
587
|
+
"internet-test-url": z.ZodOptional<z.ZodString>;
|
|
588
|
+
"skip-proxy": z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodString, z.ZodString]>>>;
|
|
589
|
+
ipv6: z.ZodOptional<z.ZodBoolean>;
|
|
590
|
+
"ipv6-vif": z.ZodOptional<z.ZodEnum<{
|
|
591
|
+
always: "always";
|
|
592
|
+
auto: "auto";
|
|
593
|
+
disabled: "disabled";
|
|
594
|
+
}>>;
|
|
595
|
+
"bypass-system": z.ZodOptional<z.ZodBoolean>;
|
|
596
|
+
replica: z.ZodOptional<z.ZodBoolean>;
|
|
597
|
+
"tls-provider": z.ZodOptional<z.ZodEnum<{
|
|
598
|
+
default: "default";
|
|
599
|
+
openssl: "openssl";
|
|
600
|
+
}>>;
|
|
601
|
+
"bypass-tun": z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
602
|
+
"always-real-ip": z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
603
|
+
"http-api": z.ZodOptional<z.ZodObject<{
|
|
604
|
+
password: z.ZodObject<{
|
|
605
|
+
type: z.ZodLiteral<"env">;
|
|
606
|
+
name: z.ZodString;
|
|
607
|
+
}, z.core.$strict>;
|
|
608
|
+
listen: z.ZodString;
|
|
609
|
+
}, z.core.$strict>>;
|
|
610
|
+
"http-api-web-dashboard": z.ZodOptional<z.ZodBoolean>;
|
|
611
|
+
"external-controller-access": z.ZodOptional<z.ZodObject<{
|
|
612
|
+
password: z.ZodObject<{
|
|
613
|
+
type: z.ZodLiteral<"env">;
|
|
614
|
+
name: z.ZodString;
|
|
615
|
+
}, z.core.$strict>;
|
|
616
|
+
listen: z.ZodString;
|
|
617
|
+
}, z.core.$strict>>;
|
|
618
|
+
"hijack-dns": z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
619
|
+
"http-listen": z.ZodOptional<z.ZodString>;
|
|
620
|
+
"socks5-listen": z.ZodOptional<z.ZodString>;
|
|
621
|
+
"proxy-restricted-to-lan": z.ZodOptional<z.ZodBoolean>;
|
|
622
|
+
}, z.core.$strict>;
|
|
623
|
+
type SurgeGeneral = z.infer<typeof generalSchema>;
|
|
624
|
+
declare const hostSchema: z.ZodObject<{
|
|
625
|
+
pattern: z.ZodString;
|
|
626
|
+
address: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodString]>>;
|
|
627
|
+
server: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodString]>>;
|
|
628
|
+
}, z.core.$strict>;
|
|
629
|
+
type SurgeHost = z.infer<typeof hostSchema>;
|
|
630
|
+
declare const tunnelSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
631
|
+
type: z.ZodLiteral<"tailscale">;
|
|
632
|
+
id: z.ZodString;
|
|
633
|
+
sectionName: z.ZodString;
|
|
634
|
+
authKey: z.ZodObject<{
|
|
635
|
+
type: z.ZodLiteral<"env">;
|
|
636
|
+
name: z.ZodString;
|
|
637
|
+
}, z.core.$strict>;
|
|
638
|
+
hostname: z.ZodString;
|
|
639
|
+
dnsServer: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
640
|
+
autoAddMagicDnsRule: z.ZodOptional<z.ZodBoolean>;
|
|
641
|
+
idleKeepalive: z.ZodOptional<z.ZodNumber>;
|
|
642
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
643
|
+
type: z.ZodLiteral<"wireguard">;
|
|
644
|
+
id: z.ZodString;
|
|
645
|
+
sectionName: z.ZodString;
|
|
646
|
+
privateKey: z.ZodObject<{
|
|
647
|
+
type: z.ZodLiteral<"env">;
|
|
648
|
+
name: z.ZodString;
|
|
649
|
+
}, z.core.$strict>;
|
|
650
|
+
selfIp: z.ZodString;
|
|
651
|
+
dnsServer: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
652
|
+
mtu: z.ZodOptional<z.ZodNumber>;
|
|
653
|
+
peers: z.ZodArray<z.ZodObject<{
|
|
654
|
+
publicKey: z.ZodString;
|
|
655
|
+
endpoint: z.ZodString;
|
|
656
|
+
allowedIps: z.ZodArray<z.ZodString>;
|
|
657
|
+
presharedKey: z.ZodOptional<z.ZodObject<{
|
|
658
|
+
type: z.ZodLiteral<"env">;
|
|
659
|
+
name: z.ZodString;
|
|
660
|
+
}, z.core.$strict>>;
|
|
661
|
+
persistentKeepalive: z.ZodOptional<z.ZodNumber>;
|
|
662
|
+
}, z.core.$strict>>;
|
|
663
|
+
}, z.core.$strict>], "type">;
|
|
664
|
+
type SurgeTunnel = z.infer<typeof tunnelSchema>;
|
|
665
|
+
declare const groupSchema: z.ZodObject<{
|
|
666
|
+
id: z.ZodString;
|
|
667
|
+
type: z.ZodEnum<{
|
|
668
|
+
select: "select";
|
|
669
|
+
smart: "smart";
|
|
670
|
+
}>;
|
|
671
|
+
members: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
|
|
672
|
+
ref: z.ZodString;
|
|
673
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
674
|
+
builtin: z.ZodEnum<{
|
|
675
|
+
DIRECT: "DIRECT";
|
|
676
|
+
REJECT: "REJECT";
|
|
677
|
+
"REJECT-DROP": "REJECT-DROP";
|
|
678
|
+
"REJECT-NO-DROP": "REJECT-NO-DROP";
|
|
679
|
+
"REJECT-TINYGIF": "REJECT-TINYGIF";
|
|
680
|
+
}>;
|
|
681
|
+
}, z.core.$strict>]>>;
|
|
682
|
+
url: z.ZodOptional<z.ZodString>;
|
|
683
|
+
intervalSeconds: z.ZodOptional<z.ZodNumber>;
|
|
684
|
+
timeoutSeconds: z.ZodOptional<z.ZodNumber>;
|
|
685
|
+
}, z.core.$strict>;
|
|
686
|
+
type SurgeGroup = z.infer<typeof groupSchema>;
|
|
687
|
+
type ConditionOptions = {
|
|
688
|
+
readonly noResolve?: boolean;
|
|
689
|
+
readonly extendedMatching?: boolean;
|
|
690
|
+
};
|
|
691
|
+
type SurgeCondition = ConditionOptions & ({
|
|
692
|
+
readonly type: "domain" | "domainSuffix" | "ipCidr" | "ipCidr6" | "sourceIp" | "processName" | "macAddress";
|
|
693
|
+
readonly value: string;
|
|
694
|
+
} | {
|
|
695
|
+
readonly type: "port" | "sourcePort";
|
|
696
|
+
readonly from: number;
|
|
697
|
+
readonly to?: number;
|
|
698
|
+
} | {
|
|
699
|
+
readonly type: "network";
|
|
700
|
+
readonly value: "tcp" | "udp";
|
|
701
|
+
} | {
|
|
702
|
+
readonly type: "all" | "any";
|
|
703
|
+
readonly conditions: readonly SurgeCondition[];
|
|
704
|
+
} | {
|
|
705
|
+
readonly type: "not";
|
|
706
|
+
readonly condition: SurgeCondition;
|
|
707
|
+
} | {
|
|
708
|
+
readonly type: "ruleSet";
|
|
709
|
+
readonly format: "rule-set" | "domain-set";
|
|
710
|
+
readonly url?: string;
|
|
711
|
+
readonly builtin?: "LAN" | "SYSTEM";
|
|
712
|
+
});
|
|
713
|
+
type SurgeRule = {
|
|
714
|
+
readonly when: SurgeCondition;
|
|
715
|
+
readonly then: SurgePolicy;
|
|
716
|
+
};
|
|
717
|
+
declare const managedSchema: z.ZodObject<{
|
|
718
|
+
url: z.ZodString;
|
|
719
|
+
query: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
720
|
+
type: z.ZodLiteral<"env">;
|
|
721
|
+
name: z.ZodString;
|
|
722
|
+
}, z.core.$strict>]>>>;
|
|
723
|
+
intervalSeconds: z.ZodNumber;
|
|
724
|
+
strict: z.ZodBoolean;
|
|
725
|
+
}, z.core.$strict>;
|
|
726
|
+
type SurgeProfileInput = {
|
|
727
|
+
readonly target: {
|
|
728
|
+
readonly engine: "surge";
|
|
729
|
+
readonly platform: "macos" | "ios";
|
|
730
|
+
readonly version: string;
|
|
731
|
+
};
|
|
732
|
+
readonly managed?: z.infer<typeof managedSchema>;
|
|
733
|
+
readonly general?: SurgeGeneral;
|
|
734
|
+
readonly hosts?: readonly SurgeHost[];
|
|
735
|
+
readonly nodes: readonly ProxyNode[];
|
|
736
|
+
readonly tunnels?: readonly SurgeTunnel[];
|
|
737
|
+
readonly groups: readonly SurgeGroup[];
|
|
738
|
+
readonly rules: readonly SurgeRule[];
|
|
739
|
+
readonly fallback: SurgePolicy;
|
|
740
|
+
readonly names?: Readonly<Record<string, string>>;
|
|
741
|
+
};
|
|
742
|
+
type SurgeProfileCompilation = {
|
|
743
|
+
readonly ok: boolean;
|
|
744
|
+
readonly artifactKind: "surge-profile";
|
|
745
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
746
|
+
readonly bindings: readonly {
|
|
747
|
+
readonly id: string;
|
|
748
|
+
readonly nativeName: string;
|
|
749
|
+
}[];
|
|
750
|
+
};
|
|
751
|
+
type SurgeProfileArtifact = {
|
|
752
|
+
readonly artifactKind: "surge-profile";
|
|
753
|
+
readonly content: string;
|
|
754
|
+
};
|
|
755
|
+
export declare function compileSurgeProfile(input: unknown): SurgeProfileCompilation;
|
|
756
|
+
export declare function renderSurgeProfile(compilation: SurgeProfileCompilation, resolveSecret: (token: Secret) => string | undefined): SurgeProfileArtifact;
|
|
757
|
+
export declare function renderSurgeProfiles(compilations: readonly SurgeProfileCompilation[], resolveSecret: (token: Secret) => string | undefined): readonly SurgeProfileArtifact[];
|
|
758
|
+
//#endregion
|
|
759
|
+
export type { Artifact, BuildResult, CaseResult, Compilation, ProxyBuilder, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, StrategyGroupCompilation, StrategyGroupInput, SurgeCondition, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileInput, SurgeRule, SurgeTunnel, TargetPlan };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
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-
|
|
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-CB08cTs0.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
+
import { isIP } from "node:net";
|
|
4
|
+
import ipaddr from "ipaddr.js";
|
|
3
5
|
//#region src/proxy-fragments.ts
|
|
4
|
-
const inputSchema = z.strictObject({
|
|
6
|
+
const inputSchema$1 = z.strictObject({
|
|
5
7
|
target: z.strictObject({
|
|
6
8
|
engine: z.string(),
|
|
7
9
|
platform: z.string(),
|
|
@@ -15,7 +17,7 @@ const inputSchema = z.strictObject({
|
|
|
15
17
|
kind: z.enum(["proxy", "group"])
|
|
16
18
|
})).max(1e3).optional()
|
|
17
19
|
});
|
|
18
|
-
const plans = /* @__PURE__ */ new WeakMap();
|
|
20
|
+
const plans$1 = /* @__PURE__ */ new WeakMap();
|
|
19
21
|
function compileProxyNodes(input) {
|
|
20
22
|
const diagnostics = [];
|
|
21
23
|
const error = (code, path, message) => diagnostics.push({
|
|
@@ -37,7 +39,7 @@ function compileProxyNodes(input) {
|
|
|
37
39
|
error("INVALID_INPUT_GRAPH", "$", "输入必须是有限纯数据,不接受 builder 或访问器");
|
|
38
40
|
return failure();
|
|
39
41
|
}
|
|
40
|
-
const parsed = inputSchema.safeParse(input);
|
|
42
|
+
const parsed = inputSchema$1.safeParse(input);
|
|
41
43
|
if (!parsed.success) {
|
|
42
44
|
error("INVALID_SCHEMA", "$", "节点、名字或外部声明不符合严格 schema");
|
|
43
45
|
return failure();
|
|
@@ -108,14 +110,14 @@ function compileProxyNodes(input) {
|
|
|
108
110
|
bindings,
|
|
109
111
|
requirements
|
|
110
112
|
});
|
|
111
|
-
plans.set(compilation, deepFreeze({
|
|
113
|
+
plans$1.set(compilation, deepFreeze({
|
|
112
114
|
nodes,
|
|
113
115
|
names: Object.fromEntries(symbols.map((s) => [s.id, s.nativeName]))
|
|
114
116
|
}));
|
|
115
117
|
return compilation;
|
|
116
118
|
}
|
|
117
119
|
function renderProxyNodes(compilation, resolveSecret) {
|
|
118
|
-
const plan = plans.get(compilation);
|
|
120
|
+
const plan = plans$1.get(compilation);
|
|
119
121
|
if (!plan) throw new RenderError("COMPILATION_FAILED");
|
|
120
122
|
const secret = secretReader(resolveSecret);
|
|
121
123
|
const entries = plan.nodes.map((node) => ({
|
|
@@ -129,4 +131,454 @@ function renderProxyNodes(compilation, resolveSecret) {
|
|
|
129
131
|
});
|
|
130
132
|
}
|
|
131
133
|
//#endregion
|
|
132
|
-
|
|
134
|
+
//#region src/surge-profile.ts
|
|
135
|
+
const builtin = z.enum([
|
|
136
|
+
"DIRECT",
|
|
137
|
+
"REJECT",
|
|
138
|
+
"REJECT-DROP",
|
|
139
|
+
"REJECT-NO-DROP",
|
|
140
|
+
"REJECT-TINYGIF"
|
|
141
|
+
]);
|
|
142
|
+
const policy$1 = z.union([z.strictObject({ ref: idSchema }), z.strictObject({ builtin })]);
|
|
143
|
+
const token = z.strictObject({
|
|
144
|
+
type: z.literal("env"),
|
|
145
|
+
name: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)
|
|
146
|
+
});
|
|
147
|
+
const safe = z.string().min(1).max(4096).refine((v) => v.trim() === v && !/[\p{C}\p{Zl}\p{Zp},=()#;"'\\]/u.test(v));
|
|
148
|
+
const domain = z.string().max(253).regex(/^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/);
|
|
149
|
+
const hostPattern = safe.refine((v) => /^[a-zA-Z0-9*?._-]+$/.test(v));
|
|
150
|
+
const ip = safe.refine((v) => isIP(v) !== 0 && !v.includes("%"));
|
|
151
|
+
const cidr = (version) => safe.refine((v) => {
|
|
152
|
+
try {
|
|
153
|
+
const [address] = ipaddr.parseCIDR(v);
|
|
154
|
+
return (!version || (address.kind() === "ipv4" ? 4 : 6) === version) && !v.includes("%");
|
|
155
|
+
} catch {
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
const port = z.number().int().min(1).max(65535);
|
|
160
|
+
function addressPort(value, allowHost, portRequired) {
|
|
161
|
+
if (!portRequired && isIP(value)) return true;
|
|
162
|
+
const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(value);
|
|
163
|
+
if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) return false;
|
|
164
|
+
const host = match[1];
|
|
165
|
+
return host.startsWith("[") ? isIP(host.slice(1, -1)) === 6 : isIP(host) === 4 || allowHost && domain.safeParse(host).success;
|
|
166
|
+
}
|
|
167
|
+
const listener = safe.refine((v) => addressPort(v, false, false));
|
|
168
|
+
const endpoint = safe.refine((v) => addressPort(v, true, true));
|
|
169
|
+
const dns = safe.refine((v) => v === "system" || addressPort(v, false, false));
|
|
170
|
+
const url = z.string().min(1).max(4096).refine((v) => {
|
|
171
|
+
try {
|
|
172
|
+
const u = new URL(v);
|
|
173
|
+
return /^https?:\/\//.test(v) && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
|
|
174
|
+
} catch {
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
const encryptedDns = z.string().max(4096).refine((v) => {
|
|
179
|
+
try {
|
|
180
|
+
const u = new URL(v);
|
|
181
|
+
return [
|
|
182
|
+
"https:",
|
|
183
|
+
"h3:",
|
|
184
|
+
"quic:",
|
|
185
|
+
"tls:",
|
|
186
|
+
"tcp:"
|
|
187
|
+
].includes(u.protocol) && !!u.hostname && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
|
|
188
|
+
} catch {
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
const list = (item) => z.array(item).min(1).max(1e3);
|
|
193
|
+
const control = z.strictObject({
|
|
194
|
+
password: token,
|
|
195
|
+
listen: safe.refine((v) => addressPort(v, false, true))
|
|
196
|
+
});
|
|
197
|
+
const generalSchema = z.strictObject({
|
|
198
|
+
loglevel: z.enum([
|
|
199
|
+
"verbose",
|
|
200
|
+
"info",
|
|
201
|
+
"notify",
|
|
202
|
+
"warning"
|
|
203
|
+
]).optional(),
|
|
204
|
+
"dns-server": list(dns).optional(),
|
|
205
|
+
"encrypted-dns-server": list(encryptedDns).optional(),
|
|
206
|
+
"show-error-page-for-reject": z.boolean().optional(),
|
|
207
|
+
"exclude-simple-hostnames": z.boolean().optional(),
|
|
208
|
+
"internet-test-url": url.optional(),
|
|
209
|
+
"skip-proxy": list(z.union([
|
|
210
|
+
hostPattern,
|
|
211
|
+
ip,
|
|
212
|
+
cidr()
|
|
213
|
+
])).optional(),
|
|
214
|
+
ipv6: z.boolean().optional(),
|
|
215
|
+
"ipv6-vif": z.enum([
|
|
216
|
+
"auto",
|
|
217
|
+
"always",
|
|
218
|
+
"disabled"
|
|
219
|
+
]).optional(),
|
|
220
|
+
"bypass-system": z.boolean().optional(),
|
|
221
|
+
replica: z.boolean().optional(),
|
|
222
|
+
"tls-provider": z.enum(["default", "openssl"]).optional(),
|
|
223
|
+
"bypass-tun": list(cidr()).optional(),
|
|
224
|
+
"always-real-ip": list(hostPattern).optional(),
|
|
225
|
+
"http-api": control.optional(),
|
|
226
|
+
"http-api-web-dashboard": z.boolean().optional(),
|
|
227
|
+
"external-controller-access": control.optional(),
|
|
228
|
+
"hijack-dns": list(safe.refine((v) => /^\*(?::\d+)?$/.test(v) ? !v.includes(":") || Number(v.slice(2)) > 0 && Number(v.slice(2)) <= 65535 : addressPort(v, false, false))).optional(),
|
|
229
|
+
"http-listen": listener.optional(),
|
|
230
|
+
"socks5-listen": listener.optional(),
|
|
231
|
+
"proxy-restricted-to-lan": z.boolean().optional()
|
|
232
|
+
});
|
|
233
|
+
const hostSchema = z.strictObject({
|
|
234
|
+
pattern: hostPattern,
|
|
235
|
+
address: z.union([ip, domain]).optional(),
|
|
236
|
+
server: z.union([dns, encryptedDns]).optional()
|
|
237
|
+
}).refine((v) => v.address !== void 0 || v.server !== void 0);
|
|
238
|
+
const key = z.string().regex(/^[A-Za-z0-9+/]{43}=$/).refine((v) => Buffer.from(v, "base64").length === 32 && Buffer.from(v, "base64").toString("base64") === v);
|
|
239
|
+
const sectionName = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/);
|
|
240
|
+
const tunnelSchema = z.discriminatedUnion("type", [z.strictObject({
|
|
241
|
+
type: z.literal("tailscale"),
|
|
242
|
+
id: idSchema,
|
|
243
|
+
sectionName,
|
|
244
|
+
authKey: token,
|
|
245
|
+
hostname: domain,
|
|
246
|
+
dnsServer: list(dns).optional(),
|
|
247
|
+
autoAddMagicDnsRule: z.boolean().optional(),
|
|
248
|
+
idleKeepalive: z.number().int().min(-1).max(2147483647).optional()
|
|
249
|
+
}), z.strictObject({
|
|
250
|
+
type: z.literal("wireguard"),
|
|
251
|
+
id: idSchema,
|
|
252
|
+
sectionName,
|
|
253
|
+
privateKey: token,
|
|
254
|
+
selfIp: ip.refine((v) => isIP(v) === 4),
|
|
255
|
+
dnsServer: list(dns).optional(),
|
|
256
|
+
mtu: z.number().int().min(576).max(9e3).optional(),
|
|
257
|
+
peers: list(z.strictObject({
|
|
258
|
+
publicKey: key,
|
|
259
|
+
endpoint,
|
|
260
|
+
allowedIps: list(cidr()),
|
|
261
|
+
presharedKey: token.optional(),
|
|
262
|
+
persistentKeepalive: z.number().int().min(0).max(65535).optional()
|
|
263
|
+
}))
|
|
264
|
+
})]);
|
|
265
|
+
const groupSchema = z.strictObject({
|
|
266
|
+
id: idSchema,
|
|
267
|
+
type: z.enum(["select", "smart"]),
|
|
268
|
+
members: list(policy$1),
|
|
269
|
+
url: url.optional(),
|
|
270
|
+
intervalSeconds: z.number().int().positive().max(2147483647).optional(),
|
|
271
|
+
timeoutSeconds: z.number().int().positive().max(3600).optional()
|
|
272
|
+
});
|
|
273
|
+
const options = {
|
|
274
|
+
noResolve: z.boolean().optional(),
|
|
275
|
+
extendedMatching: z.boolean().optional()
|
|
276
|
+
};
|
|
277
|
+
const atom = (type, value) => z.strictObject({
|
|
278
|
+
type: z.literal(type),
|
|
279
|
+
value,
|
|
280
|
+
...options
|
|
281
|
+
});
|
|
282
|
+
const conditionSchema = z.lazy(() => z.union([
|
|
283
|
+
atom("domain", domain),
|
|
284
|
+
atom("domainSuffix", domain),
|
|
285
|
+
atom("ipCidr", cidr(4)),
|
|
286
|
+
atom("ipCidr6", cidr(6)),
|
|
287
|
+
atom("sourceIp", z.union([ip, cidr()])),
|
|
288
|
+
atom("processName", safe),
|
|
289
|
+
atom("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
|
|
290
|
+
z.strictObject({
|
|
291
|
+
type: z.enum(["port", "sourcePort"]),
|
|
292
|
+
from: port,
|
|
293
|
+
to: port.optional(),
|
|
294
|
+
...options
|
|
295
|
+
}).refine((v) => v.to === void 0 || v.to >= v.from),
|
|
296
|
+
z.strictObject({
|
|
297
|
+
type: z.literal("network"),
|
|
298
|
+
value: z.enum(["tcp", "udp"]),
|
|
299
|
+
...options
|
|
300
|
+
}),
|
|
301
|
+
z.strictObject({
|
|
302
|
+
type: z.enum(["all", "any"]),
|
|
303
|
+
conditions: z.array(conditionSchema).min(2).max(100),
|
|
304
|
+
...options
|
|
305
|
+
}),
|
|
306
|
+
z.strictObject({
|
|
307
|
+
type: z.literal("not"),
|
|
308
|
+
condition: conditionSchema,
|
|
309
|
+
...options
|
|
310
|
+
}),
|
|
311
|
+
z.strictObject({
|
|
312
|
+
type: z.literal("ruleSet"),
|
|
313
|
+
format: z.enum(["rule-set", "domain-set"]),
|
|
314
|
+
url: url.optional(),
|
|
315
|
+
builtin: z.enum(["LAN", "SYSTEM"]).optional(),
|
|
316
|
+
...options
|
|
317
|
+
}).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
|
|
318
|
+
]));
|
|
319
|
+
const managedSchema = z.strictObject({
|
|
320
|
+
url: url.refine((v) => !new URL(v).search && !v.includes("?")),
|
|
321
|
+
query: z.record(z.string().min(1).max(128).regex(/^[A-Za-z][A-Za-z0-9_-]*$/), z.union([z.string().max(4096), token])).optional(),
|
|
322
|
+
intervalSeconds: z.number().int().min(60).max(2147483647),
|
|
323
|
+
strict: z.boolean()
|
|
324
|
+
});
|
|
325
|
+
const inputSchema = z.strictObject({
|
|
326
|
+
target: z.strictObject({
|
|
327
|
+
engine: z.literal("surge"),
|
|
328
|
+
platform: z.enum(["macos", "ios"]),
|
|
329
|
+
version: z.string()
|
|
330
|
+
}),
|
|
331
|
+
managed: managedSchema.optional(),
|
|
332
|
+
general: generalSchema.optional(),
|
|
333
|
+
hosts: z.array(hostSchema).max(2e3).optional(),
|
|
334
|
+
nodes: z.array(nodeSchema).max(1e3),
|
|
335
|
+
tunnels: z.array(tunnelSchema).max(1e3).optional(),
|
|
336
|
+
groups: z.array(groupSchema).max(1e3),
|
|
337
|
+
rules: z.array(z.strictObject({
|
|
338
|
+
when: conditionSchema,
|
|
339
|
+
then: policy$1
|
|
340
|
+
})).max(1e4),
|
|
341
|
+
fallback: policy$1,
|
|
342
|
+
names: z.record(idSchema, nativeNameSchema).optional()
|
|
343
|
+
});
|
|
344
|
+
const plans = /* @__PURE__ */ new WeakMap();
|
|
345
|
+
function compileSurgeProfile(input) {
|
|
346
|
+
const diagnostics = [];
|
|
347
|
+
const error = (code) => diagnostics.push({
|
|
348
|
+
severity: "error",
|
|
349
|
+
code,
|
|
350
|
+
path: "$",
|
|
351
|
+
message: code
|
|
352
|
+
});
|
|
353
|
+
const failure = () => deepFreeze({
|
|
354
|
+
ok: false,
|
|
355
|
+
artifactKind: "surge-profile",
|
|
356
|
+
diagnostics,
|
|
357
|
+
bindings: []
|
|
358
|
+
});
|
|
359
|
+
try {
|
|
360
|
+
assertData(input);
|
|
361
|
+
} catch {
|
|
362
|
+
error("INVALID_INPUT_GRAPH");
|
|
363
|
+
return failure();
|
|
364
|
+
}
|
|
365
|
+
const parsed = inputSchema.safeParse(input);
|
|
366
|
+
if (!parsed.success) {
|
|
367
|
+
error("INVALID_SCHEMA");
|
|
368
|
+
return failure();
|
|
369
|
+
}
|
|
370
|
+
if (parsed.data.general) {
|
|
371
|
+
const general = parsed.data.general;
|
|
372
|
+
parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
|
|
373
|
+
}
|
|
374
|
+
const p = deepFreeze(parsed.data);
|
|
375
|
+
if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
|
|
376
|
+
const tunnels = p.tunnels ?? [];
|
|
377
|
+
const resources = [
|
|
378
|
+
...p.nodes,
|
|
379
|
+
...tunnels,
|
|
380
|
+
...p.groups
|
|
381
|
+
];
|
|
382
|
+
if (resources.length > 1e3) error("RESOURCE_LIMIT");
|
|
383
|
+
const ids = new Set(resources.map((r) => r.id));
|
|
384
|
+
if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
|
|
385
|
+
if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
|
|
386
|
+
const bindings = resources.map((r) => ({
|
|
387
|
+
id: r.id,
|
|
388
|
+
nativeName: p.names?.[r.id] ?? r.id
|
|
389
|
+
}));
|
|
390
|
+
if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
|
|
391
|
+
if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
|
|
392
|
+
if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
|
|
393
|
+
if (p.target.platform === "ios" && [
|
|
394
|
+
"bypass-system",
|
|
395
|
+
"replica",
|
|
396
|
+
"tls-provider",
|
|
397
|
+
"bypass-tun",
|
|
398
|
+
"external-controller-access"
|
|
399
|
+
].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
|
|
400
|
+
if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
|
|
401
|
+
const checkPolicy = (action) => {
|
|
402
|
+
if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
|
|
403
|
+
};
|
|
404
|
+
const edges = new Map(resources.map((r) => [r.id, []]));
|
|
405
|
+
const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
|
|
406
|
+
for (const node of p.nodes) {
|
|
407
|
+
if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
|
|
408
|
+
validateProxyOptions(node, {
|
|
409
|
+
id: "profile",
|
|
410
|
+
engine: "surge"
|
|
411
|
+
}, diagnostics);
|
|
412
|
+
if (node.via) {
|
|
413
|
+
checkPolicy({ ref: node.via });
|
|
414
|
+
edges.get(node.id).push(node.via);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
for (const group of p.groups) {
|
|
418
|
+
if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
|
|
419
|
+
for (const member of group.members) {
|
|
420
|
+
checkPolicy(member);
|
|
421
|
+
if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
|
|
422
|
+
if ("ref" in member) edges.get(group.id).push(member.ref);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
|
|
426
|
+
const visit = (id) => {
|
|
427
|
+
if (active.has(id)) {
|
|
428
|
+
error("RESOURCE_CYCLE");
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
if (visited.has(id)) return;
|
|
432
|
+
active.add(id);
|
|
433
|
+
for (const next of edges.get(id) ?? []) visit(next);
|
|
434
|
+
active.delete(id);
|
|
435
|
+
visited.add(id);
|
|
436
|
+
};
|
|
437
|
+
if (resources.length <= 1e3) for (const id of ids) visit(id);
|
|
438
|
+
const formats = /* @__PURE__ */ new Map();
|
|
439
|
+
const checkCondition = (c, depth) => {
|
|
440
|
+
if (depth > 10) {
|
|
441
|
+
error("LOGICAL_DEPTH_EXCEEDED");
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (c.noResolve !== void 0 && ![
|
|
445
|
+
"ipCidr",
|
|
446
|
+
"ipCidr6",
|
|
447
|
+
"ruleSet"
|
|
448
|
+
].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
|
|
449
|
+
if (c.extendedMatching !== void 0 && ![
|
|
450
|
+
"domain",
|
|
451
|
+
"domainSuffix",
|
|
452
|
+
"ruleSet"
|
|
453
|
+
].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
|
|
454
|
+
if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
|
|
455
|
+
if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
|
|
456
|
+
if (c.type === "not") checkCondition(c.condition, depth + 1);
|
|
457
|
+
if (c.type === "ruleSet") {
|
|
458
|
+
if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
|
|
459
|
+
if (c.url) {
|
|
460
|
+
if (formats.has(c.url) && formats.get(c.url) !== c.format) error("RULESET_FORMAT_CONFLICT");
|
|
461
|
+
formats.set(c.url, c.format);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
for (const rule of p.rules) {
|
|
466
|
+
checkPolicy(rule.then);
|
|
467
|
+
checkCondition(rule.when, 0);
|
|
468
|
+
}
|
|
469
|
+
checkPolicy(p.fallback);
|
|
470
|
+
if (diagnostics.some((d) => d.severity === "error")) return failure();
|
|
471
|
+
if (formats.size) diagnostics.push({
|
|
472
|
+
severity: "warning",
|
|
473
|
+
code: "EXTERNAL_RULESET_UNVERIFIED",
|
|
474
|
+
path: "rules",
|
|
475
|
+
message: "External rule sets are resolved by the client, not by the compiler."
|
|
476
|
+
});
|
|
477
|
+
const result = deepFreeze({
|
|
478
|
+
ok: true,
|
|
479
|
+
artifactKind: "surge-profile",
|
|
480
|
+
diagnostics,
|
|
481
|
+
bindings
|
|
482
|
+
});
|
|
483
|
+
plans.set(result, p);
|
|
484
|
+
return result;
|
|
485
|
+
}
|
|
486
|
+
function conditionOptions(c) {
|
|
487
|
+
return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
|
|
488
|
+
}
|
|
489
|
+
function conditionText(c) {
|
|
490
|
+
switch (c.type) {
|
|
491
|
+
case "all":
|
|
492
|
+
case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
|
|
493
|
+
case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
|
|
494
|
+
case "port":
|
|
495
|
+
case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
|
|
496
|
+
case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
|
|
497
|
+
case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
|
|
498
|
+
default: return `${{
|
|
499
|
+
domain: "DOMAIN",
|
|
500
|
+
domainSuffix: "DOMAIN-SUFFIX",
|
|
501
|
+
ipCidr: "IP-CIDR",
|
|
502
|
+
ipCidr6: "IP-CIDR6",
|
|
503
|
+
sourceIp: "SRC-IP",
|
|
504
|
+
processName: "PROCESS-NAME",
|
|
505
|
+
macAddress: "MAC-ADDRESS"
|
|
506
|
+
}[c.type]},${c.value}`;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
function renderProfile(compilation, read) {
|
|
510
|
+
const p = plans.get(compilation);
|
|
511
|
+
if (!p) throw new RenderError("COMPILATION_FAILED");
|
|
512
|
+
const name = (id) => p.names?.[id] ?? id;
|
|
513
|
+
const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
|
|
514
|
+
const credential = (token, kind) => {
|
|
515
|
+
const value = read(token);
|
|
516
|
+
if (!(kind === "key" ? key.safeParse(value).success : kind === "control" ? /^[A-Za-z0-9_.+%-]+$/.test(value) : /^[A-Za-z0-9_-]+$/.test(value))) throw new RenderError("SURGE_VALUE_UNREPRESENTABLE");
|
|
517
|
+
return value;
|
|
518
|
+
};
|
|
519
|
+
const lines = [];
|
|
520
|
+
if (p.managed) {
|
|
521
|
+
const address = new URL(p.managed.url);
|
|
522
|
+
for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
|
|
523
|
+
lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
|
|
524
|
+
}
|
|
525
|
+
lines.push("[General]");
|
|
526
|
+
for (const [k, v] of Object.entries(p.general ?? {})) {
|
|
527
|
+
const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
|
|
528
|
+
lines.push(`${k} = ${value}`);
|
|
529
|
+
}
|
|
530
|
+
lines.push("", "[Host]");
|
|
531
|
+
for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
|
|
532
|
+
lines.push("", "[Proxy]");
|
|
533
|
+
for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
|
|
534
|
+
for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
|
|
535
|
+
for (const t of p.tunnels ?? []) {
|
|
536
|
+
lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
|
|
537
|
+
if (t.type === "tailscale") {
|
|
538
|
+
lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
|
|
539
|
+
if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
|
|
540
|
+
if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
|
|
541
|
+
if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
|
|
542
|
+
} else {
|
|
543
|
+
lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
|
|
544
|
+
if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
|
|
545
|
+
if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
|
|
546
|
+
for (const peer of t.peers) {
|
|
547
|
+
const values = [`public-key = ${peer.publicKey}`];
|
|
548
|
+
if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
|
|
549
|
+
values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
|
|
550
|
+
if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
|
|
551
|
+
lines.push(`peer = (${values.join(", ")})`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
lines.push("", "[Proxy Group]");
|
|
556
|
+
for (const g of p.groups) lines.push(`${name(g.id)} = ${[
|
|
557
|
+
g.type,
|
|
558
|
+
...g.members.map(action),
|
|
559
|
+
...g.url ? [`url=${g.url}`] : [],
|
|
560
|
+
...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
|
|
561
|
+
...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
|
|
562
|
+
].join(", ")}`);
|
|
563
|
+
lines.push("", "[Rule]");
|
|
564
|
+
for (const r of p.rules) lines.push([
|
|
565
|
+
conditionText(r.when),
|
|
566
|
+
action(r.then),
|
|
567
|
+
...conditionOptions(r.when)
|
|
568
|
+
].join(","));
|
|
569
|
+
lines.push(`FINAL,${action(p.fallback)}`, "");
|
|
570
|
+
return deepFreeze({
|
|
571
|
+
artifactKind: "surge-profile",
|
|
572
|
+
content: lines.join("\n")
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
function renderSurgeProfile(compilation, resolveSecret) {
|
|
576
|
+
return renderProfile(compilation, secretReader(resolveSecret));
|
|
577
|
+
}
|
|
578
|
+
function renderSurgeProfiles(compilations, resolveSecret) {
|
|
579
|
+
if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
|
|
580
|
+
const read = secretReader(resolveSecret);
|
|
581
|
+
return deepFreeze(compilations.map((c) => renderProfile(c, read)));
|
|
582
|
+
}
|
|
583
|
+
//#endregion
|
|
584
|
+
export { RenderError, StaticRuleSetUnknownError, block, buildToDirectory, compile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineConfig, direct, explain, group, match, mihomo, policy, proxy, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, secret, selectNodes, sequence, singbox, slot, strategy, surge, targetCatalog, use };
|
package/package.json
CHANGED