@blamejs/pki 0.6.49 → 0.6.51

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,43 @@ All notable changes to `@blamejs/pki` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## v0.6.51 — 2026-09-07
8
+
9
+ A CMP message that names one key and is protected by another no longer verifies.
10
+
11
+ ### Added
12
+
13
+ - pki.cmp.verify checks the senderKID of a MAC-protected message against the commonName of its sender field, which is how such a message names the shared secret it was protected with (RFC 9483 section 4.1.5). A senderKID naming another entity, or a sender carrying no commonName to match, is refused with cmp/bad-sender-kid. An anonymous sender is the exception the base protocol names: where the sender is the NULL-DN a requester uses before it knows its own name, the senderKID is a reference number rather than a name (RFC 9810 section 5.1.1), so it is carried and not compared. A KEM-protected message's senderKID is likewise carried and not compared, since no specification says what it names there.
14
+ - pki.cmp.verify refuses an opts.time that is not a Date with cmp/bad-input, at the door, rather than letting whichever check reads it first throw a bare TypeError.
15
+ - pki.cmp.verify takes opts.messageTimeTolerance, the accepted messageTime skew in seconds. RFC 9483 section 3.5 requires a present messageTime to be close to the receiver's current time but leaves the threshold to the use case, so stating a window turns the check on and a message outside it in either direction is a cmp/bad-message-time verdict. A clock runs fast as readily as slow, so a message dated ahead of the receiver is judged the same as one dated behind it. Without the option the messageTime is not judged, and a message carrying none is unaffected.
16
+
17
+ ### Changed
18
+
19
+ - A caller that passes opts.signerCert for a message whose senderKID does not match that certificate now receives a cmp/bad-sender-kid verdict where the message previously verified. A sender that sets senderKID to its certificate's subjectKeyIdentifier, which is what the field is for, is unaffected.
20
+
21
+ ### Fixed
22
+
23
+ - pki.cmp.verify holds a declared senderKID to the key that actually verified the protection, on every path (RFC 9483 section 3.5). A certificate passed as opts.signerCert is now checked against the header's senderKID exactly as one selected from extraCerts already was, so a message naming one key identifier and signed under another is refused with cmp/bad-sender-kid instead of verifying. A signer certificate carrying no subjectKeyIdentifier offers nothing for a declared identifier to name and cannot satisfy one; a message declaring no senderKID is unaffected, since the rule is conditioned on the field being present.
24
+ - A message whose extraCerts carry no certificate matching the declared senderKID reports cmp/bad-sender-kid rather than cmp/signer-cert-not-found. The two failures are different: nothing was offered, versus nothing offered carries the identifier the message declares. Reporting them apart keeps one defect from carrying two codes depending on how the certificate would have arrived. pki.cmp.session treats the new code the same way it treated the old one, so a transaction whose response declares a signer the response did not carry still falls back to the certificate the session already holds, and that certificate is put through the same identifier check.
25
+
26
+ ## v0.6.50 — 2026-09-07
27
+
28
+ A client whose key can only establish secrets can now authenticate its CMP messages with that key.
29
+
30
+ ### Added
31
+
32
+ - pki.cmp.build(message, { kem }) protects a PKIMessage with a KEM-based message authentication code (RFC 9810 section 5.1.3.4). Pass the KEM private key as a CryptoKey, a PKCS#8 DER buffer or a PEM string, the ciphertext the peer encapsulated to it, and the ML-KEM parameter set it was produced under; the ciphertext is decapsulated, a key is derived from the resulting shared secret, and the message authentication code is computed over the exact ProtectedPart. The protectionAlg is id-KemBasedMac carrying the KemBMParameter that names the derivation, so a peer can reproduce the key from the message alone.
33
+ - The derived key is bound to the transaction it belongs to. RFC 9810 requires the derivation context to carry the identifier of the message that delivered the ciphertext, which keeps a key established in one PKI management operation from authenticating another. That is this message's own transaction identifier unless the ciphertext arrived under a different one, which spec kem transactionID names. A message carrying no transaction identifier and naming none is refused rather than bound to nothing, and an optional kemContext travels into the derivation as well as into the parameters.
34
+ - pki.cmp.verify(message, { kem: { sharedSecret, transactionID? } }) checks that protection, reporting protectionType kem. The shared secret is the one this side encapsulated to the sender's KEM public key. Verification recomputes over the raw header and body bytes the parser surfaced, never a re-serialization, and compares in constant time. A KemBMParameter that is absent or does not decode, and a key-derivation or message-authentication algorithm outside the accepted set, are failed verdicts rather than defaults; the receiving-side header rules apply as they do to the other two flavors.
35
+ - session.info({ kemCiphertext: true }) fetches the ciphertext, so a client can complete the exchange without assembling the general message itself. It sends the id-it-KemCiphertextInfo query with no value, as RFC 9810 section 5.3.19.18 requires, and returns the algorithm and the ciphertext the authority encapsulated. An answer naming a KEM this client cannot decapsulate under, or carrying an empty ciphertext, is refused rather than handed back as something to try; an answer carrying no value at all is the documented absence.
36
+ - pki.schema.cmp reads the two structures the exchange uses: KemBMParameter, the parameters of the protectionAlg, and KemCiphertextInfo, the algorithm and ciphertext a peer sends.
37
+ - A message carries one protection. Naming kem alongside a signature or a shared secret is refused rather than resolved by precedence, and opts.kem passed for a message protected another way is refused too. The KEM the client decapsulates under is ML-KEM-512, 768 or 1024, under HKDF-SHA256 and HMAC-SHA256; anything else is refused rather than defaulted. The sender chooses the derived key size, so a message naming one short enough to search is refused at both ends rather than protected or verified under it, and the shared secret is accepted in any of the byte shapes an encapsulation returns.
38
+
39
+ ### Changed
40
+
41
+ - pki.cmp.verify no longer reports id-KemBasedMac as an unsupported protection algorithm, since it now verifies it. id-PasswordBasedMac and id-DHBasedMac are still refused as before.
42
+ - pki.cmp.verify takes a shared secret in any byte shape, not only a Buffer or a Uint8Array. An ArrayBuffer, which is what a KEM encapsulation returns, and a view over a larger allocation are both accepted and copied at the door as before. This applies to opts.sharedSecret as well as to the new opts.kem.sharedSecret.
43
+
7
44
  ## v0.6.49 — 2026-09-07
8
45
 
9
46
  A key that cannot sign for itself can still prove possession, by answering the authority's encrypted challenge.
package/README.md CHANGED
@@ -235,7 +235,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
235
235
  | `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
236
236
  | `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
237
237
  | `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named, and `agreeMAC` is not built, since it needs the RFC 2875 static Diffie-Hellman secret against a CA certificate the requester already holds. 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
- | `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, or `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived). Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. A certification authority can take longer to answer than a process is held open, so a `poll-timeout` carries a `resumeToken` and `resumePoll(token)` continues the same transaction in a later process: the token is plain JSON naming the transaction, the nonce the next request echoes, the polled request and the arm its grant arrives on, and the key the grant must certify. It carries no secret and grants nothing, since the protection material and the endpoint come from the session built to resume with, and the resumed poll verifies, nonce-binds, and key-binds every response. Its fields are what the resumed exchange is held to, so store it where the enrollment's own state is stored: someone who can rewrite it can widen what the resumed session accepts, as far as that session's trust anchors and the authority's protection allow and no further. The same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `session` |
238
+ | `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `krr` (key recovery, §5.3.7), `ccr` (cross-certification, §5.3.11: a `CertReqMessages` at the normative floor, where the requesting CA keeps its private key so a private-key-transport encryptedKey proof-of-possession is refused, and the optional App. D.6 single-request cardinality is not enforced), `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). Protection is exactly one of `opts.{ key, cert }`, a signature under the sender key with the algorithm resolved from the signer certificate so RSA (PKCS#1 v1.5 / PSS), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived), or `opts.kem`, a KEM-based MAC for a client whose key can only establish secrets (RFC 9810 §5.1.3.4): the ciphertext a peer encapsulated to its ML-KEM key is decapsulated, the key is derived under HKDF-SHA256 with a context bound to the transaction identifier of the message that carried the ciphertext, and `pki.cmp.verify` checks it from the shared secret. Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. A certification authority can take longer to answer than a process is held open, so a `poll-timeout` carries a `resumeToken` and `resumePoll(token)` continues the same transaction in a later process: the token is plain JSON naming the transaction, the nonce the next request echoes, the polled request and the arm its grant arrives on, and the key the grant must certify. It carries no secret and grants nothing, since the protection material and the endpoint come from the session built to resume with, and the resumed poll verifies, nonce-binds, and key-binds every response. Its fields are what the resumed exchange is held to, so store it where the enrollment's own state is stored: someone who can rewrite it can widen what the resumed session accepts, as far as that session's trust anchors and the authority's protection allow and no further. The same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `session` |
239
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, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access) 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` |
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` |
package/lib/cmp-build.js CHANGED
@@ -13,12 +13,13 @@
13
13
  * PKCS#10 via `pki.csr.sign`, a `certConf` / `pollReq` / `genm` / `rr`, or a `nested` wrapper of other
14
14
  * PKIMessages an RA forwards), and an optional
15
15
  * `PKIProtection` computed over the message. Protection is a signature under the sender key (any
16
- * registry algorithm) or a PBMAC1 shared-secret MAC. The emitted message round-trips through
16
+ * registry algorithm), a PBMAC1 shared-secret MAC, or a KEM-based MAC keyed by a secret the peer
17
+ * encapsulated to the sender's ML-KEM key. The emitted message round-trips through
17
18
  * `pki.schema.cmp.parse` and its protection verifies. `pki.cmp.transfer` carries a message to a CMP
18
19
  * endpoint (RFC 9811), `pki.cmp.verify` checks an incoming message's protection, and `pki.cmp.session`
19
20
  * drives a full enrollment transaction end to end over these. Parsing lives at `pki.schema.cmp.parse`.
20
21
  * @spec RFC 9810
21
- * @card Build a CMP PKIMessage with signature or PBMAC1 protection.
22
+ * @card Build a CMP PKIMessage with signature, PBMAC1 or KEM-based protection.
22
23
  */
23
24
 
24
25
  var asn1 = require("./asn1-der");
@@ -52,6 +53,7 @@ var signScheme = require("./sign-scheme");
52
53
  var pkix = require("./schema-pkix");
53
54
  var pkiBuild = require("./pki-build");
54
55
  var webcrypto = require("./webcrypto");
56
+ var subtle = webcrypto.webcrypto.subtle;
55
57
  var pbes2 = require("./pbes2");
56
58
  var constants = require("./constants");
57
59
  var guard = require("./guard-all");
@@ -87,9 +89,10 @@ var BODY_TAG = intrinsic.assign(intrinsic.create(null), {
87
89
  });
88
90
  var CRMF_BODY = intrinsic.assign(intrinsic.create(null), { ir: 1, cr: 1, kur: 1, krr: 1, ccr: 1 });
89
91
  var CERT_REP_ARM = intrinsic.assign(intrinsic.create(null), { ip: 1, cp: 1, kup: 1, ccp: 1 });
90
- var KNOWN_OPTS_KEYS = intrinsic.assign(intrinsic.create(null), { key: 1, cert: 1, mac: 1, extraCerts: 1, pem: 1, pss: 1, digestAlgorithm: 1 });
92
+ var KNOWN_OPTS_KEYS = intrinsic.assign(intrinsic.create(null), { key: 1, cert: 1, mac: 1, kem: 1, extraCerts: 1, pem: 1, pss: 1, digestAlgorithm: 1 });
91
93
  var KNOWN_OPTS_SIG_KEYS = intrinsic.assign(intrinsic.create(null), { key: 1, cert: 1, extraCerts: 1, pem: 1, pss: 1, digestAlgorithm: 1 });
92
94
  var KNOWN_OPTS_MAC_KEYS = intrinsic.assign(intrinsic.create(null), { mac: 1, extraCerts: 1, pem: 1 });
95
+ var KNOWN_OPTS_KEM_KEYS = intrinsic.assign(intrinsic.create(null), { kem: 1, extraCerts: 1, pem: 1 });
93
96
  var KNOWN_MESSAGE_KEYS = intrinsic.assign(intrinsic.create(null), { header: 1, body: 1 });
94
97
  var KNOWN_MAC_KEYS = intrinsic.assign(intrinsic.create(null), { secret: 1, salt: 1, iterationCount: 1, prf: 1, keyLength: 1, algorithm: 1 });
95
98
 
@@ -545,11 +548,164 @@ async function _p10crBody(csrDer, parsedCsr, tag, state) {
545
548
 
546
549
 
547
550
 
548
- function _resolveProtection(opts) {
551
+ /** @internal A byte field of the KEM protection spec, taken through the toolkit's byte door so a
552
+ * caller object cannot answer differently on a second read. */
553
+ function _kemBytes(v, what) {
554
+ if (v == null) throw _err("cmp/bad-input", what + " is required for KEM-based protection");
555
+ if (!guard.bytes.isByteSource(v)) throw _err("cmp/bad-input", what + " must be DER bytes");
556
+ return guard.bytes.snapshotSource(v, CmpError, "cmp/bad-input", what);
557
+ }
558
+
559
+ var KEM_STATIC_STRING = "CMP-KEM";
560
+ var KNOWN_KEM_KEYS = intrinsic.assign(intrinsic.create(null),
561
+ { key: 1, ciphertext: 1, kemAlgorithm: 1, kemContext: 1, transactionID: 1, len: 1 });
562
+ /** @internal The KEM algorithms a ciphertext can be decapsulated under, and the MAC the derived key
563
+ * drives. RFC 9810 sec. 5.1.3.4 leaves both to the profile and points at RFC 9481; the shipped set is
564
+ * the ML-KEM parameter sets this toolkit already establishes secrets with, under HMAC-SHA256. */
565
+ /** @internal Keyed by the DOTTED OID, not by a display name: `pki.oid.register` can re-point a name,
566
+ * and an algorithm this client supports must not become unsupported because a caller renamed it. */
567
+ var KEM_DECAPSULATE = intrinsic.create(null);
568
+ KEM_DECAPSULATE[O("id-ml-kem-512")] = "ML-KEM-512";
569
+ KEM_DECAPSULATE[O("id-ml-kem-768")] = "ML-KEM-768";
570
+ KEM_DECAPSULATE[O("id-ml-kem-1024")] = "ML-KEM-1024";
571
+ var KEM_MAC_KEY_BYTES = 32;
572
+
573
+ /** @internal The context a KEM-derived protection key is bound to (RFC 9810 sec. 5.1.3.4). Written
574
+ * ONCE and read by both the protecting and the verifying half, because two copies of one derivation
575
+ * drift: the static string, the transaction identifier and any kemContext all feed the KDF, so a
576
+ * single byte of disagreement yields a key the peer cannot reproduce. The CMP module is EXPLICIT TAGS,
577
+ * so `[0]` wraps the OCTET STRING. */
578
+ function kemOtherInfo(transactionID, kemContext) {
579
+ var kids = [b.sequence([b.utf8(KEM_STATIC_STRING)]), b.octetString(transactionID)];
580
+ if (kemContext != null) guard.list.append(kids, b.explicit(0, b.octetString(kemContext)));
581
+ return b.sequence(kids);
582
+ }
583
+
584
+ /** @internal The shared secret key: HKDF over the KEM shared secret, with the DER KemOtherInfo as
585
+ * info and `len` as the output size the MAC algorithm needs. */
586
+ async function kemSharedKey(sharedSecret, len, transactionID, kemContext) {
587
+ var info = kemOtherInfo(transactionID, kemContext);
588
+ var ikm = await subtle.importKey("raw", sharedSecret, { name: "HKDF" }, false, ["deriveBits"]);
589
+ var bits = await subtle.deriveBits(
590
+ { name: "HKDF", hash: "SHA-256", salt: intrinsic.bufferAlloc(0), info: info }, ikm, len * 8);
591
+ return intrinsic.bufferFrom(bits);
592
+ }
593
+
594
+ /** @internal The protecting half of RFC 9810 sec. 5.1.3.4: the holder of the KEM private key
595
+ * decapsulates the ciphertext the peer sent, derives the shared secret key, and MACs the message with
596
+ * it. Decapsulation failure terminates the operation with the failInfo the section names, rather than
597
+ * falling through to another flavor. */
598
+ /** @internal The decapsulation key, from the shapes every other key option in this module accepts: a
599
+ * WebCrypto CryptoKey is adopted as it is, which is what `pki.key.generate` hands back, and an encoded
600
+ * key is decoded and imported. Any copy the decode makes is collected for the caller to wipe. */
601
+ async function _kemPrivateKey(rawKey, wcName, ownedKeyCopies) {
602
+ if (rawKey && typeof rawKey === "object" && !guard.bytes.isByteSource(rawKey) &&
603
+ typeof rawKey.type === "string" && rawKey.algorithm != null) {
604
+ if (rawKey.type !== "private") {
605
+ throw _err("cmp/bad-input", "opts.kem.key is a CryptoKey of type " + guard.text.showValue(rawKey.type) +
606
+ "; decapsulation needs the private key (type \"private\")");
607
+ }
608
+ return webcrypto.adoptKey(rawKey, { name: wcName }, ["decapsulateBits"], _signE, "bad-input");
609
+ }
610
+ var keyDer = signScheme.normalizePkcs8(rawKey, "opts.kem.key", _signE, ownedKeyCopies);
611
+ return subtle.importKey("pkcs8", keyDer, { name: wcName }, false, ["decapsulateBits"]);
612
+ }
613
+
614
+ /** @internal The KemBMParameter fields in the order sec. 5.1.3.4 gives them, with the optional
615
+ * kemContext between the KDF and the length. */
616
+ function _kemBmParameterKids(len, kemContext) {
617
+ var kids = [b.sequence([b.oid(oid.byName("hkdfWithSha256"))])];
618
+ if (kemContext != null) guard.list.append(kids, b.explicit(0, b.octetString(kemContext)));
619
+ guard.list.append(kids, b.integer(_bigInt(len)));
620
+ guard.list.append(kids, b.sequence([b.oid(oid.byName("hmacWithSHA256"))]));
621
+ return kids;
622
+ }
623
+
624
+ /** @internal The MAC the derived key drives, computed the same way on both halves. */
625
+ async function kemMac(sharedKey, protectedPartDer) {
626
+ var k = await subtle.importKey("raw", sharedKey, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
627
+ return intrinsic.bufferFrom(await subtle.sign({ name: "HMAC" }, k, protectedPartDer));
628
+ }
629
+
630
+ function _resolveKemProtection(kemSpec, message) {
631
+ if (!kemSpec || typeof kemSpec !== "object" || _isBuffer(kemSpec)) {
632
+ throw _err("cmp/bad-input", "opts.kem must be an object { key, ciphertext, kemAlgorithm, kemContext?, transactionID?, len? }");
633
+ }
634
+ guard.identifier.assertKnownKeys(kemSpec, KNOWN_KEM_KEYS, _err, "cmp/bad-input", "unknown opts.kem field ");
635
+ if (kemSpec.key == null) throw _err("cmp/bad-input", "opts.kem.key is the KEM private key the ciphertext was encapsulated to");
636
+ /** @internal Taken once, and decoded LATER: normalizing a PEM or a Uint8Array allocates a buffer
637
+ * holding the private key, and anything that throws between here and the MAC would leave it behind.
638
+ * The copy is therefore made inside the protected region below, where its cleanup runs on every
639
+ * exit; a caller-owned Buffer is only viewed and is never wiped. */
640
+ var rawKey = kemSpec.key;
641
+ var ct = _kemBytes(kemSpec.ciphertext, "opts.kem.ciphertext (the KEM ciphertext the peer sent)");
642
+ var algName = kemSpec.kemAlgorithm;
643
+ if (typeof algName !== "string") throw _err("cmp/bad-input", "opts.kem.kemAlgorithm names the KEM the ciphertext was produced under");
644
+ var algOid = oid.isDottedDecimal(algName) ? algName : oid.byName(algName);
645
+ var wcName = KEM_DECAPSULATE[guard.text.keyOf(algOid)];
646
+ if (!wcName) {
647
+ throw _err("cmp/unsupported-algorithm",
648
+ "unsupported KEM " + algName + " for KEM-based message protection (ML-KEM-512/768/1024)");
649
+ }
650
+ /** @internal The ASN.1 admits len 1, and a one-byte key is one an observer of a single message can
651
+ * search exhaustively, so the floor is the one this module already applies to a MAC key rather than
652
+ * the syntax's. */
653
+ var len = kemSpec.len == null ? KEM_MAC_KEY_BYTES : kemSpec.len;
654
+ if (typeof len !== "number" || !Number.isInteger(len) ||
655
+ len < constants.LIMITS.CMP_KEM_MIN_KEY_BYTES || len > constants.LIMITS.CMP_KEM_MAX_KEY_BYTES) {
656
+ throw _err("cmp/bad-input", "opts.kem.len is the derived key size in bytes, " +
657
+ constants.LIMITS.CMP_KEM_MIN_KEY_BYTES + ".." + constants.LIMITS.CMP_KEM_MAX_KEY_BYTES +
658
+ " (a shorter key would not carry the strength the MAC is meant to have)");
659
+ }
660
+ var kemContext = kemSpec.kemContext == null ? null
661
+ : _kemBytes(kemSpec.kemContext, "opts.kem.kemContext");
662
+ /** @internal "transactionID MUST be the value from the message containing the ciphertext", which is
663
+ * this message's own id in the ordinary flow and the peer's when it sent the ciphertext first, so
664
+ * the caller can name it. */
665
+ var txid = kemSpec.transactionID != null
666
+ ? _kemBytes(kemSpec.transactionID, "opts.kem.transactionID")
667
+ /** @internal `_build` has already refused a spec with no header, so this reads the header it
668
+ * verified rather than re-testing for one. */
669
+ : _kemBytes(message.header.transactionID,
670
+ "message.header.transactionID (a KEM-derived key is bound to it)");
671
+ return {
672
+ protectionAlgDer: b.sequence([b.oid(oid.byName("kemBasedMac")), b.sequence(_kemBmParameterKids(len, kemContext))]),
673
+ certDer: null,
674
+ computeBits: async function (protectedPartDer) {
675
+ var ss = null, ssk = null, ownedKeyCopies = [];
676
+ try {
677
+ try {
678
+ var priv = await _kemPrivateKey(rawKey, wcName, ownedKeyCopies);
679
+ ss = intrinsic.bufferFrom(await subtle.decapsulateBits({ name: wcName }, priv, ct));
680
+ } catch (e) {
681
+ if (e instanceof CmpError) throw e;
682
+ throw _err("cmp/bad-message-check",
683
+ "the KEM ciphertext did not decapsulate under opts.kem.key, so no protection key can be " +
684
+ "derived and the operation is terminated (RFC 9810 sec. 5.1.3.4 step 2)", e);
685
+ }
686
+ ssk = await kemSharedKey(ss, len, txid, kemContext);
687
+ return b.bitString(await kemMac(ssk, protectedPartDer), 0);
688
+ } finally {
689
+ var owned = [];
690
+ if (ss) guard.list.append(owned, ss);
691
+ if (ssk) guard.list.append(owned, ssk);
692
+ for (var ci = 0; ci < ownedKeyCopies.length; ci++) guard.list.append(owned, ownedKeyCopies[ci]);
693
+ ownedKeyCopies.length = 0;
694
+ if (owned.length) guard.secret.zeroizeAll(owned, CmpError, "cmp/bad-input", "the KEM shared secret");
695
+ }
696
+ },
697
+ };
698
+ }
699
+
700
+ function _resolveProtection(opts, message) {
549
701
  var hasSig = opts.key != null || opts.cert != null;
550
702
  var hasMac = opts.mac != null;
551
- if (hasSig && hasMac) throw _err("cmp/bad-input", "supply exactly one of { key, cert } (signature) or { mac } (PBMAC1), not both");
552
- if (!hasSig && !hasMac) throw _err("cmp/bad-input", "a PKIMessage requires protection: supply { key, cert } for a signature or { mac } for PBMAC1");
703
+ var hasKem = opts.kem != null;
704
+ if ((hasSig ? 1 : 0) + (hasMac ? 1 : 0) + (hasKem ? 1 : 0) > 1) {
705
+ throw _err("cmp/bad-input", "supply exactly one of { key, cert } (signature), { mac } (PBMAC1) or { kem } (KEM-based MAC), not more than one");
706
+ }
707
+ if (hasKem) return _resolveKemProtection(opts.kem, message);
708
+ if (!hasSig && !hasMac) throw _err("cmp/bad-input", "a PKIMessage requires protection: supply { key, cert } for a signature, { mac } for PBMAC1, or { kem } for a KEM-based MAC");
553
709
 
554
710
  if (hasSig) {
555
711
  if (opts.key == null || opts.cert == null) throw _err("cmp/bad-input", "signature protection requires both opts.key (the private key) and opts.cert (the signer certificate)");
@@ -621,8 +777,11 @@ async function _build(message, opts) {
621
777
  return "unknown message field " + JSON.stringify(k) + " (a message carries only header + body)";
622
778
  });
623
779
  var sigForm = opts.key != null || opts.cert != null, macForm = opts.mac != null;
780
+ var kemForm = opts.kem != null;
781
+ var formCount = (sigForm ? 1 : 0) + (macForm ? 1 : 0) + (kemForm ? 1 : 0);
624
782
  guard.identifier.assertKnownKeys(opts,
625
- sigForm === macForm ? KNOWN_OPTS_KEYS : sigForm ? KNOWN_OPTS_SIG_KEYS : KNOWN_OPTS_MAC_KEYS,
783
+ formCount !== 1 ? KNOWN_OPTS_KEYS
784
+ : sigForm ? KNOWN_OPTS_SIG_KEYS : macForm ? KNOWN_OPTS_MAC_KEYS : KNOWN_OPTS_KEM_KEYS,
626
785
  _err, "cmp/bad-input", function (k) {
627
786
  return "unknown opts field " + JSON.stringify(k) +
628
787
  (macForm && (k === "pss" || k === "digestAlgorithm")
@@ -632,7 +791,7 @@ async function _build(message, opts) {
632
791
  if (message.header == null) throw _err("cmp/bad-input", "message.header is required");
633
792
  if (message.body == null) throw _err("cmp/bad-input", "message.body is required");
634
793
 
635
- var prot = _resolveProtection(opts);
794
+ var prot = _resolveProtection(opts, message);
636
795
  var senderKey = opts.key;
637
796
 
638
797
  var bodyResult = await _encodeBody(message.body, senderKey, opts);
@@ -712,6 +871,13 @@ function _collectExtraCerts(opts, protCertDer) {
712
871
  * - `key` (Buffer|CryptoKey) + `cert` (Buffer): signature protection under the sender key; `cert` is
713
872
  * the signer certificate (its SPKI resolves the algorithm) and is placed in `extraCerts`.
714
873
  * - `mac` ({ secret, salt?, iterationCount?, prf?, keyLength? }): PBMAC1 protection from a shared secret.
874
+ * - `kem` ({ key, ciphertext, kemAlgorithm, kemContext?, transactionID?, len? }): KEM-based MAC
875
+ * protection (RFC 9810 sec. 5.1.3.4), for a sender whose key establishes secrets rather than
876
+ * signing. `key` is the KEM private key as a CryptoKey (what `pki.key.generate` returns), a
877
+ * PKCS#8 DER Buffer / Uint8Array, or a PEM string. `ciphertext` is what the peer encapsulated to
878
+ * it, `kemAlgorithm` names the ML-KEM
879
+ * parameter set it was produced under, and the derived key is bound to `transactionID` (this
880
+ * message's, unless the ciphertext arrived under another) and any `kemContext`.
715
881
  * - `extraCerts` (array of Buffer): additional certificates to carry in `extraCerts [1]`.
716
882
  * - `pem` (boolean|string): return a PEM `CMP` block instead of DER.
717
883
  * - `pss` (boolean) / `digestAlgorithm` (string): signature-protection algorithm options.
@@ -875,9 +1041,12 @@ function wellKnownUrl(base, opts) {
875
1041
  var rawBasePath = _beforeQueryOrFragment(_stripSchemeAuthority(String(base)));
876
1042
  if (rawBasePath !== "" && rawBasePath !== "/") throw _err("cmp/bad-url", "an RFC 8615 well-known URI is authority-rooted; the CMP base URL must have no path component (pass a full operation URL to transfer instead): " + JSON.stringify(String(base)));
877
1043
  var segs = [".well-known", "cmp"];
878
- if (opts.label != null) { segs.push("p"); segs.push(_wellKnownSeg(opts.label, "label")); }
879
- if (opts.operation != null) segs.push(_wellKnownSeg(opts.operation, "operation"));
880
- return u.origin + "/" + segs.join("/");
1044
+ if (opts.label != null) {
1045
+ guard.list.append(segs, "p");
1046
+ guard.list.append(segs, _wellKnownSeg(opts.label, "label"));
1047
+ }
1048
+ if (opts.operation != null) guard.list.append(segs, _wellKnownSeg(opts.operation, "operation"));
1049
+ return u.origin + "/" + intrinsic.join(segs, "/");
881
1050
  }
882
1051
 
883
1052
  /**
@@ -962,4 +1131,8 @@ module.exports = {
962
1131
  },
963
1132
  // @internal
964
1133
  decodeIdpDistributionPoint: decodeIdpDistributionPoint,
1134
+ /** @internal The KEM protection derivation, read by pki.cmp.verify so the two halves of one
1135
+ * key agreement cannot drift apart. */
1136
+ kemSharedKey: kemSharedKey,
1137
+ kemMac: kemMac,
965
1138
  };
@@ -77,6 +77,14 @@ var INFO_OPS = Object.assign(Object.create(null), {
77
77
  rootCaCert: { name: "rootCaCert", requestOid: "rootCaCert", responseOid: "rootCaKeyUpdate", value: "cert", read: "readRootCaKeyUpdate" },
78
78
  certReqTemplate: { name: "certReqTemplate", requestOid: "certReqTemplate", responseOid: "certReqTemplate", value: false, read: "readCertReqTemplate" },
79
79
  crlUpdate: { name: "crlUpdate", requestOid: "crlStatusList", responseOid: "crls", value: "crlStatus", read: "readCrls" },
80
+ /** @internal The KEM ciphertext a peer encapsulated to this client's KEM public key, which the
81
+ * client then decapsulates to protect its own messages (RFC 9810 sec. 5.3.19.18 / 5.1.3.4). The
82
+ * request carries no value; the answer carries the algorithm and the ciphertext. */
83
+ kemCiphertext: { name: "kemCiphertext", requestOid: "kemCiphertextInfo", responseOid: "kemCiphertextInfo", value: false, read: "readKemCiphertextInfo" },
84
+ });
85
+ var KEM_CIPHERTEXT_ALGORITHMS = Object.assign(Object.create(null));
86
+ ["id-ml-kem-512", "id-ml-kem-768", "id-ml-kem-1024"].forEach(function (n) {
87
+ KEM_CIPHERTEXT_ALGORITHMS[oid.byName(n)] = n;
80
88
  });
81
89
  var KNOWN_REVOKE_KEYS = Object.assign(Object.create(null), { certificate: 1, certDetails: 1, reason: 1 });
82
90
  var RSA_ARCS = ["rsaEncryption", "rsaSignatureWithripemd160", "id-TA-RSA-v1-5-SHA-256",
@@ -193,8 +201,14 @@ var CAPUBS_MAX = 2 * MAX_EXTRA_CERTS;
193
201
  var SESSION_MAX_INTERMEDIATES = constants.LIMITS.PATH_BUILD_MAX_CANDIDATES - CAPUBS_MAX - MAX_EXTRA_CERTS;
194
202
  var SESSION_MAX_INTERMEDIATES_MAC = constants.LIMITS.PATH_BUILD_MAX_CANDIDATES - CAPUBS_MAX;
195
203
  function _isRecoverableVerify(code) {
204
+ /** @internal `cmp/bad-sender-kid` belongs here for the same reason `cmp/signer-cert-not-found` does:
205
+ * a response whose extraCerts carry no certificate matching the declared key identifier is one this
206
+ * session may already hold the signer for. Retrying is safe because the fallback certificate is put
207
+ * through the same identifier check, so the retry can only succeed on a certificate the message
208
+ * actually names. */
196
209
  return code === "cmp/signer-cert-not-found" || code === "cmp/protection-failed" ||
197
- code === "cmp/sender-mismatch" || code === "cmp/untrusted-signer";
210
+ code === "cmp/sender-mismatch" || code === "cmp/untrusted-signer" ||
211
+ code === "cmp/bad-sender-kid";
198
212
  }
199
213
  function _responseExtraCerts(responseBytes) {
200
214
  var extra = schemaCmp.parse(responseBytes).extraCerts;
@@ -1341,6 +1355,25 @@ function session(opts) {
1341
1355
  }
1342
1356
 
1343
1357
  function _checkInfoValue(op, value, requestValue) {
1358
+ /** @internal A ciphertext is only useful if the client can decapsulate it, so the answer is held
1359
+ * to a KEM this toolkit establishes secrets under and to a non-empty ciphertext; anything else
1360
+ * could not be turned into a protection key (RFC 9810 sec. 5.3.19.18 / 5.1.3.4). */
1361
+ if (op.name === "kemCiphertext") {
1362
+ if (!KEM_CIPHERTEXT_ALGORITHMS[value.kem.oid]) {
1363
+ throw _err("cmp/bad-info-value", "a KEM ciphertext answer names " +
1364
+ (value.kem.name || value.kem.oid) + ", which this client cannot decapsulate under (ML-KEM-512/768/1024)");
1365
+ }
1366
+ /** @internal An ML-KEM ciphertext is a fixed size, so one of any other length could not be
1367
+ * decapsulated under the algorithm the answer names. Refusing it here reports the authority's
1368
+ * answer as malformed rather than handing back material that cannot be used. */
1369
+ var want = oid.kemParams(value.kem.oid);
1370
+ if (!value.ct || value.ct.length !== want.ct) {
1371
+ throw _err("cmp/bad-info-value", "a KEM ciphertext answer for " +
1372
+ (value.kem.name || value.kem.oid) + " carries " + (value.ct ? value.ct.length : 0) +
1373
+ " bytes, and that algorithm's ciphertext is " + want.ct);
1374
+ }
1375
+ return value;
1376
+ }
1344
1377
  if (op.name === "rootCaCert") {
1345
1378
  if (value.newWithOld == null) throw _err("cmp/bad-info-value", "a rootCaKeyUpdate response must carry newWithOld -- the certificate that lets an entity trusting the OLD root gain trust in the new one (RFC 9483 sec. 4.3.2)");
1346
1379
  return _checkRootCaKeyUpdate(value, requestValue);
package/lib/cmp-verify.js CHANGED
@@ -51,8 +51,11 @@ var _certExtDecoders = pkix.certExtensionDecoders(NS).byOid;
51
51
 
52
52
  var KNOWN_VERIFY_OPTS = intrinsic.assign(intrinsic.create(null), {
53
53
  sharedSecret: 1, signerCert: 1, trustAnchors: 1, intermediates: 1, time: 1,
54
- transactionID: 1, expectRecipNonce: 1, revocationChecker: 1, maxIterations: 1,
54
+ transactionID: 1, expectRecipNonce: 1, revocationChecker: 1, maxIterations: 1, kem: 1,
55
+ messageTimeTolerance: 1,
55
56
  });
57
+ var KNOWN_KEM_VERIFY_KEYS = intrinsic.assign(intrinsic.create(null),
58
+ { sharedSecret: 1, transactionID: 1 });
56
59
 
57
60
  var PRF_HASH = _create(null);
58
61
  PRF_HASH[oid.byName("hmacWithSHA256")] = "SHA-256";
@@ -68,7 +71,7 @@ var PBMAC1_KEYLEN_MAX = 1024;
68
71
  var PRF_HLEN = intrinsic.assign(intrinsic.create(null), { "SHA-256": 32, "SHA-384": 48, "SHA-512": 64 });
69
72
 
70
73
  var UNSUPPORTED_MAC_OIDS = _create(null);
71
- ["passwordBasedMac", "dhBasedMac", "kemBasedMac"].forEach(function (n) {
74
+ ["passwordBasedMac", "dhBasedMac"].forEach(function (n) {
72
75
  var o = oid.byName(n);
73
76
  if (o) UNSUPPORTED_MAC_OIDS[o] = n;
74
77
  });
@@ -144,6 +147,30 @@ function _sanGeneralNames(parsed) {
144
147
  return [];
145
148
  }
146
149
 
150
+ /** @internal An anonymous sender: the NULL-DN a requester uses when it knows nothing about its own
151
+ * name (RFC 9810 sec. 5.1.1), encoded as a directoryName with no relative names. */
152
+ function _isNullDnSender(sender) {
153
+ return !!sender && sender.tagClass === "context" && sender.tagNumber === 4 &&
154
+ !!sender.value && _isArray(sender.value.rdns) && sender.value.rdns.length === 0;
155
+ }
156
+
157
+ /** @internal The commonName of a sender given as a directoryName, which is the name a MAC-protected
158
+ * message identifies its shared secret by (RFC 9483 sec. 4.1.5). A sender in any other GeneralName
159
+ * form, or one carrying no commonName, names nothing a senderKID could equal. */
160
+ function _senderCommonName(sender) {
161
+ if (!sender || sender.tagClass !== "context" || sender.tagNumber !== 4) return null;
162
+ var rdns = sender.value && sender.value.rdns;
163
+ if (!_isArray(rdns)) return null;
164
+ var cnOid = oid.byName("commonName");
165
+ for (var i = 0; i < rdns.length; i++) {
166
+ var rdn = rdns[i];
167
+ for (var j = 0; j < rdn.length; j++) {
168
+ if (rdn[j].type === cnOid && typeof rdn[j].value === "string") return rdn[j].value;
169
+ }
170
+ }
171
+ return null;
172
+ }
173
+
147
174
  function _senderBoundToCert(sender, parsed) {
148
175
  if (!sender || !sender.bytes) return false;
149
176
  var subjectRdns = parsed.subject.rdns;
@@ -309,6 +336,15 @@ function _uriEqual(a, b) {
309
336
  return na === nb;
310
337
  }
311
338
 
339
+ /** @internal Whether a declared key identifier names this certificate. Absent means the rule does not
340
+ * apply; present with no subjectKeyIdentifier to compare means it cannot be satisfied, so the message
341
+ * is refused rather than admitted for want of a value. */
342
+ function _senderKidMatchesCert(senderKID, parsed) {
343
+ if (senderKID == null) return true;
344
+ var ski = _certSki(parsed);
345
+ return ski != null && guard.crypto.constantTimeEqual(ski, senderKID);
346
+ }
347
+
312
348
  function _resolveSignerCert(m, opts, extra) {
313
349
  var senderKID = m.header.senderKID;
314
350
  function _signerObj(der, p) { return { der: der, spki: p.subjectPublicKeyInfo.bytes, subject: _subjectDn(p), parsed: p }; }
@@ -316,10 +352,7 @@ function _resolveSignerCert(m, opts, extra) {
316
352
  var p;
317
353
  try { p = x509.parse(der); }
318
354
  catch (_e) { return null; }
319
- if (senderKID != null) {
320
- var ski = _certSki(p);
321
- if (ski == null || !guard.crypto.constantTimeEqual(ski, senderKID)) return null;
322
- }
355
+ if (!_senderKidMatchesCert(senderKID, p)) return null;
323
356
  return _signerObj(der, p);
324
357
  }
325
358
  if (opts.signerCert != null) {
@@ -359,6 +392,22 @@ function _headerChecks(m, opts) {
359
392
  if (opts.expectRecipNonce != null && !_bufEq(m.header.recipNonce, opts.expectRecipNonce)) {
360
393
  return { code: "cmp/bad-recip-nonce", reason: "header.recipNonce does not echo the expected sender nonce" };
361
394
  }
395
+ /** @internal A stated window is checked in both directions: a clock runs fast as readily as slow, and
396
+ * a message dated ahead of the receiver is as much a replay signal as one dated behind it. */
397
+ if (opts.messageTimeTolerance != null && m.header.messageTime != null) {
398
+ var at = guard.time.instantOf(opts.time != null ? opts.time : new _Date());
399
+ var sent = guard.time.instantOf(m.header.messageTime);
400
+ if (!intrinsic.isFinite(at) || !intrinsic.isFinite(sent)) {
401
+ return { code: "cmp/bad-message-time", reason: "the header messageTime could not be read as an instant to compare against the verification time (RFC 9483 sec. 3.5)" };
402
+ }
403
+ // allow:nan-date-comparison-unguarded -- both instants are finite by the check above
404
+ var skew = (at > sent ? at - sent : sent - at) / 1000;
405
+ if (skew > opts.messageTimeTolerance) {
406
+ return { code: "cmp/bad-message-time", reason: "the header messageTime is " + intrinsic.floor(skew) +
407
+ " seconds from the verification time, outside the " + opts.messageTimeTolerance +
408
+ "-second window this caller accepts (RFC 9483 sec. 3.5)" };
409
+ }
410
+ }
362
411
  return null;
363
412
  }
364
413
 
@@ -375,6 +424,66 @@ function _keyUsageAllowsSigning(parsed) {
375
424
  return true;
376
425
  }
377
426
 
427
+ /** @internal The verifying half of RFC 9810 sec. 5.1.3.4. The peer that encapsulated holds the same
428
+ * shared secret, and derives the key from it through the derivation `pki.cmp.build` uses, so the two
429
+ * halves cannot disagree about the context. The transaction identifier the context binds to is the one
430
+ * from the message that carried the ciphertext, which the caller names when it is not this message's. */
431
+ async function _verifyKem(m, protectedPart, protectionAlg, protection, opts) {
432
+ var kemOpts = opts.kem;
433
+ if (!kemOpts) {
434
+ throw _err("cmp/bad-input", "a KEM-protected message requires opts.kem { sharedSecret, transactionID? }");
435
+ }
436
+ if (!_nonEmptySecret(kemOpts.sharedSecret)) {
437
+ throw _err("cmp/bad-input", "opts.kem.sharedSecret is the KEM shared secret the peer encapsulated");
438
+ }
439
+ if (protectionAlg.parameters === null) {
440
+ return _fail(m, "kem", protectionAlg, "cmp/protection-failed", "the KEM protectionAlg carries no KemBMParameter (RFC 9810 sec. 5.1.3.4)");
441
+ }
442
+ var params;
443
+ try { params = cmp.readKemBMParameter(protectionAlg.parameters); }
444
+ catch (e) {
445
+ return _fail(m, "kem", protectionAlg, e instanceof CmpError ? e.code : "cmp/protection-failed",
446
+ "the KemBMParameter did not decode: " + ((e && e.message) || e));
447
+ }
448
+ if (params.kdf.oid !== oid.byName("hkdfWithSha256")) {
449
+ return _fail(m, "kem", protectionAlg, "cmp/unsupported-algorithm",
450
+ "unsupported KEM key-derivation " + _stringify(params.kdf.name || params.kdf.oid) + " (HKDF-SHA256 only)");
451
+ }
452
+ if (params.mac.oid !== oid.byName("hmacWithSHA256")) {
453
+ return _fail(m, "kem", protectionAlg, "cmp/unsupported-algorithm",
454
+ "unsupported KEM message-authentication algorithm " + _stringify(params.mac.name || params.mac.oid) + " (HMAC-SHA256 only)");
455
+ }
456
+ /** @internal The sender chooses `len`, so a peer could name a key short enough to search. The
457
+ * message is refused rather than verified under a key that carries no strength. */
458
+ if (params.len < constants.LIMITS.CMP_KEM_MIN_KEY_BYTES) {
459
+ return _fail(m, "kem", protectionAlg, "cmp/protection-failed",
460
+ "the KemBMParameter names a " + params.len + "-byte protection key, and a key shorter than " +
461
+ constants.LIMITS.CMP_KEM_MIN_KEY_BYTES + " bytes would not carry the strength the MAC is meant to have");
462
+ }
463
+ var txid = kemOpts.transactionID != null
464
+ ? guard.bytes.view(kemOpts.transactionID, CmpError, "cmp/bad-input", "opts.kem.transactionID")
465
+ : m.header.transactionID;
466
+ if (txid == null) {
467
+ return _fail(m, "kem", protectionAlg, "cmp/protection-failed",
468
+ "a KEM-derived key is bound to the transaction identifier of the message that carried the ciphertext, and neither this message nor opts.kem names one");
469
+ }
470
+ var secret = guard.bytes.view(kemOpts.sharedSecret, CmpError, "cmp/bad-input", "opts.kem.sharedSecret");
471
+ var ssk = null;
472
+ try {
473
+ ssk = await cmpBuild.kemSharedKey(secret, params.len, txid, params.kemContext);
474
+ var computed = await cmpBuild.kemMac(ssk, protectedPart);
475
+ if (!guard.crypto.constantTimeEqual(computed, protection.bytes)) {
476
+ return _fail(m, "kem", protectionAlg, "cmp/protection-failed",
477
+ "the KEM-based MAC does not verify (a different shared secret, a different derivation context, or a tampered ProtectedPart)");
478
+ }
479
+ } finally {
480
+ if (ssk) guard.secret.zeroize(ssk, CmpError, "cmp/bad-input", "the KEM-derived protection key");
481
+ }
482
+ var khc = _headerChecks(m, opts);
483
+ if (khc) return _fail(m, "kem", protectionAlg, khc.code, khc.reason);
484
+ return _ok(m, "kem", protectionAlg, true, null);
485
+ }
486
+
378
487
  async function _verifyMac(m, protectedPart, protectionAlg, protection, opts) {
379
488
  if (protectionAlg.parameters === null) {
380
489
  return _fail(m, "mac", protectionAlg, "cmp/protection-failed", "the PBMAC1 protectionAlg carries no PBMAC1-params (RFC 9579 sec. 4)");
@@ -398,6 +507,23 @@ async function _verifyMac(m, protectedPart, protectionAlg, protection, opts) {
398
507
  if (!guard.crypto.constantTimeEqual(computed, protection.bytes)) {
399
508
  return _fail(m, "mac", protectionAlg, "cmp/protection-failed", "the PBMAC1 MAC does not verify (a wrong shared secret or a tampered ProtectedPart)");
400
509
  }
510
+ /** @internal Under MAC protection the sender names the shared secret, and sec. 4.1.5 requires the
511
+ * senderKID to carry that same name: the identifier and the name the message is attributed to are
512
+ * one value, so a message pointing them at different entities is refused. */
513
+ /** @internal The name rule governs a sender that HAS a name. An anonymous NULL-DN sender carries a
514
+ * reference number instead (RFC 9810 sec. 5.1.1), which names no commonName to equal, so it is
515
+ * required to be present above and left uncompared here rather than refused for failing a match the
516
+ * base protocol does not ask of it. */
517
+ if (m.header.senderKID != null && !_isNullDnSender(m.header.sender)) {
518
+ var cn = _senderCommonName(m.header.sender);
519
+ if (cn === null || !guard.crypto.constantTimeEqual(_bufferFrom(cn, "utf8"), m.header.senderKID)) {
520
+ return _fail(m, "mac", protectionAlg, "cmp/bad-sender-kid",
521
+ "the header senderKID must carry the same name as the commonName of the sender field, which " +
522
+ "is how a MAC-protected message identifies the shared secret it was protected with " +
523
+ "(RFC 9483 sec. 4.1.5)");
524
+ }
525
+ }
526
+
401
527
  var hc = _headerChecks(m, opts);
402
528
  if (hc) return _fail(m, "mac", protectionAlg, hc.code, hc.reason);
403
529
  return _ok(m, "mac", protectionAlg, true, null);
@@ -423,7 +549,17 @@ function _capWork(iterationCount, salt, keyLength, prfHash, opts) {
423
549
  async function _verifySignature(m, protectedPart, protectionAlg, protection, opts) {
424
550
  var extra = _boundExtraCerts(m.extraCerts);
425
551
  var signer = _resolveSignerCert(m, opts, extra);
426
- if (!signer) return _fail(m, "signature", protectionAlg, "cmp/signer-cert-not-found", "no signer certificate resolved (opts.signerCert, senderKID, or extraCerts)");
552
+ if (!signer) {
553
+ /** @internal Selecting from `extraCerts` narrows by the declared key identifier, so "nothing
554
+ * matched" and "nothing was offered" are different failures. Reporting them apart keeps one
555
+ * defect from carrying two codes depending on how the certificate would have arrived. */
556
+ if (m.header.senderKID != null && extra.length) {
557
+ return _fail(m, "signature", protectionAlg, "cmp/bad-sender-kid",
558
+ "no certificate in extraCerts carries the subjectKeyIdentifier the header senderKID declares, " +
559
+ "so nothing offered identifies the key that would verify the protection (RFC 9483 sec. 3.5)");
560
+ }
561
+ return _fail(m, "signature", protectionAlg, "cmp/signer-cert-not-found", "no signer certificate resolved (opts.signerCert, senderKID, or extraCerts)");
562
+ }
427
563
 
428
564
  var ok = await _engine.verifyWithSpki(protectionAlg, protection.bytes, signer.spki, protectedPart);
429
565
  if (ok !== true) return _fail(m, "signature", protectionAlg, "cmp/protection-failed", "the protection signature does not verify over the ProtectedPart under the declared protectionAlg", signer);
@@ -431,6 +567,16 @@ async function _verifySignature(m, protectedPart, protectionAlg, protection, opt
431
567
  if (!_senderBoundToCert(m.header.sender, signer.parsed)) {
432
568
  return _fail(m, "signature", protectionAlg, "cmp/sender-mismatch", "the header sender field does not match the signer certificate subject, or (for an empty subject) a subjectAltName entry (RFC 9483 sec. 3.1, RFC 5280 sec. 7.1)", signer);
433
569
  }
570
+ /** @internal The declared key identifier is checked against the certificate whose key ACTUALLY
571
+ * verified, on every route that certificate arrives by. Selecting from `extraCerts` already matches
572
+ * it while choosing, and a caller-supplied certificate reaches the same rule here, so a message
573
+ * naming one key and signed by another is refused however the verifier came by the certificate
574
+ * (RFC 9483 sec. 3.5). */
575
+ if (!_senderKidMatchesCert(m.header.senderKID, signer.parsed)) {
576
+ return _fail(m, "signature", protectionAlg, "cmp/bad-sender-kid",
577
+ "the header senderKID does not identify the certificate whose key verified the protection: it " +
578
+ "must equal that certificate's subjectKeyIdentifier (RFC 9483 sec. 3.5)", signer);
579
+ }
434
580
 
435
581
  var hc = _headerChecks(m, opts);
436
582
  if (hc) return _fail(m, "signature", protectionAlg, hc.code, hc.reason, signer);
@@ -561,15 +707,48 @@ function _assertEchoBytes(v, name) {
561
707
  throw _err("cmp/bad-input", "opts." + name + " must be a Buffer / Uint8Array");
562
708
  }
563
709
 
564
- function _fixSecret(v, made) {
710
+ /** @internal A shared secret, taken once and registered for wiping. Every byte-source shape is
711
+ * accepted, not only the ones a caller happens to have converted: a KEM encapsulation hands back an
712
+ * ArrayBuffer, and a secret read from a larger allocation arrives as a view over it. */
713
+ function _fixSecret(v, made, label) {
565
714
  if (typeof v === "string") {
566
715
  var fromString = _bufferFrom(v, "utf8");
567
716
  _append(made, fromString);
568
717
  return fromString;
569
718
  }
570
- var copy = _fixByteish(v, "sharedSecret");
571
- if (util.types.isUint8Array(copy)) _append(made, copy);
572
- return copy;
719
+ if (v != null && guard.bytes.isByteSource(v)) {
720
+ var snap = guard.bytes.snapshotSource(v, CmpError, "cmp/bad-input", "opts." + (label || "sharedSecret"));
721
+ _append(made, snap);
722
+ return snap;
723
+ }
724
+ return v;
725
+ }
726
+
727
+ /** @internal The freshness window, in seconds. RFC 9483 sec. 3.5 leaves the threshold to the use case
728
+ * and lists the check under local policy, so it is stated by the caller rather than defaulted: a
729
+ * window this library invented would refuse conforming messages from a peer whose clock is merely
730
+ * further off than that number. */
731
+ function _fixTolerance(v) {
732
+ if (v == null) return null;
733
+ if (typeof v !== "number" || !intrinsic.isFinite(v) || v < 0) {
734
+ throw _err("cmp/bad-input", "opts.messageTimeTolerance is the accepted messageTime skew in seconds, a non-negative number");
735
+ }
736
+ return v;
737
+ }
738
+
739
+ /** @internal The KEM verification material, taken once at the door like every other caller value: the
740
+ * shared secret is copied and registered for wiping, and the transaction identifier is snapshot, so
741
+ * neither can answer differently when the derivation reads it. */
742
+ function _fixKem(v, made) {
743
+ if (v == null) return null;
744
+ if (typeof v !== "object" || guard.bytes.isByteSource(v)) {
745
+ throw _err("cmp/bad-input", "opts.kem must be an object { sharedSecret, transactionID? }");
746
+ }
747
+ guard.identifier.assertKnownKeys(v, KNOWN_KEM_VERIFY_KEYS, _err, "cmp/bad-input", "unknown opts.kem field ");
748
+ return {
749
+ sharedSecret: _fixSecret(v.sharedSecret, made, "kem.sharedSecret"),
750
+ transactionID: _fixByteish(v.transactionID, "kem.transactionID"),
751
+ };
573
752
  }
574
753
 
575
754
  function _fixCertList(v, label) {
@@ -592,8 +771,13 @@ function _fixCertList(v, label) {
592
771
  for (var i = 0; i < n; i++) _append(out, _fixByteish(v[i], label + "[" + i + "]"));
593
772
  return out;
594
773
  }
774
+ /** @internal The verification instant, copied so a caller cannot move it after the fact. A value that
775
+ * is not a Date is refused here rather than carried into a comparison that would throw from whichever
776
+ * check happened to read it first. */
595
777
  function _fixTime(v) {
596
- return guard.time.isDate(v) ? new _Date(guard.time.instantOf(v)) : v;
778
+ if (v == null) return v;
779
+ if (!guard.time.isDate(v)) throw _err("cmp/bad-input", "opts.time must be a Date");
780
+ return new _Date(guard.time.instantOf(v));
597
781
  }
598
782
  function _fixVerifyOptions(opts, made) {
599
783
  if (opts == null) opts = {};
@@ -609,6 +793,8 @@ function _fixVerifyOptions(opts, made) {
609
793
  expectRecipNonce: _fixByteish(opts.expectRecipNonce, "expectRecipNonce"),
610
794
  revocationChecker: opts.revocationChecker,
611
795
  maxIterations: opts.maxIterations,
796
+ kem: _fixKem(opts.kem, made),
797
+ messageTimeTolerance: _fixTolerance(opts.messageTimeTolerance),
612
798
  };
613
799
 
614
800
  _assertEchoBytes(f.transactionID, "transactionID");
@@ -634,9 +820,17 @@ async function _verify(message, opts) {
634
820
  }
635
821
 
636
822
  var isMac = protectionAlg.oid === oid.byName("pbmac1");
823
+ var isKem = protectionAlg.oid === oid.byName("kemBasedMac");
637
824
  var hasSigCred = opts.signerCert != null || opts.trustAnchors != null;
638
825
  var hasSecret = opts.sharedSecret != null;
639
826
 
827
+ if (isKem) {
828
+ if (hasSigCred) throw _err("cmp/bad-input", "a KEM-protected message takes opts.kem, not signerCert/trustAnchors");
829
+ if (hasSecret) throw _err("cmp/bad-input", "a KEM-protected message takes opts.kem.sharedSecret, not opts.sharedSecret");
830
+ return _verifyKem(m, protectedPart, protectionAlg, protection, opts);
831
+ }
832
+ if (opts.kem != null) throw _err("cmp/bad-input", "opts.kem verifies a KEM-based MAC, and this message is protected another way");
833
+
640
834
  if (isMac) {
641
835
  if (hasSigCred) throw _err("cmp/bad-input", "a MAC-protected message takes opts.sharedSecret, not signerCert/trustAnchors");
642
836
  if (!_nonEmptySecret(opts.sharedSecret)) throw _err("cmp/bad-input", "a PBMAC1-protected message requires a non-empty opts.sharedSecret");
@@ -671,6 +865,14 @@ async function _verify(message, opts) {
671
865
  * carry at least 128 bits; a violation is a `{ valid: false }` verdict carrying `cmp/unsupported-version`,
672
866
  * `cmp/bad-transaction-id`, or `cmp/bad-sender-nonce`.
673
867
  *
868
+ * A present `senderKID` must identify the key material that verified the protection (RFC 9483
869
+ * sec. 3.5), whichever way that key was resolved. Under signature protection it must equal the
870
+ * `subjectKeyIdentifier` of the certificate whose key verified, so a certificate supplied as
871
+ * `opts.signerCert` is held to the declared identifier exactly as one selected out of `extraCerts` is,
872
+ * and a certificate carrying no `subjectKeyIdentifier` cannot satisfy one. Under MAC protection it must
873
+ * carry the same name as the `commonName` of the sender field, which is how such a message names the
874
+ * shared secret it was protected with (sec. 4.1.5). A mismatch is a `cmp/bad-sender-kid` verdict.
875
+ *
674
876
  * Returns a verdict (never a bare boolean): `{ valid, trusted, protectionType, protectionAlg, signer,
675
877
  * transactionID, senderNonce, recipNonce, header, body, code?, reason? }`. `valid` is whether the
676
878
  * protection is cryptographically intact under the declared algorithm; `trusted` is whether a MAC secret
@@ -683,6 +885,14 @@ async function _verify(message, opts) {
683
885
  *
684
886
  * @opts
685
887
  * - `sharedSecret` (string|Buffer) -- the PBMAC1 secret; REQUIRED for a MAC-protected message (UTF-8).
888
+ * - `messageTimeTolerance` (number) -- the accepted `messageTime` skew in seconds. RFC 9483
889
+ * sec. 3.5 requires a present `messageTime` to be close to the receiver's current time but leaves
890
+ * the threshold to the use case, so stating it turns the check on; a message outside the window in
891
+ * either direction is a `cmp/bad-message-time` verdict. Absent, the `messageTime` is not judged.
892
+ * - `kem` ({ sharedSecret, transactionID? }) -- REQUIRED for a KEM-protected message (RFC 9810
893
+ * sec. 5.1.3.4). `sharedSecret` is what this side encapsulated to the sender's KEM public key, and
894
+ * `transactionID` names the message that carried the ciphertext when it was not this one. The
895
+ * verdict's `protectionType` is `kem`.
686
896
  * - `signerCert` (Buffer|PEM) -- the expected signature signer certificate (else resolved from
687
897
  * `extraCerts` by `senderKID` or, per RFC 9483 sec. 3.3, `extraCerts[0]`).
688
898
  * - `trustAnchors` (Buffer|Buffer[]|PEM) -- when present the signer certificate is FULLY path-validated
package/lib/constants.js CHANGED
@@ -125,6 +125,8 @@ var LIMITS = Object.assign(Object.create(null), {
125
125
  SCT_MAX_BYTES: BYTES.kib(64) + 1,
126
126
  SCT_MAX_COUNT: 256,
127
127
  CMS_MAX_KARI_ENCRYPTED_KEYS: 64,
128
+ CMP_KEM_MAX_KEY_BYTES: 1024,
129
+ CMP_KEM_MIN_KEY_BYTES: 20,
128
130
  MERKLE_MAX_PROOF_NODES: 65,
129
131
  PROXY_MAX_TLS_ANCHORS: 256,
130
132
  PATH_MAX_CERTS: 100,
package/lib/schema-cmp.js CHANGED
@@ -43,6 +43,7 @@ var cms = require("./schema-cms.js");
43
43
  var crmf = require("./schema-crmf.js");
44
44
  var frameworkError = require("./framework-error.js");
45
45
  var guard = require("./guard-all.js");
46
+ var constants = require("./constants");
46
47
 
47
48
  var CmpError = frameworkError.CmpError;
48
49
  var PemError = frameworkError.PemError;
@@ -101,6 +102,40 @@ var GENERAL_NAME = pkix.generalName(NS, { decodeValue: true });
101
102
  var ALG_ID = pkix.algorithmIdentifier(NS);
102
103
  var EXTENSIONS = pkix.extensions(NS);
103
104
 
105
+ /** @internal The parameters of a KEM-based MAC protectionAlg (RFC 9810 sec. 5.1.3.4). `len` is the
106
+ * size of the key the KDF produces, and it is the size the MAC algorithm needs, so the two travel
107
+ * together and a verifier derives exactly what the protector derived. */
108
+ var KEM_BM_PARAMETER = schema.seq([
109
+ schema.field("kdf", ALG_ID),
110
+ /** @internal The CMP module is DEFINITIONS EXPLICIT TAGS, so `[0]` wraps the OCTET STRING rather
111
+ * than replacing its tag. */
112
+ schema.optional("kemContext", schema.octetString(), { tag: 0, explicit: true }),
113
+ schema.field("len", schema.integerLeaf()),
114
+ schema.field("mac", ALG_ID),
115
+ ], {
116
+ assert: "sequence", arity: { min: 3, max: 4 }, code: "cmp/bad-kem-data", what: "KemBMParameter",
117
+ build: function (m, ctx) {
118
+ var n = guard.range.int(m.fields.len.value, 1n, BigInt(constants.LIMITS.CMP_KEM_MAX_KEY_BYTES),
119
+ ctx.E, "cmp/bad-kem-data", "a KemBMParameter len");
120
+ return {
121
+ kdf: m.fields.kdf.value.result,
122
+ kemContext: m.fields.kemContext.present ? m.fields.kemContext.value : null,
123
+ len: n,
124
+ mac: m.fields.mac.value.result,
125
+ };
126
+ },
127
+ });
128
+
129
+ /** @internal The KEM ciphertext a peer sends so the holder of the KEM private key can derive the same
130
+ * secret (RFC 9810 sec. 5.3.19.18). */
131
+ var KEM_CIPHERTEXT_INFO = schema.seq([
132
+ schema.field("kem", ALG_ID),
133
+ schema.field("ct", schema.octetString()),
134
+ ], {
135
+ assert: "sequence", arity: { exact: 2 }, code: "cmp/bad-kem-ciphertext", what: "KemCiphertextInfo",
136
+ build: function (m) { return { kem: m.fields.kem.value.result, ct: m.fields.ct.value }; },
137
+ });
138
+
104
139
 
105
140
  var INFO_TYPE_AND_VALUE = schema.seq([
106
141
  schema.field("infoType", schema.oidLeaf()),
@@ -835,6 +870,14 @@ function matches(root) {
835
870
  return schema.isContextInRange(body, 0, 26) && !!body.children;
836
871
  }
837
872
 
873
+ /** @internal One embedded KEM structure, read under this module's namespace so every field of it
874
+ * reports in the CMP domain rather than the codec's. */
875
+ function _readKem(sch, der, code, what) {
876
+ return schema.embeddedDer(sch, der, NS, { code: code, what: what }).result;
877
+ }
878
+ function readKemBMParameter(p) { return _readKem(KEM_BM_PARAMETER, p, "cmp/bad-kem-data", "KemBMParameter"); }
879
+ function readKemCiphertextInfo(d) { return _readKem(KEM_CIPHERTEXT_INFO, d, "cmp/bad-kem-ciphertext", "KemCiphertextInfo"); }
880
+
838
881
  module.exports = {
839
882
  parse: parse,
840
883
  pemDecode: pemDecode,
@@ -847,4 +890,6 @@ module.exports = {
847
890
  readCrls: readCrls,
848
891
  readAlgorithmIdentifier: readAlgorithmIdentifier,
849
892
  readName: readName,
893
+ readKemBMParameter: readKemBMParameter,
894
+ readKemCiphertextInfo: readKemCiphertextInfo,
850
895
  };
@@ -164,10 +164,23 @@ function _assertKeyMatchesScheme(key, imp, E) {
164
164
  if (imp.hash && (!ka.hash || ka.hash.name !== imp.hash)) throw E("bad-input", "the signer CryptoKey hash (" + (ka.hash && ka.hash.name) + ") does not match the signing digest (" + imp.hash + ")");
165
165
  if (imp.namedCurve && ka.namedCurve !== imp.namedCurve) throw E("bad-input", "the signer CryptoKey curve (" + ka.namedCurve + ") does not match the certificate curve (" + imp.namedCurve + ")");
166
166
  }
167
- function _normPkcs8(k, label, E) {
167
+ /** @internal `owned`, when given, collects the copies this makes of the caller's key so the caller can
168
+ * wipe them: a Buffer is viewed and stays the caller's, while a Uint8Array or a PEM string produces a
169
+ * new buffer holding the private key. The branch is taken once here, so no caller has to re-derive
170
+ * which shape it passed. */
171
+ function _normPkcs8(k, label, E, owned) {
168
172
  if (_isBuffer(k)) return guard.bytes.view(k, E, "bad-input", label);
169
- if (_isU8(k)) return guard.bytes.snapshot(k, E, "bad-input", label);
170
- if (typeof k === "string") { try { return pkcs8.pemDecode(k); } catch (e) { throw E("bad-input", label + " PEM could not be decoded", e); } }
173
+ if (_isU8(k)) {
174
+ var snap = guard.bytes.snapshot(k, E, "bad-input", label);
175
+ if (owned) guard.list.append(owned, snap);
176
+ return snap;
177
+ }
178
+ if (typeof k === "string") {
179
+ var der;
180
+ try { der = pkcs8.pemDecode(k); } catch (e) { throw E("bad-input", label + " PEM could not be decoded", e); }
181
+ if (owned) guard.list.append(owned, der);
182
+ return der;
183
+ }
171
184
  throw E("bad-input", label + " must be a PKCS#8 DER Buffer, Uint8Array, or PEM string");
172
185
  }
173
186
  function _normCompositeKeys(key, comp, E) {
@@ -220,6 +233,9 @@ function signOverTbs(scheme, key, signedBytes, E) {
220
233
 
221
234
  module.exports = {
222
235
  resolveSignScheme: resolveSignScheme,
236
+ /** @internal A PKCS#8 private key from the shapes every signer option accepts, so a verb that takes
237
+ * a private key for something other than signing reads it the same way. */
238
+ normalizePkcs8: _normPkcs8,
223
239
  pssSpkiPinnedHash: pssSpkiPinnedHash,
224
240
  signOverTbs: signOverTbs,
225
241
  MLDSA_SUITABLE_DIGEST: MLDSA_SUITABLE_DIGEST,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.49",
3
+ "version": "0.6.51",
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:082f242e-4786-4518-b201-8797b47662eb",
5
+ "serialNumber": "urn:uuid:d9015ac6-f8a1-409f-9e1f-5ae1fc7491a1",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-07T02:07:15.421Z",
8
+ "timestamp": "2026-09-07T06:27:34.397Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/pki@0.6.49",
22
+ "bom-ref": "@blamejs/pki@0.6.51",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.49",
25
+ "version": "0.6.51",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
29
- "purl": "pkg:npm/%40blamejs/pki@0.6.49",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.51",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/pki@0.6.49",
57
+ "ref": "@blamejs/pki@0.6.51",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]