@blamejs/pki 0.5.36 → 0.5.38

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,22 @@ All notable changes to `@blamejs/pki` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## v0.5.38 — 2026-08-30
8
+
9
+ Builder verbs reject a sparse or nullish array argument with a typed error instead of a native one.
10
+
11
+ ### Changed
12
+
13
+ - The array arguments of pki.pkcs12.build (SafeContents bags), pki.ocsp.buildRequest and pki.ocsp.sign (the query and response batches), pki.cmc.build (requests and the CMS and other-message sequences), pki.crl.sign (revoked entries and the issuing-distribution-point and freshest-CRL general names), pki.crmf.build (controls and registration info), and pki.cms.encrypt (authenticated attributes) are checked for holes and nullish entries up front. A sparse or nullish array is now the verb's own typed `<domain>/bad-input` error naming the index, in place of the native `TypeError` the hole previously produced at the encoder. A valid (dense) array is unaffected and its emitted structure is byte-for-byte identical.
14
+
15
+ ## v0.5.37 — 2026-08-29
16
+
17
+ pki.cms.decrypt can return the recovered content as an async iterable of plaintext chunks.
18
+
19
+ ### Added
20
+
21
+ - `pki.cms.decrypt(input, keyMaterial, opts)` accepts `opts.stream: true`, returning the verdict's `content` as an async iterable of plaintext `Buffer` chunks instead of a single `Buffer`. It applies to EnvelopedData, AuthEnvelopedData, EncryptedData (the `{ cek }` and `{ password }` forms), and AuthenticatedData. The integrity-checked modes verify before the first chunk is yielded, so a forged message fails before any plaintext is exposed; the unauthenticated CBC modes stream the plaintext as the cipher produces it, so a large payload is never buffered whole. Every failure remains the single uniform `cms/decrypt-failed` verdict, on the streamed path as on the buffered one.
22
+
7
23
  ## v0.5.36 — 2026-08-29
8
24
 
9
25
  pki.cms.encrypt accepts an async-iterable plaintext, encrypting a large payload without holding it whole in memory.
package/README.md CHANGED
@@ -237,7 +237,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
237
237
  | `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the issuer key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
238
238
  | `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
239
239
  | `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
240
- | `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. 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` |
240
+ | `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` |
241
241
  | `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
242
  | `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` |
243
243
  | `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. Transport-free — `buildRequest`, `sign`, `buildErrorResponse`, `verify` |
package/lib/cmc-build.js CHANGED
@@ -27,6 +27,7 @@
27
27
 
28
28
  var nodeCrypto = require("node:crypto");
29
29
  var asn1 = require("./asn1-der");
30
+ var pkiBuild = require("./pki-build"); // reqDenseArray: reject a sparse/nullish caller array as a typed cmc/bad-input
30
31
  var csr = require("./schema-csr"); // to read the Subject Key Identifier a tcr request declares
31
32
  var crmf = require("./schema-crmf"); // ... and the one a crm request declares
32
33
  var cmcFmt = require("./schema-cmc"); // to read the assembled message back before signing it
@@ -510,7 +511,9 @@ function _build(spec, signer, opts) {
510
511
  // them has no replay defense, and pki.cmc.verify cannot enforce a binding the
511
512
  // client never sent, so the omission is invisible from both ends.
512
513
  guard.identifier.assertKnownKeys(spec, KNOWN_SPEC_KEYS, E, "cmc/bad-input", "unknown spec field ");
513
- var requests = spec.requests || [];
514
+ // Density up front: requests is iterated by both the forEach below and the map that encodes it, and a
515
+ // hole would survive either (map/forEach skip it) to reach b.sequence as a native error.
516
+ var requests = spec.requests != null ? pkiBuild.reqDenseArray(spec.requests, "requests", E, "cmc/bad-input") : [];
514
517
  if (!Array.isArray(requests)) throw E("cmc/bad-input", "spec.requests must be an array");
515
518
  var callerControls = spec.controls || [];
516
519
  if (!Array.isArray(callerControls)) throw E("cmc/bad-input", "spec.controls must be an array");
@@ -532,10 +535,10 @@ function _build(spec, signer, opts) {
532
535
  var fixed = fixedRequestId(r, i);
533
536
  if (fixed != null) ids.reserve(fixed, "request " + i);
534
537
  });
535
- var cmsSequence = (spec.cmsSequence || []).map(function (el, i) {
538
+ var cmsSequence = (spec.cmsSequence != null ? pkiBuild.reqDenseArray(spec.cmsSequence, "cmsSequence", E, "cmc/bad-input") : []).map(function (el, i) {
536
539
  return _claimRawElement(el, ids, "a cmsSequence element (index " + i + ")");
537
540
  });
538
- var otherMsgSequence = (spec.otherMsgSequence || []).map(function (el, i) {
541
+ var otherMsgSequence = (spec.otherMsgSequence != null ? pkiBuild.reqDenseArray(spec.otherMsgSequence, "otherMsgSequence", E, "cmc/bad-input") : []).map(function (el, i) {
539
542
  return _claimRawElement(el, ids, "an otherMsgSequence element (index " + i + ")");
540
543
  });
541
544
 
@@ -25,6 +25,7 @@ var frameworkError = require("./framework-error");
25
25
  var guard = require("./guard-all");
26
26
  var intrinsic = require("./guard-intrinsic");
27
27
  var pbes2 = require("./pbes2");
28
+ var C = require("./constants");
28
29
  var b = asn1.build;
29
30
  var subtle = webcrypto.webcrypto.subtle;
30
31
  var CmsError = frameworkError.CmsError;
@@ -105,7 +106,11 @@ async function decryptEnvelopedData(parsed, keyMaterial, opts, contentTypeName)
105
106
  // needs, so an earlier wipe would break decryption instead of protecting it. The returned object
106
107
  // is built before the `finally` runs and holds the plaintext, not the key.
107
108
  try {
108
- var content = await _openContent(parsed, eci, cek, ct); // stage 3 (uniform)
109
+ // Lazy CBC streaming (the memory win) is safe only with one candidate; several ambiguous
110
+ // candidates need the content decrypt to run eagerly so a wrong recipient is rejected and the
111
+ // next tried, exactly as the buffered path disambiguates.
112
+ var streamMode = opts.stream === true ? (candidates.length > 1 ? "eager" : "lazy") : null;
113
+ var content = await _openContent(parsed, eci, cek, ct, streamMode); // stage 3 (uniform)
109
114
  return _originFields({
110
115
  content: content,
111
116
  contentType: eci.contentType, contentTypeName: oid.name(eci.contentType) || eci.contentType,
@@ -427,7 +432,7 @@ function _assertContentCipherMode(eci, ct) {
427
432
  }
428
433
 
429
434
  // ---- stage 3: open the content (uniform failure) ---------------------------
430
- async function _openContent(parsed, eci, cek, ct) {
435
+ async function _openContent(parsed, eci, cek, ct, streamMode) {
431
436
  var alg = eci.contentEncryptionAlgorithm;
432
437
  var keyBits = intrinsic.hasOwn(CONTENT_KEYBITS, alg.oid) ? CONTENT_KEYBITS[alg.oid] : 0;
433
438
  if (!keyBits) {
@@ -455,10 +460,24 @@ async function _openContent(parsed, eci, cek, ct) {
455
460
  try {
456
461
  if (ct === "authEnvelopedData") {
457
462
  var aad = parsed.authAttrsBytes != null ? _explicitSetOf(parsed.authAttrsBytes) : Buffer.alloc(0);
458
- return _gcmOpen(cek, parsed.aead.nonce, eci.encryptedContent, parsed.mac, aad, keyBits, parsed.aead.icvLen);
463
+ // GCM authenticates before it yields: the tag is verified here, so a forged message throws
464
+ // cms/decrypt-failed now and the streamed form never yields a chunk of unverified plaintext
465
+ // (RFC 5083 sec. 1). The stream is therefore a chunker over the already-verified plaintext -- no
466
+ // memory win for GCM, which is the correct trade for the integrity guarantee.
467
+ var pt = _gcmOpen(cek, parsed.aead.nonce, eci.encryptedContent, parsed.mac, aad, keyBits, parsed.aead.icvLen);
468
+ return streamMode ? _bufferChunks(pt) : pt;
459
469
  }
460
470
  var iv = asn1.read.octetString(asn1.decode(alg.parameters));
461
471
  if (iv.length !== 16) throw _fail();
472
+ // A lazy CBC stream defers the padding check to iteration. The ambiguous-candidate loop cannot use a
473
+ // deferred check to reject a wrong recipient and try the next, so lazy streaming is used ONLY when a
474
+ // single candidate remains (a wrong key then has nothing to fall back to, so its uniform failure at
475
+ // iteration is the right verdict). "lazy" is the real memory win: the whole plaintext is never held,
476
+ // and the caller opted into receiving chunks before the final() padding check. With several ambiguous
477
+ // candidates the decrypt runs eagerly HERE -- it IS the disambiguator -- and the validated plaintext
478
+ // is then chunked, so the fallback the buffered path relies on is preserved.
479
+ if (streamMode === "lazy") return _cbcStream(cek, iv, eci.encryptedContent, keyBits);
480
+ if (streamMode === "eager") return _bufferChunks(pbes2.cbcDecrypt(cek, iv, eci.encryptedContent, keyBits, CmsError, "cms/decrypt-failed"));
462
481
  return pbes2.cbcDecrypt(cek, iv, eci.encryptedContent, keyBits, CmsError, "cms/decrypt-failed");
463
482
  } catch (e) {
464
483
  if (e instanceof CmsError && e.code !== "cms/decrypt-failed") throw e;
@@ -480,6 +499,30 @@ function _gcmOpen(cek, nonce, ct, tag, aad, keyBits, icvLen) {
480
499
  return guard.secret.cipherFinish(d, ct, CmsError, "cms/decrypt-failed", "the recovered content");
481
500
  }
482
501
 
502
+ // ---- streaming content (opts.stream): `content` becomes an async iterable of plaintext chunks -------
503
+ // The already-verified GCM plaintext, yielded a chunk at a time so the streamed and buffered forms have
504
+ // the same `content` shape. GCM holds the whole plaintext (it was verified before this ran), so this is
505
+ // a chunker, not a memory win -- the win is CBC's, below.
506
+ async function* _bufferChunks(buf) {
507
+ var chunk = C.BYTES.kib(64);
508
+ for (var off = 0; off < buf.length; off += chunk) {
509
+ var end = off + chunk;
510
+ yield intrinsic.subarray(buf, off, end < buf.length ? end : buf.length);
511
+ }
512
+ }
513
+ // The CBC streaming content. The engine decipher is created EAGERLY (subtle.decryptStream copies the key
514
+ // at creation), so the caller's post-open `cek` zeroize does not disturb it; the drive is lazy. A wrong
515
+ // key or bad padding surfaces at the engine's final() as an untyped throw, which this collapses to the
516
+ // uniform cms/decrypt-failed -- the same verdict the buffered path returns, so the stream never leaks a
517
+ // distinct failure reason. `await`, not `.then`: the drive dispatches through no caller-replaceable method.
518
+ function _cbcStream(key, iv, ct, keyBits) {
519
+ return _translateCbcStream(subtle.decryptStream({ algNode: "aes-" + keyBits + "-cbc", key: key, iv: iv }, ct));
520
+ }
521
+ async function* _translateCbcStream(engineIter) {
522
+ try { for await (var chunk of engineIter) yield chunk; }
523
+ catch (_e) { throw _fail(); }
524
+ }
525
+
483
526
  // ---- EncryptedData (sec. 8) ------------------------------------------------
484
527
  async function _decryptEncryptedData(parsed, km, opts) {
485
528
  var eci = parsed.encryptedContentInfo;
@@ -492,7 +535,7 @@ async function _decryptEncryptedData(parsed, km, opts) {
492
535
  var cek = guard.bytes.view(km.cek, CmsError, "cms/bad-input", "cek");
493
536
  if (cek.length !== keyBits / 8) throw _err("cms/bad-input", "the supplied cek length does not match the content algorithm");
494
537
  var iv = asn1.read.octetString(asn1.decode(alg.parameters));
495
- try { return _originFields({ content: pbes2.cbcDecrypt(cek, iv, eci.encryptedContent, keyBits, CmsError, "cms/decrypt-failed"), contentType: eci.contentType, contentTypeName: oid.name(eci.contentType) || eci.contentType, recipientType: "cek", recipientIndex: -1, contentEncryptionAlgorithm: alg.name || alg.oid, authenticated: false }, null, null); }
538
+ try { return _originFields({ content: opts.stream === true ? _cbcStream(cek, iv, eci.encryptedContent, keyBits) : pbes2.cbcDecrypt(cek, iv, eci.encryptedContent, keyBits, CmsError, "cms/decrypt-failed"), contentType: eci.contentType, contentTypeName: oid.name(eci.contentType) || eci.contentType, recipientType: "cek", recipientIndex: -1, contentEncryptionAlgorithm: alg.name || alg.oid, authenticated: false }, null, null); }
496
539
  catch (_e) { throw _fail(); }
497
540
  }
498
541
  async function _decryptPbes2(parsed, eci, km, opts) {
@@ -524,7 +567,7 @@ async function _decryptPbes2(parsed, eci, km, opts) {
524
567
  var key;
525
568
  try { key = nodeCrypto.pbkdf2Sync(pwE.bytes, pb.salt, pb.iterations, keyBits / 8, pb.prfNode); }
526
569
  finally { if (pwE.owned) guard.secret.zeroize(pwE.bytes, CmsError, "cms/bad-input", "the password encoding"); }
527
- try { return _originFields({ content: pbes2.cbcDecrypt(key, iv, eci.encryptedContent, keyBits, CmsError, "cms/decrypt-failed"), contentType: eci.contentType, contentTypeName: oid.name(eci.contentType) || eci.contentType, recipientType: "password", recipientIndex: -1, contentEncryptionAlgorithm: oid.name(encOid) || encOid, authenticated: false }, null, null); }
570
+ try { return _originFields({ content: opts.stream === true ? _cbcStream(key, iv, eci.encryptedContent, keyBits) : pbes2.cbcDecrypt(key, iv, eci.encryptedContent, keyBits, CmsError, "cms/decrypt-failed"), contentType: eci.contentType, contentTypeName: oid.name(eci.contentType) || eci.contentType, recipientType: "password", recipientIndex: -1, contentEncryptionAlgorithm: oid.name(encOid) || encOid, authenticated: false }, null, null); }
528
571
  catch (_e) { throw _fail(); }
529
572
  finally { guard.secret.zeroize(key, CmsError, "cms/bad-input", "the password-derived content-encryption key"); }
530
573
  }
@@ -741,8 +784,11 @@ async function _verifyAuthenticatedData(parsed, km, opts) {
741
784
  var actual = Buffer.from(await subtle.digest(mdCheck.hash, content));
742
785
  if (!actual.equals(mdCheck.declared)) throw _fail(); // sec. 9.3: recompute, never trust the originator's digest
743
786
  }
787
+ // Like GCM, the MAC is verified above before anything is yielded, so the stream is a chunker
788
+ // over the already-authenticated plaintext (uniform `content` shape, no memory win).
789
+ var authedContent = Buffer.from(content);
744
790
  return _originFields({
745
- content: Buffer.from(content),
791
+ content: opts.stream === true ? _bufferChunks(authedContent) : authedContent,
746
792
  contentType: parsed.encapContentInfo.eContentType, contentTypeName: oid.name(parsed.encapContentInfo.eContentType) || parsed.encapContentInfo.eContentType,
747
793
  recipientType: candidates[ci].ri.type, recipientIndex: candidates[ci].index,
748
794
  macAlgorithm: macAlg.name || macAlg.oid,
@@ -17,6 +17,7 @@
17
17
 
18
18
  var nodeCrypto = require("crypto");
19
19
  var asn1 = require("./asn1-der");
20
+ var pkiBuild = require("./pki-build"); // reqDenseArray: reject a sparse/nullish caller array as a typed cms/bad-input
20
21
  var oid = require("./oid");
21
22
  var x509 = require("./schema-x509");
22
23
  var schemaCms = require("./schema-cms");
@@ -589,8 +590,14 @@ async function _envelopedData(contentBytes, contentStream, cek, ca, contentType,
589
590
  // design (RFC 5652 sec. 9.2), while for AuthEnvelopedData that value is the unencrypted hash of a
590
591
  // plaintext the message exists to conceal (RFC 5083 sec. 2.1 / sec. 5).
591
592
  function _assertAuthAttrs(pairs, forbidden) {
593
+ // Reject a sparse/nullish attribute array as a typed error before b.setOf reaches it as a native one.
594
+ // This gate runs before the setOf on both the AuthEnveloped and AuthenticatedData paths.
595
+ // Validate AND SNAPSHOT: reqDenseArray returns a fresh dense copy, and it is that copy the caller must
596
+ // iterate and encode. Iterating the original `pairs` would let an indexed getter that sparsified it
597
+ // during validation slip a hole into b.setOf as a native error; the returned snapshot cannot.
598
+ var dense = pkiBuild.reqDenseArray(pairs, "authAttrs", _err, "cms/bad-input");
592
599
  var seenTypes = {};
593
- pairs.forEach(function (p) {
600
+ dense.forEach(function (p) {
594
601
  var node;
595
602
  try { node = asn1.decode(p); } catch (e) { throw _err("cms/bad-input", "an authenticated attribute is not well-formed DER", e); }
596
603
  if (node.tagClass !== "universal" || node.tagNumber !== asn1.TAGS.SEQUENCE || !node.children || node.children.length !== 2 ||
@@ -604,6 +611,7 @@ function _assertAuthAttrs(pairs, forbidden) {
604
611
  seenTypes[t] = 1;
605
612
  if (forbidden && t === forbidden.oid) throw _err("cms/bad-input", forbidden.why);
606
613
  });
614
+ return dense;
607
615
  }
608
616
 
609
617
  // The one attribute AuthEnvelopedData declines to emit. Its value is the unencrypted one-way hash of
@@ -623,9 +631,9 @@ async function _authEnvelopedData(contentBytes, contentStream, cek, ca, contentT
623
631
  throw _err("cms/bad-input", "AuthEnvelopedData with a non-data contentType requires authAttrs (RFC 5083 sec. 2.1)");
624
632
  }
625
633
  if (opts.authAttrs && opts.authAttrs.length) {
626
- _assertAuthAttrs(opts.authAttrs, AUTH_ENVELOPED_FORBIDDEN);
634
+ var denseAttrs = _assertAuthAttrs(opts.authAttrs, AUTH_ENVELOPED_FORBIDDEN);
627
635
  // authAttrs are transmitted [1] IMPLICIT but MACed under the EXPLICIT SET OF tag (RFC 5083 sec. 2.2).
628
- var setOf = b.setOf(opts.authAttrs);
636
+ var setOf = b.setOf(denseAttrs);
629
637
  aad = setOf; authAttrsDer = b.contextConstructed(1, setOf.subarray(_tlvHeaderLen(setOf)));
630
638
  }
631
639
  // A 16-octet (128-bit) GCM tag, the strongest ICV and what OpenSSL emits, so the message
@@ -799,7 +807,7 @@ async function authenticate(content, recipients, opts) {
799
807
  b.sequence([b.oid(O("messageDigest")), b.setOf([b.octetString(mdDigest)])]),
800
808
  ];
801
809
  if (opts.authAttrs && opts.authAttrs.length) pairs = pairs.concat(opts.authAttrs);
802
- _assertAuthAttrs(pairs, null);
810
+ pairs = _assertAuthAttrs(pairs, null);
803
811
  var setOf = b.setOf(pairs);
804
812
  preimage = setOf; // MAC over the 0x31 SET OF
805
813
  authAttrsDer = b.contextConstructed(2, setOf.subarray(_tlvHeaderLen(setOf))); // [2] IMPLICIT on the wire
package/lib/cms-verify.js CHANGED
@@ -1352,8 +1352,17 @@ var authenticate = cmsEncrypt.authenticate;
1352
1352
  * AEAD's authenticated data, so it is a hint, never evidence, and any certificate it carries must be
1353
1353
  * validated before use.
1354
1354
  *
1355
+ * With `stream: true` the result's `content` is an async iterable of plaintext `Buffer` chunks rather
1356
+ * than a single `Buffer`, for a payload too large to hold whole. An AuthEnvelopedData, an
1357
+ * AuthenticatedData, and the AEAD path verify integrity before the iterable yields, so a forged message
1358
+ * throws `cms/decrypt-failed` and no unverified plaintext is ever exposed. A CBC EnvelopedData or
1359
+ * EncryptedData carries no integrity, so it yields plaintext as the cipher produces it and a corrupt
1360
+ * message surfaces the same uniform `cms/decrypt-failed` on iteration, after earlier chunks reached the
1361
+ * caller who holds the key.
1362
+ *
1355
1363
  * @opts recipientIndex Explicitly select the recipient by index (overrides key-material matching).
1356
1364
  * @opts maxIterations Lower the PBKDF2 iteration cap (a DoS bound; downward only).
1365
+ * @opts stream Return `content` as an async iterable of plaintext `Buffer` chunks instead of a single `Buffer`.
1357
1366
  * @example
1358
1367
  * var rsa = { name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" };
1359
1368
  * var pair = await pki.key.generate(rsa);
package/lib/crl-sign.js CHANGED
@@ -203,7 +203,7 @@ function _idpValue(idp) {
203
203
  if (idp.onlyContainsAttributeCerts === true) throw _err("crl/bad-idp", "onlyContainsAttributeCerts=TRUE is not permitted for a conforming CRL issuer (RFC 5280 sec. 5.2.5)");
204
204
  var children = [];
205
205
  if (idp.fullName != null) {
206
- var entries = Array.isArray(idp.fullName) ? idp.fullName : [idp.fullName];
206
+ var entries = Array.isArray(idp.fullName) ? pkiBuild.reqDenseArray(idp.fullName, "issuingDistributionPoint.fullName", _err, "crl/bad-idp") : [idp.fullName];
207
207
  if (!entries.length) throw _err("crl/bad-idp", "issuingDistributionPoint fullName must carry at least one GeneralName");
208
208
  // distributionPoint [0] { fullName [0] IMPLICIT GeneralNames }
209
209
  children.push(b.contextConstructed(0, b.contextConstructed(0, Buffer.concat(entries.map(_encodeGeneralName)))));
@@ -243,11 +243,12 @@ function _validatePreEncodedIdp(inner) {
243
243
  // fullName) or an array of { fullName } distribution points.
244
244
  function _freshestValue(spec) {
245
245
  if (!Array.isArray(spec) || !spec.length) throw _err("crl/bad-input", "freshestCRL must be a non-empty array of GeneralNames (or { fullName } distribution points)");
246
- var dps = spec.every(function (e) { return e && typeof e === "object" && !Buffer.isBuffer(e) && Object.keys(e).length === 1 && e.fullName != null; })
247
- ? spec.map(function (dp) { return dp.fullName; })
248
- : [spec];
246
+ var dense = _b.reqDenseArray(spec, "freshestCRL"); // density before every()/map() skip a hole into b.sequence
247
+ var dps = dense.every(function (e) { return e && typeof e === "object" && !Buffer.isBuffer(e) && Object.keys(e).length === 1 && e.fullName != null; })
248
+ ? dense.map(function (dp) { return dp.fullName; })
249
+ : [dense];
249
250
  return b.sequence(dps.map(function (fullName) {
250
- var entries = Array.isArray(fullName) ? fullName : [fullName];
251
+ var entries = Array.isArray(fullName) ? _b.reqDenseArray(fullName, "a freshestCRL distribution point fullName") : [fullName];
251
252
  if (!entries.length) throw _err("crl/bad-input", "a freshestCRL distribution point must carry at least one GeneralName (GeneralNames is SIZE(1..MAX), RFC 5280 sec. 4.2.1.13)");
252
253
  return b.sequence([b.contextConstructed(0, b.contextConstructed(0, Buffer.concat(entries.map(_encodeGeneralName))))]);
253
254
  }));
@@ -345,7 +346,8 @@ function _buildCrlExtensions(spec, ctx) {
345
346
  function _buildRevoked(entryList, isDelta) {
346
347
  if (!Array.isArray(entryList)) throw _err("crl/bad-input", "revoked must be an array of revoked-certificate entries");
347
348
  var anyExt = false, seenSerials = {};
348
- var entries = entryList.map(function (e, idx) {
349
+ // Density before the map, which would otherwise skip a hole into b.sequence as a native error.
350
+ var entries = _b.reqDenseArray(entryList, "revoked").map(function (e, idx) {
349
351
  if (!e || typeof e !== "object" || Buffer.isBuffer(e)) throw _err("crl/bad-input", "each revoked entry must be an object");
350
352
  // Before any field of the entry is encoded, so an unrecognized name is a refusal rather than an
351
353
  // entry signed without what it asked for.
package/lib/crmf-sign.js CHANGED
@@ -148,7 +148,8 @@ function _buildAttrTypeAndValues(spec, code, label, valueMap) {
148
148
  if (Array.isArray(spec)) {
149
149
  if (!spec.length) throw _err(code, label + " must carry at least one entry");
150
150
  var seenA = {};
151
- return b.sequence(spec.map(function (e, i) {
151
+ // Density before the map, which would otherwise skip a hole into b.sequence as a native error.
152
+ return b.sequence(pkiBuild.reqDenseArray(spec, label, _err, code).map(function (e, i) {
152
153
  var der = _b.reqDer(e, label + " [" + i + "]");
153
154
  var n;
154
155
  try { n = asn1.decode(der); } catch (err) { throw _err("crmf/bad-input", "pre-encoded " + label + " [" + i + "] is not valid DER", err); }
package/lib/ocsp.js CHANGED
@@ -25,6 +25,7 @@
25
25
 
26
26
  var nodeCrypto = require("crypto");
27
27
  var asn1 = require("./asn1-der");
28
+ var pkiBuild = require("./pki-build"); // reqDenseArray: reject a sparse/nullish caller array as a typed ocsp/bad-input
28
29
  var oid = require("./oid");
29
30
  var x509 = require("./schema-x509");
30
31
  var ocspSchema = require("./schema-ocsp");
@@ -176,7 +177,9 @@ function _buildRequest(query, opts) {
176
177
  var lightweight = opts.profile === "lightweight";
177
178
  var hashName = opts.hashAlgorithm || "sha1";
178
179
  if (lightweight && hashName !== "sha1") throw _err("ocsp/bad-input", "the lightweight profile requires a SHA-1 CertID (RFC 5019 sec. 2.1.1)");
179
- var queries = Array.isArray(query) ? query : [query];
180
+ // A batch array is density-checked before the map below (which would otherwise skip a hole and reach
181
+ // Promise.all/b.sequence with an undefined); a single {cert,issuer} wraps to a dense one-element array.
182
+ var queries = Array.isArray(query) ? pkiBuild.reqDenseArray(query, "queries", _err, "ocsp/bad-input") : [query];
180
183
  if (!queries.length) throw _err("ocsp/bad-input", "buildRequest needs at least one { cert, issuer } query");
181
184
  if (lightweight && queries.length !== 1) throw _err("ocsp/bad-input", "the lightweight profile permits exactly one Request (RFC 5019 sec. 2.1.1)");
182
185
  if (opts.signer && !opts.requestorName) throw _err("ocsp/bad-input", "a signed OCSP request MUST carry requestorName (RFC 6960 sec. 4.1.2)");
@@ -335,7 +338,7 @@ function _sign(responseData, responder, opts) {
335
338
  // exit -- sync throw and async rejection alike -- rather than each fallible step needing to
336
339
  // remember. `responderKey` is the private copy; it is never the caller's object.
337
340
  function _signResponse(responseData, responder, respCert, respCertDer, responderKey, opts) {
338
- var responses = responseData.responses || [];
341
+ var responses = responseData.responses != null ? pkiBuild.reqDenseArray(responseData.responses, "responses", _err, "ocsp/bad-input") : [];
339
342
  if (!responses.length) throw _err("ocsp/bad-input", "a response MUST include at least one SingleResponse (RFC 6960 sec. 4.2.1)");
340
343
 
341
344
  return _responderID(responseData.responderID, respCert).then(function (ridNode) {
@@ -47,6 +47,7 @@ var cmsSign = require("./cms-sign"); // the signer-descriptor field tables, fo
47
47
  var cmsDecrypt = require("./cms-decrypt"); // the @internal decryptEnvelopedData seam -- opens a privacy safe off the pkcs12 parser's already-walked (BER-capable) EnvelopedData node
48
48
  var schemaPkcs12 = require("./schema-pkcs12");
49
49
  var pkix = require("./schema-pkix");
50
+ var pkiBuild = require("./pki-build"); // reqDenseArray: reject a sparse/nullish caller array as a typed pkcs12/bad-input
50
51
  var guard = require("./guard-all");
51
52
  var intrinsic = require("./guard-intrinsic");
52
53
  var frameworkError = require("./framework-error");
@@ -463,9 +464,13 @@ function _pbeOpts(enc) {
463
464
 
464
465
  // SafeContents ::= SEQUENCE OF SafeBag (ordered, and not a SET OF).
465
466
  function _buildSafeContents(bags, opts, depth) {
466
- if (!Array.isArray(bags)) throw _err("pkcs12/bad-input", "bags must be an array");
467
- if (bags.length > C.LIMITS.PKCS12_MAX_ELEMENTS) throw _err("pkcs12/bad-input", "a SafeContents exceeds the element cap " + C.LIMITS.PKCS12_MAX_ELEMENTS);
468
- return b.sequence(bags.map(function (bag) { return _buildBag(bag, opts, depth); }));
467
+ // The element cap is enforced BEFORE the density scan, so a huge dense array is rejected in O(1) rather
468
+ // than walked. reqDenseArray then rejects a non-array, or a sparse hole / nullish entry that
469
+ // Array.prototype.map would skip into Buffer.concat as a native error, testing own-property presence
470
+ // and failing at the first bad index.
471
+ if (intrinsic.isArray(bags) && bags.length > C.LIMITS.PKCS12_MAX_ELEMENTS) throw _err("pkcs12/bad-input", "a SafeContents exceeds the element cap " + C.LIMITS.PKCS12_MAX_ELEMENTS);
472
+ var dense = pkiBuild.reqDenseArray(bags, "bags", _err, "pkcs12/bad-input");
473
+ return b.sequence(dense.map(function (bag) { return _buildBag(bag, opts, depth); }));
469
474
  }
470
475
 
471
476
  // One AuthenticatedSafe element: a plaintext id-data ContentInfo, an id-encryptedData ContentInfo whose
package/lib/pki-build.js CHANGED
@@ -329,6 +329,34 @@ var KU_BIT = {
329
329
  dataEncipherment: 3, keyAgreement: 4, keyCertSign: 5, cRLSign: 6, encipherOnly: 7, decipherOnly: 8,
330
330
  };
331
331
 
332
+ // A caller-supplied array a builder is about to map over: reject a sparse hole or a nullish entry as a
333
+ // typed error. Array.prototype.map SKIPS a hole, which would otherwise reach Buffer.concat as a native
334
+ // ERR_INVALID_ARG_TYPE and, on a huge sparse length, traverse the empty slots. Tests OWN-property presence
335
+ // (intrinsic.hasOwn) at each index BEFORE reading it, so a polluted Array.prototype[i] cannot slip a hole
336
+ // past the check, and fails fast at the first bad index so the length alone can never force a walk. Takes
337
+ // the caller's error factory E (invoked E(fullCode, msg)) so a builder WITHOUT a makeBuilder instance
338
+ // routes its caller arrays through the same choke point; makeBuilder's own reqDenseArray delegates here.
339
+ function reqDenseArrayImpl(list, what, E, code) {
340
+ if (!_isArray(list)) throw E(code, what + " must be an array");
341
+ var n = list.length;
342
+ // Snapshot each own index into a FRESH dense array and return THAT, never `list`. Reading list[i] can
343
+ // fire a caller-defined indexed accessor that mutates `list` (extending it with holes past the captured
344
+ // n, or deleting an already-checked index); returning `list` would then hand the caller's map a
345
+ // newly-sparse array and the native error this guard exists to prevent. The copy captures the value as
346
+ // read, so a later mutation of `list` cannot reintroduce a hole into what the caller iterates.
347
+ var out = [];
348
+ for (var i = 0; i < n; i++) {
349
+ if (!intrinsic.hasOwn(list, i)) throw E(code, what + "[" + i + "] is missing (a sparse array is not allowed)");
350
+ var v = list[i];
351
+ if (v === undefined || v === null) throw E(code, what + "[" + i + "] is missing (a nullish array entry is not allowed)");
352
+ // defineProperty, not `out[i] = v`: a plain assignment invokes an inherited Array.prototype[i] SETTER
353
+ // ([[Set]]) if one is polluted in, which could leave `out` sparse; [[DefineOwnProperty]] always makes
354
+ // an own data property, so the snapshot is dense regardless of prototype pollution.
355
+ intrinsic.defineProperty(out, i, { value: v, writable: true, enumerable: true, configurable: true });
356
+ }
357
+ return out;
358
+ }
359
+
332
360
  // makeBuilder(ctx) -> the bound producing primitives. ctx = { ErrorClass, prefix, O, NS, NAME_SCHEMA,
333
361
  // SPKI_SCHEMA, EXT_DECODERS }. `E(kind, msg, cause)` builds a `<prefix>/<kind>` typed error.
334
362
  function makeBuilder(ctx) {
@@ -593,23 +621,9 @@ function makeBuilder(ctx) {
593
621
  if (guard.bytes.isByteSource(v)) return guard.bytes.snapshotSource(v, ErrorClass, ctx.prefix + "/bad-input", what);
594
622
  throw E("bad-input", what + " must be a DER Buffer");
595
623
  }
596
- // A caller-supplied array a builder is about to map over: reject a sparse hole or a nullish entry HERE
597
- // as a typed error. Array.prototype.map SKIPS a hole, which would otherwise reach Buffer.concat as a
598
- // native ERR_INVALID_ARG_TYPE and, on a huge sparse length, traverse the empty slots. Test OWN-property
599
- // presence at each index BEFORE reading it: a bare `list[i]` on a hole walks the prototype chain, so a
600
- // polluted `Array.prototype[i]` would read as a value and slip a hole past the check while map still
601
- // skips it. Fails fast at the first bad index, so the length alone can never force a walk. Returns the
602
- // validated dense array for the caller to map normally.
603
- function reqDenseArray(list, what) {
604
- if (!_isArray(list)) throw E("bad-input", what + " must be an array");
605
- var n = list.length;
606
- for (var i = 0; i < n; i++) {
607
- if (!intrinsic.hasOwn(list, i)) throw E("bad-input", what + "[" + i + "] is missing (a sparse array is not allowed)");
608
- var v = list[i];
609
- if (v === undefined || v === null) throw E("bad-input", what + "[" + i + "] is missing (a nullish array entry is not allowed)");
610
- }
611
- return list;
612
- }
624
+ // The bound 2-arg form every makeBuilder consumer calls (`_b.reqDenseArray(list, what)`); it delegates
625
+ // to the standalone guard above with this builder's namespace, so the density rule lives in ONE place.
626
+ function reqDenseArray(list, what) { return reqDenseArrayImpl(list, what, rawErr, ctx.prefix + "/bad-input"); }
613
627
  // A caller-supplied DER a builder validates with a PEM-accepting parser and then embeds verbatim with
614
628
  // b.raw. Those parsers unwrap PEM from a byte source, so a PEM-armored input (a Buffer straight from
615
629
  // fs.readFileSync) passes the parse, but b.raw embeds the raw ASCII armor -- which the enclosing
@@ -817,4 +831,10 @@ function tbsSerialNumber(cert) {
817
831
  return asn1.read.integer(tbs.children[hasVersion ? 1 : 0]);
818
832
  }
819
833
 
820
- module.exports = { makeBuilder: makeBuilder, KU_BIT: KU_BIT, tbsNameField: tbsNameField, tbsSerialNumber: tbsSerialNumber };
834
+ // Frozen so a co-resident cannot reassign an exported guard (e.g. reqDenseArray) to bypass it: the
835
+ // standalone consumers read reqDenseArray off this object at call time, so the object holding it must be
836
+ // immutable, the way the guard-* modules freeze their surfaces.
837
+ // Frozen so a co-resident cannot reassign an exported guard (e.g. reqDenseArray) to bypass it: the
838
+ // standalone consumers read reqDenseArray off this object at call time, so the object holding it must be
839
+ // immutable, the way the guard-* modules freeze their surfaces.
840
+ module.exports = intrinsic.freeze({ makeBuilder: makeBuilder, reqDenseArray: reqDenseArrayImpl, KU_BIT: KU_BIT, tbsNameField: tbsNameField, tbsSerialNumber: tbsSerialNumber });
package/lib/webcrypto.js CHANGED
@@ -71,6 +71,12 @@ var _cipherUpdate = intrinsic.uncurry(nodeCrypto.Cipheriv.prototype.update);
71
71
  var _cipherFinal = intrinsic.uncurry(nodeCrypto.Cipheriv.prototype.final);
72
72
  var _cipherGetAuthTag = intrinsic.uncurry(nodeCrypto.Cipheriv.prototype.getAuthTag);
73
73
  var _cipherSetAAD = intrinsic.uncurry(nodeCrypto.Cipheriv.prototype.setAAD);
74
+ // decryptStream drives these across the caller's iteration steps, so it captures them for the same
75
+ // reason: a co-resident that replaced Decipheriv.prototype.update between two chunk reads could steer
76
+ // the recovered plaintext. The captured pair keeps the yielded chunks bound to the ciphertext.
77
+ var _decipherUpdate = intrinsic.uncurry(nodeCrypto.Decipheriv.prototype.update);
78
+ var _decipherFinal = intrinsic.uncurry(nodeCrypto.Decipheriv.prototype.final);
79
+ var _STREAM_CHUNK = constants.BYTES.kib(64);
74
80
  var _bufferConcat = intrinsic.bufferConcat;
75
81
  var _bufferAlloc = intrinsic.bufferAlloc;
76
82
  var _isBuffer = intrinsic.isBuffer;
@@ -462,6 +468,32 @@ SubtleCrypto.prototype.encryptStream = async function encryptStream(spec, source
462
468
  return { ciphertext: _bufferConcat(out), tag: spec.authTagLength ? _cipherGetAuthTag(cipher) : null };
463
469
  };
464
470
 
471
+ // decryptStream(spec, ct) -> an async iterable of plaintext chunks. Unlike encryptStream the whole
472
+ // ciphertext is already in memory (a parsed message states its definite length), so this streams the
473
+ // OUTPUT: the plaintext is yielded a chunk at a time and never held whole (the memory win of streaming
474
+ // decrypt). The decipher is created EAGERLY here -- node copies the key into the cipher at creation, so
475
+ // a caller that clears spec.key after this returns (as the CMS decrypt path does once the content is
476
+ // open) does not disturb the running decipher. The chunked drive uses captured update/final + subarray,
477
+ // so a prototype swap between the caller's iteration steps cannot steer the recovered bytes. A CBC
478
+ // final() rejects a wrong key / bad padding exactly as the buffered path does; the caller translates
479
+ // that failure into its own error domain. spec: { algNode, key, iv }.
480
+ SubtleCrypto.prototype.decryptStream = function decryptStream(spec, ct) {
481
+ var decipher = nodeCrypto.createDecipheriv(spec.algNode, spec.key, spec.iv);
482
+ // Snapshot the ciphertext into a private copy NOW: the drive slices it lazily as the caller iterates,
483
+ // so a view aliasing the caller's buffer would let a reuse of that buffer after this returns change the
484
+ // recovered plaintext and its padding verdict. The copy is read; the caller's buffer is theirs to reuse.
485
+ return _decipherDrive(decipher, _bufferFrom(_toBuf(ct, "decryptStream ciphertext")), _STREAM_CHUNK);
486
+ };
487
+ async function* _decipherDrive(decipher, ct, chunkSize) {
488
+ for (var off = 0; off < ct.length; off += chunkSize) {
489
+ var end = off + chunkSize;
490
+ var piece = _decipherUpdate(decipher, _subarray(ct, off, end < ct.length ? end : ct.length));
491
+ if (piece && piece.length) yield piece;
492
+ }
493
+ var last = _decipherFinal(decipher);
494
+ if (last && last.length) yield last;
495
+ }
496
+
465
497
  SubtleCrypto.prototype.generateKey = async function generateKey(algorithm, extractable, keyUsages) {
466
498
  var alg = _normalizeAlg(algorithm, "generateKey");
467
499
  // Before the partition below, not only in the CryptoKey constructor: the asymmetric branch splits
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.5.36",
3
+ "version": "0.5.38",
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:ad664181-2b29-47c9-9841-12e12097a2ea",
5
+ "serialNumber": "urn:uuid:fe024f86-e1b5-48d0-97ee-173c19cc63b0",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-08-29T23:29:58.331Z",
8
+ "timestamp": "2026-08-30T02:10:51.770Z",
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.5.36",
22
+ "bom-ref": "@blamejs/pki@0.5.38",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.5.36",
25
+ "version": "0.5.38",
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.5.36",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.5.38",
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.5.36",
57
+ "ref": "@blamejs/pki@0.5.38",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]