@blamejs/pki 0.6.48 → 0.6.49

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,26 @@ 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.49 — 2026-09-07
8
+
9
+ A key that cannot sign for itself can still prove possession, by answering the authority's encrypted challenge.
10
+
11
+ ### Added
12
+
13
+ - 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.
14
+ - 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.
15
+ - 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.
16
+ - 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.
17
+ - 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.
18
+ - 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.
19
+
20
+ ### Fixed
21
+
22
+ - 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.
23
+ - 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.
24
+ - 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.
25
+ - 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.
26
+
7
27
  ## v0.6.48 — 2026-09-07
8
28
 
9
29
  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` |
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
@@ -160,7 +160,7 @@ function _kekIdMatches(ri, kekId) {
160
160
  return Buffer.compare(id, guard.bytes.view(kekId, CmsError, "cms/bad-input", "kekId")) === 0;
161
161
  }
162
162
 
163
- var _passThrough = intrinsic.assign(intrinsic.create(null), { "cms/unsupported-algorithm": 1, "cms/unsupported-recipient-type": 1, "cms/bad-input": 1, "cms/iteration-limit": 1, "cms/missing-key-derivation": 1, "cms/no-encrypted-content": 1 });
163
+ var _passThrough = intrinsic.assign(intrinsic.create(null), { "cms/unsupported-algorithm": 1, "cms/unsupported-recipient-type": 1, "cms/bad-input": 1, "cms/iteration-limit": 1, "cms/missing-key-derivation": 1, "cms/no-encrypted-content": 1, "cms/too-many-recipient-keys": 1 });
164
164
 
165
165
  async function _acquireCek(ri, km, opts) {
166
166
  try {
@@ -198,6 +198,29 @@ async function _ktriCek(ri, km) {
198
198
  }
199
199
  }
200
200
 
201
+ /** @internal One KeyAgreeRecipientInfo can carry an encrypted key for several recipients under one
202
+ * originator and one key-derivation, and a caller decrypting with a private key alone has no identifier
203
+ * to select its own entry by. The key-encryption key is derived once and every entry is offered to it;
204
+ * AES key wrap's integrity check settles which entry belongs to this key, so an entry that opens is one
205
+ * this key was addressed by. The attempt count is bounded because the list is attacker-supplied. */
206
+ async function _kariUnwrapAny(kek, reks) {
207
+ var list = reks || [];
208
+ /** @internal The list arrives with the message, so the number of unwraps it can demand is bounded.
209
+ * The bound caps the attempts rather than refusing the list, so an entry within it still opens the
210
+ * message it always opened. */
211
+ var tried = list.length < C.LIMITS.CMS_MAX_KARI_ENCRYPTED_KEYS
212
+ ? list.length : C.LIMITS.CMS_MAX_KARI_ENCRYPTED_KEYS;
213
+ for (var i = 0; i < tried; i++) {
214
+ try { return await _aesKwUnwrap(kek, list[i].encryptedKey); }
215
+ catch (_e) { continue; } // allow:swallow-unverified this entry is not addressed to this key; a later one may be
216
+ }
217
+ if (list.length > tried) {
218
+ throw _err("cms/too-many-recipient-keys", "a KeyAgreeRecipientInfo names " + list.length +
219
+ " encrypted keys and none of the first " + tried + " opened; at most " + tried + " are tried");
220
+ }
221
+ throw _fail();
222
+ }
223
+
201
224
  async function _kariCek(ri, km) {
202
225
  var k = _normKeyDer(km.key);
203
226
  var kek, z, mz;
@@ -207,7 +230,7 @@ async function _kariCek(ri, km) {
207
230
  var wrapAlg = _kariWrap(kea);
208
231
  var scheme = kea.oid;
209
232
  var origSpki = _originatorSpki(ri.originator);
210
- var rek = (km.cert != null && _kariRekFor(ri, x509.parse(_normCertDer(km.cert)))) || ri.recipientEncryptedKeys[0];
233
+ var rek = (km.cert != null && _kariRekFor(ri, x509.parse(_normCertDer(km.cert)))) || null;
211
234
  var kekBytes = WRAP_KEK_LENGTHS[wrapAlg.oid];
212
235
  if (!kekBytes) throw _err("cms/unsupported-algorithm", "unsupported kari key-wrap");
213
236
  var ukm = ri.ukm || null;
@@ -222,7 +245,8 @@ async function _kariCek(ri, km) {
222
245
  } else {
223
246
  var origAlg = asn1.decode(origSpki).children[0];
224
247
  var origHasParams = origAlg.children.length > 1;
225
- var curveOid = (km.cert != null && _ecCurveFromCert(km.cert)) || (origHasParams ? asn1.read.oid(origAlg.children[1]) : null);
248
+ var curveOid = (km.cert != null && _ecCurveFromCert(km.cert)) ||
249
+ (origHasParams ? asn1.read.oid(origAlg.children[1]) : _ecCurveFromPrivateKey(keyDer));
226
250
  var curve = curveOid ? CURVE[curveOid] : null;
227
251
  if (!curve) throw _err("cms/unsupported-algorithm", "unsupported or missing originator EC curve");
228
252
  var origSpkiFull = origHasParams ? origSpki : _withEcCurveParams(origSpki, curveOid);
@@ -232,7 +256,15 @@ async function _kariCek(ri, km) {
232
256
  var zKey = await subtle.importKey("raw", z, { name: "X963KDF" }, false, ["deriveBits"]);
233
257
  kek = Buffer.from(await subtle.deriveBits({ name: "X963KDF", hash: _x963Hash(scheme), info: _eccSharedInfo(wrapAlg.name, ukm, kekBytes) }, zKey, kekBytes * 8));
234
258
  }
235
- return await _aesKwUnwrap(kek, rek.encryptedKey);
259
+ /** @internal A caller that supplied a certificate selects its entry by recipient identifier, which
260
+ * is what that certificate is for. Offering every entry is for the caller that has only a key, and
261
+ * so has no identifier to select by. */
262
+ if (km.cert != null) {
263
+ var chosen = rek || ri.recipientEncryptedKeys[0];
264
+ if (!chosen) throw _fail();
265
+ return await _aesKwUnwrap(kek, chosen.encryptedKey);
266
+ }
267
+ return await _kariUnwrapAny(kek, ri.recipientEncryptedKeys);
236
268
  } finally {
237
269
  guard.secret.zeroizeAll([z, mz, kek], CmsError, "cms/bad-input", "the key-agreement shared secret");
238
270
  _releaseKeyDer(k);
@@ -507,6 +539,19 @@ function _ecCurveFromCert(cert) {
507
539
  if (spki.algorithm.oid !== O("ecPublicKey") || spki.algorithm.parameters == null) return null;
508
540
  return asn1.read.oid(asn1.decode(spki.algorithm.parameters));
509
541
  }
542
+ /** @internal The curve of the recipient's own private key. RFC 5753 sec. 7.1 lets an originator omit its
543
+ * curve parameters because the recipient already knows the curve; a recipient decrypting with a key and
544
+ * no certificate has that knowledge in the key itself, and nowhere else. */
545
+ function _ecCurveFromPrivateKey(keyDer) {
546
+ var spki;
547
+ try {
548
+ spki = nodeCrypto.createPublicKey({ key: keyDer, format: "der", type: "pkcs8" })
549
+ .export({ format: "der", type: "spki" });
550
+ } catch (_e) { return null; } // allow:swallow-unverified a key this runtime cannot read names no curve
551
+ var alg = asn1.decode(spki).children[0];
552
+ if (asn1.read.oid(alg.children[0]) !== O("ecPublicKey") || alg.children.length < 2) return null;
553
+ return asn1.read.oid(alg.children[1]);
554
+ }
510
555
  function _withEcCurveParams(spki, curveOid) {
511
556
  var node = asn1.decode(spki);
512
557
  var alg = node.children[0];
package/lib/constants.js CHANGED
@@ -124,6 +124,7 @@ var LIMITS = Object.assign(Object.create(null), {
124
124
  CBOR_MAX_ITEMS: 1000000,
125
125
  SCT_MAX_BYTES: BYTES.kib(64) + 1,
126
126
  SCT_MAX_COUNT: 256,
127
+ CMS_MAX_KARI_ENCRYPTED_KEYS: 64,
127
128
  MERKLE_MAX_PROOF_NODES: 65,
128
129
  PROXY_MAX_TLS_ANCHORS: 256,
129
130
  PATH_MAX_CERTS: 100,
@@ -4,6 +4,7 @@
4
4
  // @internal
5
5
 
6
6
  var _utilTypes = require("util").types;
7
+ var _nodeCrypto = require("node:crypto");
7
8
 
8
9
  var _call = Function.prototype.call;
9
10
  var _bind = Function.prototype.bind;
@@ -19,6 +20,10 @@ var _bufferByteLength = Buffer.byteLength;
19
20
  var _bufferCompare = Buffer.compare;
20
21
  var _bufferEquals = uncurry(Buffer.prototype.equals);
21
22
  var _bufferToString = uncurry(Buffer.prototype.toString);
23
+ /** @internal Key identity, taken off the KeyObject prototype at load. A caller that replaced this
24
+ * method could make two different keys answer as one, which is the question a proof of possession
25
+ * turns on. */
26
+ var _keyEquals = uncurry(_nodeCrypto.KeyObject.prototype.equals);
22
27
 
23
28
  var _isView = ArrayBuffer.isView;
24
29
  var _isInteger = Number.isInteger;
@@ -146,6 +151,7 @@ module.exports = Object.freeze({
146
151
  byteLength: _bufferByteLength,
147
152
  compare: _bufferCompare,
148
153
  bufferEquals: _bufferEquals,
154
+ keyEquals: _keyEquals,
149
155
  isView: _isView,
150
156
  isInteger: _isInteger,
151
157
  isSafeInteger: _isSafeInteger,
package/lib/schema-cmc.js CHANGED
@@ -42,6 +42,8 @@ var schema = require("./schema-engine");
42
42
  var pkix = require("./schema-pkix");
43
43
  var oid = require("./oid");
44
44
  var cms = require("./schema-cms");
45
+ var csr = require("./schema-csr");
46
+ var crmf = require("./schema-crmf");
45
47
  var guard = require("./guard-all");
46
48
  var frameworkError = require("./framework-error");
47
49
 
@@ -55,6 +57,8 @@ function O(name) { return oid.byName(name); }
55
57
 
56
58
  var OID_PKI_DATA = O("id-cct-PKIData");
57
59
  var OID_PKI_RESPONSE = O("id-cct-PKIResponse");
60
+ var OID_ENCRYPTED_POP = O("id-cmc-encryptedPOP");
61
+ var OID_DECRYPTED_POP = O("id-cmc-decryptedPOP");
58
62
  var OID_STATUS_INFO = O("id-cmc-statusInfo");
59
63
  var OID_STATUS_INFO_V2 = O("id-cmc-statusInfoV2");
60
64
  var OID_RESPONSE_BODY = O("id-cmc-responseBody");
@@ -79,6 +83,11 @@ var CMC_CARRIERS = Object.assign(Object.create(null), { signedData: 1, authData:
79
83
  var CONTROL_PLACEMENT = Object.create(null);
80
84
  CONTROL_PLACEMENT[OID_RESPONSE_BODY] = "pkiResponse";
81
85
  CONTROL_PLACEMENT[OID_RA_IDENTITY_WITNESS] = "pkiData";
86
+ /** @internal The two halves of the challenge-response exchange travel in opposite directions: the
87
+ * authority sends the challenge in its response, and the client answers in its next request (RFC 5272
88
+ * sec. 6.7). A message carrying the other one is not the message that section describes. */
89
+ CONTROL_PLACEMENT[OID_ENCRYPTED_POP] = "pkiResponse";
90
+ CONTROL_PLACEMENT[OID_DECRYPTED_POP] = "pkiData";
82
91
 
83
92
 
84
93
  function readBodyPartId(node, label) {
@@ -429,6 +438,181 @@ var PKI_RESPONSE = schema.seq([
429
438
  },
430
439
  });
431
440
 
441
+ /** @internal The challenge-response proof of possession a server sends when the key being certified
442
+ * cannot sign for itself (RFC 5272 sec. 6.7). The `cms` field is surfaced as the bytes it arrived as,
443
+ * because it is an EnvelopedData a caller decrypts with its own key material rather than something
444
+ * this parser opens. */
445
+ /** @internal The request a challenge quotes is one the client answers for, so it is held to the
446
+ * definition of the arm it uses rather than to its outer tag alone: a proof computed over a request
447
+ * that is not one could never be checked against anything. This is asked of a CHALLENGED request only.
448
+ * A request body carries what its sender sent, and judging it is the enrollment's business, not the
449
+ * decoder's. */
450
+ function _assertAnswerableRequest(request) {
451
+ if (request.arm !== "tcr" && request.arm !== "crm") return;
452
+ /** @internal A CertReqMessages of one, which is the shape the CRMF parser takes; built outside the
453
+ * catch below so only the parse it wraps can be what fails. */
454
+ var payload = request.arm === "tcr" ? request.certificationRequestBytes
455
+ : asn1.build.sequence([asn1.build.raw(request.certReqMsgBytes)]);
456
+ try {
457
+ if (request.arm === "tcr") { csr.parse(payload); } else { crmf.parse(payload); }
458
+ } catch (e) {
459
+ throw E("cmc/bad-pop-challenge",
460
+ "the request an EncryptedPOP quotes is not a " +
461
+ (request.arm === "tcr" ? "PKCS#10 CertificationRequest" : "CRMF CertReqMsg") +
462
+ ", so a proof over it could not be checked: " + ((e && e.message) || "malformed") +
463
+ " (RFC 5272 sec. 6.7)", e);
464
+ }
465
+ }
466
+
467
+ function parseEncryptedPop(node) {
468
+ if (node.tagClass !== "universal" || node.tagNumber !== TAGS.SEQUENCE || !node.constructed ||
469
+ node.children.length !== 5) {
470
+ throw E("cmc/bad-pop-challenge",
471
+ "an EncryptedPOP is SEQUENCE { request, cms, thePOPAlgID, witnessAlgID, witness } (RFC 5272 sec. 6.7)");
472
+ }
473
+ var envelope = _assertEnvelopedChallenge(node.children[1]);
474
+ var request;
475
+ try { request = parseTaggedRequest(node.children[0]); }
476
+ catch (e) {
477
+ throw E("cmc/bad-pop-challenge",
478
+ "an EncryptedPOP quotes the request it challenges as a TaggedRequest: " +
479
+ ((e && e.message) || "malformed") + " (RFC 5272 sec. 6.7)", e);
480
+ }
481
+ _assertAnswerableRequest(request);
482
+ return {
483
+ request: request,
484
+ /** @internal The TaggedRequest exactly as it arrived. A proof of possession is a MAC over these
485
+ * bytes, and the challenge carries them so neither side has to re-encode the request to agree on
486
+ * what was covered (RFC 5272 sec. 6.7). */
487
+ requestBytes: node.children[0].bytes,
488
+ cms: envelope.bytes,
489
+ cmsRecipientCount: envelope.recipientCount,
490
+ thePOPAlgID: _popAlgorithm(node.children[2], "thePOPAlgID"),
491
+ witnessAlgID: _popAlgorithm(node.children[3], "witnessAlgID"),
492
+ witness: _popOctetString(node.children[4], "witness"),
493
+ };
494
+ }
495
+
496
+ /** @internal A leaf of one of the POP controls. A malformed one is a malformed challenge, so it carries
497
+ * this control's code rather than the codec's. */
498
+ function _popOctetString(node, what) {
499
+ try { return asn1.read.octetString(node); }
500
+ catch (e) {
501
+ throw E("cmc/bad-pop-challenge", "a POP " + what + " is an OCTET STRING (RFC 5272 sec. 6.7)", e);
502
+ }
503
+ }
504
+
505
+ function parseDecryptedPop(node) {
506
+ if (node.tagClass !== "universal" || node.tagNumber !== TAGS.SEQUENCE || !node.constructed ||
507
+ node.children.length !== 3) {
508
+ throw E("cmc/bad-pop-challenge",
509
+ "a DecryptedPOP is SEQUENCE { bodyPartID, thePOPAlgID, thePOP } (RFC 5272 sec. 6.7)");
510
+ }
511
+ var bodyPartID;
512
+ try { bodyPartID = readBodyPartIdentity(node.children[0]); }
513
+ catch (e) {
514
+ throw E("cmc/bad-pop-challenge",
515
+ "a DecryptedPOP names the certification request it proves with a BodyPartID: " +
516
+ ((e && e.message) || "malformed") + " (RFC 5272 sec. 6.7)", e);
517
+ }
518
+ return {
519
+ bodyPartID: bodyPartID,
520
+ thePOPAlgID: _popAlgorithm(node.children[1], "thePOPAlgID"),
521
+ thePOP: _popOctetString(node.children[2], "thePOP"),
522
+ };
523
+ }
524
+
525
+ /** @internal The proof value travels in an EnvelopedData (RFC 5272 sec. 6.7), and the bytes are handed
526
+ * on unopened because opening them needs key material this parser does not hold. Unopened is not
527
+ * unchecked: a field that is not a ContentInfo carrying an EnvelopedData cannot be a challenge, and
528
+ * saying so here is what keeps a control that could never be answered from reading as one. */
529
+ function _assertEnvelopedChallenge(node) {
530
+ var kids = pkix.rootSequenceChildren(node, 2, 2);
531
+ if (!kids) {
532
+ throw E("cmc/bad-pop-challenge",
533
+ "an EncryptedPOP carries the proof value in a CMS ContentInfo, which is a SEQUENCE of a content " +
534
+ "type and its content (RFC 5272 sec. 6.7)");
535
+ }
536
+ var contentType;
537
+ try { contentType = asn1.read.oid(kids[0]); }
538
+ catch (e) {
539
+ throw E("cmc/bad-pop-challenge",
540
+ "an EncryptedPOP's ContentInfo names its content type with an OBJECT IDENTIFIER (RFC 5272 sec. 6.7)", e);
541
+ }
542
+ if (contentType !== O("envelopedData")) {
543
+ throw E("cmc/bad-pop-challenge",
544
+ "an EncryptedPOP carries the proof value in an EnvelopedData, got " +
545
+ (oid.name(contentType) || contentType) + " (RFC 5272 sec. 6.7)");
546
+ }
547
+ var content = kids[1];
548
+ if (content.tagClass !== "context" || content.tagNumber !== 0 || !content.constructed ||
549
+ content.children.length !== 1) {
550
+ throw E("cmc/bad-pop-challenge",
551
+ "an EncryptedPOP's ContentInfo carries its content in [0] EXPLICIT (RFC 5652 sec. 3)");
552
+ }
553
+ /** @internal Validated by the CMS EnvelopedData schema itself rather than by a shape check written
554
+ * here, so every field is held to one definition and the count reported below is the count of
555
+ * recipients that same definition accepted. Sec. 6.7 also allows a recipient identified by an
556
+ * issuerAndSerialNumber whose issuer is encoded as NULL, which is not the Name that schema requires;
557
+ * a challenge addressed only that way is refused here, and `pki.cms.decrypt` could not open it
558
+ * either, so it is refused where the reason can be named rather than after a failed answer. */
559
+ var enveloped;
560
+ try { enveloped = cms.walkEnvelopedData(content.children[0]); }
561
+ catch (e) {
562
+ throw E("cmc/bad-pop-challenge",
563
+ "an EncryptedPOP's ContentInfo does not carry an EnvelopedData a recipient could open: " +
564
+ ((e && e.message) || "malformed") + " (RFC 5652 sec. 6.1)", e);
565
+ }
566
+ var recipients = (enveloped.recipientInfos || []).length;
567
+ if (recipients < 1) {
568
+ throw E("cmc/bad-pop-challenge",
569
+ "an EnvelopedData names at least one recipient in its recipientInfos SET (RFC 5652 sec. 6.1)");
570
+ }
571
+ return { bytes: node.bytes, recipientCount: recipients };
572
+ }
573
+
574
+ /** @internal Both fields are AlgorithmIdentifiers, and both are read the same way: the OID names the
575
+ * algorithm and the parameters travel with it, so a caller answering a challenge copies what it was
576
+ * sent rather than reconstructing it. */
577
+ function _popAlgorithm(node, what) {
578
+ if (node.tagClass !== "universal" || node.tagNumber !== TAGS.SEQUENCE || !node.constructed ||
579
+ node.children.length < 1 || node.children.length > 2) {
580
+ throw E("cmc/bad-pop-challenge", "a POP " + what + " is an AlgorithmIdentifier (RFC 5272 sec. 6.7)");
581
+ }
582
+ var algOid;
583
+ try { algOid = asn1.read.oid(node.children[0]); }
584
+ catch (e) {
585
+ throw E("cmc/bad-pop-challenge",
586
+ "a POP " + what + " names its algorithm with an OBJECT IDENTIFIER (RFC 5272 sec. 6.7)", e);
587
+ }
588
+ return {
589
+ oid: algOid,
590
+ name: oid.name(algOid) || null,
591
+ parameters: node.children.length === 2 ? node.children[1].bytes : null,
592
+ bytes: node.bytes,
593
+ };
594
+ }
595
+
596
+ /** @internal One AttributeValue, which is what a control carrying a single structure holds. */
597
+ function _onlyValue(c, what) {
598
+ if (c.values.length !== 1) {
599
+ throw E("cmc/bad-pop-challenge",
600
+ "a " + what + " control carries exactly one AttributeValue, got " + c.values.length);
601
+ }
602
+ return asn1.decode(c.values[0]);
603
+ }
604
+
605
+ function _decodePopChallenges(controls) {
606
+ for (var i = 0; i < controls.length; i++) {
607
+ var c = controls[i];
608
+ if (c.attrType === OID_ENCRYPTED_POP) {
609
+ c.encryptedPOP = parseEncryptedPop(_onlyValue(c, "an Encrypted POP"));
610
+ } else if (c.attrType === OID_DECRYPTED_POP) {
611
+ c.decryptedPOP = parseDecryptedPop(_onlyValue(c, "a Decrypted POP"));
612
+ }
613
+ }
614
+ }
615
+
432
616
  function _collectStatuses(controls) {
433
617
  var out = [];
434
618
  for (var i = 0; i < controls.length; i++) {
@@ -445,6 +629,7 @@ function _collectStatuses(controls) {
445
629
 
446
630
  function _finishBody(body, where) {
447
631
  for (var i = 0; i < body.controls.length; i++) assertControlPlacement(body.controls[i], where);
632
+ _decodePopChallenges(body.controls);
448
633
  body.statuses = _collectStatuses(body.controls);
449
634
  body.unhandled = body.controls.filter(function (c) {
450
635
  return c.attrType !== OID_STATUS_INFO && c.attrType !== OID_STATUS_INFO_V2 && c.attrName === null;
@@ -541,9 +726,20 @@ function parsePkiResponse(input) {
541
726
  * pki.schema.cmc.parse(der).kind; // "pkiData"
542
727
  */
543
728
  function parse(input) {
544
- var parsedCms = (input && typeof input === "object" && !ArrayBuffer.isView(input) &&
545
- !guard.bytes.isByteSource(input) && input.encapContentInfo != null)
546
- ? input : cms.parse(input);
729
+ var alreadyParsed = input && typeof input === "object" && !ArrayBuffer.isView(input) &&
730
+ !guard.bytes.isByteSource(input) && input.encapContentInfo != null;
731
+ var parsedCms;
732
+ if (alreadyParsed) { parsedCms = input; }
733
+ else {
734
+ /** @internal Bytes that are not a CMS message at all are a CMC message this cannot read, and every
735
+ * other format parser answers for its own input in its own domain. */
736
+ try { parsedCms = cms.parse(input); }
737
+ catch (e) {
738
+ throw E("cmc/bad-der",
739
+ "a CMC message is carried in a CMS SignedData or AuthenticatedData, and these bytes are not " +
740
+ "one: " + ((e && e.message) || "malformed") + " (RFC 5272 sec. 3.2 / 4.2)", e);
741
+ }
742
+ }
547
743
  if (CMC_CARRIERS[parsedCms.contentTypeName] !== 1) {
548
744
  throw E("cmc/not-cmc",
549
745
  "a Full PKI Request / Response is carried in a CMS SignedData or AuthenticatedData, got " +
@@ -568,6 +764,8 @@ function parse(input) {
568
764
  }
569
765
 
570
766
  module.exports = {
767
+ parseEncryptedPop: parseEncryptedPop,
768
+ parseTaggedRequest: parseTaggedRequest,
571
769
  parse: parse,
572
770
  parsePkiData: parsePkiData,
573
771
  parsePkiResponse: parsePkiResponse,
package/lib/schema-cms.js CHANGED
@@ -555,7 +555,9 @@ var KEY_AGREE_RECIPIENT_INFO = schema.seq([
555
555
  schema.field("originator", schema.explicit(0, ORIGINATOR_IDENTIFIER_OR_KEY, { code: "cms/bad-kari" })),
556
556
  schema.optional("ukm", schema.octetString(), { tag: 1, explicit: true, emptyCode: "cms/bad-kari" }),
557
557
  schema.field("keyEncryptionAlgorithm", ALGORITHM_IDENTIFIER),
558
- schema.field("recipientEncryptedKeys", schema.seqOf(RECIPIENT_ENCRYPTED_KEY, { code: "cms/bad-recipient-encrypted-keys", what: "recipientEncryptedKeys" })),
558
+ /** @internal At least one encrypted key: a key-agreement recipient info that names none names no
559
+ * recipient, so nothing could open the content it is attached to. */
560
+ schema.field("recipientEncryptedKeys", schema.seqOf(RECIPIENT_ENCRYPTED_KEY, { min: 1, code: "cms/bad-recipient-encrypted-keys", what: "recipientEncryptedKeys" })),
559
561
  ], {
560
562
  assert: "constructed", code: "cms/bad-kari", what: "KeyAgreeRecipientInfo",
561
563
  build: function (m) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.48",
3
+ "version": "0.6.49",
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:2d1b2e87-6386-4481-940b-f4de0f1b9227",
5
+ "serialNumber": "urn:uuid:082f242e-4786-4518-b201-8797b47662eb",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-06T18:47:52.624Z",
8
+ "timestamp": "2026-09-07T02:07:15.421Z",
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.48",
22
+ "bom-ref": "@blamejs/pki@0.6.49",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.48",
25
+ "version": "0.6.49",
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.48",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.49",
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.48",
57
+ "ref": "@blamejs/pki@0.6.49",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]