sing-box-kit 0.1.1 → 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/dist/index.mjs CHANGED
@@ -8769,26 +8769,23 @@ function checkSchema(validate, value, path) {
8769
8769
  function validateConfig(value) {
8770
8770
  return checkSchema(validateOfficial, value, "");
8771
8771
  }
8772
- const definitions = sing_box_default.$defs;
8772
+ const definitions$1 = sing_box_default.$defs;
8773
+ const rootProperties = sing_box_default.properties;
8773
8774
  function definition(name) {
8774
- return definitions[name] ?? fail(name, "unknown schema definition");
8775
+ return definitions$1[name] ?? fail(name, "unknown schema definition");
8775
8776
  }
8776
- function variant(name, type) {
8777
- const schema = definition(name);
8778
- return (schema.oneOf ?? schema.anyOf)?.find((option) => option.properties?.type?.const === type || option.properties?.type?.enum?.includes(type)) ?? fail(name, "unknown schema variant");
8777
+ function definitionName(schema) {
8778
+ return schema.$ref?.slice(8);
8779
+ }
8780
+ function schemaBranches(schema) {
8781
+ const name = definitionName(schema);
8782
+ if (name) return schemaBranches(definition(name));
8783
+ return (schema.oneOf ?? schema.anyOf)?.flatMap(schemaBranches) ?? [schema];
8779
8784
  }
8780
8785
  function compileSchema(schema) {
8781
8786
  const rewriteReferences = (key, value) => key === "$ref" && typeof value === "string" && value.startsWith("#/") ? sing_box_default.$id + value : value;
8782
8787
  return ajv.compile(JSON.parse(JSON.stringify(schema, rewriteReferences)));
8783
8788
  }
8784
- function objectValidator(properties, required = []) {
8785
- return compileSchema({
8786
- type: "object",
8787
- properties,
8788
- required,
8789
- additionalProperties: false
8790
- });
8791
- }
8792
8789
  function pickSchema(properties, keys) {
8793
8790
  return Object.fromEntries(keys.map((key) => [key, properties[key] ?? fail(key, "field missing from official schema")]));
8794
8791
  }
@@ -8866,14 +8863,7 @@ const tlsProfileValidators = {
8866
8863
  handshake: {
8867
8864
  type: "object",
8868
8865
  additionalProperties: false,
8869
- properties: pickSchema(definition("InboundRealityHandshakeOptions").properties, [
8870
- "server",
8871
- "server_port",
8872
- "connect_timeout",
8873
- "detour",
8874
- "domain_resolver",
8875
- "netns"
8876
- ]),
8866
+ properties: definition("InboundRealityHandshakeOptions").properties,
8877
8867
  required: ["server", "server_port"]
8878
8868
  }
8879
8869
  },
@@ -8925,7 +8915,317 @@ const tlsProfileValidators = {
8925
8915
  })
8926
8916
  }
8927
8917
  };
8918
+ // src/input-schema.ts
8919
+ const targetSchema = {
8920
+ inbounds: "Inbound",
8921
+ outbounds: "Outbound",
8922
+ endpoints: "Endpoint",
8923
+ services: "Service",
8924
+ http_clients: "HTTPClient",
8925
+ "dns.servers": "DNSServer",
8926
+ "route.rule_set": "RuleSet",
8927
+ certificate_providers: "CertificateProvider",
8928
+ network_namespaces: "NetworkNamespace"
8929
+ };
8930
+ const tagReferences = {
8931
+ inbound: {
8932
+ role: "inbound",
8933
+ type: "InboundRef"
8934
+ },
8935
+ listen_detour: {
8936
+ role: "listen-detour",
8937
+ type: "ListenDetour"
8938
+ },
8939
+ outbound: {
8940
+ role: "egress",
8941
+ type: "Egress"
8942
+ },
8943
+ dial_detour: {
8944
+ role: "dial-detour",
8945
+ type: "Egress"
8946
+ },
8947
+ network_namespace: {
8948
+ role: "netns",
8949
+ type: "Namespace",
8950
+ allowString: true
8951
+ },
8952
+ dns_server: {
8953
+ role: "dns-server",
8954
+ type: "DnsServer"
8955
+ },
8956
+ rule_set: {
8957
+ role: "rule-set",
8958
+ type: "RuleSetRef"
8959
+ },
8960
+ certificate_provider: {
8961
+ role: "certificate-provider",
8962
+ type: "CertificateProvider"
8963
+ },
8964
+ http_client: {
8965
+ role: "http-client",
8966
+ type: "HttpClientValue"
8967
+ },
8968
+ tagged_http_client: {
8969
+ role: "http-client",
8970
+ type: "TaggedHttpClient"
8971
+ },
8972
+ tailscale_endpoint: {
8973
+ role: "tailscale-endpoint",
8974
+ type: "TailscaleEndpoint"
8975
+ },
8976
+ openconnect_endpoint: {
8977
+ role: "openconnect-endpoint",
8978
+ type: "OpenConnectEndpoint"
8979
+ },
8980
+ openvpn_client_endpoint: {
8981
+ role: "openvpn-client-endpoint",
8982
+ type: "OpenVpnClientEndpoint"
8983
+ },
8984
+ resolved_service: {
8985
+ role: "resolved-service",
8986
+ type: "ResolvedService"
8987
+ },
8988
+ ssm: {
8989
+ role: "ssm",
8990
+ type: "SsmInbound"
8991
+ },
8992
+ preferred_routes: {
8993
+ role: "preferred-routes",
8994
+ type: "PreferredRoutes"
8995
+ },
8996
+ preferred_domain: {
8997
+ role: "preferred-domain",
8998
+ type: "PreferredDomain"
8999
+ }
9000
+ };
9001
+ function tagReference(name) {
9002
+ if (!Object.hasOwn(tagReferences, name)) fail(name, "unknown tag reference");
9003
+ return tagReferences[name];
9004
+ }
9005
+ function tagged(schema, reference) {
9006
+ return {
9007
+ ...schema,
9008
+ "x-tag-reference": reference
9009
+ };
9010
+ }
9011
+ function inputProperty(key, schema) {
9012
+ if (key !== "detour") return schema;
9013
+ const reference = schema["x-tag-reference"];
9014
+ if (reference === "outbound") return tagged(schema, "dial_detour");
9015
+ if (reference === "inbound") return tagged(schema, "listen_detour");
9016
+ return schema;
9017
+ }
9018
+ function oneOrManyReference(schema, reference) {
9019
+ return {
9020
+ ...schema,
9021
+ anyOf: schema.anyOf.map((option) => option.items ? {
9022
+ ...option,
9023
+ items: tagged(option.items, reference)
9024
+ } : tagged(option, reference))
9025
+ };
9026
+ }
9027
+ function projectObject(properties, required = []) {
9028
+ return {
9029
+ type: "object",
9030
+ properties,
9031
+ required,
9032
+ additionalProperties: false
9033
+ };
9034
+ }
9035
+ function supplementFactory(target, kind, properties) {
9036
+ if (target === "dns.servers" && properties.endpoint) {
9037
+ const references = {
9038
+ tailscale: "tailscale_endpoint",
9039
+ openconnect: "openconnect_endpoint",
9040
+ openvpn: "openvpn_client_endpoint"
9041
+ };
9042
+ if (Object.hasOwn(references, kind)) properties.endpoint = tagged(properties.endpoint, references[kind]);
9043
+ }
9044
+ if (target === "dns.servers" && kind === "resolved") properties.service = tagged(properties.service, "resolved_service");
9045
+ if (target === "certificate_providers" && kind === "tailscale") properties.endpoint = tagged(properties.endpoint, "tailscale_endpoint");
9046
+ if (target === "services" && kind === "derp") properties.verify_client_endpoint = oneOrManyReference(properties.verify_client_endpoint, "tailscale_endpoint");
9047
+ if (target === "services" && kind === "ssm-api") properties.servers = {
9048
+ ...properties.servers,
9049
+ additionalProperties: tagged({ type: "string" }, "ssm")
9050
+ };
9051
+ }
9052
+ const definitions = /* @__PURE__ */ new Map();
9053
+ function inputDefinition(name) {
9054
+ const cached = definitions.get(name);
9055
+ if (cached) return cached;
9056
+ let schema = definition(name);
9057
+ if (name === "RouteOptions") schema = {
9058
+ ...schema,
9059
+ properties: {
9060
+ ...schema.properties,
9061
+ default_http_client: tagged(schema.properties.default_http_client, "tagged_http_client")
9062
+ }
9063
+ };
9064
+ if (name === "CertificateProviderReference") {
9065
+ const [tag, inline] = schema.anyOf;
9066
+ schema = {
9067
+ ...schema,
9068
+ anyOf: [tag, {
9069
+ ...inline,
9070
+ oneOf: inline.oneOf.map((branch) => {
9071
+ if (branch.properties?.type?.const !== "tailscale") return branch;
9072
+ const properties = { ...branch.properties };
9073
+ supplementFactory("certificate_providers", "tailscale", properties);
9074
+ return {
9075
+ ...branch,
9076
+ properties
9077
+ };
9078
+ })
9079
+ }]
9080
+ };
9081
+ }
9082
+ definitions.set(name, schema);
9083
+ return schema;
9084
+ }
9085
+ const rootSettings = Object.fromEntries(Object.entries(rootProperties).filter(([key]) => !Object.hasOwn(targetSchema, key) && key !== "route" && key !== "dns"));
9086
+ const sectionSettings = {
9087
+ route: projectObject(Object.fromEntries(Object.entries(inputDefinition("RouteOptions").properties).filter(([key]) => key !== "rules" && key !== "rule_set"))),
9088
+ dns: projectObject(Object.fromEntries(Object.entries(definition("DNS").properties).filter(([key]) => key !== "rules" && key !== "servers")))
9089
+ };
9090
+ const dialKeys = new Set(Object.keys(definition("DialerOptions").properties));
9091
+ const listenKeys = /* @__PURE__ */ new Set([
9092
+ "listen",
9093
+ "listen_port",
9094
+ "udp_timeout",
9095
+ "domain_resolver",
9096
+ "bind_interface",
9097
+ "routing_mark",
9098
+ "reuse_addr",
9099
+ "netns",
9100
+ "disable_tcp_keep_alive",
9101
+ "tcp_keep_alive",
9102
+ "tcp_keep_alive_interval",
9103
+ "tcp_fast_open",
9104
+ "tcp_multi_path",
9105
+ "udp_fragment",
9106
+ "detour"
9107
+ ]);
9108
+ const requiredOptions = {
9109
+ inbounds: {
9110
+ shadowsocks: ["method"],
9111
+ vless: ["users"]
9112
+ },
9113
+ outbounds: {
9114
+ vless: [
9115
+ "server",
9116
+ "server_port",
9117
+ "uuid"
9118
+ ],
9119
+ selector: ["outbounds"],
9120
+ urltest: ["outbounds"]
9121
+ },
9122
+ endpoints: { wireguard: ["address", "private_key"] },
9123
+ services: { "ssm-api": ["servers"] },
9124
+ "dns.servers": {
9125
+ tcp: ["server"],
9126
+ udp: ["server"],
9127
+ tls: ["server"],
9128
+ https: ["server"],
9129
+ tailscale: ["endpoint"],
9130
+ openconnect: ["endpoint"],
9131
+ openvpn: ["endpoint"],
9132
+ resolved: ["service"]
9133
+ },
9134
+ "route.rule_set": {
9135
+ inline: ["rules"],
9136
+ local: ["path"],
9137
+ remote: ["url"]
9138
+ },
9139
+ certificate_providers: { tailscale: ["endpoint"] },
9140
+ network_namespaces: { default: ["path"] }
9141
+ };
9142
+ function factoryCatalog(target) {
9143
+ const kinds = /* @__PURE__ */ new Map();
9144
+ for (const schema of schemaBranches(definition(targetSchema[target]))) {
9145
+ const type = schema.properties?.type;
9146
+ const kind = type?.const ?? type?.enum?.[0] ?? "http-client";
9147
+ if (typeof kind !== "string") fail(target, "expected a resource kind in the schema");
9148
+ const properties = Object.fromEntries(Object.entries(schema.properties ?? {}).map(([key, value]) => [key, inputProperty(key, value)]));
9149
+ supplementFactory(target, kind, properties);
9150
+ const listens = properties.listen !== void 0 || target === "inbounds" && kind === "tun";
9151
+ const options = {};
9152
+ const listen = {};
9153
+ const dial = {};
9154
+ for (const [key, value] of Object.entries(properties)) {
9155
+ if (key === "type" || key === "tls") continue;
9156
+ if (listens && listenKeys.has(key)) {
9157
+ if (key === "listen") continue;
9158
+ listen[key === "listen_port" ? "port" : key] = value;
9159
+ } else if (!listens && dialKeys.has(key)) {
9160
+ if (key === "detour" && target === "outbounds" && kind === "direct") continue;
9161
+ dial[key] = value;
9162
+ } else options[key] = value;
9163
+ }
9164
+ const required = [...schema.required ?? [], ...requiredOptions[target]?.[kind] ?? []];
9165
+ if (target !== "services" && target !== "http_clients") required.push("tag");
9166
+ const branch = {
9167
+ output: {
9168
+ ...schema,
9169
+ properties
9170
+ },
9171
+ options: projectObject(options, [...new Set(required)].filter((key) => Object.hasOwn(options, key))),
9172
+ listen: listens ? projectObject(listen) : void 0,
9173
+ dial: Object.keys(dial).length ? projectObject(dial) : void 0,
9174
+ tls: properties.tls
9175
+ };
9176
+ const entries = kinds.get(kind) ?? [];
9177
+ entries.push(branch);
9178
+ kinds.set(kind, entries);
9179
+ }
9180
+ return kinds;
9181
+ }
9182
+ function factoryName(kind) {
9183
+ return kind.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
9184
+ }
9185
+ function schemaShape(schema) {
9186
+ const name = definitionName(schema);
9187
+ return name ? inputDefinition(name) : schema;
9188
+ }
9189
+ const ruleMatchSchema = {
9190
+ route: matchSchema("NestedRule", "preferred_routes"),
9191
+ dns: matchSchema("NestedDNSRule", "preferred_domain")
9192
+ };
9193
+ function matchSchema(name, preferred) {
9194
+ const { type: _type, ...properties } = definition(name).oneOf[0].properties;
9195
+ properties.preferred_by = oneOrManyReference(properties.preferred_by, preferred);
9196
+ return projectObject(properties);
9197
+ }
9198
+ function ruleActionSchemas(scope) {
9199
+ const actions = schemaBranches(definition(scope === "route" ? "RuleAction" : "DNSRuleAction"));
9200
+ return new Map(actions.map((branch) => {
9201
+ const properties = { ...branch.properties };
9202
+ const action = properties.action.const;
9203
+ const required = /* @__PURE__ */ new Set(["action", ...branch.required ?? []]);
9204
+ if (action === "route" && scope === "route") required.add("outbound");
9205
+ if (scope === "dns" && (action === "route" || action === "evaluate")) required.add("server");
9206
+ if (action === "reject" && scope === "dns") properties.method = {
9207
+ type: "string",
9208
+ enum: ["default", "drop"]
9209
+ };
9210
+ return [action, projectObject(properties, [...required])];
9211
+ }));
9212
+ }
8928
9213
  // src/resource.ts
9214
+ const preferredRouteEndpoints = [
9215
+ "tailscale",
9216
+ "wireguard",
9217
+ "openconnect",
9218
+ "openvpn-client"
9219
+ ];
9220
+ const preferredDnsKinds = [
9221
+ "hosts",
9222
+ "local",
9223
+ "mdns",
9224
+ "tailscale",
9225
+ "openconnect",
9226
+ "openvpn",
9227
+ "resolved"
9228
+ ];
8929
9229
  const resources = /* @__PURE__ */ new WeakMap();
8930
9230
  const identities = /* @__PURE__ */ new WeakSet();
8931
9231
  /** Internal constructor. Factory methods supply immutable data. */
@@ -8958,7 +9258,7 @@ function copy(value, path, immutable, ancestors) {
8958
9258
  if (value === null || typeof value !== "object") return value;
8959
9259
  if (identities.has(value)) {
8960
9260
  if (immutable) return value;
8961
- fail(path, "unexpected Kit value in JSON fields");
9261
+ fail(path, "unexpected SBKit value in JSON fields");
8962
9262
  }
8963
9263
  if (ancestors.has(value)) fail(path, "cyclic configuration object");
8964
9264
  ancestors.add(value);
@@ -8972,82 +9272,102 @@ function snapshot(value, path) {
8972
9272
  function copyJson(value, path) {
8973
9273
  return copy(value, path, false, /* @__PURE__ */ new Set());
8974
9274
  }
8975
- const ref = (role) => (value, path, resolve) => resolve(value, role, path);
8976
- const arrayOrOne = (expand) => (value, path, resolve) => Array.isArray(value) ? Array.from(value, (item, index) => expand(item, `${path}[${index}]`, resolve)) : expand(value, path, resolve);
8977
- function expandFields(fields, expansions, path, resolve) {
8978
- return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0).map(([key, value]) => {
8979
- const fieldPath = keyPath(path, key);
8980
- const expand = Object.hasOwn(expansions, key) ? expansions[key] : void 0;
8981
- return [key, expand ? expand(value, fieldPath, resolve) : copyJson(value, fieldPath)];
8982
- }));
8983
- }
8984
9275
  // src/settings.ts
8985
9276
  const previewReference = (value, role, path) => {
8986
9277
  if (!resourceData(value)) fail(path, `expected a typed ${role} reference`);
8987
9278
  return "reference";
8988
9279
  };
8989
- const expandResolver = (value, path, resolve) => {
8990
- if (resourceData(value) || typeof value !== "object" || value === null) return resolve(value, "dns-server", path);
8991
- const options = record(value, path);
8992
- if (options.server === void 0) fail(`${path}.server`, "required field");
8993
- return expandFields(options, { server: ref("dns-server") }, path, resolve);
8994
- };
8995
- const expandNamespace = (value, path, resolve) => typeof value === "string" ? value : resolve(value, "netns", path);
8996
- const listenReferences = {
8997
- netns: expandNamespace,
8998
- detour: ref("listen-detour")
8999
- };
9000
- const dialReferences = {
9001
- netns: expandNamespace,
9002
- detour: ref("dial-detour"),
9003
- domain_resolver: expandResolver
9004
- };
9005
9280
  function checkDial(fields, path) {
9006
9281
  const timeout = durationNanoseconds(fields.connect_timeout, `${path}.connect_timeout`);
9007
9282
  if (fields.detour === void 0) return;
9008
9283
  if (timeout !== 0) fail(`${path}.connect_timeout`, "non-zero timeout with detour");
9009
9284
  if (fields.netns !== void 0 && fields.netns !== "") fail(`${path}.netns`, "namespace with detour");
9010
9285
  }
9011
- const commonDialKeys = [
9012
- "connect_timeout",
9013
- "domain_resolver",
9014
- "netns"
9286
+ const discriminators = [
9287
+ "type",
9288
+ "version",
9289
+ "provider"
9015
9290
  ];
9016
- function dialFields(input, path, detour) {
9017
- const fields = fieldsFrom(input, path, detour ? [...commonDialKeys, "detour"] : commonDialKeys);
9018
- checkDial(fields, path);
9019
- return fields;
9291
+ function matchesDiscriminators(schema, fields) {
9292
+ return discriminators.every((key) => {
9293
+ const property = schema.properties?.[key];
9294
+ if (property?.const === void 0 && !property?.enum) return true;
9295
+ const value = fields[key];
9296
+ if (value === void 0) return !schema.required?.includes(key);
9297
+ return property.const === value || property.enum?.includes(value) === true;
9298
+ });
9020
9299
  }
9021
- function listenFields(address, input, path, detour) {
9022
- const { port, ...options } = fieldsFrom(input, path, detour ? [
9023
- "port",
9024
- "netns",
9025
- "detour"
9026
- ] : ["port", "netns"], ["port"]);
9027
- if (typeof address !== "string") fail(`${path}.listen`, "expected a string");
9028
- return {
9029
- listen: address,
9030
- listen_port: port,
9031
- ...options
9032
- };
9300
+ function matchesShape(input, value) {
9301
+ const schema = schemaShape(input);
9302
+ const alternatives = schema.oneOf ?? schema.anyOf;
9303
+ if (alternatives) return alternatives.some((option) => matchesShape(option, value));
9304
+ if (schema.const !== void 0) return value === schema.const;
9305
+ if (schema.enum) return schema.enum.includes(value);
9306
+ if (resourceData(value)) return schema["x-tag-reference"] !== void 0;
9307
+ if (schema.type === "array") return Array.isArray(value);
9308
+ if (schema.type === "object") return value !== null && typeof value === "object" && !Array.isArray(value) && matchesDiscriminators(schema, value);
9309
+ if (schema.type === "integer") return typeof value === "number";
9310
+ return schema.type === void 0 || typeof value === schema.type;
9033
9311
  }
9034
- const expandReality = (value, path, resolve) => expandFields(record(value, path), { handshake: (handshake, path, resolve) => expandFields(record(handshake, path), dialReferences, path, resolve) }, path, resolve);
9035
- const expandTls = (value, path, resolve) => expandFields(record(value, path), {
9036
- certificate_provider: ref("certificate-provider"),
9037
- reality: expandReality
9038
- }, path, resolve);
9039
- function tlsFields(input, path, mode) {
9312
+ /** Expand annotated tags anywhere in a schema-shaped input. Ajv checks the resulting JSON. */
9313
+ function expandInput(input, value, path, resolve) {
9314
+ if (definitionName(input) === "HTTPClientReference") {
9315
+ const client = resourceData(value);
9316
+ if (client?.target === "http_clients" && client.fields.tag === void 0) return expandInput(definition("HTTPClient"), client.fields, path, resolve);
9317
+ }
9318
+ const schema = schemaShape(input);
9319
+ const annotation = schema["x-tag-reference"];
9320
+ if (annotation !== void 0) {
9321
+ const reference = tagReference(annotation);
9322
+ if ("allowString" in reference && typeof value === "string") return value;
9323
+ return resolve(value, reference.role, path);
9324
+ }
9325
+ const alternatives = schema.oneOf ?? schema.anyOf;
9326
+ if (alternatives) {
9327
+ const option = alternatives.find((branch) => matchesShape(branch, value));
9328
+ return option ? expandInput(option, value, path, resolve) : copyJson(value, path);
9329
+ }
9330
+ if (schema.items && Array.isArray(value)) {
9331
+ const items = schema.items;
9332
+ return Array.from(value, (item, index) => expandInput(items, item, `${path}[${index}]`, resolve));
9333
+ }
9334
+ if (schema.type === "object" && value !== null && typeof value === "object" && !Array.isArray(value)) {
9335
+ const fields = record(value, path);
9336
+ const detour = schema.properties?.detour?.["x-tag-reference"];
9337
+ if (detour === "dial_detour" || detour === "outbound") checkDial(fields, path);
9338
+ const additional = typeof schema.additionalProperties === "object" ? schema.additionalProperties : {};
9339
+ return Object.fromEntries(Object.entries(fields).filter(([, item]) => item !== void 0).map(([key, item]) => {
9340
+ return [key, expandInput(inputProperty(key, schema.properties && Object.hasOwn(schema.properties, key) ? schema.properties[key] : additional), item, keyPath(path, key), resolve)];
9341
+ }));
9342
+ }
9343
+ return copyJson(value, path);
9344
+ }
9345
+ function listenFields(address, input, path, schema) {
9346
+ const { port, ...options } = fieldsFrom(input, path, Object.keys(schema.properties));
9347
+ if (address !== void 0) {
9348
+ if (!Object.hasOwn(schema.properties, "port")) fail(`${path}.listen`, "unexpected field");
9349
+ if (typeof address !== "string") fail(`${path}.listen`, "expected a string");
9350
+ options.listen = address;
9351
+ }
9352
+ if (port !== void 0) options.listen_port = port;
9353
+ return options;
9354
+ }
9355
+ function tlsFields(input, path, schema, mode) {
9040
9356
  const profile = record(input, path);
9357
+ const enabled = Object.hasOwn(schemaShape(schema).properties ?? {}, "enabled");
9358
+ if (!Object.hasOwn(profile, "side")) return { tls: enabled && profile.enabled === void 0 ? {
9359
+ ...profile,
9360
+ enabled: true
9361
+ } : profile };
9362
+ if (!mode) fail(`${path}.side`, "unsupported TLS profile");
9041
9363
  const server = mode === "server" || mode === "server-reality";
9042
9364
  const isReality = profile.reality !== void 0;
9043
9365
  if (isReality && !mode.endsWith("-reality")) fail(`${path}.reality`, "unsupported TLS profile");
9044
- checkSchema(server ? isReality ? tlsProfileValidators.server.reality : profile.certificate_provider === void 0 ? tlsProfileValidators.server.files : tlsProfileValidators.server.provider : isReality ? tlsProfileValidators.client.reality : tlsProfileValidators.client.regular, expandTls(profile, path, previewReference), path);
9366
+ checkSchema(server ? isReality ? tlsProfileValidators.server.reality : profile.certificate_provider === void 0 ? tlsProfileValidators.server.files : tlsProfileValidators.server.provider : isReality ? tlsProfileValidators.client.reality : tlsProfileValidators.client.regular, expandInput(schema, profile, path, previewReference), path);
9045
9367
  const { side: _side, ...fields } = profile;
9046
9368
  if (isReality) {
9047
- const reality = record(profile.reality, `${path}.reality`);
9048
- if (server) checkDial(record(reality.handshake, `${path}.reality.handshake`), `${path}.reality.handshake`);
9049
9369
  fields.reality = {
9050
- ...reality,
9370
+ ...record(profile.reality, `${path}.reality`),
9051
9371
  enabled: true
9052
9372
  };
9053
9373
  if (!server) fields.utls = { enabled: true };
@@ -9057,40 +9377,22 @@ function tlsFields(input, path, mode) {
9057
9377
  enabled: true
9058
9378
  } };
9059
9379
  }
9060
- const httpClientObject = compileSchema(definition("HTTPClientReference").anyOf[1]);
9061
- const expandHttpClient = (value, path, resolve) => {
9062
- const data = resourceData(value);
9063
- if (data) {
9064
- if (data.target === "http_clients" && data.fields.tag === void 0) return expandFields(data.fields, data.references ?? {}, path, resolve);
9065
- return resolve(value, "http-client", path);
9066
- }
9067
- const fields = record(value, path);
9068
- if (Object.hasOwn(fields, "tag")) fail(`${path}.tag`, "unexpected field");
9069
- checkDial(fields, path);
9070
- const output = expandFields(fields, dialReferences, path, resolve);
9071
- return checkSchema(httpClientObject, output, path);
9072
- };
9073
- const expandDashboard = (value, path, resolve) => typeof value === "string" || typeof value === "boolean" ? value : expandFields(record(value, path), { http_client: expandHttpClient }, path, resolve);
9074
- const expandSsmServers = (value, path, resolve) => {
9075
- const servers = Object.entries(record(value, path));
9380
+ function checkSsmServers(value, path) {
9381
+ const servers = Object.keys(record(value, path));
9076
9382
  if (servers.length === 0) fail(path, "expected at least one SSM server");
9077
- return Object.fromEntries(servers.map(([pattern, inbound]) => {
9078
- const fieldPath = `${path}[${JSON.stringify(pattern)}]`;
9079
- if (!pattern.startsWith("/")) fail(fieldPath, "expected a route pattern starting with /");
9080
- return [pattern, resolve(inbound, "ssm", fieldPath)];
9081
- }));
9082
- };
9383
+ for (const pattern of servers) if (!pattern.startsWith("/")) fail(`${path}[${JSON.stringify(pattern)}]`, "expected a route pattern starting with /");
9384
+ }
9385
+ const directDialProperties = definition("DialerOptions").properties;
9083
9386
  function isEmptyDirect(fields) {
9084
- return durationNanoseconds(fields.connect_timeout, "connect_timeout") === 0 && (fields.netns === void 0 || fields.netns === "") && fields.domain_resolver === void 0;
9387
+ return Object.entries(fields).every(([key, value]) => {
9388
+ if (value === void 0 || !Object.hasOwn(directDialProperties, key)) return true;
9389
+ if (definitionName(directDialProperties[key]) === "Duration") return durationNanoseconds(value, key) === 0;
9390
+ if (key === "udp_fragment") return false;
9391
+ if (key === "routing_mark") return Number(value) === 0;
9392
+ return value === "" || value === 0 || value === false;
9393
+ });
9085
9394
  }
9086
9395
  // src/rules.ts
9087
- const commonMatches = [
9088
- "domain",
9089
- "domain_suffix",
9090
- "port",
9091
- "auth_user"
9092
- ];
9093
- const routeMatches = ["client"];
9094
9396
  const responseMatches = [
9095
9397
  "response_rcode",
9096
9398
  "response_answer",
@@ -9100,16 +9402,6 @@ const responseMatches = [
9100
9402
  "ip_is_private",
9101
9403
  "ip_accept_any"
9102
9404
  ];
9103
- const dnsMatches = [
9104
- "query_type",
9105
- "match_response",
9106
- ...responseMatches
9107
- ];
9108
- const referenceMatches = [
9109
- "inbound",
9110
- "rule_set",
9111
- "preferred_by"
9112
- ];
9113
9405
  const conditions = /* @__PURE__ */ new WeakMap();
9114
9406
  const allScopes = ["route", "dns"];
9115
9407
  function conditionData(value, path) {
@@ -9140,51 +9432,23 @@ function makeCondition(data) {
9140
9432
  conditions.set(value, data);
9141
9433
  return value;
9142
9434
  }
9143
- const scopeMatches = {
9144
- route: routeMatches,
9145
- dns: dnsMatches
9146
- };
9147
- const allMatches = [
9148
- ...commonMatches,
9149
- ...referenceMatches,
9150
- ...routeMatches,
9151
- ...dnsMatches
9152
- ];
9435
+ const routeKeys$1 = new Set(Object.keys(ruleMatchSchema.route.properties));
9436
+ const dnsKeys$1 = new Set(Object.keys(ruleMatchSchema.dns.properties));
9437
+ const allMatches = [.../* @__PURE__ */ new Set([...routeKeys$1, ...dnsKeys$1])];
9153
9438
  const leafValidators = {
9154
- route: objectValidator(pickSchema(definition("NestedRule").oneOf[0].properties, [
9155
- ...commonMatches,
9156
- ...referenceMatches,
9157
- ...routeMatches
9158
- ])),
9159
- dns: objectValidator(pickSchema(definition("NestedDNSRule").oneOf[0].properties, [
9160
- ...commonMatches,
9161
- ...referenceMatches,
9162
- ...dnsMatches
9163
- ]))
9164
- };
9165
- const leafReferences = {
9166
- route: {
9167
- inbound: arrayOrOne(ref("inbound")),
9168
- rule_set: arrayOrOne(ref("rule-set")),
9169
- preferred_by: arrayOrOne(ref("preferred-routes"))
9170
- },
9171
- dns: {
9172
- inbound: arrayOrOne(ref("inbound")),
9173
- rule_set: arrayOrOne(ref("rule-set")),
9174
- preferred_by: arrayOrOne(ref("preferred-domain"))
9175
- }
9439
+ route: compileSchema(ruleMatchSchema.route),
9440
+ dns: compileSchema(ruleMatchSchema.dns)
9176
9441
  };
9177
9442
  function active(value) {
9178
9443
  return value !== void 0 && value !== false && (!Array.isArray(value) || value.length !== 0);
9179
9444
  }
9180
- function checkLeaf(fields, path) {
9445
+ function checkLeaf(fields, path, scope) {
9181
9446
  if (fields.match_response === "") fail(`${path}.match_response`, "empty response tag");
9182
- if (responseMatches.some((key) => active(fields[key])) && !active(fields.match_response)) fail(`${path}.match_response`, "response fields require active response matching");
9183
- if (!Object.values(fields).some(active)) fail(path, "condition has no active fields");
9447
+ if (scope === "dns" && responseMatches.some((key) => active(fields[key])) && !active(fields.match_response)) fail(`${path}.match_response`, "response fields require active response matching");
9448
+ if (!Object.entries(fields).some(([key, value]) => key !== "invert" && active(value))) fail(path, "condition has no active fields");
9184
9449
  }
9185
9450
  function match(input) {
9186
9451
  const fields = fieldsFrom(input, "match", allMatches);
9187
- checkLeaf(fields, "match");
9188
9452
  const preferred = Array.isArray(fields.preferred_by) ? fields.preferred_by : [fields.preferred_by];
9189
9453
  const hasDnsTransport = preferred.some((value) => resourceData(value)?.target === "dns.servers");
9190
9454
  const hasOtherResource = preferred.some((value) => {
@@ -9192,11 +9456,17 @@ function match(input) {
9192
9456
  return data && data.target !== "dns.servers";
9193
9457
  });
9194
9458
  if (hasDnsTransport && hasOtherResource) fail("match.preferred_by", "mixed route and DNS targets");
9195
- const scopes = allScopes.filter((scope) => {
9196
- return !scopeMatches[scope === "route" ? "dns" : "route"].some((key) => fields[key] !== void 0) && !(scope === "route" ? hasDnsTransport : hasOtherResource);
9197
- });
9459
+ const keys = Object.keys(fields);
9460
+ const dnsOnly = hasDnsTransport || keys.some((key) => !routeKeys$1.has(key));
9461
+ const icmp = fields.network === "icmp" || Array.isArray(fields.network) && fields.network.includes("icmp");
9462
+ const addressMatch = fields.ip_cidr !== void 0 || fields.ip_is_private === true;
9463
+ const routeOnly = hasOtherResource || icmp || keys.some((key) => !dnsKeys$1.has(key)) || addressMatch && !dnsOnly;
9464
+ const scopes = allScopes.filter((scope) => scope === "route" ? !dnsOnly : !routeOnly);
9198
9465
  if (!scopes.length) fail("match", "fields have no common scope");
9199
- for (const scope of scopes) checkSchema(leafValidators[scope], expandFields(fields, leafReferences[scope], "match", previewReference), "match");
9466
+ for (const scope of scopes) {
9467
+ checkLeaf(fields, "match", scope);
9468
+ checkSchema(leafValidators[scope], expandInput(ruleMatchSchema[scope], fields, "match", previewReference), "match");
9469
+ }
9200
9470
  return makeCondition({
9201
9471
  scopes,
9202
9472
  invert: false,
@@ -9204,98 +9474,47 @@ function match(input) {
9204
9474
  });
9205
9475
  }
9206
9476
  const Rule = Object.freeze({ match });
9207
- function actionVariant(scope, action, keys, required = []) {
9208
- const raw = definition(scope === "route" ? "RuleAction" : "DNSRuleAction").oneOf.find((item) => item.properties?.action?.const === action).properties;
9209
- const properties = pickSchema(raw, ["action", ...keys]);
9210
- if (action === "reject") properties.method = {
9211
- type: "string",
9212
- enum: ["default", "drop"]
9213
- };
9214
- return {
9215
- keys: ["action", ...keys],
9216
- required: ["action", ...required],
9217
- validate: objectValidator(properties, ["action", ...required])
9218
- };
9477
+ function actionsFor(scope) {
9478
+ return new Map(Array.from(ruleActionSchemas(scope), ([action, schema]) => [action, {
9479
+ schema,
9480
+ validate: compileSchema(schema)
9481
+ }]));
9219
9482
  }
9220
- const sharedDnsOptions = [
9221
- "timeout",
9222
- "disable_cache",
9223
- "disable_optimistic_cache",
9224
- "rewrite_ttl",
9225
- "client_subnet",
9226
- "remove_client_subnet"
9227
- ];
9228
9483
  const actions = {
9229
- route: {
9230
- route: actionVariant("route", "route", ["outbound"], ["outbound"]),
9231
- bypass: actionVariant("route", "bypass", ["outbound"]),
9232
- reject: actionVariant("route", "reject", ["method", "no_drop"]),
9233
- "hijack-dns": actionVariant("route", "hijack-dns", [])
9234
- },
9235
- dns: {
9236
- route: actionVariant("dns", "route", [
9237
- "server",
9238
- "speculative",
9239
- "race",
9240
- ...sharedDnsOptions
9241
- ], ["server"]),
9242
- evaluate: actionVariant("dns", "evaluate", [
9243
- "server",
9244
- "tag",
9245
- "speculative",
9246
- ...sharedDnsOptions
9247
- ], ["server"]),
9248
- respond: actionVariant("dns", "respond", ["race"]),
9249
- "route-options": actionVariant("dns", "route-options", sharedDnsOptions),
9250
- reject: actionVariant("dns", "reject", [
9251
- "method",
9252
- "no_drop",
9253
- "race"
9254
- ]),
9255
- predefined: actionVariant("dns", "predefined", [
9256
- "rcode",
9257
- "answer",
9258
- "ns",
9259
- "extra",
9260
- "race"
9261
- ])
9262
- }
9484
+ route: actionsFor("route"),
9485
+ dns: actionsFor("dns")
9263
9486
  };
9264
9487
  function validSubnet(input) {
9265
9488
  const [address = "", prefix, ...extra] = input.split("/");
9266
9489
  const version = isIP(address);
9267
9490
  return version !== 0 && !address.includes("%") && extra.length === 0 && (prefix === void 0 || /^\d+$/.test(prefix) && Number(prefix) <= (version === 4 ? 32 : 128));
9268
9491
  }
9269
- function checkAction(fields, path) {
9492
+ function checkAction(fields, path, scope) {
9270
9493
  if (fields.method === "drop" && fields.no_drop === true) fail(`${path}.no_drop`, "no_drop with drop");
9271
9494
  if (fields.client_subnet !== void 0) {
9272
9495
  if (fields.remove_client_subnet === true) fail(`${path}.client_subnet`, "client_subnet with remove_client_subnet");
9273
9496
  if (!validSubnet(fields.client_subnet)) fail(`${path}.client_subnet`, "invalid subnet");
9274
9497
  }
9275
- if (fields.action === "route-options" && fields.rewrite_ttl === void 0 && fields.client_subnet === void 0 && fields.disable_cache !== true && fields.disable_optimistic_cache !== true && fields.remove_client_subnet !== true && durationNanoseconds(fields.timeout, `${path}.timeout`) <= 0) fail(path, "route-options requires an effective DNS option");
9498
+ if (scope === "dns" && fields.action === "route-options" && fields.rewrite_ttl === void 0 && fields.client_subnet === void 0 && fields.disable_cache !== true && fields.disable_optimistic_cache !== true && fields.remove_client_subnet !== true && durationNanoseconds(fields.timeout, `${path}.timeout`) <= 0) fail(path, "route-options requires an effective DNS option");
9276
9499
  if (fields.race === true && fields.speculative === true) fail(`${path}.race`, "race with speculative");
9277
9500
  }
9278
- const actionReferences = {
9279
- route: { outbound: ref("egress") },
9280
- dns: { server: ref("dns-server") }
9281
- };
9282
9501
  const rules = /* @__PURE__ */ new WeakMap();
9283
9502
  function makeRule(scope, condition, actionInput) {
9284
9503
  const path = `${scope}.rule`;
9285
- const variants = actions[scope];
9286
9504
  const name = record(actionInput, path).action;
9287
- if (typeof name !== "string" || !Object.hasOwn(variants, name)) fail(`${path}.action`, "unsupported action");
9288
- const variant = variants[name];
9289
- const action = fieldsFrom(actionInput, path, variant.keys, variant.required);
9290
- checkSchema(variant.validate, expandFields(action, actionReferences[scope], path, previewReference), path);
9291
- checkAction(action, path);
9505
+ const variant = typeof name === "string" ? actions[scope].get(name) : void 0;
9506
+ if (!variant) fail(`${path}.action`, "unsupported action");
9507
+ const action = fieldsFrom(actionInput, path, Object.keys(variant.schema.properties), variant.schema.required);
9508
+ checkSchema(variant.validate, expandInput(variant.schema, action, path, previewReference), path);
9509
+ checkAction(action, path, scope);
9292
9510
  if (condition !== void 0 && !conditionData(condition, path).scopes.includes(scope)) fail(path, "condition is incompatible with rule scope");
9293
9511
  if (action.race === true && !hasResponseCondition(condition)) fail(`${path}.race`, "race requires active response matching");
9294
9512
  const value = preserveIdentity({});
9295
9513
  rules.set(value, {
9296
9514
  scope,
9297
9515
  condition,
9298
- action: snapshot(action, path)
9516
+ action: snapshot(action, path),
9517
+ schema: variant.schema
9299
9518
  });
9300
9519
  return value;
9301
9520
  }
@@ -9315,11 +9534,10 @@ function expandCondition(value, scope, path, resolve) {
9315
9534
  const { node, invert } = conditionData(value, path);
9316
9535
  const inversion = invert ? { invert: true } : {};
9317
9536
  if ("fields" in node) {
9318
- checkLeaf(node.fields, path);
9319
- return {
9320
- ...expandFields(node.fields, leafReferences[scope], path, resolve),
9321
- ...inversion
9322
- };
9537
+ checkLeaf(node.fields, path, scope);
9538
+ const fields = expandInput(ruleMatchSchema[scope], node.fields, path, resolve);
9539
+ if (invert) fields.invert = node.fields.invert !== true;
9540
+ return fields;
9323
9541
  }
9324
9542
  if (!node.rules.length) fail(`${path}.rules`, "empty logical group");
9325
9543
  return {
@@ -9338,7 +9556,7 @@ function expandRule(value, scope, path, resolve) {
9338
9556
  }
9339
9557
  return {
9340
9558
  ...data.condition ? expandCondition(data.condition, scope, path, resolve) : {},
9341
- ...expandFields(data.action, actionReferences[scope], path, resolve)
9559
+ ...expandInput(data.schema, data.action, path, resolve)
9342
9560
  };
9343
9561
  }
9344
9562
  function checkDnsRules(rules, path) {
@@ -9381,14 +9599,12 @@ const topLevelLists = [
9381
9599
  const routeKeys = [
9382
9600
  "rules",
9383
9601
  "rule_set",
9384
- "final",
9385
- "default_domain_resolver",
9386
- "default_http_client"
9602
+ ...Object.keys(sectionSettings.route.properties)
9387
9603
  ];
9388
9604
  const dnsKeys = [
9389
9605
  "rules",
9390
9606
  "servers",
9391
- "final"
9607
+ ...Object.keys(sectionSettings.dns.properties)
9392
9608
  ];
9393
9609
  function array(value, path) {
9394
9610
  if (!Array.isArray(value)) fail(path, "expected an array");
@@ -9419,8 +9635,7 @@ function checkCycles(resources) {
9419
9635
  */
9420
9636
  function compile(input) {
9421
9637
  const fields = fieldsFrom(input, "config", [
9422
- "log",
9423
- "experimental",
9638
+ ...Object.keys(rootSettings),
9424
9639
  ...topLevelLists,
9425
9640
  "route",
9426
9641
  "dns"
@@ -9508,32 +9723,34 @@ function compile(input) {
9508
9723
  const { data, path } = entry;
9509
9724
  const { server, detour, domain_resolver } = data.fields;
9510
9725
  if (data.remoteDns && typeof server === "string" && !isIP(server) && detour === void 0 && domain_resolver === void 0) fail(`${path}.domain_resolver`, "hostname requires a per-server resolver or detour");
9511
- return expandFields(data.fields, data.references ?? {}, path, resolveFrom(entry));
9726
+ return (data.expand ?? copyJson)(data.fields, path, resolveFrom(entry));
9512
9727
  });
9513
9728
  }
9514
9729
  const resolve = resolveFrom();
9515
9730
  const output = {};
9516
- for (const key of ["log", "experimental"]) if (fields[key] !== void 0) output[key] = copyJson(fields[key], key);
9731
+ for (const [key, schema] of Object.entries(rootSettings)) if (fields[key] !== void 0) output[key] = expandInput(schema, fields[key], key, resolve);
9517
9732
  for (const target of topLevelLists) {
9518
9733
  const values = emitList(target);
9519
9734
  if (values !== void 0) output[target] = values;
9520
9735
  }
9521
- if (route) output.route = expandFields(route, {
9522
- rule_set: () => emitList("route.rule_set"),
9523
- final: ref("egress"),
9524
- default_domain_resolver: expandResolver,
9525
- default_http_client: ref("http-client"),
9526
- rules: (values, path) => array(values, path).map((value, index) => expandRule(value, "route", `${path}[${index}]`, resolve))
9527
- }, "route", resolve);
9528
- if (dns) output.dns = expandFields(dns, {
9529
- servers: () => emitList("dns.servers"),
9530
- final: ref("dns-server"),
9531
- rules: (values, path) => {
9532
- const rules = array(values, path).map((value, index) => expandRule(value, "dns", `${path}[${index}]`, resolve));
9533
- checkDnsRules(rules, path);
9534
- return rules;
9736
+ if (route) {
9737
+ const { rules, rule_set, ...settings } = route;
9738
+ const result = expandInput(sectionSettings.route, settings, "route", resolve);
9739
+ if (rule_set !== void 0) result.rule_set = emitList("route.rule_set");
9740
+ if (rules !== void 0) result.rules = array(rules, "route.rules").map((value, index) => expandRule(value, "route", `route.rules[${index}]`, resolve));
9741
+ output.route = result;
9742
+ }
9743
+ if (dns) {
9744
+ const { rules, servers, ...settings } = dns;
9745
+ const result = expandInput(sectionSettings.dns, settings, "dns", resolve);
9746
+ if (servers !== void 0) result.servers = emitList("dns.servers");
9747
+ if (rules !== void 0) {
9748
+ const compiled = array(rules, "dns.rules").map((value, index) => expandRule(value, "dns", `dns.rules[${index}]`, resolve));
9749
+ checkDnsRules(compiled, "dns.rules");
9750
+ result.rules = compiled;
9535
9751
  }
9536
- }, "dns", resolve);
9752
+ output.dns = result;
9753
+ }
9537
9754
  checkCycles(registrations.values());
9538
9755
  return validateConfig(output);
9539
9756
  }
@@ -9550,17 +9767,6 @@ function isUser(value) {
9550
9767
  return value !== null && typeof value === "object" && users.has(value);
9551
9768
  }
9552
9769
  // src/factories.ts
9553
- const targetSchema = {
9554
- inbounds: "Inbound",
9555
- outbounds: "Outbound",
9556
- endpoints: "Endpoint",
9557
- services: "Service",
9558
- http_clients: "HTTPClient",
9559
- "dns.servers": "DNSServer",
9560
- "route.rule_set": "RuleSet",
9561
- certificate_providers: "CertificateProvider",
9562
- network_namespaces: "NetworkNamespace"
9563
- };
9564
9770
  const targetRoles = {
9565
9771
  inbounds: ["inbound", "listen-detour"],
9566
9772
  outbounds: ["egress"],
@@ -9572,21 +9778,33 @@ const targetRoles = {
9572
9778
  certificate_providers: ["certificate-provider"],
9573
9779
  network_namespaces: ["netns"]
9574
9780
  };
9575
- const settingsGroups = [
9576
- "listen",
9577
- "dial",
9578
- "tls"
9579
- ];
9580
- const validators = /* @__PURE__ */ new WeakMap();
9581
- function validateFactoryOutput(def, fields, path) {
9582
- let validate = validators.get(def);
9583
- if (!validate) {
9584
- const name = targetSchema[def.target];
9585
- validate = compileSchema(def.target === "http_clients" ? definition(name) : variant(name, def.kind));
9586
- validators.set(def, validate);
9781
+ const endpointRoles = {
9782
+ tailscale: "tailscale-endpoint",
9783
+ openconnect: "openconnect-endpoint",
9784
+ "openvpn-client": "openvpn-client-endpoint"
9785
+ };
9786
+ const passwordAuth = {
9787
+ name: "username",
9788
+ credentials: ["password"],
9789
+ required: ["password"]
9790
+ };
9791
+ const authOptions = {
9792
+ mixed: {
9793
+ ...passwordAuth,
9794
+ allowRaw: true
9795
+ },
9796
+ socks: passwordAuth,
9797
+ shadowsocks: {
9798
+ ...passwordAuth,
9799
+ name: "name",
9800
+ allowRaw: true
9801
+ },
9802
+ vless: {
9803
+ name: "name",
9804
+ credentials: ["uuid", "flow"],
9805
+ required: ["uuid"]
9587
9806
  }
9588
- checkSchema(validate, fields, path);
9589
- }
9807
+ };
9590
9808
  function prepareUsers(fields, auth, path) {
9591
9809
  if (fields.users === void 0) return [];
9592
9810
  const users = fields.users;
@@ -9627,192 +9845,6 @@ function validateTag(tag, path) {
9627
9845
  });
9628
9846
  } else if (typeof tag !== "string" || tag === "") fail(path, "expected a non-empty tag");
9629
9847
  }
9630
- function build(def, input) {
9631
- const path = `${def.target}.${def.kind}`;
9632
- const options = fieldsFrom(input, path, [...def.required, ...def.optional ?? []], def.required);
9633
- validateTag(options.tag, `${path}.tag`);
9634
- const members = def.auth ? prepareUsers(options, def.auth, path) : [];
9635
- const extraRoles = def.prepare?.(options, path) ?? [];
9636
- const roles = Object.freeze([
9637
- ...targetRoles[def.target],
9638
- ...def.roles ?? [],
9639
- ...extraRoles
9640
- ]);
9641
- const base = snapshot(def.target === "http_clients" ? options : {
9642
- type: def.kind,
9643
- ...options
9644
- }, path);
9645
- const references = Object.freeze({
9646
- ...def.references,
9647
- ...def.listen ? listenReferences : {},
9648
- ...def.dial ? dialReferences : {},
9649
- ...def.tls ? { tls: expandTls } : {}
9650
- });
9651
- function create(groups) {
9652
- const fields = { ...base };
9653
- for (const group of settingsGroups) for (const [key, value] of Object.entries(groups[group] ?? {})) {
9654
- if (Object.hasOwn(fields, key)) fail(keyPath(path, key), "conflicting output field");
9655
- fields[key] = value;
9656
- }
9657
- validateFactoryOutput(def, expandFields(fields, references, path, previewReference), path);
9658
- const apply = (group, getFields) => {
9659
- if (groups[group]) fail(keyPath(path, group), "settings group already applied");
9660
- return create({
9661
- ...groups,
9662
- [group]: snapshot(getFields(), path)
9663
- });
9664
- };
9665
- const methods = {};
9666
- if (def.listen) methods.listen = (address, input) => apply("listen", () => listenFields(address, input, path, def.listen === "forwarding"));
9667
- if (def.dial) methods.dial = (input) => apply("dial", () => {
9668
- const dial = dialFields(input, path, def.dial === "detour");
9669
- def.checkDial?.(fields, dial, path);
9670
- return dial;
9671
- });
9672
- const tlsMode = def.tls;
9673
- if (tlsMode) methods.tls = (input) => apply("tls", () => tlsFields(input, `${path}.tls`, tlsMode));
9674
- if (def.auth) methods.authUser = (user) => {
9675
- const matching = members.filter((entry) => entry.user === user);
9676
- if (!isUser(user) || matching.length !== 1 || !user.name || members.filter((entry) => entry.name === user.name).length !== 1) fail(`${path}.authUser`, "expected one User entry with a unique non-empty name");
9677
- return Rule.match({
9678
- inbound: resource,
9679
- auth_user: user.name
9680
- });
9681
- };
9682
- const resource = createResource(Object.freeze({
9683
- target: def.target,
9684
- kind: def.kind,
9685
- fields: Object.freeze(fields),
9686
- references,
9687
- roles,
9688
- remoteDns: def.remoteDns,
9689
- startupDetour: def.startupDetour
9690
- }), methods);
9691
- return resource;
9692
- }
9693
- return create({});
9694
- }
9695
- function factory(def) {
9696
- return (options) => build(def, options);
9697
- }
9698
- const passwordAuth = {
9699
- name: "username",
9700
- credentials: ["password"],
9701
- required: ["password"]
9702
- };
9703
- const mixed = {
9704
- target: "inbounds",
9705
- kind: "mixed",
9706
- required: ["tag"],
9707
- optional: ["users", "set_system_proxy"],
9708
- listen: "forwarding",
9709
- tls: "server",
9710
- auth: {
9711
- ...passwordAuth,
9712
- allowRaw: true
9713
- }
9714
- };
9715
- const socks = {
9716
- target: "inbounds",
9717
- kind: "socks",
9718
- required: ["tag"],
9719
- optional: ["users"],
9720
- listen: "forwarding",
9721
- auth: passwordAuth
9722
- };
9723
- const inboundVless = {
9724
- target: "inbounds",
9725
- kind: "vless",
9726
- required: ["tag", "users"],
9727
- listen: "forwarding",
9728
- tls: "server-reality",
9729
- auth: {
9730
- name: "name",
9731
- credentials: ["uuid", "flow"],
9732
- required: ["uuid"]
9733
- }
9734
- };
9735
- const shadowsocks = {
9736
- target: "inbounds",
9737
- kind: "shadowsocks",
9738
- required: ["tag", "method"],
9739
- optional: [
9740
- "network",
9741
- "password",
9742
- "users",
9743
- "managed"
9744
- ],
9745
- listen: "forwarding",
9746
- auth: {
9747
- ...passwordAuth,
9748
- name: "name",
9749
- allowRaw: true
9750
- },
9751
- prepare(fields, path) {
9752
- const hasUsers = Array.isArray(fields.users) && fields.users.length > 0;
9753
- if (hasUsers && fields.managed === true) fail(`${path}.users`, "managed mode cannot have static users");
9754
- if (hasUsers || fields.managed === true) {
9755
- if (fields.method === "none") fail(`${path}.method`, "method none is unavailable in multi-user modes");
9756
- return ["ssm"];
9757
- }
9758
- }
9759
- };
9760
- function makeShadowsocks(options) {
9761
- return build(shadowsocks, options);
9762
- }
9763
- const inbound = Object.freeze({
9764
- mixed: (options) => build(mixed, options),
9765
- socks: (options) => build(socks, options),
9766
- vless: (options) => build(inboundVless, options),
9767
- shadowsocks: makeShadowsocks
9768
- });
9769
- const api = {
9770
- target: "services",
9771
- kind: "api",
9772
- required: [],
9773
- optional: [
9774
- "tag",
9775
- "secret",
9776
- "dashboard",
9777
- "access_control_allow_origin",
9778
- "access_control_allow_private_network"
9779
- ],
9780
- listen: "listener",
9781
- tls: "server",
9782
- references: { dashboard: expandDashboard }
9783
- };
9784
- const ssmApi = {
9785
- target: "services",
9786
- kind: "ssm-api",
9787
- required: ["servers"],
9788
- optional: ["tag", "cache_path"],
9789
- listen: "listener",
9790
- tls: "server",
9791
- references: { servers: expandSsmServers }
9792
- };
9793
- const service = Object.freeze({
9794
- /**
9795
- * sing-box defaults to loopback (127.0.0.1). An omitted or empty secret allows
9796
- * unauthenticated connections. Omitting server TLS uses plaintext TCP.
9797
- */
9798
- api: (options = {}) => build(api, options),
9799
- ssmApi: (options) => build(ssmApi, options)
9800
- });
9801
- const http = {
9802
- target: "http_clients",
9803
- kind: "http-client",
9804
- required: [],
9805
- optional: [
9806
- "version",
9807
- "headers",
9808
- "tag"
9809
- ],
9810
- dial: "detour",
9811
- tls: "client"
9812
- };
9813
- function httpClient(options = {}) {
9814
- return build(http, options);
9815
- }
9816
9848
  function checkGroup(fields, path) {
9817
9849
  const candidates = fields.outbounds;
9818
9850
  if (!Array.isArray(candidates) || candidates.length === 0) fail(`${path}.outbounds`, "expected at least one candidate");
@@ -9827,153 +9859,6 @@ function checkGroup(fields, path) {
9827
9859
  });
9828
9860
  if (fields.default !== void 0 && !candidates.includes(fields.default)) fail(`${path}.default`, "default must be a candidate");
9829
9861
  }
9830
- const selector = {
9831
- target: "outbounds",
9832
- kind: "selector",
9833
- required: ["tag", "outbounds"],
9834
- optional: ["default", "interrupt_exist_connections"],
9835
- prepare: checkGroup,
9836
- references: {
9837
- outbounds: arrayOrOne(ref("egress")),
9838
- default: ref("egress")
9839
- }
9840
- };
9841
- const urltest = {
9842
- target: "outbounds",
9843
- kind: "urltest",
9844
- required: ["tag", "outbounds"],
9845
- optional: [
9846
- "url",
9847
- "interval",
9848
- "tolerance",
9849
- "idle_timeout",
9850
- "interrupt_exist_connections"
9851
- ],
9852
- prepare: checkGroup,
9853
- references: { outbounds: arrayOrOne(ref("egress")) }
9854
- };
9855
- const outbound = Object.freeze({
9856
- direct: factory({
9857
- target: "outbounds",
9858
- kind: "direct",
9859
- required: ["tag"],
9860
- dial: "direct"
9861
- }),
9862
- vless: factory({
9863
- target: "outbounds",
9864
- kind: "vless",
9865
- required: [
9866
- "tag",
9867
- "server",
9868
- "server_port",
9869
- "uuid"
9870
- ],
9871
- optional: ["flow"],
9872
- dial: "detour",
9873
- tls: "client-reality",
9874
- startupDetour: true
9875
- }),
9876
- selector: (options) => build(selector, options),
9877
- urltest: (options) => build(urltest, options)
9878
- });
9879
- const endpoint = Object.freeze({
9880
- tailscale: factory({
9881
- target: "endpoints",
9882
- kind: "tailscale",
9883
- required: ["tag"],
9884
- optional: [
9885
- "state_directory",
9886
- "auth_key",
9887
- "hostname",
9888
- "accept_routes",
9889
- "exit_node",
9890
- "listen_port"
9891
- ],
9892
- dial: "detour",
9893
- roles: ["preferred-routes", "tailscale-endpoint"]
9894
- }),
9895
- wireguard: factory({
9896
- target: "endpoints",
9897
- kind: "wireguard",
9898
- required: [
9899
- "tag",
9900
- "address",
9901
- "private_key"
9902
- ],
9903
- optional: [
9904
- "peers",
9905
- "listen_port",
9906
- "system"
9907
- ],
9908
- dial: "detour",
9909
- startupDetour: true,
9910
- roles: ["preferred-routes"],
9911
- checkDial(fields, dial, path) {
9912
- if (dial.detour !== void 0 && fields.listen_port !== void 0 && fields.listen_port !== 0) fail(`${path}.listen_port`, "non-zero WireGuard listen port with detour");
9913
- }
9914
- })
9915
- });
9916
- const remoteDns = {
9917
- target: "dns.servers",
9918
- required: ["tag", "server"],
9919
- optional: ["server_port"],
9920
- dial: "detour",
9921
- remoteDns: true
9922
- };
9923
- const tailscaleDns = {
9924
- target: "dns.servers",
9925
- kind: "tailscale",
9926
- required: ["tag", "endpoint"],
9927
- optional: ["accept_default_resolvers", "accept_search_domain"],
9928
- roles: ["preferred-domain"],
9929
- references: { endpoint: ref("tailscale-endpoint") }
9930
- };
9931
- const dnsServer = Object.freeze({
9932
- tcp: factory({
9933
- ...remoteDns,
9934
- kind: "tcp"
9935
- }),
9936
- udp: factory({
9937
- ...remoteDns,
9938
- kind: "udp"
9939
- }),
9940
- tls: factory({
9941
- ...remoteDns,
9942
- kind: "tls",
9943
- tls: "client"
9944
- }),
9945
- https: factory({
9946
- ...remoteDns,
9947
- kind: "https",
9948
- tls: "client",
9949
- optional: [
9950
- "server_port",
9951
- "path",
9952
- "headers"
9953
- ]
9954
- }),
9955
- tailscale: (options) => build(tailscaleDns, options)
9956
- });
9957
- const tailscaleProvider = {
9958
- target: "certificate_providers",
9959
- kind: "tailscale",
9960
- required: ["tag", "endpoint"],
9961
- references: { endpoint: ref("tailscale-endpoint") }
9962
- };
9963
- const certificateProvider = Object.freeze({ tailscale: (options) => build(tailscaleProvider, options) });
9964
- const networkNamespace = Object.freeze({
9965
- default: factory({
9966
- target: "network_namespaces",
9967
- kind: "default",
9968
- required: ["tag", "path"]
9969
- }),
9970
- unshare: factory({
9971
- target: "network_namespaces",
9972
- kind: "unshare",
9973
- required: ["tag"],
9974
- optional: ["pid_file"]
9975
- })
9976
- });
9977
9862
  function ruleSetFormat(fields, path, location) {
9978
9863
  const input = fields[location];
9979
9864
  if (typeof input !== "string") fail(keyPath(path, location), "expected a string");
@@ -9990,47 +9875,123 @@ function ruleSetFormat(fields, path, location) {
9990
9875
  else if (extension?.endsWith(".srs")) fields.format = "binary";
9991
9876
  else fail(`${path}.format`, "cannot infer rule-set format");
9992
9877
  }
9993
- const inlineRuleSet = {
9994
- target: "route.rule_set",
9995
- kind: "inline",
9996
- required: ["tag", "rules"],
9997
- prepare(fields, path) {
9998
- if (!Array.isArray(fields.rules) || !fields.rules.length) fail(`${path}.rules`, "expected at least one rule");
9878
+ const settingsGroups = [
9879
+ "listen",
9880
+ "dial",
9881
+ "tls"
9882
+ ];
9883
+ function prepareOptions(target, kind, options, path, roles) {
9884
+ if (target === "inbounds" && kind === "shadowsocks") {
9885
+ const hasUsers = Array.isArray(options.users) && options.users.length > 0;
9886
+ if (hasUsers && options.managed === true) fail(`${path}.users`, "managed mode cannot have static users");
9887
+ if (hasUsers || options.managed === true) {
9888
+ if (options.method === "none") fail(`${path}.method`, "method none is unavailable in multi-user modes");
9889
+ roles.push("ssm");
9890
+ }
9891
+ }
9892
+ if (target === "outbounds" && (kind === "selector" || kind === "urltest")) checkGroup(options, path);
9893
+ if (target === "services" && kind === "ssm-api") checkSsmServers(options.servers, `${path}.servers`);
9894
+ if (target === "route.rule_set") {
9895
+ if (kind === "inline") {
9896
+ if (typeof options.tag !== "string") fail(`${path}.tag`, "expected a single tag");
9897
+ if (!Array.isArray(options.rules) || !options.rules.length) fail(`${path}.rules`, "expected at least one rule");
9898
+ } else ruleSetFormat(options, path, kind === "local" ? "path" : "url");
9999
9899
  }
10000
- };
10001
- const localRuleSet = {
10002
- target: "route.rule_set",
10003
- kind: "local",
10004
- required: ["tag", "path"],
10005
- optional: ["format"],
10006
- prepare: (fields, path) => ruleSetFormat(fields, path, "path")
10007
- };
10008
- const remoteRuleSet = {
10009
- target: "route.rule_set",
10010
- kind: "remote",
10011
- required: ["tag", "url"],
10012
- optional: [
10013
- "format",
10014
- "initial_path",
10015
- "update_interval",
10016
- "http_client"
10017
- ],
10018
- references: { http_client: expandHttpClient },
10019
- prepare: (fields, path) => ruleSetFormat(fields, path, "url")
10020
- };
10021
- function requireSingleTag(fields, path) {
10022
- if (typeof fields.tag !== "string") fail(`${path}.tag`, "expected a single tag");
10023
9900
  }
10024
- const ruleSet = Object.freeze({
10025
- inline(options) {
10026
- requireSingleTag(record(options, "ruleSet.inline"), "ruleSet.inline");
10027
- return build(inlineRuleSet, options);
10028
- },
10029
- local(options) {
10030
- return build(localRuleSet, options);
10031
- },
10032
- remote(options) {
10033
- return build(remoteRuleSet, options);
9901
+ function getRoles(target, kind) {
9902
+ const roles = [...targetRoles[target]];
9903
+ if (target === "endpoints") {
9904
+ if (Object.hasOwn(endpointRoles, kind)) roles.push(endpointRoles[kind]);
9905
+ if (preferredRouteEndpoints.some((preferred) => preferred === kind)) roles.push("preferred-routes");
10034
9906
  }
10035
- });
9907
+ if (target === "outbounds" && kind === "bridge") roles.push("preferred-routes");
9908
+ if (target === "dns.servers" && preferredDnsKinds.some((preferred) => preferred === kind)) roles.push("preferred-domain");
9909
+ if (target === "services" && kind === "resolved") roles.push("resolved-service");
9910
+ return roles;
9911
+ }
9912
+ function makeFactory(target, kind, branches) {
9913
+ const path = `${target}.${kind}`;
9914
+ const validators = /* @__PURE__ */ new Map();
9915
+ const auth = target === "inbounds" && Object.hasOwn(authOptions, kind) ? authOptions[kind] : void 0;
9916
+ return (input = {}) => {
9917
+ const raw = record(input, path);
9918
+ const branch = branches.length === 1 ? branches[0] : branches.find((item) => matchesDiscriminators(item.options, raw));
9919
+ if (!branch) {
9920
+ const discriminator = branches[0]?.options.properties?.version ? "version" : "provider";
9921
+ fail(keyPath(path, discriminator), "invalid or missing branch discriminator");
9922
+ }
9923
+ const options = fieldsFrom(raw, path, Object.keys(branch.options.properties), branch.options.required);
9924
+ validateTag(options.tag, `${path}.tag`);
9925
+ const members = auth ? prepareUsers(options, auth, path) : [];
9926
+ const roles = getRoles(target, kind);
9927
+ prepareOptions(target, kind, options, path, roles);
9928
+ const base = snapshot(target === "http_clients" ? options : {
9929
+ type: kind,
9930
+ ...options
9931
+ }, path);
9932
+ const expand = (value, path, resolve) => expandInput(branch.output, value, path, resolve);
9933
+ const validate = validators.get(branch) ?? compileSchema(branch.output);
9934
+ validators.set(branch, validate);
9935
+ const { listen, dial, tls } = branch;
9936
+ function create(groups) {
9937
+ const fields = { ...base };
9938
+ for (const group of settingsGroups) for (const [key, value] of Object.entries(groups[group] ?? {})) {
9939
+ if (Object.hasOwn(fields, key)) fail(keyPath(path, key), "conflicting output field");
9940
+ fields[key] = value;
9941
+ }
9942
+ checkSchema(validate, expand(fields, path, previewReference), path);
9943
+ const apply = (group, getFields) => {
9944
+ if (groups[group]) fail(keyPath(path, group), "settings group already applied");
9945
+ return create({
9946
+ ...groups,
9947
+ [group]: snapshot(getFields(), path)
9948
+ });
9949
+ };
9950
+ const methods = {};
9951
+ if (listen) methods.listen = (address, input = {}) => apply("listen", () => address !== null && typeof address === "object" ? listenFields(void 0, address, path, listen) : listenFields(address, input, path, listen));
9952
+ if (dial) methods.dial = (input) => apply("dial", () => {
9953
+ const settings = fieldsFrom(input, path, Object.keys(dial.properties));
9954
+ if (kind === "wireguard" && settings.detour !== void 0 && fields.listen_port !== void 0 && fields.listen_port !== 0) fail(`${path}.listen_port`, "non-zero WireGuard listen port with detour");
9955
+ return settings;
9956
+ });
9957
+ if (tls) {
9958
+ const name = definitionName(tls);
9959
+ let mode;
9960
+ if (name === "InboundTLSOptions") mode = kind === "vless" ? "server-reality" : "server";
9961
+ if (name === "OutboundTLSOptions") mode = kind === "vless" ? "client-reality" : "client";
9962
+ methods.tls = (input) => apply("tls", () => tlsFields(input, `${path}.tls`, tls, mode));
9963
+ }
9964
+ if (auth) methods.authUser = (user) => {
9965
+ if (!isUser(user) || members.filter((entry) => entry.user === user).length !== 1 || !user.name || members.filter((entry) => entry.name === user.name).length !== 1) fail(`${path}.authUser`, "expected one User entry with a unique non-empty name");
9966
+ return Rule.match({
9967
+ inbound: resource,
9968
+ auth_user: user.name
9969
+ });
9970
+ };
9971
+ const resource = createResource(Object.freeze({
9972
+ target,
9973
+ kind,
9974
+ fields: Object.freeze(fields),
9975
+ expand,
9976
+ roles: Object.freeze(roles),
9977
+ remoteDns: target === "dns.servers" && Object.hasOwn(base, "server"),
9978
+ startupDetour: target === "outbounds" && kind === "vless" || target === "endpoints" && kind === "wireguard"
9979
+ }), methods);
9980
+ return resource;
9981
+ }
9982
+ return create({});
9983
+ };
9984
+ }
9985
+ function factoriesFor(target) {
9986
+ return Object.fromEntries(Array.from(factoryCatalog(target), ([kind, branches]) => [factoryName(kind), makeFactory(target, kind, branches)]));
9987
+ }
9988
+ const inbound = Object.freeze(factoriesFor("inbounds"));
9989
+ const outbound = Object.freeze(factoriesFor("outbounds"));
9990
+ const endpoint = Object.freeze(factoriesFor("endpoints"));
9991
+ const service = Object.freeze(factoriesFor("services"));
9992
+ const dnsServer = Object.freeze(factoriesFor("dns.servers"));
9993
+ const certificateProvider = Object.freeze(factoriesFor("certificate_providers"));
9994
+ const networkNamespace = Object.freeze(factoriesFor("network_namespaces"));
9995
+ const httpClient = factoriesFor("http_clients").httpClient;
9996
+ const ruleSet = Object.freeze(factoriesFor("route.rule_set"));
10036
9997
  export { Rule, certificateProvider, compile, dns, dnsServer, endpoint, httpClient, inbound, networkNamespace, outbound, route, ruleSet, service, user, validateConfig };