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/factories.ts CHANGED
@@ -1,71 +1,36 @@
1
- import type {
2
- CertificateProvider as RawProvider,
3
- DNSServer as RawDnsServer,
4
- Endpoint as RawEndpoint,
5
- HeadlessRule,
6
- HTTPClient,
7
- Inbound as RawInbound,
8
- NetworkNamespace as RawNamespace,
9
- Outbound as RawOutbound,
10
- RuleSet as RawRuleSet,
11
- Service as RawService,
12
- ShadowsocksUser,
13
- User as RawUser,
14
- VLESSUser,
15
- } from "./generated/sing-box";
1
+ import type { SBKitInputs } from "./generated/sbkit-inputs";
2
+ import type { ShadowsocksUser, User as RawUser, VLESSUser } from "./generated/sing-box";
3
+ import { factoryCatalog, factoryName } from "./input-schema";
4
+ import type { FactoryBranch } from "./input-schema";
16
5
  import {
17
- arrayOrOne,
18
6
  createResource,
19
- expandFields,
20
7
  fieldsFrom,
8
+ preferredDnsKinds,
9
+ preferredRouteEndpoints,
21
10
  record,
22
- ref,
23
11
  resourceData,
24
12
  snapshot,
25
13
  } from "./resource";
26
- import type {
27
- Egress,
28
- Expansions,
29
- Fields,
30
- ReadonlyJson,
31
- Resource,
32
- Role,
33
- SsmInbound,
34
- TailscaleEndpoint,
35
- Target,
36
- } from "./resource";
14
+ import type { Resource, Role, SsmInbound, Target } from "./resource";
37
15
  import { Rule } from "./rules";
38
16
  import type { Condition } from "./rules";
39
- import { checkSchema, compileSchema, definition, fail, keyPath, variant } from "./schema";
17
+ import { checkSchema, compileSchema, definitionName, fail, keyPath } from "./schema";
40
18
  import {
41
- dialFields,
42
- dialReferences,
43
- expandDashboard,
44
- expandHttpClient,
45
- expandSsmServers,
46
- expandTls,
19
+ checkSsmServers,
20
+ expandInput,
47
21
  listenFields,
48
- listenReferences,
22
+ matchesDiscriminators,
49
23
  previewReference,
50
24
  tlsFields,
51
25
  } from "./settings";
52
- import type {
53
- ClientTls,
54
- Dial,
55
- DirectDial,
56
- HttpClientInput,
57
- InboundListener,
58
- Listener,
59
- RealityClientTls,
60
- RealityServerTls,
61
- ServerTls,
62
- TlsMode,
63
- } from "./settings";
26
+ import type { ClientTls, RealityClientTls, RealityServerTls, ServerTls, TlsMode } from "./settings";
27
+ import type { CamelCase, Fields, ReadonlyJson, StrictUnion } from "./type-utils";
64
28
  import { isUser } from "./user";
65
29
  import type { User } from "./user";
66
30
 
67
31
  interface ListenMethod<T> {
68
- listen(address: string, options: T): this;
32
+ listen(options?: T): this;
33
+ listen(address?: "port" extends keyof T ? string : undefined, options?: T): this;
69
34
  }
70
35
  interface DialMethod<T> {
71
36
  dial(options: T): this;
@@ -77,17 +42,6 @@ interface AuthMethod {
77
42
  authUser(user: User): Condition;
78
43
  }
79
44
 
80
- const targetSchema = {
81
- inbounds: "Inbound",
82
- outbounds: "Outbound",
83
- endpoints: "Endpoint",
84
- services: "Service",
85
- http_clients: "HTTPClient",
86
- "dns.servers": "DNSServer",
87
- "route.rule_set": "RuleSet",
88
- certificate_providers: "CertificateProvider",
89
- network_namespaces: "NetworkNamespace",
90
- } as const satisfies Record<Target, string>;
91
45
  const targetRoles = {
92
46
  inbounds: ["inbound", "listen-detour"],
93
47
  outbounds: ["egress"],
@@ -100,6 +54,12 @@ const targetRoles = {
100
54
  network_namespaces: ["netns"],
101
55
  } as const satisfies Record<Target, readonly Role[]>;
102
56
 
57
+ const endpointRoles = {
58
+ tailscale: "tailscale-endpoint",
59
+ openconnect: "openconnect-endpoint",
60
+ "openvpn-client": "openvpn-client-endpoint",
61
+ } as const satisfies Record<string, Role>;
62
+
103
63
  type PasswordEntry<Name extends "username" | "name"> = {
104
64
  readonly user: User;
105
65
  readonly password: string;
@@ -116,90 +76,71 @@ interface AuthOptions {
116
76
  readonly allowRaw?: boolean;
117
77
  }
118
78
 
119
- interface Definition {
120
- readonly target: Target;
121
- readonly kind: string;
122
- readonly required: readonly string[];
123
- readonly optional?: readonly string[];
124
- readonly listen?: "listener" | "forwarding";
125
- readonly dial?: "direct" | "detour";
126
- readonly tls?: TlsMode;
127
- readonly auth?: AuthOptions;
128
- readonly roles?: readonly Role[];
129
- readonly references?: Expansions;
130
- readonly remoteDns?: boolean;
131
- readonly startupDetour?: boolean;
132
- readonly prepare?: (fields: Fields, path: string) => readonly Role[] | void;
133
- readonly checkDial?: (fields: Fields, dial: Fields, path: string) => void;
134
- }
135
-
136
- type RawByTarget = {
137
- inbounds: RawInbound;
138
- outbounds: RawOutbound;
139
- endpoints: RawEndpoint;
140
- services: RawService;
141
- http_clients: HTTPClient;
142
- "dns.servers": RawDnsServer;
143
- "route.rule_set": RawRuleSet;
144
- certificate_providers: RawProvider;
145
- network_namespaces: RawNamespace;
146
- };
147
- type Variant<Raw, Kind> = Raw extends { type?: infer Type }
148
- ? Kind extends Type
149
- ? Raw
150
- : never
151
- : never;
152
- type Raw<D extends Definition> = D["target"] extends "http_clients"
153
- ? HTTPClient
154
- : Variant<RawByTarget[D["target"]], D["kind"]>;
155
- type Options<D extends Definition> = ReadonlyJson<
156
- Required<Pick<Raw<D>, Extract<D["required"][number], keyof Raw<D>>>> &
157
- Pick<Raw<D>, Extract<NonNullable<D["optional"]>[number], keyof Raw<D>>>
158
- >;
159
- type Override<T, U> = Omit<T, keyof U> & U;
79
+ const passwordAuth = {
80
+ name: "username",
81
+ credentials: ["password"],
82
+ required: ["password"],
83
+ } as const;
84
+ const authOptions = {
85
+ mixed: { ...passwordAuth, allowRaw: true },
86
+ socks: passwordAuth,
87
+ shadowsocks: { ...passwordAuth, name: "name", allowRaw: true },
88
+ vless: { name: "name", credentials: ["uuid", "flow"], required: ["uuid"] },
89
+ } as const satisfies Record<string, AuthOptions>;
160
90
 
161
- type TlsProfile = {
162
- server: ServerTls;
163
- client: ClientTls;
164
- "server-reality": ServerTls | RealityServerTls;
165
- "client-reality": ClientTls | RealityClientTls;
166
- };
91
+ type Catalog = SBKitInputs["factories"];
92
+ type Kind<T extends Target> = keyof Catalog[T] & string;
93
+ type Groups<T extends Target, K extends Kind<T>> = ReadonlyJson<Catalog[T][K]>;
94
+ type Options<T extends Target, K extends Kind<T>> =
95
+ Groups<T, K> extends { options: infer O } ? StrictUnion<O> : never;
167
96
  type Tag = string | readonly string[] | undefined;
168
- type ExtraRoles<D> = D extends { roles: readonly (infer R extends Role)[] } ? R : never;
169
- type Built<D extends Definition, T extends Tag = string> = Resource<
170
- D["target"],
171
- D["kind"],
172
- T,
173
- (typeof targetRoles)[D["target"]][number] | ExtraRoles<D>
174
- > &
175
- (D extends { listen: infer L }
176
- ? ListenMethod<L extends "forwarding" ? InboundListener : Listener>
177
- : unknown) &
178
- (D extends { dial: infer F } ? DialMethod<F extends "direct" ? DirectDial : Dial> : unknown) &
179
- (D extends { tls: infer P extends TlsMode } ? TlsMethod<TlsProfile[P]> : unknown) &
180
- (D extends { auth: AuthOptions } ? AuthMethod : unknown);
97
+ type ExtraRoles<T extends Target, K> = T extends "endpoints"
98
+ ? | (K extends keyof typeof endpointRoles ? (typeof endpointRoles)[K] : never)
99
+ | (K extends (typeof preferredRouteEndpoints)[number] ? "preferred-routes" : never)
100
+ : T extends "outbounds"
101
+ ? K extends "bridge"
102
+ ? "preferred-routes"
103
+ : never
104
+ : T extends "services"
105
+ ? K extends "resolved"
106
+ ? "resolved-service"
107
+ : never
108
+ : T extends "dns.servers"
109
+ ? K extends (typeof preferredDnsKinds)[number]
110
+ ? "preferred-domain"
111
+ : never
112
+ : never;
113
+ type Profile<T extends Target, K, F> = "enabled" extends keyof F
114
+ ? T extends "inbounds" | "services"
115
+ ? ServerTls | (K extends "vless" ? RealityServerTls : never)
116
+ : ClientTls | (K extends "vless" ? RealityClientTls : never)
117
+ : never;
118
+ type Built<
119
+ T extends Target,
120
+ K extends Kind<T>,
121
+ V extends Tag = string,
122
+ G = Groups<T, K>,
123
+ > = Resource<T, K, V, (typeof targetRoles)[T][number] | ExtraRoles<T, K>> &
124
+ (G extends { listen: infer L } ? ListenMethod<L> : unknown) &
125
+ (G extends { dial: infer D } ? DialMethod<D> : unknown) &
126
+ (G extends { tls: infer F } ? TlsMethod<(F & { side?: never }) | Profile<T, K, F>> : unknown) &
127
+ (T extends "inbounds" ? (K extends keyof typeof authOptions ? AuthMethod : unknown) : unknown);
181
128
 
182
- type SettingsGroup = "listen" | "dial" | "tls";
183
- const settingsGroups = ["listen", "dial", "tls"] as const;
184
- const validators = new WeakMap<Definition, ReturnType<typeof compileSchema>>();
129
+ type Factory<T extends Target, K extends Kind<T>> = T extends "services" | "http_clients"
130
+ ? {
131
+ (options: Options<T, K> & { tag: string }): Built<T, K>;
132
+ (
133
+ ...args: {} extends Options<T, K> ? [options?: Options<T, K>] : [options: Options<T, K>]
134
+ ): Built<T, K, string | undefined>;
135
+ }
136
+ : (options: Options<T, K>) => Built<T, K>;
185
137
 
186
- function validateFactoryOutput(def: Definition, fields: Fields, path: string): void {
187
- let validate = validators.get(def);
188
- if (!validate) {
189
- const name = targetSchema[def.target];
190
- validate = compileSchema(
191
- def.target === "http_clients" ? definition(name) : variant(name, def.kind),
192
- );
193
- validators.set(def, validate);
194
- }
195
- checkSchema(validate, fields, path);
196
- }
138
+ type Factories<T extends Target> = { [K in Kind<T> as CamelCase<K>]: Factory<T, K> };
197
139
 
198
140
  interface Membership {
199
141
  readonly user?: User;
200
142
  readonly name: unknown;
201
143
  }
202
-
203
144
  function prepareUsers(fields: Fields, auth: AuthOptions, path: string): readonly Membership[] {
204
145
  if (fields.users === undefined) return [];
205
146
  const users = fields.users;
@@ -244,237 +185,6 @@ function validateTag(tag: unknown, path: string): void {
244
185
  }
245
186
  }
246
187
 
247
- function build<D extends Definition, T extends Tag>(def: D, input: unknown): Built<D, T> {
248
- const path = `${def.target}.${def.kind}`;
249
- const options = fieldsFrom(input, path, [...def.required, ...(def.optional ?? [])], def.required);
250
- validateTag(options.tag, `${path}.tag`);
251
- const members = def.auth ? prepareUsers(options, def.auth, path) : [];
252
- const extraRoles = def.prepare?.(options, path) ?? [];
253
- const roles = Object.freeze([...targetRoles[def.target], ...(def.roles ?? []), ...extraRoles]);
254
- const base = snapshot(
255
- def.target === "http_clients" ? options : { type: def.kind, ...options },
256
- path,
257
- );
258
- const references = Object.freeze({
259
- ...def.references,
260
- ...(def.listen ? listenReferences : {}),
261
- ...(def.dial ? dialReferences : {}),
262
- ...(def.tls ? { tls: expandTls } : {}),
263
- });
264
-
265
- function create(groups: Partial<Record<SettingsGroup, Fields>>): Built<D, T> {
266
- const fields = { ...base };
267
- for (const group of settingsGroups) {
268
- for (const [key, value] of Object.entries(groups[group] ?? {})) {
269
- if (Object.hasOwn(fields, key)) fail(keyPath(path, key), "conflicting output field");
270
- fields[key] = value;
271
- }
272
- }
273
- validateFactoryOutput(def, expandFields(fields, references, path, previewReference), path);
274
-
275
- const apply = (group: SettingsGroup, getFields: () => Fields) => {
276
- if (groups[group]) fail(keyPath(path, group), "settings group already applied");
277
- return create({ ...groups, [group]: snapshot(getFields(), path) });
278
- };
279
- const methods: Fields = {};
280
- if (def.listen)
281
- methods.listen = (address: string, input: unknown) =>
282
- apply("listen", () => listenFields(address, input, path, def.listen === "forwarding"));
283
- if (def.dial)
284
- methods.dial = (input: unknown) =>
285
- apply("dial", () => {
286
- const dial = dialFields(input, path, def.dial === "detour");
287
- def.checkDial?.(fields, dial, path);
288
- return dial;
289
- });
290
- const tlsMode = def.tls;
291
- if (tlsMode)
292
- methods.tls = (input: unknown) =>
293
- apply("tls", () => tlsFields(input, `${path}.tls`, tlsMode));
294
- if (def.auth)
295
- methods.authUser = (user: User) => {
296
- const matching = members.filter((entry) => entry.user === user);
297
- if (
298
- !isUser(user) ||
299
- matching.length !== 1 ||
300
- !user.name ||
301
- members.filter((entry) => entry.name === user.name).length !== 1
302
- ) {
303
- fail(`${path}.authUser`, "expected one User entry with a unique non-empty name");
304
- }
305
- return Rule.match({
306
- inbound: resource as unknown as Resource<"inbounds", string, string>,
307
- auth_user: user.name,
308
- });
309
- };
310
- const resource = createResource<Built<D, T>>(
311
- Object.freeze({
312
- target: def.target,
313
- kind: def.kind,
314
- fields: Object.freeze(fields),
315
- references,
316
- roles,
317
- remoteDns: def.remoteDns,
318
- startupDetour: def.startupDetour,
319
- }),
320
- methods,
321
- );
322
- return resource;
323
- }
324
- return create({});
325
- }
326
-
327
- function factory<const D extends Definition>(def: D) {
328
- return (options: Options<D>): Built<D> => build(def, options);
329
- }
330
-
331
- const passwordAuth = {
332
- name: "username",
333
- credentials: ["password"],
334
- required: ["password"],
335
- } as const;
336
- const mixed = {
337
- target: "inbounds",
338
- kind: "mixed",
339
- required: ["tag"],
340
- optional: ["users", "set_system_proxy"],
341
- listen: "forwarding",
342
- tls: "server",
343
- auth: { ...passwordAuth, allowRaw: true },
344
- } as const satisfies Definition;
345
- const socks = {
346
- target: "inbounds",
347
- kind: "socks",
348
- required: ["tag"],
349
- optional: ["users"],
350
- listen: "forwarding",
351
- auth: passwordAuth,
352
- } as const satisfies Definition;
353
- const inboundVless = {
354
- target: "inbounds",
355
- kind: "vless",
356
- required: ["tag", "users"],
357
- listen: "forwarding",
358
- tls: "server-reality",
359
- auth: { name: "name", credentials: ["uuid", "flow"], required: ["uuid"] },
360
- } as const satisfies Definition;
361
-
362
- const shadowsocks = {
363
- target: "inbounds",
364
- kind: "shadowsocks",
365
- required: ["tag", "method"],
366
- optional: ["network", "password", "users", "managed"],
367
- listen: "forwarding",
368
- auth: { ...passwordAuth, name: "name", allowRaw: true },
369
- prepare(fields, path) {
370
- const hasUsers = Array.isArray(fields.users) && fields.users.length > 0;
371
- if (hasUsers && fields.managed === true)
372
- fail(`${path}.users`, "managed mode cannot have static users");
373
- if (hasUsers || fields.managed === true) {
374
- if (fields.method === "none")
375
- fail(`${path}.method`, "method none is unavailable in multi-user modes");
376
- return ["ssm"];
377
- }
378
- },
379
- } as const satisfies Definition;
380
- type ShadowsocksBase = Omit<Options<typeof shadowsocks>, "method" | "users" | "managed">;
381
- type Method = NonNullable<Extract<RawInbound, { type: "shadowsocks" }>["method"]>;
382
- type MultiMethod = Exclude<Method, "none">;
383
- type ManagedShadowsocks = ShadowsocksBase & {
384
- method: MultiMethod;
385
- managed: true;
386
- users?: readonly [];
387
- };
388
- type StaticShadowsocks = ShadowsocksBase & {
389
- method: MultiMethod;
390
- managed?: false;
391
- users: readonly [ShadowsocksEntry, ...ShadowsocksEntry[]];
392
- };
393
- type ShadowsocksOptions = ShadowsocksBase &
394
- (
395
- | { method: Method; managed?: false; users?: readonly [] }
396
- | { method: MultiMethod; managed?: boolean; users?: readonly [] }
397
- | { method: MultiMethod; managed?: false; users?: readonly ShadowsocksEntry[] }
398
- );
399
- function makeShadowsocks(
400
- options: ManagedShadowsocks | StaticShadowsocks,
401
- ): Built<typeof shadowsocks> & SsmInbound;
402
- function makeShadowsocks(options: ShadowsocksOptions): Built<typeof shadowsocks>;
403
- function makeShadowsocks(options: ShadowsocksOptions): Built<typeof shadowsocks> {
404
- return build(shadowsocks, options);
405
- }
406
-
407
- export const inbound = Object.freeze({
408
- mixed: (options: Override<Options<typeof mixed>, { users?: readonly MixedEntry[] }>) =>
409
- build<typeof mixed, string>(mixed, options),
410
- socks: (
411
- options: Override<Options<typeof socks>, { users?: readonly PasswordEntry<"username">[] }>,
412
- ) => build<typeof socks, string>(socks, options),
413
- vless: (options: Override<Options<typeof inboundVless>, { users: readonly VlessEntry[] }>) =>
414
- build<typeof inboundVless, string>(inboundVless, options),
415
- shadowsocks: makeShadowsocks,
416
- });
417
-
418
- const api = {
419
- target: "services",
420
- kind: "api",
421
- required: [],
422
- optional: [
423
- "tag",
424
- "secret",
425
- "dashboard",
426
- "access_control_allow_origin",
427
- "access_control_allow_private_network",
428
- ],
429
- listen: "listener",
430
- tls: "server",
431
- references: { dashboard: expandDashboard },
432
- } as const satisfies Definition;
433
- type RawDashboard = NonNullable<Extract<RawService, { type: "api" }>["dashboard"]>;
434
- type Dashboard =
435
- | boolean
436
- | string
437
- | Override<ReadonlyJson<Extract<RawDashboard, object>>, { http_client?: HttpClientInput }>;
438
- const ssmApi = {
439
- target: "services",
440
- kind: "ssm-api",
441
- required: ["servers"],
442
- optional: ["tag", "cache_path"],
443
- listen: "listener",
444
- tls: "server",
445
- references: { servers: expandSsmServers },
446
- } as const satisfies Definition;
447
-
448
- export const service = Object.freeze({
449
- /**
450
- * sing-box defaults to loopback (127.0.0.1). An omitted or empty secret allows
451
- * unauthenticated connections. Omitting server TLS uses plaintext TCP.
452
- */
453
- api: (options: Override<Options<typeof api>, { dashboard?: Dashboard }> = {}) =>
454
- build<typeof api, string | undefined>(api, options),
455
- ssmApi: (
456
- options: Override<Options<typeof ssmApi>, { servers: Readonly<Record<string, SsmInbound>> }>,
457
- ) => build<typeof ssmApi, string | undefined>(ssmApi, options),
458
- });
459
-
460
- const http = {
461
- target: "http_clients",
462
- kind: "http-client",
463
- required: [],
464
- optional: ["version", "headers", "tag"],
465
- dial: "detour",
466
- tls: "client",
467
- } as const satisfies Definition;
468
- export function httpClient(
469
- options: Options<typeof http> & { tag: string },
470
- ): Built<typeof http, string>;
471
- export function httpClient(options?: Options<typeof http>): Built<typeof http, string | undefined>;
472
- export function httpClient(
473
- options: Options<typeof http> = {},
474
- ): Built<typeof http, string | undefined> {
475
- return build(http, options);
476
- }
477
-
478
188
  function checkGroup(fields: Fields, path: string): void {
479
189
  const candidates = fields.outbounds;
480
190
  if (!Array.isArray(candidates) || candidates.length === 0)
@@ -492,127 +202,6 @@ function checkGroup(fields: Fields, path: string): void {
492
202
  fail(`${path}.default`, "default must be a candidate");
493
203
  }
494
204
  }
495
- const selector = {
496
- target: "outbounds",
497
- kind: "selector",
498
- required: ["tag", "outbounds"],
499
- optional: ["default", "interrupt_exist_connections"],
500
- prepare: checkGroup,
501
- references: { outbounds: arrayOrOne(ref("egress")), default: ref("egress") },
502
- } as const satisfies Definition;
503
- const urltest = {
504
- target: "outbounds",
505
- kind: "urltest",
506
- required: ["tag", "outbounds"],
507
- optional: ["url", "interval", "tolerance", "idle_timeout", "interrupt_exist_connections"],
508
- prepare: checkGroup,
509
- references: { outbounds: arrayOrOne(ref("egress")) },
510
- } as const satisfies Definition;
511
- export const outbound = Object.freeze({
512
- direct: factory({ target: "outbounds", kind: "direct", required: ["tag"], dial: "direct" }),
513
- vless: factory({
514
- target: "outbounds",
515
- kind: "vless",
516
- required: ["tag", "server", "server_port", "uuid"],
517
- optional: ["flow"],
518
- dial: "detour",
519
- tls: "client-reality",
520
- startupDetour: true,
521
- }),
522
- selector: (
523
- options: Override<Options<typeof selector>, { outbounds: readonly Egress[]; default?: Egress }>,
524
- ) => build<typeof selector, string>(selector, options),
525
- urltest: (options: Override<Options<typeof urltest>, { outbounds: readonly Egress[] }>) =>
526
- build<typeof urltest, string>(urltest, options),
527
- });
528
-
529
- export const endpoint = Object.freeze({
530
- tailscale: factory({
531
- target: "endpoints",
532
- kind: "tailscale",
533
- required: ["tag"],
534
- optional: [
535
- "state_directory",
536
- "auth_key",
537
- "hostname",
538
- "accept_routes",
539
- "exit_node",
540
- "listen_port",
541
- ],
542
- dial: "detour",
543
- roles: ["preferred-routes", "tailscale-endpoint"],
544
- }),
545
- wireguard: factory({
546
- target: "endpoints",
547
- kind: "wireguard",
548
- required: ["tag", "address", "private_key"],
549
- optional: ["peers", "listen_port", "system"],
550
- dial: "detour",
551
- startupDetour: true,
552
- roles: ["preferred-routes"],
553
- checkDial(fields, dial, path) {
554
- if (
555
- dial.detour !== undefined &&
556
- fields.listen_port !== undefined &&
557
- fields.listen_port !== 0
558
- ) {
559
- fail(`${path}.listen_port`, "non-zero WireGuard listen port with detour");
560
- }
561
- },
562
- }),
563
- });
564
-
565
- const remoteDns = {
566
- target: "dns.servers",
567
- required: ["tag", "server"],
568
- optional: ["server_port"],
569
- dial: "detour",
570
- remoteDns: true,
571
- } as const;
572
- const tailscaleDns = {
573
- target: "dns.servers",
574
- kind: "tailscale",
575
- required: ["tag", "endpoint"],
576
- optional: ["accept_default_resolvers", "accept_search_domain"],
577
- roles: ["preferred-domain"],
578
- references: { endpoint: ref("tailscale-endpoint") },
579
- } as const satisfies Definition;
580
- export const dnsServer = Object.freeze({
581
- tcp: factory({ ...remoteDns, kind: "tcp" }),
582
- udp: factory({ ...remoteDns, kind: "udp" }),
583
- tls: factory({ ...remoteDns, kind: "tls", tls: "client" }),
584
- https: factory({
585
- ...remoteDns,
586
- kind: "https",
587
- tls: "client",
588
- optional: ["server_port", "path", "headers"],
589
- }),
590
- tailscale: (options: Override<Options<typeof tailscaleDns>, { endpoint: TailscaleEndpoint }>) =>
591
- build<typeof tailscaleDns, string>(tailscaleDns, options),
592
- });
593
-
594
- const tailscaleProvider = {
595
- target: "certificate_providers",
596
- kind: "tailscale",
597
- required: ["tag", "endpoint"],
598
- references: { endpoint: ref("tailscale-endpoint") },
599
- } as const satisfies Definition;
600
- export const certificateProvider = Object.freeze({
601
- tailscale: (
602
- options: Override<Options<typeof tailscaleProvider>, { endpoint: TailscaleEndpoint }>,
603
- ) => build<typeof tailscaleProvider, string>(tailscaleProvider, options),
604
- });
605
-
606
- export const networkNamespace = Object.freeze({
607
- default: factory({ target: "network_namespaces", kind: "default", required: ["tag", "path"] }),
608
- unshare: factory({
609
- target: "network_namespaces",
610
- kind: "unshare",
611
- required: ["tag"],
612
- optional: ["pid_file"],
613
- }),
614
- });
615
-
616
205
  function ruleSetFormat(fields: Fields, path: string, location: "path" | "url"): void {
617
206
  const input = fields[location];
618
207
  if (typeof input !== "string") fail(keyPath(path, location), "expected a string");
@@ -632,50 +221,244 @@ function ruleSetFormat(fields: Fields, path: string, location: "path" | "url"):
632
221
  else fail(`${path}.format`, "cannot infer rule-set format");
633
222
  }
634
223
 
635
- const inlineRuleSet = {
636
- target: "route.rule_set",
637
- kind: "inline",
638
- required: ["tag", "rules"],
639
- prepare(fields, path) {
640
- if (!Array.isArray(fields.rules) || !fields.rules.length)
641
- fail(`${path}.rules`, "expected at least one rule");
642
- },
643
- } as const satisfies Definition;
644
- const localRuleSet = {
645
- target: "route.rule_set",
646
- kind: "local",
647
- required: ["tag", "path"],
648
- optional: ["format"],
649
- prepare: (fields, path) => ruleSetFormat(fields, path, "path"),
650
- } as const satisfies Definition;
651
- const remoteRuleSet = {
652
- target: "route.rule_set",
653
- kind: "remote",
654
- required: ["tag", "url"],
655
- optional: ["format", "initial_path", "update_interval", "http_client"],
656
- references: { http_client: expandHttpClient },
657
- prepare: (fields, path) => ruleSetFormat(fields, path, "url"),
658
- } as const satisfies Definition;
659
- function requireSingleTag(fields: Fields, path: string): void {
660
- if (typeof fields.tag !== "string") fail(`${path}.tag`, "expected a single tag");
224
+ type SettingsGroup = "listen" | "dial" | "tls";
225
+ const settingsGroups = ["listen", "dial", "tls"] as const;
226
+
227
+ function prepareOptions(
228
+ target: Target,
229
+ kind: string,
230
+ options: Fields,
231
+ path: string,
232
+ roles: Role[],
233
+ ): void {
234
+ if (target === "inbounds" && kind === "shadowsocks") {
235
+ const hasUsers = Array.isArray(options.users) && options.users.length > 0;
236
+ if (hasUsers && options.managed === true)
237
+ fail(`${path}.users`, "managed mode cannot have static users");
238
+ if (hasUsers || options.managed === true) {
239
+ if (options.method === "none")
240
+ fail(`${path}.method`, "method none is unavailable in multi-user modes");
241
+ roles.push("ssm");
242
+ }
243
+ }
244
+ if (target === "outbounds" && (kind === "selector" || kind === "urltest"))
245
+ checkGroup(options, path);
246
+ if (target === "services" && kind === "ssm-api")
247
+ checkSsmServers(options.servers, `${path}.servers`);
248
+ if (target === "route.rule_set") {
249
+ if (kind === "inline") {
250
+ if (typeof options.tag !== "string") fail(`${path}.tag`, "expected a single tag");
251
+ if (!Array.isArray(options.rules) || !options.rules.length)
252
+ fail(`${path}.rules`, "expected at least one rule");
253
+ } else {
254
+ ruleSetFormat(options, path, kind === "local" ? "path" : "url");
255
+ }
256
+ }
661
257
  }
662
258
 
663
- export const ruleSet = Object.freeze({
664
- inline(options: {
665
- tag: string;
666
- rules: readonly ReadonlyJson<HeadlessRule>[];
667
- }): Built<typeof inlineRuleSet> {
668
- requireSingleTag(record(options, "ruleSet.inline"), "ruleSet.inline");
669
- return build(inlineRuleSet, options);
670
- },
671
- local<const T extends string | readonly string[]>(
672
- options: Override<Options<typeof localRuleSet>, { tag: T }>,
673
- ) {
674
- return build<typeof localRuleSet, T>(localRuleSet, options);
675
- },
676
- remote<const T extends string | readonly string[]>(
677
- options: Override<Options<typeof remoteRuleSet>, { tag: T; http_client?: HttpClientInput }>,
678
- ) {
679
- return build<typeof remoteRuleSet, T>(remoteRuleSet, options);
259
+ function getRoles(target: Target, kind: string): Role[] {
260
+ const roles: Role[] = [...targetRoles[target]];
261
+ if (target === "endpoints") {
262
+ if (Object.hasOwn(endpointRoles, kind))
263
+ roles.push(endpointRoles[kind as keyof typeof endpointRoles]);
264
+ if (preferredRouteEndpoints.some((preferred) => preferred === kind))
265
+ roles.push("preferred-routes");
266
+ }
267
+ if (target === "outbounds" && kind === "bridge") roles.push("preferred-routes");
268
+ if (target === "dns.servers" && preferredDnsKinds.some((preferred) => preferred === kind))
269
+ roles.push("preferred-domain");
270
+ if (target === "services" && kind === "resolved") roles.push("resolved-service");
271
+ return roles;
272
+ }
273
+
274
+ function makeFactory(target: Target, kind: string, branches: FactoryBranch[]) {
275
+ const path = `${target}.${kind}`;
276
+ const validators = new Map<FactoryBranch, ReturnType<typeof compileSchema>>();
277
+ const auth =
278
+ target === "inbounds" && Object.hasOwn(authOptions, kind)
279
+ ? authOptions[kind as keyof typeof authOptions]
280
+ : undefined;
281
+ return (input: unknown = {}): Resource => {
282
+ const raw = record(input, path);
283
+ const branch =
284
+ branches.length === 1
285
+ ? branches[0]!
286
+ : branches.find((item) => matchesDiscriminators(item.options, raw));
287
+ if (!branch) {
288
+ const discriminator = branches[0]?.options.properties?.version ? "version" : "provider";
289
+ fail(keyPath(path, discriminator), "invalid or missing branch discriminator");
290
+ }
291
+ const options = fieldsFrom(
292
+ raw,
293
+ path,
294
+ Object.keys(branch.options.properties!),
295
+ branch.options.required,
296
+ );
297
+ validateTag(options.tag, `${path}.tag`);
298
+ const members = auth ? prepareUsers(options, auth, path) : [];
299
+ const roles = getRoles(target, kind);
300
+ prepareOptions(target, kind, options, path, roles);
301
+ const base = snapshot(target === "http_clients" ? options : { type: kind, ...options }, path);
302
+ const expand = (value: unknown, path: string, resolve: Parameters<typeof expandInput>[3]) =>
303
+ expandInput(branch.output, value, path, resolve);
304
+
305
+ const validate = validators.get(branch) ?? compileSchema(branch.output);
306
+ validators.set(branch, validate);
307
+ const { listen, dial, tls } = branch;
308
+
309
+ function create(groups: Partial<Record<SettingsGroup, Fields>>): Resource {
310
+ const fields = { ...base };
311
+ for (const group of settingsGroups) {
312
+ for (const [key, value] of Object.entries(groups[group] ?? {})) {
313
+ if (Object.hasOwn(fields, key)) fail(keyPath(path, key), "conflicting output field");
314
+ fields[key] = value;
315
+ }
316
+ }
317
+ checkSchema(validate, expand(fields, path, previewReference), path);
318
+
319
+ const apply = (group: SettingsGroup, getFields: () => Fields) => {
320
+ if (groups[group]) fail(keyPath(path, group), "settings group already applied");
321
+ return create({ ...groups, [group]: snapshot(getFields(), path) });
322
+ };
323
+ const methods: Fields = {};
324
+ if (listen) {
325
+ methods.listen = (address?: unknown, input: unknown = {}) =>
326
+ apply("listen", () =>
327
+ address !== null && typeof address === "object"
328
+ ? listenFields(undefined, address, path, listen)
329
+ : listenFields(address, input, path, listen),
330
+ );
331
+ }
332
+ if (dial) {
333
+ methods.dial = (input: unknown) =>
334
+ apply("dial", () => {
335
+ const settings = fieldsFrom(input, path, Object.keys(dial.properties!));
336
+ if (
337
+ kind === "wireguard" &&
338
+ settings.detour !== undefined &&
339
+ fields.listen_port !== undefined &&
340
+ fields.listen_port !== 0
341
+ ) {
342
+ fail(`${path}.listen_port`, "non-zero WireGuard listen port with detour");
343
+ }
344
+ return settings;
345
+ });
346
+ }
347
+ if (tls) {
348
+ const name = definitionName(tls);
349
+ let mode: TlsMode | undefined;
350
+ if (name === "InboundTLSOptions") mode = kind === "vless" ? "server-reality" : "server";
351
+ if (name === "OutboundTLSOptions") mode = kind === "vless" ? "client-reality" : "client";
352
+ methods.tls = (input: unknown) =>
353
+ apply("tls", () => tlsFields(input, `${path}.tls`, tls, mode));
354
+ }
355
+ if (auth) {
356
+ methods.authUser = (user: User) => {
357
+ if (
358
+ !isUser(user) ||
359
+ members.filter((entry) => entry.user === user).length !== 1 ||
360
+ !user.name ||
361
+ members.filter((entry) => entry.name === user.name).length !== 1
362
+ ) {
363
+ fail(`${path}.authUser`, "expected one User entry with a unique non-empty name");
364
+ }
365
+ return Rule.match({
366
+ inbound: resource as Resource<"inbounds", string, string>,
367
+ auth_user: user.name,
368
+ });
369
+ };
370
+ }
371
+ const resource = createResource(
372
+ Object.freeze({
373
+ target,
374
+ kind,
375
+ fields: Object.freeze(fields),
376
+ expand,
377
+ roles: Object.freeze(roles),
378
+ remoteDns: target === "dns.servers" && Object.hasOwn(base, "server"),
379
+ startupDetour:
380
+ (target === "outbounds" && kind === "vless") ||
381
+ (target === "endpoints" && kind === "wireguard"),
382
+ }),
383
+ methods,
384
+ );
385
+ return resource;
386
+ }
387
+ return create({});
388
+ };
389
+ }
390
+
391
+ function factoriesFor<T extends Target>(target: T): Factories<T> {
392
+ return Object.fromEntries(
393
+ Array.from(factoryCatalog(target), ([kind, branches]) => [
394
+ factoryName(kind),
395
+ makeFactory(target, kind, branches),
396
+ ]),
397
+ ) as Factories<T>;
398
+ }
399
+
400
+ type ShadowsocksBase = Omit<Options<"inbounds", "shadowsocks">, "method" | "users" | "managed">;
401
+ type Method = Options<"inbounds", "shadowsocks">["method"];
402
+ type MultiMethod = Exclude<Method, "none">;
403
+ type ManagedShadowsocks = ShadowsocksBase & {
404
+ method: MultiMethod;
405
+ managed: true;
406
+ users?: readonly [];
407
+ };
408
+ type StaticShadowsocks = ShadowsocksBase & {
409
+ method: MultiMethod;
410
+ managed?: false;
411
+ users: readonly [ShadowsocksEntry, ...ShadowsocksEntry[]];
412
+ };
413
+ type ShadowsocksOptions = ShadowsocksBase &
414
+ (
415
+ | { method: Method; managed?: false; users?: readonly [] }
416
+ | { method: MultiMethod; managed?: boolean; users?: readonly [] }
417
+ | { method: MultiMethod; managed?: false; users?: readonly ShadowsocksEntry[] }
418
+ );
419
+
420
+ type AuthOptionsFor<K extends "mixed" | "socks" | "vless", U> = Omit<
421
+ Options<"inbounds", K>,
422
+ "users"
423
+ > &
424
+ U;
425
+ type InboundFactories = Omit<Factories<"inbounds">, keyof typeof authOptions> & {
426
+ mixed(
427
+ options: AuthOptionsFor<"mixed", { users?: readonly MixedEntry[] }>,
428
+ ): Built<"inbounds", "mixed">;
429
+ socks(
430
+ options: AuthOptionsFor<"socks", { users?: readonly PasswordEntry<"username">[] }>,
431
+ ): Built<"inbounds", "socks">;
432
+ vless(
433
+ options: AuthOptionsFor<"vless", { users: readonly VlessEntry[] }>,
434
+ ): Built<"inbounds", "vless">;
435
+ shadowsocks: {
436
+ (
437
+ options: ManagedShadowsocks | StaticShadowsocks,
438
+ ): Built<"inbounds", "shadowsocks"> & SsmInbound;
439
+ (options: ShadowsocksOptions): Built<"inbounds", "shadowsocks">;
440
+ };
441
+ };
442
+
443
+ type RuleSetFactory<K extends "local" | "remote"> = <const T extends string | readonly string[]>(
444
+ options: Omit<Options<"route.rule_set", K>, "tag"> & { readonly tag: T },
445
+ ) => Built<"route.rule_set", K, T>;
446
+
447
+ export const inbound = Object.freeze(factoriesFor("inbounds") as unknown as InboundFactories);
448
+ export const outbound = Object.freeze(factoriesFor("outbounds"));
449
+ export const endpoint = Object.freeze(factoriesFor("endpoints"));
450
+ export const service = Object.freeze(factoriesFor("services"));
451
+ export const dnsServer = Object.freeze(factoriesFor("dns.servers"));
452
+ export const certificateProvider = Object.freeze(factoriesFor("certificate_providers"));
453
+ export const networkNamespace = Object.freeze(factoriesFor("network_namespaces"));
454
+ export const httpClient: Factory<"http_clients", "http-client"> =
455
+ factoriesFor("http_clients").httpClient;
456
+ export const ruleSet = Object.freeze(
457
+ factoriesFor("route.rule_set") as {
458
+ inline(
459
+ options: Omit<Options<"route.rule_set", "inline">, "tag"> & { tag: string },
460
+ ): Built<"route.rule_set", "inline">;
461
+ local: RuleSetFactory<"local">;
462
+ remote: RuleSetFactory<"remote">;
680
463
  },
681
- });
464
+ );