sing-box-kit 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,185 @@
1
+ import { fail, keyPath } from "./schema";
2
+
3
+ export type Fields = Record<string, unknown>;
4
+ export type ReadonlyJson<T> = T extends object
5
+ ? { readonly [K in keyof T]: ReadonlyJson<T[K]> }
6
+ : T;
7
+ export type Target =
8
+ | "inbounds"
9
+ | "outbounds"
10
+ | "endpoints"
11
+ | "services"
12
+ | "http_clients"
13
+ | "dns.servers"
14
+ | "route.rule_set"
15
+ | "certificate_providers"
16
+ | "network_namespaces";
17
+ export type Role =
18
+ | "inbound"
19
+ | "listen-detour"
20
+ | "dial-detour"
21
+ | "egress"
22
+ | "preferred-routes"
23
+ | "dns-server"
24
+ | "preferred-domain"
25
+ | "ssm"
26
+ | "certificate-provider"
27
+ | "http-client"
28
+ | "netns"
29
+ | "rule-set"
30
+ | "tailscale-endpoint";
31
+
32
+ declare const resourceBrand: unique symbol;
33
+ export interface Resource<
34
+ T extends Target = Target,
35
+ K extends string = string,
36
+ Tag extends string | readonly string[] | undefined = string | readonly string[] | undefined,
37
+ R extends Role = Role,
38
+ > {
39
+ readonly [resourceBrand]: { target: T; kind: K; tag: Tag; roles: R };
40
+ }
41
+
42
+ export type InboundRef = Resource<"inbounds" | "endpoints", string, string>;
43
+ export type ListenDetour = Resource<
44
+ "inbounds",
45
+ string,
46
+ string,
47
+ "listen-detour" | "inbound" | "ssm"
48
+ >;
49
+ export type Egress = Resource<"outbounds" | "endpoints", string, string>;
50
+ export type PreferredRoutes = Resource<"endpoints", "tailscale" | "wireguard", string>;
51
+ export type DnsServer = Resource<"dns.servers", string, string>;
52
+ export type PreferredDomain = Resource<"dns.servers", "tailscale", string>;
53
+ export type Namespace = Resource<"network_namespaces", string, string>;
54
+ export type CertificateProvider = Resource<"certificate_providers", string, string>;
55
+ export type TaggedHttpClient = Resource<"http_clients", "http-client", string>;
56
+ export type RuleSetRef = Resource<"route.rule_set", string, string | readonly [string]>;
57
+ export type SsmInbound = Resource<
58
+ "inbounds",
59
+ "shadowsocks",
60
+ string,
61
+ "inbound" | "listen-detour" | "ssm"
62
+ > & { readonly [ssmBrand]: true };
63
+ declare const ssmBrand: unique symbol;
64
+ export type TailscaleEndpoint = Resource<"endpoints", "tailscale", string>;
65
+
66
+ export type Resolve = (value: unknown, role: Role, path: string) => string;
67
+ export type Expand = (value: unknown, path: string, resolve: Resolve) => unknown;
68
+ export type Expansions = Readonly<Record<string, Expand>>;
69
+ export interface ResourceData {
70
+ readonly target: Target;
71
+ readonly kind: string;
72
+ readonly fields: Fields;
73
+ readonly roles: readonly Role[];
74
+ readonly references?: Expansions;
75
+ readonly startupDetour?: boolean;
76
+ readonly remoteDns?: boolean;
77
+ }
78
+
79
+ const resources = new WeakMap<object, ResourceData>();
80
+ const identities = new WeakSet<object>();
81
+
82
+ /** Internal constructor. Factory methods supply immutable data. */
83
+ export function createResource<T extends Resource>(data: ResourceData, methods: object = {}): T {
84
+ const value = Object.freeze(methods);
85
+ resources.set(value, data);
86
+ identities.add(value);
87
+ return value as T;
88
+ }
89
+
90
+ export function resourceData(value: unknown): ResourceData | undefined {
91
+ return value !== null && typeof value === "object" ? resources.get(value) : undefined;
92
+ }
93
+
94
+ export function preserveIdentity<T extends object>(value: T): T {
95
+ identities.add(value);
96
+ return Object.freeze(value);
97
+ }
98
+
99
+ export function record(value: unknown, path: string): Fields {
100
+ if (
101
+ value === null ||
102
+ typeof value !== "object" ||
103
+ Array.isArray(value) ||
104
+ identities.has(value)
105
+ ) {
106
+ fail(path, "expected an options object");
107
+ }
108
+ const prototype = Object.getPrototypeOf(value);
109
+ if (prototype !== Object.prototype && prototype !== null) fail(path, "expected a plain object");
110
+ return value as Fields;
111
+ }
112
+
113
+ export function fieldsFrom(
114
+ input: unknown,
115
+ path: string,
116
+ allowed: readonly string[],
117
+ required: readonly string[] = [],
118
+ ): Fields {
119
+ const value = record(input, path);
120
+ for (const key of Object.keys(value)) {
121
+ if (!allowed.includes(key)) fail(keyPath(path, key), "unexpected field");
122
+ }
123
+ for (const key of required) {
124
+ if (!Object.hasOwn(value, key) || value[key] === undefined)
125
+ fail(keyPath(path, key), "required field");
126
+ }
127
+ return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== undefined));
128
+ }
129
+
130
+ function copy(value: unknown, path: string, immutable: boolean, ancestors: Set<object>): unknown {
131
+ if (value === null || typeof value !== "object") return value;
132
+ if (identities.has(value)) {
133
+ if (immutable) return value;
134
+ fail(path, "unexpected Kit value in JSON fields");
135
+ }
136
+ if (ancestors.has(value)) fail(path, "cyclic configuration object");
137
+ ancestors.add(value);
138
+ const result = Array.isArray(value)
139
+ ? Array.from(value, (child, index) => copy(child, `${path}[${index}]`, immutable, ancestors))
140
+ : Object.fromEntries(
141
+ Object.entries(record(value, path)).map(([key, child]) => [
142
+ key,
143
+ copy(child, keyPath(path, key), immutable, ancestors),
144
+ ]),
145
+ );
146
+ ancestors.delete(value);
147
+ return immutable ? Object.freeze(result) : result;
148
+ }
149
+
150
+ export function snapshot<T>(value: T, path: string): T {
151
+ return copy(value, path, true, new Set()) as T;
152
+ }
153
+
154
+ export function copyJson<T>(value: T, path: string): T {
155
+ return copy(value, path, false, new Set()) as T;
156
+ }
157
+
158
+ export const ref =
159
+ (role: Role): Expand =>
160
+ (value, path, resolve) =>
161
+ resolve(value, role, path);
162
+
163
+ export const arrayOrOne =
164
+ (expand: Expand): Expand =>
165
+ (value, path, resolve) =>
166
+ Array.isArray(value)
167
+ ? Array.from(value, (item, index) => expand(item, `${path}[${index}]`, resolve))
168
+ : expand(value, path, resolve);
169
+
170
+ export function expandFields(
171
+ fields: Fields,
172
+ expansions: Expansions,
173
+ path: string,
174
+ resolve: Resolve,
175
+ ): Fields {
176
+ return Object.fromEntries(
177
+ Object.entries(fields)
178
+ .filter(([, value]) => value !== undefined)
179
+ .map(([key, value]) => {
180
+ const fieldPath = keyPath(path, key);
181
+ const expand = Object.hasOwn(expansions, key) ? expansions[key] : undefined;
182
+ return [key, expand ? expand(value, fieldPath, resolve) : copyJson(value, fieldPath)];
183
+ }),
184
+ );
185
+ }
package/src/rules.ts ADDED
@@ -0,0 +1,469 @@
1
+ import { isIP } from "node:net";
2
+ import type {
3
+ DNSRuleAction as RawDnsAction,
4
+ NestedDNSRule,
5
+ NestedRule,
6
+ RuleAction as RawRouteAction,
7
+ } from "./generated/sing-box";
8
+ import {
9
+ arrayOrOne,
10
+ expandFields,
11
+ fieldsFrom,
12
+ preserveIdentity,
13
+ ref,
14
+ record,
15
+ resourceData,
16
+ snapshot,
17
+ } from "./resource";
18
+ import type {
19
+ DnsServer,
20
+ Egress,
21
+ Expansions,
22
+ Fields,
23
+ InboundRef,
24
+ PreferredDomain,
25
+ PreferredRoutes,
26
+ ReadonlyJson,
27
+ Resolve,
28
+ RuleSetRef,
29
+ } from "./resource";
30
+ import {
31
+ checkSchema,
32
+ definition,
33
+ durationNanoseconds,
34
+ fail,
35
+ keyPath,
36
+ objectValidator,
37
+ pickSchema,
38
+ } from "./schema";
39
+ import { previewReference } from "./settings";
40
+
41
+ export type Scope = "route" | "dns";
42
+ type OneOrMany<T> = T | readonly T[];
43
+ type RouteLeaf = Exclude<NestedRule, { type: "logical" }>;
44
+ type DnsLeaf = Exclude<NestedDNSRule, { type: "logical" }>;
45
+
46
+ const commonMatches = ["domain", "domain_suffix", "port", "auth_user"] as const;
47
+ const routeMatches = ["client"] as const;
48
+ const responseMatches = [
49
+ "response_rcode",
50
+ "response_answer",
51
+ "response_ns",
52
+ "response_extra",
53
+ "ip_cidr",
54
+ "ip_is_private",
55
+ "ip_accept_any",
56
+ ] as const;
57
+ const dnsMatches = ["query_type", "match_response", ...responseMatches] as const;
58
+ const referenceMatches = ["inbound", "rule_set", "preferred_by"] as const;
59
+
60
+ type CommonMatches = ReadonlyJson<
61
+ Pick<RouteLeaf, Exclude<(typeof commonMatches)[number], "auth_user">>
62
+ > & {
63
+ /** An empty string can match traffic with no authenticated name. */
64
+ readonly auth_user?: OneOrMany<string>;
65
+ readonly inbound?: OneOrMany<InboundRef>;
66
+ readonly rule_set?: OneOrMany<RuleSetRef>;
67
+ };
68
+ type RouteMatches = ReadonlyJson<Pick<RouteLeaf, (typeof routeMatches)[number]>> & {
69
+ readonly preferred_by?: OneOrMany<PreferredRoutes>;
70
+ };
71
+ type DnsMatches = ReadonlyJson<Pick<DnsLeaf, (typeof dnsMatches)[number]>> & {
72
+ readonly preferred_by?: OneOrMany<PreferredDomain>;
73
+ };
74
+ type RouteMatchInput = CommonMatches &
75
+ RouteMatches & { readonly [K in (typeof dnsMatches)[number]]?: never };
76
+ type DnsMatchInput = CommonMatches &
77
+ DnsMatches & { readonly [K in (typeof routeMatches)[number]]?: never };
78
+ export type MatchFields = RouteMatchInput | DnsMatchInput;
79
+
80
+ type MatchScope<M> =
81
+ | ([M] extends [RouteMatchInput] ? "route" : never)
82
+ | ([M] extends [DnsMatchInput] ? "dns" : never);
83
+
84
+ declare const conditionBrand: unique symbol;
85
+ export interface Condition<S extends Scope = Scope> {
86
+ readonly [conditionBrand]: S;
87
+ and<O extends Scope>(
88
+ other: Condition<O> & ([S & O] extends [never] ? never : unknown),
89
+ ): Condition<S & O>;
90
+ or<O extends Scope>(
91
+ other: Condition<O> & ([S & O] extends [never] ? never : unknown),
92
+ ): Condition<S & O>;
93
+ not(): Condition<S>;
94
+ }
95
+
96
+ interface ConditionData {
97
+ readonly scopes: readonly Scope[];
98
+ readonly invert: boolean;
99
+ readonly node: { fields: Fields } | { mode: "and" | "or"; rules: readonly Condition[] };
100
+ }
101
+ const conditions = new WeakMap<Condition, ConditionData>();
102
+ const allScopes: readonly Scope[] = ["route", "dns"];
103
+ function conditionData(value: unknown, path: string): ConditionData {
104
+ return conditions.get(value as Condition) ?? fail(path, "expected a rule condition");
105
+ }
106
+
107
+ function makeCondition<S extends Scope>(data: ConditionData): Condition<S> {
108
+ const combine = (mode: "and" | "or", other: Condition) => {
109
+ const otherData = conditionData(other, "condition");
110
+ const scopes = data.scopes.filter((scope) => otherData.scopes.includes(scope));
111
+ if (scopes.length === 0) fail("condition", "operands have no common scope");
112
+ return makeCondition({ scopes, invert: false, node: { mode, rules: [value, other] } });
113
+ };
114
+ const value = preserveIdentity({
115
+ and: (other: Condition) => combine("and", other),
116
+ or: (other: Condition) => combine("or", other),
117
+ not: () => makeCondition({ ...data, invert: !data.invert }),
118
+ }) as unknown as Condition<S>;
119
+ conditions.set(value, data);
120
+ return value;
121
+ }
122
+
123
+ const scopeMatches = { route: routeMatches, dns: dnsMatches };
124
+ const allMatches = [...commonMatches, ...referenceMatches, ...routeMatches, ...dnsMatches];
125
+ const leafValidators = {
126
+ route: objectValidator(
127
+ pickSchema(definition("NestedRule").oneOf![0]!.properties!, [
128
+ ...commonMatches,
129
+ ...referenceMatches,
130
+ ...routeMatches,
131
+ ]),
132
+ ),
133
+ dns: objectValidator(
134
+ pickSchema(definition("NestedDNSRule").oneOf![0]!.properties!, [
135
+ ...commonMatches,
136
+ ...referenceMatches,
137
+ ...dnsMatches,
138
+ ]),
139
+ ),
140
+ };
141
+ const leafReferences: Record<Scope, Expansions> = {
142
+ route: {
143
+ inbound: arrayOrOne(ref("inbound")),
144
+ rule_set: arrayOrOne(ref("rule-set")),
145
+ preferred_by: arrayOrOne(ref("preferred-routes")),
146
+ },
147
+ dns: {
148
+ inbound: arrayOrOne(ref("inbound")),
149
+ rule_set: arrayOrOne(ref("rule-set")),
150
+ preferred_by: arrayOrOne(ref("preferred-domain")),
151
+ },
152
+ };
153
+
154
+ function active(value: unknown): boolean {
155
+ return value !== undefined && value !== false && (!Array.isArray(value) || value.length !== 0);
156
+ }
157
+
158
+ function checkLeaf(fields: Fields, path: string): void {
159
+ if (fields.match_response === "") fail(`${path}.match_response`, "empty response tag");
160
+ if (responseMatches.some((key) => active(fields[key])) && !active(fields.match_response)) {
161
+ fail(`${path}.match_response`, "response fields require active response matching");
162
+ }
163
+ if (!Object.values(fields).some(active)) fail(path, "condition has no active fields");
164
+ }
165
+
166
+ function match<M extends MatchFields>(
167
+ input: M & Record<Exclude<keyof M, keyof MatchFields>, never>,
168
+ ): Condition<MatchScope<M>> {
169
+ const fields = fieldsFrom(input, "match", allMatches);
170
+ checkLeaf(fields, "match");
171
+ const preferred = Array.isArray(fields.preferred_by)
172
+ ? fields.preferred_by
173
+ : [fields.preferred_by];
174
+ const hasDnsTransport = preferred.some((value) => resourceData(value)?.target === "dns.servers");
175
+ const hasOtherResource = preferred.some((value) => {
176
+ const data = resourceData(value);
177
+ return data && data.target !== "dns.servers";
178
+ });
179
+ if (hasDnsTransport && hasOtherResource)
180
+ fail("match.preferred_by", "mixed route and DNS targets");
181
+ const scopes = allScopes.filter((scope) => {
182
+ const opposite = scope === "route" ? "dns" : "route";
183
+ return (
184
+ !scopeMatches[opposite].some((key) => fields[key] !== undefined) &&
185
+ !(scope === "route" ? hasDnsTransport : hasOtherResource)
186
+ );
187
+ });
188
+ if (!scopes.length) fail("match", "fields have no common scope");
189
+ for (const scope of scopes) {
190
+ checkSchema(
191
+ leafValidators[scope],
192
+ expandFields(fields, leafReferences[scope], "match", previewReference),
193
+ "match",
194
+ );
195
+ }
196
+ return makeCondition({ scopes, invert: false, node: { fields: snapshot(fields, "match") } });
197
+ }
198
+
199
+ export const Rule = Object.freeze({ match });
200
+
201
+ type SharedDnsOptions = ReadonlyJson<
202
+ Pick<
203
+ Extract<RawDnsAction, { action: "route-options" }>,
204
+ | "timeout"
205
+ | "disable_cache"
206
+ | "disable_optimistic_cache"
207
+ | "rewrite_ttl"
208
+ | "client_subnet"
209
+ | "remove_client_subnet"
210
+ >
211
+ >;
212
+ type RejectOptions = Omit<Extract<RawRouteAction, { action: "reject" }>, "action" | "method"> & {
213
+ method?: "default" | "drop";
214
+ };
215
+ export type RouteRuleAction =
216
+ | { action: "route"; outbound: Egress }
217
+ | { action: "bypass"; outbound?: Egress }
218
+ | ({ action: "reject" } & RejectOptions)
219
+ | { action: "hijack-dns" };
220
+ export type DnsRuleAction =
221
+ | ({
222
+ action: "route";
223
+ server: DnsServer;
224
+ speculative?: boolean;
225
+ race?: boolean;
226
+ } & SharedDnsOptions)
227
+ | ({
228
+ action: "evaluate";
229
+ server: DnsServer;
230
+ tag?: string;
231
+ speculative?: boolean;
232
+ } & SharedDnsOptions)
233
+ | Extract<RawDnsAction, { action: "respond" }>
234
+ | ({ action: "route-options" } & SharedDnsOptions)
235
+ | ({ action: "reject"; race?: boolean } & RejectOptions)
236
+ | ReadonlyJson<Extract<RawDnsAction, { action: "predefined" }>>;
237
+
238
+ export type RuleAction<S extends Scope> = { route: RouteRuleAction; dns: DnsRuleAction }[S];
239
+
240
+ function actionVariant(
241
+ scope: Scope,
242
+ action: string,
243
+ keys: readonly string[],
244
+ required: readonly string[] = [],
245
+ ) {
246
+ const schema = definition(scope === "route" ? "RuleAction" : "DNSRuleAction");
247
+ const raw = schema.oneOf!.find((item) => item.properties?.action?.const === action)!.properties!;
248
+ const properties = pickSchema(raw, ["action", ...keys]);
249
+ if (action === "reject") properties.method = { type: "string", enum: ["default", "drop"] };
250
+ return {
251
+ keys: ["action", ...keys],
252
+ required: ["action", ...required],
253
+ validate: objectValidator(properties, ["action", ...required]),
254
+ };
255
+ }
256
+
257
+ const sharedDnsOptions = [
258
+ "timeout",
259
+ "disable_cache",
260
+ "disable_optimistic_cache",
261
+ "rewrite_ttl",
262
+ "client_subnet",
263
+ "remove_client_subnet",
264
+ ] as const satisfies readonly (keyof SharedDnsOptions)[];
265
+ const actions = {
266
+ route: {
267
+ route: actionVariant("route", "route", ["outbound"], ["outbound"]),
268
+ bypass: actionVariant("route", "bypass", ["outbound"]),
269
+ reject: actionVariant("route", "reject", ["method", "no_drop"]),
270
+ "hijack-dns": actionVariant("route", "hijack-dns", []),
271
+ },
272
+ dns: {
273
+ route: actionVariant(
274
+ "dns",
275
+ "route",
276
+ ["server", "speculative", "race", ...sharedDnsOptions],
277
+ ["server"],
278
+ ),
279
+ evaluate: actionVariant(
280
+ "dns",
281
+ "evaluate",
282
+ ["server", "tag", "speculative", ...sharedDnsOptions],
283
+ ["server"],
284
+ ),
285
+ respond: actionVariant("dns", "respond", ["race"]),
286
+ "route-options": actionVariant("dns", "route-options", sharedDnsOptions),
287
+ reject: actionVariant("dns", "reject", ["method", "no_drop", "race"]),
288
+ predefined: actionVariant("dns", "predefined", ["rcode", "answer", "ns", "extra", "race"]),
289
+ },
290
+ };
291
+
292
+ function validSubnet(input: string): boolean {
293
+ const [address = "", prefix, ...extra] = input.split("/");
294
+ const version = isIP(address);
295
+ return (
296
+ version !== 0 &&
297
+ !address.includes("%") &&
298
+ extra.length === 0 &&
299
+ (prefix === undefined || (/^\d+$/.test(prefix) && Number(prefix) <= (version === 4 ? 32 : 128)))
300
+ );
301
+ }
302
+
303
+ function checkAction(fields: Fields, path: string): void {
304
+ if (fields.method === "drop" && fields.no_drop === true)
305
+ fail(`${path}.no_drop`, "no_drop with drop");
306
+ if (fields.client_subnet !== undefined) {
307
+ if (fields.remove_client_subnet === true)
308
+ fail(`${path}.client_subnet`, "client_subnet with remove_client_subnet");
309
+ if (!validSubnet(fields.client_subnet as string))
310
+ fail(`${path}.client_subnet`, "invalid subnet");
311
+ }
312
+ if (
313
+ fields.action === "route-options" &&
314
+ fields.rewrite_ttl === undefined &&
315
+ fields.client_subnet === undefined &&
316
+ fields.disable_cache !== true &&
317
+ fields.disable_optimistic_cache !== true &&
318
+ fields.remove_client_subnet !== true &&
319
+ durationNanoseconds(fields.timeout, `${path}.timeout`) <= 0
320
+ ) {
321
+ fail(path, "route-options requires an effective DNS option");
322
+ }
323
+ if (fields.race === true && fields.speculative === true)
324
+ fail(`${path}.race`, "race with speculative");
325
+ }
326
+
327
+ const actionReferences = { route: { outbound: ref("egress") }, dns: { server: ref("dns-server") } };
328
+
329
+ declare const ruleBrand: unique symbol;
330
+ export interface RuleValue<S extends Scope> {
331
+ readonly [ruleBrand]: S;
332
+ }
333
+
334
+ interface RuleData {
335
+ readonly scope: Scope;
336
+ readonly condition?: Condition;
337
+ readonly action: Fields;
338
+ }
339
+ const rules = new WeakMap<object, RuleData>();
340
+
341
+ function makeRule<S extends Scope>(
342
+ scope: S,
343
+ condition: unknown,
344
+ actionInput: unknown,
345
+ ): RuleValue<S> {
346
+ const path = `${scope}.rule`;
347
+ const variants = actions[scope] as Record<string, ReturnType<typeof actionVariant>>;
348
+ const name = record(actionInput, path).action;
349
+ if (typeof name !== "string" || !Object.hasOwn(variants, name))
350
+ fail(`${path}.action`, "unsupported action");
351
+ const variant = variants[name]!;
352
+ const action = fieldsFrom(actionInput, path, variant.keys, variant.required);
353
+ checkSchema(
354
+ variant.validate,
355
+ expandFields(action, actionReferences[scope], path, previewReference),
356
+ path,
357
+ );
358
+ checkAction(action, path);
359
+ if (condition !== undefined && !conditionData(condition, path).scopes.includes(scope)) {
360
+ fail(path, "condition is incompatible with rule scope");
361
+ }
362
+ if (action.race === true && !hasResponseCondition(condition as Condition | undefined)) {
363
+ fail(`${path}.race`, "race requires active response matching");
364
+ }
365
+ const value = preserveIdentity({}) as RuleValue<S>;
366
+ rules.set(value, {
367
+ scope,
368
+ condition: condition as Condition | undefined,
369
+ action: snapshot(action, path),
370
+ });
371
+ return value;
372
+ }
373
+
374
+ function hasResponseCondition(condition: Condition | undefined): boolean {
375
+ if (!condition) return false;
376
+ const { node } = conditionData(condition, "condition");
377
+ return "fields" in node
378
+ ? active(node.fields.match_response)
379
+ : node.rules.some(hasResponseCondition);
380
+ }
381
+
382
+ interface RuleFactory<S extends Scope> {
383
+ (action: RuleAction<S>): RuleValue<S>;
384
+ <C extends Scope>(
385
+ condition: Condition<C> & (S extends C ? unknown : never),
386
+ action: RuleAction<S>,
387
+ ): RuleValue<S>;
388
+ }
389
+
390
+ function ruleFactory<S extends Scope>(scope: S): RuleFactory<S> {
391
+ return function (first: unknown, second?: unknown) {
392
+ return arguments.length === 1
393
+ ? makeRule(scope, undefined, first)
394
+ : makeRule(scope, first, second);
395
+ };
396
+ }
397
+ export const route = Object.freeze({ rule: ruleFactory("route") });
398
+ export const dns = Object.freeze({ rule: ruleFactory("dns") });
399
+
400
+ function expandCondition(value: Condition, scope: Scope, path: string, resolve: Resolve): Fields {
401
+ const { node, invert } = conditionData(value, path);
402
+ const inversion = invert ? { invert: true } : {};
403
+ if ("fields" in node) {
404
+ checkLeaf(node.fields, path);
405
+ return { ...expandFields(node.fields, leafReferences[scope], path, resolve), ...inversion };
406
+ }
407
+ if (!node.rules.length) fail(`${path}.rules`, "empty logical group");
408
+ return {
409
+ type: "logical",
410
+ mode: node.mode,
411
+ ...inversion,
412
+ rules: node.rules.map((child, index) =>
413
+ expandCondition(child, scope, `${path}.rules[${index}]`, resolve),
414
+ ),
415
+ };
416
+ }
417
+
418
+ export function expandRule(value: unknown, scope: Scope, path: string, resolve: Resolve): Fields {
419
+ const data = rules.get(value as object);
420
+ if (!data || data.scope !== scope) fail(path, `expected a ${scope} rule`);
421
+ if (data.action.action === "evaluate" && resourceData(data.action.server)?.kind === "fakeip") {
422
+ // Resolve first to preserve the registration and capability diagnostics.
423
+ const tag = resolve(data.action.server, "dns-server", `${path}.server`);
424
+ fail(`${path}.server`, "evaluate cannot use FakeIP", tag);
425
+ }
426
+ return {
427
+ ...(data.condition ? expandCondition(data.condition, scope, path, resolve) : {}),
428
+ ...expandFields(data.action, actionReferences[scope], path, resolve),
429
+ };
430
+ }
431
+
432
+ export function checkDnsRules(rules: readonly Fields[], path: string): void {
433
+ const named = new Set<string>();
434
+ let anonymous = false;
435
+
436
+ function inspect(node: Fields, nodePath: string, logicalRespond: boolean): void {
437
+ if (node.type === "logical") {
438
+ (node.rules as Fields[]).forEach((child, index) =>
439
+ inspect(child, `${nodePath}.rules[${index}]`, logicalRespond),
440
+ );
441
+ return;
442
+ }
443
+ const match = node.match_response;
444
+ if (typeof match === "string") {
445
+ if (logicalRespond)
446
+ fail(`${nodePath}.match_response`, "logical respond cannot bind a named result", match);
447
+ if (!named.has(match))
448
+ fail(`${nodePath}.match_response`, "requires an earlier named evaluate", match);
449
+ }
450
+ if (match === true && !anonymous)
451
+ fail(`${nodePath}.match_response`, "requires an earlier untagged evaluate");
452
+ }
453
+
454
+ rules.forEach((rule, index) => {
455
+ const rulePath = `${path}[${index}]`;
456
+ inspect(rule, rulePath, rule.type === "logical" && rule.action === "respond");
457
+ if (rule.action === "respond" && typeof rule.match_response !== "string" && !anonymous) {
458
+ fail(keyPath(rulePath, "action"), "respond requires an earlier untagged evaluate");
459
+ }
460
+ if (rule.action === "evaluate") {
461
+ if (typeof rule.tag === "string" && rule.tag !== "") {
462
+ if (named.has(rule.tag)) fail(`${rulePath}.tag`, "duplicate evaluate tag", rule.tag);
463
+ named.add(rule.tag);
464
+ } else {
465
+ anonymous = true;
466
+ }
467
+ }
468
+ });
469
+ }