sing-box-kit 0.1.0 → 0.1.2

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/src/rules.ts CHANGED
@@ -1,50 +1,17 @@
1
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";
2
+ import type { SBKitInputs } from "./generated/sbkit-inputs";
3
+ import { ruleActionSchemas, ruleMatchSchema } from "./input-schema";
4
+ import { fieldsFrom, preserveIdentity, record, resourceData, snapshot } from "./resource";
5
+ import type { Resolve } from "./resource";
6
+ import { checkSchema, compileSchema, durationNanoseconds, fail, keyPath } from "./schema";
7
+ import type { SchemaNode } from "./schema";
8
+ import { expandInput, previewReference } from "./settings";
9
+ import type { Fields, ReadonlyJson, StrictUnion } from "./type-utils";
40
10
 
41
11
  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" }>;
12
+ type RouteMatch = ReadonlyJson<SBKitInputs["matches"]["route"]>;
13
+ type DnsMatch = ReadonlyJson<SBKitInputs["matches"]["dns"]>;
45
14
 
46
- const commonMatches = ["domain", "domain_suffix", "port", "auth_user"] as const;
47
- const routeMatches = ["client"] as const;
48
15
  const responseMatches = [
49
16
  "response_rcode",
50
17
  "response_answer",
@@ -54,32 +21,28 @@ const responseMatches = [
54
21
  "ip_is_private",
55
22
  "ip_accept_any",
56
23
  ] 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>;
24
+ type ResponseKey = (typeof responseMatches)[number];
25
+ type DnsMatchInput = Omit<DnsMatch, ResponseKey | "match_response"> &
26
+ (
27
+ | (Pick<DnsMatch, ResponseKey> & { readonly match_response: true | string })
28
+ | {
29
+ readonly match_response?: false;
30
+ readonly ip_is_private?: false;
31
+ readonly ip_accept_any?: false;
32
+ }
33
+ );
34
+ type AllMatchKeys = keyof RouteMatch | keyof DnsMatch;
35
+ type RouteMatchInput = RouteMatch & {
36
+ readonly [K in Exclude<AllMatchKeys, keyof RouteMatch>]?: never;
70
37
  };
71
- type DnsMatches = ReadonlyJson<Pick<DnsLeaf, (typeof dnsMatches)[number]>> & {
72
- readonly preferred_by?: OneOrMany<PreferredDomain>;
38
+ type ScopedDnsMatch = DnsMatchInput & {
39
+ readonly [K in Exclude<AllMatchKeys, keyof DnsMatch>]?: never;
73
40
  };
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;
41
+ export type MatchFields = RouteMatchInput | ScopedDnsMatch;
79
42
 
80
43
  type MatchScope<M> =
81
44
  | ([M] extends [RouteMatchInput] ? "route" : never)
82
- | ([M] extends [DnsMatchInput] ? "dns" : never);
45
+ | ([M] extends [ScopedDnsMatch] ? "dns" : never);
83
46
 
84
47
  declare const conditionBrand: unique symbol;
85
48
  export interface Condition<S extends Scope = Scope> {
@@ -120,54 +83,36 @@ function makeCondition<S extends Scope>(data: ConditionData): Condition<S> {
120
83
  return value;
121
84
  }
122
85
 
123
- const scopeMatches = { route: routeMatches, dns: dnsMatches };
124
- const allMatches = [...commonMatches, ...referenceMatches, ...routeMatches, ...dnsMatches];
86
+ const routeKeys = new Set(Object.keys(ruleMatchSchema.route.properties!));
87
+ const dnsKeys = new Set(Object.keys(ruleMatchSchema.dns.properties!));
88
+ const allMatches = [...new Set([...routeKeys, ...dnsKeys])];
125
89
  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
- },
90
+ route: compileSchema(ruleMatchSchema.route),
91
+ dns: compileSchema(ruleMatchSchema.dns),
152
92
  };
153
93
 
154
94
  function active(value: unknown): boolean {
155
95
  return value !== undefined && value !== false && (!Array.isArray(value) || value.length !== 0);
156
96
  }
157
97
 
158
- function checkLeaf(fields: Fields, path: string): void {
98
+ function checkLeaf(fields: Fields, path: string, scope: Scope): void {
159
99
  if (fields.match_response === "") fail(`${path}.match_response`, "empty response tag");
160
- if (responseMatches.some((key) => active(fields[key])) && !active(fields.match_response)) {
100
+ if (
101
+ scope === "dns" &&
102
+ responseMatches.some((key) => active(fields[key])) &&
103
+ !active(fields.match_response)
104
+ ) {
161
105
  fail(`${path}.match_response`, "response fields require active response matching");
162
106
  }
163
- if (!Object.values(fields).some(active)) fail(path, "condition has no active fields");
107
+ if (!Object.entries(fields).some(([key, value]) => key !== "invert" && active(value))) {
108
+ fail(path, "condition has no active fields");
109
+ }
164
110
  }
165
111
 
166
- function match<M extends MatchFields>(
167
- input: M & Record<Exclude<keyof M, keyof MatchFields>, never>,
112
+ function match<const M extends MatchFields>(
113
+ input: M & Record<Exclude<keyof M, AllMatchKeys>, never>,
168
114
  ): Condition<MatchScope<M>> {
169
115
  const fields = fieldsFrom(input, "match", allMatches);
170
- checkLeaf(fields, "match");
171
116
  const preferred = Array.isArray(fields.preferred_by)
172
117
  ? fields.preferred_by
173
118
  : [fields.preferred_by];
@@ -178,18 +123,22 @@ function match<M extends MatchFields>(
178
123
  });
179
124
  if (hasDnsTransport && hasOtherResource)
180
125
  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
- });
126
+
127
+ const keys = Object.keys(fields);
128
+ const dnsOnly = hasDnsTransport || keys.some((key) => !routeKeys.has(key));
129
+ const icmp =
130
+ fields.network === "icmp" || (Array.isArray(fields.network) && fields.network.includes("icmp"));
131
+ const addressMatch = fields.ip_cidr !== undefined || fields.ip_is_private === true;
132
+ const routeOnly =
133
+ hasOtherResource || icmp || keys.some((key) => !dnsKeys.has(key)) || (addressMatch && !dnsOnly);
134
+ const scopes = allScopes.filter((scope) => (scope === "route" ? !dnsOnly : !routeOnly));
188
135
  if (!scopes.length) fail("match", "fields have no common scope");
136
+
189
137
  for (const scope of scopes) {
138
+ checkLeaf(fields, "match", scope);
190
139
  checkSchema(
191
140
  leafValidators[scope],
192
- expandFields(fields, leafReferences[scope], "match", previewReference),
141
+ expandInput(ruleMatchSchema[scope], fields, "match", previewReference),
193
142
  "match",
194
143
  );
195
144
  }
@@ -198,96 +147,20 @@ function match<M extends MatchFields>(
198
147
 
199
148
  export const Rule = Object.freeze({ match });
200
149
 
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
-
150
+ export type RouteRuleAction = StrictUnion<ReadonlyJson<SBKitInputs["actions"]["route"]>>;
151
+ export type DnsRuleAction = StrictUnion<ReadonlyJson<SBKitInputs["actions"]["dns"]>>;
238
152
  export type RuleAction<S extends Scope> = { route: RouteRuleAction; dns: DnsRuleAction }[S];
239
153
 
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
- };
154
+ function actionsFor(scope: Scope) {
155
+ return new Map(
156
+ Array.from(ruleActionSchemas(scope), ([action, schema]) => [
157
+ action,
158
+ { schema, validate: compileSchema(schema) },
159
+ ]),
160
+ );
255
161
  }
256
162
 
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
- };
163
+ const actions = { route: actionsFor("route"), dns: actionsFor("dns") };
291
164
 
292
165
  function validSubnet(input: string): boolean {
293
166
  const [address = "", prefix, ...extra] = input.split("/");
@@ -300,7 +173,7 @@ function validSubnet(input: string): boolean {
300
173
  );
301
174
  }
302
175
 
303
- function checkAction(fields: Fields, path: string): void {
176
+ function checkAction(fields: Fields, path: string, scope: Scope): void {
304
177
  if (fields.method === "drop" && fields.no_drop === true)
305
178
  fail(`${path}.no_drop`, "no_drop with drop");
306
179
  if (fields.client_subnet !== undefined) {
@@ -310,6 +183,7 @@ function checkAction(fields: Fields, path: string): void {
310
183
  fail(`${path}.client_subnet`, "invalid subnet");
311
184
  }
312
185
  if (
186
+ scope === "dns" &&
313
187
  fields.action === "route-options" &&
314
188
  fields.rewrite_ttl === undefined &&
315
189
  fields.client_subnet === undefined &&
@@ -324,8 +198,6 @@ function checkAction(fields: Fields, path: string): void {
324
198
  fail(`${path}.race`, "race with speculative");
325
199
  }
326
200
 
327
- const actionReferences = { route: { outbound: ref("egress") }, dns: { server: ref("dns-server") } };
328
-
329
201
  declare const ruleBrand: unique symbol;
330
202
  export interface RuleValue<S extends Scope> {
331
203
  readonly [ruleBrand]: S;
@@ -335,6 +207,7 @@ interface RuleData {
335
207
  readonly scope: Scope;
336
208
  readonly condition?: Condition;
337
209
  readonly action: Fields;
210
+ readonly schema: SchemaNode;
338
211
  }
339
212
  const rules = new WeakMap<object, RuleData>();
340
213
 
@@ -344,18 +217,17 @@ function makeRule<S extends Scope>(
344
217
  actionInput: unknown,
345
218
  ): RuleValue<S> {
346
219
  const path = `${scope}.rule`;
347
- const variants = actions[scope] as Record<string, ReturnType<typeof actionVariant>>;
348
220
  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),
221
+ const variant = typeof name === "string" ? actions[scope].get(name) : undefined;
222
+ if (!variant) fail(`${path}.action`, "unsupported action");
223
+ const action = fieldsFrom(
224
+ actionInput,
356
225
  path,
226
+ Object.keys(variant.schema.properties!),
227
+ variant.schema.required,
357
228
  );
358
- checkAction(action, path);
229
+ checkSchema(variant.validate, expandInput(variant.schema, action, path, previewReference), path);
230
+ checkAction(action, path, scope);
359
231
  if (condition !== undefined && !conditionData(condition, path).scopes.includes(scope)) {
360
232
  fail(path, "condition is incompatible with rule scope");
361
233
  }
@@ -367,6 +239,7 @@ function makeRule<S extends Scope>(
367
239
  scope,
368
240
  condition: condition as Condition | undefined,
369
241
  action: snapshot(action, path),
242
+ schema: variant.schema,
370
243
  });
371
244
  return value;
372
245
  }
@@ -401,8 +274,10 @@ function expandCondition(value: Condition, scope: Scope, path: string, resolve:
401
274
  const { node, invert } = conditionData(value, path);
402
275
  const inversion = invert ? { invert: true } : {};
403
276
  if ("fields" in node) {
404
- checkLeaf(node.fields, path);
405
- return { ...expandFields(node.fields, leafReferences[scope], path, resolve), ...inversion };
277
+ checkLeaf(node.fields, path, scope);
278
+ const fields = expandInput(ruleMatchSchema[scope], node.fields, path, resolve) as Fields;
279
+ if (invert) fields.invert = node.fields.invert !== true;
280
+ return fields;
406
281
  }
407
282
  if (!node.rules.length) fail(`${path}.rules`, "empty logical group");
408
283
  return {
@@ -425,7 +300,7 @@ export function expandRule(value: unknown, scope: Scope, path: string, resolve:
425
300
  }
426
301
  return {
427
302
  ...(data.condition ? expandCondition(data.condition, scope, path, resolve) : {}),
428
- ...expandFields(data.action, actionReferences[scope], path, resolve),
303
+ ...(expandInput(data.schema, data.action, path, resolve) as Fields),
429
304
  };
430
305
  }
431
306
 
package/src/schema.ts CHANGED
@@ -61,23 +61,29 @@ export interface SchemaNode {
61
61
  const?: unknown;
62
62
  enum?: readonly unknown[];
63
63
  properties?: SchemaFields;
64
+ required?: readonly string[];
65
+ items?: SchemaNode;
66
+ propertyNames?: SchemaNode;
67
+ additionalProperties?: SchemaNode | boolean;
64
68
  oneOf?: readonly SchemaNode[];
65
69
  anyOf?: readonly SchemaNode[];
70
+ "x-tag-reference"?: string;
66
71
  }
67
72
 
68
73
  const definitions = official.$defs as unknown as Record<string, SchemaNode>;
74
+ export const rootProperties = official.properties as SchemaFields;
69
75
  export function definition(name: string): SchemaNode {
70
76
  return definitions[name] ?? fail(name, "unknown schema definition");
71
77
  }
72
78
 
73
- export function variant(name: string, type: string): SchemaNode {
74
- const schema = definition(name);
75
- return (
76
- (schema.oneOf ?? schema.anyOf)?.find(
77
- (option) =>
78
- option.properties?.type?.const === type || option.properties?.type?.enum?.includes(type),
79
- ) ?? fail(name, "unknown schema variant")
80
- );
79
+ export function definitionName(schema: SchemaNode): string | undefined {
80
+ return schema.$ref?.slice("#/$defs/".length);
81
+ }
82
+
83
+ export function schemaBranches(schema: SchemaNode): SchemaNode[] {
84
+ const name = definitionName(schema);
85
+ if (name) return schemaBranches(definition(name));
86
+ return (schema.oneOf ?? schema.anyOf)?.flatMap(schemaBranches) ?? [schema];
81
87
  }
82
88
 
83
89
  export function compileSchema(schema: AnySchema): ValidateFunction {
@@ -88,13 +94,6 @@ export function compileSchema(schema: AnySchema): ValidateFunction {
88
94
  return ajv.compile(JSON.parse(JSON.stringify(schema, rewriteReferences)));
89
95
  }
90
96
 
91
- export function objectValidator(
92
- properties: SchemaFields,
93
- required: readonly string[] = [],
94
- ): ValidateFunction {
95
- return compileSchema({ type: "object", properties, required, additionalProperties: false });
96
- }
97
-
98
97
  export function pickSchema(properties: SchemaFields, keys: readonly string[]): SchemaFields {
99
98
  return Object.fromEntries(
100
99
  keys.map((key) => [key, properties[key] ?? fail(key, "field missing from official schema")]),
@@ -158,14 +157,7 @@ export const tlsProfileValidators = {
158
157
  handshake: {
159
158
  type: "object",
160
159
  additionalProperties: false,
161
- properties: pickSchema(definition("InboundRealityHandshakeOptions").properties!, [
162
- "server",
163
- "server_port",
164
- "connect_timeout",
165
- "detour",
166
- "domain_resolver",
167
- "netns",
168
- ]),
160
+ properties: definition("InboundRealityHandshakeOptions").properties!,
169
161
  required: ["server", "server_port"],
170
162
  },
171
163
  },