@blamejs/pki 0.6.54 → 0.7.0

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,68 @@ 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.7.0 — 2026-09-09
8
+
9
+ A Sigstore bundle signed over an artifact's own bytes is verified, not just one wrapping an attestation.
10
+
11
+ ### Added
12
+
13
+ - pki.sigstore.verifyBundle verifies a bundle carrying a message_signature. The caller passes the artifact as opts.artifact and the verifier hashes it: under the algorithm the Rekor entry names, compared against the hash that entry records, and then under the leaf certificate's key against the signature the bundle carries. The three happy-path bundles the Sigstore conformance suite publishes are covered, spanning all three bundle media types and both shapes of verification material.
14
+ - opts.artifact takes the artifact's bytes and nothing else. The digest a message_signature carries is covered by no signature, and the field's own definition states that a client must not use it to verify the signature, so there is no shape in which a caller hands over a digest instead: a hex string is refused at the door, and the digest bytes are refused where the artifact is compared against the log entry. A message_signature bundle with no opts.artifact is refused rather than verified from the digest it carries.
15
+ - The digest the bundle states is checked against the one computed, when it is there. It is optional, and a bundle omitting it verifies with messageDigestChecked reporting false. Where it disagrees with the artifact the request is refused, and the verdict reports the digest this computed rather than the one the bundle claimed. It may name any of the five HashAlgorithm members that name an algorithm, the two SHA-3 members included: those are marked deprecated, which says a producer should not choose one rather than that a bundle carrying one is malformed, and this digest names its own algorithm independently of the one the log entry records. It may name the member by its name or by its number, since the JSON mapping states that a parser accepts both; the unspecified member is refused under either spelling, as is a number outside the enum. The entry's algorithm is a different field under a different enum and stays the three the Rekor schema lists.
16
+ - The verdict has one shape for both content arms. contentType names the arm. The fields that carry a value report null where the arm has none: artifactDigest and digestAlgorithm on a DSSE bundle, and payload, statement, subjects, predicateType and predicate on a message signature. The fields that report whether a check ran stay boolean, so messageDigestChecked is false on a DSSE bundle exactly as predicateTypeChecked is false on a message signature. A caller reads the same fields either way rather than telling a missing key from a false one.
17
+ - opts.identity and opts.ctLogs run on this arm as they do on the other, so a caller pins who signed and whether the signing certificate was public when it was issued, whichever content the bundle carries.
18
+ - pki.tls offers RFC 8879 zstd certificate compression. All three registered algorithms are implemented, and each is offered only where the running Node decompresses it safely. At load each is handed a frame with its last two bytes cut: a decompressor that returns anything at all rather than faulting is dropped, because a runtime that accepts a cut frame lets a peer strip a frame's tail and have the receiver read a prefix as the whole message. Node 24.19 returned the prefix for a cut zstd frame, so zstd was dropped there. Node 24.21 faults on one, so all three are offered.
19
+
20
+ ### Changed
21
+
22
+ - A hashedrekord entry may name the verifier as a public key rather than as a certificate. The Rekor field is documented as the public key that verifies the signature, which may also be an X509 code signing certificate carrying that key, so an entry writing the key itself is conforming; it binds when that key is the bundle leaf's, and an entry naming a different key does not bind. The armor says which form the entry wrote, so neither is guessed at from the bytes.
23
+ - Every option is read once, when verification starts, and the arm gates and the verdict read that one answer. An option is whatever its name resolves to on the options object, inherited or own, which is how an unrecognized option name is already detected and refused. Reading them as own properties made an inherited artifact look missing on the arm that requires it and let an inherited predicateType past the refusal that belongs to it. Reading one twice let it answer differently across the two reads: a predicateType that was absent where the arm gate ran and present where the verdict was built returned predicateTypeChecked true on a message signature, which carries no statement to check a predicate type against.
24
+ - A transparency-log entry is read by its own kind and version together. The entry registry holds one row per kind and apiVersion, and each row states which content arm it may accompany, so a hashedrekord v0.0.2 body is refused as an unsupported version rather than read for v0.0.1 field names it does not carry, and an entry describing a DSSE envelope beside a message signature is refused rather than bound to it.
25
+ - An option that belongs to the other arm is refused rather than ignored. Supplying opts.artifact on a dsse_envelope bundle, or opts.predicateType on a message_signature, is an error, since an option read and passed over reads as a check that ran. Either name set to null or undefined counts as not supplied.
26
+ - The supported Node floor moves to 24.21.0, the current long-term-support release, which carries OpenSSL 3.5.8. Nothing is transpiled, so the supported version is the version the source runs on. On a lower version npm reports the mismatch as EBADENGINE, and refuses the install where engine-strict is set. Nothing below the floor is tested, and zstd certificate compression is unavailable there.
27
+
28
+ ### Fixed
29
+
30
+ - A bundle given as an object is copied into plain data before any rule runs on it, and every check then runs on that copy. Its fields were the caller's own to answer, and the transparency-log entry's canonicalizedBody was read separately by the three things that examine it: the binding that ties the entry to the signature and certificate, the inclusion proof folded to the signed tree root, and the signed entry timestamp. A field answering differently across those reads let one body be bound while a different one was proven, so a signature the log never recorded was attested by an authentic entry for something else and verifyBundle returned verified. The same shape reached the DSSE payload and signature, the inclusion proof's root and hashes, and the time the certificate is checked at. It affects both content arms and every version that shipped the DSSE one. A bundle given as JSON text was never affected, since parsing it yields fixed values.
31
+ - An object bundle is held to being data, which changes what is accepted. A field reached through an accessor is refused rather than called, since calling one runs code that can change the object while it is being read. So is a value JSON does not carry: a function, a symbol, a bigint or a non-finite number anywhere in the structure, because dropping one silently turned a bundle setting two content arms into a bundle setting one. A field set to undefined reads as absent, and one named `__proto__` stays a field of that name rather than becoming the copy's prototype. pki.sigstore.parseBundle takes the same copy and returns it, so what a caller reads back is what was checked and the two verbs cannot answer differently about one bundle.
32
+ - An object bundle is bounded by the same size and depth limits a text one is, and by the same numbers. The size is charged while the copy is built, so a bundle is refused before the memory is allocated rather than after: sharing one sub-object between two properties doubles the values a copy walks per level, so a few hundred bytes describes hundreds of millions of them, and a modest array of long strings is a handful of values holding tens of megabytes. Each value is charged what JSON writes it as, so the two representations of one document are judged alike: a string costs its escaped bytes, a number written in exponent form costs its digits, and the punctuation between values is counted once. A property whose value is not written costs nothing, since the document omits it. One nesting limit governs both routes.
33
+ - Nothing the copy relies on can be replaced after this package loads. The object path used to serialize the copy and read it back, so a serializer replaced afterwards could drop a field and hand the checks a bundle carrying one content arm where the copy held two; the copy is plain data already and is not converted to text at all. The operations the copy decides with are taken at load for the same reason, since replacing the one that lists what an object owns empties the bundle and replacing the one that counts a number's digits lets an oversized one through.
34
+ - The fields that name a registry row are read for being strings before they are used as keys. A messageDigest algorithm, a log entry's kind and apiVersion, and a log entry's hash algorithm reached a lookup as whatever the bundle carried, so a value whose own conversion throws escaped as an untyped error out of a verb whose contract is that malformed input is refused with a typed one.
35
+
36
+ ### Security
37
+
38
+ - pki.webauthn.verifyMetadataBlob reads opts.previousNo once, so the rollback comparison and the result it reports run on the same baseline. The option was read separately by the comparison and by the result, and a baseline that answered absent at the comparison and present afterwards skipped the comparison entirely: a metadata BLOB whose sequence number did not advance past the held baseline was accepted, and the result stated rollbackChecked true and named the baseline it had not compared against. A caller that holds its baseline in a plain value was never affected. Every option the verb reads is now taken once at entry.
39
+
40
+ ## v0.6.55 — 2026-09-07
41
+
42
+ A Diffie-Hellman key proves possession by agreeing a secret with the authority, without signing anything.
43
+
44
+ ### Added
45
+
46
+ - 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.
47
+ - 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".
48
+ - 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.
49
+ - 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.
50
+ - 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.
51
+ - 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.
52
+ - 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.
53
+ - 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.
54
+ - 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.
55
+ - 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.
56
+ - 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.
57
+ - 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.
58
+ - 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.
59
+ - 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.
60
+ - 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.
61
+ - 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.
62
+
63
+ ### Fixed
64
+
65
+ - 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.
66
+ - 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.
67
+ - 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.
68
+
7
69
  ## v0.6.54 — 2026-09-07
8
70
 
9
71
  A holder of a composite ML-KEM key can enroll for it, proving possession by opening the challenge addressed to it.
package/README.md CHANGED
@@ -64,7 +64,7 @@ Crypto API with its limits on streaming, opaque keys, and algorithm reach.
64
64
  npm i @blamejs/pki
65
65
  ```
66
66
 
67
- Requires Node.js 24.19+ and runs on the shipped runtime, with no build step and
67
+ Requires Node.js 24.21+ and runs on the shipped runtime, with no build step and
68
68
  no transpilation.
69
69
 
70
70
  ```js
@@ -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, 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` |
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` |
@@ -249,7 +249,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
249
249
  | `pki.shbs` | Stateful hash-based signature verification: HSS/LMS (RFC 8554), carried in X.509 by RFC 9802 and in CMS by RFC 9708, profiled by NIST SP 800-208 for CNSA 2.0 firmware signing. `verify` checks an HSS signature, where every level must pass, and `verifyLms` a single-tree LMS, over the raw public-key and signature blobs the parsers already surface. Pure public-input SHA-256 and SHAKE256 hashing, a data-driven typecode registry, and bounds-before-slice reads; a malformed blob throws a typed `ShbsError` while a well-formed but wrong signature returns `false`. Verification only by design, since stateful signing needs atomic one-time-key state that belongs in an HSM. `pki.path.validate` verifies an HSS-signed certificate on its own, so a chain reaching one needs no separate call: the signature covers the whole tbsCertificate rather than a digest of it (RFC 9802 §7.1), and a CertificateList naming the algorithm takes the same route. It is proven against the self-signed certificate RFC 9802 Appendix A publishes — `verify`, `verifyLms` |
250
250
  | `pki.hpke` | Hybrid Public Key Encryption (RFC 9180), the encrypt-to-a-public-key primitive behind TLS ECH, MLS, and OHTTP. `setupS` and `setupR` establish a sender or recipient context (KEM encapsulation plus the HKDF key schedule); the context's `seal` and `open` AEAD-encrypt with a sequence-counter nonce, and `export` derives further secrets; the module-level `seal` and `open` are single-shot wrappers. DHKEM (P-256, P-521, X25519, X448) by HKDF-SHA256/SHA512 by AES-GCM / ChaCha20Poly1305 / export-only, across all four modes, proven against the RFC 9180 Appendix A vectors. DHKEM(P-384) and HKDF-SHA384 are RFC-registered but Appendix A ships no vector for them, so they fail closed until an authoritative KAT exists. Pure composition over `node:crypto`; ML-KEM and X-Wing are a registry data-row extension pending stable drafts — `suites`, `setupS`, `setupR`, `seal`, `open` |
251
251
  | `pki.kem` | Composite ML-KEM key establishment (draft-ietf-lamps-pq-composite-kem), a post-quantum ML-KEM hybridized with a traditional RSA-OAEP, ECDH, X25519, or X448 so the established secret holds if either component is later broken. `encapsulate` turns a recipient's composite `SubjectPublicKeyInfo` into a 256-bit shared secret and a ciphertext; `decapsulate` recovers the same secret from the ciphertext and the composite PKCS#8 private key. Each component KEM runs independently and the two secrets are mixed through a SHA3-256 combiner that binds the traditional ciphertext, the traditional public key, and a per-algorithm label. The twelve algorithms pair ML-KEM-768 and ML-KEM-1024 with RSA-OAEP 2048/3072/4096, ECDH over P-256/P-384/P-521 and brainpoolP256r1/P384r1, X25519, and X448, each verified against the draft Appendix G known-answer vectors; a malformed key or ciphertext, an unsupported algorithm, or a component decapsulation failure throws a typed `KemError` — `encapsulate`, `decapsulate` |
252
- | `pki.sigstore` | Offline verifier for a Sigstore bundle, the artifact `npm publish --provenance` produces and the registry serves. `verifyBundle` composes five fail-closed legs against caller-pinned trust (Fulcio CA roots and Rekor log keys, never trusted from the bundle): the DSSE signature over its PAE preimage under the Fulcio leaf key, the ephemeral Fulcio certificate chain validated as of the Rekor log time, the RFC 9162 inclusion proof folded to a Rekor-signed tree root, the log entry bound to this exact signature, and the in-toto SLSA subject digest the caller confirms against the published artifact. It reuses the X.509 parser, the RFC 5280 path validator, and the Merkle verifier; the net-new codecs are the DSSE PAE byte-builder and a fail-closed JSON reader. `verified: true` says the artifact was signed and logged, not that a party you trust signed it — Fulcio issues to anyone who completes an OIDC flow, so who signed is decided only by `opts.identity`, and `identityChecked` reports which of its fields were compared. An identity policy naming no field, or a field name that is not one of the three, is refused rather than satisfied — either would accept every signer while reading as a policy in force. A sixth leg is opt-in: pinning the certificate-transparency logs in `opts.ctLogs` checks the receipt Fulcio embeds in the certificate it issues (RFC 6962 §3.2), verified over the certificate as it stood before the receipt was added and under the key of the log that issued it, so the verdict says the signing certificate was public when it was issued rather than handed out quietly. At least one receipt must verify against a pinned log, the verdict reports `sctChecked` and `validScts`, and an empty log set is refused rather than read as a policy that checks nothing — `pae`, `parseBundle`, `verifyBundle` |
252
+ | `pki.sigstore` | Offline verifier for a Sigstore bundle, the artifact `npm publish --provenance` produces and the registry serves. `verifyBundle` composes five fail-closed legs against caller-pinned trust (Fulcio CA roots and Rekor log keys, never trusted from the bundle): the DSSE signature over its PAE preimage under the Fulcio leaf key, the ephemeral Fulcio certificate chain validated as of the Rekor log time, the RFC 9162 inclusion proof folded to a Rekor-signed tree root, the log entry bound to this exact signature, and the in-toto SLSA subject digest the caller confirms against the published artifact. It reuses the X.509 parser, the RFC 5280 path validator, and the Merkle verifier; the net-new codecs are the DSSE PAE byte-builder and a fail-closed JSON reader. `verified: true` says the artifact was signed and logged, not that a party you trust signed it — Fulcio issues to anyone who completes an OIDC flow, so who signed is decided only by `opts.identity`, and `identityChecked` reports which of its fields were compared. An identity policy naming no field, or a field name that is not one of the three, is refused rather than satisfied — either would accept every signer while reading as a policy in force. A sixth leg is opt-in: pinning the certificate-transparency logs in `opts.ctLogs` checks the receipt Fulcio embeds in the certificate it issues (RFC 6962 §3.2), verified over the certificate as it stood before the receipt was added and under the key of the log that issued it, so the verdict says the signing certificate was public when it was issued rather than handed out quietly. At least one receipt must verify against a pinned log, the verdict reports `sctChecked` and `validScts`, and an empty log set is refused rather than read as a policy that checks nothing. Both content arms are read: a DSSE-wrapped in-toto attestation, and a message signature over an artifact's own bytes, which `cosign sign-blob` produces. For that arm `opts.artifact` supplies the bytes, and they are held to the hash the Rekor `hashedrekord` entry records before the signature is checked over them; the `messageDigest` the bundle carries is covered by no signature, so it is compared against the computed digest and never used in its place. `contentType` names the arm and the verdict has one shape for both — `pae`, `parseBundle`, `verifyBundle` |
253
253
  | `pki.inspect` | Human-readable inspection, the pure-JS equivalent of `openssl x509/crl/req/cms -text`. `certificate(pem \| der \| parsed)` renders an OpenSSL-style report: version, serial, signature algorithm, issuer and subject distinguished names, validity, public-key details (curve or modulus size plus the raw point or modulus), every decoded extension with its critical flag, and the signature. `crl`, `csr`, and `cms` render the other formats the same way — a CRL like `openssl crl -text`, a CSR like `openssl req -text`, and a CMS message like `openssl cms -cmsout -print`, with a stable summary for a non-SignedData ContentInfo — and `any(input)` detects the format and routes to the right report. Built over the strict parsers and the two-way OID registry with one set of field renderers, it names extension and algorithm OIDs an OpenSSL build shows only as raw bytes. No OpenSSL dependency, and the format is stable and OpenSSL-familiar rather than pinned to one OpenSSL version. A certificate policy's user notice renders as text, both its explicit text and a notice reference with the notice numbers that identify it, rather than hex, and a malformed part falls back to a hex dump rather than throwing — `certificate`, `crl`, `csr`, `cms`, `any` |
254
254
  | `pki.webauthn` | WebAuthn and passkey verification, both halves: offline trust evaluation of a W3C WebAuthn (Level 3) registration, and signature verification of the assertion every login returns. `parseAttestationObject(bytes)` decodes the CBOR attestation object, authenticatorData, and COSE credential key over the strict `pki.cbor` codec; `parseAuthenticatorData(bytes)` reads the bare form an assertion carries through the same parser; `parseClientData(bytes, opts)` decodes the `clientDataJSON` no signature check looks inside, through the shared JSON guard since these are attacker-chosen bytes, returning the challenge decoded so a caller compares bytes rather than spellings, and checking the ceremony type, challenge, and origin when the relying party supplies what it issued. `verifyAssertion(input)` verifies an assertion signature over `authenticatorData \|\| SHA-256(clientDataJSON)` — raw bytes, no COSE_Sign1, an ES256 signature in ASN.1 DER — and applies the §7.2 step 21 counter rule when a stored `previousSignCount` is given, so a counter that fails to advance is refused as a cloned authenticator. `verify(attestationObject, clientDataHash, opts)` checks the attestation-statement signature and each format's structural bindings for packed, tpm, android-key, apple, fido-u2f, and none: the x5c leaf key, the apple nonce, the tpm `certInfo` Name and `extraData` over the `pubArea`, the android `KeyDescription`, and the fido-u2f `verificationData`. It binds the credential public key to each attestation, through the signed authenticatorData for packed and fido-u2f or a cert or `pubArea`-key equality check for android-key, apple, and tpm, and enforces each leaf's certificate requirements. The credential-key check covers the full WebAuthn COSE algorithm set — ES256/384/512, RS256/384/512, PS256/384/512, EdDSA (Ed25519), and the RFC 9864 fully-specified identifiers ESP256/384/512, Ed25519, and Ed448 — validating the public-key point on its curve, rejecting the compressed EC point form, and enforcing a minimally encoded DER ECDSA signature. The verdict field is `attestationVerified`, and `signatureVerified` for an assertion, rather than a bare `verified`, because a sound statement is a different claim from an acceptable ceremony: an attestation naming another origin's RP ID with user presence clear is perfectly sound and must not be registered. Pass `expectedRpId`, `requireUserPresence`, `requireUserVerification`, or `allowedAlgorithms` and those are checked, with `bindingChecked` reporting which ran, so a check that passed can be told from one that never happened. Pass `opts.clientDataJSON` instead of the digest and the client data is read here too: the ceremony type is checked unconditionally, since a login response replayed into a registration is what that rule stops, and the challenge, origin, and top-level origin are checked against what the relying party issued, with `clientData.checked` reporting which comparisons ran. A registration verdict also carries the `credentialId`, `credentialPublicKey`, and initial `signCount` a later login needs. A credential key declaring COSE algorithm `-65535` (RSASSA-PKCS1-v1_5 with SHA-1) is refused unless `allowedAlgorithms` names it, since every signature that credential ever makes would use SHA-1. Anchoring the trust path has two routes: `opts.metadata` resolves the roots the authenticator's own model registered, and `opts.rootCertificates` pins roots directly, which is what anchors the formats FIDO MDS does not cover, Apple's authenticators and the Google hardware-attestation roots among them. `metadata` governs when both are given, and `anchoredTo` names every route that anchored the path, joined with `+` when more than one did: `"metadata"`, `"rootCertificates"`, and `"safetyNetRoots"` for the android-safetynet chain, which anchors through the roots that format requires whether or not either other route was asked for. It is `null` only when nothing anchored the path. `verifyMetadataBlob(blob, opts)` reads a FIDO Metadata Service (MDS v3) BLOB, the signed catalogue of registered authenticator models, verifying its JWS and chaining its signer to an operator-supplied FIDO root before the payload is parsed, with sequence-number rollback and `nextUpdate` freshness checks. Passing the result as `opts.metadata` to `verify` resolves the authenticator's registered attestation roots from its identifier and requires the trust path to fully validate to one of them, refusing an unlisted or revoked model. `metadataAnchors(entry, opts)` applies the same status gate for a caller anchoring the path themselves: a model the catalogue has disqualified registers no anchors. Both of the catalogue's key spaces are covered: an aaguid, and the attestation-certificate key identifiers a U2F authenticator is listed under instead. No FIDO root is bundled, there is no trust-on-first-use, and retrieving the BLOB is out of scope. Fail-closed with typed `webauthn/*` errors — `parseAttestationObject`, `verify`, `verifyMetadataBlob`, `metadataFor`, `metadataAnchors` |
255
255
  | `pki.lint` | Certificate linting, the zlint or pkilint of JavaScript. `certificate(pem \| der \| parsed, opts)` walks a parsed certificate and emits graded advisory findings, each with a stable id, a severity (`fatal`, `error`, `warn`, `notice`), a source, a spec-clause citation, and a message, against the RFC 5280 profile plus a representative CA/Browser Forum TLS BR subset: serial sign and size, validity ordering and the SC081v3 reducing validity schedule, keyCertSign coherence, extension criticality (basicConstraints, nameConstraints, policyConstraints and inhibitAnyPolicy must be critical, and keyUsage should be), nameConstraints CA-scope, unknown critical extensions, empty-subject SAN, SKI and AKI presence including the end-entity subjectKeyIdentifier, SAN required and CN-in-SAN, dNSName syntax, serverAuth EKU, weak keys, and the §4.2.1.4 certificate-policy user-notice rules (a VisibleString or BMPString explicitText, a notice past 200 characters, an empty notice, control characters, and a non-NFC UTF8String notice, each at the strength the clause states). Alone among these entries the data path never throws: hostile bytes return a `fatal` `lint/unparseable` finding carrying the strict parser's code, so a whole directory lints without a try/catch, and only config-time misuse throws a typed `LintError` — `certificate`, `rules`, `profiles` |
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) { return _universal(TAGS.SEQUENCE, true, Buffer.concat(_asBufferArray(children, "build.sequence"))); },
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 _universal(TAGS.SET, true, Buffer.concat(arr));
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 _universal(TAGS.SET, true, Buffer.concat(arr));
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/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),