sing-box-kit 0.1.0 → 0.1.2

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,299 @@
1
+ import { definition, definitionName, fail, rootProperties, schemaBranches } from "./schema";
2
+ import type { SchemaFields, SchemaNode } from "./schema";
3
+ import type { Role, Target } from "./resource";
4
+
5
+ export const targetSchema = {
6
+ inbounds: "Inbound",
7
+ outbounds: "Outbound",
8
+ endpoints: "Endpoint",
9
+ services: "Service",
10
+ http_clients: "HTTPClient",
11
+ "dns.servers": "DNSServer",
12
+ "route.rule_set": "RuleSet",
13
+ certificate_providers: "CertificateProvider",
14
+ network_namespaces: "NetworkNamespace",
15
+ } as const satisfies Record<Target, string>;
16
+
17
+ export const tagReferences = {
18
+ inbound: { role: "inbound", type: "InboundRef" },
19
+ listen_detour: { role: "listen-detour", type: "ListenDetour" },
20
+ outbound: { role: "egress", type: "Egress" },
21
+ dial_detour: { role: "dial-detour", type: "Egress" },
22
+ network_namespace: { role: "netns", type: "Namespace", allowString: true },
23
+ dns_server: { role: "dns-server", type: "DnsServer" },
24
+ rule_set: { role: "rule-set", type: "RuleSetRef" },
25
+ certificate_provider: { role: "certificate-provider", type: "CertificateProvider" },
26
+ http_client: { role: "http-client", type: "HttpClientValue" },
27
+ tagged_http_client: { role: "http-client", type: "TaggedHttpClient" },
28
+ tailscale_endpoint: { role: "tailscale-endpoint", type: "TailscaleEndpoint" },
29
+ openconnect_endpoint: { role: "openconnect-endpoint", type: "OpenConnectEndpoint" },
30
+ openvpn_client_endpoint: { role: "openvpn-client-endpoint", type: "OpenVpnClientEndpoint" },
31
+ resolved_service: { role: "resolved-service", type: "ResolvedService" },
32
+ ssm: { role: "ssm", type: "SsmInbound" },
33
+ preferred_routes: { role: "preferred-routes", type: "PreferredRoutes" },
34
+ preferred_domain: { role: "preferred-domain", type: "PreferredDomain" },
35
+ } as const satisfies Record<string, { role: Role; type: string; allowString?: boolean }>;
36
+
37
+ export function tagReference(name: string) {
38
+ if (!Object.hasOwn(tagReferences, name)) fail(name, "unknown tag reference");
39
+ return tagReferences[name as keyof typeof tagReferences];
40
+ }
41
+
42
+ function tagged(schema: SchemaNode, reference: keyof typeof tagReferences): SchemaNode {
43
+ return { ...schema, "x-tag-reference": reference };
44
+ }
45
+
46
+ export function inputProperty(key: string, schema: SchemaNode): SchemaNode {
47
+ if (key !== "detour") return schema;
48
+ const reference = schema["x-tag-reference"];
49
+ if (reference === "outbound") return tagged(schema, "dial_detour");
50
+ if (reference === "inbound") return tagged(schema, "listen_detour");
51
+ return schema;
52
+ }
53
+
54
+ function oneOrManyReference(schema: SchemaNode, reference: keyof typeof tagReferences) {
55
+ return {
56
+ ...schema,
57
+ anyOf: schema.anyOf!.map((option) =>
58
+ option.items
59
+ ? { ...option, items: tagged(option.items, reference) }
60
+ : tagged(option, reference),
61
+ ),
62
+ };
63
+ }
64
+
65
+ function projectObject(properties: SchemaFields, required: readonly string[] = []): SchemaNode {
66
+ return { type: "object", properties, required, additionalProperties: false };
67
+ }
68
+
69
+ function supplementFactory(target: Target, kind: string, properties: SchemaFields): void {
70
+ if (target === "dns.servers" && properties.endpoint) {
71
+ const references = {
72
+ tailscale: "tailscale_endpoint",
73
+ openconnect: "openconnect_endpoint",
74
+ openvpn: "openvpn_client_endpoint",
75
+ } as const;
76
+ if (Object.hasOwn(references, kind)) {
77
+ properties.endpoint = tagged(
78
+ properties.endpoint,
79
+ references[kind as keyof typeof references],
80
+ );
81
+ }
82
+ }
83
+ if (target === "dns.servers" && kind === "resolved") {
84
+ properties.service = tagged(properties.service!, "resolved_service");
85
+ }
86
+ if (target === "certificate_providers" && kind === "tailscale") {
87
+ properties.endpoint = tagged(properties.endpoint!, "tailscale_endpoint");
88
+ }
89
+ if (target === "services" && kind === "derp") {
90
+ properties.verify_client_endpoint = oneOrManyReference(
91
+ properties.verify_client_endpoint!,
92
+ "tailscale_endpoint",
93
+ );
94
+ }
95
+ if (target === "services" && kind === "ssm-api") {
96
+ const servers = properties.servers!;
97
+ properties.servers = { ...servers, additionalProperties: tagged({ type: "string" }, "ssm") };
98
+ }
99
+ }
100
+
101
+ const definitions = new Map<string, SchemaNode>();
102
+ export function inputDefinition(name: string): SchemaNode {
103
+ const cached = definitions.get(name);
104
+ if (cached) return cached;
105
+
106
+ let schema = definition(name);
107
+ if (name === "RouteOptions") {
108
+ schema = {
109
+ ...schema,
110
+ properties: {
111
+ ...schema.properties,
112
+ default_http_client: tagged(schema.properties!.default_http_client!, "tagged_http_client"),
113
+ },
114
+ };
115
+ }
116
+ if (name === "CertificateProviderReference") {
117
+ const [tag, inline] = schema.anyOf!;
118
+ schema = {
119
+ ...schema,
120
+ anyOf: [
121
+ tag!,
122
+ {
123
+ ...inline,
124
+ oneOf: inline!.oneOf!.map((branch) => {
125
+ if (branch.properties?.type?.const !== "tailscale") return branch;
126
+ const properties = { ...branch.properties };
127
+ supplementFactory("certificate_providers", "tailscale", properties);
128
+ return { ...branch, properties };
129
+ }),
130
+ },
131
+ ],
132
+ };
133
+ }
134
+ definitions.set(name, schema);
135
+ return schema;
136
+ }
137
+
138
+ export const rootSettings = Object.fromEntries(
139
+ Object.entries(rootProperties).filter(
140
+ ([key]) => !Object.hasOwn(targetSchema, key) && key !== "route" && key !== "dns",
141
+ ),
142
+ );
143
+ export const sectionSettings = {
144
+ route: projectObject(
145
+ Object.fromEntries(
146
+ Object.entries(inputDefinition("RouteOptions").properties!).filter(
147
+ ([key]) => key !== "rules" && key !== "rule_set",
148
+ ),
149
+ ),
150
+ ),
151
+ dns: projectObject(
152
+ Object.fromEntries(
153
+ Object.entries(definition("DNS").properties!).filter(
154
+ ([key]) => key !== "rules" && key !== "servers",
155
+ ),
156
+ ),
157
+ ),
158
+ };
159
+
160
+ const dialKeys = new Set(Object.keys(definition("DialerOptions").properties!));
161
+ const listenKeys = new Set([
162
+ "listen",
163
+ "listen_port",
164
+ "udp_timeout",
165
+ "domain_resolver",
166
+ "bind_interface",
167
+ "routing_mark",
168
+ "reuse_addr",
169
+ "netns",
170
+ "disable_tcp_keep_alive",
171
+ "tcp_keep_alive",
172
+ "tcp_keep_alive_interval",
173
+ "tcp_fast_open",
174
+ "tcp_multi_path",
175
+ "udp_fragment",
176
+ "detour",
177
+ ]);
178
+
179
+ // SBKit requirements supplement the schema's structural requirements.
180
+ const requiredOptions: Partial<Record<Target, Record<string, readonly string[]>>> = {
181
+ inbounds: { shadowsocks: ["method"], vless: ["users"] },
182
+ outbounds: {
183
+ vless: ["server", "server_port", "uuid"],
184
+ selector: ["outbounds"],
185
+ urltest: ["outbounds"],
186
+ },
187
+ endpoints: { wireguard: ["address", "private_key"] },
188
+ services: { "ssm-api": ["servers"] },
189
+ "dns.servers": {
190
+ tcp: ["server"],
191
+ udp: ["server"],
192
+ tls: ["server"],
193
+ https: ["server"],
194
+ tailscale: ["endpoint"],
195
+ openconnect: ["endpoint"],
196
+ openvpn: ["endpoint"],
197
+ resolved: ["service"],
198
+ },
199
+ "route.rule_set": { inline: ["rules"], local: ["path"], remote: ["url"] },
200
+ certificate_providers: { tailscale: ["endpoint"] },
201
+ network_namespaces: { default: ["path"] },
202
+ };
203
+
204
+ export interface FactoryBranch {
205
+ output: SchemaNode;
206
+ options: SchemaNode;
207
+ listen?: SchemaNode;
208
+ dial?: SchemaNode;
209
+ tls?: SchemaNode;
210
+ }
211
+
212
+ export function factoryCatalog(target: Target): Map<string, FactoryBranch[]> {
213
+ const kinds = new Map<string, FactoryBranch[]>();
214
+ for (const schema of schemaBranches(definition(targetSchema[target]))) {
215
+ const type = schema.properties?.type;
216
+ const kind = type?.const ?? type?.enum?.[0] ?? "http-client";
217
+ if (typeof kind !== "string") fail(target, "expected a resource kind in the schema");
218
+ const properties = Object.fromEntries(
219
+ Object.entries(schema.properties ?? {}).map(([key, value]) => [
220
+ key,
221
+ inputProperty(key, value),
222
+ ]),
223
+ );
224
+ supplementFactory(target, kind, properties);
225
+ const listens = properties.listen !== undefined || (target === "inbounds" && kind === "tun");
226
+ const options: SchemaFields = {};
227
+ const listen: SchemaFields = {};
228
+ const dial: SchemaFields = {};
229
+ for (const [key, value] of Object.entries(properties)) {
230
+ if (key === "type" || key === "tls") continue;
231
+ if (listens && listenKeys.has(key)) {
232
+ if (key === "listen") continue;
233
+ listen[key === "listen_port" ? "port" : key] = value;
234
+ } else if (!listens && dialKeys.has(key)) {
235
+ // sing-box disallows detouring through a direct outbound's own Dial Fields.
236
+ if (key === "detour" && target === "outbounds" && kind === "direct") continue;
237
+ dial[key] = value;
238
+ } else {
239
+ options[key] = value;
240
+ }
241
+ }
242
+ const required = [...(schema.required ?? []), ...(requiredOptions[target]?.[kind] ?? [])];
243
+ if (target !== "services" && target !== "http_clients") required.push("tag");
244
+ const branch: FactoryBranch = {
245
+ output: { ...schema, properties },
246
+ options: projectObject(
247
+ options,
248
+ [...new Set(required)].filter((key) => Object.hasOwn(options, key)),
249
+ ),
250
+ listen: listens ? projectObject(listen) : undefined,
251
+ dial: Object.keys(dial).length ? projectObject(dial) : undefined,
252
+ tls: properties.tls,
253
+ };
254
+ const entries = kinds.get(kind) ?? [];
255
+ entries.push(branch);
256
+ kinds.set(kind, entries);
257
+ }
258
+ return kinds;
259
+ }
260
+
261
+ export function factoryName(kind: string): string {
262
+ return kind.replace(/-([a-z])/g, (_match, letter: string) => letter.toUpperCase());
263
+ }
264
+
265
+ export function schemaShape(schema: SchemaNode): SchemaNode {
266
+ const name = definitionName(schema);
267
+ return name ? inputDefinition(name) : schema;
268
+ }
269
+
270
+ export const ruleMatchSchema = {
271
+ route: matchSchema("NestedRule", "preferred_routes"),
272
+ dns: matchSchema("NestedDNSRule", "preferred_domain"),
273
+ };
274
+
275
+ function matchSchema(
276
+ name: "NestedRule" | "NestedDNSRule",
277
+ preferred: "preferred_routes" | "preferred_domain",
278
+ ): SchemaNode {
279
+ const { type: _type, ...properties } = definition(name).oneOf![0]!.properties!;
280
+ properties.preferred_by = oneOrManyReference(properties.preferred_by!, preferred);
281
+ return projectObject(properties);
282
+ }
283
+
284
+ export function ruleActionSchemas(scope: "route" | "dns"): Map<string, SchemaNode> {
285
+ const actions = schemaBranches(definition(scope === "route" ? "RuleAction" : "DNSRuleAction"));
286
+ return new Map(
287
+ actions.map((branch) => {
288
+ const properties = { ...branch.properties };
289
+ const action = properties.action!.const as string;
290
+ const required = new Set(["action", ...(branch.required ?? [])]);
291
+ if (action === "route" && scope === "route") required.add("outbound");
292
+ if (scope === "dns" && (action === "route" || action === "evaluate")) required.add("server");
293
+ if (action === "reject" && scope === "dns") {
294
+ properties.method = { type: "string", enum: ["default", "drop"] };
295
+ }
296
+ return [action, projectObject(properties, [...required])];
297
+ }),
298
+ );
299
+ }
package/src/resource.ts CHANGED
@@ -1,9 +1,6 @@
1
1
  import { fail, keyPath } from "./schema";
2
+ import type { Fields } from "./type-utils";
2
3
 
3
- export type Fields = Record<string, unknown>;
4
- export type ReadonlyJson<T> = T extends object
5
- ? { readonly [K in keyof T]: ReadonlyJson<T[K]> }
6
- : T;
7
4
  export type Target =
8
5
  | "inbounds"
9
6
  | "outbounds"
@@ -27,7 +24,10 @@ export type Role =
27
24
  | "http-client"
28
25
  | "netns"
29
26
  | "rule-set"
30
- | "tailscale-endpoint";
27
+ | "tailscale-endpoint"
28
+ | "openconnect-endpoint"
29
+ | "openvpn-client-endpoint"
30
+ | "resolved-service";
31
31
 
32
32
  declare const resourceBrand: unique symbol;
33
33
  export interface Resource<
@@ -47,12 +47,30 @@ export type ListenDetour = Resource<
47
47
  "listen-detour" | "inbound" | "ssm"
48
48
  >;
49
49
  export type Egress = Resource<"outbounds" | "endpoints", string, string>;
50
- export type PreferredRoutes = Resource<"endpoints", "tailscale" | "wireguard", string>;
50
+ export const preferredRouteEndpoints = [
51
+ "tailscale",
52
+ "wireguard",
53
+ "openconnect",
54
+ "openvpn-client",
55
+ ] as const;
56
+ export type PreferredRoutes =
57
+ | Resource<"endpoints", (typeof preferredRouteEndpoints)[number], string>
58
+ | Resource<"outbounds", "bridge", string>;
51
59
  export type DnsServer = Resource<"dns.servers", string, string>;
52
- export type PreferredDomain = Resource<"dns.servers", "tailscale", string>;
60
+ export const preferredDnsKinds = [
61
+ "hosts",
62
+ "local",
63
+ "mdns",
64
+ "tailscale",
65
+ "openconnect",
66
+ "openvpn",
67
+ "resolved",
68
+ ] as const;
69
+ export type PreferredDomain = Resource<"dns.servers", (typeof preferredDnsKinds)[number], string>;
53
70
  export type Namespace = Resource<"network_namespaces", string, string>;
54
71
  export type CertificateProvider = Resource<"certificate_providers", string, string>;
55
72
  export type TaggedHttpClient = Resource<"http_clients", "http-client", string>;
73
+ export type HttpClientValue = Resource<"http_clients", "http-client", string | undefined>;
56
74
  export type RuleSetRef = Resource<"route.rule_set", string, string | readonly [string]>;
57
75
  export type SsmInbound = Resource<
58
76
  "inbounds",
@@ -62,16 +80,18 @@ export type SsmInbound = Resource<
62
80
  > & { readonly [ssmBrand]: true };
63
81
  declare const ssmBrand: unique symbol;
64
82
  export type TailscaleEndpoint = Resource<"endpoints", "tailscale", string>;
83
+ export type OpenConnectEndpoint = Resource<"endpoints", "openconnect", string>;
84
+ export type OpenVpnClientEndpoint = Resource<"endpoints", "openvpn-client", string>;
85
+ export type ResolvedService = Resource<"services", "resolved", string>;
65
86
 
66
87
  export type Resolve = (value: unknown, role: Role, path: string) => string;
67
88
  export type Expand = (value: unknown, path: string, resolve: Resolve) => unknown;
68
- export type Expansions = Readonly<Record<string, Expand>>;
69
89
  export interface ResourceData {
70
90
  readonly target: Target;
71
91
  readonly kind: string;
72
92
  readonly fields: Fields;
73
93
  readonly roles: readonly Role[];
74
- readonly references?: Expansions;
94
+ readonly expand?: Expand;
75
95
  readonly startupDetour?: boolean;
76
96
  readonly remoteDns?: boolean;
77
97
  }
@@ -131,7 +151,7 @@ function copy(value: unknown, path: string, immutable: boolean, ancestors: Set<o
131
151
  if (value === null || typeof value !== "object") return value;
132
152
  if (identities.has(value)) {
133
153
  if (immutable) return value;
134
- fail(path, "unexpected Kit value in JSON fields");
154
+ fail(path, "unexpected SBKit value in JSON fields");
135
155
  }
136
156
  if (ancestors.has(value)) fail(path, "cyclic configuration object");
137
157
  ancestors.add(value);
@@ -154,32 +174,3 @@ export function snapshot<T>(value: T, path: string): T {
154
174
  export function copyJson<T>(value: T, path: string): T {
155
175
  return copy(value, path, false, new Set()) as T;
156
176
  }
157
-
158
- export const ref =
159
- (role: Role): Expand =>
160
- (value, path, resolve) =>
161
- resolve(value, role, path);
162
-
163
- export const arrayOrOne =
164
- (expand: Expand): Expand =>
165
- (value, path, resolve) =>
166
- Array.isArray(value)
167
- ? Array.from(value, (item, index) => expand(item, `${path}[${index}]`, resolve))
168
- : expand(value, path, resolve);
169
-
170
- export function expandFields(
171
- fields: Fields,
172
- expansions: Expansions,
173
- path: string,
174
- resolve: Resolve,
175
- ): Fields {
176
- return Object.fromEntries(
177
- Object.entries(fields)
178
- .filter(([, value]) => value !== undefined)
179
- .map(([key, value]) => {
180
- const fieldPath = keyPath(path, key);
181
- const expand = Object.hasOwn(expansions, key) ? expansions[key] : undefined;
182
- return [key, expand ? expand(value, fieldPath, resolve) : copyJson(value, fieldPath)];
183
- }),
184
- );
185
- }