proxylang 0.11.0 → 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-BVhtmxFG.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";
@@ -261,6 +262,10 @@ export type Tun = {
261
262
  readonly routeExcludeAddress?: readonly string[];
262
263
  };
263
264
  export type Program = {
265
+ readonly domainMatching?: "prefer-sniffed";
266
+ readonly serverAliases?: Readonly<Record<string, string>>;
267
+ readonly cacheFile?: boolean;
268
+ readonly unsupportedUdp?: "reject";
264
269
  readonly tun?: Tun;
265
270
  readonly dns?: readonly DnsRule[];
266
271
  readonly engine: Engine;
@@ -732,6 +737,10 @@ type ProfileDefinition = {
732
737
  readonly port: number;
733
738
  readonly resolver: string;
734
739
  };
740
+ readonly domainMatching?: "prefer-sniffed";
741
+ readonly serverAliases?: Readonly<Record<string, string>>;
742
+ readonly cacheFile?: boolean;
743
+ readonly unsupportedUdp?: "reject";
735
744
  };
736
745
  };
737
746
  type Profile = DeepReadonly<Omit<ProfileDefinition, "proxies" | "groups" | "routes" | "surge" | "dns"> & {
@@ -1042,6 +1051,7 @@ export declare const singbox: {
1042
1051
  readonly engine: "sing-box";
1043
1052
  readonly format: "source" | "binary";
1044
1053
  readonly intervalSeconds: number;
1054
+ readonly resolve?: boolean;
1045
1055
  }, "engine" | "id" | "type"> & {
1046
1056
  readonly id?: string;
1047
1057
  } & {
@@ -1055,6 +1065,7 @@ export declare const singbox: {
1055
1065
  readonly engine: "sing-box";
1056
1066
  readonly format: "source" | "binary";
1057
1067
  readonly intervalSeconds: number;
1068
+ readonly resolve?: boolean;
1058
1069
  };
1059
1070
  };
1060
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-BVhtmxFG.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
@@ -548,7 +548,8 @@ const nativeRuleSetSchema = z.discriminatedUnion("engine", [
548
548
  ...remoteBase,
549
549
  engine: z.literal("sing-box"),
550
550
  format: z.enum(["source", "binary"]),
551
- intervalSeconds: updateInterval
551
+ intervalSeconds: updateInterval,
552
+ resolve: z.boolean().optional()
552
553
  }),
553
554
  z.strictObject({
554
555
  ...remoteBase,
@@ -764,7 +765,7 @@ const endpointSchema = z.strictObject({
764
765
  exitNode: ip$1.optional(),
765
766
  exitNodeAllowLanAccess: z.boolean().optional()
766
767
  }).refine((endpoint) => endpoint.exitNodeAllowLanAccess === void 0 || endpoint.exitNode !== void 0);
767
- 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);
768
769
  const url$1 = z.string().url().refine((value) => {
769
770
  try {
770
771
  const u = new URL(value);
@@ -836,6 +837,10 @@ const configSchema = z.strictObject({
836
837
  "mihomo",
837
838
  "stash"
838
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(),
839
844
  dns: dnsRulesSchema.optional(),
840
845
  nodes: z.array(nodeSchema),
841
846
  endpoints: z.array(endpointSchema).max(1e3).optional(),
@@ -1042,6 +1047,31 @@ function collectNativeRuleSets(rules, target, diagnostics) {
1042
1047
  return [...found.values()];
1043
1048
  }
1044
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
1045
1075
  //#region src/rules.ts
1046
1076
  function expandRules(entries, diagnostics, path = "routing") {
1047
1077
  const output = [];
@@ -1194,11 +1224,12 @@ function evaluate(condition, request) {
1194
1224
  reason: present ? matched ? "匹配" : "不匹配" : "字段缺失,原子条件为 false"
1195
1225
  };
1196
1226
  }
1197
- function explainRules(rules, fallback, input) {
1227
+ function explainRules(rules, fallback, input, orderedResolve = false) {
1198
1228
  const parsed = requestSchema.safeParse(input);
1199
1229
  if (!parsed.success) throw new Error("INVALID_REQUEST");
1200
1230
  const trace = [];
1201
1231
  for (const rule of rules) {
1232
+ if (orderedResolve && needsResolve(rule.when) && parsed.data.domain && !parsed.data.ip) throw new StaticMetadataUnknownError();
1202
1233
  const condition = evaluate(rule.when, parsed.data);
1203
1234
  trace.push({
1204
1235
  id: rule.id,
@@ -1257,7 +1288,7 @@ function pathsOverlap(a, b) {
1257
1288
  return a === b || a.startsWith(b.endsWith("/") ? b : `${b}/`) || b.startsWith(a.endsWith("/") ? a : `${a}/`);
1258
1289
  }
1259
1290
  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;
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;
1261
1292
  }
1262
1293
  function validateProxyOptions(node, target, diagnostics) {
1263
1294
  if (node.type === "hysteria2") {
@@ -1280,7 +1311,13 @@ function validateProxyOptions(node, target, diagnostics) {
1280
1311
  message: "VLESS 扩展选项仅支持 sing-box 1.14.4"
1281
1312
  });
1282
1313
  if (target.engine !== "surge") {
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({
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({
1284
1321
  severity: "error",
1285
1322
  code: "PROXY_OPTION_UNSUPPORTED",
1286
1323
  target: target.id,
@@ -1302,13 +1339,27 @@ function uuid(token, secret) {
1302
1339
  if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) throw new RenderError("INVALID_UUID_SECRET");
1303
1340
  return value;
1304
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
+ }
1305
1355
  function singboxProxy(node, secret) {
1306
1356
  const result = {
1307
1357
  type: node.type,
1308
1358
  tag: node.id,
1309
1359
  server: node.server,
1310
1360
  server_port: node.port,
1311
- ...node.via ? { detour: node.via } : {}
1361
+ ...node.via ? { detour: node.via } : {},
1362
+ ...node.tcpFastOpen !== void 0 ? { tcp_fast_open: node.tcpFastOpen } : {}
1312
1363
  };
1313
1364
  switch (node.type) {
1314
1365
  case "hysteria2":
@@ -1333,7 +1384,8 @@ function singboxProxy(node, secret) {
1333
1384
  result.password = secret(node.password);
1334
1385
  result.tls = {
1335
1386
  enabled: true,
1336
- ...node.serverName ? { server_name: node.serverName } : {}
1387
+ ...node.serverName ? { server_name: node.serverName } : {},
1388
+ ...node.skipCertVerify !== void 0 ? { insecure: node.skipCertVerify } : {}
1337
1389
  };
1338
1390
  break;
1339
1391
  case "shadowsocks":
@@ -1957,7 +2009,7 @@ function compile(input) {
1957
2009
  const byId = new Map(resources.map((resource) => [resource.id, resource]));
1958
2010
  if (byId.size !== resources.length) error("DUPLICATE_RESOURCE", path, "节点、组与端点共用唯一 ID 命名空间");
1959
2011
  const edges = new Map(resources.map((resource) => [resource.id, "members" in resource ? resource.members : "via" in resource && resource.via ? [resource.via] : []]));
1960
- 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}`, "节点或组引用不存在");
1961
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");
1962
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}`, "端点状态目录不能重复或互为祖先");
1963
2015
  const states = /* @__PURE__ */ new Map();
@@ -1982,7 +2034,7 @@ function compile(input) {
1982
2034
  const validateAction = (action, where, udpPossible) => {
1983
2035
  if (action.type !== "route") return;
1984
2036
  if (!byId.has(action.to)) error("MISSING_REFERENCE", where, "路由出口不存在");
1985
- 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");
1986
2038
  };
1987
2039
  for (const rule of rules) validateAction(rule.then, rule.id, truthPossibilities(rule.when, "udp").includes(true));
1988
2040
  const validateBindings = (entries, prefix) => {
@@ -2018,6 +2070,10 @@ function compile(input) {
2018
2070
  continue;
2019
2071
  }
2020
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);
2021
2077
  if (program.tun) {
2022
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);
2023
2079
  if (unsafeTunResolvers(program).length) error("TUN_DNS_LOOP", path, "TUN DNS 上游不能使用回环、未指定或 TUN 网段地址", target.id);
@@ -2050,27 +2106,34 @@ function compile(input) {
2050
2106
  if (target.engine === "surge") {
2051
2107
  for (const rule of rules) if (logicalDepth(rule.when) > 10) error("LOGICAL_DEPTH", rule.id, "Surge 逻辑条件最多嵌套 10 层", target.id);
2052
2108
  }
2053
- const checkOptions = (condition) => {
2054
- 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);
2055
- if (condition.type === "all" || condition.type === "any") condition.conditions.forEach(checkOptions);
2056
- else if (condition.type === "not") checkOptions(condition.condition);
2057
- 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);
2058
2114
  };
2059
2115
  rules.forEach((rule) => checkOptions(rule.when));
2060
2116
  const nativeRuleSets = collectNativeRuleSets(rules, target, diagnostics);
2061
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;
2062
2119
  plans.push({
2063
2120
  nativeRuleSets,
2064
2121
  target,
2065
2122
  program,
2066
2123
  rules,
2067
2124
  strategySelections: lowered.selections,
2068
- sourceMap: rules.map((rule, nativeIndex) => ({
2069
- rule: rule.id,
2070
- nativeIndex,
2071
- origin: rule.origin
2072
- })),
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
+ }),
2073
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 不创建或清理缓存。无有效缓存且下载失败时拒绝启动。"] : [],
2074
2137
  ...nativeRuleSets.length ? ["原生外部规则由客户端持续下载和解释;静态布尔结果不验证 DNS 等副作用。缓存与下载失败处理沿用客户端机制,fragment 运行方提供工作目录与下载 DNS 路径。"] : [],
2075
2138
  ...program.endpoints?.length ? [
2076
2139
  "Tailscale 需要 with_tailscale 构建标签;运行方负责登录、路由批准及每实例独占身份目录。构建不注册 tailnet。",
@@ -2097,15 +2160,15 @@ function compile(input) {
2097
2160
  }
2098
2161
  let actual;
2099
2162
  try {
2100
- 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"));
2101
2164
  } catch (cause) {
2102
- if (!(cause instanceof StaticRuleSetUnknownError)) throw cause;
2165
+ if (!(cause instanceof StaticRuleSetUnknownError) && !(cause instanceof StaticMetadataUnknownError)) throw cause;
2103
2166
  cases.push({
2104
2167
  id: test.id,
2105
2168
  passed: false,
2106
2169
  code: "CASE_INDETERMINATE"
2107
2170
  });
2108
- error("CASE_INDETERMINATE", `cases.${test.id}`, "外部规则内容未知,无法静态确定首命中");
2171
+ error("CASE_INDETERMINATE", `cases.${test.id}`, "外部规则或所需运行时元数据未知,无法静态确定首命中");
2109
2172
  continue;
2110
2173
  }
2111
2174
  const passed = (test.expect.rule === void 0 || test.expect.rule === actual.rule) && sameAction(test.expect.action, actual.action);
@@ -2140,7 +2203,7 @@ function explain(compilation, target, request) {
2140
2203
  if (!compilation.ok) throw new Error("COMPILATION_FAILED");
2141
2204
  const plan = compilation.plans.find((plan) => plan.target.id === target);
2142
2205
  if (!plan) throw new Error("UNKNOWN_TARGET");
2143
- 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");
2144
2207
  }
2145
2208
  //#endregion
2146
2209
  //#region src/secrets.ts
@@ -2688,7 +2751,11 @@ function defineProfile(input) {
2688
2751
  exactDefinition(input.singBox, [
2689
2752
  "mode",
2690
2753
  "listener",
2691
- "tun"
2754
+ "tun",
2755
+ "domainMatching",
2756
+ "serverAliases",
2757
+ "cacheFile",
2758
+ "unsupportedUdp"
2692
2759
  ]);
2693
2760
  if (!["fragment", "standalone"].includes(input.singBox.mode)) fail("INVALID_PROFILE_DEFINITION");
2694
2761
  if (input.singBox.listener !== void 0) exactDefinition(input.singBox.listener, ["port", "resolver"]);
@@ -2917,8 +2984,7 @@ function compileProfile(input) {
2917
2984
  ] : ["type"]);
2918
2985
  const members = definition.members.map((member) => {
2919
2986
  const action = lower(member);
2920
- if (action.type !== "route") return fail("PROFILE_GROUP_MEMBER_UNSUPPORTED");
2921
- return action.to;
2987
+ return action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
2922
2988
  });
2923
2989
  return {
2924
2990
  ...definition.algorithm,
@@ -2950,7 +3016,11 @@ function compileProfile(input) {
2950
3016
  routing,
2951
3017
  fallback: lower(profile.fallback),
2952
3018
  ...profile.singBox?.listener ? { listener: profile.singBox.listener } : {},
2953
- ...profile.singBox?.tun ? { tun: profile.singBox.tun } : {}
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 }
2954
3024
  } },
2955
3025
  targets: [{
2956
3026
  ...profile.target,
@@ -3087,6 +3157,7 @@ function nativeConstructor(engine) {
3087
3157
  "intervalSeconds",
3088
3158
  "noResolve",
3089
3159
  "includeSniffed",
3160
+ "resolve",
3090
3161
  "behavior",
3091
3162
  "to"
3092
3163
  ]);
@@ -3097,7 +3168,7 @@ function nativeConstructor(engine) {
3097
3168
  "url",
3098
3169
  "format",
3099
3170
  "intervalSeconds",
3100
- ...engine === "surge" ? ["noResolve", "includeSniffed"] : engine === "mihomo" ? ["behavior"] : []
3171
+ ...engine === "surge" ? ["noResolve", "includeSniffed"] : engine === "mihomo" ? ["behavior"] : ["resolve"]
3101
3172
  ]);
3102
3173
  const parsed = nativeRuleSetSchema.safeParse({
3103
3174
  ...engine === "surge" ? { format: "rule-set" } : {},
@@ -3272,24 +3343,38 @@ function singbox(plan, secret) {
3272
3343
  const { program, target } = plan;
3273
3344
  const modern = targetCatalog.find((entry) => entry.engine === target.engine && entry.version === target.version)?.dns === "typed";
3274
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;
3275
3348
  const outbounds = [{
3276
3349
  type: "direct",
3277
3350
  tag: DIRECT,
3278
3351
  ...!modern && standalone ? { domain_strategy: "prefer_ipv4" } : {}
3279
3352
  }];
3353
+ if (program.groups.some((group) => group.members.includes("REJECT"))) outbounds.push({
3354
+ type: "block",
3355
+ tag: "pl-reject"
3356
+ });
3280
3357
  for (const node of program.nodes) outbounds.push({
3281
- ...singboxProxy(node, secret),
3358
+ ...singboxProxy(aliasProxyServer(node, program.serverAliases), secret),
3282
3359
  ...modern && program.dns?.length ? { domain_resolver: {
3283
- server: DNS,
3360
+ server: domainResolver,
3284
3361
  strategy: "prefer_ipv4"
3285
3362
  } } : {}
3286
3363
  });
3287
- for (const group of program.groups) outbounds.push(singboxGroup(group));
3288
- 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
+ }] : [], {
3289
3370
  ...singCondition(rule.when),
3290
3371
  ...singAction(rule.then)
3291
- }));
3372
+ }]);
3292
3373
  const routing = { rules };
3374
+ if (program.domainMatching === "prefer-sniffed") rules.unshift({
3375
+ action: "sniff",
3376
+ sniffer: ["http", "tls"]
3377
+ });
3293
3378
  if (program.tun) {
3294
3379
  rules.unshift({
3295
3380
  inbound: ["pl-tun"],
@@ -3298,6 +3383,10 @@ function singbox(plan, secret) {
3298
3383
  });
3299
3384
  if (program.tun.autoRoute) routing.auto_detect_interface = true;
3300
3385
  }
3386
+ if (routedDns) rules.unshift({
3387
+ inbound: ["pl-dns-listener"],
3388
+ action: "hijack-dns"
3389
+ });
3301
3390
  if (plan.nativeRuleSets.length) routing.rule_set = plan.nativeRuleSets.map((r) => ({
3302
3391
  type: "remote",
3303
3392
  tag: r.id,
@@ -3313,23 +3402,34 @@ function singbox(plan, secret) {
3313
3402
  outbounds,
3314
3403
  route: routing
3315
3404
  };
3405
+ if (program.cacheFile) config.experimental = { cache_file: { enabled: true } };
3316
3406
  if (standalone) {
3317
3407
  const listener = program.listener;
3318
- config.inbounds = [{
3319
- type: "mixed",
3320
- tag: "pl-listener",
3321
- listen: "127.0.0.1",
3322
- listen_port: listener.port
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
- }] : []];
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
+ ];
3333
3433
  config.dns = {
3334
3434
  servers: [modern ? {
3335
3435
  type: "udp",
@@ -3342,15 +3442,22 @@ function singbox(plan, secret) {
3342
3442
  detour: DIRECT
3343
3443
  }],
3344
3444
  final: DNS,
3345
- strategy: "prefer_ipv4"
3445
+ strategy: "prefer_ipv4",
3446
+ ...program.domainMatching ? { reverse_mapping: true } : {}
3346
3447
  };
3347
- if (modern && !program.dns?.length) routing.default_domain_resolver = {
3348
- server: DNS,
3448
+ if (modern && (!program.dns?.length || target.version === "1.14.4")) routing.default_domain_resolver = {
3449
+ server: domainResolver,
3349
3450
  strategy: "prefer_ipv4"
3350
3451
  };
3351
3452
  }
3352
3453
  if (program.dns?.length) {
3353
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
+ });
3354
3461
  dns.rules = program.dns.map((rule, index) => {
3355
3462
  const tag = `pl-domain-dns-${index}`;
3356
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.11.0",
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": {