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.
@@ -0,0 +1,825 @@
1
+ import { createPrivateKey, createPublicKey } from "node:crypto";
2
+ import { inbound, outbound } from "./factories";
3
+ import type {
4
+ Hysteria2InboundRealm,
5
+ InboundTLSOptions,
6
+ OutboundTLSOptions,
7
+ SBKitInputs,
8
+ ShadowTLSHandshakeOptions,
9
+ V2RayTransport,
10
+ } from "./generated/sbkit-inputs";
11
+ import { fieldsFrom, record, snapshot } from "./resource";
12
+ import type { Resource, SsmInbound } from "./resource";
13
+ import { fail, keyPath } from "./schema";
14
+ import { checkTlsAlpn } from "./settings";
15
+ import type { Dial, ProtocolTlsOptions } from "./settings";
16
+ import type { Fields, ReadonlyJson, StrictUnion } from "./type-utils";
17
+ import { isUser, requireUserCredentials } from "./user";
18
+ import type { User, UserCredentials } from "./user";
19
+
20
+ type Protocol = Exclude<keyof UserCredentials, "mixed">;
21
+ type TransportProtocol = "vmess" | "vless" | "trojan";
22
+ type TlsRequired = "anytls" | "hysteria" | "hysteria2" | "naive" | "tuic";
23
+ type TlsUnsupported = "shadowsocks" | "snell" | "socks";
24
+ type Catalog = SBKitInputs["factories"];
25
+ type Options<T extends "inbounds" | "outbounds", K extends Protocol> = ReadonlyJson<
26
+ Catalog[T][K]["options"]
27
+ >;
28
+ type Inbound<K extends Protocol> = ReturnType<(typeof inbound)[K]>;
29
+ type Outbound<K extends Protocol> = ReturnType<(typeof outbound)[K]>;
30
+ type Users = readonly [User, ...User[]];
31
+ type Port = { readonly host: string; readonly port: number };
32
+ type Direct = { readonly connect: Port; readonly realm?: never };
33
+ type Hopping = { readonly host: string; readonly ports: string | readonly string[] };
34
+ type HysteriaDirect = { readonly connect: StrictUnion<Port | Hopping>; readonly realm?: never };
35
+
36
+ type Transport = StrictUnion<
37
+ | { readonly type: "tcp" | "quic" }
38
+ | ReadonlyJson<
39
+ Pick<Extract<V2RayTransport, { type: "http" }>, "type" | "host" | "path" | "method">
40
+ >
41
+ | ReadonlyJson<
42
+ Pick<
43
+ Extract<V2RayTransport, { type: "ws" }>,
44
+ "type" | "path" | "max_early_data" | "early_data_header_name"
45
+ >
46
+ >
47
+ | ReadonlyJson<Pick<Extract<V2RayTransport, { type: "grpc" }>, "type" | "service_name">>
48
+ | ReadonlyJson<Pick<Extract<V2RayTransport, { type: "httpupgrade" }>, "type" | "host" | "path">>
49
+ > & { readonly [Key in AllTransportSideFields]?: never };
50
+ type NormalTls = {
51
+ readonly mode: "tls";
52
+ readonly serverName?: string;
53
+ readonly alpn?: string | readonly string[];
54
+ };
55
+ type RealityTls = {
56
+ readonly mode: "reality";
57
+ readonly serverName: string;
58
+ readonly handshake: Port & Dial;
59
+ readonly keyPair: { readonly privateKey: string; readonly publicKey: string };
60
+ } & StrictUnion<
61
+ { readonly shortId: string } | { readonly shortIds: readonly [string, ...string[]] }
62
+ >;
63
+ type NoTls = { readonly mode: "none" };
64
+ type TransportTls<K extends TransportProtocol> = StrictUnion<
65
+ | { readonly transport: Transport; readonly tls: NormalTls }
66
+ | {
67
+ readonly transport?: Exclude<Transport, { type: "tcp" | "quic" }> | { readonly type: "tcp" };
68
+ readonly tls?: NormalTls | NoTls | (K extends "vless" ? RealityTls : never);
69
+ }
70
+ >;
71
+
72
+ const sharedOption = {
73
+ hysteria: "obfs",
74
+ hysteria2: "obfs",
75
+ shadowsocks: "method",
76
+ } as const;
77
+
78
+ const ownedServer = [
79
+ "tag",
80
+ "users",
81
+ "password",
82
+ "version",
83
+ "transport",
84
+ "managed",
85
+ "destinations",
86
+ "psk",
87
+ "mode",
88
+ "obfs_mode",
89
+ "realm",
90
+ "handshake",
91
+ ] as const;
92
+ const ownedClient = [
93
+ "tag",
94
+ "server",
95
+ "server_port",
96
+ "server_ports",
97
+ "username",
98
+ "password",
99
+ "uuid",
100
+ "flow",
101
+ "alter_id",
102
+ "auth",
103
+ "auth_str",
104
+ "userkey",
105
+ "psk",
106
+ "version",
107
+ "transport",
108
+ "mode",
109
+ "obfs_mode",
110
+ "realm",
111
+ ] as const;
112
+ type SharedOption<K extends Protocol> = K extends keyof typeof sharedOption
113
+ ? (typeof sharedOption)[K]
114
+ : never;
115
+ type SideOptions<O, Keys extends PropertyKey> = O extends unknown
116
+ ? Omit<O, Keys> & { readonly [K in Extract<Keys, keyof O | "version" | "transport">]?: never }
117
+ : never;
118
+ type ProfileOutboundOptions<K extends Protocol, Input> = K extends "snell"
119
+ ? Extract<
120
+ StrictUnion<Options<"outbounds", "snell">>,
121
+ { version: [Input] extends [{ readonly version: 5 }] ? 4 : 6 }
122
+ >
123
+ : Options<"outbounds", K>;
124
+
125
+ type Realm = ReadonlyJson<
126
+ Required<Pick<Hysteria2InboundRealm, "server_url" | "realm_id" | "stun_servers">>
127
+ > &
128
+ ReadonlyJson<Pick<Hysteria2InboundRealm, "token">>;
129
+ type RealmLocal = ReadonlyJson<
130
+ Omit<Hysteria2InboundRealm, "server_url" | "realm_id" | "stun_servers">
131
+ >;
132
+
133
+ type ServerSettings<K extends Protocol, Input> = {
134
+ readonly tag: string;
135
+ readonly listen?: ReadonlyJson<Catalog["inbounds"][K]["listen"]> & {
136
+ readonly address?: string;
137
+ };
138
+ readonly options?: SideOptions<
139
+ Options<"inbounds", K>,
140
+ (typeof ownedServer)[number] | SharedOption<K>
141
+ >;
142
+ readonly tls?: K extends TlsUnsupported | "shadowtls"
143
+ ? never
144
+ : ProtocolTlsOptions<K, ReadonlyJson<Omit<InboundTLSOptions, "enabled" | "reality">>>;
145
+ readonly transport?: K extends TransportProtocol
146
+ ? TransportSideOptions<ProfileTransport<Input>, false>
147
+ : never;
148
+ readonly realm?: K extends "hysteria2" ? RealmLocal : never;
149
+ };
150
+ type ClientTls = ReadonlyJson<Omit<OutboundTLSOptions, "enabled" | "server_name" | "reality">>;
151
+ type ClientSettings<K extends Protocol, Input> = {
152
+ readonly tag: string;
153
+ readonly dial?: ReadonlyJson<Catalog["outbounds"][K]["dial"]>;
154
+ readonly options?: SideOptions<
155
+ ProfileOutboundOptions<K, Input>,
156
+ (typeof ownedClient)[number] | SharedOption<K>
157
+ >;
158
+ readonly tls?: K extends TlsUnsupported ? never : ProtocolTlsOptions<K, ClientTls>;
159
+ readonly transport?: K extends TransportProtocol
160
+ ? TransportSideOptions<ProfileTransport<Input>, true>
161
+ : never;
162
+ readonly realm?: K extends "hysteria2" ? Omit<RealmLocal, "stun_domain_resolver"> : never;
163
+ readonly shortId?: K extends "vless" ? string : never;
164
+ };
165
+ interface Profile<
166
+ K extends Protocol,
167
+ Authenticated extends boolean,
168
+ ExtraInbound = unknown,
169
+ Input = unknown,
170
+ > {
171
+ server(this: void, options: ServerSettings<K, Input>): Inbound<K> & ExtraInbound;
172
+ client(
173
+ this: void,
174
+ ...args: Authenticated extends true
175
+ ? [user: User, options: ClientSettings<K, Input>]
176
+ : [options: ClientSettings<K, Input>]
177
+ ): Outbound<K>;
178
+ }
179
+
180
+ type TransportInput<K extends TransportProtocol> = Direct & {
181
+ readonly users: Users;
182
+ } & TransportTls<K>;
183
+ type PlainInput = Direct & { readonly tls?: NormalTls | NoTls };
184
+ type RequiredTlsInput<K extends Protocol = Protocol> = Direct & {
185
+ readonly users: Users;
186
+ readonly tls: ProtocolTlsOptions<K, NormalTls>;
187
+ };
188
+ type HysteriaInput = HysteriaDirect &
189
+ Pick<RequiredTlsInput, "users" | "tls"> &
190
+ Pick<Options<"inbounds", "hysteria">, "obfs">;
191
+ type Hysteria2Input = { readonly users: Users } & Pick<Options<"inbounds", "hysteria2">, "obfs"> &
192
+ (
193
+ | (HysteriaDirect & { readonly tls: NormalTls })
194
+ | {
195
+ readonly connect?: never;
196
+ readonly realm: Realm;
197
+ readonly tls: NormalTls & { readonly serverName: string };
198
+ }
199
+ );
200
+ type SocksInput = Direct & { readonly version?: "4" | "4a" | "5" };
201
+ type SnellInput = Direct & { readonly psk: string } & StrictUnion<
202
+ | { readonly version: 5; readonly obfs_mode?: "none" | "http" | "tls" }
203
+ | { readonly version?: 6; readonly mode?: "default" | "unshaped" | "unsafe-raw" }
204
+ >;
205
+ type ShadowTlsInput = Direct & {
206
+ readonly handshake: ReadonlyJson<ShadowTLSHandshakeOptions> & {
207
+ readonly server: string;
208
+ readonly server_port: number;
209
+ };
210
+ readonly serverName: string;
211
+ };
212
+ type ShadowsocksInput = Direct;
213
+ type ShadowsocksMethod = Options<"inbounds", "shadowsocks">["method"];
214
+ type MultiMethod = Exclude<ShadowsocksMethod, "none" | "2022-blake3-chacha20-poly1305">;
215
+ type SharedPassword = StrictUnion<
216
+ | { readonly method: "none" }
217
+ | { readonly method: Exclude<ShadowsocksMethod, "none">; readonly password: string }
218
+ >;
219
+ type MultiPassword = StrictUnion<
220
+ | { readonly method: Extract<MultiMethod, `2022-${string}`>; readonly serverKey: string }
221
+ | { readonly method: Exclude<MultiMethod, `2022-${string}`> }
222
+ >;
223
+
224
+ const transportFields = {
225
+ tcp: [],
226
+ quic: [],
227
+ http: ["host", "path", "method"],
228
+ ws: ["path", "max_early_data", "early_data_header_name"],
229
+ grpc: ["service_name"],
230
+ httpupgrade: ["host", "path"],
231
+ } as const;
232
+ const localTransportFields = {
233
+ tcp: [],
234
+ quic: [],
235
+ http: ["headers", "idle_timeout", "ping_timeout"],
236
+ ws: ["headers"],
237
+ grpc: ["idle_timeout", "ping_timeout"],
238
+ httpupgrade: ["headers"],
239
+ } as const;
240
+ const grpcClientFields = ["permit_without_stream"] as const;
241
+ type TransportKind = keyof typeof localTransportFields;
242
+ type TransportSelection<K extends TransportKind> = { readonly transport: { readonly type: K } };
243
+ type ProfileTransport<Input> = Input extends TransportSelection<infer K> ? K : "tcp";
244
+ type TransportSideField<K extends TransportKind, Client extends boolean> =
245
+ | (typeof localTransportFields)[K][number]
246
+ | (Client extends true ? (K extends "grpc" ? (typeof grpcClientFields)[number] : never) : never);
247
+ type AllTransportSideFields = TransportSideField<TransportKind, true>;
248
+ // A setting must work for every possible transport when the input type is a union.
249
+ type CommonTransportSideFields<
250
+ K extends TransportKind,
251
+ Client extends boolean,
252
+ > = keyof (K extends TransportKind ? Record<TransportSideField<K, Client>, true> : never) &
253
+ AllTransportSideFields;
254
+ type TransportSideOptions<
255
+ K extends TransportKind,
256
+ Client extends boolean,
257
+ Allowed extends AllTransportSideFields = CommonTransportSideFields<K, Client>,
258
+ > = [Allowed] extends [never]
259
+ ? never
260
+ : ReadonlyJson<Pick<StrictUnion<V2RayTransport>, Allowed>> & {
261
+ readonly [Key in Exclude<AllTransportSideFields, Allowed>]?: never;
262
+ };
263
+
264
+ const tlsRequired = new Set<Protocol>([
265
+ "anytls",
266
+ "hysteria",
267
+ "hysteria2",
268
+ "naive",
269
+ "tuic",
270
+ ] satisfies TlsRequired[]);
271
+ const versioned: readonly Protocol[] = ["socks", "shadowtls", "snell"];
272
+ const transportProtocols: readonly Protocol[] = ["vmess", "vless", "trojan"];
273
+ const namedClients: readonly Protocol[] = ["socks", "http", "naive"];
274
+ const optionalUsers: readonly Protocol[] = ["http", "socks", "snell", "shadowsocks", "shadowtls"];
275
+ const specialFields: Partial<Record<Protocol, readonly string[]>> = {
276
+ hysteria2: ["realm"],
277
+ shadowsocks: ["password", "serverKey", "managed"],
278
+ shadowtls: ["password", "serverName", "handshake"],
279
+ snell: ["psk", "obfs_mode", "mode"],
280
+ };
281
+
282
+ type NativeBuilder = Resource & {
283
+ listen(address: unknown, options: Fields): NativeBuilder;
284
+ dial(options: unknown): NativeBuilder;
285
+ tls(options: unknown): NativeBuilder;
286
+ };
287
+
288
+ // Native factories validate the assembled options and return the public resource types.
289
+ function native(factory: (options: never) => Resource, options: Fields): NativeBuilder {
290
+ return factory(options as never) as NativeBuilder;
291
+ }
292
+
293
+ function connection(value: unknown, path: string): Fields {
294
+ const { host, port } = fieldsFrom(value, path, ["host", "port"], ["host", "port"]);
295
+ if (typeof host !== "string" || host === "") fail(`${path}.host`, "expected a host");
296
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)
297
+ fail(`${path}.port`, "expected a port from 1 to 65535");
298
+ return { server: host, server_port: port };
299
+ }
300
+
301
+ function profileConnection(kind: Protocol, value: unknown, path: string): Fields {
302
+ if (kind !== "hysteria" && kind !== "hysteria2") return connection(value, path);
303
+ const fields = record(value, path);
304
+ if (!Object.hasOwn(fields, "ports")) return connection(fields, path);
305
+ const { host, ports } = fieldsFrom(fields, path, ["host", "ports"], ["host", "ports"]);
306
+ return { server: requiredString(host, `${path}.host`), server_ports: ports };
307
+ }
308
+
309
+ function usersFor(input: unknown, path: string): readonly User[] {
310
+ if (!Array.isArray(input) || input.length === 0)
311
+ fail(path, "expected a non-empty array of Users");
312
+ const names = new Set<string>();
313
+ return Array.from(input, (value, index) => {
314
+ const entry = `${path}[${index}]`;
315
+ if (!isUser(value) || !value.name) fail(entry, "expected a User with a non-empty name");
316
+ if (names.has(value.name)) fail(entry, "duplicate user name");
317
+ names.add(value.name);
318
+ return value;
319
+ });
320
+ }
321
+
322
+ function realityKeys(input: unknown, path: string): Fields {
323
+ const keys = fieldsFrom(input, path, ["privateKey", "publicKey"], ["privateKey", "publicKey"]);
324
+ const { privateKey, publicKey } = keys;
325
+ for (const [key, value] of Object.entries(keys)) {
326
+ if (
327
+ typeof value !== "string" ||
328
+ !/^[A-Za-z0-9_-]{43}$/.test(value) ||
329
+ Buffer.from(value, "base64url").toString("base64url") !== value
330
+ )
331
+ fail(`${path}.${key}`, "expected an unpadded 32-byte Base64url key");
332
+ }
333
+ // The PKCS #8 prefix identifies a raw X25519 private key.
334
+ const der = Buffer.concat([
335
+ Buffer.from("302e020100300506032b656e04220420", "hex"),
336
+ Buffer.from(privateKey as string, "base64url"),
337
+ ]);
338
+ const derived = createPublicKey(createPrivateKey({ key: der, format: "der", type: "pkcs8" }));
339
+ if (derived.export({ format: "jwk" }).x !== publicKey)
340
+ fail(`${path}.publicKey`, "does not match private key");
341
+ return keys;
342
+ }
343
+
344
+ function tlsFor(kind: Protocol, input: unknown, needsTls: boolean, path: string) {
345
+ const { mode } = record(input ?? { mode: "none" }, path);
346
+ if (mode === "tls") {
347
+ if (kind === "shadowsocks" || kind === "snell" || kind === "socks" || kind === "shadowtls")
348
+ fail(path, "TLS is unavailable for this profile");
349
+ const fields = fieldsFrom(input, path, ["mode", "serverName", "alpn"]);
350
+ checkTlsAlpn(kind, fields, path);
351
+ if (
352
+ fields.serverName !== undefined &&
353
+ (typeof fields.serverName !== "string" || !fields.serverName)
354
+ )
355
+ fail(`${path}.serverName`, "expected a server name");
356
+ return { mode, fields } as const;
357
+ }
358
+ if (needsTls) fail(path, "requires regular TLS");
359
+ if (mode === "none") {
360
+ if (input !== undefined) fieldsFrom(input, path, ["mode"]);
361
+ return { mode } as const;
362
+ }
363
+ if (mode !== "reality" || kind !== "vless") fail(`${path}.mode`, "unsupported TLS mode");
364
+ const fields = fieldsFrom(
365
+ input,
366
+ path,
367
+ ["mode", "serverName", "handshake", "keyPair", "shortId", "shortIds"],
368
+ ["serverName", "handshake", "keyPair"],
369
+ );
370
+ if (typeof fields.serverName !== "string" || !fields.serverName)
371
+ fail(`${path}.serverName`, "expected a server name");
372
+ if ((fields.shortId === undefined) === (fields.shortIds === undefined))
373
+ fail(path, "specify either shortId or shortIds");
374
+ const ids = fields.shortIds ?? [fields.shortId];
375
+ if (
376
+ !Array.isArray(ids) ||
377
+ !ids.length ||
378
+ Array.from(ids).some((id) => typeof id !== "string" || !/^(?:[\da-f]{2}){0,8}$/i.test(id)) ||
379
+ new Set(ids.map((id: string) => id.toLowerCase())).size !== ids.length
380
+ )
381
+ fail(`${path}.shortIds`, "expected unique hexadecimal short IDs");
382
+ const { host, port, ...dial } = record(fields.handshake, `${path}.handshake`);
383
+ if (Object.hasOwn(dial, "server") || Object.hasOwn(dial, "server_port"))
384
+ fail(`${path}.handshake`, "use host and port for the handshake address");
385
+ return {
386
+ mode,
387
+ serverName: fields.serverName,
388
+ keys: realityKeys(fields.keyPair, `${path}.keyPair`),
389
+ ids: ids as string[],
390
+ handshake: { ...dial, ...connection({ host, port }, `${path}.handshake`) },
391
+ } as const;
392
+ }
393
+
394
+ function checkedOptions(value: unknown, owned: readonly string[], path: string): Fields {
395
+ const fields = record(value ?? {}, path);
396
+ for (const key of Object.keys(fields))
397
+ if (owned.includes(key)) fail(keyPath(path, key), "field is controlled by the profile");
398
+ return fields;
399
+ }
400
+
401
+ function protocolOptions(
402
+ kind: Protocol,
403
+ config: Fields,
404
+ hasUsers: boolean,
405
+ sharedKey: string | undefined,
406
+ path: string,
407
+ ) {
408
+ const serverFields: Fields = {};
409
+ const clientFields: Fields = {};
410
+ if (sharedKey && config[sharedKey] !== undefined) {
411
+ serverFields[sharedKey] = config[sharedKey];
412
+ clientFields[sharedKey] = config[sharedKey];
413
+ }
414
+
415
+ switch (kind) {
416
+ case "socks": {
417
+ const version = config.version ?? "5";
418
+ if (version !== "4" && version !== "4a" && version !== "5")
419
+ fail(`${path}.version`, "unsupported SOCKS version");
420
+ clientFields.version = version;
421
+ break;
422
+ }
423
+ case "snell": {
424
+ const version = config.version ?? 6;
425
+ if (version !== 5 && version !== 6) fail(`${path}.version`, "unsupported Snell version");
426
+ const forbidden = version === 5 ? "mode" : "obfs_mode";
427
+ if (config[forbidden] !== undefined)
428
+ fail(`${path}.${forbidden}`, "unavailable for this Snell version");
429
+ serverFields.version = version;
430
+ clientFields.version = version === 5 ? 4 : 6;
431
+ const flag = version === 5 ? "obfs_mode" : "mode";
432
+ if (config[flag] !== undefined) serverFields[flag] = clientFields[flag] = config[flag];
433
+ serverFields.psk = clientFields.psk = requiredString(config.psk, `${path}.psk`);
434
+ break;
435
+ }
436
+ case "shadowtls": {
437
+ const version = config.version ?? 3;
438
+ if (version !== 1 && version !== 2 && version !== 3)
439
+ fail(`${path}.version`, "unsupported ShadowTLS version");
440
+ if (version === 3 ? !hasUsers : hasUsers)
441
+ fail(
442
+ `${path}.users`,
443
+ "users are required for ShadowTLS v3 and unavailable in other versions",
444
+ );
445
+ if (version === 2)
446
+ serverFields.password = clientFields.password = requiredString(
447
+ config.password,
448
+ `${path}.password`,
449
+ );
450
+ else if (config.password !== undefined)
451
+ fail(`${path}.password`, "shared password is available only in ShadowTLS v2");
452
+ const handshake = record(config.handshake, `${path}.handshake`);
453
+ connection({ host: handshake.server, port: handshake.server_port }, `${path}.handshake`);
454
+ serverFields.handshake = handshake;
455
+ requiredString(config.serverName, `${path}.serverName`);
456
+ serverFields.version = clientFields.version = version;
457
+ break;
458
+ }
459
+ case "shadowsocks": {
460
+ if (config.managed !== undefined && typeof config.managed !== "boolean")
461
+ fail(`${path}.managed`, "expected a boolean");
462
+ if (config.managed && hasUsers)
463
+ fail(`${path}.users`, "managed Shadowsocks uses SSM accounts");
464
+ const method = requiredString(config.method, `${path}.method`);
465
+ if (config.managed || hasUsers) {
466
+ if (method === "none" || method === "2022-blake3-chacha20-poly1305")
467
+ fail(`${path}.method`, "unavailable with multiple Shadowsocks users");
468
+ if (config.password !== undefined)
469
+ fail(`${path}.password`, "use User credentials for multiple users");
470
+ if (method.startsWith("2022-"))
471
+ serverFields.password = requiredString(config.serverKey, `${path}.serverKey`);
472
+ else if (config.serverKey !== undefined)
473
+ fail(`${path}.serverKey`, "requires a Shadowsocks 2022 AES method");
474
+ if (config.managed) serverFields.managed = true;
475
+ } else {
476
+ if (config.serverKey !== undefined) fail(`${path}.serverKey`, "requires multiple users");
477
+ if (method !== "none")
478
+ serverFields.password = clientFields.password = requiredString(
479
+ config.password,
480
+ `${path}.password`,
481
+ );
482
+ else if (config.password !== undefined)
483
+ fail(`${path}.password`, "unavailable with method none");
484
+ }
485
+ break;
486
+ }
487
+ }
488
+ return { serverFields, clientFields };
489
+ }
490
+
491
+ function makeProfile<
492
+ K extends Protocol,
493
+ Authenticated extends boolean,
494
+ ExtraInbound = unknown,
495
+ Input = unknown,
496
+ >(kind: K, input: unknown): Profile<K, Authenticated, ExtraInbound, Input> {
497
+ const path = `proxyProfile.${kind}`;
498
+ const sharedKey = Object.hasOwn(sharedOption, kind)
499
+ ? sharedOption[kind as keyof typeof sharedOption]
500
+ : undefined;
501
+ const config = snapshot(
502
+ fieldsFrom(input, path, [
503
+ "connect",
504
+ "users",
505
+ ...(kind === "shadowtls" || kind === "shadowsocks" || kind === "snell" || kind === "socks"
506
+ ? []
507
+ : ["tls"]),
508
+ ...(transportProtocols.includes(kind) ? ["transport"] : []),
509
+ ...(versioned.includes(kind) ? ["version"] : []),
510
+ ...(sharedKey ? [sharedKey] : []),
511
+ ...(specialFields[kind] ?? []),
512
+ ]),
513
+ path,
514
+ );
515
+ const realm =
516
+ config.realm === undefined
517
+ ? undefined
518
+ : fieldsFrom(
519
+ config.realm,
520
+ `${path}.realm`,
521
+ ["server_url", "realm_id", "stun_servers", "token"],
522
+ ["server_url", "realm_id", "stun_servers"],
523
+ );
524
+ if (realm && config.connect !== undefined) fail(`${path}.connect`, "conflicts with Realm");
525
+ const connect = realm ? {} : profileConnection(kind, config.connect, `${path}.connect`);
526
+ const users = config.users === undefined ? [] : usersFor(config.users, `${path}.users`);
527
+ if (!optionalUsers.includes(kind) && !users.length)
528
+ fail(`${path}.users`, "expected at least one User");
529
+
530
+ let transport: Fields = {};
531
+ let transportType: keyof typeof transportFields = "tcp";
532
+ if (config.transport !== undefined) {
533
+ const { type } = record(config.transport, `${path}.transport`);
534
+ if (typeof type !== "string" || !Object.hasOwn(transportFields, type))
535
+ fail(`${path}.transport.type`, "unsupported transport");
536
+ transportType = type as keyof typeof transportFields;
537
+ transport = fieldsFrom(config.transport, `${path}.transport`, [
538
+ "type",
539
+ ...transportFields[transportType],
540
+ ]);
541
+ }
542
+ const tls = tlsFor(
543
+ kind,
544
+ config.tls,
545
+ tlsRequired.has(kind) || transportType === "quic",
546
+ `${path}.tls`,
547
+ );
548
+ if (realm && (tls.mode !== "tls" || !tls.fields.serverName))
549
+ fail(`${path}.tls.serverName`, "required for Realm connections");
550
+
551
+ const { serverFields, clientFields } = protocolOptions(
552
+ kind,
553
+ config,
554
+ users.length > 0,
555
+ sharedKey,
556
+ path,
557
+ );
558
+
559
+ function credentials(user: User, location: string): Fields {
560
+ if (kind === "socks" && clientFields.version !== "5") {
561
+ if (requireUserCredentials(user, "socks", location).password !== "")
562
+ fail(location, "SOCKS4 and SOCKS4a use username-only authentication");
563
+ return {};
564
+ }
565
+ return { ...requireUserCredentials(user, kind, location) };
566
+ }
567
+
568
+ users.forEach((user, index) => credentials(user, `${path}.users[${index}]`));
569
+ if (users.length) serverFields.users = users;
570
+
571
+ function sideOptions(input: unknown, client: boolean) {
572
+ const part = client ? "client" : "server";
573
+ const location = `${path}.${part}`;
574
+ const local = fieldsFrom(
575
+ input,
576
+ location,
577
+ [
578
+ "tag",
579
+ "options",
580
+ "tls",
581
+ "transport",
582
+ "realm",
583
+ ...(client ? ["dial", "shortId"] : ["listen"]),
584
+ ],
585
+ ["tag"],
586
+ );
587
+ const extra = checkedOptions(
588
+ local.options,
589
+ [...(client ? ownedClient : ownedServer), ...(sharedKey ? [sharedKey] : [])],
590
+ `${location}.options`,
591
+ );
592
+ let transportOptions: Fields = {};
593
+ if (local.transport !== undefined) {
594
+ if (transportType === "tcp" || transportType === "quic")
595
+ fail(`${location}.transport`, "this transport has no side-specific fields");
596
+ transportOptions = fieldsFrom(local.transport, `${location}.transport`, [
597
+ ...localTransportFields[transportType],
598
+ ...(client && transportType === "grpc" ? grpcClientFields : []),
599
+ ]);
600
+ }
601
+ let realmOptions: Fields = {};
602
+ if (local.realm !== undefined) {
603
+ if (!realm) fail(`${location}.realm`, "requires a Realm profile");
604
+ realmOptions = fieldsFrom(local.realm, `${location}.realm`, [
605
+ "token",
606
+ "ip_version",
607
+ "port_mapping",
608
+ "http_client",
609
+ ...(client ? [] : ["stun_domain_resolver"]),
610
+ ]);
611
+ }
612
+ const fields = {
613
+ ...extra,
614
+ tag: local.tag,
615
+ ...(transportType === "tcp" ? {} : { transport: { ...transport, ...transportOptions } }),
616
+ ...(realm ? { realm: { ...realm, ...realmOptions } } : {}),
617
+ };
618
+ return { location, local, fields };
619
+ }
620
+
621
+ function applyTls(builder: NativeBuilder, local: Fields, location: string, client: boolean) {
622
+ if (local.shortId !== undefined && tls.mode !== "reality")
623
+ fail(`${location}.shortId`, "requires REALITY");
624
+ if (tls.mode === "reality") {
625
+ if (local.tls !== undefined)
626
+ fail(`${location}.tls`, "REALITY settings belong to the profile");
627
+ if (!client)
628
+ return builder.tls({
629
+ side: "server",
630
+ server_name: tls.serverName,
631
+ reality: {
632
+ private_key: tls.keys.privateKey,
633
+ short_id: tls.ids,
634
+ handshake: tls.handshake,
635
+ },
636
+ });
637
+ const selected = local.shortId ?? (tls.ids.length === 1 ? tls.ids[0] : undefined);
638
+ if (typeof selected !== "string" || !tls.ids.includes(selected))
639
+ fail(`${location}.shortId`, "select a short ID from the profile");
640
+ return builder.tls({
641
+ side: "client",
642
+ server_name: tls.serverName,
643
+ reality: { public_key: tls.keys.publicKey, short_id: selected },
644
+ });
645
+ }
646
+ if (tls.mode === "tls" || (kind === "shadowtls" && client)) {
647
+ const settings = checkedOptions(
648
+ local.tls,
649
+ [
650
+ "enabled",
651
+ "reality",
652
+ "side",
653
+ ...(client ? ["server_name"] : []),
654
+ ...(tls.mode === "tls" && tls.fields.alpn !== undefined ? ["alpn"] : []),
655
+ ],
656
+ `${location}.tls`,
657
+ );
658
+ checkTlsAlpn(kind, settings, `${location}.tls`);
659
+ if (
660
+ !client &&
661
+ !settings.certificate_provider &&
662
+ (!(settings.certificate || settings.certificate_path) ||
663
+ !(settings.key || settings.key_path))
664
+ )
665
+ fail(`${location}.tls`, "expected a certificate and key or certificate provider");
666
+ return builder.tls({
667
+ ...settings,
668
+ enabled: true,
669
+ ...(tls.mode === "tls" && tls.fields.alpn !== undefined ? { alpn: tls.fields.alpn } : {}),
670
+ ...(client
671
+ ? {
672
+ server_name:
673
+ tls.mode === "tls" ? (tls.fields.serverName ?? connect.server) : config.serverName,
674
+ }
675
+ : {}),
676
+ });
677
+ }
678
+ if (local.tls !== undefined) fail(`${location}.tls`, "TLS must be enabled in the profile");
679
+ return builder;
680
+ }
681
+
682
+ const profile = {
683
+ server(input: unknown) {
684
+ const { local, fields, location } = sideOptions(input, false);
685
+ let builder = native(inbound[kind], { ...fields, ...serverFields });
686
+ if (local.listen !== undefined) {
687
+ const { address, ...listen } = record(local.listen, `${location}.listen`);
688
+ builder = builder.listen(address, listen);
689
+ }
690
+ return applyTls(builder, local, location, false);
691
+ },
692
+ client(userOrOptions: unknown, options?: unknown) {
693
+ const authenticated = users.length > 0 || config.managed === true;
694
+ if (
695
+ authenticated &&
696
+ (!isUser(userOrOptions) ||
697
+ !userOrOptions.name ||
698
+ (config.managed !== true && !users.includes(userOrOptions)))
699
+ )
700
+ fail(`${path}.client.user`, "expected a User for this profile");
701
+ if (!authenticated && options !== undefined)
702
+ fail(`${path}.client.user`, "profile has no user selection");
703
+ const { local, fields, location } = sideOptions(
704
+ authenticated ? options : userOrOptions,
705
+ true,
706
+ );
707
+ const selected = isUser(userOrOptions) ? userOrOptions : undefined;
708
+ const auth: Fields = selected
709
+ ? {
710
+ ...credentials(selected, `${location}.user`),
711
+ ...(namedClients.includes(kind) ? { username: selected.name } : {}),
712
+ }
713
+ : {};
714
+ if (
715
+ kind === "shadowsocks" &&
716
+ typeof auth.password === "string" &&
717
+ typeof serverFields.password === "string"
718
+ )
719
+ auth.password = `${serverFields.password}:${auth.password}`;
720
+ let builder = native(outbound[kind], { ...fields, ...clientFields, ...connect, ...auth });
721
+ if (local.dial !== undefined) builder = builder.dial(local.dial);
722
+ return applyTls(builder, local, location, true);
723
+ },
724
+ };
725
+ return Object.freeze(profile) as unknown as Profile<K, Authenticated, ExtraInbound, Input>;
726
+ }
727
+
728
+ function requiredString(input: unknown, path: string): string {
729
+ if (typeof input !== "string" || !input) fail(path, "expected a non-empty string");
730
+ return input;
731
+ }
732
+
733
+ function http(input: PlainInput & { readonly users: Users }): Profile<"http", true>;
734
+ function http(input: PlainInput & { readonly users?: never }): Profile<"http", false>;
735
+ function http(input: PlainInput & { readonly users?: Users }) {
736
+ return makeProfile<"http", boolean>("http", input);
737
+ }
738
+
739
+ function socks(input: SocksInput & { readonly users: Users }): Profile<"socks", true>;
740
+ function socks(input: SocksInput & { readonly users?: never }): Profile<"socks", false>;
741
+ function socks(input: SocksInput & { readonly users?: Users }) {
742
+ return makeProfile<"socks", boolean>("socks", input);
743
+ }
744
+
745
+ function snell<const Version extends 5 | 6 = 6>(
746
+ input: SnellInput & { readonly version?: Version; readonly users: Users },
747
+ ): Profile<"snell", true, unknown, { readonly version: Version }>;
748
+ function snell<const Version extends 5 | 6 = 6>(
749
+ input: SnellInput & { readonly version?: Version; readonly users?: never },
750
+ ): Profile<"snell", false, unknown, { readonly version: Version }>;
751
+ function snell(input: SnellInput & { readonly users?: Users }) {
752
+ return makeProfile<"snell", boolean>("snell", input);
753
+ }
754
+
755
+ function shadowtls(
756
+ input: ShadowTlsInput & {
757
+ readonly version?: 3;
758
+ readonly users: Users;
759
+ readonly password?: never;
760
+ },
761
+ ): Profile<"shadowtls", true>;
762
+ function shadowtls(
763
+ input: ShadowTlsInput & {
764
+ readonly version: 1;
765
+ readonly users?: never;
766
+ readonly password?: never;
767
+ },
768
+ ): Profile<"shadowtls", false>;
769
+ function shadowtls(
770
+ input: ShadowTlsInput & {
771
+ readonly version: 2;
772
+ readonly users?: never;
773
+ readonly password: string;
774
+ },
775
+ ): Profile<"shadowtls", false>;
776
+ function shadowtls(input: ShadowTlsInput) {
777
+ return makeProfile<"shadowtls", boolean>("shadowtls", input);
778
+ }
779
+
780
+ function shadowsocks(
781
+ input: ShadowsocksInput &
782
+ MultiPassword & { readonly managed: true; readonly users?: never; readonly password?: never },
783
+ ): Profile<"shadowsocks", true, SsmInbound>;
784
+ function shadowsocks(
785
+ input: ShadowsocksInput &
786
+ MultiPassword & { readonly managed?: false; readonly users: Users; readonly password?: never },
787
+ ): Profile<"shadowsocks", true, SsmInbound>;
788
+ function shadowsocks(
789
+ input: ShadowsocksInput &
790
+ SharedPassword & {
791
+ readonly managed?: false;
792
+ readonly users?: never;
793
+ readonly serverKey?: never;
794
+ },
795
+ ): Profile<"shadowsocks", false>;
796
+ function shadowsocks(input: ShadowsocksInput) {
797
+ return makeProfile<"shadowsocks", boolean>("shadowsocks", input);
798
+ }
799
+
800
+ function transportProfile<K extends TransportProtocol>(kind: K) {
801
+ function create<const Transport extends TransportKind>(
802
+ input: TransportInput<K> & TransportSelection<Transport>,
803
+ ): Profile<K, true, unknown, TransportSelection<Transport>>;
804
+ function create(input: TransportInput<K>): Profile<K, true>;
805
+ function create(input: TransportInput<K>) {
806
+ return makeProfile<K, true>(kind, input);
807
+ }
808
+ return create;
809
+ }
810
+
811
+ export const proxyProfile = Object.freeze({
812
+ anytls: (input: RequiredTlsInput) => makeProfile<"anytls", true>("anytls", input),
813
+ http,
814
+ hysteria: (input: HysteriaInput) => makeProfile<"hysteria", true>("hysteria", input),
815
+ hysteria2: (input: Hysteria2Input) => makeProfile<"hysteria2", true>("hysteria2", input),
816
+ naive: (input: RequiredTlsInput<"naive">) => makeProfile<"naive", true>("naive", input),
817
+ shadowsocks,
818
+ shadowtls,
819
+ snell,
820
+ socks,
821
+ trojan: transportProfile("trojan"),
822
+ tuic: (input: RequiredTlsInput) => makeProfile<"tuic", true>("tuic", input),
823
+ vless: transportProfile("vless"),
824
+ vmess: transportProfile("vmess"),
825
+ });