sing-box-kit 0.1.1 → 0.1.3

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,43 @@
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 } 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
26
  import type {
53
27
  ClientTls,
54
- Dial,
55
- DirectDial,
56
- HttpClientInput,
57
- InboundListener,
58
- Listener,
28
+ ProtocolTlsOptions,
59
29
  RealityClientTls,
60
30
  RealityServerTls,
61
31
  ServerTls,
62
32
  TlsMode,
63
33
  } from "./settings";
64
- import { isUser } from "./user";
34
+ import type { CamelCase, Fields, ReadonlyJson, StrictUnion } from "./type-utils";
35
+ import { isUser, requireUserCredentials } from "./user";
65
36
  import type { User } from "./user";
66
37
 
67
38
  interface ListenMethod<T> {
68
- listen(address: string, options: T): this;
39
+ listen(options?: T): this;
40
+ listen(address?: "port" extends keyof T ? string : undefined, options?: T): this;
69
41
  }
70
42
  interface DialMethod<T> {
71
43
  dial(options: T): this;
@@ -77,17 +49,6 @@ interface AuthMethod {
77
49
  authUser(user: User): Condition;
78
50
  }
79
51
 
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
52
  const targetRoles = {
92
53
  inbounds: ["inbound", "listen-detour"],
93
54
  outbounds: ["egress"],
@@ -100,130 +61,113 @@ const targetRoles = {
100
61
  network_namespaces: ["netns"],
101
62
  } as const satisfies Record<Target, readonly Role[]>;
102
63
 
103
- type PasswordEntry<Name extends "username" | "name"> = {
104
- readonly user: User;
105
- readonly password: string;
106
- } & { readonly [K in Name]?: never };
107
- type MixedEntry = PasswordEntry<"username"> | (Readonly<RawUser> & { user?: never });
108
- type ShadowsocksEntry = PasswordEntry<"name"> | (Readonly<ShadowsocksUser> & { user?: never });
109
- type VlessEntry = Required<Pick<VLESSUser, "uuid">> &
110
- Pick<VLESSUser, "flow"> & { user: User; name?: never };
111
-
112
- interface AuthOptions {
113
- readonly name: "name" | "username";
114
- readonly credentials: readonly string[];
115
- readonly required: readonly string[];
116
- readonly allowRaw?: boolean;
117
- }
118
-
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
- }
64
+ const endpointRoles = {
65
+ tailscale: "tailscale-endpoint",
66
+ openconnect: "openconnect-endpoint",
67
+ "openvpn-client": "openvpn-client-endpoint",
68
+ } as const satisfies Record<string, Role>;
135
69
 
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;
70
+ const namedAuth = { name: "name", allowRaw: true } as const;
71
+ const usernameAuth = { name: "username", allowRaw: true } as const;
72
+ const authOptions = {
73
+ anytls: namedAuth,
74
+ http: usernameAuth,
75
+ hysteria: namedAuth,
76
+ hysteria2: namedAuth,
77
+ mixed: usernameAuth,
78
+ naive: usernameAuth,
79
+ shadowsocks: namedAuth,
80
+ shadowtls: namedAuth,
81
+ snell: namedAuth,
82
+ socks: { name: "username", allowRaw: false },
83
+ trojan: namedAuth,
84
+ tuic: namedAuth,
85
+ vless: { name: "name", allowRaw: false },
86
+ vmess: namedAuth,
87
+ } as const;
88
+ type AuthKind = keyof typeof authOptions;
89
+ type ShadowsocksEntry = User | (Readonly<ShadowsocksUser> & { user?: never });
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 StrictTransport<O> = O extends { readonly transport?: infer V }
95
+ ? O & { readonly transport?: StrictUnion<NonNullable<V>> }
96
+ : O;
97
+ type Options<T extends Target, K extends Kind<T>> =
98
+ Groups<T, K> extends { options: infer O } ? StrictUnion<StrictTransport<O>> : never;
167
99
  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>
100
+ type ExtraRoles<T extends Target, K> = T extends "endpoints"
101
+ ? | (K extends keyof typeof endpointRoles ? (typeof endpointRoles)[K] : never)
102
+ | (K extends (typeof preferredRouteEndpoints)[number] ? "preferred-routes" : never)
103
+ : T extends "outbounds"
104
+ ? K extends "bridge"
105
+ ? "preferred-routes"
106
+ : never
107
+ : T extends "services"
108
+ ? K extends "resolved"
109
+ ? "resolved-service"
110
+ : never
111
+ : T extends "dns.servers"
112
+ ? K extends (typeof preferredDnsKinds)[number]
113
+ ? "preferred-domain"
114
+ : never
115
+ : never;
116
+ type Profile<T extends Target, K, F> = "enabled" extends keyof F
117
+ ? T extends "inbounds" | "services"
118
+ ? ServerTls | (K extends "vless" ? RealityServerTls : never)
119
+ : ClientTls | (K extends "vless" ? RealityClientTls : never)
120
+ : never;
121
+ type Built<
122
+ T extends Target,
123
+ K extends Kind<T>,
124
+ V extends Tag = string,
125
+ G = Groups<T, K>,
126
+ > = Resource<T, K, V, (typeof targetRoles)[T][number] | ExtraRoles<T, K>> &
127
+ (G extends { listen: infer L } ? ListenMethod<L> : unknown) &
128
+ (G extends { dial: infer D } ? DialMethod<D> : unknown) &
129
+ (G extends { tls: infer F }
130
+ ? TlsMethod<ProtocolTlsOptions<K, (F & { side?: never }) | Profile<T, K, F>>>
177
131
  : 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);
132
+ (T extends "inbounds" ? (K extends keyof typeof authOptions ? AuthMethod : unknown) : unknown);
181
133
 
182
- type SettingsGroup = "listen" | "dial" | "tls";
183
- const settingsGroups = ["listen", "dial", "tls"] as const;
184
- const validators = new WeakMap<Definition, ReturnType<typeof compileSchema>>();
134
+ type Factory<T extends Target, K extends Kind<T>> = T extends "services" | "http_clients"
135
+ ? {
136
+ (options: Options<T, K> & { tag: string }): Built<T, K>;
137
+ (
138
+ ...args: {} extends Options<T, K> ? [options?: Options<T, K>] : [options: Options<T, K>]
139
+ ): Built<T, K, string | undefined>;
140
+ }
141
+ : (options: Options<T, K>) => Built<T, K>;
185
142
 
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
- }
143
+ type Factories<T extends Target> = { [K in Kind<T> as CamelCase<K>]: Factory<T, K> };
197
144
 
198
145
  interface Membership {
199
146
  readonly user?: User;
200
147
  readonly name: unknown;
201
148
  }
202
-
203
- function prepareUsers(fields: Fields, auth: AuthOptions, path: string): readonly Membership[] {
149
+ function prepareUsers(fields: Fields, kind: AuthKind, path: string): readonly Membership[] {
204
150
  if (fields.users === undefined) return [];
205
151
  const users = fields.users;
206
152
  if (!Array.isArray(users)) fail(`${path}.users`, "expected an array");
153
+ const auth = authOptions[kind];
207
154
  const members: Membership[] = [];
208
155
  fields.users = Array.from(users, (value, index) => {
209
156
  const entryPath = `${path}.users[${index}]`;
210
- const entry = record(value, entryPath);
211
- if (!Object.hasOwn(entry, "user") && auth.allowRaw) {
212
- const raw = fieldsFrom(entry, entryPath, [auth.name, ...auth.credentials]);
213
- members.push({ name: raw[auth.name] });
214
- return raw;
157
+ if (isUser(value)) {
158
+ members.push({ user: value, name: value.name });
159
+ if (kind === "vmess") {
160
+ const { alter_id, ...credentials } = requireUserCredentials(value, kind, entryPath);
161
+ return { name: value.name, ...credentials, alterId: alter_id };
162
+ }
163
+ return { [auth.name]: value.name, ...requireUserCredentials(value, kind, entryPath) };
215
164
  }
216
- if (Object.hasOwn(entry, auth.name))
217
- fail(keyPath(entryPath, auth.name), "explicit name with User");
218
- const { user, ...credentials } = fieldsFrom(
219
- entry,
220
- entryPath,
221
- ["user", ...auth.credentials],
222
- ["user", ...auth.required],
223
- );
224
- if (!isUser(user)) fail(`${entryPath}.user`, "expected a User");
225
- members.push({ user, name: user.name });
226
- return { [auth.name]: user.name, ...credentials };
165
+ if (!auth.allowRaw) fail(entryPath, "expected a User from user()");
166
+ const raw = record(value, entryPath);
167
+ if (Object.hasOwn(raw, "user"))
168
+ fail(`${entryPath}.user`, "pass the User directly and configure credentials in user()");
169
+ members.push({ name: raw[auth.name] });
170
+ return raw;
227
171
  });
228
172
  return members;
229
173
  }
@@ -244,237 +188,6 @@ function validateTag(tag: unknown, path: string): void {
244
188
  }
245
189
  }
246
190
 
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
191
  function checkGroup(fields: Fields, path: string): void {
479
192
  const candidates = fields.outbounds;
480
193
  if (!Array.isArray(candidates) || candidates.length === 0)
@@ -492,127 +205,6 @@ function checkGroup(fields: Fields, path: string): void {
492
205
  fail(`${path}.default`, "default must be a candidate");
493
206
  }
494
207
  }
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
208
  function ruleSetFormat(fields: Fields, path: string, location: "path" | "url"): void {
617
209
  const input = fields[location];
618
210
  if (typeof input !== "string") fail(keyPath(path, location), "expected a string");
@@ -632,50 +224,246 @@ function ruleSetFormat(fields: Fields, path: string, location: "path" | "url"):
632
224
  else fail(`${path}.format`, "cannot infer rule-set format");
633
225
  }
634
226
 
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");
227
+ type SettingsGroup = "listen" | "dial" | "tls";
228
+ const settingsGroups = ["listen", "dial", "tls"] as const;
229
+
230
+ function prepareOptions(
231
+ target: Target,
232
+ kind: string,
233
+ options: Fields,
234
+ path: string,
235
+ roles: Role[],
236
+ ): void {
237
+ if (target === "inbounds" && kind === "shadowsocks") {
238
+ const hasUsers = Array.isArray(options.users) && options.users.length > 0;
239
+ if (hasUsers && options.managed === true)
240
+ fail(`${path}.users`, "managed mode cannot have static users");
241
+ if (hasUsers || options.managed === true) {
242
+ if (options.method === "none")
243
+ fail(`${path}.method`, "method none is unavailable in multi-user modes");
244
+ roles.push("ssm");
245
+ }
246
+ }
247
+ if (target === "outbounds" && (kind === "selector" || kind === "urltest"))
248
+ checkGroup(options, path);
249
+ if (target === "services" && kind === "ssm-api")
250
+ checkSsmServers(options.servers, `${path}.servers`);
251
+ if (target === "route.rule_set") {
252
+ if (kind === "inline") {
253
+ if (typeof options.tag !== "string") fail(`${path}.tag`, "expected a single tag");
254
+ if (!Array.isArray(options.rules) || !options.rules.length)
255
+ fail(`${path}.rules`, "expected at least one rule");
256
+ } else {
257
+ ruleSetFormat(options, path, kind === "local" ? "path" : "url");
258
+ }
259
+ }
661
260
  }
662
261
 
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);
262
+ function getRoles(target: Target, kind: string): Role[] {
263
+ const roles: Role[] = [...targetRoles[target]];
264
+ if (target === "endpoints") {
265
+ if (Object.hasOwn(endpointRoles, kind))
266
+ roles.push(endpointRoles[kind as keyof typeof endpointRoles]);
267
+ if (preferredRouteEndpoints.some((preferred) => preferred === kind))
268
+ roles.push("preferred-routes");
269
+ }
270
+ if (target === "outbounds" && kind === "bridge") roles.push("preferred-routes");
271
+ if (target === "dns.servers" && preferredDnsKinds.some((preferred) => preferred === kind))
272
+ roles.push("preferred-domain");
273
+ if (target === "services" && kind === "resolved") roles.push("resolved-service");
274
+ return roles;
275
+ }
276
+
277
+ function makeFactory(target: Target, kind: string, branches: FactoryBranch[]) {
278
+ const path = `${target}.${kind}`;
279
+ const validators = new Map<FactoryBranch, ReturnType<typeof compileSchema>>();
280
+ const auth =
281
+ target === "inbounds" && Object.hasOwn(authOptions, kind) ? (kind as AuthKind) : undefined;
282
+ return (input: unknown = {}): Resource => {
283
+ const raw = record(input, path);
284
+ const branch =
285
+ branches.length === 1
286
+ ? branches[0]!
287
+ : branches.find((item) => matchesDiscriminators(item.options, raw));
288
+ if (!branch) {
289
+ const discriminator = branches[0]?.options.properties?.version ? "version" : "provider";
290
+ fail(keyPath(path, discriminator), "invalid or missing branch discriminator");
291
+ }
292
+ const options = fieldsFrom(
293
+ raw,
294
+ path,
295
+ Object.keys(branch.options.properties!),
296
+ branch.options.required,
297
+ );
298
+ validateTag(options.tag, `${path}.tag`);
299
+ const users = auth ? prepareUsers(options, auth, path) : [];
300
+ const members = kind === "shadowtls" && options.version !== 3 ? [] : users;
301
+ const roles = getRoles(target, kind);
302
+ prepareOptions(target, kind, options, path, roles);
303
+ const base = snapshot(target === "http_clients" ? options : { type: kind, ...options }, path);
304
+ const expand = (value: unknown, path: string, resolve: Parameters<typeof expandInput>[3]) =>
305
+ expandInput(branch.output, value, path, resolve);
306
+
307
+ const validate = validators.get(branch) ?? compileSchema(branch.output);
308
+ validators.set(branch, validate);
309
+ const { listen, dial, tls } = branch;
310
+
311
+ function create(groups: Partial<Record<SettingsGroup, Fields>>): Resource {
312
+ const fields = { ...base };
313
+ for (const group of settingsGroups) {
314
+ for (const [key, value] of Object.entries(groups[group] ?? {})) {
315
+ if (Object.hasOwn(fields, key)) fail(keyPath(path, key), "conflicting output field");
316
+ fields[key] = value;
317
+ }
318
+ }
319
+ checkSchema(validate, expand(fields, path, previewReference), path);
320
+
321
+ const apply = (group: SettingsGroup, getFields: () => Fields) => {
322
+ if (groups[group]) fail(keyPath(path, group), "settings group already applied");
323
+ return create({ ...groups, [group]: snapshot(getFields(), path) });
324
+ };
325
+ const methods: Fields = {};
326
+ if (listen) {
327
+ methods.listen = (address?: unknown, input: unknown = {}) =>
328
+ apply("listen", () =>
329
+ address !== null && typeof address === "object"
330
+ ? listenFields(undefined, address, path, listen)
331
+ : listenFields(address, input, path, listen),
332
+ );
333
+ }
334
+ if (dial) {
335
+ methods.dial = (input: unknown) =>
336
+ apply("dial", () => {
337
+ const settings = fieldsFrom(input, path, Object.keys(dial.properties!));
338
+ if (
339
+ kind === "wireguard" &&
340
+ settings.detour !== undefined &&
341
+ fields.listen_port !== undefined &&
342
+ fields.listen_port !== 0
343
+ ) {
344
+ fail(`${path}.listen_port`, "non-zero WireGuard listen port with detour");
345
+ }
346
+ return settings;
347
+ });
348
+ }
349
+ if (tls) {
350
+ const name = definitionName(tls);
351
+ let mode: TlsMode | undefined;
352
+ if (name === "InboundTLSOptions") mode = kind === "vless" ? "server-reality" : "server";
353
+ if (name === "OutboundTLSOptions") mode = kind === "vless" ? "client-reality" : "client";
354
+ methods.tls = (input: unknown) =>
355
+ apply("tls", () => tlsFields(input, `${path}.tls`, tls, mode, kind));
356
+ }
357
+ if (auth) {
358
+ methods.authUser = (user: User) => {
359
+ if (
360
+ !isUser(user) ||
361
+ members.filter((entry) => entry.user === user).length !== 1 ||
362
+ !user.name ||
363
+ members.filter((entry) => entry.name === user.name).length !== 1
364
+ ) {
365
+ fail(`${path}.authUser`, "expected one User entry with a unique non-empty name");
366
+ }
367
+ return Rule.match({
368
+ inbound: resource as Resource<"inbounds", string, string>,
369
+ auth_user: user.name,
370
+ });
371
+ };
372
+ }
373
+ const resource = createResource(
374
+ Object.freeze({
375
+ target,
376
+ kind,
377
+ fields: Object.freeze(fields),
378
+ expand,
379
+ roles: Object.freeze(roles),
380
+ remoteDns: target === "dns.servers" && Object.hasOwn(base, "server"),
381
+ startupDetour:
382
+ (target === "outbounds" && kind === "vless") ||
383
+ (target === "endpoints" && kind === "wireguard"),
384
+ }),
385
+ methods,
386
+ );
387
+ return resource;
388
+ }
389
+ return create({});
390
+ };
391
+ }
392
+
393
+ function factoriesFor<T extends Target>(target: T): Factories<T> {
394
+ return Object.fromEntries(
395
+ Array.from(factoryCatalog(target), ([kind, branches]) => [
396
+ factoryName(kind),
397
+ makeFactory(target, kind, branches),
398
+ ]),
399
+ ) as Factories<T>;
400
+ }
401
+
402
+ type ShadowsocksBase = Omit<Options<"inbounds", "shadowsocks">, "method" | "users" | "managed">;
403
+ type Method = Options<"inbounds", "shadowsocks">["method"];
404
+ type MultiMethod = Exclude<Method, "none">;
405
+ type ManagedShadowsocks = ShadowsocksBase & {
406
+ method: MultiMethod;
407
+ managed: true;
408
+ users?: readonly [];
409
+ };
410
+ type StaticShadowsocks = ShadowsocksBase & {
411
+ method: MultiMethod;
412
+ managed?: false;
413
+ users: readonly [ShadowsocksEntry, ...ShadowsocksEntry[]];
414
+ };
415
+ type ShadowsocksOptions = ShadowsocksBase &
416
+ (
417
+ | { method: Method; managed?: false; users?: readonly [] }
418
+ | { method: MultiMethod; managed?: boolean; users?: readonly [] }
419
+ | { method: MultiMethod; managed?: false; users?: readonly ShadowsocksEntry[] }
420
+ );
421
+
422
+ type InboundUsers<O, K extends AuthKind> = O extends { users?: readonly (infer Entry)[] }
423
+ ? Omit<O, "users"> &
424
+ (O extends { users: unknown }
425
+ ? { readonly users: readonly User[] }
426
+ : {
427
+ readonly users?: readonly (
428
+ | User
429
+ | ((typeof authOptions)[K]["allowRaw"] extends true
430
+ ? Entry & { user?: never }
431
+ : never)
432
+ )[];
433
+ })
434
+ : O;
435
+ type InboundFactories = Omit<Factories<"inbounds">, AuthKind> & {
436
+ [K in Exclude<AuthKind, "shadowsocks">]: (
437
+ options: StrictUnion<InboundUsers<Options<"inbounds", K>, K>>,
438
+ ) => Built<"inbounds", K>;
439
+ } & {
440
+ shadowsocks: {
441
+ (
442
+ options: ManagedShadowsocks | StaticShadowsocks,
443
+ ): Built<"inbounds", "shadowsocks"> & SsmInbound;
444
+ (options: ShadowsocksOptions): Built<"inbounds", "shadowsocks">;
445
+ };
446
+ };
447
+
448
+ type RuleSetFactory<K extends "local" | "remote"> = <const T extends string | readonly string[]>(
449
+ options: Omit<Options<"route.rule_set", K>, "tag"> & { readonly tag: T },
450
+ ) => Built<"route.rule_set", K, T>;
451
+
452
+ export const inbound = Object.freeze(factoriesFor("inbounds") as unknown as InboundFactories);
453
+ export const outbound = Object.freeze(factoriesFor("outbounds"));
454
+ export const endpoint = Object.freeze(factoriesFor("endpoints"));
455
+ export const service = Object.freeze(factoriesFor("services"));
456
+ export const dnsServer = Object.freeze(factoriesFor("dns.servers"));
457
+ export const certificateProvider = Object.freeze(factoriesFor("certificate_providers"));
458
+ export const networkNamespace = Object.freeze(factoriesFor("network_namespaces"));
459
+ export const httpClient: Factory<"http_clients", "http-client"> =
460
+ factoriesFor("http_clients").httpClient;
461
+ export const ruleSet = Object.freeze(
462
+ factoriesFor("route.rule_set") as {
463
+ inline(
464
+ options: Omit<Options<"route.rule_set", "inline">, "tag"> & { tag: string },
465
+ ): Built<"route.rule_set", "inline">;
466
+ local: RuleSetFactory<"local">;
467
+ remote: RuleSetFactory<"remote">;
680
468
  },
681
- });
469
+ );