proxylang 0.10.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { K as requestSchema, L as targetCatalog, M as compile, N as explain, V as StaticRuleSetUnknownError, Z as definitionDiagnostic, i as buildToDirectory, n as defineBuild, r as runBuild, t as checkBuild } from "./profile-build-BC7eIYBy.js";
2
+ import { K as requestSchema, L as targetCatalog, M as compile, N as explain, V as StaticRuleSetUnknownError, Z as definitionDiagnostic, i as buildToDirectory, n as defineBuild, r as runBuild, t as checkBuild } from "./profile-build-Cfs0OIt3.js";
3
3
  import { lstat, open, stat } from "node:fs/promises";
4
4
  import { resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
package/dist/index.d.ts CHANGED
@@ -20,6 +20,7 @@ export type NativeRuleSet = {
20
20
  readonly engine: "sing-box";
21
21
  readonly format: "source" | "binary";
22
22
  readonly intervalSeconds: number;
23
+ readonly resolve?: boolean;
23
24
  } | {
24
25
  readonly engine: "mihomo";
25
26
  readonly format: "yaml" | "text";
@@ -162,6 +163,13 @@ export type VLESSNode = ProxyBase & {
162
163
  readonly uuid: Secret;
163
164
  readonly tls?: ProxyTLS;
164
165
  readonly transport?: WebSocketTransport;
166
+ readonly flow?: "xtls-rprx-vision";
167
+ readonly packetEncoding?: "xudp" | "packetaddr";
168
+ readonly reality?: {
169
+ readonly publicKey: string;
170
+ readonly shortId: string;
171
+ };
172
+ readonly utlsFingerprint?: "chrome";
165
173
  };
166
174
  export type ProxyNode = TrojanNode | AnyTLSNode | Hysteria2Node | HttpNode | ShadowsocksNode | VMessNode | VLESSNode;
167
175
  export type TailscaleEndpoint = {
@@ -245,7 +253,20 @@ export type DnsRule = {
245
253
  readonly pattern: string;
246
254
  readonly server: string;
247
255
  };
256
+ export type Tun = {
257
+ readonly address: readonly string[];
258
+ readonly stack: "system" | "gvisor" | "mixed";
259
+ readonly autoRoute: boolean;
260
+ readonly strictRoute: boolean;
261
+ readonly dnsMode: "disabled" | "native" | "hijack";
262
+ readonly routeExcludeAddress?: readonly string[];
263
+ };
248
264
  export type Program = {
265
+ readonly domainMatching?: "prefer-sniffed";
266
+ readonly serverAliases?: Readonly<Record<string, string>>;
267
+ readonly cacheFile?: boolean;
268
+ readonly unsupportedUdp?: "reject";
269
+ readonly tun?: Tun;
249
270
  readonly dns?: readonly DnsRule[];
250
271
  readonly engine: Engine;
251
272
  readonly nodes: readonly ProxyNode[];
@@ -531,6 +552,16 @@ export declare function renderSurgeProfiles(compilations: readonly SurgeProfileC
531
552
  //#endregion
532
553
  //#region src/targets.d.ts
533
554
  export declare const targetCatalog: readonly [{
555
+ readonly engine: "sing-box";
556
+ readonly version: "1.14.4";
557
+ readonly autoGroup: "urltest";
558
+ readonly platforms: readonly ["linux", "macos"];
559
+ readonly protocols: readonly ["hysteria2", "trojan", "http", "anytls", "shadowsocks", "vmess", "vless"];
560
+ readonly endpoints: readonly ["sing-box-tailscale"];
561
+ readonly groups: readonly ["select", "urltest"];
562
+ readonly nativeRuleSets: readonly ["source", "binary"];
563
+ readonly dns: "typed";
564
+ }, {
534
565
  readonly engine: "sing-box";
535
566
  readonly version: "1.11.0";
536
567
  readonly autoGroup: "urltest";
@@ -701,10 +732,15 @@ type ProfileDefinition = {
701
732
  readonly surge?: SurgeConfig;
702
733
  readonly singBox?: {
703
734
  readonly mode: "fragment" | "standalone";
735
+ readonly tun?: Tun;
704
736
  readonly listener?: {
705
737
  readonly port: number;
706
738
  readonly resolver: string;
707
739
  };
740
+ readonly domainMatching?: "prefer-sniffed";
741
+ readonly serverAliases?: Readonly<Record<string, string>>;
742
+ readonly cacheFile?: boolean;
743
+ readonly unsupportedUdp?: "reject";
708
744
  };
709
745
  };
710
746
  type Profile = DeepReadonly<Omit<ProfileDefinition, "proxies" | "groups" | "routes" | "surge" | "dns"> & {
@@ -1015,6 +1051,7 @@ export declare const singbox: {
1015
1051
  readonly engine: "sing-box";
1016
1052
  readonly format: "source" | "binary";
1017
1053
  readonly intervalSeconds: number;
1054
+ readonly resolve?: boolean;
1018
1055
  }, "engine" | "id" | "type"> & {
1019
1056
  readonly id?: string;
1020
1057
  } & {
@@ -1028,6 +1065,7 @@ export declare const singbox: {
1028
1065
  readonly engine: "sing-box";
1029
1066
  readonly format: "source" | "binary";
1030
1067
  readonly intervalSeconds: number;
1068
+ readonly resolve?: boolean;
1031
1069
  };
1032
1070
  };
1033
1071
  tailscale: (options: Omit<TailscaleEndpoint, "type">) => TailscaleEndpoint;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as inspectDefinition, A as renderSurgeProfiles, B as validateProxyOptions, C as strategy, D as defineProfile, E as compileProfile, F as isReservedNativeName, G as nodeSchema, H as assertData, I as nativeNameSchema, J as defineProxyGroup, L as targetCatalog, M as compile, N as explain, O as compileSurgeProfile, P as compileStrategyGroups, Q as exactDefinition, R as RenderError, S as slot, T as use, U as deepFreeze, V as StaticRuleSetUnknownError, W as idSchema, X as defineRoutes, Y as defineRoute, _ as rule, a as render, b as sequence, c as direct, d as match, et as outbound, f as mihomo, g as route, h as reject, i as buildToDirectory, j as secretReader, k as renderSurgeProfile, l as dnsRule, m as proxy, n as defineBuild, o as block, p as policy, q as ProfileDefinitionError, r as runBuild, s as defineConfig, t as checkBuild, u as group, v as ruleSet, w as surge, x as singbox, y as secret, z as surgeProxy } from "./profile-build-BC7eIYBy.js";
1
+ import { $ as inspectDefinition, A as renderSurgeProfiles, B as validateProxyOptions, C as strategy, D as defineProfile, E as compileProfile, F as isReservedNativeName, G as nodeSchema, H as assertData, I as nativeNameSchema, J as defineProxyGroup, L as targetCatalog, M as compile, N as explain, O as compileSurgeProfile, P as compileStrategyGroups, Q as exactDefinition, R as RenderError, S as slot, T as use, U as deepFreeze, V as StaticRuleSetUnknownError, W as idSchema, X as defineRoutes, Y as defineRoute, _ as rule, a as render, b as sequence, c as direct, d as match, et as outbound, f as mihomo, g as route, h as reject, i as buildToDirectory, j as secretReader, k as renderSurgeProfile, l as dnsRule, m as proxy, n as defineBuild, o as block, p as policy, q as ProfileDefinitionError, r as runBuild, s as defineConfig, t as checkBuild, u as group, v as ruleSet, w as surge, x as singbox, y as secret, z as surgeProxy } from "./profile-build-Cfs0OIt3.js";
2
2
  import { z } from "zod";
3
3
  import { createHash } from "node:crypto";
4
4
  //#region src/proxy-fragments.ts
@@ -468,6 +468,39 @@ const surgeMatch = {
468
468
  }
469
469
  };
470
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
471
504
  //#region src/schema.ts
472
505
  const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
473
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])?$/);
@@ -515,7 +548,8 @@ const nativeRuleSetSchema = z.discriminatedUnion("engine", [
515
548
  ...remoteBase,
516
549
  engine: z.literal("sing-box"),
517
550
  format: z.enum(["source", "binary"]),
518
- intervalSeconds: updateInterval
551
+ intervalSeconds: updateInterval,
552
+ resolve: z.boolean().optional()
519
553
  }),
520
554
  z.strictObject({
521
555
  ...remoteBase,
@@ -710,8 +744,15 @@ const nodeSchema = z.discriminatedUnion("type", [
710
744
  }),
711
745
  z.strictObject({
712
746
  ...uuidNode,
713
- type: z.literal("vless")
714
- })
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)
715
756
  ]).refine((node) => !("transport" in node && node.transport && node.tls?.alpn) || node.tls.alpn.length === 1 && node.tls.alpn[0] === "http/1.1");
716
757
  const endpointSchema = z.strictObject({
717
758
  type: z.literal("sing-box-tailscale"),
@@ -724,7 +765,7 @@ const endpointSchema = z.strictObject({
724
765
  exitNode: ip$1.optional(),
725
766
  exitNodeAllowLanAccess: z.boolean().optional()
726
767
  }).refine((endpoint) => endpoint.exitNodeAllowLanAccess === void 0 || endpoint.exitNode !== void 0);
727
- const members = z.array(idSchema).min(1).refine(unique);
768
+ const members = z.array(z.union([idSchema, z.enum(["DIRECT", "REJECT"])])).min(1).refine(unique);
728
769
  const url$1 = z.string().url().refine((value) => {
729
770
  try {
730
771
  const u = new URL(value);
@@ -796,6 +837,10 @@ const configSchema = z.strictObject({
796
837
  "mihomo",
797
838
  "stash"
798
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(),
799
844
  dns: dnsRulesSchema.optional(),
800
845
  nodes: z.array(nodeSchema),
801
846
  endpoints: z.array(endpointSchema).max(1e3).optional(),
@@ -805,7 +850,23 @@ const configSchema = z.strictObject({
805
850
  listener: z.strictObject({
806
851
  port: port$1,
807
852
  resolver: ip$1
808
- }).optional()
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()
809
870
  })),
810
871
  targets: z.array(z.strictObject({
811
872
  id: idSchema,
@@ -986,6 +1047,31 @@ function collectNativeRuleSets(rules, target, diagnostics) {
986
1047
  return [...found.values()];
987
1048
  }
988
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
989
1075
  //#region src/rules.ts
990
1076
  function expandRules(entries, diagnostics, path = "routing") {
991
1077
  const output = [];
@@ -1138,11 +1224,12 @@ function evaluate(condition, request) {
1138
1224
  reason: present ? matched ? "匹配" : "不匹配" : "字段缺失,原子条件为 false"
1139
1225
  };
1140
1226
  }
1141
- function explainRules(rules, fallback, input) {
1227
+ function explainRules(rules, fallback, input, orderedResolve = false) {
1142
1228
  const parsed = requestSchema.safeParse(input);
1143
1229
  if (!parsed.success) throw new Error("INVALID_REQUEST");
1144
1230
  const trace = [];
1145
1231
  for (const rule of rules) {
1232
+ if (orderedResolve && needsResolve(rule.when) && parsed.data.domain && !parsed.data.ip) throw new StaticMetadataUnknownError();
1146
1233
  const condition = evaluate(rule.when, parsed.data);
1147
1234
  trace.push({
1148
1235
  id: rule.id,
@@ -1200,8 +1287,8 @@ var RenderError = class extends Error {
1200
1287
  function pathsOverlap(a, b) {
1201
1288
  return a === b || a.startsWith(b.endsWith("/") ? b : `${b}/`) || b.startsWith(a.endsWith("/") ? a : `${a}/`);
1202
1289
  }
1203
- function nodeIsTcpOnly(node, engine) {
1204
- return node.type === "http" || node.type === "anytls" && engine !== "surge" || node.type === "vmess" || node.type === "vless" || engine === "surge" && node.type === "shadowsocks" && node.surge?.udpRelay === false;
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;
1205
1292
  }
1206
1293
  function validateProxyOptions(node, target, diagnostics) {
1207
1294
  if (node.type === "hysteria2") {
@@ -1215,8 +1302,22 @@ function validateProxyOptions(node, target, diagnostics) {
1215
1302
  return;
1216
1303
  }
1217
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
+ });
1218
1313
  if (target.engine !== "surge") {
1219
- if (node.tcpFastOpen !== void 0 || "skipCertVerify" in node && node.skipCertVerify !== void 0 || tls?.skipCertVerify !== void 0 || "surge" in node && node.surge !== void 0) diagnostics.push({
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({
1220
1321
  severity: "error",
1221
1322
  code: "PROXY_OPTION_UNSUPPORTED",
1222
1323
  target: target.id,
@@ -1238,13 +1339,27 @@ function uuid(token, secret) {
1238
1339
  if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) throw new RenderError("INVALID_UUID_SECRET");
1239
1340
  return value;
1240
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
+ }
1241
1355
  function singboxProxy(node, secret) {
1242
1356
  const result = {
1243
1357
  type: node.type,
1244
1358
  tag: node.id,
1245
1359
  server: node.server,
1246
1360
  server_port: node.port,
1247
- ...node.via ? { detour: node.via } : {}
1361
+ ...node.via ? { detour: node.via } : {},
1362
+ ...node.tcpFastOpen !== void 0 ? { tcp_fast_open: node.tcpFastOpen } : {}
1248
1363
  };
1249
1364
  switch (node.type) {
1250
1365
  case "hysteria2":
@@ -1269,7 +1384,8 @@ function singboxProxy(node, secret) {
1269
1384
  result.password = secret(node.password);
1270
1385
  result.tls = {
1271
1386
  enabled: true,
1272
- ...node.serverName ? { server_name: node.serverName } : {}
1387
+ ...node.serverName ? { server_name: node.serverName } : {},
1388
+ ...node.skipCertVerify !== void 0 ? { insecure: node.skipCertVerify } : {}
1273
1389
  };
1274
1390
  break;
1275
1391
  case "shadowsocks":
@@ -1280,6 +1396,13 @@ function singboxProxy(node, secret) {
1280
1396
  case "vless":
1281
1397
  result.uuid = uuid(node.uuid, secret);
1282
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
+ }
1283
1406
  if (node.type === "vmess") Object.assign(result, {
1284
1407
  security: "aes-128-gcm",
1285
1408
  alter_id: 0
@@ -1287,7 +1410,17 @@ function singboxProxy(node, secret) {
1287
1410
  if (node.tls) result.tls = {
1288
1411
  enabled: true,
1289
1412
  server_name: node.tls.serverName,
1290
- ...node.tls.alpn ? { alpn: [...node.tls.alpn] } : {}
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
+ } } : {}
1291
1424
  };
1292
1425
  if (node.transport) result.transport = {
1293
1426
  type: "ws",
@@ -1500,6 +1633,25 @@ function clashConfig(plan, secret) {
1500
1633
  //#endregion
1501
1634
  //#region src/targets.ts
1502
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
+ },
1503
1655
  {
1504
1656
  engine: "sing-box",
1505
1657
  version: "1.11.0",
@@ -1842,7 +1994,9 @@ function compile(input) {
1842
1994
  if (Object.keys(config.programs).length === 0) error("EMPTY_PROGRAMS", "programs", "至少需要一个程序");
1843
1995
  for (const [name, program] of Object.entries(config.programs)) {
1844
1996
  const path = `programs.${name}`;
1845
- for (const node of program.nodes) if (!isIP(node.server)) error("PROXY_HOSTNAME_MODE_UNSUPPORTED", `${path}.nodes.${node.id}`, "域名代理地址目前仅允许节点片段入口");
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");
1846
2000
  validateRuleSets(program.routing, program.engine, diagnostics, path);
1847
2001
  const rules = lowerRuleSets(expandRules(program.routing, diagnostics, name), diagnostics, path);
1848
2002
  expanded.set(name, rules);
@@ -1855,11 +2009,12 @@ function compile(input) {
1855
2009
  const byId = new Map(resources.map((resource) => [resource.id, resource]));
1856
2010
  if (byId.size !== resources.length) error("DUPLICATE_RESOURCE", path, "节点、组与端点共用唯一 ID 命名空间");
1857
2011
  const edges = new Map(resources.map((resource) => [resource.id, "members" in resource ? resource.members : "via" in resource && resource.via ? [resource.via] : []]));
1858
- for (const [id, refs] of edges) for (const ref of refs) if (!byId.has(ref)) error("MISSING_REFERENCE", `${path}.${id}`, "节点或组引用不存在");
2012
+ for (const [id, refs] of edges) for (const ref of refs) if (!byId.has(ref) && !builtinMember(ref)) error("MISSING_REFERENCE", `${path}.${id}`, "节点或组引用不存在");
1859
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");
1860
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}`, "端点状态目录不能重复或互为祖先");
1861
2015
  const states = /* @__PURE__ */ new Map();
1862
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;
1863
2018
  const visit = (id) => {
1864
2019
  if (states.get(id) === 1) {
1865
2020
  error("RESOURCE_CYCLE", `${path}.${id}`, "组成员和 via 拨号依赖不能形成循环");
@@ -1868,7 +2023,7 @@ function compile(input) {
1868
2023
  if (states.get(id) === 2) return tcpOnly.get(id) ?? false;
1869
2024
  states.set(id, 1);
1870
2025
  const item = byId.get(id);
1871
- let limited = !!item && "server" in item && nodeIsTcpOnly(item, program.engine);
2026
+ let limited = !!item && "server" in item && nodeIsTcpOnly(item, program.engine, udpVersion);
1872
2027
  for (const ref of edges.get(id) ?? []) limited = visit(ref) || limited;
1873
2028
  states.set(id, 2);
1874
2029
  tcpOnly.set(id, limited);
@@ -1879,7 +2034,7 @@ function compile(input) {
1879
2034
  const validateAction = (action, where, udpPossible) => {
1880
2035
  if (action.type !== "route") return;
1881
2036
  if (!byId.has(action.to)) error("MISSING_REFERENCE", where, "路由出口不存在");
1882
- else if (udpPossible && tcpOnly.get(action.to)) error("NETWORK_UNSUPPORTED", where, "出口的可选或 via 路径含 TCP-only 节点;请用 network(tcp) 限定规则,且不能用于 fallback");
2037
+ else if (udpPossible && tcpOnly.get(action.to) && program.unsupportedUdp !== "reject") error("NETWORK_UNSUPPORTED", where, "出口的可选或 via 路径含 TCP-only 节点;请用 network(tcp) 限定规则,且不能用于 fallback");
1883
2038
  };
1884
2039
  for (const rule of rules) validateAction(rule.then, rule.id, truthPossibilities(rule.when, "udp").includes(true));
1885
2040
  const validateBindings = (entries, prefix) => {
@@ -1915,6 +2070,14 @@ function compile(input) {
1915
2070
  continue;
1916
2071
  }
1917
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
+ }
1918
2081
  if (target.mode === "standalone" && !program.listener) error("LISTENER_REQUIRED", path, "standalone 必须声明 loopback listener 与 IP DNS resolver", target.id);
1919
2082
  if (target.mode !== "standalone" && program.listener) error("UNUSED_LISTENER", path, "fragment 不能静默忽略 listener;请使用独立程序或 standalone 目标", target.id);
1920
2083
  if (program.dns?.length) {
@@ -1922,7 +2085,7 @@ function compile(input) {
1922
2085
  else if (target.mode !== "standalone") error("DNS_MODE_UNSUPPORTED", path, "通用 DNS 需要 standalone", target.id);
1923
2086
  }
1924
2087
  for (const endpoint of program.endpoints ?? []) {
1925
- if (!descriptor.endpoints.includes(endpoint.type)) error("ENDPOINT_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 端点仅支持 sing-box 1.12.0", target.id);
2088
+ if (!descriptor.endpoints.includes(endpoint.type)) error("ENDPOINT_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "当前目标版本不支持 Tailscale 端点", target.id);
1926
2089
  if (target.mode !== "standalone") error("ENDPOINT_MODE_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 需要 standalone 的普通 DNS/final 隔离引导解析", target.id);
1927
2090
  }
1928
2091
  for (const node of program.nodes) {
@@ -1943,27 +2106,34 @@ function compile(input) {
1943
2106
  if (target.engine === "surge") {
1944
2107
  for (const rule of rules) if (logicalDepth(rule.when) > 10) error("LOGICAL_DEPTH", rule.id, "Surge 逻辑条件最多嵌套 10 层", target.id);
1945
2108
  }
1946
- const checkOptions = (condition) => {
1947
- if ("includeSniffed" in condition && condition.includeSniffed === true && target.engine !== "surge" || condition.type === "ipCidr" && condition.noResolve !== void 0 && target.engine === "sing-box") error("MATCH_OPTION_UNSUPPORTED", path, "目标无法等价实现显式匹配选项", target.id);
1948
- if (condition.type === "all" || condition.type === "any") condition.conditions.forEach(checkOptions);
1949
- else if (condition.type === "not") checkOptions(condition.condition);
1950
- else if (condition.type === "ruleSet") checkOptions(condition.when);
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);
1951
2114
  };
1952
2115
  rules.forEach((rule) => checkOptions(rule.when));
1953
2116
  const nativeRuleSets = collectNativeRuleSets(rules, target, diagnostics);
1954
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;
1955
2119
  plans.push({
1956
2120
  nativeRuleSets,
1957
2121
  target,
1958
2122
  program,
1959
2123
  rules,
1960
2124
  strategySelections: lowered.selections,
1961
- sourceMap: rules.map((rule, nativeIndex) => ({
1962
- rule: rule.id,
1963
- nativeIndex,
1964
- origin: rule.origin
1965
- })),
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
+ }),
1966
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 不创建或清理缓存。无有效缓存且下载失败时拒绝启动。"] : [],
1967
2137
  ...nativeRuleSets.length ? ["原生外部规则由客户端持续下载和解释;静态布尔结果不验证 DNS 等副作用。缓存与下载失败处理沿用客户端机制,fragment 运行方提供工作目录与下载 DNS 路径。"] : [],
1968
2138
  ...program.endpoints?.length ? [
1969
2139
  "Tailscale 需要 with_tailscale 构建标签;运行方负责登录、路由批准及每实例独占身份目录。构建不注册 tailnet。",
@@ -1990,15 +2160,15 @@ function compile(input) {
1990
2160
  }
1991
2161
  let actual;
1992
2162
  try {
1993
- actual = explainRules(expanded.get(test.program), program.fallback, test.request);
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"));
1994
2164
  } catch (cause) {
1995
- if (!(cause instanceof StaticRuleSetUnknownError)) throw cause;
2165
+ if (!(cause instanceof StaticRuleSetUnknownError) && !(cause instanceof StaticMetadataUnknownError)) throw cause;
1996
2166
  cases.push({
1997
2167
  id: test.id,
1998
2168
  passed: false,
1999
2169
  code: "CASE_INDETERMINATE"
2000
2170
  });
2001
- error("CASE_INDETERMINATE", `cases.${test.id}`, "外部规则内容未知,无法静态确定首命中");
2171
+ error("CASE_INDETERMINATE", `cases.${test.id}`, "外部规则或所需运行时元数据未知,无法静态确定首命中");
2002
2172
  continue;
2003
2173
  }
2004
2174
  const passed = (test.expect.rule === void 0 || test.expect.rule === actual.rule) && sameAction(test.expect.action, actual.action);
@@ -2033,7 +2203,7 @@ function explain(compilation, target, request) {
2033
2203
  if (!compilation.ok) throw new Error("COMPILATION_FAILED");
2034
2204
  const plan = compilation.plans.find((plan) => plan.target.id === target);
2035
2205
  if (!plan) throw new Error("UNKNOWN_TARGET");
2036
- return explainRules(plan.rules, plan.program.fallback, request);
2206
+ return explainRules(plan.rules, plan.program.fallback, requestForProgram(plan.program, request), plan.target.engine === "sing-box" && plan.target.version === "1.14.4");
2037
2207
  }
2038
2208
  //#endregion
2039
2209
  //#region src/secrets.ts
@@ -2578,7 +2748,15 @@ function defineProfile(input) {
2578
2748
  "names"
2579
2749
  ]);
2580
2750
  if (input.singBox !== void 0) {
2581
- exactDefinition(input.singBox, ["mode", "listener"]);
2751
+ exactDefinition(input.singBox, [
2752
+ "mode",
2753
+ "listener",
2754
+ "tun",
2755
+ "domainMatching",
2756
+ "serverAliases",
2757
+ "cacheFile",
2758
+ "unsupportedUdp"
2759
+ ]);
2582
2760
  if (!["fragment", "standalone"].includes(input.singBox.mode)) fail("INVALID_PROFILE_DEFINITION");
2583
2761
  if (input.singBox.listener !== void 0) exactDefinition(input.singBox.listener, ["port", "resolver"]);
2584
2762
  }
@@ -2806,8 +2984,7 @@ function compileProfile(input) {
2806
2984
  ] : ["type"]);
2807
2985
  const members = definition.members.map((member) => {
2808
2986
  const action = lower(member);
2809
- if (action.type !== "route") return fail("PROFILE_GROUP_MEMBER_UNSUPPORTED");
2810
- return action.to;
2987
+ return action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
2811
2988
  });
2812
2989
  return {
2813
2990
  ...definition.algorithm,
@@ -2838,7 +3015,12 @@ function compileProfile(input) {
2838
3015
  groups,
2839
3016
  routing,
2840
3017
  fallback: lower(profile.fallback),
2841
- ...profile.singBox?.listener ? { listener: profile.singBox.listener } : {}
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 }
2842
3024
  } },
2843
3025
  targets: [{
2844
3026
  ...profile.target,
@@ -2975,6 +3157,7 @@ function nativeConstructor(engine) {
2975
3157
  "intervalSeconds",
2976
3158
  "noResolve",
2977
3159
  "includeSniffed",
3160
+ "resolve",
2978
3161
  "behavior",
2979
3162
  "to"
2980
3163
  ]);
@@ -2985,7 +3168,7 @@ function nativeConstructor(engine) {
2985
3168
  "url",
2986
3169
  "format",
2987
3170
  "intervalSeconds",
2988
- ...engine === "surge" ? ["noResolve", "includeSniffed"] : engine === "mihomo" ? ["behavior"] : []
3171
+ ...engine === "surge" ? ["noResolve", "includeSniffed"] : engine === "mihomo" ? ["behavior"] : ["resolve"]
2989
3172
  ]);
2990
3173
  const parsed = nativeRuleSetSchema.safeParse({
2991
3174
  ...engine === "surge" ? { format: "rule-set" } : {},
@@ -3158,26 +3341,52 @@ function singAction(action) {
3158
3341
  }
3159
3342
  function singbox(plan, secret) {
3160
3343
  const { program, target } = plan;
3161
- const modern = target.version === "1.12.0";
3344
+ const modern = targetCatalog.find((entry) => entry.engine === target.engine && entry.version === target.version)?.dns === "typed";
3162
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;
3163
3348
  const outbounds = [{
3164
3349
  type: "direct",
3165
3350
  tag: DIRECT,
3166
3351
  ...!modern && standalone ? { domain_strategy: "prefer_ipv4" } : {}
3167
3352
  }];
3353
+ if (program.groups.some((group) => group.members.includes("REJECT"))) outbounds.push({
3354
+ type: "block",
3355
+ tag: "pl-reject"
3356
+ });
3168
3357
  for (const node of program.nodes) outbounds.push({
3169
- ...singboxProxy(node, secret),
3358
+ ...singboxProxy(aliasProxyServer(node, program.serverAliases), secret),
3170
3359
  ...modern && program.dns?.length ? { domain_resolver: {
3171
- server: DNS,
3360
+ server: domainResolver,
3172
3361
  strategy: "prefer_ipv4"
3173
3362
  } } : {}
3174
3363
  });
3175
- for (const group of program.groups) outbounds.push(singboxGroup(group));
3176
- const rules = plan.rules.map((rule) => ({
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
+ }] : [], {
3177
3370
  ...singCondition(rule.when),
3178
3371
  ...singAction(rule.then)
3179
- }));
3372
+ }]);
3180
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
+ });
3181
3390
  if (plan.nativeRuleSets.length) routing.rule_set = plan.nativeRuleSets.map((r) => ({
3182
3391
  type: "remote",
3183
3392
  tag: r.id,
@@ -3193,14 +3402,34 @@ function singbox(plan, secret) {
3193
3402
  outbounds,
3194
3403
  route: routing
3195
3404
  };
3405
+ if (program.cacheFile) config.experimental = { cache_file: { enabled: true } };
3196
3406
  if (standalone) {
3197
3407
  const listener = program.listener;
3198
- config.inbounds = [{
3199
- type: "mixed",
3200
- tag: "pl-listener",
3201
- listen: "127.0.0.1",
3202
- listen_port: listener.port
3203
- }];
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
+ ];
3204
3433
  config.dns = {
3205
3434
  servers: [modern ? {
3206
3435
  type: "udp",
@@ -3213,15 +3442,22 @@ function singbox(plan, secret) {
3213
3442
  detour: DIRECT
3214
3443
  }],
3215
3444
  final: DNS,
3216
- strategy: "prefer_ipv4"
3445
+ strategy: "prefer_ipv4",
3446
+ ...program.domainMatching ? { reverse_mapping: true } : {}
3217
3447
  };
3218
- if (modern && !program.dns?.length) routing.default_domain_resolver = {
3219
- server: DNS,
3448
+ if (modern && (!program.dns?.length || target.version === "1.14.4")) routing.default_domain_resolver = {
3449
+ server: domainResolver,
3220
3450
  strategy: "prefer_ipv4"
3221
3451
  };
3222
3452
  }
3223
3453
  if (program.dns?.length) {
3224
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
+ });
3225
3461
  dns.rules = program.dns.map((rule, index) => {
3226
3462
  const tag = `pl-domain-dns-${index}`;
3227
3463
  if (isIP(rule.server)) dns.servers.push(modern ? {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proxylang",
3
- "version": "0.10.1",
3
+ "version": "0.12.0",
4
4
  "description": "Composable routing policies in TypeScript with explicit platform targets",
5
5
  "homepage": "https://github.com/CorrectRoadH/proxylang#readme",
6
6
  "bugs": {