sing-box-kit 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,681 @@
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";
16
+ import {
17
+ arrayOrOne,
18
+ createResource,
19
+ expandFields,
20
+ fieldsFrom,
21
+ record,
22
+ ref,
23
+ resourceData,
24
+ snapshot,
25
+ } 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";
37
+ import { Rule } from "./rules";
38
+ import type { Condition } from "./rules";
39
+ import { checkSchema, compileSchema, definition, fail, keyPath, variant } from "./schema";
40
+ import {
41
+ dialFields,
42
+ dialReferences,
43
+ expandDashboard,
44
+ expandHttpClient,
45
+ expandSsmServers,
46
+ expandTls,
47
+ listenFields,
48
+ listenReferences,
49
+ previewReference,
50
+ tlsFields,
51
+ } 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";
64
+ import { isUser } from "./user";
65
+ import type { User } from "./user";
66
+
67
+ interface ListenMethod<T> {
68
+ listen(address: string, options: T): this;
69
+ }
70
+ interface DialMethod<T> {
71
+ dial(options: T): this;
72
+ }
73
+ interface TlsMethod<T> {
74
+ tls(profile: T): this;
75
+ }
76
+ interface AuthMethod {
77
+ authUser(user: User): Condition;
78
+ }
79
+
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
+ const targetRoles = {
92
+ inbounds: ["inbound", "listen-detour"],
93
+ outbounds: ["egress"],
94
+ endpoints: ["egress", "inbound"],
95
+ services: [],
96
+ http_clients: ["http-client"],
97
+ "dns.servers": ["dns-server"],
98
+ "route.rule_set": ["rule-set"],
99
+ certificate_providers: ["certificate-provider"],
100
+ network_namespaces: ["netns"],
101
+ } as const satisfies Record<Target, readonly Role[]>;
102
+
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
+ }
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;
160
+
161
+ type TlsProfile = {
162
+ server: ServerTls;
163
+ client: ClientTls;
164
+ "server-reality": ServerTls | RealityServerTls;
165
+ "client-reality": ClientTls | RealityClientTls;
166
+ };
167
+ 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);
181
+
182
+ type SettingsGroup = "listen" | "dial" | "tls";
183
+ const settingsGroups = ["listen", "dial", "tls"] as const;
184
+ const validators = new WeakMap<Definition, ReturnType<typeof compileSchema>>();
185
+
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
+ }
197
+
198
+ interface Membership {
199
+ readonly user?: User;
200
+ readonly name: unknown;
201
+ }
202
+
203
+ function prepareUsers(fields: Fields, auth: AuthOptions, path: string): readonly Membership[] {
204
+ if (fields.users === undefined) return [];
205
+ const users = fields.users;
206
+ if (!Array.isArray(users)) fail(`${path}.users`, "expected an array");
207
+ const members: Membership[] = [];
208
+ fields.users = Array.from(users, (value, index) => {
209
+ 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;
215
+ }
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 };
227
+ });
228
+ return members;
229
+ }
230
+
231
+ function validateTag(tag: unknown, path: string): void {
232
+ if (tag === undefined) return;
233
+ if (Array.isArray(tag)) {
234
+ if (tag.length === 0) fail(path, "expected at least one tag");
235
+ const seen = new Set<string>();
236
+ Array.from(tag).forEach((value, index) => {
237
+ const field = `${path}[${index}]`;
238
+ if (typeof value !== "string" || value === "") fail(field, "expected a non-empty tag");
239
+ if (seen.has(value)) fail(field, "duplicate tag", value);
240
+ seen.add(value);
241
+ });
242
+ } else if (typeof tag !== "string" || tag === "") {
243
+ fail(path, "expected a non-empty tag");
244
+ }
245
+ }
246
+
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
+ function checkGroup(fields: Fields, path: string): void {
479
+ const candidates = fields.outbounds;
480
+ if (!Array.isArray(candidates) || candidates.length === 0)
481
+ fail(`${path}.outbounds`, "expected at least one candidate");
482
+ const seen = new Set<string>();
483
+ Array.from(candidates).forEach((candidate, index) => {
484
+ const candidatePath = `${path}.outbounds[${index}]`;
485
+ previewReference(candidate, "egress", candidatePath);
486
+ const tag = resourceData(candidate)?.fields.tag;
487
+ if (typeof tag !== "string") return;
488
+ if (seen.has(tag)) fail(candidatePath, "duplicate candidate tag", tag);
489
+ seen.add(tag);
490
+ });
491
+ if (fields.default !== undefined && !candidates.includes(fields.default)) {
492
+ fail(`${path}.default`, "default must be a candidate");
493
+ }
494
+ }
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
+ function ruleSetFormat(fields: Fields, path: string, location: "path" | "url"): void {
617
+ const input = fields[location];
618
+ if (typeof input !== "string") fail(keyPath(path, location), "expected a string");
619
+ if (Array.isArray(fields.tag) && fields.tag.length > 1) {
620
+ const paths = location === "url" ? ["url", "initial_path"] : ["path"];
621
+ for (const key of paths) {
622
+ const value = fields[key];
623
+ if (value !== undefined && (typeof value !== "string" || !value.includes("{tag}"))) {
624
+ fail(keyPath(path, key), "multiple tags require a {tag} placeholder");
625
+ }
626
+ }
627
+ }
628
+ if (fields.format !== undefined) return;
629
+ const extension = location === "url" ? URL.parse(input)?.pathname : input;
630
+ if (extension?.endsWith(".json")) fields.format = "source";
631
+ else if (extension?.endsWith(".srs")) fields.format = "binary";
632
+ else fail(`${path}.format`, "cannot infer rule-set format");
633
+ }
634
+
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");
661
+ }
662
+
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);
680
+ },
681
+ });