@blamejs/pki 0.7.30 → 0.7.32

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,37 @@ 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.32 — 2026-09-12
8
+
9
+ The certificate and CRL signers issue the RFC 5280 key identifiers without being asked.
10
+
11
+ ### Changed
12
+
13
+ - 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.
14
+ - 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.
15
+ - 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.
16
+
17
+ ### Fixed
18
+
19
+ - 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.
20
+
21
+ ## v0.7.31 — 2026-09-12
22
+
23
+ HPKE encrypts to an ML-KEM public key.
24
+
25
+ ### Added
26
+
27
+ - pki.hpke.suites.KEM.ML_KEM_512, ML_KEM_768 and ML_KEM_1024 (0x0040, 0x0041, 0x0042). The HPKE binding is FIPS 203 encapsulation and decapsulation with the 32-byte ML-KEM shared secret as the HPKE shared secret and the 64-byte seed as the private key. setupS and seal take the recipient's encapsulation key as raw bytes, as { pkm }, or as a node:crypto KeyObject; setupR and open take { skm } holding the seed, with pkm optional, or a KeyObject. The base and psk modes and every KDF and AEAD apply; the auth and auth-psk modes, which the ML-KEM KEMs do not define (draft-ietf-hpke-pq sec. 7.2), are refused with hpke/auth-unsupported at both ends. An encapsulation key that fails the FIPS 203 sec. 7.2 check (length or a coefficient at or above q) is refused at import, and an encapsulated key of the wrong length is refused before decapsulation, each as hpke/bad-key. The recipient side of the draft's A.1, A.2 and A.3 vectors (ML-KEM-512 and -768 with HKDF-SHA256, ML-KEM-1024 with HKDF-SHA384) is a full known answer: the vector's encapsulated key decapsulated under its seed, all ten decryptions and all five exports. The sender side is proven by round trip: node:crypto takes no encapsulation randomness, so a fixed ephemeral (opts.eph) is refused on an ML-KEM suite with hpke/bad-input rather than ignored.
28
+ - pki.hpke.suites.KDF.HKDF_SHA384 (0x0002), for any KEM. The draft-ietf-hpke-pq A.3 vector proves it in the key schedule. DHKEM(P-384) stays unoffered: no known-answer vector pairs it with an HKDF key schedule.
29
+
30
+ ### Changed
31
+
32
+ - A serialized HPKE private key, { skm, pkm } on setupR, open, opts.eph and opts.senderKey, passes one door for every suite. skm must be a Buffer of exactly the suite's private-key length, an EC scalar additionally in [1, n-1]; the public key is derived from it; and pkm, now optional, must equal that derivation when given. Before this a DHKEM recipient given { skm } alone escaped as a raw TypeError, and a pkm of the wrong length or of another key was fed into the KEM context unchecked, producing a context that could open nothing. A node:crypto KeyObject is checked against the suite's curve or ML-KEM parameter set, and a public KeyObject where a private one is due is refused rather than tried; each refusal is hpke/bad-key naming what was checked.
33
+ - opts.senderKey on setupS and opts.senderPublicKey on setupR are refused with hpke/bad-input in the base and psk modes, where they were previously left unused: a caller who supplied one without mode auth or auth-psk was not authenticating the exchange. A value of undefined or null is still absent. opts.eph is { skm, pkm } or absent (undefined or null); another value, such as 0 or an empty string, is refused with hpke/bad-input instead of being read as absent.
34
+ - pki.hpke.setupS and setupR read each option once, at entry, into a snapshot. mode was read at the default and again at the use, so an option supplied through an accessor could answer auth to the first read and base to the second and get an unauthenticated setup; senderKey was read at its presence check and again at import.
35
+ - The HKDF expand step wipes every block it computed when a later block's HMAC fails, as it already did on the succeeding path. A private KeyObject handed where a public key is due (the recipient key on setupS and seal, senderPublicKey on setupR) now has its public half taken before export, so no JWK carrying the private scalar is produced.
36
+ - The fuzz target for the HPKE recipient path decapsulates under an ML-KEM-768 seed as well as an X25519 key, and selects HKDF-SHA384 among the KDFs.
37
+
7
38
  ## v0.7.30 — 2026-09-12
8
39
 
9
40
  The Sigstore bundle verifier decides with operations bound when the module loads.
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. Parsing stays at `pki.schema.x509.parse` — `sign` |
235
235
  | `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, 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` |
@@ -247,7 +247,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
247
247
  | `pki.merkle` | Merkle-tree proof verification (RFC 6962 / RFC 9162). `leafHash`, `nodeHash`, and `emptyRootHash` build the domain-separated (0x00 leaf, 0x01 node) SHA-256 tree hashes. `verifyInclusion` folds an audit proof back to a root, and `verifyConsistency` reconstructs both the old and new root, which is the append-only guarantee; each is constant-time-compared to a trusted checkpoint root. Fail-closed on bad geometry, sync hashing, transport-free — `leafHash`, `nodeHash`, `emptyRootHash`, `verifyInclusion`, `verifyConsistency` |
248
248
  | `pki.trust` | Mozilla and CCADB trust-store ingestion. `parseCertdata` reads the NSS `certdata.txt` object stream and `parseCcadbCsv` the CCADB CSV export, both into one constraint-carrying anchor shape: the per-purpose trust bits, where only `CKT_NSS_TRUSTED_DELEGATOR` grants, and the per-purpose distrust-after dates the bare root list omits. Certificate and trust objects pair by byte-exact issuer and serial rather than adjacency and are cross-checked against the parsed DER, so metadata cannot attach to the wrong root. `anchor()` hands an entry to `pki.path.validate({ trustAnchors, checkPurpose })`, and `anchor(entry, { nameConstraints })` attaches the namespace a root program trusts a root for when that is narrower than the root certificate states, a `{ permitted, excluded }` pair of `{ tag, base }` subtrees that `validate` seeds as the RFC 5280 §6.1.1(h)(i) initial value, intersecting with each certificate's own constraints. Offline, fail-closed, bounded — `parseCertdata`, `parseCcadbCsv`, `anchor` |
249
249
  | `pki.shbs` | Stateful hash-based signature verification: HSS/LMS (RFC 8554), carried in X.509 by RFC 9802 and in CMS by RFC 9708, profiled by NIST SP 800-208 for CNSA 2.0 firmware signing. `verify` checks an HSS signature, where every level must pass, and `verifyLms` a single-tree LMS, over the raw public-key and signature blobs the parsers already surface. Pure public-input SHA-256 and SHAKE256 hashing, a data-driven typecode registry, and bounds-before-slice reads; a malformed blob throws a typed `ShbsError` while a well-formed but wrong signature returns `false`. Verification only by design, since stateful signing needs atomic one-time-key state that belongs in an HSM. `pki.path.validate` verifies an HSS-signed certificate on its own, so a chain reaching one needs no separate call: the signature covers the whole tbsCertificate rather than a digest of it (RFC 9802 §7.1), and a CertificateList naming the algorithm takes the same route. It is proven against the self-signed certificate RFC 9802 Appendix A publishes — `verify`, `verifyLms` |
250
- | `pki.hpke` | Hybrid Public Key Encryption (RFC 9180), the encrypt-to-a-public-key primitive behind TLS ECH, MLS, and OHTTP. `setupS` and `setupR` establish a sender or recipient context (KEM encapsulation plus the HKDF key schedule); the context's `seal` and `open` AEAD-encrypt with a sequence-counter nonce, and `export` derives further secrets; the module-level `seal` and `open` are single-shot wrappers. DHKEM (P-256, P-521, X25519, X448) by HKDF-SHA256/SHA512 by AES-GCM / ChaCha20Poly1305 / export-only, across all four modes, proven against the RFC 9180 Appendix A vectors. DHKEM(P-384) and HKDF-SHA384 are RFC-registered but Appendix A ships no vector for them, so they fail closed until an authoritative KAT exists. Pure composition over `node:crypto`; ML-KEM and X-Wing are a registry data-row extension pending stable drafts — `suites`, `setupS`, `setupR`, `seal`, `open` |
250
+ | `pki.hpke` | Hybrid Public Key Encryption (RFC 9180), the encrypt-to-a-public-key primitive behind TLS ECH, MLS, and OHTTP. `setupS` and `setupR` establish a sender or recipient context (KEM encapsulation plus the HKDF key schedule); the context's `seal` and `open` AEAD-encrypt with a sequence-counter nonce, and `export` derives further secrets; the module-level `seal` and `open` are single-shot wrappers. DHKEM (P-256, P-521, X25519, X448) in all four modes, proven against the RFC 9180 Appendix A vectors, and the post-quantum ML-KEM-512/768/1024 KEMs (IANA 0x0040 to 0x0042) in the base and psk modes, proven against the draft-ietf-hpke-pq Appendix A vectors; HKDF-SHA256/SHA384/SHA512 by AES-GCM / ChaCha20Poly1305 / export-only. DHKEM(P-384) has no vector under an HKDF key schedule and fails closed. Pure composition over `node:crypto`; the PQ/T hybrid KEMs are a registry data-row extension once the CFRG combiner draft stabilizes — `suites`, `setupS`, `setupR`, `seal`, `open` |
251
251
  | `pki.kem` | Composite ML-KEM key establishment (draft-ietf-lamps-pq-composite-kem), a post-quantum ML-KEM hybridized with a traditional RSA-OAEP, ECDH, X25519, or X448 so the established secret holds if either component is later broken. `encapsulate` turns a recipient's composite `SubjectPublicKeyInfo` into a 256-bit shared secret and a ciphertext; `decapsulate` recovers the same secret from the ciphertext and the composite PKCS#8 private key. Each component KEM runs independently and the two secrets are mixed through a SHA3-256 combiner that binds the traditional ciphertext, the traditional public key, and a per-algorithm label. The twelve algorithms pair ML-KEM-768 and ML-KEM-1024 with RSA-OAEP 2048/3072/4096, ECDH over P-256/P-384/P-521 and brainpoolP256r1/P384r1, X25519, and X448, each verified against the draft Appendix G known-answer vectors; a malformed key or ciphertext, an unsupported algorithm, or a component decapsulation failure throws a typed `KemError` — `encapsulate`, `decapsulate` |
252
252
  | `pki.sigstore` | Offline verifier for a Sigstore bundle, the artifact `npm publish --provenance` produces and the registry serves. `verifyBundle` composes five fail-closed legs against caller-pinned trust (Fulcio CA roots and Rekor log keys, never trusted from the bundle): the DSSE signature over its PAE preimage under the Fulcio leaf key, the ephemeral Fulcio certificate chain validated as of the Rekor log time, the RFC 9162 inclusion proof folded to a Rekor-signed tree root, the log entry bound to this exact signature, and the in-toto SLSA subject digest the caller confirms against the published artifact. It reuses the X.509 parser, the RFC 5280 path validator, and the Merkle verifier; the net-new codecs are the DSSE PAE byte-builder and a fail-closed JSON reader. `verified: true` says the artifact was signed and logged, not that a party you trust signed it — Fulcio issues to anyone who completes an OIDC flow, so who signed is decided only by `opts.identity`, and `identityChecked` reports which of its fields were compared. An identity policy naming no field, or a field name that is not one of the three, is refused rather than satisfied — either would accept every signer while reading as a policy in force. A sixth leg is opt-in: pinning the certificate-transparency logs in `opts.ctLogs` checks the receipt Fulcio embeds in the certificate it issues (RFC 6962 §3.2), verified over the certificate as it stood before the receipt was added and under the key of the log that issued it, so the verdict says the signing certificate was public when it was issued rather than handed out quietly. At least one receipt must verify against a pinned log, the verdict reports `sctChecked` and `validScts`, and an empty log set is refused rather than read as a policy that checks nothing. Both content arms are read: a DSSE-wrapped in-toto attestation, and a message signature over an artifact's own bytes, which `cosign sign-blob` produces. For that arm `opts.artifact` supplies the bytes, and they are held to the hash the Rekor `hashedrekord` entry records before the signature is checked over them; the `messageDigest` the bundle carries is covered by no signature, so it is compared against the computed digest and never used in its place. `contentType` names the arm and the verdict has one shape for both — `pae`, `parseBundle`, `verifyBundle` |
253
253
  | `pki.inspect` | Human-readable inspection, the pure-JS equivalent of `openssl x509/crl/req/cms -text`. `certificate(pem \| der \| parsed)` renders an OpenSSL-style report: version, serial, signature algorithm, issuer and subject distinguished names, validity, public-key details (curve or modulus size plus the raw point or modulus), every decoded extension with its critical flag, and the signature. `crl`, `csr`, and `cms` render the other formats the same way — a CRL like `openssl crl -text`, a CSR like `openssl req -text`, and a CMS message like `openssl cms -cmsout -print`, with a stable summary for a non-SignedData ContentInfo — and `any(input)` detects the format and routes to the right report. Built over the strict parsers and the two-way OID registry with one set of field renderers, it names extension and algorithm OIDs an OpenSSL build shows only as raw bytes. No OpenSSL dependency, and the format is stable and OpenSSL-familiar rather than pinned to one OpenSSL version. A certificate policy's user notice renders as text, both its explicit text and a notice reference with the notice numbers that identify it, rather than hex, and a malformed part falls back to a hex dump rather than throwing — `certificate`, `crl`, `csr`, `cms`, `any` |
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,7 +228,7 @@ 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) {
@@ -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")));
@@ -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/hpke.js CHANGED
@@ -8,16 +8,18 @@
8
8
  * @fullname HPKE (Hybrid Public Key Encryption, RFC 9180)
9
9
  * @intro Hybrid Public Key Encryption (RFC 9180): the standard construction
10
10
  * behind TLS Encrypted Client Hello, MLS, and OHTTP that turns a recipient KEM
11
- * public key into an encapsulated key plus an AEAD-encrypting context. This is
12
- * the RFC 9180 base construction: the DHKEM suites P-256, P-521, X25519, and
13
- * X448, HKDF-SHA256 / HKDF-SHA512, the three AEADs plus export-only, and all
14
- * four modes (base / psk / auth / auth-psk), each proven against the RFC 9180
15
- * Appendix A known-answer vectors. DHKEM(P-384) and HKDF-SHA384 are RFC-registered
16
- * but Appendix A ships no test vector for them, so they are omitted (a request
17
- * fails closed) until an authoritative KAT is available. Pure composition over
18
- * node:crypto: no ASN.1, no schema engine. Post-quantum KEMs (ML-KEM, X-Wing)
19
- * are a data-row extension the registry is shaped to admit once their
20
- * specifications stabilize.
11
+ * public key into an encapsulated key plus an AEAD-encrypting context. Two KEM
12
+ * families run the RFC 9180 key schedule: the DHKEM suites P-256, P-521, X25519,
13
+ * and X448 in all four modes (base / psk / auth / auth-psk), proven against the
14
+ * RFC 9180 Appendix A known-answer vectors, and the post-quantum ML-KEM-512 /
15
+ * -768 / -1024 KEMs (IANA code points 0x0040 to 0x0042, draft-ietf-hpke-pq) in
16
+ * the base and psk modes, proven against that draft's Appendix A vectors. The
17
+ * KDFs are HKDF-SHA256 / HKDF-SHA384 / HKDF-SHA512; the AEADs are AES-128-GCM,
18
+ * AES-256-GCM, ChaCha20Poly1305, and export-only. DHKEM(P-384) is RFC-registered
19
+ * but no known-answer vector pairs it with an HKDF key schedule, so a request
20
+ * for it fails closed. The PQ/T hybrid KEMs and the SHAKE-based KDFs of the HPKE
21
+ * revision are a data-row extension once their specifications stabilize. Pure
22
+ * composition over node:crypto: no ASN.1, no schema engine.
21
23
  * The RFC 9180 sec. 7 registry code points live in pki.hpke.suites
22
24
  * (KEM / KDF / AEAD / MODE), passed to the setup functions to select a suite.
23
25
  * @spec RFC 9180
@@ -28,7 +30,11 @@ var nodeCrypto = require("crypto");
28
30
  var frameworkError = require("./framework-error");
29
31
  var guard = require("./guard-all");
30
32
  var intrinsic = require("./guard-intrinsic");
33
+ var oid = require("./oid");
31
34
  var _hasOwn = intrinsic.hasOwn;
35
+ var _isBuffer = intrinsic.isBuffer, _bufferFrom = intrinsic.bufferFrom, _bufferAlloc = intrinsic.bufferAlloc;
36
+ var _bufferConcat = intrinsic.bufferConcat, _bufferEquals = intrinsic.bufferEquals, _compare = intrinsic.compare;
37
+ var _subarray = intrinsic.subarray;
32
38
 
33
39
  var HpkeError = frameworkError.HpkeError;
34
40
  function _err(code, message, cause) { return new HpkeError(code, message, cause); }
@@ -49,6 +55,7 @@ function L(s) { return Buffer.from(s, "ascii"); }
49
55
 
50
56
  var KDFS = intrinsic.assign(intrinsic.create(null), {
51
57
  0x0001: { hash: "sha256", Nh: 32 },
58
+ 0x0002: { hash: "sha384", Nh: 48 },
52
59
  0x0003: { hash: "sha512", Nh: 64 },
53
60
  });
54
61
  var AEADS = intrinsic.assign(intrinsic.create(null), {
@@ -57,11 +64,18 @@ var AEADS = intrinsic.assign(intrinsic.create(null), {
57
64
  0x0003: { cipher: "chacha20-poly1305", Nk: 32, Nn: 12, Nt: 16 },
58
65
  0xFFFF: { exportOnly: true, Nn: 12 },
59
66
  });
67
+ function _mlKemRow(name, oidName, node) {
68
+ var p = oid.kemParams(oidName);
69
+ return { kind: "mlkem", name: name, node: node, Nsecret: p.ss, Npub: p.ek, Nenc: p.ct, Nsk: 64 };
70
+ }
60
71
  var KEMS = intrinsic.assign(intrinsic.create(null), {
61
- 0x0010: { kind: "ec", curve: "P-256", nodeCurve: "prime256v1", kdf: 0x0001, Nsecret: 32, Npub: 65 },
62
- 0x0012: { kind: "ec", curve: "P-521", nodeCurve: "secp521r1", kdf: 0x0003, Nsecret: 64, Npub: 133 },
63
- 0x0020: { kind: "okp", curve: "X25519", oid: "2b656e", kdf: 0x0001, Nsecret: 32, Npub: 32 },
64
- 0x0021: { kind: "okp", curve: "X448", oid: "2b656f", kdf: 0x0003, Nsecret: 64, Npub: 56 },
72
+ 0x0010: { kind: "ec", name: "P-256", curve: "P-256", nodeCurve: "prime256v1", kdf: 0x0001, Nsecret: 32, Npub: 65, Nsk: 32 },
73
+ 0x0012: { kind: "ec", name: "P-521", curve: "P-521", nodeCurve: "secp521r1", kdf: 0x0003, Nsecret: 64, Npub: 133, Nsk: 66 },
74
+ 0x0020: { kind: "okp", name: "X25519", curve: "X25519", kdf: 0x0001, Nsecret: 32, Npub: 32, Nsk: 32 },
75
+ 0x0021: { kind: "okp", name: "X448", curve: "X448", kdf: 0x0003, Nsecret: 64, Npub: 56, Nsk: 56 },
76
+ 0x0040: _mlKemRow("ML-KEM-512", "id-ml-kem-512", "ml-kem-512"),
77
+ 0x0041: _mlKemRow("ML-KEM-768", "id-ml-kem-768", "ml-kem-768"),
78
+ 0x0042: _mlKemRow("ML-KEM-1024", "id-ml-kem-1024", "ml-kem-1024"),
65
79
  });
66
80
 
67
81
  var MODE_BASE = 0x00, MODE_PSK = 0x01, MODE_AUTH = 0x02, MODE_AUTH_PSK = 0x03;
@@ -78,19 +92,24 @@ function _extract(hash, Nh, salt, ikm) {
78
92
  }
79
93
  function _expand(hash, Nh, prk, info, len) {
80
94
  if (len > 255 * Nh) throw _err("hpke/export-length", "requested length " + len + " exceeds 255*Nh");
81
- var out = [], t = Buffer.alloc(0), n = Math.ceil(len / Nh);
82
- for (var i = 1; i <= n; i++) {
83
- var fed = concat([t, info, Buffer.from([i])]);
84
- t = nodeCrypto.createHmac(hash, prk).update(fed).digest();
95
+ var out = [], t = Buffer.alloc(0), n = Math.ceil(len / Nh), fed = null, joined = null;
96
+ try {
97
+ for (var i = 1; i <= n; i++) {
98
+ fed = concat([t, info, Buffer.from([i])]);
99
+ t = nodeCrypto.createHmac(hash, prk).update(fed).digest();
100
+ guard.secret.zeroize(fed, HpkeError, "hpke/bad-input", "an expand feedback input");
101
+ fed = null;
102
+ out.push(t);
103
+ }
104
+ joined = concat(out);
105
+ var exact = Buffer.alloc(len);
106
+ joined.copy(exact, 0, 0, len);
107
+ return exact;
108
+ } finally {
85
109
  guard.secret.zeroize(fed, HpkeError, "hpke/bad-input", "an expand feedback input");
86
- out.push(t);
110
+ guard.secret.zeroize(joined, HpkeError, "hpke/bad-input", "the KDF accumulator");
111
+ for (var oi = 0; oi < out.length; oi++) guard.secret.zeroize(out[oi], HpkeError, "hpke/bad-input", "a KDF block");
87
112
  }
88
- var joined = concat(out);
89
- var exact = Buffer.alloc(len);
90
- joined.copy(exact, 0, 0, len);
91
- guard.secret.zeroize(joined, HpkeError, "hpke/bad-input", "the KDF accumulator");
92
- for (var oi = 0; oi < out.length; oi++) guard.secret.zeroize(out[oi], HpkeError, "hpke/bad-input", "a KDF block");
93
- return exact;
94
113
  }
95
114
  function _labeledExtract(kdf, suiteId, salt, label, ikm) {
96
115
  var labeled = concat([HPKE_V1, suiteId, L(label), ikm]);
@@ -104,10 +123,27 @@ function _labeledExpand(kdf, suiteId, prk, label, info, len) {
104
123
 
105
124
  var OKP_SPKI = intrinsic.assign(intrinsic.create(null), { X25519: "302a300506032b656e032100", X448: "3042300506032b656f033900" });
106
125
  var OKP_PKCS8 = intrinsic.assign(intrinsic.create(null), { X25519: "302e020100300506032b656e04220420", X448: "3046020100300506032b656f043a0438" });
126
+ var EC_SEC1 = intrinsic.assign(intrinsic.create(null), {
127
+ "P-256": { head: "30310201010420", tail: "a00a06082a8648ce3d030107",
128
+ order: "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551" },
129
+ "P-521": { head: "30500201010442", tail: "a00706052b81040023",
130
+ order: "01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409" },
131
+ });
132
+ var ML_KEM_SPKI = intrinsic.assign(intrinsic.create(null), {
133
+ "ML-KEM-512": "30820332300b06096086480165030404010382032100",
134
+ "ML-KEM-768": "308204b2300b0609608648016503040402038204a100",
135
+ "ML-KEM-1024": "30820632300b06096086480165030404030382062100",
136
+ });
137
+ var ML_KEM_PKCS8 = intrinsic.assign(intrinsic.create(null), {
138
+ "ML-KEM-512": "3054020100300b060960864801650304040104428040",
139
+ "ML-KEM-768": "3054020100300b060960864801650304040204428040",
140
+ "ML-KEM-1024": "3054020100300b060960864801650304040304428040",
141
+ });
142
+ function _hex(h) { return _bufferFrom(h, "hex"); }
107
143
 
108
144
  function _importPublic(kem, raw) {
109
- if (!Buffer.isBuffer(raw) || raw.length !== kem.Npub) {
110
- throw _err("hpke/bad-key", kem.curve + " public key must be " + kem.Npub + " bytes");
145
+ if (!_isBuffer(raw) || raw.length !== kem.Npub) {
146
+ throw _err("hpke/bad-key", kem.name + " public key must be " + kem.Npub + " bytes");
111
147
  }
112
148
  try {
113
149
  if (kem.kind === "ec") {
@@ -116,31 +152,62 @@ function _importPublic(kem, raw) {
116
152
  var jwk = { kty: "EC", crv: kem.curve, x: raw.subarray(1, 1 + half).toString("base64url"), y: raw.subarray(1 + half).toString("base64url") };
117
153
  return nodeCrypto.createPublicKey({ key: jwk, format: "jwk" });
118
154
  }
119
- return nodeCrypto.createPublicKey({ key: Buffer.from(OKP_SPKI[kem.curve] + raw.toString("hex"), "hex"), format: "der", type: "spki" });
155
+ var prefix = kem.kind === "mlkem" ? ML_KEM_SPKI[kem.name] : OKP_SPKI[kem.curve];
156
+ return nodeCrypto.createPublicKey({ key: _bufferConcat([_hex(prefix), raw]), format: "der", type: "spki" });
120
157
  } catch (e) {
121
158
  if (e instanceof HpkeError) throw e;
122
- throw _err("hpke/bad-key", "invalid " + kem.curve + " public key", e);
159
+ throw _err("hpke/bad-key", "invalid " + kem.name + " public key" +
160
+ (kem.kind === "mlkem" ? " (FIPS 203 sec. 7.2 encapsulation key check)" : ""), e);
123
161
  }
124
162
  }
125
163
  function _exportPublic(kem, keyObject) {
126
- var jwk = keyObject.export({ format: "jwk" });
164
+ var pub = keyObject.type === "public" ? keyObject : nodeCrypto.createPublicKey(keyObject);
165
+ if (kem.kind === "mlkem") {
166
+ var der = pub.export({ format: "der", type: "spki" }), prefix = _hex(ML_KEM_SPKI[kem.name]);
167
+ if (der.length !== prefix.length + kem.Npub || !_bufferEquals(_subarray(der, 0, prefix.length), prefix)) {
168
+ throw _err("hpke/bad-key", "the KeyObject is not an " + kem.name + " key");
169
+ }
170
+ return _subarray(der, prefix.length);
171
+ }
172
+ var jwk = pub.export({ format: "jwk" });
173
+ if (jwk.crv !== kem.curve) throw _err("hpke/bad-key", "the KeyObject is not a " + kem.name + " key");
127
174
  if (kem.kind === "ec") return concat([Buffer.from([0x04]), _b64u(jwk.x), _b64u(jwk.y)]);
128
175
  return _b64u(jwk.x);
129
176
  }
130
177
  function _b64u(s) { return guard.encoding.base64url(s, null, _err, "hpke/bad-key", "JWK coordinate"); }
131
178
 
132
- function _importPrivate(kem, rawSk, rawPk) {
179
+ function _scalarInRange(d, order) {
180
+ return _compare(d, _bufferAlloc(d.length)) > 0 && _compare(d, order) < 0;
181
+ }
182
+ function _importPrivate(kem, rawSk) {
183
+ if (!_isBuffer(rawSk) || rawSk.length !== kem.Nsk) {
184
+ throw _err("hpke/bad-key", kem.name + " private key must be " +
185
+ (kem.kind === "mlkem" ? "the 64-byte seed" : "the " + kem.Nsk + "-byte scalar") + " as a Buffer");
186
+ }
187
+ var der;
188
+ if (kem.kind === "ec") {
189
+ var sec1 = EC_SEC1[kem.curve];
190
+ if (!_scalarInRange(rawSk, _hex(sec1.order))) throw _err("hpke/bad-key", kem.name + " private scalar is outside [1, n-1]");
191
+ der = _bufferConcat([_hex(sec1.head), rawSk, _hex(sec1.tail)]);
192
+ } else {
193
+ der = _bufferConcat([_hex(kem.kind === "mlkem" ? ML_KEM_PKCS8[kem.name] : OKP_PKCS8[kem.curve]), rawSk]);
194
+ }
133
195
  try {
134
- if (kem.kind === "ec") {
135
- var jwk = { kty: "EC", crv: kem.curve, d: rawSk.toString("base64url") };
136
- if (rawPk) { jwk.x = rawPk.subarray(1, 1 + (rawPk.length - 1) / 2).toString("base64url"); jwk.y = rawPk.subarray(1 + (rawPk.length - 1) / 2).toString("base64url"); }
137
- return nodeCrypto.createPrivateKey({ key: jwk, format: "jwk" });
138
- }
139
- return nodeCrypto.createPrivateKey({ key: Buffer.from(OKP_PKCS8[kem.curve] + rawSk.toString("hex"), "hex"), format: "der", type: "pkcs8" });
196
+ return nodeCrypto.createPrivateKey({ key: der, format: "der", type: kem.kind === "ec" ? "sec1" : "pkcs8" });
140
197
  } catch (e) {
141
- throw _err("hpke/bad-key", "invalid " + kem.curve + " private key", e);
198
+ throw _err("hpke/bad-key", "invalid " + kem.name + " private key", e);
199
+ } finally {
200
+ guard.secret.zeroize(der, HpkeError, "hpke/bad-input", "the private key envelope");
142
201
  }
143
202
  }
203
+ function _boundPublic(kem, privateKey, pkm) {
204
+ var derived = _exportPublic(kem, nodeCrypto.createPublicKey(privateKey));
205
+ if (pkm === undefined) return derived;
206
+ if (!_isBuffer(pkm) || !_bufferEquals(derived, pkm)) {
207
+ throw _err("hpke/bad-key", "pkm is not the " + kem.name + " public key derived from skm");
208
+ }
209
+ return derived;
210
+ }
144
211
  function _dh(privateKey, publicKey) {
145
212
  try {
146
213
  return nodeCrypto.diffieHellman({ privateKey: privateKey, publicKey: publicKey });
@@ -164,12 +231,33 @@ function _extractAndExpand(kem, dh, kemContext) {
164
231
  function _kemId(kem) { for (var k in KEMS) if (KEMS[k] === kem) return Number(k); return 0; }
165
232
 
166
233
  function _ephemeral(kem, eph) {
167
- if (eph) return { skE: _importPrivate(kem, eph.skm, eph.pkm), enc: _buf(eph.pkm) };
234
+ if (eph != null) {
235
+ if (typeof eph !== "object") throw _err("hpke/bad-input", "eph must be { skm, pkm } (a fixed ephemeral key pair), got " + guard.text.showValue(eph));
236
+ var skE = _importPrivate(kem, eph.skm);
237
+ return { skE: skE, enc: _boundPublic(kem, skE, eph.pkm) };
238
+ }
168
239
  var kp = _generate(kem);
169
240
  return { skE: kp.privateKey, enc: _exportPublic(kem, kp.publicKey) };
170
241
  }
171
242
  function _wipeDh(dh) { guard.secret.zeroize(dh, HpkeError, "hpke/bad-input", "the KEM shared secret"); }
243
+ function _mlKemEncap(kem, pkR, eph) {
244
+ if (eph != null) {
245
+ throw _err("hpke/bad-input", "eph (a fixed ephemeral key pair) applies to a DHKEM suite; " + kem.name + " encapsulation takes its randomness from the runtime");
246
+ }
247
+ var r;
248
+ try { r = nodeCrypto.encapsulate(pkR); }
249
+ catch (e) { throw _err("hpke/bad-key", kem.name + " encapsulation failed", e); }
250
+ return { sharedSecret: r.sharedKey, enc: r.ciphertext };
251
+ }
252
+ function _mlKemDecap(kem, enc, skR) {
253
+ if (enc.length !== kem.Nenc) {
254
+ throw _err("hpke/bad-key", kem.name + " encapsulated key must be " + kem.Nenc + " bytes (FIPS 203 sec. 7.3 ciphertext check)");
255
+ }
256
+ try { return nodeCrypto.decapsulate(skR, enc); }
257
+ catch (e) { throw _err("hpke/bad-key", kem.name + " decapsulation failed", e); }
258
+ }
172
259
  function _encap(kem, pkR, pkRm, eph) {
260
+ if (kem.kind === "mlkem") return _mlKemEncap(kem, pkR, eph);
173
261
  var e = _ephemeral(kem, eph);
174
262
  var dh = null;
175
263
  try {
@@ -178,6 +266,7 @@ function _encap(kem, pkR, pkRm, eph) {
178
266
  } finally { _wipeDh(dh); }
179
267
  }
180
268
  function _decap(kem, enc, skR, pkRm) {
269
+ if (kem.kind === "mlkem") return _mlKemDecap(kem, enc, skR);
181
270
  var pkE = _importPublic(kem, enc);
182
271
  var dh = null;
183
272
  try {
@@ -307,14 +396,32 @@ function _recipPublic(suite, pk) {
307
396
  }
308
397
  }
309
398
  function _recipPrivate(suite, sk) {
310
- if (sk && sk.skm) return { key: _importPrivate(suite.kem, sk.skm, sk.pkm), pkm: sk.pkm };
311
- if (Buffer.isBuffer(sk)) throw _err("hpke/bad-key", "a serialized private key must be provided as { skm, pkm } (raw scalar + public point), not a bare buffer");
399
+ var kem = suite.kem;
400
+ if (sk && sk.skm != null) {
401
+ var key = _importPrivate(kem, sk.skm);
402
+ return { key: key, pkm: _boundPublic(kem, key, sk.pkm) };
403
+ }
404
+ if (_isBuffer(sk)) {
405
+ throw _err("hpke/bad-key", "a serialized " + kem.name + " private key must be provided as { skm" +
406
+ (kem.kind === "mlkem" ? " } holding the 64-byte seed" : ", pkm } (the raw scalar, and optionally its public key)") + ", not a bare buffer");
407
+ }
312
408
  try {
313
- var pkm = _exportPublic(suite.kem, nodeCrypto.createPublicKey(sk));
409
+ if (sk.type !== "private") throw _err("hpke/bad-key", "the private key must be a private KeyObject or { skm, pkm }, got a " + guard.text.showValue(sk.type) + " KeyObject");
410
+ var pkm = _exportPublic(kem, nodeCrypto.createPublicKey(sk));
314
411
  return { key: sk, pkm: pkm };
315
412
  } catch (e) {
316
413
  if (e instanceof HpkeError) throw e;
317
- throw _err("hpke/bad-key", "invalid recipient private key (expected a node KeyObject or { skm, pkm })", e);
414
+ throw _err("hpke/bad-key", "invalid private key (expected a node KeyObject or { skm, pkm })", e);
415
+ }
416
+ }
417
+ function _requireAuthCapable(kem) {
418
+ if (kem.kind === "mlkem") {
419
+ throw _err("hpke/auth-unsupported", kem.name + " defines no AuthEncap / AuthDecap (draft-ietf-hpke-pq sec. 7.2); use the psk mode or a signature");
420
+ }
421
+ }
422
+ function _refuseUnusedAuthKey(value, name, mode) {
423
+ if (value != null) {
424
+ throw _err("hpke/bad-input", name + " applies to the auth and auth-psk modes; mode " + mode + " would leave it unused, so the exchange it was meant to authenticate would not be");
318
425
  }
319
426
  }
320
427
 
@@ -332,7 +439,7 @@ var _SETUP_S_KEYS = _withCommon({
332
439
  var _SETUP_R_KEYS = _withCommon({
333
440
  senderPublicKey: 1,
334
441
  });
335
- function _mode(opts, keys, who) {
442
+ function _options(opts, keys, who) {
336
443
  guard.identifier.assertKnownKeys(opts, keys, _err, "hpke/bad-input", function (k) {
337
444
  var other = (keys === _SETUP_S_KEYS ? _SETUP_R_KEYS : _SETUP_S_KEYS);
338
445
  return "unknown HPKE " + who + " option " + JSON.stringify(k) +
@@ -340,17 +447,21 @@ function _mode(opts, keys, who) {
340
447
  ? " -- that option belongs to the other end of the exchange, where it would authenticate or seed; here it would do nothing"
341
448
  : "") + " -- accepted: " + Object.keys(keys).sort().join(", ");
342
449
  });
343
- var mode = (opts.mode == null) ? MODE_BASE : opts.mode;
344
- if (mode !== MODE_BASE && mode !== MODE_PSK && mode !== MODE_AUTH && mode !== MODE_AUTH_PSK) {
345
- throw _err("hpke/unknown-mode", "unsupported HPKE mode " + guard.text.showValue(mode) + " (RFC 9180 sec. 5.1 defines base / psk / auth / auth-psk)");
450
+ var o = guard.identifier.snapshotOptions(opts, keys);
451
+ if (o.mode == null) o.mode = MODE_BASE;
452
+ if (o.mode !== MODE_BASE && o.mode !== MODE_PSK && o.mode !== MODE_AUTH && o.mode !== MODE_AUTH_PSK) {
453
+ throw _err("hpke/unknown-mode", "unsupported HPKE mode " + guard.text.showValue(o.mode) + " (RFC 9180 sec. 5.1 defines base / psk / auth / auth-psk)");
346
454
  }
347
- return mode;
455
+ return o;
348
456
  }
349
457
 
350
458
  // @module @intro; a data registry, not a callable primitive).
351
459
  var suites = intrinsic.assign(intrinsic.create(null), {
352
- KEM: intrinsic.assign(intrinsic.create(null), { DHKEM_P256_HKDF_SHA256: 0x0010, DHKEM_P521_HKDF_SHA512: 0x0012, DHKEM_X25519_HKDF_SHA256: 0x0020, DHKEM_X448_HKDF_SHA512: 0x0021 }),
353
- KDF: intrinsic.assign(intrinsic.create(null), { HKDF_SHA256: 0x0001, HKDF_SHA512: 0x0003 }),
460
+ KEM: intrinsic.assign(intrinsic.create(null), {
461
+ DHKEM_P256_HKDF_SHA256: 0x0010, DHKEM_P521_HKDF_SHA512: 0x0012, DHKEM_X25519_HKDF_SHA256: 0x0020, DHKEM_X448_HKDF_SHA512: 0x0021,
462
+ ML_KEM_512: 0x0040, ML_KEM_768: 0x0041, ML_KEM_1024: 0x0042,
463
+ }),
464
+ KDF: intrinsic.assign(intrinsic.create(null), { HKDF_SHA256: 0x0001, HKDF_SHA384: 0x0002, HKDF_SHA512: 0x0003 }),
354
465
  AEAD: intrinsic.assign(intrinsic.create(null), { AES_128_GCM: 0x0001, AES_256_GCM: 0x0002, CHACHA20_POLY1305: 0x0003, EXPORT_ONLY: 0xFFFF }),
355
466
  MODE: intrinsic.assign(intrinsic.create(null), { BASE: MODE_BASE, PSK: MODE_PSK, AUTH: MODE_AUTH, AUTH_PSK: MODE_AUTH_PSK }),
356
467
  });
@@ -369,9 +480,13 @@ var suites = intrinsic.assign(intrinsic.create(null), {
369
480
  * (send it to the recipient) and a `context` whose `.seal(aad, pt)` /
370
481
  * `.export(ctx, L)` encrypt and derive further secrets. `suiteIds` is
371
482
  * `{ kem, kdf, aead }` from `pki.hpke.suites`; `recipientPublicKey` is a node
372
- * KeyObject or the serialized public key bytes. `opts.mode` selects base / psk /
373
- * auth / auth-psk (default base); `opts.info`, `opts.psk`/`opts.pskId`, and
374
- * `opts.senderKey` (auth modes) supply the corresponding inputs.
483
+ * KeyObject or the serialized public key bytes (the uncompressed point, the raw
484
+ * Montgomery coordinate, or the ML-KEM encapsulation key). `opts.mode` selects
485
+ * base / psk / auth / auth-psk (default base); `opts.info`, `opts.psk`/`opts.pskId`,
486
+ * and `opts.senderKey` (auth modes) supply the corresponding inputs; an option that
487
+ * belongs to another mode, such as `senderKey` in base mode, is refused with
488
+ * `hpke/bad-input` rather than left unused. The auth modes exist for the DHKEM
489
+ * suites only: an ML-KEM suite throws `hpke/auth-unsupported`.
375
490
  *
376
491
  * @example
377
492
  * var s = pki.hpke.suites, ids = { kem: s.KEM.DHKEM_X25519_HKDF_SHA256, kdf: s.KDF.HKDF_SHA256, aead: s.AEAD.AES_128_GCM };
@@ -380,17 +495,18 @@ var suites = intrinsic.assign(intrinsic.create(null), {
380
495
  * var ct = sender.context.seal(Buffer.from("aad"), Buffer.from("secret"));
381
496
  */
382
497
  function _setupS(ids, pkR, opts) {
383
- opts = opts || {};
384
498
  var suite = _suite(ids);
385
- var mode = _mode(opts, _SETUP_S_KEYS, "sender setup");
499
+ opts = _options(opts || {}, _SETUP_S_KEYS, "sender setup");
500
+ var mode = opts.mode;
386
501
  var r = _recipPublic(suite, pkR);
387
502
  var kem = suite.kem, k;
388
503
  if (mode === MODE_AUTH || mode === MODE_AUTH_PSK) {
389
- if (kem.kind !== "ec" && kem.kind !== "okp") throw _err("hpke/auth-unsupported", "the KEM does not support authenticated modes");
504
+ _requireAuthCapable(kem);
390
505
  if (opts.senderKey == null) throw _err("hpke/auth-key-required", "an authenticated mode requires opts.senderKey (the sender's KEM private key, RFC 9180 sec. 5.1.3)");
391
506
  var s = _recipPrivate(suite, opts.senderKey);
392
507
  k = _authEncap(kem, r.key, r.pkm, s.key, s.pkm, opts.eph);
393
508
  } else {
509
+ _refuseUnusedAuthKey(opts.senderKey, "senderKey", mode);
394
510
  k = _encap(kem, r.key, r.pkm, opts.eph);
395
511
  }
396
512
  var ctx = _keySchedule(suite, mode, k.sharedSecret, _buf(opts.info), _buf(opts.psk), _buf(opts.pskId), "S");
@@ -405,12 +521,14 @@ function _setupS(ids, pkR, opts) {
405
521
  * @related pki.hpke.setupS, pki.hpke.open
406
522
  *
407
523
  * Establish the recipient HPKE context from the sender's encapsulated key `enc`
408
- * and the recipient KEM private key (a node KeyObject, or `{ skm, pkm }` holding
409
- * the raw private scalar plus its public point),
410
- * recovering the same shared secret and key schedule. The returned `context`
411
- * `.open(aad, ct)` decrypts and `.export(ctx, L)` derives secrets. `opts` mirrors
412
- * `setupS` (mode / info / psk / pskId), with `opts.senderPublicKey` for the auth
413
- * modes. A ciphertext whose tag does not verify throws `hpke/open-failed`.
524
+ * and the recipient KEM private key, recovering the same shared secret and key
525
+ * schedule. The private key is a node KeyObject, or `{ skm, pkm }` where `skm` is
526
+ * the raw private scalar of a DHKEM suite or the 64-byte seed of an ML-KEM suite;
527
+ * `pkm` is optional, and when given it must be the public key derived from `skm`
528
+ * or the call throws `hpke/bad-key`. The returned `context` `.open(aad, ct)`
529
+ * decrypts and `.export(ctx, L)` derives secrets. `opts` mirrors `setupS` (mode /
530
+ * info / psk / pskId), with `opts.senderPublicKey` for the auth modes (DHKEM
531
+ * suites only). A ciphertext whose tag does not verify throws `hpke/open-failed`.
414
532
  *
415
533
  * @example
416
534
  * var s = pki.hpke.suites, ids = { kem: s.KEM.DHKEM_X25519_HKDF_SHA256, kdf: s.KDF.HKDF_SHA256, aead: s.AEAD.AES_128_GCM };
@@ -421,16 +539,18 @@ function _setupS(ids, pkR, opts) {
421
539
  * var pt = recipient.open(Buffer.alloc(0), sender.context.seal(Buffer.alloc(0), Buffer.from("hi")));
422
540
  */
423
541
  function _setupR(ids, enc, skR, opts) {
424
- opts = opts || {};
425
542
  var suite = _suite(ids);
426
- var mode = _mode(opts, _SETUP_R_KEYS, "recipient setup");
543
+ opts = _options(opts || {}, _SETUP_R_KEYS, "recipient setup");
544
+ var mode = opts.mode;
427
545
  var r = _recipPrivate(suite, skR);
428
546
  var kem = suite.kem, ss;
429
547
  if (mode === MODE_AUTH || mode === MODE_AUTH_PSK) {
548
+ _requireAuthCapable(kem);
430
549
  if (opts.senderPublicKey == null) throw _err("hpke/auth-key-required", "an authenticated mode requires opts.senderPublicKey (the sender's KEM public key, RFC 9180 sec. 5.1.3)");
431
550
  var pkS = _recipPublic(suite, opts.senderPublicKey);
432
551
  ss = _authDecap(kem, _buf(enc), r.key, r.pkm, pkS.key, pkS.pkm);
433
552
  } else {
553
+ _refuseUnusedAuthKey(opts.senderPublicKey, "senderPublicKey", mode);
434
554
  ss = _decap(kem, _buf(enc), r.key, r.pkm);
435
555
  }
436
556
  try { return _keySchedule(suite, mode, ss, _buf(opts.info), _buf(opts.psk), _buf(opts.pskId), "R"); }
@@ -451,9 +571,9 @@ function _setupR(ids, enc, skR, opts) {
451
571
  * `setupS` options object (mode / info / psk / senderKey).
452
572
  *
453
573
  * @example
454
- * var s = pki.hpke.suites, ids = { kem: s.KEM.DHKEM_X25519_HKDF_SHA256, kdf: s.KDF.HKDF_SHA256, aead: s.AEAD.AES_256_GCM };
455
- * var pkR = Buffer.from("8c7781768956b9dd38997c5a83ab5b9315270a9f73d87d676573c5bca74e3e48", "hex");
456
- * var out = pki.hpke.seal(ids, pkR, {}, Buffer.from("aad"), Buffer.from("msg"));
574
+ * // requires: mlKemPkR -- the recipient's ML-KEM-768 encapsulation key (1184 bytes)
575
+ * var s = pki.hpke.suites, ids = { kem: s.KEM.ML_KEM_768, kdf: s.KDF.HKDF_SHA256, aead: s.AEAD.AES_256_GCM };
576
+ * var out = pki.hpke.seal(ids, mlKemPkR, {}, Buffer.from("aad"), Buffer.from("msg"));
457
577
  */
458
578
  function seal(ids, pkR, opts, aad, pt) {
459
579
  var s = null;
@@ -481,11 +601,11 @@ function seal(ids, pkR, opts, aad, pt) {
481
601
  * verify throws `hpke/open-failed` and returns no plaintext.
482
602
  *
483
603
  * @example
484
- * var s = pki.hpke.suites, ids = { kem: s.KEM.DHKEM_X25519_HKDF_SHA256, kdf: s.KDF.HKDF_SHA256, aead: s.AEAD.AES_256_GCM };
485
- * var pkR = Buffer.from("8c7781768956b9dd38997c5a83ab5b9315270a9f73d87d676573c5bca74e3e48", "hex");
486
- * var skR = Buffer.from("009f2181fba5f8908632c10ea1137c40a849728fde016c4602458b943a5dc048", "hex");
487
- * var o = pki.hpke.seal(ids, pkR, {}, Buffer.alloc(0), Buffer.from("m"));
488
- * var pt = pki.hpke.open(ids, o.enc, { skm: skR, pkm: pkR }, {}, Buffer.alloc(0), o.ct);
604
+ * // requires: mlKemPkR -- the recipient's ML-KEM-768 encapsulation key (1184 bytes)
605
+ * // requires: mlKemSkR -- { skm } holding the recipient's 64-byte ML-KEM-768 seed
606
+ * var s = pki.hpke.suites, ids = { kem: s.KEM.ML_KEM_768, kdf: s.KDF.HKDF_SHA256, aead: s.AEAD.AES_256_GCM };
607
+ * var o = pki.hpke.seal(ids, mlKemPkR, {}, Buffer.alloc(0), Buffer.from("m"));
608
+ * var pt = pki.hpke.open(ids, o.enc, mlKemSkR, {}, Buffer.alloc(0), o.ct);
489
609
  */
490
610
  function open(ids, enc, skR, opts, aad, ct) {
491
611
  var ctx = _setupR(ids, enc, skR, opts);
package/lib/pki-build.js CHANGED
@@ -1236,6 +1236,10 @@ function makeBuilder(ctx) {
1236
1236
  ka = nodeCrypto.createPublicKey({ key: a, format: "der", type: "spki" });
1237
1237
  kb = nodeCrypto.createPublicKey({ key: bb, format: "der", type: "spki" });
1238
1238
  } catch (_e) { return false; }
1239
+ /** @internal Two keys of different types are never the same key, and comparing them through
1240
+ * the runtime's equality leaves a fault queued in the crypto library that surfaces on the
1241
+ * next unrelated key import in the process, so the type decides that case first. */
1242
+ if (ka.asymmetricKeyType !== kb.asymmetricKeyType) return false;
1239
1243
  return _keyEquals(ka, kb) === true;
1240
1244
  }
1241
1245
 
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,12 +120,21 @@ 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");
@@ -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)");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.7.30",
3
+ "version": "0.7.32",
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:cccf2ff7-2673-4c48-b9bc-d452383b439d",
5
+ "serialNumber": "urn:uuid:e6cbf35c-8e98-48dd-b7b6-77d846830487",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-12T06:10:23.138Z",
8
+ "timestamp": "2026-09-12T08:16:24.422Z",
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.30",
22
+ "bom-ref": "@blamejs/pki@0.7.32",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.7.30",
25
+ "version": "0.7.32",
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.30",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.7.32",
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.30",
57
+ "ref": "@blamejs/pki@0.7.32",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]