@blamejs/pki 0.7.23 → 0.7.25

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,33 @@ 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.25 — 2026-09-12
8
+
9
+ An OCSP response can say how far back its status reaches and which CRL it came from.
10
+
11
+ ### Added
12
+
13
+ - A per-certificate response given to pki.ocsp.sign takes singleExtensions as an object beside the array of pre-encoded DER it already took: archiveCutoff is the Date before which the responder no longer holds status (RFC 6960 section 4.4.4), and crlReferences is { crlUrl, crlNum, crlTime }, any subset of the three, naming the CRL the status was drawn from (section 4.4.2). A fault in either is reported as ocsp/bad-input.
14
+ - pki.schema.ocsp.parseResponse decodes both onto the single response's extension entry, as archiveCutoff and crlReferences beside the raw value, the way it already decodes the nonce. A value that is not a GeneralizedTime, or a CrlID that is not the three-member SEQUENCE section 4.4.2 defines, is refused with ocsp/bad-archive-cutoff or ocsp/bad-crl-id rather than passed through.
15
+
16
+ ### Changed
17
+
18
+ - The signing verb that would write a Date whose year lies outside 0000 to 9999 refuses it with that verb's own code (x509/bad-input, crl/bad-input, ocsp/bad-input and so on) instead of letting it reach the DER encoder and surface as asn1/bad-generalizedtime. A DER time carries a four-digit year, so such a Date never had an encoding; what changes is which error a caller receives. The check covers every Date a signing verb writes: a certificate's or a CRMF template's validity, a CRL's update, revocation and invalidity times, an OCSP response's producedAt, thisUpdate, revocation time, archive cutoff and CRL time, a CMS signingTime, a timestamp's genTime, an attribute certificate's validity, and a CMP message time. A Date a verifying verb only compares against, such as the time option of pki.path.validate, pki.crl.isRevoked or pki.cms.verify, is accepted as before.
19
+ - A pre-encoded singleExtensions entry given to pki.ocsp.sign is now read with the parser's own singleExtensions reader before it is emitted, so a malformed archive cutoff or CRL reference is refused at the signer with the parser's code instead of being written into a response the toolkit itself cannot read. A well-formed entry is unaffected. An object passed where the array was expected was previously dropped without a word; it is now either taken as the object form or refused.
20
+
21
+ ### Fixed
22
+
23
+ - The pkijs.com sitemap dates every page on the UTC calendar the release is dated on. A page whose source was last committed in the evening west of Greenwich was dated a day earlier than the release that shipped it, and the following release could then move that date backward.
24
+
25
+ ## v0.7.24 — 2026-09-12
26
+
27
+ A certificate request can name every extension its subject owns.
28
+
29
+ ### Added
30
+
31
+ - The pki.csr.sign extensionRequest takes msCertificateTemplate, msEnrollCertType, msApplicationPolicies, subjectInfoAccess and subjectDirectoryAttributes, with the same spec shapes and the same rules pki.x509.sign applies, because one encoder serves both verbs: the same spec yields identical bytes and criticality in the request and in the certificate, and a fault is reported with a csr/* code.
32
+ - A request naming an extension the issuing CA assigns as a spec key is refused by name rather than encoded and ignored: authorityKeyIdentifier names the CA's key, precertificatePoison and signedCertificateTimestampList are the CA's exchange with a log, msCaVersion and msPreviousCertHash are the CA's own, and ocspNoCheck is the CA's decision about a responder. The pre-encoded Extension array is unchanged: it carries whatever well-formed extension a caller assembles, as it always has.
33
+
7
34
  ## v0.7.23 — 2026-09-11
8
35
 
9
36
  Subject information access, subject directory attributes and the OCSP no-check marker are read and written.
package/README.md CHANGED
@@ -214,7 +214,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
214
214
  | `pki.schema.csr` | PKCS#10 certification requests (RFC 2986): subject DN, public key, requested attributes, signature Fail-closed — `parse`, `pemDecode`, `pemEncode` |
215
215
  | `pki.schema.pkcs8` | PKCS#8 private keys (RFC 5208 / 5958): algorithm, raw key bytes, attributes, optional public key. Encrypted keys are recognized but not decrypted. Fail-closed — `parse`, `parseEncrypted`, `pemDecode`, `pemEncode` |
216
216
  | `pki.schema.cms` | CMS (RFC 5652 / 5083 / 9629): SignedData (§5, signer infos plus raw signed-attribute bytes for external verification), EnvelopedData (§6, all five RecipientInfo kinds including RFC 5753 key agreement and RFC 9629 KEM recipients with ML-KEM validation), EncryptedData (§8), AuthenticatedData (§9, MAC surface plus raw `authAttrsBytes`), and AuthEnvelopedData (RFC 5083, with RFC 5084 AES-GCM/CCM parameter validation). §11 attribute placement is enforced, countersignatures validate recursively, certificates and CRLs are validated against the closed CHOICE sets and kept raw, and every result is tagged `contentTypeName` Fail-closed — `parse`, `pemDecode`, `pemEncode` |
217
- | `pki.schema.ocsp` | OCSP requests and responses (RFC 6960): per-certificate status (good, revoked, unknown), responder identity, raw tbs bytes for external verification, certificates kept raw. Non-basic response types are recognized but not decoded. Fail-closed — `parseRequest`, `parseResponse`, `pemDecode`, `pemEncode` |
217
+ | `pki.schema.ocsp` | OCSP requests and responses (RFC 6960): per-certificate status (good, revoked, unknown), responder identity, raw tbs bytes for external verification, certificates kept raw. A response's nonce, and a single response's archive cutoff (§4.4.4) and CRL reference (§4.4.2), are decoded onto their extension entries by name; a malformed one is refused. Non-basic response types are recognized but not decoded. Fail-closed — `parseRequest`, `parseResponse`, `pemDecode`, `pemEncode` |
218
218
  | `pki.schema.tsp` | RFC 3161 timestamp requests, responses, and tokens: the TimeStampReq a client sends (imprint, requested policy, nonce, certReq), the TSTInfo payload (imprint, genTime with sub-second precision, serial, nonce, accuracy), the status-to-token coupling, and the token wrapper composed over CMS with the single-signer rule. Fail-closed — `parse`, `parseRequest`, `parseResponse`, `parseTstInfo`, `parseToken`, `pemDecode`, `pemEncode` |
219
219
  | `pki.schema.attrcert` | Attribute certificates (RFC 5755): holder and issuer identities as validated GeneralNames, the validity window as real `Date`s, and the privilege attributes and extensions decoded to structured values (role, clearance, service and access identity, group, charging identity; audit identity, target and proxy information, no-rev-avail, AA controls), with the raw signed region for a verifier. Unknown types stay opaque, and the obsolete v1 form is recognized and deferred Fail-closed — `parse`, `pemDecode`, `pemEncode` |
220
220
  | `pki.schema.crmf` | Certificate request messages (RFC 4211) — the CMP and EST enrollment body. The requested-certificate template (subject, public key, validity, extensions), proof of possession, and registration controls, with the raw `CertRequest` region surfaced for the caller to hash. Names are dual-accepted, IMPLICIT and EXPLICIT. This toolkit ships no proof-of-possession verifier yet, so confirming that a requester holds the key it asks to have certified remains the CA's own step Fail-closed — `parse`, `pemDecode`, `pemEncode` |
@@ -232,7 +232,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
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
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; the AKI optionally naming the issuing certificate by name and serial), subject alternative names, certificate policies with their RFC 5280 section 4.2.1.4 qualifiers (a CPS pointer and a user notice), name constraints, authority information access, CRL distribution points, the freshest CRL, issuer alternative names, the policy machinery path validation acts on (policy constraints, inhibit anyPolicy, policy mappings), the RFC 3739 qualified-certificate statements including the ETSI EN 319 412-5 set, the RFC 6962 certificate-transparency pair (the precertificate poison and the embedded SCT list), the Active Directory Certificate Services enrollment extensions (certificate template, legacy template name, CA version, previous-CA-certificate hash, application policies), subject information access, subject directory attributes, and the RFC 6960 OCSP no-check responder marker, from the spec. That is every extension the shared certificate-extension decoders read, so any certificate `pki.lint.certificate` and `pki.inspect` can read in full the toolkit can also issue; any other extension is taken 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
- | `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, the RFC 3739 qualified-certificate statements, 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` |
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, the RFC 3739 qualified-certificate statements, the Microsoft certificate template and application policies, subject information access, subject directory attributes, or an array of pre-encoded Extension DER; an extension the issuing CA assigns, such as the authority key identifier or the OCSP no-check marker, is refused by name rather than requested), 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` |
238
238
  | `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `krr` (key recovery, §5.3.7), `ccr` (cross-certification, §5.3.11: a `CertReqMessages` at the normative floor, where the requesting CA keeps its private key so a private-key-transport encryptedKey proof-of-possession is refused, and the optional App. D.6 single-request cardinality is not enforced), `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). Protection is exactly one of `opts.{ key, cert }`, a signature under the sender key with the algorithm resolved from the signer certificate so RSA (PKCS#1 v1.5 / PSS), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived), or `opts.kem`, a KEM-based MAC for a client whose key can only establish secrets (RFC 9810 §5.1.3.4): the ciphertext a peer encapsulated to its ML-KEM key is decapsulated, the key is derived under HKDF-SHA256 with a context bound to the transaction identifier of the message that carried the ciphertext, and `pki.cmp.verify` checks it from the shared secret. Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. A certification authority can take longer to answer than a process is held open, so a `poll-timeout` carries a `resumeToken` and `resumePoll(token)` continues the same transaction in a later process: the token is plain JSON naming the transaction, the nonce the next request echoes, the polled request and the arm its grant arrives on, and the key the grant must certify. It carries no secret and grants nothing, since the protection material and the endpoint come from the session built to resume with, and the resumed poll verifies, nonce-binds, and key-binds every response. Its fields are what the resumed exchange is held to, so store it where the enrollment's own state is stored: someone who can rewrite it can widen what the resumed session accepts, as far as that session's trust anchors and the authority's protection allow and no further. The same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. `openKeyPackage(container, opts)` opens a private key the CA generated centrally and delivered in the `privateKey` field of a granted `CertifiedKeyPair` (RFC 9483 §4.1.6): a CMS `SignedData` over an RFC 5958 `AsymmetricKeyPackage`, sealed in a CMS `EnvelopedData`. `opts.key` (with `opts.cert`) opens the key transport and key agreement containers a signature-protected request selects, `opts.password` the password container a MAC-protected request selects. The authority is authorized before any key material is returned: its certificate must chain to an anchor in `opts.trustAnchors` AND assert the `id-kp-cmKGA` extended key usage, since a certificate with no `extendedKeyUsage` permits every purpose and so authorizes nothing; `opts.authorizedBySharedSecret` states §4.1.6's exemption for an entity that authorizes by the secret that protected its request. Returns `{ keys, kga, trusted }`, where each key is a PKCS#8 `PrivateKeyInfo` ready for `pki.key.import`; `keys` is the whole RFC 5958 `AsymmetricKeyPackage` (`SIZE (1..MAX)`), while a session enrollment requires the sequence of one §4.1.6 profiles it to. Both CMS layers are read as a ContentInfo or as the bare structure, told apart by what the SEQUENCE opens with. `session(opts)` drives the whole exchange under `opts.acceptCentralKeyGeneration`: the request omits `certTemplate.publicKey`, carries no proof of possession, and goes out as `cmp2021`; the session opens the delivered container with the credential it enrolled under and surfaces it as `deliveredKey`, having first checked that the issued certificate certifies the delivered key. Without the option, such a request and such a grant are both refused. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `openKeyPackage`, `session` |
@@ -242,7 +242,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
242
242
  | `pki.cms` | CMS signing, verification, encryption, and compression (RFC 5652). `sign(content, signers, opts)` produces a SignedData (§5), attached or detached, with one or many signers over RSA, RSASSA-PSS, ECDSA, EdDSA, the post-quantum ML-DSA-44/65/87 (RFC 9882) and SLH-DSA (all twelve FIPS 205 sets, RFC 9814), and composite ML-DSA pairing ML-DSA with a traditional RSA, ECDSA, or EdDSA key (accepted only when both components verify, draft-ietf-lamps-cms-composite-sigs). It builds the signed attributes (content-type, message-digest, signing-time) as canonical DER, signs the exact §5.4 preimage, and emits a DER `Buffer` or PEM. The content may also be an async iterable of byte chunks, which signs a large detached payload without holding it in memory: the payload is hashed incrementally under every signer's digest algorithm in one pass, and `verify` accepts the same streamed form as its `content` option. A signer may also be key-only — `{ key, spki, keyIdentifier }` with no certificate — which RFC 5272 §3.2 requires when a Full PKI Request's signer is the key of a certification request that request carries: the signer identifier takes the subjectKeyIdentifier form carrying the identifier the request declares, the signature scheme resolves from the request's own public key, and no certificate is embedded. `verify(input, opts)` parses a SignedData over the strict `pki.schema.cms` codec, locates each SignerInfo's signer certificate by its issuerAndSerialNumber or subjectKeyIdentifier, and checks the signature over the exact §5.4 preimage: with signed attributes present it confirms the message-digest attribute equals the content digest and verifies over the DER re-encoding of the SignedAttributes (the on-wire `[0]` tag replaced by a universal SET OF), and otherwise directly over the content. It returns a per-signer verdict with the matched signer certificate. `valid` and `trusted` are separate claims and neither implies the other: a SignedData carries its own certificates, so `valid` says the signature is sound under one of them and nothing about who signed, while `trusted` says every signer chained to a root named in `opts.trustAnchors`, validated through the same RFC 5280 path engine `pki.path.validate` uses. Without anchors there is nothing to chain to and `trusted` is `false`; anchors that cannot be read throw, rather than reading as untrusted. An unrecognized option is refused rather than ignored. `countersign(cms, signers, opts)` adds a countersignature (§11.4) — a `SignerInfo` over the countersigned SignerInfo's signature value, any signer algorithm, nestable, with the primary bytes preserved so it still verifies — attached as the id-countersignature unsigned attribute; `verify` returns each countersignature's verdict under `signers[i].countersignatures` and every unsigned attribute — including an RFC 3161 timestamp token, attachable via `sign`'s `unsignedAttributes` — under `signers[i].unsignedAttrs`, surfaced unauthenticated. `encrypt(content, recipients, opts)` produces an EnvelopedData, AuthEnvelopedData (AES-GCM, the authenticated default), or EncryptedData, with recipients auto-dispatched off the certificate key to key transport (RSAES-OAEP; v1.5 is never emitted), key agreement (ephemeral-static ECDH over P-256/384/521 with the X9.63 KDF, and X25519/X448 with HKDF), symmetric key wrap, password (PBKDF2 with RFC 3211 PWRI-KEK), or the post-quantum ML-KEM (and composite ML-KEM, draft-lamps-pq-composite-kem) KEMRecipientInfo (RFC 9629/9936), wrapping one fresh content key for every recipient. The content may also be an async iterable of byte chunks, streamed through the AES-GCM or AES-CBC content cipher so a large plaintext is encrypted without being buffered whole; the ciphertext is assembled before the definite-length encryptedContent is emitted, byte-for-byte the buffered form. `decrypt(input, keyMaterial, opts)` recovers the content through the matching arm and returns it with an `authenticated` flag; every secret-dependent failure collapses to one uniform `cms/decrypt-failed` verdict (Bleichenbacher, EFAIL, and password-oracle freedom), and PKCS#1 v1.5 is decrypt-only under the RFC 3218 implicit-rejection countermeasure. With `opts.stream: true` the recovered `content` is an async iterable of plaintext chunks instead of a single Buffer, for a payload too large to hold whole; the authenticated modes (AuthEnvelopedData, AuthenticatedData, AES-GCM) verify integrity before the iterable yields, so a forged message throws before any plaintext is exposed, while a CBC EnvelopedData or EncryptedData yields the plaintext as the cipher produces it. Every key-establishment secret the toolkit allocates is wiped once used, on the failing path as well as the succeeding one: the KEM shared secret and its derived key-encryption key, the raw ECDH / X25519 / X448 agreement secret, a password-derived key-encryption key, and the content-encryption key itself, cleared once the message is complete since all recipients share it. Caller-supplied key material is never written to (best-effort; NIST SP 800-227 §4.2, RFC 9629 §7). `authenticate(content, recipients, opts)` produces an `id-ct-authData` (§9): cleartext content plus an HMAC-SHA-256/384/512 MAC, authenticated but not encrypted, with the fresh MAC key wrapped for every recipient through the same RecipientInfo model. The MAC covers the authenticated attributes (content-type and message-digest) re-tagged to the EXPLICIT SET OF (§9.2), or the content octets directly; `decrypt` recovers the MAC key, recomputes the MAC and independently the message-digest (§9.3), and releases the content only after both pass, with every secret-dependent failure collapsing to the uniform `cms/decrypt-failed`. `compress(content, opts)` and `decompress(input, opts)` produce and consume a CompressedData (RFC 3274; ZLIB, version 0, id-alg-zlibCompress); decompress bounds the uncompressed output at 16 MiB and stops before it is materialized, so a decompression bomb fails closed as `cms/decompress-too-large`. Compression is a size transform with no integrity or confidentiality (RFC 8551 §2.4.5). `certsOnly(certs, opts?)` builds a certs-only certificate-management message (RFC 8551 §3.8): a degenerate SignedData with an empty signerInfos and no eContent that conveys certificates and CRLs without signing anything, `parseCertsOnly(input, opts?)` reads one back to its raw certificate and CRL DER (a CRL-only message is valid here, unlike the cert-required RFC 5272 form that `pki.est.parseCertsOnly` reads), and `isCertsOnly(input)` recognizes one structurally. Fail-closed with typed `cms/*` errors — `sign`, `verify`, `countersign`, `encrypt`, `authenticate`, `decrypt`, `compress`, `decompress`, `certsOnly`, `parseCertsOnly`, `isCertsOnly` |
243
243
  | `pki.smime` | S/MIME message assembly, verification, encryption, and compression over the CMS layer (RFC 8551). `sign(content, signers, opts)` wraps a MIME entity in either form: `multipart/signed`, where the content stays readable in any MUA and a detached CMS SignedData rides alongside as `application/pkcs7-signature` with a matching `micalg`, or `application/pkcs7-mime; smime-type=signed-data`, where the whole entity is a base64 CMS SignedData. The signed bytes are the entity's §3.1.1 canonical form with CRLF line endings, and `verify(message, opts)` unwraps both forms and recomputes over the same canonicalizer, so a transport that re-wraps line endings still verifies while a tampered part fails. `encrypt(content, recipients, opts)` envelopes a MIME entity as an opaque `application/pkcs7-mime` message and `decrypt(message, keyMaterial, opts)` opens one, as `smime-type=authEnveloped-data` (AES-GCM, confidentiality and integrity, the default) or `smime-type=enveloped-data` (AES-CBC, confidentiality only, so `decrypt` reports `authenticated: false`, the §3.3 no-integrity caveat). The `smime-type` is derived from the CMS body rather than the header, and decryption is fail-closed and oracle-free. The crypto is entirely `pki.cms.sign` / `verify` / `encrypt` / `decrypt`, so it is algorithm-agnostic: any RSA / RSASSA-PSS / ECDSA / EdDSA / ML-DSA / SLH-DSA signer and any RSA-OAEP / ECDH / X25519 / X448 / AES-KW / PBKDF2 / ML-KEM recipient carries through. As with `cms.verify`, `verify` returns the per-signer verdict plus the recovered content, and `valid` and `trusted` are separate claims: `valid` says the signature is sound under a certificate the message carried, `trusted` says every signer chained to a root named in `opts.trustAnchors`. Anchoring here is validated for email at both ends of the chain — the signer certificate must carry `emailProtection` (RFC 8551 §4.4.4) and the anchor's own trust metadata must permit that purpose, since a root can be distrusted for email while remaining a good TLS root. Override either with `requiredEku` / `checkPurpose`. `compress(content, opts)` and `decompress(message, opts)` add the opaque `application/pkcs7-mime; smime-type=compressed-data; name=smime.p7z` frame (§3.6, RFC 3274), a size transform with no integrity or confidentiality (§2.4.5), bounded against a bomb; the recovered content, which may itself be signed or enveloped, is returned for the caller to re-verify. Header protection (RFC 9788): `sign` and `encrypt` take `opts.protectHeaders`, which inlines the caller's `opts.headers` on the Cryptographic Payload root (its Content-Type gaining `hp="clear"` when signed or `hp="cipher"` when encrypted) so the CMS signature or encryption covers them, defeating a transport that rewrites or reads Subject, From, and the rest. `verify` and `decrypt` surface the authenticated inner set as `protectedHeaders` plus `headerProtection { present, mode, fromMismatch, confidential, legacy }`, so a tampered outer header cannot alter it and `fromMismatch` flags an outer From that disagrees. Encryption applies a Header Confidentiality Policy: the default `hcp_baseline` obscures the outer Subject to `[...]` and removes Comments and Keywords, so the real values live only in the ciphertext, and `decrypt` recovers them. Every emitted header routes through a fail-closed injection guard that rejects a CR, LF, or NUL value and a non-ftext name, and a malformed or contradictory `hp` wrap fails closed as `smime/bad-header-protection` rather than silently downgrading. The CMS crypto is unchanged. Inbound legacy RFC 8551 header protection is recognized opt-in: `verify` and `decrypt` with `opts.legacyHeaderProtection` detect a legacy `message/rfc822`-wrapped payload by the RFC 9788 §4.10.1 four-condition identification and surface the inner headers under `headerProtection.legacy = { headers, mode, fromMismatch, confidential }`, where `headers` is an ordered `[{ name, value }]` array retaining legally repeated fields such as `Received`. Those never appear in `protectedHeaders` and never set `present: true`. Because a legacy message is structurally indistinguishable from an ordinary forwarded `message/rfc822`, this is an explicit heuristic (§4.10.2, "no strong end-to-end guarantees"): a caller keying trust off `present` or `protectedHeaders` is never misled, and only one that explicitly reads `headerProtection.legacy.headers` and cross-checks `legacy.fromMismatch` consumes it. It is off by default, and a nested crypto layer, an inner `hp=`, a non-`message/rfc822` payload, or a duplicate Content-Type reports `legacy: null`. Bidirectionally interoperable with `openssl smime` and `openssl cms`. `buildCertsOnly(certs, opts?)` wraps a `pki.cms.certsOnly` certificate-management message in one `application/pkcs7-mime; smime-type=certs-only; name=smime.p7c` entity, read back by OpenSSL's `pkcs7 -print_certs`. Fail-closed with typed `smime/*` errors — `sign`, `verify`, `encrypt`, `decrypt`, `compress`, `decompress`, `buildCertsOnly` |
244
244
  | `pki.tsp` | Time-Stamp Protocol (RFC 3161). `sign(messageImprint, tsa, opts)` produces a TimeStampToken: a CMS SignedData over `pki.cms.sign` whose content is a `TSTInfo` carrying the timestamped message imprint, the TSA policy, a serial number, and `genTime` with optional accuracy, nonce, and ordering, plus the §2.4.2 signing-certificate attribute binding the token to the TSA certificate (SHA-2 imprints, any `pki.cms.sign` TSA key). `request` and `parseRequest` build and parse the TimeStampReq a client sends (imprint, requested policy, nonce, certReq); `response` and `parseResponse` handle the TimeStampResp a TSA returns, either a granted status wrapping a token or a rejection with PKIStatus and failure info, with the §2.4.2 status-to-token coupling enforced in both directions. `verify(token, data, opts)` verifies a token fail-closed: the CMS signature over the exact signed bytes, the message imprint recomputed from the data, the TSTInfo content type, the ESSCertID(V2) binding to the TSA certificate, the §2.3 critical timeStamping-only extendedKeyUsage, the request nonce when used, and, with a trust anchor supplied, full certification-path validation of the TSA certificate at the token's `genTime` — judged under the `timeStamping` purpose, so an anchor's own per-purpose trust metadata reaches the decision rather than sitting inert. It returns `{ valid, trusted, genTime, serialNumber, tstInfo, ... }`, where `trusted` is the separate claim that the authority chained to an anchor you named: without one there is nothing to chain to and it is `false`, which is the distinction a timestamp re-read years later turns on — `sign`, `request`, `parseRequest`, `response`, `parseResponse`, `verify` |
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` |
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, and per-response `singleExtensions` naming the §4.4.4 archive cutoff and the §4.4.2 CRL reference as fields, each read back by name by the parser. `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
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` |
@@ -130,9 +130,9 @@ function _encodeV2FormIssuer(dnSpec) {
130
130
  return b.contextConstructed(0, issuerNameGns);
131
131
  }
132
132
  function _encodeValidity(notBefore, notAfter) {
133
- guard.time.assertValid(notBefore, _err, "attrcert/bad-input", "notBeforeTime");
134
- guard.time.assertValid(notAfter, _err, "attrcert/bad-input", "notAfterTime");
135
- // allow:nan-date-comparison-unguarded -- both operands are guard.time.assertValid'd above.
133
+ guard.time.assertEncodable(notBefore, _err, "attrcert/bad-input", "notBeforeTime");
134
+ guard.time.assertEncodable(notAfter, _err, "attrcert/bad-input", "notAfterTime");
135
+ // allow:nan-date-comparison-unguarded -- both operands are guard.time.assertEncodable'd above.
136
136
  if (guard.time.instantOf(notBefore) > guard.time.instantOf(notAfter)) throw _err("attrcert/bad-input", "notBeforeTime must not be after notAfterTime (RFC 5755 sec. 4.2.6)");
137
137
  return b.sequence([b.generalizedTime(notBefore), b.generalizedTime(notAfter)]);
138
138
  }
package/lib/cmp-build.js CHANGED
@@ -136,7 +136,7 @@ function _encodeInfoValue(itav) {
136
136
  return b.nullValue();
137
137
  }
138
138
  if (name === "confirmWaitTime") {
139
- guard.time.assertValid(itav.infoValue, _err, "cmp/bad-info-value", "confirmWaitTime infoValue");
139
+ guard.time.assertEncodable(itav.infoValue, _err, "cmp/bad-info-value", "confirmWaitTime infoValue");
140
140
  return b.generalizedTime(itav.infoValue);
141
141
  }
142
142
  if (name === "certProfile") {
@@ -175,7 +175,7 @@ function _encodeHeader(headerSpec, protectionAlgDer, pvno) {
175
175
  _b.encodeGeneralName(headerSpec.recipient),
176
176
  ];
177
177
  if (headerSpec.messageTime != null) {
178
- guard.time.assertValid(headerSpec.messageTime, _err, "cmp/bad-input", "header.messageTime");
178
+ guard.time.assertEncodable(headerSpec.messageTime, _err, "cmp/bad-input", "header.messageTime");
179
179
  children.push(b.explicit(0, b.generalizedTime(headerSpec.messageTime)));
180
180
  }
181
181
  if (protectionAlgDer != null) children.push(b.explicit(1, b.raw(protectionAlgDer)));
@@ -303,7 +303,7 @@ function buildCrlStatusList(spec) {
303
303
  }
304
304
  var status = [source], askedInstant = null, asked = spec.thisUpdate;
305
305
  if (asked != null) {
306
- guard.time.assertValid(asked, _err, "cmp/bad-input", "crlUpdate.thisUpdate");
306
+ guard.time.assertEncodable(asked, _err, "cmp/bad-input", "crlUpdate.thisUpdate");
307
307
  askedInstant = guard.time.instantOf(asked);
308
308
  _push(status, b.raw(_b.timeDer(new _Date(askedInstant), "crlUpdate.thisUpdate")));
309
309
  }
package/lib/cms-sign.js CHANGED
@@ -275,7 +275,7 @@ async function _signStream(stream, signers, opts) {
275
275
  throw _err("cms/bad-input",
276
276
  "a key-only signer must be the ONLY SignerInfo in a Full PKI Request (RFC 5272 sec. 3.2)");
277
277
  }
278
- if (opts.signingTime != null && opts.signingTime !== false) guard.time.assertValid(opts.signingTime, _err, "cms/bad-input", "signingTime");
278
+ if (opts.signingTime != null && opts.signingTime !== false) guard.time.assertEncodable(opts.signingTime, _err, "cms/bad-input", "signingTime");
279
279
  var rcs = intrinsic.map(list, function (s) { return _resolveSignerContext(s, opts); });
280
280
  var digestNames = [], seenDigest = intrinsic.create(null);
281
281
  intrinsic.forEach(rcs, function (r) { if (!seenDigest[r.scheme.digest]) { seenDigest[r.scheme.digest] = 1; intrinsic.push(digestNames, r.scheme.digest); } });
@@ -315,7 +315,7 @@ function _sign(content, signers, opts) {
315
315
  "it WITHOUT signed attributes would produce a signature that could be re-presented as one over " +
316
316
  "attributes (RFC 5652 sec. 5.4); sign it with signed attributes instead");
317
317
  }
318
- if (opts.signingTime != null && opts.signingTime !== false) guard.time.assertValid(opts.signingTime, _err, "cms/bad-input", "signingTime");
318
+ if (opts.signingTime != null && opts.signingTime !== false) guard.time.assertEncodable(opts.signingTime, _err, "cms/bad-input", "signingTime");
319
319
 
320
320
  return Promise.all(list.map(function (s) { return _buildSignerInfo(s, contentBuf, eContentType, opts); }))
321
321
  .then(function (built) { return _assembleSignedData(built, eContentType, opts, contentBuf); });
@@ -513,7 +513,7 @@ function _countersign(cmsInput, signers, opts) {
513
513
  guard.identifier.assertKnownKeys(opts, KNOWN_COUNTERSIGN_OPTS, _err, "cms/bad-input", "unknown opts field ");
514
514
  var list = Array.isArray(signers) ? signers : [signers];
515
515
  if (!list.length) throw _err("cms/bad-input", "pki.cms.countersign requires at least one countersigner");
516
- if (opts.signingTime != null && opts.signingTime !== false) guard.time.assertValid(opts.signingTime, _err, "cms/bad-input", "signingTime");
516
+ if (opts.signingTime != null && opts.signingTime !== false) guard.time.assertEncodable(opts.signingTime, _err, "cms/bad-input", "signingTime");
517
517
  var der = pkix.coerceToDer(cmsInput, { pemLabel: null, PemError: frameworkError.PemError, ErrorClass: CmsError, prefix: "cms" });
518
518
  var parsed = cms.parse(der);
519
519
  if (!Array.isArray(parsed.signerInfos)) throw _err("cms/bad-input", "pki.cms.countersign input is not a CMS SignedData");
package/lib/crl-sign.js CHANGED
@@ -304,7 +304,7 @@ function _buildRevoked(entryList, isDelta) {
304
304
  if (codeNum !== 0) pushE("reasonCode", false, b.enumerated(BigInt(codeNum)));
305
305
  }
306
306
  if (e.invalidityDate != null) {
307
- guard.time.assertValid(e.invalidityDate, _err, "crl/bad-input", "invalidityDate");
307
+ guard.time.assertEncodable(e.invalidityDate, _err, "crl/bad-input", "invalidityDate");
308
308
  pushE("invalidityDate", false, b.generalizedTime(e.invalidityDate));
309
309
  }
310
310
  if (e.certificateIssuer != null) throw _err("crl/bad-input", _CERT_ISSUER_DEFERRED);
@@ -397,7 +397,7 @@ function _sign(spec, issuer, opts) {
397
397
  var nextU = null;
398
398
  if (spec.nextUpdate != null) {
399
399
  nextU = _timeDer(spec.nextUpdate, "nextUpdate");
400
- // allow:nan-date-comparison-unguarded -- both operands are guard.time.assertValid'd via _timeDer on the
400
+ // allow:nan-date-comparison-unguarded -- both operands are guard.time.assertEncodable'd via _timeDer on the
401
401
  if (guard.time.instantOf(spec.nextUpdate) < guard.time.instantOf(spec.thisUpdate)) throw _err("crl/bad-input", "nextUpdate must not be before thisUpdate (RFC 5280 sec. 5.1.2.5)");
402
402
  }
403
403
 
package/lib/crmf-sign.js CHANGED
@@ -89,7 +89,7 @@ function _encodeOptionalValidity(validity) {
89
89
  var parts = [];
90
90
  if (nb != null) parts.push(b.explicit(0, _b.timeDer(nb, "validity notBefore")));
91
91
  if (na != null) parts.push(b.explicit(1, _b.timeDer(na, "validity notAfter")));
92
- // allow:nan-date-comparison-unguarded -- both instants passed timeDer's guard.time.assertValid above.
92
+ // allow:nan-date-comparison-unguarded -- both instants passed timeDer's guard.time.assertEncodable above.
93
93
  if (nb != null && na != null && guard.time.instantOf(nb) > guard.time.instantOf(na)) throw _err("crmf/bad-validity", "notBefore must not be after notAfter");
94
94
  return b.implicit(4, b.sequence(parts));
95
95
  }
package/lib/csr-sign.js CHANGED
@@ -70,8 +70,12 @@ function _challengePassword(pw) {
70
70
  * (a common-name string, an array of RDNs, or raw Name DER; MAY be empty), `subjectPublicKey` (the SPKI
71
71
  * DER of the key being certified), and optional `extensionRequest` (requested v3 extensions, as an object
72
72
  * of subjectAltName / keyUsage / extendedKeyUsage / basicConstraints / certificatePolicies /
73
- * subjectKeyIdentifier / qcStatements, or an array of pre-encoded Extension DER) and
74
- * `challengePassword`. `key` (or
73
+ * subjectKeyIdentifier / qcStatements / msCertificateTemplate / msEnrollCertType /
74
+ * msApplicationPolicies / subjectInfoAccess / subjectDirectoryAttributes and the rest of the
75
+ * subject-owned set `pki.x509.sign` takes, or an array of pre-encoded Extension DER) and
76
+ * `challengePassword`. An extension the issuing CA assigns (authorityKeyIdentifier, the
77
+ * certificate-transparency pair, the CA version and previous-certificate hash, ocspNoCheck) is not a
78
+ * request and is refused by name. `key` (or
75
79
  * `{ key }`) is the subject's own PKCS#8 private key / WebCrypto CryptoKey, so the request is self-signed
76
80
  * to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the
77
81
  * request is returned. The signature algorithm is resolved from the subject key (RSA PKCS#1 v1.5 or PSS,
package/lib/guard-time.js CHANGED
@@ -11,6 +11,10 @@ var _isNaN = Number.isNaN;
11
11
  var _Date = Date;
12
12
 
13
13
  var _dateGetTime = require("./guard-intrinsic").uncurry(Date.prototype.getTime);
14
+ var _dateGetUTCFullYear = require("./guard-intrinsic").uncurry(Date.prototype.getUTCFullYear);
15
+ /** @internal A DER GeneralizedTime carries a four-digit year and a UTCTime a narrower one, so a Date
16
+ * outside 0000..9999 has no PKI encoding. */
17
+ var DER_YEAR_MIN = 0, DER_YEAR_MAX = 9999;
14
18
 
15
19
  // @enforced-by guard-shape-reinlined
16
20
  // @guard-shape \.getTime\s*\(
@@ -24,6 +28,21 @@ function assertValid(value, E, code, label) {
24
28
  return value;
25
29
  }
26
30
 
31
+ // @enforced-by behavioral -- the year bound has no rename-proof code shape; a RED vector per producer route is the guard
32
+ /** @internal The guard for a Date a verb WRITES as a DER time: `assertValid`, then the year is held
33
+ * to DER_YEAR_MIN..DER_YEAR_MAX so the refusal carries the caller's code before the codec sees the
34
+ * value. Each producer route has a vector that a year-10000 Date reports the verb's own bad-input
35
+ * code, never asn1/bad-generalizedtime. A Date a verb only compares against (a verification clock)
36
+ * passes `assertValid` alone, and has a vector that the same Date is accepted and compared. */
37
+ function assertEncodable(value, E, code, label) {
38
+ assertValid(value, E, code, label);
39
+ var year = _dateGetUTCFullYear(value);
40
+ if (year < DER_YEAR_MIN || year > DER_YEAR_MAX) {
41
+ throw E(code, (label || "value") + " year " + year + " is outside " + DER_YEAR_MIN + ".." + DER_YEAR_MAX + ", the range a DER time can carry");
42
+ }
43
+ return value;
44
+ }
45
+
27
46
  // @enforced-by nan-date-comparison-unguarded
28
47
  function within(instant, lower, upper, E, code, label, opts) {
29
48
  assertValid(instant, E, code, label);
@@ -49,6 +68,7 @@ function toDate(value) {
49
68
 
50
69
  module.exports = _freeze({
51
70
  assertValid: assertValid,
71
+ assertEncodable: assertEncodable,
52
72
  instantOf: instantOf,
53
73
  isDate: isDate,
54
74
  toDate: toDate,
package/lib/ocsp.js CHANGED
@@ -222,6 +222,14 @@ function _normCertDer(cert, what) {
222
222
  * DER (RFC 6960 sec. 4.2.1: no CMS wrapper, no signed attributes). The responder certificate is
223
223
  * embedded in `certs [0]` so a relying party can find it. Returns the response DER, or PEM.
224
224
  *
225
+ * Each response may carry `singleExtensions`, as an object or as an array of pre-encoded Extension
226
+ * DER. The object form takes `archiveCutoff`, the Date before which the responder no longer holds
227
+ * status (RFC 6960 sec. 4.4.4), and `crlReferences`, a `{ crlUrl, crlNum, crlTime }` naming the CRL
228
+ * the status was drawn from (sec. 4.4.2), any subset of the three. A pre-encoded entry is read with
229
+ * the parser's own singleExtensions reader before it is emitted, so a response this verb signs is
230
+ * one `pki.schema.ocsp.parseResponse` reads back, and a malformed archiveCutoff or CrlID is refused
231
+ * here with the code the parser would have raised.
232
+ *
225
233
  * @opts
226
234
  * nonce a request nonce Buffer to echo back in responseExtensions (RFC 9654).
227
235
  * extendedRevoke emit the id-pkix-ocsp-extended-revoke extension (RFC 6960 sec. 4.4.8).
@@ -280,7 +288,7 @@ function _signResponse(responseData, responder, respCert, respCertDer, responder
280
288
 
281
289
  return _responderID(responseData.responderID, respCert).then(function (ridNode) {
282
290
  return Promise.all(responses.map(function (r) { return _buildSingleResponse(r, opts); })).then(function (srNodes) {
283
- var rdChildren = [ridNode, b.generalizedTime(_asDate(responseData.producedAt) || new Date()), b.sequence(srNodes)];
291
+ var rdChildren = [ridNode, b.generalizedTime(_asEncodableDate(responseData.producedAt, "producedAt") || new Date()), b.sequence(srNodes)];
284
292
  var respExts = [];
285
293
  if (opts.nonce != null) { _assertNonce(opts.nonce); respExts.push(_nonceExt(opts.nonce)); }
286
294
  if (opts.extendedRevoke) respExts.push(b.sequence([b.oid(OID_EXTENDED_REVOKE), b.octetString(b.nullValue())]));
@@ -303,6 +311,13 @@ function _asDate(d) {
303
311
  if (isNaN(guard.time.instantOf(dt))) throw _err("ocsp/bad-input", "an invalid date value " + guard.text.showValue(d));
304
312
  return dt;
305
313
  }
314
+ /** @internal `_asDate` for a Date this verb WRITES as a GeneralizedTime (producedAt, thisUpdate,
315
+ * nextUpdate, a revocation time): the encodable year range is held here so the fault stays in this
316
+ * verb's domain. The verify clock is only compared and stays on `_asDate`. */
317
+ function _asEncodableDate(d, which) {
318
+ var dt = _asDate(d);
319
+ return dt === null ? null : guard.time.assertEncodable(dt, _err, "ocsp/bad-input", which);
320
+ }
306
321
  function _snapshotSignerKey(key, owned) {
307
322
  if (Buffer.isBuffer(key) || key instanceof Uint8Array) { // allow:byte-source-narrow -- responder private key on the key-ownership contract (Buffer / Uint8Array / PEM / CryptoKey); widening keys is a separate root decision
308
323
  var copy = guard.bytes.snapshot(key, OcspError, "ocsp/bad-input", "the responder key");
@@ -331,8 +346,8 @@ function _buildSingleResponse(r, opts) {
331
346
  * attached handlers, and an earlier entry's rejection would be orphaned: the caller catches
332
347
  * sign()'s failure and the process still sees an unhandled rejection. */
333
348
  return certIdP.then(function (certID) {
334
- var thisUpdate = _asDate(r.thisUpdate) || new Date();
335
- var nextUpdate = r.nextUpdate === null ? null : (_asDate(r.nextUpdate) || _defaultNextUpdate());
349
+ var thisUpdate = _asEncodableDate(r.thisUpdate, "thisUpdate") || new Date();
350
+ var nextUpdate = r.nextUpdate === null ? null : (_asEncodableDate(r.nextUpdate, "nextUpdate") || _defaultNextUpdate());
336
351
  /** @internal RFC 6960 sec. 4.2.2.1 makes thisUpdate and nextUpdate a validity interval, and says
337
352
  * it corresponds to the {thisUpdate, nextUpdate} interval in CRLs. An interval whose end
338
353
  * precedes its start states a status window that closed before it opened, and pki.ocsp.verify
@@ -353,16 +368,76 @@ function _buildSingleResponse(r, opts) {
353
368
  var statusNode = _certStatusNode(r.status, opts);
354
369
  var srChildren = [certID, statusNode, b.generalizedTime(thisUpdate)];
355
370
  if (nextUpdate !== null) srChildren.push(b.explicit(0, b.generalizedTime(nextUpdate)));
356
- if (r.singleExtensions && r.singleExtensions.length) srChildren.push(b.explicit(1, b.sequence(r.singleExtensions)));
371
+ if (r.singleExtensions != null) {
372
+ var singleDer = _singleExtensionsDer(r.singleExtensions);
373
+ if (singleDer.length) srChildren.push(b.explicit(1, b.sequence(singleDer)));
374
+ }
357
375
  return b.sequence(srChildren);
358
376
  });
359
377
  }
360
378
  function _defaultNextUpdate() { return new Date(Date.now() + constants.TIME.days(7)); }
379
+ var _SINGLE_EXT_KEYS = Object.assign(Object.create(null), { archiveCutoff: 1, crlReferences: 1 });
380
+ var _CRL_ID_KEYS = Object.assign(Object.create(null), { crlUrl: 1, crlNum: 1, crlTime: 1 });
381
+
382
+ /** @internal RFC 6960 sec. 4.4.2 and sec. 4.4.4 put archiveCutoff and the CRL references in a
383
+ * SingleResponse's singleExtensions. The object form names them as fields; the array form carries
384
+ * pre-encoded Extension DER, and each entry is run through the parser's own singleExtensions reader
385
+ * first, so this verb never emits an entry pki.schema.ocsp.parseResponse would refuse. */
386
+ function _singleExtensionsDer(spec) {
387
+ if (Array.isArray(spec)) {
388
+ var dense = pkiBuild.reqDenseArray(spec, "singleExtensions", _err, "ocsp/bad-input");
389
+ var ders = dense.map(function (d, i) {
390
+ return guard.bytes.snapshotSource(d, OcspError, "ocsp/bad-input", "singleExtensions[" + i + "]");
391
+ });
392
+ if (ders.length) ocspSchema.readSingleExtensionsDer(ders);
393
+ return ders;
394
+ }
395
+ if (!spec || typeof spec !== "object" || Buffer.isBuffer(spec)) {
396
+ throw _err("ocsp/bad-input", "singleExtensions must be an object { archiveCutoff?, crlReferences? } or an array of pre-encoded Extension DER");
397
+ }
398
+ guard.identifier.assertKnownKeys(spec, _SINGLE_EXT_KEYS, _err, "ocsp/bad-input", function (k) {
399
+ return "unknown singleExtensions field " + guard.text.showValue(k) + " (accepted: archiveCutoff, crlReferences)";
400
+ });
401
+ var out = [];
402
+ if (spec.archiveCutoff != null) {
403
+ guard.time.assertEncodable(spec.archiveCutoff, _err, "ocsp/bad-input", "singleExtensions archiveCutoff");
404
+ out.push(b.sequence([b.oid(oid.byName("ocspArchiveCutoff")), b.octetString(b.generalizedTime(spec.archiveCutoff))]));
405
+ }
406
+ if (spec.crlReferences != null) {
407
+ var c = spec.crlReferences;
408
+ if (!c || typeof c !== "object" || Array.isArray(c) || Buffer.isBuffer(c)) {
409
+ throw _err("ocsp/bad-input", "singleExtensions crlReferences must be an object { crlUrl?, crlNum?, crlTime? }");
410
+ }
411
+ guard.identifier.assertKnownKeys(c, _CRL_ID_KEYS, _err, "ocsp/bad-input", function (k) {
412
+ return "unknown crlReferences field " + guard.text.showValue(k) + " (accepted: crlUrl, crlNum, crlTime)";
413
+ });
414
+ var fields = [];
415
+ if (c.crlUrl != null) {
416
+ if (typeof c.crlUrl !== "string" || !c.crlUrl.length) throw _err("ocsp/bad-input", "crlReferences crlUrl must be a non-empty string");
417
+ for (var j = 0; j < c.crlUrl.length; j++) {
418
+ if (c.crlUrl.charCodeAt(j) > 0x7f) throw _err("ocsp/bad-input", "crlReferences crlUrl must be 7-bit ASCII (an IA5String, RFC 6960 sec. 4.4.2)");
419
+ }
420
+ fields.push(b.explicit(0, b.ia5(c.crlUrl)));
421
+ }
422
+ if (c.crlNum != null) {
423
+ var num = guard.range.authoredInteger(c.crlNum, _err, "ocsp/bad-input", "crlReferences crlNum");
424
+ if (num < 0n) throw _err("ocsp/bad-input", "crlReferences crlNum must be non-negative (it is a cRLNumber, RFC 5280 sec. 5.2.3)");
425
+ fields.push(b.explicit(1, b.integer(num)));
426
+ }
427
+ if (c.crlTime != null) {
428
+ guard.time.assertEncodable(c.crlTime, _err, "ocsp/bad-input", "crlReferences crlTime");
429
+ fields.push(b.explicit(2, b.generalizedTime(c.crlTime)));
430
+ }
431
+ out.push(b.sequence([b.oid(oid.byName("ocspCrl")), b.octetString(b.sequence(fields))]));
432
+ }
433
+ return out;
434
+ }
435
+
361
436
  function _certStatusNode(status, opts) {
362
437
  if (status == null || status === "good") return b.contextPrimitive(0, Buffer.alloc(0));
363
438
  if (status === "unknown") return b.contextPrimitive(2, Buffer.alloc(0));
364
439
  if (typeof status === "object" && status.revoked != null) {
365
- var ri = [b.generalizedTime(_asDate(status.revoked))];
440
+ var ri = [b.generalizedTime(_asEncodableDate(status.revoked, "the revocation time"))];
366
441
  if (status.revocationReason != null) {
367
442
  var code = typeof status.revocationReason === "number" ? status.revocationReason : REASON_CODE[guard.text.keyOf(status.revocationReason)];
368
443
  if (code == null) throw _err("ocsp/bad-input", "unknown revocationReason " + guard.text.showValue(status.revocationReason));
package/lib/pki-build.js CHANGED
@@ -344,7 +344,7 @@ function makeBuilder(ctx) {
344
344
  function rawErr(fullCode, message, cause) { return new ErrorClass(fullCode, message, cause); }
345
345
 
346
346
  function timeDer(date, which) {
347
- guard.time.assertValid(date, rawErr, code("bad-input"), which);
347
+ guard.time.assertEncodable(date, rawErr, code("bad-input"), which);
348
348
  var y = date.getUTCFullYear();
349
349
  return (y >= 1950 && y <= 2049) ? b.utcTime(date) : b.generalizedTime(date);
350
350
  }
@@ -1128,7 +1128,15 @@ function makeBuilder(ctx) {
1128
1128
  nameConstraints: 1, authorityInfoAccess: 1, cRLDistributionPoints: 1, freshestCRL: 1,
1129
1129
  policyConstraints: 1, inhibitAnyPolicy: 1, policyMappings: 1, policyMappingsCritical: 1,
1130
1130
  issuerAltName: 1, qcStatements: 1, qcStatementsCritical: 1,
1131
+ msCertificateTemplate: 1, msEnrollCertType: 1, msApplicationPolicies: 1,
1132
+ subjectInfoAccess: 1, subjectDirectoryAttributes: 1,
1131
1133
  };
1134
+ /** @internal RFC 2985 sec. 5.4.2 has the attribute carry "certificate extensions the requester
1135
+ * wishes to be included". What the issuing CA assigns is not a wish: the authority key
1136
+ * identifier names the CA's key, the precertificate poison and SCT list are the CA's exchange
1137
+ * with a log, the CA version and previous-certificate hash are the CA's own, and the OCSP
1138
+ * no-check marker is the CA's decision about a responder. Those stay out of this table so a
1139
+ * request naming one is refused rather than written and ignored. */
1132
1140
  function requestedExtensions(extSpec, spki) {
1133
1141
  var EXT_DECODERS = ctx.EXT_DECODERS;
1134
1142
  if (_isArray(extSpec)) {
@@ -1174,6 +1182,11 @@ function makeBuilder(ctx) {
1174
1182
  if (extSpec.policyMappings != null) guard.list.append(out, ext(O("policyMappings"), !!extSpec.policyMappingsCritical, extPolicyMappings(extSpec.policyMappings)));
1175
1183
  if (extSpec.issuerAltName != null) guard.list.append(out, ext(O("issuerAltName"), false, encodeGeneralNames(reqDenseArray(extSpec.issuerAltName, "issuerAltName"))));
1176
1184
  if (extSpec.qcStatements != null) guard.list.append(out, ext(O("qcStatements"), !!extSpec.qcStatementsCritical, extQcStatements(extSpec.qcStatements)));
1185
+ if (extSpec.msCertificateTemplate != null) guard.list.append(out, ext(O("msCertificateTemplate"), false, extMsCertificateTemplate(extSpec.msCertificateTemplate)));
1186
+ if (extSpec.msEnrollCertType != null) guard.list.append(out, ext(O("msEnrollCertType"), false, extMsEnrollCertType(extSpec.msEnrollCertType)));
1187
+ if (extSpec.msApplicationPolicies != null) guard.list.append(out, ext(O("msApplicationPolicies"), false, extCertPolicies(extSpec.msApplicationPolicies)));
1188
+ if (extSpec.subjectInfoAccess != null) guard.list.append(out, ext(O("subjectInfoAccess"), false, extSubjectInfoAccess(extSpec.subjectInfoAccess)));
1189
+ if (extSpec.subjectDirectoryAttributes != null) guard.list.append(out, ext(O("subjectDirectoryAttributes"), false, extSubjectDirectoryAttributes(extSpec.subjectDirectoryAttributes)));
1177
1190
  if (!out.length) throw E("bad-input", "the requested extensions object must request at least one extension");
1178
1191
  return b.sequence(out);
1179
1192
  }
@@ -41,6 +41,7 @@ var constants = require("./constants");
41
41
  var frameworkError = require("./framework-error");
42
42
  var intrinsic = require("./guard-intrinsic");
43
43
  var _hasOwn = intrinsic.hasOwn;
44
+ var _String = intrinsic.String;
44
45
 
45
46
  var OcspError = frameworkError.OcspError;
46
47
  var PemError = frameworkError.PemError;
@@ -56,6 +57,8 @@ var VERSION = pkix.versionReader(NS, {});
56
57
  var OID_OCSP_BASIC = oid.byName("ocspBasic");
57
58
 
58
59
  var OID_OCSP_NONCE = oid.byName("ocspNonce");
60
+ var OID_OCSP_ARCHIVE_CUTOFF = oid.byName("ocspArchiveCutoff");
61
+ var OID_OCSP_CRL = oid.byName("ocspCrl");
59
62
 
60
63
  var STATUS_NAMES = constants.NAMES.OCSP_STATUS;
61
64
 
@@ -92,10 +95,69 @@ function _rawSignature(field) {
92
95
 
93
96
  var CERTS = schema.seqOf(certificateBytes(), { assert: "sequence", code: "ocsp/bad-certs", what: "certs", max: constants.LIMITS.OCSP_MAX_CERTS, maxCode: "ocsp/too-many-certs" });
94
97
 
98
+ /** @internal RFC 6960 sec. 4.4.4: ArchiveCutoff ::= GeneralizedTime, carried as a singleExtension. */
99
+ function _readArchiveCutoff(ext) {
100
+ var node;
101
+ try { node = asn1.decode(ext.value); }
102
+ catch (e) { throw NS.E("ocsp/bad-archive-cutoff", "the archiveCutoff extension value did not decode: " + ((e && e.message) || _String(e)), e); }
103
+ if (!(node.tagClass === "universal" && node.tagNumber === asn1.TAGS.GENERALIZED_TIME)) {
104
+ throw NS.E("ocsp/bad-archive-cutoff", "the archiveCutoff extension value must be a GeneralizedTime (RFC 6960 sec. 4.4.4)");
105
+ }
106
+ try { return asn1.read.time(node); }
107
+ catch (e) { throw NS.E("ocsp/bad-archive-cutoff", "the archiveCutoff GeneralizedTime is malformed", e); }
108
+ }
109
+
110
+ /** @internal RFC 6960 sec. 4.4.2: CrlID ::= SEQUENCE { crlUrl [0] EXPLICIT IA5String OPTIONAL,
111
+ * crlNum [1] EXPLICIT INTEGER OPTIONAL, crlTime [2] EXPLICIT GeneralizedTime OPTIONAL }. Every
112
+ * field is optional and each may appear at most once, in tag order. */
113
+ function _readCrlId(ext) {
114
+ var C = "ocsp/bad-crl-id";
115
+ var node;
116
+ try { node = asn1.decode(ext.value); }
117
+ catch (e) { throw NS.E(C, "the CRL references extension value did not decode: " + ((e && e.message) || _String(e)), e); }
118
+ if (!(node.tagClass === "universal" && node.tagNumber === asn1.TAGS.SEQUENCE && node.children)) {
119
+ throw NS.E(C, "CrlID must be a SEQUENCE (RFC 6960 sec. 4.4.2)");
120
+ }
121
+ var out = { crlUrl: null, crlNum: null, crlTime: null }, last = -1;
122
+ for (var i = 0; i < node.children.length; i++) {
123
+ var k = node.children[i];
124
+ if (k.tagClass !== "context" || !k.constructed || !k.children || k.children.length !== 1) {
125
+ throw NS.E(C, "each CrlID member must be one EXPLICIT [0], [1] or [2] tag (RFC 6960 sec. 4.4.2)");
126
+ }
127
+ if (k.tagNumber <= last) throw NS.E(C, "CrlID members must appear at most once, in tag order");
128
+ last = k.tagNumber;
129
+ var inner = k.children[0];
130
+ try {
131
+ if (k.tagNumber === 0) {
132
+ if (inner.tagClass !== "universal" || inner.tagNumber !== asn1.TAGS.IA5_STRING) throw NS.E(C, "crlUrl must be an IA5String");
133
+ out.crlUrl = asn1.read.string(inner);
134
+ } else if (k.tagNumber === 1) {
135
+ if (inner.tagClass !== "universal" || inner.tagNumber !== asn1.TAGS.INTEGER) throw NS.E(C, "crlNum must be an INTEGER");
136
+ out.crlNum = asn1.read.integer(inner);
137
+ if (out.crlNum < 0n) throw NS.E(C, "crlNum must be non-negative (it is a cRLNumber, RFC 5280 sec. 5.2.3)");
138
+ } else if (k.tagNumber === 2) {
139
+ if (inner.tagClass !== "universal" || inner.tagNumber !== asn1.TAGS.GENERALIZED_TIME) throw NS.E(C, "crlTime must be a GeneralizedTime");
140
+ out.crlTime = asn1.read.time(inner);
141
+ } else {
142
+ throw NS.E(C, "CrlID has no member tagged [" + k.tagNumber + "] (RFC 6960 sec. 4.4.2)");
143
+ }
144
+ } catch (e) {
145
+ if (e && e.code === C) throw e;
146
+ throw NS.E(C, "CrlID member [" + k.tagNumber + "] is malformed", e);
147
+ }
148
+ }
149
+ return out;
150
+ }
151
+
152
+ /** @internal The extensions this profile reads are decoded onto their entry beside the raw value,
153
+ * so a consumer gets the value by name and a malformed one is refused here rather than passed
154
+ * through as opaque bytes. The nonce is RFC 9654; the other two are RFC 6960 sec. 4.4. */
95
155
  function _validateOcspExtensions(list) {
96
156
  if (!list) return list;
97
157
  for (var i = 0; i < list.length; i++) {
98
158
  var ext = list[i];
159
+ if (ext.oid === OID_OCSP_ARCHIVE_CUTOFF) { ext.archiveCutoff = _readArchiveCutoff(ext); continue; }
160
+ if (ext.oid === OID_OCSP_CRL) { ext.crlReferences = _readCrlId(ext); continue; }
99
161
  if (ext.oid !== OID_OCSP_NONCE) continue;
100
162
  var node;
101
163
  try { node = asn1.decode(ext.value); }
@@ -500,4 +562,13 @@ module.exports = {
500
562
  pemEncode: pemEncode,
501
563
  matchesRequest: matchesRequest,
502
564
  matchesResponse: matchesResponse,
565
+ /** @internal Reads a list of pre-encoded Extension DER the way this parser reads a SingleResponse's
566
+ * singleExtensions, shared with pki.ocsp.sign so an entry the signer emits is one the parser
567
+ * reads. Throws the parser's own ocsp/* code for a malformed entry. */
568
+ readSingleExtensionsDer: function (derList) {
569
+ var node;
570
+ try { node = asn1.decode(asn1.build.sequence(intrinsic.map(derList, function (d) { return asn1.build.raw(d); }))); }
571
+ catch (e) { throw NS.E("ocsp/bad-single-response", "a pre-encoded singleExtension is not DER", e); }
572
+ return _validateOcspExtensions(schema.walk(EXTENSIONS, node, NS).result);
573
+ },
503
574
  };
package/lib/tsp-sign.js CHANGED
@@ -167,7 +167,7 @@ function _sign(messageImprint, tsa, opts) {
167
167
  if (!NODE_DIGEST[guard.text.keyOf(certHashAlg)]) throw _err("tsp/unsupported-algorithm", "unsupported certHashAlgorithm " + guard.text.showValue(certHashAlg));
168
168
 
169
169
  var imprint = b.sequence([_hashAlgId(mi.hashAlgorithm), b.octetString(guard.bytes.source(mi.hashedMessage, TspError, "tsp/bad-input", "messageImprint.hashedMessage"))]);
170
- if (opts.genTime != null) guard.time.assertValid(opts.genTime, _err, "tsp/bad-input", "genTime");
170
+ if (opts.genTime != null) guard.time.assertEncodable(opts.genTime, _err, "tsp/bad-input", "genTime");
171
171
  var genTime = guard.time.isDate(opts.genTime) ? opts.genTime : new Date();
172
172
  var serial = guard.range.authoredInteger(opts.serialNumber, _err, "tsp/bad-input", "serialNumber");
173
173
  var fields = [b.integer(1n), _policy(opts.policy), imprint, b.integer(serial), b.generalizedTime(genTime)];
package/lib/x509-sign.js CHANGED
@@ -504,9 +504,9 @@ function _sign(spec, issuer, opts) {
504
504
  var scheme = signScheme.resolveSignScheme(_certLikeFromSpki(issuerSpki), { combinedRsaSig: true, pss: opts.pss, digestAlgorithm: opts.digestAlgorithm }, true, _signE);
505
505
 
506
506
  var serialTlv = _serialInteger(spec.serialNumber);
507
- guard.time.assertValid(spec.notBefore, _err, "x509/bad-input", "notBefore");
508
- guard.time.assertValid(spec.notAfter, _err, "x509/bad-input", "notAfter");
509
- // allow:nan-date-comparison-unguarded -- both operands are guard.time.assertValid'd on the two lines above (an Invalid Date throws before this comparison).
507
+ guard.time.assertEncodable(spec.notBefore, _err, "x509/bad-input", "notBefore");
508
+ guard.time.assertEncodable(spec.notAfter, _err, "x509/bad-input", "notAfter");
509
+ // allow:nan-date-comparison-unguarded -- both operands are guard.time.assertEncodable'd on the two lines above (an Invalid Date throws before this comparison).
510
510
  if (guard.time.instantOf(spec.notBefore) > guard.time.instantOf(spec.notAfter)) throw _err("x509/bad-input", "notBefore must not be after notAfter (RFC 5280 sec. 4.1.2.5)");
511
511
  var validityDer = b.sequence([_timeDer(spec.notBefore, "notBefore"), _timeDer(spec.notAfter, "notAfter")]);
512
512
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.7.23",
3
+ "version": "0.7.25",
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:d0937d40-1cca-4e77-9a29-1835e7a8ae04",
5
+ "serialNumber": "urn:uuid:6c1d7d34-8c46-44b5-aab6-26ca7c728d37",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-12T00:20:25.960Z",
8
+ "timestamp": "2026-09-12T02:32:19.183Z",
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.23",
22
+ "bom-ref": "@blamejs/pki@0.7.25",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.7.23",
25
+ "version": "0.7.25",
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.23",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.7.25",
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.23",
57
+ "ref": "@blamejs/pki@0.7.25",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]