sing-box-kit 0.1.3 → 0.1.4
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 +2 -1
- package/dist/index.d.mts +70 -4
- package/dist/index.mjs +260 -24
- package/docs/generators.md +31 -0
- package/docs/internal/README.md +2 -2
- package/docs/proxy-profiles.md +1 -1
- package/index.ts +1 -0
- package/package.json +7 -3
- package/schema/README.md +1 -1
- package/src/compile.ts +2 -2
- package/src/generate.ts +116 -0
- package/src/internal/certificate.ts +72 -0
- package/src/internal/crypto.ts +34 -0
- package/src/internal/ech.ts +32 -0
- package/src/internal/reality.ts +21 -0
- package/src/ip.ts +63 -0
- package/src/proxy-profile.ts +50 -28
- package/src/rules.ts +6 -14
package/README.md
CHANGED
|
@@ -26,7 +26,7 @@ bun config.ts > config.json
|
|
|
26
26
|
sing-box check -c config.json
|
|
27
27
|
```
|
|
28
28
|
|
|
29
|
-
On Node.js 22.
|
|
29
|
+
On Node.js 22.13 or later, install with `npm install sing-box-kit`, save the same example as `config.mjs`, and generate JSON with `node config.mjs > config.json`.
|
|
30
30
|
|
|
31
31
|
To run the example from a source checkout, run `vp install --frozen-lockfile` and use `./index` as the import path.
|
|
32
32
|
|
|
@@ -36,6 +36,7 @@ To run the example from a source checkout, run `vp install --frozen-lockfile` an
|
|
|
36
36
|
- [Resource factories and registration](docs/resources.md)
|
|
37
37
|
- [Generate server and client proxy configurations](docs/proxy-profiles.md)
|
|
38
38
|
- [Listen, dial, resolver, and TLS settings](docs/settings.md)
|
|
39
|
+
- [Generate credentials and key pairs](docs/generators.md)
|
|
39
40
|
- [Routing rules and shared conditions](docs/rules.md)
|
|
40
41
|
- [DNS rules and response evaluation](docs/dns-rules.md)
|
|
41
42
|
|
package/dist/index.d.mts
CHANGED
|
@@ -6125,6 +6125,9 @@ interface Profile<K extends Protocol, Authenticated extends boolean, ExtraInboun
|
|
|
6125
6125
|
type TransportInput<K extends TransportProtocol> = Direct & {
|
|
6126
6126
|
readonly users: Users;
|
|
6127
6127
|
} & TransportTls<K>;
|
|
6128
|
+
type VlessInput = TransportInput<"vless">;
|
|
6129
|
+
type VlessProfile<Input = unknown> = Profile<"vless", true, unknown, Input>;
|
|
6130
|
+
type VlessProfileResult<Input = unknown> = VlessProfile<Input> | Promise<VlessProfile<Input>>;
|
|
6128
6131
|
type PlainInput = Direct & {
|
|
6129
6132
|
readonly tls?: NormalTls | NoTls;
|
|
6130
6133
|
};
|
|
@@ -6252,6 +6255,20 @@ declare function shadowsocks(input: ShadowsocksInput & SharedPassword & {
|
|
|
6252
6255
|
readonly users?: never;
|
|
6253
6256
|
readonly serverKey?: never;
|
|
6254
6257
|
}): Profile<"shadowsocks", false>;
|
|
6258
|
+
declare function vless<const Transport extends TransportKind>(input: VlessInput & TransportSelection<Transport> & {
|
|
6259
|
+
readonly tls: RealityTls;
|
|
6260
|
+
}): Promise<VlessProfile<TransportSelection<Transport>>>;
|
|
6261
|
+
declare function vless<const Transport extends TransportKind>(input: VlessInput & TransportSelection<Transport> & {
|
|
6262
|
+
readonly tls?: NormalTls | NoTls;
|
|
6263
|
+
}): VlessProfile<TransportSelection<Transport>>;
|
|
6264
|
+
declare function vless<const Transport extends TransportKind>(input: VlessInput & TransportSelection<Transport>): VlessProfileResult<TransportSelection<Transport>>;
|
|
6265
|
+
declare function vless(input: VlessInput & {
|
|
6266
|
+
readonly tls: RealityTls;
|
|
6267
|
+
}): Promise<VlessProfile>;
|
|
6268
|
+
declare function vless(input: VlessInput & {
|
|
6269
|
+
readonly tls?: NormalTls | NoTls;
|
|
6270
|
+
}): VlessProfile;
|
|
6271
|
+
declare function vless(input: VlessInput): VlessProfileResult;
|
|
6255
6272
|
export declare const proxyProfile: Readonly<{
|
|
6256
6273
|
anytls: (input: RequiredTlsInput) => Profile<"anytls", true, unknown, unknown>;
|
|
6257
6274
|
http: typeof http;
|
|
@@ -6267,13 +6284,62 @@ export declare const proxyProfile: Readonly<{
|
|
|
6267
6284
|
(input: TransportInput<"trojan">): Profile<"trojan", true, unknown, unknown>;
|
|
6268
6285
|
};
|
|
6269
6286
|
tuic: (input: RequiredTlsInput) => Profile<"tuic", true, unknown, unknown>;
|
|
6270
|
-
vless:
|
|
6271
|
-
<const Transport extends TransportKind>(input: TransportInput<"vless"> & TransportSelection<Transport>): Profile<"vless", true, unknown, TransportSelection<Transport>>;
|
|
6272
|
-
(input: TransportInput<"vless">): Profile<"vless", true, unknown, unknown>;
|
|
6273
|
-
};
|
|
6287
|
+
vless: typeof vless;
|
|
6274
6288
|
vmess: {
|
|
6275
6289
|
<const Transport extends TransportKind>(input: TransportInput<"vmess"> & TransportSelection<Transport>): Profile<"vmess", true, unknown, TransportSelection<Transport>>;
|
|
6276
6290
|
(input: TransportInput<"vmess">): Profile<"vmess", true, unknown, unknown>;
|
|
6277
6291
|
};
|
|
6278
6292
|
}>;
|
|
6293
|
+
declare function uuid(): string;
|
|
6294
|
+
declare function random(length: number): Uint8Array;
|
|
6295
|
+
declare function randomHex(length: number): string;
|
|
6296
|
+
declare function randomBase64(length: number): string;
|
|
6297
|
+
declare function randomBase64Url(length: number): string;
|
|
6298
|
+
declare function x25519PublicKey(privateKey: Uint8Array): Promise<Uint8Array>;
|
|
6299
|
+
declare function x25519KeyPair(): Promise<{
|
|
6300
|
+
privateKey: Uint8Array<ArrayBuffer>;
|
|
6301
|
+
publicKey: Uint8Array<ArrayBufferLike>;
|
|
6302
|
+
}>;
|
|
6303
|
+
declare function reality(): Promise<{
|
|
6304
|
+
privateKey: string;
|
|
6305
|
+
publicKey: string;
|
|
6306
|
+
}>;
|
|
6307
|
+
declare function wireguard(): Promise<{
|
|
6308
|
+
privateKey: string;
|
|
6309
|
+
publicKey: string;
|
|
6310
|
+
}>;
|
|
6311
|
+
declare function vapidKeyPair(): Promise<{
|
|
6312
|
+
privateKey: string;
|
|
6313
|
+
publicKey: string;
|
|
6314
|
+
}>;
|
|
6315
|
+
declare function tailcatKeyPair(): Promise<{
|
|
6316
|
+
privateKey: string;
|
|
6317
|
+
publicKey: string;
|
|
6318
|
+
discoKey: string;
|
|
6319
|
+
preSharedKey: string;
|
|
6320
|
+
address: string;
|
|
6321
|
+
}>;
|
|
6322
|
+
declare function echKeyPair(publicName: string): Promise<{
|
|
6323
|
+
config: string;
|
|
6324
|
+
key: string;
|
|
6325
|
+
}>;
|
|
6326
|
+
declare function tlsKeyPair(serverName: string, months?: number): Promise<{
|
|
6327
|
+
privateKey: string;
|
|
6328
|
+
certificate: string;
|
|
6329
|
+
}>;
|
|
6330
|
+
export declare const generate: {
|
|
6331
|
+
readonly uuid: typeof uuid;
|
|
6332
|
+
readonly random: typeof random;
|
|
6333
|
+
readonly randomHex: typeof randomHex;
|
|
6334
|
+
readonly randomBase64: typeof randomBase64;
|
|
6335
|
+
readonly randomBase64Url: typeof randomBase64Url;
|
|
6336
|
+
readonly x25519KeyPair: typeof x25519KeyPair;
|
|
6337
|
+
readonly x25519PublicKey: typeof x25519PublicKey;
|
|
6338
|
+
readonly reality: typeof reality;
|
|
6339
|
+
readonly wireguard: typeof wireguard;
|
|
6340
|
+
readonly vapidKeyPair: typeof vapidKeyPair;
|
|
6341
|
+
readonly tailcatKeyPair: typeof tailcatKeyPair;
|
|
6342
|
+
readonly echKeyPair: typeof echKeyPair;
|
|
6343
|
+
readonly tlsKeyPair: typeof tlsKeyPair;
|
|
6344
|
+
};
|
|
6279
6345
|
export type { ClientTls, CompileInput, Condition, Dial, DirectDial, DnsRuleAction, DomainResolver, HeadlessRule, HttpClientInput, InboundListener, InlineHttpClient, Listener, MatchFields, RealityClientTls, RealityServerTls, RouteRuleAction, RuleAction, RuleValue, Scope, ServerTls, SingBoxConfig, User, UserCredentials };
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
import { isIP } from "node:net";
|
|
2
1
|
import Ajv2020 from "ajv/dist/2020.js";
|
|
3
|
-
import {
|
|
2
|
+
import { base64, base64url, hex } from "@peculiar/utils/encoding";
|
|
3
|
+
import { concatToUint8Array, toArrayBuffer } from "@peculiar/utils/bytes";
|
|
4
|
+
import "reflect-metadata";
|
|
5
|
+
import { pem } from "@peculiar/utils/pem";
|
|
6
|
+
import { BasicConstraintsExtension, ExtendedKeyUsage, ExtendedKeyUsageExtension, KeyUsageFlags, KeyUsagesExtension, SubjectAlternativeNameExtension, X509CertificateGenerator } from "@peculiar/x509";
|
|
4
7
|
// schema/sing-box.json
|
|
5
8
|
var sing_box_default = {
|
|
6
9
|
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
@@ -9211,6 +9214,42 @@ function ruleActionSchemas(scope) {
|
|
|
9211
9214
|
return [action, projectObject(properties, [...required])];
|
|
9212
9215
|
}));
|
|
9213
9216
|
}
|
|
9217
|
+
// src/ip.ts
|
|
9218
|
+
const ipv4Octet = /^(?:0|[1-9][0-9]{0,2})$/;
|
|
9219
|
+
const ipv6Group = /^[0-9a-f]{1,4}$/i;
|
|
9220
|
+
const ipv6Zone = /^[0-9a-z.:-]+$/i;
|
|
9221
|
+
const cidrPrefix = /^[0-9]+$/;
|
|
9222
|
+
function isIPv4(input) {
|
|
9223
|
+
const octets = input.split(".", 5);
|
|
9224
|
+
return octets.length === 4 && octets.every((octet) => ipv4Octet.test(octet) && Number(octet) <= 255);
|
|
9225
|
+
}
|
|
9226
|
+
function isIPv6(input) {
|
|
9227
|
+
const [address = "", zone, extraZone] = input.split("%", 3);
|
|
9228
|
+
if (!address.includes(":") || extraZone !== void 0 || zone !== void 0 && !ipv6Zone.test(zone)) return false;
|
|
9229
|
+
const [head = "", tail, extra] = address.split("::", 3);
|
|
9230
|
+
if (extra !== void 0) return false;
|
|
9231
|
+
const groups = head ? head.split(":", 9) : [];
|
|
9232
|
+
if (tail) groups.push(...tail.split(":", 9));
|
|
9233
|
+
let groupCount = groups.length;
|
|
9234
|
+
const last = groups.at(-1);
|
|
9235
|
+
if (last?.includes(".")) {
|
|
9236
|
+
if (tail === "" || !isIPv4(last)) return false;
|
|
9237
|
+
groups.pop();
|
|
9238
|
+
groupCount++;
|
|
9239
|
+
}
|
|
9240
|
+
return (tail === void 0 ? groupCount === 8 : groupCount < 8) && groups.every((group) => ipv6Group.test(group));
|
|
9241
|
+
}
|
|
9242
|
+
function isIP(input) {
|
|
9243
|
+
if (isIPv4(input)) return 4;
|
|
9244
|
+
if (isIPv6(input)) return 6;
|
|
9245
|
+
return 0;
|
|
9246
|
+
}
|
|
9247
|
+
function isCIDR(input) {
|
|
9248
|
+
const [address = "", prefix, extra] = input.split("/", 3);
|
|
9249
|
+
if (prefix === void 0 || extra !== void 0 || address.includes("%") || !cidrPrefix.test(prefix)) return false;
|
|
9250
|
+
const version = isIP(address);
|
|
9251
|
+
return version !== 0 && Number(prefix) <= (version === 4 ? 32 : 128);
|
|
9252
|
+
}
|
|
9214
9253
|
// src/resource.ts
|
|
9215
9254
|
const preferredRouteEndpoints = [
|
|
9216
9255
|
"tailscale",
|
|
@@ -9489,16 +9528,12 @@ const actions = {
|
|
|
9489
9528
|
route: actionsFor("route"),
|
|
9490
9529
|
dns: actionsFor("dns")
|
|
9491
9530
|
};
|
|
9492
|
-
function validSubnet(input) {
|
|
9493
|
-
const [address = "", prefix, ...extra] = input.split("/");
|
|
9494
|
-
const version = isIP(address);
|
|
9495
|
-
return version !== 0 && !address.includes("%") && extra.length === 0 && (prefix === void 0 || /^\d+$/.test(prefix) && Number(prefix) <= (version === 4 ? 32 : 128));
|
|
9496
|
-
}
|
|
9497
9531
|
function checkAction(fields, path, scope) {
|
|
9498
9532
|
if (fields.method === "drop" && fields.no_drop === true) fail(`${path}.no_drop`, "no_drop with drop");
|
|
9499
9533
|
if (fields.client_subnet !== void 0) {
|
|
9500
9534
|
if (fields.remove_client_subnet === true) fail(`${path}.client_subnet`, "client_subnet with remove_client_subnet");
|
|
9501
|
-
|
|
9535
|
+
const subnet = fields.client_subnet;
|
|
9536
|
+
if (!(subnet.includes("/") ? isCIDR(subnet) : !subnet.includes("%") && isIP(subnet) !== 0)) fail(`${path}.client_subnet`, "invalid subnet");
|
|
9502
9537
|
}
|
|
9503
9538
|
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");
|
|
9504
9539
|
if (fields.race === true && fields.speculative === true) fail(`${path}.race`, "race with speculative");
|
|
@@ -10050,6 +10085,39 @@ const certificateProvider = Object.freeze(factoriesFor("certificate_providers"))
|
|
|
10050
10085
|
const networkNamespace = Object.freeze(factoriesFor("network_namespaces"));
|
|
10051
10086
|
const httpClient = factoriesFor("http_clients").httpClient;
|
|
10052
10087
|
const ruleSet = Object.freeze(factoriesFor("route.rule_set"));
|
|
10088
|
+
// src/internal/crypto.ts
|
|
10089
|
+
const x25519Pkcs8Header = hex.decode("302e020100300506032b656e04220420");
|
|
10090
|
+
function randomBytes(length) {
|
|
10091
|
+
if (!Number.isSafeInteger(length) || length < 0) throw new RangeError("Random byte length must be a non-negative integer");
|
|
10092
|
+
const bytes = new Uint8Array(length);
|
|
10093
|
+
for (let offset = 0; offset < bytes.length; offset += 65536) globalThis.crypto.getRandomValues(bytes.subarray(offset, offset + 65536));
|
|
10094
|
+
return bytes;
|
|
10095
|
+
}
|
|
10096
|
+
async function deriveX25519PublicKey(privateKey) {
|
|
10097
|
+
if (privateKey.length !== 32) throw new RangeError("X25519 private key must be 32 bytes");
|
|
10098
|
+
const { subtle } = globalThis.crypto;
|
|
10099
|
+
const pkcs8 = toArrayBuffer(concatToUint8Array([x25519Pkcs8Header, privateKey]));
|
|
10100
|
+
const key = await subtle.importKey("pkcs8", pkcs8, "X25519", false, ["deriveBits"]);
|
|
10101
|
+
const basePoint = /* @__PURE__ */ new Uint8Array(32);
|
|
10102
|
+
basePoint[0] = 9;
|
|
10103
|
+
const publicKey = await subtle.importKey("raw", basePoint, "X25519", false, []);
|
|
10104
|
+
return new Uint8Array(await subtle.deriveBits({
|
|
10105
|
+
name: "X25519",
|
|
10106
|
+
public: publicKey
|
|
10107
|
+
}, key, 256));
|
|
10108
|
+
}
|
|
10109
|
+
// src/internal/reality.ts
|
|
10110
|
+
function decodeKey(input, path) {
|
|
10111
|
+
if (typeof input !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(input)) fail(path, "expected an unpadded 32-byte Base64url key");
|
|
10112
|
+
const bytes = base64url.decode(input);
|
|
10113
|
+
if (base64url.encode(bytes) !== input) fail(path, "expected an unpadded 32-byte Base64url key");
|
|
10114
|
+
return bytes;
|
|
10115
|
+
}
|
|
10116
|
+
async function validateRealityKeyPair({ privateKey, publicKey }, path) {
|
|
10117
|
+
const privateBytes = decodeKey(privateKey, `${path}.privateKey`);
|
|
10118
|
+
decodeKey(publicKey, `${path}.publicKey`);
|
|
10119
|
+
if (base64url.encode(await deriveX25519PublicKey(privateBytes)) !== publicKey) fail(`${path}.publicKey`, "does not match private key");
|
|
10120
|
+
}
|
|
10053
10121
|
// src/proxy-profile.ts
|
|
10054
10122
|
const sharedOption = {
|
|
10055
10123
|
hysteria: "obfs",
|
|
@@ -10199,18 +10267,6 @@ function usersFor(input, path) {
|
|
|
10199
10267
|
return value;
|
|
10200
10268
|
});
|
|
10201
10269
|
}
|
|
10202
|
-
function realityKeys(input, path) {
|
|
10203
|
-
const keys = fieldsFrom(input, path, ["privateKey", "publicKey"], ["privateKey", "publicKey"]);
|
|
10204
|
-
const { privateKey, publicKey } = keys;
|
|
10205
|
-
for (const [key, value] of Object.entries(keys)) if (typeof value !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(value) || Buffer.from(value, "base64url").toString("base64url") !== value) fail(`${path}.${key}`, "expected an unpadded 32-byte Base64url key");
|
|
10206
|
-
const der = Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), Buffer.from(privateKey, "base64url")]);
|
|
10207
|
-
if (createPublicKey(createPrivateKey({
|
|
10208
|
-
key: der,
|
|
10209
|
-
format: "der",
|
|
10210
|
-
type: "pkcs8"
|
|
10211
|
-
})).export({ format: "jwk" }).x !== publicKey) fail(`${path}.publicKey`, "does not match private key");
|
|
10212
|
-
return keys;
|
|
10213
|
-
}
|
|
10214
10270
|
function tlsFor(kind, input, needsTls, path) {
|
|
10215
10271
|
const { mode } = record(input ?? { mode: "none" }, path);
|
|
10216
10272
|
if (mode === "tls") {
|
|
@@ -10254,7 +10310,7 @@ function tlsFor(kind, input, needsTls, path) {
|
|
|
10254
10310
|
return {
|
|
10255
10311
|
mode,
|
|
10256
10312
|
serverName: fields.serverName,
|
|
10257
|
-
keys:
|
|
10313
|
+
keys: fieldsFrom(fields.keyPair, `${path}.keyPair`, ["privateKey", "publicKey"], ["privateKey", "publicKey"]),
|
|
10258
10314
|
ids,
|
|
10259
10315
|
handshake: {
|
|
10260
10316
|
...dial,
|
|
@@ -10469,7 +10525,7 @@ function makeProfile(kind, input) {
|
|
|
10469
10525
|
if (local.tls !== void 0) fail(`${location}.tls`, "TLS must be enabled in the profile");
|
|
10470
10526
|
return builder;
|
|
10471
10527
|
}
|
|
10472
|
-
|
|
10528
|
+
const result = Object.freeze({
|
|
10473
10529
|
server(input) {
|
|
10474
10530
|
const { local, fields, location } = sideOptions(input, false);
|
|
10475
10531
|
let builder = native(inbound[kind], {
|
|
@@ -10503,6 +10559,8 @@ function makeProfile(kind, input) {
|
|
|
10503
10559
|
return applyTls(builder, local, location, true);
|
|
10504
10560
|
}
|
|
10505
10561
|
});
|
|
10562
|
+
if (tls.mode === "reality") return validateRealityKeyPair(tls.keys, `${path}.tls.keyPair`).then(() => result);
|
|
10563
|
+
return result;
|
|
10506
10564
|
}
|
|
10507
10565
|
function requiredString(input, path) {
|
|
10508
10566
|
if (typeof input !== "string" || !input) fail(path, "expected a non-empty string");
|
|
@@ -10529,6 +10587,13 @@ function transportProfile(kind) {
|
|
|
10529
10587
|
}
|
|
10530
10588
|
return create;
|
|
10531
10589
|
}
|
|
10590
|
+
async function vlessReality(input) {
|
|
10591
|
+
return makeProfile("vless", input);
|
|
10592
|
+
}
|
|
10593
|
+
function vless(input) {
|
|
10594
|
+
if (input?.tls?.mode === "reality") return vlessReality(input);
|
|
10595
|
+
return makeProfile("vless", input);
|
|
10596
|
+
}
|
|
10532
10597
|
const proxyProfile = Object.freeze({
|
|
10533
10598
|
anytls: (input) => makeProfile("anytls", input),
|
|
10534
10599
|
http,
|
|
@@ -10541,7 +10606,178 @@ const proxyProfile = Object.freeze({
|
|
|
10541
10606
|
socks,
|
|
10542
10607
|
trojan: transportProfile("trojan"),
|
|
10543
10608
|
tuic: (input) => makeProfile("tuic", input),
|
|
10544
|
-
vless
|
|
10609
|
+
vless,
|
|
10545
10610
|
vmess: transportProfile("vmess")
|
|
10546
10611
|
});
|
|
10547
|
-
|
|
10612
|
+
// src/internal/certificate.ts
|
|
10613
|
+
async function serverCertificate(serverName, months) {
|
|
10614
|
+
if (!Number.isSafeInteger(months) || months < 1) throw new RangeError("TLS validity must be a positive integer number of months");
|
|
10615
|
+
const now = /* @__PURE__ */ new Date();
|
|
10616
|
+
const expires = new Date(now);
|
|
10617
|
+
expires.setUTCMonth(expires.getUTCMonth() + months);
|
|
10618
|
+
if (!Number.isFinite(expires.getTime()) || expires.getUTCFullYear() > 9999) throw new RangeError("TLS expiry is outside the supported date range");
|
|
10619
|
+
if (/[\s\\/@?#%]/.test(serverName)) throw new TypeError("TLS server name must be a DNS name or IP address");
|
|
10620
|
+
const version = isIP(serverName);
|
|
10621
|
+
const dnsName = version || serverName.includes(":") ? void 0 : URL.parse(`http://${serverName}/`)?.hostname;
|
|
10622
|
+
if (!version && (!dnsName || !/^(?:\*\.)?[a-z\d_-]+(?:\.[a-z\d_-]+)*\.?$/i.test(dnsName))) throw new TypeError("TLS server name must be a DNS name or IP address");
|
|
10623
|
+
const crypto = globalThis.crypto;
|
|
10624
|
+
const algorithm = {
|
|
10625
|
+
name: "RSASSA-PKCS1-v1_5",
|
|
10626
|
+
modulusLength: 2048,
|
|
10627
|
+
publicExponent: new Uint8Array([
|
|
10628
|
+
1,
|
|
10629
|
+
0,
|
|
10630
|
+
1
|
|
10631
|
+
]),
|
|
10632
|
+
hash: "SHA-256"
|
|
10633
|
+
};
|
|
10634
|
+
const keys = await crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);
|
|
10635
|
+
const name = dnsName || serverName;
|
|
10636
|
+
const san = version === 6 ? new URL(`http://[${serverName}]`).hostname.slice(1, -1) : name;
|
|
10637
|
+
const certificate = await X509CertificateGenerator.createSelfSigned({
|
|
10638
|
+
name: [{ CN: [name] }],
|
|
10639
|
+
notBefore: /* @__PURE__ */ new Date(now.getTime() - 36e5),
|
|
10640
|
+
notAfter: expires,
|
|
10641
|
+
signingAlgorithm: algorithm,
|
|
10642
|
+
keys,
|
|
10643
|
+
extensions: [
|
|
10644
|
+
new KeyUsagesExtension(KeyUsageFlags.digitalSignature | KeyUsageFlags.keyEncipherment, true),
|
|
10645
|
+
new ExtendedKeyUsageExtension([ExtendedKeyUsage.serverAuth]),
|
|
10646
|
+
new BasicConstraintsExtension(false),
|
|
10647
|
+
new SubjectAlternativeNameExtension([{
|
|
10648
|
+
type: version ? "ip" : "dns",
|
|
10649
|
+
value: san
|
|
10650
|
+
}])
|
|
10651
|
+
]
|
|
10652
|
+
}, crypto);
|
|
10653
|
+
return {
|
|
10654
|
+
privateKey: pem.encode("PRIVATE KEY", await crypto.subtle.exportKey("pkcs8", keys.privateKey)),
|
|
10655
|
+
certificate: pem.encode("CERTIFICATE", certificate.rawData)
|
|
10656
|
+
};
|
|
10657
|
+
}
|
|
10658
|
+
// src/internal/ech.ts
|
|
10659
|
+
const cipherSuites = hex.decode("000100010001000200010003");
|
|
10660
|
+
function uint16(value) {
|
|
10661
|
+
const bytes = /* @__PURE__ */ new Uint8Array(2);
|
|
10662
|
+
new DataView(bytes.buffer).setUint16(0, value);
|
|
10663
|
+
return bytes;
|
|
10664
|
+
}
|
|
10665
|
+
function vector16(bytes) {
|
|
10666
|
+
return concatToUint8Array([uint16(bytes.length), bytes]);
|
|
10667
|
+
}
|
|
10668
|
+
function encodeEchKeyPair(name, privateKey, publicKey) {
|
|
10669
|
+
const contents = concatToUint8Array([
|
|
10670
|
+
Uint8Array.of(0),
|
|
10671
|
+
uint16(32),
|
|
10672
|
+
vector16(publicKey),
|
|
10673
|
+
vector16(cipherSuites),
|
|
10674
|
+
Uint8Array.of(0, name.length),
|
|
10675
|
+
name,
|
|
10676
|
+
uint16(0)
|
|
10677
|
+
]);
|
|
10678
|
+
const config = vector16(concatToUint8Array([uint16(65037), vector16(contents)]));
|
|
10679
|
+
return {
|
|
10680
|
+
config: pem.encode("ECH CONFIGS", config),
|
|
10681
|
+
key: pem.encode("ECH KEYS", concatToUint8Array([vector16(privateKey), config]))
|
|
10682
|
+
};
|
|
10683
|
+
}
|
|
10684
|
+
// src/generate.ts
|
|
10685
|
+
function uuid() {
|
|
10686
|
+
return globalThis.crypto.randomUUID();
|
|
10687
|
+
}
|
|
10688
|
+
function random(length) {
|
|
10689
|
+
return randomBytes(length);
|
|
10690
|
+
}
|
|
10691
|
+
function randomHex(length) {
|
|
10692
|
+
return hex.encode(random(length));
|
|
10693
|
+
}
|
|
10694
|
+
function randomBase64(length) {
|
|
10695
|
+
return base64.encode(random(length));
|
|
10696
|
+
}
|
|
10697
|
+
function randomBase64Url(length) {
|
|
10698
|
+
return base64url.encode(random(length));
|
|
10699
|
+
}
|
|
10700
|
+
function x25519PublicKey(privateKey) {
|
|
10701
|
+
return deriveX25519PublicKey(privateKey);
|
|
10702
|
+
}
|
|
10703
|
+
async function x25519KeyPair() {
|
|
10704
|
+
const privateKey = randomBytes(32);
|
|
10705
|
+
privateKey[0] = privateKey[0] & 248;
|
|
10706
|
+
privateKey[31] = privateKey[31] & 127 | 64;
|
|
10707
|
+
return {
|
|
10708
|
+
privateKey,
|
|
10709
|
+
publicKey: await x25519PublicKey(privateKey)
|
|
10710
|
+
};
|
|
10711
|
+
}
|
|
10712
|
+
async function reality() {
|
|
10713
|
+
const { privateKey, publicKey } = await x25519KeyPair();
|
|
10714
|
+
return {
|
|
10715
|
+
privateKey: base64url.encode(privateKey),
|
|
10716
|
+
publicKey: base64url.encode(publicKey)
|
|
10717
|
+
};
|
|
10718
|
+
}
|
|
10719
|
+
async function wireguard() {
|
|
10720
|
+
const { privateKey, publicKey } = await x25519KeyPair();
|
|
10721
|
+
return {
|
|
10722
|
+
privateKey: base64.encode(privateKey),
|
|
10723
|
+
publicKey: base64.encode(publicKey)
|
|
10724
|
+
};
|
|
10725
|
+
}
|
|
10726
|
+
async function vapidKeyPair() {
|
|
10727
|
+
const { subtle } = globalThis.crypto;
|
|
10728
|
+
const key = await subtle.generateKey({
|
|
10729
|
+
name: "ECDSA",
|
|
10730
|
+
namedCurve: "P-256"
|
|
10731
|
+
}, true, ["sign", "verify"]);
|
|
10732
|
+
const { d: privateKey } = await subtle.exportKey("jwk", key.privateKey);
|
|
10733
|
+
const publicKey = await subtle.exportKey("raw", key.publicKey);
|
|
10734
|
+
return {
|
|
10735
|
+
privateKey,
|
|
10736
|
+
publicKey: base64url.encode(publicKey)
|
|
10737
|
+
};
|
|
10738
|
+
}
|
|
10739
|
+
async function tailcatKeyPair() {
|
|
10740
|
+
const { privateKey, publicKey } = await x25519KeyPair();
|
|
10741
|
+
const { subtle } = globalThis.crypto;
|
|
10742
|
+
const hmacKey = await subtle.importKey("raw", privateKey, {
|
|
10743
|
+
name: "HMAC",
|
|
10744
|
+
hash: "SHA-256"
|
|
10745
|
+
}, false, ["sign"]);
|
|
10746
|
+
const discoLabel = new TextEncoder().encode("github.com/tailscale/tailcat disco key v1");
|
|
10747
|
+
const discoPrivateKey = new Uint8Array(await subtle.sign("HMAC", hmacKey, discoLabel));
|
|
10748
|
+
const view = new DataView(publicKey.buffer, publicKey.byteOffset, publicKey.byteLength);
|
|
10749
|
+
const groups = Array.from({ length: 5 }, (_, index) => view.getUint16(index * 2).toString(16));
|
|
10750
|
+
const address = new URL(`http://[fd7a:115c:a1e0:${groups.join(":")}]`).hostname.slice(1, -1);
|
|
10751
|
+
return {
|
|
10752
|
+
privateKey: base64.encode(privateKey),
|
|
10753
|
+
publicKey: base64.encode(publicKey),
|
|
10754
|
+
discoKey: base64.encode(await x25519PublicKey(discoPrivateKey)),
|
|
10755
|
+
preSharedKey: randomBase64(32),
|
|
10756
|
+
address
|
|
10757
|
+
};
|
|
10758
|
+
}
|
|
10759
|
+
async function echKeyPair(publicName) {
|
|
10760
|
+
const name = new TextEncoder().encode(publicName);
|
|
10761
|
+
if (name.length < 1 || name.length > 255) throw new RangeError("ECH public name must be between 1 and 255 bytes");
|
|
10762
|
+
const { privateKey, publicKey } = await x25519KeyPair();
|
|
10763
|
+
return encodeEchKeyPair(name, privateKey, publicKey);
|
|
10764
|
+
}
|
|
10765
|
+
function tlsKeyPair(serverName, months = 1) {
|
|
10766
|
+
return serverCertificate(serverName, months);
|
|
10767
|
+
}
|
|
10768
|
+
const generate = {
|
|
10769
|
+
uuid,
|
|
10770
|
+
random,
|
|
10771
|
+
randomHex,
|
|
10772
|
+
randomBase64,
|
|
10773
|
+
randomBase64Url,
|
|
10774
|
+
x25519KeyPair,
|
|
10775
|
+
x25519PublicKey,
|
|
10776
|
+
reality,
|
|
10777
|
+
wireguard,
|
|
10778
|
+
vapidKeyPair,
|
|
10779
|
+
tailcatKeyPair,
|
|
10780
|
+
echKeyPair,
|
|
10781
|
+
tlsKeyPair
|
|
10782
|
+
};
|
|
10783
|
+
export { Rule, certificateProvider, compile, dns, dnsServer, endpoint, generate, httpClient, inbound, networkNamespace, outbound, proxyProfile, route, ruleSet, service, user, validateConfig };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Generate credentials and key pairs
|
|
2
|
+
|
|
3
|
+
The generators use `globalThis.crypto` in Bun and Node.js. UUID and random byte generators return immediately. Key generation and public-key derivation return promises.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { generate } from "sing-box-kit";
|
|
7
|
+
|
|
8
|
+
const uuid = generate.uuid();
|
|
9
|
+
const { privateKey, publicKey } = await generate.reality();
|
|
10
|
+
const shortId = generate.randomHex(8);
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Use the Reality private key in the server's `private_key` field and the public key in the client's `public_key` field. Use the same short ID on both sides.
|
|
14
|
+
|
|
15
|
+
| Function | Result |
|
|
16
|
+
| ------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
|
|
17
|
+
| `generate.uuid()` | UUID v4 string |
|
|
18
|
+
| `generate.random(length)` | Random bytes as a `Uint8Array` |
|
|
19
|
+
| `generate.randomHex(length)` | Lowercase hexadecimal string |
|
|
20
|
+
| `generate.randomBase64(length)` | Standard padded Base64 string |
|
|
21
|
+
| `generate.randomBase64Url(length)` | Unpadded Base64url string |
|
|
22
|
+
| `await generate.x25519KeyPair()` | Raw 32-byte `privateKey` and `publicKey` |
|
|
23
|
+
| `await generate.x25519PublicKey(privateKey)` | Raw public key derived from a 32-byte `Uint8Array` |
|
|
24
|
+
| `await generate.reality()` | `privateKey` and `publicKey` as unpadded Base64url |
|
|
25
|
+
| `await generate.wireguard()` | `privateKey` and `publicKey` as standard padded Base64 |
|
|
26
|
+
| `await generate.vapidKeyPair()` | P-256 `privateKey` and uncompressed `publicKey` as unpadded Base64url |
|
|
27
|
+
| `await generate.tailcatKeyPair()` | Padded Base64 `privateKey`, `publicKey`, `discoKey`, and `preSharedKey`, plus an IPv6 `address` |
|
|
28
|
+
| `await generate.echKeyPair(publicName)` | PEM `config` for the client and PEM `key` for the server |
|
|
29
|
+
| `await generate.tlsKeyPair(serverName, months?)` | PEM `privateKey` and self-signed `certificate` for a DNS name or IP address. Defaults to one month. |
|
|
30
|
+
|
|
31
|
+
Random lengths count bytes before encoding. Tailcat configuration requires sing-box 1.15 or later.
|
package/docs/internal/README.md
CHANGED
|
@@ -27,5 +27,5 @@ The [package entry point](../../index.ts) exports resource builders, rule builde
|
|
|
27
27
|
## Where to check a change
|
|
28
28
|
|
|
29
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
|
|
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
|
|
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 the suite with `vp test` on Node.js or `bun run --bun vp test --pool=threads` on Bun.
|
|
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 runs the test suite on both runtimes.
|
package/docs/proxy-profiles.md
CHANGED
|
@@ -42,7 +42,7 @@ VMess, VLESS, and Trojan default to TCP. Select `http`, `ws`, `grpc`, `httpupgra
|
|
|
42
42
|
|
|
43
43
|
For regular TLS, the client uses the public host as the verification name by default. Set `tls.serverName` when it differs. Set `tls.alpn` in the profile to send the same list to both ends. V2Ray QUIC requires regular TLS.
|
|
44
44
|
|
|
45
|
-
For VLESS REALITY,
|
|
45
|
+
For VLESS REALITY, pass `tls: { mode: "reality", serverName, handshake: { host, port }, keyPair: { privateKey, publicKey }, shortId }` and use `await proxyProfile.vless(options)` to validate the key pair with Web Crypto before building either resource. To accept multiple short IDs, use `shortIds` and pass `shortId` in the client options.
|
|
46
46
|
|
|
47
47
|
## Protocol versions and shared keys
|
|
48
48
|
|
package/index.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sing-box-kit",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"description": "Build and validate sing-box configurations with Bun and Node.js.",
|
|
5
5
|
"license": "GPL-3.0-or-later",
|
|
6
6
|
"repository": {
|
|
@@ -33,16 +33,20 @@
|
|
|
33
33
|
"schema:generate": "bun scripts/generate-schema.ts"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"
|
|
36
|
+
"@peculiar/utils": "^4.1.0",
|
|
37
|
+
"@peculiar/x509": "^3.1.0",
|
|
38
|
+
"ajv": "^8.20.0",
|
|
39
|
+
"reflect-metadata": "^0.2.2"
|
|
37
40
|
},
|
|
38
41
|
"devDependencies": {
|
|
42
|
+
"@actions/github": "^9.0.0",
|
|
39
43
|
"@types/bun": "latest",
|
|
40
44
|
"json-schema-to-typescript": "^16.0.0",
|
|
41
45
|
"typescript": "^7.0.2",
|
|
42
46
|
"vite-plus": "1.8.0"
|
|
43
47
|
},
|
|
44
48
|
"engines": {
|
|
45
|
-
"node": ">=22.
|
|
49
|
+
"node": ">=22.13.0"
|
|
46
50
|
},
|
|
47
51
|
"packageManager": "bun@1.4.5"
|
|
48
52
|
}
|
package/schema/README.md
CHANGED
|
@@ -13,7 +13,7 @@ vp install --frozen-lockfile
|
|
|
13
13
|
bun run schema:generate
|
|
14
14
|
git diff --exit-code -- src/generated
|
|
15
15
|
vp check
|
|
16
|
-
|
|
16
|
+
vp test
|
|
17
17
|
```
|
|
18
18
|
|
|
19
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.
|
package/src/compile.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { isIP } from "node:net";
|
|
2
1
|
import type { SBKitInputs } from "./generated/sbkit-inputs";
|
|
3
|
-
import { rootSettings, sectionSettings } from "./input-schema";
|
|
4
2
|
import type { SingBoxConfig } from "./generated/sing-box";
|
|
3
|
+
import { rootSettings, sectionSettings } from "./input-schema";
|
|
4
|
+
import { isIP } from "./ip";
|
|
5
5
|
import { copyJson, fieldsFrom, resourceData } from "./resource";
|
|
6
6
|
import type {
|
|
7
7
|
DnsServer,
|
package/src/generate.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { base64, base64url, hex } from "@peculiar/utils/encoding";
|
|
2
|
+
import { serverCertificate } from "./internal/certificate";
|
|
3
|
+
import { deriveX25519PublicKey, randomBytes } from "./internal/crypto";
|
|
4
|
+
import { encodeEchKeyPair } from "./internal/ech";
|
|
5
|
+
|
|
6
|
+
function uuid(): string {
|
|
7
|
+
return globalThis.crypto.randomUUID();
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function random(length: number): Uint8Array {
|
|
11
|
+
return randomBytes(length);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function randomHex(length: number): string {
|
|
15
|
+
return hex.encode(random(length));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function randomBase64(length: number): string {
|
|
19
|
+
return base64.encode(random(length));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function randomBase64Url(length: number): string {
|
|
23
|
+
return base64url.encode(random(length));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function x25519PublicKey(privateKey: Uint8Array): Promise<Uint8Array> {
|
|
27
|
+
return deriveX25519PublicKey(privateKey);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function x25519KeyPair() {
|
|
31
|
+
const privateKey = randomBytes(32);
|
|
32
|
+
privateKey[0] = privateKey[0]! & 248;
|
|
33
|
+
privateKey[31] = (privateKey[31]! & 127) | 64;
|
|
34
|
+
return { privateKey, publicKey: await x25519PublicKey(privateKey) };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function reality() {
|
|
38
|
+
const { privateKey, publicKey } = await x25519KeyPair();
|
|
39
|
+
return {
|
|
40
|
+
privateKey: base64url.encode(privateKey),
|
|
41
|
+
publicKey: base64url.encode(publicKey),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function wireguard() {
|
|
46
|
+
const { privateKey, publicKey } = await x25519KeyPair();
|
|
47
|
+
return {
|
|
48
|
+
privateKey: base64.encode(privateKey),
|
|
49
|
+
publicKey: base64.encode(publicKey),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function vapidKeyPair() {
|
|
54
|
+
const { subtle } = globalThis.crypto;
|
|
55
|
+
const key = await subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
|
|
56
|
+
"sign",
|
|
57
|
+
"verify",
|
|
58
|
+
]);
|
|
59
|
+
const { d: privateKey } = await subtle.exportKey("jwk", key.privateKey);
|
|
60
|
+
const publicKey = await subtle.exportKey("raw", key.publicKey);
|
|
61
|
+
return { privateKey: privateKey!, publicKey: base64url.encode(publicKey) };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function tailcatKeyPair() {
|
|
65
|
+
const { privateKey, publicKey } = await x25519KeyPair();
|
|
66
|
+
const { subtle } = globalThis.crypto;
|
|
67
|
+
const hmacKey = await subtle.importKey(
|
|
68
|
+
"raw",
|
|
69
|
+
privateKey,
|
|
70
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
71
|
+
false,
|
|
72
|
+
["sign"],
|
|
73
|
+
);
|
|
74
|
+
const discoLabel = new TextEncoder().encode("github.com/tailscale/tailcat disco key v1");
|
|
75
|
+
const discoPrivateKey = new Uint8Array(await subtle.sign("HMAC", hmacKey, discoLabel));
|
|
76
|
+
const view = new DataView(publicKey.buffer, publicKey.byteOffset, publicKey.byteLength);
|
|
77
|
+
const groups = Array.from({ length: 5 }, (_, index) => view.getUint16(index * 2).toString(16));
|
|
78
|
+
const address = new URL(`http://[fd7a:115c:a1e0:${groups.join(":")}]`).hostname.slice(1, -1);
|
|
79
|
+
return {
|
|
80
|
+
privateKey: base64.encode(privateKey),
|
|
81
|
+
publicKey: base64.encode(publicKey),
|
|
82
|
+
discoKey: base64.encode(await x25519PublicKey(discoPrivateKey)),
|
|
83
|
+
preSharedKey: randomBase64(32),
|
|
84
|
+
address,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function echKeyPair(publicName: string) {
|
|
89
|
+
const name = new TextEncoder().encode(publicName);
|
|
90
|
+
if (name.length < 1 || name.length > 255) {
|
|
91
|
+
throw new RangeError("ECH public name must be between 1 and 255 bytes");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const { privateKey, publicKey } = await x25519KeyPair();
|
|
95
|
+
return encodeEchKeyPair(name, privateKey, publicKey);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function tlsKeyPair(serverName: string, months = 1) {
|
|
99
|
+
return serverCertificate(serverName, months);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export const generate = {
|
|
103
|
+
uuid,
|
|
104
|
+
random,
|
|
105
|
+
randomHex,
|
|
106
|
+
randomBase64,
|
|
107
|
+
randomBase64Url,
|
|
108
|
+
x25519KeyPair,
|
|
109
|
+
x25519PublicKey,
|
|
110
|
+
reality,
|
|
111
|
+
wireguard,
|
|
112
|
+
vapidKeyPair,
|
|
113
|
+
tailcatKeyPair,
|
|
114
|
+
echKeyPair,
|
|
115
|
+
tlsKeyPair,
|
|
116
|
+
} as const;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import "reflect-metadata";
|
|
2
|
+
import { pem } from "@peculiar/utils/pem";
|
|
3
|
+
import {
|
|
4
|
+
BasicConstraintsExtension,
|
|
5
|
+
ExtendedKeyUsage,
|
|
6
|
+
ExtendedKeyUsageExtension,
|
|
7
|
+
KeyUsageFlags,
|
|
8
|
+
KeyUsagesExtension,
|
|
9
|
+
SubjectAlternativeNameExtension,
|
|
10
|
+
X509CertificateGenerator,
|
|
11
|
+
} from "@peculiar/x509";
|
|
12
|
+
import { isIP } from "../ip";
|
|
13
|
+
|
|
14
|
+
export async function serverCertificate(serverName: string, months: number) {
|
|
15
|
+
if (!Number.isSafeInteger(months) || months < 1) {
|
|
16
|
+
throw new RangeError("TLS validity must be a positive integer number of months");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const now = new Date();
|
|
20
|
+
const expires = new Date(now);
|
|
21
|
+
expires.setUTCMonth(expires.getUTCMonth() + months);
|
|
22
|
+
if (!Number.isFinite(expires.getTime()) || expires.getUTCFullYear() > 9999) {
|
|
23
|
+
throw new RangeError("TLS expiry is outside the supported date range");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (/[\s\\/@?#%]/.test(serverName)) {
|
|
27
|
+
throw new TypeError("TLS server name must be a DNS name or IP address");
|
|
28
|
+
}
|
|
29
|
+
const version = isIP(serverName);
|
|
30
|
+
const dnsName =
|
|
31
|
+
version || serverName.includes(":") ? undefined : URL.parse(`http://${serverName}/`)?.hostname;
|
|
32
|
+
if (!version && (!dnsName || !/^(?:\*\.)?[a-z\d_-]+(?:\.[a-z\d_-]+)*\.?$/i.test(dnsName))) {
|
|
33
|
+
throw new TypeError("TLS server name must be a DNS name or IP address");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const crypto = globalThis.crypto;
|
|
37
|
+
const algorithm = {
|
|
38
|
+
name: "RSASSA-PKCS1-v1_5",
|
|
39
|
+
modulusLength: 2048,
|
|
40
|
+
publicExponent: new Uint8Array([1, 0, 1]),
|
|
41
|
+
hash: "SHA-256",
|
|
42
|
+
};
|
|
43
|
+
const keys = await crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);
|
|
44
|
+
|
|
45
|
+
const name = dnsName || serverName;
|
|
46
|
+
// Normalize IPv4-mapped IPv6 to hexadecimal groups for the SAN encoder.
|
|
47
|
+
const san = version === 6 ? new URL(`http://[${serverName}]`).hostname.slice(1, -1) : name;
|
|
48
|
+
const certificate = await X509CertificateGenerator.createSelfSigned(
|
|
49
|
+
{
|
|
50
|
+
name: [{ CN: [name] }],
|
|
51
|
+
notBefore: new Date(now.getTime() - 3_600_000),
|
|
52
|
+
notAfter: expires,
|
|
53
|
+
signingAlgorithm: algorithm,
|
|
54
|
+
keys,
|
|
55
|
+
extensions: [
|
|
56
|
+
new KeyUsagesExtension(
|
|
57
|
+
KeyUsageFlags.digitalSignature | KeyUsageFlags.keyEncipherment,
|
|
58
|
+
true,
|
|
59
|
+
),
|
|
60
|
+
new ExtendedKeyUsageExtension([ExtendedKeyUsage.serverAuth]),
|
|
61
|
+
new BasicConstraintsExtension(false),
|
|
62
|
+
new SubjectAlternativeNameExtension([{ type: version ? "ip" : "dns", value: san }]),
|
|
63
|
+
],
|
|
64
|
+
},
|
|
65
|
+
crypto,
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
privateKey: pem.encode("PRIVATE KEY", await crypto.subtle.exportKey("pkcs8", keys.privateKey)),
|
|
70
|
+
certificate: pem.encode("CERTIFICATE", certificate.rawData),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { concatToUint8Array, toArrayBuffer } from "@peculiar/utils/bytes";
|
|
2
|
+
import { hex } from "@peculiar/utils/encoding";
|
|
3
|
+
|
|
4
|
+
// RFC 8410 PKCS#8 header for a 32-byte X25519 private key.
|
|
5
|
+
const x25519Pkcs8Header = hex.decode("302e020100300506032b656e04220420");
|
|
6
|
+
|
|
7
|
+
export function randomBytes(length: number): Uint8Array<ArrayBuffer> {
|
|
8
|
+
if (!Number.isSafeInteger(length) || length < 0) {
|
|
9
|
+
throw new RangeError("Random byte length must be a non-negative integer");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const bytes = new Uint8Array(length);
|
|
13
|
+
// Web Crypto limits each getRandomValues call to 65,536 bytes.
|
|
14
|
+
for (let offset = 0; offset < bytes.length; offset += 65_536) {
|
|
15
|
+
globalThis.crypto.getRandomValues(bytes.subarray(offset, offset + 65_536));
|
|
16
|
+
}
|
|
17
|
+
return bytes;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function deriveX25519PublicKey(
|
|
21
|
+
privateKey: Uint8Array,
|
|
22
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
23
|
+
if (privateKey.length !== 32) throw new RangeError("X25519 private key must be 32 bytes");
|
|
24
|
+
|
|
25
|
+
const { subtle } = globalThis.crypto;
|
|
26
|
+
const pkcs8 = toArrayBuffer(concatToUint8Array([x25519Pkcs8Header, privateKey]));
|
|
27
|
+
const key = await subtle.importKey("pkcs8", pkcs8, "X25519", false, ["deriveBits"]);
|
|
28
|
+
|
|
29
|
+
// X25519 with the standard base point yields the corresponding public key.
|
|
30
|
+
const basePoint = new Uint8Array(32);
|
|
31
|
+
basePoint[0] = 9;
|
|
32
|
+
const publicKey = await subtle.importKey("raw", basePoint, "X25519", false, []);
|
|
33
|
+
return new Uint8Array(await subtle.deriveBits({ name: "X25519", public: publicKey }, key, 256));
|
|
34
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { concatToUint8Array } from "@peculiar/utils/bytes";
|
|
2
|
+
import { hex } from "@peculiar/utils/encoding";
|
|
3
|
+
import { pem } from "@peculiar/utils/pem";
|
|
4
|
+
|
|
5
|
+
const cipherSuites = hex.decode("000100010001000200010003"); // HKDF-SHA256 and three AEADs.
|
|
6
|
+
|
|
7
|
+
function uint16(value: number): Uint8Array {
|
|
8
|
+
const bytes = new Uint8Array(2);
|
|
9
|
+
new DataView(bytes.buffer).setUint16(0, value);
|
|
10
|
+
return bytes;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function vector16(bytes: Uint8Array): Uint8Array {
|
|
14
|
+
return concatToUint8Array([uint16(bytes.length), bytes]);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function encodeEchKeyPair(name: Uint8Array, privateKey: Uint8Array, publicKey: Uint8Array) {
|
|
18
|
+
const contents = concatToUint8Array([
|
|
19
|
+
Uint8Array.of(0), // Configuration ID.
|
|
20
|
+
uint16(0x0020), // DHKEM(X25519, HKDF-SHA256).
|
|
21
|
+
vector16(publicKey),
|
|
22
|
+
vector16(cipherSuites),
|
|
23
|
+
Uint8Array.of(0, name.length), // Maximum name length and public name length.
|
|
24
|
+
name,
|
|
25
|
+
uint16(0), // No extensions.
|
|
26
|
+
]);
|
|
27
|
+
const config = vector16(concatToUint8Array([uint16(0xfe0d), vector16(contents)]));
|
|
28
|
+
return {
|
|
29
|
+
config: pem.encode("ECH CONFIGS", config),
|
|
30
|
+
key: pem.encode("ECH KEYS", concatToUint8Array([vector16(privateKey), config])),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { base64url } from "@peculiar/utils/encoding";
|
|
2
|
+
import { fail } from "../schema";
|
|
3
|
+
import { deriveX25519PublicKey } from "./crypto";
|
|
4
|
+
|
|
5
|
+
function decodeKey(input: unknown, path: string): Uint8Array {
|
|
6
|
+
if (typeof input !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(input))
|
|
7
|
+
fail(path, "expected an unpadded 32-byte Base64url key");
|
|
8
|
+
const bytes = base64url.decode(input);
|
|
9
|
+
if (base64url.encode(bytes) !== input) fail(path, "expected an unpadded 32-byte Base64url key");
|
|
10
|
+
return bytes;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function validateRealityKeyPair(
|
|
14
|
+
{ privateKey, publicKey }: { privateKey?: unknown; publicKey?: unknown },
|
|
15
|
+
path: string,
|
|
16
|
+
): Promise<void> {
|
|
17
|
+
const privateBytes = decodeKey(privateKey, `${path}.privateKey`);
|
|
18
|
+
decodeKey(publicKey, `${path}.publicKey`);
|
|
19
|
+
if (base64url.encode(await deriveX25519PublicKey(privateBytes)) !== publicKey)
|
|
20
|
+
fail(`${path}.publicKey`, "does not match private key");
|
|
21
|
+
}
|
package/src/ip.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
const ipv4Octet = /^(?:0|[1-9][0-9]{0,2})$/;
|
|
2
|
+
const ipv6Group = /^[0-9a-f]{1,4}$/i;
|
|
3
|
+
const ipv6Zone = /^[0-9a-z.:-]+$/i;
|
|
4
|
+
const cidrPrefix = /^[0-9]+$/;
|
|
5
|
+
|
|
6
|
+
export function isIPv4(input: string): boolean {
|
|
7
|
+
const octets = input.split(".", 5);
|
|
8
|
+
return (
|
|
9
|
+
octets.length === 4 && octets.every((octet) => ipv4Octet.test(octet) && Number(octet) <= 255)
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function isIPv6(input: string): boolean {
|
|
14
|
+
const [address = "", zone, extraZone] = input.split("%", 3);
|
|
15
|
+
if (
|
|
16
|
+
!address.includes(":") ||
|
|
17
|
+
extraZone !== undefined ||
|
|
18
|
+
(zone !== undefined && !ipv6Zone.test(zone))
|
|
19
|
+
) {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const [head = "", tail, extra] = address.split("::", 3);
|
|
24
|
+
if (extra !== undefined) return false;
|
|
25
|
+
|
|
26
|
+
const groups = head ? head.split(":", 9) : [];
|
|
27
|
+
if (tail) groups.push(...tail.split(":", 9));
|
|
28
|
+
|
|
29
|
+
let groupCount = groups.length;
|
|
30
|
+
const last = groups.at(-1);
|
|
31
|
+
if (last?.includes(".")) {
|
|
32
|
+
if (tail === "" || !isIPv4(last)) return false;
|
|
33
|
+
groups.pop();
|
|
34
|
+
// An embedded IPv4 address occupies two 16-bit groups.
|
|
35
|
+
groupCount++;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return (
|
|
39
|
+
(tail === undefined ? groupCount === 8 : groupCount < 8) &&
|
|
40
|
+
groups.every((group) => ipv6Group.test(group))
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function isIP(input: string): 0 | 4 | 6 {
|
|
45
|
+
if (isIPv4(input)) return 4;
|
|
46
|
+
if (isIPv6(input)) return 6;
|
|
47
|
+
return 0;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isCIDR(input: string): boolean {
|
|
51
|
+
const [address = "", prefix, extra] = input.split("/", 3);
|
|
52
|
+
if (
|
|
53
|
+
prefix === undefined ||
|
|
54
|
+
extra !== undefined ||
|
|
55
|
+
address.includes("%") ||
|
|
56
|
+
!cidrPrefix.test(prefix)
|
|
57
|
+
) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const version = isIP(address);
|
|
62
|
+
return version !== 0 && Number(prefix) <= (version === 4 ? 32 : 128);
|
|
63
|
+
}
|
package/src/proxy-profile.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { createPrivateKey, createPublicKey } from "node:crypto";
|
|
2
1
|
import { inbound, outbound } from "./factories";
|
|
3
2
|
import type {
|
|
4
3
|
Hysteria2InboundRealm,
|
|
@@ -8,6 +7,7 @@ import type {
|
|
|
8
7
|
ShadowTLSHandshakeOptions,
|
|
9
8
|
V2RayTransport,
|
|
10
9
|
} from "./generated/sbkit-inputs";
|
|
10
|
+
import { validateRealityKeyPair } from "./internal/reality";
|
|
11
11
|
import { fieldsFrom, record, snapshot } from "./resource";
|
|
12
12
|
import type { Resource, SsmInbound } from "./resource";
|
|
13
13
|
import { fail, keyPath } from "./schema";
|
|
@@ -180,6 +180,9 @@ interface Profile<
|
|
|
180
180
|
type TransportInput<K extends TransportProtocol> = Direct & {
|
|
181
181
|
readonly users: Users;
|
|
182
182
|
} & TransportTls<K>;
|
|
183
|
+
type VlessInput = TransportInput<"vless">;
|
|
184
|
+
type VlessProfile<Input = unknown> = Profile<"vless", true, unknown, Input>;
|
|
185
|
+
type VlessProfileResult<Input = unknown> = VlessProfile<Input> | Promise<VlessProfile<Input>>;
|
|
183
186
|
type PlainInput = Direct & { readonly tls?: NormalTls | NoTls };
|
|
184
187
|
type RequiredTlsInput<K extends Protocol = Protocol> = Direct & {
|
|
185
188
|
readonly users: Users;
|
|
@@ -319,28 +322,6 @@ function usersFor(input: unknown, path: string): readonly User[] {
|
|
|
319
322
|
});
|
|
320
323
|
}
|
|
321
324
|
|
|
322
|
-
function realityKeys(input: unknown, path: string): Fields {
|
|
323
|
-
const keys = fieldsFrom(input, path, ["privateKey", "publicKey"], ["privateKey", "publicKey"]);
|
|
324
|
-
const { privateKey, publicKey } = keys;
|
|
325
|
-
for (const [key, value] of Object.entries(keys)) {
|
|
326
|
-
if (
|
|
327
|
-
typeof value !== "string" ||
|
|
328
|
-
!/^[A-Za-z0-9_-]{43}$/.test(value) ||
|
|
329
|
-
Buffer.from(value, "base64url").toString("base64url") !== value
|
|
330
|
-
)
|
|
331
|
-
fail(`${path}.${key}`, "expected an unpadded 32-byte Base64url key");
|
|
332
|
-
}
|
|
333
|
-
// The PKCS #8 prefix identifies a raw X25519 private key.
|
|
334
|
-
const der = Buffer.concat([
|
|
335
|
-
Buffer.from("302e020100300506032b656e04220420", "hex"),
|
|
336
|
-
Buffer.from(privateKey as string, "base64url"),
|
|
337
|
-
]);
|
|
338
|
-
const derived = createPublicKey(createPrivateKey({ key: der, format: "der", type: "pkcs8" }));
|
|
339
|
-
if (derived.export({ format: "jwk" }).x !== publicKey)
|
|
340
|
-
fail(`${path}.publicKey`, "does not match private key");
|
|
341
|
-
return keys;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
325
|
function tlsFor(kind: Protocol, input: unknown, needsTls: boolean, path: string) {
|
|
345
326
|
const { mode } = record(input ?? { mode: "none" }, path);
|
|
346
327
|
if (mode === "tls") {
|
|
@@ -385,7 +366,12 @@ function tlsFor(kind: Protocol, input: unknown, needsTls: boolean, path: string)
|
|
|
385
366
|
return {
|
|
386
367
|
mode,
|
|
387
368
|
serverName: fields.serverName,
|
|
388
|
-
keys:
|
|
369
|
+
keys: fieldsFrom(
|
|
370
|
+
fields.keyPair,
|
|
371
|
+
`${path}.keyPair`,
|
|
372
|
+
["privateKey", "publicKey"],
|
|
373
|
+
["privateKey", "publicKey"],
|
|
374
|
+
),
|
|
389
375
|
ids: ids as string[],
|
|
390
376
|
handshake: { ...dial, ...connection({ host, port }, `${path}.handshake`) },
|
|
391
377
|
} as const;
|
|
@@ -488,12 +474,19 @@ function protocolOptions(
|
|
|
488
474
|
return { serverFields, clientFields };
|
|
489
475
|
}
|
|
490
476
|
|
|
477
|
+
function makeProfile<
|
|
478
|
+
K extends Exclude<Protocol, "vless">,
|
|
479
|
+
Authenticated extends boolean,
|
|
480
|
+
ExtraInbound = unknown,
|
|
481
|
+
Input = unknown,
|
|
482
|
+
>(kind: K, input: unknown): Profile<K, Authenticated, ExtraInbound, Input>;
|
|
483
|
+
function makeProfile(kind: "vless", input: unknown): VlessProfileResult;
|
|
491
484
|
function makeProfile<
|
|
492
485
|
K extends Protocol,
|
|
493
486
|
Authenticated extends boolean,
|
|
494
487
|
ExtraInbound = unknown,
|
|
495
488
|
Input = unknown,
|
|
496
|
-
>(kind: K, input: unknown)
|
|
489
|
+
>(kind: K, input: unknown) {
|
|
497
490
|
const path = `proxyProfile.${kind}`;
|
|
498
491
|
const sharedKey = Object.hasOwn(sharedOption, kind)
|
|
499
492
|
? sharedOption[kind as keyof typeof sharedOption]
|
|
@@ -722,7 +715,15 @@ function makeProfile<
|
|
|
722
715
|
return applyTls(builder, local, location, true);
|
|
723
716
|
},
|
|
724
717
|
};
|
|
725
|
-
|
|
718
|
+
const result = Object.freeze(profile) as unknown as Profile<
|
|
719
|
+
K,
|
|
720
|
+
Authenticated,
|
|
721
|
+
ExtraInbound,
|
|
722
|
+
Input
|
|
723
|
+
>;
|
|
724
|
+
if (tls.mode === "reality")
|
|
725
|
+
return validateRealityKeyPair(tls.keys, `${path}.tls.keyPair`).then(() => result);
|
|
726
|
+
return result;
|
|
726
727
|
}
|
|
727
728
|
|
|
728
729
|
function requiredString(input: unknown, path: string): string {
|
|
@@ -797,7 +798,7 @@ function shadowsocks(input: ShadowsocksInput) {
|
|
|
797
798
|
return makeProfile<"shadowsocks", boolean>("shadowsocks", input);
|
|
798
799
|
}
|
|
799
800
|
|
|
800
|
-
function transportProfile<K extends TransportProtocol
|
|
801
|
+
function transportProfile<K extends Exclude<TransportProtocol, "vless">>(kind: K) {
|
|
801
802
|
function create<const Transport extends TransportKind>(
|
|
802
803
|
input: TransportInput<K> & TransportSelection<Transport>,
|
|
803
804
|
): Profile<K, true, unknown, TransportSelection<Transport>>;
|
|
@@ -808,6 +809,27 @@ function transportProfile<K extends TransportProtocol>(kind: K) {
|
|
|
808
809
|
return create;
|
|
809
810
|
}
|
|
810
811
|
|
|
812
|
+
async function vlessReality(input: VlessInput): Promise<VlessProfile> {
|
|
813
|
+
return makeProfile("vless", input);
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
function vless<const Transport extends TransportKind>(
|
|
817
|
+
input: VlessInput & TransportSelection<Transport> & { readonly tls: RealityTls },
|
|
818
|
+
): Promise<VlessProfile<TransportSelection<Transport>>>;
|
|
819
|
+
function vless<const Transport extends TransportKind>(
|
|
820
|
+
input: VlessInput & TransportSelection<Transport> & { readonly tls?: NormalTls | NoTls },
|
|
821
|
+
): VlessProfile<TransportSelection<Transport>>;
|
|
822
|
+
function vless<const Transport extends TransportKind>(
|
|
823
|
+
input: VlessInput & TransportSelection<Transport>,
|
|
824
|
+
): VlessProfileResult<TransportSelection<Transport>>;
|
|
825
|
+
function vless(input: VlessInput & { readonly tls: RealityTls }): Promise<VlessProfile>;
|
|
826
|
+
function vless(input: VlessInput & { readonly tls?: NormalTls | NoTls }): VlessProfile;
|
|
827
|
+
function vless(input: VlessInput): VlessProfileResult;
|
|
828
|
+
function vless(input: VlessInput) {
|
|
829
|
+
if (input?.tls?.mode === "reality") return vlessReality(input);
|
|
830
|
+
return makeProfile("vless", input);
|
|
831
|
+
}
|
|
832
|
+
|
|
811
833
|
export const proxyProfile = Object.freeze({
|
|
812
834
|
anytls: (input: RequiredTlsInput) => makeProfile<"anytls", true>("anytls", input),
|
|
813
835
|
http,
|
|
@@ -820,6 +842,6 @@ export const proxyProfile = Object.freeze({
|
|
|
820
842
|
socks,
|
|
821
843
|
trojan: transportProfile("trojan"),
|
|
822
844
|
tuic: (input: RequiredTlsInput) => makeProfile<"tuic", true>("tuic", input),
|
|
823
|
-
vless
|
|
845
|
+
vless,
|
|
824
846
|
vmess: transportProfile("vmess"),
|
|
825
847
|
});
|
package/src/rules.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { isIP } from "node:net";
|
|
2
1
|
import type { SBKitInputs } from "./generated/sbkit-inputs";
|
|
3
2
|
import { ruleActionSchemas, ruleMatchSchema } from "./input-schema";
|
|
3
|
+
import { isCIDR, isIP } from "./ip";
|
|
4
4
|
import { fieldsFrom, preserveIdentity, record, resourceData, snapshot } from "./resource";
|
|
5
5
|
import type { Resolve } from "./resource";
|
|
6
6
|
import { checkSchema, compileSchema, durationNanoseconds, fail, keyPath } from "./schema";
|
|
@@ -162,25 +162,17 @@ function actionsFor(scope: Scope) {
|
|
|
162
162
|
|
|
163
163
|
const actions = { route: actionsFor("route"), dns: actionsFor("dns") };
|
|
164
164
|
|
|
165
|
-
function validSubnet(input: string): boolean {
|
|
166
|
-
const [address = "", prefix, ...extra] = input.split("/");
|
|
167
|
-
const version = isIP(address);
|
|
168
|
-
return (
|
|
169
|
-
version !== 0 &&
|
|
170
|
-
!address.includes("%") &&
|
|
171
|
-
extra.length === 0 &&
|
|
172
|
-
(prefix === undefined || (/^\d+$/.test(prefix) && Number(prefix) <= (version === 4 ? 32 : 128)))
|
|
173
|
-
);
|
|
174
|
-
}
|
|
175
|
-
|
|
176
165
|
function checkAction(fields: Fields, path: string, scope: Scope): void {
|
|
177
166
|
if (fields.method === "drop" && fields.no_drop === true)
|
|
178
167
|
fail(`${path}.no_drop`, "no_drop with drop");
|
|
179
168
|
if (fields.client_subnet !== undefined) {
|
|
180
169
|
if (fields.remove_client_subnet === true)
|
|
181
170
|
fail(`${path}.client_subnet`, "client_subnet with remove_client_subnet");
|
|
182
|
-
|
|
183
|
-
|
|
171
|
+
const subnet = fields.client_subnet as string;
|
|
172
|
+
const valid = subnet.includes("/")
|
|
173
|
+
? isCIDR(subnet)
|
|
174
|
+
: !subnet.includes("%") && isIP(subnet) !== 0;
|
|
175
|
+
if (!valid) fail(`${path}.client_subnet`, "invalid subnet");
|
|
184
176
|
}
|
|
185
177
|
if (
|
|
186
178
|
scope === "dns" &&
|