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,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
+ }