proxylang 0.2.0 → 0.4.0
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 +32 -1
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +34 -12
- package/dist/index.js +10 -2
- package/dist/{profile-build-jJlIs97b.js → profile-build-DYCbePBx.js} +333 -133
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -24,7 +24,7 @@ proxylang 把这些关系直接写进代码:
|
|
|
24
24
|
需要 **Node.js 24(最低 24.11.0)**。安装 npm 包:
|
|
25
25
|
|
|
26
26
|
```sh
|
|
27
|
-
npm install --save-exact proxylang@0.
|
|
27
|
+
npm install --save-exact proxylang@0.3.0
|
|
28
28
|
npx proxylang --help
|
|
29
29
|
```
|
|
30
30
|
|
|
@@ -49,6 +49,37 @@ DEMO_PASSWORD=example-only vp exec node dist/cli.js build examples/clients.ts --
|
|
|
49
49
|
|
|
50
50
|
[四客户端示例](examples/clients.ts)展示完整配置;下面从规则开始,逐步写出自己的版本。
|
|
51
51
|
|
|
52
|
+
## 直接组合设备配置
|
|
53
|
+
|
|
54
|
+
Profile 的 `proxies` 同时容纳普通代理、WireGuard 和 Tailscale。规则、代理组、Host 和 General 均可直接组合嵌套数组;General 按顺序浅合并,后者整键覆盖。
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { defineProfile, defineRoutes, outbound, proxy, secret, surge } from "proxylang";
|
|
58
|
+
|
|
59
|
+
const exit = proxy.trojan({
|
|
60
|
+
id: "edge",
|
|
61
|
+
server: "proxy.example.com",
|
|
62
|
+
port: 443,
|
|
63
|
+
password: secret("PASSWORD"),
|
|
64
|
+
});
|
|
65
|
+
const work = defineRoutes({ when: [surge.match.domainSuffix("github.com")], to: "edge" });
|
|
66
|
+
const local = defineRoutes({
|
|
67
|
+
when: [surge.match.domainSuffix("internal.example")],
|
|
68
|
+
to: outbound.direct,
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
const laptop = defineProfile({
|
|
72
|
+
target: { engine: "surge", platform: "macos", version: "6.10.0" },
|
|
73
|
+
proxies: [exit],
|
|
74
|
+
groups: [],
|
|
75
|
+
routes: [local, work],
|
|
76
|
+
fallback: "edge",
|
|
77
|
+
surge: { general: [{ loglevel: "notify" }], hosts: [] },
|
|
78
|
+
});
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
字符串目的地是当前 Profile 的资源 ID,不是显示名称;缺失引用会阻止构建。平台专属代理仍须满足目标能力。完整语义见[Profile 组合契约](docs/feature/target-compilation/profile-composition.md)。
|
|
82
|
+
|
|
52
83
|
## Usage
|
|
53
84
|
|
|
54
85
|
将下面三个 TypeScript 代码块按顺序保存为项目中的 `proxy.config.ts`。
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { Q as requestSchema, R as compile, U as targetCatalog, i as buildToDirectory, n as profileBuildFailure, q as StaticRuleSetUnknownError, r as runBuild, z as explain } from "./profile-build-
|
|
2
|
+
import { Q as requestSchema, R as compile, U as targetCatalog, i as buildToDirectory, n as profileBuildFailure, q as StaticRuleSetUnknownError, r as runBuild, z as explain } from "./profile-build-DYCbePBx.js";
|
|
3
3
|
import { open } from "node:fs/promises";
|
|
4
4
|
import { resolve } from "node:path";
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
package/dist/index.d.ts
CHANGED
|
@@ -25,7 +25,7 @@ export type NativeRuleSet = {
|
|
|
25
25
|
readonly intervalSeconds: number;
|
|
26
26
|
});
|
|
27
27
|
export type Match = NamedRuleSet | NativeRuleSet | {
|
|
28
|
-
readonly type: "domain" | "domainSuffix" | "ipCidr" | "sourceIp";
|
|
28
|
+
readonly type: "domain" | "domainSuffix" | "ipCidr" | "sourceIp" | "processName";
|
|
29
29
|
readonly value: string;
|
|
30
30
|
} | {
|
|
31
31
|
readonly type: "port" | "sourcePort";
|
|
@@ -225,7 +225,12 @@ export type Group = Exclude<ConcreteGroup, {
|
|
|
225
225
|
readonly type: "surge-smart";
|
|
226
226
|
}> | Strategy;
|
|
227
227
|
export type Engine = "surge" | "sing-box" | "mihomo" | "stash";
|
|
228
|
+
export type DnsRule = {
|
|
229
|
+
readonly pattern: string;
|
|
230
|
+
readonly server: string;
|
|
231
|
+
};
|
|
228
232
|
export type Program = {
|
|
233
|
+
readonly dns?: readonly DnsRule[];
|
|
229
234
|
readonly engine: Engine;
|
|
230
235
|
readonly nodes: readonly ProxyNode[];
|
|
231
236
|
readonly endpoints?: readonly TailscaleEndpoint[];
|
|
@@ -250,6 +255,7 @@ export type Request = {
|
|
|
250
255
|
readonly domain?: string;
|
|
251
256
|
readonly ip?: string;
|
|
252
257
|
readonly sourceIp?: string;
|
|
258
|
+
readonly processName?: string;
|
|
253
259
|
readonly port?: number;
|
|
254
260
|
readonly sourcePort?: number;
|
|
255
261
|
};
|
|
@@ -650,22 +656,27 @@ type ProfileCondition = Exclude<Match | SurgeCondition, {
|
|
|
650
656
|
readonly noResolve?: boolean;
|
|
651
657
|
readonly extendedMatching?: boolean;
|
|
652
658
|
};
|
|
653
|
-
type ProfileDestination = ProxyNode | ProxyGroupDefinition | SurgeTunnel | TailscaleEndpoint | {
|
|
659
|
+
type ProfileDestination = string | ProxyNode | ProxyGroupDefinition | SurgeTunnel | TailscaleEndpoint | {
|
|
654
660
|
readonly builtin: "DIRECT" | "REJECT" | "REJECT-DROP" | "REJECT-NO-DROP" | "REJECT-TINYGIF";
|
|
655
661
|
};
|
|
656
|
-
type
|
|
662
|
+
type Fragments<T> = readonly (T | Fragments<T>)[];
|
|
663
|
+
type ProfileProxy = ProxyNode | SurgeTunnel | TailscaleEndpoint;
|
|
664
|
+
type SurgeConfig = DeepReadonly<Pick<SurgeProfileInput, "managed" | "names">> & {
|
|
665
|
+
readonly general?: DeepReadonly<SurgeGeneral> | Fragments<DeepReadonly<SurgeGeneral>>;
|
|
666
|
+
readonly hosts?: Fragments<DeepReadonly<SurgeHost>>;
|
|
667
|
+
};
|
|
657
668
|
type ProfileDefinition = {
|
|
669
|
+
readonly dns?: Fragments<DnsRule>;
|
|
658
670
|
readonly target: SurgeProfileInput["target"] | {
|
|
659
671
|
readonly engine: "sing-box";
|
|
660
672
|
readonly platform: "macos" | "linux";
|
|
661
673
|
readonly version: string;
|
|
662
674
|
};
|
|
663
|
-
readonly
|
|
664
|
-
readonly groups:
|
|
665
|
-
readonly routes:
|
|
675
|
+
readonly proxies: Fragments<ProfileProxy>;
|
|
676
|
+
readonly groups: Fragments<ProxyGroupDefinition>;
|
|
677
|
+
readonly routes: Fragments<RouteDefinition>;
|
|
666
678
|
readonly fallback: ProfileDestination;
|
|
667
|
-
readonly
|
|
668
|
-
readonly surge?: DeepReadonly<SurgeConfig>;
|
|
679
|
+
readonly surge?: SurgeConfig;
|
|
669
680
|
readonly singBox?: {
|
|
670
681
|
readonly mode: "fragment" | "standalone";
|
|
671
682
|
readonly listener?: {
|
|
@@ -674,7 +685,13 @@ type ProfileDefinition = {
|
|
|
674
685
|
};
|
|
675
686
|
};
|
|
676
687
|
};
|
|
677
|
-
type Profile = DeepReadonly<ProfileDefinition
|
|
688
|
+
type Profile = DeepReadonly<Omit<ProfileDefinition, "proxies" | "groups" | "routes" | "surge" | "dns"> & {
|
|
689
|
+
readonly dns?: readonly DnsRule[];
|
|
690
|
+
readonly proxies: readonly ProfileProxy[];
|
|
691
|
+
readonly groups: readonly ProxyGroupDefinition[];
|
|
692
|
+
readonly routes: readonly RouteDefinition[];
|
|
693
|
+
readonly surge?: Pick<SurgeProfileInput, "managed" | "general" | "hosts" | "names">;
|
|
694
|
+
}>;
|
|
678
695
|
type ProfileCompilation = {
|
|
679
696
|
readonly engine: "surge";
|
|
680
697
|
readonly ok: boolean;
|
|
@@ -688,7 +705,7 @@ type ProfileCompilation = {
|
|
|
688
705
|
readonly ok: false;
|
|
689
706
|
readonly code: string;
|
|
690
707
|
};
|
|
691
|
-
declare function surgeConfig(input: SurgeConfig):
|
|
708
|
+
declare function surgeConfig(input: SurgeConfig): SurgeConfig;
|
|
692
709
|
export declare function defineProfile(input: ProfileDefinition | Profile): Profile;
|
|
693
710
|
/** No secrets or I/O. All engine adaptations retain strict validation. */
|
|
694
711
|
export declare function compileProfile(input: ProfileDefinition | Profile): ProfileCompilation;
|
|
@@ -708,6 +725,7 @@ declare function proxyBuilder<N extends ProxyNode>(node: N): ProxyBuilder<Extrac
|
|
|
708
725
|
//#region src/dsl.d.ts
|
|
709
726
|
export declare const ruleSet: (definition: Omit<NamedRuleSet, "type">) => NamedRuleSet;
|
|
710
727
|
export declare const match: {
|
|
728
|
+
processName: (value: string) => Match;
|
|
711
729
|
ruleSet: (set: NamedRuleSet) => Match;
|
|
712
730
|
domain: (value: string) => Match;
|
|
713
731
|
domainSuffix: (value: string) => Match;
|
|
@@ -958,7 +976,7 @@ type BuildContext = {
|
|
|
958
976
|
readonly validation: boolean;
|
|
959
977
|
};
|
|
960
978
|
type BuildDefinition = {
|
|
961
|
-
readonly profiles: Readonly<Record<string, Profile>>;
|
|
979
|
+
readonly profiles: Readonly<Record<string, Profile | ProfileDefinition>>;
|
|
962
980
|
readonly preflight?: () => readonly string[];
|
|
963
981
|
readonly resolveSecret?: (token: Secret, context: BuildContext) => string | undefined;
|
|
964
982
|
};
|
|
@@ -974,4 +992,8 @@ export declare function runBuild(input: BuildDefinition, output: string, options
|
|
|
974
992
|
readonly validation?: boolean;
|
|
975
993
|
}): Promise<ProfileBuildResult>;
|
|
976
994
|
//#endregion
|
|
977
|
-
|
|
995
|
+
//#region src/proxy-id.d.ts
|
|
996
|
+
/** Stable identity independent of engine and mutable metadata. */
|
|
997
|
+
export declare function proxyId(provider: string, label: string): string;
|
|
998
|
+
//#endregion
|
|
999
|
+
export type { Artifact, BuildContext, BuildDefinition, BuildResult, CaseResult, Compilation, DeepReadonly, Fragments, Profile, ProfileBuildResult, ProfileCompilation, ProfileCondition, ProfileDefinition, ProfileDestination, ProfileProxy, ProxyBuilder, ProxyGroupDefinition, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, RouteDefinition, StrategyGroupCompilation, StrategyGroupInput, SurgeCondition, SurgeConfig, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileInput, SurgeRule, SurgeTunnel, TargetPlan };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { A as defineRoute, B as compileStrategyGroups, C as strategy, D as defineProfile, E as compileProfile, F as renderSurgeProfile, G as surgeProxy, H as nativeNameSchema, I as renderSurgeProfiles, J as assertData, K as validateProxyOptions, L as secretReader, M as outbound, N as selectProxies, O as ProfileDefinitionError, P as compileSurgeProfile, R as compile, S as slot, T as use, U as targetCatalog, V as isReservedNativeName, W as RenderError, X as idSchema, Y as deepFreeze, Z as nodeSchema, _ as ruleSet, a as render, b as sequence, c as direct, d as mihomo, f as policy, g as rule, h as route, i as buildToDirectory, j as defineRoutes, k as defineProxyGroup, l as group, m as reject, o as block, p as proxy, q as StaticRuleSetUnknownError, r as runBuild, s as defineConfig, t as defineBuild, u as match, v as secret, w as surge, x as singbox, y as selectNodes, z as explain } from "./profile-build-
|
|
1
|
+
import { A as defineRoute, B as compileStrategyGroups, C as strategy, D as defineProfile, E as compileProfile, F as renderSurgeProfile, G as surgeProxy, H as nativeNameSchema, I as renderSurgeProfiles, J as assertData, K as validateProxyOptions, L as secretReader, M as outbound, N as selectProxies, O as ProfileDefinitionError, P as compileSurgeProfile, R as compile, S as slot, T as use, U as targetCatalog, V as isReservedNativeName, W as RenderError, X as idSchema, Y as deepFreeze, Z as nodeSchema, _ as ruleSet, a as render, b as sequence, c as direct, d as mihomo, f as policy, g as rule, h as route, i as buildToDirectory, j as defineRoutes, k as defineProxyGroup, l as group, m as reject, o as block, p as proxy, q as StaticRuleSetUnknownError, r as runBuild, s as defineConfig, t as defineBuild, u as match, v as secret, w as surge, x as singbox, y as selectNodes, z as explain } from "./profile-build-DYCbePBx.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
3
4
|
//#region src/proxy-fragments.ts
|
|
4
5
|
const inputSchema = z.strictObject({
|
|
5
6
|
target: z.strictObject({
|
|
@@ -129,4 +130,11 @@ function renderProxyNodes(compilation, resolveSecret) {
|
|
|
129
130
|
});
|
|
130
131
|
}
|
|
131
132
|
//#endregion
|
|
132
|
-
|
|
133
|
+
//#region src/proxy-id.ts
|
|
134
|
+
/** Stable identity independent of engine and mutable metadata. */
|
|
135
|
+
function proxyId(provider, label) {
|
|
136
|
+
if (typeof provider !== "string" || !provider.length || typeof label !== "string" || !label.length) throw new Error("INVALID_PROXY_ID_INPUT");
|
|
137
|
+
return `node-${createHash("sha256").update(JSON.stringify([provider, label])).digest("hex").slice(0, 16)}`;
|
|
138
|
+
}
|
|
139
|
+
//#endregion
|
|
140
|
+
export { ProfileDefinitionError, RenderError, StaticRuleSetUnknownError, block, buildToDirectory, compile, compileProfile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineBuild, defineConfig, defineProfile, defineProxyGroup, defineRoute, defineRoutes, direct, explain, group, match, mihomo, outbound, policy, proxy, proxyId, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, runBuild, secret, selectNodes, selectProxies, sequence, singbox, slot, strategy, surge, targetCatalog, use };
|
|
@@ -1,119 +1,54 @@
|
|
|
1
1
|
import { isIP } from "node:net";
|
|
2
|
-
import ipaddr from "ipaddr.js";
|
|
3
2
|
import { z } from "zod";
|
|
3
|
+
import ipaddr from "ipaddr.js";
|
|
4
4
|
import { stringify } from "yaml";
|
|
5
5
|
import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
|
|
6
6
|
import { join, resolve } from "node:path";
|
|
7
7
|
import { randomUUID } from "node:crypto";
|
|
8
|
-
//#region src/
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
severity: "error",
|
|
19
|
-
code,
|
|
20
|
-
path,
|
|
21
|
-
message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
|
|
22
|
-
});
|
|
23
|
-
const visit = (m) => {
|
|
24
|
-
if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
|
|
25
|
-
const key = canonical(m);
|
|
26
|
-
if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
|
|
27
|
-
definitions.set(m.id, key);
|
|
28
|
-
if (m.type === "ruleSet") visit(m.when);
|
|
29
|
-
else {
|
|
30
|
-
if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
|
|
31
|
-
if (m.engine === "surge") {
|
|
32
|
-
const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
|
|
33
|
-
const url = new URL(m.url).href;
|
|
34
|
-
if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
|
|
35
|
-
urls.set(url, settings);
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
} else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
|
|
39
|
-
else if (m.type === "not") visit(m.condition);
|
|
40
|
-
};
|
|
41
|
-
const walk = (items) => {
|
|
42
|
-
for (const item of items) if (item.type === "rule") visit(item.when);
|
|
43
|
-
else if (item.type === "block") {
|
|
44
|
-
if (item.when) visit(item.when);
|
|
45
|
-
walk(item.rules);
|
|
46
|
-
} else walk(item.policy.rules);
|
|
47
|
-
};
|
|
48
|
-
walk(entries);
|
|
49
|
-
}
|
|
50
|
-
function lowerRuleSets(rules, diagnostics, path) {
|
|
51
|
-
let count = 0;
|
|
52
|
-
let origins = 0;
|
|
53
|
-
const lower = (m, origin, depth) => {
|
|
54
|
-
if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
|
|
55
|
-
if (m.type === "ruleSet") {
|
|
56
|
-
origin.push(`rule-set:${m.id}`);
|
|
57
|
-
return lower(m.when, origin, depth + 1);
|
|
58
|
-
}
|
|
59
|
-
if (m.type === "all" || m.type === "any") return {
|
|
60
|
-
...m,
|
|
61
|
-
conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
|
|
62
|
-
};
|
|
63
|
-
if (m.type === "not") return {
|
|
64
|
-
...m,
|
|
65
|
-
condition: lower(m.condition, origin, depth + 1)
|
|
66
|
-
};
|
|
67
|
-
return m;
|
|
68
|
-
};
|
|
8
|
+
//#region src/dns.ts
|
|
9
|
+
const domain$2 = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
|
10
|
+
function dohUrl(value) {
|
|
11
|
+
const url = new URL(value);
|
|
12
|
+
if (!/^https:\/\/[^/]+\//.test(value)) url.pathname = "/dns-query";
|
|
13
|
+
return url;
|
|
14
|
+
}
|
|
15
|
+
const server = z.string().max(2048).refine((value) => {
|
|
16
|
+
if (isIP(value) && !value.includes("%")) return true;
|
|
17
|
+
if (!value.startsWith("https://") || /[\s\p{C},()\\"'?#]/u.test(value)) return false;
|
|
69
18
|
try {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
origins += origin.length;
|
|
75
|
-
if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
|
|
76
|
-
return {
|
|
77
|
-
...r,
|
|
78
|
-
when,
|
|
79
|
-
origin
|
|
80
|
-
};
|
|
81
|
-
});
|
|
19
|
+
const url = new URL(value);
|
|
20
|
+
const authority = value.slice(8).split("/")[0];
|
|
21
|
+
const path = value.slice(8 + authority.length);
|
|
22
|
+
return !url.username && !url.password && !authority.endsWith(":") && !!url.hostname && (!path || url.pathname === path);
|
|
82
23
|
} catch {
|
|
83
|
-
|
|
84
|
-
severity: "error",
|
|
85
|
-
code: "EXPANSION_LIMIT",
|
|
86
|
-
path,
|
|
87
|
-
message: "展开规则、条件或来源超过预算"
|
|
88
|
-
});
|
|
89
|
-
return [];
|
|
24
|
+
return false;
|
|
90
25
|
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
26
|
+
});
|
|
27
|
+
const dnsRulesSchema = z.array(z.strictObject({
|
|
28
|
+
pattern: z.string().min(1).max(253).refine((value) => domain$2.test(value.startsWith("*.") ? value.slice(2) : value)),
|
|
29
|
+
server
|
|
30
|
+
})).max(2e3).superRefine((rules, ctx) => {
|
|
31
|
+
if (rules.length > 2e3 || rules.some((rule) => rule.pattern.length > 253 || rule.server.length > 2048)) return;
|
|
32
|
+
for (let i = 0; i < rules.length; i++) for (let j = 0; j < i; j++) {
|
|
33
|
+
const a = rules[i], b = rules[j];
|
|
34
|
+
const x = a.pattern.toLowerCase(), y = b.pattern.toLowerCase();
|
|
35
|
+
if (x === y || overlap(x, y) && a.server !== b.server) {
|
|
36
|
+
ctx.addIssue({
|
|
37
|
+
code: "custom",
|
|
38
|
+
message: "DNS_RULE_CONFLICT"
|
|
103
39
|
});
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
return [...found.values()];
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
function overlap(a, b) {
|
|
45
|
+
const wildA = a.startsWith("*."), wildB = b.startsWith("*.");
|
|
46
|
+
if (wildA && wildB) return a.slice(1).endsWith(b.slice(1)) || b.slice(1).endsWith(a.slice(1));
|
|
47
|
+
return wildA ? b.endsWith(a.slice(1)) : wildB && a.endsWith(b.slice(1));
|
|
48
|
+
}
|
|
49
|
+
function dnsCondition(rule) {
|
|
50
|
+
const pattern = rule.pattern.toLowerCase();
|
|
51
|
+
return pattern.startsWith("*.") ? { domain_regex: [`^.+\\.${pattern.slice(2).replaceAll(".", "\\.")}$`] } : { domain: [pattern] };
|
|
117
52
|
}
|
|
118
53
|
//#endregion
|
|
119
54
|
//#region src/schema.ts
|
|
@@ -130,6 +65,7 @@ const cidr$1 = z.string().refine((x) => {
|
|
|
130
65
|
return false;
|
|
131
66
|
}
|
|
132
67
|
});
|
|
68
|
+
const processNameSchema = z.string().min(1).max(255).regex(/^[^/\\*?[\],()\p{C}]+$/u);
|
|
133
69
|
const port$1 = z.number().int().min(1).max(65535);
|
|
134
70
|
const network = z.enum(["tcp", "udp"]);
|
|
135
71
|
const atom$2 = (type, value) => z.strictObject({
|
|
@@ -184,7 +120,8 @@ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
|
|
|
184
120
|
atom$2("domain", domain$1),
|
|
185
121
|
atom$2("domainSuffix", domain$1),
|
|
186
122
|
atom$2("ipCidr", cidr$1),
|
|
187
|
-
atom$2("sourceIp", cidr$1),
|
|
123
|
+
atom$2("sourceIp", z.union([ip$1, cidr$1])),
|
|
124
|
+
atom$2("processName", processNameSchema),
|
|
188
125
|
z.strictObject({
|
|
189
126
|
type: z.literal("port"),
|
|
190
127
|
from: port$1,
|
|
@@ -402,6 +339,7 @@ const requestSchema = z.strictObject({
|
|
|
402
339
|
domain: domain$1.optional(),
|
|
403
340
|
ip: ip$1.optional(),
|
|
404
341
|
sourceIp: ip$1.optional(),
|
|
342
|
+
processName: processNameSchema.optional(),
|
|
405
343
|
port: port$1.optional(),
|
|
406
344
|
sourcePort: port$1.optional()
|
|
407
345
|
});
|
|
@@ -413,6 +351,7 @@ const configSchema = z.strictObject({
|
|
|
413
351
|
"mihomo",
|
|
414
352
|
"stash"
|
|
415
353
|
]),
|
|
354
|
+
dns: dnsRulesSchema.optional(),
|
|
416
355
|
nodes: z.array(nodeSchema),
|
|
417
356
|
endpoints: z.array(endpointSchema).max(1e3).optional(),
|
|
418
357
|
groups: z.array(groupSchema$1),
|
|
@@ -490,6 +429,117 @@ function deepFreeze(value) {
|
|
|
490
429
|
return value;
|
|
491
430
|
}
|
|
492
431
|
//#endregion
|
|
432
|
+
//#region src/rulesets.ts
|
|
433
|
+
function canonical(value) {
|
|
434
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
435
|
+
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(",")}}`;
|
|
436
|
+
return JSON.stringify(value);
|
|
437
|
+
}
|
|
438
|
+
function validateRuleSets(entries, engine, diagnostics, path) {
|
|
439
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
440
|
+
const urls = /* @__PURE__ */ new Map();
|
|
441
|
+
const error = (code) => diagnostics.push({
|
|
442
|
+
severity: "error",
|
|
443
|
+
code,
|
|
444
|
+
path,
|
|
445
|
+
message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
|
|
446
|
+
});
|
|
447
|
+
const visit = (m) => {
|
|
448
|
+
if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
|
|
449
|
+
const key = canonical(m);
|
|
450
|
+
if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
|
|
451
|
+
definitions.set(m.id, key);
|
|
452
|
+
if (m.type === "ruleSet") visit(m.when);
|
|
453
|
+
else {
|
|
454
|
+
if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
|
|
455
|
+
if (m.engine === "surge") {
|
|
456
|
+
const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
|
|
457
|
+
const url = new URL(m.url).href;
|
|
458
|
+
if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
|
|
459
|
+
urls.set(url, settings);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
} else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
|
|
463
|
+
else if (m.type === "not") visit(m.condition);
|
|
464
|
+
};
|
|
465
|
+
const walk = (items) => {
|
|
466
|
+
for (const item of items) if (item.type === "rule") visit(item.when);
|
|
467
|
+
else if (item.type === "block") {
|
|
468
|
+
if (item.when) visit(item.when);
|
|
469
|
+
walk(item.rules);
|
|
470
|
+
} else walk(item.policy.rules);
|
|
471
|
+
};
|
|
472
|
+
walk(entries);
|
|
473
|
+
}
|
|
474
|
+
function lowerRuleSets(rules, diagnostics, path) {
|
|
475
|
+
let count = 0;
|
|
476
|
+
let origins = 0;
|
|
477
|
+
const lower = (m, origin, depth) => {
|
|
478
|
+
if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
|
|
479
|
+
if (m.type === "ruleSet") {
|
|
480
|
+
origin.push(`rule-set:${m.id}`);
|
|
481
|
+
return lower(m.when, origin, depth + 1);
|
|
482
|
+
}
|
|
483
|
+
if (m.type === "all" || m.type === "any") return {
|
|
484
|
+
...m,
|
|
485
|
+
conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
|
|
486
|
+
};
|
|
487
|
+
if (m.type === "not") return {
|
|
488
|
+
...m,
|
|
489
|
+
condition: lower(m.condition, origin, depth + 1)
|
|
490
|
+
};
|
|
491
|
+
return m;
|
|
492
|
+
};
|
|
493
|
+
try {
|
|
494
|
+
if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
|
|
495
|
+
return rules.map((r) => {
|
|
496
|
+
const origin = [...r.origin];
|
|
497
|
+
const when = lower(r.when, origin, 0);
|
|
498
|
+
origins += origin.length;
|
|
499
|
+
if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
|
|
500
|
+
return {
|
|
501
|
+
...r,
|
|
502
|
+
when,
|
|
503
|
+
origin
|
|
504
|
+
};
|
|
505
|
+
});
|
|
506
|
+
} catch {
|
|
507
|
+
diagnostics.push({
|
|
508
|
+
severity: "error",
|
|
509
|
+
code: "EXPANSION_LIMIT",
|
|
510
|
+
path,
|
|
511
|
+
message: "展开规则、条件或来源超过预算"
|
|
512
|
+
});
|
|
513
|
+
return [];
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function collectNativeRuleSets(rules, target, diagnostics) {
|
|
517
|
+
const found = /* @__PURE__ */ new Map();
|
|
518
|
+
const visit = (m, nested) => {
|
|
519
|
+
if (m.type === "nativeRuleSet") {
|
|
520
|
+
found.set(m.id, m);
|
|
521
|
+
if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
|
|
522
|
+
severity: "error",
|
|
523
|
+
code: "RULESET_COMPOSITION_UNSUPPORTED",
|
|
524
|
+
target: target.id,
|
|
525
|
+
path: `targets.${target.id}.ruleSets.${m.id}`,
|
|
526
|
+
message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
|
|
527
|
+
});
|
|
528
|
+
} else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
|
|
529
|
+
else if (m.type === "not") visit(m.condition, true);
|
|
530
|
+
else if (m.type === "ruleSet") visit(m.when, nested);
|
|
531
|
+
};
|
|
532
|
+
rules.forEach((r) => visit(r.when, false));
|
|
533
|
+
for (const r of found.values()) diagnostics.push({
|
|
534
|
+
severity: "warning",
|
|
535
|
+
code: "EXTERNAL_RULESET_UNVERIFIED",
|
|
536
|
+
target: target.id,
|
|
537
|
+
path: `targets.${target.id}.ruleSets.${r.id}`,
|
|
538
|
+
message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
|
|
539
|
+
});
|
|
540
|
+
return [...found.values()];
|
|
541
|
+
}
|
|
542
|
+
//#endregion
|
|
493
543
|
//#region src/rules.ts
|
|
494
544
|
function expandRules(entries, diagnostics, path = "routing") {
|
|
495
545
|
const output = [];
|
|
@@ -563,7 +613,7 @@ function expandRules(entries, diagnostics, path = "routing") {
|
|
|
563
613
|
function inCidr(address, cidr) {
|
|
564
614
|
if (!address) return false;
|
|
565
615
|
const parsed = ipaddr.parse(address);
|
|
566
|
-
const [base, bits] = ipaddr.parseCIDR(cidr);
|
|
616
|
+
const [base, bits] = ipaddr.parseCIDR(cidr.includes("/") ? cidr : `${cidr}/${cidr.includes(":") ? 128 : 32}`);
|
|
567
617
|
return parsed.kind() === base.kind() && parsed.match(base, bits);
|
|
568
618
|
}
|
|
569
619
|
var StaticRuleSetUnknownError = class extends Error {
|
|
@@ -613,6 +663,10 @@ function evaluate(condition, request) {
|
|
|
613
663
|
present = request.ip !== void 0;
|
|
614
664
|
matched = inCidr(request.ip, condition.value);
|
|
615
665
|
break;
|
|
666
|
+
case "processName":
|
|
667
|
+
present = request.processName !== void 0;
|
|
668
|
+
matched = request.processName === condition.value;
|
|
669
|
+
break;
|
|
616
670
|
case "sourceIp":
|
|
617
671
|
present = request.sourceIp !== void 0;
|
|
618
672
|
matched = inCidr(request.sourceIp, condition.value);
|
|
@@ -909,7 +963,8 @@ function conditionText$1(condition) {
|
|
|
909
963
|
case "domain": return `DOMAIN,${condition.value}`;
|
|
910
964
|
case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
|
|
911
965
|
case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
|
|
912
|
-
case "
|
|
966
|
+
case "processName": return `PROCESS-NAME,${condition.value}`;
|
|
967
|
+
case "sourceIp": return `SRC-IP-CIDR,${condition.value.includes("/") ? condition.value : `${condition.value}/${condition.value.includes(":") ? 128 : 32}`}`;
|
|
913
968
|
case "network": return `NETWORK,${condition.value}`;
|
|
914
969
|
case "port":
|
|
915
970
|
case "sourcePort": return `${condition.type === "port" ? "DST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
|
|
@@ -1283,7 +1338,7 @@ function compile(input) {
|
|
|
1283
1338
|
}
|
|
1284
1339
|
const parsed = configSchema.safeParse(input);
|
|
1285
1340
|
if (!parsed.success) {
|
|
1286
|
-
for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
|
|
1341
|
+
for (const issue of parsed.error.issues.slice(0, 20)) error(issue.message === "DNS_RULE_CONFLICT" ? "DNS_RULE_CONFLICT" : "INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
|
|
1287
1342
|
return deepFreeze({
|
|
1288
1343
|
ok: false,
|
|
1289
1344
|
diagnostics,
|
|
@@ -1371,6 +1426,10 @@ function compile(input) {
|
|
|
1371
1426
|
if (program.engine !== target.engine) error("ENGINE_MISMATCH", path, "平台程序与目标引擎不一致", target.id);
|
|
1372
1427
|
if (target.mode === "standalone" && !program.listener) error("LISTENER_REQUIRED", path, "standalone 必须声明 loopback listener 与 IP DNS resolver", target.id);
|
|
1373
1428
|
if (target.mode !== "standalone" && program.listener) error("UNUSED_LISTENER", path, "fragment 不能静默忽略 listener;请使用独立程序或 standalone 目标", target.id);
|
|
1429
|
+
if (program.dns?.length) {
|
|
1430
|
+
if (target.engine !== "sing-box") error("DNS_TARGET_UNSUPPORTED", path, "通用 DNS 需要 sing-box standalone 或 Surge Profile", target.id);
|
|
1431
|
+
else if (target.mode !== "standalone") error("DNS_MODE_UNSUPPORTED", path, "通用 DNS 需要 standalone", target.id);
|
|
1432
|
+
}
|
|
1374
1433
|
for (const endpoint of program.endpoints ?? []) {
|
|
1375
1434
|
if (!descriptor.endpoints.includes(endpoint.type)) error("ENDPOINT_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 端点仅支持 sing-box 1.12.0", target.id);
|
|
1376
1435
|
if (target.mode !== "standalone") error("ENDPOINT_MODE_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 需要 standalone 的普通 DNS/final 隔离引导解析", target.id);
|
|
@@ -1596,6 +1655,8 @@ const generalSchema = z.strictObject({
|
|
|
1596
1655
|
"socks5-listen": listener.optional(),
|
|
1597
1656
|
"proxy-restricted-to-lan": z.boolean().optional()
|
|
1598
1657
|
});
|
|
1658
|
+
/** Internal fragment validation; caller must inspect data descriptors before invoking. */
|
|
1659
|
+
const validateSurgeGeneral = (input) => generalSchema.safeParse(input).success;
|
|
1599
1660
|
const hostSchema = z.strictObject({
|
|
1600
1661
|
pattern: hostPattern,
|
|
1601
1662
|
address: z.union([ip, domain]).optional(),
|
|
@@ -2136,6 +2197,10 @@ function lowerSurgeProfile(input) {
|
|
|
2136
2197
|
});
|
|
2137
2198
|
}
|
|
2138
2199
|
function lower(destination) {
|
|
2200
|
+
if (typeof destination === "string") {
|
|
2201
|
+
if (!registry.has(destination)) fail$1("UNKNOWN_DESTINATION_ID");
|
|
2202
|
+
return { ref: destination };
|
|
2203
|
+
}
|
|
2139
2204
|
if (!destination || typeof destination !== "object") fail$1("INVALID_DESTINATION");
|
|
2140
2205
|
if ("builtin" in destination) {
|
|
2141
2206
|
exactDefinition(destination, ["builtin"]);
|
|
@@ -2304,13 +2369,13 @@ function defineProfile(input) {
|
|
|
2304
2369
|
inspectDefinition(input);
|
|
2305
2370
|
exactDefinition(input, [
|
|
2306
2371
|
"target",
|
|
2307
|
-
"
|
|
2372
|
+
"proxies",
|
|
2308
2373
|
"groups",
|
|
2309
2374
|
"routes",
|
|
2310
2375
|
"fallback",
|
|
2311
|
-
"endpoints",
|
|
2312
2376
|
"surge",
|
|
2313
|
-
"singBox"
|
|
2377
|
+
"singBox",
|
|
2378
|
+
"dns"
|
|
2314
2379
|
]);
|
|
2315
2380
|
exactDefinition(input.target, [
|
|
2316
2381
|
"engine",
|
|
@@ -2328,8 +2393,83 @@ function defineProfile(input) {
|
|
|
2328
2393
|
if (!["fragment", "standalone"].includes(input.singBox.mode)) fail("INVALID_PROFILE_DEFINITION");
|
|
2329
2394
|
if (input.singBox.listener !== void 0) exactDefinition(input.singBox.listener, ["port", "resolver"]);
|
|
2330
2395
|
}
|
|
2331
|
-
|
|
2332
|
-
|
|
2396
|
+
let remaining = 1e5;
|
|
2397
|
+
function flatten(fragments) {
|
|
2398
|
+
if (!Array.isArray(fragments)) fail("INVALID_PROFILE_DEFINITION");
|
|
2399
|
+
const result = [];
|
|
2400
|
+
function visit(value) {
|
|
2401
|
+
if (--remaining < 0) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
|
|
2402
|
+
if (Array.isArray(value)) for (const item of value) visit(item);
|
|
2403
|
+
else {
|
|
2404
|
+
if (!value || typeof value !== "object") fail("INVALID_PROFILE_DEFINITION");
|
|
2405
|
+
result.push(value);
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
visit(fragments);
|
|
2409
|
+
return result;
|
|
2410
|
+
}
|
|
2411
|
+
const proxies = flatten(input.proxies);
|
|
2412
|
+
const groups = flatten(input.groups);
|
|
2413
|
+
const routes = flatten(input.routes);
|
|
2414
|
+
const dns = input.dns === void 0 ? void 0 : flatten(input.dns);
|
|
2415
|
+
if (dns) {
|
|
2416
|
+
const checked = dnsRulesSchema.safeParse(dns);
|
|
2417
|
+
if (!checked.success) fail(checked.error.issues.some((issue) => issue.message === "DNS_RULE_CONFLICT") ? "DNS_RULE_CONFLICT" : "INVALID_DNS_RULES");
|
|
2418
|
+
}
|
|
2419
|
+
let surge;
|
|
2420
|
+
if (input.surge !== void 0) {
|
|
2421
|
+
let general;
|
|
2422
|
+
if (input.surge.general !== void 0) {
|
|
2423
|
+
general = {};
|
|
2424
|
+
const checked = /* @__PURE__ */ new Set();
|
|
2425
|
+
const costs = /* @__PURE__ */ new Map();
|
|
2426
|
+
let validationRemaining = 1e5;
|
|
2427
|
+
function cost(value) {
|
|
2428
|
+
if (!value || typeof value !== "object") return 1;
|
|
2429
|
+
const cached = costs.get(value);
|
|
2430
|
+
if (cached !== void 0) return cached;
|
|
2431
|
+
let total = 1;
|
|
2432
|
+
for (const item of Object.values(value)) {
|
|
2433
|
+
total += cost(item);
|
|
2434
|
+
if (total > 1e5) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
|
|
2435
|
+
}
|
|
2436
|
+
costs.set(value, total);
|
|
2437
|
+
return total;
|
|
2438
|
+
}
|
|
2439
|
+
const fragments = Array.isArray(input.surge.general) ? input.surge.general : [input.surge.general];
|
|
2440
|
+
for (const fragment of flatten(fragments)) {
|
|
2441
|
+
if (!checked.has(fragment)) {
|
|
2442
|
+
validationRemaining -= cost(fragment);
|
|
2443
|
+
if (validationRemaining < 0) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
|
|
2444
|
+
if (!validateSurgeGeneral(fragment)) fail("INVALID_SURGE_GENERAL");
|
|
2445
|
+
checked.add(fragment);
|
|
2446
|
+
}
|
|
2447
|
+
Object.assign(general, fragment);
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
surge = {
|
|
2451
|
+
...input.surge,
|
|
2452
|
+
...general === void 0 ? {} : { general },
|
|
2453
|
+
...input.surge.hosts === void 0 ? {} : { hosts: flatten(input.surge.hosts) }
|
|
2454
|
+
};
|
|
2455
|
+
}
|
|
2456
|
+
if (dns?.length && surge?.hosts?.length) fail("DNS_HOSTS_CONFLICT");
|
|
2457
|
+
const { dns: _dns, surge: _surge, proxies: _proxies, groups: _groups, routes: _routes, ...rest } = input;
|
|
2458
|
+
return snapshotProfile({
|
|
2459
|
+
...rest,
|
|
2460
|
+
...dns === void 0 ? {} : { dns },
|
|
2461
|
+
proxies,
|
|
2462
|
+
groups,
|
|
2463
|
+
routes,
|
|
2464
|
+
...surge === void 0 ? {} : { surge }
|
|
2465
|
+
});
|
|
2466
|
+
}
|
|
2467
|
+
function isEndpoint(proxy) {
|
|
2468
|
+
return [
|
|
2469
|
+
"wireguard",
|
|
2470
|
+
"tailscale",
|
|
2471
|
+
"sing-box-tailscale"
|
|
2472
|
+
].includes(proxy.type);
|
|
2333
2473
|
}
|
|
2334
2474
|
function surgeCondition$1(condition, depth = 0) {
|
|
2335
2475
|
if (depth > 10) return fail("LOGICAL_DEPTH_EXCEEDED");
|
|
@@ -2371,14 +2511,17 @@ function compileProfile(input) {
|
|
|
2371
2511
|
try {
|
|
2372
2512
|
const profile = defineProfile(input);
|
|
2373
2513
|
snapshotDefinition(profile.routes.map((route) => route.when));
|
|
2514
|
+
const nodes = profile.proxies.filter((proxy) => !isEndpoint(proxy));
|
|
2515
|
+
const endpoints = profile.proxies.filter(isEndpoint);
|
|
2374
2516
|
if (profile.target.engine === "surge") {
|
|
2375
2517
|
if (profile.singBox !== void 0) fail("PROFILE_EXTENSION_UNSUPPORTED");
|
|
2376
|
-
if (
|
|
2518
|
+
if (endpoints.some((endpoint) => endpoint.type === "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
|
|
2377
2519
|
const compilation = compileSurgeProfile(lowerSurgeProfile({
|
|
2378
2520
|
target: profile.target,
|
|
2379
2521
|
...profile.surge,
|
|
2380
|
-
|
|
2381
|
-
|
|
2522
|
+
...profile.dns?.length ? { hosts: profile.dns } : {},
|
|
2523
|
+
nodes,
|
|
2524
|
+
tunnels: endpoints,
|
|
2382
2525
|
groups: profile.groups,
|
|
2383
2526
|
routes: profile.routes.map((route) => ({
|
|
2384
2527
|
...route,
|
|
@@ -2394,18 +2537,21 @@ function compileProfile(input) {
|
|
|
2394
2537
|
}
|
|
2395
2538
|
if (profile.target.engine !== "sing-box") return fail("PROFILE_TARGET_UNSUPPORTED");
|
|
2396
2539
|
if (profile.surge !== void 0) fail("PROFILE_EXTENSION_UNSUPPORTED");
|
|
2397
|
-
if (
|
|
2540
|
+
if (endpoints.some((endpoint) => endpoint.type !== "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
|
|
2398
2541
|
const registry = /* @__PURE__ */ new Map();
|
|
2399
|
-
for (const resource of [
|
|
2400
|
-
...profile.nodes,
|
|
2401
|
-
...profile.groups,
|
|
2402
|
-
...profile.endpoints ?? []
|
|
2403
|
-
]) {
|
|
2542
|
+
for (const resource of [...profile.proxies, ...profile.groups]) {
|
|
2404
2543
|
if (!resource || typeof resource.id !== "string") fail("INVALID_RESOURCE_DEFINITION");
|
|
2405
2544
|
if (registry.has(resource.id)) fail("DUPLICATE_RESOURCE_ID");
|
|
2406
2545
|
registry.set(resource.id, resource);
|
|
2407
2546
|
}
|
|
2408
2547
|
const lower = (destination) => {
|
|
2548
|
+
if (typeof destination === "string") {
|
|
2549
|
+
if (!registry.has(destination)) return fail("UNKNOWN_DESTINATION_ID");
|
|
2550
|
+
return {
|
|
2551
|
+
type: "route",
|
|
2552
|
+
to: destination
|
|
2553
|
+
};
|
|
2554
|
+
}
|
|
2409
2555
|
if (!destination || typeof destination !== "object") return fail("INVALID_DESTINATION");
|
|
2410
2556
|
if ("builtin" in destination) {
|
|
2411
2557
|
exactDefinition(destination, ["builtin"]);
|
|
@@ -2466,8 +2612,9 @@ function compileProfile(input) {
|
|
|
2466
2612
|
const compilation = compile(snapshotDefinition({
|
|
2467
2613
|
programs: { profile: {
|
|
2468
2614
|
engine: "sing-box",
|
|
2469
|
-
|
|
2470
|
-
|
|
2615
|
+
...profile.dns === void 0 ? {} : { dns: profile.dns },
|
|
2616
|
+
nodes,
|
|
2617
|
+
endpoints,
|
|
2471
2618
|
groups,
|
|
2472
2619
|
routing,
|
|
2473
2620
|
fallback: lower(profile.fallback),
|
|
@@ -2517,6 +2664,13 @@ const ruleSet = (definition) => ({
|
|
|
2517
2664
|
type: "ruleSet"
|
|
2518
2665
|
});
|
|
2519
2666
|
const match = {
|
|
2667
|
+
processName: (value) => {
|
|
2668
|
+
if (!processNameSchema.safeParse(value).success) throw new Error("INVALID_PROCESS_NAME");
|
|
2669
|
+
return {
|
|
2670
|
+
type: "processName",
|
|
2671
|
+
value
|
|
2672
|
+
};
|
|
2673
|
+
},
|
|
2520
2674
|
ruleSet: (set) => set,
|
|
2521
2675
|
domain: (value) => ({
|
|
2522
2676
|
type: "domain",
|
|
@@ -2694,7 +2848,8 @@ function singCondition(condition) {
|
|
|
2694
2848
|
case "domain": return { domain: [condition.value] };
|
|
2695
2849
|
case "domainSuffix": return { domain_suffix: [condition.value] };
|
|
2696
2850
|
case "ipCidr": return { ip_cidr: [condition.value] };
|
|
2697
|
-
case "
|
|
2851
|
+
case "processName": return { process_name: [condition.value] };
|
|
2852
|
+
case "sourceIp": return { source_ip_cidr: [condition.value.includes("/") ? condition.value : `${condition.value}/${isIP(condition.value) === 6 ? 128 : 32}`] };
|
|
2698
2853
|
case "network": return { network: [condition.value] };
|
|
2699
2854
|
case "port":
|
|
2700
2855
|
case "sourcePort": {
|
|
@@ -2722,7 +2877,13 @@ function singbox(plan, secret) {
|
|
|
2722
2877
|
tag: DIRECT,
|
|
2723
2878
|
...!modern && standalone ? { domain_strategy: "prefer_ipv4" } : {}
|
|
2724
2879
|
}];
|
|
2725
|
-
for (const node of program.nodes) outbounds.push(
|
|
2880
|
+
for (const node of program.nodes) outbounds.push({
|
|
2881
|
+
...singboxProxy(node, secret),
|
|
2882
|
+
...modern && program.dns?.length ? { domain_resolver: {
|
|
2883
|
+
server: DNS,
|
|
2884
|
+
strategy: "prefer_ipv4"
|
|
2885
|
+
} } : {}
|
|
2886
|
+
});
|
|
2726
2887
|
for (const group of program.groups) outbounds.push(singboxGroup(group));
|
|
2727
2888
|
const rules = plan.rules.map((rule) => ({
|
|
2728
2889
|
...singCondition(rule.when),
|
|
@@ -2757,8 +2918,7 @@ function singbox(plan, secret) {
|
|
|
2757
2918
|
type: "udp",
|
|
2758
2919
|
tag: DNS,
|
|
2759
2920
|
server: listener.resolver,
|
|
2760
|
-
server_port: 53
|
|
2761
|
-
detour: DIRECT
|
|
2921
|
+
server_port: 53
|
|
2762
2922
|
} : {
|
|
2763
2923
|
tag: DNS,
|
|
2764
2924
|
address: `udp://${isIP(listener.resolver) === 6 ? `[${listener.resolver}]` : listener.resolver}`,
|
|
@@ -2767,11 +2927,51 @@ function singbox(plan, secret) {
|
|
|
2767
2927
|
final: DNS,
|
|
2768
2928
|
strategy: "prefer_ipv4"
|
|
2769
2929
|
};
|
|
2770
|
-
if (modern) routing.default_domain_resolver = {
|
|
2930
|
+
if (modern && !program.dns?.length) routing.default_domain_resolver = {
|
|
2771
2931
|
server: DNS,
|
|
2772
2932
|
strategy: "prefer_ipv4"
|
|
2773
2933
|
};
|
|
2774
2934
|
}
|
|
2935
|
+
if (program.dns?.length) {
|
|
2936
|
+
const dns = config.dns;
|
|
2937
|
+
dns.rules = program.dns.map((rule, index) => {
|
|
2938
|
+
const tag = `pl-domain-dns-${index}`;
|
|
2939
|
+
if (isIP(rule.server)) dns.servers.push(modern ? {
|
|
2940
|
+
type: "udp",
|
|
2941
|
+
tag,
|
|
2942
|
+
server: rule.server,
|
|
2943
|
+
server_port: 53
|
|
2944
|
+
} : {
|
|
2945
|
+
tag,
|
|
2946
|
+
address: `udp://${isIP(rule.server) === 6 ? `[${rule.server}]` : rule.server}`,
|
|
2947
|
+
detour: DIRECT
|
|
2948
|
+
});
|
|
2949
|
+
else {
|
|
2950
|
+
const url = dohUrl(rule.server);
|
|
2951
|
+
dns.servers.push(modern ? {
|
|
2952
|
+
type: "https",
|
|
2953
|
+
tag,
|
|
2954
|
+
server: url.hostname.replace(/^\[|\]$/g, ""),
|
|
2955
|
+
server_port: Number(url.port || 443),
|
|
2956
|
+
path: url.pathname,
|
|
2957
|
+
tls: { enabled: true },
|
|
2958
|
+
domain_resolver: {
|
|
2959
|
+
server: DNS,
|
|
2960
|
+
strategy: "prefer_ipv4"
|
|
2961
|
+
}
|
|
2962
|
+
} : {
|
|
2963
|
+
tag,
|
|
2964
|
+
address: url.href,
|
|
2965
|
+
address_resolver: DNS,
|
|
2966
|
+
detour: DIRECT
|
|
2967
|
+
});
|
|
2968
|
+
}
|
|
2969
|
+
return {
|
|
2970
|
+
...dnsCondition(rule),
|
|
2971
|
+
server: tag
|
|
2972
|
+
};
|
|
2973
|
+
});
|
|
2974
|
+
}
|
|
2775
2975
|
if (program.endpoints?.length) {
|
|
2776
2976
|
config.endpoints = program.endpoints.map((endpoint) => ({
|
|
2777
2977
|
type: "tailscale",
|
|
@@ -2789,8 +2989,7 @@ function singbox(plan, secret) {
|
|
|
2789
2989
|
type: "udp",
|
|
2790
2990
|
tag: `pl-ts-dns-${endpoint.id}`,
|
|
2791
2991
|
server: endpoint.bootstrapResolver,
|
|
2792
|
-
server_port: 53
|
|
2793
|
-
detour: DIRECT
|
|
2992
|
+
server_port: 53
|
|
2794
2993
|
});
|
|
2795
2994
|
}
|
|
2796
2995
|
return config;
|
|
@@ -2805,6 +3004,7 @@ function surgeCondition(condition) {
|
|
|
2805
3004
|
case "domain": return `DOMAIN,${condition.value}`;
|
|
2806
3005
|
case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
|
|
2807
3006
|
case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
|
|
3007
|
+
case "processName": return `PROCESS-NAME,${condition.value}`;
|
|
2808
3008
|
case "sourceIp": return `SRC-IP,${condition.value}`;
|
|
2809
3009
|
case "network": return `PROTOCOL,${condition.value.toUpperCase()}`;
|
|
2810
3010
|
case "port":
|
package/package.json
CHANGED