proxylang 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +36 -1
- package/dist/index.d.ts +26 -2
- package/dist/index.js +7 -603
- package/dist/{host-Bea3np6i.js → surge-build-DbQ9Ddhc.js} +740 -62
- package/package.json +1 -1
|
@@ -2,7 +2,7 @@ import { z } from "zod";
|
|
|
2
2
|
import { isIP } from "node:net";
|
|
3
3
|
import ipaddr from "ipaddr.js";
|
|
4
4
|
import { stringify } from "yaml";
|
|
5
|
-
import { lstat, mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
|
|
6
6
|
import { join, resolve } from "node:path";
|
|
7
7
|
import { randomUUID } from "node:crypto";
|
|
8
8
|
//#region src/surge-definitions.ts
|
|
@@ -81,6 +81,10 @@ function snapshot(input) {
|
|
|
81
81
|
}
|
|
82
82
|
return copy(input, 0);
|
|
83
83
|
}
|
|
84
|
+
function snapshotDefinition(input) {
|
|
85
|
+
inspect(input);
|
|
86
|
+
return snapshot(input);
|
|
87
|
+
}
|
|
84
88
|
function exact(value, keys) {
|
|
85
89
|
if (!value || typeof value !== "object" || Array.isArray(value)) fail("DEFINITION_NOT_DATA");
|
|
86
90
|
if (Object.keys(value).some((key) => !keys.includes(key))) fail("DEFINITION_UNKNOWN_FIELD");
|
|
@@ -115,16 +119,22 @@ function defineProxyGroup(input) {
|
|
|
115
119
|
}
|
|
116
120
|
function defineRoute(input) {
|
|
117
121
|
inspect(input);
|
|
118
|
-
exact(input, [
|
|
119
|
-
"id",
|
|
120
|
-
"when",
|
|
121
|
-
"to"
|
|
122
|
-
]);
|
|
122
|
+
exact(input, ["when", "to"]);
|
|
123
123
|
return {
|
|
124
124
|
...input,
|
|
125
125
|
type: "route"
|
|
126
126
|
};
|
|
127
127
|
}
|
|
128
|
+
function defineRoutes(input) {
|
|
129
|
+
inspect(input);
|
|
130
|
+
exact(input, ["when", "to"]);
|
|
131
|
+
if (!Array.isArray(input.when)) fail("INVALID_ROUTE_DEFINITION");
|
|
132
|
+
return input.when.map((when) => ({
|
|
133
|
+
type: "route",
|
|
134
|
+
when,
|
|
135
|
+
to: input.to
|
|
136
|
+
}));
|
|
137
|
+
}
|
|
128
138
|
function selectProxies(nodes, query = {}) {
|
|
129
139
|
inspect({
|
|
130
140
|
nodes,
|
|
@@ -209,17 +219,13 @@ function defineSurgeProfile(input) {
|
|
|
209
219
|
...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
|
|
210
220
|
};
|
|
211
221
|
});
|
|
212
|
-
const ids = /* @__PURE__ */ new Set();
|
|
213
222
|
const rules = input.routes.map((definition) => {
|
|
214
223
|
exact(definition, [
|
|
215
224
|
"type",
|
|
216
|
-
"id",
|
|
217
225
|
"when",
|
|
218
226
|
"to"
|
|
219
227
|
]);
|
|
220
228
|
if (definition.type !== "route") fail("INVALID_ROUTE_DEFINITION");
|
|
221
|
-
if (ids.has(definition.id)) fail("DUPLICATE_ROUTE_ID");
|
|
222
|
-
ids.add(definition.id);
|
|
223
229
|
return {
|
|
224
230
|
when: definition.when,
|
|
225
231
|
then: lower(definition.to)
|
|
@@ -238,7 +244,7 @@ function condition(value) {
|
|
|
238
244
|
inspect(value);
|
|
239
245
|
return value;
|
|
240
246
|
}
|
|
241
|
-
function atom$
|
|
247
|
+
function atom$2(type) {
|
|
242
248
|
return (value, options = {}) => {
|
|
243
249
|
inspect(options);
|
|
244
250
|
return condition({
|
|
@@ -249,13 +255,13 @@ function atom$1(type) {
|
|
|
249
255
|
};
|
|
250
256
|
}
|
|
251
257
|
const surgeMatch = {
|
|
252
|
-
domain: atom$
|
|
253
|
-
domainSuffix: atom$
|
|
254
|
-
ipCidr: atom$
|
|
255
|
-
ipCidr6: atom$
|
|
256
|
-
sourceIp: atom$
|
|
257
|
-
processName: atom$
|
|
258
|
-
macAddress: atom$
|
|
258
|
+
domain: atom$2("domain"),
|
|
259
|
+
domainSuffix: atom$2("domainSuffix"),
|
|
260
|
+
ipCidr: atom$2("ipCidr"),
|
|
261
|
+
ipCidr6: atom$2("ipCidr6"),
|
|
262
|
+
sourceIp: atom$2("sourceIp"),
|
|
263
|
+
processName: atom$2("processName"),
|
|
264
|
+
macAddress: atom$2("macAddress"),
|
|
259
265
|
network: (value, options = {}) => {
|
|
260
266
|
inspect(options);
|
|
261
267
|
return condition({
|
|
@@ -326,9 +332,9 @@ const surgeMatch = {
|
|
|
326
332
|
//#endregion
|
|
327
333
|
//#region src/schema.ts
|
|
328
334
|
const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
|
|
329
|
-
const domain = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/);
|
|
330
|
-
const ip = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
|
|
331
|
-
const cidr = z.string().refine((x) => {
|
|
335
|
+
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])?$/);
|
|
336
|
+
const ip$1 = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
|
|
337
|
+
const cidr$1 = z.string().refine((x) => {
|
|
332
338
|
try {
|
|
333
339
|
const [address, prefix] = x.split("/");
|
|
334
340
|
if (!address || !prefix || !/^\d+$/.test(prefix) || isIP(address) === 0 || address.includes("%")) return false;
|
|
@@ -338,9 +344,9 @@ const cidr = z.string().refine((x) => {
|
|
|
338
344
|
return false;
|
|
339
345
|
}
|
|
340
346
|
});
|
|
341
|
-
const port = z.number().int().min(1).max(65535);
|
|
347
|
+
const port$1 = z.number().int().min(1).max(65535);
|
|
342
348
|
const network = z.enum(["tcp", "udp"]);
|
|
343
|
-
const atom = (type, value) => z.strictObject({
|
|
349
|
+
const atom$1 = (type, value) => z.strictObject({
|
|
344
350
|
type: z.literal(type),
|
|
345
351
|
value
|
|
346
352
|
});
|
|
@@ -389,19 +395,19 @@ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
|
|
|
389
395
|
id: idSchema,
|
|
390
396
|
when: matchSchema
|
|
391
397
|
}),
|
|
392
|
-
atom("domain", domain),
|
|
393
|
-
atom("domainSuffix", domain),
|
|
394
|
-
atom("ipCidr", cidr),
|
|
395
|
-
atom("sourceIp", cidr),
|
|
398
|
+
atom$1("domain", domain$1),
|
|
399
|
+
atom$1("domainSuffix", domain$1),
|
|
400
|
+
atom$1("ipCidr", cidr$1),
|
|
401
|
+
atom$1("sourceIp", cidr$1),
|
|
396
402
|
z.strictObject({
|
|
397
403
|
type: z.literal("port"),
|
|
398
|
-
from: port,
|
|
399
|
-
to: port
|
|
404
|
+
from: port$1,
|
|
405
|
+
to: port$1
|
|
400
406
|
}).refine((v) => v.from <= v.to),
|
|
401
407
|
z.strictObject({
|
|
402
408
|
type: z.literal("sourcePort"),
|
|
403
|
-
from: port,
|
|
404
|
-
to: port
|
|
409
|
+
from: port$1,
|
|
410
|
+
to: port$1
|
|
405
411
|
}).refine((v) => v.from <= v.to),
|
|
406
412
|
z.strictObject({
|
|
407
413
|
type: z.literal("network"),
|
|
@@ -458,8 +464,8 @@ const secretSchema = z.strictObject({
|
|
|
458
464
|
});
|
|
459
465
|
const nodeBase = {
|
|
460
466
|
id: idSchema,
|
|
461
|
-
server: z.union([ip, domain]),
|
|
462
|
-
port,
|
|
467
|
+
server: z.union([ip$1, domain$1]),
|
|
468
|
+
port: port$1,
|
|
463
469
|
via: idSchema.optional(),
|
|
464
470
|
tcpFastOpen: z.boolean().optional(),
|
|
465
471
|
label: z.string().min(1).max(256).optional(),
|
|
@@ -468,14 +474,14 @@ const nodeBase = {
|
|
|
468
474
|
tags: z.array(idSchema).refine(unique).optional()
|
|
469
475
|
};
|
|
470
476
|
const tlsSchema = z.strictObject({
|
|
471
|
-
serverName: domain,
|
|
477
|
+
serverName: domain$1,
|
|
472
478
|
skipCertVerify: z.boolean().optional(),
|
|
473
479
|
alpn: z.array(z.string().min(1).refine((x) => !/\p{C}/u.test(x) && Buffer.byteLength(x) <= 255)).min(1).refine(unique).optional()
|
|
474
480
|
});
|
|
475
481
|
const transportSchema = z.strictObject({
|
|
476
482
|
type: z.literal("ws"),
|
|
477
483
|
path: z.string().max(2048).regex(/^\/[A-Za-z0-9/._~-]*$/).refine((x) => !x.startsWith("//")),
|
|
478
|
-
host: domain.optional()
|
|
484
|
+
host: domain$1.optional()
|
|
479
485
|
});
|
|
480
486
|
const uuidNode = {
|
|
481
487
|
...nodeBase,
|
|
@@ -493,7 +499,7 @@ const nodeSchema = z.discriminatedUnion("type", [
|
|
|
493
499
|
...nodeBase,
|
|
494
500
|
type: z.literal("trojan"),
|
|
495
501
|
password: secretSchema,
|
|
496
|
-
serverName: domain.optional(),
|
|
502
|
+
serverName: domain$1.optional(),
|
|
497
503
|
skipCertVerify: z.boolean().optional(),
|
|
498
504
|
surge: z.strictObject({
|
|
499
505
|
...surgeOptions,
|
|
@@ -504,7 +510,7 @@ const nodeSchema = z.discriminatedUnion("type", [
|
|
|
504
510
|
...nodeBase,
|
|
505
511
|
type: z.literal("anytls"),
|
|
506
512
|
password: secretSchema,
|
|
507
|
-
serverName: domain.optional(),
|
|
513
|
+
serverName: domain$1.optional(),
|
|
508
514
|
skipCertVerify: z.boolean().optional(),
|
|
509
515
|
surge: z.strictObject({
|
|
510
516
|
...surgeOptions,
|
|
@@ -545,16 +551,16 @@ const nodeSchema = z.discriminatedUnion("type", [
|
|
|
545
551
|
const endpointSchema = z.strictObject({
|
|
546
552
|
type: z.literal("sing-box-tailscale"),
|
|
547
553
|
id: idSchema,
|
|
548
|
-
hostname: domain.refine((x) => !x.includes(".")),
|
|
554
|
+
hostname: domain$1.refine((x) => !x.includes(".")),
|
|
549
555
|
stateDirectory: z.string().max(4096).refine((x) => x.startsWith("/") && !/[\p{C}$\\]/u.test(x) && x.split("/").slice(1).every((part) => part !== "" && part !== "." && part !== "..")),
|
|
550
556
|
acceptRoutes: z.boolean(),
|
|
551
|
-
bootstrapResolver: ip,
|
|
557
|
+
bootstrapResolver: ip$1,
|
|
552
558
|
authKey: secretSchema.optional(),
|
|
553
|
-
exitNode: ip.optional(),
|
|
559
|
+
exitNode: ip$1.optional(),
|
|
554
560
|
exitNodeAllowLanAccess: z.boolean().optional()
|
|
555
561
|
}).refine((endpoint) => endpoint.exitNodeAllowLanAccess === void 0 || endpoint.exitNode !== void 0);
|
|
556
562
|
const members = z.array(idSchema).min(1).refine(unique);
|
|
557
|
-
const url = z.string().url().refine((value) => {
|
|
563
|
+
const url$1 = z.string().url().refine((value) => {
|
|
558
564
|
try {
|
|
559
565
|
const u = new URL(value);
|
|
560
566
|
return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password && !u.hash;
|
|
@@ -564,7 +570,7 @@ const url = z.string().url().refine((value) => {
|
|
|
564
570
|
});
|
|
565
571
|
const urltestAlgorithmSchema = z.strictObject({
|
|
566
572
|
type: z.literal("urltest"),
|
|
567
|
-
url,
|
|
573
|
+
url: url$1,
|
|
568
574
|
intervalSeconds: z.number().int().min(1).max(86400).default(180),
|
|
569
575
|
toleranceMs: z.number().int().min(0).max(6e4).default(50)
|
|
570
576
|
});
|
|
@@ -589,7 +595,7 @@ const strategySchema = z.union([z.strictObject({
|
|
|
589
595
|
...strategyBase,
|
|
590
596
|
implementations: implementationsSchema.refine((v) => !!v.surge || !!v["sing-box"] || !!v.mihomo || !!v.stash)
|
|
591
597
|
})]);
|
|
592
|
-
const groupSchema = z.union([
|
|
598
|
+
const groupSchema$1 = z.union([
|
|
593
599
|
strategySchema,
|
|
594
600
|
z.strictObject({
|
|
595
601
|
type: z.enum(["select", "smart"]),
|
|
@@ -600,18 +606,18 @@ const groupSchema = z.union([
|
|
|
600
606
|
type: z.literal("urltest"),
|
|
601
607
|
id: idSchema,
|
|
602
608
|
members,
|
|
603
|
-
url,
|
|
609
|
+
url: url$1,
|
|
604
610
|
intervalSeconds: z.number().int().min(1).max(86400).default(180),
|
|
605
611
|
toleranceMs: z.number().int().min(0).max(6e4).default(50)
|
|
606
612
|
})
|
|
607
613
|
]);
|
|
608
614
|
const requestSchema = z.strictObject({
|
|
609
615
|
network,
|
|
610
|
-
domain: domain.optional(),
|
|
611
|
-
ip: ip.optional(),
|
|
612
|
-
sourceIp: ip.optional(),
|
|
613
|
-
port: port.optional(),
|
|
614
|
-
sourcePort: port.optional()
|
|
616
|
+
domain: domain$1.optional(),
|
|
617
|
+
ip: ip$1.optional(),
|
|
618
|
+
sourceIp: ip$1.optional(),
|
|
619
|
+
port: port$1.optional(),
|
|
620
|
+
sourcePort: port$1.optional()
|
|
615
621
|
});
|
|
616
622
|
const configSchema = z.strictObject({
|
|
617
623
|
programs: z.record(idSchema, z.strictObject({
|
|
@@ -623,12 +629,12 @@ const configSchema = z.strictObject({
|
|
|
623
629
|
]),
|
|
624
630
|
nodes: z.array(nodeSchema),
|
|
625
631
|
endpoints: z.array(endpointSchema).max(1e3).optional(),
|
|
626
|
-
groups: z.array(groupSchema),
|
|
632
|
+
groups: z.array(groupSchema$1),
|
|
627
633
|
routing: z.array(entrySchema),
|
|
628
634
|
fallback: actionSchema,
|
|
629
635
|
listener: z.strictObject({
|
|
630
|
-
port,
|
|
631
|
-
resolver: ip
|
|
636
|
+
port: port$1,
|
|
637
|
+
resolver: ip$1
|
|
632
638
|
}).optional()
|
|
633
639
|
})),
|
|
634
640
|
targets: z.array(z.strictObject({
|
|
@@ -792,7 +798,7 @@ const block = (id, rules, when) => ({
|
|
|
792
798
|
rules,
|
|
793
799
|
...when ? { when } : {}
|
|
794
800
|
});
|
|
795
|
-
const policy$
|
|
801
|
+
const policy$2 = (definition) => ({
|
|
796
802
|
type: "policy",
|
|
797
803
|
...definition
|
|
798
804
|
});
|
|
@@ -1384,13 +1390,13 @@ function clashGroup(group, name = (id) => id) {
|
|
|
1384
1390
|
} : {}
|
|
1385
1391
|
};
|
|
1386
1392
|
}
|
|
1387
|
-
function conditionText(condition) {
|
|
1393
|
+
function conditionText$1(condition) {
|
|
1388
1394
|
switch (condition.type) {
|
|
1389
|
-
case "ruleSet": return conditionText(condition.when);
|
|
1395
|
+
case "ruleSet": return conditionText$1(condition.when);
|
|
1390
1396
|
case "nativeRuleSet": return `RULE-SET,${condition.id}`;
|
|
1391
1397
|
case "all":
|
|
1392
|
-
case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${conditionText(c)})`).join(",")})`;
|
|
1393
|
-
case "not": return `NOT,((${conditionText(condition.condition)}))`;
|
|
1398
|
+
case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${conditionText$1(c)})`).join(",")})`;
|
|
1399
|
+
case "not": return `NOT,((${conditionText$1(condition.condition)}))`;
|
|
1394
1400
|
case "domain": return `DOMAIN,${condition.value}`;
|
|
1395
1401
|
case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
|
|
1396
1402
|
case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
|
|
@@ -1400,13 +1406,13 @@ function conditionText(condition) {
|
|
|
1400
1406
|
case "sourcePort": return `${condition.type === "port" ? "DST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
|
|
1401
1407
|
}
|
|
1402
1408
|
}
|
|
1403
|
-
const policy = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
|
|
1409
|
+
const policy$1 = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
|
|
1404
1410
|
function clashConfig(plan, secret) {
|
|
1405
1411
|
const { program, target } = plan;
|
|
1406
1412
|
const config = {
|
|
1407
1413
|
proxies: program.nodes.map((node) => clashProxy(node, target.engine, secret)),
|
|
1408
1414
|
"proxy-groups": program.groups.map((g) => clashGroup(g)),
|
|
1409
|
-
rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText(rule.when).replace(/,no-resolve$/, "")},${policy(rule.then)},no-resolve` : `${conditionText(rule.when)},${policy(rule.then)}`), `MATCH,${policy(program.fallback)}`]
|
|
1415
|
+
rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText$1(rule.when).replace(/,no-resolve$/, "")},${policy$1(rule.then)},no-resolve` : `${conditionText$1(rule.when)},${policy$1(rule.then)}`), `MATCH,${policy$1(program.fallback)}`]
|
|
1410
1416
|
};
|
|
1411
1417
|
if (plan.nativeRuleSets.length) config["rule-providers"] = Object.fromEntries(plan.nativeRuleSets.map((r) => [r.id, {
|
|
1412
1418
|
type: "http",
|
|
@@ -1654,7 +1660,7 @@ function singboxGroup(group, name = (id) => id) {
|
|
|
1654
1660
|
interrupt_exist_connections: false
|
|
1655
1661
|
};
|
|
1656
1662
|
}
|
|
1657
|
-
const inputSchema = z.strictObject({
|
|
1663
|
+
const inputSchema$1 = z.strictObject({
|
|
1658
1664
|
target: z.strictObject({
|
|
1659
1665
|
engine: z.enum([
|
|
1660
1666
|
"surge",
|
|
@@ -1694,7 +1700,7 @@ function compileStrategyGroups(input) {
|
|
|
1694
1700
|
error("INVALID_INPUT_GRAPH", "$", "输入不是有限的声明数据");
|
|
1695
1701
|
return failure();
|
|
1696
1702
|
}
|
|
1697
|
-
const parsed = inputSchema.safeParse(input);
|
|
1703
|
+
const parsed = inputSchema$1.safeParse(input);
|
|
1698
1704
|
if (!parsed.success) {
|
|
1699
1705
|
error("INVALID_SCHEMA", "$", "策略目录、名字或目标不符合严格 schema");
|
|
1700
1706
|
return failure();
|
|
@@ -2319,4 +2325,676 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
2319
2325
|
};
|
|
2320
2326
|
}
|
|
2321
2327
|
//#endregion
|
|
2322
|
-
|
|
2328
|
+
//#region src/surge-profile.ts
|
|
2329
|
+
const builtin = z.enum([
|
|
2330
|
+
"DIRECT",
|
|
2331
|
+
"REJECT",
|
|
2332
|
+
"REJECT-DROP",
|
|
2333
|
+
"REJECT-NO-DROP",
|
|
2334
|
+
"REJECT-TINYGIF"
|
|
2335
|
+
]);
|
|
2336
|
+
const policy = z.union([z.strictObject({ ref: idSchema }), z.strictObject({ builtin })]);
|
|
2337
|
+
const token = z.strictObject({
|
|
2338
|
+
type: z.literal("env"),
|
|
2339
|
+
name: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)
|
|
2340
|
+
});
|
|
2341
|
+
const safe = z.string().min(1).max(4096).refine((v) => v.trim() === v && !/[\p{C}\p{Zl}\p{Zp},=()#;"'\\]/u.test(v));
|
|
2342
|
+
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])?$/);
|
|
2343
|
+
const hostPattern = safe.refine((v) => /^[a-zA-Z0-9*?._-]+$/.test(v));
|
|
2344
|
+
const ip = safe.refine((v) => isIP(v) !== 0 && !v.includes("%"));
|
|
2345
|
+
const cidr = (version) => safe.refine((v) => {
|
|
2346
|
+
try {
|
|
2347
|
+
const [address] = ipaddr.parseCIDR(v);
|
|
2348
|
+
return (!version || (address.kind() === "ipv4" ? 4 : 6) === version) && !v.includes("%");
|
|
2349
|
+
} catch {
|
|
2350
|
+
return false;
|
|
2351
|
+
}
|
|
2352
|
+
});
|
|
2353
|
+
const port = z.number().int().min(1).max(65535);
|
|
2354
|
+
function addressPort(value, allowHost, portRequired) {
|
|
2355
|
+
if (!portRequired && isIP(value)) return true;
|
|
2356
|
+
const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(value);
|
|
2357
|
+
if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) return false;
|
|
2358
|
+
const host = match[1];
|
|
2359
|
+
return host.startsWith("[") ? isIP(host.slice(1, -1)) === 6 : isIP(host) === 4 || allowHost && domain.safeParse(host).success;
|
|
2360
|
+
}
|
|
2361
|
+
const listener = safe.refine((v) => addressPort(v, false, false));
|
|
2362
|
+
const endpoint = safe.refine((v) => addressPort(v, true, true));
|
|
2363
|
+
const dns = safe.refine((v) => v === "system" || addressPort(v, false, false));
|
|
2364
|
+
const url = z.string().min(1).max(4096).refine((v) => {
|
|
2365
|
+
try {
|
|
2366
|
+
const u = new URL(v);
|
|
2367
|
+
return /^https?:\/\//.test(v) && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
|
|
2368
|
+
} catch {
|
|
2369
|
+
return false;
|
|
2370
|
+
}
|
|
2371
|
+
});
|
|
2372
|
+
const encryptedDns = z.string().max(4096).refine((v) => {
|
|
2373
|
+
try {
|
|
2374
|
+
const u = new URL(v);
|
|
2375
|
+
return [
|
|
2376
|
+
"https:",
|
|
2377
|
+
"h3:",
|
|
2378
|
+
"quic:",
|
|
2379
|
+
"tls:",
|
|
2380
|
+
"tcp:"
|
|
2381
|
+
].includes(u.protocol) && !!u.hostname && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
|
|
2382
|
+
} catch {
|
|
2383
|
+
return false;
|
|
2384
|
+
}
|
|
2385
|
+
});
|
|
2386
|
+
const list = (item) => z.array(item).min(1).max(1e3);
|
|
2387
|
+
const control = z.strictObject({
|
|
2388
|
+
password: token,
|
|
2389
|
+
listen: safe.refine((v) => addressPort(v, false, true))
|
|
2390
|
+
});
|
|
2391
|
+
const generalSchema = z.strictObject({
|
|
2392
|
+
loglevel: z.enum([
|
|
2393
|
+
"verbose",
|
|
2394
|
+
"info",
|
|
2395
|
+
"notify",
|
|
2396
|
+
"warning"
|
|
2397
|
+
]).optional(),
|
|
2398
|
+
"dns-server": list(dns).optional(),
|
|
2399
|
+
"encrypted-dns-server": list(encryptedDns).optional(),
|
|
2400
|
+
"show-error-page-for-reject": z.boolean().optional(),
|
|
2401
|
+
"exclude-simple-hostnames": z.boolean().optional(),
|
|
2402
|
+
"internet-test-url": url.optional(),
|
|
2403
|
+
"skip-proxy": list(z.union([
|
|
2404
|
+
hostPattern,
|
|
2405
|
+
ip,
|
|
2406
|
+
cidr()
|
|
2407
|
+
])).optional(),
|
|
2408
|
+
ipv6: z.boolean().optional(),
|
|
2409
|
+
"ipv6-vif": z.enum([
|
|
2410
|
+
"auto",
|
|
2411
|
+
"always",
|
|
2412
|
+
"disabled"
|
|
2413
|
+
]).optional(),
|
|
2414
|
+
"bypass-system": z.boolean().optional(),
|
|
2415
|
+
replica: z.boolean().optional(),
|
|
2416
|
+
"tls-provider": z.enum(["default", "openssl"]).optional(),
|
|
2417
|
+
"bypass-tun": list(cidr()).optional(),
|
|
2418
|
+
"always-real-ip": list(hostPattern).optional(),
|
|
2419
|
+
"http-api": control.optional(),
|
|
2420
|
+
"http-api-web-dashboard": z.boolean().optional(),
|
|
2421
|
+
"external-controller-access": control.optional(),
|
|
2422
|
+
"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(),
|
|
2423
|
+
"http-listen": listener.optional(),
|
|
2424
|
+
"socks5-listen": listener.optional(),
|
|
2425
|
+
"proxy-restricted-to-lan": z.boolean().optional()
|
|
2426
|
+
});
|
|
2427
|
+
const hostSchema = z.strictObject({
|
|
2428
|
+
pattern: hostPattern,
|
|
2429
|
+
address: z.union([ip, domain]).optional(),
|
|
2430
|
+
server: z.union([dns, encryptedDns]).optional()
|
|
2431
|
+
}).refine((v) => v.address !== void 0 || v.server !== void 0);
|
|
2432
|
+
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);
|
|
2433
|
+
const sectionName = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/);
|
|
2434
|
+
const tunnelSchema = z.discriminatedUnion("type", [z.strictObject({
|
|
2435
|
+
type: z.literal("tailscale"),
|
|
2436
|
+
id: idSchema,
|
|
2437
|
+
sectionName,
|
|
2438
|
+
authKey: token,
|
|
2439
|
+
hostname: domain,
|
|
2440
|
+
dnsServer: list(dns).optional(),
|
|
2441
|
+
autoAddMagicDnsRule: z.boolean().optional(),
|
|
2442
|
+
idleKeepalive: z.number().int().min(-1).max(2147483647).optional()
|
|
2443
|
+
}), z.strictObject({
|
|
2444
|
+
type: z.literal("wireguard"),
|
|
2445
|
+
id: idSchema,
|
|
2446
|
+
sectionName,
|
|
2447
|
+
privateKey: token,
|
|
2448
|
+
selfIp: ip.refine((v) => isIP(v) === 4),
|
|
2449
|
+
dnsServer: list(dns).optional(),
|
|
2450
|
+
mtu: z.number().int().min(576).max(9e3).optional(),
|
|
2451
|
+
peers: list(z.strictObject({
|
|
2452
|
+
publicKey: key,
|
|
2453
|
+
endpoint,
|
|
2454
|
+
allowedIps: list(cidr()),
|
|
2455
|
+
presharedKey: token.optional(),
|
|
2456
|
+
persistentKeepalive: z.number().int().min(0).max(65535).optional()
|
|
2457
|
+
}))
|
|
2458
|
+
})]);
|
|
2459
|
+
const groupSchema = z.strictObject({
|
|
2460
|
+
id: idSchema,
|
|
2461
|
+
type: z.enum(["select", "smart"]),
|
|
2462
|
+
members: list(policy),
|
|
2463
|
+
url: url.optional(),
|
|
2464
|
+
intervalSeconds: z.number().int().positive().max(2147483647).optional(),
|
|
2465
|
+
timeoutSeconds: z.number().int().positive().max(3600).optional()
|
|
2466
|
+
});
|
|
2467
|
+
const options = {
|
|
2468
|
+
noResolve: z.boolean().optional(),
|
|
2469
|
+
extendedMatching: z.boolean().optional()
|
|
2470
|
+
};
|
|
2471
|
+
const atom = (type, value) => z.strictObject({
|
|
2472
|
+
type: z.literal(type),
|
|
2473
|
+
value,
|
|
2474
|
+
...options
|
|
2475
|
+
});
|
|
2476
|
+
const conditionSchema = z.lazy(() => z.union([
|
|
2477
|
+
atom("domain", domain),
|
|
2478
|
+
atom("domainSuffix", domain),
|
|
2479
|
+
atom("ipCidr", cidr(4)),
|
|
2480
|
+
atom("ipCidr6", cidr(6)),
|
|
2481
|
+
atom("sourceIp", z.union([ip, cidr()])),
|
|
2482
|
+
atom("processName", safe),
|
|
2483
|
+
atom("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
|
|
2484
|
+
z.strictObject({
|
|
2485
|
+
type: z.enum(["port", "sourcePort"]),
|
|
2486
|
+
from: port,
|
|
2487
|
+
to: port.optional(),
|
|
2488
|
+
...options
|
|
2489
|
+
}).refine((v) => v.to === void 0 || v.to >= v.from),
|
|
2490
|
+
z.strictObject({
|
|
2491
|
+
type: z.literal("network"),
|
|
2492
|
+
value: z.enum(["tcp", "udp"]),
|
|
2493
|
+
...options
|
|
2494
|
+
}),
|
|
2495
|
+
z.strictObject({
|
|
2496
|
+
type: z.enum(["all", "any"]),
|
|
2497
|
+
conditions: z.array(conditionSchema).min(2).max(100),
|
|
2498
|
+
...options
|
|
2499
|
+
}),
|
|
2500
|
+
z.strictObject({
|
|
2501
|
+
type: z.literal("not"),
|
|
2502
|
+
condition: conditionSchema,
|
|
2503
|
+
...options
|
|
2504
|
+
}),
|
|
2505
|
+
z.strictObject({
|
|
2506
|
+
type: z.literal("ruleSet"),
|
|
2507
|
+
format: z.enum(["rule-set", "domain-set"]),
|
|
2508
|
+
url: url.optional(),
|
|
2509
|
+
builtin: z.enum(["LAN", "SYSTEM"]).optional(),
|
|
2510
|
+
...options
|
|
2511
|
+
}).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
|
|
2512
|
+
]));
|
|
2513
|
+
const managedSchema = z.strictObject({
|
|
2514
|
+
url: url.refine((v) => !new URL(v).search && !v.includes("?")),
|
|
2515
|
+
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(),
|
|
2516
|
+
intervalSeconds: z.number().int().min(60).max(2147483647),
|
|
2517
|
+
strict: z.boolean()
|
|
2518
|
+
});
|
|
2519
|
+
const inputSchema = z.strictObject({
|
|
2520
|
+
target: z.strictObject({
|
|
2521
|
+
engine: z.literal("surge"),
|
|
2522
|
+
platform: z.enum(["macos", "ios"]),
|
|
2523
|
+
version: z.string()
|
|
2524
|
+
}),
|
|
2525
|
+
managed: managedSchema.optional(),
|
|
2526
|
+
general: generalSchema.optional(),
|
|
2527
|
+
hosts: z.array(hostSchema).max(2e3).optional(),
|
|
2528
|
+
nodes: z.array(nodeSchema).max(1e3),
|
|
2529
|
+
tunnels: z.array(tunnelSchema).max(1e3).optional(),
|
|
2530
|
+
groups: z.array(groupSchema).max(1e3),
|
|
2531
|
+
rules: z.array(z.strictObject({
|
|
2532
|
+
when: conditionSchema,
|
|
2533
|
+
then: policy
|
|
2534
|
+
})).max(1e4),
|
|
2535
|
+
fallback: policy,
|
|
2536
|
+
names: z.record(idSchema, nativeNameSchema).optional()
|
|
2537
|
+
});
|
|
2538
|
+
const plans = /* @__PURE__ */ new WeakMap();
|
|
2539
|
+
function compileSurgeProfile(input) {
|
|
2540
|
+
const diagnostics = [];
|
|
2541
|
+
const error = (code) => diagnostics.push({
|
|
2542
|
+
severity: "error",
|
|
2543
|
+
code,
|
|
2544
|
+
path: "$",
|
|
2545
|
+
message: code
|
|
2546
|
+
});
|
|
2547
|
+
const failure = () => deepFreeze({
|
|
2548
|
+
ok: false,
|
|
2549
|
+
artifactKind: "surge-profile",
|
|
2550
|
+
diagnostics,
|
|
2551
|
+
bindings: []
|
|
2552
|
+
});
|
|
2553
|
+
try {
|
|
2554
|
+
assertData(input);
|
|
2555
|
+
} catch {
|
|
2556
|
+
error("INVALID_INPUT_GRAPH");
|
|
2557
|
+
return failure();
|
|
2558
|
+
}
|
|
2559
|
+
const parsed = inputSchema.safeParse(input);
|
|
2560
|
+
if (!parsed.success) {
|
|
2561
|
+
error("INVALID_SCHEMA");
|
|
2562
|
+
return failure();
|
|
2563
|
+
}
|
|
2564
|
+
if (parsed.data.general) {
|
|
2565
|
+
const general = parsed.data.general;
|
|
2566
|
+
parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
|
|
2567
|
+
}
|
|
2568
|
+
const p = deepFreeze(parsed.data);
|
|
2569
|
+
if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
|
|
2570
|
+
const tunnels = p.tunnels ?? [];
|
|
2571
|
+
const resources = [
|
|
2572
|
+
...p.nodes,
|
|
2573
|
+
...tunnels,
|
|
2574
|
+
...p.groups
|
|
2575
|
+
];
|
|
2576
|
+
if (resources.length > 1e3) error("RESOURCE_LIMIT");
|
|
2577
|
+
const ids = new Set(resources.map((r) => r.id));
|
|
2578
|
+
if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
|
|
2579
|
+
if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
|
|
2580
|
+
const bindings = resources.map((r) => ({
|
|
2581
|
+
id: r.id,
|
|
2582
|
+
nativeName: p.names?.[r.id] ?? r.id
|
|
2583
|
+
}));
|
|
2584
|
+
if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
|
|
2585
|
+
if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
|
|
2586
|
+
if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
|
|
2587
|
+
if (p.target.platform === "ios" && [
|
|
2588
|
+
"bypass-system",
|
|
2589
|
+
"replica",
|
|
2590
|
+
"tls-provider",
|
|
2591
|
+
"bypass-tun",
|
|
2592
|
+
"external-controller-access"
|
|
2593
|
+
].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
|
|
2594
|
+
if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
|
|
2595
|
+
const checkPolicy = (action) => {
|
|
2596
|
+
if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
|
|
2597
|
+
};
|
|
2598
|
+
const edges = new Map(resources.map((r) => [r.id, []]));
|
|
2599
|
+
const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
|
|
2600
|
+
for (const node of p.nodes) {
|
|
2601
|
+
if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
|
|
2602
|
+
validateProxyOptions(node, {
|
|
2603
|
+
id: "profile",
|
|
2604
|
+
engine: "surge"
|
|
2605
|
+
}, diagnostics);
|
|
2606
|
+
if (node.via) {
|
|
2607
|
+
checkPolicy({ ref: node.via });
|
|
2608
|
+
edges.get(node.id).push(node.via);
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
for (const group of p.groups) {
|
|
2612
|
+
if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
|
|
2613
|
+
for (const member of group.members) {
|
|
2614
|
+
checkPolicy(member);
|
|
2615
|
+
if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
|
|
2616
|
+
if ("ref" in member) edges.get(group.id).push(member.ref);
|
|
2617
|
+
}
|
|
2618
|
+
}
|
|
2619
|
+
const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
|
|
2620
|
+
const visit = (id) => {
|
|
2621
|
+
if (active.has(id)) {
|
|
2622
|
+
error("RESOURCE_CYCLE");
|
|
2623
|
+
return;
|
|
2624
|
+
}
|
|
2625
|
+
if (visited.has(id)) return;
|
|
2626
|
+
active.add(id);
|
|
2627
|
+
for (const next of edges.get(id) ?? []) visit(next);
|
|
2628
|
+
active.delete(id);
|
|
2629
|
+
visited.add(id);
|
|
2630
|
+
};
|
|
2631
|
+
if (resources.length <= 1e3) for (const id of ids) visit(id);
|
|
2632
|
+
const formats = /* @__PURE__ */ new Map();
|
|
2633
|
+
const checkCondition = (c, depth) => {
|
|
2634
|
+
if (depth > 10) {
|
|
2635
|
+
error("LOGICAL_DEPTH_EXCEEDED");
|
|
2636
|
+
return;
|
|
2637
|
+
}
|
|
2638
|
+
if (c.noResolve !== void 0 && ![
|
|
2639
|
+
"ipCidr",
|
|
2640
|
+
"ipCidr6",
|
|
2641
|
+
"ruleSet"
|
|
2642
|
+
].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
|
|
2643
|
+
if (c.extendedMatching !== void 0 && ![
|
|
2644
|
+
"domain",
|
|
2645
|
+
"domainSuffix",
|
|
2646
|
+
"ruleSet"
|
|
2647
|
+
].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
|
|
2648
|
+
if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
|
|
2649
|
+
if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
|
|
2650
|
+
if (c.type === "not") checkCondition(c.condition, depth + 1);
|
|
2651
|
+
if (c.type === "ruleSet") {
|
|
2652
|
+
if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
|
|
2653
|
+
if (c.url) {
|
|
2654
|
+
if (formats.has(c.url) && formats.get(c.url) !== c.format) error("RULESET_FORMAT_CONFLICT");
|
|
2655
|
+
formats.set(c.url, c.format);
|
|
2656
|
+
}
|
|
2657
|
+
}
|
|
2658
|
+
};
|
|
2659
|
+
for (const rule of p.rules) {
|
|
2660
|
+
checkPolicy(rule.then);
|
|
2661
|
+
checkCondition(rule.when, 0);
|
|
2662
|
+
}
|
|
2663
|
+
checkPolicy(p.fallback);
|
|
2664
|
+
if (diagnostics.some((d) => d.severity === "error")) return failure();
|
|
2665
|
+
if (formats.size) diagnostics.push({
|
|
2666
|
+
severity: "warning",
|
|
2667
|
+
code: "EXTERNAL_RULESET_UNVERIFIED",
|
|
2668
|
+
path: "rules",
|
|
2669
|
+
message: "External rule sets are resolved by the client, not by the compiler."
|
|
2670
|
+
});
|
|
2671
|
+
const result = deepFreeze({
|
|
2672
|
+
ok: true,
|
|
2673
|
+
artifactKind: "surge-profile",
|
|
2674
|
+
diagnostics,
|
|
2675
|
+
bindings
|
|
2676
|
+
});
|
|
2677
|
+
plans.set(result, p);
|
|
2678
|
+
return result;
|
|
2679
|
+
}
|
|
2680
|
+
function conditionOptions(c) {
|
|
2681
|
+
return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
|
|
2682
|
+
}
|
|
2683
|
+
function conditionText(c) {
|
|
2684
|
+
switch (c.type) {
|
|
2685
|
+
case "all":
|
|
2686
|
+
case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
|
|
2687
|
+
case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
|
|
2688
|
+
case "port":
|
|
2689
|
+
case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
|
|
2690
|
+
case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
|
|
2691
|
+
case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
|
|
2692
|
+
default: return `${{
|
|
2693
|
+
domain: "DOMAIN",
|
|
2694
|
+
domainSuffix: "DOMAIN-SUFFIX",
|
|
2695
|
+
ipCidr: "IP-CIDR",
|
|
2696
|
+
ipCidr6: "IP-CIDR6",
|
|
2697
|
+
sourceIp: "SRC-IP",
|
|
2698
|
+
processName: "PROCESS-NAME",
|
|
2699
|
+
macAddress: "MAC-ADDRESS"
|
|
2700
|
+
}[c.type]},${c.value}`;
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
function renderProfile(compilation, read) {
|
|
2704
|
+
const p = plans.get(compilation);
|
|
2705
|
+
if (!p) throw new RenderError("COMPILATION_FAILED");
|
|
2706
|
+
const name = (id) => p.names?.[id] ?? id;
|
|
2707
|
+
const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
|
|
2708
|
+
const credential = (token, kind) => {
|
|
2709
|
+
const value = read(token);
|
|
2710
|
+
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");
|
|
2711
|
+
return value;
|
|
2712
|
+
};
|
|
2713
|
+
const lines = [];
|
|
2714
|
+
if (p.managed) {
|
|
2715
|
+
const address = new URL(p.managed.url);
|
|
2716
|
+
for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
|
|
2717
|
+
lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
|
|
2718
|
+
}
|
|
2719
|
+
lines.push("[General]");
|
|
2720
|
+
for (const [k, v] of Object.entries(p.general ?? {})) {
|
|
2721
|
+
const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
|
|
2722
|
+
lines.push(`${k} = ${value}`);
|
|
2723
|
+
}
|
|
2724
|
+
lines.push("", "[Host]");
|
|
2725
|
+
for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
|
|
2726
|
+
lines.push("", "[Proxy]");
|
|
2727
|
+
for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
|
|
2728
|
+
for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
|
|
2729
|
+
for (const t of p.tunnels ?? []) {
|
|
2730
|
+
lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
|
|
2731
|
+
if (t.type === "tailscale") {
|
|
2732
|
+
lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
|
|
2733
|
+
if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
|
|
2734
|
+
if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
|
|
2735
|
+
if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
|
|
2736
|
+
} else {
|
|
2737
|
+
lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
|
|
2738
|
+
if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
|
|
2739
|
+
if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
|
|
2740
|
+
for (const peer of t.peers) {
|
|
2741
|
+
const values = [`public-key = ${peer.publicKey}`];
|
|
2742
|
+
if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
|
|
2743
|
+
values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
|
|
2744
|
+
if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
|
|
2745
|
+
lines.push(`peer = (${values.join(", ")})`);
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2749
|
+
lines.push("", "[Proxy Group]");
|
|
2750
|
+
for (const g of p.groups) lines.push(`${name(g.id)} = ${[
|
|
2751
|
+
g.type,
|
|
2752
|
+
...g.members.map(action),
|
|
2753
|
+
...g.url ? [`url=${g.url}`] : [],
|
|
2754
|
+
...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
|
|
2755
|
+
...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
|
|
2756
|
+
].join(", ")}`);
|
|
2757
|
+
lines.push("", "[Rule]");
|
|
2758
|
+
for (const r of p.rules) lines.push([
|
|
2759
|
+
conditionText(r.when),
|
|
2760
|
+
action(r.then),
|
|
2761
|
+
...conditionOptions(r.when)
|
|
2762
|
+
].join(","));
|
|
2763
|
+
lines.push(`FINAL,${action(p.fallback)}`, "");
|
|
2764
|
+
return deepFreeze({
|
|
2765
|
+
artifactKind: "surge-profile",
|
|
2766
|
+
content: lines.join("\n")
|
|
2767
|
+
});
|
|
2768
|
+
}
|
|
2769
|
+
function renderSurgeProfile(compilation, resolveSecret) {
|
|
2770
|
+
return renderProfile(compilation, secretReader(resolveSecret));
|
|
2771
|
+
}
|
|
2772
|
+
function renderSurgeProfiles(compilations, resolveSecret) {
|
|
2773
|
+
if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
|
|
2774
|
+
const read = secretReader(resolveSecret);
|
|
2775
|
+
return deepFreeze(compilations.map((c) => renderProfile(c, read)));
|
|
2776
|
+
}
|
|
2777
|
+
//#endregion
|
|
2778
|
+
//#region src/surge-publish.ts
|
|
2779
|
+
var SurgePublishError = class extends Error {
|
|
2780
|
+
published;
|
|
2781
|
+
constructor(message, published) {
|
|
2782
|
+
super(message);
|
|
2783
|
+
this.published = published;
|
|
2784
|
+
}
|
|
2785
|
+
};
|
|
2786
|
+
async function publishProfiles(files, surgeDirectory, io = { rename }) {
|
|
2787
|
+
if (!files.size || files.size > 16 || [...files.keys()].some((name) => !/^[a-z0-9][a-z0-9-]*\.conf$/.test(name))) throw new Error("INVALID_PROFILE_FILENAMES");
|
|
2788
|
+
const root = resolve(surgeDirectory);
|
|
2789
|
+
const generations = join(root, ".generations");
|
|
2790
|
+
const id = randomUUID();
|
|
2791
|
+
const generation = join(generations, id);
|
|
2792
|
+
const pointer = join(root, `.out-${id}`);
|
|
2793
|
+
const output = join(root, "out");
|
|
2794
|
+
const backup = join(generations, `legacy-${id}`);
|
|
2795
|
+
const lock = join(root, ".build-lock");
|
|
2796
|
+
const remove = io.rm ?? rm;
|
|
2797
|
+
let failure;
|
|
2798
|
+
let locked = false, created = false, committed = false, movedLegacy = false, recoveryFailed = false;
|
|
2799
|
+
async function directory(path) {
|
|
2800
|
+
await mkdir(path, {
|
|
2801
|
+
recursive: true,
|
|
2802
|
+
mode: 448
|
|
2803
|
+
});
|
|
2804
|
+
const stat = await lstat(path);
|
|
2805
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
|
|
2806
|
+
}
|
|
2807
|
+
try {
|
|
2808
|
+
await directory(root);
|
|
2809
|
+
try {
|
|
2810
|
+
await mkdir(lock, { mode: 448 });
|
|
2811
|
+
locked = true;
|
|
2812
|
+
} catch (error) {
|
|
2813
|
+
if (error.code === "EEXIST") throw new Error("OUTPUT_LOCKED");
|
|
2814
|
+
throw error;
|
|
2815
|
+
}
|
|
2816
|
+
await directory(generations);
|
|
2817
|
+
let previous;
|
|
2818
|
+
try {
|
|
2819
|
+
previous = await lstat(output);
|
|
2820
|
+
} catch (error) {
|
|
2821
|
+
if (error.code !== "ENOENT") throw error;
|
|
2822
|
+
}
|
|
2823
|
+
if (previous?.isSymbolicLink()) {
|
|
2824
|
+
const target = await readlink(output);
|
|
2825
|
+
if (!/^\.generations\/(?:legacy-)?[a-f0-9-]{36}$/.test(target)) throw new Error("UNMANAGED_OUTPUT_LINK");
|
|
2826
|
+
const stat = await lstat(join(root, target));
|
|
2827
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
|
|
2828
|
+
} else if (previous && !previous.isDirectory()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
|
|
2829
|
+
await mkdir(generation, { mode: 448 });
|
|
2830
|
+
created = true;
|
|
2831
|
+
for (const [name, content] of files) await writeFile(join(generation, name), content, {
|
|
2832
|
+
mode: 384,
|
|
2833
|
+
flag: "wx"
|
|
2834
|
+
});
|
|
2835
|
+
await symlink(`.generations/${id}`, pointer, "dir");
|
|
2836
|
+
if (previous?.isDirectory()) {
|
|
2837
|
+
await io.rename(output, backup);
|
|
2838
|
+
movedLegacy = true;
|
|
2839
|
+
}
|
|
2840
|
+
try {
|
|
2841
|
+
await io.rename(pointer, output);
|
|
2842
|
+
committed = true;
|
|
2843
|
+
} catch (error) {
|
|
2844
|
+
if (movedLegacy) try {
|
|
2845
|
+
await io.rename(backup, output);
|
|
2846
|
+
movedLegacy = false;
|
|
2847
|
+
} catch {
|
|
2848
|
+
recoveryFailed = true;
|
|
2849
|
+
throw new Error("PUBLISH_RECOVERY_REQUIRED");
|
|
2850
|
+
}
|
|
2851
|
+
throw error;
|
|
2852
|
+
}
|
|
2853
|
+
} catch (error) {
|
|
2854
|
+
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";
|
|
2855
|
+
failure = new Error(code);
|
|
2856
|
+
} finally {
|
|
2857
|
+
if (!recoveryFailed) try {
|
|
2858
|
+
await remove(pointer, { force: true });
|
|
2859
|
+
if (created && !committed) await remove(generation, {
|
|
2860
|
+
recursive: true,
|
|
2861
|
+
force: true
|
|
2862
|
+
});
|
|
2863
|
+
if (locked) await remove(lock, {
|
|
2864
|
+
recursive: true,
|
|
2865
|
+
force: true
|
|
2866
|
+
});
|
|
2867
|
+
} catch {
|
|
2868
|
+
failure ??= /* @__PURE__ */ new Error("PROFILE_PUBLISH_CLEANUP_FAILED");
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
if (failure) throw new SurgePublishError(failure.message === "PROFILE_PUBLISH_CLEANUP_FAILED" ? committed ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : failure.message, committed);
|
|
2872
|
+
}
|
|
2873
|
+
//#endregion
|
|
2874
|
+
//#region src/surge-host.ts
|
|
2875
|
+
/** Complete-profile batches use the out symlink protocol; the Program host remains unchanged. */
|
|
2876
|
+
async function buildSurgeProfilesToDirectory(profiles, output, resolveSecret = (token) => process.env[token.name]) {
|
|
2877
|
+
if (typeof output !== "string" || !output.trim()) return {
|
|
2878
|
+
published: false,
|
|
2879
|
+
exitCode: 1,
|
|
2880
|
+
code: "INVALID_OUTPUT_DIRECTORY"
|
|
2881
|
+
};
|
|
2882
|
+
try {
|
|
2883
|
+
const entries = Object.entries(profiles);
|
|
2884
|
+
if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
|
|
2885
|
+
published: false,
|
|
2886
|
+
exitCode: 1,
|
|
2887
|
+
code: "INVALID_PROFILE_FILENAMES"
|
|
2888
|
+
};
|
|
2889
|
+
const compiled = entries.map(([, input]) => compileSurgeProfile(input));
|
|
2890
|
+
if (compiled.some((profile) => !profile.ok)) return {
|
|
2891
|
+
published: false,
|
|
2892
|
+
exitCode: 1,
|
|
2893
|
+
code: "COMPILATION_FAILED"
|
|
2894
|
+
};
|
|
2895
|
+
const artifacts = renderSurgeProfiles(compiled, resolveSecret);
|
|
2896
|
+
await publishProfiles(new Map(entries.map(([id], i) => [`${id}.conf`, artifacts[i].content])), output);
|
|
2897
|
+
return {
|
|
2898
|
+
published: true,
|
|
2899
|
+
exitCode: 0,
|
|
2900
|
+
code: "PUBLISHED",
|
|
2901
|
+
active: join(resolve(output), "out")
|
|
2902
|
+
};
|
|
2903
|
+
} catch (error) {
|
|
2904
|
+
if (error instanceof SurgePublishError) return {
|
|
2905
|
+
published: error.published,
|
|
2906
|
+
exitCode: error.published ? 2 : 1,
|
|
2907
|
+
code: error.message,
|
|
2908
|
+
...error.published ? { active: join(resolve(output), "out") } : {},
|
|
2909
|
+
...error.message === "PUBLISH_RECOVERY_REQUIRED" ? { hint: "out may be absent; preserve the lock, backup, generation and temporary pointer for manual recovery" } : {}
|
|
2910
|
+
};
|
|
2911
|
+
return {
|
|
2912
|
+
published: false,
|
|
2913
|
+
exitCode: 1,
|
|
2914
|
+
code: error instanceof RenderError ? error.code : "BUILD_FAILED"
|
|
2915
|
+
};
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
//#endregion
|
|
2919
|
+
//#region src/surge-build.ts
|
|
2920
|
+
function record(value, keys) {
|
|
2921
|
+
if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
|
|
2922
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
2923
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
2924
|
+
if (typeof key !== "string" || keys && !keys.includes(key) || !descriptor.enumerable || !("value" in descriptor)) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
|
|
2925
|
+
}
|
|
2926
|
+
}
|
|
2927
|
+
/** Capture data and callback references before application preflight can change its source. */
|
|
2928
|
+
function defineSurgeBuild(input) {
|
|
2929
|
+
try {
|
|
2930
|
+
record(input, [
|
|
2931
|
+
"profiles",
|
|
2932
|
+
"preflight",
|
|
2933
|
+
"resolveSecret"
|
|
2934
|
+
]);
|
|
2935
|
+
record(input.profiles);
|
|
2936
|
+
for (const callback of [input.preflight, input.resolveSecret]) if (callback !== void 0 && typeof callback !== "function") throw new Error();
|
|
2937
|
+
return Object.freeze({
|
|
2938
|
+
profiles: deepFreeze(snapshotDefinition(input.profiles)),
|
|
2939
|
+
...input.preflight === void 0 ? {} : { preflight: input.preflight },
|
|
2940
|
+
...input.resolveSecret === void 0 ? {} : { resolveSecret: input.resolveSecret }
|
|
2941
|
+
});
|
|
2942
|
+
} catch {
|
|
2943
|
+
throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
|
|
2944
|
+
}
|
|
2945
|
+
}
|
|
2946
|
+
function surgeBuildFailure(code, validation = false, profileCount = 0) {
|
|
2947
|
+
return {
|
|
2948
|
+
published: false,
|
|
2949
|
+
exitCode: 1,
|
|
2950
|
+
code,
|
|
2951
|
+
warnings: {},
|
|
2952
|
+
validation,
|
|
2953
|
+
profileCount
|
|
2954
|
+
};
|
|
2955
|
+
}
|
|
2956
|
+
/** Pure orchestration result; the CLI owns stdout and process exit status. */
|
|
2957
|
+
async function runSurgeBuild(input, output, options = {}) {
|
|
2958
|
+
let validation;
|
|
2959
|
+
try {
|
|
2960
|
+
record(options, ["validation"]);
|
|
2961
|
+
if (options.validation !== void 0 && typeof options.validation !== "boolean") throw new Error();
|
|
2962
|
+
validation = options.validation ?? false;
|
|
2963
|
+
} catch {
|
|
2964
|
+
return surgeBuildFailure("INVALID_BUILD_OPTIONS");
|
|
2965
|
+
}
|
|
2966
|
+
let definition;
|
|
2967
|
+
try {
|
|
2968
|
+
definition = defineSurgeBuild(input);
|
|
2969
|
+
} catch {
|
|
2970
|
+
return surgeBuildFailure("INVALID_BUILD_DEFINITION", validation);
|
|
2971
|
+
}
|
|
2972
|
+
const profileCount = Object.keys(definition.profiles).length;
|
|
2973
|
+
const failure = (code) => surgeBuildFailure(code, validation, profileCount);
|
|
2974
|
+
if (typeof output !== "string" || !output.trim()) return failure("INVALID_OUTPUT_DIRECTORY");
|
|
2975
|
+
if (validation && !definition.resolveSecret) return failure("VALIDATION_RESOLVER_REQUIRED");
|
|
2976
|
+
let codes;
|
|
2977
|
+
try {
|
|
2978
|
+
codes = definition.preflight ? definition.preflight() : [];
|
|
2979
|
+
} catch {
|
|
2980
|
+
return failure("PREFLIGHT_FAILED");
|
|
2981
|
+
}
|
|
2982
|
+
try {
|
|
2983
|
+
codes = snapshotDefinition(codes);
|
|
2984
|
+
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();
|
|
2985
|
+
} catch {
|
|
2986
|
+
return failure("INVALID_PREFLIGHT_WARNINGS");
|
|
2987
|
+
}
|
|
2988
|
+
const warnings = {};
|
|
2989
|
+
for (const code of codes) warnings[code] = (warnings[code] ?? 0) + 1;
|
|
2990
|
+
const context = Object.freeze({ validation });
|
|
2991
|
+
const resolver = definition.resolveSecret;
|
|
2992
|
+
return {
|
|
2993
|
+
...await buildSurgeProfilesToDirectory(definition.profiles, output, resolver ? (token) => resolver(token, context) : (token) => process.env[token.name]),
|
|
2994
|
+
warnings,
|
|
2995
|
+
validation,
|
|
2996
|
+
profileCount
|
|
2997
|
+
};
|
|
2998
|
+
}
|
|
2999
|
+
//#endregion
|
|
3000
|
+
export { route as A, use as B, direct as C, policy$2 as D, mihomo as E, sequence as F, requestSchema as G, deepFreeze as H, singbox$1 as I, defineRoute as J, ProfileDefinitionError as K, slot as L, ruleSet as M, secret as N, proxy as O, selectNodes as P, selectProxies as Q, strategy as R, defineConfig as S, match as T, idSchema as U, assertData as V, nodeSchema as W, defineSurgeProfile as X, defineRoutes as Y, outbound as Z, RenderError as _, compileSurgeProfile as a, StaticRuleSetUnknownError as b, buildToDirectory as c, compile as d, explain as f, targetCatalog as g, nativeNameSchema as h, buildSurgeProfilesToDirectory as i, rule as j, reject as k, render as l, isReservedNativeName as m, runSurgeBuild as n, renderSurgeProfile as o, compileStrategyGroups as p, defineProxyGroup as q, surgeBuildFailure as r, renderSurgeProfiles as s, defineSurgeBuild as t, secretReader as u, surgeProxy as v, group as w, block as x, validateProxyOptions as y, surge$1 as z };
|