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.
package/src/schema.ts ADDED
@@ -0,0 +1,207 @@
1
+ import Ajv2020 from "ajv/dist/2020.js";
2
+ import type { AnySchema, ErrorObject, ValidateFunction } from "ajv";
3
+ import official from "../schema/sing-box.json";
4
+ import type { SingBoxConfig } from "./generated/sing-box";
5
+
6
+ export function fail(path: string, category: string, tag?: string): never {
7
+ throw new Error(
8
+ `${path}: ${category}${tag === undefined ? "" : ` (tag ${JSON.stringify(tag)})`}`,
9
+ );
10
+ }
11
+
12
+ export function keyPath(path: string, key: string): string {
13
+ if (/^[A-Za-z_$][\w$]*$/.test(key)) return path ? `${path}.${key}` : key;
14
+ return `${path}[${JSON.stringify(key)}]`;
15
+ }
16
+
17
+ const ajv = new Ajv2020({
18
+ strict: true,
19
+ allErrors: true,
20
+ coerceTypes: false,
21
+ useDefaults: false,
22
+ removeAdditional: false,
23
+ ownProperties: true,
24
+ });
25
+ ajv.addKeyword({ keyword: "x-tag-reference", schemaType: "string", valid: true });
26
+ const validateOfficial = ajv.compile<SingBoxConfig>(official);
27
+
28
+ function errorPath(error: ErrorObject, value: unknown, root: string): string {
29
+ let path = root;
30
+ let current = value;
31
+ for (const encoded of error.instancePath.split("/").slice(1)) {
32
+ const key = encoded.replaceAll("~1", "/").replaceAll("~0", "~");
33
+ path = Array.isArray(current) ? `${path}[${key}]` : keyPath(path, key);
34
+ current =
35
+ current && typeof current === "object"
36
+ ? (current as Record<string, unknown>)[key]
37
+ : undefined;
38
+ }
39
+ const key = error.params.additionalProperty ?? error.params.missingProperty;
40
+ return typeof key === "string" ? keyPath(path, key) : path;
41
+ }
42
+
43
+ export function checkSchema<T>(validate: ValidateFunction<T>, value: unknown, path: string): T {
44
+ if (validate(value)) return value;
45
+ const errors = (validate.errors ?? []).filter(
46
+ (error) => !["anyOf", "oneOf", "if"].includes(error.keyword),
47
+ );
48
+ const paths = [...new Set(errors.map((error) => errorPath(error, value, path) || "config"))];
49
+ fail(paths.join(", ") || path || "config", "schema validation failed");
50
+ }
51
+
52
+ export function validateConfig(value: unknown): SingBoxConfig {
53
+ return checkSchema(validateOfficial, value, "");
54
+ }
55
+
56
+ // Resolve references in projected schemas against the same, untouched snapshot.
57
+ export type SchemaFields = Record<string, SchemaNode>;
58
+ export interface SchemaNode {
59
+ type?: string;
60
+ $ref?: string;
61
+ const?: unknown;
62
+ enum?: readonly unknown[];
63
+ properties?: SchemaFields;
64
+ oneOf?: readonly SchemaNode[];
65
+ anyOf?: readonly SchemaNode[];
66
+ }
67
+
68
+ const definitions = official.$defs as unknown as Record<string, SchemaNode>;
69
+ export function definition(name: string): SchemaNode {
70
+ return definitions[name] ?? fail(name, "unknown schema definition");
71
+ }
72
+
73
+ export function variant(name: string, type: string): SchemaNode {
74
+ const schema = definition(name);
75
+ return (
76
+ (schema.oneOf ?? schema.anyOf)?.find(
77
+ (option) =>
78
+ option.properties?.type?.const === type || option.properties?.type?.enum?.includes(type),
79
+ ) ?? fail(name, "unknown schema variant")
80
+ );
81
+ }
82
+
83
+ export function compileSchema(schema: AnySchema): ValidateFunction {
84
+ const rewriteReferences = (key: string, value: unknown) =>
85
+ key === "$ref" && typeof value === "string" && value.startsWith("#/")
86
+ ? official.$id + value
87
+ : value;
88
+ return ajv.compile(JSON.parse(JSON.stringify(schema, rewriteReferences)));
89
+ }
90
+
91
+ export function objectValidator(
92
+ properties: SchemaFields,
93
+ required: readonly string[] = [],
94
+ ): ValidateFunction {
95
+ return compileSchema({ type: "object", properties, required, additionalProperties: false });
96
+ }
97
+
98
+ export function pickSchema(properties: SchemaFields, keys: readonly string[]): SchemaFields {
99
+ return Object.fromEntries(
100
+ keys.map((key) => [key, properties[key] ?? fail(key, "field missing from official schema")]),
101
+ );
102
+ }
103
+
104
+ const duration = compileSchema(definition("Duration"));
105
+ const durationUnits: Record<string, number> = {
106
+ ns: 1,
107
+ us: 1e3,
108
+ µs: 1e3,
109
+ μs: 1e3,
110
+ ms: 1e6,
111
+ s: 1e9,
112
+ m: 60e9,
113
+ h: 3600e9,
114
+ d: 86400e9,
115
+ };
116
+
117
+ export function durationNanoseconds(value: unknown, path: string): number {
118
+ if (value === undefined) return 0;
119
+ const input = checkSchema(duration, value, path) as string;
120
+ let nanoseconds = 0;
121
+ for (const match of input.matchAll(/(\d+(?:\.\d*)?|\.\d+)(ns|us|µs|μs|ms|s|m|h|d)/g)) {
122
+ nanoseconds += Math.trunc(Number(match[1]) * durationUnits[match[2]!]!);
123
+ }
124
+ return input.startsWith("-") ? -nanoseconds : nanoseconds;
125
+ }
126
+
127
+ const nonempty = { type: "string", minLength: 1 };
128
+ const shortId = { type: "string", pattern: "^(?:[0-9a-fA-F]{2}){0,8}$" };
129
+ // Unpadded Base64url needs 43 characters for a 32-byte key.
130
+ const realityKey = { type: "string", pattern: "^[A-Za-z0-9_-]{43}$" };
131
+
132
+ export const tlsProfileValidators = {
133
+ server: {
134
+ files: compileSchema({
135
+ type: "object",
136
+ additionalProperties: false,
137
+ properties: { side: { const: "server" }, certificate_path: nonempty, key_path: nonempty },
138
+ required: ["side", "certificate_path", "key_path"],
139
+ }),
140
+ provider: compileSchema({
141
+ type: "object",
142
+ additionalProperties: false,
143
+ properties: { side: { const: "server" }, certificate_provider: nonempty },
144
+ required: ["side", "certificate_provider"],
145
+ }),
146
+ reality: compileSchema({
147
+ type: "object",
148
+ additionalProperties: false,
149
+ properties: {
150
+ side: { const: "server" },
151
+ server_name: nonempty,
152
+ reality: {
153
+ type: "object",
154
+ additionalProperties: false,
155
+ properties: {
156
+ private_key: realityKey,
157
+ short_id: { anyOf: [shortId, { type: "array", items: shortId }] },
158
+ handshake: {
159
+ type: "object",
160
+ additionalProperties: false,
161
+ properties: pickSchema(definition("InboundRealityHandshakeOptions").properties!, [
162
+ "server",
163
+ "server_port",
164
+ "connect_timeout",
165
+ "detour",
166
+ "domain_resolver",
167
+ "netns",
168
+ ]),
169
+ required: ["server", "server_port"],
170
+ },
171
+ },
172
+ required: ["private_key", "short_id", "handshake"],
173
+ },
174
+ },
175
+ required: ["side", "server_name", "reality"],
176
+ }),
177
+ },
178
+ client: {
179
+ regular: compileSchema({
180
+ type: "object",
181
+ additionalProperties: false,
182
+ properties: {
183
+ side: { const: "client" },
184
+ ...pickSchema(definition("OutboundTLSOptions").properties!, [
185
+ "server_name",
186
+ "certificate_path",
187
+ ]),
188
+ },
189
+ required: ["side"],
190
+ }),
191
+ reality: compileSchema({
192
+ type: "object",
193
+ additionalProperties: false,
194
+ properties: {
195
+ side: { const: "client" },
196
+ server_name: nonempty,
197
+ reality: {
198
+ type: "object",
199
+ additionalProperties: false,
200
+ properties: { public_key: realityKey, short_id: shortId },
201
+ required: ["public_key", "short_id"],
202
+ },
203
+ },
204
+ required: ["side", "server_name", "reality"],
205
+ }),
206
+ },
207
+ };
@@ -0,0 +1,247 @@
1
+ import type {
2
+ DomainResolver as RawDomainResolver,
3
+ HTTPClient,
4
+ HTTPClientReference,
5
+ InboundRealityHandshakeOptions,
6
+ InboundTLSOptions,
7
+ OutboundTLSOptions,
8
+ } from "./generated/sing-box";
9
+ import { expandFields, fieldsFrom, record, ref, resourceData } from "./resource";
10
+ import type {
11
+ CertificateProvider,
12
+ DnsServer,
13
+ Egress,
14
+ Expand,
15
+ Fields,
16
+ ListenDetour,
17
+ Namespace,
18
+ ReadonlyJson,
19
+ Resolve,
20
+ Resource,
21
+ } from "./resource";
22
+ import {
23
+ checkSchema,
24
+ compileSchema,
25
+ definition,
26
+ durationNanoseconds,
27
+ fail,
28
+ tlsProfileValidators,
29
+ } from "./schema";
30
+
31
+ export type DomainResolver =
32
+ | DnsServer
33
+ | (ReadonlyJson<Omit<Extract<RawDomainResolver, object>, "server">> & {
34
+ readonly server: DnsServer;
35
+ });
36
+
37
+ export interface DirectDial {
38
+ /**
39
+ * Go Duration string. An explicit detour disallows a non-zero timeout on
40
+ * the resource using it. Configure the timeout on the detour target.
41
+ * On a direct detour target, an effective zero is equivalent to omission.
42
+ */
43
+ readonly connect_timeout?: HTTPClient["connect_timeout"];
44
+ readonly domain_resolver?: DomainResolver;
45
+ readonly netns?: Namespace | string;
46
+ }
47
+
48
+ export interface Dial extends DirectDial {
49
+ readonly detour?: Egress;
50
+ }
51
+
52
+ export interface Listener {
53
+ readonly port: number;
54
+ readonly netns?: Namespace | string;
55
+ }
56
+
57
+ export interface InboundListener extends Listener {
58
+ readonly detour?: ListenDetour;
59
+ }
60
+
61
+ export type ServerTls = { side: "server"; reality?: never } & (
62
+ | (Required<Pick<InboundTLSOptions, "certificate_path" | "key_path">> & {
63
+ certificate_provider?: never;
64
+ })
65
+ | { certificate_provider: CertificateProvider; certificate_path?: never; key_path?: never }
66
+ );
67
+ export type ClientTls = { side: "client"; reality?: never } & ReadonlyJson<
68
+ Pick<OutboundTLSOptions, "server_name" | "certificate_path">
69
+ >;
70
+ export type RealityServerTls = {
71
+ side: "server";
72
+ server_name: string;
73
+ certificate_path?: never;
74
+ key_path?: never;
75
+ certificate_provider?: never;
76
+ reality: {
77
+ private_key: string;
78
+ short_id: string | readonly string[];
79
+ handshake: Required<Pick<InboundRealityHandshakeOptions, "server" | "server_port">> & Dial;
80
+ };
81
+ };
82
+ export type RealityClientTls = {
83
+ side: "client";
84
+ server_name: string;
85
+ certificate_path?: never;
86
+ reality: { public_key: string; short_id: string };
87
+ };
88
+
89
+ export type HttpClientValue = Resource<"http_clients", "http-client", string | undefined>;
90
+ export type InlineHttpClient = ReadonlyJson<
91
+ Omit<Extract<HTTPClientReference, object>, keyof Dial>
92
+ > &
93
+ Dial & { readonly tag?: never };
94
+ export type HttpClientInput = HttpClientValue | InlineHttpClient;
95
+
96
+ export const previewReference: Resolve = (value, role, path) => {
97
+ if (!resourceData(value)) fail(path, `expected a typed ${role} reference`);
98
+ return "reference";
99
+ };
100
+
101
+ export const expandResolver: Expand = (value, path, resolve) => {
102
+ if (resourceData(value) || typeof value !== "object" || value === null) {
103
+ return resolve(value, "dns-server", path);
104
+ }
105
+ const options = record(value, path);
106
+ if (options.server === undefined) fail(`${path}.server`, "required field");
107
+ return expandFields(options, { server: ref("dns-server") }, path, resolve);
108
+ };
109
+
110
+ const expandNamespace: Expand = (value, path, resolve) =>
111
+ typeof value === "string" ? value : resolve(value, "netns", path);
112
+ export const listenReferences = { netns: expandNamespace, detour: ref("listen-detour") };
113
+ export const dialReferences = {
114
+ netns: expandNamespace,
115
+ detour: ref("dial-detour"),
116
+ domain_resolver: expandResolver,
117
+ };
118
+
119
+ export function checkDial(fields: Fields, path: string): void {
120
+ const timeout = durationNanoseconds(fields.connect_timeout, `${path}.connect_timeout`);
121
+ if (fields.detour === undefined) return;
122
+ if (timeout !== 0) fail(`${path}.connect_timeout`, "non-zero timeout with detour");
123
+ if (fields.netns !== undefined && fields.netns !== "")
124
+ fail(`${path}.netns`, "namespace with detour");
125
+ }
126
+
127
+ const commonDialKeys = [
128
+ "connect_timeout",
129
+ "domain_resolver",
130
+ "netns",
131
+ ] as const satisfies readonly (keyof DirectDial)[];
132
+ export function dialFields(input: unknown, path: string, detour: boolean): Fields {
133
+ const fields = fieldsFrom(input, path, detour ? [...commonDialKeys, "detour"] : commonDialKeys);
134
+ checkDial(fields, path);
135
+ return fields;
136
+ }
137
+
138
+ export function listenFields(
139
+ address: string,
140
+ input: unknown,
141
+ path: string,
142
+ detour: boolean,
143
+ ): Fields {
144
+ const { port, ...options } = fieldsFrom(
145
+ input,
146
+ path,
147
+ detour ? ["port", "netns", "detour"] : ["port", "netns"],
148
+ ["port"],
149
+ );
150
+ if (typeof address !== "string") fail(`${path}.listen`, "expected a string");
151
+ return { listen: address, listen_port: port, ...options };
152
+ }
153
+
154
+ const expandReality: Expand = (value, path, resolve) =>
155
+ expandFields(
156
+ record(value, path),
157
+ {
158
+ handshake: (handshake, path, resolve) =>
159
+ expandFields(record(handshake, path), dialReferences, path, resolve),
160
+ },
161
+ path,
162
+ resolve,
163
+ );
164
+
165
+ export const expandTls: Expand = (value, path, resolve) =>
166
+ expandFields(
167
+ record(value, path),
168
+ {
169
+ certificate_provider: ref("certificate-provider"),
170
+ reality: expandReality,
171
+ },
172
+ path,
173
+ resolve,
174
+ );
175
+
176
+ export type TlsMode = "server" | "client" | "server-reality" | "client-reality";
177
+
178
+ export function tlsFields(input: unknown, path: string, mode: TlsMode): Fields {
179
+ const profile = record(input, path);
180
+ const server = mode === "server" || mode === "server-reality";
181
+ const isReality = profile.reality !== undefined;
182
+ if (isReality && !mode.endsWith("-reality")) fail(`${path}.reality`, "unsupported TLS profile");
183
+ const validate = server
184
+ ? isReality
185
+ ? tlsProfileValidators.server.reality
186
+ : profile.certificate_provider === undefined
187
+ ? tlsProfileValidators.server.files
188
+ : tlsProfileValidators.server.provider
189
+ : isReality
190
+ ? tlsProfileValidators.client.reality
191
+ : tlsProfileValidators.client.regular;
192
+
193
+ checkSchema(validate, expandTls(profile, path, previewReference), path);
194
+ const { side: _side, ...fields } = profile;
195
+ if (isReality) {
196
+ const reality = record(profile.reality, `${path}.reality`);
197
+ if (server)
198
+ checkDial(
199
+ record(reality.handshake, `${path}.reality.handshake`),
200
+ `${path}.reality.handshake`,
201
+ );
202
+ fields.reality = { ...reality, enabled: true };
203
+ if (!server) fields.utls = { enabled: true };
204
+ }
205
+ return { tls: { ...fields, enabled: true } };
206
+ }
207
+
208
+ const httpClientObject = compileSchema(definition("HTTPClientReference").anyOf![1]!);
209
+ export const expandHttpClient: Expand = (value, path, resolve) => {
210
+ const data = resourceData(value);
211
+ if (data) {
212
+ if (data.target === "http_clients" && data.fields.tag === undefined) {
213
+ return expandFields(data.fields, data.references ?? {}, path, resolve);
214
+ }
215
+ return resolve(value, "http-client", path);
216
+ }
217
+ const fields = record(value, path);
218
+ if (Object.hasOwn(fields, "tag")) fail(`${path}.tag`, "unexpected field");
219
+ checkDial(fields, path);
220
+ const output = expandFields(fields, dialReferences, path, resolve);
221
+ return checkSchema(httpClientObject, output, path);
222
+ };
223
+
224
+ export const expandDashboard: Expand = (value, path, resolve) =>
225
+ typeof value === "string" || typeof value === "boolean"
226
+ ? value
227
+ : expandFields(record(value, path), { http_client: expandHttpClient }, path, resolve);
228
+
229
+ export const expandSsmServers: Expand = (value, path, resolve) => {
230
+ const servers = Object.entries(record(value, path));
231
+ if (servers.length === 0) fail(path, "expected at least one SSM server");
232
+ return Object.fromEntries(
233
+ servers.map(([pattern, inbound]) => {
234
+ const fieldPath = `${path}[${JSON.stringify(pattern)}]`;
235
+ if (!pattern.startsWith("/")) fail(fieldPath, "expected a route pattern starting with /");
236
+ return [pattern, resolve(inbound, "ssm", fieldPath)];
237
+ }),
238
+ );
239
+ };
240
+
241
+ export function isEmptyDirect(fields: Fields): boolean {
242
+ return (
243
+ durationNanoseconds(fields.connect_timeout, "connect_timeout") === 0 &&
244
+ (fields.netns === undefined || fields.netns === "") &&
245
+ fields.domain_resolver === undefined
246
+ );
247
+ }
package/src/user.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { fieldsFrom, preserveIdentity } from "./resource";
2
+ import { fail } from "./schema";
3
+
4
+ declare const userBrand: unique symbol;
5
+ export interface User {
6
+ readonly name: string;
7
+ readonly [userBrand]: true;
8
+ }
9
+
10
+ const users = new WeakSet<object>();
11
+
12
+ export function user(input: { name: string }): User {
13
+ const { name } = fieldsFrom(input, "user", ["name"], ["name"]);
14
+ if (typeof name !== "string") fail("user.name", "expected a string");
15
+ const value = preserveIdentity({ name });
16
+ users.add(value);
17
+ return value as User;
18
+ }
19
+
20
+ export function isUser(value: unknown): value is User {
21
+ return value !== null && typeof value === "object" && users.has(value);
22
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "exclude": ["dist", "node_modules"],
3
+ "compilerOptions": {
4
+ // Environment setup & latest features
5
+ "lib": ["ESNext"],
6
+ "target": "ESNext",
7
+ "module": "Preserve",
8
+ "moduleDetection": "force",
9
+ "jsx": "react-jsx",
10
+ "allowJs": true,
11
+ "types": ["bun"],
12
+
13
+ // Bundler mode
14
+ "moduleResolution": "bundler",
15
+ "allowImportingTsExtensions": true,
16
+ "verbatimModuleSyntax": true,
17
+ "noEmit": true,
18
+
19
+ // Best practices
20
+ "strict": true,
21
+ "skipLibCheck": true,
22
+ "noFallthroughCasesInSwitch": true,
23
+ "noUncheckedIndexedAccess": true,
24
+ "noImplicitOverride": true,
25
+
26
+ // Some stricter flags (disabled by default)
27
+ "noUnusedLocals": false,
28
+ "noUnusedParameters": false,
29
+ "noPropertyAccessFromIndexSignature": false
30
+ }
31
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { defineConfig } from "vite-plus";
2
+
3
+ export default defineConfig({
4
+ pack: {
5
+ entry: ["./index.ts"],
6
+ format: "esm",
7
+ dts: true,
8
+ },
9
+ fmt: {
10
+ ignorePatterns: ["dist/**", "schema/sing-box.json", "src/generated/sing-box.ts"],
11
+ },
12
+ lint: {
13
+ ignorePatterns: ["dist/**", "src/generated/sing-box.ts"],
14
+ options: { typeAware: true, typeCheck: true },
15
+ },
16
+ });