@blamejs/pki 0.6.53 → 0.6.55
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 +37 -0
- package/README.md +1 -1
- package/lib/asn1-der.js +27 -3
- package/lib/cmc-build.js +41 -12
- package/lib/constants.js +4 -0
- package/lib/crmf-sign.js +821 -18
- package/lib/oid.js +8 -0
- package/lib/schema-pkix.js +15 -0
- package/lib/sigstore.js +27 -1
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,43 @@ All notable changes to `@blamejs/pki` are documented here. The format
|
|
|
4
4
|
follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
|
|
5
5
|
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
6
|
|
|
7
|
+
## v0.6.55 — 2026-09-07
|
|
8
|
+
|
|
9
|
+
A Diffie-Hellman key proves possession by agreeing a secret with the authority, without signing anything.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- pki.crmf.build assembles the agreeMAC proof of possession (RFC 4211 section 4.3, RFC 2875 section 3). The requester supplies pop.key, its own Diffie-Hellman private key, and pop.caCert, the authority's certificate it already holds; the two agree a secret, a key is derived from it, and that key MACs the request. The proof carries id-dhPop-static-HMAC-SHA1, and both that OID and id-alg-dhPOP are registered.
|
|
14
|
+
- The proof value is the DhPopStatic structure section 3 defines, not the bare MAC: the BIT STRING carries a SEQUENCE of the issuer name and serial number of the certificate the authority's key came from, and the HMAC result as an OCTET STRING. The section says so after the computation it describes, "i.e. encodes the above sequence instead of the raw output from 3d".
|
|
15
|
+
- The key is derived as RFC 2875 section 3 states it: SHA-1 over the authority certificate's subject name, the agreed secret, and its issuer name, in that order. Section 4.3 settles which certificate those names come from and what to do when one is absent, so an authority certificate whose subject name is empty contributes its subjectAltName instead, and one carrying neither is refused rather than keyed from nothing. That alternative name is read as the GeneralNames it is rather than measured, since the certificate parser surfaces an extension's bytes without running the decoder registered for it: an empty list carries a length while naming nobody, and so does one holding a value that no arm of the GeneralName choice covers. The three arms the shared name reader takes on their tag or admits empty are read further: an x400Address must open with the standard attributes an ORAddress begins with, rather than with whatever value carries that tag, and must name somebody in one of its components, every built-in field being optional so that naming data can sit in the domain-defined or extension attributes instead; a directoryName wrapping a Name of no relative names substitutes an empty name for the empty name that reached this fallback, and an ediPartyName is read down to the strings it names a party with, a DirectoryString being one of five string types carrying at least one character. A party named with an empty string, or with bytes that are not the encoding their tag claims, names nobody either. Section 4.3 states the same fallback for an empty issuer name, which a certificate reaching this proof cannot carry: RFC 5280 section 4.1.2.4 requires a non-empty issuer, and the certificate parser enforces it.
|
|
16
|
+
- The MAC covers the DER certReq, and the request must name both a subject and a public key. Section 4.3's own ASN.1 comment states both, where the prose states neither: the proof is "a MAC (over the DER-encoded value of the certReq parameter in CertReqMsg, which must include both subject and publicKey)". A template naming only one of them is refused.
|
|
17
|
+
- pop.key must be the private half of certTemplate.publicKey. The authority derives its side of the agreement from the requested key, so a private key from another pair agrees a secret with the authority and yields a MAC the authority cannot reproduce: a proof of possession of something the request never asked to have certified. The encryptedKey arm holds its enclosed key to the same rule.
|
|
18
|
+
- The proof is admitted only for a finite-field Diffie-Hellman pair, which is what section 3 defines it over, and only when the requester's key can actually reach the authority's, which section 4.3 requires. An elliptic-curve or montgomery pair agrees a secret through the same operation and is refused rather than emitted under an OID naming something the recipient is not performing; so is a key on another group, and a key this runtime cannot classify is named as unrecognized rather than reported as a key type. Every copy of private material the proof allocates is cleared before the call returns, on the refusing paths as well as the building one: the agreed secret, the key derived from it, and the copy taken of the caller's key. The caller's own key is left untouched.
|
|
19
|
+
- Every key this proof touches is read in both encodings a finite-field key is written in. An X.509 Diffie-Hellman certificate names dhpublicnumber and carries X9.42 DomainParameters (RFC 3279 section 2.3.3) where this runtime classifies only the PKCS#3 form, so such a key is rewritten into the form it reads: the authority's certificate, the requested key, the enclosed key an encryptedKey proof archives and the public half derived from it, and the requester's own private key, which is a PKCS#8 whose algorithm is rewritten while the private value it wraps is unchanged. That private key is taken in every form the verb accepts it in: DER, a PEM block, and a key object the runtime holds without classifying, since admitting one of the three is not supporting the encoding. The request still carries the encoding the caller asked to have certified.
|
|
20
|
+
- Whether a set of parameters describes the key it carries is asked of every key read, in either encoding, since a request carries those parameters on to whoever reads it next. The modulus must be prime, and the public value must lie inside the group. Where the certificate states a subgroup order, that order must divide p-1, must be an order the generator actually has, must be prime, and must hold the public value; where a cofactor is given with it, the two must account for p. The requester's own private key is read the same way, since the PKCS#3 form it is rewritten into carries neither the order nor the cofactor and that rewrite is the last place either is looked at. A PrivateKeyInfo states no public value, so the two tests that hold one to these parameters are the only ones it is not held to.
|
|
21
|
+
- These rules govern a key a secret is agreed with. The encryptedKey arm asks the one question RFC 4211 section 4.2 states, whether the enclosed key is the private half of the requested one, and agrees nothing, so it reads both encodings for their shape and does not measure the group: whether a key sits in a good group is the certifying authority's policy, and answering it here would mean proving a modulus prime, which costs seconds and bounds the size, so a key too large to prove would become a key too large to archive. A legacy group and a group larger than any agreement would accept both still enroll there. What a stated order and cofactor say about the p and g beside them is a separate question, and that arm answers it: the conversion drops both while the request goes out carrying the caller's own encoding of them, and the tests are a multiplication and a modulo rather than the exponentiation and the primality proofs the size bound exists for.
|
|
22
|
+
- Both exponents this agreement uses must be ones the other side cannot work out. RFC 2631 section 2.2 states X9.42's own requirement, that the private key lie in the interval [2, q-2], and the exponents outside it agree a secret that follows from values the request and the authority certificate already carry: zero agrees one, one agrees the other side's public value itself, and the order less one agrees the inverse of that value. A MAC keyed from any of them proves possession of nothing. The requester's key and the authority's are held to it alike, since an agreement has two exponents and either one outside the interval makes the secret public.
|
|
23
|
+
- The rule is read through the group's own order. A safe prime also has elements of order 2q, and the PKCS#3 form states no order, so a generator of that full order is admitted; its square root of one reflects each excluded value, so the exponent q+1 produces p minus g and q-1 produces p minus the inverse of g. Each agrees the negation of a secret that already follows, so the reflections are excluded with the values they reflect. An exponent that is merely small is a different matter and is not tested: it cannot be read off the public value without solving a discrete log, no specification states a floor for it, and the interval admits it. The test reads the public value each key states rather than the key itself, so it needs no copy of private material and no stated order.
|
|
24
|
+
- The floors are the strength the agreement itself needs. A stated order must be large enough to hide an exponent: a prime order makes the public value's order exactly that value rather than a divisor of it, which is worth nothing when the value is small, and three is prime. The floor is the smallest subgroup order NIST SP 800-56A states for a finite-field group. Where no order is stated, which the PKCS#3 form cannot, the modulus must be a safe prime, whose element orders are one, two, r and 2r alone, and that order carries the same floor, since seven is a safe prime whose own subgroup has order three. The modulus carries a floor of 2048 bits, the size the toolkit's linter already names for a public key: a large subgroup says a value is hard to take a discrete log of inside the group and says nothing about the group itself, and a 512-bit safe prime has a 255-bit subgroup while the secret agreed in it is recoverable. A 1024-bit legacy group no longer completes this proof. Proving a modulus prime costs from a fraction of a second over a 2048-bit group to a second or two at the 4096-bit bound, and the answers are remembered, so a run of requests against one authority proves its group once.
|
|
25
|
+
- The one optional field a PKCS#3 DHParameter carries is held to the modulus beside it. privateValueLength states how many bits the private value has, and a private value is less than the modulus, so a length above the modulus's own bit count describes no value the group holds; it was read for being a positive integer and carried through unchanged, so a request could travel stating one. The encoded size bounds the count before anything is shifted by it, since the field is an INTEGER the codec admits at any width.
|
|
26
|
+
- A refusal names the key it is about. The authority certificate, the requested key, the requester's private key and the enclosed private key each reported as the authority certificate's, whichever one the reader had been handed.
|
|
27
|
+
- The parameters are sized before anything is computed with them, since these tests raise one operand to the power of another and prove a modulus prime, while the DER reader admits an integer far wider than any Diffie-Hellman group. The bound is 4096 bits, which covers every MODP group a certificate carries. Every container is read for the tag it carries rather than for having children, so a context-specific constructed value in place of the DomainParameters SEQUENCE is refused rather than rewritten into a key that imports while the request carries the original. The cofactor and the validation parameters are each optional and independent, so a fourth field is read by its tag: the cofactor is held against p and q, and the validation parameters against the seed BIT STRING and pgenCounter INTEGER they consist of. The public key BIT STRING must hold whole octets, since the codec admits a nonzero unused-bit count whose padding bits are zero and that BIT STRING is carried through unchanged.
|
|
28
|
+
- The authority certificate's keyUsage is enforced. A keyUsage extension restricts the certified key to the purposes it asserts (RFC 5280 section 4.2.1.3), and this proof uses the authority's key to agree a secret, so a certificate that states its purposes without stating keyAgreement is refused rather than used for it. A certificate carrying no keyUsage states no restriction and is unaffected.
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
|
|
32
|
+
- A constructed DER value is written into one allocation. Building a SEQUENCE or a SET concatenated the children and then concatenated that with the header, leaving an intermediate holding everything the children carry; where a structure is built over private material, that intermediate was a copy of it no caller could reach to clear. pki.asn1.build.sequence, .set and .setOf now assemble directly, which covers every caller rather than the ones that remembered to. The encoding is unchanged, byte for byte. Clearing a key's copies is still best effort, since a runtime copies buffers where no code can reach them.
|
|
33
|
+
- pki.sigstore.verifyBundle refuses a bundle that carries both content arms. A bundle setting dsse_envelope and message_signature together was verified on the envelope alone, returning a verdict that said nothing about the other arm the bundle carried. The bundle's content is a oneof, so exactly one arm may be present and both is now sigstore/bad-bundle.
|
|
34
|
+
- The same rule holds for verificationMaterial, whose certificate, x509CertificateChain and publicKey are a oneof of the same kind. More than one arm set drew the leaf certificate from one and the chain it is validated through from another, so the certificate whose key was checked and the certificates it was checked through came from different statements about the same signer, and a publicKey beside either certificate arm named a second signer identity the verdict said nothing about.
|
|
35
|
+
|
|
36
|
+
## v0.6.54 — 2026-09-07
|
|
37
|
+
|
|
38
|
+
A holder of a composite ML-KEM key can enroll for it, proving possession by opening the challenge addressed to it.
|
|
39
|
+
|
|
40
|
+
### Fixed
|
|
41
|
+
|
|
42
|
+
- pki.cmc.build completes an unsigned enrollment for a composite ML-KEM key (RFC 5272 App. C.1). The rule is unchanged: the challenge must be addressed to the key the request asks for, and a challenge opened by any other key licenses nothing. What changed is how the two are compared. A key the runtime engine cannot read has no key object to compare, so the composite SubjectPublicKeyInfo answers instead, which is sound because that encoding is canonical: fixed component widths under a single OID, with no compressed-point spelling for two forms of one key to differ over. That ambiguity is the reason the classical comparison uses key objects, and it does not arise here. Every other key type is compared exactly as before.
|
|
43
|
+
|
|
7
44
|
## v0.6.53 — 2026-09-07
|
|
8
45
|
|
|
9
46
|
A composite ML-KEM private key states its public half, so a holder can name the recipient it is.
|
package/README.md
CHANGED
|
@@ -234,7 +234,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
234
234
|
| `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. 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` |
|
|
235
235
|
| `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
|
|
236
236
|
| `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
|
|
237
|
-
| `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
|
|
237
|
+
| `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named. `pop.method: 'agreeMAC'` completes the four: `pop.key` is the requester's finite-field Diffie-Hellman private key, as a PKCS#8 DER, a PEM `PRIVATE KEY` block or a `KeyObject`, and `pop.caCert` the authority's certificate it already holds; the two agree a static secret (RFC 2875 sec. 3), and the key derived from it MACs the DER `certReq` under `id-dhPop-static-HMAC-SHA1`. Either key may name its group in the PKCS#3 or the X9.42 encoding. `pop.key` must be the private half of `certTemplate.publicKey`, and the template must name both a subject and a public key. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
|
|
238
238
|
| `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `krr` (key recovery, §5.3.7), `ccr` (cross-certification, §5.3.11: a `CertReqMessages` at the normative floor, where the requesting CA keeps its private key so a private-key-transport encryptedKey proof-of-possession is refused, and the optional App. D.6 single-request cardinality is not enforced), `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). Protection is exactly one of `opts.{ key, cert }`, a signature under the sender key with the algorithm resolved from the signer certificate so RSA (PKCS#1 v1.5 / PSS), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived), or `opts.kem`, a KEM-based MAC for a client whose key can only establish secrets (RFC 9810 §5.1.3.4): the ciphertext a peer encapsulated to its ML-KEM key is decapsulated, the key is derived under HKDF-SHA256 with a context bound to the transaction identifier of the message that carried the ciphertext, and `pki.cmp.verify` checks it from the shared secret. Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. A certification authority can take longer to answer than a process is held open, so a `poll-timeout` carries a `resumeToken` and `resumePoll(token)` continues the same transaction in a later process: the token is plain JSON naming the transaction, the nonce the next request echoes, the polled request and the arm its grant arrives on, and the key the grant must certify. It carries no secret and grants nothing, since the protection material and the endpoint come from the session built to resume with, and the resumed poll verifies, nonce-binds, and key-binds every response. Its fields are what the resumed exchange is held to, so store it where the enrollment's own state is stored: someone who can rewrite it can widen what the resumed session accepts, as far as that session's trust anchors and the authority's protection allow and no further. The same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. `openKeyPackage(container, opts)` opens a private key the CA generated centrally and delivered in the `privateKey` field of a granted `CertifiedKeyPair` (RFC 9483 §4.1.6): a CMS `SignedData` over an RFC 5958 `AsymmetricKeyPackage`, sealed in a CMS `EnvelopedData`. `opts.key` (with `opts.cert`) opens the key transport and key agreement containers a signature-protected request selects, `opts.password` the password container a MAC-protected request selects. The authority is authorized before any key material is returned: its certificate must chain to an anchor in `opts.trustAnchors` AND assert the `id-kp-cmKGA` extended key usage, since a certificate with no `extendedKeyUsage` permits every purpose and so authorizes nothing; `opts.authorizedBySharedSecret` states §4.1.6's exemption for an entity that authorizes by the secret that protected its request. Returns `{ keys, kga, trusted }`, where each key is a PKCS#8 `PrivateKeyInfo` ready for `pki.key.import`; `keys` is the whole RFC 5958 `AsymmetricKeyPackage` (`SIZE (1..MAX)`), while a session enrollment requires the sequence of one §4.1.6 profiles it to. Both CMS layers are read as a ContentInfo or as the bare structure, told apart by what the SEQUENCE opens with. `session(opts)` drives the whole exchange under `opts.acceptCentralKeyGeneration`: the request omits `certTemplate.publicKey`, carries no proof of possession, and goes out as `cmp2021`; the session opens the delivered container with the credential it enrolled under and surfaces it as `deliveredKey`, having first checked that the issued certificate certifies the delivered key. Without the option, such a request and such a grant are both refused. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `openKeyPackage`, `session` |
|
|
239
239
|
| `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the issuer key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
|
|
240
240
|
| `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
|
package/lib/asn1-der.js
CHANGED
|
@@ -660,6 +660,28 @@ function sequenceTlv(node) {
|
|
|
660
660
|
return Buffer.concat([Buffer.from([TAGS.SEQUENCE | CONSTRUCTED_BIT]), encodeLength(content.length), content]);
|
|
661
661
|
}
|
|
662
662
|
|
|
663
|
+
/** @internal A constructed value written into ONE allocation, rather than concatenating the children
|
|
664
|
+
* and then concatenating that with the header. The two-step form leaves an intermediate holding
|
|
665
|
+
* everything the children carry; where they carry private material that intermediate is a copy of it
|
|
666
|
+
* no caller can reach to clear, since it is a local here and becomes garbage on return. Its output is
|
|
667
|
+
* byte-identical to the two-step form: the same identifier, the same length, the same children in
|
|
668
|
+
* the same order. */
|
|
669
|
+
function encodeConstructed(classBits, tagNumber, parts) {
|
|
670
|
+
var total = 0;
|
|
671
|
+
for (var i = 0; i < parts.length; i++) total += parts[i].length;
|
|
672
|
+
var id = encodeIdentifier(classBits, true, tagNumber);
|
|
673
|
+
var len = encodeLength(total);
|
|
674
|
+
var out = intrinsic.bufferAlloc(id.length + len.length + total);
|
|
675
|
+
intrinsic.typedArraySet(out, id, 0);
|
|
676
|
+
intrinsic.typedArraySet(out, len, id.length);
|
|
677
|
+
var at = id.length + len.length;
|
|
678
|
+
for (var j = 0; j < parts.length; j++) {
|
|
679
|
+
intrinsic.typedArraySet(out, parts[j], at);
|
|
680
|
+
at += parts[j].length;
|
|
681
|
+
}
|
|
682
|
+
return out;
|
|
683
|
+
}
|
|
684
|
+
|
|
663
685
|
function encodeIdentifier(classBits, constructed, tagNumber) {
|
|
664
686
|
if (typeof tagNumber !== "number" || !isFinite(tagNumber) || tagNumber < 0 || Math.floor(tagNumber) !== tagNumber) {
|
|
665
687
|
throw new Asn1Error("asn1/bad-tag", "tag number must be a non-negative integer");
|
|
@@ -853,16 +875,18 @@ var build = intrinsic.assign(intrinsic.create(null), {
|
|
|
853
875
|
},
|
|
854
876
|
utcTime: function (date) { return _universal(TAGS.UTC_TIME, false, Buffer.from(_utcTimeString(date), "latin1")); },
|
|
855
877
|
generalizedTime: function (date) { return _universal(TAGS.GENERALIZED_TIME, false, Buffer.from(_generalizedTimeString(date), "latin1")); },
|
|
856
|
-
sequence: function (children) {
|
|
878
|
+
sequence: function (children) {
|
|
879
|
+
return encodeConstructed(CLASS_UNIVERSAL, TAGS.SEQUENCE, _asBufferArray(children, "build.sequence"));
|
|
880
|
+
},
|
|
857
881
|
set: function (children) {
|
|
858
882
|
var arr = _asBufferArray(children, "build.set").slice();
|
|
859
883
|
arr.sort(Buffer.compare);
|
|
860
|
-
return
|
|
884
|
+
return encodeConstructed(CLASS_UNIVERSAL, TAGS.SET, arr);
|
|
861
885
|
},
|
|
862
886
|
setOf: function (children) {
|
|
863
887
|
var arr = _asBufferArray(children, "build.setOf").slice();
|
|
864
888
|
arr.sort(Buffer.compare);
|
|
865
|
-
return
|
|
889
|
+
return encodeConstructed(CLASS_UNIVERSAL, TAGS.SET, arr);
|
|
866
890
|
},
|
|
867
891
|
explicit: function (tagNumber, inner) { return encodeTLV(CLASS_CONTEXT, true, tagNumber, _asBuffer(inner, "build.explicit")); },
|
|
868
892
|
contextPrimitive: function (tagNumber, content) { return encodeTLV(CLASS_CONTEXT, false, tagNumber, _asBuffer(content, "build.contextPrimitive")); },
|
package/lib/cmc-build.js
CHANGED
|
@@ -17,6 +17,7 @@ var oid = require("./oid");
|
|
|
17
17
|
var cmsSign = require("./cms-sign");
|
|
18
18
|
var cmsEncrypt = require("./cms-encrypt");
|
|
19
19
|
var cmsDecrypt = require("./cms-decrypt");
|
|
20
|
+
var compositeKem = require("./composite-kem");
|
|
20
21
|
var key = require("./key");
|
|
21
22
|
var _createPublicKey = nodeCrypto.createPublicKey;
|
|
22
23
|
var guard = require("./guard-all");
|
|
@@ -518,19 +519,40 @@ function _requestIdentity(parsed) {
|
|
|
518
519
|
|
|
519
520
|
/** @internal Whether the key that opened the challenge is the key the request asks to have certified.
|
|
520
521
|
* Only a tcr is answered this way: a crm request carries its own proof-of-possession field. */
|
|
521
|
-
function _provesRequestKey(
|
|
522
|
-
if (!
|
|
523
|
-
var
|
|
522
|
+
function _provesRequestKey(opening, outgoing) {
|
|
523
|
+
if (!opening || !outgoing || !outgoing.certificationRequestBytes) return false;
|
|
524
|
+
var requestedSpki;
|
|
525
|
+
try {
|
|
526
|
+
requestedSpki = csr.parse(outgoing.certificationRequestBytes).subjectPublicKeyInfo.bytes;
|
|
527
|
+
} catch (_e) { return false; } // allow:swallow-unverified a request this runtime cannot read proves nothing here
|
|
524
528
|
/** @internal Compared as keys rather than as encodings: an elliptic-curve point written in compressed
|
|
525
529
|
* form and the same point written uncompressed are different bytes and the same key, and it is the key
|
|
526
530
|
* the section is about. */
|
|
531
|
+
if (opening.key !== null) {
|
|
532
|
+
var requested;
|
|
533
|
+
try {
|
|
534
|
+
requested = _createPublicKey({ key: requestedSpki, format: "der", type: "spki" });
|
|
535
|
+
} catch (_e) { return false; } // allow:swallow-unverified a key this runtime cannot read proves nothing here
|
|
536
|
+
return intrinsic.keyEquals(requested, opening.key);
|
|
537
|
+
}
|
|
538
|
+
/** @internal A key the runtime engine cannot read has no KeyObject to compare, and a composite
|
|
539
|
+
* ML-KEM key is one. Its encoding answers instead, which is sound because that encoding is
|
|
540
|
+
* canonical: fixed component widths under a single OID, with no compressed-point spelling for two
|
|
541
|
+
* forms of one key to differ over, which is the ambiguity the comparison above exists to absorb. */
|
|
542
|
+
if (!_isCompositeSpki(requestedSpki)) return false;
|
|
543
|
+
return intrinsic.bufferEquals(requestedSpki, opening.spki);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** @internal Whether a SubjectPublicKeyInfo names a composite ML-KEM algorithm, read from its
|
|
547
|
+
* AlgorithmIdentifier alone. Anything this cannot read is not one. */
|
|
548
|
+
function _isCompositeSpki(spki) {
|
|
527
549
|
try {
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
550
|
+
var node = asn1.decode(spki);
|
|
551
|
+
if (!node.children || node.children.length !== 2) return false;
|
|
552
|
+
var alg = node.children[0];
|
|
553
|
+
if (!alg.children || alg.children.length < 1) return false;
|
|
554
|
+
return compositeKem.isCompositeKem(asn1.read.oid(alg.children[0]));
|
|
555
|
+
} catch (_e) { return false; } // allow:swallow-unverified an unreadable algorithm is not a composite one
|
|
534
556
|
}
|
|
535
557
|
|
|
536
558
|
/** @internal The public half of the key that OPENED the challenge. The recipient kind comes from the
|
|
@@ -539,11 +561,18 @@ function _provesRequestKey(openingKey, outgoing) {
|
|
|
539
561
|
* yields null, and the request is then refused rather than accepted on an unproven key. */
|
|
540
562
|
async function _openingPublicKey(recipient, recipientType) {
|
|
541
563
|
if (!ASYMMETRIC_RECIPIENT[recipientType]) return null;
|
|
564
|
+
var spki;
|
|
542
565
|
try {
|
|
543
|
-
|
|
544
|
-
key: await key.publicFromPrivate(recipient.key), format: "der", type: "spki",
|
|
545
|
-
});
|
|
566
|
+
spki = await key.publicFromPrivate(recipient.key);
|
|
546
567
|
} catch (_e) { return null; } // allow:swallow-unverified a key whose public half cannot be derived proves nothing here
|
|
568
|
+
/** @internal Both spellings of the answer: the KeyObject the comparison prefers, and the encoding a
|
|
569
|
+
* key the runtime engine cannot read has instead of one. A null `key` is not a failure; it says the
|
|
570
|
+
* engine does not know this algorithm, and the comparison below decides what that permits. */
|
|
571
|
+
var asKey;
|
|
572
|
+
try {
|
|
573
|
+
asKey = _createPublicKey({ key: spki, format: "der", type: "spki" });
|
|
574
|
+
} catch (_e) { asKey = null; } // allow:swallow-unverified a composite key the runtime cannot read is compared by its canonical bytes
|
|
575
|
+
return { spki: spki, key: asKey };
|
|
547
576
|
}
|
|
548
577
|
|
|
549
578
|
async function _recoverProofValue(decoded, recipient, witnessHash) {
|
package/lib/constants.js
CHANGED
|
@@ -115,6 +115,10 @@ var LIMITS = Object.assign(Object.create(null), {
|
|
|
115
115
|
MAX_DECODE_DEPTH_CEILING: 256,
|
|
116
116
|
PEM_MAX_BYTES: BYTES.mib(16),
|
|
117
117
|
DER_MAX_INTEGER_BYTES: BYTES.kib(16),
|
|
118
|
+
DH_MAX_MODULUS_BYTES: 512,
|
|
119
|
+
DH_MIN_SUBGROUP_BYTES: 20,
|
|
120
|
+
DH_MIN_MODULUS_BYTES: 256,
|
|
121
|
+
DH_PRIME_MEMO_ENTRIES: 64,
|
|
118
122
|
OID_MAX_SUBIDENTIFIER_BYTES: 32,
|
|
119
123
|
HTTP_MAX_RESPONSE_BYTES: BYTES.mib(24),
|
|
120
124
|
HTTP_AUTH_HEADER_MAX_BYTES: BYTES.kib(8),
|