@blamejs/pki 0.7.14 → 0.7.16

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,28 @@ 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.7.16 — 2026-09-11
8
+
9
+ Where to fetch the issuer and the CRL can be named in a plain spec.
10
+
11
+ ### Added
12
+
13
+ - extensions.authorityInfoAccess takes a list of { accessMethod, accessLocation } (RFC 5280 section 4.2.2.1). The method is a registered name such as "ocsp" or "caIssuers", or a dotted OID; the location is a GeneralName in either form the builder accepts, including a bare string classified into its form. An empty list, an unregistered method name, and an entry with no accessLocation are refused with x509/bad-input or csr/bad-input. The extension is emitted non-critical, which that clause requires.
14
+ - extensions.cRLDistributionPoints takes a list of distribution points (RFC 5280 section 4.2.1.13), and extensions.freshestCRL takes the same shape, which section 4.2.1.15 gives it. An entry is either a GeneralName standing for a single fullName, so a list of URL strings is the short form, or { fullName, reasons, cRLIssuer } for the full one. reasons names ReasonFlags bits, whose numbering is not the CRLReason numbering pki.crl.sign takes: section 5.3.1 numbers privilegeWithdrawn 9 and aACompromise 10, while section 4.2.1.13 gives them bits 7 and 8. A distribution point naming only reasons is refused, which section 4.2.1.13 requires, as is an empty list or an unknown reason name. Both are emitted non-critical.
15
+ - All three are accepted on the pki.csr.sign extensionRequest object as well, so a request and an issued certificate are written the same way.
16
+
17
+ ## v0.7.15 — 2026-09-11
18
+
19
+ Name constraints can be issued from a plain spec.
20
+
21
+ ### Added
22
+
23
+ - extensions.nameConstraints takes { permitted, excluded }, with at least one side present, on pki.x509.sign and on the pki.csr.sign extensionRequest object. Each entry names one GeneralName form: { dNSName: ".example.com" }, { rfc822Name: "example.com" }, { uniformResourceIdentifier: ".example.com" }, { directoryName: [{ commonName: "Sub" }] }, or { iPAddress: buf } where buf is an address followed by its mask, 8 octets for IPv4 and 32 for IPv6. A base names a namespace rather than a subject, so it may carry a leading dot and is held to the rule for a constraint base, the same rule pki.trust.anchor applies to the subtrees it seeds. A bare string is refused, because the name form decides which namespace is constrained. The extension is emitted critical, which RFC 5280 section 4.2.1.10 requires. A subtree naming neither direction, an empty list, or a base that describes no namespace is refused with x509/bad-input or csr/bad-input. The constraint a certificate carries is enforced by OpenSSL as well as by pki.path.validate, checked in the release gates.
24
+
25
+ ### Fixed
26
+
27
+ - pki.x509.sign refuses a nameConstraints extension on a certificate that is not a CA. RFC 5280 section 4.2.1.10 states the extension is used only in a CA certificate, and pki.lint.certificate already graded such a certificate error as lint/rfc5280/name-constraints-not-ca; the signer emitted it anyway when the extension arrived as pre-encoded DER in the extensions array. A name constraint on an end-entity certificate restricts nothing, so a caller reading it as a restriction was reading one that no validator would apply. Supply it on a certificate whose basicConstraints sets cA true.
28
+
7
29
  ## v0.7.14 — 2026-09-11
8
30
 
9
31
  Every option a verify verb decides with is taken once.
package/README.md CHANGED
@@ -231,7 +231,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
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
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
- | `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. `randomSerial()` draws the same 20-octet CSPRNG serial the signer uses when the spec names none, so a serial can be reserved or logged before the certificate is issued. 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` |
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. `randomSerial()` draws the same 20-octet CSPRNG serial the signer uses when the spec names none, so a serial can be reserved or logged before the certificate is issued. 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, certificate policies, name constraints, authority information access, CRL distribution points, and the freshest CRL from the spec, taking any other extension as pre-encoded DER. `extensions.nameConstraints` takes `{ permitted, excluded }` lists of GeneralName-form objects, restricting what the CA being issued may itself issue; each base is held to the rule for a constraint base, and the extension is emitted critical as §4.2.1.10 requires. 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` |
237
237
  | `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public 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. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named. `pop.method: 'agreeMAC'` completes the four: `pop.key` is the requester's finite-field Diffie-Hellman private key, as a PKCS#8 DER, a PEM `PRIVATE KEY` block or a `KeyObject`, and `pop.caCert` the authority's certificate it already holds; the two agree a static secret (RFC 2875 sec. 3), and the key derived from it MACs the DER `certReq` under `id-dhPop-static-HMAC-SHA1`. Either key may name its group in the PKCS#3 or the X9.42 encoding. `pop.key` must be the private half of `certTemplate.publicKey`, and the template must name both a subject and a public key. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
package/lib/pki-build.js CHANGED
@@ -24,6 +24,8 @@ var _String = intrinsic.String;
24
24
  var _objectKeys = intrinsic.keys;
25
25
  var _isBufferChk = intrinsic.isBuffer;
26
26
  var _stringify = intrinsic.stringify;
27
+ var _mapIntrinsic = intrinsic.map;
28
+ var _bufferConcatIntrinsic = intrinsic.bufferConcat;
27
29
 
28
30
  function _isAlphaCode(c) { return (c >= 65 && c <= 90) || (c >= 97 && c <= 122); }
29
31
  function _isDigitCode(c) { return c >= 48 && c <= 57; }
@@ -247,6 +249,17 @@ var KU_BIT = intrinsic.assign(intrinsic.create(null), {
247
249
  dataEncipherment: 3, keyAgreement: 4, keyCertSign: 5, cRLSign: 6, encipherOnly: 7, decipherOnly: 8,
248
250
  });
249
251
 
252
+ /** @internal ReasonFlags bit positions (RFC 5280 sec. 4.2.1.13). These do NOT line up with the
253
+ * CRLReason ENUMERATED of sec. 5.3.1, which leaves 7 unused and numbers privilegeWithdrawn 9 and
254
+ * aACompromise 10; here they are bits 7 and 8. Bit 0 is named `unused` and is not settable, and
255
+ * unspecified and removeFromCRL have no bit at all. */
256
+ var REASON_FLAG_BIT = intrinsic.assign(intrinsic.create(null), {
257
+ keyCompromise: 1, cACompromise: 2, affiliationChanged: 3, superseded: 4,
258
+ cessationOfOperation: 5, certificateHold: 6, privilegeWithdrawn: 7, aACompromise: 8,
259
+ });
260
+ var AIA_KEYS = intrinsic.assign(intrinsic.create(null), { accessMethod: 1, accessLocation: 1 });
261
+ var DP_KEYS = intrinsic.assign(intrinsic.create(null), { fullName: 1, reasons: 1, cRLIssuer: 1 });
262
+
250
263
  /** @internal The serial a certificate gets when the caller names none: 20 CSPRNG octets read as a
251
264
  * positive integer, the top of the range RFC 5280 sec. 4.1.2.2 allows. The top bit is cleared so the
252
265
  * DER INTEGER carries no sign octet. A zero leading octet is drawn again. Substituting a fixed value
@@ -284,6 +297,13 @@ var CERT_FIXED_CRITICALITY = intrinsic.create(null);
284
297
  CERT_FIXED_CRITICALITY[oid.byName(r[0])] = { critical: r[1], citation: r[2] };
285
298
  });
286
299
 
300
+ var NC_KEYS = intrinsic.assign(intrinsic.create(null), { permitted: 1, excluded: 1 });
301
+ var NC_FORM_TAG = intrinsic.assign(intrinsic.create(null), {
302
+ rfc822Name: 1, dNSName: 2, directoryName: 4, uniformResourceIdentifier: 6, uri: 6, iPAddress: 7,
303
+ });
304
+ /** @internal permittedSubtrees is [0] and excludedSubtrees is [1], in that order. */
305
+ function _forEachNcSide(fn) { fn("permitted", 0); fn("excluded", 1); }
306
+
287
307
  function makeBuilder(ctx) {
288
308
  var ErrorClass = ctx.ErrorClass, O = ctx.O, NS = ctx.NS;
289
309
  var NAME_SCHEMA = ctx.NAME_SCHEMA, SPKI_SCHEMA = ctx.SPKI_SCHEMA;
@@ -446,6 +466,155 @@ function makeBuilder(ctx) {
446
466
  return b.contextConstructed(implicitTag, Buffer.concat(members));
447
467
  }
448
468
  function extSan(entries) { return encodeGeneralNames(entries); }
469
+ /** @internal AuthorityInfoAccessSyntax (RFC 5280 sec. 4.2.2.1): SEQUENCE SIZE (1..MAX) OF
470
+ * AccessDescription { accessMethod OBJECT IDENTIFIER, accessLocation GeneralName }. */
471
+ function extAuthorityInfoAccess(list) {
472
+ if (!_isArray(list) || !list.length) {
473
+ throw E("bad-input", "authorityInfoAccess must name at least one { accessMethod, accessLocation } (RFC 5280 sec. 4.2.2.1)");
474
+ }
475
+ var dense = reqDenseArray(list, "authorityInfoAccess");
476
+ return b.sequence(_mapIntrinsic(dense, function (d, i) {
477
+ var who = "authorityInfoAccess entry " + i;
478
+ if (!d || typeof d !== "object" || _isArray(d) || _isBufferChk(d)) {
479
+ throw E("bad-input", who + " must be an object { accessMethod, accessLocation }");
480
+ }
481
+ guard.identifier.assertKnownKeys(d, AIA_KEYS, E, "bad-input", function (k) {
482
+ return "unknown " + who + " field " + _stringify(k) + " (accepted: accessMethod, accessLocation)";
483
+ });
484
+ if (d.accessLocation == null) throw E("bad-input", who + " requires an accessLocation GeneralName");
485
+ /** @internal A fault in the SPEC is this module's, so the name is typed here rather than left
486
+ * to the OID registry, whose own error names a different domain than the one a caller of this
487
+ * verb branches on. */
488
+ if (typeof d.accessMethod !== "string" || !d.accessMethod.length) {
489
+ throw E("bad-input", who + " requires an accessMethod naming a registered access method or a dotted-decimal OID");
490
+ }
491
+ return b.sequence([b.oid(_resolveOid(d.accessMethod, who + " accessMethod")), encodeGeneralName(d.accessLocation)]);
492
+ }));
493
+ }
494
+ /** @internal One DistributionPoint (RFC 5280 sec. 4.2.1.13). distributionPoint [0] wraps a
495
+ * DistributionPointName whose fullName is [0] IMPLICIT GeneralNames; reasons is [1] IMPLICIT
496
+ * ReasonFlags; cRLIssuer is [2] IMPLICIT GeneralNames. A DistributionPoint must not consist of
497
+ * only the reasons field, so one of the other two is required. An entry that names none of the
498
+ * three field names is a GeneralName standing for a single fullName. */
499
+ function distributionPoint(entry, what, idx) {
500
+ var who = what + " entry " + idx;
501
+ var spec = entry;
502
+ var isDpObject = !!entry && typeof entry === "object" && !_isArray(entry) && !_isBufferChk(entry) &&
503
+ guard.list.anyMatches(_objectKeys(entry), function (k) { return DP_KEYS[k] === 1; });
504
+ if (!isDpObject) spec = { fullName: [entry] };
505
+ guard.identifier.assertKnownKeys(spec, DP_KEYS, E, "bad-input", function (k) {
506
+ return "unknown " + who + " field " + _stringify(k) + " (accepted: fullName, reasons, cRLIssuer)";
507
+ });
508
+ if (spec.fullName == null && spec.cRLIssuer == null) {
509
+ throw E("bad-input", who + " must name a fullName or a cRLIssuer; a DistributionPoint must not consist of only the reasons field (RFC 5280 sec. 4.2.1.13)");
510
+ }
511
+ var fields = [];
512
+ if (spec.fullName != null) {
513
+ /** @internal [0] distributionPoint wraps [0] fullName, so the GeneralNames tag nests inside it. */
514
+ guard.list.append(fields, b.contextConstructed(0, encodeGeneralNames(reqDenseArray(spec.fullName, who + " fullName"), 0)));
515
+ }
516
+ if (spec.reasons != null) {
517
+ if (!_isArray(spec.reasons) || !spec.reasons.length) throw E("bad-input", who + " reasons must name at least one ReasonFlags bit");
518
+ var bits = _mapIntrinsic(reqDenseArray(spec.reasons, who + " reasons"), function (r) {
519
+ var bit = REASON_FLAG_BIT[guard.text.keyOf(r)];
520
+ if (bit == null) throw E("bad-input", who + " names an unknown CRL reason " + guard.text.showValue(r));
521
+ return bit;
522
+ });
523
+ guard.list.append(fields, b.implicit(1, b.namedBitString(bits)));
524
+ }
525
+ if (spec.cRLIssuer != null) {
526
+ /** @internal Sec. 4.2.1.13 requires cRLIssuer to carry the NAME of the CRL issuer, and a
527
+ * GeneralName carries an X.501 Name only as directoryName. The path validator compares only
528
+ * directoryName entries, so a cRLIssuer naming none matches no issuer and the distribution
529
+ * point would leave revocation undetermined rather than point at a CRL. */
530
+ var issuers = reqDenseArray(spec.cRLIssuer, who + " cRLIssuer");
531
+ /** @internal A Name with no RDNs names nobody, and pki.crl.sign refuses to issue a CRL under
532
+ * one, so an empty directoryName leaves the point matching no conforming CRL exactly as a
533
+ * missing one would. The name is encoded to ask, since a caller may write it as a string, an
534
+ * RDN array, or raw Name DER. */
535
+ var named = guard.list.anyMatches(issuers, function (e) {
536
+ if (!e || typeof e !== "object" || _isArray(e) || _isBufferChk(e) || e.directoryName == null) return false;
537
+ try {
538
+ return !isEmptyName(encodeName(e.directoryName));
539
+ } catch (_e) {
540
+ /** @internal A directoryName that cannot encode as a Name is not a usable issuer name, so
541
+ * it does not satisfy the requirement; the refusal below names the real fault. */
542
+ return false;
543
+ }
544
+ });
545
+ if (!named) {
546
+ throw E("bad-input", who + " cRLIssuer must name the CRL issuer as a non-empty directoryName (RFC 5280 sec. 4.2.1.13); a cRLIssuer carrying no usable directoryName matches no CRL issuer");
547
+ }
548
+ guard.list.append(fields, encodeGeneralNames(issuers, 2));
549
+ }
550
+ return b.sequence(fields);
551
+ }
552
+ /** @internal CRLDistributionPoints (RFC 5280 sec. 4.2.1.13). freshestCRL (sec. 4.2.1.15) states
553
+ * that the same syntax is used, so both route here. */
554
+ function extCrlDistributionPoints(list, what) {
555
+ if (!_isArray(list) || !list.length) {
556
+ throw E("bad-input", what + " must name at least one distribution point (RFC 5280 sec. 4.2.1.13)");
557
+ }
558
+ var dense = reqDenseArray(list, what);
559
+ return b.sequence(_mapIntrinsic(dense, function (e, i) { return distributionPoint(e, what, i); }));
560
+ }
561
+ /** @internal One GeneralSubtree (RFC 5280 sec. 4.2.1.10). Within this profile minimum is 0 and
562
+ * maximum is absent, so a subtree is its base alone. A base names a NAMESPACE rather than a
563
+ * subject, so it is held to the constraint-base rule: it may carry a leading dot, and an
564
+ * iPAddress base is an address followed by its mask. */
565
+ function constraintSubtree(entry, where, idx) {
566
+ var who = "nameConstraints." + where + " entry " + idx;
567
+ if (!entry || typeof entry !== "object" || _isArray(entry) || _isBufferChk(entry)) {
568
+ throw E("bad-input", who + " must be an object naming one GeneralName form; a bare string does not say which namespace is constrained");
569
+ }
570
+ var keys = _objectKeys(entry);
571
+ if (keys.length !== 1) throw E("bad-input", who + " must name exactly one GeneralName form, got " + keys.length);
572
+ var k = keys[0], v = entry[k];
573
+ var tag = NC_FORM_TAG[k];
574
+ if (tag == null) {
575
+ throw E("bad-input", who + " names an unsupported constraint form " + _stringify(k) +
576
+ " (supported: rfc822Name, dNSName, directoryName, uniformResourceIdentifier, iPAddress)");
577
+ }
578
+ if (tag === 7) {
579
+ if (!guard.bytes.isByteSource(v)) throw E("bad-input", who + " iPAddress base must be a byte source");
580
+ var ip = guard.bytes.source(v, ErrorClass, ctx.prefix + "/bad-input", who + " iPAddress base");
581
+ if (ip.length !== 8 && ip.length !== 32) {
582
+ throw E("bad-input", who + " iPAddress base must be 8 octets (an IPv4 address and its mask) or 32 (IPv6), got " + ip.length);
583
+ }
584
+ return b.sequence([b.contextPrimitive(7, ip)]);
585
+ }
586
+ if (tag === 4) return b.sequence([b.explicit(4, encodeName(v))]);
587
+ if (typeof v !== "string") throw E("bad-input", who + " base must be a string for " + k);
588
+ var why = guard.name.constraintBaseRefusal(tag, v);
589
+ if (why !== null) throw E("bad-input", who + " base " + why);
590
+ return b.sequence([b.contextPrimitive(tag, ia5Content(v))]);
591
+ }
592
+ /** @internal NameConstraints (RFC 5280 sec. 4.2.1.10). permittedSubtrees [0] and excludedSubtrees
593
+ * [1] are IMPLICIT, so each replaces the GeneralSubtrees SEQUENCE tag and holds its members
594
+ * directly. The extension is emitted critical by its caller, which that clause requires. */
595
+ function extNameConstraints(spec) {
596
+ if (!spec || typeof spec !== "object" || _isArray(spec)) {
597
+ throw E("bad-input", "nameConstraints must be an object naming permitted and/or excluded subtrees");
598
+ }
599
+ guard.identifier.assertKnownKeys(spec, NC_KEYS, E, "bad-input", function (k) {
600
+ return "unknown nameConstraints field " + _stringify(k) + " (accepted: permitted, excluded)";
601
+ });
602
+ var kids = [];
603
+ _forEachNcSide(function (where, implicitTag) {
604
+ var list = spec[where];
605
+ if (list == null) return;
606
+ if (!_isArray(list) || !list.length) {
607
+ throw E("bad-input", "nameConstraints." + where + " must be a non-empty array of GeneralName-form objects");
608
+ }
609
+ var dense = reqDenseArray(list, "nameConstraints." + where);
610
+ var subs = _mapIntrinsic(dense, function (e, idx) { return constraintSubtree(e, where, idx); });
611
+ guard.list.append(kids, b.contextConstructed(implicitTag, _bufferConcatIntrinsic(subs)));
612
+ });
613
+ if (!kids.length) {
614
+ throw E("bad-input", "nameConstraints must name at least one of permitted or excluded (RFC 5280 sec. 4.2.1.10 forbids an empty sequence)");
615
+ }
616
+ return b.sequence(kids);
617
+ }
449
618
  function extCertPolicies(names) {
450
619
  if (!_isArray(names) || !names.length) throw E("bad-input", "certificatePolicies must list at least one policy OID");
451
620
  var seen = intrinsic.create(null);
@@ -522,6 +691,7 @@ function makeBuilder(ctx) {
522
691
  var REQ_EXT_KEYS = {
523
692
  subjectAltName: 1, keyUsage: 1, keyUsageCritical: 1, extendedKeyUsage: 1, extendedKeyUsageCritical: 1,
524
693
  basicConstraints: 1, certificatePolicies: 1, certificatePoliciesCritical: 1, subjectKeyIdentifier: 1,
694
+ nameConstraints: 1, authorityInfoAccess: 1, cRLDistributionPoints: 1, freshestCRL: 1,
525
695
  };
526
696
  function requestedExtensions(extSpec, spki) {
527
697
  var EXT_DECODERS = ctx.EXT_DECODERS;
@@ -558,6 +728,11 @@ function makeBuilder(ctx) {
558
728
  if (extSpec.basicConstraints != null) { validateBcSpec(extSpec.basicConstraints); out.push(ext(O("basicConstraints"), extSpec.basicConstraints.critical !== false, extBasicConstraints(extSpec.basicConstraints))); }
559
729
  if (extSpec.subjectAltName != null) out.push(ext(O("subjectAltName"), false, extSan(extSpec.subjectAltName)));
560
730
  if (extSpec.certificatePolicies != null) out.push(ext(O("certificatePolicies"), !!extSpec.certificatePoliciesCritical, extCertPolicies(extSpec.certificatePolicies)));
731
+ /** @internal RFC 5280 sec. 4.2.1.10 fixes this extension critical, in a request as in the certificate. */
732
+ if (extSpec.nameConstraints != null) guard.list.append(out, ext(O("nameConstraints"), true, extNameConstraints(extSpec.nameConstraints)));
733
+ if (extSpec.authorityInfoAccess != null) guard.list.append(out, ext(O("authorityInfoAccess"), false, extAuthorityInfoAccess(extSpec.authorityInfoAccess)));
734
+ if (extSpec.cRLDistributionPoints != null) guard.list.append(out, ext(O("cRLDistributionPoints"), false, extCrlDistributionPoints(extSpec.cRLDistributionPoints, "cRLDistributionPoints")));
735
+ if (extSpec.freshestCRL != null) guard.list.append(out, ext(O("freshestCRL"), false, extCrlDistributionPoints(extSpec.freshestCRL, "freshestCRL")));
561
736
  if (!out.length) throw E("bad-input", "the requested extensions object must request at least one extension");
562
737
  return b.sequence(out);
563
738
  }
@@ -621,6 +796,8 @@ function makeBuilder(ctx) {
621
796
  return {
622
797
  E: E, code: code, KU_BIT: KU_BIT,
623
798
  encodeName: encodeName, isEmptyName: isEmptyName, encodeGeneralName: encodeGeneralName,
799
+ extNameConstraints: extNameConstraints, extAuthorityInfoAccess: extAuthorityInfoAccess,
800
+ extCrlDistributionPoints: extCrlDistributionPoints,
624
801
  encodeGeneralNames: encodeGeneralNames, serialInteger: serialInteger, timeDer: timeDer,
625
802
  requestedExtensions: requestedExtensions,
626
803
  extKeyUsage: extKeyUsage, extExtKeyUsage: extExtKeyUsage, validateBcSpec: validateBcSpec,
package/lib/x509-sign.js CHANGED
@@ -50,7 +50,8 @@ var KNOWN_SIGN_OPTS = intrinsic.assign(intrinsic.create(null), { digestAlgorithm
50
50
  var KNOWN_EXT_KEYS = intrinsic.assign(intrinsic.create(null), {
51
51
  subjectKeyIdentifier: 1, authorityKeyIdentifier: 1, keyUsage: 1, keyUsageCritical: 1,
52
52
  extendedKeyUsage: 1, extendedKeyUsageCritical: 1, basicConstraints: 1, subjectAltName: 1,
53
- certificatePolicies: 1, certificatePoliciesCritical: 1,
53
+ certificatePolicies: 1, certificatePoliciesCritical: 1, nameConstraints: 1,
54
+ authorityInfoAccess: 1, cRLDistributionPoints: 1, freshestCRL: 1,
54
55
  });
55
56
 
56
57
  var _b = pkiBuild.makeBuilder({ ErrorClass: CertificateError, prefix: "x509", O: O, NS: NS, NAME_SCHEMA: NAME_SCHEMA, SPKI_SCHEMA: SPKI_SCHEMA, EXT_DECODERS: EXT_DECODERS });
@@ -60,6 +61,8 @@ var _encodeName = _b.encodeName, _isEmptyName = _b.isEmptyName, _reqDer = _b.req
60
61
  _certLikeFromSpki = _b.certLikeFromSpki, _assertCertVerifies = _b.assertSignatureVerifies,
61
62
  _ext = _b.ext, _extBasicConstraints = _b.extBasicConstraints, _validateBcSpec = _b.validateBcSpec,
62
63
  _extKeyUsage = _b.extKeyUsage, _extExtKeyUsage = _b.extExtKeyUsage, _extSki = _b.extSki,
64
+ _extNameConstraints = _b.extNameConstraints, _extAia = _b.extAuthorityInfoAccess,
65
+ _extCrlDp = _b.extCrlDistributionPoints,
63
66
  _extAki = _b.extAki, _extSan = _b.extSan, _extCertPolicies = _b.extCertPolicies,
64
67
  _skiKeyId = _b.skiKeyId, _spkiKeyId = _b.spkiKeyId, _serialInteger = _b.serialInteger;
65
68
 
@@ -81,8 +84,8 @@ function _akiKeyId(val, ctx) {
81
84
  function _buildExtensions(extSpec, ctx) {
82
85
  if (extSpec == null) return [];
83
86
  if (_isArray(extSpec)) {
84
- var seenExt = intrinsic.create(null), arrCa = false, arrKeyCertSign = false, arrPathLen = false;
85
- var oidBc = O("basicConstraints"), oidKu = O("keyUsage");
87
+ var seenExt = intrinsic.create(null), arrCa = false, arrKeyCertSign = false, arrPathLen = false, arrNameConstraints = false;
88
+ var oidBc = O("basicConstraints"), oidKu = O("keyUsage"), oidNc = O("nameConstraints");
86
89
  var arr = extSpec.map(function (e, i) {
87
90
  var der = _reqDer(e, "extension");
88
91
  _assertValidExtension(der, i);
@@ -90,6 +93,7 @@ function _buildExtensions(extSpec, ctx) {
90
93
  var extnId = asn1.read.oid(n.children[0]);
91
94
  if (seenExt[extnId]) throw _err("x509/bad-input", "duplicate extension " + extnId + " in the extensions array (RFC 5280 sec. 4.2 -- at most one instance of an extension)");
92
95
  seenExt[extnId] = true;
96
+ if (extnId === oidNc) arrNameConstraints = true;
93
97
  _assertCertCriticality(extnId, n.children.length === 3, "pre-encoded");
94
98
  var dec = EXT_DECODERS[extnId];
95
99
  if (dec) {
@@ -109,6 +113,7 @@ function _buildExtensions(extSpec, ctx) {
109
113
  });
110
114
  if (arrKeyCertSign && !arrCa) throw _err("x509/bad-input", "keyUsage keyCertSign requires basicConstraints cA=TRUE (RFC 5280 sec. 4.2.1.3)");
111
115
  if (arrPathLen && (!arrCa || !arrKeyCertSign)) throw _err("x509/bad-input", "basicConstraints pathLenConstraint requires cA=TRUE and keyUsage keyCertSign (RFC 5280 sec. 4.2.1.9)");
116
+ if (arrNameConstraints && !arrCa) throw _err("x509/bad-input", "nameConstraints appears only in a CA certificate, so it requires basicConstraints cA=TRUE (RFC 5280 sec. 4.2.1.10)");
112
117
  return arr;
113
118
  }
114
119
  if (typeof extSpec !== "object") throw _err("x509/bad-input", "extensions must be an object or an array of pre-encoded Extension DER");
@@ -138,6 +143,15 @@ function _buildExtensions(extSpec, ctx) {
138
143
  }
139
144
  if (extSpec.subjectAltName != null) out.push(_ext(O("subjectAltName"), ctx.subjectEmpty, _extSan(extSpec.subjectAltName)));
140
145
  if (extSpec.certificatePolicies != null) out.push(_ext(O("certificatePolicies"), !!extSpec.certificatePoliciesCritical, _extCertPolicies(extSpec.certificatePolicies)));
146
+ /** @internal Sections 4.2.2.1 and 4.2.1.15 fix these non-critical; sec. 4.2.1.13 states a SHOULD
147
+ * and the toolkit issues the conforming form. */
148
+ if (extSpec.authorityInfoAccess != null) guard.list.append(out, _ext(O("authorityInfoAccess"), false, _extAia(extSpec.authorityInfoAccess)));
149
+ if (extSpec.cRLDistributionPoints != null) guard.list.append(out, _ext(O("cRLDistributionPoints"), false, _extCrlDp(extSpec.cRLDistributionPoints, "cRLDistributionPoints")));
150
+ if (extSpec.freshestCRL != null) guard.list.append(out, _ext(O("freshestCRL"), false, _extCrlDp(extSpec.freshestCRL, "freshestCRL")));
151
+ if (extSpec.nameConstraints != null) {
152
+ if (!caTrue) throw _err("x509/bad-input", "nameConstraints appears only in a CA certificate, so it requires basicConstraints cA=TRUE (RFC 5280 sec. 4.2.1.10)");
153
+ guard.list.append(out, _ext(O("nameConstraints"), true, _extNameConstraints(extSpec.nameConstraints)));
154
+ }
141
155
  return out;
142
156
  }
143
157
 
@@ -219,6 +233,27 @@ function _hasCriticalSan(extSpec) {
219
233
  * SPKI), a structural fault throws `CertificateError`, while a malformed leaf inside those bytes
220
234
  * throws `Asn1Error`, the same two-error contract the parsers present.
221
235
  *
236
+ * `extensions.nameConstraints` restricts what the CA being issued may itself issue, as
237
+ * `{ permitted: [...], excluded: [...] }` with at least one side present. Each entry names one
238
+ * GeneralName form: `{ dNSName: ".example.com" }`, `{ rfc822Name: "example.com" }`,
239
+ * `{ uniformResourceIdentifier: ".example.com" }`, `{ directoryName: [{ commonName: "Sub" }] }`, or
240
+ * `{ iPAddress: buf }` where `buf` is an address followed by its mask, 8 octets for IPv4 and 32 for
241
+ * IPv6. A base names a namespace rather than a subject, so it may carry a leading dot and is held to
242
+ * the rule for a constraint base. A bare string is refused here, since the name form decides which
243
+ * namespace is constrained. The extension is emitted critical, which RFC 5280 sec. 4.2.1.10 requires,
244
+ * and it appears only on a certificate whose `basicConstraints` sets `cA: true`.
245
+ *
246
+ * `extensions.authorityInfoAccess` names where to reach the issuer, as a list of
247
+ * `{ accessMethod, accessLocation }`. The method is a registered name (`"ocsp"`, `"caIssuers"`) or a
248
+ * dotted OID; the location is a `GeneralName` in either accepted form.
249
+ * `extensions.cRLDistributionPoints` names where to fetch the CRL, and `extensions.freshestCRL` the
250
+ * delta CRL, which RFC 5280 sec. 4.2.1.15 gives the same syntax. Each takes a list whose entries are
251
+ * either a `GeneralName` standing for a single `fullName`, or
252
+ * `{ fullName, reasons, cRLIssuer }` for the full form; `reasons` names RFC 5280 sec. 4.2.1.13
253
+ * ReasonFlags bits, whose numbering differs from the CRLReason values `pki.crl.sign` takes. A
254
+ * distribution point naming only `reasons` is refused, which that clause requires. All three are
255
+ * emitted non-critical.
256
+ *
222
257
  * @opts
223
258
  * - `pem` (boolean) -- return a PEM `CERTIFICATE` string instead of DER.
224
259
  * - `pss` (boolean) -- sign an RSA key with RSASSA-PSS instead of PKCS#1 v1.5.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.7.14",
3
+ "version": "0.7.16",
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:bf9440b0-2e9b-45e1-8551-36b17188bd96",
5
+ "serialNumber": "urn:uuid:cef547e4-7949-46e6-bb7a-f2379b60393e",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-11T02:22:59.455Z",
8
+ "timestamp": "2026-09-11T04:59:20.784Z",
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.7.14",
22
+ "bom-ref": "@blamejs/pki@0.7.16",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.7.14",
25
+ "version": "0.7.16",
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.7.14",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.7.16",
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.7.14",
57
+ "ref": "@blamejs/pki@0.7.16",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]