Network
Framework network helpers — DNS-over-HTTPS dispatch, TLS configuration, OCSP/CT validation, NTP/NTS-KE bootstrap.
b.network is the umbrella facade over the framework's outbound- network surface: DNS (default DoH on, optional DoT, lookup cache with TTL bound), TLS trust store (CA bundle / system trust / ignored-cert opt-in), proxy resolution from HTTP_PROXY / HTTPS_PROXY / NO_PROXY, NTP / NTS-KE drift checks, SMTP policy (MTA-STS / DANE / TLS-RPT), heartbeat watchdog, byte quota, SSRF allowlist, and socket-level defaults (TCP_NODELAY / SO_KEEPALIVE).
bootFromEnv reads BLAMEJS_* environment variables once at startup and applies the union to the live facade — operators wire it from a process-supervisor's env without touching code. snapshot returns a redacted view of the current configuration for the operations dashboard. applyToSocket is the per-socket tuning hook for primitives building their own server (tls, wsServer, etc.).
b.network.dns.dane.matchCertificate(opts) #
{
{
tlsa: [ { usage, selector, matchingType, data: Buffer|hex } ], // the TLSA RRset
certificate: Buffer, // leaf certificate (DER)
chain?: Buffer[], // intermediate / CA certs (DER), for TA usages
}
}
Match a server certificate against a set of (DNSSEC-verified) TLSA records (RFC 6698 / 7671). For each record the selected data — the full certificate DER (selector 0) or its subjectPublicKeyInfo (selector 1) — is hashed per the matching type (exact / SHA-256 / SHA-512) and compared, constant-time, to the record's association data. End-entity usages (PKIX-EE 1, DANE-EE 3) are matched against the leaf certificate; trust-anchor usages (PKIX-TA 0, DANE-TA 2) are matched against the leaf and any supplied chain.
Returns the matching record plus what the caller must still do: a DANE-EE match is self-sufficient (the TLSA pins the key); a DANE-TA match still needs chain-to-anchor verification; PKIX usages still need full PKIX validation. Throws dane/no-match if nothing matches. Throws dane/compromised-key when the leaf certificate carries a key that b.crypto.compromisedKey reports, or when every match is a trust anchor that carries one or that the leaf reaches only through a supplied chain certificate that carries one. A trust-anchor match does not validate the path to the anchor; the path is searched only when another supplied chain certificate carries a compromised key or a key that cannot be judged, once per anchor per call. Selector 1 hashes the subjectPublicKeyInfo DER of the key node:crypto loads from the certificate. For a key that node:crypto cannot load, such as a composite ML-DSA key, it hashes the subjectPublicKeyInfo bytes the certificate carries. A certificate that does not parse, or whose key cannot be judged, throws dane/bad-certificate. Malformed options throw dane/bad-arg, dane/bad-tlsa, dane/bad-bytes, dane/unsupported-usage, dane/unsupported-selector or dane/unsupported-matching. Verify the TLSA RRset with b.network.dns.dnssec before trusting the records — an unauthenticated TLSA proves nothing.
var r = b.network.dns.dane.matchCertificate({ tlsa: records, certificate: leafDer });
// → { ok: true, matched: { usage: 3, selector: 1, matchingType: 1 }, daneAuthenticated: true, pkixRequired: false }
b.network.dns.resolver.create(opts?) #
{
profile: "strict" | "balanced" | "permissive",
posture: "hipaa" | "pci-dss" | "gdpr" | "soc2",
maxTtlMs: number, // cap any TTL from upstream; default 24h
minTtlMs: number, // floor short-TTL records; default 60s
serveStale: number | false, // ms to retain expired entries; default 6h
timeoutMs: number, // per-query upstream deadline; default 10s
transport: { lookup(name, qtype) → Promise }, // operator override
audit: b.audit namespace,
}
Build a resolver instance with the given options. Returns an instance with .query(name, type, opts) → Promise<{ rrs, ttl, fromCache, stale, validated, response }> plus per-type shortcuts.
create throws resolver/bad-profile for an unknown profile, resolver/bad-transport for a transport without a lookup function, and resolver/bad-input for a non-positive timeoutMs or maxTtlMs, a negative minTtlMs or serveStale, or a maxCacheEntries that is not a positive integer.
A query rejects with resolver/bad-input for an empty name, an unknown type or a name that is not host-shaped, resolver/bad-opt when validate is not a boolean, resolver/nxdomain when the name does not exist, resolver/server-failure for a SERVFAIL or REFUSED reply, resolver/query-failed for any other non-zero RCODE, and resolver/validate-failed when validate: true meets an answer without the AD bit.
A transport failure rejects with one of these codes:
- resolver/upstream-timeout when the transport does not answer within timeoutMs, or rejects with dns/lookup-timeout from b.network.dns. - resolver/server-failure when the transport rejects with dns/server-failure from b.network.dns. - resolver/upstream-connection-failed when the connection to the server fails, for example ECONNREFUSED or ECONNRESET, or when the transport rejects with any other error whose transient is true. - resolver/upstream-http when the DoH server answers HTTP 429 or a 5xx status, and resolver/upstream-rejected when it answers any other status that is not 200, for example 403 or 404. Both carry the status as err.statusCode, and a transport error that carries a numeric statusCode is classified the same way. - resolver/upstream-too-large when the DoH reply is larger than 64 KiB. - resolver/upstream-failed for any other transport error, for example a certificate the connection does not accept, or a TypeError from an operator transport. A transport that rejects with a ResolverError keeps that error's code.
A query sent through the default DoH transport to a server whose certificate chain carries a compromised key rejects with resolver/compromised-key, and one whose chain reaches no trust anchor of the connection (see b.network.tls.applyToContext) rejects with resolver/upstream-failed. When the DoH endpoint has no ca, a certificate in Node's default CA store whose key is compromised is not trusted, so a server whose chain ends at it rejects with resolver/upstream-failed. A reply that cannot be parsed rejects with the safe-dns error code that b.safeDns.parseResponse throws. When the transport fails, the reply cannot be parsed, or the reply is SERVFAIL or REFUSED, and a cached answer is within the serveStale window, the query returns that cached answer marked stale.
resolver/server-failure, resolver/upstream-timeout, resolver/upstream-connection-failed and resolver/upstream-http are transient (err.permanent === false), so b.retry retries them. Every other resolver/* code is permanent.
Domain names in rrs (each name, and the CNAME / NS / PTR / MX / SRV / SOA targets in decoded) are in the RFC 1035 §5.1 presentation form that b.safeDns.parseResponse returns: a dot or backslash inside a label is escaped, and a label byte outside 0x21-0x7E is written as \DDD. A hostname made of letters, digits, hyphens and underscores is returned unchanged. followCnames refuses a target that carries an escape with resolver/bad-input.
var resolver = b.network.dns.resolver.create({ profile: "strict" });
var r = await resolver.queryTxt("_dmarc.example.com");
console.log(r.rrs.map(function (rr) { return rr.decoded.join(""); }));
b.network.dns.resolver.followCnames(name, type, opts?) #
{
validate: boolean, // per-call: refuse if upstream AD=0
}
Walk CNAME redirections until the target record arrives or the chain depth cap from b.safeDns trips. Returns the same shape as query() plus chain: [name, name, ...] listing each hop.
var r = await resolver.followCnames("alias.example.com", "A");
console.log(r.chain, r.rrs.map(function (rr) { return rr.decoded; }));
b.network.dns.resolver.resolveTxt(qname, dnsLookup?, resolver?) #
Resolve TXT records for qname via the operator's dnsLookup(qname, "TXT") override when supplied, otherwise the framework's shared validating (DoH / DoT / system, DNSSEC-checked) resolver — normalized to the string[][] shape dnsPromises.resolveTxt returns. Throws an ENODATA Error when no TXT records exist.
This is the secure DNS path for every email-auth policy lookup (DMARC / DKIM / ARC / BIMI / MTA-STS / TLS-RPT). Plaintext system DNS (dnsPromises.resolveTxt) is spoofable — DNS cache-poisoning / Kaminsky-class — and must NOT be used for records a downgrade or redirect would exploit.
Pass resolver (a b.network.dns.resolver.create() instance) to reshape TXT records off a caller-owned resolver instead of the shared one — the mail-auth and mail-dkim modules use this so their TXT lookups share the same resolver (and cache) they use for A / MX / PTR, instead of each re-rolling the reshape.
// requires: outbound DNS (DoH/DoT) to resolve the name below
var rrs = await b.network.dns.resolver.resolveTxt("_dmarc.example.com");
// → [ ["v=DMARC1; p=reject"] ]
b.network.dns.resolver.safeResolveTxt(qname, opts?) #
{
dnsLookup: function, // operator override (qname, "TXT") => string[][]
errorFactory: function, // (code, message) => Error, thrown on non-absence failures
code: string, // error code passed to errorFactory
}
resolveTxt wrapped with the email-auth policy-fetch convention: a domain with no record (ENOTFOUND / ENODATA) returns null (absence is not an error); any other failure throws the caller's typed error via errorFactory(code, message) so each protocol keeps its own error class. The same secure resolver path as resolveTxt — never plaintext system DNS.
// requires: outbound DNS (DoH/DoT) to resolve the name below
var rrs = await b.network.dns.resolver.safeResolveTxt("_mta-sts.example.com", {
errorFactory: function (code, msg) { return new SmtpPolicyError(code, msg); },
code: "smtp/mta-sts-txt-lookup-failed",
});
if (rrs === null) return null; // no MTA-STS record published
b.network.dns.setCacheTtlBounds(opts?) #
{
minMs: number, // default: 0
maxMs: number, // default: 300000 (5 minutes)
negativeMs: number, // default: 0
}
Caches each b.network.dns.lookup answer for the TTL the DNS answer carries, held between minMs and maxMs. This is the default: with no call, an answer is cached for its TTL up to 5 minutes, and an answer with TTL 0 is not cached. The TTL is the smallest TTL among the answer's records, CNAME records included. A lookup that goes through the system resolver (the resolver chosen by useSystemResolver, and every name that is local-form such as localhost) has no TTL to read, so its answer is cached only under setCacheTtlMs.
setCacheTtlMs(ms) replaces the answer TTL with a fixed time, and setCacheTtlMs(0) turns the cache off; calling setCacheTtlBounds again goes back to the answer TTL and empties the cache.
A failed lookup is cached for negativeMs (default 0, not cached). A transient failure (a SERVFAIL or REFUSED reply, which rejects with dns/server-failure, a timeout, or a transport error) is never cached, so the next lookup asks the resolver again.
Throws dns/bad-cache-ttl when an option is not a non-negative finite number or minMs is greater than maxMs, and dns/bad-opt for an option that is not listed below.
var b = require("@blamejs/core");
b.network.dns.setCacheTtlBounds({ minMs: 1000, maxMs: 60000 });
b.network.dns.querySvcb(name, opts?) #
{
{
transport: "doh" | "dot" | "system",
}
}
Query SVCB records (RFC 9460 §2) for name. Returns an array of { priority, target, params } records sorted by priority. AliasMode records (priority === 0) carry a target and empty params — the caller chases the alias by re-querying the target. ServiceMode records (priority > 0) carry SvcParams: alpn / port / ipv4hint / ipv6hint / ech / mandatory / dohpath. Unknown SvcParamKeys surface under params.unknown[key] as raw bytes — operators implementing forward-compat can still read them. Malformed rdata throws DnsError with code dns/svcb-malformed.
Resolving the query raises every refusal that step can make: dns/bad-host for a name that is not host-shaped, dns/bad-transport for a transport outside the three above, dns/transport-unavailable when the chosen transport is not configured, dns/no-system-resolvers when the system has none, dns/bad-reply for a reply it cannot parse, and dns/no-result when the name does not exist (NXDOMAIN). A SERVFAIL or REFUSED reply rejects with dns/server-failure, which is transient (err.permanent === false), and any other non-zero RCODE (FORMERR, NOTIMP) with the permanent dns/query-failed. dns/unsupported-type, dns/wrong-family and dns/resolve-failed are raised by b.network.dns.resolve and by the protocol resolver, neither of which this query goes through.
The transport rejects rather than throwing, so these arrive as a rejected promise: dns/doh-failed for a DoH request that errors, dns/doh-http for a non-2xx DoH reply, dns/doh-too-large for a DoH body over 256 KiB, dns/dot-handshake-failed and dns/dot-failed for a DoT session that cannot start or that errors, dns/system-failed for a system-resolver query that errors, and dns/lookup-timeout when the lookup exceeds its budget. A DoH or DoT server whose certificate chain carries a compromised key fails the query with dns/compromised-key. When the resolver has no ca, the DoH or DoT connection does not trust a certificate in Node's default CA store whose key is compromised (one added through NODE_EXTRA_CA_CERTS, for example), so a server whose chain ends at that certificate fails certificate verification with dns/doh-failed or dns/dot-handshake-failed. A DoH or DoT server whose chain reaches no trust anchor of the connection (see b.network.tls.applyToContext) fails with dns/doh-failed or dns/dot-handshake-failed as well. DoH requests go through Node's environment proxy (HTTPS_PROXY and NO_PROXY) when NODE_USE_ENV_PROXY or --use-env-proxy is set. Without that proxy, DoH queries offer HTTP/2 and, when the DoH server accepts it, share one HTTP/2 connection that stays open for 2 minutes after its last query; a DoH server that answers only HTTP/1.1 gets a new connection for each query. A query sent on that shared connection also sends an HTTP/2 PING. When neither the PING acknowledgment nor the response arrives within half the lookup timeout (at most 2 seconds), or the server closes the connection or sends GOAWAY before the response headers arrive, the connection is closed and the query is sent once more on a new connection. When the server resets the query's stream on a connection that is still open, the query is sent once more on the same connection, and a second reset rejects with dns/doh-failed. After a GOAWAY, the connection is closed once its open queries finish. A connection on which a query timed out before its response headers arrived is not used for later queries.
// requires: outbound DNS to resolve the name below
var b = require("@blamejs/core");
var rrs = await b.network.dns.querySvcb("_443._wss.example.com");
b.network.dns.queryHttps(name, opts?) #
{
{
transport: "doh" | "dot" | "system",
}
}
Query HTTPS records (RFC 9460 §9). Identical to querySvcb except the QTYPE is HTTPS (65) — the user-agent-facing variant of SVCB for https:// origins. Browsers query this for ECH discovery and h3 advertisement; servers can call it to validate their own published HTTPS RRset. Returns the same shape as querySvcb.
// requires: outbound DNS to resolve the name below
var b = require("@blamejs/core");
var rrs = await b.network.dns.queryHttps("example.com");
b.network.dns.discoverEncrypted(opts?) #
{
{
name: string,
insecureSystemResolverOnly: boolean,
}
}
RFC 9462 Discovery of Designated Resolvers. Queries _dns.resolver.arpa for SVCB records that advertise encrypted DNS alternatives (DoH / DoT) hosted by the network's currently-configured Do53 resolver. Returns a list of resolver descriptors with { transport, alpn, target, port, dohpath, ipv4hint, ipv6hint, priority }.
The discovery query goes through the system resolver by default (RFC 9462 §4 — DDR validation requires the response to come from the Do53 resolver whose IP we compare). Callers that already have a trusted DoH / DoT transport configured can pass { insecureSystemResolverOnly: false } to allow DDR via the encrypted transport too.
Throws DnsError with code dns/ddr-not-discovered when the resolver does not publish DDR records. A resolver that answers the DDR query with NXDOMAIN, an empty answer, REFUSED, NOTIMP, FORMERR or any other non-zero RCODE except SERVFAIL also rejects with dns/ddr-not-discovered. A SERVFAIL reply rejects with dns/server-failure. Both codes are transient (err.permanent === false). The call throws dns/bad-host when name is not a non-empty host-shaped string, and dns/bad-opt when insecureSystemResolverOnly is not a boolean, so a caller that meant to widen the discovery is refused rather than kept on the narrow path.
The underlying SVCB query raises its own refusals through this call: dns/bad-transport, dns/transport-unavailable, dns/no-system-resolvers, dns/bad-reply, dns/svcb-malformed and dns/server-failure for a SERVFAIL reply. Its dns/no-result and dns/query-failed, and its dns/server-failure for a REFUSED reply, do NOT reach the caller: this primitive translates them to dns/ddr-not-discovered. dns/unsupported-type, dns/wrong-family and dns/resolve-failed are raised by b.network.dns.resolve and by the protocol resolver, neither of which this call goes through.
The transport's own failures arrive as a rejected promise here too: dns/doh-failed, dns/doh-http, dns/doh-too-large, dns/dot-handshake-failed, dns/dot-failed, dns/system-failed, dns/lookup-timeout and dns/compromised-key, each as described on b.network.dns.querySvcb.
var b = require("@blamejs/core");
var resolvers = await b.network.dns.discoverEncrypted();
b.network.dns.useDesignatedResolvers(list) #
RFC 9463 Discovery of Network-designated Resolvers. The framework doesn't run a DHCP / IPv6 RA client itself; an operator-side agent (or the output of discoverEncrypted()) supplies the resolver list and the framework swaps its transport over to the lowest-priority entry. Items are tried in order: the first one that successfully configures (DoH useDnsOverHttps, DoT useDnsOverTls) wins.
Each entry shape:
{ transport: "doh" | "dot", url: string, host: string, port: number, servername: string, alpn: Array
Throws DnsError with code dns/dnr-no-resolvers if list is empty, and dns/dnr-malformed if an entry is missing its required transport-specific fields.
Each accepted entry is then configured as a resolver, which validates it: dns/bad-doh-url, dns/bad-doh-method, dns/bad-doh-provider and dns/bad-doh-ca for a DoH entry, and dns/bad-dot-host, dns/bad-dot-port, dns/bad-dot-servername and dns/bad-dot-ca for a DoT entry, and dns/compromised-key for either when its ca holds a certificate with a compromised key. A list that is well-formed but whose entries do not configure is refused rather than partially applied.
var b = require("@blamejs/core");
var found = await b.network.dns.discoverEncrypted();
b.network.dns.useDesignatedResolvers(found.map(function (r) {
return r.transport === "doh"
? { transport: "doh", url: "https://" + r.target + (r.dohpath || "/dns-query") }
: { transport: "dot", host: r.target, port: r.port, servername: r.target };
}));
b.network.dns.resolve4(host, opts?) #
{
transport: undefined, // "doh" | "dot" | "system"; default: the configured transport
}
Resolves the A records of host and returns their addresses as strings, in the order the answer carries them. An IPv4 literal is returned as it is. The query goes over DNS-over-HTTPS or DNS-over-TLS when one is configured, and otherwise through the system resolver; opts.transport picks one.
host is checked before any query is sent, on every transport. A name that contains a NUL or another control byte, a URL delimiter, an empty label, or exceeds the RFC 1035 lengths rejects with dns/bad-host, as does a missing host. On Node.js before 24.22.1 the system resolver would otherwise query the part of "a.example\0.b.example" before the NUL.
Other rejections: dns/wrong-family for an IPv6 literal, dns/bad-transport for an unknown opts.transport, dns/transport-unavailable when the requested transport is not configured, dns/no-result for a name that does not exist (NXDOMAIN) or has no A records, dns/lookup-timeout past the lookup deadline, and dns/resolve-failed when the system resolver fails without a DNS response code. On every transport, a SERVFAIL or REFUSED reply rejects with dns/server-failure, which is transient (err.permanent === false), and any other non-zero RCODE with the permanent dns/query-failed. These errors and an NXDOMAIN dns/no-result carry the response code as err.rcode. Over DoH, dns/doh-failed rejects a request that errors, dns/doh-http a non-2xx reply and dns/doh-too-large a body over 256 KiB; over DoT, dns/dot-failed rejects a session that errors. dns/bad-reply rejects a reply that cannot be parsed, and dns/compromised-key a DoH or DoT server whose certificate chain carries a compromised key.
// requires: a resolver that can reach the public DNS
var addrs = await b.network.dns.resolve4("example.com");
// → [ "192.0.2.10" ]
b.network.dns.resolve6(host, opts?) #
{
transport: undefined, // "doh" | "dot" | "system"; default: the configured transport
}
Resolves the AAAA records of host and returns their addresses as strings. An IPv6 literal is returned as it is. Transport choice and the rejections are those of b.network.dns.resolve4: a host that is not a DNS name (a NUL or other control byte, a URL delimiter, an empty label, RFC 1035 lengths) rejects with dns/bad-host before any query is sent, an IPv4 literal with dns/wrong-family, and an unknown transport with dns/bad-transport; dns/transport-unavailable, dns/no-result, dns/server-failure, dns/query-failed, dns/lookup-timeout, dns/resolve-failed, dns/doh-failed, dns/doh-http, dns/doh-too-large, dns/dot-failed, dns/bad-reply and dns/compromised-key follow the same rules.
// requires: a resolver that can reach the public DNS
var addrs = await b.network.dns.resolve6("example.com");
// → [ "2001:db8::10" ]
b.network.dns.resolveAaaa(host, opts?) #
{
transport: undefined, // "doh" | "dot" | "system"; default: the configured transport
}
Another name for b.network.dns.resolve6, with the same transport choice and the same rejections: dns/bad-host before any query for a host that is not a DNS name, dns/wrong-family, dns/bad-transport, dns/transport-unavailable, dns/no-result, dns/server-failure, dns/query-failed, dns/lookup-timeout, dns/resolve-failed, dns/doh-failed, dns/doh-http, dns/doh-too-large, dns/dot-failed, dns/bad-reply and dns/compromised-key.
// requires: a resolver that can reach the public DNS
var addrs = await b.network.dns.resolveAaaa("example.com");
// → [ "2001:db8::10" ]
b.network.dns.resolve(host, type?, opts?) #
{
transport: undefined, // "doh" | "dot" | "system"; default: the configured transport
}
Resolves host for one record type. "A" (the default) and "AAAA" return the addresses b.network.dns.resolve4 and b.network.dns.resolve6 return, and "SVCB" and "HTTPS" return the parsed records of b.network.dns.querySvcb and b.network.dns.queryHttps. The type is matched without regard to case; any other type, or a type that is not a string, rejects with dns/unsupported-type.
Every type checks host before any query is sent: a name with a NUL or other control byte, a URL delimiter, an empty label, or over the RFC 1035 lengths rejects with dns/bad-host. The other rejections are those of the primitive the type dispatches to: dns/wrong-family, dns/bad-transport, dns/transport-unavailable, dns/no-result, dns/server-failure (a SERVFAIL or REFUSED reply, transient), dns/query-failed, dns/lookup-timeout, dns/resolve-failed, dns/doh-failed, dns/doh-http, dns/doh-too-large, dns/dot-failed, dns/bad-reply and dns/compromised-key, plus dns/no-system-resolvers, dns/system-failed and dns/svcb-malformed for "SVCB" and "HTTPS".
// requires: a resolver that can reach the public DNS
var addrs = await b.network.dns.resolve("example.com", "AAAA");
// → [ "2001:db8::10" ]
b.network.dns.reverse(ip) #
Looks up the PTR names of an IPv4 or IPv6 address through the system resolver and returns them in the order the answer carries them, or an empty array when there are none. ip must be an IP literal: anything else, including a string with a NUL or other byte after the address, rejects with dns/bad-ip before any query is sent. dns/lookup-timeout rejects past the lookup deadline and dns/reverse-failed when the resolver fails.
// requires: a resolver that can reach the public DNS
var names = await b.network.dns.reverse("192.0.2.5");
// → [ "host.example.net" ]
b.network.dns.isNullMx(mxRecords) #
RFC 7505 Null-MX check — returns true when the supplied MX records signal "this domain does not accept email" (a single MX record with priority 0 and exchange .). Operators sending mail call this before delivery to skip domains that have explicitly opted out of email. Returns false for any other shape (zero records, multiple records, non-zero priority, non-. exchange).
MX records are expected in the { priority, exchange } shape returned by node:dns.resolveMx (or b.network.dns.resolve(host, "MX")). Operator supplies the records; this is a pure classifier, no network call.
var node = require("node:dns/promises");
var mx;
try { mx = await node.resolveMx("example.com"); }
catch (e) { mx = []; }
var acceptsMail = !b.network.dns.isNullMx(mx);
// → false when the domain publishes Null-MX (RFC 7505): refuse to send
// rather than queue mail that can never be delivered
b.network.dns.classifyDnskeyAlgorithm(algorithm) #
Classify a DNSKEY / RRSIG algorithm number against the IANA DNS Security Algorithm Numbers registry, flagging SHA-1-based and other deprecated algorithms per RFC 9905 (Deprecating DNSSEC SHA-1 Usage), RFC 9904 (Algorithm Implementation Requirements, which obsoletes RFC 8624), and RFC 6725 (RSAMD5 deprecation).
deprecated answers "should this still be accepted", so it follows the VALIDATION requirement. Where a spelling differs between signing and validation — RSASHA512 is NOT RECOMMENDED to sign with but MUST still validate — the reason names both, since one boolean cannot.
Returns { algorithm, name, deprecated, reason, known } for any IANA-assigned number; known: false for unassigned numbers (operators decide whether unassigned == deprecated for their threat model). Returns null for non-integer / non-finite input. The registry's Reserved range 123-251 is reported as { name: "Reserved", deprecated: true, known: true }. Algorithm 0 (DELETE) is the CDS / CDNSKEY delete signal of RFC 8078 and is reported as deprecated, since nothing signs or validates with it.
Operators auditing inbound DNSSEC chain-of-trust evidence call this on each link's algorithm number and refuse the validation when deprecated === true. Defensive request-shape reader — never throws.
var v = b.network.dns.classifyDnskeyAlgorithm(5);
// → { algorithm: 5, name: "RSASHA1", deprecated: true,
// reason: "SHA-1 deprecated (RFC 9905 §3)", known: true }
var refused = v && v.deprecated ? "refuse DNSSEC algo " + v.name : null;
// → "refuse DNSSEC algo RSASHA1" — the classifier reports, the caller decides
b.network.dns.classifyDnskeyAlgorithm(13);
// → { algorithm: 13, name: "ECDSAP256SHA256", deprecated: false, ... }
b.network.dns.classifyDsDigestType(digestType) #
Classify a DS-record digest type against the IANA DNSSEC Delegation Signer (DS) Resource Record (RR) Type Digest Algorithms registry, flagging SHA-1 (digest type 1) as deprecated per RFC 9905 §4.
Returns { digestType, name, deprecated, reason, known } for any IANA-assigned number; null for non-integer input. The registry's Reserved range 128-252 is reported as { name: "Reserved", deprecated: true, known: true } and 253-254 as { name: "Private Use", deprecated: false, known: true } (RFC 9904). Other numbers report known: false.
var v = b.network.dns.classifyDsDigestType(1);
// → { digestType: 1, name: "SHA-1", deprecated: true,
// reason: "SHA-1 deprecated (RFC 9905 §4)", known: true }
b.network.dns.classifyDsDigestType(2);
// → { digestType: 2, name: "SHA-256", deprecated: false, ... }
b.network.dns.dnssec.keyTag(dnskeyRdata) #
Compute the RFC 4034 Appendix B key tag of a DNSKEY from its full RDATA (flags || protocol || algorithm || public key) — the 16-bit identifier an RRSIG / DS references to select the signing key.
var tag = b.network.dns.dnssec.keyTag(dnskeyRdata);
b.network.dns.dnssec.verifyDs(opts) #
{
{
ownerName: string, // the child zone name (the DNSKEY owner)
dnskeyRdata: Buffer, // full DNSKEY RDATA (flags||protocol||alg||publicKey)
ds: { keyTag, algorithm, digestType, digest: Buffer }, // the parent DS
}
}
Verify a DS (Delegation Signer) record against a child DNSKEY — the link that lets a parent zone vouch for a child's key. The DS digest (SHA-256 / SHA-384) is recomputed over the owner name plus the DNSKEY RDATA and compared to the DS, with the key tag and algorithm checked.
A DS that matches a DNSKEY which b.crypto.compromisedKey reports, such as an ECDSA key whose private scalar is 1, throws dnssec/compromised-key. A DNSKEY whose algorithm this module does not verify is not checked for a compromised key. A missing DS throws dnssec/bad-ds, a digest type other than 2 or 4 throws dnssec/unsupported-digest, a key tag that differs from the DNSKEY's throws dnssec/keytag-mismatch, and a DS algorithm or digest that differs from the DNSKEY's throws dnssec/ds-mismatch. A non-Buffer RDATA or digest throws dnssec/bad-bytes, and an owner name that does not encode throws dnssec/bad-name.
b.network.dns.dnssec.verifyDs({ ownerName: "example.com", dnskeyRdata: ksk, ds: parentDs });
b.network.dns.dnssec.verifyRrset(opts) #
{
{
name: string, // owner name of the RRset
type: string|number, // RR type (e.g. "DNSKEY", "A")
class?: number, // default 1 (IN)
rdatas: Buffer[], // each record's wire-format RDATA
rrsig: { // the RRSIG covering the RRset
algorithm, labels, originalTtl, expiration, inception, keyTag,
signerName: string, signature: Buffer,
},
dnskey: { algorithm, publicKey: Buffer }, // the signing DNSKEY (publicKey = bytes after flags/proto/alg)
at?: Date, // validity instant (default now); must be a valid Date
}
}
Verify an RRSIG over an RRset against a DNSKEY (RFC 4035 §5.3). The signed data is reconstructed in canonical form — the RRSIG RDATA without the signature, then the RRset's records ordered by canonical RDATA with the RRSIG Original TTL — and the signature is verified with the DNSKEY (RSA/SHA-256, ECDSA P-256/384, Ed25519). The signature's inception / expiration window is enforced against opts.at. RR types carrying embedded domain names are refused (dnssec/uncanonicalizable-type) rather than mis-validated. A DNSKEY that b.crypto.compromisedKey reports, such as an ECDSA key whose private scalar is 1, throws dnssec/compromised-key.
name and rrsig.signerName are read in RFC 1035 §5.1 presentation form, the form b.safeDns.parseResponse returns: \. is a dot inside a label, \\ a backslash, and \DDD the byte with that decimal value. A name with an empty or over-long label, a malformed escape, or more than 255 octets throws dnssec/bad-name.
b.network.dns.dnssec.verifyRrset({ name: "example.com", type: "DNSKEY", rdatas: keys, rrsig: sig, dnskey: ksk });
b.network.dns.dnssec.nsec3Hash(name, opts) #
{
{
salt: Buffer, // zone NSEC3 salt (may be empty)
iterations: number, // additional hash iterations (>= 0)
}
}
Compute the RFC 5155 §5 NSEC3 hash of a name — iterated SHA-1 over the canonical (lowercased, root-terminated) wire form with the zone's salt. The result is the unencoded hash; the NSEC3 owner label is its base32hex encoding. SHA-1 is the only hash IANA registers for NSEC3, so this is a wire-protocol constant, not a cryptographic default.
name is read in RFC 1035 §5.1 presentation form, as b.network.dns.dnssec.verifyRrset describes, and a name it cannot read throws dnssec/bad-name.
var h = b.network.dns.dnssec.nsec3Hash("a.example.com", { salt: salt, iterations: 0 });
b.network.dns.dnssec.verifyDenial(opts) #
{
{
qname: string, // the queried name
qtype: string|number, // queried type (required for proof "nodata")
proof: string, // "nxdomain" | "nodata"
zone: string, // the signer zone apex (a suffix of qname)
nsec3?: [ { owner: string, rdata: Buffer } ], // NSEC3 records (owner = base32hex-label.zone)
nsec?: [ { owner: string, rdata: Buffer } ], // NSEC records
maxIterations?: number, // NSEC3 iteration cap (default 500)
allowOptOut?: boolean, // accept an Opt-Out NXDOMAIN proof (default false)
}
}
Prove that a name does not exist (NXDOMAIN) or that a name has no records of a given type (NODATA) from the signed NSEC (RFC 4034 §4) or NSEC3 (RFC 5155) records in a response's Authority section. This is the other half of "verify the answer yourself": verifyRrset proves a positive answer, verifyDenial proves a negative.
The records MUST already be verified with verifyRrset — this checks the denial RELATION (closest-encloser, covering ranges, type-bitmap absence), not the signatures. For NSEC3, the iterated-hash count is capped (opts.maxIterations, default 500) to bound the SHA-1 work an attacker can force. An NXDOMAIN proof that relies on an Opt-Out NSEC3 (RFC 5155 §6) is refused unless opts.allowOptOut — opt-out only proves "no signed records", not non-existence.
qname, zone and every record owner are read in RFC 1035 §5.1 presentation form, as b.network.dns.dnssec.verifyRrset describes, so an owner name from b.safeDns.parseResponse is passed unchanged. A name that cannot be read throws dnssec/bad-name.
b.network.dns.dnssec.verifyDenial({
qname: "nope.example.com", proof: "nxdomain", zone: "example.com", nsec3: records,
});
b.network.dns.dnssec.verifyChain(opts) #
{
{
links: [ { // ordered root-first
zone: string,
dnskeys: Buffer[], // the zone's DNSKEY RRset RDATAs
dnskeyRrsig: { algorithm, labels, originalTtl, expiration, inception, keyTag, signerName, signature },
dsRdatas?: Buffer[], // DS RRset for this zone (served by parent; omit for root)
dsRrsig?: { ... }, // RRSIG over the DS RRset (signed by parent; omit for root)
} ],
trustAnchors?: [ { keyTag, algorithm, digestType, digest: Buffer } ], // default IANA root
at?: Date, // validity instant (default now)
}
}
Validate a DNSSEC delegation chain from the root down to a zone, against a pinned trust anchor (RFC 4035 §5). For each link, the zone's DNSKEY RRset must be self-signed by one of its keys; that signing key must be vouched for either by a pinned anchor (root) or by a DS record served by the already-trusted parent. The DS RRset itself is verified against the parent's keys, so trust flows root → TLD → zone with no gap. The default anchors are the IANA root KSKs; override with opts.trustAnchors.
This composes verifyRrset + verifyDs + the key tag; it returns the leaf zone's trusted DNSKEY set, which the caller then passes to verifyRrset / verifyDenial for the actual answer. A chain whose signing key at any link is a compromised key, including the key that matches a trust anchor, throws dnssec/compromised-key.
KeyTrap (CVE-2023-50387) amplification is bounded with non-configurable caps: at most 4 same-tag DNSKEY candidates are tried per RRSIG, at most 64 DNSKEYs per zone link and 16 DS records per delegation are accepted, the chain is at most 128 links deep, and the whole response is held to a signature-validation budget that scales with chain depth (so a legitimate deep delegation always fits while bounded collisions stay bounded). A hostile zone publishing many colliding keys / signatures is refused with dnssec/too-many-colliding-keys / dnssec/too-many-dnskeys / dnssec/too-many-ds / dnssec/too-many-links / dnssec/validation-budget-exceeded rather than driving O(keys x sigs) verifications. (NSEC3 iteration counts are separately capped at 150 per RFC 9276 / the CVE-2023-50868 fix.)
var trusted = b.network.dns.dnssec.verifyChain({ links: [rootLink, orgLink] });
// → { ok: true, zone: "org.", keys: [ ...trusted org DNSKEY rdatas ] }
b.network.smtp.policy.mtaSts.fetch(domain, opts?) #
{
dnsLookup: function, // default: none; async (name, "TXT") => string[][]
resolver: object, // default: the shared validating resolver; a b.network.dns.resolver with queryTxt(name)
httpClient: object, // default: b.httpClient; an object with request(opts)
}
Looks up the _mta-sts. TXT record (RFC 8461 §3.1) and, when it carries one v=STSv1 record with a valid id, fetches the policy from https://mta-sts.. It returns the parsed policy { version, mode, mx, max_age, id, fetchedAt }, the cached policy when the id has not changed, or null when the domain publishes no policy.
The domain is looked up in its UTS #46 canonical form. A domain that contains % or another ASCII character other than a letter, a digit, -, _ or . is refused, as are a control character, the root name . and an IP address. Every check runs before any DNS query or HTTPS request. When _mta-sts. would be longer than 253 octets, no record can be published there, and the call returns null without a query.
Throws smtp/bad-domain when domain is not a DNS domain name, smtp/mta-sts-txt-lookup-failed when the TXT lookup fails for a reason other than a missing name, smtp/mta-sts-fetch-failed when the policy request returns a status other than 2xx or 404, and smtp/mta-sts-empty, smtp/mta-sts-bad-version or smtp/mta-sts-bad-mode when the policy text is empty, is not STSv1, or has a mode other than enforce, testing or none. A lookup or fetch failure returns the cached policy instead when one is unexpired.
// requires: a resolver that can reach the public DNS
var policy = await b.network.smtp.policy.mtaSts.fetch("example.com");
// → { version: "STSv1", mode: "enforce", mx: ["mx1.example.com"], max_age: 86400, ... } or null
b.network.smtp.policy.dane.tlsa(domain, port?, opts?) #
{
dnssecValidated: boolean, // default: false; must be true
resolver: object, // default: none; a b.network.dns.resolver with queryTlsa(name)
}
Looks up the TLSA records for _ (RFC 7672) and returns them as [{ usage, selector, mtype, dataHex }]. The lookup uses opts.resolver.queryTlsa when opts.resolver is set, and node:dns.promises.resolveTlsa otherwise. A name that has no TLSA records returns an empty array.
The domain is looked up in its UTS #46 canonical form. A domain that contains % or another ASCII character other than a letter, a digit, -, _ or . is refused, as are a control character, the root name . and an IP address. port defaults to 25. When _ would be longer than 253 octets, no record can be published there, and the call returns an empty array without a query once the DNSSEC and resolver checks below have passed.
The caller passes opts.dnssecValidated: true to state that the resolver validates DNSSEC. Without it the call throws before any DNS query is made.
Throws smtp/bad-domain when domain is not a DNS domain name, smtp/bad-port when port is not an integer from 1 to 65535, smtp/dane-no-dnssec when opts.dnssecValidated is not true, smtp/dane-resolver-no-tlsa when opts.resolver has no queryTlsa method, smtp/dane-unavailable when the runtime has no node:dns.promises.resolveTlsa, and smtp/dane-lookup-failed when the lookup fails for a reason other than a missing name.
// requires: a resolver that can reach the public DNS
var records = await b.network.smtp.policy.dane.tlsa("mx1.example.com", 25,
{ dnssecValidated: true });
// → [ { usage: 3, selector: 1, mtype: 1, dataHex: "ab12..." } ]
b.network.smtp.policy.dane.verifyChain(certChain, tlsaRecords, opts?) #
{
allowPkixModes: boolean, // default: false; count PKIX-TA / PKIX-EE matches
}
Matches the certificate chain an SMTP peer presented against the peer's TLSA records (RFC 7672). certChain holds the DER of each certificate, leaf first, and tlsaRecords holds records in the shape b.network.smtp.policy.dane.tlsa returns. A DANE-EE (3) record is matched against the leaf. A DANE-TA (2) record is matched against the later certificates, and a match counts only when a signature-verified path runs from the leaf through the other supplied certificates to the matched one. PKIX-TA (0) and PKIX-EE (1) records count only when opts.allowPkixModes is true. A PKIX-TA match needs the same verified path as a DANE-TA match, and every PKIX match carries pkixPathRequired: true: the caller still validates the chain against its own trust store.
Returns { ok, matches, errors }. ok is true when at least one record matched. Each entry in errors carries tlsaIndex, reason and, for most reasons, certIndex and note. The reasons are: dane-compromised-key when the matched certificate, the leaf, or a certificate on the path from the leaf to a matched anchor carries a key that b.crypto.compromisedKey reports, such as an ECDSA key whose private scalar is 1 or a listed leaked key; dane-unreadable-key when such a certificate's key could not be read to make that check; dane-ta-path-not-validated or pkix-ta-path-not-validated when no verified path reaches the matched anchor; dane-ta-unparseable-leaf, pkix-ta-unparseable-leaf, dane-ta-unparseable-anchor or pkix-ta-unparseable-anchor when a certificate a trust-anchor match needs does not parse as X.509; pkix-modes-not-allowed for a PKIX record without opts.allowPkixModes; and unsupported-usage for any other usage value. A DANE-EE or PKIX-EE match on a leaf that node:crypto cannot parse is judged on the subjectPublicKeyInfo the leaf carries, and is refused as dane-unreadable-key when that key cannot be read either. The path to one matched anchor is searched once per call, however many records match it.
Throws smtp/dane-bad-chain when certChain is not a non-empty array of Buffers, and smtp/dane-bad-tlsa when tlsaRecords is not an array.
var rv = b.network.smtp.policy.dane.verifyChain([leafDer, issuerDer], records);
// → { ok: true, matches: [ { tlsaIndex: 0, certIndex: 0, usage: "DANE-EE", mtype: "SHA-256" } ], errors: [] }
b.network.smtp.policy.tlsRpt.fetchPolicy(domain, opts?) #
{
dnsLookup: function, // default: none; async (name, "TXT") => string[][]
resolver: object, // default: the shared validating resolver; a b.network.dns.resolver with queryTxt(name)
}
Looks up the _smtp._tls. TXT record (RFC 8460 §3) and returns { version: "TLSRPTv1", rua: [uri, ...] } when exactly one record carries v=TLSRPTv1 and names at least one rua URI. It returns null when the domain publishes no such record.
The domain is looked up in its UTS #46 canonical form. A domain that contains % or another ASCII character other than a letter, a digit, -, _ or . is refused, as are a control character, the root name . and an IP address. Every check runs before any DNS query. When _smtp._tls. would be longer than 253 octets, no record can be published there, and the call returns null without a query.
Throws smtp/tls-rpt-bad-domain when domain is not a DNS domain name, and smtp/tls-rpt-lookup-failed when the TXT lookup fails for a reason other than a missing name.
// requires: a resolver that can reach the public DNS
var policy = await b.network.smtp.policy.tlsRpt.fetchPolicy("example.com");
// → { version: "TLSRPTv1", rua: ["mailto:tlsrpt@example.com"] } or null
b.network.tls.serverKeyAgreementGroups(override?, where?) #
Return the OpenSSL group string for a TLS listener's ecdhCurve, built from the live key-share preference (b.network.tls.preferredGroups.get()). Each preferred group is written as a tuple of its own, with "/" between tuples, so the listener chooses by its own ranking and not by the key share the client sent. While the preference is the shipped default, one more tuple follows with the classical curves the default does not already name (X448, secp256r1, secp384r1, secp521r1), so a client that offers only those can still connect. After preferredGroups.set(...) the string holds exactly the configured groups.
A flat colon-separated list is one tuple. Within one tuple OpenSSL takes the group the client sent a key share for, so a listener on "X25519MLKEM768:X25519" negotiates X25519 with a client that lists X25519 first, and a listener with no ecdhCurve uses OpenSSL's default list, which does the same for a client offering SecP256r1MLKEM768 or SecP384r1MLKEM1024 next to X25519.
b.network.tls.applyToContext and b.mail.server.tls.context write this string, and b.pqcGate reads it to decide which client offers it counts as post-quantum.
override, when given, is returned in its place: a non-empty string unchanged, or an array of group names joined with ":". An empty or non-string value throws tls/bad-group-preference, and where names the option in that message.
b.network.tls.serverKeyAgreementGroups();
// -> "X25519MLKEM768/SecP256r1MLKEM768/SecP384r1MLKEM1024/X25519/X448:secp256r1:secp384r1:secp521r1"
b.network.tls.preferredGroups.set(["X25519MLKEM768", "X25519"]);
b.network.tls.serverKeyAgreementGroups();
// -> "X25519MLKEM768/X25519"
b.network.tls.applyToContext(opts?) #
{
base: object, // the node:tls options to extend; default {}
role: string, // "server" or "client"; default "server"
}
Copy opts.base and add the framework's TLS posture to the copy: the trust anchors registered with b.network.tls.addCa (and the system roots after b.network.tls.useSystemTrust(true)) as ca, the key-exchange group string as ecdhCurve. It adds no RFC 8879 certificate-compression algorithms; base.certificateCompression is checked and kept as given. Pass the result to tls.createServer, https.createServer or tls.createSecureContext for a listener, or, with role: "client", to tls.connect or new https.Agent.
With the default role: "server", ecdhCurve is b.network.tls.serverKeyAgreementGroups(), so the listener picks the highest-ranked group the client offers even when the client lists a classical group first and sends its key share. That is the string a b.pqcGate without groups expects from the listener behind it. With role: "client", ecdhCurve is the outbound offer order from b.network.tls.outboundPosture(). An outbound caller that omits role gets the listener string, which offers the fallback curves as well.
The post-quantum groups exist only in TLS 1.3. A listener whose base sets maxVersion below "TLSv1.3", or a secureProtocol that pins an older version, negotiates TLS 1.2 with classical ECDHE whatever its ecdhCurve, and a b.pqcGate in front of it passes clients that then negotiate classical ECDHE.
An ecdhCurve or groups already in base is kept as given (an array is joined with ":") and written as ecdhCurve, and groups is removed from the result. A listener configured this way behind b.pqcGate needs the same string passed as the gate's groups. A non-string or empty override throws tls/bad-group-preference, and a role other than "server" or "client" throws tls/bad-role.
b.network.tls.addCa, b.network.tls.addCaBundle and the BLAMEJS_EXTRA_CA_CERTS variables refuse a certificate whose key is compromised (see b.crypto.compromisedKey) with tls/compromised-key, and b.network.tls.useSystemTrust(true) leaves out every system root with a compromised key. A ca in base that is kept throws tls/compromised-key when one of its certificates has a compromised key. With role: "client", the result's checkServerIdentity checks the server's certificate chain and then runs base.checkServerIdentity (Node's tls.checkServerIdentity when it is absent). The check walks the chain the server shows, starting at the leaf, and stops at the first certificate that is a trust anchor of the dial (a certificate in the ca of the dial it runs on, or in Node's default CA store when that dial has none, or one with the same subject and public key) or that such an anchor signed. A dial that passes a prebuilt secureContext is checked against the result's ca instead. An anchor may issue without basicConstraints cA:TRUE when OpenSSL accepts it as an issuer: a self-signed X.509 v1 certificate, or a certificate with keyUsage keyCertSign and no basicConstraints. Each certificate before that point must be within its validity period and signed by the next certificate shown. A certificate on the walk, or the anchor it reaches, whose key is compromised is refused with tls/compromised-key. A chain that reaches no anchor this way is refused with tls/server-chain-unverifiable, which includes a server that sends an expired alternate issuer or a decoy root ahead of the path OpenSSL verified.
Before the chain walk, the check reads the host the way the WHATWG URL host parser does, after the full UTS46 mapping that url.domainToASCII applies. It refuses with tls/non-canonical-ip-host a host that the resolver or a URL parser reads as an IPv4 address but that is not written as a dotted-decimal address: octal or hex parts (0177.0.0.1, 0x7f.0.0.1), fewer than four parts (127.1), a single number (2130706433), a trailing dot (127.0.0.1.), fullwidth digits or dots, or an address followed by a code point that UTS46 removes, such as U+00AD (soft hyphen) or U+200B (zero width space). Any host whose last label, after that mapping, is all digits or 0x followed by hex digits counts. It refuses with tls/bad-host a host other than an IP literal that carries an ASCII control character, white space or %, or an empty label (127.0.0.1.., a..b, .example.com), or that b.publicSuffix.canonicalDomain returns "" for: a code point that url.domainToASCII refuses, a character other than a letter, digit, hyphen, dot or underscore after that mapping, a label over 63 octets, or a name over 253 octets. Neither base.checkServerIdentity nor Node's matcher runs for either kind of host, on any Node release. The check reads both the name Node checks the certificate against (the servername, or the host when no servername is set) and the host the dial connected to, so a dial to 127.1 with servername: "example.com" is refused with tls/non-canonical-ip-host as well.
The result carries RFC 8879 certificate compression only when base.certificateCompression lists algorithms. With it on, OpenSSL decompresses the peer's Certificate message before the chain is verified. A base.certificateCompression that is not an array, that names an algorithm outside b.network.tls.certificateCompressionAlgorithms(), or that names an algorithm twice throws tls/bad-cert-compression. One that lists "brotli" throws tls/unsafe-cert-compression on a Node release without the fix for CVE-2026-111497 (24.x older than 24.22.1, 26.x older than 26.12.1, and every 23.x and 25.x release), and on a Node built against a shared Brotli library older than 1.2.1. The Brotli decoder there writes out of bounds on a crafted stream, and a TLS peer reaches it during the handshake.
A dial whose trust the walk cannot read (a prebuilt secureContext when the result has no ca, or a pfx, whose CA certificates Node trusts) is walked the same way, and a chain that reaches no anchor the walk knows is then checked certificate by certificate as Node shows it: each one for a compromised key and for a signature by the certificate shown as its issuer. Node does not call checkServerIdentity on a resumed session, so a dial with rejectUnauthorized: false that resumes the session of a connection the check refused reports authorized: true. An https.Agent drops the session of a connection that closed with an error, so a dial through one that keeps certificate verification on is refused each time.
When no trust anchor is registered and base has no ca, a client, or a server with requestCert, verifies against Node's default CA store. That store also holds the certificates from NODE_EXTRA_CA_CERTS, --use-system-ca and tls.setDefaultCACertificates. When one of those has a compromised key, the result's ca is the default store without it, and OpenSSL does not verify a chain through it. The certificates Node bundles are not checked here; b.network.tls.useSystemTrust(true) checks them. Under --use-openssl-ca, or a Node build that uses the OpenSSL default CA store, the default store does not list the OpenSSL store, and the result gets no ca from it. The chain check then reads its anchors from the default store, from SSL_CERT_FILE and SSL_CERT_DIR, and on Linux from tls.getCACertificates("system"), and refuses a chain that reaches an anchor with a compromised key with tls/compromised-key.
With role: "server" and base.requestCert, the result's secureOptions adds SSL_OP_NO_TICKET, so a client cannot resume a session from a ticket without sending its certificate chain again. The server role does not check client certificate chains for compromised keys on its own: pass the listener to b.network.tls.checkClientChains, which marks a client whose chain carries a compromised key as unauthorized with tls/compromised-key.
var tls = require("node:tls");
var server = tls.createServer(b.network.tls.applyToContext({
base: { key: keyPem, cert: certPem },
}));
// ecdhCurve:
// "X25519MLKEM768/SecP256r1MLKEM768/SecP384r1MLKEM1024/X25519/X448:secp256r1:secp384r1:secp521r1"
var agent = new (require("node:https").Agent)(
b.network.tls.applyToContext({ base: {}, role: "client" }));
// ecdhCurve: "X25519MLKEM768:SecP256r1MLKEM768:SecP384r1MLKEM1024:X25519"
var mtls = tls.createServer(b.network.tls.applyToContext({
base: { key: keyPem, cert: certPem, ca: clientCaPem, requestCert: true },
}));
b.network.tls.checkClientChains(mtls);
b.network.tls.certificateCompressionAlgorithms() #
The RFC 8879 certificate-compression algorithms an operator may list in a certificateCompression option on this runtime, newest-runtime order, as a fresh array you own. It is a copy of b.constants.TLS_CERT_COMPRESSION().
Certificate compression is off by default. b.router's listen(), b.mail.server.tls.context, b.httpClient, b.pqcAgent.create, b.network.tls.applyToContext, b.network.tls.buildOptions, b.network.tls.outboundPosture and the protocol clients built on them advertise no algorithm unless the caller passes certificateCompression. With compression on, OpenSSL decompresses the peer's Certificate message during the handshake, before the chain is verified: a listener with requestCert decompresses any client's certificate, including with rejectUnauthorized: false, and a dial decompresses the certificate the server, or anyone on the path, sends. A list that is not an array, that names an algorithm outside this array, or that names an algorithm twice is refused with tls/bad-cert-compression (network-tls/bad-tls-options from b.network.tls.buildOptions).
On a Node release without the fix for CVE-2026-111497 (24.x older than 24.22.1, 26.x older than 26.12.1, and every 23.x and 25.x release), and on a Node built against a shared Brotli library older than 1.2.1, the array leaves out "brotli". The Brotli decoder there writes out of bounds on a crafted stream. An explicit certificateCompression that lists "brotli" is refused there with tls/unsafe-cert-compression.
Certificate compression shrinks the TLS Certificate message. On a post-quantum deployment that message is the largest one on the wire during a handshake: an ML-DSA-87 signature alone runs about 4.6 KB before any public key or chain.
Returns an empty array on a runtime that does not implement the extension.
b.network.tls.certificateCompressionAlgorithms();
// -> ["zlib", "brotli", "zstd"] on Node 26.12.1
// -> ["zlib", "zstd"] on Node 24.21.0
// Turn on zstd for one outbound connection.
var opts = b.network.tls.buildOptions({ certificateCompression: ["zstd"] });
b.network.tls.outboundPosture() #
The framework's outbound TLS posture as a fresh options object, ready to merge into any tls.connect, https.request or https.Agent options:
var connectOpts = Object.assign({ host: h, port: p }, b.network.tls.outboundPosture());
Every protocol client the framework ships — DNS-over-HTTPS and DNS-over-TLS, NTS-KE, Redis, syslog, WebSocket, proxy tunnels, the HTTP client, the ECH and OCSP paths — merges this rather than listing the keys itself, so raising the posture is one edit that cannot reach some outbound paths and miss others.
It reads the LIVE key-share preference, so b.network.tls.preferredGroups.set(...) (or the b.network.tls.pqc alias) takes effect on the next dial across every one of those clients. Call it per connection rather than caching the result, or an operator's later narrowing will not reach the wire.
The posture has no certificateCompression, so a dial built from it advertises no RFC 8879 certificate compression and never decompresses the server's certificate. See b.network.tls.certificateCompressionAlgorithms for turning it on.
// Restrict every outbound handshake to the NIST-curve hybrids.
b.network.tls.preferredGroups.set(["SecP256r1MLKEM768", "SecP384r1MLKEM1024"]);
b.network.tls.outboundPosture();
// → { minVersion: "TLSv1.3",
// ecdhCurve: "SecP256r1MLKEM768:SecP384r1MLKEM1024" }
b.network.tls.explainOutboundFailure(err, ctx?) #
{
host: string, // peer named in the message; default: omitted
port: number, // appended to host when both are present
tlsOpts: object, // the options the dial used; each setting below is read from it
minVersion: string, // the floor that was applied; default: the live posture
maxVersion: string, // the ceiling that was applied, when a caller capped the dial below TLS 1.3
secureProtocol: string, // an OpenSSL method name, when a caller pinned one version that way
ecdhCurve: string, // the group list that was offered; default: the live posture
}
Turn a refused outbound handshake into a sentence naming the likely cause.
OpenSSL reports a rejected ClientHello as a bare alert — tlsv1 alert protocol version — which names neither the peer nor anything an operator can act on, and reads as a problem with the request rather than with the posture the client applied to it. Two of those alerts are routinely the posture doing its job:
A protocol_version alert against a client pinning minVersion: "TLSv1.3" means the peer offers no TLS 1.3. That is a version refusal and has nothing to do with the key-exchange groups, which is worth stating plainly: the post-quantum posture is the framework's most visible property, so it draws the blame for handshake failures it did not cause.
A handshake_failure alert against a narrowed group list means the peer shares none of the offered groups. Under the shipped preference this cannot happen — the list ends in classical X25519, so a peer with no post-quantum hybrid negotiates that — so it points at a list an operator has narrowed past what the peer can do.
Neither alert is exclusive to these causes, so the wording is hedged and the original error text is carried through rather than replaced. Returns null when the error is not one this can speak to, which callers use to fall back to the original message.
Pass tlsOpts — the options object the dial was made with — rather than copying settings out of it. Handing the object over names every setting it could carry, so the explanation stays right as the diagnosis learns to read settings a caller was not thinking about when the error handler was written.
var why = b.network.tls.explainOutboundFailure(err, { host: "registry.example.com", port: 443 });
// -> "TLS handshake refused by registry.example.com:443 - the peer most
// likely does not offer TLS 1.3, ..."
b.network.tls.annotateOutboundFailure(err, ctx?) #
{
host: string, // peer named in the message
port: number, // appended to host when both are present
tlsOpts: object, // the options the dial used; see explainOutboundFailure for the settings read from it
}
Rewrite a refused handshake's message in place to name the likely cause, and hand the same error back.
The error object is kept rather than replaced so err.code, the error class and anything a caller already branches on survive untouched; only the message changes, and only when there is something to say. The stack's leading line is refreshed alongside it, since it embeds a copy of the message captured at construction.
Diagnosis never fails a request: any error raised while working out the explanation is swallowed and the original message stands.
socket.on("error", function (err) {
b.network.tls.annotateOutboundFailure(err, { host: host, port: port });
handle(err);
});
b.network.tls.ocsp.connect(opts) #
{
host: string, // the server to dial
port: number, // the server's TLS port
servername: string, // SNI name and certificate identity; default from host
ca: string|Buffer|Array, // trust anchors for this dial
checkServerIdentity: function, // runs after the framework's chain check
certificateCompression: string[], // RFC 8879 algorithms to advertise; default none
}
b.network.tls.outboundPosture
Open a TLS connection that asks the server for a stapled OCSP response, close it once the handshake completes, and resolve with { authorized, ocspBytes, peerCert }. ocspBytes is the stapled response, or null when the server stapled none, and peerCert is the server's certificate with its issuer chain.
The dial starts from b.network.tls.outboundPosture(), and the other options in opts are passed to tls.connect. The connection advertises RFC 8879 certificate compression only when opts.certificateCompression lists algorithms from b.network.tls.certificateCompressionAlgorithms(). With it on, OpenSSL decompresses the server's Certificate message before the chain is verified.
The promise rejects before the dial with tls/bad-cert-compression when certificateCompression is not an array, has an entry that is not a string, names an algorithm outside b.network.tls.certificateCompressionAlgorithms(), or names an algorithm twice. It rejects with tls/unsafe-cert-compression when the list names "brotli" on a Node release without the fix for CVE-2026-111497 (24.x older than 24.22.1, 26.x older than 26.12.1, and every 23.x and 25.x release) or on a Node built against a shared Brotli library older than 1.2.1. It rejects with tls/bad-servername when servername is not a non-empty host name or is an IP address other than host, and with tls/compromised-key when a certificate in ca has a compromised key. After the dial starts, it rejects with tls/connect-failed when tls.connect throws, and otherwise with the socket's error, including the tls/compromised-key, tls/server-chain-unverifiable, tls/non-canonical-ip-host and tls/bad-host refusals that b.network.tls.applyToContext describes for a client.
// requires: a reachable TLS server that staples OCSP
var b = require("@blamejs/core");
var rv = await b.network.tls.ocsp.connect({ host: "example.com", port: 443 });
rv.ocspBytes === null; // true when the server stapled nothing
b.network.tls.ocsp.requireStapled(opts) #
{
host: string, // the server to dial
port: number, // the server's TLS port
servername: string, // SNI name and certificate identity; default from host
ca: string|Buffer|Array, // trust anchors for this dial
checkServerIdentity: function, // runs after the framework's chain check
certificateCompression: string[], // RFC 8879 algorithms to advertise; default none
}
Dial the way b.network.tls.ocsp.connect does, and reject with tls/ocsp-not-stapled when the server staples no OCSP response, or with tls/ocsp-empty when the stapled response is empty. It takes the same options, resolves with the same { authorized, ocspBytes, peerCert }, and rejects with the same codes, including tls/bad-cert-compression and tls/unsafe-cert-compression before the dial for a bad certificateCompression list.
// requires: a reachable TLS server that staples OCSP
var b = require("@blamejs/core");
var rv = await b.network.tls.ocsp.requireStapled({ host: "example.com", port: 443 });
rv.ocspBytes.length > 0; // true
b.network.tls.ocsp.requireGood(opts) #
{
host: string, // the server to dial
port: number, // the server's TLS port
servername: string, // SNI name and certificate identity; default from host
ca: string|Buffer|Array, // trust anchors for this dial
checkServerIdentity: function, // runs after the framework's chain check
certificateCompression: string[], // RFC 8879 algorithms to advertise; default none
issuerPem: string, // PEM of the OCSP-signing certificate; required
issuerCertDer: Buffer, // DER of the issuer certificate for the CertID match
serialHex: string, // serial to match; default the server certificate's
clockSkewMs: number, // tolerance on thisUpdate / nextUpdate; default 5 minutes
maxAgeMs: number, // oldest thisUpdate accepted when nextUpdate is absent; default 24 hours
}
Dial the way b.network.tls.ocsp.requireStapled does, then check the stapled response's signature against opts.issuerPem, its CertID against the server certificate's serial, and its update times, and resolve with the connection result plus ocspEvaluation. It rejects with tls/ocsp-missing-issuer before the dial when issuerPem is missing, with tls/ocsp-empty when the stapled response is empty, and with tls/ocsp-not-good when the evaluation does not report a good status. It also rejects with every code b.network.tls.ocsp.requireStapled names, including tls/bad-cert-compression and tls/unsafe-cert-compression before the dial for a bad certificateCompression list.
// requires: a reachable TLS server that staples OCSP
var b = require("@blamejs/core");
var rv = await b.network.tls.ocsp.requireGood({
host: "example.com", port: 443, issuerPem: issuerPem,
});
rv.ocspEvaluation.ok; // true
b.network.tls.parseEchConfigList(raw) #
Parse a draft-ietf-tls-esni-22 ECHConfigList byte string (the value of the ech= SvcParam in an SVCB or HTTPS DNS record per RFC 9460 paragraph 7.4.2). Accepts a Buffer or a strict-base64 string. Returns { rawLength, configs: [{ version, length, keyConfig, ... }] }.
For each ECHConfig at the published draft-22 version (0xfe0d) the decoded keyConfig carries configId, kemId, publicKey (Buffer), and cipherSuites (each { kdfId, aeadId }); the entry also exposes maximumNameLength, publicName, and extensions. Unknown future ECH versions surface their raw body Buffer so the caller can forward them to a Node build that supports them.
Throws NetworkTlsError("tls/ech-config-malformed") on any framing violation (truncated length prefix, vector overflow, bad cipher_suites stride, etc.).
var b = require("@blamejs/core");
var rrs = await b.network.dns.queryHttps("example.com");
// `ech` is optional in an HTTPS record, and a domain can drop or rotate it
// at any time — handle its absence rather than indexing into the match.
var rec = rrs.find(function (r) { return r.params && r.params.ech; });
if (rec) {
var parsed = b.network.tls.parseEchConfigList(rec.params.ech);
// parsed.configs[0].keyConfig.kemId === 0x0020 (X25519)
}
b.network.tls.sniFor(host) #
Return the TLS Server Name Indication value for an outbound dial to host. A hostname is returned unchanged. An IPv4 or IPv6 literal, with or without the square brackets a URL puts around IPv6, returns undefined, as does an empty or non-string host. RFC 6066 section 3 does not allow a literal address in SNI: Node 26 refuses one with ERR_INVALID_ARG_VALUE from tls.connect, and earlier releases send it with a DEP0123 warning. When servername is left out, Node checks the server certificate against the IP addresses in its subjectAltName. The host handed to tls.connect must be the address without brackets: Node checks the certificate for [::1] against that text and fails the handshake.
Every framework dial that derives its server name from a host passes it through this function, including an explicit servername option, so an address given there is not sent either.
A host that the resolver or a URL parser reads as an IPv4 address also returns undefined, whatever its spelling: 127.1, 0x7f.0.0.1, 0177.0.0.1, 2130706433, 127.0.0.1., fullwidth digits, or an address followed by a code point that UTS46 removes, such as U+00AD. Any host whose last label, after the UTS46 mapping that url.domainToASCII applies, is all digits or 0x followed by hex digits is read this way. The framework dial then refuses such a host with tls/non-canonical-ip-host when it checks the server certificate (see b.network.tls.applyToContext).
b.network.tls.sniFor("example.com");
// → "example.com"
b.network.tls.sniFor("192.0.2.10");
// → undefined
b.network.tls.sniFor("127.1");
// → undefined
b.network.tls.sniFor("[2001:db8::1]");
// → undefined
b.network.tls.identityFor(host, servername?, opts?) #
{
label: string, // names the option in the message; default "servername"
errorClass: function|object, // error class thrown; default b.network.tls.NetworkTlsError
code: string, // error code; default "tls/bad-servername"
}
Return the TLS identity options for an outbound dial to host, as an object to merge into the tls.connect options. When servername is set it names the identity, and otherwise host does. A host name gives { servername: name }: Node sends that name as SNI and checks the server certificate against it. An IPv4 or IPv6 literal, with or without square brackets, gives {}: no SNI is sent, and Node checks the certificate against the IP addresses in its subjectAltName for the dialed host.
host here may carry the square brackets of a URL, but the host handed to tls.connect must not. Given [::1], Node checks the certificate against that text rather than the address, and the handshake fails with ERR_TLS_CERT_ALTNAME_INVALID; on Linux the lookup of [::1] fails first with ENOTFOUND. Every framework dial removes the brackets from an IPv6 host before it connects.
With no server name set, Node checks the certificate against host, so an IP-literal servername is accepted only when it is the same address as host. The comparison is by address: ::1, [::1] and 0:0:0:0:0:0:0:1 are one address, and so are ::ffff:127.0.0.1 and ::ffff:7f00:1. An IPv4 address and its IPv4-mapped IPv6 form (127.0.0.1 and ::ffff:127.0.0.1) are compared as two addresses. A zone ID is part of the address, so fe80::1%eth0 and fe80::1%eth1 are two addresses, and so are fe80::1%eth0 and fe80::1. An IP-literal servername naming any other address throws, as does a servername that is not a non-empty string. A host or servername that the resolver reads as an IPv4 address in a non-canonical spelling, such as 127.1 or 0x0a.0.0.5, is an address here (see b.network.tls.sniFor): as the host it gives {}, and as a servername it throws, because it is not written as the same address as the host. A dial to such a host, or to a host that is not a valid host name, is refused at the certificate check with tls/non-canonical-ip-host or tls/bad-host whether or not a servername is set (see b.network.tls.applyToContext). A servername that is not a valid host name also throws: one that carries an ASCII control character, white space or %, an empty label such as example.com.., or that b.publicSuffix.canonicalDomain does not accept. The error is a NetworkTlsError with code tls/bad-servername unless opts.errorClass and opts.code name another; an error class with a factory(code, message) is built through it. Every framework dial that takes a host and a servername option builds its identity here.
The options are checked on every call: a label or code that is not a non-empty string, or an errorClass that is neither a constructor nor an object with a factory function, throws NetworkTlsError tls/bad-identity-opts.
b.network.tls.identityFor("example.com");
// → { servername: "example.com" }
b.network.tls.identityFor("192.0.2.10", "api.example.com");
// → { servername: "api.example.com" }
b.network.tls.identityFor("2001:db8::1", "[2001:db8:0::1]");
// → {}
b.network.tls.connectWithEch(opts) #
{
{
host: string,
port: number,
alpn: string[],
ipFamily: 4 | 6,
timeoutMs: number,
servername: string,
ca: string|Buffer|Array,
checkServerIdentity: function,
echOverride: Buffer|string,
rejectUnauthorized: boolean,
}
}
b.network.tls.checkServerIdentity9525
Open a TLS-1.3 outbound connection with Encrypted Client Hello (ECH, draft-ietf-tls-esni-22) when the destination publishes an ech= SvcParam via SVCB/HTTPS records (RFC 9460 paragraph 2.4 / paragraph 9). The flow:
1. b.network.dns.queryHttps(host) to discover ECH config. 2. If any record carries ech=, the parsed ECHConfigList is attached to tls.connect({ ech }) so the outer ClientHello uses the published public_name SNI and the inner ClientHello (real SNI, ALPN, etc.) is HPKE-encrypted under the published public key. 3. If no record carries ech=, or DNS fails, the function falls back to a normal TLS connect (still TLSv1.3-floor + framework PQC group preference). Operators get an observability.event so the degradation is visible. 4. If the running Node build does not support the ech connect option, the function emits a one-shot warn and connects without ECH — never throws on missing Node-side support.
An IP-literal host has no HTTPS record, so step 1 is skipped and the connection is made without ECH. A host that the dial would refuse with tls/bad-host or tls/non-canonical-ip-host is refused before step 1, with or without echOverride, so no HTTPS-record query and no address lookup is made for it. The server name comes from b.network.tls.identityFor(host, servername): a name is sent as SNI and the certificate is checked against it, and an IP literal sends no SNI and the certificate is checked against the IP addresses for host. A servername that is an IP address other than host, or is not a non-empty string, throws tls/ech-bad-opts.
The returned promise rejects with tls/ech-config-malformed when echOverride does not parse as an ECHConfigList, with network-tls/bad-tls-options when ca is not a PEM string, a Buffer, or an array of those, with tls/compromised-key when a certificate in ca has a compromised key (see b.crypto.compromisedKey) or when the server's certificate chain carries one before it reaches a trust anchor, with tls/server-chain-unverifiable when that chain reaches no trust anchor (see b.network.tls.applyToContext), with tls/non-canonical-ip-host when host is an IPv4 address in a spelling other than dotted decimal, such as 127.1 or 0x7f.0.0.1, with tls/bad-host when host (or the servername Node checks the certificate against) carries an ASCII control character, white space or %, an empty label, or is a name that b.publicSuffix.canonicalDomain does not accept (see b.network.tls.applyToContext), with tls/ech-connect-failed when tls.connect throws, with tls/ech-timeout when the handshake does not complete within timeoutMs, and with tls/ech-dns-unavailable when the DNS module cannot be loaded for the HTTPS-record lookup.
Returns the connected tls.TLSSocket once secureConnect fires. b.httpClient will compose this in a follow-up release; this primitive is the operator escape hatch for raw outbound TLS over ECH (custom protocol clients, mTLS testing, ECH validation tools).
// requires: outbound DNS for the ECH config, and a reachable peer
var b = require("@blamejs/core");
var sock = await b.network.tls.connectWithEch({
host: "ech-target.example.com",
alpn: ["h2", "http/1.1"],
});
sock.write("GET / HTTP/1.1\r\nHost: ech-target.example.com\r\n\r\n");
b.network.tls.checkServerIdentity9525(host, cert) #
Drop-in replacement for Node's tls.checkServerIdentity that implements RFC 9525 paragraph 6 strictly. Operators pass it to tls.connect({ checkServerIdentity }) (or to any framework primitive that exposes pkixStrict: true).
Differences vs Node's default matcher:
- SAN-required when present is mandatory: a peer cert lacking subjectAltName refuses with tls/pkix-san-required (RFC 9525 paragraph 6.4.4 forbids Common Name fallback). - CN-only legacy certs surface a distinct tls/pkix-cn-fallback-refused code so audit logs distinguish "missing SAN" from "ancient CN-only cert still shipping". - Wildcard matching is restricted to the entire leftmost label. *.example.com matches foo.example.com but NOT foo.bar.example.com and NOT example.com. Partial wildcards like f*o.example.com and middle wildcards like foo.*.example.com refuse. - IP literals match iPAddress SAN entries only — never DNS entries, never wildcards. IPv6 comparison is byte-equal after canonicalization (zone-id stripped, :: expanded, and a dotted IPv4 tail such as ::ffff:192.0.2.1 read as its two hextets). - A host that the resolver or a URL parser reads as an IPv4 address but that is not written in dotted decimal (0177.0.0.1, 0x7f.0.0.1, 127.1, 2130706433, 127.0.0.1., fullwidth digits, an address followed by a code point that UTS46 removes such as U+00AD, or any host whose last label after the UTS46 mapping is all digits or 0x followed by hex digits) matches no SAN entry, neither dNSName nor iPAddress. - A host other than an IP literal that carries an ASCII control character, white space or %, an empty label (127.0.0.1.., a..b.com, .example.com), or that b.publicSuffix.canonicalDomain does not accept as a host name, matches no SAN entry.
Every other refusal carries tls/pkix-hostname-mismatch: a name no SAN entry matches, a wildcard that does not cover the host, a host that is not a non-empty string, a missing peer cert, an IP literal with no matching iPAddress entry, an IPv4 address in a non-canonical spelling, a host that is not a valid host name, and a subjectaltname with a malformed quoted entry, which leaves no entry to match the host against.
Returns Error | undefined — the Error shape Node expects; when undefined, the connection is permitted to proceed. The codes above are read off that returned Error, which this function returns rather than throws.
var tls = require("node:tls");
var b = require("@blamejs/core");
var sock = tls.connect({
host: "internal.example.com",
port: 443,
checkServerIdentity: b.network.tls.checkServerIdentity9525,
});
b.network.tls.checkClientChains(server) #
Check the certificate chain of every client that server authorizes. Pass a tls.Server, an https.Server or an http2 secure server that sets requestCert. b.router and b.createApp listeners with tlsOptions.requestCert run the same check without this call.
On each secureConnection whose socket is authorized, the check walks the client's certificate chain as Node shows it, starting at the leaf, and stops at the first certificate that is a trust anchor of the server (a certificate in the server's ca, or in Node's default CA store when the server has no ca, or one with the same subject and public key) or that such an anchor signed. Each certificate before that point must be within its validity period and signed by the next certificate shown. When a certificate on the walk, or the anchor it reaches, has a compromised key (see b.crypto.compromisedKey), the socket's authorized becomes false and its authorizationError becomes tls/compromised-key. A chain that reaches no anchor this way marks the socket with tls/client-chain-unverifiable, or with tls/resumed-chain-unverifiable on a resumed session. That includes a client that sends an expired alternate issuer or a decoy root ahead of the path OpenSSL verified.
A resumed session does not carry the chain the client sent, so its leaf passes only when a certificate in the server's ca signed it. List the intermediate CA certificates that issue client certificates in the server's ca to keep resumed sessions of those clients authorized. Each refusal writes the audit row tls.client_chain.refused, and the server closes the socket unless it was built with rejectUnauthorized: false. A socket that is already unauthorized keeps its own authorizationError and is not walked. The result for a socket is kept, and a later check of the same socket and leaf certificate, such as b.middleware.requireMtls on a keep-alive request, returns it without walking the chain again.
A server whose trust the walk cannot read, because it was built with a pfx or serves other secure contexts through SNICallback or addContext, is walked the same way, and a chain that reaches no anchor in its ca is then checked certificate by certificate as Node shows it: each one for a compromised key and for a signature by the certificate shown as its issuer.
The call also adds SSL_OP_NO_TICKET to the server's current secure context, so a client cannot resume a session from a ticket and each client sends its chain on a full handshake. A context the server installs later with server.setSecureContext keeps its own secureOptions; a session a client resumes from a server-side session cache (the newSession and resumeSession events) is checked as described above.
A value without prependListener throws tls/bad-server. Calling it twice on one server adds one check. It returns server.
var tls = require("node:tls");
var server = tls.createServer(b.network.tls.applyToContext({
base: { key: keyPem, cert: certPem, ca: clientCaPem, requestCert: true },
}), function (socket) {
socket.end(socket.authorized ? "hello" : "refused");
});
b.network.tls.checkClientChains(server);
b.network.dns.tsig.sign(message, opts) #
{
keyName: string, // REQUIRED — the shared-key name
secret: string | Buffer, // REQUIRED — base64 string or raw bytes
algorithm: string, // default: "hmac-sha256"
fudge: number, // default: 300 (seconds)
time: number, // default: now (Unix seconds)
originalId: number, // default: the message's own ID
requestMac: Buffer, // when signing a response (§5.4.1)
error: number, // default: 0 (NOERROR)
otherData: Buffer, // default: empty
allowLegacy: boolean, // permit HMAC-MD5 / HMAC-SHA-1
}
Append a TSIG resource record to a DNS message (a Buffer of wire bytes) and return the signed wire Buffer. The MAC is the HMAC over the message plus the RFC 8945 §4.3.3 TSIG variables. Returns { wire, mac } — wire is the message with the TSIG RR appended and ARCOUNT incremented, and mac is the raw HMAC (keep it to verify the matching response).
algorithm takes a name from the IANA TSIG Algorithm Names registry, matched case-insensitively. "hmac-md5" is accepted as a shorter spelling of the registered HMAC-MD5.SIG-ALG.REG.INT, which is the name written to the wire and hashed into the MAC.
keyName is read in RFC 1035 §5.1 presentation form, so a\.b.example. names the key whose first label is a.b. A key name with an empty or over-long label, a malformed escape, or more than 255 octets throws tsig/bad-name.
Throws TsigError: tsig/bad-message for a message that is not a DNS wire Buffer, tsig/bad-opt for a missing keyName or an out-of-range fudge or time, tsig/bad-secret for a secret that is not base64 or a Buffer, tsig/bad-algorithm for an algorithm outside the registry, tsig/legacy-algorithm for HMAC-MD5 or HMAC-SHA-1 without allowLegacy, and tsig/bad-name as above.
var signed = b.network.dns.tsig.sign(queryWire, {
keyName: "update.key.", secret: "",
});
socket.send(signed.wire);
b.network.dns.tsig.verify(message, opts) #
{
keys: object, // { "": { secret, algorithm } }
keyName: string, // single-key form (with secret)
secret: string | Buffer, // single-key form
algorithm: string, // expected algorithm (single-key form)
now: number, // default: now (Unix seconds)
requestMac: Buffer, // when verifying a response (§5.4.1)
allowLegacy: boolean,
}
Verify the TSIG record on a DNS message: locate the trailing TSIG RR, recompute the HMAC over the RFC 8945 §4.3.3 digest, compare it in constant time, and check that now is within fudge seconds of timeSigned. Returns { valid, keyName, algorithm, timeSigned, fudge, error, macValid, timeValid, reason }; valid is true only when the MAC matches, the time window holds, and the embedded error is NOERROR. Never throws for an authentication failure — only for a malformed message or unknown key shape.
The returned keyName is in RFC 1035 §5.1 presentation form: a dot inside a label is \., a backslash is \\, and a byte outside 0x21-0x7E is \DDD. The names in keys and keyName are read in the same form and matched without regard to ASCII case.
Throws TsigError: tsig/bad-message for a message that is not a DNS wire Buffer; tsig/truncated for a message, record or name label that runs past its end; tsig/no-tsig when there are no additional records; tsig/trailing-bytes for bytes after the final record; tsig/not-tsig when the final record is not a TSIG record; tsig/bad-rr for a TSIG record whose CLASS is not ANY or whose TTL is not 0; tsig/bad-rdata for a RDATA length mismatch; tsig/bad-name for a reserved label type or a compression-pointer loop; tsig/bad-secret for a key secret that is not base64 or a Buffer; tsig/bad-algorithm for an algorithm outside the registry; and tsig/legacy-algorithm for HMAC-MD5 or HMAC-SHA-1 without allowLegacy.
var r = b.network.dns.tsig.verify(received, {
keys: { "update.key.": { secret: "" } },
});
if (!r.valid) refuse(r.reason);
b.network.socket.applyToSocket(socket) #
Apply the framework's socket defaults (TCP_NODELAY, SO_KEEPALIVE + initial-delay) to a freshly-created net.Socket / tls.TLSSocket. Best-effort: a socket that has already errored, lacks the setter methods, or rejects the call is left as-is. Returns the same socket. Used by primitives that build their own server (b.tls, b.wsServer, b.smtp) so every socket on the wire follows the same tuning.
var net = require("net");
var s = new net.Socket();
var ret = b.network.socket.applyToSocket(s);
ret === s;
// → true
s.destroy();
b.network.bootFromEnv(opts) #
{
env: object, // default process.env — pass a fixture object in tests
audit: boolean, // default true — emit `network.boot.from_env`
}
Read BLAMEJS_* environment variables once and apply the union to the live network facade. Recognized keys cover NTP servers / timeout / drift thresholds, DNS servers / result-order / family / lookup-timeout / cache-TTL / DoH URL or provider / DoT host+port, HTTP_PROXY / HTTPS_PROXY / NO_PROXY, extra-CA file or directory, BLAMEJS_USE_SYSTEM_TRUST, and the socket TCP_NODELAY / SO_KEEPALIVE defaults. Returns an applied report — exactly which keys took effect. Audits network.boot.from_env unless opts.audit:false.
A BLAMEJS_EXTRA_CA_CERTS file or BLAMEJS_EXTRA_CA_CERTS_DIR directory holding a certificate whose key is compromised (see b.crypto.compromisedKey) throws tls/compromised-key and adds none of that file's or directory's certificates. BLAMEJS_USE_SYSTEM_TRUST adds the system roots without the ones whose key is compromised.
A BLAMEJS_SOCKET_KEEPALIVE_DELAY_MS that does not parse as a non-negative integer throws socket/bad-keepalive-delay. The socket defaults are set through b.network.socket.setDefaultNoDelay and b.network.socket.setDefaultKeepAlive, which throw socket/bad-no-delay and socket/bad-keepalive for a value that is not a boolean; BLAMEJS_SOCKET_NO_DELAY and BLAMEJS_SOCKET_KEEPALIVE are read as booleans, so those two codes do not come from the environment.
// requires: outbound NTP (udp/123) to the servers named below
var applied = b.network.bootFromEnv({
env: { BLAMEJS_NTP_SERVERS: "time.cloudflare.com,time.google.com" },
audit: false,
});
applied.ntp.servers;
// → 2
b.network.snapshot() #
Return a redacted snapshot of the network facade's current configuration: NTP servers + drift thresholds, DNS state (servers, result-order, family, DoH/DoT, cache TTL), proxy resolution, TLS trust-store size + system-trust flag, heartbeat statuses, and socket defaults. Cheap; safe to call from a /healthz or operations endpoint. No secrets are returned.
var snap = b.network.snapshot();
typeof snap.tls.caCount;
// → "number"