@blamejs/pki 0.6.1 → 0.6.3

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,27 @@ 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.3 — 2026-08-30
8
+
9
+ pki.cms builds and reads certs-only certificate-management messages: a degenerate CMS SignedData that conveys certificates and CRLs without signing anything (RFC 8551 sec. 3.8).
10
+
11
+ ### Added
12
+
13
+ - pki.cms.certsOnly(certs, opts?) builds a certs-only certificate-management message (RFC 8551 sec. 3.8): a degenerate CMS SignedData with version 1, an empty digestAlgorithms and signerInfos, an id-data encapContentInfo with the eContent absent, and the caller's certificates in certificates [0] and any CRLs in crls [1], both DER-sorted and deduplicated. certs is a certificate or an array of them (DER Buffer or PEM string), and opts.crls carries CRLs the same way; at least one certificate or CRL is required. Each entry is parsed as a real X.509 certificate or CertificateList before it is embedded, so a non-certificate, a non-CRL, or a tagged CertificateChoices alternative is refused with a typed cms/bad-input rather than emitted. opts.pem returns a PEM string instead of DER.
14
+ - pki.cms.parseCertsOnly(input, opts?) reads a certs-only message (DER Buffer or PEM) and returns { certificates, crls } as raw DER. It requires a degenerate SignedData (id-data with no eContent, empty signerInfos) and refuses a non-degenerate structure with cms/not-certs-only. Unlike the RFC 5272 Simple PKI Response that pki.est.parseCertsOnly reads, a CRL-only message is accepted (RFC 8551 sec. 3.8 conveys certificates and/or CRLs); a message carrying neither is refused. opts.maxCerts caps the number of certificates and CRLs parsed and returned, a bound on an untrusted bundle.
15
+ - pki.cms.isCertsOnly(input) reports whether input is a certs-only message structurally, returning true for a SignedData with an id-data content, absent eContent, and empty signerInfos, and false for any other well-formed CMS. Undecodable bytes throw a typed CmsError.
16
+ - pki.smime.buildCertsOnly(certs, opts?) wraps a certs-only message in one application/pkcs7-mime; smime-type=certs-only; name=smime.p7c S/MIME entity (RFC 8551 sec. 3.2.1), with the certs-only DER as the base64 body. It accepts the same certificate and opts.crls inputs as pki.cms.certsOnly.
17
+
18
+ ## v0.6.2 — 2026-08-30
19
+
20
+ pki.scep builds and reads SCEP (RFC 8894) enrollment messages: a client assembles a PKCSReq or RenewalReq request and parses a CA's response back to its verified transaction attributes and issued certificates.
21
+
22
+ ### Added
23
+
24
+ - pki.scep.build(spec) assembles a SCEP request pkiMessage (RFC 8894 sec. 3). Given a PKCS#10 certification request as messageData, a recipient CA certificate, and a signer { cert, key }, it verifies the request's own proof-of-possession, encrypts it to the CA as the inner EnvelopedData (pkcsPKIEnvelope, AES-128-CBC with RSAES-OAEP key transport, not the legacy RSAES-PKCS1-v1_5, so the CA must support OAEP), and signs that under the transaction attributes: the messageType (PKCSReq or RenewalReq), a caller-unique transactionId, and a 16-byte senderNonce that is generated when omitted. The messageData must be a well-formed PKCS#10 whose self-signature verifies under its own subject public key, or it is refused (scep/bad-input or scep/bad-popo) rather than enveloped into a message the CA would reject. The recipient CA certificate must assert the keyEncipherment key usage, since the EnvelopedData uses RSA key transport. A malformed spec, an unknown messageType, an over-long transactionId, or a senderNonce that is not 16 bytes is refused with a typed ScepError.
25
+ - pki.scep.parse(bytes, opts?) disassembles a SCEP pkiMessage. It verifies the outer SignedData signature first and refuses a message whose signature does not verify (scep/bad-signature), so the transaction attributes it returns are read only from a verified signer and are never surfaced alongside a false verdict. A valid signature proves only that the message is self-consistent with the certificate it embeds; pass opts.signerCert to authenticate a CA response against the CA certificate you hold, which refuses a signer whose public key does not match (scep/untrusted-signer) and reports signerAuthenticated. The verdict carries the messageType, transactionId, senderNonce, and, for a CertRep, the pkiStatus, failInfo, failInfoText, and recipientNonce, each mapped from its RFC 8894 enumerant and refused when unknown. Passing recipientKey ({ cert, key }) decrypts the pkcsPKIEnvelope to recover the messageData; a SUCCESS CertRep's payload is validated as a degenerate certs-only CMS SignedData and its issued certificate(s) and any CRL are surfaced in certificates and crls (a GetCRL response carries a CRL and no certificate), raw for the caller to path-validate. Passing expectedSenderNonce refuses a response whose recipientNonce does not echo the nonce that was sent. A message carrying more than one signer, a duplicate or multi-valued transaction attribute, or a missing mandatory attribute is refused.
26
+ - pki.errors.ScepError is the typed error for the SCEP codec, alongside the other per-domain PkiError subclasses.
27
+
7
28
  ## v0.6.1 — 2026-08-30
8
29
 
9
30
  pki.ct verifies all of a certificate's SCTs against a trusted log-list and renders a certificate-level Certificate Transparency verdict, and pki.path.validate gains an optional CT gate.
package/README.md CHANGED
@@ -222,6 +222,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
222
222
  | `pki.schema.cmp` | CMP messages (RFC 9810): the header (version, sender and recipient including the anonymous NULL-DN, nonces, transaction id, general info), the 27-arm body (certificate requests via the CRMF parser, an encrypted certificate's EnvelopedData via CMS, response / revocation / confirmation / error / support / polling arms structural, the rest raw), and the exact `headerBytes` and `bodyBytes` slices an external verifier reconstructs the protected part from. The CMP-before-OCSP dispatch order is enforced Fail-closed — `parse`, `pemDecode`, `pemEncode` |
223
223
  | `pki.schema.csrattrs` | EST CSR Attributes (`CsrAttrs`, RFC 8951 §3.5 / RFC 9908) — the `AttrOrOID` items a server sends to shape an enrollment: bare OIDs, attributes with raw values, and decoded views of the RFC 9908 meaningful types (extension requests, EC and RSA key-type conventions, the certification-request-info template). Unknown types are surfaced raw; structure and the RFC 9908 semantic MUSTs are fail-closed — `parse` |
224
224
  | `pki.est` | Enrollment over Secure Transport (RFC 7030 / 8951 / 9908 / 7616). The client verbs `cacerts`, `simpleenroll`, `simplereenroll`, `serverkeygen`, `csrattrs`, and `fullcmc` drive the RFC 7030 flow over `pki.transport` (inject your own via `opts.transport`, or take the fail-closed default): HTTPS only, an explicit trust anchor required, same-origin redirects followed while a downgrade or loop is refused, a 202 Retry-After surfaced but never slept, HTTP Basic or Digest (RFC 7616, SHA-256 / SHA-512-256; MD5 and no-qop refused by default) answered only after the server is authenticated, and the issued certificate chosen by public-key match. `serverkeygen` requests a server-generated key, cleartext or an opaque CMS EnvelopedData, with encryption bound to the CSR's key-identifier attribute over a confidentiality-bearing cipher. `csrattrs` fetches the CA's RFC 9908 attributes policy. `fullcmc` (§4.3) carries a CMC Full PKI Request and reduces the CA's answer through `pki.cmc.verify` to one terminal outcome, refusing a response that fails to echo the transaction and nonce the request carried, or that covers a key the request never asked for; a certs-only reply to a bound request is refused rather than read as an issuance. Under the verbs sit the transport-agnostic codecs they compose: the RFC 8951 base64 transfer codec (which ignores Content-Transfer-Encoding), the `multipart/mixed` splitter, the certs-only and serverkeygen response validators over CMS, the enroll-attribute builders, and the HTTP response classifier — `transferDecode`/`transferEncode`, `parseCertsOnly`, `splitMultipartMixed`, `parseServerKeygenResponse`, `findIssuedCert`, `classifyResponse`, `paths`, and the builders |
225
+ | `pki.scep` | SCEP pkiMessage codec (RFC 8894), the client side of Simple Certificate Enrollment. `build(spec)` assembles a `PKCSReq` or `RenewalReq` request: it verifies the PKCS#10 certification request's own proof-of-possession, encrypts it to the CA as the inner EnvelopedData (`pkcsPKIEnvelope`, AES-128-CBC), and signs that under the transaction attributes RFC 8894 §3.2 defines, a messageType, a caller-unique transactionId, and a 16-byte senderNonce. The recipient CA certificate must assert `keyEncipherment`. `parse(bytes, opts?)` reads a `PKCSReq`, `RenewalReq`, or `CertRep` back (the `CertPoll`, `GetCert`, and `GetCRL` client queries are refused): it verifies the outer signature first and refuses a message whose signature does not check, so the transaction attributes it returns come only from a verified signer, never alongside a false verdict. Because a valid signature only proves self-consistency with the embedded certificate, pass `opts.signerCert` to authenticate a CA response against the CA certificate you hold (a public-key mismatch is refused, `signerAuthenticated` reports the result); a caller that omits it gets a crypto-only verdict and must authenticate the surfaced `signerCert` itself. It maps the messageType, pkiStatus, failInfo, and the nonces from their RFC 8894 enumerants and refuses an unknown one; given `recipientKey` it decrypts the `pkcsPKIEnvelope` to the messageData, and given `expectedSenderNonce` it refuses a response whose recipientNonce does not echo it. It reads a CA's CertRep in full. Issuing a CertRep is not yet built — `build`, `parse` |
225
226
  | `pki.transport` | The shared, fail-closed `node:https` transport the enrollment clients drive. `pki.transport.https(defaults)` returns a `transport(request) → { status, headers, body, tls }`, where `tls` carries the negotiated `protocol`, `cipher`, and raw `peerCertificate`. This is the toolkit's only socket choke point: an explicit trust anchor (or an opt-in to the system store) is required, `rejectUnauthorized` is always on, TLS is floored at 1.2, the response body is capped while it streams, and a stalled socket times out. The EST, ACME, and CMP clients reuse it verbatim. If you inject your own transport, return `tls` too: `pki.est.serverkeygen` asserts the negotiated cipher can protect the delivered private key, and a transport that reports no cipher is trusted rather than refused, so omitting the field silently skips that check — `https` |
226
227
  | `pki.jose` | Flattened JWS (RFC 7515) and JWK thumbprints (RFC 7638). `sign` and `verify` run a Flattened JWS against declarative profiles (ACME outer, EAB inner, keyChange inner) that carry the required and forbidden header rules as data. `base64url` is the strict RFC 4648 §5 codec, rejecting padding, non-alphabet characters, and non-canonical trailing bits. `parseJson` is a bounded reader that refuses duplicate members at any depth. `thumbprint` is the RFC 7638 / 8037 / 9964 canonical digest. The algorithm registry binds each `alg` to its key type (ES/RS/PS/EdDSA/ML-DSA), leaving no code path for `alg:none`, an RS256→HS256 key confusion, or an all-zero ECDSA signature; `assertPublicJwk` refuses a JWK carrying private material, so an exported private key is never published. `opts.key` names the key a message must be signed under and governs: where the profile also permits an embedded header `jwk`, the two must be the same key — compared as RFC 7638 thumbprints, so member order cannot make equal keys differ — and a disagreement is refused rather than resolved in the message's favor. `keySource` reports which key answered, since a signature checked against a key you named is a different claim from one checked against the key the message carried — `sign`, `verify`, `base64url`, `parseJson`, `thumbprint`, `assertPublicJwk` |
227
228
  | `pki.acme` | ACME (RFC 8555 / 8737 / 8738 / 9773). `client(directoryUrl, opts)` is a stateful client driving a live CA directory over `pki.transport`: `newAccount`, `newOrder`, `newAuthz`, `getOrder`, `getAuthorization`, `getChallenge`, `respondToChallenge`, `finalize`, `pollOrder`, `pollAuthorization`, and `downloadCertificate` walk the issuance flow, with `newAuthz` pre-authorizing a single identifier (§7.4.1) and `downloadCertificate` binding the issued certificate to the order — its key, its identifiers, or both; at least one is required by default and the result reports `boundToKey` / `boundToIdentifiers` — before choosing among alternate chains (`Link rel="alternate"`, §7.4.2, via a `selectChain` predicate bounded by `maxAlternates`). `revokeCert` (account-key or certificate-key signed), `keyChange`, `deactivateAccount`, `deactivateAuthorization`, `renewalInfo` (ARI), and `renewalWindow` (the RFC 9773 §4.2/4.3 renewal decision) complete the lifecycle. Every URL is HTTPS only, an explicit trust anchor is required, each request carries a fresh single-use nonce with a bounded badNonce retry, reads are POST-as-GET, polling is bounded and sleeps on a Retry-After via an injectable sleeper capped by a poll count and a total-wait budget, and every response body is size-capped. The transport is injectable via `opts.transport`. Over the message layer it composes resource-object validators (closed status enums, conditional-required fields, unknown fields ignored), the three §7.1.6 state machines, the request builders (newAccount with External Account Binding, newOrder with `replaces`, finalize with a CSR identifier-set match and account-key-reuse rejection, challenge responses, deactivation, revokeCert in both key modes, the keyChange nested JWS, POST-as-GET), the http-01 / dns-01 / tls-alpn-01 challenge computations, the dns and ip identifier validators, and the ARI certID with serial sign-padding preserved — `client`, `validate`, `identify`, `assertTransition`, the builders, `keyAuthorization`, `http01`, `dns01`, `tlsAlpn01Extension`, `verifyTlsAlpn01`, `ariCertId` |
@@ -238,8 +239,8 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
238
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` |
239
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` |
240
241
  | `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
241
- | `pki.cms` | CMS signing, verification, encryption, and compression (RFC 5652). `sign(content, signers, opts)` produces a SignedData (§5), attached or detached, with one or many signers over RSA, RSASSA-PSS, ECDSA, EdDSA, the post-quantum ML-DSA-44/65/87 (RFC 9882) and SLH-DSA (all twelve FIPS 205 sets, RFC 9814), and composite ML-DSA pairing ML-DSA with a traditional RSA, ECDSA, or EdDSA key (accepted only when both components verify, draft-ietf-lamps-cms-composite-sigs). It builds the signed attributes (content-type, message-digest, signing-time) as canonical DER, signs the exact §5.4 preimage, and emits a DER `Buffer` or PEM. The content may also be an async iterable of byte chunks, which signs a large detached payload without holding it in memory: the payload is hashed incrementally under every signer's digest algorithm in one pass, and `verify` accepts the same streamed form as its `content` option. A signer may also be key-only — `{ key, spki, keyIdentifier }` with no certificate — which RFC 5272 §3.2 requires when a Full PKI Request's signer is the key of a certification request that request carries: the signer identifier takes the subjectKeyIdentifier form carrying the identifier the request declares, the signature scheme resolves from the request's own public key, and no certificate is embedded. `verify(input, opts)` parses a SignedData over the strict `pki.schema.cms` codec, locates each SignerInfo's signer certificate by its issuerAndSerialNumber or subjectKeyIdentifier, and checks the signature over the exact §5.4 preimage: with signed attributes present it confirms the message-digest attribute equals the content digest and verifies over the DER re-encoding of the SignedAttributes (the on-wire `[0]` tag replaced by a universal SET OF), and otherwise directly over the content. It returns a per-signer verdict with the matched signer certificate. `valid` and `trusted` are separate claims and neither implies the other: a SignedData carries its own certificates, so `valid` says the signature is sound under one of them and nothing about who signed, while `trusted` says every signer chained to a root named in `opts.trustAnchors`, validated through the same RFC 5280 path engine `pki.path.validate` uses. Without anchors there is nothing to chain to and `trusted` is `false`; anchors that cannot be read throw, rather than reading as untrusted. An unrecognized option is refused rather than ignored. `countersign(cms, signers, opts)` adds a countersignature (§11.4) — a `SignerInfo` over the countersigned SignerInfo's signature value, any signer algorithm, nestable, with the primary bytes preserved so it still verifies — attached as the id-countersignature unsigned attribute; `verify` returns each countersignature's verdict under `signers[i].countersignatures` and every unsigned attribute — including an RFC 3161 timestamp token, attachable via `sign`'s `unsignedAttributes` — under `signers[i].unsignedAttrs`, surfaced unauthenticated. `encrypt(content, recipients, opts)` produces an EnvelopedData, AuthEnvelopedData (AES-GCM, the authenticated default), or EncryptedData, with recipients auto-dispatched off the certificate key to key transport (RSAES-OAEP; v1.5 is never emitted), key agreement (ephemeral-static ECDH over P-256/384/521 with the X9.63 KDF, and X25519/X448 with HKDF), symmetric key wrap, password (PBKDF2 with RFC 3211 PWRI-KEK), or the post-quantum ML-KEM KEMRecipientInfo (RFC 9629/9936), wrapping one fresh content key for every recipient. The content may also be an async iterable of byte chunks, streamed through the AES-GCM or AES-CBC content cipher so a large plaintext is encrypted without being buffered whole; the ciphertext is assembled before the definite-length encryptedContent is emitted, byte-for-byte the buffered form. `decrypt(input, keyMaterial, opts)` recovers the content through the matching arm and returns it with an `authenticated` flag; every secret-dependent failure collapses to one uniform `cms/decrypt-failed` verdict (Bleichenbacher, EFAIL, and password-oracle freedom), and PKCS#1 v1.5 is decrypt-only under the RFC 3218 implicit-rejection countermeasure. With `opts.stream: true` the recovered `content` is an async iterable of plaintext chunks instead of a single Buffer, for a payload too large to hold whole; the authenticated modes (AuthEnvelopedData, AuthenticatedData, AES-GCM) verify integrity before the iterable yields, so a forged message throws before any plaintext is exposed, while a CBC EnvelopedData or EncryptedData yields the plaintext as the cipher produces it. Every key-establishment secret the toolkit allocates is wiped once used, on the failing path as well as the succeeding one: the KEM shared secret and its derived key-encryption key, the raw ECDH / X25519 / X448 agreement secret, a password-derived key-encryption key, and the content-encryption key itself, cleared once the message is complete since all recipients share it. Caller-supplied key material is never written to (best-effort; NIST SP 800-227 §4.2, RFC 9629 §7). `authenticate(content, recipients, opts)` produces an `id-ct-authData` (§9): cleartext content plus an HMAC-SHA-256/384/512 MAC, authenticated but not encrypted, with the fresh MAC key wrapped for every recipient through the same RecipientInfo model. The MAC covers the authenticated attributes (content-type and message-digest) re-tagged to the EXPLICIT SET OF (§9.2), or the content octets directly; `decrypt` recovers the MAC key, recomputes the MAC and independently the message-digest (§9.3), and releases the content only after both pass, with every secret-dependent failure collapsing to the uniform `cms/decrypt-failed`. `compress(content, opts)` and `decompress(input, opts)` produce and consume a CompressedData (RFC 3274; ZLIB, version 0, id-alg-zlibCompress); decompress bounds the uncompressed output at 16 MiB and stops before it is materialized, so a decompression bomb fails closed as `cms/decompress-too-large`. Compression is a size transform with no integrity or confidentiality (RFC 8551 §2.4.5). Fail-closed with typed `cms/*` errors — `sign`, `verify`, `countersign`, `encrypt`, `authenticate`, `decrypt`, `compress`, `decompress` |
242
- | `pki.smime` | S/MIME message assembly, verification, encryption, and compression over the CMS layer (RFC 8551). `sign(content, signers, opts)` wraps a MIME entity in either form: `multipart/signed`, where the content stays readable in any MUA and a detached CMS SignedData rides alongside as `application/pkcs7-signature` with a matching `micalg`, or `application/pkcs7-mime; smime-type=signed-data`, where the whole entity is a base64 CMS SignedData. The signed bytes are the entity's §3.1.1 canonical form with CRLF line endings, and `verify(message, opts)` unwraps both forms and recomputes over the same canonicalizer, so a transport that re-wraps line endings still verifies while a tampered part fails. `encrypt(content, recipients, opts)` envelopes a MIME entity as an opaque `application/pkcs7-mime` message and `decrypt(message, keyMaterial, opts)` opens one, as `smime-type=authEnveloped-data` (AES-GCM, confidentiality and integrity, the default) or `smime-type=enveloped-data` (AES-CBC, confidentiality only, so `decrypt` reports `authenticated: false`, the §3.3 no-integrity caveat). The `smime-type` is derived from the CMS body rather than the header, and decryption is fail-closed and oracle-free. The crypto is entirely `pki.cms.sign` / `verify` / `encrypt` / `decrypt`, so it is algorithm-agnostic: any RSA / RSASSA-PSS / ECDSA / EdDSA / ML-DSA / SLH-DSA signer and any RSA-OAEP / ECDH / X25519 / X448 / AES-KW / PBKDF2 / ML-KEM recipient carries through. As with `cms.verify`, `verify` returns the per-signer verdict plus the recovered content, and `valid` and `trusted` are separate claims: `valid` says the signature is sound under a certificate the message carried, `trusted` says every signer chained to a root named in `opts.trustAnchors`. Anchoring here is validated for email at both ends of the chain — the signer certificate must carry `emailProtection` (RFC 8551 §4.4.4) and the anchor's own trust metadata must permit that purpose, since a root can be distrusted for email while remaining a good TLS root. Override either with `requiredEku` / `checkPurpose`. `compress(content, opts)` and `decompress(message, opts)` add the opaque `application/pkcs7-mime; smime-type=compressed-data; name=smime.p7z` frame (§3.6, RFC 3274), a size transform with no integrity or confidentiality (§2.4.5), bounded against a bomb; the recovered content, which may itself be signed or enveloped, is returned for the caller to re-verify. Header protection (RFC 9788): `sign` and `encrypt` take `opts.protectHeaders`, which inlines the caller's `opts.headers` on the Cryptographic Payload root (its Content-Type gaining `hp="clear"` when signed or `hp="cipher"` when encrypted) so the CMS signature or encryption covers them, defeating a transport that rewrites or reads Subject, From, and the rest. `verify` and `decrypt` surface the authenticated inner set as `protectedHeaders` plus `headerProtection { present, mode, fromMismatch, confidential, legacy }`, so a tampered outer header cannot alter it and `fromMismatch` flags an outer From that disagrees. Encryption applies a Header Confidentiality Policy: the default `hcp_baseline` obscures the outer Subject to `[...]` and removes Comments and Keywords, so the real values live only in the ciphertext, and `decrypt` recovers them. Every emitted header routes through a fail-closed injection guard that rejects a CR, LF, or NUL value and a non-ftext name, and a malformed or contradictory `hp` wrap fails closed as `smime/bad-header-protection` rather than silently downgrading. The CMS crypto is unchanged. Inbound legacy RFC 8551 header protection is recognized opt-in: `verify` and `decrypt` with `opts.legacyHeaderProtection` detect a legacy `message/rfc822`-wrapped payload by the RFC 9788 §4.10.1 four-condition identification and surface the inner headers under `headerProtection.legacy = { headers, mode, fromMismatch, confidential }`, where `headers` is an ordered `[{ name, value }]` array retaining legally repeated fields such as `Received`. Those never appear in `protectedHeaders` and never set `present: true`. Because a legacy message is structurally indistinguishable from an ordinary forwarded `message/rfc822`, this is an explicit heuristic (§4.10.2, "no strong end-to-end guarantees"): a caller keying trust off `present` or `protectedHeaders` is never misled, and only one that explicitly reads `headerProtection.legacy.headers` and cross-checks `legacy.fromMismatch` consumes it. It is off by default, and a nested crypto layer, an inner `hp=`, a non-`message/rfc822` payload, or a duplicate Content-Type reports `legacy: null`. Bidirectionally interoperable with `openssl smime` and `openssl cms`. Fail-closed with typed `smime/*` errors — `sign`, `verify`, `encrypt`, `decrypt`, `compress`, `decompress` |
242
+ | `pki.cms` | CMS signing, verification, encryption, and compression (RFC 5652). `sign(content, signers, opts)` produces a SignedData (§5), attached or detached, with one or many signers over RSA, RSASSA-PSS, ECDSA, EdDSA, the post-quantum ML-DSA-44/65/87 (RFC 9882) and SLH-DSA (all twelve FIPS 205 sets, RFC 9814), and composite ML-DSA pairing ML-DSA with a traditional RSA, ECDSA, or EdDSA key (accepted only when both components verify, draft-ietf-lamps-cms-composite-sigs). It builds the signed attributes (content-type, message-digest, signing-time) as canonical DER, signs the exact §5.4 preimage, and emits a DER `Buffer` or PEM. The content may also be an async iterable of byte chunks, which signs a large detached payload without holding it in memory: the payload is hashed incrementally under every signer's digest algorithm in one pass, and `verify` accepts the same streamed form as its `content` option. A signer may also be key-only — `{ key, spki, keyIdentifier }` with no certificate — which RFC 5272 §3.2 requires when a Full PKI Request's signer is the key of a certification request that request carries: the signer identifier takes the subjectKeyIdentifier form carrying the identifier the request declares, the signature scheme resolves from the request's own public key, and no certificate is embedded. `verify(input, opts)` parses a SignedData over the strict `pki.schema.cms` codec, locates each SignerInfo's signer certificate by its issuerAndSerialNumber or subjectKeyIdentifier, and checks the signature over the exact §5.4 preimage: with signed attributes present it confirms the message-digest attribute equals the content digest and verifies over the DER re-encoding of the SignedAttributes (the on-wire `[0]` tag replaced by a universal SET OF), and otherwise directly over the content. It returns a per-signer verdict with the matched signer certificate. `valid` and `trusted` are separate claims and neither implies the other: a SignedData carries its own certificates, so `valid` says the signature is sound under one of them and nothing about who signed, while `trusted` says every signer chained to a root named in `opts.trustAnchors`, validated through the same RFC 5280 path engine `pki.path.validate` uses. Without anchors there is nothing to chain to and `trusted` is `false`; anchors that cannot be read throw, rather than reading as untrusted. An unrecognized option is refused rather than ignored. `countersign(cms, signers, opts)` adds a countersignature (§11.4) — a `SignerInfo` over the countersigned SignerInfo's signature value, any signer algorithm, nestable, with the primary bytes preserved so it still verifies — attached as the id-countersignature unsigned attribute; `verify` returns each countersignature's verdict under `signers[i].countersignatures` and every unsigned attribute — including an RFC 3161 timestamp token, attachable via `sign`'s `unsignedAttributes` — under `signers[i].unsignedAttrs`, surfaced unauthenticated. `encrypt(content, recipients, opts)` produces an EnvelopedData, AuthEnvelopedData (AES-GCM, the authenticated default), or EncryptedData, with recipients auto-dispatched off the certificate key to key transport (RSAES-OAEP; v1.5 is never emitted), key agreement (ephemeral-static ECDH over P-256/384/521 with the X9.63 KDF, and X25519/X448 with HKDF), symmetric key wrap, password (PBKDF2 with RFC 3211 PWRI-KEK), or the post-quantum ML-KEM KEMRecipientInfo (RFC 9629/9936), wrapping one fresh content key for every recipient. The content may also be an async iterable of byte chunks, streamed through the AES-GCM or AES-CBC content cipher so a large plaintext is encrypted without being buffered whole; the ciphertext is assembled before the definite-length encryptedContent is emitted, byte-for-byte the buffered form. `decrypt(input, keyMaterial, opts)` recovers the content through the matching arm and returns it with an `authenticated` flag; every secret-dependent failure collapses to one uniform `cms/decrypt-failed` verdict (Bleichenbacher, EFAIL, and password-oracle freedom), and PKCS#1 v1.5 is decrypt-only under the RFC 3218 implicit-rejection countermeasure. With `opts.stream: true` the recovered `content` is an async iterable of plaintext chunks instead of a single Buffer, for a payload too large to hold whole; the authenticated modes (AuthEnvelopedData, AuthenticatedData, AES-GCM) verify integrity before the iterable yields, so a forged message throws before any plaintext is exposed, while a CBC EnvelopedData or EncryptedData yields the plaintext as the cipher produces it. Every key-establishment secret the toolkit allocates is wiped once used, on the failing path as well as the succeeding one: the KEM shared secret and its derived key-encryption key, the raw ECDH / X25519 / X448 agreement secret, a password-derived key-encryption key, and the content-encryption key itself, cleared once the message is complete since all recipients share it. Caller-supplied key material is never written to (best-effort; NIST SP 800-227 §4.2, RFC 9629 §7). `authenticate(content, recipients, opts)` produces an `id-ct-authData` (§9): cleartext content plus an HMAC-SHA-256/384/512 MAC, authenticated but not encrypted, with the fresh MAC key wrapped for every recipient through the same RecipientInfo model. The MAC covers the authenticated attributes (content-type and message-digest) re-tagged to the EXPLICIT SET OF (§9.2), or the content octets directly; `decrypt` recovers the MAC key, recomputes the MAC and independently the message-digest (§9.3), and releases the content only after both pass, with every secret-dependent failure collapsing to the uniform `cms/decrypt-failed`. `compress(content, opts)` and `decompress(input, opts)` produce and consume a CompressedData (RFC 3274; ZLIB, version 0, id-alg-zlibCompress); decompress bounds the uncompressed output at 16 MiB and stops before it is materialized, so a decompression bomb fails closed as `cms/decompress-too-large`. Compression is a size transform with no integrity or confidentiality (RFC 8551 §2.4.5). `certsOnly(certs, opts?)` builds a certs-only certificate-management message (RFC 8551 §3.8): a degenerate SignedData with an empty signerInfos and no eContent that conveys certificates and CRLs without signing anything, `parseCertsOnly(input, opts?)` reads one back to its raw certificate and CRL DER (a CRL-only message is valid here, unlike the cert-required RFC 5272 form that `pki.est.parseCertsOnly` reads), and `isCertsOnly(input)` recognizes one structurally. Fail-closed with typed `cms/*` errors — `sign`, `verify`, `countersign`, `encrypt`, `authenticate`, `decrypt`, `compress`, `decompress`, `certsOnly`, `parseCertsOnly`, `isCertsOnly` |
243
+ | `pki.smime` | S/MIME message assembly, verification, encryption, and compression over the CMS layer (RFC 8551). `sign(content, signers, opts)` wraps a MIME entity in either form: `multipart/signed`, where the content stays readable in any MUA and a detached CMS SignedData rides alongside as `application/pkcs7-signature` with a matching `micalg`, or `application/pkcs7-mime; smime-type=signed-data`, where the whole entity is a base64 CMS SignedData. The signed bytes are the entity's §3.1.1 canonical form with CRLF line endings, and `verify(message, opts)` unwraps both forms and recomputes over the same canonicalizer, so a transport that re-wraps line endings still verifies while a tampered part fails. `encrypt(content, recipients, opts)` envelopes a MIME entity as an opaque `application/pkcs7-mime` message and `decrypt(message, keyMaterial, opts)` opens one, as `smime-type=authEnveloped-data` (AES-GCM, confidentiality and integrity, the default) or `smime-type=enveloped-data` (AES-CBC, confidentiality only, so `decrypt` reports `authenticated: false`, the §3.3 no-integrity caveat). The `smime-type` is derived from the CMS body rather than the header, and decryption is fail-closed and oracle-free. The crypto is entirely `pki.cms.sign` / `verify` / `encrypt` / `decrypt`, so it is algorithm-agnostic: any RSA / RSASSA-PSS / ECDSA / EdDSA / ML-DSA / SLH-DSA signer and any RSA-OAEP / ECDH / X25519 / X448 / AES-KW / PBKDF2 / ML-KEM recipient carries through. As with `cms.verify`, `verify` returns the per-signer verdict plus the recovered content, and `valid` and `trusted` are separate claims: `valid` says the signature is sound under a certificate the message carried, `trusted` says every signer chained to a root named in `opts.trustAnchors`. Anchoring here is validated for email at both ends of the chain — the signer certificate must carry `emailProtection` (RFC 8551 §4.4.4) and the anchor's own trust metadata must permit that purpose, since a root can be distrusted for email while remaining a good TLS root. Override either with `requiredEku` / `checkPurpose`. `compress(content, opts)` and `decompress(message, opts)` add the opaque `application/pkcs7-mime; smime-type=compressed-data; name=smime.p7z` frame (§3.6, RFC 3274), a size transform with no integrity or confidentiality (§2.4.5), bounded against a bomb; the recovered content, which may itself be signed or enveloped, is returned for the caller to re-verify. Header protection (RFC 9788): `sign` and `encrypt` take `opts.protectHeaders`, which inlines the caller's `opts.headers` on the Cryptographic Payload root (its Content-Type gaining `hp="clear"` when signed or `hp="cipher"` when encrypted) so the CMS signature or encryption covers them, defeating a transport that rewrites or reads Subject, From, and the rest. `verify` and `decrypt` surface the authenticated inner set as `protectedHeaders` plus `headerProtection { present, mode, fromMismatch, confidential, legacy }`, so a tampered outer header cannot alter it and `fromMismatch` flags an outer From that disagrees. Encryption applies a Header Confidentiality Policy: the default `hcp_baseline` obscures the outer Subject to `[...]` and removes Comments and Keywords, so the real values live only in the ciphertext, and `decrypt` recovers them. Every emitted header routes through a fail-closed injection guard that rejects a CR, LF, or NUL value and a non-ftext name, and a malformed or contradictory `hp` wrap fails closed as `smime/bad-header-protection` rather than silently downgrading. The CMS crypto is unchanged. Inbound legacy RFC 8551 header protection is recognized opt-in: `verify` and `decrypt` with `opts.legacyHeaderProtection` detect a legacy `message/rfc822`-wrapped payload by the RFC 9788 §4.10.1 four-condition identification and surface the inner headers under `headerProtection.legacy = { headers, mode, fromMismatch, confidential }`, where `headers` is an ordered `[{ name, value }]` array retaining legally repeated fields such as `Received`. Those never appear in `protectedHeaders` and never set `present: true`. Because a legacy message is structurally indistinguishable from an ordinary forwarded `message/rfc822`, this is an explicit heuristic (§4.10.2, "no strong end-to-end guarantees"): a caller keying trust off `present` or `protectedHeaders` is never misled, and only one that explicitly reads `headerProtection.legacy.headers` and cross-checks `legacy.fromMismatch` consumes it. It is off by default, and a nested crypto layer, an inner `hp=`, a non-`message/rfc822` payload, or a duplicate Content-Type reports `legacy: null`. Bidirectionally interoperable with `openssl smime` and `openssl cms`. `buildCertsOnly(certs, opts?)` wraps a `pki.cms.certsOnly` certificate-management message in one `application/pkcs7-mime; smime-type=certs-only; name=smime.p7c` entity, read back by OpenSSL's `pkcs7 -print_certs`. Fail-closed with typed `smime/*` errors — `sign`, `verify`, `encrypt`, `decrypt`, `compress`, `decompress`, `buildCertsOnly` |
243
244
  | `pki.tsp` | Time-Stamp Protocol (RFC 3161). `sign(messageImprint, tsa, opts)` produces a TimeStampToken: a CMS SignedData over `pki.cms.sign` whose content is a `TSTInfo` carrying the timestamped message imprint, the TSA policy, a serial number, and `genTime` with optional accuracy, nonce, and ordering, plus the §2.4.2 signing-certificate attribute binding the token to the TSA certificate (SHA-2 imprints, any `pki.cms.sign` TSA key). `request` and `parseRequest` build and parse the TimeStampReq a client sends (imprint, requested policy, nonce, certReq); `response` and `parseResponse` handle the TimeStampResp a TSA returns, either a granted status wrapping a token or a rejection with PKIStatus and failure info, with the §2.4.2 status-to-token coupling enforced in both directions. `verify(token, data, opts)` verifies a token fail-closed: the CMS signature over the exact signed bytes, the message imprint recomputed from the data, the TSTInfo content type, the ESSCertID(V2) binding to the TSA certificate, the §2.3 critical timeStamping-only extendedKeyUsage, the request nonce when used, and, with a trust anchor supplied, full certification-path validation of the TSA certificate at the token's `genTime` — judged under the `timeStamping` purpose, so an anchor's own per-purpose trust metadata reaches the decision rather than sitting inert. It returns `{ valid, trusted, genTime, serialNumber, tstInfo, ... }`, where `trusted` is the separate claim that the authority chained to an anchor you named: without one there is nothing to chain to and it is `false`, which is the distinction a timestamp re-read years later turns on — `sign`, `request`, `parseRequest`, `response`, `parseResponse`, `verify` |
244
245
  | `pki.ocsp` | Online Certificate Status Protocol (RFC 6960), both the responder and relying-party surface. `buildRequest(query, opts)` builds an OCSPRequest for one or more `{ cert, issuer }` pairs, with the CertID hashed under SHA-1 by default per the RFC 5019 lightweight profile or under SHA-2, plus an optional RFC 9654 nonce and an optional requestor signature. `sign(responseData, responder, opts)` produces a signed BasicOCSPResponse over the exact `ResponseData` DER, from the issuing CA directly or a delegated responder, under any `pki.cms.sign` key including the post-quantum ML-DSA and SLH-DSA sets, with `good`, `revoked` (reason and time), or `unknown` per-certificate status. `buildErrorResponse(status)` produces the unsigned §2.3 error (`tryLater`, `unauthorized`, and the rest). `verify(response, opts)` verifies a response fail-closed against the same hardened gates `pki.path.ocspChecker` runs: the CertID binding, responder authorization (the issuing CA, or a CA-issued delegate bearing id-kp-OCSPSigning and id-pkix-ocsp-nocheck and passing the full out-of-path certificate gates), the signature over `tbsResponseDataBytes`, currency against `thisUpdate` and `nextUpdate`, and the request-nonce echo. It returns `{ status: "good" / "revoked" / "unknown", ... }` and never silently accepts. `verifyRequest(request, opts)` is the responder-side inverse of `buildRequest`: it verifies a client's signed request (RFC 6960 §4.1.1) under the requestor certificate the request carries, trying each embedded certificate since the field is unordered, and reports `signed`, `signatureValid`, every certificate whose key verified (`signerCerts`, so a key carried under an expired certificate beside its renewal is not hidden behind ordering) with the first one's decoded subject, the full embedded certificate bag (`certs`, including intermediates for path building), and the request's CertIDs; an unsigned request is reported with `signed: false` rather than refused. Transport-free — `buildRequest`, `sign`, `buildErrorResponse`, `verify`, `verifyRequest` |
245
246
  | `pki.ct` | Certificate Transparency (RFC 6962). `parseSctList` decodes the `SignedCertificateTimestampList` a certificate or OCSP response carries, a TLS-presentation-language payload inside the §3.3 double DER wrap, into per-SCT log id, exact `timestamp` (BigInt), named signature algorithm, and raw signature. `reconstructSignedData` rebuilds the exact `digitally-signed` preimage, and `verifySct` verifies an SCT signature against a log's public key, routing an ECDSA signature through the strict DER-conformance gate and verifying through the crypto engine, resolving true or false and throwing a typed error on a structural fault. On the producing side, `encodeSctList` builds the extension value byte for byte as the exact inverse of `parseSctList`, and `signSct` performs a log's signing step. For trust, `parseLogList` ingests the CT log-list JSON into constraint-carrying trusted logs, recomputing each log's id as SHA-256 of its key and refusing a disagreeing id (a swapped key, §3.2) and decoding the state and temporal-interval constraints; `verifySctWithLogList` resolves the log key from an SCT's log id, enforces the state (usable, qualified, and readonly trusted; retired only before retirement; pending and rejected refused) and the temporal-interval window, then delegates the signature check to `verifySct`. `verifyLogListSignature(json, signature, publicKey)` verifies the detached `log_list.sig` over the raw log-list bytes against a caller-pinned signer key (RSASSA-PKCS1-v1.5/SHA-256 and an EC P-256 arm, with forgeable-key defenses failing closed), cross-checked against `openssl dgst`. `fetchLogList(opts)` turns that chain into a live client: it GETs the `log_list.json` and its detached `log_list.sig` over `pki.transport`, verifies the detached signature over the raw fetched bytes against a caller-pinned distributor key before parsing, so an unverified document is never parsed, read, cached, or surfaced, then ingests the same bytes through `parseLogList` and returns the trusted-log set plus the surfaced `version` and `timestamp`. Above the per-SCT layer, `verifySctList` renders a certificate-level verdict over every SCT a certificate carries (§3.3), reporting how many distinct trusted logs verified an SCT (so a duplicated SCT cannot inflate the count) and from how many distinct trusted operators against a caller's CT policy (`minScts` and `minOperators`, both defaulting to the RFC floor of one), where a policy shortfall is a verdict and a per-SCT failure is a recorded row rather than a thrown call; `x509CertEntry` reconstructs the precertificate log entry from a final certificate by removing the SCT-list extension from its TBSCertificate as byte surgery, so its embedded SCTs verify end to end (§3.2). The toolkit bakes in no vendor URL or key, TLS trust is explicit with `rejectUnauthorized` always on, each response is size-capped before the trust chain, and the transport is injectable so the whole path is testable offline — `parseSctList`, `reconstructSignedData`, `verifySct`, `encodeSctList`, `signSct`, `parseLogList`, `verifySctWithLogList`, `verifySctList`, `x509CertEntry`, `verifyLogListSignature`, `fetchLogList` |
@@ -281,8 +282,9 @@ stdout.
281
282
 
282
283
  ### What's coming
283
284
 
284
- SCEP enrollment, and additional NIST-on-ramp PQC signatures as the OID registry
285
- admits them, are on the roadmap and ride this same core. [ROADMAP.md](ROADMAP.md)
285
+ SCEP certificate issuance (the CertRep responder side), and additional
286
+ NIST-on-ramp PQC signatures as the OID registry admits them, are on the roadmap
287
+ and ride this same core. [ROADMAP.md](ROADMAP.md)
286
288
  carries the full plan and the current status of each area;
287
289
  [CHANGELOG.md](CHANGELOG.md) carries what has landed.
288
290
 
package/index.js CHANGED
@@ -55,6 +55,7 @@ var shbs = require("./lib/shbs");
55
55
  var hpke = require("./lib/hpke");
56
56
  var sigstore = require("./lib/sigstore");
57
57
  var est = require("./lib/est");
58
+ var scep = require("./lib/scep");
58
59
  var transport = require("./lib/http-transport");
59
60
  var jose = require("./lib/jose");
60
61
  var acme = require("./lib/acme");
@@ -96,7 +97,8 @@ module.exports = {
96
97
  // its path builder through. That is plumbing between two internal modules, not an operator verb,
97
98
  // and exporting the module wholesale would put it on the public surface.
98
99
  cms: { verify: cms.verify, sign: cms.sign, countersign: cms.countersign, encrypt: cms.encrypt,
99
- authenticate: cms.authenticate, decrypt: cms.decrypt, compress: cms.compress, decompress: cms.decompress },
100
+ authenticate: cms.authenticate, decrypt: cms.decrypt, compress: cms.compress, decompress: cms.decompress,
101
+ certsOnly: cms.certsOnly, parseCertsOnly: cms.parseCertsOnly, isCertsOnly: cms.isCertsOnly },
100
102
  smime: smime,
101
103
  // `cmc` interprets an RFC 5272 Full PKI Response into one terminal verdict;
102
104
  // `pki.schema.cmc` is the decoder underneath it.
@@ -164,6 +166,7 @@ module.exports = {
164
166
  // splitter, certs-only + serverkeygen validators over CMS, the enroll-attribute
165
167
  // builders, the HTTP response classifier). est opens no socket; fail-closed.
166
168
  est: est,
169
+ scep: { build: scep.build, parse: scep.parse },
167
170
  // `transport` is the shared fail-closed node:https transport the enrollment clients
168
171
  // drive -- pki.transport.https(defaults) returns a transport(request) -> {status,
169
172
  // headers, body}. The toolkit's sole socket choke point: explicit trust anchors,
package/lib/cms-sign.js CHANGED
@@ -16,6 +16,7 @@
16
16
  var asn1 = require("./asn1-der");
17
17
  var oid = require("./oid");
18
18
  var x509 = require("./schema-x509");
19
+ var crlSchema = require("./schema-crl");
19
20
  var pkix = require("./schema-pkix");
20
21
  var frameworkError = require("./framework-error");
21
22
 
@@ -576,6 +577,71 @@ function _dedupe(ders) {
576
577
  return out;
577
578
  }
578
579
 
580
+ // ---- pki.cms.certsOnly (RFC 8551 sec. 3.8 / RFC 5652 sec. 5.1) --------------
581
+ // A certificate-management ("certs-only") message: a degenerate SignedData that conveys
582
+ // certificates and/or CRLs and signs nothing. Documented by the @primitive block in cms-verify.js
583
+ // (the @module pki.cms home).
584
+ var KNOWN_CERTS_ONLY_OPTS = { crls: 1, pem: 1 };
585
+
586
+ // A single entity or an array of them -> a dense array (empty when the argument is nullish).
587
+ // reqDenseArray snapshots the array structure and refuses a sparse hole or a nullish entry
588
+ // (M15), so a caller array that mutates under iteration cannot reintroduce a hole.
589
+ function _certsOnlyList(v, what) {
590
+ if (v == null) return [];
591
+ return intrinsic.isArray(v) ? _b.reqDenseArray(v, what) : [v];
592
+ }
593
+
594
+ // Normalize one caller-supplied certificate/CRL to validated raw DER: snapshot the byte source at
595
+ // the door so a later mutation cannot swap the bytes (M15), accept a PEM block, then parse it with
596
+ // `parseFn` so a non-<thing> -- including a tagged CertificateChoices / RevocationInfoChoice
597
+ // alternative, whose first byte is a context tag rather than 0x30 -- is a typed cms/bad-input and is
598
+ // never embedded (M9/M10/M11). `pemLabel` is the PEM armor type.
599
+ function _normEntityDer(v, what, pemLabel, parseFn) {
600
+ var der;
601
+ if (guard.bytes.isByteSource(v)) {
602
+ der = guard.bytes.snapshotSource(v, CmsError, "cms/bad-input", what);
603
+ if (der[0] !== 0x30) {
604
+ var decoded = pkix.pemDecodeLenient(intrinsic.bufToString(der, "latin1"), pemLabel);
605
+ if (decoded === null) throw _err("cms/bad-input", what + " must be a plain DER " + pemLabel + " (a tagged alternative is not permitted) or a PEM block");
606
+ der = decoded;
607
+ }
608
+ } else if (typeof v === "string") {
609
+ var d2 = pkix.pemDecodeLenient(v, pemLabel);
610
+ if (d2 === null) throw _err("cms/bad-input", what + " PEM is not a " + pemLabel + " block");
611
+ der = d2;
612
+ } else {
613
+ throw _err("cms/bad-input", what + " must be a DER Buffer or a PEM string");
614
+ }
615
+ try { parseFn(der); }
616
+ catch (e) { throw _err("cms/bad-input", what + " is not a valid " + pemLabel, e); }
617
+ return der;
618
+ }
619
+ function _parseX509(der) { return x509.parse(der); }
620
+ function _parseCrl(der) { return crlSchema.parse(der); }
621
+
622
+ function certsOnly(certs, opts) {
623
+ opts = guard.identifier.optionsObject(opts, _err, "cms/bad-input", "pki.cms.certsOnly options");
624
+ guard.identifier.assertKnownKeys(opts, KNOWN_CERTS_ONLY_OPTS, _err, "cms/bad-input", "unknown opts field ");
625
+ var certList = _certsOnlyList(certs, "certificates");
626
+ var crlList = _certsOnlyList(opts.crls, "crls");
627
+ // RFC 8551 sec. 3.8 conveys "certificates and/or CRLs"; a message with neither conveys nothing.
628
+ if (!certList.length && !crlList.length) throw _err("cms/bad-input", "a certs-only message must carry at least one certificate or CRL (RFC 8551 sec. 3.8)");
629
+ // Each entity validated + snapshotted at the door, then DER-sorted + deduped (X.690 sec. 11.6).
630
+ var certDers = intrinsic.sort(_dedupe(intrinsic.map(certList, function (c) { return _normEntityDer(c, "a certificate", "CERTIFICATE", _parseX509); })), intrinsic.compare);
631
+ var crlDers = intrinsic.sort(_dedupe(intrinsic.map(crlList, function (c) { return _normEntityDer(c, "a CRL", "X509 CRL", _parseCrl); })), intrinsic.compare);
632
+ // The degenerate SignedData (RFC 5652 sec. 5.1): version 1 (all choices plain, id-data, no signer),
633
+ // an empty digestAlgorithms + signerInfos, an id-data encapContentInfo with eContent ABSENT, and the
634
+ // caller certificates [0] / crls [1]. The strict re-parse enforces the version<->contents coupling.
635
+ var encap = b.sequence([b.oid(OID_DATA)]);
636
+ var sdFields = [b.integer(1n), b.set([]), encap];
637
+ if (certDers.length) intrinsic.push(sdFields, b.contextConstructed(0, intrinsic.bufferConcat(certDers))); // [0] IMPLICIT SET OF
638
+ if (crlDers.length) intrinsic.push(sdFields, b.contextConstructed(1, intrinsic.bufferConcat(crlDers))); // [1] IMPLICIT SET OF
639
+ intrinsic.push(sdFields, b.set([])); // signerInfos SET OF {}
640
+ var signedData = b.sequence(sdFields);
641
+ var contentInfo = b.sequence([b.oid(OID_SIGNED_DATA), b.explicit(0, signedData)]);
642
+ return opts.pem ? pkix.pemEncode(contentInfo, "CMS", frameworkError.PemError) : contentInfo;
643
+ }
644
+
579
645
  function _toBuf(v, what) {
580
646
  if (guard.bytes.isByteSource(v)) return guard.bytes.snapshotSource(v, CmsError, "cms/bad-input", what);
581
647
  throw _err("cms/bad-input", what + " must be a Buffer");
@@ -785,7 +851,7 @@ function _countersign(cmsInput, signers, opts) {
785
851
  // * the `crls [1]` preservation branches in `countersign`. pki.cms.sign never emits a crls field,
786
852
  // so a store this producer countersigns never carries one to preserve.
787
853
  module.exports = {
788
- sign: sign, countersign: countersign,
854
+ sign: sign, countersign: countersign, certsOnly: certsOnly,
789
855
  // @internal -- the signer-descriptor field tables, for a verb that AUTHORS signer descriptors
790
856
  // from its own caller's options and gates them at its own door.
791
857
  KNOWN_SIGNER_CERT_KEYS: KNOWN_SIGNER_CERT_KEYS,
package/lib/cms-verify.js CHANGED
@@ -580,6 +580,17 @@ function _surfaceUnsignedAttrs(si) {
580
580
  });
581
581
  }
582
582
 
583
+ // The AUTHENTICATED attributes, surfaced per signer so a caller reads a signed attribute -- a content
584
+ // type, a signing time, a protocol's own transaction state (SCEP's messageType / nonces) -- BOUND to
585
+ // the verified signature rather than re-parsed from the untrusted message, where an attacker could
586
+ // present attributes the signature never covered. The signature is over the SignedAttributes these
587
+ // decode from, so read them only where the signer's `ok` is true.
588
+ function _surfaceSignedAttrs(si) {
589
+ return intrinsic.map(si.signedAttrs || [], function (a) {
590
+ return { type: a.type, typeName: oid.name(a.type) || null, values: a.values };
591
+ });
592
+ }
593
+
583
594
  // Verify every countersignature attached to `si` (RFC 5652 sec. 11.4): each id-countersignature
584
595
  // value is a SignerInfo over `si`'s signature octets. Returns per-countersignature verdicts; a
585
596
  // countersignature's own countersignatures verify over its signature octets (recursive). A
@@ -860,6 +871,8 @@ async function _verify(input, opts) {
860
871
  // whose profile requires attributes (RFC 8551 S/MIME does) can only enforce it if the verdict says
861
872
  // which they got.
862
873
  verdict.signedAttributesPresent = !!siOne.signedAttrsBytes;
874
+ // The authenticated attributes themselves, bound to this signer's verdict (read only when ok).
875
+ verdict.signedAttributes = _surfaceSignedAttrs(siOne);
863
876
  intrinsic.push(signers, verdict);
864
877
  }
865
878
  // The content type travels with the verdict. An operator applying a policy of their own -- "I only
@@ -870,6 +883,10 @@ async function _verify(input, opts) {
870
883
  // `every` replaced after load reports the whole set sound without reading one signer.
871
884
  valid: signers.length > 0 && guard.list.allMatch(signers, function (s) { return s.ok === true; }),
872
885
  eContentType: parsed.encapContentInfo.eContentType,
886
+ // The attached encapsulated content (null for a detached signature). A signer's message-digest
887
+ // attribute binds these exact bytes, so a `valid` verdict lets a caller consume the authenticated
888
+ // eContent -- SCEP's pkcsPKIEnvelope -- without a second parse of the untrusted message.
889
+ eContent: parsed.encapContentInfo.eContent != null ? parsed.encapContentInfo.eContent : null,
873
890
  signers: signers,
874
891
  };
875
892
  await _applyTrust(res, parsedCerts, trustCfg);
@@ -1423,5 +1440,129 @@ var compress = cmsCompress.compress;
1423
1440
  */
1424
1441
  var decompress = cmsCompress.decompress;
1425
1442
 
1443
+ // A certs-only reader/recognizer input: a DER Buffer (snapshotted at the door so a later mutation
1444
+ // cannot swap the bytes the verdict describes) or a PEM CMS/PKCS7 block. An undecodable input is a
1445
+ // typed cms/bad-input, never a raw throw.
1446
+ var KNOWN_PARSE_CERTS_ONLY_OPTS = { maxCerts: 1 };
1447
+ function _certsOnlyInputDer(input, verb) {
1448
+ if (guard.bytes.isByteSource(input)) {
1449
+ var buf = guard.bytes.snapshotSource(input, CmsError, "cms/bad-input", verb + " input");
1450
+ if (buf[0] === 0x30) return buf;
1451
+ input = intrinsic.bufToString(buf, "latin1");
1452
+ }
1453
+ if (typeof input === "string") {
1454
+ var der = pkix.pemDecodeLenient(input, "CMS");
1455
+ if (der === null) der = pkix.pemDecodeLenient(input, "PKCS7");
1456
+ if (der === null) throw _err("cms/bad-input", verb + " input is neither DER nor a PEM CMS/PKCS7 block");
1457
+ return der;
1458
+ }
1459
+ throw _err("cms/bad-input", verb + " input must be a DER Buffer or a PEM string");
1460
+ }
1461
+
1462
+ /**
1463
+ * @primitive pki.cms.certsOnly
1464
+ * @signature pki.cms.certsOnly(certs, opts?) -> Buffer | string
1465
+ * @since 0.6.3
1466
+ * @status stable
1467
+ * @spec RFC 8551, RFC 5652
1468
+ * @related pki.cms.parseCertsOnly, pki.cms.isCertsOnly, pki.smime.buildCertsOnly
1469
+ *
1470
+ * Build a "certs-only" certificate-management message (RFC 8551 sec. 3.8): a degenerate CMS
1471
+ * `SignedData` that conveys certificates and/or CRLs and signs nothing. The emitted structure is
1472
+ * version 1 with an empty `digestAlgorithms`, an id-data `encapContentInfo` whose `eContent` is absent,
1473
+ * the certificates in `certificates [0]` and any CRLs in `crls [1]` (both DER-sorted and deduplicated),
1474
+ * and an empty `signerInfos`. It is how an AIA `caIssuers` bundle or an `application/pkcs7-mime;
1475
+ * smime-type=certs-only` attachment distributes a set of certificates. `certs` is a certificate or an
1476
+ * array of them (DER `Buffer` or PEM string), each parsed before embedding so a non-certificate is a
1477
+ * typed `CmsError` and is never emitted. At least one certificate or CRL is required.
1478
+ *
1479
+ * @opts crls A CRL or array of CRLs (DER Buffer or PEM string) to convey alongside the certificates.
1480
+ * @opts pem Return a PEM string instead of a DER Buffer.
1481
+ * @example
1482
+ * var pair = await pki.key.generate("Ed25519");
1483
+ * var leafDer = await pki.x509.sign({ subject: "Leaf", subjectPublicKey: await pki.key.export(pair.publicKey),
1484
+ * notBefore: new Date("2026-01-01T00:00:00Z"), notAfter: new Date("2036-01-01T00:00:00Z") }, { key: await pki.key.export(pair.privateKey) });
1485
+ * var bundle = pki.cms.certsOnly([leafDer]);
1486
+ * var r = pki.cms.parseCertsOnly(bundle); // { certificates: [leafDer], crls: [] }
1487
+ */
1488
+ var certsOnly = cmsSign.certsOnly;
1489
+
1490
+ /**
1491
+ * @primitive pki.cms.parseCertsOnly
1492
+ * @signature pki.cms.parseCertsOnly(input, opts?) -> { certificates, crls }
1493
+ * @since 0.6.3
1494
+ * @status stable
1495
+ * @spec RFC 8551, RFC 5652
1496
+ * @related pki.cms.certsOnly, pki.cms.isCertsOnly, pki.est.parseCertsOnly
1497
+ *
1498
+ * Read a certs-only certificate-management message (DER Buffer or PEM) and recover the raw certificate
1499
+ * and CRL DER it carries. It requires a degenerate `SignedData` (id-data with no eContent, empty
1500
+ * `signerInfos`) and returns `{ certificates: [DER], crls: [DER] }`; a non-degenerate structure is a
1501
+ * typed `cms/not-certs-only`. A CRL-only message is accepted (RFC 8551 sec. 3.8 conveys "certificates
1502
+ * and/or CRLs"), unlike the stricter RFC 5272 Simple PKI Response `pki.est.parseCertsOnly`; a message
1503
+ * carrying neither certificates nor CRLs is refused. Each embedded certificate and CRL is validated
1504
+ * before it is returned.
1505
+ *
1506
+ * @opts maxCerts Cap the number of certificates and CRLs parsed and returned (a DoS bound on an untrusted bundle).
1507
+ * @example
1508
+ * var pair = await pki.key.generate("Ed25519");
1509
+ * var certDer = await pki.x509.sign({ subject: "Leaf", subjectPublicKey: await pki.key.export(pair.publicKey),
1510
+ * notBefore: new Date("2026-01-01T00:00:00Z"), notAfter: new Date("2036-01-01T00:00:00Z") }, { key: await pki.key.export(pair.privateKey) });
1511
+ * var bundleDer = pki.cms.certsOnly([certDer]);
1512
+ * var r = pki.cms.parseCertsOnly(bundleDer);
1513
+ * r.certificates; // array of raw certificate DER Buffers
1514
+ */
1515
+ function parseCertsOnly(input, opts) {
1516
+ opts = guard.identifier.optionsObject(opts, _err, "cms/bad-input", "pki.cms.parseCertsOnly options");
1517
+ guard.identifier.assertKnownKeys(opts, KNOWN_PARSE_CERTS_ONLY_OPTS, _err, "cms/bad-input", "pki.cms.parseCertsOnly has an unknown option ");
1518
+ // maxCerts bounds the parse of an untrusted bundle, so the bound itself is validated at the door: a
1519
+ // negative, fractional, NaN, or non-numeric cap that slice would silently treat as no cap (or, for
1520
+ // -1, as "all but the last") is refused rather than forwarded (guard.limits.cap). Absent or null
1521
+ // leaves the count uncapped.
1522
+ var maxCerts = guard.limits.cap(opts.maxCerts == null ? undefined : opts.maxCerts, "maxCerts", undefined, { E: _err, code: "cms/bad-input" });
1523
+ return cms.parseCertsOnly(_certsOnlyInputDer(input, "pki.cms.parseCertsOnly"), _err, "cms", maxCerts, false);
1524
+ }
1525
+
1526
+ /**
1527
+ * @primitive pki.cms.isCertsOnly
1528
+ * @signature pki.cms.isCertsOnly(input) -> boolean
1529
+ * @since 0.6.3
1530
+ * @status stable
1531
+ * @spec RFC 8551, RFC 5652
1532
+ * @related pki.cms.certsOnly, pki.cms.parseCertsOnly
1533
+ *
1534
+ * Recognize a certs-only certificate-management message structurally: `true` when `input` (DER Buffer
1535
+ * or PEM) is a CMS `SignedData` with an id-data `encapContentInfo` whose `eContent` is absent and an
1536
+ * empty `signerInfos`, `false` for any other well-formed CMS (a signed message, an EnvelopedData).
1537
+ * Undecodable bytes throw a typed `CmsError`.
1538
+ *
1539
+ * @example
1540
+ * var pair = await pki.key.generate("Ed25519");
1541
+ * var certDer = await pki.x509.sign({ subject: "Leaf", subjectPublicKey: await pki.key.export(pair.publicKey),
1542
+ * notBefore: new Date("2026-01-01T00:00:00Z"), notAfter: new Date("2036-01-01T00:00:00Z") }, { key: await pki.key.export(pair.privateKey) });
1543
+ * pki.cms.isCertsOnly(pki.cms.certsOnly([certDer])); // true
1544
+ */
1545
+ function isCertsOnly(input) {
1546
+ // A certs-only message is a SignedData with an id-data content, absent eContent, and no signer.
1547
+ // digestAlgorithms is deliberately NOT constrained: RFC 5652 sec. 5.1 permits a non-empty set even
1548
+ // with no signer, so a valid but non-canonical bundle (an EST or AIA response) is still recognized.
1549
+ var der = _certsOnlyInputDer(input, "pki.cms.isCertsOnly");
1550
+ var r;
1551
+ try {
1552
+ r = cms.parse(der);
1553
+ } catch (e) {
1554
+ // A well-formed CMS ContentInfo whose content type this toolkit does not model (a bare id-data,
1555
+ // a DigestedData) is definitively not a certs-only SignedData, so the predicate reports false
1556
+ // rather than making a caller catch an exception for a valid non-SignedData CMS. Truly
1557
+ // undecodable bytes (not a ContentInfo at all) still throw.
1558
+ if (e && e.code === "cms/unsupported-content-type") return false;
1559
+ throw e;
1560
+ }
1561
+ return r.contentTypeName === "signedData" &&
1562
+ r.encapContentInfo.eContentType === oid.byName("data") &&
1563
+ r.encapContentInfo.eContent === null &&
1564
+ r.signerInfos.length === 0;
1565
+ }
1566
+
1426
1567
  // `setEngine` is @internal -- the path-validate injection seam, never part of pki.cms.
1427
- module.exports = { verify: verify, sign: sign, countersign: countersign, encrypt: encrypt, authenticate: authenticate, decrypt: decrypt, compress: compress, decompress: decompress, setEngine: setEngine };
1568
+ module.exports = { verify: verify, sign: sign, countersign: countersign, encrypt: encrypt, authenticate: authenticate, decrypt: decrypt, compress: compress, decompress: decompress, certsOnly: certsOnly, parseCertsOnly: parseCertsOnly, isCertsOnly: isCertsOnly, setEngine: setEngine };
package/lib/constants.js CHANGED
@@ -349,6 +349,11 @@ var LIMITS = {
349
349
  // ACME challenge token entropy floor (RFC 8555 sec. 8, errata 6950): >= 128
350
350
  // bits of base64url is >= 22 characters. A shorter token is refused before use.
351
351
  ACME_TOKEN_MIN_CHARS: 22,
352
+ // SCEP transactionID length ceiling (RFC 8894 sec. 3.2.1.1). The RFC sets no
353
+ // length; a real transaction id is a short hash or key fingerprint, so the
354
+ // builder caps the caller-supplied PrintableString here rather than emitting
355
+ // an unbounded attribute.
356
+ SCEP_TRANSACTION_ID_MAX: 255,
352
357
  // OCSP embedded-certificate ceiling. A BasicOCSPResponse (or an OCSP request
353
358
  // Signature) carries the responder / requestor certificate plus at most a short
354
359
  // chain; the delegated-responder authorization loop verifies each candidate
@@ -248,6 +248,12 @@ var SmimeError = defineClass("SmimeError", { withCause: true });
248
248
  // inner `asn1/*` decode error) as `.cause`.
249
249
  var CtError = defineClass("CtError", { withCause: true });
250
250
 
251
+ // ScepError -- a byte sequence that is not a well-formed SCEP pkiMessage (RFC 8894): a
252
+ // malformed CMS layering, a missing or mis-encoded transaction attribute, an unknown
253
+ // messageType / pkiStatus / failInfo enumerant, a nonce mismatch, or a weak-algorithm
254
+ // profile violation. Fail-closed: a malformed or off-profile message is a typed verdict.
255
+ var ScepError = defineClass("ScepError", { withCause: true });
256
+
251
257
  // TlsError -- a byte sequence that is not a well-formed TLS handshake structure:
252
258
  // an RFC 8879 CompressedCertificate whose framing is violated (a lying vector
253
259
  // length, a field read past its bound, an empty compressed message), whose
@@ -395,6 +401,7 @@ module.exports = {
395
401
  CmpError: CmpError,
396
402
  PathError: PathError,
397
403
  CtError: CtError,
404
+ ScepError: ScepError,
398
405
  TlsError: TlsError,
399
406
  C509Error: C509Error,
400
407
  ShbsError: ShbsError,
package/lib/oid.js CHANGED
@@ -572,6 +572,16 @@ var FAMILIES = {
572
572
  // (WebAuthn L3 8.3.1).
573
573
  tcgKp: { base: [2, 23, 133, 8], of: { tcgKpAikCertificate: 3 } },
574
574
  tcgAt: { base: [2, 23, 133, 2], of: { tpmManufacturer: 1, tpmModel: 2, tpmVersion: 3 } },
575
+
576
+ // SCEP (RFC 8894) transaction attributes on the VeriSign arc 2.16.840.1.113733.1.9
577
+ // (id-attributes). scep-prefixed because the CMC arc already registers senderNonce /
578
+ // transactionId under different OIDs (RFC 8894 sec. 3.2.1, Tables 1-2).
579
+ scepAttribute: { base: [2, 16, 840, 1, 113733, 1, 9], of: {
580
+ scepMessageType: 2, scepPkiStatus: 3, scepFailInfo: 4,
581
+ scepSenderNonce: 5, scepRecipientNonce: 6, scepTransactionId: 7 } },
582
+ // id-scep on the PKIX arc 1.3.6.1.5.5.7.24; failInfoText is the only leaf SCEP uses
583
+ // (RFC 8894 sec. 3.2.1.4).
584
+ scep: { base: [1, 3, 6, 1, 5, 5, 7, 24], of: { scepFailInfoText: 1 } },
575
585
  };
576
586
 
577
587
  var _byOid = new Map();
package/lib/scep.js ADDED
@@ -0,0 +1,562 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (c) blamejs contributors
3
+ "use strict";
4
+ /**
5
+ * @module pki.scep
6
+ * @nav Schema
7
+ * @title SCEP
8
+ * @fullname Simple Certificate Enrolment Protocol (RFC 8894)
9
+ * @order 193
10
+ * @slug scep
11
+ *
12
+ * @intro
13
+ * The SCEP pkiMessage codec. SCEP wraps a PKCS#10 certification request (or an
14
+ * issued certificate) in two nested CMS layers: an inner EnvelopedData
15
+ * (`pkcsPKIEnvelope`) that encrypts the messageData to the recipient, and an
16
+ * outer SignedData that signs it under a set of authenticated transaction
17
+ * attributes -- messageType, transactionID, pkiStatus, failInfo, and the
18
+ * sender/recipient nonces (RFC 8894 sec. 3). `pki.scep.build` assembles a
19
+ * request pkiMessage (PKCSReq / RenewalReq); `pki.scep.parse` verifies the
20
+ * outer signature, reads the transaction attributes BOUND to the verified
21
+ * signer, and (given the recipient key) decrypts the pkcsPKIEnvelope to the
22
+ * messageData.
23
+ *
24
+ * The transaction attributes are surfaced only from a signature that verified:
25
+ * a pkiMessage whose outer signature does not check is refused, never returned
26
+ * with a false verdict. The pkcsPKIEnvelope is built with AES-128-CBC. This is
27
+ * the message layer, transport-agnostic; a live SCEP CA is driven over
28
+ * pki.transport separately.
29
+ *
30
+ * @card
31
+ * Build and read SCEP (RFC 8894) enrollment messages: a PKCSReq / RenewalReq
32
+ * request wrapped in the signed-over-encrypted CMS layering, and a PKCSReq,
33
+ * RenewalReq, or CertRep parsed back to its verified transaction attributes and
34
+ * decrypted messageData.
35
+ */
36
+
37
+ var frameworkError = require("./framework-error");
38
+ var ScepError = frameworkError.ScepError;
39
+ var oid = require("./oid");
40
+ var asn1 = require("./asn1-der");
41
+ var b = asn1.build;
42
+ var cmsSign = require("./cms-sign");
43
+ var cmsVerify = require("./cms-verify");
44
+ var cmsEncrypt = require("./cms-encrypt");
45
+ var cmsDecrypt = require("./cms-decrypt");
46
+ require("./path-validate"); // side-effect: injects the certification-path signature engine into csr-verify at load
47
+ var csrVerify = require("./csr-verify"); // verify an embedded PKCS#10's proof-of-possession before enveloping it
48
+ var schemaCms = require("./schema-cms");
49
+ var schemaCsr = require("./schema-csr");
50
+ var schemaX509 = require("./schema-x509");
51
+ var schemaCrl = require("./schema-crl");
52
+ var pkix = require("./schema-pkix");
53
+ var guard = require("./guard-all");
54
+ var C = require("./constants");
55
+ var nodeCrypto = require("node:crypto");
56
+
57
+ function _err(code, msg, cause) { return new ScepError(code, msg, cause); }
58
+
59
+ // The namespace pkix.keyUsageOf reads a certificate's keyUsage extension through.
60
+ var _KU_NS = pkix.makeNS("scep", ScepError, oid);
61
+
62
+ // The messageType values are a DATA table (RFC 8894 sec. 3.2.1.2, Table 3), never a switch: name <-> the
63
+ // decimal ASCII a PrintableString carries. RFC 8894 renumbered the legacy draft (RenewalReq is 17, and
64
+ // there is no GetCertInitial -- it is CertPoll 20).
65
+ var MESSAGE_TYPE = { CertRep: "3", RenewalReq: "17", PKCSReq: "19", CertPoll: "20", GetCert: "21", GetCRL: "22" };
66
+ // pkiStatus (Table 4): SUCCESS 0, FAILURE 2, PENDING 3 -- note there is NO value 1.
67
+ var PKI_STATUS = { SUCCESS: "0", FAILURE: "2", PENDING: "3" };
68
+ // failInfo (Table 5).
69
+ var FAIL_INFO = { badAlg: "0", badMessageCheck: "1", badRequest: "2", badTime: "3", badCertId: "4" };
70
+
71
+ // name -> code and code -> name, built once from each table so a lookup is a data read, not a switch.
72
+ function _invert(table) { var o = Object.create(null); for (var k in table) if (Object.prototype.hasOwnProperty.call(table, k)) o[table[k]] = k; return o; }
73
+ var MESSAGE_TYPE_BY_CODE = _invert(MESSAGE_TYPE), PKI_STATUS_BY_CODE = _invert(PKI_STATUS), FAIL_INFO_BY_CODE = _invert(FAIL_INFO);
74
+
75
+ // The message types pki.scep.parse reads: the enrollment request pair a client builds and the CertRep
76
+ // response it receives. The CertPoll / GetCert / GetCRL client queries are refused (see parse).
77
+ var _PARSE_SUPPORTED = { PKCSReq: 1, RenewalReq: 1, CertRep: 1 };
78
+
79
+ // The RFC 8894 sec. 3 EnvelopedData content-encryption profile. AES-128-CBC is the mandatory strong
80
+ // cipher; the toolkit's own cms.encrypt refuses the weak legacy ciphers structurally, so the builder
81
+ // only names the one it emits.
82
+ var ENVELOPE_CIPHER = "aes-128-cbc";
83
+
84
+ // The empty external content a conforming FAILURE / PENDING CertRep is verified against: its
85
+ // pkcsPKIEnvelope is omitted, so the SignedData carries no encapsulated content (RFC 8894 sec. 3.3.2).
86
+ var EMPTY_CONTENT = Buffer.alloc(0);
87
+
88
+ // A 16-byte nonce (RFC 8894 sec. 3.2.1.5): a caller value copied at the door and validated to width, or
89
+ // a fresh random one. The copy makes a caller value read after an await immune to concurrent mutation.
90
+ function _nonce(v, label) {
91
+ if (v == null) return nodeCrypto.randomBytes(16);
92
+ var buf = guard.bytes.snapshotSource(v, ScepError, "scep/bad-nonce", label);
93
+ if (buf.length !== 16) throw _err("scep/bad-nonce", label + " must be exactly 16 bytes (RFC 8894 sec. 3.2.1.5), got " + buf.length);
94
+ return buf;
95
+ }
96
+
97
+ // A caller PrintableString for a transaction id: bounded (the RFC sets no length, so cap it against a DoS)
98
+ // and restricted to the PrintableString character set (asn1.build.printable enforces the set).
99
+ function _transactionId(v) {
100
+ if (typeof v !== "string" || v.length === 0) throw _err("scep/bad-input", "transactionId must be a non-empty string (RFC 8894 sec. 3.2.1.1)");
101
+ if (v.length > C.LIMITS.SCEP_TRANSACTION_ID_MAX) throw _err("scep/bad-input", "transactionId exceeds the " + C.LIMITS.SCEP_TRANSACTION_ID_MAX + "-character cap");
102
+ return v;
103
+ }
104
+
105
+ // Assert some bytes are a CMS ContentInfo wrapping a well-formed EnvelopedData whose encrypted content
106
+ // type is id-data -- the pkcsPKIEnvelope profile (RFC 8894 sec. 3.2, sec. 3.2.2). Delegated to the
107
+ // strict CMS parser, and checked structurally without decryption, so an absent, malformed, or
108
+ // off-profile envelope is refused for every envelope-carrying message whether or not a recipient key
109
+ // was supplied.
110
+ function _assertValidEnvelope(bytes, messageType) {
111
+ if (bytes == null) throw _err("scep/missing-envelope", "the pkcsPKIEnvelope is mandatory for a " + messageType + " message but the signed content is absent (RFC 8894 sec. 3.2)");
112
+ var parsed;
113
+ try { parsed = schemaCms.parse(bytes); }
114
+ catch (e) { throw _err("scep/missing-envelope", "the pkcsPKIEnvelope of a " + messageType + " message is not a decodable CMS EnvelopedData (RFC 8894 sec. 3.2)", e); }
115
+ if (parsed.contentTypeName !== "envelopedData") throw _err("scep/missing-envelope", "the pkcsPKIEnvelope of a " + messageType + " message must be an EnvelopedData (RFC 8894 sec. 3.2), got " + parsed.contentTypeName);
116
+ if (parsed.encryptedContentInfo.contentType !== oid.byName("data")) throw _err("scep/bad-envelope-content-type", "the pkcsPKIEnvelope's encrypted content type must be id-data (RFC 8894 sec. 3.2.2), got " + parsed.encryptedContentInfo.contentType);
117
+ // The EnvelopedData must actually carry ciphertext: an inner envelope whose encryptedContent is absent
118
+ // or a zero-length OCTET STRING has no messageData to recover (SCEP provides none out of band), so it
119
+ // is refused (RFC 8894 sec. 3.2).
120
+ var ct = parsed.encryptedContentInfo.encryptedContent;
121
+ if (ct == null || ct.length === 0) throw _err("scep/missing-envelope", "the pkcsPKIEnvelope of a " + messageType + " message carries no encrypted content (RFC 8894 sec. 3.2)");
122
+ }
123
+
124
+ // Validate a SUCCESS CertRep's messageData as a degenerate certificates-only CMS SignedData (RFC 8894
125
+ // sec. 3.4) and surface its certificates and CRLs raw, for the caller to path-validate. The issued
126
+ // certificate(s) answer an enrollment; a CRL answers a GetCRL (sec. 3.3.4), so certificates and CRLs are
127
+ // accepted independently and a payload carrying neither is refused.
128
+ function _readIssuancePayload(der) {
129
+ var r;
130
+ try { r = schemaCms.parse(der); }
131
+ catch (e) { throw _err("scep/bad-response", "a SUCCESS CertRep messageData did not decode as a CMS SignedData (RFC 8894 sec. 3.4)", e); }
132
+ if (r.contentTypeName !== "signedData" || r.encapContentInfo.eContentType !== oid.byName("data") ||
133
+ r.encapContentInfo.eContent !== null || r.signerInfos.length !== 0) {
134
+ throw _err("scep/not-certs-only", "a SUCCESS CertRep messageData must be a degenerate certificates-only CMS SignedData (RFC 8894 sec. 3.4)");
135
+ }
136
+ // Validate each entry as a plain X.509 certificate / CRL: a universal-SEQUENCE CertificateChoice or
137
+ // RevocationInfoChoice must be a well-formed certificate / CRL, and a tagged alternative (attribute
138
+ // cert, other-message, otherRevInfo) is not a plain issuance object and is refused.
139
+ var certs = [], crls = [], i;
140
+ var rc = r.certificates || [], rl = r.crls || [];
141
+ for (i = 0; i < rc.length; i++) {
142
+ if (rc[i].tagClass !== "universal") throw _err("scep/bad-certificate", "a SUCCESS CertRep certificates field carried a tagged CertificateChoices alternative, not a plain X.509 certificate (RFC 8894 sec. 3.4)");
143
+ try { schemaX509.parse(rc[i].bytes); }
144
+ catch (e) { throw _err("scep/bad-certificate", "a SUCCESS CertRep carried a non-certificate in its certificates field", e); }
145
+ certs[i] = rc[i].bytes;
146
+ }
147
+ for (i = 0; i < rl.length; i++) {
148
+ if (rl[i].tagClass !== "universal") throw _err("scep/bad-crl", "a SUCCESS CertRep crls field carried a tagged RevocationInfoChoice alternative, not a plain X.509 CRL (RFC 5652 sec. 10.2.1)");
149
+ try { schemaCrl.parse(rl[i].bytes); }
150
+ catch (e) { throw _err("scep/bad-crl", "a SUCCESS CertRep carried a non-CRL in its crls field", e); }
151
+ crls[i] = rl[i].bytes;
152
+ }
153
+ if (certs.length === 0 && crls.length === 0) {
154
+ throw _err("scep/empty-response", "a SUCCESS CertRep messageData carried neither a certificate nor a CRL (RFC 8894 sec. 3.3.2)");
155
+ }
156
+ return { certificates: certs, crls: crls };
157
+ }
158
+
159
+ // Build one SCEP transaction attribute { type, values:[valueDER] } for cms.sign's additionalSignedAttributes.
160
+ function _attr(name, valueDer) { return { type: oid.byName(name), values: [valueDer] }; }
161
+
162
+ // Find the single surfaced signed attribute of a given OID name (the values are raw AttributeValue
163
+ // DER). The CMS parser rejects a repeated attribute type (cms/duplicate-signed-attr) before these
164
+ // attributes are surfaced, so a SCEP transaction attribute appears at most once. It is also
165
+ // single-valued: a value SET that does not hold exactly one value is an ambiguous transaction state
166
+ // and is refused rather than resolved to the first value (RFC 8894 sec. 3.2.1).
167
+ function _find(attrs, name) {
168
+ var want = oid.byName(name);
169
+ for (var i = 0; i < attrs.length; i++) {
170
+ if (attrs[i].type !== want) continue;
171
+ if (!attrs[i].values || attrs[i].values.length !== 1) {
172
+ throw _err("scep/bad-attribute", "the " + name + " transaction attribute must carry exactly one value (RFC 8894 sec. 3.2.1)");
173
+ }
174
+ return attrs[i];
175
+ }
176
+ return null;
177
+ }
178
+ // Read a string transaction attribute to its JS string, requiring the exact ASN.1 string type RFC 8894
179
+ // sec. 3.2 pins for it (a generic string reader would accept an off-profile UTF8String or IA5String
180
+ // where a PrintableString is required). Returns null when the attribute is absent.
181
+ function _readStr(attrs, name, expectedTag) {
182
+ var a = _find(attrs, name);
183
+ if (a == null) return null;
184
+ var node;
185
+ try { node = asn1.decode(a.values[0]); }
186
+ catch (e) { throw _err("scep/bad-attribute", "the " + name + " transaction attribute is not decodable", e); }
187
+ if (node.tagClass !== "universal" || node.tagNumber !== expectedTag) {
188
+ throw _err("scep/bad-attribute", "the " + name + " transaction attribute is not the ASN.1 string type RFC 8894 sec. 3.2 requires");
189
+ }
190
+ try { return asn1.read.string(node); }
191
+ catch (e) { throw _err("scep/bad-attribute", "the " + name + " transaction attribute is not a readable string", e); }
192
+ }
193
+ var _T_PRINTABLE = asn1.TAGS.PRINTABLE_STRING, _T_UTF8 = asn1.TAGS.UTF8_STRING;
194
+ // Read a 16-byte OCTET STRING nonce attribute, or null when absent.
195
+ function _readNonce(attrs, name) {
196
+ var a = _find(attrs, name);
197
+ if (a == null) return null;
198
+ var n;
199
+ try { n = asn1.read.octetString(asn1.decode(a.values[0])); }
200
+ catch (e) { throw _err("scep/bad-nonce", "the " + name + " transaction attribute is not a readable OCTET STRING", e); }
201
+ if (n.length !== 16) throw _err("scep/bad-nonce", "the " + name + " nonce must be exactly 16 bytes (RFC 8894 sec. 3.2.1.5), got " + n.length);
202
+ return n;
203
+ }
204
+
205
+ // Whether two certificates carry the same subject public key -- the SCEP signer-authentication test
206
+ // (a CertRep must be signed by the CA the client already holds, RFC 8894 sec. 3.1). Compared by the
207
+ // SubjectPublicKeyInfo so a re-encoded certificate of the same key still matches.
208
+ function _sameKey(certA, certB) {
209
+ var a, bb;
210
+ try { a = schemaX509.parse(certA).subjectPublicKeyInfo.bytes; bb = schemaX509.parse(certB).subjectPublicKeyInfo.bytes; }
211
+ catch (e) { throw _err("scep/bad-input", "a certificate could not be parsed for signer authentication: " + e.message, e); }
212
+ return guard.crypto.constantTimeEqual(a, bb);
213
+ }
214
+
215
+ // The pkcsPKIEnvelope uses RSAES-OAEP key transport, so the recipient MUST be an RSA key-transport
216
+ // certificate (RFC 8894 sec. 3). An EC / X25519 / ML-KEM recipient would make cms.encrypt emit a
217
+ // key-agreement or KEM recipient off the SCEP profile, so it is refused before the CMS dispatch.
218
+ function _assertRsaRecipient(recipientDer) {
219
+ var spki;
220
+ try { spki = schemaX509.parse(recipientDer).subjectPublicKeyInfo; }
221
+ catch (e) { throw _err("scep/bad-input", "the recipient is not a parseable certificate: " + e.message, e); }
222
+ if (spki.algorithm.oid !== oid.byName("rsaEncryption")) {
223
+ throw _err("scep/bad-recipient", "the SCEP recipient must be an RSA key-transport certificate (RFC 8894 sec. 3); its public-key algorithm is " + spki.algorithm.oid);
224
+ }
225
+ }
226
+
227
+ // A SCEP signer's certificate MUST be authorized to sign: its keyUsage extension, when present, must
228
+ // assert digitalSignature (RFC 8894 sec. 2.3 requires that bit specifically). A certificate whose
229
+ // keyUsage omits it, permitting only encryption or non-repudiation, is refused, so a signature it makes
230
+ // is not read as authenticated. A certificate with no keyUsage extension is unrestricted and passes.
231
+ function _assertSigningKeyUsage(certDer, label) {
232
+ var cert;
233
+ try { cert = schemaX509.parse(certDer); }
234
+ catch (e) { throw _err("scep/bad-input", "the " + label + " could not be parsed for its key usage: " + e.message, e); }
235
+ var ku = pkix.keyUsageOf(_KU_NS, cert, _err, "scep/bad-input", "the " + label + "'s");
236
+ if (ku != null && ku.digitalSignature !== true) {
237
+ throw _err("scep/bad-signer-usage", "the " + label + " keyUsage does not assert digitalSignature, so it is not authorized to sign (RFC 8894 sec. 2.3)");
238
+ }
239
+ }
240
+
241
+ // Snapshot the recipient key material at the parse door: the certificate byte source is copied so a
242
+ // concurrent mutation cannot redirect the decryption, and the private / content key is held by
243
+ // reference (copying a secret is the worse defect). null passes through unchanged.
244
+ function _captureRecipientKey(rk) {
245
+ if (rk == null) return null;
246
+ rk = guard.identifier.optionsObject(rk, _err, "scep/bad-input", "opts.recipientKey");
247
+ var out = {};
248
+ if (rk.cert != null) out.cert = guard.bytes.snapshotSource(rk.cert, ScepError, "scep/bad-input", "opts.recipientKey.cert");
249
+ if (rk.key != null) out.key = rk.key;
250
+ if (rk.cek != null) out.cek = rk.cek;
251
+ return out;
252
+ }
253
+
254
+ /**
255
+ * @primitive pki.scep.build
256
+ * @signature pki.scep.build(spec) -> Promise<Buffer>
257
+ * @since 0.6.2
258
+ * @status stable
259
+ * @spec RFC 8894
260
+ * @related pki.scep.parse, pki.cms.sign, pki.cms.encrypt, pki.csr.sign
261
+ *
262
+ * Assemble a SCEP pkiMessage (RFC 8894 sec. 3). A request (`PKCSReq` / `RenewalReq`) encrypts the
263
+ * supplied PKCS#10 `messageData` to the recipient CA certificate as the inner EnvelopedData
264
+ * (`pkcsPKIEnvelope`, AES-128-CBC), then signs it under the transaction attributes with the caller's
265
+ * signer certificate and key. `transactionId` is a caller-unique PrintableString; `senderNonce` is a
266
+ * 16-byte value (a fresh random one is generated when omitted). The recipient CA certificate must
267
+ * assert the `keyEncipherment` key usage (the EnvelopedData uses RSA key transport). The content key
268
+ * is transported under RSAES-OAEP (SHA-256), the toolkit's key-transport algorithm; the legacy
269
+ * RSAES-PKCS1-v1_5 that older SCEP servers expect is never emitted, so the CA must support OAEP.
270
+ *
271
+ * For a `PKCSReq` the caller's signer SHOULD be a self-signed certificate using the same subject name
272
+ * and key as the PKCS#10 request (RFC 8894 sec. 2.3); a `RenewalReq` is signed with the existing
273
+ * CA-issued certificate instead, which is why this is the caller's choice rather than an enforced
274
+ * match. The proof-of-possession over the PKCS#10 itself is verified regardless.
275
+ *
276
+ * @opts
277
+ * - `messageType` -- "PKCSReq" | "RenewalReq" (this release's request set).
278
+ * - `messageData` -- the PKCS#10 CertificationRequest DER to enrol.
279
+ * - `recipient` -- the CA (or RA) certificate DER the messageData is encrypted to (an RSA key-transport certificate; a non-RSA recipient is refused, since the envelope uses RSAES-OAEP).
280
+ * - `signer` -- `{ cert, key }`, the outer SignedData signer (the client for a request).
281
+ * - `transactionId` -- a caller-unique PrintableString identifying the transaction.
282
+ * - `senderNonce` -- a 16-byte Buffer (generated when omitted).
283
+ * @example
284
+ * // requires: csrDer -- the PKCS#10 CertificationRequest DER to enrol
285
+ * // requires: caCertDer -- the SCEP CA (or RA) certificate the request is encrypted to (keyEncipherment)
286
+ * // requires: clientCertDer -- the client's own certificate, the outer signer
287
+ * // requires: clientKeyPkcs8 -- the client's private key matching clientCertDer
288
+ * var msg = await pki.scep.build({ messageType: "PKCSReq", messageData: csrDer,
289
+ * recipient: caCertDer, signer: { cert: clientCertDer, key: clientKeyPkcs8 },
290
+ * transactionId: "txn-0001" });
291
+ */
292
+ async function build(spec) {
293
+ spec = guard.identifier.optionsObject(spec, _err, "scep/bad-input", "pki.scep.build spec");
294
+ guard.identifier.assertKnownKeys(spec, _BUILD_KEYS, _err, "scep/bad-input", "pki.scep.build has an unknown option: ");
295
+ var mtCode = MESSAGE_TYPE[spec.messageType];
296
+ if (mtCode == null) throw _err("scep/bad-message-type", "unknown messageType " + JSON.stringify(spec.messageType) + " (RFC 8894 sec. 3.2.1.2)");
297
+ if (spec.messageType !== "PKCSReq" && spec.messageType !== "RenewalReq") {
298
+ throw _err("scep/bad-message-type", "pki.scep.build issues a request (PKCSReq / RenewalReq); " + spec.messageType + " is not built in this release");
299
+ }
300
+ if (spec.signer == null || typeof spec.signer !== "object") throw _err("scep/bad-input", "a signer { cert, key } is required");
301
+ var senderNonce = _nonce(spec.senderNonce, "senderNonce");
302
+ var txnId = _transactionId(spec.transactionId);
303
+ // The messageData is a PKCS#10 CertificationRequest whose self-signature is its proof-of-possession
304
+ // (RFC 8894 sec. 3.3.1, over RFC 2986). Verify the structure and that proof before enveloping it, so
305
+ // arbitrary bytes or a request whose signature does not verify under its own subject public key are
306
+ // refused here rather than encrypted into a message a CA would reject.
307
+ // Capture every input read after an await at this synchronous door, so a caller that mutates or reuses
308
+ // the spec while verification or encryption is pending cannot desync what was verified from what is
309
+ // emitted, or substitute the recipient a request is encrypted to. The certificate byte sources are
310
+ // copied; the signer private key is held by reference (copying a secret is the worse defect).
311
+ var messageData = guard.bytes.snapshotSource(spec.messageData, ScepError, "scep/bad-input", "messageData");
312
+ var recipient = guard.bytes.snapshotSource(spec.recipient, ScepError, "scep/bad-input", "recipient");
313
+ _assertRsaRecipient(recipient);
314
+ var signerCert = guard.bytes.snapshotSource(spec.signer.cert, ScepError, "scep/bad-input", "signer.cert");
315
+ _assertSigningKeyUsage(signerCert, "signer certificate");
316
+ var signerKey = spec.signer.key;
317
+ var parsedCsr;
318
+ try { parsedCsr = schemaCsr.parse(messageData); }
319
+ catch (e) { throw _err("scep/bad-input", "messageData is not a valid PKCS#10 CertificationRequest (RFC 8894 sec. 3.3.1): " + e.message, e); }
320
+ if (!(await csrVerify.verifyCsrSignature(parsedCsr))) {
321
+ throw _err("scep/bad-popo", "the PKCS#10 messageData failed its proof-of-possession: its self-signature does not verify under its own subject public key, so a CA would reject it");
322
+ }
323
+ // Inner EnvelopedData: encrypt the PKCS#10 to the recipient CA, AES-128-CBC (RFC 8894 sec. 3).
324
+ var pkcsPKIEnvelope;
325
+ try {
326
+ pkcsPKIEnvelope = await cmsEncrypt.encrypt(messageData, [{ cert: recipient }], { contentEncryptionAlgorithm: ENVELOPE_CIPHER });
327
+ } catch (e) {
328
+ if (e && e.isPkiError) throw _err("scep/bad-input", "the pkcsPKIEnvelope could not be built (recipient must be a keyEncipherment CA certificate and messageData a PKCS#10): " + e.message, e);
329
+ throw e;
330
+ }
331
+ // Outer SignedData over the envelope, carrying the transaction attributes as authenticated attributes.
332
+ var attrs = [
333
+ _attr("scepMessageType", b.printable(mtCode)),
334
+ _attr("scepTransactionId", b.printable(txnId)),
335
+ _attr("scepSenderNonce", b.octetString(senderNonce)),
336
+ ];
337
+ try {
338
+ return await cmsSign.sign(pkcsPKIEnvelope, { cert: signerCert, key: signerKey }, { additionalSignedAttributes: attrs });
339
+ } catch (e) {
340
+ if (e && e.isPkiError) throw _err("scep/bad-input", "the pkiMessage could not be signed: " + e.message, e);
341
+ throw e;
342
+ }
343
+ }
344
+ var _BUILD_KEYS = { messageType: 1, messageData: 1, recipient: 1, signer: 1, transactionId: 1, senderNonce: 1 };
345
+
346
+ /**
347
+ * @primitive pki.scep.parse
348
+ * @signature pki.scep.parse(bytes, opts?) -> Promise<verdict>
349
+ * @since 0.6.2
350
+ * @status stable
351
+ * @spec RFC 8894
352
+ * @related pki.scep.build, pki.cms.verify, pki.cms.decrypt
353
+ *
354
+ * Disassemble a SCEP pkiMessage (RFC 8894 sec. 3): verify the outer SignedData signature, read the
355
+ * transaction attributes BOUND to the verified signer (never from a separate untrusted parse), and,
356
+ * given the recipient key, decrypt the pkcsPKIEnvelope to recover the messageData. It reads the
357
+ * enrollment message types PKCSReq, RenewalReq, and CertRep; the CertPoll, GetCert, and GetCRL client
358
+ * queries a CA processes are refused (`scep/unsupported-message-type`). The verdict is
359
+ * `{ signatureValid, signerAuthenticated, signerCert, messageType, transactionId, senderNonce,
360
+ * recipientNonce, pkiStatus, failInfo, failInfoText, messageData, certificates, crls }` (fields null
361
+ * when the message does not carry them). For a decrypted SUCCESS CertRep, `certificates` and `crls`
362
+ * hold the issued certificate(s) and any CRL validated out of the certs-only messageData, raw for the
363
+ * caller to path-validate; a GetCRL response carries the CRL and no certificate (RFC 8894 sec. 3.3.4). A malformed message, a missing mandatory attribute, an unknown enumerant, or a
364
+ * nonce mismatch is a typed `ScepError`.
365
+ *
366
+ * `signatureValid` proves only that the message is self-consistent with the certificate it embeds; it
367
+ * does NOT authenticate the signer. A SCEP client MUST authenticate a CA response against the CA
368
+ * certificate it holds: pass `opts.signerCert` and this refuses a signer whose public key does not
369
+ * match (`scep/untrusted-signer`) and reports `signerAuthenticated: true`. A caller that omits it gets
370
+ * a crypto-only verdict (`signerAuthenticated: false`) and MUST authenticate the surfaced `signerCert`
371
+ * itself before acting on the transaction state.
372
+ *
373
+ * @opts
374
+ * - `recipientKey` -- `{ cert, key }` for the recipient, to decrypt the pkcsPKIEnvelope into `messageData`.
375
+ * - `signerCert` -- the expected signer certificate DER (the CA certificate for a CertRep); the message signer's public key must match it, or the message is refused.
376
+ * - `expectedSenderNonce` -- a 16-byte Buffer; a message whose `recipientNonce` does not echo it is refused.
377
+ * @example
378
+ * // requires: pkiMessage -- a SCEP pkiMessage DER (from pki.scep.build, or a CA's response)
379
+ * // requires: caCertDer -- the recipient certificate the pkcsPKIEnvelope was encrypted to
380
+ * // requires: caKeyPkcs8 -- the private key matching caCertDer, to decrypt the messageData
381
+ * var v = await pki.scep.parse(pkiMessage, { recipientKey: { cert: caCertDer, key: caKeyPkcs8 } });
382
+ * v.messageType; // "PKCSReq"
383
+ * v.messageData; // the recovered PKCS#10 DER
384
+ */
385
+ async function parse(bytes, opts) {
386
+ opts = guard.identifier.optionsObject(opts, _err, "scep/bad-input", "pki.scep.parse options");
387
+ guard.identifier.assertKnownKeys(opts, _PARSE_KEYS, _err, "scep/bad-input", "pki.scep.parse has an unknown option: ");
388
+ // Snapshot the message bytes once at this synchronous door: parse verifies them twice (a detached
389
+ // FAILURE / PENDING is re-verified against an empty payload), so a caller that swaps a mutable Buffer
390
+ // between the two attempts must not be able to return one message's attributes for another.
391
+ var msgBytes = guard.bytes.snapshotSource(bytes, ScepError, "scep/bad-der", "pkiMessage");
392
+ // Capture every option read after the awaited verification at this synchronous door, so a caller that
393
+ // mutates or reuses opts while verification is pending cannot swap the authenticated signer, the echo
394
+ // nonce, or the decryption recipient after the checks that depend on them have started. Certificate
395
+ // byte sources are copied; the recipient private key is held by reference.
396
+ var expectedSignerCert = opts.signerCert != null ? guard.bytes.snapshotSource(opts.signerCert, ScepError, "scep/bad-input", "opts.signerCert") : null;
397
+ var expectedSenderNonce = opts.expectedSenderNonce != null ? _nonce(opts.expectedSenderNonce, "expectedSenderNonce") : null;
398
+ var recipientKey = _captureRecipientKey(opts.recipientKey);
399
+ var v;
400
+ try { v = await cmsVerify.verify(msgBytes); }
401
+ catch (e) {
402
+ // A conforming FAILURE or PENDING CertRep omits the pkcsPKIEnvelope, so the SignedData has no
403
+ // encapsulated content and cms.verify reports it as detached. Re-verify against an empty payload,
404
+ // which the signature accepts only when the message-digest was taken over no content; a message
405
+ // signed over any other bytes still fails (RFC 8894 sec. 3.3.2).
406
+ if (e && e.code === "cms/detached-content-required") {
407
+ try { v = await cmsVerify.verify(msgBytes, { content: EMPTY_CONTENT }); }
408
+ catch (e2) {
409
+ if (e2 && e2.isPkiError) throw _err("scep/bad-der", "the pkiMessage is not a verifiable CMS SignedData (RFC 8894 sec. 3): " + e2.message, e2);
410
+ throw e2;
411
+ }
412
+ } else if (e && e.isPkiError) {
413
+ throw _err("scep/bad-der", "the pkiMessage is not a verifiable CMS SignedData (RFC 8894 sec. 3): " + e.message, e);
414
+ } else { throw e; }
415
+ }
416
+ if (v.signers.length !== 1) throw _err("scep/bad-signer", "a SCEP pkiMessage MUST carry exactly one SignerInfo (RFC 8894 sec. 3.1), got " + v.signers.length);
417
+ // Fail closed: the transaction attributes are only trustworthy once the outer signature verifies.
418
+ // cms.verify returns a per-signer verdict rather than throwing, so a bad signature MUST be refused
419
+ // here before any attribute is read -- never surfaced as a false verdict alongside the attributes.
420
+ if (v.valid !== true) throw _err("scep/bad-signature", "the pkiMessage outer signature did not verify (RFC 8894 sec. 3.1)");
421
+ // The SignedData eContentType MUST be id-data (RFC 8894 sec. 3.2): a message that verifies as CMS but
422
+ // names another encapsulated content type is not a valid SCEP pkiMessage.
423
+ if (v.eContentType !== oid.byName("data")) throw _err("scep/bad-content-type", "the pkiMessage eContentType must be id-data (RFC 8894 sec. 3.2)");
424
+ var signer = v.signers[0];
425
+ // A SCEP signer's certificate must be authorized to sign (RFC 8894 sec. 2.3): a signature from a
426
+ // certificate whose keyUsage permits only encryption is not read as an authenticated pkiMessage.
427
+ _assertSigningKeyUsage(signer.cert, "pkiMessage signer certificate");
428
+ // A valid signature proves only that the message is self-consistent with the certificate it embeds,
429
+ // NOT that the signer is the expected party: anyone can mint a certificate and sign a forged CertRep
430
+ // that echoes an observed nonce. A SCEP client MUST authenticate a CA response against the CA
431
+ // certificate it already holds (RFC 8894 sec. 3.1). When opts.signerCert names the expected signer,
432
+ // require the message signer's public key to match it; a caller that omits it gets a crypto-only
433
+ // verdict (signerAuthenticated: false) and MUST authenticate the surfaced signerCert itself before
434
+ // acting on the transaction state.
435
+ var signerAuthenticated = false;
436
+ if (expectedSignerCert != null) {
437
+ // The certificate the caller pins is authenticated only if it is itself authorized to sign: a
438
+ // same-key certificate embedded in the message cannot lend its digitalSignature bit to a pinned
439
+ // certificate that permits only encryption (RFC 8894 sec. 2.3).
440
+ _assertSigningKeyUsage(expectedSignerCert, "opts.signerCert");
441
+ if (!_sameKey(signer.cert, expectedSignerCert)) {
442
+ throw _err("scep/untrusted-signer", "the pkiMessage signer's public key does not match opts.signerCert (RFC 8894 sec. 3.1)");
443
+ }
444
+ signerAuthenticated = true;
445
+ }
446
+ var attrs = signer.signedAttributes;
447
+ // The mandatory attributes (RFC 8894 sec. 3.2.1): transactionID, messageType, senderNonce.
448
+ var messageTypeCode = _readStr(attrs, "scepMessageType", _T_PRINTABLE);
449
+ var transactionId = _readStr(attrs, "scepTransactionId", _T_PRINTABLE);
450
+ var senderNonce = _readNonce(attrs, "scepSenderNonce");
451
+ if (messageTypeCode == null) throw _err("scep/missing-attribute", "the pkiMessage is missing its messageType attribute (RFC 8894 sec. 3.2.1)");
452
+ if (transactionId == null) throw _err("scep/missing-attribute", "the pkiMessage is missing its transactionID attribute (RFC 8894 sec. 3.2.1)");
453
+ if (senderNonce == null) throw _err("scep/missing-attribute", "the pkiMessage is missing its senderNonce attribute (RFC 8894 sec. 3.2.1)");
454
+ var messageType = MESSAGE_TYPE_BY_CODE[messageTypeCode];
455
+ if (messageType == null) throw _err("scep/bad-message-type", "unknown messageType " + JSON.stringify(messageTypeCode) + " (RFC 8894 sec. 3.2.1.2)");
456
+ // This release reads the enrollment messages a SCEP client builds and receives: PKCSReq, RenewalReq,
457
+ // and the CertRep response. The CertPoll / GetCert / GetCRL client queries a CA processes carry
458
+ // IssuerAndSubject / IssuerAndSerialNumber messageData this codec does not model, so they are refused
459
+ // rather than accepted with an unvalidated payload (RFC 8894 sec. 3.3.3, sec. 3.3.4).
460
+ if (_PARSE_SUPPORTED[messageType] !== 1) {
461
+ throw _err("scep/unsupported-message-type", "pki.scep.parse reads PKCSReq, RenewalReq, and CertRep; " + messageType + " is not read in this release");
462
+ }
463
+ var out = {
464
+ signatureValid: true, signerAuthenticated: signerAuthenticated, signerCert: signer.cert,
465
+ messageType: messageType, transactionId: transactionId, senderNonce: senderNonce,
466
+ recipientNonce: null, pkiStatus: null, failInfo: null, failInfoText: null, messageData: null,
467
+ certificates: null, crls: null,
468
+ };
469
+ // A CertRep carries pkiStatus (+ failInfo/failInfoText on FAILURE) and echoes the request's senderNonce.
470
+ if (messageType === "CertRep") {
471
+ var statusCode = _readStr(attrs, "scepPkiStatus", _T_PRINTABLE);
472
+ if (statusCode == null) throw _err("scep/missing-attribute", "a CertRep is missing its pkiStatus attribute (RFC 8894 sec. 3.2.1.3)");
473
+ out.pkiStatus = PKI_STATUS_BY_CODE[statusCode];
474
+ if (out.pkiStatus == null) throw _err("scep/bad-pki-status", "unknown pkiStatus " + JSON.stringify(statusCode) + " (RFC 8894 sec. 3.2.1.3)");
475
+ out.recipientNonce = _readNonce(attrs, "scepRecipientNonce");
476
+ // A CertRep MUST echo the request's senderNonce in a recipientNonce (RFC 8894 sec. 3.1), so a
477
+ // response missing it cannot be correlated to its request and is refused regardless of whether the
478
+ // caller supplied expectedSenderNonce.
479
+ if (out.recipientNonce == null) throw _err("scep/missing-attribute", "a CertRep is missing its recipientNonce attribute (RFC 8894 sec. 3.2.1.5)");
480
+ if (out.pkiStatus === "FAILURE") {
481
+ var failCode = _readStr(attrs, "scepFailInfo", _T_PRINTABLE);
482
+ if (failCode == null) throw _err("scep/missing-attribute", "a FAILURE CertRep is missing its failInfo attribute (RFC 8894 sec. 3.2.1.4)");
483
+ out.failInfo = FAIL_INFO_BY_CODE[failCode];
484
+ if (out.failInfo == null) throw _err("scep/bad-fail-info", "unknown failInfo " + JSON.stringify(failCode) + " (RFC 8894 sec. 3.2.1.4)");
485
+ out.failInfoText = _readStr(attrs, "scepFailInfoText", _T_UTF8);
486
+ } else if (_find(attrs, "scepFailInfo") != null || _find(attrs, "scepFailInfoText") != null) {
487
+ // failInfo and failInfoText are defined for a FAILURE response (RFC 8894 sec. 3.2.1.4): a SUCCESS
488
+ // or PENDING CertRep carrying them asserts a contradictory authenticated status and is refused.
489
+ throw _err("scep/unexpected-attribute", "a " + out.pkiStatus + " CertRep must not carry a failInfo or failInfoText attribute (RFC 8894 sec. 3.2.1.4)");
490
+ }
491
+ } else {
492
+ // A request (PKCSReq / RenewalReq) is an initial message: the response-only attributes pkiStatus,
493
+ // failInfo, failInfoText, and recipientNonce are defined for a CertRep and MUST NOT appear here
494
+ // (RFC 8894 sec. 3.2.1). A request carrying any of them is off-profile and refused.
495
+ if (_find(attrs, "scepPkiStatus") != null || _find(attrs, "scepFailInfo") != null ||
496
+ _find(attrs, "scepFailInfoText") != null || _find(attrs, "scepRecipientNonce") != null) {
497
+ throw _err("scep/unexpected-attribute", "a " + messageType + " request must not carry a CertRep response attribute, pkiStatus / failInfo / failInfoText / recipientNonce (RFC 8894 sec. 3.2.1)");
498
+ }
499
+ }
500
+ // A caller-stated expected senderNonce echo (RFC 8894 sec. 3.2.1.5): a message whose recipientNonce
501
+ // does not match the nonce we sent MUST be rejected.
502
+ if (expectedSenderNonce != null) {
503
+ if (out.recipientNonce == null || !guard.crypto.constantTimeEqual(out.recipientNonce, expectedSenderNonce)) {
504
+ throw _err("scep/nonce-mismatch", "the pkiMessage recipientNonce does not echo the sent senderNonce (RFC 8894 sec. 3.2.1.5)");
505
+ }
506
+ }
507
+ // The pkcsPKIEnvelope is carried by a request and a SUCCESS CertRep, and is OMITTED by a FAILURE or
508
+ // PENDING CertRep, whose payload is the status itself (RFC 8894 sec. 3.3.2.1). Decrypt only when the
509
+ // message is one that carries the envelope, so a non-SUCCESS CertRep's authenticated status is
510
+ // returned rather than turned into a decrypt failure over content that is not an EnvelopedData. The
511
+ // eContent is bound to the verified signature (cms.verify).
512
+ var carriesEnvelope = !(messageType === "CertRep" && (out.pkiStatus === "FAILURE" || out.pkiStatus === "PENDING"));
513
+ if (carriesEnvelope) {
514
+ // For a message that carries messageData, the pkcsPKIEnvelope is mandatory, MUST be an EnvelopedData,
515
+ // and MUST encrypt id-data (RFC 8894 sec. 3.2, sec. 3.2.2). This is checked structurally, before any
516
+ // recipient-key decryption, so an absent or off-profile envelope is never accepted as a valid
517
+ // message with a null messageData, whether or not a recipient key was supplied.
518
+ _assertValidEnvelope(v.eContent, messageType);
519
+ } else {
520
+ // A FAILURE or PENDING CertRep MUST omit the pkcsPKIEnvelope (RFC 8894 sec. 3.3.2): its payload is
521
+ // the status itself, so the SignedData carries no encapsulated content (cms.verify surfaces it as a
522
+ // null eContent). Any present eContent -- an attached OCTET STRING even a zero-length one -- is
523
+ // off-profile and refused, so attacker-supplied bytes are never accepted under a non-SUCCESS verdict.
524
+ if (v.eContent != null) {
525
+ throw _err("scep/unexpected-envelope", "a " + out.pkiStatus + " CertRep must omit the pkcsPKIEnvelope (RFC 8894 sec. 3.3.2), but it carries encapsulated content");
526
+ }
527
+ }
528
+ if (recipientKey != null && carriesEnvelope && v.eContent != null) {
529
+ var dec;
530
+ try { dec = await cmsDecrypt.decrypt(v.eContent, recipientKey); }
531
+ catch (e) {
532
+ if (e && e.isPkiError) throw _err("scep/decrypt-failed", "the pkcsPKIEnvelope could not be decrypted with the recipient key: " + e.message, e);
533
+ throw e;
534
+ }
535
+ out.messageData = dec.content;
536
+ // A SUCCESS CertRep's messageData MUST be a degenerate certs-only CMS SignedData carrying the
537
+ // issued certificate(s) (RFC 8894 sec. 3.3.2, sec. 3.4). Validate that structure through the strict
538
+ // CMS parser and surface the certificates, so a decrypted payload that is not a valid issuance
539
+ // cannot read as a successful enrollment. The certificates are raw, for the caller to path-validate.
540
+ if (messageType === "CertRep" && out.pkiStatus === "SUCCESS") {
541
+ var payload = _readIssuancePayload(dec.content);
542
+ out.certificates = payload.certificates;
543
+ out.crls = payload.crls;
544
+ } else if (messageType === "PKCSReq" || messageType === "RenewalReq") {
545
+ // A request's messageData MUST be a PKCS#10 CertificationRequest (RFC 8894 sec. 3.3.1). Validate
546
+ // the structure so a decrypted payload that is not one cannot read as a valid request; the raw
547
+ // bytes stay in messageData for the caller to verify the proof-of-possession.
548
+ try { schemaCsr.parse(dec.content); }
549
+ catch (e) { throw _err("scep/bad-request-payload", "a " + messageType + " messageData must be a PKCS#10 CertificationRequest (RFC 8894 sec. 3.3.1)", e); }
550
+ }
551
+ }
552
+ return out;
553
+ }
554
+ var _PARSE_KEYS = { recipientKey: 1, expectedSenderNonce: 1, signerCert: 1 };
555
+
556
+ module.exports = {
557
+ build: build,
558
+ parse: parse,
559
+ MESSAGE_TYPES: MESSAGE_TYPE,
560
+ PKI_STATUS: PKI_STATUS,
561
+ FAIL_INFO: FAIL_INFO,
562
+ };
package/lib/schema-cms.js CHANGED
@@ -1400,7 +1400,13 @@ function assertAttachedCiphertext(eci, E, code, label) {
1400
1400
  // `maxCerts` (optional) caps how many certificates / CRLs are validated + returned, BEFORE the per-element
1401
1401
  // X.509 / CRL parse -- so an untrusted source (an AIA caIssuers URL) cannot force tens of thousands of parses
1402
1402
  // with one in-cap-bytes bundle; the EST client passes no cap (a /cacerts chain is small and fully returned).
1403
- function parseCertsOnly(der, E, prefix, maxCerts) {
1403
+ // `requireCert` (default true) sets the profile floor: the RFC 5272 sec. 4.1 Simple PKI Response the
1404
+ // EST client and path builder read REQUIRES at least one certificate, so they pass nothing and get the
1405
+ // strict floor. The general RFC 8551 sec. 3.8 / RFC 5652 sec. 5.1 certificate-management message
1406
+ // permits "certificates and/or CRLs", so pki.cms.parseCertsOnly passes `requireCert: false` and a
1407
+ // CRL-only message is accepted; a message with neither is still refused.
1408
+ function parseCertsOnly(der, E, prefix, maxCerts, requireCert) {
1409
+ var needCert = requireCert !== false;
1404
1410
  var r;
1405
1411
  try { r = parse(der); }
1406
1412
  catch (e) { throw E(prefix + "/bad-response", "a certs-only response did not decode as CMS: " + ((e && e.message) || String(e)), e); }
@@ -1409,9 +1415,21 @@ function parseCertsOnly(der, E, prefix, maxCerts) {
1409
1415
  throw E(prefix + "/not-certs-only", "a certs-only Simple PKI Response must carry id-data with no eContent (RFC 5272 sec. 4.1)");
1410
1416
  }
1411
1417
  if (r.signerInfos.length !== 0) throw E(prefix + "/not-certs-only", "a certs-only Simple PKI Response must have empty signerInfos (RFC 5272 sec. 4.1)");
1412
- if (!r.certificates || r.certificates.length === 0) throw E(prefix + "/no-certificates", "a certs-only response must contain at least one certificate (RFC 5272 sec. 4.1)");
1413
- // Cap BEFORE the per-certificate X.509 parse: bound parse work by count, not only by the decoded byte size.
1414
- var certs = (maxCerts != null && r.certificates.length > maxCerts) ? r.certificates.slice(0, maxCerts) : r.certificates;
1418
+ // digestAlgorithms is NOT required to be empty: RFC 5652 sec. 5.1 permits any number of elements
1419
+ // (including algorithms no SignerInfo uses), so a valid EST /cacerts or AIA caIssuers bundle may
1420
+ // carry a non-empty set. The builder emits an empty one (the canonical form), but the reader
1421
+ // accepts a non-empty one rather than rejecting valid CMS.
1422
+ var allCerts = r.certificates; // parse always surfaces certificates and crls as arrays (empty when the field is absent)
1423
+ var allCrls = r.crls;
1424
+ if (needCert) {
1425
+ if (allCerts.length === 0) throw E(prefix + "/no-certificates", "a certs-only response must contain at least one certificate (RFC 5272 sec. 4.1)");
1426
+ } else if (allCerts.length === 0 && allCrls.length === 0) {
1427
+ throw E(prefix + "/no-certificates", "a certs-only message must contain at least one certificate or CRL (RFC 8551 sec. 3.8)");
1428
+ }
1429
+ // Cap BEFORE the per-element parse: bound parse work by count, not only by the decoded byte size. The
1430
+ // cap is on the COMBINED number of certificates and CRLs, so a bundle carrying both cannot force up to
1431
+ // 2*maxCerts parses: certificates are counted first and CRLs draw only from the remaining budget.
1432
+ var certs = (maxCerts != null && allCerts.length > maxCerts) ? allCerts.slice(0, maxCerts) : allCerts;
1415
1433
  for (var i = 0; i < certs.length; i++) {
1416
1434
  // A universal-SEQUENCE CertificateChoice must be a well-formed X.509 Certificate, not merely any SEQUENCE;
1417
1435
  // a tagged CertificateChoices alternative (attribute cert / other) is not a plain certificate.
@@ -1419,8 +1437,8 @@ function parseCertsOnly(der, E, prefix, maxCerts) {
1419
1437
  try { schemaX509.parse(certs[i].bytes); }
1420
1438
  catch (e) { throw E(prefix + "/bad-certificate", "a certs-only response carried a non-certificate in its certificates field (RFC 5272 sec. 4.1)", e); }
1421
1439
  }
1422
- var allCrls = r.crls || [];
1423
- var crls = (maxCerts != null && allCrls.length > maxCerts) ? allCrls.slice(0, maxCerts) : allCrls;
1440
+ var crlCap = maxCerts != null ? (maxCerts - certs.length) : null; // the budget certificates left for CRLs
1441
+ var crls = (crlCap != null && allCrls.length > crlCap) ? allCrls.slice(0, crlCap) : allCrls;
1424
1442
  for (var j = 0; j < crls.length; j++) {
1425
1443
  if (crls[j].tagClass !== "universal") throw E(prefix + "/bad-crl", "a certs-only response CRL must be a plain X.509 CertificateList, not a tagged otherRevInfo alternative (RFC 5652 sec. 10.2.1)");
1426
1444
  try { schemaCrl.parse(crls[j].bytes); }
package/lib/smime.js CHANGED
@@ -1266,4 +1266,35 @@ function _decodeCms(ent) {
1266
1266
 
1267
1267
  function _toBuf(v) { return Buffer.isBuffer(v) ? v : Buffer.from(v); }
1268
1268
 
1269
- module.exports = { sign: sign, verify: verify, encrypt: encrypt, decrypt: decrypt, compress: compress, decompress: decompress };
1269
+ var CERTS_ONLY_OPTS = { crls: 1 };
1270
+
1271
+ /**
1272
+ * @primitive pki.smime.buildCertsOnly
1273
+ * @signature pki.smime.buildCertsOnly(certs, opts?) -> Buffer
1274
+ * @since 0.6.3
1275
+ * @status stable
1276
+ * @spec RFC 8551, RFC 5652
1277
+ * @related pki.cms.certsOnly, pki.cms.parseCertsOnly, pki.smime.encrypt
1278
+ *
1279
+ * Wrap a certs-only certificate-management message (RFC 8551 sec. 3.8) in one S/MIME
1280
+ * `application/pkcs7-mime; smime-type=certs-only; name=smime.p7c` entity: the base64 body is the
1281
+ * `pki.cms.certsOnly` DER, with `Content-Disposition: attachment; filename=smime.p7c` (RFC 8551
1282
+ * sec. 3.2.1). `certs` and `opts.crls` are the certificate/CRL inputs `pki.cms.certsOnly` accepts, and
1283
+ * at least one certificate or CRL is required. A certs-only message carries no user content, so the
1284
+ * header-protection options of `pki.smime.encrypt` do not apply here.
1285
+ *
1286
+ * @opts crls A CRL or array of CRLs (DER Buffer or PEM string) to convey alongside the certificates.
1287
+ * @example
1288
+ * var pair = await pki.key.generate("Ed25519");
1289
+ * var leafDer = await pki.x509.sign({ subject: "Leaf", subjectPublicKey: await pki.key.export(pair.publicKey),
1290
+ * notBefore: new Date("2026-01-01T00:00:00Z"), notAfter: new Date("2036-01-01T00:00:00Z") }, { key: await pki.key.export(pair.privateKey) });
1291
+ * var p7c = pki.smime.buildCertsOnly([leafDer]);
1292
+ */
1293
+ function buildCertsOnly(certs, opts) {
1294
+ opts = opts || {};
1295
+ _knownOpts(opts, CERTS_ONLY_OPTS, "buildCertsOnly");
1296
+ var der = _toBuf(cms.certsOnly(certs, { crls: opts.crls }));
1297
+ return _capped(Buffer.concat([_pkcs7MimeHead("certs-only", "smime.p7c"), _base64Body(der), mime.CRLF]));
1298
+ }
1299
+
1300
+ module.exports = { sign: sign, verify: verify, encrypt: encrypt, decrypt: decrypt, compress: compress, decompress: decompress, buildCertsOnly: buildCertsOnly };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:1d7ac08a-caae-46f2-b074-9a7c370ea22f",
5
+ "serialNumber": "urn:uuid:85d92993-2810-4099-a38f-0556df923c66",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-08-30T12:52:47.496Z",
8
+ "timestamp": "2026-08-30T22:55:28.945Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/pki@0.6.1",
22
+ "bom-ref": "@blamejs/pki@0.6.3",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.1",
25
+ "version": "0.6.3",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
29
- "purl": "pkg:npm/%40blamejs/pki@0.6.1",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.3",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/pki@0.6.1",
57
+ "ref": "@blamejs/pki@0.6.3",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]