proxylang 0.10.1 → 0.11.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-BVhtmxFG.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
@@ -162,6 +162,13 @@ export type VLESSNode = ProxyBase & {
162
162
  readonly uuid: Secret;
163
163
  readonly tls?: ProxyTLS;
164
164
  readonly transport?: WebSocketTransport;
165
+ readonly flow?: "xtls-rprx-vision";
166
+ readonly packetEncoding?: "xudp" | "packetaddr";
167
+ readonly reality?: {
168
+ readonly publicKey: string;
169
+ readonly shortId: string;
170
+ };
171
+ readonly utlsFingerprint?: "chrome";
165
172
  };
166
173
  export type ProxyNode = TrojanNode | AnyTLSNode | Hysteria2Node | HttpNode | ShadowsocksNode | VMessNode | VLESSNode;
167
174
  export type TailscaleEndpoint = {
@@ -245,7 +252,16 @@ export type DnsRule = {
245
252
  readonly pattern: string;
246
253
  readonly server: string;
247
254
  };
255
+ export type Tun = {
256
+ readonly address: readonly string[];
257
+ readonly stack: "system" | "gvisor" | "mixed";
258
+ readonly autoRoute: boolean;
259
+ readonly strictRoute: boolean;
260
+ readonly dnsMode: "disabled" | "native" | "hijack";
261
+ readonly routeExcludeAddress?: readonly string[];
262
+ };
248
263
  export type Program = {
264
+ readonly tun?: Tun;
249
265
  readonly dns?: readonly DnsRule[];
250
266
  readonly engine: Engine;
251
267
  readonly nodes: readonly ProxyNode[];
@@ -531,6 +547,16 @@ export declare function renderSurgeProfiles(compilations: readonly SurgeProfileC
531
547
  //#endregion
532
548
  //#region src/targets.d.ts
533
549
  export declare const targetCatalog: readonly [{
550
+ readonly engine: "sing-box";
551
+ readonly version: "1.14.4";
552
+ readonly autoGroup: "urltest";
553
+ readonly platforms: readonly ["linux", "macos"];
554
+ readonly protocols: readonly ["hysteria2", "trojan", "http", "anytls", "shadowsocks", "vmess", "vless"];
555
+ readonly endpoints: readonly ["sing-box-tailscale"];
556
+ readonly groups: readonly ["select", "urltest"];
557
+ readonly nativeRuleSets: readonly ["source", "binary"];
558
+ readonly dns: "typed";
559
+ }, {
534
560
  readonly engine: "sing-box";
535
561
  readonly version: "1.11.0";
536
562
  readonly autoGroup: "urltest";
@@ -701,6 +727,7 @@ type ProfileDefinition = {
701
727
  readonly surge?: SurgeConfig;
702
728
  readonly singBox?: {
703
729
  readonly mode: "fragment" | "standalone";
730
+ readonly tun?: Tun;
704
731
  readonly listener?: {
705
732
  readonly port: number;
706
733
  readonly resolver: string;
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-BVhtmxFG.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])?$/);
@@ -710,8 +743,15 @@ const nodeSchema = z.discriminatedUnion("type", [
710
743
  }),
711
744
  z.strictObject({
712
745
  ...uuidNode,
713
- type: z.literal("vless")
714
- })
746
+ type: z.literal("vless"),
747
+ flow: z.literal("xtls-rprx-vision").optional(),
748
+ packetEncoding: z.enum(["xudp", "packetaddr"]).optional(),
749
+ utlsFingerprint: z.literal("chrome").optional(),
750
+ reality: z.strictObject({
751
+ publicKey: z.string().regex(/^[A-Za-z0-9_-]{43}$/).refine((value) => Buffer.from(value, "base64url").toString("base64url") === value),
752
+ shortId: z.string().regex(/^(?:[0-9a-fA-F]{2}){0,8}$/)
753
+ }).optional()
754
+ }).refine((node) => !node.reality || !!node.tls && node.utlsFingerprint === "chrome").refine((node) => !node.flow || !!node.tls && !node.transport).refine((node) => !node.utlsFingerprint || !!node.tls)
715
755
  ]).refine((node) => !("transport" in node && node.transport && node.tls?.alpn) || node.tls.alpn.length === 1 && node.tls.alpn[0] === "http/1.1");
716
756
  const endpointSchema = z.strictObject({
717
757
  type: z.literal("sing-box-tailscale"),
@@ -805,7 +845,23 @@ const configSchema = z.strictObject({
805
845
  listener: z.strictObject({
806
846
  port: port$1,
807
847
  resolver: ip$1
808
- }).optional()
848
+ }).optional(),
849
+ tun: z.strictObject({
850
+ address: z.array(cidr$1).min(1).max(2).refine(validTunAddresses),
851
+ stack: z.enum([
852
+ "system",
853
+ "gvisor",
854
+ "mixed"
855
+ ]),
856
+ autoRoute: z.boolean(),
857
+ strictRoute: z.boolean(),
858
+ dnsMode: z.enum([
859
+ "disabled",
860
+ "native",
861
+ "hijack"
862
+ ]),
863
+ routeExcludeAddress: z.array(cidr$1).optional()
864
+ }).refine((tun) => !tun.strictRoute || tun.autoRoute).optional()
809
865
  })),
810
866
  targets: z.array(z.strictObject({
811
867
  id: idSchema,
@@ -1200,8 +1256,8 @@ var RenderError = class extends Error {
1200
1256
  function pathsOverlap(a, b) {
1201
1257
  return a === b || a.startsWith(b.endsWith("/") ? b : `${b}/`) || b.startsWith(a.endsWith("/") ? a : `${a}/`);
1202
1258
  }
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;
1259
+ function nodeIsTcpOnly(node, engine, version) {
1260
+ return node.type === "http" || node.type === "anytls" && engine !== "surge" || 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
1261
  }
1206
1262
  function validateProxyOptions(node, target, diagnostics) {
1207
1263
  if (node.type === "hysteria2") {
@@ -1215,8 +1271,16 @@ function validateProxyOptions(node, target, diagnostics) {
1215
1271
  return;
1216
1272
  }
1217
1273
  const tls = "tls" in node ? node.tls : void 0;
1274
+ const modern = target.engine === "sing-box" && target.version === "1.14.4";
1275
+ if (node.type === "vless" && !modern && (node.flow !== void 0 || node.packetEncoding !== void 0 || node.reality !== void 0 || node.utlsFingerprint !== void 0)) diagnostics.push({
1276
+ severity: "error",
1277
+ code: "PROXY_OPTION_UNSUPPORTED",
1278
+ target: target.id,
1279
+ path: `targets.${target.id}.nodes.${node.id}`,
1280
+ message: "VLESS 扩展选项仅支持 sing-box 1.14.4"
1281
+ });
1218
1282
  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({
1283
+ if (node.tcpFastOpen !== void 0 || "skipCertVerify" in node && node.skipCertVerify !== void 0 || !modern && tls?.skipCertVerify !== void 0 || "surge" in node && node.surge !== void 0) diagnostics.push({
1220
1284
  severity: "error",
1221
1285
  code: "PROXY_OPTION_UNSUPPORTED",
1222
1286
  target: target.id,
@@ -1280,6 +1344,13 @@ function singboxProxy(node, secret) {
1280
1344
  case "vless":
1281
1345
  result.uuid = uuid(node.uuid, secret);
1282
1346
  result.network = "tcp";
1347
+ if (node.type === "vless") {
1348
+ if (node.flow) result.flow = node.flow;
1349
+ if (node.packetEncoding) {
1350
+ result.packet_encoding = node.packetEncoding;
1351
+ delete result.network;
1352
+ }
1353
+ }
1283
1354
  if (node.type === "vmess") Object.assign(result, {
1284
1355
  security: "aes-128-gcm",
1285
1356
  alter_id: 0
@@ -1287,7 +1358,17 @@ function singboxProxy(node, secret) {
1287
1358
  if (node.tls) result.tls = {
1288
1359
  enabled: true,
1289
1360
  server_name: node.tls.serverName,
1290
- ...node.tls.alpn ? { alpn: [...node.tls.alpn] } : {}
1361
+ ...node.tls.alpn ? { alpn: [...node.tls.alpn] } : {},
1362
+ ...node.tls.skipCertVerify !== void 0 ? { insecure: node.tls.skipCertVerify } : {},
1363
+ ...node.type === "vless" && node.utlsFingerprint ? { utls: {
1364
+ enabled: true,
1365
+ fingerprint: node.utlsFingerprint
1366
+ } } : {},
1367
+ ...node.type === "vless" && node.reality ? { reality: {
1368
+ enabled: true,
1369
+ public_key: node.reality.publicKey,
1370
+ short_id: node.reality.shortId
1371
+ } } : {}
1291
1372
  };
1292
1373
  if (node.transport) result.transport = {
1293
1374
  type: "ws",
@@ -1500,6 +1581,25 @@ function clashConfig(plan, secret) {
1500
1581
  //#endregion
1501
1582
  //#region src/targets.ts
1502
1583
  const targetCatalog = deepFreeze([
1584
+ {
1585
+ engine: "sing-box",
1586
+ version: "1.14.4",
1587
+ autoGroup: "urltest",
1588
+ platforms: ["linux", "macos"],
1589
+ protocols: [
1590
+ "hysteria2",
1591
+ "trojan",
1592
+ "http",
1593
+ "anytls",
1594
+ "shadowsocks",
1595
+ "vmess",
1596
+ "vless"
1597
+ ],
1598
+ endpoints: ["sing-box-tailscale"],
1599
+ groups: ["select", "urltest"],
1600
+ nativeRuleSets: ["source", "binary"],
1601
+ dns: "typed"
1602
+ },
1503
1603
  {
1504
1604
  engine: "sing-box",
1505
1605
  version: "1.11.0",
@@ -1842,7 +1942,9 @@ function compile(input) {
1842
1942
  if (Object.keys(config.programs).length === 0) error("EMPTY_PROGRAMS", "programs", "至少需要一个程序");
1843
1943
  for (const [name, program] of Object.entries(config.programs)) {
1844
1944
  const path = `programs.${name}`;
1845
- for (const node of program.nodes) if (!isIP(node.server)) error("PROXY_HOSTNAME_MODE_UNSUPPORTED", `${path}.nodes.${node.id}`, "域名代理地址目前仅允许节点片段入口");
1945
+ const programTargets = config.targets.filter((target) => target.program === name);
1946
+ const supportsHostname = program.engine === "sing-box" && programTargets.length > 0 && programTargets.every((target) => target.version === "1.14.4");
1947
+ 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
1948
  validateRuleSets(program.routing, program.engine, diagnostics, path);
1847
1949
  const rules = lowerRuleSets(expandRules(program.routing, diagnostics, name), diagnostics, path);
1848
1950
  expanded.set(name, rules);
@@ -1860,6 +1962,7 @@ function compile(input) {
1860
1962
  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
1963
  const states = /* @__PURE__ */ new Map();
1862
1964
  const tcpOnly = /* @__PURE__ */ new Map();
1965
+ const udpVersion = programTargets.length > 0 && programTargets.every((target) => target.engine === "sing-box" && target.version === "1.14.4") ? "1.14.4" : void 0;
1863
1966
  const visit = (id) => {
1864
1967
  if (states.get(id) === 1) {
1865
1968
  error("RESOURCE_CYCLE", `${path}.${id}`, "组成员和 via 拨号依赖不能形成循环");
@@ -1868,7 +1971,7 @@ function compile(input) {
1868
1971
  if (states.get(id) === 2) return tcpOnly.get(id) ?? false;
1869
1972
  states.set(id, 1);
1870
1973
  const item = byId.get(id);
1871
- let limited = !!item && "server" in item && nodeIsTcpOnly(item, program.engine);
1974
+ let limited = !!item && "server" in item && nodeIsTcpOnly(item, program.engine, udpVersion);
1872
1975
  for (const ref of edges.get(id) ?? []) limited = visit(ref) || limited;
1873
1976
  states.set(id, 2);
1874
1977
  tcpOnly.set(id, limited);
@@ -1915,6 +2018,10 @@ function compile(input) {
1915
2018
  continue;
1916
2019
  }
1917
2020
  if (program.engine !== target.engine) error("ENGINE_MISMATCH", path, "平台程序与目标引擎不一致", target.id);
2021
+ if (program.tun) {
2022
+ 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);
2023
+ if (unsafeTunResolvers(program).length) error("TUN_DNS_LOOP", path, "TUN DNS 上游不能使用回环、未指定或 TUN 网段地址", target.id);
2024
+ }
1918
2025
  if (target.mode === "standalone" && !program.listener) error("LISTENER_REQUIRED", path, "standalone 必须声明 loopback listener 与 IP DNS resolver", target.id);
1919
2026
  if (target.mode !== "standalone" && program.listener) error("UNUSED_LISTENER", path, "fragment 不能静默忽略 listener;请使用独立程序或 standalone 目标", target.id);
1920
2027
  if (program.dns?.length) {
@@ -1922,7 +2029,7 @@ function compile(input) {
1922
2029
  else if (target.mode !== "standalone") error("DNS_MODE_UNSUPPORTED", path, "通用 DNS 需要 standalone", target.id);
1923
2030
  }
1924
2031
  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);
2032
+ if (!descriptor.endpoints.includes(endpoint.type)) error("ENDPOINT_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "当前目标版本不支持 Tailscale 端点", target.id);
1926
2033
  if (target.mode !== "standalone") error("ENDPOINT_MODE_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 需要 standalone 的普通 DNS/final 隔离引导解析", target.id);
1927
2034
  }
1928
2035
  for (const node of program.nodes) {
@@ -2578,7 +2685,11 @@ function defineProfile(input) {
2578
2685
  "names"
2579
2686
  ]);
2580
2687
  if (input.singBox !== void 0) {
2581
- exactDefinition(input.singBox, ["mode", "listener"]);
2688
+ exactDefinition(input.singBox, [
2689
+ "mode",
2690
+ "listener",
2691
+ "tun"
2692
+ ]);
2582
2693
  if (!["fragment", "standalone"].includes(input.singBox.mode)) fail("INVALID_PROFILE_DEFINITION");
2583
2694
  if (input.singBox.listener !== void 0) exactDefinition(input.singBox.listener, ["port", "resolver"]);
2584
2695
  }
@@ -2838,7 +2949,8 @@ function compileProfile(input) {
2838
2949
  groups,
2839
2950
  routing,
2840
2951
  fallback: lower(profile.fallback),
2841
- ...profile.singBox?.listener ? { listener: profile.singBox.listener } : {}
2952
+ ...profile.singBox?.listener ? { listener: profile.singBox.listener } : {},
2953
+ ...profile.singBox?.tun ? { tun: profile.singBox.tun } : {}
2842
2954
  } },
2843
2955
  targets: [{
2844
2956
  ...profile.target,
@@ -3158,7 +3270,7 @@ function singAction(action) {
3158
3270
  }
3159
3271
  function singbox(plan, secret) {
3160
3272
  const { program, target } = plan;
3161
- const modern = target.version === "1.12.0";
3273
+ const modern = targetCatalog.find((entry) => entry.engine === target.engine && entry.version === target.version)?.dns === "typed";
3162
3274
  const standalone = target.mode === "standalone";
3163
3275
  const outbounds = [{
3164
3276
  type: "direct",
@@ -3178,6 +3290,14 @@ function singbox(plan, secret) {
3178
3290
  ...singAction(rule.then)
3179
3291
  }));
3180
3292
  const routing = { rules };
3293
+ if (program.tun) {
3294
+ rules.unshift({
3295
+ inbound: ["pl-tun"],
3296
+ port: 53,
3297
+ action: "hijack-dns"
3298
+ });
3299
+ if (program.tun.autoRoute) routing.auto_detect_interface = true;
3300
+ }
3181
3301
  if (plan.nativeRuleSets.length) routing.rule_set = plan.nativeRuleSets.map((r) => ({
3182
3302
  type: "remote",
3183
3303
  tag: r.id,
@@ -3200,7 +3320,16 @@ function singbox(plan, secret) {
3200
3320
  tag: "pl-listener",
3201
3321
  listen: "127.0.0.1",
3202
3322
  listen_port: listener.port
3203
- }];
3323
+ }, ...program.tun ? [{
3324
+ type: "tun",
3325
+ tag: "pl-tun",
3326
+ address: [...program.tun.address],
3327
+ stack: program.tun.stack,
3328
+ auto_route: program.tun.autoRoute,
3329
+ strict_route: program.tun.strictRoute,
3330
+ dns_mode: program.tun.dnsMode,
3331
+ ...program.tun.routeExcludeAddress ? { route_exclude_address: [...program.tun.routeExcludeAddress] } : {}
3332
+ }] : []];
3204
3333
  config.dns = {
3205
3334
  servers: [modern ? {
3206
3335
  type: "udp",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proxylang",
3
- "version": "0.10.1",
3
+ "version": "0.11.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": {