proxylang 0.3.0 → 0.4.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 { Q as requestSchema, R as compile, U as targetCatalog, i as buildToDirectory, n as profileBuildFailure, q as StaticRuleSetUnknownError, r as runBuild, z as explain } from "./profile-build-CA9qC6N2.js";
2
+ import { Q as requestSchema, R as compile, U as targetCatalog, i as buildToDirectory, n as profileBuildFailure, q as StaticRuleSetUnknownError, r as runBuild, z as explain } from "./profile-build-DYCbePBx.js";
3
3
  import { open } from "node:fs/promises";
4
4
  import { resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
package/dist/index.d.ts CHANGED
@@ -25,7 +25,7 @@ export type NativeRuleSet = {
25
25
  readonly intervalSeconds: number;
26
26
  });
27
27
  export type Match = NamedRuleSet | NativeRuleSet | {
28
- readonly type: "domain" | "domainSuffix" | "ipCidr" | "sourceIp";
28
+ readonly type: "domain" | "domainSuffix" | "ipCidr" | "sourceIp" | "processName";
29
29
  readonly value: string;
30
30
  } | {
31
31
  readonly type: "port" | "sourcePort";
@@ -225,7 +225,12 @@ export type Group = Exclude<ConcreteGroup, {
225
225
  readonly type: "surge-smart";
226
226
  }> | Strategy;
227
227
  export type Engine = "surge" | "sing-box" | "mihomo" | "stash";
228
+ export type DnsRule = {
229
+ readonly pattern: string;
230
+ readonly server: string;
231
+ };
228
232
  export type Program = {
233
+ readonly dns?: readonly DnsRule[];
229
234
  readonly engine: Engine;
230
235
  readonly nodes: readonly ProxyNode[];
231
236
  readonly endpoints?: readonly TailscaleEndpoint[];
@@ -250,6 +255,7 @@ export type Request = {
250
255
  readonly domain?: string;
251
256
  readonly ip?: string;
252
257
  readonly sourceIp?: string;
258
+ readonly processName?: string;
253
259
  readonly port?: number;
254
260
  readonly sourcePort?: number;
255
261
  };
@@ -660,6 +666,7 @@ type SurgeConfig = DeepReadonly<Pick<SurgeProfileInput, "managed" | "names">> &
660
666
  readonly hosts?: Fragments<DeepReadonly<SurgeHost>>;
661
667
  };
662
668
  type ProfileDefinition = {
669
+ readonly dns?: Fragments<DnsRule>;
663
670
  readonly target: SurgeProfileInput["target"] | {
664
671
  readonly engine: "sing-box";
665
672
  readonly platform: "macos" | "linux";
@@ -678,7 +685,8 @@ type ProfileDefinition = {
678
685
  };
679
686
  };
680
687
  };
681
- type Profile = DeepReadonly<Omit<ProfileDefinition, "proxies" | "groups" | "routes" | "surge"> & {
688
+ type Profile = DeepReadonly<Omit<ProfileDefinition, "proxies" | "groups" | "routes" | "surge" | "dns"> & {
689
+ readonly dns?: readonly DnsRule[];
682
690
  readonly proxies: readonly ProfileProxy[];
683
691
  readonly groups: readonly ProxyGroupDefinition[];
684
692
  readonly routes: readonly RouteDefinition[];
@@ -717,6 +725,7 @@ declare function proxyBuilder<N extends ProxyNode>(node: N): ProxyBuilder<Extrac
717
725
  //#region src/dsl.d.ts
718
726
  export declare const ruleSet: (definition: Omit<NamedRuleSet, "type">) => NamedRuleSet;
719
727
  export declare const match: {
728
+ processName: (value: string) => Match;
720
729
  ruleSet: (set: NamedRuleSet) => Match;
721
730
  domain: (value: string) => Match;
722
731
  domainSuffix: (value: string) => Match;
@@ -983,4 +992,8 @@ export declare function runBuild(input: BuildDefinition, output: string, options
983
992
  readonly validation?: boolean;
984
993
  }): Promise<ProfileBuildResult>;
985
994
  //#endregion
995
+ //#region src/proxy-id.d.ts
996
+ /** Stable identity independent of engine and mutable metadata. */
997
+ export declare function proxyId(provider: string, label: string): string;
998
+ //#endregion
986
999
  export type { Artifact, BuildContext, BuildDefinition, BuildResult, CaseResult, Compilation, DeepReadonly, Fragments, Profile, ProfileBuildResult, ProfileCompilation, ProfileCondition, ProfileDefinition, ProfileDestination, ProfileProxy, ProxyBuilder, ProxyGroupDefinition, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, RouteDefinition, StrategyGroupCompilation, StrategyGroupInput, SurgeCondition, SurgeConfig, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileInput, SurgeRule, SurgeTunnel, TargetPlan };
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
- import { A as defineRoute, B as compileStrategyGroups, C as strategy, D as defineProfile, E as compileProfile, F as renderSurgeProfile, G as surgeProxy, H as nativeNameSchema, I as renderSurgeProfiles, J as assertData, K as validateProxyOptions, L as secretReader, M as outbound, N as selectProxies, O as ProfileDefinitionError, P as compileSurgeProfile, R as compile, S as slot, T as use, U as targetCatalog, V as isReservedNativeName, W as RenderError, X as idSchema, Y as deepFreeze, Z as nodeSchema, _ as ruleSet, a as render, b as sequence, c as direct, d as mihomo, f as policy, g as rule, h as route, i as buildToDirectory, j as defineRoutes, k as defineProxyGroup, l as group, m as reject, o as block, p as proxy, q as StaticRuleSetUnknownError, r as runBuild, s as defineConfig, t as defineBuild, u as match, v as secret, w as surge, x as singbox, y as selectNodes, z as explain } from "./profile-build-CA9qC6N2.js";
1
+ import { A as defineRoute, B as compileStrategyGroups, C as strategy, D as defineProfile, E as compileProfile, F as renderSurgeProfile, G as surgeProxy, H as nativeNameSchema, I as renderSurgeProfiles, J as assertData, K as validateProxyOptions, L as secretReader, M as outbound, N as selectProxies, O as ProfileDefinitionError, P as compileSurgeProfile, R as compile, S as slot, T as use, U as targetCatalog, V as isReservedNativeName, W as RenderError, X as idSchema, Y as deepFreeze, Z as nodeSchema, _ as ruleSet, a as render, b as sequence, c as direct, d as mihomo, f as policy, g as rule, h as route, i as buildToDirectory, j as defineRoutes, k as defineProxyGroup, l as group, m as reject, o as block, p as proxy, q as StaticRuleSetUnknownError, r as runBuild, s as defineConfig, t as defineBuild, u as match, v as secret, w as surge, x as singbox, y as selectNodes, z as explain } from "./profile-build-DYCbePBx.js";
2
2
  import { z } from "zod";
3
+ import { createHash } from "node:crypto";
3
4
  //#region src/proxy-fragments.ts
4
5
  const inputSchema = z.strictObject({
5
6
  target: z.strictObject({
@@ -129,4 +130,11 @@ function renderProxyNodes(compilation, resolveSecret) {
129
130
  });
130
131
  }
131
132
  //#endregion
132
- export { ProfileDefinitionError, RenderError, StaticRuleSetUnknownError, block, buildToDirectory, compile, compileProfile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineBuild, defineConfig, defineProfile, defineProxyGroup, defineRoute, defineRoutes, direct, explain, group, match, mihomo, outbound, policy, proxy, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, runBuild, secret, selectNodes, selectProxies, sequence, singbox, slot, strategy, surge, targetCatalog, use };
133
+ //#region src/proxy-id.ts
134
+ /** Stable identity independent of engine and mutable metadata. */
135
+ function proxyId(provider, label) {
136
+ if (typeof provider !== "string" || !provider.length || typeof label !== "string" || !label.length) throw new Error("INVALID_PROXY_ID_INPUT");
137
+ return `node-${createHash("sha256").update(JSON.stringify([provider, label])).digest("hex").slice(0, 16)}`;
138
+ }
139
+ //#endregion
140
+ export { ProfileDefinitionError, RenderError, StaticRuleSetUnknownError, block, buildToDirectory, compile, compileProfile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineBuild, defineConfig, defineProfile, defineProxyGroup, defineRoute, defineRoutes, direct, explain, group, match, mihomo, outbound, policy, proxy, proxyId, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, runBuild, secret, selectNodes, selectProxies, sequence, singbox, slot, strategy, surge, targetCatalog, use };
@@ -1,119 +1,54 @@
1
1
  import { isIP } from "node:net";
2
- import ipaddr from "ipaddr.js";
3
2
  import { z } from "zod";
3
+ import ipaddr from "ipaddr.js";
4
4
  import { stringify } from "yaml";
5
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
- //#region src/rulesets.ts
9
- function canonical(value) {
10
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
11
- if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
12
- return JSON.stringify(value);
13
- }
14
- function validateRuleSets(entries, engine, diagnostics, path) {
15
- const definitions = /* @__PURE__ */ new Map();
16
- const urls = /* @__PURE__ */ new Map();
17
- const error = (code) => diagnostics.push({
18
- severity: "error",
19
- code,
20
- path,
21
- message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
22
- });
23
- const visit = (m) => {
24
- if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
25
- const key = canonical(m);
26
- if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
27
- definitions.set(m.id, key);
28
- if (m.type === "ruleSet") visit(m.when);
29
- else {
30
- if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
31
- if (m.engine === "surge") {
32
- const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
33
- const url = new URL(m.url).href;
34
- if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
35
- urls.set(url, settings);
36
- }
37
- }
38
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
39
- else if (m.type === "not") visit(m.condition);
40
- };
41
- const walk = (items) => {
42
- for (const item of items) if (item.type === "rule") visit(item.when);
43
- else if (item.type === "block") {
44
- if (item.when) visit(item.when);
45
- walk(item.rules);
46
- } else walk(item.policy.rules);
47
- };
48
- walk(entries);
49
- }
50
- function lowerRuleSets(rules, diagnostics, path) {
51
- let count = 0;
52
- let origins = 0;
53
- const lower = (m, origin, depth) => {
54
- if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
55
- if (m.type === "ruleSet") {
56
- origin.push(`rule-set:${m.id}`);
57
- return lower(m.when, origin, depth + 1);
58
- }
59
- if (m.type === "all" || m.type === "any") return {
60
- ...m,
61
- conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
62
- };
63
- if (m.type === "not") return {
64
- ...m,
65
- condition: lower(m.condition, origin, depth + 1)
66
- };
67
- return m;
68
- };
8
+ //#region src/dns.ts
9
+ const domain$2 = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
10
+ function dohUrl(value) {
11
+ const url = new URL(value);
12
+ if (!/^https:\/\/[^/]+\//.test(value)) url.pathname = "/dns-query";
13
+ return url;
14
+ }
15
+ const server = z.string().max(2048).refine((value) => {
16
+ if (isIP(value) && !value.includes("%")) return true;
17
+ if (!value.startsWith("https://") || /[\s\p{C},()\\"'?#]/u.test(value)) return false;
69
18
  try {
70
- if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
71
- return rules.map((r) => {
72
- const origin = [...r.origin];
73
- const when = lower(r.when, origin, 0);
74
- origins += origin.length;
75
- if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
76
- return {
77
- ...r,
78
- when,
79
- origin
80
- };
81
- });
19
+ const url = new URL(value);
20
+ const authority = value.slice(8).split("/")[0];
21
+ const path = value.slice(8 + authority.length);
22
+ return !url.username && !url.password && !authority.endsWith(":") && !!url.hostname && (!path || url.pathname === path);
82
23
  } catch {
83
- diagnostics.push({
84
- severity: "error",
85
- code: "EXPANSION_LIMIT",
86
- path,
87
- message: "展开规则、条件或来源超过预算"
88
- });
89
- return [];
24
+ return false;
90
25
  }
91
- }
92
- function collectNativeRuleSets(rules, target, diagnostics) {
93
- const found = /* @__PURE__ */ new Map();
94
- const visit = (m, nested) => {
95
- if (m.type === "nativeRuleSet") {
96
- found.set(m.id, m);
97
- if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
98
- severity: "error",
99
- code: "RULESET_COMPOSITION_UNSUPPORTED",
100
- target: target.id,
101
- path: `targets.${target.id}.ruleSets.${m.id}`,
102
- message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
26
+ });
27
+ const dnsRulesSchema = z.array(z.strictObject({
28
+ pattern: z.string().min(1).max(253).refine((value) => domain$2.test(value.startsWith("*.") ? value.slice(2) : value)),
29
+ server
30
+ })).max(2e3).superRefine((rules, ctx) => {
31
+ if (rules.length > 2e3 || rules.some((rule) => rule.pattern.length > 253 || rule.server.length > 2048)) return;
32
+ for (let i = 0; i < rules.length; i++) for (let j = 0; j < i; j++) {
33
+ const a = rules[i], b = rules[j];
34
+ const x = a.pattern.toLowerCase(), y = b.pattern.toLowerCase();
35
+ if (x === y || overlap(x, y) && a.server !== b.server) {
36
+ ctx.addIssue({
37
+ code: "custom",
38
+ message: "DNS_RULE_CONFLICT"
103
39
  });
104
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
105
- else if (m.type === "not") visit(m.condition, true);
106
- else if (m.type === "ruleSet") visit(m.when, nested);
107
- };
108
- rules.forEach((r) => visit(r.when, false));
109
- for (const r of found.values()) diagnostics.push({
110
- severity: "warning",
111
- code: "EXTERNAL_RULESET_UNVERIFIED",
112
- target: target.id,
113
- path: `targets.${target.id}.ruleSets.${r.id}`,
114
- message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
115
- });
116
- return [...found.values()];
40
+ return;
41
+ }
42
+ }
43
+ });
44
+ function overlap(a, b) {
45
+ const wildA = a.startsWith("*."), wildB = b.startsWith("*.");
46
+ if (wildA && wildB) return a.slice(1).endsWith(b.slice(1)) || b.slice(1).endsWith(a.slice(1));
47
+ return wildA ? b.endsWith(a.slice(1)) : wildB && a.endsWith(b.slice(1));
48
+ }
49
+ function dnsCondition(rule) {
50
+ const pattern = rule.pattern.toLowerCase();
51
+ return pattern.startsWith("*.") ? { domain_regex: [`^.+\\.${pattern.slice(2).replaceAll(".", "\\.")}$`] } : { domain: [pattern] };
117
52
  }
118
53
  //#endregion
119
54
  //#region src/schema.ts
@@ -130,6 +65,7 @@ const cidr$1 = z.string().refine((x) => {
130
65
  return false;
131
66
  }
132
67
  });
68
+ const processNameSchema = z.string().min(1).max(255).regex(/^[^/\\*?[\],()\p{C}]+$/u);
133
69
  const port$1 = z.number().int().min(1).max(65535);
134
70
  const network = z.enum(["tcp", "udp"]);
135
71
  const atom$2 = (type, value) => z.strictObject({
@@ -184,7 +120,8 @@ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
184
120
  atom$2("domain", domain$1),
185
121
  atom$2("domainSuffix", domain$1),
186
122
  atom$2("ipCidr", cidr$1),
187
- atom$2("sourceIp", cidr$1),
123
+ atom$2("sourceIp", z.union([ip$1, cidr$1])),
124
+ atom$2("processName", processNameSchema),
188
125
  z.strictObject({
189
126
  type: z.literal("port"),
190
127
  from: port$1,
@@ -402,6 +339,7 @@ const requestSchema = z.strictObject({
402
339
  domain: domain$1.optional(),
403
340
  ip: ip$1.optional(),
404
341
  sourceIp: ip$1.optional(),
342
+ processName: processNameSchema.optional(),
405
343
  port: port$1.optional(),
406
344
  sourcePort: port$1.optional()
407
345
  });
@@ -413,6 +351,7 @@ const configSchema = z.strictObject({
413
351
  "mihomo",
414
352
  "stash"
415
353
  ]),
354
+ dns: dnsRulesSchema.optional(),
416
355
  nodes: z.array(nodeSchema),
417
356
  endpoints: z.array(endpointSchema).max(1e3).optional(),
418
357
  groups: z.array(groupSchema$1),
@@ -490,6 +429,117 @@ function deepFreeze(value) {
490
429
  return value;
491
430
  }
492
431
  //#endregion
432
+ //#region src/rulesets.ts
433
+ function canonical(value) {
434
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
435
+ if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
436
+ return JSON.stringify(value);
437
+ }
438
+ function validateRuleSets(entries, engine, diagnostics, path) {
439
+ const definitions = /* @__PURE__ */ new Map();
440
+ const urls = /* @__PURE__ */ new Map();
441
+ const error = (code) => diagnostics.push({
442
+ severity: "error",
443
+ code,
444
+ path,
445
+ message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
446
+ });
447
+ const visit = (m) => {
448
+ if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
449
+ const key = canonical(m);
450
+ if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
451
+ definitions.set(m.id, key);
452
+ if (m.type === "ruleSet") visit(m.when);
453
+ else {
454
+ if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
455
+ if (m.engine === "surge") {
456
+ const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
457
+ const url = new URL(m.url).href;
458
+ if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
459
+ urls.set(url, settings);
460
+ }
461
+ }
462
+ } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
463
+ else if (m.type === "not") visit(m.condition);
464
+ };
465
+ const walk = (items) => {
466
+ for (const item of items) if (item.type === "rule") visit(item.when);
467
+ else if (item.type === "block") {
468
+ if (item.when) visit(item.when);
469
+ walk(item.rules);
470
+ } else walk(item.policy.rules);
471
+ };
472
+ walk(entries);
473
+ }
474
+ function lowerRuleSets(rules, diagnostics, path) {
475
+ let count = 0;
476
+ let origins = 0;
477
+ const lower = (m, origin, depth) => {
478
+ if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
479
+ if (m.type === "ruleSet") {
480
+ origin.push(`rule-set:${m.id}`);
481
+ return lower(m.when, origin, depth + 1);
482
+ }
483
+ if (m.type === "all" || m.type === "any") return {
484
+ ...m,
485
+ conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
486
+ };
487
+ if (m.type === "not") return {
488
+ ...m,
489
+ condition: lower(m.condition, origin, depth + 1)
490
+ };
491
+ return m;
492
+ };
493
+ try {
494
+ if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
495
+ return rules.map((r) => {
496
+ const origin = [...r.origin];
497
+ const when = lower(r.when, origin, 0);
498
+ origins += origin.length;
499
+ if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
500
+ return {
501
+ ...r,
502
+ when,
503
+ origin
504
+ };
505
+ });
506
+ } catch {
507
+ diagnostics.push({
508
+ severity: "error",
509
+ code: "EXPANSION_LIMIT",
510
+ path,
511
+ message: "展开规则、条件或来源超过预算"
512
+ });
513
+ return [];
514
+ }
515
+ }
516
+ function collectNativeRuleSets(rules, target, diagnostics) {
517
+ const found = /* @__PURE__ */ new Map();
518
+ const visit = (m, nested) => {
519
+ if (m.type === "nativeRuleSet") {
520
+ found.set(m.id, m);
521
+ if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
522
+ severity: "error",
523
+ code: "RULESET_COMPOSITION_UNSUPPORTED",
524
+ target: target.id,
525
+ path: `targets.${target.id}.ruleSets.${m.id}`,
526
+ message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
527
+ });
528
+ } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
529
+ else if (m.type === "not") visit(m.condition, true);
530
+ else if (m.type === "ruleSet") visit(m.when, nested);
531
+ };
532
+ rules.forEach((r) => visit(r.when, false));
533
+ for (const r of found.values()) diagnostics.push({
534
+ severity: "warning",
535
+ code: "EXTERNAL_RULESET_UNVERIFIED",
536
+ target: target.id,
537
+ path: `targets.${target.id}.ruleSets.${r.id}`,
538
+ message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
539
+ });
540
+ return [...found.values()];
541
+ }
542
+ //#endregion
493
543
  //#region src/rules.ts
494
544
  function expandRules(entries, diagnostics, path = "routing") {
495
545
  const output = [];
@@ -563,7 +613,7 @@ function expandRules(entries, diagnostics, path = "routing") {
563
613
  function inCidr(address, cidr) {
564
614
  if (!address) return false;
565
615
  const parsed = ipaddr.parse(address);
566
- const [base, bits] = ipaddr.parseCIDR(cidr);
616
+ const [base, bits] = ipaddr.parseCIDR(cidr.includes("/") ? cidr : `${cidr}/${cidr.includes(":") ? 128 : 32}`);
567
617
  return parsed.kind() === base.kind() && parsed.match(base, bits);
568
618
  }
569
619
  var StaticRuleSetUnknownError = class extends Error {
@@ -613,6 +663,10 @@ function evaluate(condition, request) {
613
663
  present = request.ip !== void 0;
614
664
  matched = inCidr(request.ip, condition.value);
615
665
  break;
666
+ case "processName":
667
+ present = request.processName !== void 0;
668
+ matched = request.processName === condition.value;
669
+ break;
616
670
  case "sourceIp":
617
671
  present = request.sourceIp !== void 0;
618
672
  matched = inCidr(request.sourceIp, condition.value);
@@ -909,7 +963,8 @@ function conditionText$1(condition) {
909
963
  case "domain": return `DOMAIN,${condition.value}`;
910
964
  case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
911
965
  case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
912
- case "sourceIp": return `SRC-IP-CIDR,${condition.value}`;
966
+ case "processName": return `PROCESS-NAME,${condition.value}`;
967
+ case "sourceIp": return `SRC-IP-CIDR,${condition.value.includes("/") ? condition.value : `${condition.value}/${condition.value.includes(":") ? 128 : 32}`}`;
913
968
  case "network": return `NETWORK,${condition.value}`;
914
969
  case "port":
915
970
  case "sourcePort": return `${condition.type === "port" ? "DST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
@@ -1283,7 +1338,7 @@ function compile(input) {
1283
1338
  }
1284
1339
  const parsed = configSchema.safeParse(input);
1285
1340
  if (!parsed.success) {
1286
- for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
1341
+ for (const issue of parsed.error.issues.slice(0, 20)) error(issue.message === "DNS_RULE_CONFLICT" ? "DNS_RULE_CONFLICT" : "INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
1287
1342
  return deepFreeze({
1288
1343
  ok: false,
1289
1344
  diagnostics,
@@ -1371,6 +1426,10 @@ function compile(input) {
1371
1426
  if (program.engine !== target.engine) error("ENGINE_MISMATCH", path, "平台程序与目标引擎不一致", target.id);
1372
1427
  if (target.mode === "standalone" && !program.listener) error("LISTENER_REQUIRED", path, "standalone 必须声明 loopback listener 与 IP DNS resolver", target.id);
1373
1428
  if (target.mode !== "standalone" && program.listener) error("UNUSED_LISTENER", path, "fragment 不能静默忽略 listener;请使用独立程序或 standalone 目标", target.id);
1429
+ if (program.dns?.length) {
1430
+ if (target.engine !== "sing-box") error("DNS_TARGET_UNSUPPORTED", path, "通用 DNS 需要 sing-box standalone 或 Surge Profile", target.id);
1431
+ else if (target.mode !== "standalone") error("DNS_MODE_UNSUPPORTED", path, "通用 DNS 需要 standalone", target.id);
1432
+ }
1374
1433
  for (const endpoint of program.endpoints ?? []) {
1375
1434
  if (!descriptor.endpoints.includes(endpoint.type)) error("ENDPOINT_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 端点仅支持 sing-box 1.12.0", target.id);
1376
1435
  if (target.mode !== "standalone") error("ENDPOINT_MODE_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 需要 standalone 的普通 DNS/final 隔离引导解析", target.id);
@@ -2315,7 +2374,8 @@ function defineProfile(input) {
2315
2374
  "routes",
2316
2375
  "fallback",
2317
2376
  "surge",
2318
- "singBox"
2377
+ "singBox",
2378
+ "dns"
2319
2379
  ]);
2320
2380
  exactDefinition(input.target, [
2321
2381
  "engine",
@@ -2351,6 +2411,11 @@ function defineProfile(input) {
2351
2411
  const proxies = flatten(input.proxies);
2352
2412
  const groups = flatten(input.groups);
2353
2413
  const routes = flatten(input.routes);
2414
+ const dns = input.dns === void 0 ? void 0 : flatten(input.dns);
2415
+ if (dns) {
2416
+ const checked = dnsRulesSchema.safeParse(dns);
2417
+ if (!checked.success) fail(checked.error.issues.some((issue) => issue.message === "DNS_RULE_CONFLICT") ? "DNS_RULE_CONFLICT" : "INVALID_DNS_RULES");
2418
+ }
2354
2419
  let surge;
2355
2420
  if (input.surge !== void 0) {
2356
2421
  let general;
@@ -2388,9 +2453,11 @@ function defineProfile(input) {
2388
2453
  ...input.surge.hosts === void 0 ? {} : { hosts: flatten(input.surge.hosts) }
2389
2454
  };
2390
2455
  }
2391
- const { surge: _surge, proxies: _proxies, groups: _groups, routes: _routes, ...rest } = input;
2456
+ if (dns?.length && surge?.hosts?.length) fail("DNS_HOSTS_CONFLICT");
2457
+ const { dns: _dns, surge: _surge, proxies: _proxies, groups: _groups, routes: _routes, ...rest } = input;
2392
2458
  return snapshotProfile({
2393
2459
  ...rest,
2460
+ ...dns === void 0 ? {} : { dns },
2394
2461
  proxies,
2395
2462
  groups,
2396
2463
  routes,
@@ -2452,6 +2519,7 @@ function compileProfile(input) {
2452
2519
  const compilation = compileSurgeProfile(lowerSurgeProfile({
2453
2520
  target: profile.target,
2454
2521
  ...profile.surge,
2522
+ ...profile.dns?.length ? { hosts: profile.dns } : {},
2455
2523
  nodes,
2456
2524
  tunnels: endpoints,
2457
2525
  groups: profile.groups,
@@ -2497,55 +2565,58 @@ function compileProfile(input) {
2497
2565
  to: destination.id
2498
2566
  };
2499
2567
  };
2568
+ const groups = profile.groups.map((definition) => {
2569
+ exactDefinition(definition, [
2570
+ "type",
2571
+ "id",
2572
+ "name",
2573
+ "algorithm",
2574
+ "members",
2575
+ "url",
2576
+ "intervalSeconds",
2577
+ "timeoutSeconds"
2578
+ ]);
2579
+ if (definition.type !== "proxy-group" || typeof definition.name !== "string" || !definition.name.trim()) fail("INVALID_GROUP_DEFINITION");
2580
+ if (definition.url !== void 0 || definition.intervalSeconds !== void 0 || definition.timeoutSeconds !== void 0) fail("PROFILE_GROUP_OPTIONS_UNSUPPORTED");
2581
+ exactDefinition(definition.algorithm, definition.algorithm.type === "urltest" ? [
2582
+ "type",
2583
+ "url",
2584
+ "intervalSeconds",
2585
+ "toleranceMs"
2586
+ ] : ["type"]);
2587
+ const members = definition.members.map((member) => {
2588
+ const action = lower(member);
2589
+ if (action.type !== "route") return fail("PROFILE_GROUP_MEMBER_UNSUPPORTED");
2590
+ return action.to;
2591
+ });
2592
+ return {
2593
+ ...definition.algorithm,
2594
+ id: definition.id,
2595
+ members
2596
+ };
2597
+ });
2598
+ const routing = profile.routes.map((route, index) => {
2599
+ exactDefinition(route, [
2600
+ "type",
2601
+ "when",
2602
+ "to"
2603
+ ]);
2604
+ if (route.type !== "route") fail("INVALID_ROUTE_DEFINITION");
2605
+ return {
2606
+ type: "rule",
2607
+ id: `route-${index + 1}`,
2608
+ when: route.when,
2609
+ then: lower(route.to)
2610
+ };
2611
+ });
2500
2612
  const compilation = compile(snapshotDefinition({
2501
2613
  programs: { profile: {
2502
2614
  engine: "sing-box",
2615
+ ...profile.dns === void 0 ? {} : { dns: profile.dns },
2503
2616
  nodes,
2504
2617
  endpoints,
2505
- groups: profile.groups.map((definition) => {
2506
- exactDefinition(definition, [
2507
- "type",
2508
- "id",
2509
- "name",
2510
- "algorithm",
2511
- "members",
2512
- "url",
2513
- "intervalSeconds",
2514
- "timeoutSeconds"
2515
- ]);
2516
- if (definition.type !== "proxy-group" || typeof definition.name !== "string" || !definition.name.trim()) fail("INVALID_GROUP_DEFINITION");
2517
- if (definition.url !== void 0 || definition.intervalSeconds !== void 0 || definition.timeoutSeconds !== void 0) fail("PROFILE_GROUP_OPTIONS_UNSUPPORTED");
2518
- exactDefinition(definition.algorithm, definition.algorithm.type === "urltest" ? [
2519
- "type",
2520
- "url",
2521
- "intervalSeconds",
2522
- "toleranceMs"
2523
- ] : ["type"]);
2524
- const members = definition.members.map((member) => {
2525
- const action = lower(member);
2526
- if (action.type !== "route") return fail("PROFILE_GROUP_MEMBER_UNSUPPORTED");
2527
- return action.to;
2528
- });
2529
- return {
2530
- ...definition.algorithm,
2531
- id: definition.id,
2532
- members
2533
- };
2534
- }),
2535
- routing: profile.routes.map((route, index) => {
2536
- exactDefinition(route, [
2537
- "type",
2538
- "when",
2539
- "to"
2540
- ]);
2541
- if (route.type !== "route") fail("INVALID_ROUTE_DEFINITION");
2542
- return {
2543
- type: "rule",
2544
- id: `route-${index + 1}`,
2545
- when: route.when,
2546
- then: lower(route.to)
2547
- };
2548
- }),
2618
+ groups,
2619
+ routing,
2549
2620
  fallback: lower(profile.fallback),
2550
2621
  ...profile.singBox?.listener ? { listener: profile.singBox.listener } : {}
2551
2622
  } },
@@ -2593,6 +2664,13 @@ const ruleSet = (definition) => ({
2593
2664
  type: "ruleSet"
2594
2665
  });
2595
2666
  const match = {
2667
+ processName: (value) => {
2668
+ if (!processNameSchema.safeParse(value).success) throw new Error("INVALID_PROCESS_NAME");
2669
+ return {
2670
+ type: "processName",
2671
+ value
2672
+ };
2673
+ },
2596
2674
  ruleSet: (set) => set,
2597
2675
  domain: (value) => ({
2598
2676
  type: "domain",
@@ -2770,7 +2848,8 @@ function singCondition(condition) {
2770
2848
  case "domain": return { domain: [condition.value] };
2771
2849
  case "domainSuffix": return { domain_suffix: [condition.value] };
2772
2850
  case "ipCidr": return { ip_cidr: [condition.value] };
2773
- case "sourceIp": return { source_ip_cidr: [condition.value] };
2851
+ case "processName": return { process_name: [condition.value] };
2852
+ case "sourceIp": return { source_ip_cidr: [condition.value.includes("/") ? condition.value : `${condition.value}/${isIP(condition.value) === 6 ? 128 : 32}`] };
2774
2853
  case "network": return { network: [condition.value] };
2775
2854
  case "port":
2776
2855
  case "sourcePort": {
@@ -2798,7 +2877,13 @@ function singbox(plan, secret) {
2798
2877
  tag: DIRECT,
2799
2878
  ...!modern && standalone ? { domain_strategy: "prefer_ipv4" } : {}
2800
2879
  }];
2801
- for (const node of program.nodes) outbounds.push(singboxProxy(node, secret));
2880
+ for (const node of program.nodes) outbounds.push({
2881
+ ...singboxProxy(node, secret),
2882
+ ...modern && program.dns?.length ? { domain_resolver: {
2883
+ server: DNS,
2884
+ strategy: "prefer_ipv4"
2885
+ } } : {}
2886
+ });
2802
2887
  for (const group of program.groups) outbounds.push(singboxGroup(group));
2803
2888
  const rules = plan.rules.map((rule) => ({
2804
2889
  ...singCondition(rule.when),
@@ -2833,8 +2918,7 @@ function singbox(plan, secret) {
2833
2918
  type: "udp",
2834
2919
  tag: DNS,
2835
2920
  server: listener.resolver,
2836
- server_port: 53,
2837
- detour: DIRECT
2921
+ server_port: 53
2838
2922
  } : {
2839
2923
  tag: DNS,
2840
2924
  address: `udp://${isIP(listener.resolver) === 6 ? `[${listener.resolver}]` : listener.resolver}`,
@@ -2843,11 +2927,51 @@ function singbox(plan, secret) {
2843
2927
  final: DNS,
2844
2928
  strategy: "prefer_ipv4"
2845
2929
  };
2846
- if (modern) routing.default_domain_resolver = {
2930
+ if (modern && !program.dns?.length) routing.default_domain_resolver = {
2847
2931
  server: DNS,
2848
2932
  strategy: "prefer_ipv4"
2849
2933
  };
2850
2934
  }
2935
+ if (program.dns?.length) {
2936
+ const dns = config.dns;
2937
+ dns.rules = program.dns.map((rule, index) => {
2938
+ const tag = `pl-domain-dns-${index}`;
2939
+ if (isIP(rule.server)) dns.servers.push(modern ? {
2940
+ type: "udp",
2941
+ tag,
2942
+ server: rule.server,
2943
+ server_port: 53
2944
+ } : {
2945
+ tag,
2946
+ address: `udp://${isIP(rule.server) === 6 ? `[${rule.server}]` : rule.server}`,
2947
+ detour: DIRECT
2948
+ });
2949
+ else {
2950
+ const url = dohUrl(rule.server);
2951
+ dns.servers.push(modern ? {
2952
+ type: "https",
2953
+ tag,
2954
+ server: url.hostname.replace(/^\[|\]$/g, ""),
2955
+ server_port: Number(url.port || 443),
2956
+ path: url.pathname,
2957
+ tls: { enabled: true },
2958
+ domain_resolver: {
2959
+ server: DNS,
2960
+ strategy: "prefer_ipv4"
2961
+ }
2962
+ } : {
2963
+ tag,
2964
+ address: url.href,
2965
+ address_resolver: DNS,
2966
+ detour: DIRECT
2967
+ });
2968
+ }
2969
+ return {
2970
+ ...dnsCondition(rule),
2971
+ server: tag
2972
+ };
2973
+ });
2974
+ }
2851
2975
  if (program.endpoints?.length) {
2852
2976
  config.endpoints = program.endpoints.map((endpoint) => ({
2853
2977
  type: "tailscale",
@@ -2865,8 +2989,7 @@ function singbox(plan, secret) {
2865
2989
  type: "udp",
2866
2990
  tag: `pl-ts-dns-${endpoint.id}`,
2867
2991
  server: endpoint.bootstrapResolver,
2868
- server_port: 53,
2869
- detour: DIRECT
2992
+ server_port: 53
2870
2993
  });
2871
2994
  }
2872
2995
  return config;
@@ -2881,6 +3004,7 @@ function surgeCondition(condition) {
2881
3004
  case "domain": return `DOMAIN,${condition.value}`;
2882
3005
  case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
2883
3006
  case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
3007
+ case "processName": return `PROCESS-NAME,${condition.value}`;
2884
3008
  case "sourceIp": return `SRC-IP,${condition.value}`;
2885
3009
  case "network": return `PROTOCOL,${condition.value.toUpperCase()}`;
2886
3010
  case "port":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proxylang",
3
- "version": "0.3.0",
3
+ "version": "0.4.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": {