proxylang 0.12.0 → 0.13.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.
@@ -1,4008 +0,0 @@
1
- import { isIP } from "node:net";
2
- import { z } from "zod";
3
- import { createHash, randomUUID } from "node:crypto";
4
- import ipaddr from "ipaddr.js";
5
- import { stringify } from "yaml";
6
- import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
7
- import { join, resolve } from "node:path";
8
- //#region src/match-identity.ts
9
- /** Identity only: preserve explicit false in author snapshots. */
10
- function domainIdentityFields(value) {
11
- return Object.entries(value).filter(([key, field]) => field !== void 0 && !(key === "includeSniffed" && field === false)).sort(([a], [b]) => a.localeCompare(b));
12
- }
13
- //#endregion
14
- //#region src/dns.ts
15
- 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;
16
- function dohUrl(value) {
17
- const url = new URL(value);
18
- if (!/^https:\/\/[^/]+\//.test(value)) url.pathname = "/dns-query";
19
- return url;
20
- }
21
- const server = z.string().max(2048).refine((value) => {
22
- if (isIP(value) && !value.includes("%")) return true;
23
- if (!value.startsWith("https://") || /[\s\p{C},()\\"'?#]/u.test(value)) return false;
24
- try {
25
- const url = new URL(value);
26
- const authority = value.slice(8).split("/")[0];
27
- const path = value.slice(8 + authority.length);
28
- return !url.username && !url.password && !authority.endsWith(":") && !!url.hostname && (!path || url.pathname === path);
29
- } catch {
30
- return false;
31
- }
32
- });
33
- const dnsRulesSchema = z.array(z.strictObject({
34
- pattern: z.string().min(1).max(253).refine((value) => domain$2.test(value.startsWith("*.") ? value.slice(2) : value)),
35
- server
36
- })).max(2e3).superRefine((rules, ctx) => {
37
- if (rules.length > 2e3 || rules.some((rule) => rule.pattern.length > 253 || rule.server.length > 2048)) return;
38
- for (let i = 0; i < rules.length; i++) for (let j = 0; j < i; j++) {
39
- const a = rules[i], b = rules[j];
40
- const x = a.pattern.toLowerCase(), y = b.pattern.toLowerCase();
41
- if (x === y || overlap(x, y) && a.server !== b.server) {
42
- ctx.addIssue({
43
- code: "custom",
44
- message: "DNS_RULE_CONFLICT"
45
- });
46
- return;
47
- }
48
- }
49
- });
50
- function overlap(a, b) {
51
- const wildA = a.startsWith("*."), wildB = b.startsWith("*.");
52
- if (wildA && wildB) return a.slice(1).endsWith(b.slice(1)) || b.slice(1).endsWith(a.slice(1));
53
- return wildA ? b.endsWith(a.slice(1)) : wildB && a.endsWith(b.slice(1));
54
- }
55
- function dnsCondition(rule) {
56
- const pattern = rule.pattern.toLowerCase();
57
- return pattern.startsWith("*.") ? { domain_regex: [`^.+\\.${pattern.slice(2).replaceAll(".", "\\.")}$`] } : { domain: [pattern] };
58
- }
59
- //#endregion
60
- //#region src/surge-definitions.ts
61
- const definitionCodes = /* @__PURE__ */ new Set([
62
- "DEFINITION_CYCLE",
63
- "DEFINITION_DEPTH_EXCEEDED",
64
- "DEFINITION_EDGE_BUDGET_EXCEEDED",
65
- "DEFINITION_NOT_DATA",
66
- "DEFINITION_OBJECT_BUDGET_EXCEEDED",
67
- "DEFINITION_OUTPUT_BUDGET_EXCEEDED",
68
- "DEFINITION_UNKNOWN_FIELD",
69
- "DNS_HOSTS_CONFLICT",
70
- "DNS_RULE_CONFLICT",
71
- "DUPLICATE_RESOURCE_ID",
72
- "GROUP_NAME_CONFLICT",
73
- "INVALID_BUILD_DEFINITION",
74
- "INVALID_DESTINATION",
75
- "INVALID_DNS_RULE",
76
- "INVALID_DNS_RULES",
77
- "INVALID_GROUP_DEFINITION",
78
- "INVALID_MATCH_OPTIONS",
79
- "INVALID_NATIVE_RULESET",
80
- "INVALID_PROFILE_DEFINITION",
81
- "INVALID_RESOURCE_DEFINITION",
82
- "INVALID_ROUTE_DEFINITION",
83
- "INVALID_SECRETS_DEFINITION",
84
- "INVALID_SURGE_GENERAL",
85
- "INVALID_SURGE_HOSTS",
86
- "LOGICAL_DEPTH_EXCEEDED",
87
- "PROFILE_CONDITION_UNSUPPORTED",
88
- "PROFILE_DESTINATION_UNSUPPORTED",
89
- "PROFILE_ENDPOINT_UNSUPPORTED",
90
- "PROFILE_EXTENSION_UNSUPPORTED",
91
- "PROFILE_GROUP_MEMBER_UNSUPPORTED",
92
- "PROFILE_GROUP_OPTIONS_UNSUPPORTED",
93
- "PROFILE_TARGET_UNSUPPORTED",
94
- "RULESET_COMPOSITION_UNSUPPORTED",
95
- "UNKNOWN_DESTINATION_ID",
96
- "UNREGISTERED_DESTINATION_INSTANCE",
97
- "UNSUPPORTED_GROUP_ALGORITHM"
98
- ]);
99
- function validDiagnosticPath(path) {
100
- return typeof path === "string" && /^(dns|surge\.hosts)\[\d{1,4}\]$/.test(path);
101
- }
102
- function definitionDiagnostic(error) {
103
- try {
104
- if (!error || typeof error !== "object") return;
105
- const name = Object.getOwnPropertyDescriptor(error, "name")?.value;
106
- const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
107
- if (name !== "ProfileDefinitionError" || typeof code !== "string" || !definitionCodes.has(code)) return;
108
- const paths = Object.getOwnPropertyDescriptor(error, "paths")?.value;
109
- if (code === "DNS_HOSTS_CONFLICT" && Array.isArray(paths) && Object.getOwnPropertyDescriptor(paths, "length")?.value === 2) {
110
- const first = Object.getOwnPropertyDescriptor(paths, "0")?.value;
111
- const second = Object.getOwnPropertyDescriptor(paths, "1")?.value;
112
- if (validDiagnosticPath(first) && validDiagnosticPath(second)) return {
113
- code,
114
- paths: [first, second]
115
- };
116
- }
117
- return { code };
118
- } catch {
119
- return;
120
- }
121
- }
122
- var ProfileDefinitionError = class extends Error {
123
- code;
124
- paths;
125
- constructor(code, paths) {
126
- super(code);
127
- this.code = code;
128
- this.name = "ProfileDefinitionError";
129
- if (paths?.length === 2 && paths.every(validDiagnosticPath)) this.paths = Object.freeze([...paths]);
130
- }
131
- };
132
- const fail$1 = (code) => {
133
- throw new ProfileDefinitionError(code);
134
- };
135
- /** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
136
- function inspectDefinition(root) {
137
- let edges = 0;
138
- let objects = 0;
139
- const visiting = /* @__PURE__ */ new Set();
140
- const heights = /* @__PURE__ */ new Map();
141
- function visit(value, depth) {
142
- if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
143
- if (value === null || typeof value !== "object") {
144
- if (![
145
- "undefined",
146
- "string",
147
- "number",
148
- "boolean"
149
- ].includes(typeof value) && value !== null) fail$1("DEFINITION_NOT_DATA");
150
- return 0;
151
- }
152
- if (visiting.has(value)) fail$1("DEFINITION_CYCLE");
153
- const cached = heights.get(value);
154
- if (cached !== void 0) {
155
- if (depth + cached > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
156
- return cached;
157
- }
158
- if (++objects > 2e4) fail$1("DEFINITION_OBJECT_BUDGET_EXCEEDED");
159
- const proto = Object.getPrototypeOf(value);
160
- if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail$1("DEFINITION_NOT_DATA");
161
- if (Array.isArray(value) && value.length > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
162
- visiting.add(value);
163
- let height = 0;
164
- for (const key of Reflect.ownKeys(value)) {
165
- if (++edges > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
166
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
167
- if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail$1("DEFINITION_NOT_DATA");
168
- height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
169
- }
170
- visiting.delete(value);
171
- heights.set(value, height);
172
- return height;
173
- }
174
- visit(root, 0);
175
- }
176
- /** Count output occurrences, not identities, before allocating each copied value. */
177
- function snapshot(input) {
178
- let remaining = 1e5;
179
- function copy(value, depth) {
180
- if (--remaining < 0) fail$1("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
181
- if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
182
- if (value === null || typeof value !== "object") return value;
183
- if (Array.isArray(value)) {
184
- const output = [];
185
- for (const item of value) output.push(copy(item, depth + 1));
186
- return output;
187
- }
188
- const output = {};
189
- for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
190
- value: copy(item, depth + 1),
191
- enumerable: true,
192
- writable: true,
193
- configurable: true
194
- });
195
- return output;
196
- }
197
- return copy(input, 0);
198
- }
199
- function snapshotDefinition(input) {
200
- inspectDefinition(input);
201
- return snapshot(input);
202
- }
203
- function exactDefinition(value, keys) {
204
- if (!value || typeof value !== "object" || Array.isArray(value)) fail$1("DEFINITION_NOT_DATA");
205
- if (Object.keys(value).some((key) => !keys.includes(key))) fail$1("DEFINITION_UNKNOWN_FIELD");
206
- }
207
- const outbound = {
208
- direct: Object.freeze({ builtin: "DIRECT" }),
209
- reject: Object.freeze({ builtin: "REJECT" }),
210
- rejectDrop: Object.freeze({ builtin: "REJECT-DROP" }),
211
- rejectNoDrop: Object.freeze({ builtin: "REJECT-NO-DROP" }),
212
- rejectTinyGif: Object.freeze({ builtin: "REJECT-TINYGIF" })
213
- };
214
- function defineProxyGroup(input) {
215
- inspectDefinition(input);
216
- exactDefinition(input, [
217
- "id",
218
- "name",
219
- "algorithm",
220
- "members",
221
- "url",
222
- "intervalSeconds",
223
- "timeoutSeconds"
224
- ]);
225
- if (!input.algorithm || ![
226
- "select",
227
- "surge-smart",
228
- "urltest"
229
- ].includes(input.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
230
- exactDefinition(input.algorithm, input.algorithm.type === "urltest" ? [
231
- "type",
232
- "url",
233
- "intervalSeconds",
234
- "toleranceMs"
235
- ] : ["type"]);
236
- if (!Array.isArray(input.members)) fail$1("INVALID_GROUP_DEFINITION");
237
- return {
238
- ...input,
239
- type: "proxy-group",
240
- algorithm: { ...input.algorithm },
241
- members: [...input.members]
242
- };
243
- }
244
- function defineRoute(input) {
245
- inspectDefinition(input);
246
- exactDefinition(input, ["when", "to"]);
247
- return {
248
- ...input,
249
- type: "route"
250
- };
251
- }
252
- function defineRoutes(input) {
253
- inspectDefinition(input);
254
- exactDefinition(input, ["when", "to"]);
255
- if (!Array.isArray(input.when)) fail$1("INVALID_ROUTE_DEFINITION");
256
- return input.when.map((when) => ({
257
- type: "route",
258
- when,
259
- to: input.to
260
- }));
261
- }
262
- function lowerSurgeProfile(input) {
263
- inspectDefinition(input);
264
- exactDefinition(input, [
265
- "target",
266
- "managed",
267
- "general",
268
- "hosts",
269
- "nodes",
270
- "tunnels",
271
- "names",
272
- "groups",
273
- "routes",
274
- "fallback"
275
- ]);
276
- 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");
277
- const registry = /* @__PURE__ */ new Map();
278
- const names = Object.assign(Object.create(null), input.names);
279
- for (const resource of [
280
- ...input.nodes,
281
- ...input.tunnels ?? [],
282
- ...input.groups
283
- ]) {
284
- if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail$1("INVALID_RESOURCE_DEFINITION");
285
- if (registry.has(resource.id)) fail$1("DUPLICATE_RESOURCE_ID");
286
- registry.set(resource.id, resource);
287
- const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
288
- if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail$1("GROUP_NAME_CONFLICT");
289
- Object.defineProperty(names, resource.id, {
290
- value: names[resource.id] ?? name,
291
- enumerable: true,
292
- configurable: true,
293
- writable: true
294
- });
295
- }
296
- function lower(destination) {
297
- if (typeof destination === "string") {
298
- if (!registry.has(destination)) fail$1("UNKNOWN_DESTINATION_ID");
299
- return { ref: destination };
300
- }
301
- if (!destination || typeof destination !== "object") fail$1("INVALID_DESTINATION");
302
- if ("builtin" in destination) {
303
- exactDefinition(destination, ["builtin"]);
304
- if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail$1("INVALID_DESTINATION");
305
- return { builtin: destination.builtin };
306
- }
307
- if (registry.get(destination.id) !== destination) fail$1("UNREGISTERED_DESTINATION_INSTANCE");
308
- return { ref: destination.id };
309
- }
310
- const groups = input.groups.map((definition) => {
311
- exactDefinition(definition, [
312
- "type",
313
- "id",
314
- "name",
315
- "algorithm",
316
- "members",
317
- "url",
318
- "intervalSeconds",
319
- "timeoutSeconds"
320
- ]);
321
- if (definition.type !== "proxy-group") fail$1("INVALID_GROUP_DEFINITION");
322
- if (!definition.algorithm || !["select", "surge-smart"].includes(definition.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
323
- exactDefinition(definition.algorithm, ["type"]);
324
- if (!Array.isArray(definition.members)) fail$1("INVALID_GROUP_DEFINITION");
325
- const { id, url, intervalSeconds, timeoutSeconds } = definition;
326
- return {
327
- id,
328
- type: definition.algorithm.type === "select" ? "select" : "smart",
329
- members: definition.members.map(lower),
330
- ...url === void 0 ? {} : { url },
331
- ...intervalSeconds === void 0 ? {} : { intervalSeconds },
332
- ...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
333
- };
334
- });
335
- const rules = input.routes.map((definition) => {
336
- exactDefinition(definition, [
337
- "type",
338
- "when",
339
- "to"
340
- ]);
341
- if (definition.type !== "route") fail$1("INVALID_ROUTE_DEFINITION");
342
- return {
343
- when: definition.when,
344
- then: lower(definition.to)
345
- };
346
- });
347
- const { routes: _routes, groups: _groups, fallback, ...rest } = input;
348
- return snapshot({
349
- ...rest,
350
- names,
351
- groups,
352
- rules,
353
- fallback: lower(fallback)
354
- });
355
- }
356
- function condition(value) {
357
- inspectDefinition(value);
358
- exactDefinition(value, [
359
- "type",
360
- "noResolve",
361
- ...value.type === "ruleSet" ? [
362
- "format",
363
- "url",
364
- "builtin",
365
- "intervalSeconds"
366
- ] : value.type === "all" || value.type === "any" ? ["conditions"] : value.type === "not" ? ["condition"] : value.type === "port" || value.type === "sourcePort" ? ["from", "to"] : ["value"],
367
- ...[
368
- "domain",
369
- "domainSuffix",
370
- "ruleSet"
371
- ].includes(value.type) ? ["includeSniffed"] : []
372
- ]);
373
- if (value.includeSniffed !== void 0 && typeof value.includeSniffed !== "boolean") throw new ProfileDefinitionError("INVALID_MATCH_OPTIONS");
374
- return value;
375
- }
376
- function atom$2(type) {
377
- return (value, options) => {
378
- inspectDefinition(options ?? {});
379
- exactDefinition(options ?? {}, ["noResolve", ...["domain", "domainSuffix"].includes(type) ? ["includeSniffed"] : []]);
380
- return condition({
381
- ...options,
382
- type,
383
- value
384
- });
385
- };
386
- }
387
- const surgeMatch = {
388
- domain: atom$2("domain"),
389
- domainSuffix: atom$2("domainSuffix"),
390
- ipCidr: atom$2("ipCidr"),
391
- ipCidr6: atom$2("ipCidr6"),
392
- ipAsn: (value, options = {}) => {
393
- inspectDefinition(options);
394
- return condition({
395
- ...options,
396
- type: "ipAsn",
397
- value
398
- });
399
- },
400
- sourceIp: atom$2("sourceIp"),
401
- processName: atom$2("processName"),
402
- macAddress: atom$2("macAddress"),
403
- network: (value, options = {}) => {
404
- inspectDefinition(options);
405
- return condition({
406
- ...options,
407
- type: "network",
408
- value
409
- });
410
- },
411
- port: (from, to, options = {}) => {
412
- inspectDefinition(options);
413
- return condition({
414
- ...options,
415
- type: "port",
416
- from,
417
- ...to === void 0 ? {} : { to }
418
- });
419
- },
420
- sourcePort: (from, to, options = {}) => {
421
- inspectDefinition(options);
422
- return condition({
423
- ...options,
424
- type: "sourcePort",
425
- from,
426
- ...to === void 0 ? {} : { to }
427
- });
428
- },
429
- all: (conditions, options = {}) => {
430
- inspectDefinition({
431
- conditions,
432
- options
433
- });
434
- return condition({
435
- ...options,
436
- type: "all",
437
- conditions: [...conditions]
438
- });
439
- },
440
- any: (conditions, options = {}) => {
441
- inspectDefinition({
442
- conditions,
443
- options
444
- });
445
- return condition({
446
- ...options,
447
- type: "any",
448
- conditions: [...conditions]
449
- });
450
- },
451
- not: (value, options = {}) => {
452
- inspectDefinition({
453
- value,
454
- options
455
- });
456
- return condition({
457
- ...options,
458
- type: "not",
459
- condition: value
460
- });
461
- },
462
- ruleSet: (options) => {
463
- inspectDefinition(options);
464
- return condition({
465
- ...options,
466
- type: "ruleSet"
467
- });
468
- }
469
- };
470
- //#endregion
471
- //#region src/tun.ts
472
- function validTunAddresses(addresses) {
473
- const families = /* @__PURE__ */ new Set();
474
- try {
475
- for (const value of addresses) {
476
- const [address, prefix] = ipaddr.parseCIDR(value);
477
- const family = address.kind();
478
- const bits = family === "ipv4" ? 32 : 128;
479
- if (families.has(family) || prefix > bits - 2) return false;
480
- families.add(family);
481
- const numeric = address.toByteArray().reduce((total, byte) => total << 8n | BigInt(byte), 0n);
482
- const mask = (1n << BigInt(bits - prefix)) - 1n;
483
- if ((numeric & mask) === mask) return false;
484
- }
485
- return true;
486
- } catch {
487
- return false;
488
- }
489
- }
490
- function unsafeTunResolvers(program) {
491
- if (!program.tun) return [];
492
- const networks = program.tun.address.map((value) => ipaddr.parseCIDR(value));
493
- return [
494
- ...program.listener ? [program.listener.resolver] : [],
495
- ...(program.dns ?? []).map((rule) => isIP(rule.server) ? rule.server : new URL(rule.server).hostname.replace(/^\[|\]$/g, "")),
496
- ...(program.endpoints ?? []).map((endpoint) => endpoint.bootstrapResolver)
497
- ].filter((value) => {
498
- if (!isIP(value)) return false;
499
- const address = ipaddr.process(value);
500
- return ["loopback", "unspecified"].includes(address.range()) || networks.some(([network, prefix]) => address.kind() === network.kind() && address.match(network, prefix));
501
- });
502
- }
503
- //#endregion
504
- //#region src/schema.ts
505
- const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
506
- 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])?$/);
507
- const ip$1 = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
508
- const cidr$1 = z.string().refine((x) => {
509
- try {
510
- const [address, prefix] = x.split("/");
511
- if (!address || !prefix || !/^\d+$/.test(prefix) || isIP(address) === 0 || address.includes("%")) return false;
512
- ipaddr.parseCIDR(x);
513
- return true;
514
- } catch {
515
- return false;
516
- }
517
- });
518
- const processNameSchema = z.string().min(1).max(255).regex(/^[^/\\*?[\],()\p{C}]+$/u);
519
- const port$1 = z.number().int().min(1).max(65535);
520
- const network = z.enum(["tcp", "udp"]);
521
- const atom$1 = (type, value) => z.strictObject({
522
- type: z.literal(type),
523
- value
524
- });
525
- const remoteBase = {
526
- type: z.literal("nativeRuleSet"),
527
- id: idSchema,
528
- url: z.string().max(2048).refine((value) => {
529
- try {
530
- const url = new URL(value);
531
- return /^https?:\/\//.test(value) && ["http:", "https:"].includes(url.protocol) && !url.username && !url.password && !url.hash && !/[\s\p{C},()\\"']/u.test(value);
532
- } catch {
533
- return false;
534
- }
535
- })
536
- };
537
- const updateInterval = z.number().int().min(60).max(2147483647);
538
- const nativeRuleSetSchema = z.discriminatedUnion("engine", [
539
- z.strictObject({
540
- ...remoteBase,
541
- engine: z.literal("surge"),
542
- format: z.enum(["rule-set", "domain-set"]),
543
- intervalSeconds: updateInterval.optional(),
544
- noResolve: z.boolean().optional(),
545
- includeSniffed: z.boolean().optional()
546
- }),
547
- z.strictObject({
548
- ...remoteBase,
549
- engine: z.literal("sing-box"),
550
- format: z.enum(["source", "binary"]),
551
- intervalSeconds: updateInterval,
552
- resolve: z.boolean().optional()
553
- }),
554
- z.strictObject({
555
- ...remoteBase,
556
- engine: z.literal("mihomo"),
557
- format: z.enum(["yaml", "text"]),
558
- behavior: z.enum([
559
- "domain",
560
- "ipcidr",
561
- "classical"
562
- ]),
563
- intervalSeconds: updateInterval
564
- })
565
- ]);
566
- const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
567
- nativeRuleSetSchema,
568
- z.strictObject({
569
- type: z.literal("ruleSet"),
570
- id: idSchema,
571
- when: matchSchema
572
- }),
573
- z.strictObject({
574
- type: z.literal("domain"),
575
- value: domain$1,
576
- includeSniffed: z.boolean().optional()
577
- }),
578
- z.strictObject({
579
- type: z.literal("domainSuffix"),
580
- value: domain$1,
581
- includeSniffed: z.boolean().optional()
582
- }),
583
- z.strictObject({
584
- type: z.literal("ipCidr"),
585
- value: cidr$1,
586
- noResolve: z.boolean().optional()
587
- }),
588
- atom$1("sourceIp", z.union([ip$1, cidr$1])),
589
- atom$1("processName", processNameSchema),
590
- z.strictObject({
591
- type: z.literal("port"),
592
- from: port$1,
593
- to: port$1
594
- }).refine((v) => v.from <= v.to),
595
- z.strictObject({
596
- type: z.literal("sourcePort"),
597
- from: port$1,
598
- to: port$1
599
- }).refine((v) => v.from <= v.to),
600
- z.strictObject({
601
- type: z.literal("network"),
602
- value: network
603
- }),
604
- z.strictObject({
605
- type: z.enum(["all", "any"]),
606
- conditions: z.array(matchSchema).min(1)
607
- }),
608
- z.strictObject({
609
- type: z.literal("not"),
610
- condition: matchSchema
611
- })
612
- ]));
613
- const actionSchema = z.discriminatedUnion("type", [z.strictObject({ type: z.enum(["direct", "reject"]) }), z.strictObject({
614
- type: z.literal("route"),
615
- to: idSchema
616
- })]);
617
- const slotSchema = z.strictObject({
618
- type: z.literal("slot"),
619
- name: idSchema
620
- });
621
- const ruleAction = z.discriminatedUnion("type", [actionSchema, slotSchema]);
622
- const unique = (items) => new Set(items).size === items.length;
623
- const policySchema = z.lazy(() => z.strictObject({
624
- type: z.literal("policy"),
625
- id: idSchema,
626
- exits: z.array(idSchema).refine(unique),
627
- rules: z.array(entrySchema).min(1)
628
- }));
629
- const entrySchema = z.lazy(() => z.discriminatedUnion("type", [
630
- z.strictObject({
631
- type: z.literal("rule"),
632
- id: idSchema,
633
- when: matchSchema,
634
- then: ruleAction
635
- }),
636
- z.strictObject({
637
- type: z.literal("block"),
638
- id: idSchema,
639
- rules: z.array(entrySchema).min(1),
640
- when: matchSchema.optional()
641
- }),
642
- z.strictObject({
643
- type: z.literal("use"),
644
- id: idSchema,
645
- policy: policySchema,
646
- bindings: z.record(idSchema, ruleAction)
647
- })
648
- ]));
649
- const secretSchema = z.strictObject({
650
- type: z.literal("env"),
651
- name: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)
652
- });
653
- const nodeBase = {
654
- id: idSchema,
655
- server: z.union([ip$1, domain$1]),
656
- port: port$1,
657
- via: idSchema.optional(),
658
- tcpFastOpen: z.boolean().optional(),
659
- label: z.string().min(1).max(256).optional()
660
- };
661
- const tlsSchema = z.strictObject({
662
- serverName: domain$1,
663
- skipCertVerify: z.boolean().optional(),
664
- alpn: z.array(z.string().min(1).refine((x) => !/\p{C}/u.test(x) && Buffer.byteLength(x) <= 255)).min(1).refine(unique).optional()
665
- });
666
- const transportSchema = z.strictObject({
667
- type: z.literal("ws"),
668
- path: z.string().max(2048).regex(/^\/[A-Za-z0-9/._~-]*$/).refine((x) => !x.startsWith("//")),
669
- host: domain$1.optional()
670
- });
671
- const uuidNode = {
672
- ...nodeBase,
673
- uuid: secretSchema,
674
- tls: tlsSchema.optional(),
675
- transport: transportSchema.optional()
676
- };
677
- const surgeOptions$1 = { blockQuic: z.enum([
678
- "auto",
679
- "on",
680
- "off"
681
- ]).optional() };
682
- const portHoppingSchema = z.string().max(2048).regex(/^[0-9]+(?:-[0-9]+)?(?:;[0-9]+(?:-[0-9]+)?)*$/).refine((value) => value.split(";").every((part) => {
683
- const [start, end = start] = part.split("-").map(Number);
684
- return start !== void 0 && end !== void 0 && start >= 1 && end <= 65535 && start <= end;
685
- }));
686
- const nodeSchema = z.discriminatedUnion("type", [
687
- z.strictObject({
688
- ...nodeBase,
689
- type: z.literal("trojan"),
690
- password: secretSchema,
691
- serverName: domain$1.optional(),
692
- skipCertVerify: z.boolean().optional(),
693
- surge: z.strictObject({
694
- ...surgeOptions$1,
695
- udpRelay: z.literal(true).optional()
696
- }).optional()
697
- }),
698
- z.strictObject({
699
- ...nodeBase,
700
- type: z.literal("anytls"),
701
- password: secretSchema,
702
- serverName: domain$1.optional(),
703
- skipCertVerify: z.boolean().optional(),
704
- surge: z.strictObject({
705
- ...surgeOptions$1,
706
- udpRelay: z.literal(true).optional()
707
- }).optional()
708
- }),
709
- z.strictObject({
710
- ...nodeBase,
711
- type: z.literal("hysteria2"),
712
- tcpFastOpen: z.never().optional(),
713
- password: secretSchema,
714
- serverName: domain$1.optional(),
715
- skipCertVerify: z.boolean().optional(),
716
- portHopping: portHoppingSchema.optional(),
717
- portHoppingInterval: z.number().int().positive().optional()
718
- }).refine((node) => node.portHoppingInterval === void 0 || node.portHopping !== void 0),
719
- z.strictObject({
720
- ...nodeBase,
721
- type: z.literal("http"),
722
- serverName: z.undefined().optional(),
723
- password: secretSchema,
724
- username: secretSchema.optional()
725
- }),
726
- z.strictObject({
727
- ...nodeBase,
728
- type: z.literal("shadowsocks"),
729
- surge: z.strictObject({
730
- ...surgeOptions$1,
731
- udpRelay: z.boolean().optional()
732
- }).optional(),
733
- method: z.enum([
734
- "aes-128-gcm",
735
- "aes-256-gcm",
736
- "chacha20-ietf-poly1305"
737
- ]),
738
- password: secretSchema
739
- }),
740
- z.strictObject({
741
- ...uuidNode,
742
- type: z.literal("vmess"),
743
- surge: z.strictObject(surgeOptions$1).optional()
744
- }),
745
- z.strictObject({
746
- ...uuidNode,
747
- type: z.literal("vless"),
748
- flow: z.literal("xtls-rprx-vision").optional(),
749
- packetEncoding: z.enum(["xudp", "packetaddr"]).optional(),
750
- utlsFingerprint: z.literal("chrome").optional(),
751
- reality: z.strictObject({
752
- publicKey: z.string().regex(/^[A-Za-z0-9_-]{43}$/).refine((value) => Buffer.from(value, "base64url").toString("base64url") === value),
753
- shortId: z.string().regex(/^(?:[0-9a-fA-F]{2}){0,8}$/)
754
- }).optional()
755
- }).refine((node) => !node.reality || !!node.tls && node.utlsFingerprint === "chrome").refine((node) => !node.flow || !!node.tls && !node.transport).refine((node) => !node.utlsFingerprint || !!node.tls)
756
- ]).refine((node) => !("transport" in node && node.transport && node.tls?.alpn) || node.tls.alpn.length === 1 && node.tls.alpn[0] === "http/1.1");
757
- const endpointSchema = z.strictObject({
758
- type: z.literal("sing-box-tailscale"),
759
- id: idSchema,
760
- hostname: domain$1.refine((x) => !x.includes(".")),
761
- stateDirectory: z.string().max(4096).refine((x) => x.startsWith("/") && !/[\p{C}$\\]/u.test(x) && x.split("/").slice(1).every((part) => part !== "" && part !== "." && part !== "..")),
762
- acceptRoutes: z.boolean(),
763
- bootstrapResolver: ip$1,
764
- authKey: secretSchema.optional(),
765
- exitNode: ip$1.optional(),
766
- exitNodeAllowLanAccess: z.boolean().optional()
767
- }).refine((endpoint) => endpoint.exitNodeAllowLanAccess === void 0 || endpoint.exitNode !== void 0);
768
- const members = z.array(z.union([idSchema, z.enum(["DIRECT", "REJECT"])])).min(1).refine(unique);
769
- const url$1 = z.string().url().refine((value) => {
770
- try {
771
- const u = new URL(value);
772
- return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password && !u.hash;
773
- } catch {
774
- return false;
775
- }
776
- });
777
- const urltestAlgorithmSchema = z.strictObject({
778
- type: z.literal("urltest"),
779
- url: url$1,
780
- intervalSeconds: z.number().int().min(1).max(86400).default(180),
781
- toleranceMs: z.number().int().min(0).max(6e4).default(50)
782
- });
783
- const algorithmSchema = z.union([z.strictObject({ type: z.enum(["select", "surge-smart"]) }), urltestAlgorithmSchema]);
784
- const portableAlgorithmSchema = z.union([z.strictObject({ type: z.enum(["select", "auto"]) }), urltestAlgorithmSchema]);
785
- const implementationsSchema = z.strictObject({
786
- surge: algorithmSchema.optional(),
787
- "sing-box": algorithmSchema.optional(),
788
- mihomo: algorithmSchema.optional(),
789
- stash: algorithmSchema.optional()
790
- });
791
- const strategyBase = {
792
- type: z.literal("strategy"),
793
- id: idSchema,
794
- members
795
- };
796
- const strategySchema = z.union([z.strictObject({
797
- ...strategyBase,
798
- algorithm: portableAlgorithmSchema,
799
- implementations: implementationsSchema.optional()
800
- }), z.strictObject({
801
- ...strategyBase,
802
- implementations: implementationsSchema.refine((v) => !!v.surge || !!v["sing-box"] || !!v.mihomo || !!v.stash)
803
- })]);
804
- const groupSchema$1 = z.union([
805
- strategySchema,
806
- z.strictObject({
807
- type: z.enum(["select", "smart"]),
808
- id: idSchema,
809
- members
810
- }),
811
- z.strictObject({
812
- type: z.literal("urltest"),
813
- id: idSchema,
814
- members,
815
- url: url$1,
816
- intervalSeconds: z.number().int().min(1).max(86400).default(180),
817
- toleranceMs: z.number().int().min(0).max(6e4).default(50)
818
- })
819
- ]);
820
- const requestSchema = z.strictObject({
821
- network,
822
- domain: domain$1.optional(),
823
- tlsSni: domain$1.optional(),
824
- httpHost: domain$1.optional(),
825
- ip: ip$1.optional(),
826
- sourceIp: ip$1.optional(),
827
- processName: processNameSchema.optional(),
828
- port: port$1.optional(),
829
- sourcePort: port$1.optional()
830
- });
831
- const configSchema = z.strictObject({
832
- outDir: z.string().min(1).refine((value) => value.trim() === value && !value.includes("\0")).optional(),
833
- programs: z.record(idSchema, z.strictObject({
834
- engine: z.enum([
835
- "surge",
836
- "sing-box",
837
- "mihomo",
838
- "stash"
839
- ]),
840
- domainMatching: z.literal("prefer-sniffed").optional(),
841
- serverAliases: z.record(domain$1.refine((value) => !isIP(value)), z.union([domain$1, ip$1])).optional(),
842
- cacheFile: z.boolean().optional(),
843
- unsupportedUdp: z.literal("reject").optional(),
844
- dns: dnsRulesSchema.optional(),
845
- nodes: z.array(nodeSchema),
846
- endpoints: z.array(endpointSchema).max(1e3).optional(),
847
- groups: z.array(groupSchema$1),
848
- routing: z.array(entrySchema),
849
- fallback: actionSchema,
850
- listener: z.strictObject({
851
- port: port$1,
852
- resolver: ip$1
853
- }).optional(),
854
- tun: z.strictObject({
855
- address: z.array(cidr$1).min(1).max(2).refine(validTunAddresses),
856
- stack: z.enum([
857
- "system",
858
- "gvisor",
859
- "mixed"
860
- ]),
861
- autoRoute: z.boolean(),
862
- strictRoute: z.boolean(),
863
- dnsMode: z.enum([
864
- "disabled",
865
- "native",
866
- "hijack"
867
- ]),
868
- routeExcludeAddress: z.array(cidr$1).optional()
869
- }).refine((tun) => !tun.strictRoute || tun.autoRoute).optional()
870
- })),
871
- targets: z.array(z.strictObject({
872
- id: idSchema,
873
- program: idSchema,
874
- engine: z.enum([
875
- "surge",
876
- "sing-box",
877
- "mihomo",
878
- "stash"
879
- ]),
880
- platform: z.enum(["macos", "linux"]),
881
- version: z.string().regex(/^\d+\.\d+\.\d+$/),
882
- mode: z.enum(["fragment", "standalone"]).default("fragment")
883
- })).min(1),
884
- cases: z.array(z.strictObject({
885
- id: idSchema,
886
- program: idSchema,
887
- request: requestSchema,
888
- expect: z.strictObject({
889
- rule: z.string().min(1).optional(),
890
- action: actionSchema
891
- })
892
- })).optional(),
893
- warningsAsErrors: z.boolean().optional()
894
- });
895
- /** Only schema-owned constraints are rendered; Zod messages can contain input values. */
896
- function schemaIssueMessage(issue) {
897
- switch (issue.code) {
898
- case "invalid_type": return `字段类型错误或缺失;需要 ${issue.expected}`;
899
- case "too_small": return `字段低于下限;${issue.origin} 的最小值或长度为 ${issue.minimum}`;
900
- case "too_big": return `字段超过上限;${issue.origin} 的最大值或长度为 ${issue.maximum}`;
901
- case "invalid_value": return `字段必须使用声明的枚举值:${issue.values.map(String).join("、")}`;
902
- case "invalid_format": return "字段格式不符合约束;检查域名、标识符或路径格式";
903
- case "unrecognized_keys": return "对象包含当前声明不支持的字段;请删除额外字段";
904
- case "invalid_union": return "声明不符合任何支持的分支;检查 type、engine 及对应必填字段";
905
- default: return "字段不满足语义约束;检查地址、范围顺序、重复项或相关字段组合";
906
- }
907
- }
908
- /** Reject cycles, executable values and excessive expansion before recursive schema parsing. */
909
- function assertData(value) {
910
- const ancestors = /* @__PURE__ */ new Set();
911
- let count = 0;
912
- const visit = (v, depth) => {
913
- if (++count > 1e5 || depth > 64) throw new Error("INPUT_LIMIT");
914
- if (v === void 0 || v === null || [
915
- "string",
916
- "number",
917
- "boolean"
918
- ].includes(typeof v)) return;
919
- if (typeof v !== "object" || ancestors.has(v)) throw new Error("INPUT_GRAPH");
920
- if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) throw new Error("INPUT_OBJECT");
921
- ancestors.add(v);
922
- for (const key of Reflect.ownKeys(v)) {
923
- const descriptor = Object.getOwnPropertyDescriptor(v, key);
924
- if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(v) && key === "length")) throw new Error("INPUT_OBJECT");
925
- visit(descriptor.value, depth + 1);
926
- }
927
- ancestors.delete(v);
928
- };
929
- visit(value, 0);
930
- }
931
- function deepFreeze(value) {
932
- if (value && typeof value === "object" && !Object.isFrozen(value)) {
933
- Object.freeze(value);
934
- for (const item of Object.values(value)) deepFreeze(item);
935
- }
936
- return value;
937
- }
938
- //#endregion
939
- //#region src/rulesets.ts
940
- function canonical(value) {
941
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
942
- if (value && typeof value === "object") return `{${domainIdentityFields(value).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
943
- return JSON.stringify(value);
944
- }
945
- function validateRuleSets(entries, engine, diagnostics, path) {
946
- const definitions = /* @__PURE__ */ new Map();
947
- const urls = /* @__PURE__ */ new Map();
948
- const error = (code) => diagnostics.push({
949
- severity: "error",
950
- code,
951
- path,
952
- message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
953
- });
954
- const visit = (m) => {
955
- if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
956
- const key = canonical(m);
957
- if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
958
- definitions.set(m.id, key);
959
- if (m.type === "ruleSet") visit(m.when);
960
- else {
961
- if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
962
- if (m.engine === "surge") {
963
- const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
964
- const url = new URL(m.url).href;
965
- if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
966
- urls.set(url, settings);
967
- }
968
- }
969
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
970
- else if (m.type === "not") visit(m.condition);
971
- };
972
- const walk = (items) => {
973
- for (const item of items) if (item.type === "rule") visit(item.when);
974
- else if (item.type === "block") {
975
- if (item.when) visit(item.when);
976
- walk(item.rules);
977
- } else walk(item.policy.rules);
978
- };
979
- walk(entries);
980
- }
981
- function lowerRuleSets(rules, diagnostics, path) {
982
- let count = 0;
983
- let origins = 0;
984
- const lower = (m, origin, depth) => {
985
- if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
986
- if (m.type === "ruleSet") {
987
- origin.push(`rule-set:${m.id}`);
988
- return lower(m.when, origin, depth + 1);
989
- }
990
- if (m.type === "all" || m.type === "any") return {
991
- ...m,
992
- conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
993
- };
994
- if (m.type === "not") return {
995
- ...m,
996
- condition: lower(m.condition, origin, depth + 1)
997
- };
998
- return m;
999
- };
1000
- try {
1001
- if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
1002
- return rules.map((r) => {
1003
- const origin = [...r.origin];
1004
- const when = lower(r.when, origin, 0);
1005
- origins += origin.length;
1006
- if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
1007
- return {
1008
- ...r,
1009
- when,
1010
- origin
1011
- };
1012
- });
1013
- } catch {
1014
- diagnostics.push({
1015
- severity: "error",
1016
- code: "EXPANSION_LIMIT",
1017
- path,
1018
- message: "展开规则、条件或来源超过预算"
1019
- });
1020
- return [];
1021
- }
1022
- }
1023
- function collectNativeRuleSets(rules, target, diagnostics) {
1024
- const found = /* @__PURE__ */ new Map();
1025
- const visit = (m, nested) => {
1026
- if (m.type === "nativeRuleSet") {
1027
- found.set(m.id, m);
1028
- if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
1029
- severity: "error",
1030
- code: "RULESET_COMPOSITION_UNSUPPORTED",
1031
- target: target.id,
1032
- path: `targets.${target.id}.ruleSets.${m.id}`,
1033
- message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
1034
- });
1035
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
1036
- else if (m.type === "not") visit(m.condition, true);
1037
- else if (m.type === "ruleSet") visit(m.when, nested);
1038
- };
1039
- rules.forEach((r) => visit(r.when, false));
1040
- for (const r of found.values()) diagnostics.push({
1041
- severity: "warning",
1042
- code: "EXTERNAL_RULESET_UNVERIFIED",
1043
- target: target.id,
1044
- path: `targets.${target.id}.ruleSets.${r.id}`,
1045
- message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
1046
- });
1047
- return [...found.values()];
1048
- }
1049
- //#endregion
1050
- //#region src/singbox-semantics.ts
1051
- const builtinMember = (id) => id === "DIRECT" || id === "REJECT";
1052
- const singboxMemberTag = (id) => id === "DIRECT" ? "pl-direct" : id === "REJECT" ? "pl-reject" : id;
1053
- /** Only top-level atoms (or transparent named wrappers) can request ordered DNS. */
1054
- function needsResolve(condition) {
1055
- if (condition.type === "ruleSet") return needsResolve(condition.when);
1056
- return condition.type === "ipCidr" && condition.noResolve !== true || condition.type === "nativeRuleSet" && condition.engine === "sing-box" && condition.resolve === true;
1057
- }
1058
- var StaticMetadataUnknownError = class extends Error {
1059
- constructor() {
1060
- super("STATIC_METADATA_UNKNOWN");
1061
- this.name = "StaticMetadataUnknownError";
1062
- }
1063
- };
1064
- function requestForProgram(program, request) {
1065
- if (program.domainMatching !== "prefer-sniffed") return request;
1066
- if (request.tlsSni && request.httpHost && request.tlsSni !== request.httpHost) throw new StaticMetadataUnknownError();
1067
- return {
1068
- ...request,
1069
- domain: request.tlsSni || request.httpHost || request.domain,
1070
- tlsSni: void 0,
1071
- httpHost: void 0
1072
- };
1073
- }
1074
- //#endregion
1075
- //#region src/rules.ts
1076
- function expandRules(entries, diagnostics, path = "routing") {
1077
- const output = [];
1078
- const seen = /* @__PURE__ */ new Set();
1079
- let limited = false;
1080
- const error = (code, where, message) => diagnostics.push({
1081
- severity: "error",
1082
- code,
1083
- path: where,
1084
- message
1085
- });
1086
- function resolve(action, bindings, inPolicy, where) {
1087
- if (action.type === "slot") {
1088
- if (!Object.hasOwn(bindings, action.name)) {
1089
- error("UNBOUND_SLOT", where, "出口槽位未声明或未绑定");
1090
- return;
1091
- }
1092
- return bindings[action.name];
1093
- }
1094
- if (inPolicy && action.type === "route") {
1095
- error("POLICY_RESOURCE_CAPTURE", where, "共享 policy 必须通过 slot 引用出口");
1096
- return;
1097
- }
1098
- return action;
1099
- }
1100
- function walk(items, prefix, guards, bindings, inPolicy, origin) {
1101
- for (const entry of items) {
1102
- if (limited) return;
1103
- if (entry.type === "rule" && output.length >= 1e4) {
1104
- limited = true;
1105
- error("EXPANSION_LIMIT", path, "展开规则超过10000条");
1106
- return;
1107
- }
1108
- const id = `${prefix}/${entry.id}`;
1109
- if (seen.has(id)) {
1110
- error("DUPLICATE_RULE_ID", id, "同一实例路径出现重复 ID");
1111
- continue;
1112
- }
1113
- seen.add(id);
1114
- if (entry.type === "rule") {
1115
- const action = resolve(entry.then, bindings, inPolicy, id);
1116
- if (action) output.push({
1117
- id,
1118
- when: guards.length ? match.all(...guards, entry.when) : entry.when,
1119
- then: action,
1120
- origin: [...origin, entry.id]
1121
- });
1122
- } else if (entry.type === "block") walk(entry.rules, id, entry.when ? [...guards, entry.when] : guards, bindings, inPolicy, [...origin, entry.id]);
1123
- else {
1124
- const expected = new Set(entry.policy.exits);
1125
- if (Object.keys(entry.bindings).some((key) => !expected.has(key)) || entry.policy.exits.some((key) => !Object.hasOwn(entry.bindings, key))) {
1126
- error("POLICY_BINDINGS", id, "bindings 必须完整且只包含 policy 声明的出口");
1127
- continue;
1128
- }
1129
- const bound = Object.create(null);
1130
- for (const key of entry.policy.exits) {
1131
- const result = resolve(entry.bindings[key], bindings, inPolicy, `${id}/bindings/${key}`);
1132
- if (result) bound[key] = result;
1133
- }
1134
- walk(entry.policy.rules, id, guards, bound, true, [
1135
- ...origin,
1136
- `use:${entry.id}`,
1137
- `policy:${entry.policy.id}`
1138
- ]);
1139
- }
1140
- }
1141
- }
1142
- walk(entries, path, [], {}, false, []);
1143
- return limited ? [] : output;
1144
- }
1145
- function inCidr(address, cidr) {
1146
- if (!address) return false;
1147
- const parsed = ipaddr.parse(address);
1148
- const [base, bits] = ipaddr.parseCIDR(cidr.includes("/") ? cidr : `${cidr}/${cidr.includes(":") ? 128 : 32}`);
1149
- return parsed.kind() === base.kind() && parsed.match(base, bits);
1150
- }
1151
- var StaticRuleSetUnknownError = class extends Error {
1152
- constructor() {
1153
- super("STATIC_RULESET_UNKNOWN");
1154
- this.name = "StaticRuleSetUnknownError";
1155
- }
1156
- };
1157
- function evaluate(condition, request) {
1158
- if (condition.type === "ruleSet") return evaluate(condition.when, request);
1159
- if (condition.type === "nativeRuleSet") return {
1160
- type: condition.type,
1161
- matched: null,
1162
- reason: "外部规则内容由客户端解释,静态未知"
1163
- };
1164
- if (condition.type === "all" || condition.type === "any") {
1165
- const children = condition.conditions.map((child) => evaluate(child, request));
1166
- const matched = condition.type === "all" ? children.some((child) => child.matched === false) ? false : children.some((child) => child.matched === null) ? null : true : children.some((child) => child.matched === true) ? true : children.some((child) => child.matched === null) ? null : false;
1167
- return {
1168
- type: condition.type,
1169
- matched,
1170
- reason: condition.type === "all" ? "所有子条件同时成立" : "至少一个子条件成立",
1171
- children
1172
- };
1173
- }
1174
- if (condition.type === "not") {
1175
- const child = evaluate(condition.condition, request);
1176
- return {
1177
- type: "not",
1178
- matched: child.matched === null ? null : !child.matched,
1179
- reason: "布尔取反;缺失字段的原子条件为 false",
1180
- children: [child]
1181
- };
1182
- }
1183
- let matched;
1184
- let present;
1185
- switch (condition.type) {
1186
- case "domain":
1187
- case "domainSuffix": {
1188
- const domains = condition.includeSniffed ? [
1189
- request.domain,
1190
- request.tlsSni,
1191
- request.httpHost
1192
- ] : [request.domain];
1193
- present = domains.some((value) => value !== void 0);
1194
- matched = domains.some((value) => value !== void 0 && (value === condition.value || condition.type === "domainSuffix" && value.endsWith(`.${condition.value}`)));
1195
- break;
1196
- }
1197
- case "ipCidr":
1198
- present = request.ip !== void 0;
1199
- matched = inCidr(request.ip, condition.value);
1200
- break;
1201
- case "processName":
1202
- present = request.processName !== void 0;
1203
- matched = request.processName === condition.value;
1204
- break;
1205
- case "sourceIp":
1206
- present = request.sourceIp !== void 0;
1207
- matched = inCidr(request.sourceIp, condition.value);
1208
- break;
1209
- case "port":
1210
- present = request.port !== void 0;
1211
- matched = present && request.port >= condition.from && request.port <= condition.to;
1212
- break;
1213
- case "sourcePort":
1214
- present = request.sourcePort !== void 0;
1215
- matched = present && request.sourcePort >= condition.from && request.sourcePort <= condition.to;
1216
- break;
1217
- case "network":
1218
- present = true;
1219
- matched = request.network === condition.value;
1220
- }
1221
- return {
1222
- type: condition.type,
1223
- matched,
1224
- reason: present ? matched ? "匹配" : "不匹配" : "字段缺失,原子条件为 false"
1225
- };
1226
- }
1227
- function explainRules(rules, fallback, input, orderedResolve = false) {
1228
- const parsed = requestSchema.safeParse(input);
1229
- if (!parsed.success) throw new Error("INVALID_REQUEST");
1230
- const trace = [];
1231
- for (const rule of rules) {
1232
- if (orderedResolve && needsResolve(rule.when) && parsed.data.domain && !parsed.data.ip) throw new StaticMetadataUnknownError();
1233
- const condition = evaluate(rule.when, parsed.data);
1234
- trace.push({
1235
- id: rule.id,
1236
- origin: rule.origin,
1237
- condition
1238
- });
1239
- if (condition.matched === null) throw new StaticRuleSetUnknownError();
1240
- if (condition.matched) return {
1241
- mode: "static",
1242
- rule: rule.id,
1243
- action: rule.then,
1244
- trace
1245
- };
1246
- }
1247
- return {
1248
- mode: "static",
1249
- rule: "$fallback",
1250
- action: fallback,
1251
- trace
1252
- };
1253
- }
1254
- /** Over-approximation of possible truth values, never a proof from unobserved metadata. */
1255
- function truthPossibilities(condition, network) {
1256
- switch (condition.type) {
1257
- case "ruleSet": return truthPossibilities(condition.when, network);
1258
- case "network": return [condition.value === network];
1259
- case "not": return truthPossibilities(condition.condition, network).map((v) => !v);
1260
- case "all": {
1261
- const sets = condition.conditions.map((c) => truthPossibilities(c, network));
1262
- return [...sets.every((s) => s.includes(true)) ? [true] : [], ...sets.some((s) => s.includes(false)) ? [false] : []];
1263
- }
1264
- case "any": {
1265
- const sets = condition.conditions.map((c) => truthPossibilities(c, network));
1266
- return [...sets.some((s) => s.includes(true)) ? [true] : [], ...sets.every((s) => s.includes(false)) ? [false] : []];
1267
- }
1268
- default: return [false, true];
1269
- }
1270
- }
1271
- function logicalDepth(condition) {
1272
- if (condition.type === "ruleSet") return logicalDepth(condition.when);
1273
- if (condition.type === "all" || condition.type === "any") return 1 + Math.max(...condition.conditions.map(logicalDepth));
1274
- if (condition.type === "not") return 1 + logicalDepth(condition.condition);
1275
- return 0;
1276
- }
1277
- //#endregion
1278
- //#region src/proxies.ts
1279
- var RenderError = class extends Error {
1280
- code;
1281
- constructor(code) {
1282
- super(code);
1283
- this.code = code;
1284
- this.name = "RenderError";
1285
- }
1286
- };
1287
- function pathsOverlap(a, b) {
1288
- return a === b || a.startsWith(b.endsWith("/") ? b : `${b}/`) || b.startsWith(a.endsWith("/") ? a : `${a}/`);
1289
- }
1290
- function nodeIsTcpOnly(node, engine, version) {
1291
- return node.type === "http" || node.type === "anytls" && engine !== "surge" && !(engine === "sing-box" && version === "1.14.4") || node.type === "vmess" || node.type === "vless" && !(engine === "sing-box" && version === "1.14.4" && node.packetEncoding) || engine === "surge" && node.type === "shadowsocks" && node.surge?.udpRelay === false;
1292
- }
1293
- function validateProxyOptions(node, target, diagnostics) {
1294
- if (node.type === "hysteria2") {
1295
- if (target.engine === "surge" && node.portHopping && node.via) diagnostics.push({
1296
- severity: "error",
1297
- code: "PROXY_OPTION_UNSUPPORTED",
1298
- target: target.id,
1299
- path: `targets.${target.id}.nodes.${node.id}`,
1300
- message: "Surge 端口跳跃不能与 underlying-proxy 同用"
1301
- });
1302
- return;
1303
- }
1304
- const tls = "tls" in node ? node.tls : void 0;
1305
- const modern = target.engine === "sing-box" && target.version === "1.14.4";
1306
- if (node.type === "vless" && !modern && (node.flow !== void 0 || node.packetEncoding !== void 0 || node.reality !== void 0 || node.utlsFingerprint !== void 0)) diagnostics.push({
1307
- severity: "error",
1308
- code: "PROXY_OPTION_UNSUPPORTED",
1309
- target: target.id,
1310
- path: `targets.${target.id}.nodes.${node.id}`,
1311
- message: "VLESS 扩展选项仅支持 sing-box 1.14.4"
1312
- });
1313
- if (target.engine !== "surge") {
1314
- const surgeOptions = "surge" in node ? node.surge : void 0;
1315
- const supportedUdpDeclaration = modern && surgeOptions !== void 0 && [
1316
- "trojan",
1317
- "anytls",
1318
- "shadowsocks"
1319
- ].includes(node.type) && Object.keys(surgeOptions).length === 1 && "udpRelay" in surgeOptions && surgeOptions.udpRelay === true;
1320
- if (!modern && node.tcpFastOpen !== void 0 || modern && node.type === "anytls" && node.tcpFastOpen === true || !modern && "skipCertVerify" in node && node.skipCertVerify !== void 0 || !modern && tls?.skipCertVerify !== void 0 || surgeOptions !== void 0 && !supportedUdpDeclaration) diagnostics.push({
1321
- severity: "error",
1322
- code: "PROXY_OPTION_UNSUPPORTED",
1323
- target: target.id,
1324
- path: `targets.${target.id}.nodes.${node.id}`,
1325
- message: "显式节点选项尚未实现此精确目标的编码"
1326
- });
1327
- return;
1328
- }
1329
- if (("serverName" in node ? node.serverName : tls?.serverName) === "off" || tls?.alpn !== void 0) diagnostics.push({
1330
- severity: "error",
1331
- code: "PROXY_OPTION_UNSUPPORTED",
1332
- target: target.id,
1333
- path: `targets.${target.id}.nodes.${node.id}`,
1334
- message: "Surge 编码不接受特殊 SNI off 或显式 ALPN;不会丢弃 TLS 选项"
1335
- });
1336
- }
1337
- function uuid(token, secret) {
1338
- const value = secret(token);
1339
- if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) throw new RenderError("INVALID_UUID_SECRET");
1340
- return value;
1341
- }
1342
- function aliasProxyServer(node, aliases) {
1343
- const server = aliases?.[node.server];
1344
- if (!server) return node;
1345
- if (node.type === "trojan" || node.type === "anytls" || node.type === "hysteria2") return {
1346
- ...node,
1347
- server,
1348
- serverName: node.serverName ?? node.server
1349
- };
1350
- return {
1351
- ...node,
1352
- server
1353
- };
1354
- }
1355
- function singboxProxy(node, secret) {
1356
- const result = {
1357
- type: node.type,
1358
- tag: node.id,
1359
- server: node.server,
1360
- server_port: node.port,
1361
- ...node.via ? { detour: node.via } : {},
1362
- ...node.tcpFastOpen !== void 0 ? { tcp_fast_open: node.tcpFastOpen } : {}
1363
- };
1364
- switch (node.type) {
1365
- case "hysteria2":
1366
- result.password = secret(node.password);
1367
- result.tls = {
1368
- enabled: true,
1369
- ...node.serverName ? { server_name: node.serverName } : {},
1370
- ...node.skipCertVerify !== void 0 ? { insecure: node.skipCertVerify } : {}
1371
- };
1372
- if (node.portHopping) {
1373
- delete result.server_port;
1374
- result.server_ports = node.portHopping.split(";").map((part) => part.includes("-") ? part.replace("-", ":") : `${part}:${part}`);
1375
- }
1376
- if (node.portHoppingInterval !== void 0) result.hop_interval = `${node.portHoppingInterval}s`;
1377
- break;
1378
- case "http":
1379
- result.password = secret(node.password);
1380
- if (node.username) result.username = secret(node.username);
1381
- break;
1382
- case "trojan":
1383
- case "anytls":
1384
- result.password = secret(node.password);
1385
- result.tls = {
1386
- enabled: true,
1387
- ...node.serverName ? { server_name: node.serverName } : {},
1388
- ...node.skipCertVerify !== void 0 ? { insecure: node.skipCertVerify } : {}
1389
- };
1390
- break;
1391
- case "shadowsocks":
1392
- result.password = secret(node.password);
1393
- result.method = node.method;
1394
- break;
1395
- case "vmess":
1396
- case "vless":
1397
- result.uuid = uuid(node.uuid, secret);
1398
- result.network = "tcp";
1399
- if (node.type === "vless") {
1400
- if (node.flow) result.flow = node.flow;
1401
- if (node.packetEncoding) {
1402
- result.packet_encoding = node.packetEncoding;
1403
- delete result.network;
1404
- }
1405
- }
1406
- if (node.type === "vmess") Object.assign(result, {
1407
- security: "aes-128-gcm",
1408
- alter_id: 0
1409
- });
1410
- if (node.tls) result.tls = {
1411
- enabled: true,
1412
- server_name: node.tls.serverName,
1413
- ...node.tls.alpn ? { alpn: [...node.tls.alpn] } : {},
1414
- ...node.tls.skipCertVerify !== void 0 ? { insecure: node.tls.skipCertVerify } : {},
1415
- ...node.type === "vless" && node.utlsFingerprint ? { utls: {
1416
- enabled: true,
1417
- fingerprint: node.utlsFingerprint
1418
- } } : {},
1419
- ...node.type === "vless" && node.reality ? { reality: {
1420
- enabled: true,
1421
- public_key: node.reality.publicKey,
1422
- short_id: node.reality.shortId
1423
- } } : {}
1424
- };
1425
- if (node.transport) result.transport = {
1426
- type: "ws",
1427
- path: node.transport.path,
1428
- ...node.transport.host ? { headers: { Host: node.transport.host } } : {}
1429
- };
1430
- }
1431
- return result;
1432
- }
1433
- function clashProxy(node, engine, secret) {
1434
- const result = {
1435
- name: node.id,
1436
- type: node.type === "shadowsocks" ? "ss" : node.type,
1437
- server: node.server,
1438
- port: node.port,
1439
- ...node.via ? { "dialer-proxy": node.via } : {},
1440
- ...engine === "stash" ? { "block-quic": "off" } : {}
1441
- };
1442
- switch (node.type) {
1443
- case "hysteria2":
1444
- result[engine === "stash" ? "auth" : "password"] = secret(node.password);
1445
- if (node.serverName) result.sni = node.serverName;
1446
- if (node.skipCertVerify !== void 0) result["skip-cert-verify"] = node.skipCertVerify;
1447
- if (node.portHopping) result.ports = node.portHopping.replaceAll(";", ",");
1448
- if (node.portHoppingInterval !== void 0) result["hop-interval"] = node.portHoppingInterval;
1449
- break;
1450
- case "http":
1451
- result.password = secret(node.password);
1452
- if (node.username) result.username = secret(node.username);
1453
- break;
1454
- case "trojan":
1455
- case "anytls":
1456
- result.password = secret(node.password);
1457
- if (node.serverName) result.sni = node.serverName;
1458
- if (node.type === "trojan") result.udp = true;
1459
- break;
1460
- case "shadowsocks":
1461
- result.password = secret(node.password);
1462
- result.cipher = node.method;
1463
- result.udp = true;
1464
- break;
1465
- case "vmess":
1466
- case "vless":
1467
- result.uuid = uuid(node.uuid, secret);
1468
- result.udp = false;
1469
- if (node.type === "vmess") Object.assign(result, {
1470
- cipher: "aes-128-gcm",
1471
- alterId: 0
1472
- });
1473
- result.tls = !!node.tls;
1474
- if (node.tls) {
1475
- result[engine === "stash" ? "sni" : "servername"] = node.tls.serverName;
1476
- if (node.tls.alpn) result.alpn = [...node.tls.alpn];
1477
- }
1478
- if (node.transport) {
1479
- result.network = "ws";
1480
- result["ws-opts"] = {
1481
- path: node.transport.path,
1482
- ...node.transport.host ? { headers: { Host: node.transport.host } } : {}
1483
- };
1484
- }
1485
- }
1486
- return result;
1487
- }
1488
- function surgeProxy(node, secret, name = (id) => id) {
1489
- const atom = (value) => {
1490
- if (!/^[A-Za-z0-9_./:@+%-]+$/.test(value)) throw new RenderError("SURGE_VALUE_UNREPRESENTABLE");
1491
- return value;
1492
- };
1493
- const params = [
1494
- `${name(node.id)} = ${node.type === "shadowsocks" ? "ss" : node.type}`,
1495
- node.server,
1496
- String(node.port)
1497
- ];
1498
- switch (node.type) {
1499
- case "http":
1500
- if (node.username) params.push(`username=${atom(secret(node.username))}`);
1501
- params.push(`password=${atom(secret(node.password))}`);
1502
- break;
1503
- case "hysteria2":
1504
- params.push(`password=${atom(secret(node.password))}`);
1505
- if (node.serverName) params.push(`sni=${node.serverName}`);
1506
- if (node.skipCertVerify !== void 0) params.push(`skip-cert-verify=${node.skipCertVerify}`);
1507
- if (node.portHopping) params.push(`port-hopping=${node.portHopping}`);
1508
- if (node.portHoppingInterval !== void 0) params.push(`port-hopping-interval=${node.portHoppingInterval}`);
1509
- break;
1510
- case "trojan":
1511
- case "anytls":
1512
- params.push(`password=${atom(secret(node.password))}`);
1513
- if (node.serverName) params.push(`sni=${node.serverName}`);
1514
- if (node.skipCertVerify !== void 0) params.push(`skip-cert-verify=${node.skipCertVerify}`);
1515
- break;
1516
- case "shadowsocks":
1517
- params.push(`encrypt-method=${node.method}`, `password=${atom(secret(node.password))}`);
1518
- break;
1519
- case "vmess":
1520
- params.push(`username=${uuid(node.uuid, secret)}`, "vmess-aead=true", "encrypt-method=aes-128-gcm", `tls=${!!node.tls}`);
1521
- if (node.tls) params.push(`sni=${node.tls.serverName}`);
1522
- if (node.tls?.skipCertVerify !== void 0) params.push(`skip-cert-verify=${node.tls.skipCertVerify}`);
1523
- if (node.transport) {
1524
- params.push("ws=true", `ws-path=${node.transport.path}`);
1525
- if (node.transport.host) params.push(`ws-headers=Host:${node.transport.host}`);
1526
- }
1527
- break;
1528
- case "vless": throw new RenderError("PROTOCOL_UNSUPPORTED");
1529
- }
1530
- if (node.tcpFastOpen !== void 0) params.push(`tfo=${node.tcpFastOpen}`);
1531
- if (node.type === "trojan" || node.type === "anytls" && node.surge?.udpRelay) params.push("udp-relay=true");
1532
- if (node.type === "shadowsocks") params.push(`udp-relay=${node.surge?.udpRelay ?? true}`, `block-quic=${node.surge?.blockQuic ?? "off"}`);
1533
- if (node.type !== "shadowsocks" && "surge" in node && node.surge?.blockQuic !== void 0) params.push(`block-quic=${node.surge.blockQuic}`);
1534
- if (node.via) params.push(`underlying-proxy=${name(node.via)}`);
1535
- return params.join(", ");
1536
- }
1537
- //#endregion
1538
- //#region src/clash.ts
1539
- /** Shared syntax is not a shared capability declaration: validate each exact target first. */
1540
- function validateClashTarget(target, rules, diagnostics) {
1541
- if (target.engine !== "stash") return;
1542
- if (target.mode === "standalone") diagnostics.push({
1543
- severity: "error",
1544
- code: "MODE_UNSUPPORTED",
1545
- path: `targets.${target.id}.mode`,
1546
- target: target.id,
1547
- message: "Stash 仅支持 fragment;系统接管不能等价为本机显式代理"
1548
- });
1549
- const visit = (condition, path) => {
1550
- if (condition.type === "sourceIp" || condition.type === "sourcePort" || condition.type === "port" && condition.from !== condition.to) diagnostics.push({
1551
- severity: "error",
1552
- code: "MATCH_UNSUPPORTED",
1553
- path,
1554
- target: target.id,
1555
- message: "Stash 4.2.1 不支持来源匹配或端口范围;不会省略条件"
1556
- });
1557
- if (condition.type === "all" || condition.type === "any") condition.conditions.forEach((child, i) => visit(child, `${path}.conditions.${i}`));
1558
- if (condition.type === "not") visit(condition.condition, `${path}.condition`);
1559
- };
1560
- for (const rule of rules) visit(rule.when, `${rule.id}.when`);
1561
- }
1562
- function clashGroup(group, name = (id) => id) {
1563
- if (group.type !== "select" && group.type !== "urltest") throw new Error("GROUP_UNSUPPORTED");
1564
- return {
1565
- name: name(group.id),
1566
- type: group.type === "select" ? "select" : "url-test",
1567
- proxies: group.members.map(name),
1568
- ...group.type === "urltest" ? {
1569
- url: group.url,
1570
- interval: group.intervalSeconds ?? 180,
1571
- tolerance: group.toleranceMs ?? 50
1572
- } : {}
1573
- };
1574
- }
1575
- function conditionText$1(condition) {
1576
- switch (condition.type) {
1577
- case "ruleSet": return conditionText$1(condition.when);
1578
- case "nativeRuleSet": return `RULE-SET,${condition.id}`;
1579
- case "all":
1580
- case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${conditionText$1(c)})`).join(",")})`;
1581
- case "not": return `NOT,((${conditionText$1(condition.condition)}))`;
1582
- case "domain": return `DOMAIN,${condition.value}`;
1583
- case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
1584
- case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}${condition.noResolve !== false ? ",no-resolve" : ""}`;
1585
- case "processName": return `PROCESS-NAME,${condition.value}`;
1586
- case "sourceIp": return `SRC-IP-CIDR,${condition.value.includes("/") ? condition.value : `${condition.value}/${condition.value.includes(":") ? 128 : 32}`}`;
1587
- case "network": return `NETWORK,${condition.value}`;
1588
- case "port":
1589
- case "sourcePort": return `${condition.type === "port" ? "DST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
1590
- }
1591
- }
1592
- const policy$2 = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
1593
- function clashConfig(plan, secret) {
1594
- const { program, target } = plan;
1595
- const config = {
1596
- proxies: program.nodes.map((node) => clashProxy(node, target.engine, secret)),
1597
- "proxy-groups": program.groups.map((g) => clashGroup(g)),
1598
- 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)}`]
1599
- };
1600
- if (plan.nativeRuleSets.length) config["rule-providers"] = Object.fromEntries(plan.nativeRuleSets.map((r) => [r.id, {
1601
- type: "http",
1602
- url: r.url,
1603
- path: `rule-providers/pl-${r.id}.${r.format === "yaml" ? "yaml" : "txt"}`,
1604
- interval: r.intervalSeconds,
1605
- behavior: "behavior" in r ? r.behavior : "classical",
1606
- format: r.format,
1607
- proxy: "DIRECT"
1608
- }]));
1609
- if (target.mode === "standalone") {
1610
- const listener = program.listener;
1611
- Object.assign(config, {
1612
- "mixed-port": listener.port,
1613
- "allow-lan": false,
1614
- "bind-address": "127.0.0.1",
1615
- mode: "rule",
1616
- ipv6: false,
1617
- "geo-auto-update": false,
1618
- sniffer: { enable: false },
1619
- dns: {
1620
- enable: true,
1621
- ipv6: false,
1622
- "enhanced-mode": "redir-host",
1623
- nameserver: [listener.resolver],
1624
- "default-nameserver": [listener.resolver],
1625
- "respect-rules": false,
1626
- "use-hosts": false,
1627
- "use-system-hosts": false
1628
- }
1629
- });
1630
- }
1631
- return config;
1632
- }
1633
- //#endregion
1634
- //#region src/targets.ts
1635
- const targetCatalog = deepFreeze([
1636
- {
1637
- engine: "sing-box",
1638
- version: "1.14.4",
1639
- autoGroup: "urltest",
1640
- platforms: ["linux", "macos"],
1641
- protocols: [
1642
- "hysteria2",
1643
- "trojan",
1644
- "http",
1645
- "anytls",
1646
- "shadowsocks",
1647
- "vmess",
1648
- "vless"
1649
- ],
1650
- endpoints: ["sing-box-tailscale"],
1651
- groups: ["select", "urltest"],
1652
- nativeRuleSets: ["source", "binary"],
1653
- dns: "typed"
1654
- },
1655
- {
1656
- engine: "sing-box",
1657
- version: "1.11.0",
1658
- autoGroup: "urltest",
1659
- platforms: ["linux", "macos"],
1660
- protocols: [
1661
- "hysteria2",
1662
- "trojan",
1663
- "http",
1664
- "shadowsocks",
1665
- "vmess",
1666
- "vless"
1667
- ],
1668
- endpoints: [],
1669
- groups: ["select", "urltest"],
1670
- nativeRuleSets: ["source", "binary"],
1671
- dns: "legacy"
1672
- },
1673
- {
1674
- engine: "sing-box",
1675
- version: "1.12.0",
1676
- autoGroup: "urltest",
1677
- platforms: ["linux", "macos"],
1678
- protocols: [
1679
- "hysteria2",
1680
- "trojan",
1681
- "http",
1682
- "anytls",
1683
- "shadowsocks",
1684
- "vmess",
1685
- "vless"
1686
- ],
1687
- endpoints: ["sing-box-tailscale"],
1688
- groups: ["select", "urltest"],
1689
- nativeRuleSets: ["source", "binary"],
1690
- dns: "typed"
1691
- },
1692
- {
1693
- engine: "surge",
1694
- version: "6.10.0",
1695
- autoGroup: "surge-smart",
1696
- platforms: ["macos"],
1697
- protocols: [
1698
- "hysteria2",
1699
- "trojan",
1700
- "http",
1701
- "anytls",
1702
- "shadowsocks",
1703
- "vmess"
1704
- ],
1705
- endpoints: [],
1706
- groups: ["select", "surge-smart"],
1707
- nativeRuleSets: ["rule-set", "domain-set"],
1708
- dns: "general"
1709
- },
1710
- {
1711
- engine: "mihomo",
1712
- version: "1.19.32",
1713
- autoGroup: "urltest",
1714
- platforms: ["linux", "macos"],
1715
- protocols: [
1716
- "hysteria2",
1717
- "trojan",
1718
- "http",
1719
- "anytls",
1720
- "shadowsocks",
1721
- "vmess",
1722
- "vless"
1723
- ],
1724
- endpoints: [],
1725
- groups: ["select", "urltest"],
1726
- nativeRuleSets: ["yaml", "text"],
1727
- dns: "clash"
1728
- },
1729
- {
1730
- engine: "stash",
1731
- version: "4.2.1",
1732
- autoGroup: null,
1733
- platforms: ["macos"],
1734
- protocols: [
1735
- "hysteria2",
1736
- "trojan",
1737
- "http",
1738
- "anytls",
1739
- "shadowsocks",
1740
- "vmess"
1741
- ],
1742
- endpoints: [],
1743
- groups: ["select"],
1744
- nativeRuleSets: [],
1745
- dns: "external"
1746
- }
1747
- ]);
1748
- //#endregion
1749
- //#region src/native-names.ts
1750
- const nativeNameSchema = z.string().min(1).max(256).refine((value) => value.trim() === value && !/[\p{C}\p{Zl}\p{Zp},=[\]()#;]/u.test(value) && !["DIRECT", "REJECT"].includes(value.toUpperCase()) && !value.toLowerCase().startsWith("pl-"));
1751
- function isReservedNativeName(name, engine) {
1752
- return (engine === "surge" ? [
1753
- "REJECT-DROP",
1754
- "REJECT-NO-DROP",
1755
- "REJECT-TINYGIF"
1756
- ] : engine === "mihomo" ? [
1757
- "GLOBAL",
1758
- "PASS",
1759
- "COMPATIBLE",
1760
- "REJECT-DROP",
1761
- "PASS-RULE"
1762
- ] : engine === "stash" ? [
1763
- "GLOBAL",
1764
- "PASS",
1765
- "COMPATIBLE",
1766
- "REJECT-DROP"
1767
- ] : []).includes(name.toUpperCase());
1768
- }
1769
- //#endregion
1770
- //#region src/strategies.ts
1771
- function satisfiesAlgorithm(requested, actual) {
1772
- if (requested.type === "auto") return actual.type === "urltest" || actual.type === "surge-smart";
1773
- if (requested.type === "select") return actual.type === "select";
1774
- return actual.type === "urltest" && actual.url === requested.url && (actual.intervalSeconds ?? 180) === (requested.intervalSeconds ?? 180) && (actual.toleranceMs ?? 50) === (requested.toleranceMs ?? 50);
1775
- }
1776
- function lowerStrategies(groups, target, diagnostics, path) {
1777
- const selected = [];
1778
- const selections = [];
1779
- const { engine } = target;
1780
- const descriptor = targetCatalog.find((d) => d.engine === engine && d.version === target.version && d.platforms.includes(target.platform));
1781
- for (const group of groups) {
1782
- if (group.type !== "strategy") {
1783
- selected.push(group);
1784
- continue;
1785
- }
1786
- const requested = group.algorithm;
1787
- if (requested && Object.values(group.implementations ?? {}).some((implementation) => implementation && !satisfiesAlgorithm(requested, implementation))) {
1788
- diagnostics.push({
1789
- severity: "error",
1790
- code: "ALGORITHM_CONTRACT_MISMATCH",
1791
- path: `${path}.groups.${group.id}.implementations`,
1792
- message: "平台实现不满足声明的通用算法或固定参数"
1793
- });
1794
- continue;
1795
- }
1796
- const override = group.implementations?.[engine];
1797
- let algorithm = override;
1798
- if (!algorithm && requested) {
1799
- if (requested.type !== "auto") algorithm = requested;
1800
- else if (descriptor?.autoGroup === "surge-smart") algorithm = { type: "surge-smart" };
1801
- else if (descriptor?.autoGroup === "urltest") algorithm = {
1802
- type: "urltest",
1803
- url: "https://www.gstatic.com/generate_204",
1804
- intervalSeconds: 180,
1805
- toleranceMs: 50
1806
- };
1807
- }
1808
- const code = !algorithm ? requested ? "GROUP_UNSUPPORTED" : "STRATEGY_IMPLEMENTATION_MISSING" : algorithm.type === "surge-smart" && engine !== "surge" ? "ALGORITHM_ENGINE_MISMATCH" : void 0;
1809
- if (code) {
1810
- diagnostics.push({
1811
- severity: "error",
1812
- code,
1813
- path: `${path}.groups.${group.id}`,
1814
- message: "策略没有目标实现或所选算法属于其它引擎"
1815
- });
1816
- continue;
1817
- }
1818
- selected.push({
1819
- id: group.id,
1820
- members: group.members,
1821
- ...algorithm
1822
- });
1823
- selections.push({
1824
- id: group.id,
1825
- engine,
1826
- algorithm,
1827
- members: group.members,
1828
- ...requested ? {
1829
- requestedAlgorithm: requested,
1830
- implementationSource: override ? "override" : "default"
1831
- } : {}
1832
- });
1833
- }
1834
- return {
1835
- groups: selected,
1836
- selections
1837
- };
1838
- }
1839
- function validateSmartMembers(groups, nodes, diagnostics, path) {
1840
- for (const group of groups) if (group.type === "surge-smart" && group.members.some((member) => !nodes.has(member))) diagnostics.push({
1841
- severity: "error",
1842
- code: "SMART_MEMBER_UNSUPPORTED",
1843
- path: `${path}.groups.${group.id}`,
1844
- message: "Surge Smart 成员只能是节点,不能是组或内建动作"
1845
- });
1846
- }
1847
- function surgeGroup(group, name = (id) => id) {
1848
- if (group.type !== "select" && group.type !== "surge-smart") throw new Error("GROUP_UNSUPPORTED");
1849
- return `${name(group.id)} = ${group.type === "surge-smart" ? "smart" : "select"}, ${group.members.map(name).join(", ")}`;
1850
- }
1851
- function singboxGroup(group, name = (id) => id) {
1852
- if (group.type !== "select" && group.type !== "urltest") throw new Error("GROUP_UNSUPPORTED");
1853
- return group.type === "select" ? {
1854
- type: "selector",
1855
- tag: name(group.id),
1856
- outbounds: group.members.map(name),
1857
- default: name(group.members[0]),
1858
- interrupt_exist_connections: false
1859
- } : {
1860
- type: "urltest",
1861
- tag: name(group.id),
1862
- outbounds: group.members.map(name),
1863
- url: group.url,
1864
- interval: `${group.intervalSeconds ?? 180}s`,
1865
- tolerance: group.toleranceMs ?? 50,
1866
- idle_timeout: "30m",
1867
- interrupt_exist_connections: false
1868
- };
1869
- }
1870
- const inputSchema$1 = z.strictObject({
1871
- target: z.strictObject({
1872
- engine: z.enum([
1873
- "surge",
1874
- "sing-box",
1875
- "mihomo",
1876
- "stash"
1877
- ]),
1878
- platform: z.enum(["macos", "linux"]),
1879
- version: z.string().regex(/^\d+\.\d+\.\d+$/)
1880
- }),
1881
- nodes: z.array(z.strictObject({
1882
- id: idSchema,
1883
- nativeName: nativeNameSchema
1884
- })).max(1e3),
1885
- strategies: z.array(strategySchema).max(1e3),
1886
- names: z.record(idSchema, nativeNameSchema).optional()
1887
- });
1888
- /** Only group topology/encoding is checked here; nodes, via, protocols and routes remain consumer-owned. */
1889
- function compileStrategyGroups(input) {
1890
- const diagnostics = [];
1891
- const error = (code, path, message) => diagnostics.push({
1892
- severity: "error",
1893
- code,
1894
- path,
1895
- message
1896
- });
1897
- const failure = () => deepFreeze({
1898
- ok: false,
1899
- artifactKind: "strategy-groups",
1900
- diagnostics,
1901
- selections: [],
1902
- content: null
1903
- });
1904
- try {
1905
- assertData(input);
1906
- } catch {
1907
- error("INVALID_INPUT_GRAPH", "$", "输入不是有限的声明数据");
1908
- return failure();
1909
- }
1910
- const parsed = inputSchema$1.safeParse(input);
1911
- if (!parsed.success) {
1912
- error("INVALID_SCHEMA", "$", "策略目录、名字或目标不符合严格 schema");
1913
- return failure();
1914
- }
1915
- const { target, nodes, strategies, names = {} } = parsed.data;
1916
- const descriptor = targetCatalog.find((d) => d.engine === target.engine && d.version === target.version && d.platforms.includes(target.platform));
1917
- if (!descriptor) {
1918
- error("UNKNOWN_TARGET", "target", "引擎、平台与精确版本不在支持目录");
1919
- return failure();
1920
- }
1921
- const ids = [...nodes.map((n) => n.id), ...strategies.map((s) => s.id)];
1922
- if (new Set(ids).size !== ids.length || ids.length > 1e3) error("DUPLICATE_RESOURCE", "$", "资源 ID 必须唯一且总数不超过 1000");
1923
- if (Object.keys(names).some((id) => !strategies.some((s) => s.id === id))) error("UNKNOWN_NAME_MAPPING", "names", "只能映射已声明策略 ID");
1924
- const nativeNames = new Map([...nodes.map((n) => [n.id, n.nativeName]), ...strategies.map((s) => [s.id, Object.hasOwn(names, s.id) ? names[s.id] : s.id])]);
1925
- if ([...nativeNames.values()].some((name) => !nativeNameSchema.safeParse(name).success)) error("INVALID_NATIVE_NAME", "names", "最终名称不符合原生名称约束");
1926
- if ([...nativeNames.values()].some((value) => isReservedNativeName(value, target.engine))) error("INVALID_NATIVE_NAME", "names", "最终名称与目标内建策略冲突");
1927
- if (new Set(nativeNames.values()).size !== nativeNames.size) error("DUPLICATE_NATIVE_NAME", "names", "最终节点和策略名称必须唯一");
1928
- const { groups, selections } = lowerStrategies(strategies, target, diagnostics, "$");
1929
- const all = new Set(ids);
1930
- for (const g of groups) {
1931
- if (!descriptor.groups.includes(g.type)) error("GROUP_UNSUPPORTED", `strategies.${g.id}`, "目标后端不能保持此算法的参数语义");
1932
- for (const member of g.members) if (!all.has(member)) error("MISSING_REFERENCE", `strategies.${g.id}`, "成员不在节点或策略目录中");
1933
- }
1934
- const byId = new Map(groups.map((g) => [g.id, g]));
1935
- const state = /* @__PURE__ */ new Map();
1936
- const visit = (id) => {
1937
- if (state.get(id) === 1) {
1938
- error("RESOURCE_CYCLE", `strategies.${id}`, "组依赖形成循环");
1939
- return;
1940
- }
1941
- if (state.get(id) === 2) return;
1942
- state.set(id, 1);
1943
- for (const member of byId.get(id)?.members ?? []) visit(member);
1944
- state.set(id, 2);
1945
- };
1946
- if (ids.length <= 1e3) for (const id of byId.keys()) visit(id);
1947
- validateSmartMembers(groups, new Set(nodes.map((n) => n.id)), diagnostics, "$");
1948
- if (diagnostics.length) return failure();
1949
- const name = (id) => nativeNames.get(id);
1950
- return deepFreeze({
1951
- ok: true,
1952
- artifactKind: "strategy-groups",
1953
- diagnostics,
1954
- selections,
1955
- content: target.engine === "surge" ? groups.map((g) => surgeGroup(g, name)).join("\n") + "\n" : target.engine === "mihomo" || target.engine === "stash" ? stringify({ "proxy-groups": groups.map((g) => clashGroup(g, name)) }) : JSON.stringify(groups.map((g) => singboxGroup(g, name)), null, 2) + "\n"
1956
- });
1957
- }
1958
- //#endregion
1959
- //#region src/compiler.ts
1960
- function compile(input) {
1961
- const diagnostics = [];
1962
- const plans = [];
1963
- const cases = [];
1964
- const error = (code, path, message, target) => diagnostics.push({
1965
- severity: "error",
1966
- code,
1967
- path,
1968
- message,
1969
- ...target ? { target } : {}
1970
- });
1971
- try {
1972
- assertData(input);
1973
- } catch {
1974
- error("INVALID_INPUT_GRAPH", "$", "配置必须是无循环的有限数据图(最多 64 层、100000 项),不得包含访问器或可执行值");
1975
- return deepFreeze({
1976
- ok: false,
1977
- diagnostics,
1978
- plans: [],
1979
- cases
1980
- });
1981
- }
1982
- const parsed = configSchema.safeParse(input);
1983
- if (!parsed.success) {
1984
- 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));
1985
- return deepFreeze({
1986
- ok: false,
1987
- diagnostics,
1988
- plans: [],
1989
- cases
1990
- });
1991
- }
1992
- const config = deepFreeze(parsed.data);
1993
- const expanded = /* @__PURE__ */ new Map();
1994
- if (Object.keys(config.programs).length === 0) error("EMPTY_PROGRAMS", "programs", "至少需要一个程序");
1995
- for (const [name, program] of Object.entries(config.programs)) {
1996
- const path = `programs.${name}`;
1997
- const programTargets = config.targets.filter((target) => target.program === name);
1998
- const supportsHostname = program.engine === "sing-box" && programTargets.length > 0 && programTargets.every((target) => target.version === "1.14.4");
1999
- for (const node of program.nodes) if (!isIP(node.server) && !supportsHostname) error("PROXY_HOSTNAME_MODE_UNSUPPORTED", `${path}.nodes.${node.id}`, "域名代理地址仅支持节点片段入口或 sing-box 1.14.4");
2000
- validateRuleSets(program.routing, program.engine, diagnostics, path);
2001
- const rules = lowerRuleSets(expandRules(program.routing, diagnostics, name), diagnostics, path);
2002
- expanded.set(name, rules);
2003
- const endpoints = program.endpoints ?? [];
2004
- const resources = [
2005
- ...program.nodes,
2006
- ...program.groups,
2007
- ...endpoints
2008
- ];
2009
- const byId = new Map(resources.map((resource) => [resource.id, resource]));
2010
- if (byId.size !== resources.length) error("DUPLICATE_RESOURCE", path, "节点、组与端点共用唯一 ID 命名空间");
2011
- const edges = new Map(resources.map((resource) => [resource.id, "members" in resource ? resource.members : "via" in resource && resource.via ? [resource.via] : []]));
2012
- for (const [id, refs] of edges) for (const ref of refs) if (!byId.has(ref) && !builtinMember(ref)) error("MISSING_REFERENCE", `${path}.${id}`, "节点或组引用不存在");
2013
- for (const [id, refs] of edges) for (const ref of refs) if (byId.get(ref)?.type === "sing-box-tailscale") error("ENDPOINT_REFERENCE_UNSUPPORTED", `${path}.${id}`, "端点只能由 route 引用,不能作为组成员或 via");
2014
- for (let i = 0; i < endpoints.length; i++) for (let j = 0; j < i; j++) if (pathsOverlap(endpoints[i].stateDirectory, endpoints[j].stateDirectory)) error("ENDPOINT_STATE_OVERLAP", `${path}.endpoints.${endpoints[i].id}`, "端点状态目录不能重复或互为祖先");
2015
- const states = /* @__PURE__ */ new Map();
2016
- const tcpOnly = /* @__PURE__ */ new Map();
2017
- const udpVersion = programTargets.length > 0 && programTargets.every((target) => target.engine === "sing-box" && target.version === "1.14.4") ? "1.14.4" : void 0;
2018
- const visit = (id) => {
2019
- if (states.get(id) === 1) {
2020
- error("RESOURCE_CYCLE", `${path}.${id}`, "组成员和 via 拨号依赖不能形成循环");
2021
- return true;
2022
- }
2023
- if (states.get(id) === 2) return tcpOnly.get(id) ?? false;
2024
- states.set(id, 1);
2025
- const item = byId.get(id);
2026
- let limited = !!item && "server" in item && nodeIsTcpOnly(item, program.engine, udpVersion);
2027
- for (const ref of edges.get(id) ?? []) limited = visit(ref) || limited;
2028
- states.set(id, 2);
2029
- tcpOnly.set(id, limited);
2030
- return limited;
2031
- };
2032
- if (resources.length > 1e3) error("RESOURCE_LIMIT", path, "单程序最多 1000 个节点、组与端点");
2033
- else for (const id of byId.keys()) visit(id);
2034
- const validateAction = (action, where, udpPossible) => {
2035
- if (action.type !== "route") return;
2036
- if (!byId.has(action.to)) error("MISSING_REFERENCE", where, "路由出口不存在");
2037
- else if (udpPossible && tcpOnly.get(action.to) && program.unsupportedUdp !== "reject") error("NETWORK_UNSUPPORTED", where, "出口的可选或 via 路径含 TCP-only 节点;请用 network(tcp) 限定规则,且不能用于 fallback");
2038
- };
2039
- for (const rule of rules) validateAction(rule.then, rule.id, truthPossibilities(rule.when, "udp").includes(true));
2040
- const validateBindings = (entries, prefix) => {
2041
- for (const entry of entries) {
2042
- if (entry.type === "block") validateBindings(entry.rules, `${prefix}/${entry.id}`);
2043
- if (entry.type === "use") {
2044
- for (const [key, action] of Object.entries(entry.bindings)) if (action.type !== "slot") validateAction(action, `${prefix}/${entry.id}/bindings/${key}`, false);
2045
- validateBindings(entry.policy.rules, `${prefix}/${entry.id}`);
2046
- }
2047
- }
2048
- };
2049
- validateBindings(program.routing, name);
2050
- validateAction(program.fallback, `${path}.fallback`, true);
2051
- }
2052
- const targetIds = /* @__PURE__ */ new Set();
2053
- for (const target of config.targets) {
2054
- const path = `targets.${target.id}`;
2055
- if (targetIds.has(target.id)) error("DUPLICATE_TARGET", path, "构建目标 ID 重复");
2056
- targetIds.add(target.id);
2057
- const descriptor = targetCatalog.find((item) => item.engine === target.engine && item.version === target.version && item.platforms.includes(target.platform));
2058
- if (!descriptor) {
2059
- error("UNKNOWN_TARGET", path, "目标引擎、精确版本和平台组合不在支持目录中", target.id);
2060
- continue;
2061
- }
2062
- const originalProgram = config.programs[target.program];
2063
- const lowered = lowerStrategies(originalProgram?.groups ?? [], target, diagnostics, path);
2064
- const program = originalProgram ? {
2065
- ...originalProgram,
2066
- groups: lowered.groups
2067
- } : void 0;
2068
- if (!program) {
2069
- error("MISSING_PROGRAM", path, "目标引用的程序不存在", target.id);
2070
- continue;
2071
- }
2072
- if (program.engine !== target.engine) error("ENGINE_MISMATCH", path, "平台程序与目标引擎不一致", target.id);
2073
- const modernSingbox = target.engine === "sing-box" && target.version === "1.14.4";
2074
- if (!modernSingbox && (program.domainMatching !== void 0 || program.serverAliases !== void 0 || program.cacheFile !== void 0 || program.unsupportedUdp !== void 0)) error("PROGRAM_OPTION_UNSUPPORTED", path, "显式 sing-box 选项仅支持 1.14.4", target.id);
2075
- if (program.cacheFile !== void 0 && target.mode !== "standalone") error("PROGRAM_OPTION_UNSUPPORTED", path, "持久缓存需要 standalone 的稳定工作目录", target.id);
2076
- for (const group of program.groups) if (group.members.some(builtinMember) && (!modernSingbox || group.type !== "select")) error("GROUP_BUILTIN_UNSUPPORTED", `${path}.groups.${group.id}`, "内建组成员只支持 sing-box 1.14.4 select", target.id);
2077
- if (program.tun) {
2078
- if (target.engine !== "sing-box" || target.version !== "1.14.4" || target.mode !== "standalone") error("TUN_TARGET_UNSUPPORTED", path, "TUN 仅支持 sing-box 1.14.4 standalone", target.id);
2079
- if (unsafeTunResolvers(program).length) error("TUN_DNS_LOOP", path, "TUN DNS 上游不能使用回环、未指定或 TUN 网段地址", target.id);
2080
- }
2081
- if (target.mode === "standalone" && !program.listener) error("LISTENER_REQUIRED", path, "standalone 必须声明 loopback listener 与 IP DNS resolver", target.id);
2082
- if (target.mode !== "standalone" && program.listener) error("UNUSED_LISTENER", path, "fragment 不能静默忽略 listener;请使用独立程序或 standalone 目标", target.id);
2083
- if (program.dns?.length) {
2084
- if (target.engine !== "sing-box") error("DNS_TARGET_UNSUPPORTED", path, "通用 DNS 需要 sing-box standalone 或 Surge Profile", target.id);
2085
- else if (target.mode !== "standalone") error("DNS_MODE_UNSUPPORTED", path, "通用 DNS 需要 standalone", target.id);
2086
- }
2087
- for (const endpoint of program.endpoints ?? []) {
2088
- if (!descriptor.endpoints.includes(endpoint.type)) error("ENDPOINT_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "当前目标版本不支持 Tailscale 端点", target.id);
2089
- if (target.mode !== "standalone") error("ENDPOINT_MODE_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 需要 standalone 的普通 DNS/final 隔离引导解析", target.id);
2090
- }
2091
- for (const node of program.nodes) {
2092
- validateProxyOptions(node, target, diagnostics);
2093
- if (!descriptor.protocols.includes(node.type)) error("PROTOCOL_UNSUPPORTED", `${path}.nodes.${node.id}`, "目标版本不支持该代理协议", target.id);
2094
- if (node.label) diagnostics.push({
2095
- severity: "warning",
2096
- code: "LABEL_NOT_EMITTED",
2097
- path: `${path}.nodes.${node.id}.label`,
2098
- target: target.id,
2099
- message: "原生节点使用稳定 ID;展示 label 不写入配置,不影响路由"
2100
- });
2101
- }
2102
- for (const group of program.groups) if (!descriptor.groups.includes(group.type)) error("GROUP_UNSUPPORTED", `${path}.groups.${group.id}`, "目标未实现该组机制;不会自动替换为另一种组", target.id);
2103
- validateSmartMembers(program.groups, new Set(program.nodes.map((n) => n.id)), diagnostics, path);
2104
- const rules = expanded.get(target.program);
2105
- if (target.engine === "mihomo" || target.engine === "stash") validateClashTarget(target, rules, diagnostics);
2106
- if (target.engine === "surge") {
2107
- for (const rule of rules) if (logicalDepth(rule.when) > 10) error("LOGICAL_DEPTH", rule.id, "Surge 逻辑条件最多嵌套 10 层", target.id);
2108
- }
2109
- const checkOptions = (condition, nested = false) => {
2110
- if ("includeSniffed" in condition && condition.includeSniffed === true && target.engine !== "surge" && !(modernSingbox && program.domainMatching === "prefer-sniffed") || condition.type === "ipCidr" && condition.noResolve !== void 0 && target.engine === "sing-box" && !modernSingbox || condition.type === "nativeRuleSet" && condition.engine === "sing-box" && condition.resolve !== void 0 && !modernSingbox || modernSingbox && nested && needsResolve(condition)) error("MATCH_OPTION_UNSUPPORTED", path, "目标无法等价实现显式匹配选项", target.id);
2111
- if (condition.type === "all" || condition.type === "any") condition.conditions.forEach((child) => checkOptions(child, true));
2112
- else if (condition.type === "not") checkOptions(condition.condition, true);
2113
- else if (condition.type === "ruleSet") checkOptions(condition.when, nested);
2114
- };
2115
- rules.forEach((rule) => checkOptions(rule.when));
2116
- const nativeRuleSets = collectNativeRuleSets(rules, target, diagnostics);
2117
- for (const resource of nativeRuleSets) if (!descriptor.nativeRuleSets.includes(resource.format)) error("RULESET_UNSUPPORTED", `${path}.ruleSets.${resource.id}`, "精确目标不支持此原生规则资源格式", target.id);
2118
- let nativeIndex = target.engine === "sing-box" ? Number(!!program.tun) + Number(!!program.domainMatching) + Number(modernSingbox && target.mode === "standalone" && !!program.dns?.length) : 0;
2119
- plans.push({
2120
- nativeRuleSets,
2121
- target,
2122
- program,
2123
- rules,
2124
- strategySelections: lowered.selections,
2125
- sourceMap: rules.map((rule) => {
2126
- if (modernSingbox && needsResolve(rule.when)) nativeIndex++;
2127
- return {
2128
- rule: rule.id,
2129
- nativeIndex: nativeIndex++,
2130
- origin: rule.origin
2131
- };
2132
- }),
2133
- preconditions: [
2134
- ...program.domainMatching ? ["显式 prefer-sniffed:HTTP/TLS 识别域名优先,回退原域名,不覆盖目的地址;不等同 includeSniffed 多来源 OR。"] : [],
2135
- ...program.unsupportedUdp ? ["显式 unsupportedUdp:reject:保留 TCP-only 候选;选中该出口时 UDP 由原生拒绝,不回退直连,不表示节点支持 UDP。"] : [],
2136
- ...program.cacheFile ? ["原生 cache.db 属于客户端稳定工作目录;SDK 不创建或清理缓存。无有效缓存且下载失败时拒绝启动。"] : [],
2137
- ...nativeRuleSets.length ? ["原生外部规则由客户端持续下载和解释;静态布尔结果不验证 DNS 等副作用。缓存与下载失败处理沿用客户端机制,fragment 运行方提供工作目录与下载 DNS 路径。"] : [],
2138
- ...program.endpoints?.length ? [
2139
- "Tailscale 需要 with_tailscale 构建标签;运行方负责登录、路由批准及每实例独占身份目录。构建不注册 tailnet。",
2140
- "状态目录真实路径必须独立于产物与清理范围;output 重叠检查仅为词法检查,不能证明运行主机符号链接隔离。",
2141
- "普通 DNS/final 与端点控制面引导 DNS 分离;未配置 MagicDNS,私有域名须由运行方提供适用的普通解析器。"
2142
- ] : [],
2143
- ...target.engine === "surge" && program.nodes.some((node) => node.type === "vmess") ? ["Surge VMess 的 TCP-only 由语言路由检查保证;fragment 组合方不得额外引入通往此节点的 UDP 路由。"] : [],
2144
- ...target.engine === "stash" ? ["Stash 4.2.1 原生未验证;block-quic: off 按现行文档编码,历史版本 QUIC 行为未验证。"] : [],
2145
- "规则只匹配已观测元数据;不自动嗅探或为了 IP 条件解析域名。",
2146
- "节点 server 与 via 各跳必须是 IP;运行时组选择、代理连通性不由静态解释保证。",
2147
- ...target.mode !== "standalone" ? ["此配置是 fragment,组合方负责入口、直接 DNS 解析路径及 source/domain/IP 元数据来源。"] : ["仅本机 loopback 显式代理;不是 TUN 或 LAN 网关。DNS 上游固定直连。"]
2148
- ],
2149
- nativeValidation: "not-run"
2150
- });
2151
- }
2152
- const caseIds = /* @__PURE__ */ new Set();
2153
- for (const test of config.cases ?? []) {
2154
- if (caseIds.has(test.id)) error("DUPLICATE_CASE", `cases.${test.id}`, "案例 ID 重复");
2155
- caseIds.add(test.id);
2156
- const program = config.programs[test.program];
2157
- if (!program) {
2158
- error("MISSING_PROGRAM", `cases.${test.id}`, "案例引用的程序不存在");
2159
- continue;
2160
- }
2161
- let actual;
2162
- try {
2163
- actual = explainRules(expanded.get(test.program), program.fallback, requestForProgram(program, test.request), program.engine === "sing-box" && config.targets.filter((target) => target.program === test.program).every((target) => target.version === "1.14.4"));
2164
- } catch (cause) {
2165
- if (!(cause instanceof StaticRuleSetUnknownError) && !(cause instanceof StaticMetadataUnknownError)) throw cause;
2166
- cases.push({
2167
- id: test.id,
2168
- passed: false,
2169
- code: "CASE_INDETERMINATE"
2170
- });
2171
- error("CASE_INDETERMINATE", `cases.${test.id}`, "外部规则或所需运行时元数据未知,无法静态确定首命中");
2172
- continue;
2173
- }
2174
- const passed = (test.expect.rule === void 0 || test.expect.rule === actual.rule) && sameAction(test.expect.action, actual.action);
2175
- cases.push({
2176
- id: test.id,
2177
- passed,
2178
- actual: {
2179
- rule: actual.rule,
2180
- action: actual.action
2181
- }
2182
- });
2183
- if (!passed) error("CASE_FAILED", `cases.${test.id}`, "请求的首命中规则或逻辑出口不符合预期");
2184
- }
2185
- if (config.warningsAsErrors) {
2186
- for (let i = 0; i < diagnostics.length; i++) if (diagnostics[i].severity === "warning") diagnostics[i] = {
2187
- ...diagnostics[i],
2188
- severity: "error"
2189
- };
2190
- }
2191
- const ok = !diagnostics.some((d) => d.severity === "error");
2192
- return deepFreeze({
2193
- ok,
2194
- diagnostics,
2195
- plans: ok ? plans : [],
2196
- cases
2197
- });
2198
- }
2199
- function sameAction(a, b) {
2200
- return a.type === b.type && (a.type !== "route" || b.type === "route" && a.to === b.to);
2201
- }
2202
- function explain(compilation, target, request) {
2203
- if (!compilation.ok) throw new Error("COMPILATION_FAILED");
2204
- const plan = compilation.plans.find((plan) => plan.target.id === target);
2205
- if (!plan) throw new Error("UNKNOWN_TARGET");
2206
- return explainRules(plan.rules, plan.program.fallback, requestForProgram(plan.program, request), plan.target.engine === "sing-box" && plan.target.version === "1.14.4");
2207
- }
2208
- //#endregion
2209
- //#region src/secrets.ts
2210
- const failures = /* @__PURE__ */ new WeakMap();
2211
- function secretFailure(error) {
2212
- return error !== null && typeof error === "object" ? failures.get(error) ?? {} : {};
2213
- }
2214
- function failure(code, name, reason) {
2215
- const error = new RenderError(code);
2216
- if (/^[A-Z][A-Z0-9_]{0,127}$/.test(name)) failures.set(error, Object.freeze({
2217
- secretName: name,
2218
- secretReason: reason
2219
- }));
2220
- return error;
2221
- }
2222
- /** One reader per rendering batch; exceptions and missing values never disclose credentials. */
2223
- function secretReader(resolveSecret) {
2224
- const values = /* @__PURE__ */ new Map();
2225
- return (token) => {
2226
- if (values.has(token.name)) return values.get(token.name);
2227
- let value;
2228
- try {
2229
- value = resolveSecret(token);
2230
- } catch (error) {
2231
- const nested = secretFailure(error);
2232
- throw failure("SECRET_RESOLUTION_FAILED", token.name, nested.secretName === token.name && nested.secretReason === "MISSING" ? "MISSING" : "RESOLUTION_FAILED");
2233
- }
2234
- if (typeof value !== "string" || value.length === 0) throw failure("SECRET_MISSING", token.name, "MISSING");
2235
- values.set(token.name, value);
2236
- return value;
2237
- };
2238
- }
2239
- //#endregion
2240
- //#region src/surge-profile.ts
2241
- const builtin = z.enum([
2242
- "DIRECT",
2243
- "REJECT",
2244
- "REJECT-DROP",
2245
- "REJECT-NO-DROP",
2246
- "REJECT-TINYGIF"
2247
- ]);
2248
- const policy$1 = z.union([z.strictObject({ ref: idSchema }), z.strictObject({ builtin })]);
2249
- const token = z.strictObject({
2250
- type: z.literal("env"),
2251
- name: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)
2252
- });
2253
- const safe = z.string().min(1).max(4096).refine((v) => v.trim() === v && !/[\p{C}\p{Zl}\p{Zp},=()#;"'\\]/u.test(v));
2254
- const domain = z.string().max(253).regex(/^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/);
2255
- const hostPattern = safe.refine((v) => /^[a-zA-Z0-9*?._-]+$/.test(v));
2256
- const ip = safe.refine((v) => isIP(v) !== 0 && !v.includes("%"));
2257
- const cidr = (version) => safe.refine((v) => {
2258
- try {
2259
- const [address] = ipaddr.parseCIDR(v);
2260
- return (!version || (address.kind() === "ipv4" ? 4 : 6) === version) && !v.includes("%");
2261
- } catch {
2262
- return false;
2263
- }
2264
- });
2265
- const port = z.number().int().min(1).max(65535);
2266
- function addressPort(value, allowHost, portRequired) {
2267
- if (!portRequired && isIP(value)) return true;
2268
- const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(value);
2269
- if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) return false;
2270
- const host = match[1];
2271
- return host.startsWith("[") ? isIP(host.slice(1, -1)) === 6 : isIP(host) === 4 || allowHost && domain.safeParse(host).success;
2272
- }
2273
- const listener = safe.refine((v) => addressPort(v, false, false));
2274
- const endpoint = safe.refine((v) => addressPort(v, true, true));
2275
- const dns = safe.refine((v) => v === "system" || addressPort(v, false, false));
2276
- const url = z.string().min(1).max(4096).refine((v) => {
2277
- try {
2278
- const u = new URL(v);
2279
- return /^https?:\/\//.test(v) && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
2280
- } catch {
2281
- return false;
2282
- }
2283
- });
2284
- const encryptedDns = z.string().max(4096).refine((v) => {
2285
- try {
2286
- const u = new URL(v);
2287
- return [
2288
- "https:",
2289
- "h3:",
2290
- "quic:",
2291
- "tls:",
2292
- "tcp:"
2293
- ].includes(u.protocol) && !!u.hostname && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
2294
- } catch {
2295
- return false;
2296
- }
2297
- });
2298
- const list = (item) => z.array(item).min(1).max(1e3);
2299
- const control = z.strictObject({
2300
- password: token,
2301
- listen: safe.refine((v) => addressPort(v, false, true))
2302
- });
2303
- const generalSchema = z.strictObject({
2304
- loglevel: z.enum([
2305
- "verbose",
2306
- "info",
2307
- "notify",
2308
- "warning"
2309
- ]).optional(),
2310
- "dns-server": list(dns).optional(),
2311
- "encrypted-dns-server": list(encryptedDns).optional(),
2312
- "show-error-page-for-reject": z.boolean().optional(),
2313
- "exclude-simple-hostnames": z.boolean().optional(),
2314
- "internet-test-url": url.optional(),
2315
- "skip-proxy": list(z.union([
2316
- hostPattern,
2317
- ip,
2318
- cidr()
2319
- ])).optional(),
2320
- ipv6: z.boolean().optional(),
2321
- "ipv6-vif": z.enum([
2322
- "auto",
2323
- "always",
2324
- "disabled"
2325
- ]).optional(),
2326
- "bypass-system": z.boolean().optional(),
2327
- replica: z.boolean().optional(),
2328
- "tls-provider": z.enum(["default", "openssl"]).optional(),
2329
- "bypass-tun": list(cidr()).optional(),
2330
- "always-real-ip": list(hostPattern).optional(),
2331
- "http-api": control.optional(),
2332
- "http-api-web-dashboard": z.boolean().optional(),
2333
- "external-controller-access": control.optional(),
2334
- "hijack-dns": list(safe.refine((v) => /^\*(?::\d+)?$/.test(v) ? !v.includes(":") || Number(v.slice(2)) > 0 && Number(v.slice(2)) <= 65535 : addressPort(v, false, false))).optional(),
2335
- "http-listen": listener.optional(),
2336
- "socks5-listen": listener.optional(),
2337
- "proxy-restricted-to-lan": z.boolean().optional()
2338
- });
2339
- /** Internal fragment validation; caller must inspect data descriptors before invoking. */
2340
- const validateSurgeGeneral = (input) => generalSchema.safeParse(input).success;
2341
- const hostSchema = z.strictObject({
2342
- pattern: hostPattern,
2343
- address: z.union([ip, domain]).optional(),
2344
- server: z.union([dns, encryptedDns]).optional()
2345
- }).refine((v) => v.address !== void 0 || v.server !== void 0);
2346
- const key = z.string().regex(/^[A-Za-z0-9+/]{43}=$/).refine((v) => Buffer.from(v, "base64").length === 32 && Buffer.from(v, "base64").toString("base64") === v);
2347
- const sectionName = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/);
2348
- const tunnelSchema = z.discriminatedUnion("type", [z.strictObject({
2349
- type: z.literal("tailscale"),
2350
- id: idSchema,
2351
- sectionName,
2352
- authKey: token,
2353
- hostname: domain,
2354
- dnsServer: list(dns).optional(),
2355
- autoAddMagicDnsRule: z.boolean().optional(),
2356
- idleKeepalive: z.number().int().min(-1).max(2147483647).optional()
2357
- }), z.strictObject({
2358
- type: z.literal("wireguard"),
2359
- id: idSchema,
2360
- sectionName,
2361
- privateKey: token,
2362
- selfIp: ip.refine((v) => isIP(v) === 4),
2363
- dnsServer: list(dns).optional(),
2364
- mtu: z.number().int().min(576).max(9e3).optional(),
2365
- peers: list(z.strictObject({
2366
- publicKey: key,
2367
- endpoint,
2368
- allowedIps: list(cidr()),
2369
- presharedKey: token.optional(),
2370
- persistentKeepalive: z.number().int().min(0).max(65535).optional()
2371
- }))
2372
- })]);
2373
- const groupSchema = z.strictObject({
2374
- id: idSchema,
2375
- type: z.enum(["select", "smart"]),
2376
- members: list(policy$1),
2377
- url: url.optional(),
2378
- intervalSeconds: z.number().int().positive().max(2147483647).optional(),
2379
- timeoutSeconds: z.number().int().positive().max(3600).optional()
2380
- });
2381
- const options$1 = { noResolve: z.boolean().optional() };
2382
- const domainOptions = {
2383
- ...options$1,
2384
- includeSniffed: z.boolean().optional()
2385
- };
2386
- const atom = (type, value) => z.strictObject({
2387
- type: z.literal(type),
2388
- value,
2389
- ...["domain", "domainSuffix"].includes(type) ? domainOptions : options$1
2390
- });
2391
- const conditionSchema = z.lazy(() => z.union([
2392
- atom("domain", domain),
2393
- atom("domainSuffix", domain),
2394
- atom("ipCidr", cidr(4)),
2395
- atom("ipCidr6", cidr(6)),
2396
- z.strictObject({
2397
- type: z.literal("ipAsn"),
2398
- value: z.number().int().min(1).max(4294967295),
2399
- ...options$1
2400
- }),
2401
- atom("sourceIp", z.union([ip, cidr()])),
2402
- atom("processName", safe),
2403
- atom("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
2404
- z.strictObject({
2405
- type: z.enum(["port", "sourcePort"]),
2406
- from: port,
2407
- to: port.optional(),
2408
- ...options$1
2409
- }).refine((v) => v.to === void 0 || v.to >= v.from),
2410
- z.strictObject({
2411
- type: z.literal("network"),
2412
- value: z.enum(["tcp", "udp"]),
2413
- ...options$1
2414
- }),
2415
- z.strictObject({
2416
- type: z.enum(["all", "any"]),
2417
- conditions: z.array(conditionSchema).min(2).max(100),
2418
- ...options$1
2419
- }),
2420
- z.strictObject({
2421
- type: z.literal("not"),
2422
- condition: conditionSchema,
2423
- ...options$1
2424
- }),
2425
- z.strictObject({
2426
- type: z.literal("ruleSet"),
2427
- format: z.enum(["rule-set", "domain-set"]),
2428
- url: url.optional(),
2429
- builtin: z.enum(["LAN", "SYSTEM"]).optional(),
2430
- intervalSeconds: z.number().int().min(60).max(2147483647).optional(),
2431
- ...domainOptions
2432
- }).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
2433
- ]));
2434
- const managedSchema = z.strictObject({
2435
- url: url.refine((v) => !new URL(v).search && !v.includes("?")),
2436
- query: z.record(z.string().min(1).max(128).regex(/^[A-Za-z][A-Za-z0-9_-]*$/), z.union([z.string().max(4096), token])).optional(),
2437
- intervalSeconds: z.number().int().min(60).max(2147483647),
2438
- strict: z.boolean()
2439
- });
2440
- const inputSchema = z.strictObject({
2441
- target: z.strictObject({
2442
- engine: z.literal("surge"),
2443
- platform: z.enum(["macos", "ios"]),
2444
- version: z.string()
2445
- }),
2446
- managed: managedSchema.optional(),
2447
- general: generalSchema.optional(),
2448
- hosts: z.array(hostSchema).max(2e3).optional(),
2449
- nodes: z.array(nodeSchema).max(1e3),
2450
- tunnels: z.array(tunnelSchema).max(1e3).optional(),
2451
- groups: z.array(groupSchema).max(1e3),
2452
- rules: z.array(z.strictObject({
2453
- when: conditionSchema,
2454
- then: policy$1
2455
- })).max(1e4),
2456
- fallback: policy$1,
2457
- names: z.record(idSchema, nativeNameSchema).optional()
2458
- });
2459
- const plans = /* @__PURE__ */ new WeakMap();
2460
- function compileSurgeProfile(input) {
2461
- const diagnostics = [];
2462
- const error = (code) => diagnostics.push({
2463
- severity: "error",
2464
- code,
2465
- path: "$",
2466
- message: code
2467
- });
2468
- const failure = () => deepFreeze({
2469
- ok: false,
2470
- artifactKind: "surge-profile",
2471
- diagnostics,
2472
- bindings: []
2473
- });
2474
- try {
2475
- assertData(input);
2476
- } catch {
2477
- error("INVALID_INPUT_GRAPH");
2478
- return failure();
2479
- }
2480
- const parsed = inputSchema.safeParse(input);
2481
- if (!parsed.success) {
2482
- error("INVALID_SCHEMA");
2483
- return failure();
2484
- }
2485
- if (parsed.data.general) {
2486
- const general = parsed.data.general;
2487
- parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
2488
- }
2489
- const p = deepFreeze(parsed.data);
2490
- if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
2491
- const tunnels = p.tunnels ?? [];
2492
- const resources = [
2493
- ...p.nodes,
2494
- ...tunnels,
2495
- ...p.groups
2496
- ];
2497
- if (resources.length > 1e3) error("RESOURCE_LIMIT");
2498
- const ids = new Set(resources.map((r) => r.id));
2499
- if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
2500
- if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
2501
- const bindings = resources.map((r) => ({
2502
- id: r.id,
2503
- nativeName: p.names?.[r.id] ?? r.id
2504
- }));
2505
- if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
2506
- if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
2507
- if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
2508
- if (p.target.platform === "ios" && [
2509
- "bypass-system",
2510
- "replica",
2511
- "tls-provider",
2512
- "bypass-tun",
2513
- "external-controller-access"
2514
- ].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
2515
- if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
2516
- const checkPolicy = (action) => {
2517
- if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
2518
- };
2519
- const edges = new Map(resources.map((r) => [r.id, []]));
2520
- const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
2521
- for (const node of p.nodes) {
2522
- if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
2523
- validateProxyOptions(node, {
2524
- id: "profile",
2525
- engine: "surge"
2526
- }, diagnostics);
2527
- if (node.via) {
2528
- checkPolicy({ ref: node.via });
2529
- edges.get(node.id).push(node.via);
2530
- }
2531
- }
2532
- for (const group of p.groups) {
2533
- if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
2534
- for (const member of group.members) {
2535
- checkPolicy(member);
2536
- if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
2537
- if ("ref" in member) edges.get(group.id).push(member.ref);
2538
- }
2539
- }
2540
- const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
2541
- const visit = (id) => {
2542
- if (active.has(id)) {
2543
- error("RESOURCE_CYCLE");
2544
- return;
2545
- }
2546
- if (visited.has(id)) return;
2547
- active.add(id);
2548
- for (const next of edges.get(id) ?? []) visit(next);
2549
- active.delete(id);
2550
- visited.add(id);
2551
- };
2552
- if (resources.length <= 1e3) for (const id of ids) visit(id);
2553
- const formats = /* @__PURE__ */ new Map();
2554
- const checkCondition = (c, depth) => {
2555
- if (depth > 10) {
2556
- error("LOGICAL_DEPTH_EXCEEDED");
2557
- return;
2558
- }
2559
- if (c.noResolve !== void 0 && ![
2560
- "ipCidr",
2561
- "ipCidr6",
2562
- "ipAsn",
2563
- "ruleSet"
2564
- ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
2565
- if (c.includeSniffed !== void 0 && ![
2566
- "domain",
2567
- "domainSuffix",
2568
- "ruleSet"
2569
- ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
2570
- if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
2571
- if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
2572
- if (c.type === "not") checkCondition(c.condition, depth + 1);
2573
- if (c.type === "ruleSet") {
2574
- if (c.intervalSeconds !== void 0 && (depth > 0 || c.builtin)) error("RULESET_COMPOSITION_UNSUPPORTED");
2575
- if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
2576
- if (c.url) {
2577
- const key = new URL(c.url).href;
2578
- const settings = `${c.format}:${c.intervalSeconds ?? 86400}`;
2579
- if (formats.has(key) && formats.get(key) !== settings) error("RULESET_FORMAT_CONFLICT");
2580
- formats.set(key, settings);
2581
- }
2582
- }
2583
- };
2584
- for (const rule of p.rules) {
2585
- checkPolicy(rule.then);
2586
- checkCondition(rule.when, 0);
2587
- }
2588
- checkPolicy(p.fallback);
2589
- if (diagnostics.some((d) => d.severity === "error")) return failure();
2590
- if (formats.size) diagnostics.push({
2591
- severity: "warning",
2592
- code: "EXTERNAL_RULESET_UNVERIFIED",
2593
- path: "rules",
2594
- message: "External rule sets are resolved by the client, not by the compiler."
2595
- });
2596
- const result = deepFreeze({
2597
- ok: true,
2598
- artifactKind: "surge-profile",
2599
- diagnostics,
2600
- bindings
2601
- });
2602
- plans.set(result, p);
2603
- return result;
2604
- }
2605
- function conditionOptions(c) {
2606
- return [
2607
- ...c.noResolve ? ["no-resolve"] : [],
2608
- ..."includeSniffed" in c && c.includeSniffed ? ["extended-matching"] : [],
2609
- ...c.type === "ruleSet" && c.intervalSeconds !== void 0 ? [`update-interval=${c.intervalSeconds}`] : []
2610
- ];
2611
- }
2612
- function conditionText(c) {
2613
- switch (c.type) {
2614
- case "all":
2615
- case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
2616
- case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
2617
- case "port":
2618
- case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
2619
- case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
2620
- case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
2621
- default: return `${{
2622
- domain: "DOMAIN",
2623
- domainSuffix: "DOMAIN-SUFFIX",
2624
- ipCidr: "IP-CIDR",
2625
- ipCidr6: "IP-CIDR6",
2626
- ipAsn: "IP-ASN",
2627
- sourceIp: "SRC-IP",
2628
- processName: "PROCESS-NAME",
2629
- macAddress: "MAC-ADDRESS"
2630
- }[c.type]},${c.value}`;
2631
- }
2632
- }
2633
- function renderProfile(compilation, read) {
2634
- const p = plans.get(compilation);
2635
- if (!p) throw new RenderError("COMPILATION_FAILED");
2636
- const name = (id) => p.names?.[id] ?? id;
2637
- const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
2638
- const credential = (token, kind) => {
2639
- const value = read(token);
2640
- 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");
2641
- return value;
2642
- };
2643
- const lines = [];
2644
- if (p.managed) {
2645
- const address = new URL(p.managed.url);
2646
- for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
2647
- lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
2648
- }
2649
- lines.push("[General]");
2650
- for (const [k, v] of Object.entries(p.general ?? {})) {
2651
- const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
2652
- lines.push(`${k} = ${value}`);
2653
- }
2654
- lines.push("", "[Host]");
2655
- for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
2656
- lines.push("", "[Proxy]");
2657
- for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
2658
- for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
2659
- for (const t of p.tunnels ?? []) {
2660
- lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
2661
- if (t.type === "tailscale") {
2662
- lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
2663
- if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
2664
- if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
2665
- if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
2666
- } else {
2667
- lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
2668
- if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
2669
- if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
2670
- for (const peer of t.peers) {
2671
- const values = [`public-key = ${peer.publicKey}`];
2672
- if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
2673
- values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
2674
- if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
2675
- lines.push(`peer = (${values.join(", ")})`);
2676
- }
2677
- }
2678
- }
2679
- lines.push("", "[Proxy Group]");
2680
- for (const g of p.groups) lines.push(`${name(g.id)} = ${[
2681
- g.type,
2682
- ...g.members.map(action),
2683
- ...g.url ? [`url=${g.url}`] : [],
2684
- ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
2685
- ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
2686
- ].join(", ")}`);
2687
- lines.push("", "[Rule]");
2688
- for (const r of p.rules) lines.push([
2689
- conditionText(r.when),
2690
- action(r.then),
2691
- ...conditionOptions(r.when)
2692
- ].join(","));
2693
- lines.push(`FINAL,${action(p.fallback)}`, "");
2694
- return deepFreeze({
2695
- artifactKind: "surge-profile",
2696
- content: lines.join("\n")
2697
- });
2698
- }
2699
- function renderSurgeProfile(compilation, resolveSecret) {
2700
- return renderProfile(compilation, secretReader(resolveSecret));
2701
- }
2702
- function renderSurgeProfiles(compilations, resolveSecret) {
2703
- if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
2704
- const read = secretReader(resolveSecret);
2705
- return deepFreeze(compilations.map((c) => renderProfile(c, read)));
2706
- }
2707
- //#endregion
2708
- //#region src/profile.ts
2709
- const fail = (code) => {
2710
- throw new ProfileDefinitionError(code);
2711
- };
2712
- /** Keep aliases across nodes, groups and destinations; reject accessors before cloning. */
2713
- function snapshotProfile(input) {
2714
- inspectDefinition(input);
2715
- return deepFreeze(structuredClone(input));
2716
- }
2717
- function surgeConfig(input) {
2718
- inspectDefinition(input);
2719
- exactDefinition(input, [
2720
- "managed",
2721
- "general",
2722
- "hosts",
2723
- "names"
2724
- ]);
2725
- return snapshotProfile(input);
2726
- }
2727
- function defineProfile(input) {
2728
- inspectDefinition(input);
2729
- exactDefinition(input, [
2730
- "target",
2731
- "proxies",
2732
- "groups",
2733
- "routes",
2734
- "fallback",
2735
- "surge",
2736
- "singBox",
2737
- "dns"
2738
- ]);
2739
- exactDefinition(input.target, [
2740
- "engine",
2741
- "platform",
2742
- "version"
2743
- ]);
2744
- if (input.surge !== void 0) exactDefinition(input.surge, [
2745
- "managed",
2746
- "general",
2747
- "hosts",
2748
- "names"
2749
- ]);
2750
- if (input.singBox !== void 0) {
2751
- exactDefinition(input.singBox, [
2752
- "mode",
2753
- "listener",
2754
- "tun",
2755
- "domainMatching",
2756
- "serverAliases",
2757
- "cacheFile",
2758
- "unsupportedUdp"
2759
- ]);
2760
- if (!["fragment", "standalone"].includes(input.singBox.mode)) fail("INVALID_PROFILE_DEFINITION");
2761
- if (input.singBox.listener !== void 0) exactDefinition(input.singBox.listener, ["port", "resolver"]);
2762
- }
2763
- let remaining = 1e5;
2764
- function flatten(fragments) {
2765
- if (!Array.isArray(fragments)) fail("INVALID_PROFILE_DEFINITION");
2766
- const result = [];
2767
- function visit(value) {
2768
- if (--remaining < 0) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
2769
- if (Array.isArray(value)) for (const item of value) visit(item);
2770
- else {
2771
- if (!value || typeof value !== "object") fail("INVALID_PROFILE_DEFINITION");
2772
- result.push(value);
2773
- }
2774
- }
2775
- visit(fragments);
2776
- return result;
2777
- }
2778
- const proxies = flatten(input.proxies);
2779
- const groups = flatten(input.groups);
2780
- const routes = flatten(input.routes);
2781
- const dns = input.dns === void 0 ? void 0 : flatten(input.dns);
2782
- if (dns) {
2783
- const checked = dnsRulesSchema.safeParse(dns);
2784
- if (!checked.success) fail(checked.error.issues.some((issue) => issue.message === "DNS_RULE_CONFLICT") ? "DNS_RULE_CONFLICT" : "INVALID_DNS_RULES");
2785
- }
2786
- let surge;
2787
- if (input.surge !== void 0) {
2788
- let general;
2789
- if (input.surge.general !== void 0) {
2790
- general = {};
2791
- const checked = /* @__PURE__ */ new Set();
2792
- const costs = /* @__PURE__ */ new Map();
2793
- let validationRemaining = 1e5;
2794
- function cost(value) {
2795
- if (!value || typeof value !== "object") return 1;
2796
- const cached = costs.get(value);
2797
- if (cached !== void 0) return cached;
2798
- let total = 1;
2799
- for (const item of Object.values(value)) {
2800
- total += cost(item);
2801
- if (total > 1e5) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
2802
- }
2803
- costs.set(value, total);
2804
- return total;
2805
- }
2806
- const fragments = Array.isArray(input.surge.general) ? input.surge.general : [input.surge.general];
2807
- for (const fragment of flatten(fragments)) {
2808
- if (!checked.has(fragment)) {
2809
- validationRemaining -= cost(fragment);
2810
- if (validationRemaining < 0) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
2811
- if (!validateSurgeGeneral(fragment)) fail("INVALID_SURGE_GENERAL");
2812
- checked.add(fragment);
2813
- }
2814
- Object.assign(general, fragment);
2815
- }
2816
- }
2817
- surge = {
2818
- ...input.surge,
2819
- ...general === void 0 ? {} : { general },
2820
- ...input.surge.hosts === void 0 ? {} : { hosts: flatten(input.surge.hosts) }
2821
- };
2822
- }
2823
- if (dns?.length && surge?.hosts?.length) {
2824
- if (dns.length + surge.hosts.length > 2e3) fail("INVALID_SURGE_HOSTS");
2825
- const patterns = new Map(dns.map((entry, index) => [entry.pattern.toLowerCase(), index]));
2826
- for (const [index, host] of surge.hosts.entries()) {
2827
- if (typeof host?.pattern !== "string") fail("INVALID_SURGE_HOSTS");
2828
- const dnsIndex = patterns.get(host.pattern.toLowerCase());
2829
- if (dnsIndex !== void 0) throw new ProfileDefinitionError("DNS_HOSTS_CONFLICT", [`dns[${dnsIndex}]`, `surge.hosts[${index}]`]);
2830
- }
2831
- }
2832
- const { dns: _dns, surge: _surge, proxies: _proxies, groups: _groups, routes: _routes, ...rest } = input;
2833
- return snapshotProfile({
2834
- ...rest,
2835
- ...dns === void 0 ? {} : { dns },
2836
- proxies,
2837
- groups,
2838
- routes,
2839
- ...surge === void 0 ? {} : { surge }
2840
- });
2841
- }
2842
- function isEndpoint(proxy) {
2843
- return [
2844
- "wireguard",
2845
- "tailscale",
2846
- "sing-box-tailscale"
2847
- ].includes(proxy.type);
2848
- }
2849
- function surgeCondition$1(condition, depth = 0) {
2850
- if (depth > 10) return fail("LOGICAL_DEPTH_EXCEEDED");
2851
- if (condition.type === "nativeRuleSet" || condition.type === "ruleSet" && "when" in condition) {
2852
- const parsed = matchSchema.safeParse(condition);
2853
- if (!parsed.success) return fail("PROFILE_CONDITION_UNSUPPORTED");
2854
- const value = parsed.data;
2855
- if (value.type === "ruleSet") return surgeCondition$1(value.when, depth);
2856
- if (value.type !== "nativeRuleSet" || value.engine !== "surge") return fail("PROFILE_CONDITION_UNSUPPORTED");
2857
- if (depth > 0 && value.intervalSeconds !== void 0) return fail("RULESET_COMPOSITION_UNSUPPORTED");
2858
- return {
2859
- type: "ruleSet",
2860
- format: value.format,
2861
- url: value.url,
2862
- ...value.intervalSeconds !== void 0 ? { intervalSeconds: value.intervalSeconds } : {},
2863
- ...value.noResolve !== void 0 ? { noResolve: value.noResolve } : {},
2864
- ...value.includeSniffed !== void 0 ? { includeSniffed: value.includeSniffed } : {}
2865
- };
2866
- }
2867
- if (condition.type === "all" || condition.type === "any") {
2868
- if (!Array.isArray(condition.conditions)) return fail("PROFILE_CONDITION_UNSUPPORTED");
2869
- if (condition.conditions.length === 1) {
2870
- exactDefinition(condition, ["type", "conditions"]);
2871
- return surgeCondition$1(condition.conditions[0], depth + 1);
2872
- }
2873
- return {
2874
- ...condition,
2875
- conditions: condition.conditions.map((child) => surgeCondition$1(child, depth + 1))
2876
- };
2877
- }
2878
- if (condition.type === "not") return {
2879
- ...condition,
2880
- condition: surgeCondition$1(condition.condition, depth + 1)
2881
- };
2882
- if (condition.type === "ipCidr" && isIP(condition.value.split("/")[0]) === 6) return {
2883
- ...condition,
2884
- type: "ipCidr6"
2885
- };
2886
- return condition;
2887
- }
2888
- /** No secrets or I/O. All engine adaptations retain strict validation. */
2889
- function compileProfile(input) {
2890
- try {
2891
- const profile = defineProfile(input);
2892
- snapshotDefinition(profile.routes.map((route) => route.when));
2893
- const ruleSets = [];
2894
- const collectRuleSets = (condition) => {
2895
- if (condition.type === "nativeRuleSet" || condition.type === "ruleSet" && "when" in condition) {
2896
- const parsed = matchSchema.safeParse(condition);
2897
- if (!parsed.success) return fail("PROFILE_CONDITION_UNSUPPORTED");
2898
- ruleSets.push({
2899
- type: "rule",
2900
- id: `ruleset-${ruleSets.length}`,
2901
- when: parsed.data,
2902
- then: { type: "direct" }
2903
- });
2904
- } else if (condition.type === "all" || condition.type === "any") condition.conditions.forEach(collectRuleSets);
2905
- else if (condition.type === "not") collectRuleSets(condition.condition);
2906
- };
2907
- profile.routes.forEach((route) => collectRuleSets(route.when));
2908
- const ruleSetDiagnostics = [];
2909
- validateRuleSets(ruleSets, profile.target.engine, ruleSetDiagnostics, "routes");
2910
- const ruleSetError = ruleSetDiagnostics.find((diagnostic) => diagnostic.severity === "error");
2911
- if (ruleSetError) return fail(ruleSetError.code);
2912
- const nodes = profile.proxies.filter((proxy) => !isEndpoint(proxy));
2913
- const endpoints = profile.proxies.filter(isEndpoint);
2914
- if (profile.target.engine === "surge") {
2915
- if (profile.singBox !== void 0) fail("PROFILE_EXTENSION_UNSUPPORTED");
2916
- if (endpoints.some((endpoint) => endpoint.type === "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
2917
- const compilation = compileSurgeProfile(lowerSurgeProfile({
2918
- target: profile.target,
2919
- ...profile.surge,
2920
- ...profile.dns?.length ? { hosts: [...profile.dns, ...profile.surge?.hosts ?? []] } : {},
2921
- nodes,
2922
- tunnels: endpoints,
2923
- groups: profile.groups,
2924
- routes: profile.routes.map((route) => ({
2925
- ...route,
2926
- when: surgeCondition$1(route.when)
2927
- })),
2928
- fallback: profile.fallback
2929
- }));
2930
- return {
2931
- engine: "surge",
2932
- ok: compilation.ok,
2933
- compilation
2934
- };
2935
- }
2936
- if (profile.target.engine !== "sing-box") return fail("PROFILE_TARGET_UNSUPPORTED");
2937
- if (profile.surge !== void 0) fail("PROFILE_EXTENSION_UNSUPPORTED");
2938
- if (endpoints.some((endpoint) => endpoint.type !== "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
2939
- const registry = /* @__PURE__ */ new Map();
2940
- for (const resource of [...profile.proxies, ...profile.groups]) {
2941
- if (!resource || typeof resource.id !== "string") fail("INVALID_RESOURCE_DEFINITION");
2942
- if (registry.has(resource.id)) fail("DUPLICATE_RESOURCE_ID");
2943
- registry.set(resource.id, resource);
2944
- }
2945
- const lower = (destination) => {
2946
- if (typeof destination === "string") {
2947
- if (!registry.has(destination)) return fail("UNKNOWN_DESTINATION_ID");
2948
- return {
2949
- type: "route",
2950
- to: destination
2951
- };
2952
- }
2953
- if (!destination || typeof destination !== "object") return fail("INVALID_DESTINATION");
2954
- if ("builtin" in destination) {
2955
- exactDefinition(destination, ["builtin"]);
2956
- if (destination.builtin === "DIRECT") return { type: "direct" };
2957
- if (destination.builtin === "REJECT") return { type: "reject" };
2958
- return fail("PROFILE_DESTINATION_UNSUPPORTED");
2959
- }
2960
- if (registry.get(destination.id) !== destination) fail("UNREGISTERED_DESTINATION_INSTANCE");
2961
- return {
2962
- type: "route",
2963
- to: destination.id
2964
- };
2965
- };
2966
- const groups = profile.groups.map((definition) => {
2967
- exactDefinition(definition, [
2968
- "type",
2969
- "id",
2970
- "name",
2971
- "algorithm",
2972
- "members",
2973
- "url",
2974
- "intervalSeconds",
2975
- "timeoutSeconds"
2976
- ]);
2977
- if (definition.type !== "proxy-group" || typeof definition.name !== "string" || !definition.name.trim()) fail("INVALID_GROUP_DEFINITION");
2978
- if (definition.url !== void 0 || definition.intervalSeconds !== void 0 || definition.timeoutSeconds !== void 0) fail("PROFILE_GROUP_OPTIONS_UNSUPPORTED");
2979
- exactDefinition(definition.algorithm, definition.algorithm.type === "urltest" ? [
2980
- "type",
2981
- "url",
2982
- "intervalSeconds",
2983
- "toleranceMs"
2984
- ] : ["type"]);
2985
- const members = definition.members.map((member) => {
2986
- const action = lower(member);
2987
- return action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
2988
- });
2989
- return {
2990
- ...definition.algorithm,
2991
- id: definition.id,
2992
- members
2993
- };
2994
- });
2995
- const routing = profile.routes.map((route, index) => {
2996
- exactDefinition(route, [
2997
- "type",
2998
- "when",
2999
- "to"
3000
- ]);
3001
- if (route.type !== "route") fail("INVALID_ROUTE_DEFINITION");
3002
- return {
3003
- type: "rule",
3004
- id: `route-${index + 1}`,
3005
- when: route.when,
3006
- then: lower(route.to)
3007
- };
3008
- });
3009
- const compilation = compile(snapshotDefinition({
3010
- programs: { profile: {
3011
- engine: "sing-box",
3012
- ...profile.dns === void 0 ? {} : { dns: profile.dns },
3013
- nodes,
3014
- endpoints,
3015
- groups,
3016
- routing,
3017
- fallback: lower(profile.fallback),
3018
- ...profile.singBox?.listener ? { listener: profile.singBox.listener } : {},
3019
- ...profile.singBox?.tun ? { tun: profile.singBox.tun } : {},
3020
- ...profile.singBox?.domainMatching === void 0 ? {} : { domainMatching: profile.singBox.domainMatching },
3021
- ...profile.singBox?.serverAliases === void 0 ? {} : { serverAliases: profile.singBox.serverAliases },
3022
- ...profile.singBox?.unsupportedUdp === void 0 ? {} : { unsupportedUdp: profile.singBox.unsupportedUdp },
3023
- ...profile.singBox?.cacheFile === void 0 ? {} : { cacheFile: profile.singBox.cacheFile }
3024
- } },
3025
- targets: [{
3026
- ...profile.target,
3027
- id: "profile",
3028
- program: "profile",
3029
- mode: profile.singBox?.mode ?? "fragment"
3030
- }]
3031
- }));
3032
- return {
3033
- engine: "sing-box",
3034
- ok: compilation.ok,
3035
- compilation
3036
- };
3037
- } catch (error) {
3038
- return {
3039
- engine: "invalid",
3040
- ok: false,
3041
- code: error instanceof ProfileDefinitionError ? error.code : "INVALID_PROFILE_DEFINITION",
3042
- ...error instanceof ProfileDefinitionError && error.paths ? { paths: error.paths } : {}
3043
- };
3044
- }
3045
- }
3046
- //#endregion
3047
- //#region src/proxy-builder.ts
3048
- /** Fluent construction is separate from the plain-data node consumed by the compiler. */
3049
- function proxyBuilder(node) {
3050
- assertData(node);
3051
- const copy = deepFreeze(structuredClone(node));
3052
- const fork = (patch) => proxyBuilder({
3053
- ...copy,
3054
- ...patch
3055
- });
3056
- return Object.freeze({
3057
- via: (id) => fork({ via: id }),
3058
- label: (text) => fork({ label: text }),
3059
- tcpFastOpen: (enabled) => fork({ tcpFastOpen: enabled }),
3060
- build: () => deepFreeze(structuredClone(copy))
3061
- });
3062
- }
3063
- //#endregion
3064
- //#region src/dsl.ts
3065
- function dnsRule(pattern, server) {
3066
- inspectDefinition({
3067
- pattern,
3068
- server
3069
- });
3070
- const batch = Array.isArray(pattern);
3071
- const patterns = batch ? pattern : [pattern];
3072
- if (patterns.length > 2e3) throw new ProfileDefinitionError("INVALID_DNS_RULE");
3073
- const checked = dnsRulesSchema.safeParse(patterns.map((value) => ({
3074
- pattern: value,
3075
- server
3076
- })));
3077
- if (!checked.success) throw new ProfileDefinitionError("INVALID_DNS_RULE");
3078
- return batch ? checked.data : checked.data[0];
3079
- }
3080
- const ruleSet = (definition) => {
3081
- inspectDefinition(definition);
3082
- exactDefinition(definition, ["id", "when"]);
3083
- return snapshotDefinition({
3084
- ...definition,
3085
- type: "ruleSet"
3086
- });
3087
- };
3088
- function options(value, keys) {
3089
- inspectDefinition(value);
3090
- exactDefinition(value, keys);
3091
- if (Object.values(value).some((v) => v !== void 0 && typeof v !== "boolean")) throw new ProfileDefinitionError("INVALID_MATCH_OPTIONS");
3092
- return snapshotDefinition(value);
3093
- }
3094
- const match = {
3095
- processName: (value) => {
3096
- if (!processNameSchema.safeParse(value).success) throw new Error("INVALID_PROCESS_NAME");
3097
- return {
3098
- type: "processName",
3099
- value
3100
- };
3101
- },
3102
- ruleSet: (set) => set,
3103
- domain: (value, opts = {}) => ({
3104
- type: "domain",
3105
- value,
3106
- ...options(opts, ["includeSniffed"])
3107
- }),
3108
- domainSuffix: (value, opts = {}) => ({
3109
- type: "domainSuffix",
3110
- value,
3111
- ...options(opts, ["includeSniffed"])
3112
- }),
3113
- ipCidr: (value, opts = {}) => ({
3114
- type: "ipCidr",
3115
- value,
3116
- ...options(opts, ["noResolve"])
3117
- }),
3118
- sourceIp: (value) => ({
3119
- type: "sourceIp",
3120
- value
3121
- }),
3122
- port: (from, to = from) => ({
3123
- type: "port",
3124
- from,
3125
- to
3126
- }),
3127
- sourcePort: (from, to = from) => ({
3128
- type: "sourcePort",
3129
- from,
3130
- to
3131
- }),
3132
- network: (value) => ({
3133
- type: "network",
3134
- value
3135
- }),
3136
- all: (...conditions) => ({
3137
- type: "all",
3138
- conditions
3139
- }),
3140
- any: (...conditions) => ({
3141
- type: "any",
3142
- conditions
3143
- }),
3144
- not: (condition) => ({
3145
- type: "not",
3146
- condition
3147
- })
3148
- };
3149
- function nativeConstructor(engine) {
3150
- function construct(value) {
3151
- inspectDefinition(value);
3152
- if (!value || typeof value !== "object") throw new ProfileDefinitionError("INVALID_NATIVE_RULESET");
3153
- exactDefinition(value, [
3154
- "id",
3155
- "url",
3156
- "format",
3157
- "intervalSeconds",
3158
- "noResolve",
3159
- "includeSniffed",
3160
- "resolve",
3161
- "behavior",
3162
- "to"
3163
- ]);
3164
- const input = value;
3165
- const { to, ...resource } = input;
3166
- exactDefinition(resource, [
3167
- "id",
3168
- "url",
3169
- "format",
3170
- "intervalSeconds",
3171
- ...engine === "surge" ? ["noResolve", "includeSniffed"] : engine === "mihomo" ? ["behavior"] : ["resolve"]
3172
- ]);
3173
- const parsed = nativeRuleSetSchema.safeParse({
3174
- ...engine === "surge" ? { format: "rule-set" } : {},
3175
- ...resource,
3176
- id: resource.id ?? "ruleset-pending",
3177
- type: "nativeRuleSet",
3178
- engine
3179
- });
3180
- if (!parsed.success) throw new ProfileDefinitionError("INVALID_NATIVE_RULESET");
3181
- const { id: _id, type: _type, ...fields } = parsed.data;
3182
- const id = resource.id ?? `ruleset-${createHash("sha256").update(JSON.stringify(domainIdentityFields(fields))).digest("hex").slice(0, 16)}`;
3183
- const when = snapshotDefinition({
3184
- ...parsed.data,
3185
- id
3186
- });
3187
- if (Object.hasOwn(input, "to")) {
3188
- if (to === void 0) throw new ProfileDefinitionError("INVALID_DESTINATION");
3189
- return {
3190
- type: "route",
3191
- when,
3192
- to
3193
- };
3194
- }
3195
- return when;
3196
- }
3197
- return construct;
3198
- }
3199
- const surgeRuleSet = nativeConstructor("surge");
3200
- const mihomoRuleSet = nativeConstructor("mihomo");
3201
- const singboxRuleSet = nativeConstructor("sing-box");
3202
- const direct = () => ({ type: "direct" });
3203
- const reject = () => ({ type: "reject" });
3204
- const route = (to) => ({
3205
- type: "route",
3206
- to
3207
- });
3208
- /** An exit parameter declared by policy.exits and resolved by use.bindings. */
3209
- const slot = (name) => ({
3210
- type: "slot",
3211
- name
3212
- });
3213
- const secret = (name) => ({
3214
- type: "env",
3215
- name
3216
- });
3217
- const rule = (id, when, then) => ({
3218
- type: "rule",
3219
- id,
3220
- when,
3221
- then
3222
- });
3223
- const block = (id, rules, when) => ({
3224
- type: "block",
3225
- id,
3226
- rules,
3227
- ...when ? { when } : {}
3228
- });
3229
- const policy = (definition) => ({
3230
- type: "policy",
3231
- ...definition
3232
- });
3233
- const use = (definition, options) => ({
3234
- type: "use",
3235
- id: options.id,
3236
- policy: definition,
3237
- bindings: options.bindings
3238
- });
3239
- const sequence = (...parts) => parts.flatMap((part) => Array.isArray(part) ? part : [part]);
3240
- const defineConfig = (config) => config;
3241
- /** A shared strategy declares an algorithm or explicitly selects native implementations. */
3242
- const strategy = (definition) => ({
3243
- type: "strategy",
3244
- ...definition
3245
- });
3246
- const group = {
3247
- auto: () => ({ type: "auto" }),
3248
- select: () => ({ type: "select" }),
3249
- urltest: (options) => ({
3250
- type: "urltest",
3251
- ...options
3252
- })
3253
- };
3254
- const surge$1 = {
3255
- config: surgeConfig,
3256
- match: surgeMatch,
3257
- smart: () => ({ type: "surge-smart" }),
3258
- ruleSet: surgeRuleSet
3259
- };
3260
- const mihomo = {
3261
- ruleSet: mihomoRuleSet,
3262
- ruleProvider: mihomoRuleSet
3263
- };
3264
- /** Protocol constructors keep credentials and options specific to their protocol. */
3265
- function nodeConstructor(type) {
3266
- return (options) => ({
3267
- ...options,
3268
- type
3269
- });
3270
- }
3271
- const proxy = {
3272
- builder: proxyBuilder,
3273
- http: nodeConstructor("http"),
3274
- trojan: nodeConstructor("trojan"),
3275
- anytls: nodeConstructor("anytls"),
3276
- hysteria2: nodeConstructor("hysteria2"),
3277
- shadowsocks: nodeConstructor("shadowsocks"),
3278
- vmess: nodeConstructor("vmess"),
3279
- vless: nodeConstructor("vless")
3280
- };
3281
- const singbox$1 = {
3282
- ruleSet: singboxRuleSet,
3283
- tailscale: (options) => ({
3284
- ...options,
3285
- type: "sing-box-tailscale"
3286
- })
3287
- };
3288
- //#endregion
3289
- //#region src/render.ts
3290
- const DIRECT = "pl-direct";
3291
- const DNS = "pl-dns";
3292
- const actionTag = (action) => action.type === "route" ? action.to : action.type === "direct" ? DIRECT : "pl-reject";
3293
- /** Secret resolution is once per token per batch, including across providers. */
3294
- function render(compilation, resolveSecret) {
3295
- if (!compilation.ok) throw new RenderError("COMPILATION_FAILED");
3296
- const secret = secretReader(resolveSecret);
3297
- return compilation.plans.map((plan) => ({
3298
- target: plan.target.id,
3299
- filename: `${plan.target.id}.${plan.target.engine === "surge" ? "conf" : plan.target.engine === "sing-box" ? "json" : "yaml"}`,
3300
- content: plan.target.engine === "surge" ? surge(plan, secret) : plan.target.engine === "sing-box" ? JSON.stringify(singbox(plan, secret), null, 2) + "\n" : stringify(clashConfig(plan, secret))
3301
- }));
3302
- }
3303
- function singCondition(condition) {
3304
- switch (condition.type) {
3305
- case "ruleSet": return singCondition(condition.when);
3306
- case "nativeRuleSet": return { rule_set: [condition.id] };
3307
- case "all":
3308
- case "any": return {
3309
- type: "logical",
3310
- mode: condition.type === "all" ? "and" : "or",
3311
- rules: condition.conditions.map(singCondition)
3312
- };
3313
- case "not": return {
3314
- type: "logical",
3315
- mode: "and",
3316
- rules: [singCondition(condition.condition)],
3317
- invert: true
3318
- };
3319
- case "domain": return { domain: [condition.value] };
3320
- case "domainSuffix": return { domain_suffix: [condition.value] };
3321
- case "ipCidr": return { ip_cidr: [condition.value] };
3322
- case "processName": return { process_name: [condition.value] };
3323
- case "sourceIp": return { source_ip_cidr: [condition.value.includes("/") ? condition.value : `${condition.value}/${isIP(condition.value) === 6 ? 128 : 32}`] };
3324
- case "network": return { network: [condition.value] };
3325
- case "port":
3326
- case "sourcePort": {
3327
- const key = condition.type === "port" ? "port" : "source_port";
3328
- return condition.from === condition.to ? { [key]: [condition.from] } : { [`${key}_range`]: [`${condition.from}:${condition.to}`] };
3329
- }
3330
- }
3331
- }
3332
- function singAction(action) {
3333
- return action.type === "reject" ? {
3334
- action: "reject",
3335
- method: "default",
3336
- no_drop: true
3337
- } : {
3338
- action: "route",
3339
- outbound: actionTag(action)
3340
- };
3341
- }
3342
- function singbox(plan, secret) {
3343
- const { program, target } = plan;
3344
- const modern = targetCatalog.find((entry) => entry.engine === target.engine && entry.version === target.version)?.dns === "typed";
3345
- const standalone = target.mode === "standalone";
3346
- const routedDns = target.version === "1.14.4" && standalone && !!program.dns?.length;
3347
- const domainResolver = routedDns ? "pl-routed-dns" : DNS;
3348
- const outbounds = [{
3349
- type: "direct",
3350
- tag: DIRECT,
3351
- ...!modern && standalone ? { domain_strategy: "prefer_ipv4" } : {}
3352
- }];
3353
- if (program.groups.some((group) => group.members.includes("REJECT"))) outbounds.push({
3354
- type: "block",
3355
- tag: "pl-reject"
3356
- });
3357
- for (const node of program.nodes) outbounds.push({
3358
- ...singboxProxy(aliasProxyServer(node, program.serverAliases), secret),
3359
- ...modern && program.dns?.length ? { domain_resolver: {
3360
- server: domainResolver,
3361
- strategy: "prefer_ipv4"
3362
- } } : {}
3363
- });
3364
- for (const group of program.groups) outbounds.push(singboxGroup(group, singboxMemberTag));
3365
- const rules = plan.rules.flatMap((rule) => [...target.version === "1.14.4" && needsResolve(rule.when) ? [{
3366
- ip_cidr: ["0.0.0.0/0", "::/0"],
3367
- invert: true,
3368
- action: "resolve"
3369
- }] : [], {
3370
- ...singCondition(rule.when),
3371
- ...singAction(rule.then)
3372
- }]);
3373
- const routing = { rules };
3374
- if (program.domainMatching === "prefer-sniffed") rules.unshift({
3375
- action: "sniff",
3376
- sniffer: ["http", "tls"]
3377
- });
3378
- if (program.tun) {
3379
- rules.unshift({
3380
- inbound: ["pl-tun"],
3381
- port: 53,
3382
- action: "hijack-dns"
3383
- });
3384
- if (program.tun.autoRoute) routing.auto_detect_interface = true;
3385
- }
3386
- if (routedDns) rules.unshift({
3387
- inbound: ["pl-dns-listener"],
3388
- action: "hijack-dns"
3389
- });
3390
- if (plan.nativeRuleSets.length) routing.rule_set = plan.nativeRuleSets.map((r) => ({
3391
- type: "remote",
3392
- tag: r.id,
3393
- url: r.url,
3394
- format: r.format,
3395
- update_interval: `${r.intervalSeconds}s`,
3396
- download_detour: DIRECT
3397
- }));
3398
- if (program.fallback.type === "reject") rules.push(singAction(program.fallback));
3399
- else routing.final = actionTag(program.fallback);
3400
- const config = {
3401
- log: { level: "warn" },
3402
- outbounds,
3403
- route: routing
3404
- };
3405
- if (program.cacheFile) config.experimental = { cache_file: { enabled: true } };
3406
- if (standalone) {
3407
- const listener = program.listener;
3408
- config.inbounds = [
3409
- {
3410
- type: "mixed",
3411
- tag: "pl-listener",
3412
- listen: "127.0.0.1",
3413
- listen_port: listener.port
3414
- },
3415
- ...routedDns ? [{
3416
- type: "direct",
3417
- tag: "pl-dns-listener",
3418
- listen: "127.0.0.1",
3419
- listen_port: listener.port,
3420
- network: "udp"
3421
- }] : [],
3422
- ...program.tun ? [{
3423
- type: "tun",
3424
- tag: "pl-tun",
3425
- address: [...program.tun.address],
3426
- stack: program.tun.stack,
3427
- auto_route: program.tun.autoRoute,
3428
- strict_route: program.tun.strictRoute,
3429
- dns_mode: program.tun.dnsMode,
3430
- ...program.tun.routeExcludeAddress ? { route_exclude_address: [...program.tun.routeExcludeAddress] } : {}
3431
- }] : []
3432
- ];
3433
- config.dns = {
3434
- servers: [modern ? {
3435
- type: "udp",
3436
- tag: DNS,
3437
- server: listener.resolver,
3438
- server_port: 53
3439
- } : {
3440
- tag: DNS,
3441
- address: `udp://${isIP(listener.resolver) === 6 ? `[${listener.resolver}]` : listener.resolver}`,
3442
- detour: DIRECT
3443
- }],
3444
- final: DNS,
3445
- strategy: "prefer_ipv4",
3446
- ...program.domainMatching ? { reverse_mapping: true } : {}
3447
- };
3448
- if (modern && (!program.dns?.length || target.version === "1.14.4")) routing.default_domain_resolver = {
3449
- server: domainResolver,
3450
- strategy: "prefer_ipv4"
3451
- };
3452
- }
3453
- if (program.dns?.length) {
3454
- const dns = config.dns;
3455
- if (routedDns) dns.servers.push({
3456
- type: "udp",
3457
- tag: "pl-routed-dns",
3458
- server: "127.0.0.1",
3459
- server_port: program.listener.port
3460
- });
3461
- dns.rules = program.dns.map((rule, index) => {
3462
- const tag = `pl-domain-dns-${index}`;
3463
- if (isIP(rule.server)) dns.servers.push(modern ? {
3464
- type: "udp",
3465
- tag,
3466
- server: rule.server,
3467
- server_port: 53
3468
- } : {
3469
- tag,
3470
- address: `udp://${isIP(rule.server) === 6 ? `[${rule.server}]` : rule.server}`,
3471
- detour: DIRECT
3472
- });
3473
- else {
3474
- const url = dohUrl(rule.server);
3475
- dns.servers.push(modern ? {
3476
- type: "https",
3477
- tag,
3478
- server: url.hostname.replace(/^\[|\]$/g, ""),
3479
- server_port: Number(url.port || 443),
3480
- path: url.pathname,
3481
- tls: { enabled: true },
3482
- domain_resolver: {
3483
- server: DNS,
3484
- strategy: "prefer_ipv4"
3485
- }
3486
- } : {
3487
- tag,
3488
- address: url.href,
3489
- address_resolver: DNS,
3490
- detour: DIRECT
3491
- });
3492
- }
3493
- return {
3494
- ...dnsCondition(rule),
3495
- server: tag
3496
- };
3497
- });
3498
- }
3499
- if (program.endpoints?.length) {
3500
- config.endpoints = program.endpoints.map((endpoint) => ({
3501
- type: "tailscale",
3502
- tag: endpoint.id,
3503
- hostname: endpoint.hostname,
3504
- state_directory: endpoint.stateDirectory,
3505
- accept_routes: endpoint.acceptRoutes,
3506
- domain_resolver: { server: `pl-ts-dns-${endpoint.id}` },
3507
- ...endpoint.authKey ? { auth_key: secret(endpoint.authKey) } : {},
3508
- ...endpoint.exitNode ? { exit_node: endpoint.exitNode } : {},
3509
- ...endpoint.exitNodeAllowLanAccess !== void 0 ? { exit_node_allow_lan_access: endpoint.exitNodeAllowLanAccess } : {}
3510
- }));
3511
- const dns = config.dns;
3512
- for (const endpoint of program.endpoints) dns.servers.push({
3513
- type: "udp",
3514
- tag: `pl-ts-dns-${endpoint.id}`,
3515
- server: endpoint.bootstrapResolver,
3516
- server_port: 53
3517
- });
3518
- }
3519
- return config;
3520
- }
3521
- function surgeOptions(condition) {
3522
- return [
3523
- ...condition.type === "ipCidr" && condition.noResolve !== false ? ["no-resolve"] : [],
3524
- ...condition.type === "nativeRuleSet" && condition.engine === "surge" && condition.noResolve ? ["no-resolve"] : [],
3525
- ..."includeSniffed" in condition && condition.includeSniffed ? ["extended-matching"] : []
3526
- ].map((value) => `,${value}`).join("");
3527
- }
3528
- function surgeCondition(condition) {
3529
- switch (condition.type) {
3530
- case "ruleSet": return surgeCondition(condition.when);
3531
- case "nativeRuleSet": return `${condition.format === "domain-set" ? "DOMAIN-SET" : "RULE-SET"},${condition.url}`;
3532
- case "all":
3533
- case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${surgeCondition(c)}${surgeOptions(c)})`).join(",")})`;
3534
- case "not": return `NOT,((${surgeCondition(condition.condition)}${surgeOptions(condition.condition)}))`;
3535
- case "domain": return `DOMAIN,${condition.value}`;
3536
- case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
3537
- case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}`;
3538
- case "processName": return `PROCESS-NAME,${condition.value}`;
3539
- case "sourceIp": return `SRC-IP,${condition.value}`;
3540
- case "network": return `PROTOCOL,${condition.value.toUpperCase()}`;
3541
- case "port":
3542
- case "sourcePort": return `${condition.type === "port" ? "DEST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
3543
- }
3544
- }
3545
- function surge(plan, secret) {
3546
- const policy = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
3547
- const lines = ["# Generated by proxylang; see manifest for source mapping and preconditions."];
3548
- if (plan.target.mode === "standalone") lines.push("[General]", "loglevel = warning", "allow-wifi-access = false", `http-listen = 127.0.0.1:${plan.program.listener.port}`, `dns-server = ${plan.program.listener.resolver}`, "");
3549
- lines.push("[Proxy]");
3550
- for (const node of plan.program.nodes) lines.push(surgeProxy(node, secret));
3551
- lines.push("", "[Proxy Group]");
3552
- for (const group of plan.program.groups) lines.push(surgeGroup(group));
3553
- lines.push("", "[Rule]");
3554
- for (const rule of plan.rules) {
3555
- lines.push(`# ${rule.id}`);
3556
- 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}` : ""}`);
3557
- }
3558
- lines.push(`FINAL,${policy(plan.program.fallback)}`);
3559
- return lines.join("\n") + "\n";
3560
- }
3561
- //#endregion
3562
- //#region src/host.ts
3563
- const buildHints = {
3564
- INVALID_OUTPUT_DIRECTORY: "提供非空输出目录路径",
3565
- OUTPUT_LOCKED: "确认没有构建正在运行;检查并处理遗留锁后重试,不要删除仍在使用的锁",
3566
- SECRET_MISSING: "在构建环境提供配置引用的非空秘密变量",
3567
- SECRET_RESOLUTION_FAILED: "检查秘密解析器;原始异常不会进入构建报告",
3568
- PUBLISHED_CLEANUP_FAILED: "活动指针已经切换;检查残留锁和临时文件,不要假设发布失败",
3569
- FAILED_CLEANUP_REQUIRED: "旧活动指针保留;检查本次残留产物和锁后重试"
3570
- };
3571
- function outputFailure(error) {
3572
- const code = error && typeof error === "object" ? Object.getOwnPropertyDescriptor(error, "code")?.value : void 0;
3573
- if (code === "EACCES" || code === "EPERM") return {
3574
- reason: "ACCESS_DENIED",
3575
- hint: "检查输出目录的写入和遍历权限"
3576
- };
3577
- if (code === "ENOSPC" || code === "EDQUOT") return {
3578
- reason: "NO_SPACE",
3579
- hint: "释放磁盘空间或调整存储配额后重试"
3580
- };
3581
- if (code === "EROFS") return {
3582
- reason: "READ_ONLY",
3583
- hint: "选择可写的本地输出目录"
3584
- };
3585
- if ([
3586
- "ENOTDIR",
3587
- "EISDIR",
3588
- "EEXIST",
3589
- "UNSAFE_DIRECTORY"
3590
- ].includes(code)) return {
3591
- reason: "INVALID_DIRECTORY",
3592
- hint: "检查输出根、generations 和 active.json 的文件类型;输出目录不能是符号链接"
3593
- };
3594
- return {
3595
- reason: "IO_ERROR",
3596
- hint: "检查输出目录及文件系统状态,旧活动配置在发布前失败时保持不变"
3597
- };
3598
- }
3599
- async function directory(path) {
3600
- await mkdir(path, {
3601
- recursive: true,
3602
- mode: 448
3603
- });
3604
- const stat = await lstat(path);
3605
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw Object.assign(/* @__PURE__ */ new Error("UNSAFE_DIRECTORY"), { code: "UNSAFE_DIRECTORY" });
3606
- }
3607
- /** All targets publish together by one active.json rename. Config files never go to stdout. */
3608
- async function buildToDirectory(compilation, output, resolveSecret = (token) => process.env[token.name]) {
3609
- if (!compilation.ok) return {
3610
- published: false,
3611
- exitCode: 1,
3612
- code: "COMPILATION_FAILED"
3613
- };
3614
- if (typeof output !== "string" || !output.trim()) return {
3615
- published: false,
3616
- exitCode: 1,
3617
- code: "INVALID_OUTPUT_DIRECTORY",
3618
- hint: buildHints.INVALID_OUTPUT_DIRECTORY
3619
- };
3620
- const root = resolve(output);
3621
- if (compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(root, endpoint.stateDirectory)))) return {
3622
- published: false,
3623
- exitCode: 1,
3624
- code: "ENDPOINT_STATE_OVERLAP"
3625
- };
3626
- const lock = join(root, ".proxylang-lock");
3627
- const id = randomUUID();
3628
- const relativeGeneration = `generations/${id}`;
3629
- const generation = join(root, relativeGeneration);
3630
- const pointer = join(root, `.active-${id}.json`);
3631
- let locked = false;
3632
- let created = false;
3633
- let published = false;
3634
- let code = "BUILD_FAILED";
3635
- let cleanupFailed = false;
3636
- let detail = {};
3637
- try {
3638
- await directory(root);
3639
- try {
3640
- await mkdir(lock, { mode: 448 });
3641
- locked = true;
3642
- } catch (error) {
3643
- if (error.code === "EEXIST") return {
3644
- published: false,
3645
- exitCode: 1,
3646
- code: "OUTPUT_LOCKED",
3647
- hint: buildHints.OUTPUT_LOCKED
3648
- };
3649
- throw error;
3650
- }
3651
- const artifacts = render(compilation, resolveSecret);
3652
- await directory(join(root, "generations"));
3653
- await mkdir(generation, { mode: 448 });
3654
- created = true;
3655
- for (const artifact of artifacts) await writeFile(join(generation, artifact.filename), artifact.content, {
3656
- encoding: "utf8",
3657
- mode: 384,
3658
- flag: "wx"
3659
- });
3660
- const manifest = {
3661
- schemaVersion: 1,
3662
- targets: compilation.plans.map((plan) => ({
3663
- target: plan.target,
3664
- sourceMap: plan.sourceMap,
3665
- strategySelections: plan.strategySelections,
3666
- preconditions: plan.preconditions,
3667
- nativeValidation: plan.nativeValidation
3668
- })),
3669
- diagnostics: compilation.diagnostics,
3670
- cases: compilation.cases,
3671
- artifacts: artifacts.map((artifact) => ({
3672
- target: artifact.target,
3673
- filename: artifact.filename
3674
- }))
3675
- };
3676
- await writeFile(join(generation, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n", {
3677
- mode: 384,
3678
- flag: "wx"
3679
- });
3680
- const active = {
3681
- schemaVersion: 1,
3682
- generation: relativeGeneration,
3683
- manifest: `${relativeGeneration}/manifest.json`,
3684
- artifacts: Object.fromEntries(artifacts.map((artifact) => [artifact.target, `${relativeGeneration}/${artifact.filename}`]))
3685
- };
3686
- await writeFile(pointer, JSON.stringify(active, null, 2) + "\n", {
3687
- mode: 384,
3688
- flag: "wx"
3689
- });
3690
- await rename(pointer, join(root, "active.json"));
3691
- published = true;
3692
- code = "PUBLISHED";
3693
- } catch (error) {
3694
- code = error instanceof RenderError ? error.code : "OUTPUT_FAILED";
3695
- detail = error instanceof RenderError ? {
3696
- hint: buildHints[code],
3697
- ...secretFailure(error)
3698
- } : outputFailure(error);
3699
- } finally {
3700
- if (locked) {
3701
- try {
3702
- await rm(pointer, { force: true });
3703
- } catch {
3704
- cleanupFailed = true;
3705
- }
3706
- if (created && !published) try {
3707
- await rm(generation, { recursive: true });
3708
- } catch {
3709
- cleanupFailed = true;
3710
- }
3711
- try {
3712
- await rm(lock, { recursive: true });
3713
- } catch {
3714
- cleanupFailed = true;
3715
- }
3716
- }
3717
- }
3718
- const resultCode = cleanupFailed ? published ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : code;
3719
- return {
3720
- published,
3721
- exitCode: published ? cleanupFailed ? 2 : 0 : 1,
3722
- code: resultCode,
3723
- ...detail,
3724
- ...buildHints[resultCode] ? { hint: buildHints[resultCode] } : {},
3725
- ...published ? {
3726
- active: join(root, "active.json"),
3727
- generation
3728
- } : {}
3729
- };
3730
- }
3731
- //#endregion
3732
- //#region src/surge-publish.ts
3733
- var SurgePublishError = class extends Error {
3734
- published;
3735
- constructor(message, published) {
3736
- super(message);
3737
- this.published = published;
3738
- }
3739
- };
3740
- async function publishProfiles(files, surgeDirectory, io = { rename }) {
3741
- if (!files.size || files.size > 16 || [...files.keys()].some((name) => !/^[a-z0-9][a-z0-9-]*\.(?:conf|json)$/.test(name))) throw new Error("INVALID_PROFILE_FILENAMES");
3742
- const root = resolve(surgeDirectory);
3743
- const generations = join(root, ".generations");
3744
- const id = randomUUID();
3745
- const generation = join(generations, id);
3746
- const pointer = join(root, `.out-${id}`);
3747
- const output = join(root, "out");
3748
- const backup = join(generations, `legacy-${id}`);
3749
- const lock = join(root, ".build-lock");
3750
- const remove = io.rm ?? rm;
3751
- let failure;
3752
- let locked = false, created = false, committed = false, movedLegacy = false, recoveryFailed = false;
3753
- async function directory(path) {
3754
- await mkdir(path, {
3755
- recursive: true,
3756
- mode: 448
3757
- });
3758
- const stat = await lstat(path);
3759
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
3760
- }
3761
- try {
3762
- await directory(root);
3763
- try {
3764
- await mkdir(lock, { mode: 448 });
3765
- locked = true;
3766
- } catch (error) {
3767
- if (error.code === "EEXIST") throw new Error("OUTPUT_LOCKED");
3768
- throw error;
3769
- }
3770
- await directory(generations);
3771
- let previous;
3772
- try {
3773
- previous = await lstat(output);
3774
- } catch (error) {
3775
- if (error.code !== "ENOENT") throw error;
3776
- }
3777
- if (previous?.isSymbolicLink()) {
3778
- const target = await readlink(output);
3779
- if (!/^\.generations\/(?:legacy-)?[a-f0-9-]{36}$/.test(target)) throw new Error("UNMANAGED_OUTPUT_LINK");
3780
- const stat = await lstat(join(root, target));
3781
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
3782
- } else if (previous && !previous.isDirectory()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
3783
- await mkdir(generation, { mode: 448 });
3784
- created = true;
3785
- for (const [name, content] of files) await writeFile(join(generation, name), content, {
3786
- mode: 384,
3787
- flag: "wx"
3788
- });
3789
- await symlink(`.generations/${id}`, pointer, "dir");
3790
- if (previous?.isDirectory()) {
3791
- await io.rename(output, backup);
3792
- movedLegacy = true;
3793
- }
3794
- try {
3795
- await io.rename(pointer, output);
3796
- committed = true;
3797
- } catch (error) {
3798
- if (movedLegacy) try {
3799
- await io.rename(backup, output);
3800
- movedLegacy = false;
3801
- } catch {
3802
- recoveryFailed = true;
3803
- throw new Error("PUBLISH_RECOVERY_REQUIRED");
3804
- }
3805
- throw error;
3806
- }
3807
- } catch (error) {
3808
- const code = error instanceof Error && /^(?:INVALID_PROFILE_FILENAMES|OUTPUT_LOCKED|UNMANAGED_OUTPUT_LINK|UNSAFE_OUTPUT_DIRECTORY|PUBLISH_RECOVERY_REQUIRED)$/.test(error.message) ? error.message : "PROFILE_PUBLISH_FAILED";
3809
- failure = new Error(code);
3810
- } finally {
3811
- if (!recoveryFailed) try {
3812
- await remove(pointer, { force: true });
3813
- if (created && !committed) await remove(generation, {
3814
- recursive: true,
3815
- force: true
3816
- });
3817
- if (locked) await remove(lock, {
3818
- recursive: true,
3819
- force: true
3820
- });
3821
- } catch {
3822
- failure ??= /* @__PURE__ */ new Error("PROFILE_PUBLISH_CLEANUP_FAILED");
3823
- }
3824
- }
3825
- if (failure) throw new SurgePublishError(failure.message === "PROFILE_PUBLISH_CLEANUP_FAILED" ? committed ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : failure.message, committed);
3826
- }
3827
- //#endregion
3828
- //#region src/profile-build.ts
3829
- function compileBatch(profiles, output) {
3830
- const entries = Object.entries(profiles);
3831
- const compiled = [];
3832
- let outputDirectoryChecked = false;
3833
- const result = (code, paths) => ({
3834
- ...paths ? { paths } : {},
3835
- ok: code === "CHECKED",
3836
- code,
3837
- entries,
3838
- compiled,
3839
- outputDirectoryChecked
3840
- });
3841
- if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return result("INVALID_PROFILE_FILENAMES");
3842
- compiled.push(...entries.map(([, profile]) => compileProfile(profile)));
3843
- const invalid = compiled.find((profile) => !profile.ok);
3844
- if (invalid) return result(invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED", invalid.engine === "invalid" ? invalid.paths : void 0);
3845
- if (output !== void 0) {
3846
- outputDirectoryChecked = true;
3847
- if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(output, endpoint.stateDirectory))))) return result("ENDPOINT_STATE_OVERLAP");
3848
- }
3849
- return result("CHECKED");
3850
- }
3851
- function checkBuild(input) {
3852
- const root = process.cwd();
3853
- let definition;
3854
- try {
3855
- definition = defineBuild(input);
3856
- } catch {
3857
- return {
3858
- ok: false,
3859
- code: "INVALID_BUILD_DEFINITION",
3860
- profileCount: 0,
3861
- outputDirectoryChecked: false,
3862
- profiles: []
3863
- };
3864
- }
3865
- const checked = compileBatch(definition.profiles, definition.outDir === void 0 ? void 0 : resolve(root, definition.outDir));
3866
- return {
3867
- ok: checked.ok,
3868
- code: checked.code,
3869
- profileCount: checked.entries.length,
3870
- outputDirectoryChecked: checked.outputDirectoryChecked,
3871
- profiles: checked.compiled.map((profile, index) => ({
3872
- id: checked.entries[index][0],
3873
- engine: profile.engine,
3874
- ok: profile.ok,
3875
- ...profile.engine === "invalid" ? {
3876
- code: profile.code,
3877
- ...profile.paths ? { paths: profile.paths } : {},
3878
- diagnostics: []
3879
- } : { diagnostics: profile.compilation.diagnostics }
3880
- }))
3881
- };
3882
- }
3883
- async function publish(profiles, output, readSecret) {
3884
- try {
3885
- const checked = compileBatch(profiles, output);
3886
- if (!checked.ok) return {
3887
- published: false,
3888
- exitCode: 1,
3889
- code: checked.code,
3890
- ...checked.paths ? { paths: checked.paths } : {}
3891
- };
3892
- const { entries, compiled } = checked;
3893
- const read = secretReader(readSecret);
3894
- const files = /* @__PURE__ */ new Map();
3895
- for (const [index, profile] of compiled.entries()) {
3896
- if (profile.engine === "invalid") throw new Error();
3897
- const artifacts = profile.engine === "surge" ? renderSurgeProfiles([profile.compilation], read) : render(profile.compilation, read);
3898
- files.set(`${entries[index][0]}.${profile.engine === "surge" ? "conf" : "json"}`, artifacts[0].content);
3899
- }
3900
- await publishProfiles(files, output);
3901
- return {
3902
- published: true,
3903
- exitCode: 0,
3904
- code: "PUBLISHED",
3905
- active: join(resolve(output), "out")
3906
- };
3907
- } catch (error) {
3908
- if (error instanceof SurgePublishError) return {
3909
- published: error.published,
3910
- exitCode: error.published ? 2 : 1,
3911
- code: error.message,
3912
- ...error.published ? { active: join(resolve(output), "out") } : {},
3913
- ...error.message === "PUBLISH_RECOVERY_REQUIRED" ? { hint: "out may be absent; preserve the lock, backup, generation and temporary pointer for manual recovery" } : {}
3914
- };
3915
- return {
3916
- published: false,
3917
- exitCode: 1,
3918
- code: error instanceof RenderError ? error.code : "BUILD_FAILED",
3919
- ...secretFailure(error)
3920
- };
3921
- }
3922
- }
3923
- function record(value, keys) {
3924
- if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
3925
- for (const key of Reflect.ownKeys(value)) {
3926
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
3927
- if (typeof key !== "string" || keys && !keys.includes(key) || !descriptor.enumerable || !("value" in descriptor)) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
3928
- }
3929
- }
3930
- /** Capture data and callback references before application preflight can change its source. */
3931
- function defineBuild(input) {
3932
- try {
3933
- record(input, [
3934
- "profiles",
3935
- "preflight",
3936
- "secrets",
3937
- "outDir"
3938
- ]);
3939
- if (input.outDir !== void 0 && (typeof input.outDir !== "string" || !input.outDir.trim() || input.outDir.trim() !== input.outDir || input.outDir.includes("\0"))) throw new Error();
3940
- record(input.profiles);
3941
- for (const callback of [input.preflight, input.secrets]) if (callback !== void 0 && typeof callback !== "function") throw new Error();
3942
- return Object.freeze({
3943
- ...input.outDir === void 0 ? {} : { outDir: input.outDir },
3944
- profiles: snapshotProfile(input.profiles),
3945
- ...input.preflight === void 0 ? {} : { preflight: input.preflight },
3946
- ...input.secrets === void 0 ? {} : { secrets: input.secrets }
3947
- });
3948
- } catch {
3949
- throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
3950
- }
3951
- }
3952
- function profileBuildFailure(code, validation = false, profileCount = 0) {
3953
- return {
3954
- published: false,
3955
- exitCode: 1,
3956
- code,
3957
- warnings: {},
3958
- validation,
3959
- profileCount
3960
- };
3961
- }
3962
- /** Pure orchestration result; the CLI owns stdout and process exit status. */
3963
- async function runBuild(input, output, options = {}) {
3964
- const root = process.cwd();
3965
- let validation;
3966
- try {
3967
- record(options, ["validation"]);
3968
- if (options.validation !== void 0 && typeof options.validation !== "boolean") throw new Error();
3969
- validation = options.validation ?? false;
3970
- } catch {
3971
- return profileBuildFailure("INVALID_BUILD_OPTIONS");
3972
- }
3973
- let definition;
3974
- try {
3975
- definition = defineBuild(input);
3976
- } catch {
3977
- return profileBuildFailure("INVALID_BUILD_DEFINITION", validation);
3978
- }
3979
- const profileCount = Object.keys(definition.profiles).length;
3980
- const failure = (code) => profileBuildFailure(code, validation, profileCount);
3981
- if (typeof output !== "string" || !output.trim()) return failure("INVALID_OUTPUT_DIRECTORY");
3982
- output = resolve(root, output);
3983
- if (validation && !definition.secrets) return failure("VALIDATION_SECRETS_REQUIRED");
3984
- let codes;
3985
- try {
3986
- codes = definition.preflight ? definition.preflight() : [];
3987
- } catch {
3988
- return failure("PREFLIGHT_FAILED");
3989
- }
3990
- try {
3991
- codes = snapshotDefinition(codes);
3992
- if (!Array.isArray(codes) || codes.length > 1e3 || codes.some((code) => typeof code !== "string" || !/^[A-Z][A-Z0-9_]{0,63}$/.test(code))) throw new Error();
3993
- } catch {
3994
- return failure("INVALID_PREFLIGHT_WARNINGS");
3995
- }
3996
- const warnings = {};
3997
- for (const code of codes) warnings[code] = (warnings[code] ?? 0) + 1;
3998
- const context = Object.freeze({ validation });
3999
- const readSecret = definition.secrets;
4000
- return {
4001
- ...await publish(definition.profiles, output, readSecret ? (token) => readSecret(token, context) : (token) => process.env[token.name]),
4002
- warnings,
4003
- validation,
4004
- profileCount
4005
- };
4006
- }
4007
- //#endregion
4008
- export { inspectDefinition as $, 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, exactDefinition 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, definitionDiagnostic as Z, rule as _, render as a, sequence as b, direct as c, match as d, outbound as et, mihomo as f, route as g, reject as h, buildToDirectory as i, secretReader as j, renderSurgeProfile as k, dnsRule as l, proxy as m, defineBuild as n, block as o, policy as p, ProfileDefinitionError as q, runBuild as r, defineConfig as s, checkBuild as t, group as u, ruleSet as v, surge$1 as w, singbox$1 as x, secret as y, surgeProxy as z };