@blamejs/pki 0.6.17 → 0.6.20

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,36 @@ 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.20 — 2026-09-01
8
+
9
+ A vulnerable build-time dependency is refreshed; it is not part of the published package.
10
+
11
+ ### Security
12
+
13
+ - browserslist, a transitive development dependency of the fuzzing harness, is updated from 4.28.4 to 4.28.8, clearing GHSA-73wf-gq98-2v4g and GHSA-c83g-rgw3-j3cx (both High). browserslist is a build-time and test-time dependency and is not part of the published package.
14
+
15
+ ## v0.6.19 — 2026-09-01
16
+
17
+ pki.scep.build issues the CA-side CertRep response, so the toolkit produces the SCEP certification-authority reply the client enrollment verbs consume.
18
+
19
+ ### Added
20
+
21
+ - pki.scep.build({ messageType: "CertRep", pkiStatus, transactionId, recipientNonce, ... }) issues a SCEP CertRep response (RFC 8894 sec. 3.3.2). SUCCESS takes certificates (and/or crls, leaf identified by content since the CMS certificate SET is DER-ordered) plus the requester's recipient certificate and the CA signer; the issued certificates ride a certs-only SignedData inside a pkcsPKIEnvelope encrypted to the requester. FAILURE takes a failInfo (and optional failInfoText) and PENDING takes neither; both omit the pkcsPKIEnvelope and are signed detached. recipientNonce (echoing the request's senderNonce) and transactionId are required; a missing failInfo on a FAILURE, a SUCCESS without a certificate/CRL or recipient, an envelope field on a FAILURE or PENDING, or an unknown pkiStatus or failInfo is refused with a typed scep/bad-input.
22
+
23
+ ### Fixed
24
+
25
+ - An enumerated option whose value collides with an inherited Object.prototype property name, such as a pkiStatus, contentEncryptionAlgorithm, macAlgorithm, digestAlgorithm, PKCS#8 cipher, or ACME resource kind of "toString" or "constructor", is now refused with the verb's own typed bad-input error across pki.scep.build, pki.cms.encrypt, pki.cms.authenticate, pki.key.encrypt, pki.acme.validate, and pki.acme.assertTransition. Such a value previously resolved to the inherited method and the call surfaced an unrelated error, and pki.acme.validate accepted the kind and returned without checking any field.
26
+ - pki.scep.build now requires a primitive-string pkiStatus. A boxed String or an object that coerces to a status name is refused with scep/bad-input, instead of building a CertRep whose signed pkiStatus attribute claims SUCCESS while the pkcsPKIEnvelope that a SUCCESS response requires is absent.
27
+
28
+ ## v0.6.18 — 2026-09-01
29
+
30
+ pki.cms.encrypt and pki.cms.decrypt envelope to and open a composite ML-KEM recipient, extending the CMS KEMRecipientInfo arm to the hybrid post-quantum key-establishment algorithms.
31
+
32
+ ### Added
33
+
34
+ - pki.cms.encrypt accepts a recipient certificate carrying a composite ML-KEM public key (id-MLKEM768-* or id-MLKEM1024-*, twelve algorithms pairing ML-KEM-768/1024 with RSA-OAEP 2048/3072/4096, ECDH over P-256/P-384/P-521 and brainpoolP256r1/P384r1, X25519, or X448) and emits an id-ori-kem KEMRecipientInfo: the composite as the kem algorithm with absent parameters, the composite ciphertext, HKDF-SHA256 as the kdf, and AES-256 key wrap with a 32-octet key-encryption key (RFC 9629 / RFC 9936). The recipient certificate must assert the keyEncipherment key usage.
35
+ - pki.cms.decrypt opens a composite ML-KEM KEMRecipientInfo with the recipient's composite PKCS#8 key, recovering the content-encryption key through the same KDF and unwrap. A wrong key, a tampered ciphertext, or a traditional-component decapsulation failure returns the uniform cms/decrypt-failed verdict, never a distinguishing error.
36
+
7
37
  ## v0.6.17 — 2026-09-01
8
38
 
9
39
  pki.scep.getCert and pki.scep.getCrl retrieve an already-issued certificate or a CA's CRL over SCEP, sending RFC 8894 GetCert and GetCRL queries and reading the result out of the CA's signed CertRep.
package/README.md CHANGED
@@ -222,7 +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 request: a `PKCSReq` or `RenewalReq` wraps a PKCS#10 certification request, whose own proof-of-possession it verifies first; a `CertPoll` wraps an IssuerAndSubject naming the issuing CA and the request subject; and a `GetCert` or `GetCRL` wraps an IssuerAndSerialNumber naming a certificate by its issuer and a positive serial of at most 20 octets. It encrypts the messageData 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`, `CertPoll`, `GetCert`, `GetCRL`, or `CertRep` back (a messageType outside the RFC 8894 registry is 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. `getCACaps(baseUrl, opts?)`, `getCACert(baseUrl, opts?)`, `getNextCACert(baseUrl, opts)`, `enroll(baseUrl, opts)`, `renew(baseUrl, opts)`, `getCert(baseUrl, opts)`, and `getCrl(baseUrl, opts)` carry that codec to a live CA over HTTP (RFC 8894 §4) through an injectable transport (`pki.transport.https` by default): `getCACaps` reports the CA's advertised capabilities and never lowers the client's algorithm choice on the unauthenticated response, `getCACert` pins the CA certificate to an out-of-band `expectedFingerprint` a returned certificate must match, `getNextCACert` fetches the CA's next (rollover) certificate and verifies the SignedData response against the current CA certificate (`caCertificate`) before returning it, refusing a response signed by any other key, and `enroll` and `renew` POST a PKCSReq or RenewalReq, authenticate the CertRep against the CA certificate and its nonce echo, select the issued certificate by public-key match, throw on a FAILURE with the CA's failInfo, and poll a PENDING response with CertPoll requests until the CA answers or a bounded poll-count and total-wait budget is spent. `getCert` and `getCrl` retrieve an already-issued certificate or a CA CRL by issuer and serial number, authenticated the same way; RFC 8894 §2.6, §2.7, and §3.3.4 recommend these queries only where HTTP certificate-store access (RFC 4387), LDAP, or a CRL distribution point is unavailable, so prefer those where a CA offers them. Issuing a CertRep (the certification-authority side) is not yet built — `build`, `parse`, `parseCapabilities`, `getCACaps`, `getCACert`, `getNextCACert`, `enroll`, `renew`, `getCert`, `getCrl` |
225
+ | `pki.scep` | SCEP pkiMessage codec (RFC 8894), the client side of Simple Certificate Enrollment. `build(spec)` assembles a request: a `PKCSReq` or `RenewalReq` wraps a PKCS#10 certification request, whose own proof-of-possession it verifies first; a `CertPoll` wraps an IssuerAndSubject naming the issuing CA and the request subject; and a `GetCert` or `GetCRL` wraps an IssuerAndSerialNumber naming a certificate by its issuer and a positive serial of at most 20 octets. It encrypts the messageData 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`. `build` also issues the CA-side `CertRep` response (§3.3.2): a SUCCESS envelopes a certs-only SignedData of the issued certificate (or the CRL for a GetCRL) to the requester and signs it under the CA key, while a FAILURE (carrying a `failInfo`) or a PENDING omits the pkcsPKIEnvelope and is signed detached, each echoing the request's senderNonce as `recipientNonce`. `parse(bytes, opts?)` reads a `PKCSReq`, `RenewalReq`, `CertPoll`, `GetCert`, `GetCRL`, or `CertRep` back (a messageType outside the RFC 8894 registry is 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. `getCACaps(baseUrl, opts?)`, `getCACert(baseUrl, opts?)`, `getNextCACert(baseUrl, opts)`, `enroll(baseUrl, opts)`, `renew(baseUrl, opts)`, `getCert(baseUrl, opts)`, and `getCrl(baseUrl, opts)` carry that codec to a live CA over HTTP (RFC 8894 §4) through an injectable transport (`pki.transport.https` by default): `getCACaps` reports the CA's advertised capabilities and never lowers the client's algorithm choice on the unauthenticated response, `getCACert` pins the CA certificate to an out-of-band `expectedFingerprint` a returned certificate must match, `getNextCACert` fetches the CA's next (rollover) certificate and verifies the SignedData response against the current CA certificate (`caCertificate`) before returning it, refusing a response signed by any other key, and `enroll` and `renew` POST a PKCSReq or RenewalReq, authenticate the CertRep against the CA certificate and its nonce echo, select the issued certificate by public-key match, throw on a FAILURE with the CA's failInfo, and poll a PENDING response with CertPoll requests until the CA answers or a bounded poll-count and total-wait budget is spent. `getCert` and `getCrl` retrieve an already-issued certificate or a CA CRL by issuer and serial number, authenticated the same way; RFC 8894 §2.6, §2.7, and §3.3.4 recommend these queries only where HTTP certificate-store access (RFC 4387), LDAP, or a CRL distribution point is unavailable, so prefer those where a CA offers them. GET-carried PKIOperation and HTTP proxy authentication are not yet built — `build`, `parse`, `parseCapabilities`, `getCACaps`, `getCACert`, `getNextCACert`, `enroll`, `renew`, `getCert`, `getCrl` |
226
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` |
227
227
  | `pki.jose` | Flattened JWS (RFC 7515) and JWK thumbprints (RFC 7638). `sign` and `verify` run a Flattened JWS against declarative profiles (ACME outer, EAB inner, keyChange inner) that carry the required and forbidden header rules as data. `base64url` is the strict RFC 4648 §5 codec, rejecting padding, non-alphabet characters, and non-canonical trailing bits. `parseJson` is a bounded reader that refuses duplicate members at any depth. `thumbprint` is the RFC 7638 / 8037 / 9964 canonical digest. The algorithm registry binds each `alg` to its key type (ES/RS/PS/EdDSA/ML-DSA), leaving no code path for `alg:none`, an RS256→HS256 key confusion, or an all-zero ECDSA signature; `assertPublicJwk` refuses a JWK carrying private material, so an exported private key is never published. `opts.key` names the key a message must be signed under and governs: where the profile also permits an embedded header `jwk`, the two must be the same key — compared as RFC 7638 thumbprints, so member order cannot make equal keys differ — and a disagreement is refused rather than resolved in the message's favor. `keySource` reports which key answered, since a signature checked against a key you named is a different claim from one checked against the key the message carried — `sign`, `verify`, `base64url`, `parseJson`, `thumbprint`, `assertPublicJwk` |
228
228
  | `pki.acme` | ACME (RFC 8555 / 8737 / 8738 / 9773). `client(directoryUrl, opts)` is a stateful client driving a live CA directory over `pki.transport`: `newAccount`, `newOrder`, `newAuthz`, `getOrder`, `getAuthorization`, `getChallenge`, `respondToChallenge`, `finalize`, `pollOrder`, `pollAuthorization`, and `downloadCertificate` walk the issuance flow, with `newAuthz` pre-authorizing a single identifier (§7.4.1) and `downloadCertificate` binding the issued certificate to the order — its key, its identifiers, or both; at least one is required by default and the result reports `boundToKey` / `boundToIdentifiers` — before choosing among alternate chains (`Link rel="alternate"`, §7.4.2, via a `selectChain` predicate bounded by `maxAlternates`). `revokeCert` (account-key or certificate-key signed), `keyChange`, `updateAccount` (change the account contacts, §7.3.2), `listOrders` (the account's orders list, following the §7.1.2.1 `Link rel="next"` pagination bounded by a page cap and confined to the orders origin), `deactivateAccount`, `deactivateAuthorization`, `renewalInfo` (ARI), 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 (and, when `opts.resignKeys` supplies caller-approved alternative account-key algorithms, a bounded RFC 8555 §6.2 badSignatureAlgorithm re-sign that the CA's advertised list can only filter, never widen, so it cannot force a weaker algorithm), reads are POST-as-GET, polling is bounded and sleeps on a Retry-After via an injectable sleeper capped by a poll count and a total-wait budget, and every response body is size-capped. The transport is injectable via `opts.transport`. Over the message layer it composes resource-object validators (closed status enums, conditional-required fields, unknown fields ignored), the three §7.1.6 state machines, the request builders (newAccount with External Account Binding, newOrder with `replaces`, finalize with a CSR identifier-set match and account-key-reuse rejection, challenge responses, deactivation, revokeCert in both key modes, the keyChange nested JWS, POST-as-GET), the http-01 / dns-01 / tls-alpn-01 challenge computations, the dns and ip identifier validators, and the ARI certID with serial sign-padding preserved — `client`, `validate`, `identify`, `assertTransition`, the builders, `keyAuthorization`, `http01`, `dns01`, `tlsAlpn01Extension`, `verifyTlsAlpn01`, `ariCertId` |
@@ -239,7 +239,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
239
239
  | `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the issuer key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
240
240
  | `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
241
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` |
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` |
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 (and composite ML-KEM, draft-lamps-pq-composite-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
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` |
244
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` |
245
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` |
package/index.js CHANGED
@@ -160,7 +160,7 @@ module.exports = {
160
160
  // `kem` is composite ML-KEM key establishment (draft-ietf-lamps-pq-composite-kem):
161
161
  // pki.kem.encapsulate / decapsulate over a post-quantum ML-KEM hybridized with a
162
162
  // traditional RSA-OAEP / ECDH / X25519 / X448, mixed through the SHA3-256 combiner.
163
- kem: compositeKem,
163
+ kem: { encapsulate: compositeKem.encapsulate, decapsulate: compositeKem.decapsulate },
164
164
  // `sigstore` verifies a Sigstore bundle (the npm --provenance artifact): a
165
165
  // keyless Fulcio signature over a DSSE-wrapped in-toto SLSA attestation with a
166
166
  // Rekor inclusion proof -- offline, zero-dep, against caller-pinned trust.
package/lib/acme.js CHANGED
@@ -223,7 +223,7 @@ var STATUS = {
223
223
  challenge: ["pending", "processing", "valid", "invalid"],
224
224
  };
225
225
 
226
- var SPECS = {
226
+ var SPECS = intrinsic.assign(intrinsic.create(null), {
227
227
  directory: [
228
228
  { name: "newNonce", type: "url", required: true },
229
229
  { name: "newAccount", type: "url", required: true },
@@ -275,7 +275,7 @@ var SPECS = {
275
275
  ordersList: [
276
276
  { name: "orders", type: "array", required: true, elemType: "url" },
277
277
  ],
278
- };
278
+ });
279
279
 
280
280
  function _checkType(kind, field, value, obj) {
281
281
  switch (field.type) {
@@ -408,11 +408,11 @@ function _canonicalizeIpv6(value) {
408
408
  }
409
409
 
410
410
 
411
- var TRANSITIONS = {
411
+ var TRANSITIONS = intrinsic.assign(intrinsic.create(null), {
412
412
  challenge: { pending: ["processing", "valid", "invalid"], processing: ["processing", "valid", "invalid"] },
413
413
  authorization: { pending: ["valid", "invalid", "deactivated"], valid: ["expired", "deactivated", "revoked"] },
414
414
  order: { pending: ["ready", "invalid"], ready: ["processing", "valid", "invalid"], processing: ["valid", "invalid"] },
415
- };
415
+ });
416
416
 
417
417
  /**
418
418
  * @primitive pki.acme.assertTransition
@@ -434,7 +434,7 @@ function assertTransition(kind, from, to) {
434
434
  var table = TRANSITIONS[kind];
435
435
  if (!table) throw E("acme/bad-input", "unknown resource kind " + JSON.stringify(kind));
436
436
  if (from === to) return;
437
- var allowed = table[from];
437
+ var allowed = _hasOwn(table, from) ? table[from] : null;
438
438
  if (!allowed || allowed.indexOf(to) === -1) throw E("acme/bad-transition", "illegal " + kind + " transition " + JSON.stringify(from) + " -> " + JSON.stringify(to) + " (RFC 8555 sec. 7.1.6)");
439
439
  }
440
440
 
@@ -817,7 +817,7 @@ function newAccount(o) {
817
817
  });
818
818
  }
819
819
 
820
- var _HMAC_HASH = { HS256: "SHA-256", HS384: "SHA-384", HS512: "SHA-512" };
820
+ var _HMAC_HASH = intrinsic.assign(intrinsic.create(null), { HS256: "SHA-256", HS384: "SHA-384", HS512: "SHA-512" });
821
821
 
822
822
  /**
823
823
  * @primitive pki.acme.externalAccountBinding
@@ -15,6 +15,7 @@ var frameworkError = require("./framework-error");
15
15
  var guard = require("./guard-all");
16
16
  var intrinsic = require("./guard-intrinsic");
17
17
  var pbes2 = require("./pbes2");
18
+ var compositeKem = require("./composite-kem");
18
19
  var C = require("./constants");
19
20
  var b = asn1.build;
20
21
  var subtle = webcrypto.webcrypto.subtle;
@@ -268,8 +269,9 @@ async function _pwriCek(ri, km, opts) {
268
269
 
269
270
  async function _kemriCek(ri, km) {
270
271
  var k = ri.kemri;
271
- var wcName = _mlkemName(k.kem.oid);
272
- if (!wcName) throw _err("cms/unsupported-algorithm", "unsupported KEM " + k.kem.oid);
272
+ var isComposite = compositeKem.isCompositeKem(k.kem.oid);
273
+ var wcName = isComposite ? null : _mlkemName(k.kem.oid);
274
+ if (!isComposite && !wcName) throw _err("cms/unsupported-algorithm", "unsupported KEM " + k.kem.oid);
273
275
  if (k.kdf.oid !== O("hkdfWithSha256")) throw _err("cms/unsupported-algorithm", "unsupported KEM key-derivation " + k.kdf.oid);
274
276
  var wantCt = KEM_CT_LENGTHS[k.kem.oid];
275
277
  var kemct = k.kemct;
@@ -277,14 +279,22 @@ async function _kemriCek(ri, km) {
277
279
  var kekBytes = Number(k.kekLength);
278
280
  var wrapAlg = k.wrap;
279
281
  if (WRAP_KEK_LENGTHS[wrapAlg.oid] !== kekBytes) throw _fail();
280
- var keyCopy = _normKeyDer(km.key);
281
- var priv;
282
- try { priv = await subtle.importKey("pkcs8", keyCopy.der, { name: wcName }, false, ["decapsulateBits"]); }
283
- finally { _releaseKeyDer(keyCopy); }
284
282
  var ss = null, kek = null, ssAb = null, kekAb = null;
285
283
  try {
286
- ssAb = await subtle.decapsulateBits({ name: wcName }, priv, kemct);
287
- ss = Buffer.from(ssAb);
284
+ if (isComposite) {
285
+ var ckey = _normKeyDer(km.key);
286
+ try {
287
+ if (pkcs8.parse(ckey.der).privateKeyAlgorithm.oid !== k.kem.oid) throw _fail();
288
+ ss = await compositeKem.decapsulate(ckey.der, kemct);
289
+ } finally { _releaseKeyDer(ckey); }
290
+ } else {
291
+ var keyCopy = _normKeyDer(km.key);
292
+ var priv;
293
+ try { priv = await subtle.importKey("pkcs8", keyCopy.der, { name: wcName }, false, ["decapsulateBits"]); }
294
+ finally { _releaseKeyDer(keyCopy); }
295
+ ssAb = await subtle.decapsulateBits({ name: wcName }, priv, kemct);
296
+ ss = Buffer.from(ssAb);
297
+ }
288
298
  var ssKey = await subtle.importKey("raw", ss, { name: "HKDF" }, false, ["deriveBits"]);
289
299
  kekAb = await subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: Buffer.alloc(0), info: _kemOtherInfo(wrapAlg.name, kekBytes, k.ukm || null) }, ssKey, kekBytes * 8);
290
300
  kek = Buffer.from(kekAb);
@@ -15,6 +15,7 @@ var frameworkError = require("./framework-error");
15
15
  var guard = require("./guard-all");
16
16
  var intrinsic = require("./guard-intrinsic");
17
17
  var pbes2 = require("./pbes2");
18
+ var compositeKem = require("./composite-kem");
18
19
  var b = asn1.build;
19
20
  var subtle = webcrypto.webcrypto.subtle;
20
21
  var pkix = require("./schema-pkix");
@@ -33,14 +34,14 @@ function _normCertDer(cert, what) {
33
34
  throw _err("cms/bad-input", (what || "a certificate") + " must be a DER Buffer, Uint8Array, or PEM string");
34
35
  }
35
36
 
36
- var CONTENT_ALGS = {
37
+ var CONTENT_ALGS = intrinsic.assign(intrinsic.create(null), {
37
38
  "aes-128-gcm": { oid: "aes128-GCM", keyBits: 128, aead: true },
38
39
  "aes-192-gcm": { oid: "aes192-GCM", keyBits: 192, aead: true },
39
40
  "aes-256-gcm": { oid: "aes256-GCM", keyBits: 256, aead: true },
40
41
  "aes-128-cbc": { oid: "aes128-CBC", keyBits: 128, aead: false },
41
42
  "aes-192-cbc": { oid: "aes192-CBC", keyBits: 192, aead: false },
42
43
  "aes-256-cbc": { oid: "aes256-CBC", keyBits: 256, aead: false },
43
- };
44
+ });
44
45
 
45
46
  function _wrapOidForKek(keyBytes) {
46
47
  if (keyBytes === 16) return "aes128-wrap";
@@ -82,7 +83,7 @@ function _assertKeyUsage(cert, bitName, arm) {
82
83
  if (ku && ku[bitName] !== true) throw _err("cms/bad-key-usage", "the " + arm + " recipient certificate's keyUsage does not assert " + bitName);
83
84
  }
84
85
 
85
- var OAEP_HASH = { sha256: "SHA-256", sha384: "SHA-384", sha512: "SHA-512" };
86
+ var OAEP_HASH = intrinsic.assign(intrinsic.create(null), { sha256: "SHA-256", sha384: "SHA-384", sha512: "SHA-512" });
86
87
  function _oaepParams(hashName) {
87
88
  var hAlg = _algId(hashName, "null");
88
89
  var mgf = b.sequence([b.oid(O("mgf1")), hAlg]);
@@ -212,17 +213,26 @@ function _kemOtherInfo(wrapName, kekBytes, ukm) {
212
213
  if (ukm) kids.push(b.explicit(0, b.octetString(ukm)));
213
214
  return b.sequence(kids);
214
215
  }
216
+ async function _kemEncapsulate(keyOid, cert) {
217
+ if (KEM_WC[keyOid]) {
218
+ var pub = await subtle.importKey("spki", cert.subjectPublicKeyInfo.bytes, { name: KEM_WC[keyOid] }, false, ["encapsulateBits"]);
219
+ var kem = await subtle.encapsulateBits({ name: KEM_WC[keyOid] }, pub);
220
+ return { ss: Buffer.from(kem.sharedKey), kemct: Buffer.from(kem.ciphertext), wrapName: KEM_WRAP[keyOid], raw: kem.sharedKey };
221
+ }
222
+ if (compositeKem.isCompositeKem(keyOid)) {
223
+ var out = await compositeKem.encapsulate(cert.subjectPublicKeyInfo.bytes);
224
+ return { ss: out.sharedSecret, kemct: out.ciphertext, wrapName: "aes256-wrap", raw: null };
225
+ }
226
+ throw _err("cms/unsupported-algorithm", "unsupported KEM recipient key algorithm");
227
+ }
215
228
  async function _buildKemri(cek, cert, opts) {
216
229
  _assertKeyUsage(cert, "keyEncipherment", "kemri");
217
230
  var keyOid = cert.subjectPublicKeyInfo.algorithm.oid;
218
- var wcName = KEM_WC[keyOid];
219
- if (!wcName) throw _err("cms/unsupported-algorithm", "unsupported KEM recipient key algorithm");
220
- var wrapName = KEM_WRAP[keyOid];
221
- var kekBytes = WRAP_KEK_LENGTHS[O(wrapName)];
222
231
  var ukm = opts.ukm ? guard.bytes.view(opts.ukm, CmsError, "cms/bad-input", "ukm") : null;
223
- var pub = await subtle.importKey("spki", cert.subjectPublicKeyInfo.bytes, { name: wcName }, false, ["encapsulateBits"]);
224
- var kem = await subtle.encapsulateBits({ name: wcName }, pub);
225
- var ss = Buffer.from(kem.sharedKey), kemct = Buffer.from(kem.ciphertext);
232
+ var enc = await _kemEncapsulate(keyOid, cert);
233
+ var wrapName = enc.wrapName;
234
+ var kekBytes = WRAP_KEK_LENGTHS[O(wrapName)];
235
+ var ss = enc.ss, kemct = enc.kemct;
226
236
  var kek = null, kekAb = null;
227
237
  try {
228
238
  var ssKey = await subtle.importKey("raw", ss, { name: "HKDF" }, false, ["deriveBits"]);
@@ -236,7 +246,7 @@ async function _buildKemri(cek, cert, opts) {
236
246
  var kemri = b.sequence(kemriKids);
237
247
  return { tag: 4, node: b.sequence([b.oid(O("kem")), kemri]) };
238
248
  } finally {
239
- guard.secret.zeroizeAll([ss, kek, kem.sharedKey ? new Uint8Array(kem.sharedKey) : null, kekAb ? new Uint8Array(kekAb) : null],
249
+ guard.secret.zeroizeAll([ss, kek, enc.raw ? new Uint8Array(enc.raw) : null, kekAb ? new Uint8Array(kekAb) : null],
240
250
  CmsError, "cms/bad-input", "the KEM shared secret");
241
251
  }
242
252
  }
@@ -272,7 +282,7 @@ function _pwriWrapIv(kek, cek, iv) {
272
282
  }
273
283
  }
274
284
 
275
- var PRF_HASH = { hmacWithSHA1: "SHA-1", hmacWithSHA256: "SHA-256", hmacWithSHA384: "SHA-384", hmacWithSHA512: "SHA-512" };
285
+ var PRF_HASH = intrinsic.assign(intrinsic.create(null), { hmacWithSHA1: "SHA-1", hmacWithSHA256: "SHA-256", hmacWithSHA384: "SHA-384", hmacWithSHA512: "SHA-512" });
276
286
  function _prfHash(prf) { if (!PRF_HASH[prf]) throw _err("cms/bad-input", "unsupported pwri prf " + JSON.stringify(prf)); return PRF_HASH[prf]; }
277
287
 
278
288
  var _PWRI_KEYS = { password: 1, iterations: 1, prf: 1, salt: 1 };
@@ -316,7 +326,7 @@ async function _buildRecipient(cek, desc, opts, consumed) {
316
326
  _assertRecipientKeys(desc, _AGREE_RECIPIENT_KEYS, "key-agreement certificate");
317
327
  return _buildKari(cek, cert, mergeOpts(opts, desc, _AGREE_RECIPIENT_KEYS, consumed));
318
328
  }
319
- if (KEM_WC[keyOid]) {
329
+ if (KEM_WC[keyOid] || compositeKem.isCompositeKem(keyOid)) {
320
330
  _assertRecipientKeys(desc, _AGREE_RECIPIENT_KEYS, "KEM certificate");
321
331
  return _buildKemri(cek, cert, mergeOpts(opts, desc, _AGREE_RECIPIENT_KEYS, consumed));
322
332
  }
@@ -547,13 +557,13 @@ function _tlvHeaderLen(der) {
547
557
  }
548
558
 
549
559
 
550
- var MAC_ALGS = {
560
+ var MAC_ALGS = intrinsic.assign(intrinsic.create(null), {
551
561
  "hmac-sha256": { oid: "hmacWithSHA256", wc: "SHA-256", node: "sha256" },
552
562
  "hmac-sha384": { oid: "hmacWithSHA384", wc: "SHA-384", node: "sha384" },
553
563
  "hmac-sha512": { oid: "hmacWithSHA512", wc: "SHA-512", node: "sha512" },
554
- };
564
+ });
555
565
  var MAC_KEY_OCTETS = 32;
556
- var SUPPORTED_DIGEST = { sha256: 1, sha384: 1, sha512: 1 };
566
+ var SUPPORTED_DIGEST = intrinsic.assign(intrinsic.create(null), { sha256: 1, sha384: 1, sha512: 1 });
557
567
 
558
568
  async function authenticate(content, recipients, opts) {
559
569
  opts = opts || {};
package/lib/cms-verify.js CHANGED
@@ -787,7 +787,9 @@ var countersign = cmsSign.countersign;
787
787
  * recipient certificate's public-key algorithm -- RSA yields a ktri with RSAES-OAEP-SHA256 (PKCS#1
788
788
  * v1.5 is never emitted); EC P-256/384/521 a kari with ephemeral-static ECDH and the X9.63 KDF;
789
789
  * X25519/X448 a kari per RFC 8418 (HKDF); ML-KEM-512/768/1024 an ori/KEMRecipientInfo per RFC
790
- * 9629 + 9936. `{ password }` yields a pwri (PBKDF2 + RFC 3211 PWRI-KEK); `{ kek, kekId }` a kekri
790
+ * 9629 + 9936; a composite ML-KEM (id-MLKEM768-* / id-MLKEM1024-*, draft-lamps-pq-composite-kem) the
791
+ * same ori/KEMRecipientInfo with the composite as the kem algorithm and AES-256-Wrap. `{ password }`
792
+ * yields a pwri (PBKDF2 + RFC 3211 PWRI-KEK); `{ kek, kekId }` a kekri
791
793
  * (AES key wrap). For EncryptedData (no RecipientInfos), pass a single non-array `{ cek }` or
792
794
  * `{ password }` descriptor. The default AES-256-GCM content encryption produces an
793
795
  * authenticated AuthEnvelopedData; a CBC choice produces an unauthenticated EnvelopedData.
@@ -829,7 +831,7 @@ var encrypt = cmsEncrypt.encrypt;
829
831
  * authenticated but not encrypted, the authenticated-only sibling of AuthEnvelopedData. A single
830
832
  * fresh MAC key is minted and wrapped for every recipient with the same RecipientInfo model
831
833
  * `pki.cms.encrypt` uses for a content-encryption key, so `recipients` is the identical array of
832
- * descriptors: `{ cert }` (RSA -> ktri RSAES-OAEP, EC/X25519/X448 -> kari, ML-KEM -> ori/KEMRI),
834
+ * descriptors: `{ cert }` (RSA -> ktri RSAES-OAEP, EC/X25519/X448 -> kari, ML-KEM or composite ML-KEM -> ori/KEMRI),
833
835
  * `{ password }` (pwri), or `{ kek, kekId }` (kekri). By default the MAC covers the authenticated
834
836
  * attributes (a content-type and a message-digest = digest of the content) re-tagged to the EXPLICIT
835
837
  * SET OF (RFC 5652 sec. 9.2); with `authenticatedAttributes: false` (id-data content only) it covers
@@ -870,7 +872,7 @@ var authenticate = cmsEncrypt.authenticate;
870
872
  * Decrypt a CMS EnvelopedData / AuthEnvelopedData / EncryptedData, or verify a CMS AuthenticatedData
871
873
  * (DER Buffer or PEM). It selects the recipient the key material targets, acquires the
872
874
  * content-encryption or MAC key through the matching arm (ktri OAEP or PKCS#1 v1.5 decrypt-only; kari
873
- * ECDH / X25519 / X448; kekri; pwri; ori/ML-KEM), and decrypts (or MAC-verifies) the content.
875
+ * ECDH / X25519 / X448; kekri; pwri; ori/ML-KEM or composite ML-KEM), and decrypts (or MAC-verifies) the content.
874
876
  * `keyMaterial` is `{ key, cert }` (the recipient private key + its certificate, which drives recipient
875
877
  * matching), `{ password }`, `{ kek, kekId? }`, or `{ cek }` (EncryptedData raw-key mode). Fail-closed
876
878
  * and oracle-free: every secret-dependent failure collapses to the SINGLE uniform
@@ -307,7 +307,10 @@ async function _encapsulate(publicKey) {
307
307
  return { sharedSecret: ss, ciphertext: Buffer.concat([r[0].ct, r[1].ct]) };
308
308
  }
309
309
 
310
+ function _isCompositeKem(algOid) { return COMPOSITE_KEM[algOid] != null; }
311
+
310
312
  module.exports = {
311
313
  encapsulate: _encapsulate,
312
314
  decapsulate: _decapsulate,
315
+ isCompositeKem: _isCompositeKem,
313
316
  };
package/lib/key.js CHANGED
@@ -36,7 +36,7 @@ var PemError = frameworkError.PemError;
36
36
  function O(n) { return oid.byName(n); }
37
37
  function _err(code, msg, cause) { return new KeyError(code, msg, cause); }
38
38
 
39
- var CIPHER_NAME = { "aes-128-cbc": "aes128-CBC", "aes-192-cbc": "aes192-CBC", "aes-256-cbc": "aes256-CBC" };
39
+ var CIPHER_NAME = Object.assign(Object.create(null), { "aes-128-cbc": "aes128-CBC", "aes-192-cbc": "aes192-CBC", "aes-256-cbc": "aes256-CBC" });
40
40
 
41
41
  var INFER_ALG = {};
42
42
  ["Ed25519", "Ed448", "X25519", "X448"].forEach(function (n) { INFER_ALG[O(n)] = { name: n }; });
package/lib/scep.js CHANGED
@@ -16,8 +16,8 @@
16
16
  * outer SignedData that signs it under a set of authenticated transaction
17
17
  * attributes -- messageType, transactionID, pkiStatus, failInfo, and the
18
18
  * sender/recipient nonces (RFC 8894 sec. 3). `pki.scep.build` assembles a
19
- * request pkiMessage (PKCSReq, RenewalReq, CertPoll, GetCert, or GetCRL);
20
- * `pki.scep.parse` verifies the
19
+ * request pkiMessage (PKCSReq, RenewalReq, CertPoll, GetCert, or GetCRL) or a
20
+ * CA-side CertRep response; `pki.scep.parse` verifies the
21
21
  * outer signature, reads the transaction attributes BOUND to the verified
22
22
  * signer, and (given the recipient key) decrypts the pkcsPKIEnvelope to the
23
23
  * messageData.
@@ -29,10 +29,10 @@
29
29
  * pki.transport separately.
30
30
  *
31
31
  * @card
32
- * Build and read SCEP (RFC 8894) client messages: a PKCSReq, RenewalReq,
33
- * CertPoll, GetCert, or GetCRL request wrapped in the signed-over-encrypted CMS
34
- * layering, and any of those or a CertRep parsed back to its verified transaction
35
- * attributes and decrypted messageData.
32
+ * Build and read SCEP (RFC 8894) messages: a PKCSReq, RenewalReq, CertPoll,
33
+ * GetCert, or GetCRL request, or a CA-side CertRep response, wrapped in the
34
+ * signed-over-encrypted CMS layering, and any of them parsed back to its verified
35
+ * transaction attributes and decrypted messageData.
36
36
  */
37
37
 
38
38
  var frameworkError = require("./framework-error");
@@ -63,14 +63,14 @@ function _err(code, msg, cause) { return new ScepError(code, msg, cause); }
63
63
 
64
64
  var _KU_NS = pkix.makeNS("scep", ScepError, oid);
65
65
 
66
- var MESSAGE_TYPE = { CertRep: "3", RenewalReq: "17", PKCSReq: "19", CertPoll: "20", GetCert: "21", GetCRL: "22" };
67
- var PKI_STATUS = { SUCCESS: "0", FAILURE: "2", PENDING: "3" };
68
- var FAIL_INFO = { badAlg: "0", badMessageCheck: "1", badRequest: "2", badTime: "3", badCertId: "4" };
66
+ var MESSAGE_TYPE = Object.assign(Object.create(null), { CertRep: "3", RenewalReq: "17", PKCSReq: "19", CertPoll: "20", GetCert: "21", GetCRL: "22" });
67
+ var PKI_STATUS = Object.assign(Object.create(null), { SUCCESS: "0", FAILURE: "2", PENDING: "3" });
68
+ var FAIL_INFO = Object.assign(Object.create(null), { badAlg: "0", badMessageCheck: "1", badRequest: "2", badTime: "3", badCertId: "4" });
69
69
 
70
70
  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; }
71
71
  var MESSAGE_TYPE_BY_CODE = _invert(MESSAGE_TYPE), PKI_STATUS_BY_CODE = _invert(PKI_STATUS), FAIL_INFO_BY_CODE = _invert(FAIL_INFO);
72
72
 
73
- var _PARSE_SUPPORTED = { PKCSReq: 1, RenewalReq: 1, CertRep: 1, CertPoll: 1, GetCert: 1, GetCRL: 1 };
73
+ var _PARSE_SUPPORTED = Object.assign(Object.create(null), { PKCSReq: 1, RenewalReq: 1, CertRep: 1, CertPoll: 1, GetCert: 1, GetCRL: 1 });
74
74
 
75
75
  var ENVELOPE_CIPHER = "aes-128-cbc";
76
76
 
@@ -225,16 +225,26 @@ function _captureRecipientKey(rk) {
225
225
  * CA-issued certificate instead, which is why this is the caller's choice rather than an enforced
226
226
  * match. The proof-of-possession over the PKCS#10 itself is verified regardless.
227
227
  *
228
+ * A `CertRep` response is the CA (responder) side: it carries the transaction `pkiStatus`, echoes the
229
+ * request's senderNonce as `recipientNonce`, and is signed under the CA's `signer`. A SUCCESS response
230
+ * envelopes a certs-only SignedData of the issued `certificates` (or the `crls` of a GetCRL response) to
231
+ * the requester's `recipient` certificate; a FAILURE (which carries a `failInfo`) or a PENDING response
232
+ * omits the pkcsPKIEnvelope and is signed detached (RFC 8894 sec. 3.3.2).
233
+ *
228
234
  * @opts
229
- * - `messageType` -- "PKCSReq" | "RenewalReq" | "CertPoll" | "GetCert" | "GetCRL".
235
+ * - `messageType` -- "PKCSReq" | "RenewalReq" | "CertPoll" | "GetCert" | "GetCRL" | "CertRep".
230
236
  * - `messageData` -- the PKCS#10 CertificationRequest DER, for a PKCSReq or RenewalReq.
231
237
  * - `requestSubject` -- the request subject Name DER, for a CertPoll.
232
238
  * - `certificate` -- for a GetCert or GetCRL, the certificate DER whose issuer and serial name the target (the convenience form).
233
239
  * - `issuer` / `serialNumber` -- for a GetCert or GetCRL, the issuer Name DER and a positive serial (a BigInt, number, or hex string) naming the target directly. For a CertPoll, `issuer` alone names the issuing CA (defaulting to the recipient's subject) when the request is encrypted to a separate RA.
234
- * - `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).
235
- * - `signer` -- `{ cert, key }`, the outer SignedData signer (the client for a request).
236
- * - `transactionId` -- a caller-unique PrintableString identifying the transaction.
240
+ * - `recipient` -- the certificate DER the pkcsPKIEnvelope is encrypted to (an RSA key-transport certificate; a non-RSA recipient is refused, since the envelope uses RSAES-OAEP): the CA or RA certificate for a request, the requester's certificate for a SUCCESS CertRep.
241
+ * - `signer` -- `{ cert, key }`, the outer SignedData signer (the client for a request, the CA for a CertRep).
242
+ * - `transactionId` -- a caller-unique PrintableString identifying the transaction (echoes the request's on a CertRep).
237
243
  * - `senderNonce` -- a 16-byte Buffer (generated when omitted).
244
+ * - `pkiStatus` -- for a CertRep, "SUCCESS" | "FAILURE" | "PENDING".
245
+ * - `recipientNonce` -- for a CertRep, the 16-byte value echoing the request's senderNonce (required).
246
+ * - `certificates` / `crls` -- for a SUCCESS CertRep, arrays of the issued certificate DER (or CRL DER) the certs-only SignedData carries.
247
+ * - `failInfo` / `failInfoText` -- for a FAILURE CertRep, the failInfo (badAlg / badMessageCheck / badRequest / badTime / badCertId) and an optional detail string.
238
248
  * @example
239
249
  * // requires: csrDer -- the PKCS#10 CertificationRequest DER to enrol
240
250
  * // requires: caCertDer -- the SCEP CA (or RA) certificate the request is encrypted to (keyEncipherment)
@@ -246,11 +256,15 @@ function _captureRecipientKey(rk) {
246
256
  */
247
257
  async function build(spec) {
248
258
  spec = guard.identifier.optionsObject(spec, _err, "scep/bad-input", "pki.scep.build spec");
249
- guard.identifier.assertKnownKeys(spec, _BUILD_KEYS, _err, "scep/bad-input", "pki.scep.build has an unknown option: ");
250
259
  var mtCode = MESSAGE_TYPE[spec.messageType];
251
260
  if (mtCode == null) throw _err("scep/bad-message-type", "unknown messageType " + JSON.stringify(spec.messageType) + " (RFC 8894 sec. 3.2.1.2)");
261
+ if (spec.messageType === "CertRep") {
262
+ guard.identifier.assertKnownKeys(spec, _CERTREP_KEYS, _err, "scep/bad-input", "pki.scep.build (CertRep) has an unknown option: ");
263
+ return await _buildCertRep(spec);
264
+ }
265
+ guard.identifier.assertKnownKeys(spec, _REQUEST_KEYS, _err, "scep/bad-input", "pki.scep.build has an unknown option: ");
252
266
  if (spec.messageType !== "PKCSReq" && spec.messageType !== "RenewalReq" && spec.messageType !== "CertPoll" && spec.messageType !== "GetCert" && spec.messageType !== "GetCRL") {
253
- throw _err("scep/bad-message-type", "pki.scep.build issues a request (PKCSReq / RenewalReq / CertPoll / GetCert / GetCRL); " + spec.messageType + " is not built in this release");
267
+ throw _err("scep/bad-message-type", "pki.scep.build issues a request (PKCSReq / RenewalReq / CertPoll / GetCert / GetCRL) or a CertRep response; " + spec.messageType + " is not built in this release");
254
268
  }
255
269
  if (spec.signer == null || typeof spec.signer !== "object") throw _err("scep/bad-input", "a signer { cert, key } is required");
256
270
  var senderNonce = _nonce(spec.senderNonce, "senderNonce");
@@ -293,7 +307,69 @@ async function build(spec) {
293
307
  throw e;
294
308
  }
295
309
  }
296
- var _BUILD_KEYS = { messageType: 1, messageData: 1, recipient: 1, requestSubject: 1, issuer: 1, certificate: 1, serialNumber: 1, signer: 1, transactionId: 1, senderNonce: 1 };
310
+ var _REQUEST_KEYS = { messageType: 1, messageData: 1, recipient: 1, requestSubject: 1, issuer: 1, certificate: 1, serialNumber: 1, signer: 1, transactionId: 1, senderNonce: 1 };
311
+ var _CERTREP_KEYS = { messageType: 1, signer: 1, transactionId: 1, senderNonce: 1, pkiStatus: 1, recipientNonce: 1, certificates: 1, crls: 1, recipient: 1, failInfo: 1, failInfoText: 1 };
312
+
313
+ async function _buildCertRep(spec) {
314
+ if (spec.signer == null || typeof spec.signer !== "object") throw _err("scep/bad-input", "a signer { cert, key } is required");
315
+ if (typeof spec.pkiStatus !== "string") throw _err("scep/bad-input", "a CertRep pkiStatus must be SUCCESS, FAILURE, or PENDING (RFC 8894 sec. 3.2.1.3), got " + JSON.stringify(spec.pkiStatus));
316
+ var statusCode = PKI_STATUS[spec.pkiStatus];
317
+ if (statusCode == null) throw _err("scep/bad-input", "a CertRep pkiStatus must be SUCCESS, FAILURE, or PENDING (RFC 8894 sec. 3.2.1.3), got " + JSON.stringify(spec.pkiStatus));
318
+ var txnId = _transactionId(spec.transactionId);
319
+ if (spec.recipientNonce == null) throw _err("scep/bad-input", "a CertRep must echo the request's senderNonce as recipientNonce (RFC 8894 sec. 3.2.1.5)");
320
+ var recipientNonce = _nonce(spec.recipientNonce, "recipientNonce");
321
+ var senderNonce = _nonce(spec.senderNonce, "senderNonce");
322
+ var signerCert = guard.bytes.snapshotSource(spec.signer.cert, ScepError, "scep/bad-input", "signer.cert");
323
+ var signerKey = spec.signer.key;
324
+ _assertSigningKeyUsage(signerCert, "signer certificate");
325
+ var attrs = [
326
+ _attr("scepMessageType", b.printable(MESSAGE_TYPE.CertRep)),
327
+ _attr("scepTransactionId", b.printable(txnId)),
328
+ _attr("scepSenderNonce", b.octetString(senderNonce)),
329
+ _attr("scepPkiStatus", b.printable(statusCode)),
330
+ _attr("scepRecipientNonce", b.octetString(recipientNonce)),
331
+ ];
332
+ if (spec.pkiStatus !== "FAILURE" && (spec.failInfo != null || spec.failInfoText != null)) {
333
+ throw _err("scep/bad-input", "failInfo and failInfoText are only valid on a FAILURE CertRep (RFC 8894 sec. 3.2.1.4)");
334
+ }
335
+ var content = null;
336
+ if (spec.pkiStatus === "SUCCESS") {
337
+ var certs = spec.certificates != null ? spec.certificates : [];
338
+ var crls = spec.crls != null ? spec.crls : [];
339
+ if (!Array.isArray(certs) || !Array.isArray(crls)) throw _err("scep/bad-input", "a CertRep certificates and crls must be arrays of certificate / CRL DER");
340
+ if (certs.length === 0 && crls.length === 0) throw _err("scep/bad-input", "a SUCCESS CertRep must carry at least one certificate or CRL (RFC 8894 sec. 3.3.2.1)");
341
+ if (spec.recipient == null) throw _err("scep/bad-input", "a SUCCESS CertRep needs a recipient certificate to encrypt the pkcsPKIEnvelope to (RFC 8894 sec. 3.2.2)");
342
+ var recipient = guard.bytes.snapshotSource(spec.recipient, ScepError, "scep/bad-input", "recipient");
343
+ _assertRsaRecipient(recipient);
344
+ var certsOnlyDer;
345
+ try { certsOnlyDer = cmsSign.certsOnly(certs, { crls: crls }); }
346
+ catch (e) { throw _err("scep/bad-input", "a SUCCESS CertRep certificates / crls must be valid certificate / CRL DER (RFC 8894 sec. 3.4): " + e.message, e); }
347
+ try { content = await cmsEncrypt.encrypt(certsOnlyDer, [{ cert: recipient }], { contentEncryptionAlgorithm: ENVELOPE_CIPHER }); }
348
+ catch (e) {
349
+ if (e && e.isPkiError) throw _err("scep/bad-input", "the SUCCESS CertRep pkcsPKIEnvelope could not be built (the recipient must be a keyEncipherment certificate): " + e.message, e);
350
+ throw e;
351
+ }
352
+ } else {
353
+ if (spec.certificates != null || spec.crls != null || spec.recipient != null) {
354
+ throw _err("scep/bad-input", "a " + spec.pkiStatus + " CertRep must omit certificates, crls, and recipient: the pkcsPKIEnvelope is omitted (RFC 8894 sec. 3.3.2." + (spec.pkiStatus === "FAILURE" ? "2" : "3") + ")");
355
+ }
356
+ if (spec.pkiStatus === "FAILURE") {
357
+ var failCode = FAIL_INFO[spec.failInfo];
358
+ if (failCode == null) throw _err("scep/bad-input", "a FAILURE CertRep must carry a failInfo of badAlg / badMessageCheck / badRequest / badTime / badCertId (RFC 8894 sec. 3.2.1.4), got " + JSON.stringify(spec.failInfo));
359
+ attrs.push(_attr("scepFailInfo", b.printable(failCode)));
360
+ if (spec.failInfoText != null) attrs.push(_attr("scepFailInfoText", b.utf8(String(spec.failInfoText))));
361
+ }
362
+ }
363
+ var signOpts = { additionalSignedAttributes: attrs };
364
+ var signContent = content;
365
+ if (content == null) { signContent = Buffer.alloc(0); signOpts.detached = true; }
366
+ try {
367
+ return await cmsSign.sign(signContent, { cert: signerCert, key: signerKey }, signOpts);
368
+ } catch (e) {
369
+ if (e && e.isPkiError) throw _err("scep/bad-input", "the CertRep could not be signed: " + e.message, e);
370
+ throw e;
371
+ }
372
+ }
297
373
 
298
374
  function _buildIssuerAndSubject(recipientCertDer, requestSubjectSource, issuerOverride) {
299
375
  var subject = guard.bytes.snapshotSource(requestSubjectSource, ScepError, "scep/bad-input", "requestSubject");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.17",
3
+ "version": "0.6.20",
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:ea4426a6-da57-4694-9766-3f651e6423ae",
5
+ "serialNumber": "urn:uuid:40b50089-a128-40ea-a5a2-b82960272544",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-01T14:08:00.688Z",
8
+ "timestamp": "2026-09-01T19:36:06.284Z",
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.17",
22
+ "bom-ref": "@blamejs/pki@0.6.20",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.17",
25
+ "version": "0.6.20",
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.17",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.20",
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.17",
57
+ "ref": "@blamejs/pki@0.6.20",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]