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.
- package/README.md +27 -9
- package/dist/index.d.mts +2573 -596
- package/dist/index.mjs +612 -651
- package/docs/configuration.md +21 -43
- package/docs/dns-rules.md +43 -0
- package/docs/internal/README.md +31 -0
- package/docs/resources.md +47 -0
- package/docs/rules.md +38 -45
- package/docs/settings.md +36 -0
- package/package.json +1 -1
- package/schema/README.md +3 -3
- package/scripts/generate-schema.ts +153 -0
- package/src/compile.ts +35 -59
- package/src/factories.ts +315 -532
- package/src/generated/sbkit-inputs.ts +2671 -0
- package/src/input-schema.ts +299 -0
- package/src/resource.ts +30 -39
- package/src/rules.ts +82 -207
- package/src/schema.ts +15 -23
- package/src/settings.ts +155 -156
- package/src/type-utils.ts +15 -0
- package/vite.config.ts +2 -2
package/docs/configuration.md
CHANGED
|
@@ -1,56 +1,34 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Build and validate a configuration
|
|
2
2
|
|
|
3
|
-
Create resources with the factories
|
|
3
|
+
Create resources with the package factories, apply any shared settings, then pass the finished resources to `compile()`. Use those same resource values wherever the configuration references them.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
```ts
|
|
6
|
+
import { compile, dnsServer, outbound } from "sing-box-kit";
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
| `inbound.mixed()`, `inbound.socks()`, `inbound.shadowsocks()`, `inbound.vless()` | `inbounds` |
|
|
10
|
-
| `outbound.direct()`, `outbound.vless()`, `outbound.selector()`, `outbound.urltest()` | `outbounds` |
|
|
11
|
-
| `endpoint.tailscale()`, `endpoint.wireguard()` | `endpoints` |
|
|
12
|
-
| `service.api()`, `service.ssmApi()` | `services` |
|
|
13
|
-
| Tagged `httpClient()` | `http_clients` |
|
|
14
|
-
| `dnsServer.tcp()`, `dnsServer.udp()`, `dnsServer.tls()`, `dnsServer.https()`, `dnsServer.tailscale()` | `dns.servers` |
|
|
15
|
-
| `ruleSet.inline()`, `ruleSet.local()`, `ruleSet.remote()` | `route.rule_set` |
|
|
16
|
-
| `certificateProvider.tailscale()` | `certificate_providers` |
|
|
17
|
-
| `networkNamespace.default()`, `networkNamespace.unshare()` | `network_namespaces` |
|
|
8
|
+
const resolver = dnsServer.local({ tag: "local" });
|
|
9
|
+
const direct = outbound.direct({ tag: "direct" }).dial({ domain_resolver: resolver });
|
|
18
10
|
|
|
19
|
-
|
|
11
|
+
const config = compile({
|
|
12
|
+
outbounds: [direct],
|
|
13
|
+
dns: { servers: [resolver], final: resolver, strategy: "prefer_ipv4" },
|
|
14
|
+
route: { final: direct },
|
|
15
|
+
});
|
|
16
|
+
```
|
|
20
17
|
|
|
21
|
-
|
|
18
|
+
## Register and reference resources
|
|
22
19
|
|
|
23
|
-
|
|
20
|
+
Each builder method returns a new resource. In the example, register the result of `.dial()` in `outbounds` and pass that same value to `route.final`. If you recreate a resource with the same tag, rebuild any references to use the new value. Apply each settings method at most once per chain.
|
|
24
21
|
|
|
25
|
-
|
|
22
|
+
`compile()` checks that each reference points to a registered resource that supports the requested role. It resolves references to tags even inside objects, maps, and arrays. Outbounds and endpoints share a tag scope. Services without explicit tags use their zero-based list position for collision checks.
|
|
26
23
|
|
|
27
|
-
|
|
28
|
-
- `.dial(options)` accepts `connect_timeout`, `domain_resolver`, and `netns`. On dialers that accept `detour`, supply an outbound or endpoint. Put any non-zero timeout or namespace setting on the detour target. An otherwise empty direct outbound cannot be used as an explicit dial detour. WireGuard also disallows a non-zero `listen_port` with a dial detour.
|
|
29
|
-
- In Listen and Dial Fields, a typed `netns` value resolves to a registered namespace tag. A string passes through as supplied. sing-box looks for a registered tag before treating it as an OS name or path.
|
|
30
|
-
- Supply a DNS server to `domain_resolver` or `route.default_domain_resolver` directly or as `{ server: resolver, ...options }`. A TCP, UDP, TLS, or HTTPS DNS server configured with a hostname needs its own resolver or an explicit detour.
|
|
24
|
+
See [Resource factories and registration](resources.md) for the lists where each resource belongs and [Shared settings](settings.md) for available builder methods.
|
|
31
25
|
|
|
32
|
-
##
|
|
26
|
+
## Set top-level, route, and DNS options
|
|
33
27
|
|
|
34
|
-
|
|
28
|
+
Pass `$schema`, `log`, `ntp`, `certificate`, and `experimental` at the root of the input to `compile()`. Set route and DNS options directly under `route` and `dns`. See [Routing rules](rules.md) and [DNS rules](dns-rules.md) for their respective rule lists.
|
|
35
29
|
|
|
36
|
-
|
|
30
|
+
The returned `SingBoxConfig` is ready for `JSON.stringify()`. The compiler preserves list order, sing-box field names, and explicit values such as `false`, `0`, and empty arrays.
|
|
37
31
|
|
|
38
|
-
|
|
32
|
+
## Validate existing JSON
|
|
39
33
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
The API service defaults to loopback `127.0.0.1`. Omitting TLS uses plaintext TCP, and an omitted or empty `secret` allows unauthenticated connections. `dashboard` accepts a boolean, path string, or settings object. Set `enabled: true` to enable the dashboard in object form.
|
|
43
|
-
|
|
44
|
-
The dashboard and remote rule-sets accept either a tagged client registered in `http_clients`, an untagged `httpClient()` builder, or an inline HTTP settings object. The inline object supports the sing-box HTTP client shape without `tag`, with Kit references for `detour`, `domain_resolver`, and typed `netns`. The dashboard uses its own default settings when its client is omitted. Set `route.default_http_client` to a registered client or let sing-box use the first registered client as its default.
|
|
45
|
-
|
|
46
|
-
The SSM API service accepts a non-empty `servers` map from HTTP paths starting with `/` to registered Shadowsocks inbounds. Use static multi-user Shadowsocks with a non-empty `users` list or managed Shadowsocks with `managed: true`. The `none` method is available for single-user Shadowsocks. Managed mode requires an omitted or empty static user list.
|
|
47
|
-
|
|
48
|
-
## Groups and rule-sets
|
|
49
|
-
|
|
50
|
-
Selectors and URL tests take a non-empty `outbounds` list of egress references with unique tags. A selector's optional `default` must be a member of that list.
|
|
51
|
-
|
|
52
|
-
Inline rule-sets take a single tag and at least one `HeadlessRule`. Local and remote rule-sets infer `source` from a `.json` file and `binary` from a `.srs` file. For remote URLs the path determines the format. Supply `format` explicitly for other paths.
|
|
53
|
-
|
|
54
|
-
Local and remote rule-sets support multiple tags. Put `{tag}` in the local `path`, or in the remote `url` and any supplied `initial_path`. Use a single-tag rule-set when matching a rule-set in a route or DNS rule.
|
|
55
|
-
|
|
56
|
-
See [Route and DNS rules](rules.md) for condition and action examples.
|
|
34
|
+
Pass a parsed JSON configuration to `validateConfig(value)` to check it against the pinned sing-box schema. The function accepts raw tag strings and returns the validated `SingBoxConfig`. Use `compile()` when building a config with SBKit resources to also check registration, reference capabilities, and dependencies.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# DNS rules and response evaluation
|
|
2
|
+
|
|
3
|
+
Create a DNS rule with `dns.rule(condition, action)` and add it to `dns.rules` in `compile()`. Use `dns.rule(action)` for a rule that matches every query that reaches it. Register each referenced DNS server in `dns.servers`. See [Resource factories and registration](resources.md#dns-servers) for the available server types.
|
|
4
|
+
|
|
5
|
+
## Match conditions
|
|
6
|
+
|
|
7
|
+
Use `Rule.match(fields)` and the same condition methods as [routing rules](rules.md#match-conditions). DNS conditions include `query_type`, `query_client_subnet`, `query_dnssec`, and the response fields described below. DNS `preferred_by` accepts one or more Hosts, Local, mDNS, Tailscale, OpenConnect, OpenVPN, or Resolved DNS servers.
|
|
8
|
+
|
|
9
|
+
## DNS actions
|
|
10
|
+
|
|
11
|
+
| Action | Options |
|
|
12
|
+
| --------------- | --------------------------------------------------------------------------------------- |
|
|
13
|
+
| `route` | Requires a DNS `server`. Accepts shared DNS options, `race`, and `speculative`. |
|
|
14
|
+
| `evaluate` | Requires a DNS `server`. Accepts a result `tag`, shared DNS options, and `speculative`. |
|
|
15
|
+
| `respond` | Optional `race` |
|
|
16
|
+
| `route-options` | Requires at least one effective shared DNS option |
|
|
17
|
+
| `predefined` | Optional `rcode`, `answer`, `ns`, `extra`, and `race` |
|
|
18
|
+
| `reject` | Optional `method` of `default` or `drop`, plus `no_drop` and `race` |
|
|
19
|
+
|
|
20
|
+
Shared DNS options include `timeout`, `disable_cache`, `disable_optimistic_cache`, `rewrite_ttl`, `client_subnet`, and `remove_client_subnet`. For `route-options`, a positive timeout, a true flag, a valid subnet, or an explicit TTL counts as effective. A TTL of zero counts.
|
|
21
|
+
|
|
22
|
+
## DNS response evaluation
|
|
23
|
+
|
|
24
|
+
Place an `evaluate` rule before rules that depend on its response. Match a named response with `match_response: "tag"`, or an untagged response with `match_response: true`. With response matching active, a leaf can also test `response_rcode`, `response_answer`, `response_ns`, `response_extra`, `ip_cidr`, `ip_is_private`, or `ip_accept_any`.
|
|
25
|
+
|
|
26
|
+
A `respond` rule can return a named response when its own default condition matches that tag. For a logical `respond` rule, use an untagged evaluation. Enable `race` only on a rule with active response matching and omit `speculative` on that rule.
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { compile, dns, dnsServer, Rule } from "sing-box-kit";
|
|
30
|
+
|
|
31
|
+
const resolver = dnsServer.udp({ tag: "resolver", server: "192.0.2.53" });
|
|
32
|
+
const evaluate = dns.rule(Rule.match({ domain_suffix: "example.test" }), {
|
|
33
|
+
action: "evaluate",
|
|
34
|
+
server: resolver,
|
|
35
|
+
tag: "example-answer",
|
|
36
|
+
});
|
|
37
|
+
const respond = dns.rule(
|
|
38
|
+
Rule.match({ match_response: "example-answer", response_rcode: "NOERROR" }),
|
|
39
|
+
{ action: "respond" },
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
compile({ dns: { servers: [resolver], rules: [evaluate, respond] } });
|
|
43
|
+
```
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# SBKit internals
|
|
2
|
+
|
|
3
|
+
The [package entry point](../../index.ts) exports resource builders, rule builders, `compile()`, `validateConfig()`, and their public types. Users build a configuration from SBKit values, then call `compile()` to turn those values into sing-box JSON. The [configuration guide](../configuration.md) shows this flow through the public API.
|
|
4
|
+
|
|
5
|
+
## Resource builders and rules
|
|
6
|
+
|
|
7
|
+
- [`src/input-schema.ts`](../../src/input-schema.ts) projects the pinned schema into factory branches, configuration sections, and rule match and action schemas. A factory branch describes its options, output, and which shared settings methods it supports. The projection also maps `x-tag-reference` annotations to SBKit reference types and runtime roles.
|
|
8
|
+
- [`src/factories.ts`](../../src/factories.ts) builds the factory collections from that catalog. Each factory selects a schema branch, checks its options, and creates a resource. Calling `.listen()`, `.dial()`, or `.tls()` builds a new resource from the original options and the accumulated settings.
|
|
9
|
+
- [`src/resource.ts`](../../src/resource.ts) keeps resource metadata in a `WeakMap` keyed by the frozen builder value. The metadata includes its target list, kind, fields, and reference roles. Snapshots copy and freeze ordinary options while retaining the identity of SBKit values that may be referenced later.
|
|
10
|
+
- [`src/settings.ts`](../../src/settings.ts) normalizes listener and TLS settings and expands references in schema-shaped inputs. During builder validation, it uses placeholder strings for resource references so Ajv can validate the JSON shape before the full configuration is available.
|
|
11
|
+
- [`src/rules.ts`](../../src/rules.ts) stores condition trees and rule actions. Each condition carries the scopes it supports. Combining conditions intersects those scopes, while expansion turns groups into sing-box logical rules and places the action at the top level. [`src/user.ts`](../../src/user.ts) supplies the identity-bearing `User` values that inbound builders use to implement `.authUser()`.
|
|
12
|
+
|
|
13
|
+
## Configuration compilation
|
|
14
|
+
|
|
15
|
+
[`src/compile.ts`](../../src/compile.ts) assembles the configuration in this order.
|
|
16
|
+
|
|
17
|
+
1. **Register resources.** Read the root and nested resource lists and index each resource by its object identity. Index tags separately to catch collisions. Outbounds and endpoints share a tag scope.
|
|
18
|
+
2. **Expand settings and rules.** Walk the projected schemas and resolve each typed reference to a tag. The resolver checks the requested role, a single explicit tag, and registration of the exact builder value. During expansion it records dependency edges for group membership and for the detours and DNS resolver references that need cycle checks.
|
|
19
|
+
3. **Check relationships and validate JSON.** Check DNS response dependencies in rule order and reject cycles in the recorded dependency graph. Pass the assembled configuration to `validateConfig()`.
|
|
20
|
+
|
|
21
|
+
[`src/schema.ts`](../../src/schema.ts) owns the Ajv validators and formats validation errors with configuration paths. A direct call to `validateConfig()` starts at the final schema check and accepts raw sing-box JSON.
|
|
22
|
+
|
|
23
|
+
## Schema and generated types
|
|
24
|
+
|
|
25
|
+
[`schema/sing-box.json`](../../schema/sing-box.json) is the upstream snapshot used for final JSON validation. [`scripts/generate-schema.ts`](../../scripts/generate-schema.ts) generates [`sing-box.ts`](../../src/generated/sing-box.ts) from that snapshot for the raw `SingBoxConfig` shape. It generates [`sbkit-inputs.ts`](../../src/generated/sbkit-inputs.ts) from the projections in `input-schema.ts` for builder options, config sections, and rule inputs. Reusing those projections keeps the generated TypeScript inputs and runtime checks aligned. Follow the [schema generation guide](../../schema/README.md) when updating the pin or regenerating the types.
|
|
26
|
+
|
|
27
|
+
## Where to check a change
|
|
28
|
+
|
|
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.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Resource factories and registration
|
|
2
|
+
|
|
3
|
+
Choose a factory from the table and register its finished value in the corresponding `compile()` list. The pinned sing-box v1.14.4 schema contains 77 kinds with a `type` discriminator. SBKit also exports a standalone `httpClient()` factory.
|
|
4
|
+
|
|
5
|
+
| Package export | Factory methods | Register in |
|
|
6
|
+
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------- |
|
|
7
|
+
| `inbound` | `anytls`, `cloudflared`, `direct`, `http`, `hysteria`, `hysteria2`, `mixed`, `naive`, `redirect`, `shadowsocks`, `shadowtls`, `snell`, `socks`, `tproxy`, `trojan`, `tuic`, `tun`, `vless`, `vmess` | `inbounds` |
|
|
8
|
+
| `outbound` | `anytls`, `block`, `bridge`, `direct`, `http`, `hysteria`, `hysteria2`, `naive`, `selector`, `shadowsocks`, `shadowtls`, `snell`, `socks`, `ssh`, `tor`, `trojan`, `tuic`, `urltest`, `vless`, `vmess` | `outbounds` |
|
|
9
|
+
| `endpoint` | `openconnect`, `openvpnClient`, `openvpnServer`, `tailscale`, `wireguard` | `endpoints` |
|
|
10
|
+
| `service` | `api`, `ccm`, `derp`, `hysteriaRealm`, `ocm`, `oomKiller`, `resolved`, `ssmApi`, `usbipClient`, `usbipServer` | `services` |
|
|
11
|
+
| `dnsServer` | `dhcp`, `fakeip`, `h3`, `hosts`, `https`, `local`, `mdns`, `openconnect`, `openvpn`, `quic`, `resolved`, `tailscale`, `tcp`, `tls`, `udp` | `dns.servers` |
|
|
12
|
+
| `ruleSet` | `inline`, `local`, `remote` | `route.rule_set` |
|
|
13
|
+
| `certificateProvider` | `acme`, `cloudflareOriginCa`, `tailscale` | `certificate_providers` |
|
|
14
|
+
| `networkNamespace` | `default`, `unshare` | `network_namespaces` |
|
|
15
|
+
| `httpClient()` | Call directly. Supply a tag to register it. | `http_clients` |
|
|
16
|
+
|
|
17
|
+
## Inbounds and outbounds
|
|
18
|
+
|
|
19
|
+
Snell inbounds take `version: 5` or `6`. Snell outbounds take `version: 4` or `6`. The version selects which options you can supply.
|
|
20
|
+
|
|
21
|
+
VLESS builders take `transport` and `multiplex` in the factory options. See [TLS profiles](settings.md#tls-profiles) for configuring REALITY.
|
|
22
|
+
|
|
23
|
+
Selectors and URL tests take a non-empty `outbounds` list of egress references with unique tags. A selector's optional `default` must be a member of that list.
|
|
24
|
+
|
|
25
|
+
## DNS servers
|
|
26
|
+
|
|
27
|
+
`dnsServer.openconnect()` takes an `endpoint.openconnect()` value, `dnsServer.openvpn()` takes an `endpoint.openvpnClient()` value, and `dnsServer.resolved()` takes a tagged `service.resolved()` value. See [DNS resolvers](settings.md#dns-resolvers) for hostname resolution and [DNS rules](dns-rules.md) for selecting a server.
|
|
28
|
+
|
|
29
|
+
## Services
|
|
30
|
+
|
|
31
|
+
The API service defaults to loopback `127.0.0.1`. Omitting TLS uses plaintext TCP, and an omitted or empty `secret` allows unauthenticated connections. `dashboard` accepts a boolean, path string, or settings object. Set `enabled: true` to enable the dashboard in object form. The dashboard uses its own default settings when its HTTP client is omitted.
|
|
32
|
+
|
|
33
|
+
DERP accepts a Tailscale endpoint or an array of those endpoints in `verify_client_endpoint`.
|
|
34
|
+
|
|
35
|
+
The SSM API service accepts a non-empty `servers` map from HTTP paths starting with `/` to registered Shadowsocks inbounds. Use static multi-user Shadowsocks with a non-empty `users` list or managed Shadowsocks with `managed: true`. The `none` method is available for single-user Shadowsocks. Managed mode requires an omitted or empty static user list.
|
|
36
|
+
|
|
37
|
+
USB/IP Server accepts `devices` with the default provider, written as `provider: "default"`, `provider: ""`, or by omitting `provider`. Supply `provider: "dynamic"` to select the dynamic provider.
|
|
38
|
+
|
|
39
|
+
## HTTP clients
|
|
40
|
+
|
|
41
|
+
The API dashboard and remote rule-sets accept a tagged client registered in `http_clients`, an untagged `httpClient()` builder, or an inline HTTP settings object. The inline object supports the sing-box HTTP client fields other than `tag`, including SBKit references for `detour`, `domain_resolver`, and `netns`. Set `route.default_http_client` to a registered client or let sing-box use the first registered client as its default.
|
|
42
|
+
|
|
43
|
+
## Rule-sets
|
|
44
|
+
|
|
45
|
+
Inline rule-sets take a single tag and at least one `HeadlessRule`. Local and remote rule-sets infer `source` from a `.json` file and `binary` from a `.srs` file. For remote URLs the path determines the format. Supply `format` explicitly for other paths.
|
|
46
|
+
|
|
47
|
+
Local and remote rule-sets support multiple tags. Put `{tag}` in the local `path`, or in the remote `url` and any supplied `initial_path`. Use a single-tag rule-set when matching a rule-set in a route or DNS rule.
|
package/docs/rules.md
CHANGED
|
@@ -1,13 +1,47 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Routing rules and shared conditions
|
|
2
2
|
|
|
3
|
-
Use `Rule.match(fields)` to create a condition. Attach an action with `route.rule(condition, action)`
|
|
3
|
+
Use `Rule.match(fields)` to create a condition. Attach an action with `route.rule(condition, action)` and put the result in `route.rules`. The one-argument form, such as `route.rule({ action: "reject" })`, matches all traffic that reaches the rule.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { compile, outbound, route, Rule } from "sing-box-kit";
|
|
7
|
+
|
|
8
|
+
const direct = outbound.direct({ tag: "direct" });
|
|
9
|
+
compile({
|
|
10
|
+
outbounds: [direct],
|
|
11
|
+
route: {
|
|
12
|
+
rules: [
|
|
13
|
+
route.rule(Rule.match({ domain_suffix: "example.test" }), {
|
|
14
|
+
action: "route",
|
|
15
|
+
outbound: direct,
|
|
16
|
+
}),
|
|
17
|
+
route.rule({ action: "reject" }),
|
|
18
|
+
],
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
```
|
|
4
22
|
|
|
5
23
|
## Match conditions
|
|
6
24
|
|
|
7
|
-
|
|
25
|
+
Use the condition fields from the pinned schema. Route and DNS rules share fields such as `domain`, `domain_suffix`, `network`, `port`, `inbound`, `rule_set`, and `auth_user`. Routing rules also support `client`, `network: "icmp"`, and `ip_cidr` for the destination address.
|
|
26
|
+
|
|
27
|
+
The `inbound`, `rule_set`, and `preferred_by` fields accept one typed resource or an array of typed resources. Route `preferred_by` accepts Tailscale, WireGuard, OpenConnect, and OpenVPN client endpoints and Bridge outbounds. See [DNS match conditions](dns-rules.md#match-conditions) for DNS-specific fields and server types.
|
|
8
28
|
|
|
9
29
|
Use `.and()`, `.or()`, and `.not()` to build a condition tree. Each group retains its operand order, so `a.or(b).and(c)` means `(a OR b) AND c`. The action appears at the top level. Combining conditions requires at least one rule scope common to both operands.
|
|
10
30
|
|
|
31
|
+
## Route actions
|
|
32
|
+
|
|
33
|
+
| Action | Options |
|
|
34
|
+
| --------------- | -------------------------------------------------------------------------------------- |
|
|
35
|
+
| `route` | Requires an egress `outbound`. Accepts route options. |
|
|
36
|
+
| `bypass` | Optional egress `outbound`. Accepts route options. |
|
|
37
|
+
| `hijack-dns` | None |
|
|
38
|
+
| `route-options` | Route options such as `override_address` and `override_port` |
|
|
39
|
+
| `sniff` | Optional `sniffer` and `timeout` |
|
|
40
|
+
| `resolve` | Optional typed DNS `server`, strategy, timeout, cache settings, TTL, and client subnet |
|
|
41
|
+
| `reject` | Optional `method` of `default`, `drop`, or `reply` for ICMP echo, plus `no_drop` |
|
|
42
|
+
|
|
43
|
+
Route options include `override_address`, `override_port`, and the other fields defined by the pinned schema. Use these options with `route`, `bypass`, or `route-options`.
|
|
44
|
+
|
|
11
45
|
## Match authenticated users
|
|
12
46
|
|
|
13
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`.
|
|
@@ -15,7 +49,7 @@ A `User` represents a name shared across inbounds. Supply credentials on each in
|
|
|
15
49
|
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.
|
|
16
50
|
|
|
17
51
|
```ts
|
|
18
|
-
import { compile, inbound, outbound, route, Rule, user } from "
|
|
52
|
+
import { compile, inbound, outbound, route, Rule, user } from "sing-box-kit";
|
|
19
53
|
|
|
20
54
|
const alice = user({ name: "alice" });
|
|
21
55
|
const proxy = inbound
|
|
@@ -38,44 +72,3 @@ compile({
|
|
|
38
72
|
},
|
|
39
73
|
});
|
|
40
74
|
```
|
|
41
|
-
|
|
42
|
-
## Actions
|
|
43
|
-
|
|
44
|
-
| Rule scope | Action | Options |
|
|
45
|
-
| ---------- | --------------- | -------------------------------------------------------------------------------------- |
|
|
46
|
-
| Route | `route` | Requires an egress `outbound` |
|
|
47
|
-
| Route | `bypass` | Optional egress `outbound` |
|
|
48
|
-
| Route | `hijack-dns` | None |
|
|
49
|
-
| DNS | `route` | Requires a DNS `server`. Accepts shared DNS options, `race`, and `speculative` |
|
|
50
|
-
| DNS | `evaluate` | Requires a DNS `server`. Accepts a result `tag`, shared DNS options, and `speculative` |
|
|
51
|
-
| DNS | `respond` | Optional `race` |
|
|
52
|
-
| DNS | `route-options` | Requires at least one effective shared DNS option |
|
|
53
|
-
| DNS | `predefined` | Optional `rcode`, `answer`, `ns`, `extra`, and `race` |
|
|
54
|
-
| Both | `reject` | Optional `method` of `default` or `drop`, plus `no_drop`. DNS also accepts `race` |
|
|
55
|
-
|
|
56
|
-
Shared DNS options include `timeout`, `disable_cache`, `disable_optimistic_cache`, `rewrite_ttl`, `client_subnet`, and `remove_client_subnet`. For `route-options`, a positive timeout, a true flag, a valid subnet, or an explicit TTL counts as effective. A TTL of zero counts.
|
|
57
|
-
|
|
58
|
-
## DNS response evaluation
|
|
59
|
-
|
|
60
|
-
Place an `evaluate` rule before rules that depend on its response. Match a named response with `match_response: "tag"`, or an untagged response with `match_response: true`. With response matching active, a leaf can also test `response_rcode`, `response_answer`, `response_ns`, `response_extra`, `ip_cidr`, `ip_is_private`, or `ip_accept_any`.
|
|
61
|
-
|
|
62
|
-
A `respond` rule can return a named response when its own default condition matches that tag. For a logical `respond` rule, use an untagged evaluation. Enable `race` only on a rule with active response matching and omit `speculative` on that rule.
|
|
63
|
-
|
|
64
|
-
```ts
|
|
65
|
-
import { compile, dns, dnsServer, Rule } from "./index";
|
|
66
|
-
|
|
67
|
-
const resolver = dnsServer.udp({ tag: "resolver", server: "192.0.2.53" });
|
|
68
|
-
const evaluate = dns.rule(Rule.match({ domain_suffix: "example.test" }), {
|
|
69
|
-
action: "evaluate",
|
|
70
|
-
server: resolver,
|
|
71
|
-
tag: "example-answer",
|
|
72
|
-
});
|
|
73
|
-
const respond = dns.rule(
|
|
74
|
-
Rule.match({ match_response: "example-answer", response_rcode: "NOERROR" }),
|
|
75
|
-
{ action: "respond" },
|
|
76
|
-
);
|
|
77
|
-
|
|
78
|
-
compile({ dns: { servers: [resolver], rules: [evaluate, respond] } });
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
See the [configuration reference](configuration.md) for resource registration and TLS.
|
package/docs/settings.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Shared settings
|
|
2
|
+
|
|
3
|
+
Each builder exposes the shared methods and fields available for its kind in the pinned sing-box schema. See [Build and validate a configuration](configuration.md) for how to register and reference the finished values.
|
|
4
|
+
|
|
5
|
+
## Listen fields
|
|
6
|
+
|
|
7
|
+
`.listen(address, { port, ...options })` writes `listen` and `listen_port`. You can omit `port`, omit the address with `.listen({ port, ...options })`, or pass `undefined` for the address. A listen `detour` takes a registered inbound. TUN can use `.listen({ netns, udp_timeout })`.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { compile, inbound } from "sing-box-kit";
|
|
11
|
+
|
|
12
|
+
const mixed = inbound.mixed({ tag: "mixed" }).listen("127.0.0.1", { port: 1080, reuse_addr: true });
|
|
13
|
+
compile({ inbounds: [mixed] });
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Dial fields
|
|
17
|
+
|
|
18
|
+
`.dial(options)` accepts the supported Dial Fields. On dialers with `detour`, supply a registered outbound or endpoint. Put any non-zero connection timeout or namespace setting on the detour target. An otherwise empty direct outbound is invalid as an explicit dial detour. A WireGuard endpoint with a dial detour requires a zero or omitted `listen_port`.
|
|
19
|
+
|
|
20
|
+
In Listen and Dial Fields, a typed `netns` value resolves to a registered namespace tag. A string passes through as supplied. sing-box looks for a registered tag before treating the string as an OS name or path.
|
|
21
|
+
|
|
22
|
+
## DNS resolvers
|
|
23
|
+
|
|
24
|
+
Supply a registered DNS server to `domain_resolver` or `route.default_domain_resolver` directly or as `{ server: resolver, ...options }`. A TCP, UDP, TLS, HTTPS, HTTP/3, or QUIC DNS server configured with a hostname needs its own resolver or an explicit detour.
|
|
25
|
+
|
|
26
|
+
## TLS profiles
|
|
27
|
+
|
|
28
|
+
Use `.tls(options)` for the kind's TLS fields, such as `outbound.http({ tag: "proxy" }).tls({ server_name: "proxy.example", alpn: ["h2"] })`. For configurations with an `enabled` field the builder defaults it to `true` and preserves an explicit `false`. OpenConnect and OpenVPN take their own TLS options.
|
|
29
|
+
|
|
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
|
+
|
|
32
|
+
### VLESS with REALITY
|
|
33
|
+
|
|
34
|
+
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.
|
|
35
|
+
|
|
36
|
+
REALITY keys are unpadded Base64url strings for 32-byte keys. Short IDs are even-length hexadecimal strings of up to 16 characters, including the empty string. The inbound accepts a string or an array of strings. Keep the private key in the server configuration and share the public key and a selected short ID with the client.
|
package/package.json
CHANGED
package/schema/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Schema and type generation
|
|
2
2
|
|
|
3
|
-
The [pinned schema](sing-box.json) is the verbatim output of `sing-box schema`.
|
|
3
|
+
The [pinned schema](sing-box.json) is the verbatim output of `sing-box schema`. SBKit uses it for both Ajv validation and TypeScript generation.
|
|
4
4
|
|
|
5
5
|
[`version.json`](version.json) records the output of `sing-box version --name` and the `Revision` reported by `sing-box version` for the same binary.
|
|
6
6
|
|
|
@@ -11,9 +11,9 @@ The upstream sing-box project is Copyright (C) 2022 by nekohasekai and publishes
|
|
|
11
11
|
```sh
|
|
12
12
|
vp install --frozen-lockfile
|
|
13
13
|
bun run schema:generate
|
|
14
|
-
git diff --exit-code -- src/generated
|
|
14
|
+
git diff --exit-code -- src/generated
|
|
15
15
|
vp check
|
|
16
16
|
bun test
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
-
Type generation reads the local snapshot and works offline after dependency installation. CI checks
|
|
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.
|
|
@@ -1,7 +1,160 @@
|
|
|
1
1
|
import { compile } from "json-schema-to-typescript";
|
|
2
|
+
import type { JSONSchema } from "json-schema-to-typescript";
|
|
3
|
+
import {
|
|
4
|
+
factoryCatalog,
|
|
5
|
+
inputDefinition,
|
|
6
|
+
inputProperty,
|
|
7
|
+
rootSettings,
|
|
8
|
+
ruleActionSchemas,
|
|
9
|
+
ruleMatchSchema,
|
|
10
|
+
schemaShape,
|
|
11
|
+
sectionSettings,
|
|
12
|
+
tagReference,
|
|
13
|
+
targetSchema,
|
|
14
|
+
} from "../src/input-schema";
|
|
15
|
+
import type { Target } from "../src/resource";
|
|
16
|
+
import { definitionName } from "../src/schema";
|
|
17
|
+
import type { SchemaNode } from "../src/schema";
|
|
2
18
|
|
|
3
19
|
const schema = await Bun.file(new URL("../schema/sing-box.json", import.meta.url)).json();
|
|
4
20
|
const types = await compile({ ...schema, title: "SingBoxConfig" }, "SingBoxConfig", {
|
|
5
21
|
additionalProperties: false,
|
|
6
22
|
});
|
|
7
23
|
await Bun.write(new URL("../src/generated/sing-box.ts", import.meta.url), types);
|
|
24
|
+
|
|
25
|
+
const definitions: Record<string, unknown> = {};
|
|
26
|
+
const imports = new Set<string>();
|
|
27
|
+
const projections = new Map<string, string>();
|
|
28
|
+
|
|
29
|
+
function typedReference(reference: string): { tsType: string } {
|
|
30
|
+
const entry = tagReference(reference);
|
|
31
|
+
const type = entry.type;
|
|
32
|
+
imports.add(type);
|
|
33
|
+
return { tsType: "allowString" in entry ? `${type} | string` : type };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function transform(value: unknown): unknown {
|
|
37
|
+
if (Array.isArray(value)) return value.map(transform);
|
|
38
|
+
if (!value || typeof value !== "object") return value;
|
|
39
|
+
const node = value as SchemaNode;
|
|
40
|
+
const annotation = node["x-tag-reference"];
|
|
41
|
+
if (typeof annotation === "string") return typedReference(annotation);
|
|
42
|
+
if (node.propertyNames && typeof node.additionalProperties === "object") {
|
|
43
|
+
const keys = schemaShape(node.propertyNames).enum;
|
|
44
|
+
if (keys?.every((key) => typeof key === "string")) {
|
|
45
|
+
const field = transform(node.additionalProperties);
|
|
46
|
+
return {
|
|
47
|
+
type: "object",
|
|
48
|
+
properties: Object.fromEntries(keys.map((key) => [key, field])),
|
|
49
|
+
additionalProperties: false,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const name = definitionName(node);
|
|
54
|
+
if (name) {
|
|
55
|
+
if (!Object.hasOwn(definitions, name)) {
|
|
56
|
+
definitions[name] = {};
|
|
57
|
+
definitions[name] = transform(inputDefinition(name));
|
|
58
|
+
}
|
|
59
|
+
return node;
|
|
60
|
+
}
|
|
61
|
+
return Object.fromEntries(
|
|
62
|
+
Object.entries(value).map(([key, item]) => [
|
|
63
|
+
key,
|
|
64
|
+
key === "properties"
|
|
65
|
+
? Object.fromEntries(
|
|
66
|
+
Object.entries(node.properties!).map(([property, schema]) => [
|
|
67
|
+
property,
|
|
68
|
+
transform(inputProperty(property, schema)),
|
|
69
|
+
]),
|
|
70
|
+
)
|
|
71
|
+
: transform(item),
|
|
72
|
+
]),
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function object(properties: Record<string, unknown>) {
|
|
77
|
+
return {
|
|
78
|
+
type: "object",
|
|
79
|
+
properties,
|
|
80
|
+
required: Object.keys(properties),
|
|
81
|
+
additionalProperties: false,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function projection(name: string, schema: SchemaNode) {
|
|
86
|
+
const key = JSON.stringify(schema);
|
|
87
|
+
let definition = projections.get(key);
|
|
88
|
+
if (!definition) {
|
|
89
|
+
projections.set(key, name);
|
|
90
|
+
definitions[name] = transform(schema);
|
|
91
|
+
definition = name;
|
|
92
|
+
}
|
|
93
|
+
return { $ref: `#/$defs/${definition}` };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function factoryTypes(target: Target) {
|
|
97
|
+
return object(
|
|
98
|
+
Object.fromEntries(
|
|
99
|
+
Array.from(factoryCatalog(target), ([kind, branches]) => {
|
|
100
|
+
const name =
|
|
101
|
+
targetSchema[target] +
|
|
102
|
+
kind
|
|
103
|
+
.split("-")
|
|
104
|
+
.map((word) => word[0]!.toUpperCase() + word.slice(1))
|
|
105
|
+
.join("");
|
|
106
|
+
const first = branches[0]!;
|
|
107
|
+
const groups: Record<string, unknown> = {
|
|
108
|
+
options: projection(
|
|
109
|
+
`${name}Options`,
|
|
110
|
+
branches.length > 1
|
|
111
|
+
? { oneOf: branches.map((branch) => branch.options) }
|
|
112
|
+
: first.options,
|
|
113
|
+
),
|
|
114
|
+
};
|
|
115
|
+
for (const group of ["listen", "dial", "tls"] as const) {
|
|
116
|
+
const settings = first[group];
|
|
117
|
+
if (settings)
|
|
118
|
+
groups[group] = definitionName(settings)
|
|
119
|
+
? transform(settings)
|
|
120
|
+
: projection(`${name}${group[0]!.toUpperCase()}${group.slice(1)}`, settings);
|
|
121
|
+
}
|
|
122
|
+
return [kind, object(groups)];
|
|
123
|
+
}),
|
|
124
|
+
),
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const factories = Object.fromEntries(
|
|
129
|
+
(Object.keys(targetSchema) as Target[]).map((target) => [target, factoryTypes(target)]),
|
|
130
|
+
);
|
|
131
|
+
const sbkit = {
|
|
132
|
+
...object({
|
|
133
|
+
factories: object(factories),
|
|
134
|
+
root: object(
|
|
135
|
+
Object.fromEntries(
|
|
136
|
+
Object.entries(rootSettings).map(([key, value]) => [key, transform(value)]),
|
|
137
|
+
),
|
|
138
|
+
),
|
|
139
|
+
sections: object({
|
|
140
|
+
route: projection("RouteSettings", sectionSettings.route),
|
|
141
|
+
dns: projection("DnsSettings", sectionSettings.dns),
|
|
142
|
+
}),
|
|
143
|
+
matches: object({
|
|
144
|
+
route: projection("RouteMatchFields", ruleMatchSchema.route),
|
|
145
|
+
dns: projection("DnsMatchFields", ruleMatchSchema.dns),
|
|
146
|
+
}),
|
|
147
|
+
actions: object({
|
|
148
|
+
route: projection("RouteActionInput", { oneOf: [...ruleActionSchemas("route").values()] }),
|
|
149
|
+
dns: projection("DnsActionInput", { oneOf: [...ruleActionSchemas("dns").values()] }),
|
|
150
|
+
}),
|
|
151
|
+
}),
|
|
152
|
+
$defs: definitions,
|
|
153
|
+
} as JSONSchema;
|
|
154
|
+
|
|
155
|
+
const sbkitTypes = await compile(sbkit, "SBKitInputs", {
|
|
156
|
+
additionalProperties: false,
|
|
157
|
+
bannerComment: `/* Generated by scripts/generate-schema.ts. */
|
|
158
|
+
import type { ${[...imports].sort().join(", ")} } from "../resource";`,
|
|
159
|
+
});
|
|
160
|
+
await Bun.write(new URL("../src/generated/sbkit-inputs.ts", import.meta.url), sbkitTypes);
|