@blamejs/pki 0.6.41 → 0.6.43

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/CHANGELOG.md CHANGED
@@ -4,6 +4,26 @@ All notable changes to `@blamejs/pki` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## v0.6.43 — 2026-09-06
8
+
9
+ Path building finds a path through a mesh of cross-certified domains without walking the foreign branches first.
10
+
11
+ ### Changed
12
+
13
+ - pki.path.build orders candidates in a mesh of cross-certified domains by the two RFC 4158 section 3.5 name heuristics it had not applied. A candidate is ranked by how many leading relative distinguished names it shares with the name the search is heading for: its issuer against a trust anchor's name when building forward (section 3.5.16), and its subject against the leaf's issuer when building in reverse (the section 3.5.16 and section 3.5.19 reverse methods). Names are compared under the RFC 5280 section 7.1 rule, so a certificate in the target's own domain is tried before one from a cross-certified domain. Forward building additionally sorts a candidate under every candidate that can complete the path when its basicConstraints path length constraint cannot cover the certificates already below it in the chain (section 3.5.7), counting the non-self-issued ones the way RFC 5280 section 6.1.4(m) does, so a key-rollover certificate below the candidate spends none of its budget. That ordering outranks the other hints rather than competing with them, so a key identifier match or an anchor-adjacent issuer does not raise a candidate whose constraint the path already exceeds. All of it is ordering alone: no candidate is removed, every assembled path is handed to pki.path.validate, and an unbounded search still reaches every path the pool holds. A build over a mesh reaches a path within a smaller opts.maxCandidatesConsidered budget and reports a lower candidatesConsidered. A bounded search spends that budget on whichever branches the order steers it to, so a build that reports path/build-limit where the earlier order succeeded wants a larger opts.maxCandidatesConsidered, and the same holds for the opts.maxAiaFetches allowance.
14
+
15
+ ## v0.6.42 — 2026-09-06
16
+
17
+ A trust anchor carries the namespace a root program trusts a root for, so a certificate outside it is refused even where the root certificate states no such limit.
18
+
19
+ ### Added
20
+
21
+ - pki.trust.anchor(entry, opts) accepts opts.nameConstraints, the namespace a root program applies to a root outside any extension the root certificate carries. It is a { permitted, excluded } pair of { tag, base } subtrees, the shape pki.path.validate takes for opts.initialPermittedSubtrees, and validate seeds it as the RFC 5280 section 6.1.1(h)(i) initial value: it intersects with each certificate's own nameConstraints so a leaf must satisfy both, and an excluded subtree rejects a name whatever the permitted set says. A verdict reports it at anchorConstraints.nameConstraintsApplied. The subtrees are copied out of the caller's object, so changing that object afterwards leaves the namespace an anchor already vouches for unchanged. An overlay naming no subtree, one carrying a malformed subtree, and one supplying its subtrees through an accessor are each refused with trust/bad-input, since carrying any of them would widen the namespace the operator asked to restrict.
22
+
23
+ ### Changed
24
+
25
+ - pki.path.validate refuses a subtree in opts.initialPermittedSubtrees, opts.initialExcludedSubtrees, or a trust anchor's nameConstraints whose base is outside the form its tag names, with path/bad-input. Tag 1 is a mailbox, a host name, or a host name written as a subtree with a leading dot, and a mailbox may name its domain as a bracketed IPv4 or IPv6 address literal; tags 2 and 6 are host names, and a tag-6 base is the dotted host a certificate's URI is compared by rather than a URI; tag 4 names at least one relative name, with dotted-decimal object identifier types and string values; tag 7 is 8 bytes for IPv4 or 32 for IPv6. A host name is labels of letters, digits and hyphens, with a hyphen at neither edge of a label, 63 characters to a label and 253 to the name. An anchor whose nameConstraints names no subtree at all is refused the same way. Such a base previously reached the comparison, where it either matched every name, so a permitted subtree restricted nothing, or matched none, so an excluded subtree kept nothing out. A certificate's own nameConstraints extension is unaffected and is compared as the certificate wrote it.
26
+
7
27
  ## v0.6.41 — 2026-09-05
8
28
 
9
29
  A lookup table answers from its own entries, so a name taken off the wire cannot resolve to something the table never registered.
package/README.md CHANGED
@@ -230,7 +230,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
230
230
  | `pki.cmc` | Build and interpret CMC messages (RFC 5272). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and signs it through `pki.cms.sign` under `id-cct-PKIData`. A PKCS#10 (`tcr`) request is verified against its own proof-of-possession before signing, so a request whose self-signature does not verify under its subject public key is refused rather than signed into a message a CA would reject. Body-part identifiers are unique across the whole message and never the reserved 0; a caller's clash is refused rather than renumbered, since a control may already reference it. An Identity Proof V2 witness is computed over the `reqSequence` bytes exactly as emitted (§6.2.1 step 1) rather than a re-serialization, a POP Link Witness is emitted only alongside the POP Link Random control §6.3.1.1 requires beside it, and a renewal carries neither Identification nor Identity Proof in either version. `verify(response, sent)` takes what the CA returned plus the state the client retained and reduces it to one terminal outcome: `issued`, `pending`, `confirm-required`, `pop-required`, or `rejected`. It binds the exchange first — Transaction Identifier, the Sender and Recipient Nonce echo compared in constant time and by full value so a truncation cannot match, and the Data Return echo — with each check applying only if the client sent that half, and, once sent, an absent or differing echo being a refusal, which is the replay defense. `bodyPartIDs` extends the same rule to what the response is about: a status reporting on a body part the request never sent is refused, which the transaction and nonce cannot catch, because a server can echo both correctly while answering about a different message. Several status controls are permitted and the worst governs, so a failure cannot hide behind an earlier success; the absence of any status control is success, per §6.1.2. The carrier's signature must verify (§3.2.1.3.4): a conforming SignedData carries its own signer certificate, so the ordinary build-then-verify flow needs nothing extra and the verdict reports `signatureVerified: true`. Where the signer is found nowhere the posture is fail-closed with a named opt-out — supply `certs` with the responder's certificate, or `allowUnverified: true`, in which case the verdict reports `signatureVerified: false`. Doing neither is refused, the opt-out never excuses a signature that is present and wrong, and a carrier with no signer at all is refused outright. The response's own `cmsSequence` and `otherMsgs` come back raw, since a request whose only arm was the other-message form has no certificate to return and §4.1 puts its answer there. Nothing is trusted: issued certificates are read from the CMS certificate bag (§4.2) and surfaced raw for `pki.path.validate`, and a Publish Trust Anchors control is surfaced with `trusted: false` rather than added to a store — `build`, `verify` |
231
231
  | `pki.schema.cmc` | Decode CMC messages (RFC 5272 as updated by RFC 6402): a Full PKI Request (`PKIData`) or Full PKI Response (`PKIResponse`) riding inside a CMS SignedData, reached by the encapsulated content type (`id-cct-PKIData` / `id-cct-PKIResponse`). Controls are surfaced in wire order with their values raw, so an unrecognized one is data rather than a fault. Tagged requests decode across all three arms. The status verdicts (`CMCStatusInfo` v1 and `CMCStatusInfoV2`) are collected as an ordered list, and the RFC 6402 two-module `OtherStatusInfo` ambiguity — `pendInfo` and `extendedFailInfo` are both untagged SEQUENCEs in the 1988 module, told apart only by their first element — is resolved by inspection and refused when it cannot be told apart. Body-part identity is unique across the whole message rather than per sequence, 0 is reserved as the reference to the enclosing PKIData, and the `reqSequence` bytes are surfaced exactly as they appeared so an Identity Proof witness is computed over the wire bytes. A companion decoder for CMS content rather than an auto-routed format — `parse`, `parsePkiData`, `parsePkiResponse` |
232
232
  | `pki.schema.engine` | The declarative ASN.1 structure-schema engine every format parser composes — `walk`, `encode`, `embeddedDer`, and the schema combinators |
233
- | `pki.path` | Certification-path validation (RFC 5280 §6). `validate` runs the §6.1 state machine over an ordered path and a trust anchor: signature chaining across RSA, ECDSA, EdDSA, ML-DSA, SLH-DSA and hybrid composite ML-DSA (a composite is accepted only when both its post-quantum and traditional components verify), validity windows, name chaining, basic constraints and path length, key usage, name constraints, and the certificate-policy tree. It returns a structured verdict with per-check reason codes and enforces a `pki.trust` anchor's per-purpose distrust-after dates and delegator purposes through `checkPurpose` — an anchor that carries either one with no purpose named to select by is refused as a configuration fault rather than validated as though it carried none. The verdict says what was established. `revocationChecked` takes the weakest outcome on the path: `false` with no checker supplied, `"determined"` when every certificate got an explicit good or revoked answer, `"waived"` when `softFail` turned an undetermined one into a pass, and `"undetermined"` when one could not be answered at all — which includes a checker that throws, a fault `softFail` does not waive because `softFail` opts into an undetermined answer, not into a broken checker. `anchorConstraints` names the purpose the anchor was judged under and whether each of its two constraints applied. `crlChecker` supplies CRL-based revocation, covering partitioned and sharded CRLs, whose §6.3.3 Distribution Point ↔ IDP correspondence lets corresponding shards accumulate reason coverage until all eight revocation reasons are covered, and delta CRLs, merged onto the complete CRL they may be combined with (§5.2.4) so a held certificate its delta releases reads good, while a delta that merges with nothing still reports what it lists and still withholds good. `ocspChecker` supplies OCSP-based revocation (RFC 6960: CertID binding, responder authorization, signature, currency) over the same pluggable hook. `build(leaf, opts)` is the discovering complement (RFC 4158): from a leaf, an untrusted pool of candidate CA certificates, and a trust store, it finds the ordered leaf-to-anchor path `validate` accepts, using name chaining plus the RFC 4158 §3.5 sort hints (an AKI/SKI match, an anchor-adjacent issuer, CA plus keyCertSign, validity at the check time — ordering hints, never filters), a depth-first search with backtracking so the first accepted path wins, and a bounded search (chain-length cap, candidate-expansion cap, identity-tuple visited set) so a cross-certificate cycle or Bridge-CA fan-out terminates deterministically. Every accept flows through `validate`, and its verdict is cross-checked against `openssl verify`. Opt-in AIA `caIssuers` fetching (`opts.fetchAia: true`) discovers a missing intermediate from a certificate's Authority Information Access URL (§4.2.2.1) over `pki.transport`, triggered only on a pool miss and bounded against SSRF and amplification: HTTPS only, a total fetch budget that caps fetching silently rather than throwing, a per-cert URL cap, a build-wide URL dedupe, a response-size and certificate-count cap, no redirect following, and every fault a silent skip. The TLS trust (`opts.tls`) stays distinct from the PKI `trustAnchors`, and every fetched certificate remains untrusted pool material that still flows through `validate` (never a trust anchor). It is off by default, so the default build is byte-identical offline. An `opts.direction` of `"reverse"` searches from a trust anchor toward the leaf (RFC 4158 §3.1), narrower when the anchor set is small and the leaf's issuer options fan out, and `"auto"` picks the direction by first-hop fan-out; reverse building reuses the same pool, visited set, caps, and `validate` gate, so the direction changes only search order, and the anchor is excluded from the returned path. Reverse building is pool-only and does not combine with `fetchAia`. When `opts.userInitialPolicySet` names acceptable certificate-policy OIDs and more than one path validates, build returns the accepted path whose user-constrained policy set best satisfies that set (RFC 4158 §4) rather than the first accepted path, the ranking bounded by the same candidate cap and a malformed set refused with `path/bad-input`; an `anyPolicy` entry is unconstrained and returns the first accepted path. Pure and re-entrant — `validate`, `build`, `crlChecker`, `ocspChecker` |
233
+ | `pki.path` | Certification-path validation (RFC 5280 §6). `validate` runs the §6.1 state machine over an ordered path and a trust anchor: signature chaining across RSA, ECDSA, EdDSA, ML-DSA, SLH-DSA and hybrid composite ML-DSA (a composite is accepted only when both its post-quantum and traditional components verify), validity windows, name chaining, basic constraints and path length, key usage, name constraints, and the certificate-policy tree. It returns a structured verdict with per-check reason codes and enforces a `pki.trust` anchor's per-purpose distrust-after dates and delegator purposes through `checkPurpose` — an anchor that carries either one with no purpose named to select by is refused as a configuration fault rather than validated as though it carried none. The verdict says what was established. `revocationChecked` takes the weakest outcome on the path: `false` with no checker supplied, `"determined"` when every certificate got an explicit good or revoked answer, `"waived"` when `softFail` turned an undetermined one into a pass, and `"undetermined"` when one could not be answered at all — which includes a checker that throws, a fault `softFail` does not waive because `softFail` opts into an undetermined answer, not into a broken checker. `anchorConstraints` names the purpose the anchor was judged under and whether each of its two constraints applied. `crlChecker` supplies CRL-based revocation, covering partitioned and sharded CRLs, whose §6.3.3 Distribution Point ↔ IDP correspondence lets corresponding shards accumulate reason coverage until all eight revocation reasons are covered, and delta CRLs, merged onto the complete CRL they may be combined with (§5.2.4) so a held certificate its delta releases reads good, while a delta that merges with nothing still reports what it lists and still withholds good. `ocspChecker` supplies OCSP-based revocation (RFC 6960: CertID binding, responder authorization, signature, currency) over the same pluggable hook. `build(leaf, opts)` is the discovering complement (RFC 4158): from a leaf, an untrusted pool of candidate CA certificates, and a trust store, it finds the ordered leaf-to-anchor path `validate` accepts, using name chaining plus the RFC 4158 §3.5 sort hints (an AKI/SKI match, an anchor-adjacent issuer, CA plus keyCertSign, validity at the check time — ordering hints, never filters), a depth-first search with backtracking so the first accepted path wins, and a bounded search (chain-length cap, candidate-expansion cap, identity-tuple visited set) so a cross-certificate cycle or Bridge-CA fan-out terminates deterministically. Every accept flows through `validate`, and its verdict is cross-checked against `openssl verify`. Opt-in AIA `caIssuers` fetching (`opts.fetchAia: true`) discovers a missing intermediate from a certificate's Authority Information Access URL (§4.2.2.1) over `pki.transport`, triggered only on a pool miss and bounded against SSRF and amplification: HTTPS only, a total fetch budget that caps fetching silently rather than throwing, a per-cert URL cap, a build-wide URL dedupe, a response-size and certificate-count cap, no redirect following, and every fault a silent skip. The TLS trust (`opts.tls`) stays distinct from the PKI `trustAnchors`, and every fetched certificate remains untrusted pool material that still flows through `validate` (never a trust anchor). It is off by default, so the default build is byte-identical offline. An `opts.direction` of `"reverse"` searches from a trust anchor toward the leaf (RFC 4158 §3.1), narrower when the anchor set is small and the leaf's issuer options fan out, and `"auto"` picks the direction by first-hop fan-out; reverse building reuses the same pool, visited set, caps, and `validate` gate, so the direction changes only search order, and the anchor is excluded from the returned path. Reverse building is pool-only and does not combine with `fetchAia`. When `opts.userInitialPolicySet` names acceptable certificate-policy OIDs and more than one path validates, build returns the accepted path whose user-constrained policy set best satisfies that set (RFC 4158 §4) rather than the first accepted path, the ranking bounded by the same candidate cap and a malformed set refused with `path/bad-input`; an `anyPolicy` entry is unconstrained and returns the first accepted path. In a mesh of cross-certified domains, where many candidates chain by name to the same place, a candidate is ranked by how many leading relative distinguished names it shares with the name the search is heading for (§3.5.16 and the §3.5.19 reverse method), so a certificate in the target's own domain is tried before one from a cross-certified domain, and forward building sorts a candidate under every candidate that can complete the path when its path length constraint cannot cover the certificates already below it (§3.5.7), an ordering that outranks the other hints rather than competing with them. No candidate is removed and an unbounded search still reaches every path the pool holds; a bounded one spends `maxCandidatesConsidered` on whichever branches the order steers it to. Pure and re-entrant — `validate`, `build`, `crlChecker`, `ocspChecker` |
234
234
  | `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key), subject alternative names, and certificate policies from the spec, taking any other extension as pre-encoded DER. It derives the version from the field set and enforces the serial bounds, the UTCTime/GeneralizedTime cutover, the DER default omissions, and the CA cross-field rules; a violation throws a typed `CertificateError`. Returns DER, or a PEM `CERTIFICATE` with `opts.pem`. Every arm is independently verified by OpenSSL. Parsing stays at `pki.schema.x509.parse` — `sign` |
235
235
  | `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
236
236
  | `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
@@ -245,7 +245,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
245
245
  | `pki.ocsp` | Online Certificate Status Protocol (RFC 6960), both the responder and relying-party surface. `buildRequest(query, opts)` builds an OCSPRequest for one or more `{ cert, issuer }` pairs, with the CertID hashed under SHA-1 by default per the RFC 5019 lightweight profile or under SHA-2, plus an optional RFC 9654 nonce and an optional requestor signature. `sign(responseData, responder, opts)` produces a signed BasicOCSPResponse over the exact `ResponseData` DER, from the issuing CA directly or a delegated responder, under any `pki.cms.sign` key including the post-quantum ML-DSA and SLH-DSA sets, with `good`, `revoked` (reason and time), or `unknown` per-certificate status. `buildErrorResponse(status)` produces the unsigned §2.3 error (`tryLater`, `unauthorized`, and the rest). `verify(response, opts)` verifies a response fail-closed against the same hardened gates `pki.path.ocspChecker` runs: the CertID binding, responder authorization (the issuing CA, or a CA-issued delegate bearing id-kp-OCSPSigning and id-pkix-ocsp-nocheck and passing the full out-of-path certificate gates), the signature over `tbsResponseDataBytes`, currency against `thisUpdate` and `nextUpdate`, and the request-nonce echo. It returns `{ status: "good" / "revoked" / "unknown", ... }` and never silently accepts. `verifyRequest(request, opts)` is the responder-side inverse of `buildRequest`: it verifies a client's signed request (RFC 6960 §4.1.1) under the requestor certificate the request carries, trying each embedded certificate since the field is unordered, and reports `signed`, `signatureValid`, every certificate whose key verified (`signerCerts`, so a key carried under an expired certificate beside its renewal is not hidden behind ordering) with the first one's decoded subject, the full embedded certificate bag (`certs`, including intermediates for path building), and the request's CertIDs; an unsigned request is reported with `signed: false` rather than refused. Transport-free — `buildRequest`, `sign`, `buildErrorResponse`, `verify`, `verifyRequest` |
246
246
  | `pki.ct` | Certificate Transparency (RFC 6962). `parseSctList` decodes the `SignedCertificateTimestampList` a certificate or OCSP response carries, a TLS-presentation-language payload inside the §3.3 double DER wrap, into per-SCT log id, exact `timestamp` (BigInt), named signature algorithm, and raw signature. `reconstructSignedData` rebuilds the exact `digitally-signed` preimage, and `verifySct` verifies an SCT signature against a log's public key, routing an ECDSA signature through the strict DER-conformance gate and verifying through the crypto engine, resolving true or false and throwing a typed error on a structural fault. On the producing side, `encodeSctList` builds the extension value byte for byte as the exact inverse of `parseSctList`, and `signSct` performs a log's signing step. For trust, `parseLogList` ingests the CT log-list JSON into constraint-carrying trusted logs, recomputing each log's id as SHA-256 of its key and refusing a disagreeing id (a swapped key, §3.2) and decoding the state and temporal-interval constraints; `verifySctWithLogList` resolves the log key from an SCT's log id, enforces the state (usable, qualified, and readonly trusted; retired only before retirement; pending and rejected refused) and the temporal-interval window, then delegates the signature check to `verifySct`. `verifyLogListSignature(json, signature, publicKey)` verifies the detached `log_list.sig` over the raw log-list bytes against a caller-pinned signer key (RSASSA-PKCS1-v1.5/SHA-256 and an EC P-256 arm, with forgeable-key defenses failing closed), cross-checked against `openssl dgst`. `fetchLogList(opts)` turns that chain into a live client: it GETs the `log_list.json` and its detached `log_list.sig` over `pki.transport`, verifies the detached signature over the raw fetched bytes against a caller-pinned distributor key before parsing, so an unverified document is never parsed, read, cached, or surfaced, then ingests the same bytes through `parseLogList` and returns the trusted-log set plus the surfaced `version` and `timestamp`. Above the per-SCT layer, `verifySctList` renders a certificate-level verdict over every SCT a certificate carries (§3.3), reporting how many distinct trusted logs verified an SCT (so a duplicated SCT cannot inflate the count) and from how many distinct trusted operators against a caller's CT policy (`minScts` and `minOperators`, both defaulting to the RFC floor of one), where a policy shortfall is a verdict and a per-SCT failure is a recorded row rather than a thrown call; `x509CertEntry` reconstructs the precertificate log entry from a final certificate by removing the SCT-list extension from its TBSCertificate as byte surgery, so its embedded SCTs verify end to end (§3.2). The toolkit bakes in no vendor URL or key, TLS trust is explicit with `rejectUnauthorized` always on, each response is size-capped before the trust chain, and the transport is injectable so the whole path is testable offline — `parseSctList`, `reconstructSignedData`, `verifySct`, `encodeSctList`, `signSct`, `parseLogList`, `verifySctWithLogList`, `verifySctList`, `x509CertEntry`, `verifyLogListSignature`, `fetchLogList` |
247
247
  | `pki.merkle` | Merkle-tree proof verification (RFC 6962 / RFC 9162). `leafHash`, `nodeHash`, and `emptyRootHash` build the domain-separated (0x00 leaf, 0x01 node) SHA-256 tree hashes. `verifyInclusion` folds an audit proof back to a root, and `verifyConsistency` reconstructs both the old and new root, which is the append-only guarantee; each is constant-time-compared to a trusted checkpoint root. Fail-closed on bad geometry, sync hashing, transport-free — `leafHash`, `nodeHash`, `emptyRootHash`, `verifyInclusion`, `verifyConsistency` |
248
- | `pki.trust` | Mozilla and CCADB trust-store ingestion. `parseCertdata` reads the NSS `certdata.txt` object stream and `parseCcadbCsv` the CCADB CSV export, both into one constraint-carrying anchor shape: the per-purpose trust bits, where only `CKT_NSS_TRUSTED_DELEGATOR` grants, and the per-purpose distrust-after dates the bare root list omits. Certificate and trust objects pair by byte-exact issuer and serial rather than adjacency and are cross-checked against the parsed DER, so metadata cannot attach to the wrong root. `anchor()` hands an entry to `pki.path.validate({ trustAnchors, checkPurpose })`. Offline, fail-closed, bounded — `parseCertdata`, `parseCcadbCsv`, `anchor` |
248
+ | `pki.trust` | Mozilla and CCADB trust-store ingestion. `parseCertdata` reads the NSS `certdata.txt` object stream and `parseCcadbCsv` the CCADB CSV export, both into one constraint-carrying anchor shape: the per-purpose trust bits, where only `CKT_NSS_TRUSTED_DELEGATOR` grants, and the per-purpose distrust-after dates the bare root list omits. Certificate and trust objects pair by byte-exact issuer and serial rather than adjacency and are cross-checked against the parsed DER, so metadata cannot attach to the wrong root. `anchor()` hands an entry to `pki.path.validate({ trustAnchors, checkPurpose })`, and `anchor(entry, { nameConstraints })` attaches the namespace a root program trusts a root for when that is narrower than the root certificate states, a `{ permitted, excluded }` pair of `{ tag, base }` subtrees that `validate` seeds as the RFC 5280 §6.1.1(h)(i) initial value, intersecting with each certificate's own constraints. Offline, fail-closed, bounded — `parseCertdata`, `parseCcadbCsv`, `anchor` |
249
249
  | `pki.shbs` | Stateful hash-based signature verification: HSS/LMS (RFC 8554), carried in X.509 by RFC 9802 and in CMS by RFC 9708, profiled by NIST SP 800-208 for CNSA 2.0 firmware signing. `verify` checks an HSS signature, where every level must pass, and `verifyLms` a single-tree LMS, over the raw public-key and signature blobs the parsers already surface. Pure public-input SHA-256 and SHAKE256 hashing, a data-driven typecode registry, and bounds-before-slice reads; a malformed blob throws a typed `ShbsError` while a well-formed but wrong signature returns `false`. Verification only by design, since stateful signing needs atomic one-time-key state that belongs in an HSM — `verify`, `verifyLms` |
250
250
  | `pki.hpke` | Hybrid Public Key Encryption (RFC 9180), the encrypt-to-a-public-key primitive behind TLS ECH, MLS, and OHTTP. `setupS` and `setupR` establish a sender or recipient context (KEM encapsulation plus the HKDF key schedule); the context's `seal` and `open` AEAD-encrypt with a sequence-counter nonce, and `export` derives further secrets; the module-level `seal` and `open` are single-shot wrappers. DHKEM (P-256, P-521, X25519, X448) by HKDF-SHA256/SHA512 by AES-GCM / ChaCha20Poly1305 / export-only, across all four modes, proven against the RFC 9180 Appendix A vectors. DHKEM(P-384) and HKDF-SHA384 are RFC-registered but Appendix A ships no vector for them, so they fail closed until an authoritative KAT exists. Pure composition over `node:crypto`; ML-KEM and X-Wing are a registry data-row extension pending stable drafts — `suites`, `setupS`, `setupR`, `seal`, `open` |
251
251
  | `pki.kem` | Composite ML-KEM key establishment (draft-ietf-lamps-pq-composite-kem), a post-quantum ML-KEM hybridized with a traditional RSA-OAEP, ECDH, X25519, or X448 so the established secret holds if either component is later broken. `encapsulate` turns a recipient's composite `SubjectPublicKeyInfo` into a 256-bit shared secret and a ciphertext; `decapsulate` recovers the same secret from the ciphertext and the composite PKCS#8 private key. Each component KEM runs independently and the two secrets are mixed through a SHA3-256 combiner that binds the traditional ciphertext, the traditional public key, and a per-algorithm label. The twelve algorithms pair ML-KEM-768 and ML-KEM-1024 with RSA-OAEP 2048/3072/4096, ECDH over P-256/P-384/P-521 and brainpoolP256r1/P384r1, X25519, and X448, each verified against the draft Appendix G known-answer vectors; a malformed key or ciphertext, an unsupported algorithm, or a component decapsulation failure throws a typed `KemError` — `encapsulate`, `decapsulate` |
package/lib/guard-name.js CHANGED
@@ -4,6 +4,11 @@
4
4
  // @internal
5
5
 
6
6
  var intrinsic = require("./guard-intrinsic");
7
+ var _append = require("./guard-list").append;
8
+ var _assertCanonicalOid = require("./guard-identifier").assertCanonicalOid;
9
+ var _ipUtils = require("./ip-utils");
10
+ var _isIPv4 = _ipUtils.isIPv4;
11
+ var _expandIpv6Hex = _ipUtils.expandIpv6Hex;
7
12
 
8
13
  var _charCodeAt = intrinsic.uncurry(String.prototype.charCodeAt);
9
14
  var _charAt = intrinsic.uncurry(String.prototype.charAt);
@@ -11,6 +16,7 @@ var _toLowerCase = intrinsic.uncurry(String.prototype.toLowerCase);
11
16
  var _toUpperCase = intrinsic.uncurry(String.prototype.toUpperCase);
12
17
  var _strSlice = intrinsic.uncurry(String.prototype.slice);
13
18
  var _lastIndexOf = intrinsic.uncurry(String.prototype.lastIndexOf);
19
+ var _indexOf = intrinsic.uncurry(String.prototype.indexOf);
14
20
  var _numToString = intrinsic.uncurry(Number.prototype.toString);
15
21
  var _create = intrinsic.create;
16
22
  var _hasOwn = intrinsic.hasOwn;
@@ -197,9 +203,274 @@ function lowerAscii(s) {
197
203
  return out;
198
204
  }
199
205
 
206
+ function _charTable(chars) {
207
+ var t = _create(null);
208
+ for (var i = 0; i < chars.length; i++) t[_charCodeAt(chars, i)] = true;
209
+ return t;
210
+ }
211
+ var _FQDN_TABLE = _charTable("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-");
212
+ var _DIGDOT_TABLE = _charTable("0123456789.");
213
+ function _allCharsIn(s, table) {
214
+ if (s.length === 0) return false;
215
+ for (var i = 0; i < s.length; i++) if (!table[_charCodeAt(s, i)]) return false;
216
+ return true;
217
+ }
218
+
219
+ function stripTrailingDot(s) { return _charAt(s, s.length - 1) === "." ? _strSlice(s, 0, -1) : s; }
220
+
221
+ /** @internal A host name of two or more labels that is not an address, which is the form a URI
222
+ * name constraint is compared by (RFC 5280 sec. 4.2.1.10). */
223
+ function isFqdnHost(host) {
224
+ var h = stripTrailingDot(host);
225
+ if (h === "" || _indexOf(h, ".") === -1) return false;
226
+ if (!_allCharsIn(h, _FQDN_TABLE)) return false;
227
+ if (_allCharsIn(h, _DIGDOT_TABLE)) return false;
228
+ return true;
229
+ }
230
+
231
+ var _LDH_ALNUM = _charTable("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
232
+ var MAX_LABEL = 63;
233
+ var MAX_HOST = 253;
234
+ var MAX_LOCAL_PART = 64;
235
+
236
+ /** @internal One label of a host name (RFC 1034 sec. 3.5, RFC 1123 sec. 2.1): letters, digits and
237
+ * hyphens, with a hyphen at neither edge, and 63 characters at most. */
238
+ function _isHostLabel(s, from, to) {
239
+ var n = to - from;
240
+ if (n === 0 || n > MAX_LABEL) return false;
241
+ if (!_LDH_ALNUM[_charCodeAt(s, from)] || !_LDH_ALNUM[_charCodeAt(s, to - 1)]) return false;
242
+ for (var i = from + 1; i < to - 1; i++) {
243
+ var c = _charCodeAt(s, i);
244
+ if (!_LDH_ALNUM[c] && c !== 0x2d) return false;
245
+ }
246
+ return true;
247
+ }
248
+
249
+ /** @internal A host name written as labels separated by dots, carrying no trailing dot: the caller
250
+ * strips the one dot the comparison strips, so a second one is an empty label and is refused. */
251
+ function _isHostName(s) {
252
+ if (s.length === 0 || s.length > MAX_HOST) return false;
253
+ var start = 0;
254
+ for (var i = 0; i <= s.length; i++) {
255
+ if (i === s.length || _charCodeAt(s, i) === 0x2e) {
256
+ if (!_isHostLabel(s, start, i)) return false;
257
+ start = i + 1;
258
+ }
259
+ }
260
+ return true;
261
+ }
262
+
263
+ var _ATEXT_TABLE = _charTable("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-/=?^_`{|}~");
264
+
265
+ /** @internal A quoted local part (RFC 5321 sec. 4.1.2 Quoted-string): printable ASCII between
266
+ * quotes, where a backslash escapes the character after it. */
267
+ function _isQuotedLocal(s) {
268
+ var n = s.length;
269
+ if (n < 2 || _charCodeAt(s, n - 1) !== 0x22) return false;
270
+ for (var i = 1; i < n - 1; i++) {
271
+ var c = _charCodeAt(s, i);
272
+ if (c === 0x5c) {
273
+ i += 1;
274
+ if (i >= n - 1) return false;
275
+ var e = _charCodeAt(s, i);
276
+ if (e < 0x20 || e > 0x7e) return false;
277
+ continue;
278
+ }
279
+ if (c < 0x20 || c > 0x7e || c === 0x22) return false;
280
+ }
281
+ return true;
282
+ }
283
+
284
+ /** @internal The local part of a mailbox (RFC 5321 sec. 4.1.2): either a quoted string, or atoms
285
+ * separated by dots, which is the form a certificate's mailbox is compared against. */
286
+ function _isMailboxLocal(s) {
287
+ if (s.length === 0 || s.length > MAX_LOCAL_PART) return false;
288
+ if (_charCodeAt(s, 0) === 0x22) return _isQuotedLocal(s);
289
+ var pieceLen = 0;
290
+ for (var i = 0; i < s.length; i++) {
291
+ var c = _charCodeAt(s, i);
292
+ if (c === 0x2e) {
293
+ if (pieceLen === 0) return false;
294
+ pieceLen = 0;
295
+ continue;
296
+ }
297
+ if (!_ATEXT_TABLE[c]) return false;
298
+ pieceLen += 1;
299
+ }
300
+ return pieceLen > 0;
301
+ }
302
+
303
+ var _IPV6_TAG = "ipv6:";
304
+ /** @internal An address literal (RFC 5321 sec. 4.1.3), the other form a mailbox may name its domain
305
+ * in: an IPv4 address in brackets, or an IPv6 address behind the tag that introduces one. The
306
+ * comparison holds a mailbox constraint's domain to an exact match, so a literal is a domain it can
307
+ * reach a verdict on. */
308
+ function _isAddressLiteral(s) {
309
+ var n = s.length;
310
+ if (n < 3 || _charCodeAt(s, 0) !== 0x5b || _charCodeAt(s, n - 1) !== 0x5d) return false;
311
+ var inner = _strSlice(s, 1, n - 1);
312
+ if (_toLowerCase(_strSlice(inner, 0, _IPV6_TAG.length)) === _IPV6_TAG) {
313
+ return _expandIpv6Hex(_strSlice(inner, _IPV6_TAG.length)) !== null;
314
+ }
315
+ return _isIPv4(inner);
316
+ }
317
+
318
+ /** @internal The two halves of a mailbox, `null` when it carries no separator and the string
319
+ * "ambiguous" when it carries more than one. This is the split the rfc822Name comparison runs, so a
320
+ * constraint the comparison cannot separate is one this answers the same way. */
321
+ function splitMailbox(addr) {
322
+ var first = _indexOf(addr, "@");
323
+ if (first === -1) return null;
324
+ if (first !== _lastIndexOf(addr, "@")) return "ambiguous";
325
+ return [_strSlice(addr, 0, first), _strSlice(addr, first + 1)];
326
+ }
327
+
328
+ /** @internal A host name, optionally written as a subtree with a leading dot, and with the one
329
+ * trailing dot the comparison strips. */
330
+ function _hostConstraintBody(s) {
331
+ var h = stripTrailingDot(s);
332
+ return _charAt(h, 0) === "." ? _strSlice(h, 1) : h;
333
+ }
334
+
335
+ /** @internal Why a name-constraint base cannot be enforced, or null when it can. A base outside the
336
+ * form its tag names is not a narrower namespace: an empty dNSName base matches every name, and a
337
+ * base holding characters no host name can hold matches none, so the same value that reads as a
338
+ * restriction either lifts one or applies to nothing. The comparisons this mirrors are in
339
+ * lib/path-validate.js, and a base refused here is one they would answer with no verdict. */
340
+ function constraintBaseRefusal(tag, base) {
341
+ if (typeof base !== "string") return "must be a string for tag " + tag;
342
+ if (tag === 1) {
343
+ var mb = splitMailbox(base);
344
+ if (mb === null) {
345
+ if (_isAddressLiteral(base)) return null;
346
+ return _isHostName(_hostConstraintBody(base)) ? null
347
+ : "must be a mailbox, a host name, or a host name written as a subtree with a leading dot";
348
+ }
349
+ if (mb === "ambiguous") {
350
+ return "carries more than one at-sign, so the comparison cannot tell which one separates the mailbox";
351
+ }
352
+ if (!_isMailboxLocal(mb[0])) return "must carry the local part of a mailbox before its at-sign";
353
+ if (_isAddressLiteral(mb[1])) return null;
354
+ return _isHostName(stripTrailingDot(mb[1])) ? null
355
+ : "must end in the host name or bracketed address literal of a mailbox";
356
+ }
357
+ if (tag === 2) {
358
+ return _isHostName(_hostConstraintBody(base)) ? null
359
+ : "must be a host name, optionally written as a subtree with a leading dot";
360
+ }
361
+ if (tag === 6) {
362
+ var h = _hostConstraintBody(_toLowerCase(base));
363
+ var dotted = _isHostName(h) && _indexOf(h, ".") !== -1 && !_allCharsIn(h, _DIGDOT_TABLE);
364
+ return dotted ? null
365
+ : "must be a dotted host name, which is the part of a URI a certificate is compared by";
366
+ }
367
+ return null;
368
+ }
369
+
370
+ var _ATV_KEYS = ["type", "value", "name"];
371
+
372
+ /** @internal A distinguished name a caller supplied, copied into fresh plain objects by reading
373
+ * descriptors only. A Proxy answers its own reads and an accessor runs caller code, so either one
374
+ * at any level is refused before anything is copied: a name that decides what it says while it is
375
+ * being read can show a narrow value to a check and a wide one to the use, and where the name is a
376
+ * namespace restriction that is the difference between a certificate being refused and admitted. */
377
+ function copyDnRdns(rdns, E, code, who) {
378
+ assertPlainDnRdns(rdns, E, code, who);
379
+ /** @internal A name of no relative names is a prefix of every name, so as a constraint it reaches
380
+ * the same verdict on all of them. */
381
+ if (rdns.length === 0) throw E(code, who + " must name at least one relative distinguished name");
382
+ var out = [];
383
+ for (var i = 0; i < rdns.length; i++) {
384
+ var rd = intrinsic.getOwnPropertyDescriptor(rdns, i);
385
+ if (rd === undefined) throw E(code, who + " index " + i + " is a hole or is inherited; every entry must be its own");
386
+ var rdn = rd.value;
387
+ if (!_isArray(rdn)) throw E(code, who + "[" + i + "] must be an array of attributes");
388
+ if (rdn.length === 0) throw E(code, who + "[" + i + "] must carry at least one attribute");
389
+ var rdnOut = [];
390
+ for (var j = 0; j < rdn.length; j++) {
391
+ var ad = intrinsic.getOwnPropertyDescriptor(rdn, j);
392
+ if (ad === undefined) throw E(code, who + "[" + i + "] index " + j + " is a hole or is inherited; every entry must be its own");
393
+ var atv = ad.value;
394
+ if (atv === null || typeof atv !== "object") throw E(code, who + "[" + i + "][" + j + "] must be an attribute object carrying a type and a value");
395
+ var atvOut = {};
396
+ for (var k = 0; k < _ATV_KEYS.length; k++) {
397
+ var fd = intrinsic.getOwnPropertyDescriptor(atv, _ATV_KEYS[k]);
398
+ if (fd === undefined) continue;
399
+ intrinsic.defineProperty(atvOut, _ATV_KEYS[k], { value: fd.value, enumerable: true, configurable: true, writable: true });
400
+ }
401
+ if (!_hasOwn(atvOut, "type") || !_hasOwn(atvOut, "value")) {
402
+ throw E(code, who + "[" + i + "][" + j + "] must carry its type and value as own data properties");
403
+ }
404
+ /** @internal Every attribute a certificate's name is compared against is a string compared to
405
+ * a string, so an attribute holding anything else is equal to nothing it will ever meet, and
406
+ * NaN is not even equal to itself. A name built out of those is not a narrower namespace. */
407
+ _assertCanonicalOid(atvOut.type, E, code, who + "[" + i + "][" + j + "].type");
408
+ if (typeof atvOut.value !== "string") {
409
+ throw E(code, who + "[" + i + "][" + j + "].value must be a string, the form a name is compared in");
410
+ }
411
+ assertNoControlBytes(atvOut.value, E, code, who + "[" + i + "][" + j + "].value");
412
+ _append(rdnOut, atvOut);
413
+ }
414
+ _append(out, rdnOut);
415
+ }
416
+ return out;
417
+ }
418
+
419
+ /** @internal The shape check the copy above relies on. */
420
+ function assertPlainDnRdns(rdns, E, code, who) {
421
+ if (intrinsic.types.isProxy(rdns)) throw E(code, who + " must be a plain array, not a Proxy");
422
+ for (var i = 0; i < rdns.length; i++) {
423
+ var rd = intrinsic.getOwnPropertyDescriptor(rdns, i);
424
+ if (rd === undefined) continue;
425
+ if (!_hasOwn(rd, "value")) throw E(code, who + " entry " + i + " must be a data property, not an accessor");
426
+ var rdn = rd.value;
427
+ if (!_isArray(rdn)) continue;
428
+ if (intrinsic.types.isProxy(rdn)) throw E(code, who + "[" + i + "] must be a plain array, not a Proxy");
429
+ for (var j = 0; j < rdn.length; j++) {
430
+ var ad = intrinsic.getOwnPropertyDescriptor(rdn, j);
431
+ if (ad === undefined) continue;
432
+ if (!_hasOwn(ad, "value")) throw E(code, who + "[" + i + "] entry " + j + " must be a data property, not an accessor");
433
+ var atv = ad.value;
434
+ if (atv === null || typeof atv !== "object") continue;
435
+ if (intrinsic.types.isProxy(atv)) throw E(code, who + "[" + i + "][" + j + "] must not be a Proxy");
436
+ if (_isArray(atv)) throw E(code, who + "[" + i + "][" + j + "] must be an attribute object, not an array");
437
+ for (var k = 0; k < _ATV_KEYS.length; k++) {
438
+ var fd = intrinsic.getOwnPropertyDescriptor(atv, _ATV_KEYS[k]);
439
+ if (fd !== undefined && !_hasOwn(fd, "value")) {
440
+ throw E(code, who + "[" + i + "][" + j + "]." + _ATV_KEYS[k] + " must be a data property, not an accessor");
441
+ }
442
+ }
443
+ }
444
+ }
445
+ }
446
+
447
+ /** @internal The `rdns` of a directoryName base, captured the same way. An inherited Proxy answers
448
+ * `in` through its has trap, which is caller code running inside a read meant to be getter-free, so
449
+ * the prototype chain is walked before the property is asked for at all. Returns undefined when the
450
+ * base carries no rdns array, which the caller reads as "not a directoryName base". */
451
+ function capturedRdns(base, E, code, who) {
452
+ if (intrinsic.types.isProxy(base)) throw E(code, who + " must not be a Proxy");
453
+ var baseProto = intrinsic.getPrototypeOf(base);
454
+ while (baseProto !== null) {
455
+ if (intrinsic.types.isProxy(baseProto)) throw E(code, who + " must not inherit from a Proxy");
456
+ baseProto = intrinsic.getPrototypeOf(baseProto);
457
+ }
458
+ var d = intrinsic.getOwnPropertyDescriptor(base, "rdns");
459
+ if (d === undefined) {
460
+ if ("rdns" in base) throw E(code, who + " rdns must be an own data property, not inherited");
461
+ return undefined;
462
+ }
463
+ if (!_hasOwn(d, "value")) throw E(code, who + " rdns must be a data property, not an accessor");
464
+ if (!_isArray(d.value)) return undefined;
465
+ return copyDnRdns(d.value, E, code, who + " rdns");
466
+ }
467
+
200
468
  module.exports = intrinsic.freeze({
469
+ capturedRdns: capturedRdns, copyDnRdns: copyDnRdns,
201
470
  assertNoControlBytes: assertNoControlBytes, assertPrintableIa5: assertPrintableIa5,
202
471
  dnEqual: dnEqual, rdnEqual: rdnEqual, emailEqual: emailEqual, dpnCorresponds: dpnCorresponds,
203
472
  escapeControlBytes: escapeControlBytes, escapeDnValue: escapeDnValue,
204
473
  lowerAscii: lowerAscii,
474
+ stripTrailingDot: stripTrailingDot, isFqdnHost: isFqdnHost, splitMailbox: splitMailbox,
475
+ constraintBaseRefusal: constraintBaseRefusal,
205
476
  });
@@ -323,12 +323,7 @@ function requireCriticalExt(ext, name, checks) {
323
323
  }
324
324
 
325
325
 
326
- function splitMailbox(addr) {
327
- var first = addr.indexOf("@");
328
- if (first === -1) return null;
329
- if (first !== addr.lastIndexOf("@")) return "ambiguous";
330
- return [addr.slice(0, first), addr.slice(first + 1)];
331
- }
326
+ var splitMailbox = guard.name.splitMailbox;
332
327
 
333
328
  function emailMatch(constraint, mailbox) {
334
329
  var mb = splitMailbox(mailbox);
@@ -346,7 +341,7 @@ function emailMatch(constraint, mailbox) {
346
341
  return host === c;
347
342
  }
348
343
 
349
- function stripTrailingDot(s) { return s.charAt(s.length - 1) === "." ? s.slice(0, -1) : s; }
344
+ var stripTrailingDot = guard.name.stripTrailingDot;
350
345
 
351
346
  function hostConstraintMatch(constraint, host) {
352
347
  var c = stripTrailingDot(constraint.toLowerCase()), h = stripTrailingDot(host.toLowerCase());
@@ -356,13 +351,6 @@ function hostConstraintMatch(constraint, host) {
356
351
  }
357
352
 
358
353
  function _charTable(chars) { var t = []; for (var i = 0; i < chars.length; i++) t[_charCodeAt(chars, i)] = true; return t; }
359
- var _FQDN_TABLE = _charTable("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-");
360
- var _DIGDOT_TABLE = _charTable("0123456789.");
361
- function _allCharsIn(s, table) {
362
- if (s.length === 0) return false;
363
- for (var i = 0; i < s.length; i++) if (!table[_charCodeAt(s, i)]) return false;
364
- return true;
365
- }
366
354
  function _startsWithDigit(s) { if (s.length === 0) return false; var c = _charCodeAt(s, 0); return c >= 48 && c <= 57; }
367
355
 
368
356
  var _SCHEME_TABLE = _charTable("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+.-");
@@ -389,13 +377,7 @@ function _stripBrackets(s) {
389
377
  return (n >= 2 && _charCodeAt(s, 0) === 91 && _charCodeAt(s, n - 1) === 93) ? s.slice(1, n - 1) : s;
390
378
  }
391
379
 
392
- function isFqdnHost(host) {
393
- var h = stripTrailingDot(host);
394
- if (h === "" || h.indexOf(".") === -1) return false;
395
- if (!_allCharsIn(h, _FQDN_TABLE)) return false;
396
- if (_allCharsIn(h, _DIGDOT_TABLE)) return false;
397
- return true;
398
- }
380
+ var isFqdnHost = guard.name.isFqdnHost;
399
381
 
400
382
  function uriMatch(constraint, uri) {
401
383
  var host = uriHost(uri);
@@ -544,7 +526,7 @@ function treeIsEmpty(tree) { return tree.children.length === 0; }
544
526
 
545
527
  function isSubtreeBaseValid(tag, base) {
546
528
  switch (tag) {
547
- case 1: case 2: case 6: return typeof base === "string";
529
+ case 1: case 2: case 6: return guard.name.constraintBaseRefusal(tag, base) === null;
548
530
  case 7: return Buffer.isBuffer(base) && (base.length === 8 || base.length === 32);
549
531
  case 4: return base !== null && typeof base === "object" && !!base.rdns && intrinsic.isArray(base.rdns);
550
532
  default: return base !== undefined;
@@ -923,7 +905,13 @@ function validateCriticalExtensionStructure(cert) {
923
905
  * intermediate's own `nameConstraints` extension intersects with them and a leaf
924
906
  * must satisfy both. They are a separate generation from
925
907
  * `opts.initialPermittedSubtrees`, so those two intersect as well. A mis-shaped
926
- * subtree is refused with `path/bad-input` rather than left inert.
908
+ * subtree is refused with `path/bad-input` rather than left inert, and so is one
909
+ * whose base is outside the form its tag names: a host name for tags 2 and 6, a
910
+ * mailbox or host name for tag 1, at least one relative name with object
911
+ * identifier types and string values for tag 4, and 8 or 32 bytes for tag 7. An
912
+ * anchor whose `nameConstraints` names no subtree at all is refused the same way.
913
+ * A certificate's own `nameConstraints` extension is compared as the certificate
914
+ * wrote it; this rule is on the subtrees a caller supplies.
927
915
  *
928
916
  * @example
929
917
  * var pair = await pki.key.generate("Ed25519");
@@ -1996,82 +1984,8 @@ var _ATV_KEYS = ["type", "value", "name"];
1996
1984
  * and nothing deeper, so exactly those levels are walked and a self-referencing array is refused
1997
1985
  * rather than followed.
1998
1986
  */
1999
- function _copyDnRdns(rdns, who) {
2000
- _assertPlainDnRdns(rdns, who);
2001
- var out = [];
2002
- for (var i = 0; i < rdns.length; i++) {
2003
- var rd = intrinsic.getOwnPropertyDescriptor(rdns, i);
2004
- if (rd === undefined) throw E("path/bad-input", who + " index " + i + " is a hole or is inherited; every entry must be its own");
2005
- var rdn = rd.value;
2006
- if (!intrinsic.isArray(rdn)) throw E("path/bad-input", who + "[" + i + "] must be an array of attributes");
2007
- var rdnOut = [];
2008
- for (var j = 0; j < rdn.length; j++) {
2009
- var ad = intrinsic.getOwnPropertyDescriptor(rdn, j);
2010
- if (ad === undefined) throw E("path/bad-input", who + "[" + i + "] index " + j + " is a hole or is inherited; every entry must be its own");
2011
- var atv = ad.value;
2012
- if (atv === null || typeof atv !== "object") throw E("path/bad-input", who + "[" + i + "][" + j + "] must be an attribute object carrying a type and a value");
2013
- var atvOut = {};
2014
- for (var k = 0; k < _ATV_KEYS.length; k++) {
2015
- var fd = intrinsic.getOwnPropertyDescriptor(atv, _ATV_KEYS[k]);
2016
- if (fd === undefined) continue;
2017
- intrinsic.defineProperty(atvOut, _ATV_KEYS[k], { value: fd.value, enumerable: true, configurable: true, writable: true });
2018
- }
2019
- if (!intrinsic.hasOwn(atvOut, "type") || !intrinsic.hasOwn(atvOut, "value")) {
2020
- throw E("path/bad-input", who + "[" + i + "][" + j + "] must carry its type and value as own data properties");
2021
- }
2022
- guard.list.append(rdnOut, atvOut);
2023
- }
2024
- guard.list.append(out, rdnOut);
2025
- }
2026
- return out;
2027
- }
2028
- /**
2029
- * @internal The shape check the copy above relies on: a Proxy answers its own reads and an accessor
2030
- * runs caller code, so either one at any level of the directoryName is refused before it is copied.
2031
- */
2032
- function _assertPlainDnRdns(rdns, who) {
2033
- if (intrinsic.types.isProxy(rdns)) throw E("path/bad-input", who + " must be a plain array, not a Proxy");
2034
- for (var i = 0; i < rdns.length; i++) {
2035
- var rd = intrinsic.getOwnPropertyDescriptor(rdns, i);
2036
- if (rd === undefined) continue;
2037
- if (!intrinsic.hasOwn(rd, "value")) throw E("path/bad-input", who + " entry " + i + " must be a data property, not an accessor");
2038
- var rdn = rd.value;
2039
- if (!intrinsic.isArray(rdn)) continue;
2040
- if (intrinsic.types.isProxy(rdn)) throw E("path/bad-input", who + "[" + i + "] must be a plain array, not a Proxy");
2041
- for (var j = 0; j < rdn.length; j++) {
2042
- var ad = intrinsic.getOwnPropertyDescriptor(rdn, j);
2043
- if (ad === undefined) continue;
2044
- if (!intrinsic.hasOwn(ad, "value")) throw E("path/bad-input", who + "[" + i + "] entry " + j + " must be a data property, not an accessor");
2045
- var atv = ad.value;
2046
- if (atv === null || typeof atv !== "object") continue;
2047
- if (intrinsic.types.isProxy(atv)) throw E("path/bad-input", who + "[" + i + "][" + j + "] must not be a Proxy");
2048
- if (intrinsic.isArray(atv)) throw E("path/bad-input", who + "[" + i + "][" + j + "] must be an attribute object, not an array");
2049
- for (var k = 0; k < _ATV_KEYS.length; k++) {
2050
- var fd = intrinsic.getOwnPropertyDescriptor(atv, _ATV_KEYS[k]);
2051
- if (fd !== undefined && !intrinsic.hasOwn(fd, "value")) {
2052
- throw E("path/bad-input", who + "[" + i + "][" + j + "]." + _ATV_KEYS[k] + " must be a data property, not an accessor");
2053
- }
2054
- }
2055
- }
2056
- }
2057
- }
2058
1987
  function _capturedRdns(base, who) {
2059
- if (intrinsic.types.isProxy(base)) throw E("path/bad-input", who + ": a trustAnchor nameConstraints directoryName base must not be a Proxy");
2060
- /** @internal An inherited Proxy answers `in` through its has trap, which is caller code running
2061
- * inside what is meant to be a getter-free read. */
2062
- var baseProto = intrinsic.getPrototypeOf(base);
2063
- while (baseProto !== null) {
2064
- if (intrinsic.types.isProxy(baseProto)) throw E("path/bad-input", who + ": a trustAnchor nameConstraints directoryName base must not inherit from a Proxy");
2065
- baseProto = intrinsic.getPrototypeOf(baseProto);
2066
- }
2067
- var d = intrinsic.getOwnPropertyDescriptor(base, "rdns");
2068
- if (d === undefined) {
2069
- if ("rdns" in base) throw E("path/bad-input", who + ": a trustAnchor nameConstraints directoryName rdns must be an own data property, not inherited");
2070
- return undefined;
2071
- }
2072
- if (!intrinsic.hasOwn(d, "value")) throw E("path/bad-input", who + ": a trustAnchor nameConstraints directoryName rdns must be a data property, not an accessor");
2073
- if (!intrinsic.isArray(d.value)) return undefined;
2074
- return _copyDnRdns(d.value, who + ": a trustAnchor nameConstraints directoryName rdns");
1988
+ return guard.name.capturedRdns(base, E, "path/bad-input", who + ": a trustAnchor nameConstraints directoryName base");
2075
1989
  }
2076
1990
  var _NC_SUBTREE_KEYS = ["tag", "base"];
2077
1991
  var _NC_LIST_KEYS = ["permitted", "excluded"];
@@ -2168,6 +2082,12 @@ function _copyAnchorNameConstraints(nc, who) {
2168
2082
  var checkedList = checkedSubtreeSeeds(copiedList, "trustAnchors[].nameConstraints." + key);
2169
2083
  intrinsic.defineProperty(out, key, { value: checkedList, enumerable: true, configurable: true, writable: true });
2170
2084
  }
2085
+ /** @internal An anchor carrying the option but naming no subtree restricts nothing, and reads to
2086
+ * whoever built it as a namespace that has been applied. */
2087
+ if ((out.permitted === undefined || out.permitted.length === 0) &&
2088
+ (out.excluded === undefined || out.excluded.length === 0)) {
2089
+ throw E("path/bad-input", who + ": a trustAnchor nameConstraints must name at least one permitted or excluded subtree");
2090
+ }
2171
2091
  return out;
2172
2092
  }
2173
2093
 
@@ -2363,16 +2283,76 @@ function _candBaseScore(cand, time) {
2363
2283
  return score;
2364
2284
  }
2365
2285
 
2286
+ /** @internal A relative name that cannot be compared ends the shared prefix below; the count is a sort hint
2287
+ * and every candidate is still tried, so the comparison fault decides nothing. */
2288
+ function _rdnEqualSoft(a, b) {
2289
+ try { return rdnEqual(a, b); }
2290
+ catch (_e) { return false; } // allow:swallow-unverified a name the comparison refuses ends the shared prefix
2291
+ }
2292
+
2293
+ /** @internal How many leading relative names two distinguished names share, under the RFC 5280 sec. 7.1
2294
+ * comparison. Names in a public-key infrastructure are built as a tree, so in a mesh of cross-certified domains
2295
+ * a certificate in the target's own domain shares a prefix with it and one from a foreign domain shares little
2296
+ * or none (RFC 4158 sec. 3.5.16, sec. 3.5.19). */
2297
+ function rdnPrefixLength(a, b) {
2298
+ if (!intrinsic.isArray(a) || !intrinsic.isArray(b)) return 0;
2299
+ var n = a.length < b.length ? a.length : b.length;
2300
+ for (var i = 0; i < n; i++) {
2301
+ if (!_rdnEqualSoft(a[i], b[i])) return i;
2302
+ }
2303
+ return n;
2304
+ }
2305
+
2306
+ var RDN_PREFIX_WEIGHT = 5;
2307
+ /** @internal Within the name term, a shared prefix is the weaker signal and stays under an exact match,
2308
+ * however many relative names it shares. The terms are summed the way the rest of the RFC 4158 sec. 3.5
2309
+ * hints are, so this bounds the name term rather than the whole score. */
2310
+ var RDN_PREFIX_MAX = 95;
2311
+ var EXACT_NAME_BONUS = 100;
2312
+ function _prefixScore(a, b) {
2313
+ var s = rdnPrefixLength(a, b) * RDN_PREFIX_WEIGHT;
2314
+ return s > RDN_PREFIX_MAX ? RDN_PREFIX_MAX : s;
2315
+ }
2316
+
2317
+ /** @internal RFC 4158 sec. 3.5.7: a certificate whose path length constraint cannot cover the certificates
2318
+ * already below it in the path cannot complete that path. The constraint counts the non-self-issued
2319
+ * certificates that follow (RFC 5280 sec. 6.1.4(m)), which forward building knows from the chain it holds, so
2320
+ * a key-rollover certificate below the candidate spends none of the budget. */
2321
+ function _forwardPathLenIneligible(cand, chain) {
2322
+ /** @internal A forward chain is built by prepending, so the leaf is its last entry and every entry before
2323
+ * it is an intermediate the candidate would sit above. */
2324
+ var below = 0;
2325
+ for (var i = 0; i < chain.length - 1; i++) {
2326
+ if (!selfIssued(chain[i])) below += 1;
2327
+ }
2328
+ if (below === 0) return false;
2329
+ var bc = softDecode(cand, OID.basicConstraints);
2330
+ var lim = bc && bc.value ? bc.value.pathLenConstraint : undefined;
2331
+ if (typeof lim !== "number") return false;
2332
+ return lim < below;
2333
+ }
2334
+
2335
+ /** @internal Reverse building holds no such count: it knows what lies between a candidate and the anchor, and
2336
+ * the constraint governs what lies between the candidate and the target, which is the part not yet built. Every
2337
+ * candidate at one frame would take the same penalty, which orders nothing, so the rule is forward-only here. */
2338
+
2339
+ /** @internal RFC 4158 sec. 3.5.19, a candidate whose subject shares more relative names with the target's
2340
+ * issuer, orders nothing in this direction: forward building selects a candidate BY its subject matching the
2341
+ * current certificate's issuer, so every candidate at one decision point carries that same name. Reverse
2342
+ * building selects by issuer instead, and there the rule is the ordering below. */
2366
2343
  function scoreCandidate(cand, childAki, anchors, time) {
2367
2344
  var score = _candBaseScore(cand, time);
2368
2345
  if (childAki) {
2369
2346
  var d = softDecode(cand, OID.subjectKeyIdentifier);
2370
2347
  if (d && Buffer.isBuffer(d.value) && d.value.equals(childAki)) score += 1000;
2371
2348
  }
2349
+ var best = 0;
2372
2350
  for (var i = 0; i < anchors.length; i++) {
2373
- if (nameMatchSoft(cand.issuer.rdns, anchors[i].name.rdns)) { score += 100; break; }
2351
+ if (nameMatchSoft(cand.issuer.rdns, anchors[i].name.rdns)) { best = EXACT_NAME_BONUS; break; }
2352
+ var p = _prefixScore(cand.issuer.rdns, anchors[i].name.rdns);
2353
+ if (p > best) best = p;
2374
2354
  }
2375
- return score;
2355
+ return score + best;
2376
2356
  }
2377
2357
 
2378
2358
  function scoreCandidateReverse(cand, parentCert, leafCert, time) {
@@ -2384,7 +2364,8 @@ function scoreCandidateReverse(cand, parentCert, leafCert, time) {
2384
2364
  if (d && intrinsic.isBuffer(d.value) && intrinsic.bufferEquals(d.value, candAki)) score += 1000;
2385
2365
  }
2386
2366
  }
2387
- if (nameMatchSoft(leafCert.issuer.rdns, cand.subject.rdns)) score += 100;
2367
+ if (nameMatchSoft(leafCert.issuer.rdns, cand.subject.rdns)) score += EXACT_NAME_BONUS;
2368
+ else score += _prefixScore(cand.subject.rdns, leafCert.issuer.rdns);
2388
2369
  return score;
2389
2370
  }
2390
2371
 
@@ -2431,8 +2412,14 @@ function _assertUserInitialPolicySet(uips, prefix) {
2431
2412
  }
2432
2413
  }
2433
2414
 
2415
+ /** @internal Sorted so the candidate tried FIRST is last in the array, since the caller pushes onto a stack.
2416
+ * A candidate whose path length constraint cannot cover the certificates below it sorts under every candidate
2417
+ * that can, whatever the heuristics score it, and the score orders within each of the two groups. */
2434
2418
  function _pushCandidates(frame, scored, stack, counter, down) {
2435
- scored.sort(function (a, b) { return a.score - b.score; });
2419
+ scored.sort(function (a, b) {
2420
+ if (!a.ineligible !== !b.ineligible) return a.ineligible ? -1 : 1;
2421
+ return a.score - b.score;
2422
+ });
2436
2423
  var n = 0;
2437
2424
  for (var ci = 0; ci < scored.length; ci++) {
2438
2425
  counter.tick();
@@ -2545,7 +2532,25 @@ async function _fetchAiaIssuers(current, aia) {
2545
2532
  * Candidate issuers are matched by RFC 5280 7.1 name chaining, prioritized by the RFC 4158 3.5
2546
2533
  * heuristics (a subjectKeyIdentifier/authorityKeyIdentifier match, an anchor-adjacent issuer,
2547
2534
  * CA + keyCertSign, validity at the check time; each orders the search without excluding a
2548
- * candidate), and searched depth-first with backtracking: the first ordered path that
2535
+ * candidate).
2536
+ *
2537
+ * Where cross-certified domains meet, several candidates chain by name and the order they are
2538
+ * tried in decides how much of the mesh is walked. Two more RFC 4158 3.5 orderings apply there.
2539
+ * A candidate is ranked by how many leading relative names it shares with the name the search is
2540
+ * heading for, its issuer against a trust anchor's name going forward (3.5.16) and its subject
2541
+ * against the leaf's issuer going in reverse (3.5.16 and 3.5.19 reverse methods), so a
2542
+ * certificate in the target's own domain is tried before one from a cross-certified domain.
2543
+ * Forward building also sorts a candidate under every candidate that can complete the path when its
2544
+ * `basicConstraints` path length constraint cannot cover the certificates already below it (3.5.7,
2545
+ * counting the non-self-issued ones the way 5280 6.1.4(m) does). That one outranks the other hints
2546
+ * rather than competing with them, so a key identifier or an anchor-adjacent issuer does not raise
2547
+ * a candidate whose constraint the path already exceeds. All of it is ordering alone: no candidate
2548
+ * is removed, every assembled path is handed to `validate`, and an unbounded search still reaches
2549
+ * every path the pool holds. A bounded one spends its budget on whichever branches it is steered
2550
+ * to, so a build that reports `path/build-limit` where an earlier order succeeded wants a larger
2551
+ * `maxCandidatesConsidered`, and the same holds for the `maxAiaFetches` allowance.
2552
+ *
2553
+ * The search runs depth-first with backtracking: the first ordered path that
2549
2554
  * `pki.path.validate` accepts wins. A name or key-identifier match is only an ordering hint;
2550
2555
  * every accept flows through `validate`, so `build` never weakens or duplicates a 6.1 check. The
2551
2556
  * search over the untrusted pool is bounded: a depth cap on chain length, a total-work cap on
@@ -2782,7 +2787,8 @@ async function build(leaf, opts) {
2782
2787
  var fbScored = [];
2783
2788
  for (var pj = fb.poolMark; pj < pool.length; pj++) {
2784
2789
  if (nameMatchSoft(pool[pj].subject.rdns, fbCur.issuer.rdns)) {
2785
- guard.list.append(fbScored, { cand: pool[pj], score: scoreCandidate(pool[pj], fbAki, anchors, opts.time) });
2790
+ guard.list.append(fbScored, { cand: pool[pj], score: scoreCandidate(pool[pj], fbAki, anchors, opts.time),
2791
+ ineligible: _forwardPathLenIneligible(pool[pj], fb.chain) });
2786
2792
  }
2787
2793
  }
2788
2794
  fb.poolMark = pool.length;
@@ -2810,7 +2816,8 @@ async function build(leaf, opts) {
2810
2816
  var scored = [];
2811
2817
  for (var pi = 0; pi < pool.length; pi++) {
2812
2818
  if (nameMatchSoft(pool[pi].subject.rdns, current.issuer.rdns)) {
2813
- guard.list.append(scored, { cand: pool[pi], score: scoreCandidate(pool[pi], childAki, anchors, opts.time) });
2819
+ guard.list.append(scored, { cand: pool[pi], score: scoreCandidate(pool[pi], childAki, anchors, opts.time),
2820
+ ineligible: _forwardPathLenIneligible(pool[pi], frame.chain) });
2814
2821
  }
2815
2822
  }
2816
2823
  if (aiaCtx && frame.hop < maxDepth && aiaCtx.fetches < aiaCtx.maxFetches) {
package/lib/trust.js CHANGED
@@ -722,8 +722,39 @@ function parseCcadbCsv(text) {
722
722
  * store catches the wrong root before a single validation runs (the
723
723
  * authoritative gate stays inside `validate`).
724
724
  *
725
+ * `opts.nameConstraints` attaches the namespace a root program trusts a root
726
+ * for, when that is narrower than the root certificate itself states. Such a
727
+ * restriction lives in the program's data rather than in any `nameConstraints`
728
+ * extension the certificate carries, so it has to be supplied here. It is a
729
+ * `{ permitted, excluded }` pair of `{ tag, base }` subtrees, the same shape
730
+ * `pki.path.validate` takes for `opts.initialPermittedSubtrees`, and validate
731
+ * seeds it as the RFC 5280 sec. 6.1.1(h)(i) initial value: it intersects with
732
+ * every certificate's own constraints, so a leaf must satisfy both, and an
733
+ * excluded subtree rejects whatever is permitted. The subtrees are copied out
734
+ * of the caller's object, so changing that object afterwards does not change
735
+ * the namespace an anchor already vouches for. An overlay naming no subtree,
736
+ * or one supplying its subtrees through an accessor, is refused rather than
737
+ * carried, since either would widen the namespace the operator meant to
738
+ * restrict. A verdict reports `anchorConstraints.nameConstraintsApplied`.
739
+ *
740
+ * A base is held to the form its tag names, and one outside that form is
741
+ * refused here rather than carried to a comparison that cannot reach a verdict
742
+ * on it. Tag 1 (`rfc822Name`) is a mailbox, a host name, or a host name written
743
+ * as a subtree with a leading dot, and a mailbox may name its domain as a
744
+ * bracketed address literal; tag 2 (`dNSName`) is a host name, with or
745
+ * without that leading dot; tag 6 (`uniformResourceIdentifier`) is the dotted
746
+ * host name a certificate's URI is compared by, not a URI; tag 4
747
+ * (`directoryName`) is `{ rdns }` naming at least one relative name, whose
748
+ * attribute types are dotted-decimal object identifiers and whose values are
749
+ * strings; tag 7 (`iPAddress`) is 8 bytes for IPv4 or 32 for IPv6, an address
750
+ * followed by its mask. A host name is labels of letters, digits and hyphens,
751
+ * with a hyphen at neither edge of a label, 63 characters to a label and 253 to
752
+ * the name, and it may carry the one trailing dot the comparison strips. Tags
753
+ * outside that set are refused.
754
+ *
725
755
  * @opts
726
756
  * purpose: string // "serverAuth" | "emailProtection" | "codeSigning"; fail-fast purpose check
757
+ * nameConstraints: { permitted?: [{ tag, base }], excluded?: [{ tag, base }] } // the root program's applied namespace; tags 1, 2, 4, 6, 7
727
758
  *
728
759
  * @example
729
760
  * var ca = await pki.key.generate("Ed25519");
@@ -746,7 +777,138 @@ function parseCcadbCsv(text) {
746
777
  * await pki.path.validate([pki.schema.x509.parse(der)],
747
778
  * { time: new Date("2026-06-01T00:00:00Z"), trustAnchors: anchor, checkPurpose: "serverAuth" });
748
779
  */
749
- var _ANCHOR_OPTS = intrinsic.assign(intrinsic.create(null), { purpose: 1 });
780
+ var _ANCHOR_OPTS = intrinsic.assign(intrinsic.create(null), { purpose: 1, nameConstraints: 1 });
781
+
782
+ /** @internal A subtree list copied entry by entry, reading `tag` and `base` from their own data
783
+ * properties. An accessor could answer with a narrow subtree while it is checked and a wide one
784
+ * when it is read again, and a dropped entry widens the namespace the anchor vouches for, so a
785
+ * list that does not describe itself in plain values is refused rather than partly copied. */
786
+ function _copySubtrees(list, where) {
787
+ if (list === undefined || list === null) return [];
788
+ if (!intrinsic.isArray(list) || intrinsic.types.isProxy(list)) {
789
+ throw E("trust/bad-input", "anchor: nameConstraints." + where + " must be a plain array of { tag, base } subtree entries");
790
+ }
791
+ var out = [];
792
+ for (var i = 0; i < list.length; i++) {
793
+ var d = intrinsic.getOwnPropertyDescriptor(list, i);
794
+ if (!d || !_hasOwn(d, "value")) {
795
+ throw E("trust/bad-input", "anchor: nameConstraints." + where + " entry " + i + " must be a data property, not a hole or an accessor");
796
+ }
797
+ var st = d.value;
798
+ if (!st || typeof st !== "object" || intrinsic.types.isProxy(st)) {
799
+ throw E("trust/bad-input", "anchor: nameConstraints." + where + " entry " + i + " must be a { tag, base } object");
800
+ }
801
+ var tagD = intrinsic.getOwnPropertyDescriptor(st, "tag");
802
+ var baseD = intrinsic.getOwnPropertyDescriptor(st, "base");
803
+ if (!tagD || !_hasOwn(tagD, "value") || !baseD || !_hasOwn(baseD, "value")) {
804
+ throw E("trust/bad-input", "anchor: nameConstraints." + where + " entry " + i + " must carry its own tag and base as plain values");
805
+ }
806
+ var tag = tagD.value;
807
+ if (typeof tag !== "number" || !intrinsic.isInteger(tag) || tag < 0 || tag > 8) {
808
+ throw E("trust/bad-input", "anchor: nameConstraints." + where + " entry " + i + " tag must be a GeneralName tag number 0..8, got " + guard.text.showValue(tag));
809
+ }
810
+ _assertSubtreeBaseForm(tag, baseD.value, where, i);
811
+ /** @internal Appended through the list guard: a setter planted on the array prototype swallows
812
+ * a plain index assignment, and a subtree list that came back empty would restrict nothing. */
813
+ guard.list.append(out, { tag: tag, base: _copySubtreeBase(tag, baseD.value, where) });
814
+ }
815
+ return out;
816
+ }
817
+
818
+ /** @internal The base of one subtree, copied by its name form so the anchor holds no reference the
819
+ * caller can still reach. A byte base is snapshotted through the byte guard, which accepts every
820
+ * source `pki.path.validate` does rather than Buffers alone, so bytes changed afterwards do not
821
+ * change the namespace. A directoryName goes through the guard that owns distinguished-name
822
+ * capture, which refuses a Proxy or an accessor anywhere in the name instead of running it: reading
823
+ * such a name is caller code, and it could clear the restriction it is being asked to describe. */
824
+ function _copySubtreeBase(tag, base, where) {
825
+ if (typeof base === "string") return base;
826
+ if (tag === 7) {
827
+ return guard.bytes.snapshotSource(base, TrustError, "trust/bad-input", "anchor: nameConstraints." + where + " iPAddress base");
828
+ }
829
+ var rdns = guard.name.capturedRdns(base, E, "trust/bad-input", "anchor: nameConstraints." + where + " directoryName base");
830
+ if (rdns === undefined) {
831
+ throw E("trust/bad-input", "anchor: nameConstraints." + where + " directoryName base must carry its own rdns array");
832
+ }
833
+ return { rdns: rdns };
834
+ }
835
+
836
+ var _NC_KEYS = intrinsic.assign(intrinsic.create(null), { permitted: 1, excluded: 1 });
837
+
838
+ /** @internal One of the overlay's two subtree lists, taken from its own data property. A list the
839
+ * object only inherits is refused rather than read as absent: treating it as absent drops the
840
+ * restriction it carries, and dropping an exclusion admits the namespace it was written to keep
841
+ * out. An accessor is refused for the same reason, since it decides what it says while it is read. */
842
+ function _subtreeListDescriptor(nc, key) {
843
+ var d = intrinsic.getOwnPropertyDescriptor(nc, key);
844
+ if (d === undefined) {
845
+ if (key in intrinsic.Object(nc)) {
846
+ throw E("trust/bad-input", "anchor: opts.nameConstraints." + key + " must be the object's own property, not one it inherits");
847
+ }
848
+ return undefined;
849
+ }
850
+ if (!_hasOwn(d, "value")) {
851
+ throw E("trust/bad-input", "anchor: opts.nameConstraints." + key + " must be a plain value, not an accessor");
852
+ }
853
+ return d;
854
+ }
855
+
856
+ /** @internal A subtree base held to the form its tag names, so a base that cannot describe a
857
+ * namespace is refused here rather than carried to the validator, and so no shape falls through to
858
+ * being returned by reference: a base the anchor still shares with the caller is one the caller can
859
+ * complete afterwards, which moves the namespace an anchor has already vouched for. */
860
+ function _assertSubtreeBaseForm(tag, base, where, index) {
861
+ var who = "anchor: nameConstraints." + where + " entry " + index;
862
+ if (tag === 1 || tag === 2 || tag === 6) {
863
+ var why = guard.name.constraintBaseRefusal(tag, base);
864
+ if (why !== null) throw E("trust/bad-input", who + " base " + why);
865
+ return;
866
+ }
867
+ if (tag === 7) {
868
+ if (!guard.bytes.isByteSource(base)) throw E("trust/bad-input", who + " iPAddress base must be a byte source");
869
+ /** @internal An iPAddress subtree is an address followed by its mask, so 8 bytes for IPv4 and
870
+ * 32 for IPv6. Any other length names no range, and the validator refuses it later; refusing it
871
+ * here means the anchor an operator is handed is one that can be enforced. */
872
+ var ipLen = guard.bytes.lengthOf(guard.bytes.source(base, TrustError, "trust/bad-input", who + " iPAddress base"));
873
+ if (ipLen !== 8 && ipLen !== 32) {
874
+ throw E("trust/bad-input", who + " iPAddress base must be 8 bytes (IPv4 address and mask) or 32 (IPv6), got " + ipLen);
875
+ }
876
+ return;
877
+ }
878
+ if (tag === 4) {
879
+ if (base === null || typeof base !== "object") throw E("trust/bad-input", who + " directoryName base must be an object carrying rdns");
880
+ return;
881
+ }
882
+ throw E("trust/bad-input", who + " tag " + tag + " names a form this overlay cannot constrain; use tag 1, 2, 4, 6 or 7");
883
+ }
884
+
885
+ /** @internal The overlay a root program applies to a root outside any nameConstraints extension the
886
+ * certificate carries. It only ever narrows, so an absent one is the status quo and is left off the
887
+ * anchor entirely; a malformed one is refused, since carrying it wrongly would widen a namespace the
888
+ * operator meant to restrict. The subtrees are held to their shapes again by `pki.path.validate`,
889
+ * which is where the RFC 5280 sec. 6.1.1(h)(i) seeding happens. */
890
+ function _copyNameConstraints(nc) {
891
+ if (nc === undefined || nc === null) return null;
892
+ if (typeof nc !== "object" || intrinsic.isArray(nc) || intrinsic.types.isProxy(nc)) {
893
+ throw E("trust/bad-input", "anchor: opts.nameConstraints must be a { permitted, excluded } object of { tag, base } subtree entries");
894
+ }
895
+ /** @internal Runs before the membership tests below, which is what makes them safe to ask: this
896
+ * refuses an overlay inheriting from a Proxy, whose has trap would otherwise answer `in` with
897
+ * caller code while the lists are being read. It also names a misspelled field, which would
898
+ * otherwise be read as an absent list, and an absent excluded list admits the namespace the
899
+ * operator wrote it to keep out. */
900
+ guard.identifier.assertKnownKeys(nc, _NC_KEYS, E, "trust/bad-input", "anchor: opts.nameConstraints has an unknown field ");
901
+ var pD = _subtreeListDescriptor(nc, "permitted");
902
+ var eD = _subtreeListDescriptor(nc, "excluded");
903
+ var out = {
904
+ permitted: _copySubtrees(pD ? pD.value : null, "permitted"),
905
+ excluded: _copySubtrees(eD ? eD.value : null, "excluded"),
906
+ };
907
+ if (!out.permitted.length && !out.excluded.length) {
908
+ throw E("trust/bad-input", "anchor: opts.nameConstraints names no subtree; omit it rather than passing an empty restriction");
909
+ }
910
+ return out;
911
+ }
750
912
  function anchor(entry, opts) {
751
913
  if (!entry || typeof entry !== "object") {
752
914
  throw E("trust/bad-input", "anchor expects a trust-store entry ({ name, publicKey, algorithm, ... })");
@@ -770,7 +932,8 @@ function anchor(entry, opts) {
770
932
  if (!derived && (entry.purposes != null || (entry.distrustAfter && Object.keys(entry.distrustAfter).length))) {
771
933
  throw E("trust/bad-input", "this entry carries a trust store's per-purpose metadata but is not the entry the store produced -- it has been rebuilt, and the metadata is a statement about the key the store read, not about whichever key the copy now names. Pass pki.trust.parseCertdata / parseCcadbCsv output unmodified");
772
934
  }
773
- return {
935
+ var nameConstraints = _copyNameConstraints(opts.nameConstraints);
936
+ var out = {
774
937
  name: _copyName(meta.name),
775
938
  publicKey: Buffer.isBuffer(meta.publicKey) ? Buffer.from(meta.publicKey) : meta.publicKey,
776
939
  algorithm: meta.algorithm,
@@ -779,6 +942,12 @@ function anchor(entry, opts) {
779
942
  distrustAfter: _copyDistrustAfter(meta.distrustAfter),
780
943
  purposes: _copyPurposes(meta.purposes),
781
944
  };
945
+ /** @internal Set only when an overlay was supplied, so an anchor without one is the object this
946
+ * verb returned before the option existed, and defined rather than assigned: an accessor planted
947
+ * on Object.prototype under this name would otherwise take the assignment and leave the anchor
948
+ * carrying no restriction at all. */
949
+ if (nameConstraints) guard.verdict.set(out, "nameConstraints", nameConstraints);
950
+ return out;
782
951
  }
783
952
 
784
953
  module.exports = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.41",
3
+ "version": "0.6.43",
4
4
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:c14ed2d9-f3d5-4322-88e1-51afbe3a3fbe",
5
+ "serialNumber": "urn:uuid:226aab27-22ce-4c29-9028-5849c0bf6587",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-06T02:19:25.175Z",
8
+ "timestamp": "2026-09-06T06:39:34.959Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/pki@0.6.41",
22
+ "bom-ref": "@blamejs/pki@0.6.43",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.41",
25
+ "version": "0.6.43",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
29
- "purl": "pkg:npm/%40blamejs/pki@0.6.41",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.43",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/pki@0.6.41",
57
+ "ref": "@blamejs/pki@0.6.43",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]