@blamejs/pki 0.7.31 → 0.7.33

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,32 @@ 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.33 — 2026-09-12
8
+
9
+ pki.x509.extension encodes one certificate extension from its plain value form.
10
+
11
+ ### Added
12
+
13
+ - pki.x509.extension(name, value, opts) returns one Extension as DER. name is any extension name spec.extensions takes, or a dotted OID; value is the plain form spec.extensions takes for that name (the key-usage and purpose lists, the basicConstraints object, GeneralName lists, the policy, constraint, access and distribution-point objects, the qualified-certificate statements, the Active Directory enrollment values, true for the NULL-valued markers, and the explicit forms of the two key identifiers). For an unregistered dotted OID, value is the already-encoded extnValue as bytes and opts.critical is taken as stated. The criticality of a registered extension follows what pki.x509.sign emits for the object form: where RFC 5280 fixes it or the toolkit issues one form only, opts.critical may only restate that value and is otherwise refused with x509/bad-input; keyUsage, extendedKeyUsage, certificatePolicies, policyMappings, qcStatements and subjectAltName take opts.critical, and basicConstraints carries critical inside its value. subjectKeyIdentifier: true and authorityKeyIdentifier: true, which derive a value from the subject key or the issuer, are refused here and the message names spec.extensions; the authorityKeyIdentifier object form requires the key id bytes. Every registered extension encodes byte-identically through this verb and through spec.extensions. An unregistered OID's extnValue must hold exactly one DER-encoded value (RFC 5280 sec. 4.1), and a dotted string that is not a canonical OID (a first arc above 2, a second arc above 39 under arcs 0 and 1, a leading-zero arc) is refused as x509/bad-input rather than surfacing the OID codec's own error.
14
+
15
+ ### Changed
16
+
17
+ - The pre-encoded array form of extensions on the certificate, CSR, CRL, attribute-certificate and timestamp signers holds an extension no decoder answers for to the same rule: its extnValue must be exactly one DER-encoded value, or the signer refuses it with its own bad-input code. An extension the signer decodes keeps the decoder's typed refusal.
18
+
19
+ ## v0.7.32 — 2026-09-12
20
+
21
+ The certificate and CRL signers issue the RFC 5280 key identifiers without being asked.
22
+
23
+ ### Changed
24
+
25
+ - pki.x509.sign emits a subjectKeyIdentifier derived from the subject key by method (1) unless the extensions object names one, and an authorityKeyIdentifier whose keyIdentifier is the issuer certificate's SKI (or, without one, the issuer key's method (1) value) unless the certificate is self-signed, which RFC 5280 sec. 4.2.1.1 defines by the signature: the subject's own key signs it and the names agree. A spec with no extensions, or with an empty extensions object, therefore issues a v3 certificate carrying those two extensions where it issued a v1 certificate before. subjectKeyIdentifier: false omits the SKI on an end entity (sec. 4.2.1.2 states a SHOULD there) and is refused with x509/bad-input on a CA (a MUST); authorityKeyIdentifier: false is honored on a self-signed certificate (the section's one exception) and refused with x509/bad-input on any other. The pre-encoded array form of extensions is unchanged and emits exactly what it is given, so extensions: [] remains the way to a v1 certificate.
26
+ - The authorityKeyIdentifier object form carries the keyIdentifier whether or not it is named: RFC 5280 sec. 4.2.1.1 requires the field, so { authorityCertIssuer, authorityCertSerialNumber } alone now yields all three fields, and keyIdentifier: false is honored on a self-signed certificate only. A keyIdentifier stated as bytes under an issuer given as a certificate that carries a subjectKeyIdentifier must equal that SKI (sec. 4.2.1.2) or the call is refused with x509/bad-input; under a name-and-key issuer it is taken as given.
27
+ - pki.crl.sign emits an authorityKeyIdentifier on every CRL unless the extensions object names one, with the same keyIdentifier derivation; RFC 5280 sec. 5.2.1 places it on every CRL a conforming issuer signs with no exception, so authorityKeyIdentifier: false is refused with crl/bad-input, and a keyIdentifier stated as bytes under an issuer certificate that carries a subjectKeyIdentifier must equal it. A CRL spec with no extensions object is v2 with that extension; the pre-encoded array form is unchanged.
28
+
29
+ ### Fixed
30
+
31
+ - Comparing two public keys of different algorithms (an EC key against an Ed25519 or ML-DSA key) no longer leaves a fault queued in the crypto library. node:crypto's KeyObject equality answers false for such a pair but queues an OpenSSL error that made the next private-key import in the process fail with ERR_OSSL_EVP_DIFFERENT_KEY_TYPES. The key-equality helper behind the CMP session's key-rollover checks, the CRMF template check, the CMC challenge-opening check and the certificate signer's self-signed test now decides the different-type case by the key type and never asks the runtime to compare across types.
32
+
7
33
  ## v0.7.31 — 2026-09-12
8
34
 
9
35
  HPKE encrypts to an ML-KEM public key.
package/README.md CHANGED
@@ -231,12 +231,12 @@ 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; 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` |
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; both emitted without being named, the SKI on every certificate and the AKI on every certificate that is not self-signed, which is what RFC 5280 §4.2.1.1 and §4.2.1.2 place on the issuing CA, and `false` declines each only where the RFC allows the omission), 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. `extension(name, value, opts)` encodes one Extension DER from the same plain value form, for the pre-encoded array form on the certificate, CSR, and CRL signers: the criticality follows what the signer emits, `opts.critical` reaches only the extensions whose criticality is the issuer's choice, and an unregistered dotted OID takes its extnValue as bytes. Parsing stays at `pki.schema.x509.parse` — `sign`, `randomSerial`, `extension` |
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, 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 MAC algorithm it does not compute (reported as MAC-protected under that algorithm, never as a failed signature), 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` |
239
- | `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuer alternative name, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access, which is every extension RFC 5280 §5.2 defines) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the issuer 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. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
239
+ | `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuer alternative name, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access, which is every extension RFC 5280 §5.2 defines) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The authority key identifier is emitted on every CRL whether or not it is named, as §5.2.1 places it on every conforming issuer, from the issuer certificate's SKI or the issuer key. The signature algorithm is resolved from the issuer 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. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
240
240
  | `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
241
241
  | `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
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` |
@@ -307,7 +307,7 @@ function _buildExtensions(extSpec, aaSpki) {
307
307
  var seenA = intrinsic.create(null);
308
308
  var exts = extSpec.map(function (e, i) {
309
309
  var der = _b.reqDer(e, "extension");
310
- _b.assertValidExtension(der, i);
310
+ _b.assertValidExtension(der, i, EXT_DECODERS);
311
311
  var n = asn1.decode(der);
312
312
  var extnId = asn1.read.oid(n.children[0]);
313
313
  if (seenA[extnId]) throw _err("attrcert/bad-input", "duplicate extension " + extnId + " (RFC 5755 sec. 4.2.9)");
package/lib/cmc-build.js CHANGED
@@ -533,6 +533,10 @@ function _provesRequestKey(opening, outgoing) {
533
533
  try {
534
534
  requested = _createPublicKey({ key: requestedSpki, format: "der", type: "spki" });
535
535
  } catch (_e) { return false; } // allow:swallow-unverified a key this runtime cannot read proves nothing here
536
+ /** @internal Keys of different types are never the same key, and comparing them through the
537
+ * runtime's equality leaves a fault queued in the crypto library that surfaces on the next
538
+ * unrelated key import in the process, so the type decides that case first. */
539
+ if (requested.asymmetricKeyType !== opening.key.asymmetricKeyType) return false;
536
540
  return intrinsic.keyEquals(requested, opening.key);
537
541
  }
538
542
  /** @internal A key the runtime engine cannot read has no KeyObject to compare, and a composite
package/lib/crl-sign.js CHANGED
@@ -24,7 +24,7 @@ var x509Schema = require("./schema-x509");
24
24
  var signScheme = require("./sign-scheme");
25
25
  var guard = require("./guard-all");
26
26
  var intrinsic = require("./guard-intrinsic");
27
- var _hasOwn = intrinsic.hasOwn;
27
+ var _hasOwn = intrinsic.hasOwn, _bufferEquals = intrinsic.bufferEquals;
28
28
  var frameworkError = require("./framework-error");
29
29
  var pkix = require("./schema-pkix");
30
30
  var schema = require("./schema-engine");
@@ -143,15 +143,24 @@ function _resolveReason(reason, isDelta) {
143
143
  return codeNum;
144
144
  }
145
145
 
146
+ function _issuerSkiOf(ctx) {
147
+ if (!ctx.issuerCert) return null;
148
+ var ski = (ctx.issuerCert.extensions || []).filter(function (e) { return e.oid === OID_SKI; })[0];
149
+ if (ski) { try { return asn1.read.octetString(asn1.decode(ski.value)); } catch (_e) { } } // allow:swallow-unverified -- a malformed issuer SKI is read as absent; the authorityKeyIdentifier keyIdentifier is then derived from the issuer public key
150
+ return null;
151
+ }
146
152
  function _akiKeyId(val, ctx) {
147
- if (guard.bytes.isByteSource(val)) return guard.bytes.snapshotSource(val, CrlError, "crl/bad-input", "the authorityKeyIdentifier keyIdentifier");
148
- if (val === true) {
149
- if (ctx.issuerCert) {
150
- var ski = (ctx.issuerCert.extensions || []).filter(function (e) { return e.oid === OID_SKI; })[0];
151
- if (ski) { try { return asn1.read.octetString(asn1.decode(ski.value)); } catch (_e) { } } // allow:swallow-unverified -- a malformed issuer SKI is read as absent; the authorityKeyIdentifier keyIdentifier is then derived from the issuer public key
153
+ var issuerSki = _issuerSkiOf(ctx);
154
+ if (guard.bytes.isByteSource(val)) {
155
+ var given = guard.bytes.snapshotSource(val, CrlError, "crl/bad-input", "the authorityKeyIdentifier keyIdentifier");
156
+ /** @internal Sec. 5.2.1 names the CRL signer certificate's subject key identifier as the value,
157
+ * so a stated one is held to it when that certificate is at hand. */
158
+ if (issuerSki && !_bufferEquals(given, issuerSki)) {
159
+ throw _err("crl/bad-input", "the authorityKeyIdentifier keyIdentifier must equal the issuer certificate's subjectKeyIdentifier (RFC 5280 sec. 5.2.1); omit it to take that value");
152
160
  }
153
- return _spkiKeyId(ctx.issuerSpki);
161
+ return given;
154
162
  }
163
+ if (val === true) return issuerSki || _spkiKeyId(ctx.issuerSpki);
155
164
  throw _err("crl/bad-input", "authorityKeyIdentifier must be true (auto-derive from the issuer) or a Buffer key id");
156
165
  }
157
166
 
@@ -219,12 +228,12 @@ function _buildCrlExtensions(spec, ctx) {
219
228
  var crlNumberVal = null;
220
229
  if (spec.crlNumber != null) { var cn = _boundedInteger(spec.crlNumber, "cRLNumber"); crlNumberVal = cn.value; push("cRLNumber", false, cn.tlv); }
221
230
  var ext = spec.extensions;
222
- if (ext == null) return { exts: out, isDelta: isDelta };
231
+ if (ext == null) ext = {};
223
232
  if (Array.isArray(ext)) {
224
233
  var arrBase = null, arrCrlNum = null;
225
234
  ext.forEach(function (e, i) {
226
235
  var der = _reqDer(e, "extension");
227
- _assertValidExtension(der, i);
236
+ _assertValidExtension(der, i, EXT_DECODERS);
228
237
  var node = asn1.decode(der);
229
238
  var extnId = asn1.read.oid(node.children[0]);
230
239
  if (seen[extnId]) throw _err("crl/bad-input", "duplicate extension " + extnId + " (RFC 5280 sec. 5.2)");
@@ -258,7 +267,12 @@ function _buildCrlExtensions(spec, ctx) {
258
267
  return "unknown CRL extension " + JSON.stringify(k) + " in the extensions spec; pass a pre-encoded Extension DER via the array form";
259
268
  });
260
269
  isDelta = ext.deltaCRLIndicator != null;
261
- if (ext.authorityKeyIdentifier != null) push("authorityKeyIdentifier", false, _extAki(_akiKeyId(ext.authorityKeyIdentifier, ctx)));
270
+ /** @internal Sec. 5.2.1: a conforming CRL issuer MUST use the key identifier method and MUST
271
+ * include the extension in every CRL, with no exception, so it is emitted unless named and
272
+ * declining it is refused. */
273
+ var akiVal = ext.authorityKeyIdentifier == null ? true : ext.authorityKeyIdentifier;
274
+ if (akiVal === false) throw _err("crl/bad-input", "a conforming CRL issuer MUST include the authorityKeyIdentifier in every CRL it issues, so authorityKeyIdentifier: false is refused (RFC 5280 sec. 5.2.1)");
275
+ push("authorityKeyIdentifier", false, _extAki(_akiKeyId(akiVal, ctx)));
262
276
  /** @internal Sec. 5.2.2 takes the OID and syntax from sec. 4.2.1.7, so this is the certificate's
263
277
  * own GeneralNames encoder, and states a SHOULD for non-critical, which is the form emitted. */
264
278
  if (ext.issuerAltName != null) push("issuerAltName", false, _b.encodeGeneralNames(_b.reqDenseArray(ext.issuerAltName, "issuerAltName")));
@@ -312,7 +326,7 @@ function _buildRevoked(entryList, isDelta) {
312
326
  if (!Array.isArray(e.extensions)) throw _err("crl/bad-input", "revoked entry [" + idx + "] extensions must be an array of pre-encoded Extension DER");
313
327
  e.extensions.forEach(function (x, j) {
314
328
  var der = _reqDer(x, "entry extension");
315
- _assertValidExtension(der, j);
329
+ _assertValidExtension(der, j, EXT_DECODERS);
316
330
  var xnode = asn1.decode(der);
317
331
  var extnId = asn1.read.oid(xnode.children[0]);
318
332
  if (seen[extnId]) throw _err("crl/bad-input", "duplicate entry extension " + extnId + " in revoked entry [" + idx + "]");
@@ -451,7 +465,13 @@ function _sign(spec, issuer, opts) {
451
465
  * signature algorithm is resolved from the signing key, so every algorithm the toolkit signs with (RSA
452
466
  * PKCS#1 v1.5 / PSS, ECDSA, EdDSA, ML-DSA, SLH-DSA, composite) is available without a per-algorithm branch.
453
467
  *
454
- * The version is derived from the field set (v2 when any CRL or entry extension is present, else v1). The
468
+ * The `authorityKeyIdentifier` is emitted whether or not the object form names it, because sec. 5.2.1
469
+ * places it on every CRL a conforming issuer signs: its keyIdentifier is the issuer certificate's
470
+ * subjectKeyIdentifier or, without one, the method (1) value of the issuer key. A stated value is held
471
+ * to the issuer certificate's subjectKeyIdentifier when the issuer is given as a certificate carrying
472
+ * one; `authorityKeyIdentifier: false` is refused. The pre-encoded array form emits exactly what it
473
+ * is given. The version is derived from the field set (v2 when any CRL or entry extension is present,
474
+ * else v1). The
455
475
  * outer `signatureAlgorithm` is emitted from the same source as `tbsCertList.signature` (sec. 5.1.1.2); an
456
476
  * empty revocation list omits `revokedCertificates` instead of emitting an empty SEQUENCE (sec. 5.1.2.6);
457
477
  * `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime (sec. 5.3.1/5.3.2);
package/lib/pki-build.js CHANGED
@@ -1088,12 +1088,15 @@ function makeBuilder(ctx) {
1088
1088
  throw E("bad-input", what + " is not a well-formed SubjectPublicKeyInfo", e);
1089
1089
  }
1090
1090
  }
1091
- function assertValidExtension(der, idx) {
1092
- var n;
1091
+ /** @internal `decoders`, when given, names the extensions the caller decodes itself after this
1092
+ * check, so a malformed value there keeps the decoder's own code; every other extnValue is held
1093
+ * here to being one DER value. */
1094
+ function assertValidExtension(der, idx, decoders) {
1095
+ var n, extnId;
1093
1096
  try { n = asn1.decode(der); }
1094
1097
  catch (e) { throw E("bad-input", "pre-encoded extension [" + idx + "] is not valid DER", e); }
1095
1098
  if (n.tagNumber !== asn1.TAGS.SEQUENCE || n.tagClass !== "universal" || !n.children || n.children.length < 2 || n.children.length > 3) throw E("bad-input", "pre-encoded extension [" + idx + "] must be an Extension SEQUENCE { extnID, critical?, extnValue }");
1096
- try { asn1.read.oid(n.children[0]); }
1099
+ try { extnId = asn1.read.oid(n.children[0]); }
1097
1100
  catch (e) { throw E("bad-input", "pre-encoded extension [" + idx + "] extnID is not an OBJECT IDENTIFIER", e); }
1098
1101
  if (n.children.length === 3) {
1099
1102
  var crit;
@@ -1103,6 +1106,13 @@ function makeBuilder(ctx) {
1103
1106
  }
1104
1107
  var last = n.children[n.children.length - 1];
1105
1108
  if (last.tagNumber !== asn1.TAGS.OCTET_STRING || last.tagClass !== "universal") throw E("bad-input", "pre-encoded extension [" + idx + "] extnValue must be an OCTET STRING");
1109
+ if (!(decoders && intrinsic.hasOwn(decoders, extnId))) assertExtnValueIsDer(last.content, "pre-encoded extension [" + idx + "]");
1110
+ }
1111
+ /** @internal RFC 5280 sec. 4.1: extnValue holds the DER encoding of one ASN.1 value, so the octets
1112
+ * must decode as exactly one TLV, which the strict codec's trailing-byte refusal also enforces. */
1113
+ function assertExtnValueIsDer(content, label) {
1114
+ try { asn1.decode(content); }
1115
+ catch (e) { throw E("bad-input", label + " extnValue must hold exactly one DER-encoded value (RFC 5280 sec. 4.1)", e); }
1106
1116
  }
1107
1117
  /** @internal Applies the certificate profile's fixed-criticality table. The CRL, CRL-entry and
1108
1118
  * attribute-certificate profiles set their own criticality in their own signers. */
@@ -1136,7 +1146,7 @@ function makeBuilder(ctx) {
1136
1146
  var seen = intrinsic.create(null);
1137
1147
  return b.sequence(extSpec.map(function (e, i) {
1138
1148
  var der = reqDer(e, "extension");
1139
- assertValidExtension(der, i);
1149
+ assertValidExtension(der, i, EXT_DECODERS);
1140
1150
  var n = asn1.decode(der);
1141
1151
  var extnId = asn1.read.oid(n.children[0]);
1142
1152
  if (seen[extnId]) throw E("bad-input", "duplicate requested extension " + extnId + " (RFC 5280 sec. 4.2)");
@@ -1236,6 +1246,10 @@ function makeBuilder(ctx) {
1236
1246
  ka = nodeCrypto.createPublicKey({ key: a, format: "der", type: "spki" });
1237
1247
  kb = nodeCrypto.createPublicKey({ key: bb, format: "der", type: "spki" });
1238
1248
  } catch (_e) { return false; }
1249
+ /** @internal Two keys of different types are never the same key, and comparing them through
1250
+ * the runtime's equality leaves a fault queued in the crypto library that surfaces on the
1251
+ * next unrelated key import in the process, so the type decides that case first. */
1252
+ if (ka.asymmetricKeyType !== kb.asymmetricKeyType) return false;
1239
1253
  return _keyEquals(ka, kb) === true;
1240
1254
  }
1241
1255
 
@@ -1256,6 +1270,7 @@ function makeBuilder(ctx) {
1256
1270
  extMsPreviousCertHash: extMsPreviousCertHash, extMsEnrollCertType: extMsEnrollCertType,
1257
1271
  spkiKeyId: spkiKeyId, skiKeyId: skiKeyId,
1258
1272
  reqDer: reqDer, reqDenseArray: reqDenseArray, reqDerSequence: reqDerSequence, assertValidSpki: assertValidSpki, assertValidExtension: assertValidExtension,
1273
+ assertExtnValueIsDer: assertExtnValueIsDer,
1259
1274
  assertCertCriticality: assertCertCriticality,
1260
1275
  certLikeFromSpki: certLikeFromSpki, assertSignatureVerifies: assertSignatureVerifies,
1261
1276
  samePublicKey: samePublicKey,
package/lib/x509-sign.js CHANGED
@@ -22,7 +22,7 @@ var x509 = require("./schema-x509");
22
22
  var signScheme = require("./sign-scheme");
23
23
  var guard = require("./guard-all");
24
24
  var intrinsic = require("./guard-intrinsic");
25
- var _isArray = intrinsic.isArray;
25
+ var _isArray = intrinsic.isArray, _bufferEquals = intrinsic.bufferEquals;
26
26
  var frameworkError = require("./framework-error");
27
27
  var schema = require("./schema-engine");
28
28
  var pkix = require("./schema-pkix");
@@ -83,11 +83,17 @@ function _skiValueOf(caCert) {
83
83
  return null;
84
84
  }
85
85
  function _akiKeyId(val, ctx) {
86
- if (guard.bytes.isByteSource(val)) return guard.bytes.snapshotSource(val, CertificateError, "x509/bad-input", "the authorityKeyIdentifier keyIdentifier");
87
- if (val === true) {
88
- if (ctx.issuerCert) { var ski = _skiValueOf(ctx.issuerCert); if (ski) return ski; }
89
- return _spkiKeyId(ctx.issuerSpki);
86
+ var issuerSki = ctx.issuerCert ? _skiValueOf(ctx.issuerCert) : null;
87
+ if (guard.bytes.isByteSource(val)) {
88
+ var given = guard.bytes.snapshotSource(val, CertificateError, "x509/bad-input", "the authorityKeyIdentifier keyIdentifier");
89
+ /** @internal Sec. 4.2.1.2: the issuer certificate's subjectKeyIdentifier MUST be the value
90
+ * placed in the authorityKeyIdentifier of what it issues, so a stated value is held to it. */
91
+ if (issuerSki && !_bufferEquals(given, issuerSki)) {
92
+ throw _err("x509/bad-input", "the authorityKeyIdentifier keyIdentifier must equal the issuer certificate's subjectKeyIdentifier (RFC 5280 sec. 4.2.1.2); omit it to take that value");
93
+ }
94
+ return given;
90
95
  }
96
+ if (val === true) return issuerSki || _spkiKeyId(ctx.issuerSpki);
91
97
  throw _err("x509/bad-input", "authorityKeyIdentifier must be true (auto-derive from the issuer) or a Buffer key id");
92
98
  }
93
99
 
@@ -114,18 +120,27 @@ function _akiFields(val, ctx) {
114
120
  if (issuerName === true) issuerName = [{ directoryName: ctx.issuerCert.issuer.bytes }];
115
121
  if (serial === true) serial = "0x" + ctx.issuerCert.serialNumberHex;
116
122
  }
117
- return [val.keyIdentifier == null ? null : _akiKeyId(val.keyIdentifier, ctx),
118
- issuerName == null ? null : issuerName, serial == null ? null : serial];
123
+ /** @internal Sec. 4.2.1.1: the keyIdentifier field MUST be included in every certificate a
124
+ * conforming CA generates, self-signed ones excepted, so the object form carries it unless
125
+ * declined, and declining it is refused where the section allows no omission. */
126
+ var keyId = val.keyIdentifier == null ? true : val.keyIdentifier;
127
+ if (keyId === false) {
128
+ if (!ctx.selfSigned) throw _err("x509/bad-input", "the authorityKeyIdentifier keyIdentifier MUST be included in every certificate a CA generates other than a self-signed one, so keyIdentifier: false is refused here (RFC 5280 sec. 4.2.1.1)");
129
+ keyId = null;
130
+ } else {
131
+ keyId = _akiKeyId(keyId, ctx);
132
+ }
133
+ return [keyId, issuerName == null ? null : issuerName, serial == null ? null : serial];
119
134
  }
120
135
 
121
136
  function _buildExtensions(extSpec, ctx) {
122
- if (extSpec == null) return [];
137
+ if (extSpec == null) extSpec = {};
123
138
  if (_isArray(extSpec)) {
124
139
  var seenExt = intrinsic.create(null), arrCa = false, arrKeyCertSign = false, arrPathLen = false, arrNameConstraints = false;
125
140
  var oidBc = O("basicConstraints"), oidKu = O("keyUsage"), oidNc = O("nameConstraints");
126
141
  var arr = extSpec.map(function (e, i) {
127
142
  var der = _reqDer(e, "extension");
128
- _assertValidExtension(der, i);
143
+ _assertValidExtension(der, i, EXT_DECODERS);
129
144
  var n = asn1.decode(der);
130
145
  var extnId = asn1.read.oid(n.children[0]);
131
146
  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)");
@@ -171,9 +186,21 @@ function _buildExtensions(extSpec, ctx) {
171
186
  }
172
187
 
173
188
  var out = [];
174
- if (extSpec.subjectKeyIdentifier != null) out.push(_ext(O("subjectKeyIdentifier"), false, _extSki(_skiKeyId(extSpec.subjectKeyIdentifier, ctx.spki))));
175
- if (extSpec.authorityKeyIdentifier != null) {
176
- var akiF = _akiFields(extSpec.authorityKeyIdentifier, ctx);
189
+ /** @internal Sec. 4.2.1.2: the SKI MUST appear in every CA certificate and SHOULD in every end
190
+ * entity, so it is emitted unless declined, and declining is refused on a CA. Sec. 4.2.1.1: the
191
+ * AKI keyIdentifier MUST be included in every certificate a conforming CA generates, the one
192
+ * exception being a self-signed certificate, so the same shape applies with that exception. */
193
+ var skiVal = extSpec.subjectKeyIdentifier == null ? true : extSpec.subjectKeyIdentifier;
194
+ if (skiVal === false) {
195
+ if (caTrue) throw _err("x509/bad-input", "a CA certificate MUST carry a subjectKeyIdentifier, so subjectKeyIdentifier: false is refused when basicConstraints cA is TRUE (RFC 5280 sec. 4.2.1.2)");
196
+ } else {
197
+ out.push(_ext(O("subjectKeyIdentifier"), false, _extSki(_skiKeyId(skiVal, ctx.spki))));
198
+ }
199
+ var akiVal = extSpec.authorityKeyIdentifier == null ? !ctx.selfSigned : extSpec.authorityKeyIdentifier;
200
+ if (akiVal === false) {
201
+ if (!ctx.selfSigned) throw _err("x509/bad-input", "the authorityKeyIdentifier keyIdentifier MUST be included in every certificate a CA generates other than a self-signed one, so authorityKeyIdentifier: false is refused here (RFC 5280 sec. 4.2.1.1)");
202
+ } else {
203
+ var akiF = _akiFields(akiVal, ctx);
177
204
  out.push(_ext(O("authorityKeyIdentifier"), false, _extAki(akiF[0], akiF[1], akiF[2])));
178
205
  }
179
206
  if (ku != null) out.push(_ext(O("keyUsage"), extSpec.keyUsageCritical !== false, _extKeyUsage(ku)));
@@ -339,7 +366,15 @@ function _hasCriticalSan(extSpec) {
339
366
  * or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, or a composite arm, so every algorithm the
340
367
  * toolkit signs with is available here without a per-algorithm branch.
341
368
  *
342
- * The version is derived from the field set (v3 when extensions are present, else v1). Serial bounds
369
+ * The version is derived from the field set (v3 when extensions are present, else v1). Two
370
+ * extensions are emitted without being named, because RFC 5280 places them on the issuing CA: a
371
+ * `subjectKeyIdentifier` derived from the subject key by method (1), and, unless the certificate is
372
+ * self-signed (the subject's own key signs it and the names agree), an `authorityKeyIdentifier`
373
+ * whose keyIdentifier is the issuer certificate's SKI or, without one, the issuer key's method (1)
374
+ * value. `subjectKeyIdentifier: false` omits the first on an end entity (sec. 4.2.1.2 states a
375
+ * SHOULD there) and is refused on a CA (a MUST); `authorityKeyIdentifier: false` is honored on a
376
+ * self-signed certificate (sec. 4.2.1.1 allows the omission there) and refused on any other. The
377
+ * pre-encoded array form of `extensions` emits exactly what it is given. Serial bounds
343
378
  * (positive, <= 20 octets), the validity UTCTime/GeneralizedTime cutover, the DER DEFAULT omissions
344
379
  * (v1 tag, `critical=FALSE`, `cA=FALSE`), and the CA cross-field rules (keyCertSign and
345
380
  * pathLenConstraint require cA=TRUE) are all enforced; a violation throws a typed `CertificateError`.
@@ -394,7 +429,10 @@ function _hasCriticalSan(extSpec) {
394
429
  * naming the issuing certificate directly (RFC 5280 sec. 4.2.1.1). The issuer name and the serial are
395
430
  * both present or both absent, which is the rule the reader applies. Each of the two also takes
396
431
  * `true`, which reads it from the issuing certificate, so the pair identifies the certificate that
397
- * actually signed this one; `true` requires an issuer given as a certificate.
432
+ * actually signed this one; `true` requires an issuer given as a certificate. The object form
433
+ * carries the `keyIdentifier` whether or not it is named (`keyIdentifier: false` omits it on a
434
+ * self-signed certificate only), and a stated key id is held to the issuer certificate's
435
+ * subjectKeyIdentifier when the issuer is given as a certificate carrying one (sec. 4.2.1.2).
398
436
  *
399
437
  * `extensions.qcStatements` builds the RFC 3739 sec. 3.2.6 qualified-certificate statements, as a
400
438
  * list of `{ statementId, info? }`. A statement the toolkit knows encodes its own value syntax:
@@ -510,17 +548,22 @@ function _sign(spec, issuer, opts) {
510
548
  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
549
  var validityDer = b.sequence([_timeDer(spec.notBefore, "notBefore"), _timeDer(spec.notAfter, "notAfter")]);
512
550
 
551
+ /** @internal Sec. 4.2.1.1 defines the self-signed exception by the signature: it is generated
552
+ * with the private key of the certificate's own subject public key. The bare `{ key }` issuer
553
+ * form is that by construction; an explicit issuer is measured, key and name both, and the key
554
+ * is compared as a key rather than as an encoding, since one EC key has two point encodings. */
555
+ var selfIssued = guard.name.dnEqual(
556
+ schema.walk(NAME_SCHEMA, asn1.decode(subjectDer), NS).result.rdns,
557
+ schema.walk(NAME_SCHEMA, asn1.decode(issuerDer), NS).result.rdns,
558
+ _err, "x509/bad-input", "issuer/subject DN");
559
+ var selfSignedCert = selfIssued && _b.samePublicKey(issuerSpki, spki);
513
560
  var extSpec = spec.extensions;
514
- var exts = _buildExtensions(extSpec, { spki: spki, issuerSpki: issuerSpki, issuerCert: issuerCert, subjectEmpty: subjectEmpty });
561
+ var exts = _buildExtensions(extSpec, { spki: spki, issuerSpki: issuerSpki, issuerCert: issuerCert, subjectEmpty: subjectEmpty, selfSigned: selfSignedCert });
515
562
  if (subjectEmpty && !_hasCriticalSan(extSpec)) {
516
563
  throw _err("x509/bad-input", "an empty subject requires a critical subjectAltName (RFC 5280 sec. 4.1.2.6)");
517
564
  }
518
565
  if (issuerPathLen != null) {
519
566
  var issued = _issuedCaInfo(extSpec);
520
- var selfIssued = guard.name.dnEqual(
521
- schema.walk(NAME_SCHEMA, asn1.decode(subjectDer), NS).result.rdns,
522
- schema.walk(NAME_SCHEMA, asn1.decode(issuerDer), NS).result.rdns,
523
- _err, "x509/bad-input", "issuer/subject DN");
524
567
  if (issued.cA && !selfIssued) {
525
568
  if (issuerPathLen < 1) throw _err("x509/bad-input", "the issuer certificate pathLenConstraint (0) forbids issuing a non-self-issued CA certificate below it (RFC 5280 sec. 4.2.1.9)");
526
569
  if (issued.pathLen != null && issued.pathLen > issuerPathLen - 1) throw _err("x509/bad-input", "the issued CA certificate pathLenConstraint exceeds the issuer's remaining path length (RFC 5280 sec. 4.2.1.9)");
@@ -579,4 +622,164 @@ function _sign(spec, issuer, opts) {
579
622
  */
580
623
  function randomSerial() { return pkiBuild.randomSerial(); }
581
624
 
582
- module.exports = { sign: sign, randomSerial: randomSerial };
625
+ /** @internal One row per extension the object form of `spec.extensions` encodes, for the standalone
626
+ * encoder: the registry OID name, the value encoder, and how the criticality is decided. `fixed`
627
+ * is the value the RFC or the toolkit's posture emits, refused if a knob disagrees; `knob` marks
628
+ * the extensions whose criticality is the issuer's choice (or, for subjectAltName, follows a
629
+ * subject this encoder does not hold); `flag` marks a NULL-valued marker given as `true`. The two
630
+ * key identifiers take only their explicit forms here: deriving one needs the subject key or the
631
+ * issuer, which live in the assembled spec. */
632
+ function _flagValue(name, v) {
633
+ if (v !== true) throw _err("x509/bad-input", name + " is a flag, so it is true or omitted");
634
+ return asn1.build.nullValue();
635
+ }
636
+ function _standaloneSki(v) {
637
+ if (v === true) throw _err("x509/bad-input", "subjectKeyIdentifier: true derives the key id from the subject key, which this encoder does not hold; pass the key id bytes, or name it in spec.extensions");
638
+ return _extSki(_skiKeyId(v, null));
639
+ }
640
+ function _standaloneAki(v) {
641
+ if (v === true) throw _err("x509/bad-input", "authorityKeyIdentifier: true derives the key id from the issuer, which this encoder does not hold; pass { keyIdentifier } bytes, or name it in spec.extensions");
642
+ if (guard.bytes.isByteSource(v)) return _extAki(_akiKeyId(v, {}), null, null);
643
+ if (typeof v !== "object" || _isArray(v) || v === null) throw _err("x509/bad-input", "authorityKeyIdentifier must be a Buffer key id or an object { keyIdentifier, authorityCertIssuer, authorityCertSerialNumber }");
644
+ if (!guard.bytes.isByteSource(v.keyIdentifier)) {
645
+ throw _err("x509/bad-input", "authorityKeyIdentifier keyIdentifier must be the key id bytes here (RFC 5280 sec. 4.2.1.1 requires the field, and deriving it needs the issuer); name it in spec.extensions to derive it");
646
+ }
647
+ var f = _akiFields(v, { selfSigned: false });
648
+ return _extAki(f[0], f[1], f[2]);
649
+ }
650
+ var EXTENSION_ROWS = [
651
+ ["subjectKeyIdentifier", "subjectKeyIdentifier", { fixed: false, cite: "RFC 5280 sec. 4.2.1.2" }, _standaloneSki],
652
+ ["authorityKeyIdentifier", "authorityKeyIdentifier", { fixed: false, cite: "RFC 5280 sec. 4.2.1.1" }, _standaloneAki],
653
+ ["keyUsage", "keyUsage", { knob: true, dflt: true }, function (v) { return _extKeyUsage(v); }],
654
+ ["extendedKeyUsage", "extKeyUsage", { knob: true, dflt: false }, function (v) { return _extExtKeyUsage(v); }],
655
+ ["basicConstraints", "basicConstraints", { inValue: true }, function (v) {
656
+ _validateBcSpec(v);
657
+ if (v.cA === true && v.critical === false) throw _err("x509/bad-input", "a CA certificate's basicConstraints MUST be critical (RFC 5280 sec. 4.2.1.9)");
658
+ if (v.pathLen != null && v.cA !== true) throw _err("x509/bad-input", "basicConstraints pathLenConstraint requires cA=TRUE (RFC 5280 sec. 4.2.1.9)");
659
+ return _extBasicConstraints(v);
660
+ }],
661
+ ["subjectAltName", "subjectAltName", { knob: true, dflt: false }, function (v) { return _extSan(v); }],
662
+ ["issuerAltName", "issuerAltName", { fixed: false, cite: "RFC 5280 sec. 4.2.1.7" }, function (v) { return _encodeGeneralNames(_reqDenseArray(v, "issuerAltName")); }],
663
+ ["certificatePolicies", "certificatePolicies", { knob: true, dflt: false }, function (v) { return _extCertPolicies(v); }],
664
+ ["nameConstraints", "nameConstraints", { fixed: true, cite: "RFC 5280 sec. 4.2.1.10" }, function (v) { return _extNameConstraints(v); }],
665
+ ["policyConstraints", "policyConstraints", { fixed: true, cite: "RFC 5280 sec. 4.2.1.11" }, function (v) { return _extPolicyConstraints(v); }],
666
+ ["inhibitAnyPolicy", "inhibitAnyPolicy", { fixed: true, cite: "RFC 5280 sec. 4.2.1.14" }, function (v) { return _extInhibitAnyPolicy(v); }],
667
+ ["policyMappings", "policyMappings", { knob: true, dflt: false }, function (v) { return _extPolicyMappings(v); }],
668
+ ["authorityInfoAccess", "authorityInfoAccess", { fixed: false, cite: "RFC 5280 sec. 4.2.2.1" }, function (v) { return _extAia(v); }],
669
+ ["subjectInfoAccess", "subjectInfoAccess", { fixed: false, cite: "RFC 5280 sec. 4.2.2.2" }, function (v) { return _b.extSubjectInfoAccess(v); }],
670
+ ["cRLDistributionPoints", "cRLDistributionPoints", { fixed: false, cite: "RFC 5280 sec. 4.2.1.13" }, function (v) { return _extCrlDp(v, "cRLDistributionPoints"); }],
671
+ ["freshestCRL", "freshestCRL", { fixed: false, cite: "RFC 5280 sec. 4.2.1.15" }, function (v) { return _extCrlDp(v, "freshestCRL"); }],
672
+ ["qcStatements", "qcStatements", { knob: true, dflt: false }, function (v) { return _extQcStatements(v); }],
673
+ ["subjectDirectoryAttributes", "subjectDirectoryAttributes", { fixed: false, cite: "RFC 5280 sec. 4.2.1.8" }, function (v) { return _b.extSubjectDirectoryAttributes(v); }],
674
+ ["msCertificateTemplate", "msCertificateTemplate", { fixed: false, cite: "the toolkit issues the form its readers accept" }, function (v) { return _b.extMsCertificateTemplate(v); }],
675
+ ["msEnrollCertType", "msEnrollCertType", { fixed: false, cite: "the toolkit issues the form its readers accept" }, function (v) { return _b.extMsEnrollCertType(v); }],
676
+ ["msCaVersion", "msCaVersion", { fixed: false, cite: "the toolkit issues the form its readers accept" }, function (v) { return _b.extMsCaVersion(v); }],
677
+ ["msPreviousCertHash", "msPreviousCertHash", { fixed: false, cite: "the toolkit issues the form its readers accept" }, function (v) { return _b.extMsPreviousCertHash(v); }],
678
+ ["msApplicationPolicies", "msApplicationPolicies", { fixed: false, cite: "the toolkit issues the form its readers accept" }, function (v) { return _extCertPolicies(v); }],
679
+ ["ocspNoCheck", "ocspNoCheck", { fixed: false, cite: "RFC 6960 sec. 4.2.2.2.1" }, function (v) { return _flagValue("ocspNoCheck", v); }],
680
+ ["precertificatePoison", "precertificatePoison", { fixed: true, cite: "RFC 6962 sec. 3.1" }, function (v) { return _flagValue("precertificatePoison", v); }],
681
+ ["signedCertificateTimestampList", "signedCertificateTimestampList", { fixed: false, cite: "RFC 6962 sec. 3.3" }, function (v) { return _encodeSctList(v); }],
682
+ ];
683
+ var EXTENSION_BY_NAME = intrinsic.create(null), EXTENSION_BY_OID = intrinsic.create(null);
684
+ intrinsic.forEach(EXTENSION_ROWS, function (r) {
685
+ var row = { name: r[0], oid: O(r[1]), rule: r[2], encode: r[3] };
686
+ EXTENSION_BY_NAME[r[0]] = row;
687
+ EXTENSION_BY_OID[row.oid] = row;
688
+ });
689
+ var KNOWN_EXTENSION_OPTS = intrinsic.assign(intrinsic.create(null), { critical: 1 });
690
+
691
+ function _extensionRow(name) {
692
+ if (typeof name !== "string") throw _err("x509/bad-input", "the extension name must be a registered extension name or a dotted OID string, got " + guard.text.showValue(name));
693
+ if (intrinsic.hasOwn(EXTENSION_BY_NAME, name)) return EXTENSION_BY_NAME[name];
694
+ if (oid.isDottedDecimal(name)) return intrinsic.hasOwn(EXTENSION_BY_OID, name) ? EXTENSION_BY_OID[name] : null;
695
+ throw _err("x509/bad-input", "unknown extension " + guard.text.showValue(name) + "; the names spec.extensions takes are accepted, and any other extension is named by its dotted OID with its extnValue pre-encoded");
696
+ }
697
+ function _extensionCritical(row, opts) {
698
+ var rule = row.rule, stated = opts.critical;
699
+ if (rule.inValue) {
700
+ if (stated !== undefined) throw _err("x509/bad-input", row.name + " carries its criticality in the value ({ cA, pathLen, critical }), so opts.critical does not apply");
701
+ return null;
702
+ }
703
+ if (rule.knob) return stated === undefined ? rule.dflt : stated;
704
+ if (stated !== undefined && stated !== rule.fixed) {
705
+ throw _err("x509/bad-input", row.name + " is emitted " + (rule.fixed ? "critical" : "non-critical") + " (" + rule.cite + "), so opts.critical cannot say otherwise");
706
+ }
707
+ return rule.fixed;
708
+ }
709
+
710
+ /**
711
+ * @primitive pki.x509.extension
712
+ * @signature pki.x509.extension(name, value, opts?) -> Buffer
713
+ * @since 0.7.33
714
+ * @status stable
715
+ * @spec RFC 5280 sec. 4.2
716
+ * @related pki.x509.sign, pki.csr.sign, pki.crl.sign
717
+ *
718
+ * Encode one X.509 `Extension` as DER, ready for the pre-encoded array form of `extensions` on
719
+ * `pki.x509.sign`, `pki.csr.sign`, or `pki.crl.sign`. `name` is one of the extension names
720
+ * `spec.extensions` takes, or a dotted OID string. For a name (or the dotted OID of one), `value`
721
+ * is the same plain form `spec.extensions` takes for it: the key-usage and purpose name lists, the
722
+ * `{ cA, pathLen, critical }` object, the GeneralName lists, the policy, constraint, access, and
723
+ * distribution-point objects, the statement and template objects, `true` for the NULL-valued
724
+ * markers, and for the two key identifiers their explicit forms (the key id bytes for
725
+ * `subjectKeyIdentifier`; bytes or `{ keyIdentifier, authorityCertIssuer, authorityCertSerialNumber }`
726
+ * with the key id present for `authorityKeyIdentifier`). The forms that derive a value from the
727
+ * subject key or the issuer (`true`) are refused here, since only the assembled spec holds those.
728
+ * For any other dotted OID, `value` is a `BufferSource` holding the already-encoded `extnValue`.
729
+ *
730
+ * The criticality follows what the signer emits for the object form. Where RFC 5280 fixes it
731
+ * (the key identifiers, the constraint and policy-constraint extensions, the access and
732
+ * distribution extensions), or the toolkit issues one form only, `opts.critical` may only restate
733
+ * that value. `keyUsage` (default critical), `extendedKeyUsage`, `certificatePolicies`,
734
+ * `policyMappings`, `qcStatements` (default non-critical), and `subjectAltName` (critical exactly
735
+ * when the subject is empty, which the caller knows) take `opts.critical`; `basicConstraints`
736
+ * carries `critical` inside its value. An unregistered OID takes `opts.critical` as stated.
737
+ *
738
+ * @opts
739
+ * - `critical` (boolean) -- the criticality, where the extension admits a choice.
740
+ *
741
+ * @example
742
+ * var ku = pki.x509.extension("keyUsage", ["digitalSignature"]);
743
+ * var san = pki.x509.extension("subjectAltName", ["leaf.example"]);
744
+ * var custom = pki.x509.extension("1.3.6.1.4.1.99999.7", pki.asn1.build.utf8("v1"), { critical: false });
745
+ * var pair = await pki.key.generate("Ed25519");
746
+ * var der = await pki.x509.sign(
747
+ * { subject: "leaf.example", subjectPublicKey: await pki.key.export(pair.publicKey),
748
+ * notBefore: new Date("2026-01-01T00:00:00Z"), notAfter: new Date("2027-01-01T00:00:00Z"),
749
+ * extensions: [ku, san, custom] },
750
+ * { key: pair.privateKey });
751
+ * pki.schema.x509.parse(der).extensions.length; // 3
752
+ */
753
+ function extension(name, value, opts) {
754
+ var fixed = guard.bytes.fixArguments(CertificateError, "x509/bad-input", [
755
+ [value, "the extension value"], [opts, "pki.x509.extension options"],
756
+ ]);
757
+ try { return _extension(name, fixed.values[0], fixed.values[1]); }
758
+ finally { fixed.release(); }
759
+ }
760
+ function _extension(name, value, opts) {
761
+ opts = guard.identifier.optionsObject(opts, _err, "x509/bad-input", "pki.x509.extension options");
762
+ guard.identifier.assertKnownKeys(opts, KNOWN_EXTENSION_OPTS, _err, "x509/bad-input", "pki.x509.extension has an unknown option ");
763
+ if (opts.critical !== undefined && typeof opts.critical !== "boolean") throw _err("x509/bad-input", "opts.critical must be a boolean");
764
+ if (value === undefined || value === null) throw _err("x509/bad-input", "the extension value is required");
765
+ var row = _extensionRow(name);
766
+ if (row === null) {
767
+ if (!guard.bytes.isByteSource(value)) throw _err("x509/bad-input", "an extension named by a dotted OID takes its extnValue as pre-encoded bytes");
768
+ var raw = guard.bytes.snapshotSource(value, CertificateError, "x509/bad-input", "the pre-encoded extnValue");
769
+ _b.assertExtnValueIsDer(raw, "the " + name + " extension");
770
+ try { return _ext(name, opts.critical === true, raw); }
771
+ catch (e) {
772
+ if (e instanceof CertificateError) throw e;
773
+ throw _err("x509/bad-input", "the extension name " + guard.text.showValue(name) + " is not a valid OBJECT IDENTIFIER", e);
774
+ }
775
+ }
776
+ if (guard.bytes.isByteSource(value) && !(row.name === "subjectKeyIdentifier" || row.name === "authorityKeyIdentifier" || row.name === "msPreviousCertHash")) {
777
+ throw _err("x509/bad-input", row.name + " takes the plain form spec.extensions takes, not pre-encoded bytes; name the extension by a dotted OID that is not registered to pass raw bytes");
778
+ }
779
+ var critical = _extensionCritical(row, opts);
780
+ var valueDer = row.encode(value);
781
+ if (critical === null) critical = value.critical !== false;
782
+ return _ext(row.oid, critical, valueDer);
783
+ }
784
+
785
+ module.exports = { sign: sign, randomSerial: randomSerial, extension: extension };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.7.31",
3
+ "version": "0.7.33",
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:12c7bd5e-a715-426d-b609-24c3b76f11be",
5
+ "serialNumber": "urn:uuid:878bd8cd-85dc-427a-af01-745a1ae9c732",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-12T07:21:39.704Z",
8
+ "timestamp": "2026-09-12T09:01:17.710Z",
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.31",
22
+ "bom-ref": "@blamejs/pki@0.7.33",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.7.31",
25
+ "version": "0.7.33",
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.31",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.7.33",
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.31",
57
+ "ref": "@blamejs/pki@0.7.33",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]