@blamejs/pki 0.6.48 → 0.6.50

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,44 @@ 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.50 — 2026-09-07
8
+
9
+ A client whose key can only establish secrets can now authenticate its CMP messages with that key.
10
+
11
+ ### Added
12
+
13
+ - 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.
14
+ - 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.
15
+ - 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.
16
+ - 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.
17
+ - 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.
18
+ - 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.
19
+
20
+ ### Changed
21
+
22
+ - 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.
23
+ - 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.
24
+
25
+ ## v0.6.49 — 2026-09-07
26
+
27
+ A key that cannot sign for itself can still prove possession, by answering the authority's encrypted challenge.
28
+
29
+ ### Added
30
+
31
+ - pki.schema.cmc.parse decodes the two controls of the challenge-response proof of possession (RFC 5272 section 6.7). An Encrypted POP control surfaces as encryptedPOP with its request, its enveloped challenge, the two algorithm identifiers and the witness; a Decrypted POP control surfaces as decryptedPOP with its body part, algorithm and proof. The enveloped challenge is surfaced as the bytes it arrived as, since it is opened with key material the parser does not hold. Both algorithm identifiers keep their parameters, so a client answers with what it was sent. A control of either kind that is not the structure the section defines is refused with cmc/bad-pop-challenge. The two travel in opposite directions, so an Encrypted POP in a request or a Decrypted POP in a response is refused with cmc/control-misplaced. The challenge is held to what a client would have to answer: its envelope to the CMS EnvelopedData definition, and the request it quotes to the definition of the arm it uses, so a challenge nothing could answer is refused rather than surfaced as one.
32
+ - pki.cmc.build(spec, signer) takes spec popChallenge of { challenge, recipient } and answers it: the enveloped proof value is decrypted with the recipient key material, hashed under the witness algorithm the challenge names, and compared with the witness it carries. A value that does not decrypt, or that does not hash to that witness, is not the value the authority issued, so the request is refused with cmc/pop-failed and no proof is sent. The section makes that abort mandatory, and answering is not separable from checking: pki.cmc.build computes a proof only after the witness matches. A Decrypted POP control hand-encoded into spec.controls alongside spec popChallenge is refused, since a message carrying two leaves the authority no proof to check; the same now holds for the Identity Proof and POP Link controls that spec identityProof and spec popLink compute.
33
+ - The answer is a MAC over the request the challenge carried, keyed by the decrypted proof value, under the algorithm the challenge named rather than one the client picks. A proof value longer than 64 bytes is truncated to 64 for the key, which the section states and an implementation that skips it will compute a different proof than the authority expects. The control names the certification request in the new request, so a request carrying more than one is refused rather than guessed at. All three request arms bind: a PKCS#10 request by its own bytes, a CRMF one by its message, and an other-message one by its type together with its value. Every way a challenge can be malformed carries cmc/bad-pop-challenge, from bytes that are not DER through a field of the wrong type, so a caller classifies them the same way. RFC 5274 section 4.2 sets what a conforming client answers under: SHA-1 or SHA-256 for the witness, HMAC-SHA1 or HMAC-SHA256 for the proof. Anything else is refused rather than defaulted, as is an identifier carrying a parameter value, since those four algorithms are encoded with the parameters absent or NULL and the answer copies the identifier it was sent. The decrypted proof value and the key derived from it are wiped once the answer is built.
34
+ - A PKCS#10 request whose signature algorithm is id-alg-noSignature is accepted when this message answers a challenge for that same request. A decrypt-only key cannot sign the request that asks for its certificate, and RFC 5272 Appendix C.1 fills the signature field with an algorithm that proves nothing and sends the proof through the section 6.7 challenge instead; the request was previously refused with cmc/bad-popo, so the enrollment the challenge exists for could not be made. The challenge has to prove the key the request asks for: section 6.7 encrypts the proof value to that key, so the request is accepted only when the key that opened the challenge is the request's own subject public key. A challenge opened by any other key, or by a password or a key-encryption key, says nothing about the key being certified and does not stand in for the missing signature. The two keys are compared as keys rather than as encodings, so a curve point written in compressed form matches the same point written uncompressed. A key whose public half cannot be derived on the running Node, which today means the composite ML-KEM families, leaves the request refused rather than accepted. Without an answered challenge for that request it is still refused, since it carries no proof of possession at all, and its parameters must be present and encoded as NULL. A request that does carry a signature is still held to it.
35
+ - pki.schema.cmc.parse also reports how many recipients the challenge names, as encryptedPOP cmsRecipientCount, so a client answering one knows how many to try without walking the envelope itself.
36
+ - The client decrypts with the key alone, which is what the exchange requires: the key being certified has no certificate for a recipient identifier to name. Section 6.7 says the identifier should be the request's subject key identifier, and that form is answered. The alternative it allows, an issuer and serial number whose issuer is encoded as NULL, is not: that is not a Name, and the CMS EnvelopedData definition refuses it. A challenge addressed only that way is refused while parsing, with cmc/bad-pop-challenge naming the reason, and pki.cms.decrypt could not have opened it either. The proof also has to cover the request the message carries: a challenge quoting a different certification request is refused rather than answered for the wrong one.
37
+
38
+ ### Fixed
39
+
40
+ - pki.schema.cmc.parse reports bytes that are not a CMS carrier as cmc/bad-der rather than cms/bad-der. Every other format parser answers for its own input in its own domain, and this one passed the carrier parser's code through, so a caller matching on the cmc prefix missed the most common malformed input there is.
41
+ - pki.cms.decrypt opens a key-agreement recipient whose encrypted key is not the first one listed. One KeyAgreeRecipientInfo can carry an encrypted key for several recipients under a single originator, and a caller decrypting with a private key alone has no recipient identifier to select its own entry by, so only the first entry was tried and a message addressed to that caller was refused as undecryptable. A caller with no certificate is now offered every entry, and AES key wrap's integrity check settles which one belongs to the key, so an entry opens only for the key it was encrypted to. A caller that supplies a certificate is unaffected: its entry is still chosen by recipient identifier. At most 64 entries are tried, since the list arrives with the message; a longer list still opens on an entry within that bound, and one whose only openable entry sits past it is refused with cms/too-many-recipient-keys.
42
+ - pki.schema.cms.parse refuses a key-agreement recipient that names no encrypted key. Such a recipient names nobody, so nothing could open the content it is attached to; it now fails with cms/bad-recipient-encrypted-keys while parsing rather than reaching a decrypt that has nothing to try.
43
+ - pki.cms.decrypt takes the curve of a key-agreement originator that omitted its parameters from the recipient's own private key. RFC 5753 section 7.1 allows the originator to omit them because the recipient knows the curve, but the curve was read only from a recipient certificate, so a caller decrypting with a key alone was refused with cms/unsupported-algorithm.
44
+
7
45
  ## v0.6.48 — 2026-09-07
8
46
 
9
47
  A CMC enrollment request can be authenticated by a shared secret instead of a signature.
package/README.md CHANGED
@@ -227,7 +227,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
227
227
  | `pki.jose` | Flattened JWS (RFC 7515) and JWK thumbprints (RFC 7638). `sign` and `verify` run a Flattened JWS against declarative profiles (ACME outer, EAB inner, keyChange inner) that carry the required and forbidden header rules as data. `base64url` is the strict RFC 4648 §5 codec, rejecting padding, non-alphabet characters, and non-canonical trailing bits. `parseJson` is a bounded reader that refuses duplicate members at any depth. `thumbprint` is the RFC 7638 / 8037 / 9964 canonical digest. The algorithm registry binds each `alg` to its key type (ES/RS/PS/EdDSA/ML-DSA), leaving no code path for `alg:none`, an RS256→HS256 key confusion, or an all-zero ECDSA signature; `assertPublicJwk` refuses a JWK carrying private material, so an exported private key is never published. `opts.key` names the key a message must be signed under and governs: where the profile also permits an embedded header `jwk`, the two must be the same key — compared as RFC 7638 thumbprints, so member order cannot make equal keys differ — and a disagreement is refused rather than resolved in the message's favor. `keySource` reports which key answered, since a signature checked against a key you named is a different claim from one checked against the key the message carried — `sign`, `verify`, `base64url`, `parseJson`, `thumbprint`, `assertPublicJwk` |
228
228
  | `pki.acme` | ACME (RFC 8555 / 8737 / 8738 / 9773). `client(directoryUrl, opts)` is a stateful client driving a live CA directory over `pki.transport`: `newAccount`, `newOrder`, `newAuthz`, `getOrder`, `getAuthorization`, `getChallenge`, `respondToChallenge`, `finalize`, `pollOrder`, `pollAuthorization`, and `downloadCertificate` walk the issuance flow, with `newAuthz` pre-authorizing a single identifier (§7.4.1) and `downloadCertificate` binding the issued certificate to the order — its key, its identifiers, or both; at least one is required by default and the result reports `boundToKey` / `boundToIdentifiers` — before choosing among alternate chains (`Link rel="alternate"`, §7.4.2, via a `selectChain` predicate bounded by `maxAlternates`). `revokeCert` (account-key or certificate-key signed), `keyChange`, `updateAccount` (change the account contacts, §7.3.2), `listOrders` (the account's orders list, following the §7.1.2.1 `Link rel="next"` pagination bounded by a page cap and confined to the orders origin), `deactivateAccount`, `deactivateAuthorization`, `renewalInfo` (ARI), `renewalWindow` (the RFC 9773 §4.2/4.3 renewal decision), and `scheduleRenewal` (the §4.1 auto-sleeping renewal loop that sleeps until the selected instant and refetches until it is time to renew, stopping at the certificate's notAfter) complete the lifecycle. Every URL is HTTPS only, an explicit trust anchor is required, each request carries a fresh single-use nonce with a bounded badNonce retry (and, when `opts.resignKeys` supplies caller-approved alternative account-key algorithms, a bounded RFC 8555 §6.2 badSignatureAlgorithm re-sign that the CA's advertised list can only filter, never widen, so it cannot force a weaker algorithm), reads are POST-as-GET, polling is bounded and sleeps on a Retry-After via an injectable sleeper capped by a poll count and a total-wait budget, and every response body is size-capped. The transport is injectable via `opts.transport`. Over the message layer it composes resource-object validators (closed status enums, conditional-required fields, unknown fields ignored), the three §7.1.6 state machines, the request builders (newAccount with External Account Binding, newOrder with `replaces`, finalize with a CSR identifier-set match and account-key-reuse rejection, challenge responses, deactivation, revokeCert in both key modes, the keyChange nested JWS, POST-as-GET), the http-01 / dns-01 / tls-alpn-01 challenge computations, the dns and ip identifier validators, and the ARI certID with serial sign-padding preserved — `client`, `validate`, `identify`, `assertTransition`, the builders, `keyAuthorization`, `http01`, `dns01`, `tlsAlpn01Extension`, `verifyTlsAlpn01`, `ariCertId` |
229
229
  | `pki.schema.smime` | S/MIME ESS signed-attribute values (RFC 5035 / RFC 8551). `parseSigningCertificate` and `parseSigningCertificateV2` bind a signature to its signing certificate (cert hash, hash algorithm, issuer `GeneralNames` and serial); `parseSmimeCapabilities` decodes the ordered capability list; `decodeAttribute` dispatches a CMS attribute by OID, enforcing the single-value rule and deferring on unknown types. A companion decoder for CMS signed attributes rather than an auto-routed format — `parseSigningCertificate`, `parseSigningCertificateV2`, `parseSmimeCapabilities`, `decodeAttribute` |
230
- | `pki.cmc` | Build and interpret CMC messages (RFC 5272). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and carries it either way RFC 5272 §3.2 allows: `{ cert, key }` signs it, while `{ mac: { identifier, secret } }` authenticates it under a shared secret for a client that holds no key yet, using the PasswordRecipientInfo that section requires and deriving the key from the identifier followed by the secret. A signed request goes through `pki.cms.sign` under `id-cct-PKIData`. A PKCS#10 (`tcr`) request is verified against its own proof-of-possession before signing, so a request whose self-signature does not verify under its subject public key is refused rather than signed into a message a CA would reject. Body-part identifiers are unique across the whole message and never the reserved 0; a caller's clash is refused rather than renumbered, since a control may already reference it. An Identity Proof V2 witness is computed over the `reqSequence` bytes exactly as emitted (§6.2.1 step 1) rather than a re-serialization, a POP Link Witness is emitted only alongside the POP Link Random control §6.3.1.1 requires beside it, and a renewal carries neither Identification nor Identity Proof in either version. `verify(response, sent)` takes what the CA returned plus the state the client retained and reduces it to one terminal outcome: `issued`, `pending`, `confirm-required`, `pop-required`, or `rejected`. It binds the exchange first — Transaction Identifier, the Sender and Recipient Nonce echo compared in constant time and by full value so a truncation cannot match, and the Data Return echo — with each check applying only if the client sent that half, and, once sent, an absent or differing echo being a refusal, which is the replay defense. `bodyPartIDs` extends the same rule to what the response is about: a status reporting on a body part the request never sent is refused, which the transaction and nonce cannot catch, because a server can echo both correctly while answering about a different message. Several status controls are permitted and the worst governs, so a failure cannot hide behind an earlier success; the absence of any status control is success, per §6.1.2. The carrier's signature must verify (§3.2.1.3.4): a conforming SignedData carries its own signer certificate, so the ordinary build-then-verify flow needs nothing extra and the verdict reports `signatureVerified: true`. Where the signer is found nowhere the posture is fail-closed with a named opt-out — supply `certs` with the responder's certificate, or `allowUnverified: true`, in which case the verdict reports `signatureVerified: false`. Doing neither is refused, the opt-out never excuses a signature that is present and wrong, and a carrier with no signer at all is refused outright. The response's own `cmsSequence` and `otherMsgs` come back raw, since a request whose only arm was the other-message form has no certificate to return and §4.1 puts its answer there. Nothing is trusted: issued certificates are read from the CMS certificate bag (§4.2) and surfaced raw for `pki.path.validate`, and a Publish Trust Anchors control is surfaced with `trusted: false` rather than added to a store — `build`, `verify` |
230
+ | `pki.cmc` | Build and interpret CMC messages (RFC 5272). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and carries it either way RFC 5272 §3.2 allows: `{ cert, key }` signs it, while `{ mac: { identifier, secret } }` authenticates it under a shared secret for a client that holds no key yet, using the PasswordRecipientInfo that section requires and deriving the key from the identifier followed by the secret. A key that cannot sign for itself proves possession another way: `spec.popChallenge` answers the authority's encrypted challenge (RFC 5272 §6.7), decrypting the proof value, confirming it hashes to the witness the challenge carries, and returning the MAC the authority asked for, with `cmc/pop-failed` when the value is not the one issued. A signed request goes through `pki.cms.sign` under `id-cct-PKIData`. A PKCS#10 (`tcr`) request is verified against its own proof-of-possession before signing, so a request whose self-signature does not verify under its subject public key is refused rather than signed into a message a CA would reject. Body-part identifiers are unique across the whole message and never the reserved 0; a caller's clash is refused rather than renumbered, since a control may already reference it. An Identity Proof V2 witness is computed over the `reqSequence` bytes exactly as emitted (§6.2.1 step 1) rather than a re-serialization, a POP Link Witness is emitted only alongside the POP Link Random control §6.3.1.1 requires beside it, and a renewal carries neither Identification nor Identity Proof in either version. `verify(response, sent)` takes what the CA returned plus the state the client retained and reduces it to one terminal outcome: `issued`, `pending`, `confirm-required`, `pop-required`, or `rejected`. It binds the exchange first — Transaction Identifier, the Sender and Recipient Nonce echo compared in constant time and by full value so a truncation cannot match, and the Data Return echo — with each check applying only if the client sent that half, and, once sent, an absent or differing echo being a refusal, which is the replay defense. `bodyPartIDs` extends the same rule to what the response is about: a status reporting on a body part the request never sent is refused, which the transaction and nonce cannot catch, because a server can echo both correctly while answering about a different message. Several status controls are permitted and the worst governs, so a failure cannot hide behind an earlier success; the absence of any status control is success, per §6.1.2. The carrier's signature must verify (§3.2.1.3.4): a conforming SignedData carries its own signer certificate, so the ordinary build-then-verify flow needs nothing extra and the verdict reports `signatureVerified: true`. Where the signer is found nowhere the posture is fail-closed with a named opt-out — supply `certs` with the responder's certificate, or `allowUnverified: true`, in which case the verdict reports `signatureVerified: false`. Doing neither is refused, the opt-out never excuses a signature that is present and wrong, and a carrier with no signer at all is refused outright. The response's own `cmsSequence` and `otherMsgs` come back raw, since a request whose only arm was the other-message form has no certificate to return and §4.1 puts its answer there. Nothing is trusted: issued certificates are read from the CMS certificate bag (§4.2) and surfaced raw for `pki.path.validate`, and a Publish Trust Anchors control is surfaced with `trusted: false` rather than added to a store — `build`, `verify` |
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` |
@@ -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/cmc-build.js CHANGED
@@ -16,6 +16,9 @@ var cmcFmt = require("./schema-cmc");
16
16
  var oid = require("./oid");
17
17
  var cmsSign = require("./cms-sign");
18
18
  var cmsEncrypt = require("./cms-encrypt");
19
+ var cmsDecrypt = require("./cms-decrypt");
20
+ var key = require("./key");
21
+ var _createPublicKey = nodeCrypto.createPublicKey;
19
22
  var guard = require("./guard-all");
20
23
  var intrinsic = require("./guard-intrinsic");
21
24
  var _hasOwn = intrinsic.hasOwn;
@@ -23,6 +26,7 @@ var _isArray = intrinsic.isArray;
23
26
  var _isBuffer = intrinsic.isBuffer;
24
27
  var _bufferFrom = intrinsic.bufferFrom;
25
28
  var _bufferConcat = intrinsic.bufferConcat;
29
+ var _subarray = intrinsic.subarray;
26
30
  var frameworkError = require("./framework-error");
27
31
 
28
32
  var CmcError = frameworkError.CmcError;
@@ -32,6 +36,7 @@ function O(name) { return oid.byName(name); }
32
36
 
33
37
  var OID_IDENTITY_PROOF_V2 = O("id-cmc-identityProofV2");
34
38
  var OID_POP_LINK_RANDOM = O("id-cmc-popLinkRandom");
39
+ var OID_DECRYPTED_POP = O("id-cmc-decryptedPOP");
35
40
  var OID_IDENTIFICATION = O("id-cmc-identification");
36
41
  var OID_SHA256 = O("sha256");
37
42
  var OID_HMAC_SHA256 = O("hmacWithSHA256");
@@ -47,7 +52,7 @@ var POP_LINK_RANDOM_BYTES = 64;
47
52
 
48
53
  var KNOWN_SPEC_KEYS = intrinsic.assign(intrinsic.create(null), {
49
54
  requests: 1, controls: 1, cmsSequence: 1, otherMsgSequence: 1,
50
- identityProof: 1, popLink: 1, renewal: 1,
55
+ identityProof: 1, popLink: 1, renewal: 1, popChallenge: 1,
51
56
  transactionId: 1, senderNonce: 1, dataReturn: 1,
52
57
  });
53
58
 
@@ -185,13 +190,59 @@ function fixedRequestId(req, index) {
185
190
  return req.bodyPartID == null ? null : req.bodyPartID;
186
191
  }
187
192
 
188
- async function _assertTcrPops(requests) {
193
+ async function _assertTcrPops(requests, popProvenRequest) {
189
194
  for (var i = 0; i < requests.length; i++) {
190
- if (requests[i] && requests[i].tcr != null) await _assertOneTcrPop(requests[i].tcr, i);
195
+ if (requests[i] && requests[i].tcr != null) await _assertOneTcrPop(requests[i].tcr, i, popProvenRequest);
191
196
  }
192
197
  }
193
- async function _assertOneTcrPop(tcr, i) {
194
- var parsed = csr.parse(_der(tcr, "a tcr certificationRequest"));
198
+ /** @internal The parameters an algorithm identifier carries, which for these four are absent or NULL. */
199
+ function _assertNoAlgorithmParameters(algId, what) {
200
+ var params = algId.parameters;
201
+ if (params == null) return;
202
+ if (params.length === 2 && params[0] === 0x05 && params[1] === 0x00) return;
203
+ throw E("cmc/bad-pop-challenge",
204
+ "the challenge's " + what + " carries a parameter value, and the algorithms RFC 5274 sec. 4.2 " +
205
+ "names take none: they are encoded with the parameters absent or NULL");
206
+ }
207
+
208
+ /** @internal Whether these bytes are one DER OCTET STRING and nothing else. */
209
+ function _isNoSignatureValue(bytes) {
210
+ if (!bytes || !bytes.length) return false;
211
+ var node;
212
+ try { node = asn1.decode(bytes); }
213
+ catch (_e) { return false; } // allow:swallow-unverified bytes that do not decode are not a NoSignatureValue
214
+ return node.tagClass === "universal" && node.tagNumber === asn1.TAGS.OCTET_STRING && !node.constructed;
215
+ }
216
+
217
+ /** @internal A key that can only decrypt cannot sign the request that asks for its certificate, so RFC
218
+ * 5272 App. C.1 gives it a signature algorithm that carries no proof and sends the proof through the
219
+ * sec. 6.7 challenge instead. A request in that form is accepted here only when this message answers a
220
+ * challenge for that same request; without one it carries no proof of possession at all. */
221
+ async function _assertOneTcrPop(tcr, i, popProvenRequest) {
222
+ var der = _der(tcr, "a tcr certificationRequest");
223
+ var parsed = csr.parse(der);
224
+ if (parsed.signatureAlgorithm.oid === O("id-alg-noSignature")) {
225
+ var params = parsed.signatureAlgorithm.parameters;
226
+ if (!params || params.length !== 2 || params[0] !== 0x05 || params[1] !== 0x00) {
227
+ throw E("cmc/bad-popo", "a tcr request [" + i + "] uses id-alg-noSignature, whose parameters must be " +
228
+ "present and encoded as NULL (RFC 5272 App. C.1)");
229
+ }
230
+ /** @internal "NoSignatureValue ::= OCTET STRING" (App. C.1), carried in the signature BIT STRING.
231
+ * The section says it holds the hash of the request but names no algorithm, so the encoding is what
232
+ * can be checked here; a value that is not one is a request an authority would reject. */
233
+ var sig = parsed.signatureValue;
234
+ if (!sig || sig.unusedBits !== 0 || !_isNoSignatureValue(sig.bytes)) {
235
+ throw E("cmc/bad-popo", "a tcr request [" + i + "] uses id-alg-noSignature, whose signature is a " +
236
+ "NoSignatureValue OCTET STRING (RFC 5272 App. C.1)");
237
+ }
238
+ if (!popProvenRequest || popProvenRequest.length !== der.length ||
239
+ !guard.crypto.constantTimeEqual(popProvenRequest, der)) {
240
+ throw E("cmc/bad-popo", "a tcr request [" + i + "] is signed with id-alg-noSignature, which proves " +
241
+ "nothing about the key; such a request carries its proof of possession in an answered " +
242
+ "challenge, so pass the one the authority sent as popChallenge (RFC 5272 App. C.1, sec. 6.7)");
243
+ }
244
+ return;
245
+ }
195
246
  if (!(await csrVerify.verifyCsrSignature(parsed))) {
196
247
  throw E("cmc/bad-popo", "a tcr request [" + i + "] failed its proof-of-possession: the PKCS#10 signature does not verify under the request's own subject public key (RFC 5272 sec. 6.3), so a CA would reject it -- refusing it here rather than signing it");
197
248
  }
@@ -285,10 +336,58 @@ var BINDING_TYPE_NAME = intrinsic.assign(intrinsic.create(null), {
285
336
  dataReturn: "an OCTET STRING (RFC 5272 sec. 6.4)",
286
337
  });
287
338
 
339
+ /** @internal Controls the builder computes for itself from a spec field. Their value is a proof, so a
340
+ * second one arriving hand-encoded cannot be reconciled with the computed one the way an Identification
341
+ * name can: the two would both be emitted, and a message carrying two proofs of the same thing is one an
342
+ * authority has no rule for. Naming the spec field that produces it says which of the two to drop. */
343
+ var GENERATED_BY_OID = intrinsic.create(null);
344
+ GENERATED_BY_OID[O("id-cmc-identityProofV2")] = { field: "identityProof" };
345
+ GENERATED_BY_OID[O("id-cmc-popLinkWitnessV2")] = { field: "popLink" };
346
+ GENERATED_BY_OID[O("id-cmc-popLinkRandom")] = { field: "popLink" };
347
+ GENERATED_BY_OID[O("id-cmc-decryptedPOP")] = { field: "popChallenge", perTarget: true };
348
+
349
+ /** @internal The bodyPartID a Decrypted POP names, which is the request its proof covers. Several may
350
+ * ride in one message, one per request, so it is the target that has to be unique rather than the
351
+ * control. A value that will not read as one is treated as naming nothing, and a second such control is
352
+ * refused because there is no target to tell the two apart by. */
353
+ function _decryptedPopTarget(controlValue) {
354
+ try {
355
+ var node = asn1.decode(controlValue);
356
+ return intrinsic.bigIntToString(asn1.read.integer(node.children[0]), 10);
357
+ } catch (_e) { return null; } // allow:swallow-unverified an unreadable control names no request
358
+ }
359
+
360
+ function _assertNotAlsoComputed(controlType, controlValue, seen, spec) {
361
+ var generated = GENERATED_BY_OID[controlType];
362
+ if (!generated) return;
363
+ /** @internal Tested the way the producer tests it. A field this reads as present but the emitting
364
+ * code skips would refuse a message that carries one control, not two. */
365
+ if (spec[generated.field]) {
366
+ throw E("cmc/bad-input",
367
+ "spec." + generated.field + " computes this control, and spec.controls carries one as well; a " +
368
+ "request carries one or the other, since a message with two leaves the authority no proof to " +
369
+ "check (RFC 5272 sec. 6.2.1 / 6.3.1 / 6.7)");
370
+ }
371
+ var target = generated.perTarget ? _decryptedPopTarget(controlValue) : null;
372
+ var slot = generated.perTarget ? controlType + ":" + (target === null ? "?" : target) : controlType;
373
+ if (seen[guard.text.keyOf(slot)]) {
374
+ throw E("cmc/bad-input",
375
+ "spec.controls carries two " + (oid.name(controlType) || controlType) + " controls" +
376
+ (generated.perTarget
377
+ ? (target === null
378
+ ? " that name no readable certification request, so nothing tells the two proofs apart"
379
+ : " naming certification request " + target + ", so the authority has two proofs of one request")
380
+ : "") +
381
+ "; a message with two leaves the authority no proof to check (RFC 5272 sec. 6.2.1 / 6.3.1 / 6.7)");
382
+ }
383
+ seen[guard.text.keyOf(slot)] = true;
384
+ }
385
+
288
386
  function _assertNoDuplicateBinding(callerControls, spec) {
289
387
  var seen = intrinsic.create(null);
290
388
  callerControls.forEach(function (c) {
291
- var field = BINDING_BY_OID[_oidOf(c.type)];
389
+ var controlOid = _oidOf(c.type);
390
+ var field = BINDING_BY_OID[controlOid];
292
391
  if (!field) return;
293
392
  try { BINDING_READER[field](asn1.decode(_der(c.value, "a control value"))); }
294
393
  catch (e) {
@@ -374,6 +473,175 @@ function identityProofV2(secret, reqSequenceBytes, identity) {
374
473
  }
375
474
  }
376
475
 
476
+ /** @internal RFC 5274 sec. 4.2 names what a conforming client implements for this exchange: SHA-1 MUST
477
+ * and SHA-256 SHOULD for the witness, HMAC-SHA1 MUST and HMAC-SHA256 SHOULD for the proof. Both MUSTs
478
+ * are legacy algorithms and are accepted because the profile requires them of a client answering a
479
+ * challenge, which is a server's choice to make rather than this side's. Anything else is refused: a
480
+ * proof computed under an algorithm the server did not ask for is not an answer. */
481
+ var POP_WITNESS_HASH = intrinsic.create(null);
482
+ POP_WITNESS_HASH[O("sha1")] = "sha1";
483
+ POP_WITNESS_HASH[O("sha256")] = "sha256";
484
+ var POP_MAC_HASH = intrinsic.create(null);
485
+ POP_MAC_HASH[O("hmacWithSHA1")] = "sha1";
486
+ POP_MAC_HASH[O("hmacWithSHA256")] = "sha256";
487
+ var POP_MAC_KEY_MAX_BYTES = 64;
488
+ var KNOWN_POP_CHALLENGE_KEYS = intrinsic.assign(intrinsic.create(null),
489
+ { challenge: 1, recipient: 1 });
490
+
491
+ /** @internal The key this challenge is addressed to is the one being certified, which by definition has
492
+ * no certificate yet, so the recipient cannot be selected by matching one. Sec. 6.7 says the identifier
493
+ * "SHOULD be the SKI" of the request, and that an issuerAndSerialNumber form carries a NULL issuer with
494
+ * the request's bodyPartID as the serial: neither names a certificate this caller holds. So each
495
+ * recipient is tried with the key, and the WITNESS decides which attempt recovered the right value,
496
+ * which is the check the section already requires and the only one that can answer the question. A
497
+ * caller who does hold the certificate can still pass it and select the ordinary way. */
498
+ var POP_MAX_RECIPIENTS = 8;
499
+
500
+ /** @internal The CMS recipient kinds that identify a key. A password or a key-encryption key opens the
501
+ * envelope without saying whose it is, so a decryption through one proves possession of no key. */
502
+ var ASYMMETRIC_RECIPIENT = intrinsic.assign(intrinsic.create(null), { ktri: 1, kari: 1, ori: 1 });
503
+
504
+ /** @internal What identifies a request within its arm, which is everything a TaggedRequest carries
505
+ * except the body part identifier the new message is entitled to renumber. Defined once, so the two
506
+ * sides of the comparison below cannot read different things: the other-message arm is identified by
507
+ * its type together with its value, since a value alone could belong to another type. */
508
+ function _requestIdentity(parsed) {
509
+ if (!parsed) return null;
510
+ if (parsed.arm === "tcr") return { arm: "tcr", bytes: parsed.certificationRequestBytes };
511
+ if (parsed.arm === "crm") return { arm: "crm", bytes: parsed.certReqMsgBytes };
512
+ if (parsed.arm === "orm" && parsed.requestMessageType) {
513
+ return { arm: "orm",
514
+ bytes: _bufferConcat([b.oid(parsed.requestMessageType), parsed.requestMessageValueBytes]) };
515
+ }
516
+ return null;
517
+ }
518
+
519
+ /** @internal Whether the key that opened the challenge is the key the request asks to have certified.
520
+ * Only a tcr is answered this way: a crm request carries its own proof-of-possession field. */
521
+ function _provesRequestKey(openingKey, outgoing) {
522
+ if (!openingKey || !outgoing || !outgoing.certificationRequestBytes) return false;
523
+ var requested;
524
+ /** @internal Compared as keys rather than as encodings: an elliptic-curve point written in compressed
525
+ * form and the same point written uncompressed are different bytes and the same key, and it is the key
526
+ * the section is about. */
527
+ try {
528
+ requested = _createPublicKey({
529
+ key: csr.parse(outgoing.certificationRequestBytes).subjectPublicKeyInfo.bytes,
530
+ format: "der", type: "spki",
531
+ });
532
+ } catch (_e) { return false; } // allow:swallow-unverified a key this runtime cannot read proves nothing here
533
+ return intrinsic.keyEquals(requested, openingKey);
534
+ }
535
+
536
+ /** @internal The public half of the key that OPENED the challenge. The recipient kind comes from the
537
+ * decryption that succeeded rather than from the caller's object, so key material the envelope never
538
+ * exercised is not read as the key that answered it. A key whose public half this runtime cannot derive
539
+ * yields null, and the request is then refused rather than accepted on an unproven key. */
540
+ async function _openingPublicKey(recipient, recipientType) {
541
+ if (!ASYMMETRIC_RECIPIENT[recipientType]) return null;
542
+ try {
543
+ return _createPublicKey({
544
+ key: await key.publicFromPrivate(recipient.key), format: "der", type: "spki",
545
+ });
546
+ } catch (_e) { return null; } // allow:swallow-unverified a key whose public half cannot be derived proves nothing here
547
+ }
548
+
549
+ async function _recoverProofValue(decoded, recipient, witnessHash) {
550
+ /** @internal The count is read off the parse rather than re-walked here, so the structure the parser
551
+ * accepted and the structure this loop iterates cannot disagree. */
552
+ var count = decoded.cmsRecipientCount;
553
+ if (count > POP_MAX_RECIPIENTS) {
554
+ throw E("cmc/bad-pop-challenge",
555
+ "the challenge's enveloped proof value names " + count + " recipients; a challenge is addressed to " +
556
+ "the key being certified, and at most " + POP_MAX_RECIPIENTS + " are tried (RFC 5272 sec. 6.7)");
557
+ }
558
+ for (var i = 0; i < count; i++) {
559
+ var opened;
560
+ try {
561
+ opened = await cmsDecrypt.decrypt(decoded.cms, recipient, { recipientIndex: i });
562
+ } catch (_e) {
563
+ continue; // allow:swallow-unverified this recipient is not addressed to the supplied key; the witness decides
564
+ }
565
+ var candidate = opened.content;
566
+ var computed = nodeCrypto.createHash(witnessHash).update(candidate).digest();
567
+ var matches = computed.length === decoded.witness.length &&
568
+ guard.crypto.constantTimeEqual(computed, decoded.witness);
569
+ guard.secret.zeroize(computed, CmcError, "cmc/bad-input", "the computed witness");
570
+ /** @internal The kind of recipient that actually opened it travels with the value, so what proved
571
+ * possession is decided by the decryption that happened rather than by the caller's object. */
572
+ if (matches) return { value: candidate, recipientType: opened.recipientType };
573
+ guard.secret.zeroize(candidate, CmcError, "cmc/bad-input", "a rejected proof value");
574
+ }
575
+ throw E("cmc/pop-failed",
576
+ "no recipient of the challenge yielded a proof value hashing to the witness it carries, so this " +
577
+ "client cannot prove possession and the enrollment is abandoned (RFC 5272 sec. 6.7 step 3)");
578
+ }
579
+
580
+ /** @internal The client half of RFC 5272 sec. 6.7: decrypt the challenge, confirm it is the value the
581
+ * server hashed into the witness, and answer with a MAC over the request it carried. The witness check
582
+ * is not separable from the answer, because a client that cannot confirm the value "MUST abort the
583
+ * enrollment process" rather than prove possession of something it could not read. */
584
+ async function answerPopChallenge(popChallenge, ids) {
585
+ if (!popChallenge || typeof popChallenge !== "object" || _isArray(popChallenge) || _isBuffer(popChallenge)) {
586
+ throw E("cmc/bad-input", "popChallenge is { challenge, recipient } (RFC 5272 sec. 6.7)");
587
+ }
588
+ guard.identifier.assertKnownKeys(popChallenge, KNOWN_POP_CHALLENGE_KEYS, E, "cmc/bad-input",
589
+ "unknown popChallenge field ");
590
+ var recipient = popChallenge.recipient;
591
+ if (!recipient || typeof recipient !== "object" || _isArray(recipient) || _isBuffer(recipient)) {
592
+ throw E("cmc/bad-input",
593
+ "popChallenge.recipient is the CMS key material that opens the challenge, in the shape " +
594
+ "pki.cms.decrypt takes (RFC 5272 sec. 6.7)");
595
+ }
596
+ /** @internal The challenge arrives from the authority, so bytes that are not DER at all are a
597
+ * malformed challenge like any other and carry the same code rather than the codec's. */
598
+ var challengeBytes = _der(popChallenge.challenge, "the popChallenge challenge");
599
+ var challengeNode;
600
+ try { challengeNode = asn1.decode(challengeBytes); }
601
+ catch (e) {
602
+ throw E("cmc/bad-pop-challenge",
603
+ "the popChallenge challenge is the DER of an EncryptedPOP control value: " +
604
+ ((e && e.message) || "malformed") + " (RFC 5272 sec. 6.7)", e);
605
+ }
606
+ var decoded = cmcFmt.parseEncryptedPop(challengeNode);
607
+ var witnessHash = POP_WITNESS_HASH[guard.text.keyOf(decoded.witnessAlgID.oid)];
608
+ var macHash = POP_MAC_HASH[guard.text.keyOf(decoded.thePOPAlgID.oid)];
609
+ if (!witnessHash || !macHash) {
610
+ throw E("cmc/bad-pop-challenge",
611
+ "the challenge names an algorithm this client does not answer under: RFC 5274 sec. 4.2 requires " +
612
+ "SHA-1 or SHA-256 for the witness and HMAC-SHA1 or HMAC-SHA256 for the proof, got " +
613
+ decoded.witnessAlgID.oid + " and " + decoded.thePOPAlgID.oid);
614
+ }
615
+ /** @internal These four algorithms take no parameters: a SHA-2 identifier carries them absent or as
616
+ * NULL (RFC 5754 sec. 2), and the SHA-1 and HMAC identifiers carry NULL. A parameter value that is
617
+ * neither is not one of the algorithms named, and copying it into the answer would send the authority
618
+ * an identifier it cannot read. */
619
+ _assertNoAlgorithmParameters(decoded.witnessAlgID, "witnessAlgID");
620
+ _assertNoAlgorithmParameters(decoded.thePOPAlgID, "thePOPAlgID");
621
+
622
+ var proofValue = null, macKey = null;
623
+ try {
624
+ var recovered = await _recoverProofValue(decoded, recipient, witnessHash);
625
+ proofValue = recovered.value;
626
+ /** @internal "The POP Proof Value is used as the secret value in the HMAC algorithm and the request
627
+ * is used as the data. If the POP Proof Value is greater than 64 bytes, only the first 64 bytes of
628
+ * the POP Proof Value is used as the secret." The data is the TaggedRequest exactly as the
629
+ * challenge carried it, which is the copy the server holds and the reason sec. 6.7 puts the request
630
+ * in the challenge at all: neither side re-encodes it. */
631
+ macKey = _bufferFrom(proofValue.length > POP_MAC_KEY_MAX_BYTES
632
+ ? _subarray(proofValue, 0, POP_MAC_KEY_MAX_BYTES) : proofValue);
633
+ var thePOP = nodeCrypto.createHmac(macHash, macKey).update(decoded.requestBytes).digest();
634
+ return { algBytes: decoded.thePOPAlgID.bytes, thePOP: thePOP, ids: ids,
635
+ recipientSpki: await _openingPublicKey(recipient, recovered.recipientType),
636
+ challengedRequest: _requestIdentity(decoded.request) };
637
+ } finally {
638
+ var owned = [];
639
+ if (proofValue && _isBuffer(proofValue)) guard.list.append(owned, proofValue);
640
+ if (macKey) guard.list.append(owned, macKey);
641
+ if (owned.length) guard.secret.zeroizeAll(owned, CmcError, "cmc/bad-input", "the POP proof value");
642
+ }
643
+ }
644
+
377
645
  function popLinkWitnessV2(secret, R) {
378
646
  _assertSecret(secret, "a POP Link Witness V2 control");
379
647
  var key = nodeCrypto.createHash("sha256").update(secret, "utf8").digest();
@@ -458,6 +726,9 @@ async function _build(spec, signer, opts) {
458
726
  /** @internal The names a caller-written Identification control gives this client, collected as those
459
727
  * controls are encoded so the name checked is the name carried (RFC 5272 sec. 6.2.3). */
460
728
  var controlIdentifiers = [], controlIdentificationCount = 0, controlIdentifierUnreadable = false;
729
+ /** @internal Which of the controls the builder computes have already arrived hand-encoded, checked
730
+ * against the bytes being encoded rather than a second read of the caller's object. */
731
+ var generatedSeen = intrinsic.create(null);
461
732
  callerControls.forEach(function (c) {
462
733
  if (!c || typeof c !== "object" || c.type == null || c.value == null) {
463
734
  throw E("cmc/bad-input", "each control is { type, value }");
@@ -471,6 +742,7 @@ async function _build(spec, signer, opts) {
471
742
  * it carries. The Identification name below is read off THESE bytes for the same reason. */
472
743
  var controlType = _oidOf(c.type);
473
744
  var controlValue = _der(c.value, "a control value");
745
+ _assertNotAlsoComputed(controlType, controlValue, generatedSeen, spec);
474
746
  if (controlType === OID_IDENTIFICATION) {
475
747
  controlIdentificationCount += 1;
476
748
  var idNode;
@@ -485,7 +757,7 @@ async function _build(spec, signer, opts) {
485
757
  controlIdentifierUnreadable = true;
486
758
  }
487
759
  }
488
- controls.push(encodeControl(controlType, [controlValue], ids));
760
+ guard.list.append(controls, encodeControl(controlType, [controlValue], ids));
489
761
  });
490
762
 
491
763
  _assertNoDuplicateBinding(callerControls, spec);
@@ -572,6 +844,45 @@ async function _build(spec, signer, opts) {
572
844
  }
573
845
  }
574
846
 
847
+ /** @internal The answer to a challenge-response proof of possession (RFC 5272 sec. 6.7 step 4). Its
848
+ * bodyPartID names the certification request in THIS request, not the one the challenge quoted, so
849
+ * the server can tie the proof to what is being asked for now. With more than one request there is
850
+ * no single answer to give, and guessing which one the proof covers is not this side's call. */
851
+ var popProvenRequest = null;
852
+ if (spec.popChallenge) {
853
+ if (encodedRequests.length !== 1) {
854
+ throw E("cmc/bad-input",
855
+ "a challenge-response proof of possession answers for one certification request, and this " +
856
+ "request carries " + encodedRequests.length + " (RFC 5272 sec. 6.7)");
857
+ }
858
+ var answered = await answerPopChallenge(spec.popChallenge, ids);
859
+ /** @internal The proof covers the request the CHALLENGE carried, and the control names the request
860
+ * in THIS message. If those are not the same certification request, the message proves possession
861
+ * of a key for a request it does not contain, so the two are compared on everything but the body
862
+ * part identifier, which the new message is entitled to renumber. */
863
+ var outgoing = cmcFmt.parseTaggedRequest(asn1.decode(encodedRequests[0].der));
864
+ var outgoingId = _requestIdentity(outgoing);
865
+ if (!answered.challengedRequest || !outgoingId ||
866
+ answered.challengedRequest.arm !== outgoingId.arm ||
867
+ answered.challengedRequest.bytes.length !== outgoingId.bytes.length ||
868
+ !guard.crypto.constantTimeEqual(answered.challengedRequest.bytes, outgoingId.bytes)) {
869
+ throw E("cmc/bad-input",
870
+ "the challenge answers for a different certification request than this message carries, so the " +
871
+ "proof would not cover the request it names (RFC 5272 sec. 6.7 step 4)");
872
+ }
873
+ /** @internal What the challenge proved possession of. A request signed with id-alg-noSignature has
874
+ * no signature to prove it, and App. C.1 sends exactly that case here, so this is the request that
875
+ * is then allowed to carry one. Opening the challenge shows possession of the key it was encrypted
876
+ * to, which sec. 6.7 says is the key in the request; a challenge opened by any other key says
877
+ * nothing about the key being certified, so it does not stand in for the missing signature. */
878
+ popProvenRequest = _provesRequestKey(answered.recipientSpki, outgoing) ? outgoingId.bytes : null;
879
+ guard.list.append(controls, encodeControl(OID_DECRYPTED_POP, [b.sequence([
880
+ b.integer(BigInt(encodedRequests[0].bodyPartID)),
881
+ b.raw(answered.algBytes),
882
+ b.octetString(answered.thePOP),
883
+ ])], ids));
884
+ }
885
+
575
886
  if (spec.popLink) {
576
887
  guard.identifier.assertKnownKeys(spec.popLink, KNOWN_POP_LINK_KEYS, E, "cmc/bad-input",
577
888
  function (k) { return "unknown field " + JSON.stringify(k) + " on popLink -- it is { secret }"; });
@@ -611,7 +922,7 @@ async function _build(spec, signer, opts) {
611
922
  guard.identifier.assertKnownKeys(signer, KNOWN_MAC_CARRIER_KEYS, E, "cmc/bad-input", "unknown shared-secret carrier field ");
612
923
  var macBytes = macPassword(signer.mac);
613
924
  try {
614
- await _assertTcrPops(requests);
925
+ await _assertTcrPops(requests, popProvenRequest);
615
926
  /** @internal The Password Recipient Info option, which sec. 3.2(a) requires, is what the CMS
616
927
  * producer selects for a password recipient, and it generates the MAC key sec. 3.2(b) calls for. */
617
928
  return await cmsEncrypt.authenticate(pkiData, [{ password: macBytes }],
@@ -630,7 +941,7 @@ async function _build(spec, signer, opts) {
630
941
  ownedKeyBytes.length = 0;
631
942
  }
632
943
  try {
633
- await _assertTcrPops(requests);
944
+ await _assertTcrPops(requests, popProvenRequest);
634
945
  return await cmsSign.sign(pkiData, copiedSigner, { eContentType: "id-cct-PKIData", pem: opts.pem });
635
946
  } finally {
636
947
  _wipeOwnedKeys();
package/lib/cmc-verify.js CHANGED
@@ -550,6 +550,26 @@ function _shape(body, sent, signatureVerified, bound) {
550
550
  * carry neither Identification nor Identity Proof (sec. 3.2 (a)), so asking for both is refused
551
551
  * and never silently dropped.
552
552
  *
553
+ * `spec.popChallenge: { challenge, recipient }` answers an authority's challenge-response proof of
554
+ * possession, which is how a key that cannot sign for itself proves the client holds it (RFC 5272
555
+ * sec. 6.7). `challenge` is the Encrypted POP control's value and `recipient` is the key material
556
+ * `pki.cms.decrypt` takes. The proof value is decrypted, hashed under the witness algorithm the
557
+ * challenge names and compared with the witness it carries; a value that does not decrypt or does not
558
+ * match is not the one the authority issued, so the request is refused with `cmc/pop-failed` and no
559
+ * proof is sent. The answer is a MAC over the request the challenge carried, keyed by that value
560
+ * (truncated to 64 bytes, sec. 6.7) under the algorithm the challenge named, and it names the
561
+ * certification request in THIS request, so a request carrying more than one is refused. The
562
+ * algorithms are the ones RFC 5274 sec. 4.2 requires of a client: SHA-1 or SHA-256 for the witness,
563
+ * HMAC-SHA1 or HMAC-SHA256 for the proof.
564
+ *
565
+ * A `tcr` request signed with `id-alg-noSignature` (RFC 5272 App. C.1) is the request a decrypt-only
566
+ * key produces, and it carries no proof of its own. It is accepted only when this message answers a
567
+ * challenge for that same request and the key that opened the challenge is the request's own subject
568
+ * public key, compared as keys rather than as encodings. A challenge opened by a password or a
569
+ * key-encryption key identifies no key and does not qualify, and its parameters must be present and
570
+ * encoded as NULL. Without such an answer the request is refused with `cmc/bad-popo`, and a request
571
+ * that does carry a signature is still held to it.
572
+ *
553
573
  * `spec.transactionId` (number|bigint), `spec.senderNonce` and `spec.dataReturn` (bytes) attach the
554
574
  * exchange-binding controls (RFC 5272 sec. 6.6 / 6.4), the same three `pki.cmc.verify` checks the
555
575
  * response against. They are named fields, not something to hand-encode into