proxylang 0.4.0 → 0.5.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/dist/cli.js +1 -1
- package/dist/index.d.ts +173 -24
- package/dist/index.js +2 -2
- package/dist/{profile-build-DYCbePBx.js → profile-build-Cokl8MBF.js} +784 -691
- package/package.json +1 -1
|
@@ -1,88 +1,426 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
1
2
|
import { isIP } from "node:net";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
import ipaddr from "ipaddr.js";
|
|
4
5
|
import { stringify } from "yaml";
|
|
5
6
|
import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
|
|
6
7
|
import { join, resolve } from "node:path";
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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;
|
|
18
|
-
try {
|
|
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);
|
|
23
|
-
} catch {
|
|
24
|
-
return false;
|
|
8
|
+
//#region src/surge-definitions.ts
|
|
9
|
+
var ProfileDefinitionError = class extends Error {
|
|
10
|
+
code;
|
|
11
|
+
constructor(code) {
|
|
12
|
+
super(code);
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.name = "ProfileDefinitionError";
|
|
25
15
|
}
|
|
26
|
-
}
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
16
|
+
};
|
|
17
|
+
const fail$1 = (code) => {
|
|
18
|
+
throw new ProfileDefinitionError(code);
|
|
19
|
+
};
|
|
20
|
+
/** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
|
|
21
|
+
function inspectDefinition(root) {
|
|
22
|
+
let edges = 0;
|
|
23
|
+
let objects = 0;
|
|
24
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
25
|
+
const heights = /* @__PURE__ */ new Map();
|
|
26
|
+
function visit(value, depth) {
|
|
27
|
+
if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
|
|
28
|
+
if (value === null || typeof value !== "object") {
|
|
29
|
+
if (![
|
|
30
|
+
"undefined",
|
|
31
|
+
"string",
|
|
32
|
+
"number",
|
|
33
|
+
"boolean"
|
|
34
|
+
].includes(typeof value) && value !== null) fail$1("DEFINITION_NOT_DATA");
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
37
|
+
if (visiting.has(value)) fail$1("DEFINITION_CYCLE");
|
|
38
|
+
const cached = heights.get(value);
|
|
39
|
+
if (cached !== void 0) {
|
|
40
|
+
if (depth + cached > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
|
|
41
|
+
return cached;
|
|
42
|
+
}
|
|
43
|
+
if (++objects > 2e4) fail$1("DEFINITION_OBJECT_BUDGET_EXCEEDED");
|
|
44
|
+
const proto = Object.getPrototypeOf(value);
|
|
45
|
+
if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail$1("DEFINITION_NOT_DATA");
|
|
46
|
+
if (Array.isArray(value) && value.length > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
|
|
47
|
+
visiting.add(value);
|
|
48
|
+
let height = 0;
|
|
49
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
50
|
+
if (++edges > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
|
|
51
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
52
|
+
if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail$1("DEFINITION_NOT_DATA");
|
|
53
|
+
height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
|
|
41
54
|
}
|
|
55
|
+
visiting.delete(value);
|
|
56
|
+
heights.set(value, height);
|
|
57
|
+
return height;
|
|
42
58
|
}
|
|
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));
|
|
59
|
+
visit(root, 0);
|
|
48
60
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
61
|
+
/** Count output occurrences, not identities, before allocating each copied value. */
|
|
62
|
+
function snapshot(input) {
|
|
63
|
+
let remaining = 1e5;
|
|
64
|
+
function copy(value, depth) {
|
|
65
|
+
if (--remaining < 0) fail$1("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
|
|
66
|
+
if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
|
|
67
|
+
if (value === null || typeof value !== "object") return value;
|
|
68
|
+
if (Array.isArray(value)) {
|
|
69
|
+
const output = [];
|
|
70
|
+
for (const item of value) output.push(copy(item, depth + 1));
|
|
71
|
+
return output;
|
|
72
|
+
}
|
|
73
|
+
const output = {};
|
|
74
|
+
for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
|
|
75
|
+
value: copy(item, depth + 1),
|
|
76
|
+
enumerable: true,
|
|
77
|
+
writable: true,
|
|
78
|
+
configurable: true
|
|
79
|
+
});
|
|
80
|
+
return output;
|
|
81
|
+
}
|
|
82
|
+
return copy(input, 0);
|
|
52
83
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
84
|
+
function snapshotDefinition(input) {
|
|
85
|
+
inspectDefinition(input);
|
|
86
|
+
return snapshot(input);
|
|
87
|
+
}
|
|
88
|
+
function exactDefinition(value, keys) {
|
|
89
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) fail$1("DEFINITION_NOT_DATA");
|
|
90
|
+
if (Object.keys(value).some((key) => !keys.includes(key))) fail$1("DEFINITION_UNKNOWN_FIELD");
|
|
91
|
+
}
|
|
92
|
+
const outbound = {
|
|
93
|
+
direct: Object.freeze({ builtin: "DIRECT" }),
|
|
94
|
+
reject: Object.freeze({ builtin: "REJECT" }),
|
|
95
|
+
rejectDrop: Object.freeze({ builtin: "REJECT-DROP" }),
|
|
96
|
+
rejectNoDrop: Object.freeze({ builtin: "REJECT-NO-DROP" }),
|
|
97
|
+
rejectTinyGif: Object.freeze({ builtin: "REJECT-TINYGIF" })
|
|
98
|
+
};
|
|
99
|
+
function defineProxyGroup(input) {
|
|
100
|
+
inspectDefinition(input);
|
|
101
|
+
exactDefinition(input, [
|
|
102
|
+
"id",
|
|
103
|
+
"name",
|
|
104
|
+
"algorithm",
|
|
105
|
+
"members",
|
|
106
|
+
"url",
|
|
107
|
+
"intervalSeconds",
|
|
108
|
+
"timeoutSeconds"
|
|
109
|
+
]);
|
|
110
|
+
if (!input.algorithm || ![
|
|
111
|
+
"select",
|
|
112
|
+
"surge-smart",
|
|
113
|
+
"urltest"
|
|
114
|
+
].includes(input.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
|
|
115
|
+
exactDefinition(input.algorithm, input.algorithm.type === "urltest" ? [
|
|
116
|
+
"type",
|
|
117
|
+
"url",
|
|
118
|
+
"intervalSeconds",
|
|
119
|
+
"toleranceMs"
|
|
120
|
+
] : ["type"]);
|
|
121
|
+
if (!Array.isArray(input.members)) fail$1("INVALID_GROUP_DEFINITION");
|
|
122
|
+
return {
|
|
123
|
+
...input,
|
|
124
|
+
type: "proxy-group",
|
|
125
|
+
algorithm: { ...input.algorithm },
|
|
126
|
+
members: [...input.members]
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function defineRoute(input) {
|
|
130
|
+
inspectDefinition(input);
|
|
131
|
+
exactDefinition(input, ["when", "to"]);
|
|
132
|
+
return {
|
|
133
|
+
...input,
|
|
134
|
+
type: "route"
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
function defineRoutes(input) {
|
|
138
|
+
inspectDefinition(input);
|
|
139
|
+
exactDefinition(input, ["when", "to"]);
|
|
140
|
+
if (!Array.isArray(input.when)) fail$1("INVALID_ROUTE_DEFINITION");
|
|
141
|
+
return input.when.map((when) => ({
|
|
142
|
+
type: "route",
|
|
143
|
+
when,
|
|
144
|
+
to: input.to
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
function selectProxies(nodes, query = {}) {
|
|
148
|
+
inspectDefinition({
|
|
149
|
+
nodes,
|
|
150
|
+
query
|
|
151
|
+
});
|
|
152
|
+
exactDefinition(query, [
|
|
153
|
+
"ids",
|
|
154
|
+
"regions",
|
|
155
|
+
"providers",
|
|
156
|
+
"tags"
|
|
157
|
+
]);
|
|
158
|
+
if (!Array.isArray(nodes) || nodes.some((node) => !node || typeof node !== "object")) fail$1("DEFINITION_NOT_DATA");
|
|
159
|
+
for (const values of Object.values(query)) if (values !== void 0 && !Array.isArray(values)) fail$1("DEFINITION_NOT_DATA");
|
|
160
|
+
return nodes.filter((node) => (!query.ids || query.ids.includes(node.id)) && (!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))));
|
|
161
|
+
}
|
|
162
|
+
function lowerSurgeProfile(input) {
|
|
163
|
+
inspectDefinition(input);
|
|
164
|
+
exactDefinition(input, [
|
|
165
|
+
"target",
|
|
166
|
+
"managed",
|
|
167
|
+
"general",
|
|
168
|
+
"hosts",
|
|
169
|
+
"nodes",
|
|
170
|
+
"tunnels",
|
|
171
|
+
"names",
|
|
172
|
+
"groups",
|
|
173
|
+
"routes",
|
|
174
|
+
"fallback"
|
|
175
|
+
]);
|
|
176
|
+
if (!Array.isArray(input.nodes) || !Array.isArray(input.groups) || !Array.isArray(input.routes) || input.tunnels !== void 0 && !Array.isArray(input.tunnels)) fail$1("DEFINITION_NOT_DATA");
|
|
177
|
+
const registry = /* @__PURE__ */ new Map();
|
|
178
|
+
const names = Object.assign(Object.create(null), input.names);
|
|
179
|
+
for (const resource of [
|
|
180
|
+
...input.nodes,
|
|
181
|
+
...input.tunnels ?? [],
|
|
182
|
+
...input.groups
|
|
183
|
+
]) {
|
|
184
|
+
if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail$1("INVALID_RESOURCE_DEFINITION");
|
|
185
|
+
if (registry.has(resource.id)) fail$1("DUPLICATE_RESOURCE_ID");
|
|
186
|
+
registry.set(resource.id, resource);
|
|
187
|
+
const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
|
|
188
|
+
if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail$1("GROUP_NAME_CONFLICT");
|
|
189
|
+
Object.defineProperty(names, resource.id, {
|
|
190
|
+
value: names[resource.id] ?? name,
|
|
191
|
+
enumerable: true,
|
|
192
|
+
configurable: true,
|
|
193
|
+
writable: true
|
|
194
|
+
});
|
|
66
195
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
const atom$2 = (type, value) => z.strictObject({
|
|
72
|
-
type: z.literal(type),
|
|
73
|
-
value
|
|
74
|
-
});
|
|
75
|
-
const remoteBase = {
|
|
76
|
-
type: z.literal("nativeRuleSet"),
|
|
77
|
-
id: idSchema,
|
|
78
|
-
url: z.string().max(2048).refine((value) => {
|
|
79
|
-
try {
|
|
80
|
-
const url = new URL(value);
|
|
81
|
-
return /^https?:\/\//.test(value) && ["http:", "https:"].includes(url.protocol) && !url.username && !url.password && !url.hash && !/[\s\p{C},()\\"']/u.test(value);
|
|
82
|
-
} catch {
|
|
83
|
-
return false;
|
|
196
|
+
function lower(destination) {
|
|
197
|
+
if (typeof destination === "string") {
|
|
198
|
+
if (!registry.has(destination)) fail$1("UNKNOWN_DESTINATION_ID");
|
|
199
|
+
return { ref: destination };
|
|
84
200
|
}
|
|
85
|
-
|
|
201
|
+
if (!destination || typeof destination !== "object") fail$1("INVALID_DESTINATION");
|
|
202
|
+
if ("builtin" in destination) {
|
|
203
|
+
exactDefinition(destination, ["builtin"]);
|
|
204
|
+
if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail$1("INVALID_DESTINATION");
|
|
205
|
+
return { builtin: destination.builtin };
|
|
206
|
+
}
|
|
207
|
+
if (registry.get(destination.id) !== destination) fail$1("UNREGISTERED_DESTINATION_INSTANCE");
|
|
208
|
+
return { ref: destination.id };
|
|
209
|
+
}
|
|
210
|
+
const groups = input.groups.map((definition) => {
|
|
211
|
+
exactDefinition(definition, [
|
|
212
|
+
"type",
|
|
213
|
+
"id",
|
|
214
|
+
"name",
|
|
215
|
+
"algorithm",
|
|
216
|
+
"members",
|
|
217
|
+
"url",
|
|
218
|
+
"intervalSeconds",
|
|
219
|
+
"timeoutSeconds"
|
|
220
|
+
]);
|
|
221
|
+
if (definition.type !== "proxy-group") fail$1("INVALID_GROUP_DEFINITION");
|
|
222
|
+
if (!definition.algorithm || !["select", "surge-smart"].includes(definition.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
|
|
223
|
+
exactDefinition(definition.algorithm, ["type"]);
|
|
224
|
+
if (!Array.isArray(definition.members)) fail$1("INVALID_GROUP_DEFINITION");
|
|
225
|
+
const { id, url, intervalSeconds, timeoutSeconds } = definition;
|
|
226
|
+
return {
|
|
227
|
+
id,
|
|
228
|
+
type: definition.algorithm.type === "select" ? "select" : "smart",
|
|
229
|
+
members: definition.members.map(lower),
|
|
230
|
+
...url === void 0 ? {} : { url },
|
|
231
|
+
...intervalSeconds === void 0 ? {} : { intervalSeconds },
|
|
232
|
+
...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
|
|
233
|
+
};
|
|
234
|
+
});
|
|
235
|
+
const rules = input.routes.map((definition) => {
|
|
236
|
+
exactDefinition(definition, [
|
|
237
|
+
"type",
|
|
238
|
+
"when",
|
|
239
|
+
"to"
|
|
240
|
+
]);
|
|
241
|
+
if (definition.type !== "route") fail$1("INVALID_ROUTE_DEFINITION");
|
|
242
|
+
return {
|
|
243
|
+
when: definition.when,
|
|
244
|
+
then: lower(definition.to)
|
|
245
|
+
};
|
|
246
|
+
});
|
|
247
|
+
const { routes: _routes, groups: _groups, fallback, ...rest } = input;
|
|
248
|
+
return snapshot({
|
|
249
|
+
...rest,
|
|
250
|
+
names,
|
|
251
|
+
groups,
|
|
252
|
+
rules,
|
|
253
|
+
fallback: lower(fallback)
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
function condition(value) {
|
|
257
|
+
inspectDefinition(value);
|
|
258
|
+
return value;
|
|
259
|
+
}
|
|
260
|
+
function atom$2(type) {
|
|
261
|
+
return (value, options = {}) => {
|
|
262
|
+
inspectDefinition(options);
|
|
263
|
+
return condition({
|
|
264
|
+
...options,
|
|
265
|
+
type,
|
|
266
|
+
value
|
|
267
|
+
});
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
const surgeMatch = {
|
|
271
|
+
domain: atom$2("domain"),
|
|
272
|
+
domainSuffix: atom$2("domainSuffix"),
|
|
273
|
+
ipCidr: atom$2("ipCidr"),
|
|
274
|
+
ipCidr6: atom$2("ipCidr6"),
|
|
275
|
+
sourceIp: atom$2("sourceIp"),
|
|
276
|
+
processName: atom$2("processName"),
|
|
277
|
+
macAddress: atom$2("macAddress"),
|
|
278
|
+
network: (value, options = {}) => {
|
|
279
|
+
inspectDefinition(options);
|
|
280
|
+
return condition({
|
|
281
|
+
...options,
|
|
282
|
+
type: "network",
|
|
283
|
+
value
|
|
284
|
+
});
|
|
285
|
+
},
|
|
286
|
+
port: (from, to, options = {}) => {
|
|
287
|
+
inspectDefinition(options);
|
|
288
|
+
return condition({
|
|
289
|
+
...options,
|
|
290
|
+
type: "port",
|
|
291
|
+
from,
|
|
292
|
+
...to === void 0 ? {} : { to }
|
|
293
|
+
});
|
|
294
|
+
},
|
|
295
|
+
sourcePort: (from, to, options = {}) => {
|
|
296
|
+
inspectDefinition(options);
|
|
297
|
+
return condition({
|
|
298
|
+
...options,
|
|
299
|
+
type: "sourcePort",
|
|
300
|
+
from,
|
|
301
|
+
...to === void 0 ? {} : { to }
|
|
302
|
+
});
|
|
303
|
+
},
|
|
304
|
+
all: (conditions, options = {}) => {
|
|
305
|
+
inspectDefinition({
|
|
306
|
+
conditions,
|
|
307
|
+
options
|
|
308
|
+
});
|
|
309
|
+
return condition({
|
|
310
|
+
...options,
|
|
311
|
+
type: "all",
|
|
312
|
+
conditions: [...conditions]
|
|
313
|
+
});
|
|
314
|
+
},
|
|
315
|
+
any: (conditions, options = {}) => {
|
|
316
|
+
inspectDefinition({
|
|
317
|
+
conditions,
|
|
318
|
+
options
|
|
319
|
+
});
|
|
320
|
+
return condition({
|
|
321
|
+
...options,
|
|
322
|
+
type: "any",
|
|
323
|
+
conditions: [...conditions]
|
|
324
|
+
});
|
|
325
|
+
},
|
|
326
|
+
not: (value, options = {}) => {
|
|
327
|
+
inspectDefinition({
|
|
328
|
+
value,
|
|
329
|
+
options
|
|
330
|
+
});
|
|
331
|
+
return condition({
|
|
332
|
+
...options,
|
|
333
|
+
type: "not",
|
|
334
|
+
condition: value
|
|
335
|
+
});
|
|
336
|
+
},
|
|
337
|
+
ruleSet: (options) => {
|
|
338
|
+
inspectDefinition(options);
|
|
339
|
+
return condition({
|
|
340
|
+
...options,
|
|
341
|
+
type: "ruleSet"
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
//#endregion
|
|
346
|
+
//#region src/dns.ts
|
|
347
|
+
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;
|
|
348
|
+
function dohUrl(value) {
|
|
349
|
+
const url = new URL(value);
|
|
350
|
+
if (!/^https:\/\/[^/]+\//.test(value)) url.pathname = "/dns-query";
|
|
351
|
+
return url;
|
|
352
|
+
}
|
|
353
|
+
const server = z.string().max(2048).refine((value) => {
|
|
354
|
+
if (isIP(value) && !value.includes("%")) return true;
|
|
355
|
+
if (!value.startsWith("https://") || /[\s\p{C},()\\"'?#]/u.test(value)) return false;
|
|
356
|
+
try {
|
|
357
|
+
const url = new URL(value);
|
|
358
|
+
const authority = value.slice(8).split("/")[0];
|
|
359
|
+
const path = value.slice(8 + authority.length);
|
|
360
|
+
return !url.username && !url.password && !authority.endsWith(":") && !!url.hostname && (!path || url.pathname === path);
|
|
361
|
+
} catch {
|
|
362
|
+
return false;
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
const dnsRulesSchema = z.array(z.strictObject({
|
|
366
|
+
pattern: z.string().min(1).max(253).refine((value) => domain$2.test(value.startsWith("*.") ? value.slice(2) : value)),
|
|
367
|
+
server
|
|
368
|
+
})).max(2e3).superRefine((rules, ctx) => {
|
|
369
|
+
if (rules.length > 2e3 || rules.some((rule) => rule.pattern.length > 253 || rule.server.length > 2048)) return;
|
|
370
|
+
for (let i = 0; i < rules.length; i++) for (let j = 0; j < i; j++) {
|
|
371
|
+
const a = rules[i], b = rules[j];
|
|
372
|
+
const x = a.pattern.toLowerCase(), y = b.pattern.toLowerCase();
|
|
373
|
+
if (x === y || overlap(x, y) && a.server !== b.server) {
|
|
374
|
+
ctx.addIssue({
|
|
375
|
+
code: "custom",
|
|
376
|
+
message: "DNS_RULE_CONFLICT"
|
|
377
|
+
});
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
function overlap(a, b) {
|
|
383
|
+
const wildA = a.startsWith("*."), wildB = b.startsWith("*.");
|
|
384
|
+
if (wildA && wildB) return a.slice(1).endsWith(b.slice(1)) || b.slice(1).endsWith(a.slice(1));
|
|
385
|
+
return wildA ? b.endsWith(a.slice(1)) : wildB && a.endsWith(b.slice(1));
|
|
386
|
+
}
|
|
387
|
+
function dnsCondition(rule) {
|
|
388
|
+
const pattern = rule.pattern.toLowerCase();
|
|
389
|
+
return pattern.startsWith("*.") ? { domain_regex: [`^.+\\.${pattern.slice(2).replaceAll(".", "\\.")}$`] } : { domain: [pattern] };
|
|
390
|
+
}
|
|
391
|
+
//#endregion
|
|
392
|
+
//#region src/schema.ts
|
|
393
|
+
const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
|
|
394
|
+
const domain$1 = 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
|
+
const ip$1 = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
|
|
396
|
+
const cidr$1 = z.string().refine((x) => {
|
|
397
|
+
try {
|
|
398
|
+
const [address, prefix] = x.split("/");
|
|
399
|
+
if (!address || !prefix || !/^\d+$/.test(prefix) || isIP(address) === 0 || address.includes("%")) return false;
|
|
400
|
+
ipaddr.parseCIDR(x);
|
|
401
|
+
return true;
|
|
402
|
+
} catch {
|
|
403
|
+
return false;
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
const processNameSchema = z.string().min(1).max(255).regex(/^[^/\\*?[\],()\p{C}]+$/u);
|
|
407
|
+
const port$1 = z.number().int().min(1).max(65535);
|
|
408
|
+
const network = z.enum(["tcp", "udp"]);
|
|
409
|
+
const atom$1 = (type, value) => z.strictObject({
|
|
410
|
+
type: z.literal(type),
|
|
411
|
+
value
|
|
412
|
+
});
|
|
413
|
+
const remoteBase = {
|
|
414
|
+
type: z.literal("nativeRuleSet"),
|
|
415
|
+
id: idSchema,
|
|
416
|
+
url: z.string().max(2048).refine((value) => {
|
|
417
|
+
try {
|
|
418
|
+
const url = new URL(value);
|
|
419
|
+
return /^https?:\/\//.test(value) && ["http:", "https:"].includes(url.protocol) && !url.username && !url.password && !url.hash && !/[\s\p{C},()\\"']/u.test(value);
|
|
420
|
+
} catch {
|
|
421
|
+
return false;
|
|
422
|
+
}
|
|
423
|
+
})
|
|
86
424
|
};
|
|
87
425
|
const updateInterval = z.number().int().min(60).max(2147483647);
|
|
88
426
|
const nativeRuleSetSchema = z.discriminatedUnion("engine", [
|
|
@@ -90,7 +428,9 @@ const nativeRuleSetSchema = z.discriminatedUnion("engine", [
|
|
|
90
428
|
...remoteBase,
|
|
91
429
|
engine: z.literal("surge"),
|
|
92
430
|
format: z.enum(["rule-set", "domain-set"]),
|
|
93
|
-
intervalSeconds: updateInterval.optional()
|
|
431
|
+
intervalSeconds: updateInterval.optional(),
|
|
432
|
+
noResolve: z.boolean().optional(),
|
|
433
|
+
extendedMatching: z.boolean().optional()
|
|
94
434
|
}),
|
|
95
435
|
z.strictObject({
|
|
96
436
|
...remoteBase,
|
|
@@ -117,11 +457,23 @@ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
|
|
|
117
457
|
id: idSchema,
|
|
118
458
|
when: matchSchema
|
|
119
459
|
}),
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
460
|
+
z.strictObject({
|
|
461
|
+
type: z.literal("domain"),
|
|
462
|
+
value: domain$1,
|
|
463
|
+
extendedMatching: z.boolean().optional()
|
|
464
|
+
}),
|
|
465
|
+
z.strictObject({
|
|
466
|
+
type: z.literal("domainSuffix"),
|
|
467
|
+
value: domain$1,
|
|
468
|
+
extendedMatching: z.boolean().optional()
|
|
469
|
+
}),
|
|
470
|
+
z.strictObject({
|
|
471
|
+
type: z.literal("ipCidr"),
|
|
472
|
+
value: cidr$1,
|
|
473
|
+
noResolve: z.boolean().optional()
|
|
474
|
+
}),
|
|
475
|
+
atom$1("sourceIp", z.union([ip$1, cidr$1])),
|
|
476
|
+
atom$1("processName", processNameSchema),
|
|
125
477
|
z.strictObject({
|
|
126
478
|
type: z.literal("port"),
|
|
127
479
|
from: port$1,
|
|
@@ -212,7 +564,7 @@ const uuidNode = {
|
|
|
212
564
|
tls: tlsSchema.optional(),
|
|
213
565
|
transport: transportSchema.optional()
|
|
214
566
|
};
|
|
215
|
-
const surgeOptions = { blockQuic: z.enum([
|
|
567
|
+
const surgeOptions$1 = { blockQuic: z.enum([
|
|
216
568
|
"auto",
|
|
217
569
|
"on",
|
|
218
570
|
"off"
|
|
@@ -225,7 +577,7 @@ const nodeSchema = z.discriminatedUnion("type", [
|
|
|
225
577
|
serverName: domain$1.optional(),
|
|
226
578
|
skipCertVerify: z.boolean().optional(),
|
|
227
579
|
surge: z.strictObject({
|
|
228
|
-
...surgeOptions,
|
|
580
|
+
...surgeOptions$1,
|
|
229
581
|
udpRelay: z.literal(true).optional()
|
|
230
582
|
}).optional()
|
|
231
583
|
}),
|
|
@@ -236,7 +588,7 @@ const nodeSchema = z.discriminatedUnion("type", [
|
|
|
236
588
|
serverName: domain$1.optional(),
|
|
237
589
|
skipCertVerify: z.boolean().optional(),
|
|
238
590
|
surge: z.strictObject({
|
|
239
|
-
...surgeOptions,
|
|
591
|
+
...surgeOptions$1,
|
|
240
592
|
udpRelay: z.literal(true).optional()
|
|
241
593
|
}).optional()
|
|
242
594
|
}),
|
|
@@ -251,7 +603,7 @@ const nodeSchema = z.discriminatedUnion("type", [
|
|
|
251
603
|
...nodeBase,
|
|
252
604
|
type: z.literal("shadowsocks"),
|
|
253
605
|
surge: z.strictObject({
|
|
254
|
-
...surgeOptions,
|
|
606
|
+
...surgeOptions$1,
|
|
255
607
|
udpRelay: z.boolean().optional()
|
|
256
608
|
}).optional(),
|
|
257
609
|
method: z.enum([
|
|
@@ -264,7 +616,7 @@ const nodeSchema = z.discriminatedUnion("type", [
|
|
|
264
616
|
z.strictObject({
|
|
265
617
|
...uuidNode,
|
|
266
618
|
type: z.literal("vmess"),
|
|
267
|
-
surge: z.strictObject(surgeOptions).optional()
|
|
619
|
+
surge: z.strictObject(surgeOptions$1).optional()
|
|
268
620
|
}),
|
|
269
621
|
z.strictObject({
|
|
270
622
|
...uuidNode,
|
|
@@ -337,6 +689,8 @@ const groupSchema$1 = z.union([
|
|
|
337
689
|
const requestSchema = z.strictObject({
|
|
338
690
|
network,
|
|
339
691
|
domain: domain$1.optional(),
|
|
692
|
+
tlsSni: domain$1.optional(),
|
|
693
|
+
httpHost: domain$1.optional(),
|
|
340
694
|
ip: ip$1.optional(),
|
|
341
695
|
sourceIp: ip$1.optional(),
|
|
342
696
|
processName: processNameSchema.optional(),
|
|
@@ -652,13 +1006,16 @@ function evaluate(condition, request) {
|
|
|
652
1006
|
let present;
|
|
653
1007
|
switch (condition.type) {
|
|
654
1008
|
case "domain":
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
1009
|
+
case "domainSuffix": {
|
|
1010
|
+
const domains = condition.extendedMatching ? [
|
|
1011
|
+
request.domain,
|
|
1012
|
+
request.tlsSni,
|
|
1013
|
+
request.httpHost
|
|
1014
|
+
] : [request.domain];
|
|
1015
|
+
present = domains.some((value) => value !== void 0);
|
|
1016
|
+
matched = domains.some((value) => value !== void 0 && (value === condition.value || condition.type === "domainSuffix" && value.endsWith(`.${condition.value}`)));
|
|
661
1017
|
break;
|
|
1018
|
+
}
|
|
662
1019
|
case "ipCidr":
|
|
663
1020
|
present = request.ip !== void 0;
|
|
664
1021
|
matched = inCidr(request.ip, condition.value);
|
|
@@ -962,7 +1319,7 @@ function conditionText$1(condition) {
|
|
|
962
1319
|
case "not": return `NOT,((${conditionText$1(condition.condition)}))`;
|
|
963
1320
|
case "domain": return `DOMAIN,${condition.value}`;
|
|
964
1321
|
case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
|
|
965
|
-
case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
|
|
1322
|
+
case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}${condition.noResolve !== false ? ",no-resolve" : ""}`;
|
|
966
1323
|
case "processName": return `PROCESS-NAME,${condition.value}`;
|
|
967
1324
|
case "sourceIp": return `SRC-IP-CIDR,${condition.value.includes("/") ? condition.value : `${condition.value}/${condition.value.includes(":") ? 128 : 32}`}`;
|
|
968
1325
|
case "network": return `NETWORK,${condition.value}`;
|
|
@@ -976,7 +1333,7 @@ function clashConfig(plan, secret) {
|
|
|
976
1333
|
const config = {
|
|
977
1334
|
proxies: program.nodes.map((node) => clashProxy(node, target.engine, secret)),
|
|
978
1335
|
"proxy-groups": program.groups.map((g) => clashGroup(g)),
|
|
979
|
-
rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText$1(rule.when).replace(/,no-resolve$/, "")},${policy$2(rule.then)},no-resolve` : `${conditionText$1(rule.when)},${policy$2(rule.then)}`), `MATCH,${policy$2(program.fallback)}`]
|
|
1336
|
+
rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText$1(rule.when).replace(/,no-resolve$/, "")},${policy$2(rule.then)}${rule.when.noResolve !== false ? ",no-resolve" : ""}` : `${conditionText$1(rule.when)},${policy$2(rule.then)}`), `MATCH,${policy$2(program.fallback)}`]
|
|
980
1337
|
};
|
|
981
1338
|
if (plan.nativeRuleSets.length) config["rule-providers"] = Object.fromEntries(plan.nativeRuleSets.map((r) => [r.id, {
|
|
982
1339
|
type: "http",
|
|
@@ -1452,6 +1809,13 @@ function compile(input) {
|
|
|
1452
1809
|
if (target.engine === "surge") {
|
|
1453
1810
|
for (const rule of rules) if (logicalDepth(rule.when) > 10) error("LOGICAL_DEPTH", rule.id, "Surge 逻辑条件最多嵌套 10 层", target.id);
|
|
1454
1811
|
}
|
|
1812
|
+
const checkOptions = (condition) => {
|
|
1813
|
+
if ("extendedMatching" in condition && condition.extendedMatching === true && target.engine !== "surge" || condition.type === "ipCidr" && condition.noResolve !== void 0 && target.engine === "sing-box") error("MATCH_OPTION_UNSUPPORTED", path, "目标无法等价实现显式匹配选项", target.id);
|
|
1814
|
+
if (condition.type === "all" || condition.type === "any") condition.conditions.forEach(checkOptions);
|
|
1815
|
+
else if (condition.type === "not") checkOptions(condition.condition);
|
|
1816
|
+
else if (condition.type === "ruleSet") checkOptions(condition.when);
|
|
1817
|
+
};
|
|
1818
|
+
rules.forEach((rule) => checkOptions(rule.when));
|
|
1455
1819
|
const nativeRuleSets = collectNativeRuleSets(rules, target, diagnostics);
|
|
1456
1820
|
for (const resource of nativeRuleSets) if (!descriptor.nativeRuleSets.includes(resource.format)) error("RULESET_UNSUPPORTED", `${path}.ruleSets.${resource.id}`, "精确目标不支持此原生规则资源格式", target.id);
|
|
1457
1821
|
plans.push({
|
|
@@ -1697,50 +2061,51 @@ const groupSchema = z.strictObject({
|
|
|
1697
2061
|
intervalSeconds: z.number().int().positive().max(2147483647).optional(),
|
|
1698
2062
|
timeoutSeconds: z.number().int().positive().max(3600).optional()
|
|
1699
2063
|
});
|
|
1700
|
-
const options = {
|
|
2064
|
+
const options$1 = {
|
|
1701
2065
|
noResolve: z.boolean().optional(),
|
|
1702
2066
|
extendedMatching: z.boolean().optional()
|
|
1703
2067
|
};
|
|
1704
|
-
const atom
|
|
2068
|
+
const atom = (type, value) => z.strictObject({
|
|
1705
2069
|
type: z.literal(type),
|
|
1706
2070
|
value,
|
|
1707
|
-
...options
|
|
2071
|
+
...options$1
|
|
1708
2072
|
});
|
|
1709
2073
|
const conditionSchema = z.lazy(() => z.union([
|
|
1710
|
-
atom
|
|
1711
|
-
atom
|
|
1712
|
-
atom
|
|
1713
|
-
atom
|
|
1714
|
-
atom
|
|
1715
|
-
atom
|
|
1716
|
-
atom
|
|
2074
|
+
atom("domain", domain),
|
|
2075
|
+
atom("domainSuffix", domain),
|
|
2076
|
+
atom("ipCidr", cidr(4)),
|
|
2077
|
+
atom("ipCidr6", cidr(6)),
|
|
2078
|
+
atom("sourceIp", z.union([ip, cidr()])),
|
|
2079
|
+
atom("processName", safe),
|
|
2080
|
+
atom("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
|
|
1717
2081
|
z.strictObject({
|
|
1718
2082
|
type: z.enum(["port", "sourcePort"]),
|
|
1719
2083
|
from: port,
|
|
1720
2084
|
to: port.optional(),
|
|
1721
|
-
...options
|
|
2085
|
+
...options$1
|
|
1722
2086
|
}).refine((v) => v.to === void 0 || v.to >= v.from),
|
|
1723
2087
|
z.strictObject({
|
|
1724
2088
|
type: z.literal("network"),
|
|
1725
2089
|
value: z.enum(["tcp", "udp"]),
|
|
1726
|
-
...options
|
|
2090
|
+
...options$1
|
|
1727
2091
|
}),
|
|
1728
2092
|
z.strictObject({
|
|
1729
2093
|
type: z.enum(["all", "any"]),
|
|
1730
2094
|
conditions: z.array(conditionSchema).min(2).max(100),
|
|
1731
|
-
...options
|
|
2095
|
+
...options$1
|
|
1732
2096
|
}),
|
|
1733
2097
|
z.strictObject({
|
|
1734
2098
|
type: z.literal("not"),
|
|
1735
2099
|
condition: conditionSchema,
|
|
1736
|
-
...options
|
|
2100
|
+
...options$1
|
|
1737
2101
|
}),
|
|
1738
2102
|
z.strictObject({
|
|
1739
2103
|
type: z.literal("ruleSet"),
|
|
1740
2104
|
format: z.enum(["rule-set", "domain-set"]),
|
|
1741
2105
|
url: url.optional(),
|
|
1742
2106
|
builtin: z.enum(["LAN", "SYSTEM"]).optional(),
|
|
1743
|
-
|
|
2107
|
+
intervalSeconds: z.number().int().min(60).max(2147483647).optional(),
|
|
2108
|
+
...options$1
|
|
1744
2109
|
}).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
|
|
1745
2110
|
]));
|
|
1746
2111
|
const managedSchema = z.strictObject({
|
|
@@ -1777,574 +2142,243 @@ function compileSurgeProfile(input) {
|
|
|
1777
2142
|
path: "$",
|
|
1778
2143
|
message: code
|
|
1779
2144
|
});
|
|
1780
|
-
const failure = () => deepFreeze({
|
|
1781
|
-
ok: false,
|
|
1782
|
-
artifactKind: "surge-profile",
|
|
1783
|
-
diagnostics,
|
|
1784
|
-
bindings: []
|
|
1785
|
-
});
|
|
1786
|
-
try {
|
|
1787
|
-
assertData(input);
|
|
1788
|
-
} catch {
|
|
1789
|
-
error("INVALID_INPUT_GRAPH");
|
|
1790
|
-
return failure();
|
|
1791
|
-
}
|
|
1792
|
-
const parsed = inputSchema.safeParse(input);
|
|
1793
|
-
if (!parsed.success) {
|
|
1794
|
-
error("INVALID_SCHEMA");
|
|
1795
|
-
return failure();
|
|
1796
|
-
}
|
|
1797
|
-
if (parsed.data.general) {
|
|
1798
|
-
const general = parsed.data.general;
|
|
1799
|
-
parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
|
|
1800
|
-
}
|
|
1801
|
-
const p = deepFreeze(parsed.data);
|
|
1802
|
-
if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
|
|
1803
|
-
const tunnels = p.tunnels ?? [];
|
|
1804
|
-
const resources = [
|
|
1805
|
-
...p.nodes,
|
|
1806
|
-
...tunnels,
|
|
1807
|
-
...p.groups
|
|
1808
|
-
];
|
|
1809
|
-
if (resources.length > 1e3) error("RESOURCE_LIMIT");
|
|
1810
|
-
const ids = new Set(resources.map((r) => r.id));
|
|
1811
|
-
if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
|
|
1812
|
-
if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
|
|
1813
|
-
const bindings = resources.map((r) => ({
|
|
1814
|
-
id: r.id,
|
|
1815
|
-
nativeName: p.names?.[r.id] ?? r.id
|
|
1816
|
-
}));
|
|
1817
|
-
if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
|
|
1818
|
-
if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
|
|
1819
|
-
if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
|
|
1820
|
-
if (p.target.platform === "ios" && [
|
|
1821
|
-
"bypass-system",
|
|
1822
|
-
"replica",
|
|
1823
|
-
"tls-provider",
|
|
1824
|
-
"bypass-tun",
|
|
1825
|
-
"external-controller-access"
|
|
1826
|
-
].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
|
|
1827
|
-
if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
|
|
1828
|
-
const checkPolicy = (action) => {
|
|
1829
|
-
if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
|
|
1830
|
-
};
|
|
1831
|
-
const edges = new Map(resources.map((r) => [r.id, []]));
|
|
1832
|
-
const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
|
|
1833
|
-
for (const node of p.nodes) {
|
|
1834
|
-
if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
|
|
1835
|
-
validateProxyOptions(node, {
|
|
1836
|
-
id: "profile",
|
|
1837
|
-
engine: "surge"
|
|
1838
|
-
}, diagnostics);
|
|
1839
|
-
if (node.via) {
|
|
1840
|
-
checkPolicy({ ref: node.via });
|
|
1841
|
-
edges.get(node.id).push(node.via);
|
|
1842
|
-
}
|
|
1843
|
-
}
|
|
1844
|
-
for (const group of p.groups) {
|
|
1845
|
-
if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
|
|
1846
|
-
for (const member of group.members) {
|
|
1847
|
-
checkPolicy(member);
|
|
1848
|
-
if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
|
|
1849
|
-
if ("ref" in member) edges.get(group.id).push(member.ref);
|
|
1850
|
-
}
|
|
1851
|
-
}
|
|
1852
|
-
const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
|
|
1853
|
-
const visit = (id) => {
|
|
1854
|
-
if (active.has(id)) {
|
|
1855
|
-
error("RESOURCE_CYCLE");
|
|
1856
|
-
return;
|
|
1857
|
-
}
|
|
1858
|
-
if (visited.has(id)) return;
|
|
1859
|
-
active.add(id);
|
|
1860
|
-
for (const next of edges.get(id) ?? []) visit(next);
|
|
1861
|
-
active.delete(id);
|
|
1862
|
-
visited.add(id);
|
|
1863
|
-
};
|
|
1864
|
-
if (resources.length <= 1e3) for (const id of ids) visit(id);
|
|
1865
|
-
const formats = /* @__PURE__ */ new Map();
|
|
1866
|
-
const checkCondition = (c, depth) => {
|
|
1867
|
-
if (depth > 10) {
|
|
1868
|
-
error("LOGICAL_DEPTH_EXCEEDED");
|
|
1869
|
-
return;
|
|
1870
|
-
}
|
|
1871
|
-
if (c.noResolve !== void 0 && ![
|
|
1872
|
-
"ipCidr",
|
|
1873
|
-
"ipCidr6",
|
|
1874
|
-
"ruleSet"
|
|
1875
|
-
].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
|
|
1876
|
-
if (c.extendedMatching !== void 0 && ![
|
|
1877
|
-
"domain",
|
|
1878
|
-
"domainSuffix",
|
|
1879
|
-
"ruleSet"
|
|
1880
|
-
].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
|
|
1881
|
-
if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
|
|
1882
|
-
if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
|
|
1883
|
-
if (c.type === "not") checkCondition(c.condition, depth + 1);
|
|
1884
|
-
if (c.type === "ruleSet") {
|
|
1885
|
-
if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
|
|
1886
|
-
if (c.url) {
|
|
1887
|
-
if (formats.has(c.url) && formats.get(c.url) !== c.format) error("RULESET_FORMAT_CONFLICT");
|
|
1888
|
-
formats.set(c.url, c.format);
|
|
1889
|
-
}
|
|
1890
|
-
}
|
|
1891
|
-
};
|
|
1892
|
-
for (const rule of p.rules) {
|
|
1893
|
-
checkPolicy(rule.then);
|
|
1894
|
-
checkCondition(rule.when, 0);
|
|
1895
|
-
}
|
|
1896
|
-
checkPolicy(p.fallback);
|
|
1897
|
-
if (diagnostics.some((d) => d.severity === "error")) return failure();
|
|
1898
|
-
if (formats.size) diagnostics.push({
|
|
1899
|
-
severity: "warning",
|
|
1900
|
-
code: "EXTERNAL_RULESET_UNVERIFIED",
|
|
1901
|
-
path: "rules",
|
|
1902
|
-
message: "External rule sets are resolved by the client, not by the compiler."
|
|
1903
|
-
});
|
|
1904
|
-
const result = deepFreeze({
|
|
1905
|
-
ok: true,
|
|
1906
|
-
artifactKind: "surge-profile",
|
|
1907
|
-
diagnostics,
|
|
1908
|
-
bindings
|
|
1909
|
-
});
|
|
1910
|
-
plans.set(result, p);
|
|
1911
|
-
return result;
|
|
1912
|
-
}
|
|
1913
|
-
function conditionOptions(c) {
|
|
1914
|
-
return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
|
|
1915
|
-
}
|
|
1916
|
-
function conditionText(c) {
|
|
1917
|
-
switch (c.type) {
|
|
1918
|
-
case "all":
|
|
1919
|
-
case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
|
|
1920
|
-
case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
|
|
1921
|
-
case "port":
|
|
1922
|
-
case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
|
|
1923
|
-
case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
|
|
1924
|
-
case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
|
|
1925
|
-
default: return `${{
|
|
1926
|
-
domain: "DOMAIN",
|
|
1927
|
-
domainSuffix: "DOMAIN-SUFFIX",
|
|
1928
|
-
ipCidr: "IP-CIDR",
|
|
1929
|
-
ipCidr6: "IP-CIDR6",
|
|
1930
|
-
sourceIp: "SRC-IP",
|
|
1931
|
-
processName: "PROCESS-NAME",
|
|
1932
|
-
macAddress: "MAC-ADDRESS"
|
|
1933
|
-
}[c.type]},${c.value}`;
|
|
1934
|
-
}
|
|
1935
|
-
}
|
|
1936
|
-
function renderProfile(compilation, read) {
|
|
1937
|
-
const p = plans.get(compilation);
|
|
1938
|
-
if (!p) throw new RenderError("COMPILATION_FAILED");
|
|
1939
|
-
const name = (id) => p.names?.[id] ?? id;
|
|
1940
|
-
const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
|
|
1941
|
-
const credential = (token, kind) => {
|
|
1942
|
-
const value = read(token);
|
|
1943
|
-
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");
|
|
1944
|
-
return value;
|
|
1945
|
-
};
|
|
1946
|
-
const lines = [];
|
|
1947
|
-
if (p.managed) {
|
|
1948
|
-
const address = new URL(p.managed.url);
|
|
1949
|
-
for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
|
|
1950
|
-
lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
|
|
1951
|
-
}
|
|
1952
|
-
lines.push("[General]");
|
|
1953
|
-
for (const [k, v] of Object.entries(p.general ?? {})) {
|
|
1954
|
-
const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
|
|
1955
|
-
lines.push(`${k} = ${value}`);
|
|
1956
|
-
}
|
|
1957
|
-
lines.push("", "[Host]");
|
|
1958
|
-
for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
|
|
1959
|
-
lines.push("", "[Proxy]");
|
|
1960
|
-
for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
|
|
1961
|
-
for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
|
|
1962
|
-
for (const t of p.tunnels ?? []) {
|
|
1963
|
-
lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
|
|
1964
|
-
if (t.type === "tailscale") {
|
|
1965
|
-
lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
|
|
1966
|
-
if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
|
|
1967
|
-
if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
|
|
1968
|
-
if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
|
|
1969
|
-
} else {
|
|
1970
|
-
lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
|
|
1971
|
-
if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
|
|
1972
|
-
if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
|
|
1973
|
-
for (const peer of t.peers) {
|
|
1974
|
-
const values = [`public-key = ${peer.publicKey}`];
|
|
1975
|
-
if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
|
|
1976
|
-
values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
|
|
1977
|
-
if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
|
|
1978
|
-
lines.push(`peer = (${values.join(", ")})`);
|
|
1979
|
-
}
|
|
1980
|
-
}
|
|
1981
|
-
}
|
|
1982
|
-
lines.push("", "[Proxy Group]");
|
|
1983
|
-
for (const g of p.groups) lines.push(`${name(g.id)} = ${[
|
|
1984
|
-
g.type,
|
|
1985
|
-
...g.members.map(action),
|
|
1986
|
-
...g.url ? [`url=${g.url}`] : [],
|
|
1987
|
-
...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
|
|
1988
|
-
...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
|
|
1989
|
-
].join(", ")}`);
|
|
1990
|
-
lines.push("", "[Rule]");
|
|
1991
|
-
for (const r of p.rules) lines.push([
|
|
1992
|
-
conditionText(r.when),
|
|
1993
|
-
action(r.then),
|
|
1994
|
-
...conditionOptions(r.when)
|
|
1995
|
-
].join(","));
|
|
1996
|
-
lines.push(`FINAL,${action(p.fallback)}`, "");
|
|
1997
|
-
return deepFreeze({
|
|
1998
|
-
artifactKind: "surge-profile",
|
|
1999
|
-
content: lines.join("\n")
|
|
2000
|
-
});
|
|
2001
|
-
}
|
|
2002
|
-
function renderSurgeProfile(compilation, resolveSecret) {
|
|
2003
|
-
return renderProfile(compilation, secretReader(resolveSecret));
|
|
2004
|
-
}
|
|
2005
|
-
function renderSurgeProfiles(compilations, resolveSecret) {
|
|
2006
|
-
if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
|
|
2007
|
-
const read = secretReader(resolveSecret);
|
|
2008
|
-
return deepFreeze(compilations.map((c) => renderProfile(c, read)));
|
|
2009
|
-
}
|
|
2010
|
-
//#endregion
|
|
2011
|
-
//#region src/surge-definitions.ts
|
|
2012
|
-
var ProfileDefinitionError = class extends Error {
|
|
2013
|
-
code;
|
|
2014
|
-
constructor(code) {
|
|
2015
|
-
super(code);
|
|
2016
|
-
this.code = code;
|
|
2017
|
-
this.name = "ProfileDefinitionError";
|
|
2018
|
-
}
|
|
2019
|
-
};
|
|
2020
|
-
const fail$1 = (code) => {
|
|
2021
|
-
throw new ProfileDefinitionError(code);
|
|
2022
|
-
};
|
|
2023
|
-
/** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
|
|
2024
|
-
function inspectDefinition(root) {
|
|
2025
|
-
let edges = 0;
|
|
2026
|
-
let objects = 0;
|
|
2027
|
-
const visiting = /* @__PURE__ */ new Set();
|
|
2028
|
-
const heights = /* @__PURE__ */ new Map();
|
|
2029
|
-
function visit(value, depth) {
|
|
2030
|
-
if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
|
|
2031
|
-
if (value === null || typeof value !== "object") {
|
|
2032
|
-
if (![
|
|
2033
|
-
"undefined",
|
|
2034
|
-
"string",
|
|
2035
|
-
"number",
|
|
2036
|
-
"boolean"
|
|
2037
|
-
].includes(typeof value) && value !== null) fail$1("DEFINITION_NOT_DATA");
|
|
2038
|
-
return 0;
|
|
2039
|
-
}
|
|
2040
|
-
if (visiting.has(value)) fail$1("DEFINITION_CYCLE");
|
|
2041
|
-
const cached = heights.get(value);
|
|
2042
|
-
if (cached !== void 0) {
|
|
2043
|
-
if (depth + cached > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
|
|
2044
|
-
return cached;
|
|
2045
|
-
}
|
|
2046
|
-
if (++objects > 2e4) fail$1("DEFINITION_OBJECT_BUDGET_EXCEEDED");
|
|
2047
|
-
const proto = Object.getPrototypeOf(value);
|
|
2048
|
-
if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail$1("DEFINITION_NOT_DATA");
|
|
2049
|
-
if (Array.isArray(value) && value.length > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
|
|
2050
|
-
visiting.add(value);
|
|
2051
|
-
let height = 0;
|
|
2052
|
-
for (const key of Reflect.ownKeys(value)) {
|
|
2053
|
-
if (++edges > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
|
|
2054
|
-
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
2055
|
-
if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail$1("DEFINITION_NOT_DATA");
|
|
2056
|
-
height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
|
|
2145
|
+
const failure = () => deepFreeze({
|
|
2146
|
+
ok: false,
|
|
2147
|
+
artifactKind: "surge-profile",
|
|
2148
|
+
diagnostics,
|
|
2149
|
+
bindings: []
|
|
2150
|
+
});
|
|
2151
|
+
try {
|
|
2152
|
+
assertData(input);
|
|
2153
|
+
} catch {
|
|
2154
|
+
error("INVALID_INPUT_GRAPH");
|
|
2155
|
+
return failure();
|
|
2156
|
+
}
|
|
2157
|
+
const parsed = inputSchema.safeParse(input);
|
|
2158
|
+
if (!parsed.success) {
|
|
2159
|
+
error("INVALID_SCHEMA");
|
|
2160
|
+
return failure();
|
|
2161
|
+
}
|
|
2162
|
+
if (parsed.data.general) {
|
|
2163
|
+
const general = parsed.data.general;
|
|
2164
|
+
parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
|
|
2165
|
+
}
|
|
2166
|
+
const p = deepFreeze(parsed.data);
|
|
2167
|
+
if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
|
|
2168
|
+
const tunnels = p.tunnels ?? [];
|
|
2169
|
+
const resources = [
|
|
2170
|
+
...p.nodes,
|
|
2171
|
+
...tunnels,
|
|
2172
|
+
...p.groups
|
|
2173
|
+
];
|
|
2174
|
+
if (resources.length > 1e3) error("RESOURCE_LIMIT");
|
|
2175
|
+
const ids = new Set(resources.map((r) => r.id));
|
|
2176
|
+
if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
|
|
2177
|
+
if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
|
|
2178
|
+
const bindings = resources.map((r) => ({
|
|
2179
|
+
id: r.id,
|
|
2180
|
+
nativeName: p.names?.[r.id] ?? r.id
|
|
2181
|
+
}));
|
|
2182
|
+
if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
|
|
2183
|
+
if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
|
|
2184
|
+
if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
|
|
2185
|
+
if (p.target.platform === "ios" && [
|
|
2186
|
+
"bypass-system",
|
|
2187
|
+
"replica",
|
|
2188
|
+
"tls-provider",
|
|
2189
|
+
"bypass-tun",
|
|
2190
|
+
"external-controller-access"
|
|
2191
|
+
].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
|
|
2192
|
+
if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
|
|
2193
|
+
const checkPolicy = (action) => {
|
|
2194
|
+
if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
|
|
2195
|
+
};
|
|
2196
|
+
const edges = new Map(resources.map((r) => [r.id, []]));
|
|
2197
|
+
const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
|
|
2198
|
+
for (const node of p.nodes) {
|
|
2199
|
+
if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
|
|
2200
|
+
validateProxyOptions(node, {
|
|
2201
|
+
id: "profile",
|
|
2202
|
+
engine: "surge"
|
|
2203
|
+
}, diagnostics);
|
|
2204
|
+
if (node.via) {
|
|
2205
|
+
checkPolicy({ ref: node.via });
|
|
2206
|
+
edges.get(node.id).push(node.via);
|
|
2057
2207
|
}
|
|
2058
|
-
visiting.delete(value);
|
|
2059
|
-
heights.set(value, height);
|
|
2060
|
-
return height;
|
|
2061
2208
|
}
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
if (--remaining < 0) fail$1("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
|
|
2069
|
-
if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
|
|
2070
|
-
if (value === null || typeof value !== "object") return value;
|
|
2071
|
-
if (Array.isArray(value)) {
|
|
2072
|
-
const output = [];
|
|
2073
|
-
for (const item of value) output.push(copy(item, depth + 1));
|
|
2074
|
-
return output;
|
|
2209
|
+
for (const group of p.groups) {
|
|
2210
|
+
if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
|
|
2211
|
+
for (const member of group.members) {
|
|
2212
|
+
checkPolicy(member);
|
|
2213
|
+
if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
|
|
2214
|
+
if ("ref" in member) edges.get(group.id).push(member.ref);
|
|
2075
2215
|
}
|
|
2076
|
-
const output = {};
|
|
2077
|
-
for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
|
|
2078
|
-
value: copy(item, depth + 1),
|
|
2079
|
-
enumerable: true,
|
|
2080
|
-
writable: true,
|
|
2081
|
-
configurable: true
|
|
2082
|
-
});
|
|
2083
|
-
return output;
|
|
2084
2216
|
}
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
}
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
direct: Object.freeze({ builtin: "DIRECT" }),
|
|
2097
|
-
reject: Object.freeze({ builtin: "REJECT" }),
|
|
2098
|
-
rejectDrop: Object.freeze({ builtin: "REJECT-DROP" }),
|
|
2099
|
-
rejectNoDrop: Object.freeze({ builtin: "REJECT-NO-DROP" }),
|
|
2100
|
-
rejectTinyGif: Object.freeze({ builtin: "REJECT-TINYGIF" })
|
|
2101
|
-
};
|
|
2102
|
-
function defineProxyGroup(input) {
|
|
2103
|
-
inspectDefinition(input);
|
|
2104
|
-
exactDefinition(input, [
|
|
2105
|
-
"id",
|
|
2106
|
-
"name",
|
|
2107
|
-
"algorithm",
|
|
2108
|
-
"members",
|
|
2109
|
-
"url",
|
|
2110
|
-
"intervalSeconds",
|
|
2111
|
-
"timeoutSeconds"
|
|
2112
|
-
]);
|
|
2113
|
-
if (!input.algorithm || ![
|
|
2114
|
-
"select",
|
|
2115
|
-
"surge-smart",
|
|
2116
|
-
"urltest"
|
|
2117
|
-
].includes(input.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
|
|
2118
|
-
exactDefinition(input.algorithm, input.algorithm.type === "urltest" ? [
|
|
2119
|
-
"type",
|
|
2120
|
-
"url",
|
|
2121
|
-
"intervalSeconds",
|
|
2122
|
-
"toleranceMs"
|
|
2123
|
-
] : ["type"]);
|
|
2124
|
-
if (!Array.isArray(input.members)) fail$1("INVALID_GROUP_DEFINITION");
|
|
2125
|
-
return {
|
|
2126
|
-
...input,
|
|
2127
|
-
type: "proxy-group",
|
|
2128
|
-
algorithm: { ...input.algorithm },
|
|
2129
|
-
members: [...input.members]
|
|
2217
|
+
const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
|
|
2218
|
+
const visit = (id) => {
|
|
2219
|
+
if (active.has(id)) {
|
|
2220
|
+
error("RESOURCE_CYCLE");
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
if (visited.has(id)) return;
|
|
2224
|
+
active.add(id);
|
|
2225
|
+
for (const next of edges.get(id) ?? []) visit(next);
|
|
2226
|
+
active.delete(id);
|
|
2227
|
+
visited.add(id);
|
|
2130
2228
|
};
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2229
|
+
if (resources.length <= 1e3) for (const id of ids) visit(id);
|
|
2230
|
+
const formats = /* @__PURE__ */ new Map();
|
|
2231
|
+
const checkCondition = (c, depth) => {
|
|
2232
|
+
if (depth > 10) {
|
|
2233
|
+
error("LOGICAL_DEPTH_EXCEEDED");
|
|
2234
|
+
return;
|
|
2235
|
+
}
|
|
2236
|
+
if (c.noResolve !== void 0 && ![
|
|
2237
|
+
"ipCidr",
|
|
2238
|
+
"ipCidr6",
|
|
2239
|
+
"ruleSet"
|
|
2240
|
+
].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
|
|
2241
|
+
if (c.extendedMatching !== void 0 && ![
|
|
2242
|
+
"domain",
|
|
2243
|
+
"domainSuffix",
|
|
2244
|
+
"ruleSet"
|
|
2245
|
+
].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
|
|
2246
|
+
if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
|
|
2247
|
+
if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
|
|
2248
|
+
if (c.type === "not") checkCondition(c.condition, depth + 1);
|
|
2249
|
+
if (c.type === "ruleSet") {
|
|
2250
|
+
if (c.intervalSeconds !== void 0 && (depth > 0 || c.builtin)) error("RULESET_COMPOSITION_UNSUPPORTED");
|
|
2251
|
+
if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
|
|
2252
|
+
if (c.url) {
|
|
2253
|
+
const key = new URL(c.url).href;
|
|
2254
|
+
const settings = `${c.format}:${c.intervalSeconds ?? 86400}`;
|
|
2255
|
+
if (formats.has(key) && formats.get(key) !== settings) error("RULESET_FORMAT_CONFLICT");
|
|
2256
|
+
formats.set(key, settings);
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2138
2259
|
};
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
function selectProxies(nodes, query = {}) {
|
|
2151
|
-
inspectDefinition({
|
|
2152
|
-
nodes,
|
|
2153
|
-
query
|
|
2260
|
+
for (const rule of p.rules) {
|
|
2261
|
+
checkPolicy(rule.then);
|
|
2262
|
+
checkCondition(rule.when, 0);
|
|
2263
|
+
}
|
|
2264
|
+
checkPolicy(p.fallback);
|
|
2265
|
+
if (diagnostics.some((d) => d.severity === "error")) return failure();
|
|
2266
|
+
if (formats.size) diagnostics.push({
|
|
2267
|
+
severity: "warning",
|
|
2268
|
+
code: "EXTERNAL_RULESET_UNVERIFIED",
|
|
2269
|
+
path: "rules",
|
|
2270
|
+
message: "External rule sets are resolved by the client, not by the compiler."
|
|
2154
2271
|
});
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
"
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
return nodes.filter((node) => (!query.ids || query.ids.includes(node.id)) && (!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))));
|
|
2272
|
+
const result = deepFreeze({
|
|
2273
|
+
ok: true,
|
|
2274
|
+
artifactKind: "surge-profile",
|
|
2275
|
+
diagnostics,
|
|
2276
|
+
bindings
|
|
2277
|
+
});
|
|
2278
|
+
plans.set(result, p);
|
|
2279
|
+
return result;
|
|
2164
2280
|
}
|
|
2165
|
-
function
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
"
|
|
2169
|
-
"
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
"
|
|
2175
|
-
"
|
|
2176
|
-
"
|
|
2177
|
-
"
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
|
|
2191
|
-
if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail$1("GROUP_NAME_CONFLICT");
|
|
2192
|
-
Object.defineProperty(names, resource.id, {
|
|
2193
|
-
value: names[resource.id] ?? name,
|
|
2194
|
-
enumerable: true,
|
|
2195
|
-
configurable: true,
|
|
2196
|
-
writable: true
|
|
2197
|
-
});
|
|
2281
|
+
function conditionOptions(c) {
|
|
2282
|
+
return [
|
|
2283
|
+
...c.noResolve ? ["no-resolve"] : [],
|
|
2284
|
+
...c.extendedMatching ? ["extended-matching"] : [],
|
|
2285
|
+
...c.type === "ruleSet" && c.intervalSeconds !== void 0 ? [`update-interval=${c.intervalSeconds}`] : []
|
|
2286
|
+
];
|
|
2287
|
+
}
|
|
2288
|
+
function conditionText(c) {
|
|
2289
|
+
switch (c.type) {
|
|
2290
|
+
case "all":
|
|
2291
|
+
case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
|
|
2292
|
+
case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
|
|
2293
|
+
case "port":
|
|
2294
|
+
case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
|
|
2295
|
+
case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
|
|
2296
|
+
case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
|
|
2297
|
+
default: return `${{
|
|
2298
|
+
domain: "DOMAIN",
|
|
2299
|
+
domainSuffix: "DOMAIN-SUFFIX",
|
|
2300
|
+
ipCidr: "IP-CIDR",
|
|
2301
|
+
ipCidr6: "IP-CIDR6",
|
|
2302
|
+
sourceIp: "SRC-IP",
|
|
2303
|
+
processName: "PROCESS-NAME",
|
|
2304
|
+
macAddress: "MAC-ADDRESS"
|
|
2305
|
+
}[c.type]},${c.value}`;
|
|
2198
2306
|
}
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2307
|
+
}
|
|
2308
|
+
function renderProfile(compilation, read) {
|
|
2309
|
+
const p = plans.get(compilation);
|
|
2310
|
+
if (!p) throw new RenderError("COMPILATION_FAILED");
|
|
2311
|
+
const name = (id) => p.names?.[id] ?? id;
|
|
2312
|
+
const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
|
|
2313
|
+
const credential = (token, kind) => {
|
|
2314
|
+
const value = read(token);
|
|
2315
|
+
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");
|
|
2316
|
+
return value;
|
|
2317
|
+
};
|
|
2318
|
+
const lines = [];
|
|
2319
|
+
if (p.managed) {
|
|
2320
|
+
const address = new URL(p.managed.url);
|
|
2321
|
+
for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
|
|
2322
|
+
lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
|
|
2323
|
+
}
|
|
2324
|
+
lines.push("[General]");
|
|
2325
|
+
for (const [k, v] of Object.entries(p.general ?? {})) {
|
|
2326
|
+
const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
|
|
2327
|
+
lines.push(`${k} = ${value}`);
|
|
2328
|
+
}
|
|
2329
|
+
lines.push("", "[Host]");
|
|
2330
|
+
for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
|
|
2331
|
+
lines.push("", "[Proxy]");
|
|
2332
|
+
for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
|
|
2333
|
+
for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
|
|
2334
|
+
for (const t of p.tunnels ?? []) {
|
|
2335
|
+
lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
|
|
2336
|
+
if (t.type === "tailscale") {
|
|
2337
|
+
lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
|
|
2338
|
+
if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
|
|
2339
|
+
if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
|
|
2340
|
+
if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
|
|
2341
|
+
} else {
|
|
2342
|
+
lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
|
|
2343
|
+
if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
|
|
2344
|
+
if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
|
|
2345
|
+
for (const peer of t.peers) {
|
|
2346
|
+
const values = [`public-key = ${peer.publicKey}`];
|
|
2347
|
+
if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
|
|
2348
|
+
values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
|
|
2349
|
+
if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
|
|
2350
|
+
lines.push(`peer = (${values.join(", ")})`);
|
|
2351
|
+
}
|
|
2209
2352
|
}
|
|
2210
|
-
if (registry.get(destination.id) !== destination) fail$1("UNREGISTERED_DESTINATION_INSTANCE");
|
|
2211
|
-
return { ref: destination.id };
|
|
2212
2353
|
}
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
type: definition.algorithm.type === "select" ? "select" : "smart",
|
|
2232
|
-
members: definition.members.map(lower),
|
|
2233
|
-
...url === void 0 ? {} : { url },
|
|
2234
|
-
...intervalSeconds === void 0 ? {} : { intervalSeconds },
|
|
2235
|
-
...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
|
|
2236
|
-
};
|
|
2237
|
-
});
|
|
2238
|
-
const rules = input.routes.map((definition) => {
|
|
2239
|
-
exactDefinition(definition, [
|
|
2240
|
-
"type",
|
|
2241
|
-
"when",
|
|
2242
|
-
"to"
|
|
2243
|
-
]);
|
|
2244
|
-
if (definition.type !== "route") fail$1("INVALID_ROUTE_DEFINITION");
|
|
2245
|
-
return {
|
|
2246
|
-
when: definition.when,
|
|
2247
|
-
then: lower(definition.to)
|
|
2248
|
-
};
|
|
2249
|
-
});
|
|
2250
|
-
const { routes: _routes, groups: _groups, fallback, ...rest } = input;
|
|
2251
|
-
return snapshot({
|
|
2252
|
-
...rest,
|
|
2253
|
-
names,
|
|
2254
|
-
groups,
|
|
2255
|
-
rules,
|
|
2256
|
-
fallback: lower(fallback)
|
|
2354
|
+
lines.push("", "[Proxy Group]");
|
|
2355
|
+
for (const g of p.groups) lines.push(`${name(g.id)} = ${[
|
|
2356
|
+
g.type,
|
|
2357
|
+
...g.members.map(action),
|
|
2358
|
+
...g.url ? [`url=${g.url}`] : [],
|
|
2359
|
+
...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
|
|
2360
|
+
...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
|
|
2361
|
+
].join(", ")}`);
|
|
2362
|
+
lines.push("", "[Rule]");
|
|
2363
|
+
for (const r of p.rules) lines.push([
|
|
2364
|
+
conditionText(r.when),
|
|
2365
|
+
action(r.then),
|
|
2366
|
+
...conditionOptions(r.when)
|
|
2367
|
+
].join(","));
|
|
2368
|
+
lines.push(`FINAL,${action(p.fallback)}`, "");
|
|
2369
|
+
return deepFreeze({
|
|
2370
|
+
artifactKind: "surge-profile",
|
|
2371
|
+
content: lines.join("\n")
|
|
2257
2372
|
});
|
|
2258
2373
|
}
|
|
2259
|
-
function
|
|
2260
|
-
|
|
2261
|
-
return value;
|
|
2374
|
+
function renderSurgeProfile(compilation, resolveSecret) {
|
|
2375
|
+
return renderProfile(compilation, secretReader(resolveSecret));
|
|
2262
2376
|
}
|
|
2263
|
-
function
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
...options,
|
|
2268
|
-
type,
|
|
2269
|
-
value
|
|
2270
|
-
});
|
|
2271
|
-
};
|
|
2377
|
+
function renderSurgeProfiles(compilations, resolveSecret) {
|
|
2378
|
+
if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
|
|
2379
|
+
const read = secretReader(resolveSecret);
|
|
2380
|
+
return deepFreeze(compilations.map((c) => renderProfile(c, read)));
|
|
2272
2381
|
}
|
|
2273
|
-
const surgeMatch = {
|
|
2274
|
-
domain: atom("domain"),
|
|
2275
|
-
domainSuffix: atom("domainSuffix"),
|
|
2276
|
-
ipCidr: atom("ipCidr"),
|
|
2277
|
-
ipCidr6: atom("ipCidr6"),
|
|
2278
|
-
sourceIp: atom("sourceIp"),
|
|
2279
|
-
processName: atom("processName"),
|
|
2280
|
-
macAddress: atom("macAddress"),
|
|
2281
|
-
network: (value, options = {}) => {
|
|
2282
|
-
inspectDefinition(options);
|
|
2283
|
-
return condition({
|
|
2284
|
-
...options,
|
|
2285
|
-
type: "network",
|
|
2286
|
-
value
|
|
2287
|
-
});
|
|
2288
|
-
},
|
|
2289
|
-
port: (from, to, options = {}) => {
|
|
2290
|
-
inspectDefinition(options);
|
|
2291
|
-
return condition({
|
|
2292
|
-
...options,
|
|
2293
|
-
type: "port",
|
|
2294
|
-
from,
|
|
2295
|
-
...to === void 0 ? {} : { to }
|
|
2296
|
-
});
|
|
2297
|
-
},
|
|
2298
|
-
sourcePort: (from, to, options = {}) => {
|
|
2299
|
-
inspectDefinition(options);
|
|
2300
|
-
return condition({
|
|
2301
|
-
...options,
|
|
2302
|
-
type: "sourcePort",
|
|
2303
|
-
from,
|
|
2304
|
-
...to === void 0 ? {} : { to }
|
|
2305
|
-
});
|
|
2306
|
-
},
|
|
2307
|
-
all: (conditions, options = {}) => {
|
|
2308
|
-
inspectDefinition({
|
|
2309
|
-
conditions,
|
|
2310
|
-
options
|
|
2311
|
-
});
|
|
2312
|
-
return condition({
|
|
2313
|
-
...options,
|
|
2314
|
-
type: "all",
|
|
2315
|
-
conditions: [...conditions]
|
|
2316
|
-
});
|
|
2317
|
-
},
|
|
2318
|
-
any: (conditions, options = {}) => {
|
|
2319
|
-
inspectDefinition({
|
|
2320
|
-
conditions,
|
|
2321
|
-
options
|
|
2322
|
-
});
|
|
2323
|
-
return condition({
|
|
2324
|
-
...options,
|
|
2325
|
-
type: "any",
|
|
2326
|
-
conditions: [...conditions]
|
|
2327
|
-
});
|
|
2328
|
-
},
|
|
2329
|
-
not: (value, options = {}) => {
|
|
2330
|
-
inspectDefinition({
|
|
2331
|
-
value,
|
|
2332
|
-
options
|
|
2333
|
-
});
|
|
2334
|
-
return condition({
|
|
2335
|
-
...options,
|
|
2336
|
-
type: "not",
|
|
2337
|
-
condition: value
|
|
2338
|
-
});
|
|
2339
|
-
},
|
|
2340
|
-
ruleSet: (options) => {
|
|
2341
|
-
inspectDefinition(options);
|
|
2342
|
-
return condition({
|
|
2343
|
-
...options,
|
|
2344
|
-
type: "ruleSet"
|
|
2345
|
-
});
|
|
2346
|
-
}
|
|
2347
|
-
};
|
|
2348
2382
|
//#endregion
|
|
2349
2383
|
//#region src/profile.ts
|
|
2350
2384
|
const fail = (code) => {
|
|
@@ -2478,11 +2512,15 @@ function surgeCondition$1(condition, depth = 0) {
|
|
|
2478
2512
|
if (!parsed.success) return fail("PROFILE_CONDITION_UNSUPPORTED");
|
|
2479
2513
|
const value = parsed.data;
|
|
2480
2514
|
if (value.type === "ruleSet") return surgeCondition$1(value.when, depth);
|
|
2481
|
-
if (value.type !== "nativeRuleSet" || value.engine !== "surge"
|
|
2515
|
+
if (value.type !== "nativeRuleSet" || value.engine !== "surge") return fail("PROFILE_CONDITION_UNSUPPORTED");
|
|
2516
|
+
if (depth > 0 && value.intervalSeconds !== void 0) return fail("RULESET_COMPOSITION_UNSUPPORTED");
|
|
2482
2517
|
return {
|
|
2483
2518
|
type: "ruleSet",
|
|
2484
2519
|
format: value.format,
|
|
2485
|
-
url: value.url
|
|
2520
|
+
url: value.url,
|
|
2521
|
+
...value.intervalSeconds !== void 0 ? { intervalSeconds: value.intervalSeconds } : {},
|
|
2522
|
+
...value.noResolve !== void 0 ? { noResolve: value.noResolve } : {},
|
|
2523
|
+
...value.extendedMatching !== void 0 ? { extendedMatching: value.extendedMatching } : {}
|
|
2486
2524
|
};
|
|
2487
2525
|
}
|
|
2488
2526
|
if (condition.type === "all" || condition.type === "any") {
|
|
@@ -2663,6 +2701,12 @@ const ruleSet = (definition) => ({
|
|
|
2663
2701
|
...definition,
|
|
2664
2702
|
type: "ruleSet"
|
|
2665
2703
|
});
|
|
2704
|
+
function options(value, keys) {
|
|
2705
|
+
inspectDefinition(value);
|
|
2706
|
+
exactDefinition(value, keys);
|
|
2707
|
+
if (Object.values(value).some((v) => v !== void 0 && typeof v !== "boolean")) throw new ProfileDefinitionError("INVALID_MATCH_OPTIONS");
|
|
2708
|
+
return { ...value };
|
|
2709
|
+
}
|
|
2666
2710
|
const match = {
|
|
2667
2711
|
processName: (value) => {
|
|
2668
2712
|
if (!processNameSchema.safeParse(value).success) throw new Error("INVALID_PROCESS_NAME");
|
|
@@ -2672,17 +2716,20 @@ const match = {
|
|
|
2672
2716
|
};
|
|
2673
2717
|
},
|
|
2674
2718
|
ruleSet: (set) => set,
|
|
2675
|
-
domain: (value) => ({
|
|
2719
|
+
domain: (value, opts = {}) => ({
|
|
2676
2720
|
type: "domain",
|
|
2677
|
-
value
|
|
2721
|
+
value,
|
|
2722
|
+
...options(opts, ["extendedMatching"])
|
|
2678
2723
|
}),
|
|
2679
|
-
domainSuffix: (value) => ({
|
|
2724
|
+
domainSuffix: (value, opts = {}) => ({
|
|
2680
2725
|
type: "domainSuffix",
|
|
2681
|
-
value
|
|
2726
|
+
value,
|
|
2727
|
+
...options(opts, ["extendedMatching"])
|
|
2682
2728
|
}),
|
|
2683
|
-
ipCidr: (value) => ({
|
|
2729
|
+
ipCidr: (value, opts = {}) => ({
|
|
2684
2730
|
type: "ipCidr",
|
|
2685
|
-
value
|
|
2731
|
+
value,
|
|
2732
|
+
...options(opts, ["noResolve"])
|
|
2686
2733
|
}),
|
|
2687
2734
|
sourceIp: (value) => ({
|
|
2688
2735
|
type: "sourceIp",
|
|
@@ -2715,6 +2762,58 @@ const match = {
|
|
|
2715
2762
|
condition
|
|
2716
2763
|
})
|
|
2717
2764
|
};
|
|
2765
|
+
function nativeConstructor(engine) {
|
|
2766
|
+
function construct(value) {
|
|
2767
|
+
inspectDefinition(value);
|
|
2768
|
+
if (!value || typeof value !== "object") throw new ProfileDefinitionError("INVALID_NATIVE_RULESET");
|
|
2769
|
+
exactDefinition(value, [
|
|
2770
|
+
"id",
|
|
2771
|
+
"url",
|
|
2772
|
+
"format",
|
|
2773
|
+
"intervalSeconds",
|
|
2774
|
+
"noResolve",
|
|
2775
|
+
"extendedMatching",
|
|
2776
|
+
"behavior",
|
|
2777
|
+
"to"
|
|
2778
|
+
]);
|
|
2779
|
+
const input = value;
|
|
2780
|
+
const { to, ...resource } = input;
|
|
2781
|
+
exactDefinition(resource, [
|
|
2782
|
+
"id",
|
|
2783
|
+
"url",
|
|
2784
|
+
"format",
|
|
2785
|
+
"intervalSeconds",
|
|
2786
|
+
...engine === "surge" ? ["noResolve", "extendedMatching"] : engine === "mihomo" ? ["behavior"] : []
|
|
2787
|
+
]);
|
|
2788
|
+
const parsed = nativeRuleSetSchema.safeParse({
|
|
2789
|
+
...engine === "surge" ? { format: "rule-set" } : {},
|
|
2790
|
+
...resource,
|
|
2791
|
+
id: resource.id ?? "ruleset-pending",
|
|
2792
|
+
type: "nativeRuleSet",
|
|
2793
|
+
engine
|
|
2794
|
+
});
|
|
2795
|
+
if (!parsed.success) throw new ProfileDefinitionError("INVALID_NATIVE_RULESET");
|
|
2796
|
+
const { id: _id, type: _type, ...fields } = parsed.data;
|
|
2797
|
+
const id = resource.id ?? `ruleset-${createHash("sha256").update(JSON.stringify(Object.entries(fields).filter(([, value]) => value !== void 0).sort(([a], [b]) => a.localeCompare(b)))).digest("hex").slice(0, 16)}`;
|
|
2798
|
+
const when = snapshotDefinition({
|
|
2799
|
+
...parsed.data,
|
|
2800
|
+
id
|
|
2801
|
+
});
|
|
2802
|
+
if (Object.hasOwn(input, "to")) {
|
|
2803
|
+
if (to === void 0) throw new ProfileDefinitionError("INVALID_DESTINATION");
|
|
2804
|
+
return {
|
|
2805
|
+
type: "route",
|
|
2806
|
+
when,
|
|
2807
|
+
to
|
|
2808
|
+
};
|
|
2809
|
+
}
|
|
2810
|
+
return when;
|
|
2811
|
+
}
|
|
2812
|
+
return construct;
|
|
2813
|
+
}
|
|
2814
|
+
const surgeRuleSet = nativeConstructor("surge");
|
|
2815
|
+
const mihomoRuleSet = nativeConstructor("mihomo");
|
|
2816
|
+
const singboxRuleSet = nativeConstructor("sing-box");
|
|
2718
2817
|
const direct = () => ({ type: "direct" });
|
|
2719
2818
|
const reject = () => ({ type: "reject" });
|
|
2720
2819
|
const route = (to) => ({
|
|
@@ -2775,18 +2874,12 @@ const surge$1 = {
|
|
|
2775
2874
|
config: surgeConfig,
|
|
2776
2875
|
match: surgeMatch,
|
|
2777
2876
|
smart: () => ({ type: "surge-smart" }),
|
|
2778
|
-
ruleSet:
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
})
|
|
2877
|
+
ruleSet: surgeRuleSet
|
|
2878
|
+
};
|
|
2879
|
+
const mihomo = {
|
|
2880
|
+
ruleSet: mihomoRuleSet,
|
|
2881
|
+
ruleProvider: mihomoRuleSet
|
|
2784
2882
|
};
|
|
2785
|
-
const mihomo = { ruleProvider: (options) => ({
|
|
2786
|
-
...options,
|
|
2787
|
-
type: "nativeRuleSet",
|
|
2788
|
-
engine: "mihomo"
|
|
2789
|
-
}) };
|
|
2790
2883
|
/** Protocol constructors keep credentials and options specific to their protocol. */
|
|
2791
2884
|
function nodeConstructor(type) {
|
|
2792
2885
|
return (options) => ({
|
|
@@ -2804,11 +2897,7 @@ const proxy = {
|
|
|
2804
2897
|
vless: nodeConstructor("vless")
|
|
2805
2898
|
};
|
|
2806
2899
|
const singbox$1 = {
|
|
2807
|
-
ruleSet:
|
|
2808
|
-
...options,
|
|
2809
|
-
type: "nativeRuleSet",
|
|
2810
|
-
engine: "sing-box"
|
|
2811
|
-
}),
|
|
2900
|
+
ruleSet: singboxRuleSet,
|
|
2812
2901
|
tailscale: (options) => ({
|
|
2813
2902
|
...options,
|
|
2814
2903
|
type: "sing-box-tailscale"
|
|
@@ -2994,16 +3083,23 @@ function singbox(plan, secret) {
|
|
|
2994
3083
|
}
|
|
2995
3084
|
return config;
|
|
2996
3085
|
}
|
|
3086
|
+
function surgeOptions(condition) {
|
|
3087
|
+
return [
|
|
3088
|
+
...condition.type === "ipCidr" && condition.noResolve !== false ? ["no-resolve"] : [],
|
|
3089
|
+
...condition.type === "nativeRuleSet" && condition.engine === "surge" && condition.noResolve ? ["no-resolve"] : [],
|
|
3090
|
+
..."extendedMatching" in condition && condition.extendedMatching ? ["extended-matching"] : []
|
|
3091
|
+
].map((value) => `,${value}`).join("");
|
|
3092
|
+
}
|
|
2997
3093
|
function surgeCondition(condition) {
|
|
2998
3094
|
switch (condition.type) {
|
|
2999
3095
|
case "ruleSet": return surgeCondition(condition.when);
|
|
3000
3096
|
case "nativeRuleSet": return `${condition.format === "domain-set" ? "DOMAIN-SET" : "RULE-SET"},${condition.url}`;
|
|
3001
3097
|
case "all":
|
|
3002
|
-
case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${surgeCondition(c)})`).join(",")})`;
|
|
3003
|
-
case "not": return `NOT,((${surgeCondition(condition.condition)}))`;
|
|
3098
|
+
case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${surgeCondition(c)}${surgeOptions(c)})`).join(",")})`;
|
|
3099
|
+
case "not": return `NOT,((${surgeCondition(condition.condition)}${surgeOptions(condition.condition)}))`;
|
|
3004
3100
|
case "domain": return `DOMAIN,${condition.value}`;
|
|
3005
3101
|
case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
|
|
3006
|
-
case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}
|
|
3102
|
+
case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}`;
|
|
3007
3103
|
case "processName": return `PROCESS-NAME,${condition.value}`;
|
|
3008
3104
|
case "sourceIp": return `SRC-IP,${condition.value}`;
|
|
3009
3105
|
case "network": return `PROTOCOL,${condition.value.toUpperCase()}`;
|
|
@@ -3022,10 +3118,7 @@ function surge(plan, secret) {
|
|
|
3022
3118
|
lines.push("", "[Rule]");
|
|
3023
3119
|
for (const rule of plan.rules) {
|
|
3024
3120
|
lines.push(`# ${rule.id}`);
|
|
3025
|
-
|
|
3026
|
-
const condition = surgeCondition(rule.when).replace(/,no-resolve$/, "");
|
|
3027
|
-
lines.push(`${condition},${policy(rule.then)},no-resolve`);
|
|
3028
|
-
} else lines.push(`${surgeCondition(rule.when)},${policy(rule.then)}${rule.when.type === "nativeRuleSet" && rule.when.intervalSeconds !== void 0 ? `,update-interval=${rule.when.intervalSeconds}` : ""}`);
|
|
3121
|
+
lines.push(`${surgeCondition(rule.when)},${policy(rule.then)}${surgeOptions(rule.when)}${rule.when.type === "nativeRuleSet" && rule.when.intervalSeconds !== void 0 ? `,update-interval=${rule.when.intervalSeconds}` : ""}`);
|
|
3029
3122
|
}
|
|
3030
3123
|
lines.push(`FINAL,${policy(plan.program.fallback)}`);
|
|
3031
3124
|
return lines.join("\n") + "\n";
|
|
@@ -3424,4 +3517,4 @@ async function runBuild(input, output, options = {}) {
|
|
|
3424
3517
|
};
|
|
3425
3518
|
}
|
|
3426
3519
|
//#endregion
|
|
3427
|
-
export {
|
|
3520
|
+
export { renderSurgeProfiles as A, validateProxyOptions as B, strategy as C, defineProfile as D, compileProfile as E, isReservedNativeName as F, nodeSchema as G, assertData as H, nativeNameSchema as I, defineProxyGroup as J, requestSchema as K, targetCatalog as L, compile as M, explain as N, compileSurgeProfile as O, compileStrategyGroups as P, selectProxies as Q, RenderError as R, slot as S, use as T, deepFreeze as U, StaticRuleSetUnknownError as V, idSchema as W, defineRoutes as X, defineRoute as Y, outbound as Z, ruleSet as _, render as a, sequence as b, direct as c, mihomo as d, policy as f, rule as g, route as h, buildToDirectory as i, secretReader as j, renderSurgeProfile as k, group as l, reject as m, profileBuildFailure as n, block as o, proxy as p, ProfileDefinitionError as q, runBuild as r, defineConfig as s, defineBuild as t, match as u, secret as v, surge$1 as w, singbox$1 as x, selectNodes as y, surgeProxy as z };
|