sing-box-kit 0.1.2 → 0.1.4

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,31 @@
1
+ # Generate credentials and key pairs
2
+
3
+ The generators use `globalThis.crypto` in Bun and Node.js. UUID and random byte generators return immediately. Key generation and public-key derivation return promises.
4
+
5
+ ```ts
6
+ import { generate } from "sing-box-kit";
7
+
8
+ const uuid = generate.uuid();
9
+ const { privateKey, publicKey } = await generate.reality();
10
+ const shortId = generate.randomHex(8);
11
+ ```
12
+
13
+ Use the Reality private key in the server's `private_key` field and the public key in the client's `public_key` field. Use the same short ID on both sides.
14
+
15
+ | Function | Result |
16
+ | ------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
17
+ | `generate.uuid()` | UUID v4 string |
18
+ | `generate.random(length)` | Random bytes as a `Uint8Array` |
19
+ | `generate.randomHex(length)` | Lowercase hexadecimal string |
20
+ | `generate.randomBase64(length)` | Standard padded Base64 string |
21
+ | `generate.randomBase64Url(length)` | Unpadded Base64url string |
22
+ | `await generate.x25519KeyPair()` | Raw 32-byte `privateKey` and `publicKey` |
23
+ | `await generate.x25519PublicKey(privateKey)` | Raw public key derived from a 32-byte `Uint8Array` |
24
+ | `await generate.reality()` | `privateKey` and `publicKey` as unpadded Base64url |
25
+ | `await generate.wireguard()` | `privateKey` and `publicKey` as standard padded Base64 |
26
+ | `await generate.vapidKeyPair()` | P-256 `privateKey` and uncompressed `publicKey` as unpadded Base64url |
27
+ | `await generate.tailcatKeyPair()` | Padded Base64 `privateKey`, `publicKey`, `discoKey`, and `preSharedKey`, plus an IPv6 `address` |
28
+ | `await generate.echKeyPair(publicName)` | PEM `config` for the client and PEM `key` for the server |
29
+ | `await generate.tlsKeyPair(serverName, months?)` | PEM `privateKey` and self-signed `certificate` for a DNS name or IP address. Defaults to one month. |
30
+
31
+ Random lengths count bytes before encoding. Tailcat configuration requires sing-box 1.15 or later.
@@ -27,5 +27,5 @@ The [package entry point](../../index.ts) exports resource builders, rule builde
27
27
  ## Where to check a change
28
28
 
29
29
  - [`tests/types.ts`](../../tests/types.ts) covers accepted and rejected TypeScript calls through the public API. Run `vp check` to check those cases.
30
- - [`tests/compile.test.ts`](../../tests/compile.test.ts) and [`tests/schema-coverage.test.ts`](../../tests/schema-coverage.test.ts) cover emitted JSON, reference resolution, rules, and validation errors. [`tests/factories.test.ts`](../../tests/factories.test.ts) compares public factories and branches with the pinned schema. Run them with `bun test`.
31
- - [`tests/sing-box-check.ts`](../../tests/sing-box-check.ts) runs the pinned sing-box binary against representative compiled configurations. The [CI workflow](../../.github/workflows/ci.yml) also checks generated files and smoke-tests the packed library on Node.js.
30
+ - [`tests/compile.test.ts`](../../tests/compile.test.ts) and [`tests/schema-coverage.test.ts`](../../tests/schema-coverage.test.ts) cover emitted JSON, reference resolution, rules, and validation errors. [`tests/factories.test.ts`](../../tests/factories.test.ts) compares public factories and branches with the pinned schema. Run the suite with `vp test` on Node.js or `bun run --bun vp test --pool=threads` on Bun.
31
+ - [`tests/sing-box-check.ts`](../../tests/sing-box-check.ts) runs the pinned sing-box binary against representative compiled configurations. The [CI workflow](../../.github/workflows/ci.yml) also checks generated files and runs the test suite on both runtimes.
@@ -0,0 +1,63 @@
1
+ # Generate server and client proxy configurations
2
+
3
+ A `proxyProfile` defines the public connection address and the settings both ends need to agree on. Call `.server()` to build the inbound for all configured users and `.client()` with a specific `User` to build that user's outbound. Add each resource to its own `compile()` call.
4
+
5
+ ```ts
6
+ import { compile, proxyProfile, user } from "sing-box-kit";
7
+
8
+ const alice = user({
9
+ name: "alice",
10
+ credentials: { vless: { uuid: "00000000-0000-4000-8000-000000000001" } },
11
+ });
12
+ const bob = user({
13
+ name: "bob",
14
+ credentials: { vless: { uuid: "00000000-0000-4000-8000-000000000002" } },
15
+ });
16
+ const proxy = proxyProfile.vless({
17
+ users: [alice, bob],
18
+ connect: { host: "edge.example", port: 443 },
19
+ transport: { type: "grpc", service_name: "proxy" },
20
+ tls: { mode: "tls" },
21
+ });
22
+
23
+ const incoming = proxy
24
+ .server({
25
+ tag: "incoming",
26
+ tls: { certificate_path: "cert.pem", key_path: "key.pem" },
27
+ })
28
+ .listen("0.0.0.0", { port: 8443 });
29
+ const outgoing = proxy.client(alice, { tag: "outgoing" });
30
+
31
+ const serverConfig = compile({ inbounds: [incoming] });
32
+ const aliceConfig = compile({ outbounds: [outgoing] });
33
+ ```
34
+
35
+ Reuse the same `User` object when selecting a client or calling `.authUser()` on the returned inbound. Each protocol has its own credential entry on `User`. The profile uses that entry wherever the same user and protocol appear. Serialize the generated client config when distributing it. The profile inputs can contain every user's credentials and the server's private key.
36
+
37
+ Supply a `tag` to each `.server()` and `.client()` call. Set listen fields in `.server({ tag, listen: { address, port } })` or chain `.listen(address, { port })`. On the client, pass dial fields in the call or chain `.dial()`.
38
+
39
+ ## Transport and TLS
40
+
41
+ VMess, VLESS, and Trojan default to TCP. Select `http`, `ws`, `grpc`, `httpupgrade`, or `quic` with `transport.type`. Set shared parameters such as the gRPC service name in the profile. Set side-specific `transport.headers` for HTTP, WebSocket, and HTTPUpgrade, or transport timeouts for HTTP and gRPC. Use `options` on `.server()` and `.client()` for other protocol-specific fields, such as VLESS packet encoding on the client.
42
+
43
+ For regular TLS, the client uses the public host as the verification name by default. Set `tls.serverName` when it differs. Set `tls.alpn` in the profile to send the same list to both ends. V2Ray QUIC requires regular TLS.
44
+
45
+ For VLESS REALITY, pass `tls: { mode: "reality", serverName, handshake: { host, port }, keyPair: { privateKey, publicKey }, shortId }` and use `await proxyProfile.vless(options)` to validate the key pair with Web Crypto before building either resource. To accept multiple short IDs, use `shortIds` and pass `shortId` in the client options.
46
+
47
+ ## Protocol versions and shared keys
48
+
49
+ | Protocol | Profile setting |
50
+ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
51
+ | SOCKS | `version: "4"`, `"4a"`, or `"5"` (default). For SOCKS4 and SOCKS4a username-only authentication, set `credentials.socks.password` to an empty string. |
52
+ | ShadowTLS | `version: 1` for no authentication, `2` for a shared `password`, or `3` (default) for `users`. Set `handshake` and `serverName` in the profile. |
53
+ | Snell | `version: 5` builds a v5 inbound and a compatible v4 outbound. `version: 6` (default) uses v6 on both ends. Set the shared `psk` in the profile. |
54
+
55
+ Call `.client({ tag })` when the profile uses no authentication or a shared key with no per-user credential.
56
+
57
+ With Snell `version: 5` and `obfs_mode: "http"`, set the v4 outbound's obfuscation host in the client call's `options.obfs_host`.
58
+
59
+ ## Shadowsocks SSM and Hysteria2 Realm
60
+
61
+ For Shadowsocks 2022 AES with multiple users, put the server key in `serverKey` and each user key in `credentials.shadowsocks.password`. For SSM-managed users, set `managed: true`, register the returned inbound with `service.ssmApi()`, and pass a `User` with the issued key to `.client()`. User registration takes place separately through SSM.
62
+
63
+ For Hysteria or Hysteria2 port hopping, use `connect: { host, ports: ["443:444", "8443:8443"] }` and configure the corresponding server-side port forwarding. For Hysteria2 Realm, provide `realm: { server_url, realm_id, stun_servers, token }` in place of `connect` and specify the Hysteria2 server's certificate name in `tls.serverName`. Both sides use the shared Realm settings. Set `realm.token` on an individual generation call when it uses a different token.
package/docs/rules.md CHANGED
@@ -44,18 +44,20 @@ Route options include `override_address`, `override_port`, and the other fields
44
44
 
45
45
  ## Match authenticated users
46
46
 
47
- A `User` represents a name shared across inbounds. Supply credentials on each inbound entry. SOCKS, Mixed, and Shadowsocks use `password`. VLESS uses `uuid` with optional `flow`. Mixed and Shadowsocks also accept their sing-box entry formats. In an entry that uses `user`, omit the explicit `username` or `name`.
47
+ A `User` represents a name shared across inbounds. Set protocol credentials in `user({ name, credentials })` and pass that object in `users` to an inbound factory or [proxy profile](proxy-profiles.md). For example, use `credentials.socks.password` for SOCKS and `credentials.vless.uuid` with optional `flow` for VLESS.
48
+
49
+ The inbound factories for SOCKS, Mixed, Shadowsocks, VLESS, HTTP, VMess, Trojan, Hysteria, Hysteria2, TUIC, ShadowTLS v3, Naive, AnyTLS, and Snell support `.authUser()` for configured users.
48
50
 
49
51
  Call `inboundValue.authUser(user)` on the final inbound to match that inbound and authenticated name together. The exact `User` object must appear once, and its name must be non-empty and unique on that inbound. To match a name added through the SSM API, use `Rule.match({ inbound: managedInbound, auth_user: "alice" })`. A plain `auth_user` condition can also match a name across inbounds. An empty string can match traffic with no authenticated name.
50
52
 
51
53
  ```ts
52
54
  import { compile, inbound, outbound, route, Rule, user } from "sing-box-kit";
53
55
 
54
- const alice = user({ name: "alice" });
56
+ const alice = user({ name: "alice", credentials: { socks: { password: "example-password" } } });
55
57
  const proxy = inbound
56
58
  .socks({
57
59
  tag: "proxy",
58
- users: [{ user: alice, password: "example-password" }],
60
+ users: [alice],
59
61
  })
60
62
  .listen("127.0.0.1", { port: 1080 });
61
63
  const egress = outbound.direct({ tag: "egress" });
package/docs/settings.md CHANGED
@@ -29,6 +29,8 @@ Use `.tls(options)` for the kind's TLS fields, such as `outbound.http({ tag: "pr
29
29
 
30
30
  Standard inbound and outbound TLS builders also accept side-tagged profiles. Use `side: "server"` with a `certificate_path` and `key_path` pair or a registered `certificate_provider`. Use `side: "client"` with optional `server_name` and `certificate_path` settings.
31
31
 
32
+ Naive builders and proxy profiles negotiate ALPN automatically. Omit `alpn` from their TLS settings.
33
+
32
34
  ### VLESS with REALITY
33
35
 
34
36
  On the inbound, set `server_name` and pass `reality: { private_key, short_id, handshake }`. The handshake has its own `server`, `server_port`, and optional Dial Fields. On the outbound, set the VLESS `server` and `server_port` for the connection, set the TLS `server_name` for verification, and pass `reality: { public_key, short_id }`. SBKit enables uTLS for that client profile.
package/index.ts CHANGED
@@ -12,6 +12,7 @@ export {
12
12
  service,
13
13
  } from "./src/factories";
14
14
  export type { HeadlessRule, SingBoxConfig } from "./src/generated/sing-box";
15
+ export { proxyProfile } from "./src/proxy-profile";
15
16
  export { dns, route, Rule } from "./src/rules";
16
17
  export type {
17
18
  Condition,
@@ -37,4 +38,5 @@ export type {
37
38
  ServerTls,
38
39
  } from "./src/settings";
39
40
  export { user } from "./src/user";
40
- export type { User } from "./src/user";
41
+ export type { User, UserCredentials } from "./src/user";
42
+ export { generate } from "./src/generate";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sing-box-kit",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Build and validate sing-box configurations with Bun and Node.js.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -33,16 +33,20 @@
33
33
  "schema:generate": "bun scripts/generate-schema.ts"
34
34
  },
35
35
  "dependencies": {
36
- "ajv": "^8.20.0"
36
+ "@peculiar/utils": "^4.1.0",
37
+ "@peculiar/x509": "^3.1.0",
38
+ "ajv": "^8.20.0",
39
+ "reflect-metadata": "^0.2.2"
37
40
  },
38
41
  "devDependencies": {
42
+ "@actions/github": "^9.0.0",
39
43
  "@types/bun": "latest",
40
44
  "json-schema-to-typescript": "^16.0.0",
41
45
  "typescript": "^7.0.2",
42
46
  "vite-plus": "1.8.0"
43
47
  },
44
48
  "engines": {
45
- "node": ">=22.1.0"
49
+ "node": ">=22.13.0"
46
50
  },
47
51
  "packageManager": "bun@1.4.5"
48
52
  }
package/schema/README.md CHANGED
@@ -13,7 +13,7 @@ vp install --frozen-lockfile
13
13
  bun run schema:generate
14
14
  git diff --exit-code -- src/generated
15
15
  vp check
16
- bun test
16
+ vp test
17
17
  ```
18
18
 
19
19
  Type generation reads the local snapshot and works offline after dependency installation. CI checks both generated type files and independently compares the public factory names and branches to the pinned schema. SBKit's input types use the same schema projections as the runtime builders. Run `bun tests/sing-box-check.ts` with the pinned binary on `PATH`, or set `SING_BOX` to its path, to check the representative configurations. When updating the supported sing-box version, update the schema snapshot, `version.json`, generated types, and affected test expectations together.
package/src/compile.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { isIP } from "node:net";
2
1
  import type { SBKitInputs } from "./generated/sbkit-inputs";
3
- import { rootSettings, sectionSettings } from "./input-schema";
4
2
  import type { SingBoxConfig } from "./generated/sing-box";
3
+ import { rootSettings, sectionSettings } from "./input-schema";
4
+ import { isIP } from "./ip";
5
5
  import { copyJson, fieldsFrom, resourceData } from "./resource";
6
6
  import type {
7
7
  DnsServer,
package/src/factories.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { SBKitInputs } from "./generated/sbkit-inputs";
2
- import type { ShadowsocksUser, User as RawUser, VLESSUser } from "./generated/sing-box";
2
+ import type { ShadowsocksUser } from "./generated/sing-box";
3
3
  import { factoryCatalog, factoryName } from "./input-schema";
4
4
  import type { FactoryBranch } from "./input-schema";
5
5
  import {
@@ -23,9 +23,16 @@ import {
23
23
  previewReference,
24
24
  tlsFields,
25
25
  } from "./settings";
26
- import type { ClientTls, RealityClientTls, RealityServerTls, ServerTls, TlsMode } from "./settings";
26
+ import type {
27
+ ClientTls,
28
+ ProtocolTlsOptions,
29
+ RealityClientTls,
30
+ RealityServerTls,
31
+ ServerTls,
32
+ TlsMode,
33
+ } from "./settings";
27
34
  import type { CamelCase, Fields, ReadonlyJson, StrictUnion } from "./type-utils";
28
- import { isUser } from "./user";
35
+ import { isUser, requireUserCredentials } from "./user";
29
36
  import type { User } from "./user";
30
37
 
31
38
  interface ListenMethod<T> {
@@ -60,39 +67,35 @@ const endpointRoles = {
60
67
  "openvpn-client": "openvpn-client-endpoint",
61
68
  } as const satisfies Record<string, Role>;
62
69
 
63
- type PasswordEntry<Name extends "username" | "name"> = {
64
- readonly user: User;
65
- readonly password: string;
66
- } & { readonly [K in Name]?: never };
67
- type MixedEntry = PasswordEntry<"username"> | (Readonly<RawUser> & { user?: never });
68
- type ShadowsocksEntry = PasswordEntry<"name"> | (Readonly<ShadowsocksUser> & { user?: never });
69
- type VlessEntry = Required<Pick<VLESSUser, "uuid">> &
70
- Pick<VLESSUser, "flow"> & { user: User; name?: never };
71
-
72
- interface AuthOptions {
73
- readonly name: "name" | "username";
74
- readonly credentials: readonly string[];
75
- readonly required: readonly string[];
76
- readonly allowRaw?: boolean;
77
- }
78
-
79
- const passwordAuth = {
80
- name: "username",
81
- credentials: ["password"],
82
- required: ["password"],
83
- } as const;
70
+ const namedAuth = { name: "name", allowRaw: true } as const;
71
+ const usernameAuth = { name: "username", allowRaw: true } as const;
84
72
  const authOptions = {
85
- mixed: { ...passwordAuth, allowRaw: true },
86
- socks: passwordAuth,
87
- shadowsocks: { ...passwordAuth, name: "name", allowRaw: true },
88
- vless: { name: "name", credentials: ["uuid", "flow"], required: ["uuid"] },
89
- } as const satisfies Record<string, AuthOptions>;
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 });
90
90
 
91
91
  type Catalog = SBKitInputs["factories"];
92
92
  type Kind<T extends Target> = keyof Catalog[T] & string;
93
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;
94
97
  type Options<T extends Target, K extends Kind<T>> =
95
- Groups<T, K> extends { options: infer O } ? StrictUnion<O> : never;
98
+ Groups<T, K> extends { options: infer O } ? StrictUnion<StrictTransport<O>> : never;
96
99
  type Tag = string | readonly string[] | undefined;
97
100
  type ExtraRoles<T extends Target, K> = T extends "endpoints"
98
101
  ? | (K extends keyof typeof endpointRoles ? (typeof endpointRoles)[K] : never)
@@ -123,7 +126,9 @@ type Built<
123
126
  > = Resource<T, K, V, (typeof targetRoles)[T][number] | ExtraRoles<T, K>> &
124
127
  (G extends { listen: infer L } ? ListenMethod<L> : unknown) &
125
128
  (G extends { dial: infer D } ? DialMethod<D> : unknown) &
126
- (G extends { tls: infer F } ? TlsMethod<(F & { side?: never }) | Profile<T, K, F>> : unknown) &
129
+ (G extends { tls: infer F }
130
+ ? TlsMethod<ProtocolTlsOptions<K, (F & { side?: never }) | Profile<T, K, F>>>
131
+ : unknown) &
127
132
  (T extends "inbounds" ? (K extends keyof typeof authOptions ? AuthMethod : unknown) : unknown);
128
133
 
129
134
  type Factory<T extends Target, K extends Kind<T>> = T extends "services" | "http_clients"
@@ -141,30 +146,28 @@ interface Membership {
141
146
  readonly user?: User;
142
147
  readonly name: unknown;
143
148
  }
144
- function prepareUsers(fields: Fields, auth: AuthOptions, path: string): readonly Membership[] {
149
+ function prepareUsers(fields: Fields, kind: AuthKind, path: string): readonly Membership[] {
145
150
  if (fields.users === undefined) return [];
146
151
  const users = fields.users;
147
152
  if (!Array.isArray(users)) fail(`${path}.users`, "expected an array");
153
+ const auth = authOptions[kind];
148
154
  const members: Membership[] = [];
149
155
  fields.users = Array.from(users, (value, index) => {
150
156
  const entryPath = `${path}.users[${index}]`;
151
- const entry = record(value, entryPath);
152
- if (!Object.hasOwn(entry, "user") && auth.allowRaw) {
153
- const raw = fieldsFrom(entry, entryPath, [auth.name, ...auth.credentials]);
154
- members.push({ name: raw[auth.name] });
155
- 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) };
156
164
  }
157
- if (Object.hasOwn(entry, auth.name))
158
- fail(keyPath(entryPath, auth.name), "explicit name with User");
159
- const { user, ...credentials } = fieldsFrom(
160
- entry,
161
- entryPath,
162
- ["user", ...auth.credentials],
163
- ["user", ...auth.required],
164
- );
165
- if (!isUser(user)) fail(`${entryPath}.user`, "expected a User");
166
- members.push({ user, name: user.name });
167
- 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;
168
171
  });
169
172
  return members;
170
173
  }
@@ -275,9 +278,7 @@ function makeFactory(target: Target, kind: string, branches: FactoryBranch[]) {
275
278
  const path = `${target}.${kind}`;
276
279
  const validators = new Map<FactoryBranch, ReturnType<typeof compileSchema>>();
277
280
  const auth =
278
- target === "inbounds" && Object.hasOwn(authOptions, kind)
279
- ? authOptions[kind as keyof typeof authOptions]
280
- : undefined;
281
+ target === "inbounds" && Object.hasOwn(authOptions, kind) ? (kind as AuthKind) : undefined;
281
282
  return (input: unknown = {}): Resource => {
282
283
  const raw = record(input, path);
283
284
  const branch =
@@ -295,7 +296,8 @@ function makeFactory(target: Target, kind: string, branches: FactoryBranch[]) {
295
296
  branch.options.required,
296
297
  );
297
298
  validateTag(options.tag, `${path}.tag`);
298
- const members = auth ? prepareUsers(options, auth, path) : [];
299
+ const users = auth ? prepareUsers(options, auth, path) : [];
300
+ const members = kind === "shadowtls" && options.version !== 3 ? [] : users;
299
301
  const roles = getRoles(target, kind);
300
302
  prepareOptions(target, kind, options, path, roles);
301
303
  const base = snapshot(target === "http_clients" ? options : { type: kind, ...options }, path);
@@ -350,7 +352,7 @@ function makeFactory(target: Target, kind: string, branches: FactoryBranch[]) {
350
352
  if (name === "InboundTLSOptions") mode = kind === "vless" ? "server-reality" : "server";
351
353
  if (name === "OutboundTLSOptions") mode = kind === "vless" ? "client-reality" : "client";
352
354
  methods.tls = (input: unknown) =>
353
- apply("tls", () => tlsFields(input, `${path}.tls`, tls, mode));
355
+ apply("tls", () => tlsFields(input, `${path}.tls`, tls, mode, kind));
354
356
  }
355
357
  if (auth) {
356
358
  methods.authUser = (user: User) => {
@@ -417,21 +419,24 @@ type ShadowsocksOptions = ShadowsocksBase &
417
419
  | { method: MultiMethod; managed?: false; users?: readonly ShadowsocksEntry[] }
418
420
  );
419
421
 
420
- type AuthOptionsFor<K extends "mixed" | "socks" | "vless", U> = Omit<
421
- Options<"inbounds", K>,
422
- "users"
423
- > &
424
- U;
425
- type InboundFactories = Omit<Factories<"inbounds">, keyof typeof authOptions> & {
426
- mixed(
427
- options: AuthOptionsFor<"mixed", { users?: readonly MixedEntry[] }>,
428
- ): Built<"inbounds", "mixed">;
429
- socks(
430
- options: AuthOptionsFor<"socks", { users?: readonly PasswordEntry<"username">[] }>,
431
- ): Built<"inbounds", "socks">;
432
- vless(
433
- options: AuthOptionsFor<"vless", { users: readonly VlessEntry[] }>,
434
- ): Built<"inbounds", "vless">;
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
+ } & {
435
440
  shadowsocks: {
436
441
  (
437
442
  options: ManagedShadowsocks | StaticShadowsocks,
@@ -0,0 +1,116 @@
1
+ import { base64, base64url, hex } from "@peculiar/utils/encoding";
2
+ import { serverCertificate } from "./internal/certificate";
3
+ import { deriveX25519PublicKey, randomBytes } from "./internal/crypto";
4
+ import { encodeEchKeyPair } from "./internal/ech";
5
+
6
+ function uuid(): string {
7
+ return globalThis.crypto.randomUUID();
8
+ }
9
+
10
+ function random(length: number): Uint8Array {
11
+ return randomBytes(length);
12
+ }
13
+
14
+ function randomHex(length: number): string {
15
+ return hex.encode(random(length));
16
+ }
17
+
18
+ function randomBase64(length: number): string {
19
+ return base64.encode(random(length));
20
+ }
21
+
22
+ function randomBase64Url(length: number): string {
23
+ return base64url.encode(random(length));
24
+ }
25
+
26
+ function x25519PublicKey(privateKey: Uint8Array): Promise<Uint8Array> {
27
+ return deriveX25519PublicKey(privateKey);
28
+ }
29
+
30
+ async function x25519KeyPair() {
31
+ const privateKey = randomBytes(32);
32
+ privateKey[0] = privateKey[0]! & 248;
33
+ privateKey[31] = (privateKey[31]! & 127) | 64;
34
+ return { privateKey, publicKey: await x25519PublicKey(privateKey) };
35
+ }
36
+
37
+ async function reality() {
38
+ const { privateKey, publicKey } = await x25519KeyPair();
39
+ return {
40
+ privateKey: base64url.encode(privateKey),
41
+ publicKey: base64url.encode(publicKey),
42
+ };
43
+ }
44
+
45
+ async function wireguard() {
46
+ const { privateKey, publicKey } = await x25519KeyPair();
47
+ return {
48
+ privateKey: base64.encode(privateKey),
49
+ publicKey: base64.encode(publicKey),
50
+ };
51
+ }
52
+
53
+ async function vapidKeyPair() {
54
+ const { subtle } = globalThis.crypto;
55
+ const key = await subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
56
+ "sign",
57
+ "verify",
58
+ ]);
59
+ const { d: privateKey } = await subtle.exportKey("jwk", key.privateKey);
60
+ const publicKey = await subtle.exportKey("raw", key.publicKey);
61
+ return { privateKey: privateKey!, publicKey: base64url.encode(publicKey) };
62
+ }
63
+
64
+ async function tailcatKeyPair() {
65
+ const { privateKey, publicKey } = await x25519KeyPair();
66
+ const { subtle } = globalThis.crypto;
67
+ const hmacKey = await subtle.importKey(
68
+ "raw",
69
+ privateKey,
70
+ { name: "HMAC", hash: "SHA-256" },
71
+ false,
72
+ ["sign"],
73
+ );
74
+ const discoLabel = new TextEncoder().encode("github.com/tailscale/tailcat disco key v1");
75
+ const discoPrivateKey = new Uint8Array(await subtle.sign("HMAC", hmacKey, discoLabel));
76
+ const view = new DataView(publicKey.buffer, publicKey.byteOffset, publicKey.byteLength);
77
+ const groups = Array.from({ length: 5 }, (_, index) => view.getUint16(index * 2).toString(16));
78
+ const address = new URL(`http://[fd7a:115c:a1e0:${groups.join(":")}]`).hostname.slice(1, -1);
79
+ return {
80
+ privateKey: base64.encode(privateKey),
81
+ publicKey: base64.encode(publicKey),
82
+ discoKey: base64.encode(await x25519PublicKey(discoPrivateKey)),
83
+ preSharedKey: randomBase64(32),
84
+ address,
85
+ };
86
+ }
87
+
88
+ async function echKeyPair(publicName: string) {
89
+ const name = new TextEncoder().encode(publicName);
90
+ if (name.length < 1 || name.length > 255) {
91
+ throw new RangeError("ECH public name must be between 1 and 255 bytes");
92
+ }
93
+
94
+ const { privateKey, publicKey } = await x25519KeyPair();
95
+ return encodeEchKeyPair(name, privateKey, publicKey);
96
+ }
97
+
98
+ function tlsKeyPair(serverName: string, months = 1) {
99
+ return serverCertificate(serverName, months);
100
+ }
101
+
102
+ export const generate = {
103
+ uuid,
104
+ random,
105
+ randomHex,
106
+ randomBase64,
107
+ randomBase64Url,
108
+ x25519KeyPair,
109
+ x25519PublicKey,
110
+ reality,
111
+ wireguard,
112
+ vapidKeyPair,
113
+ tailcatKeyPair,
114
+ echKeyPair,
115
+ tlsKeyPair,
116
+ } as const;
@@ -0,0 +1,72 @@
1
+ import "reflect-metadata";
2
+ import { pem } from "@peculiar/utils/pem";
3
+ import {
4
+ BasicConstraintsExtension,
5
+ ExtendedKeyUsage,
6
+ ExtendedKeyUsageExtension,
7
+ KeyUsageFlags,
8
+ KeyUsagesExtension,
9
+ SubjectAlternativeNameExtension,
10
+ X509CertificateGenerator,
11
+ } from "@peculiar/x509";
12
+ import { isIP } from "../ip";
13
+
14
+ export async function serverCertificate(serverName: string, months: number) {
15
+ if (!Number.isSafeInteger(months) || months < 1) {
16
+ throw new RangeError("TLS validity must be a positive integer number of months");
17
+ }
18
+
19
+ const now = new Date();
20
+ const expires = new Date(now);
21
+ expires.setUTCMonth(expires.getUTCMonth() + months);
22
+ if (!Number.isFinite(expires.getTime()) || expires.getUTCFullYear() > 9999) {
23
+ throw new RangeError("TLS expiry is outside the supported date range");
24
+ }
25
+
26
+ if (/[\s\\/@?#%]/.test(serverName)) {
27
+ throw new TypeError("TLS server name must be a DNS name or IP address");
28
+ }
29
+ const version = isIP(serverName);
30
+ const dnsName =
31
+ version || serverName.includes(":") ? undefined : URL.parse(`http://${serverName}/`)?.hostname;
32
+ if (!version && (!dnsName || !/^(?:\*\.)?[a-z\d_-]+(?:\.[a-z\d_-]+)*\.?$/i.test(dnsName))) {
33
+ throw new TypeError("TLS server name must be a DNS name or IP address");
34
+ }
35
+
36
+ const crypto = globalThis.crypto;
37
+ const algorithm = {
38
+ name: "RSASSA-PKCS1-v1_5",
39
+ modulusLength: 2048,
40
+ publicExponent: new Uint8Array([1, 0, 1]),
41
+ hash: "SHA-256",
42
+ };
43
+ const keys = await crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);
44
+
45
+ const name = dnsName || serverName;
46
+ // Normalize IPv4-mapped IPv6 to hexadecimal groups for the SAN encoder.
47
+ const san = version === 6 ? new URL(`http://[${serverName}]`).hostname.slice(1, -1) : name;
48
+ const certificate = await X509CertificateGenerator.createSelfSigned(
49
+ {
50
+ name: [{ CN: [name] }],
51
+ notBefore: new Date(now.getTime() - 3_600_000),
52
+ notAfter: expires,
53
+ signingAlgorithm: algorithm,
54
+ keys,
55
+ extensions: [
56
+ new KeyUsagesExtension(
57
+ KeyUsageFlags.digitalSignature | KeyUsageFlags.keyEncipherment,
58
+ true,
59
+ ),
60
+ new ExtendedKeyUsageExtension([ExtendedKeyUsage.serverAuth]),
61
+ new BasicConstraintsExtension(false),
62
+ new SubjectAlternativeNameExtension([{ type: version ? "ip" : "dns", value: san }]),
63
+ ],
64
+ },
65
+ crypto,
66
+ );
67
+
68
+ return {
69
+ privateKey: pem.encode("PRIVATE KEY", await crypto.subtle.exportKey("pkcs8", keys.privateKey)),
70
+ certificate: pem.encode("CERTIFICATE", certificate.rawData),
71
+ };
72
+ }
@@ -0,0 +1,34 @@
1
+ import { concatToUint8Array, toArrayBuffer } from "@peculiar/utils/bytes";
2
+ import { hex } from "@peculiar/utils/encoding";
3
+
4
+ // RFC 8410 PKCS#8 header for a 32-byte X25519 private key.
5
+ const x25519Pkcs8Header = hex.decode("302e020100300506032b656e04220420");
6
+
7
+ export function randomBytes(length: number): Uint8Array<ArrayBuffer> {
8
+ if (!Number.isSafeInteger(length) || length < 0) {
9
+ throw new RangeError("Random byte length must be a non-negative integer");
10
+ }
11
+
12
+ const bytes = new Uint8Array(length);
13
+ // Web Crypto limits each getRandomValues call to 65,536 bytes.
14
+ for (let offset = 0; offset < bytes.length; offset += 65_536) {
15
+ globalThis.crypto.getRandomValues(bytes.subarray(offset, offset + 65_536));
16
+ }
17
+ return bytes;
18
+ }
19
+
20
+ export async function deriveX25519PublicKey(
21
+ privateKey: Uint8Array,
22
+ ): Promise<Uint8Array<ArrayBuffer>> {
23
+ if (privateKey.length !== 32) throw new RangeError("X25519 private key must be 32 bytes");
24
+
25
+ const { subtle } = globalThis.crypto;
26
+ const pkcs8 = toArrayBuffer(concatToUint8Array([x25519Pkcs8Header, privateKey]));
27
+ const key = await subtle.importKey("pkcs8", pkcs8, "X25519", false, ["deriveBits"]);
28
+
29
+ // X25519 with the standard base point yields the corresponding public key.
30
+ const basePoint = new Uint8Array(32);
31
+ basePoint[0] = 9;
32
+ const publicKey = await subtle.importKey("raw", basePoint, "X25519", false, []);
33
+ return new Uint8Array(await subtle.deriveBits({ name: "X25519", public: publicKey }, key, 256));
34
+ }