@blamejs/pki 0.5.24 → 0.5.26

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,60 @@ 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.5.26 — 2026-08-22
8
+
9
+ Revoking a certificate and asking a certification authority what it offers now go through the same verified CMP transaction as enrollment.
10
+
11
+ ### Added
12
+
13
+ - `session.revoke(request)` drives the RFC 9483 sec. 4.2 revocation exchange. The request names the certificate as `{ certificate }` or as `{ certDetails: { issuer, serialNumber } }`, with an optional `reason` taking a CRLReason name. It returns a terminal verdict of `revoked`, `rejected`, or `poll-timeout`, carrying the responder's `PKIStatusInfo` and any `CertId` values and CRLs the response supplied.
14
+ - `session.info(request)` drives the four RFC 9483 sec. 4.3 support messages, one per call. `{ caCerts: true }` asks for the certification authority certificates available for chain construction. `{ rootCaCert: <cert> }` asks for a root key update and reads the `RootCaKeyUpdateContent` reply. `{ certReqTemplate: true }` asks for the requirements a future certificate request should meet, returning the template and any `keySpec` constraints. `{ crlUpdate: { issuer, dpn?, thisUpdate? } }` asks for a CRL from a named source. The verdict is `answered`, `rejected`, or `poll-timeout`; `answered` reports `present` alongside `value`, since an absent response value is how each of the four says nothing is available.
15
+ - `pki.cmp.build` accepts a structured `crlEntryDetails` on an `rr` body: `{ reason: 'keyCompromise' }` encodes the reasonCode extension the profile requires. A pre-encoded `Extensions` DER is still accepted for an entry extension outside that shape.
16
+ - The `id-regCtrl-algId`, `id-regCtrl-rsaKeyLen`, and `id-regCtrl-altCertTemplate` object identifiers RFC 9480 sec. 2.16 adds are in the registry, so a `keySpec` control resolves to a name.
17
+
18
+ ### Changed
19
+
20
+ - Delayed delivery is recognized for a revocation and a support message. RFC 9483 sec. 4.4 puts the `waiting` status in an `ip`, `cp`, or `kup` when answering an enrollment and in an error message when answering anything else, so an error body carrying `waiting` now drives the bounded poll loop for those two operations, with the `pollReq` referring to the whole message. An error message that is not delayed delivery must state the rejection status: an error naming `accepted`, `grantedWithMods`, or another non-rejection status, or a `waiting` carrying `failInfo`, is refused as malformed rather than surfaced as a trusted rejection verdict its own `PKIStatusInfo` contradicts. An enrollment has no delayed-delivery error at all — the profile places enrollment `waiting` in an `ip`, `cp`, or `kup` — so a `waiting` error answering an enrollment is refused, not read as a rejection.
21
+ - One transaction per session covers all three verbs. A session that has revoked will not then enroll, because both would run under the same transactionID and nonce chain.
22
+
23
+ ### Security
24
+
25
+ - A session revokes its own certificate. The signature over an `rr` is the proof of authorization to revoke (RFC 9483 sec. 4.2), so the certificate named in the request must be the one the session protects its messages with, compared by serial number and by the RFC 5280 sec. 7.1 canonical distinguished-name rule. A PBMAC1 session is refused outright: a shared secret establishes a bootstrapping relationship and says nothing about which certificate the holder may revoke. Revocation on behalf of another entity is a registration authority operation and is driven with `pki.cmp.build` and `pki.cmp.transfer`.
26
+ - The reasonCode is always sent, at `unspecified(0)` when no reason is given. RFC 9483 sec. 4.2 makes `crlEntryDetails` required and says the code must be 0 when the reason is unknown or is not to be published. This is the opposite of the RFC 5280 sec. 5.3.1 rule for a CRL entry, where absence and `unspecified` carry the same meaning and the extension is omitted, so the CRL behavior is not reused here.
27
+ - A response is held to the shape its operation defines before its content is read. An `rp` must carry exactly one status, and an accepted one must not also carry `failInfo`. When an accepted `rp` names the certificates it revoked in `revCerts`, that entry is bound to the certificate the request named: exactly one entry, its issuer and serialNumber equal to the revoked certificate's under the RFC 5280 sec. 7.1 canonical rule, so a verified `revoked` verdict cannot report an unrelated certificate as revoked. A `genp` must carry exactly one `InfoTypeAndValue`, whose infoType must be the one that operation is answered with: a root key update is requested with `id-it-rootCaCert` and answered with `id-it-rootCaKeyUpdate`, so a response echoing the request identifier is a different operation's answer and is refused.
28
+ - A `rootCaKeyUpdate` response must carry `newWithOld`, and the three certificates must stand in the relationships that make a root key update work. RFC 9480 marks the field OPTIONAL in the syntax and RFC 9483 sec. 4.3.2 requires it of a response, for the reason it states: an entity that trusts the old root needs that certificate to gain trust in the new one. That is a claim about signatures and keys, not about the fields being present, so `newWithOld` is checked to carry the new root key, to name the same subject as `newWithNew`, and to be issued and signed by the old root named in the request, and `oldWithNew`, when sent, to carry the old root key, name the old root, and be issued and signed by the new one. The names matter as much as the keys: a certification authority that has ever issued an ordinary certificate for the new key satisfies key equality and signature validity on its own, and its holder could pair it with a self-signed certificate of their choosing and have the result read as the authority's rollover. Names are compared under the RFC 5280 sec. 7.1 canonical rule, so a re-encoded but equal name still matches. Each of the three must also carry the authority the update transfers — `basicConstraints` with `cA` TRUE, and a `keyUsage`, where present, that allows `keyCertSign` — since an ordinary end-entity certificate for the same subject and key satisfies names, key and signature while being able to certify nothing. `newWithNew` is checked under its own key when it is self-issued, which is the case for a root; sec. 4.3.2 also extends this operation to a directly trusted non-root certificate, whose issuer the message does not carry, and there its own signature is left unchecked rather than the update refused for a check that cannot be run. Three certificates that merely parse establish neither direction of the transition. The signatures go through the same certification-path engine that verifies a message's protection, so the EdDSA low-order-point and algorithm-confusion gates apply here too, and a signature that is not octet-aligned (a BIT STRING declaring unused bits) is refused before the engine, the same shape the path verifier rejects. The certificate the request names as the current root is itself held to being a CA — refused at the door, before the one-shot transaction engages — since the response's rollover signatures are verified against its key, and an end-entity certificate there would let a cross-certificate read as a rollover.
29
+ - A `certReqTemplate` response must omit `publicKey`, `serialNumber`, `signingAlg`, `issuerUID`, and `subjectUID` from its template (RFC 9483 sec. 4.3.3). A template stating a public key would direct an entity to request a certificate over a key the responder chose, which is what the `keySpec` field exists to avoid. A `keySpec` control must be `id-regCtrl-algId` carrying a non-RSA AlgorithmIdentifier or `id-regCtrl-rsaKeyLen` carrying a positive integer. "Other than RSA" is decided by OID family. Every object identifier under an RSA-dedicated arc — the PKCS#1 arc, the TeleTrusT rsaSignature arc, or the BSI TR-03110 id-TA-RSA arc (EAC Terminal Authentication) — is an RSA algorithm, save the PKCS#1 arc's two auxiliary parameters (`mgf1` and `pSpecified`, the mask-generation and OAEP-label identifiers), which are not RSA algorithms and are surfaced, so a standardized member this toolkit has not separately named — `sha1WithRSAEncryption`, the `md*` and `sha224` variants — is refused with the ones it has; the RSA identifiers on arcs it shares with non-RSA algorithms — `id-rsa-kem`, `id-kem-rsa`, the RSASSA-PKCS1-v1_5-with-SHA-3 set, RSASSA-PSS-with-SHAKE, every legacy OIW RSA identifier on the arc it shares with DES, DSA, and the hashes, the X.500 directory RSA OIDs (the `rsa` public-key identifier and the signatureAlgorithm sub-arc's RSA members), and the Chinese GM/T `sm3WithRSAEncryption` — are named explicitly, since no prefix can isolate RSA there. Each arc is read from the registry rather than written as a literal, so `pki.oid.register` cannot move it underneath the check. The composite ML-DSA + RSA signatures are deliberately not refused: a hybrid is a composite key rather than an RSA one, and `rsaKeyLen` cannot state it either. That is the only rule the control is held to: an algorithm the registry cannot name is surfaced rather than refused, since a `keySpec` carries one entry per algorithm the CA supports and the entity picks one it can generate, so an unrecognized offer is passed to the caller with a null name rather than failing the whole exchange and dropping the algorithms alongside it.
30
+ - A CRL answer is bound to the query that asked for it. RFC 9483 sec. 4.3.4 does not say a responder returns a CRL; it returns the latest one from the referenced source, and only when it is more recent than a `thisUpdate` the request supplied, with the response value absent in every other case. A CRL from another issuer, or one no newer than the copy the caller already holds, answers a different question, so it is refused rather than reported as `answered`. The issuer is compared under the RFC 5280 sec. 7.1 canonical rule. A request that names a distribution point is bound to that point wherever the CRL states one: RFC 5280 sec. 5.2.5 puts the scope in `issuingDistributionPoint`, and sec. 4.3.4's own note names that extension as a place a distribution point name is obtained from. The test is the one RFC 5280 sec. 6.3.3 applies to a shard CRL, at least one name in common compared as identical encodings, which sec. 5.2.5 requires of the two fields; a canonical comparison would accept a CRL published for a point the request never named. A CRL stating no scope is claiming to be its issuer's complete list, which sec. 5.2.5 permits and which answers a request for any point of that issuer, so the distribution point cannot bind that case. The issuer is required for it: a request naming a `dpn` must name an `issuer` as well, and the two are used differently. `CRLSource` is a CHOICE, so the message carries the distribution point (sec. 4.3.4 sends that alternative when a distribution point name is available), while the issuer states which CA's CRL the caller will accept. A `dpn` alone is refused rather than answered with a CRL from a CA nobody named; sec. 4.3.4's own note says a distribution point name is obtained from a certificate's `cRLDistributionPoints` or from a held CRL's `issuingDistributionPoint`, and both carry the issuer alongside it. An unbound request is still available through `pki.cmp.build` and `pki.cmp.transfer`.
31
+
32
+ ### Notes
33
+
34
+ - A `crlUpdate` request carries one `CRLSource` alternative, since it is a CHOICE: the `dpn` when a distribution point name is given, the `issuer` otherwise. The `dpn` arm takes `fullName`; the `nameRelativeToCRLIssuer` alternative is not built, which is the line `pki.crl.sign` already draws for `issuingDistributionPoint` and `freshestCRL`.
35
+ - The registration authority side of these operations is unchanged: `krr` and `ccr` requests and the `nested` body remain unbuildable, and a session has no way to resume a poll across a process restart.
36
+
37
+ ## v0.5.25 — 2026-08-21
38
+
39
+ A key that cannot sign can now prove possession, so an ML-KEM certificate request has a proof to carry instead of no option at all.
40
+
41
+ ### Added
42
+
43
+ - `pki.crmf.build` emits a `POPOPrivKey` proof of possession under `pop.type` of `keyEncipherment` or `keyAgreement`. `pop.method: 'subsequentMessage'` with `pop.subsequentMessage` of `encrCert` or `challengeResp` declares which follow-up exchange completes the proof (RFC 9810 sec. 5.2.8.3.2 and sec. 5.2.8.3.3); no key material leaves the requester and every key type can produce it. `pop.method: 'encryptedKey'` encloses the requester's private key for the certification authority in a CMS `EnvelopedData` whose content type is `id-ct-encKeyWithID`, taking `pop.privateKey`, `pop.recipients`, `pop.identifier`, and `pop.archive: true`. `pki.cmp.build` carries either in an `ir`, `cr`, or `kur` body.
44
+ - The requested version follows what the message carries: a CMP request whose proof of possession uses `encryptedKey` or `agreeMAC` announces cmp2021(3), which RFC 9810 sec. 5.2.8.3 requires. Before this a request carrying an `encryptedKey` proof went out announcing cmp2000(2), and this toolkit's own reader refused the message it had just built.
45
+
46
+ ### Changed
47
+
48
+ - `spec.pop` refuses a field it does not recognize. Each rule below is one a caller turns off by naming it, so a misspelled key must not read as an omitted one: `archve: true` would have withheld the archival consent while appearing to give it.
49
+
50
+ ### Security
51
+
52
+ - An `encryptedKey` proof must enclose the private half of `certTemplate.publicKey`. RFC 4211 sec. 4.2 defines the field as "the encrypted private key matching the public key for which the certificate is to be issued"; enclosing any other key proves possession of something the request never asked to have certified, while every structural check still passes. The public key is derived from the supplied private key through the toolkit's own key engine and compared before the message is built.
53
+ - An `encryptedKey` proof requires `pop.identifier`. The ASN.1 marks `EncKeyWithID.identifier` OPTIONAL and RFC 4211 sec. 4.2.1 then makes it mandatory whenever the purpose is proving possession, for a reason the section states: without it a decrypting agent holds a key it cannot attribute, so an intercepted key can be wrapped in someone else's request and recovered.
54
+ - The two alternatives RFC 4211 sec. 4.2 deprecates as it defines them, `thisMessage` and `dhMAC`, are refused with their successors named. `pki.schema.crmf.parse` still reads both, since a peer may send one.
55
+ - A `keyEncipherment` proof cannot carry a MAC alternative. RFC 4211 sec. 4.2 lists three methods for an encipherment key and introduces the MAC alternatives only in sec. 4.3, "for keyAgreement (only)". The parser already refused such a message; the builder no longer produces one.
56
+
57
+ ### Notes
58
+
59
+ - The `agreeMAC` proof is not built. It requires the RFC 2875 static Diffie-Hellman shared secret between the requester's key and a certification authority certificate the requester already holds, a classical key-agreement primitive this toolkit does not otherwise carry. `pki.crmf.verifyPop` continues to report an inbound `agreeMAC` as unverified, naming the arm. Use `subsequentMessage`, which any key type can produce.
60
+
7
61
  ## v0.5.24 — 2026-08-21
8
62
 
9
63
  An ACME certificate download is now bound to the order that asked for it, so a certificate for another key or another name is refused instead of returned as the issued one.
package/README.md CHANGED
@@ -232,8 +232,8 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
232
232
  | `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key), subject alternative names, and certificate policies from the spec, taking any other extension as pre-encoded DER. It derives the version from the field set and enforces the serial bounds, the UTCTime/GeneralizedTime cutover, the DER default omissions, and the CA cross-field rules; a violation throws a typed `CertificateError`. Returns DER, or a PEM `CERTIFICATE` with `opts.pem`. Every arm is independently verified by OpenSSL. Parsing stays at `pki.schema.x509.parse` — `sign` |
233
233
  | `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` |
234
234
  | `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` |
235
- | `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. 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` |
236
- | `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`, `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, and responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`. 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. `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 }`. 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` |
235
+ | `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` |
236
+ | `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`, `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, and responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`. 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. `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 }`. 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` |
237
237
  | `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` |
238
238
  | `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` |
239
239
  | `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
package/lib/cmp-build.js CHANGED
@@ -31,9 +31,29 @@
31
31
  // shared lib/pki-build primitives, bound to the cmp namespace.
32
32
 
33
33
  var asn1 = require("./asn1-der");
34
+ var schema = require("./schema-engine");
34
35
  var oid = require("./oid");
35
36
  var cmp = require("./schema-cmp");
36
37
  var crmf = require("./crmf-sign");
38
+ var schemaCrmf = require("./schema-crmf");
39
+ var intrinsic = require("./guard-intrinsic");
40
+ // Own-key membership through an operation taken at load: it decides which proof-of-possession
41
+ // methods couple the message to a protocol version, and an inherited name is one no RFC defined.
42
+ var _hasOwn = intrinsic.hasOwn;
43
+ // The same load-bound treatment for the operations that shape a revocation request and a support
44
+ // message: each decides what reaches the wire, so a replaced built-in must not get a say.
45
+ var _isArray = intrinsic.isArray;
46
+ var _isBuffer = intrinsic.isBuffer;
47
+ var _bufferConcat = intrinsic.bufferConcat;
48
+ var _map = intrinsic.map;
49
+ var _keys = intrinsic.keys;
50
+ var _forEach = intrinsic.forEach;
51
+ var _push = intrinsic.push;
52
+ var _stringify = intrinsic.stringify;
53
+ var _bigInt = intrinsic.BigInt;
54
+ // The constructor taken at load: re-materializing an instant that is about to be encoded must not
55
+ // go through a Date a caller could have replaced after this module was read.
56
+ var _Date = intrinsic.Date;
37
57
  var csr = require("./schema-csr");
38
58
  var crl = require("./schema-crl");
39
59
  var x509 = require("./schema-x509");
@@ -262,10 +282,14 @@ function _encodeGenMsgContent(list) {
262
282
  // RevReqContent ::= SEQUENCE OF RevDetails { certDetails CertTemplate, crlEntryDetails Extensions OPTIONAL }.
263
283
  function _encodeRevDetails(rd) {
264
284
  if (!rd || typeof rd !== "object" || Buffer.isBuffer(rd)) throw _err("cmp/bad-rev-req", "each RevDetails must be an object { certDetails, crlEntryDetails? }");
285
+ guard.identifier.assertKnownKeys(rd, KNOWN_REV_DETAILS_KEYS, _err, "cmp/bad-rev-req", "unknown RevDetails field ");
265
286
  if (rd.certDetails == null) throw _err("cmp/bad-rev-req", "RevDetails.certDetails (a CertTemplate) is required");
266
287
  var certDetails;
267
- if (Buffer.isBuffer(rd.certDetails) || rd.certDetails instanceof Uint8Array) {
268
- certDetails = b.raw(_b.reqDer(rd.certDetails, "RevDetails.certDetails (a pre-encoded CertTemplate DER)"));
288
+ if (guard.bytes.isByteSource(rd.certDetails)) {
289
+ // The pre-encoded escape hatch: normalized through the byte guard so every BufferSource the guard
290
+ // accepts (Buffer, any typed-array view, DataView, raw ArrayBuffer) is taken, not a narrowed subset
291
+ // that would drop a caller's container into the { issuer, serialNumber } branch below.
292
+ certDetails = b.raw(guard.bytes.snapshotSource(rd.certDetails, CmpError, "cmp/bad-rev-req", "RevDetails.certDetails (a pre-encoded CertTemplate DER)"));
269
293
  } else {
270
294
  // A revocation must identify the certificate to revoke by issuer + serialNumber (RFC 9810 App. D sec.
271
295
  // 5.3.2); the pre-encoded-CertTemplate hatch above is the escape for an advanced identification.
@@ -273,10 +297,153 @@ function _encodeRevDetails(rd) {
273
297
  certDetails = b.raw(crmf.buildCertTemplate(rd.certDetails));
274
298
  }
275
299
  var children = [certDetails];
276
- if (rd.crlEntryDetails != null) children.push(b.raw(_b.reqDer(rd.crlEntryDetails, "RevDetails.crlEntryDetails (a pre-encoded Extensions DER)")));
300
+ if (rd.crlEntryDetails != null) children.push(b.raw(_encodeCrlEntryDetails(rd.crlEntryDetails)));
277
301
  return b.sequence(children);
278
302
  }
279
303
 
304
+ // crlEntryDetails ::= Extensions. A revocation request states WHY, so the structured form
305
+ // { reason } encodes the single reasonCode extension RFC 9483 sec. 4.2 requires. A caller
306
+ // needing another entry extension passes a pre-encoded Extensions DER instead.
307
+ //
308
+ // The reasonCode is emitted even at unspecified(0). RFC 5280 sec. 5.3.1 omits that value from a
309
+ // CRL entry, where absence and unspecified carry the same meaning; sec. 4.2 governs a different
310
+ // structure and says the field is REQUIRED and "MUST be 0 (unspecified)" when the reason is
311
+ // unknown or is not to be published, so the omit-on-zero rule does not travel here.
312
+ var KNOWN_REV_DETAILS_KEYS = { certDetails: 1, crlEntryDetails: 1 };
313
+ var KNOWN_CRL_ENTRY_DETAIL_KEYS = { reason: 1 };
314
+ var CRL_REASON_BY_NAME = intrinsic.create(null);
315
+ _forEach(_keys(constants.NAMES.CRL_REASON), function (v) { CRL_REASON_BY_NAME[constants.NAMES.CRL_REASON[v]] = intrinsic.Number(v); });
316
+ function _encodeCrlEntryDetails(spec) {
317
+ // A pre-encoded Extensions DER is classified through the byte guard and normalized through it, so
318
+ // every BufferSource form is taken as bytes. A narrowed check would drop a raw ArrayBuffer / DataView
319
+ // into the { reason } branch below, where an absent reason silently becomes a generated unspecified(0)
320
+ // reasonCode -- a different revocation reason than the caller encoded.
321
+ if (guard.bytes.isByteSource(spec)) return guard.bytes.snapshotSource(spec, CmpError, "cmp/bad-rev-req", "RevDetails.crlEntryDetails (a pre-encoded Extensions DER)");
322
+ // After the byte guard, the only valid structured form is a plain { reason? } record. Anything else --
323
+ // an array, a Date/Map/Set or other exotic, a boxed primitive -- carries no `reason`, so the fallback
324
+ // below would read undefined and emit a generated unspecified(0) reasonCode: a real revocation reason
325
+ // the caller never wrote, from a value outside the documented { reason } | DER union. assertKnownKeys
326
+ // does not catch these (an empty array or a keyless exotic has no unknown key to reject), so the value
327
+ // is held to being a plain record through guard.identifier.assertPlainRecord rather than a bare
328
+ // typeof-object test.
329
+ guard.identifier.assertPlainRecord(spec, _err, "cmp/bad-rev-req", "RevDetails.crlEntryDetails ({ reason } or a pre-encoded Extensions DER)");
330
+ guard.identifier.assertKnownKeys(spec, KNOWN_CRL_ENTRY_DETAIL_KEYS, _err, "cmp/bad-rev-req", "unknown crlEntryDetails field ");
331
+ // Read `reason` ONCE: a caller getter or Proxy could otherwise answer the validation with one value
332
+ // (a known reason) and the encode with another (null -> a generated unspecified(0)), so the request
333
+ // would carry a different revocation reason than the one that was checked.
334
+ // Read `reason` ONCE, consistent with the module's read-once discipline: build() already deep-copies
335
+ // the caller's message at entry, so a getter or Proxy cannot vary between the reads here, but reading
336
+ // one local keeps validation and encode on the same value with no dependence on that upstream copy.
337
+ var reason = spec.reason;
338
+ if (reason != null && (typeof reason !== "string" || !_hasOwn(CRL_REASON_BY_NAME, reason))) {
339
+ throw _err("cmp/bad-rev-req", "unknown CRLReason " + _stringify(reason) + " (RFC 5280 sec. 5.3.1)");
340
+ }
341
+ var code = reason == null ? 0 : CRL_REASON_BY_NAME[reason];
342
+ return b.sequence([_b.ext(O("reasonCode"), false, b.enumerated(_bigInt(code)))]);
343
+ }
344
+
345
+ // ---- support-message request values (RFC 9480 sec. 2.17, profiled by RFC 9483 sec. 4.3.4) ----
346
+ //
347
+ // CRLSource ::= CHOICE { dpn [0] DistributionPointName, issuer [1] GeneralNames }
348
+ // CRLStatus ::= SEQUENCE { source CRLSource, thisUpdate Time OPTIONAL }
349
+ // CRLStatusListValue ::= SEQUENCE SIZE (1..MAX) OF CRLStatus
350
+ //
351
+ // The CMP module is EXPLICIT TAGS, so CRLSource's own [0] / [1] wrap their alternative. The
352
+ // DistributionPointName inside the dpn arm keeps the IMPLICIT tagging of the module it is
353
+ // imported from, which is why its fullName [0] is a bare context-constructed GeneralNames.
354
+ var KNOWN_CRL_STATUS_KEYS = { dpn: 1, issuer: 1, thisUpdate: 1 };
355
+ var KNOWN_DPN_KEYS = { fullName: 1 };
356
+ function buildCrlStatusList(spec) {
357
+ if (!spec || typeof spec !== "object" || _isBuffer(spec)) throw _err("cmp/bad-input", "a crlUpdate request must be an object { dpn | issuer, thisUpdate? }");
358
+ guard.identifier.assertKnownKeys(spec, KNOWN_CRL_STATUS_KEYS, _err, "cmp/bad-input", "unknown crlUpdate field ");
359
+ // Each caller field is read ONCE, here, and every use below is of the value that was read. A
360
+ // second read of the same field can answer differently, and what is encoded then differs from
361
+ // what the answer is held to.
362
+ var dpnSpec = spec.dpn, issuerSpec = spec.issuer;
363
+ if (dpnSpec == null && issuerSpec == null) {
364
+ throw _err("cmp/bad-input", "a crlUpdate identifies the requested CRL by a dpn (a distribution point name), an issuer (the CA that issues it), or both (RFC 9483 sec. 4.3.4)");
365
+ }
366
+ // A distribution point name is a pointer the responder resolves internally, so on its own it
367
+ // leaves nothing to hold the answer to: a CRL claiming to be its issuer's complete list states no
368
+ // scope at all (RFC 5280 sec. 5.2.5 permits that), and the request named no issuer to compare it
369
+ // with, so any well-formed CRL from any CA would answer. The issuer is therefore required
370
+ // alongside a dpn, naming the CA whose CRL the caller will accept. sec. 4.3.4's own note says
371
+ // where a distribution point name comes from, and both sources -- a certificate's
372
+ // cRLDistributionPoints, a held CRL's issuingDistributionPoint -- carry the issuer with it.
373
+ if (dpnSpec != null && issuerSpec == null) {
374
+ throw _err("cmp/bad-input", "a crlUpdate naming a dpn must also name the issuer whose CRL is acceptable: a distribution point name alone leaves the response unbound, since a complete CRL states no scope to compare it against (RFC 9483 sec. 4.3.4, RFC 5280 sec. 5.2.5). Drive an unbound request with pki.cmp.build + pki.cmp.transfer.");
375
+ }
376
+ var source, issuerNameDer = null, dpnNames = null;
377
+ // The issuer, when given, is kept whether or not it goes on the wire: a caller who names one is
378
+ // saying which CA's CRL they will accept, and pki.cmp.session holds the answer to it. Taking the
379
+ // encoded Name from here means the comparison reads the name the caller gave rather than
380
+ // re-interpreting the spec at a later boundary.
381
+ if (issuerSpec != null) issuerNameDer = _b.encodeName(issuerSpec);
382
+ if (dpnSpec != null) {
383
+ // CRLSource is a CHOICE, so exactly one alternative goes on the wire, and sec. 4.3.4 settles
384
+ // which: the dpn "if the CRL distribution point name is available", otherwise the issuer. A
385
+ // caller giving both is answered by the dpn, the more specific pointer, with the issuer held
386
+ // back to bind the response.
387
+ if (typeof dpnSpec !== "object" || _isBuffer(dpnSpec)) throw _err("cmp/bad-input", "crlUpdate.dpn must be { fullName: [<GeneralName>...] }");
388
+ guard.identifier.assertKnownKeys(dpnSpec, KNOWN_DPN_KEYS, _err, "cmp/bad-input", "unknown crlUpdate.dpn field ");
389
+ // The nameRelativeToCRLIssuer arm of DistributionPointName is not built, matching the same
390
+ // decision in pki.crl.sign for issuingDistributionPoint and freshestCRL. Re-open it in all
391
+ // three together, since a partial relative-name surface would encode names one verb can
392
+ // produce and its sibling cannot.
393
+ var fullName = dpnSpec.fullName;
394
+ if (fullName == null) throw _err("cmp/bad-input", "crlUpdate.dpn requires fullName (the nameRelativeToCRLIssuer arm is not built; pki.crl.sign draws the same line for issuingDistributionPoint)");
395
+ var entries = _isArray(fullName) ? fullName : [fullName];
396
+ if (!entries.length) throw _err("cmp/bad-input", "crlUpdate.dpn.fullName must carry at least one GeneralName");
397
+ // The encoded GeneralNames are kept for the same reason as the issuer Name. RFC 5280 sec. 5.2.5
398
+ // pins the comparison to the identical encoding, so what is kept is the bytes that went on the
399
+ // wire rather than the spec they were built from.
400
+ dpnNames = _map(entries, function (e) { return _b.encodeGeneralName(e); });
401
+ source = b.explicit(0, b.contextConstructed(0, _bufferConcat(dpnNames)));
402
+ } else {
403
+ // sec. 4.3.4: the issuer choice "MUST contain the issuer DN in the directoryName field of a
404
+ // GeneralName element". The directoryName [4] EXPLICIT wraps the SAME encoded Name saved above for
405
+ // the response binding (issuerNameDer), not a second read of issuerSpec: a caller's issuer can be an
406
+ // accessor, and re-encoding it here would put one name on the wire while the answer is held to
407
+ // another, so a CRL from the name that was validated could answer a request that named a different one.
408
+ source = b.explicit(1, b.sequence([b.explicit(4, b.raw(issuerNameDer))]));
409
+ }
410
+ // Read ONCE. A caller's thisUpdate can be an accessor, so encoding from one read and validating
411
+ // against a second could judge the answer against a cutoff the request never carried. The instant
412
+ // that went on the wire is returned with the bytes, and it is that value the response is held to.
413
+ var status = [source], askedInstant = null, asked = spec.thisUpdate;
414
+ if (asked != null) {
415
+ askedInstant = guard.time.instantOf(asked, _err, "cmp/bad-input", "crlUpdate.thisUpdate");
416
+ _push(status, b.raw(_b.timeDer(new _Date(askedInstant), "crlUpdate.thisUpdate")));
417
+ }
418
+ return {
419
+ der: b.sequence([b.sequence(status)]),
420
+ issuerName: issuerNameDer,
421
+ thisUpdate: askedInstant,
422
+ dpn: dpnNames === null ? null : { kind: "fullName", names: dpnNames },
423
+ };
424
+ }
425
+
426
+ // The distributionPoint [0] of a CRL's issuingDistributionPoint extension (RFC 5280 sec. 5.2.5),
427
+ // decoded to the DistributionPointName form guard.name.dpnCorresponds compares, or null when the
428
+ // extension names no point -- a complete CRL, whose scope is its issuer's whole population rather
429
+ // than one point of it. A structural fault THROWS instead of reading as "names no point": a session
430
+ // binds a requested distribution point to this value, and an unreadable extension resolving to
431
+ // "nothing to compare" would skip the binding it is read for.
432
+ var IDP_SCHEMA = pkix.issuingDistributionPoint("cmp/bad-info-value");
433
+ function decodeIdpDistributionPoint(valueBytes) {
434
+ var m;
435
+ try { m = schema.walk(IDP_SCHEMA, asn1.decode(valueBytes), NS); }
436
+ catch (e) { throw _err("cmp/bad-info-value", "the returned CRL carries a malformed issuingDistributionPoint extension (RFC 5280 sec. 5.2.5)", e); }
437
+ if (!m.fields.distributionPoint.present) return null;
438
+ // distributionPoint [0] EXPLICIT-wraps the DistributionPointName CHOICE (a context tag on a
439
+ // CHOICE-typed field is always EXPLICIT), so the name is its single child.
440
+ var wrap = m.fields.distributionPoint.node;
441
+ if (!wrap.children || wrap.children.length !== 1) {
442
+ throw _err("cmp/bad-info-value", "an issuingDistributionPoint distributionPoint [0] must wrap exactly one DistributionPointName (RFC 5280 sec. 5.2.5)");
443
+ }
444
+ return pkix.distributionPointName(NS, wrap.children[0], "cmp/bad-info-value");
445
+ }
446
+
280
447
  function _encodeRevReqContent(list) {
281
448
  if (!Array.isArray(list) || !list.length) throw _err("cmp/bad-rev-req", "rr must be a non-empty array of RevDetails");
282
449
  return b.sequence(list.map(_encodeRevDetails));
@@ -422,6 +589,29 @@ function _encodeKeyRecRepContent(spec, state) {
422
589
  return b.sequence(children);
423
590
  }
424
591
 
592
+ // Does a built CertReqMessages carry a proof of possession that RFC 9810 sec. 5.2.8.3 couples to
593
+ // cmp2021(3)? Stated over the RFC's pair rather than over the arms this toolkit happens to emit, so
594
+ // the coupling still holds if agreeMAC is built later.
595
+ var CMP2021_POP_METHODS = { agreeMAC: 1, encryptedKey: 1 };
596
+ function _popNeedsCmp2021(crmfDer) {
597
+ var messages;
598
+ // Re-reading a CertReqMessages this process just produced. A fault here is an internal
599
+ // inconsistency, not a caller error, so it is named in this module's namespace: a crmf/* parse code
600
+ // surfacing from cmp.build would send the operator looking at a request they wrote correctly. A
601
+ // CRMF fault raised while BUILDING that body still passes through untranslated, where it does name
602
+ // the caller's own input.
603
+ try { messages = schemaCrmf.parse(crmfDer).messages; }
604
+ catch (e) {
605
+ throw _err("cmp/bad-body", "the certificate request body this message just built did not parse back: " +
606
+ ((e && e.message) || e), e);
607
+ }
608
+ for (var i = 0; i < messages.length; i++) {
609
+ var popo = messages[i].popo;
610
+ if (popo && popo.method && _hasOwn(CMP2021_POP_METHODS, popo.method)) return true;
611
+ }
612
+ return false;
613
+ }
614
+
425
615
  // Dispatch the single-key body object to its EXPLICIT-tagged arm. Returns { bodyTLV, usesCmp2021 }.
426
616
  function _encodeBody(bodySpec, key, opts) {
427
617
  if (!bodySpec || typeof bodySpec !== "object" || Buffer.isBuffer(bodySpec)) throw _err("cmp/bad-input", "message.body must be a single-key object");
@@ -442,7 +632,13 @@ function _encodeBody(bodySpec, key, opts) {
442
632
  delete reqSpec.key;
443
633
  }
444
634
  return crmf.build(reqSpec, popKey, {}).then(function (crmfDer) {
445
- return { bodyTLV: b.explicit(tag, b.raw(crmfDer)), usesCmp2021: false };
635
+ // RFC 9810 sec. 5.2.8.3: "When using agreeMAC or encryptedKey choices, the pvno cmp2021(3)
636
+ // MUST be used." Read off the message that was actually emitted rather than off the spec that
637
+ // asked for it, so the announced version answers for the bytes on the wire. The parser
638
+ // enforces the same rule on the way in, and before this the two disagreed: a request carrying
639
+ // an encryptedKey proof went out announcing cmp2000(2), and this toolkit's own reader refused
640
+ // the message this toolkit had just built.
641
+ return { bodyTLV: b.explicit(tag, b.raw(crmfDer)), usesCmp2021: _popNeedsCmp2021(crmfDer) };
446
642
  });
447
643
  }
448
644
  var inner;
@@ -520,7 +716,10 @@ function _resolveProtection(opts) {
520
716
  if (!Buffer.isBuffer(secret) || !secret.length) throw _err("cmp/bad-input", "opts.mac.secret must be a non-empty string or Buffer");
521
717
  }
522
718
  var secretBuf = Buffer.isBuffer(secret) ? secret : Buffer.from(secret, "utf8");
523
- var prf = m.prf || "SHA-256";
719
+ // Default only when prf is absent (null/undefined), the same test the iterationCount and keyLength
720
+ // siblings below use. `m.prf || "SHA-256"` would default on any falsy value, so a supplied "", false, or
721
+ // 0 -- none a valid PRF name -- would silently encode HMAC-SHA-256 instead of being refused.
722
+ var prf = m.prf != null ? m.prf : "SHA-256";
524
723
  if (!PBMAC1_PRF[prf]) throw _err("cmp/bad-input", "opts.mac.prf must be SHA-256 / SHA-384 / SHA-512");
525
724
  var iterationCount = m.iterationCount != null ? m.iterationCount : PBMAC1_DEFAULT_ITER;
526
725
  if (typeof iterationCount !== "number" || !Number.isInteger(iterationCount) || iterationCount < PBMAC1_MIN_ITER) throw _err("cmp/bad-input", "opts.mac.iterationCount must be at least " + PBMAC1_MIN_ITER + " (RFC 8018 sec. 4.2)");
@@ -914,4 +1113,19 @@ function wellKnownUrl(base, opts) {
914
1113
  * pki.cmp.wellKnownUrl("https://ca.example", { label: "myca", operation: "cr" });
915
1114
  * // // ".../.well-known/cmp/p/myca/cr"
916
1115
  */
917
- module.exports = { build: build, transfer: transfer, wellKnownUrl: wellKnownUrl };
1116
+ module.exports = {
1117
+ build: build, transfer: transfer, wellKnownUrl: wellKnownUrl,
1118
+ buildCrlStatusList: buildCrlStatusList, // @internal -- pki.cmp.session composes it for a crlUpdate support message
1119
+ // @internal -- one key, several legal SPKI encodings (a compressed EC point among them), so the
1120
+ // session compares root-rollover keys through the same definition the builders already use.
1121
+ samePublicKey: function (a, b) { return _b.samePublicKey(a, b); },
1122
+ // @internal -- the shared certificate-extension decoders, so a consumer reads basicConstraints or
1123
+ // keyUsage through the same definition every format uses instead of walking the bytes again.
1124
+ decodeCertExtension: function (dottedOid, valueBytes) {
1125
+ var dec = EXT_DECODERS[dottedOid];
1126
+ return dec ? dec(valueBytes) : null;
1127
+ },
1128
+ // @internal -- the CRL-side companion: schema-crl leaves issuingDistributionPoint raw, and the
1129
+ // session needs the point it names to bind a crlUpdate answer to the point that was requested.
1130
+ decodeIdpDistributionPoint: decodeIdpDistributionPoint,
1131
+ };