@blamejs/pki 0.5.35 → 0.5.36
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 +8 -0
- package/README.md +1 -1
- package/lib/cms-encrypt.js +60 -14
- package/lib/cms-sign.js +4 -8
- package/lib/cms-verify.js +8 -8
- package/lib/guard-bytes.js +15 -1
- package/lib/webcrypto.js +49 -0
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,14 @@ 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.36 — 2026-08-29
|
|
8
|
+
|
|
9
|
+
pki.cms.encrypt accepts an async-iterable plaintext, encrypting a large payload without holding it whole in memory.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `pki.cms.encrypt(content, recipients, opts)` accepts an async iterable of byte chunks as `content` (detected by `Symbol.asyncIterator`), alongside the existing `Buffer`, typed-array, `DataView`, and `ArrayBuffer` forms. It streams the plaintext through the AES-GCM or AES-CBC content cipher chunk by chunk, assembling only the ciphertext, so a large plaintext is not held in memory whole. The output is a byte-for-byte match for the buffered form and decrypts with `pki.cms.decrypt` and OpenSSL. This covers the recipient-based EnvelopedData and AuthEnvelopedData as well as the `{ cek }` and `{ password }` EncryptedData forms.
|
|
14
|
+
|
|
7
15
|
## v0.5.35 — 2026-08-29
|
|
8
16
|
|
|
9
17
|
pki.cmp.build now assembles the nested PKIMessage body an RA uses to forward or batch complete messages.
|
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. `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. 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/cms-encrypt.js
CHANGED
|
@@ -492,7 +492,21 @@ var _AUTHENTICATE_OPTS_BARE = {
|
|
|
492
492
|
keyIdentifier: 1, oaepHash: 1, ukm: 1, pem: 1,
|
|
493
493
|
};
|
|
494
494
|
|
|
495
|
-
|
|
495
|
+
function encrypt(content, recipients, opts) {
|
|
496
|
+
// The options and recipients are copied BEFORE the content is classified. Classifying reads
|
|
497
|
+
// content[Symbol.asyncIterator] -- a caller accessor that runs in-realm -- which could otherwise
|
|
498
|
+
// change the content type, the output encoding, or a recipient after the call has begun. With the
|
|
499
|
+
// copies taken first, that probe cannot reach them; the streamed sign path copies the same way. The
|
|
500
|
+
// copy runs inside guard-async's boundary, so a fault in it leaves as a rejection, and the copies
|
|
501
|
+
// (which may hold a symmetric key or a password) are cleared on every path out.
|
|
502
|
+
return guard.bytes.fixedCall(CmsError, "cms/bad-input", [
|
|
503
|
+
[recipients, "recipients"], [opts, "pki.cms.encrypt options"],
|
|
504
|
+
], function (recipientsCopy, optsCopy) {
|
|
505
|
+
return _encryptImpl(content, recipientsCopy, optsCopy);
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
async function _encryptImpl(content, recipients, opts) {
|
|
496
510
|
opts = opts || {};
|
|
497
511
|
// The content algorithm selects the structure, so it is resolved before the door and the table
|
|
498
512
|
// that runs is the one belonging to the structure this call will emit.
|
|
@@ -506,7 +520,11 @@ async function encrypt(content, recipients, opts) {
|
|
|
506
520
|
? " for a CBC content algorithm; authenticated attributes are carried only by an AuthEnvelopedData, which an AEAD algorithm produces"
|
|
507
521
|
: "");
|
|
508
522
|
});
|
|
509
|
-
|
|
523
|
+
// An async-iterable content streams the plaintext through the cipher without buffering it whole; a byte
|
|
524
|
+
// source takes the one-shot path. asyncStreamOf reads Symbol.asyncIterator once and wins only when the
|
|
525
|
+
// value is not already a byte source, so a Buffer with a stray asyncIterator stays a Buffer.
|
|
526
|
+
var contentStream = guard.bytes.asyncStreamOf(content);
|
|
527
|
+
var contentBytes = contentStream ? null : guard.bytes.view(content, CmsError, "cms/bad-input", "content");
|
|
510
528
|
var contentType = opts.contentType || "data";
|
|
511
529
|
var cek = nodeCrypto.randomBytes(ca.keyBits / 8);
|
|
512
530
|
|
|
@@ -515,7 +533,7 @@ async function encrypt(content, recipients, opts) {
|
|
|
515
533
|
// inside the recipient loop would destroy the key the remaining recipients must be given.
|
|
516
534
|
try {
|
|
517
535
|
// EncryptedData: a single non-array { cek } or { password } descriptor, no RecipientInfos.
|
|
518
|
-
if (!Array.isArray(recipients)) return _encryptedData(contentBytes, recipients, ca, contentType, opts, cek);
|
|
536
|
+
if (!Array.isArray(recipients)) return await _encryptedData(contentBytes, contentStream, recipients, ca, contentType, opts, cek);
|
|
519
537
|
|
|
520
538
|
if (!recipients.length) throw _err("cms/bad-input", "at least one recipient is required (RFC 5652 sec. 6.1)");
|
|
521
539
|
var recips = [];
|
|
@@ -524,8 +542,8 @@ async function encrypt(content, recipients, opts) {
|
|
|
524
542
|
_assertDefaultsConsumed(opts, consumed);
|
|
525
543
|
var riNodes = recips.map(_taggedRecipient);
|
|
526
544
|
|
|
527
|
-
if (ca.aead) return _emit(_authEnvelopedData(contentBytes, cek, ca, contentType, opts, riNodes, recips), "authEnvelopedData", opts);
|
|
528
|
-
return _emit(_envelopedData(contentBytes, cek, ca, contentType, riNodes, recips), "envelopedData", opts);
|
|
545
|
+
if (ca.aead) return _emit(await _authEnvelopedData(contentBytes, contentStream, cek, ca, contentType, opts, riNodes, recips), "authEnvelopedData", opts);
|
|
546
|
+
return _emit(await _envelopedData(contentBytes, contentStream, cek, ca, contentType, riNodes, recips), "envelopedData", opts);
|
|
529
547
|
} finally {
|
|
530
548
|
guard.secret.zeroize(cek, CmsError, "cms/bad-input", "the content-encryption key");
|
|
531
549
|
}
|
|
@@ -536,9 +554,25 @@ function _emit(inner, ctName, opts) {
|
|
|
536
554
|
return opts.pem ? schemaCms.pemEncode(ci, "CMS") : ci;
|
|
537
555
|
}
|
|
538
556
|
|
|
539
|
-
|
|
557
|
+
// Run a streamed plaintext through the content cipher, translating the engine's malformed-streamed-content
|
|
558
|
+
// domain into this verb's cms/bad-input via the shared guard, so pki.cms.encrypt keeps its typed CmsError
|
|
559
|
+
// contract (the streamed sign/verify paths translate the same way).
|
|
560
|
+
async function _encStream(spec, stream) {
|
|
561
|
+
try {
|
|
562
|
+
return await subtle.encryptStream(spec, stream);
|
|
563
|
+
} catch (e) {
|
|
564
|
+
guard.bytes.translateStreamError(e, _err, "cms/bad-input");
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
async function _envelopedData(contentBytes, contentStream, cek, ca, contentType, riNodes, recips) {
|
|
540
569
|
var iv = nodeCrypto.randomBytes(16);
|
|
541
|
-
|
|
570
|
+
// A streamed plaintext runs through the CBC cipher incrementally (assembling only the ciphertext, whose
|
|
571
|
+
// length the encryptedContent OCTET STRING needs); a Buffer takes the one-shot path. Both produce the
|
|
572
|
+
// same wire bytes for the same plaintext, so the emitted DER is identical to the buffered form.
|
|
573
|
+
var enc = contentStream
|
|
574
|
+
? (await _encStream({ algNode: "aes-" + ca.keyBits + "-cbc", key: cek, iv: iv }, contentStream)).ciphertext
|
|
575
|
+
: pbes2.cbcEncrypt(cek, iv, contentBytes, ca.keyBits, CmsError, "cms/bad-input");
|
|
542
576
|
var eci = b.sequence([b.oid(O(contentType)), b.sequence([b.oid(O(ca.oid)), b.octetString(iv)]), b.contextPrimitive(0, enc)]);
|
|
543
577
|
return b.sequence([b.integer(BigInt(_envelopedVersion(recips, false))), b.setOf(riNodes), eci]);
|
|
544
578
|
}
|
|
@@ -580,7 +614,7 @@ var AUTH_ENVELOPED_FORBIDDEN = {
|
|
|
580
614
|
why: "authAttrs must not carry the message-digest attribute in an AuthEnvelopedData: its value is the unencrypted hash of the plaintext, which enables content tracking and confirmation of a guessed plaintext (RFC 5083 sec. 2.1, sec. 5)",
|
|
581
615
|
};
|
|
582
616
|
|
|
583
|
-
function _authEnvelopedData(contentBytes, cek, ca, contentType, opts, riNodes, recips) {
|
|
617
|
+
async function _authEnvelopedData(contentBytes, contentStream, cek, ca, contentType, opts, riNodes, recips) {
|
|
584
618
|
var nonce = nodeCrypto.randomBytes(12);
|
|
585
619
|
var authAttrsDer = null, aad = Buffer.alloc(0);
|
|
586
620
|
// RFC 5083 sec. 2.1: authAttrs MUST be present when the content type is not id-data. Emitting an
|
|
@@ -597,7 +631,15 @@ function _authEnvelopedData(contentBytes, cek, ca, contentType, opts, riNodes, r
|
|
|
597
631
|
// A 16-octet (128-bit) GCM tag, the strongest ICV and what OpenSSL emits, so the message
|
|
598
632
|
// interops across OpenSSL 3.5 / 4.x. The aes-ICVlen (16) is carried explicitly (RFC 5084 sec. 3.2
|
|
599
633
|
// omits it only when it equals the DEFAULT 12); it MUST equal the mac octet length (M42).
|
|
600
|
-
|
|
634
|
+
// A streamed plaintext runs through the GCM cipher incrementally; the tag is produced at final() over the
|
|
635
|
+
// same bytes, so the ciphertext + tag equal the one-shot form for the same plaintext and AAD.
|
|
636
|
+
var g;
|
|
637
|
+
if (contentStream) {
|
|
638
|
+
var r = await _encStream({ algNode: "aes-" + ca.keyBits + "-gcm", key: cek, iv: nonce, aad: aad, authTagLength: 16 }, contentStream);
|
|
639
|
+
g = { ct: r.ciphertext, tag: r.tag };
|
|
640
|
+
} else {
|
|
641
|
+
g = _gcmEncrypt(cek, nonce, contentBytes, aad, ca.keyBits, 16);
|
|
642
|
+
}
|
|
601
643
|
var eci = b.sequence([b.oid(O(contentType)), b.sequence([b.oid(O(ca.oid)), _gcmParams(nonce, 16)]), b.contextPrimitive(0, g.ct)]);
|
|
602
644
|
var kids = [b.integer(0n), b.setOf(riNodes), eci];
|
|
603
645
|
if (authAttrsDer) kids.push(authAttrsDer);
|
|
@@ -616,7 +658,7 @@ function _authEnvelopedData(contentBytes, cek, ca, contentType, opts, riNodes, r
|
|
|
616
658
|
var _ENCRYPTED_DATA_CEK_KEYS = { cek: 1 };
|
|
617
659
|
var _ENCRYPTED_DATA_PW_KEYS = { password: 1, iterations: 1, salt: 1, prf: 1 };
|
|
618
660
|
|
|
619
|
-
function _encryptedData(contentBytes, desc, ca, contentType, opts, cek) {
|
|
661
|
+
async function _encryptedData(contentBytes, contentStream, desc, ca, contentType, opts, cek) {
|
|
620
662
|
if (ca.aead) throw _err("cms/bad-input", "EncryptedData supports only CBC content encryption");
|
|
621
663
|
// An EncryptedData carries no RecipientInfos at all, so nothing here reads a per-recipient
|
|
622
664
|
// default. This branch returns before the recipient loop, so it answers for them itself.
|
|
@@ -638,17 +680,19 @@ function _encryptedData(contentBytes, desc, ca, contentType, opts, cek) {
|
|
|
638
680
|
if (encKey.length !== ca.keyBits / 8) throw _err("cms/bad-input", "the supplied cek length does not match " + opts.contentEncryptionAlgorithm);
|
|
639
681
|
contentAlgNode = b.sequence([b.oid(O(ca.oid)), b.octetString(iv)]);
|
|
640
682
|
} else if (desc && desc.password != null) {
|
|
641
|
-
return _encryptedDataPbes2(contentBytes, desc, ca, contentType, iv, opts);
|
|
683
|
+
return _encryptedDataPbes2(contentBytes, contentStream, desc, ca, contentType, iv, opts);
|
|
642
684
|
} else {
|
|
643
685
|
throw _err("cms/bad-input", "EncryptedData needs a single { cek } or { password } descriptor");
|
|
644
686
|
}
|
|
645
|
-
var enc =
|
|
687
|
+
var enc = contentStream
|
|
688
|
+
? (await _encStream({ algNode: "aes-" + ca.keyBits + "-cbc", key: encKey, iv: iv }, contentStream)).ciphertext
|
|
689
|
+
: pbes2.cbcEncrypt(encKey, iv, contentBytes, ca.keyBits, CmsError, "cms/bad-input");
|
|
646
690
|
var eci = b.sequence([b.oid(O(contentType)), contentAlgNode, b.contextPrimitive(0, enc)]);
|
|
647
691
|
var inner = b.sequence([b.integer(0n), eci]);
|
|
648
692
|
return _emit(inner, "encryptedData", opts);
|
|
649
693
|
}
|
|
650
694
|
|
|
651
|
-
function _encryptedDataPbes2(contentBytes, desc, ca, contentType, iv, opts) {
|
|
695
|
+
async function _encryptedDataPbes2(contentBytes, contentStream, desc, ca, contentType, iv, opts) {
|
|
652
696
|
// A string / Uint8Array password is encoded into a buffer this toolkit allocated, a credential
|
|
653
697
|
// copy, so it is cleared once the derivation has consumed it. A caller-supplied Buffer is
|
|
654
698
|
// borrowed and left intact.
|
|
@@ -662,7 +706,9 @@ function _encryptedDataPbes2(contentBytes, desc, ca, contentType, iv, opts) {
|
|
|
662
706
|
var key = nodeCrypto.pbkdf2Sync(password, salt, iterations, ca.keyBits / 8, pbes2.prfNodeByName(prf, _err, "cms"));
|
|
663
707
|
if (pwOwn2.owned) guard.secret.zeroize(password, CmsError, "cms/bad-input", "the password encoding");
|
|
664
708
|
try {
|
|
665
|
-
var enc =
|
|
709
|
+
var enc = contentStream
|
|
710
|
+
? (await _encStream({ algNode: "aes-" + ca.keyBits + "-cbc", key: key, iv: iv }, contentStream)).ciphertext
|
|
711
|
+
: pbes2.cbcEncrypt(key, iv, contentBytes, ca.keyBits, CmsError, "cms/bad-input");
|
|
666
712
|
var contentAlg = pbes2.pbes2AlgId(salt, iterations, prf, ca.oid, iv);
|
|
667
713
|
var eci = b.sequence([b.oid(O(contentType)), contentAlg, b.contextPrimitive(0, enc)]);
|
|
668
714
|
var inner = b.sequence([b.integer(0n), eci]);
|
package/lib/cms-sign.js
CHANGED
|
@@ -464,14 +464,10 @@ async function _signStream(stream, signers, opts) {
|
|
|
464
464
|
try {
|
|
465
465
|
digests = await subtle.digestStream(wcNames, stream);
|
|
466
466
|
} catch (e) {
|
|
467
|
-
// The engine reports malformed streamed content in its own domain; report it in this verb's
|
|
468
|
-
//
|
|
469
|
-
//
|
|
470
|
-
|
|
471
|
-
// algorithm names are this module's own, so webcrypto/syntax here is never an algorithm fault.
|
|
472
|
-
if (e && e.code === "webcrypto/data") throw _err("cms/bad-input", "a streamed content chunk is not a byte source", e);
|
|
473
|
-
if (e && e.code === "webcrypto/syntax") throw _err("cms/bad-input", "the streamed content is not a valid async iterable of byte chunks", e);
|
|
474
|
-
throw e;
|
|
467
|
+
// The engine reports malformed streamed content in its own domain; report it in this verb's via the
|
|
468
|
+
// shared guard, rather than leaking the engine code. The digest algorithm names are this module's own,
|
|
469
|
+
// so a webcrypto/syntax here is never an algorithm fault.
|
|
470
|
+
guard.bytes.translateStreamError(e, _err, "cms/bad-input");
|
|
475
471
|
}
|
|
476
472
|
var byName = {};
|
|
477
473
|
intrinsic.forEach(digestNames, function (n, i) { byName[n] = intrinsic.bufferFrom(digests[i]); });
|
package/lib/cms-verify.js
CHANGED
|
@@ -743,14 +743,10 @@ async function _resolveContentDigests(parsed, streamSource) {
|
|
|
743
743
|
try {
|
|
744
744
|
ds = await subtle.digestStream(intrinsic.map(names, function (n) { return DIGEST_HASH[n]; }), streamSource);
|
|
745
745
|
} catch (e) {
|
|
746
|
-
// The engine reports malformed streamed content in its own domain; report it in this verb's
|
|
747
|
-
//
|
|
748
|
-
//
|
|
749
|
-
|
|
750
|
-
// algorithm names are this module's own, so webcrypto/syntax here is never an algorithm fault.
|
|
751
|
-
if (e && e.code === "webcrypto/data") throw _err("cms/bad-input", "a streamed content chunk is not a byte source", e);
|
|
752
|
-
if (e && e.code === "webcrypto/syntax") throw _err("cms/bad-input", "the streamed content is not a valid async iterable of byte chunks", e);
|
|
753
|
-
throw e;
|
|
746
|
+
// The engine reports malformed streamed content in its own domain; report it in this verb's via the
|
|
747
|
+
// shared guard, rather than leaking the engine code. The digest algorithm names are this module's own,
|
|
748
|
+
// so a webcrypto/syntax here is never an algorithm fault.
|
|
749
|
+
guard.bytes.translateStreamError(e, _err, "cms/bad-input");
|
|
754
750
|
}
|
|
755
751
|
var byName = {};
|
|
756
752
|
intrinsic.forEach(names, function (n, i) { byName[n] = intrinsic.bufferFrom(ds[i]); });
|
|
@@ -1252,6 +1248,10 @@ var countersign = cmsSign.countersign;
|
|
|
1252
1248
|
* (AES key wrap). For EncryptedData (no RecipientInfos), pass a single non-array `{ cek }` or
|
|
1253
1249
|
* `{ password }` descriptor. The default AES-256-GCM content encryption produces an
|
|
1254
1250
|
* authenticated AuthEnvelopedData; a CBC choice produces an unauthenticated EnvelopedData.
|
|
1251
|
+
* `content` is a byte source (a `Buffer`, typed array, `DataView`, or `ArrayBuffer`) OR an async
|
|
1252
|
+
* iterable of byte chunks. An async iterable is streamed through the content cipher incrementally, so
|
|
1253
|
+
* a large plaintext is never buffered whole; the ciphertext is assembled before the DER is emitted, and
|
|
1254
|
+
* the emitted message is byte-for-byte what the buffered form of the same plaintext would produce.
|
|
1255
1255
|
* Malformed input throws a typed `CmsError`.
|
|
1256
1256
|
*
|
|
1257
1257
|
* @opts contentEncryptionAlgorithm `"aes-256-gcm"` (default, AuthEnvelopedData) / `"aes-128-gcm"` / `"aes-256-cbc"` / `"aes-128-cbc"` (EnvelopedData).
|
package/lib/guard-bytes.js
CHANGED
|
@@ -129,6 +129,20 @@ function asyncStreamOf(x) {
|
|
|
129
129
|
return stream;
|
|
130
130
|
}
|
|
131
131
|
|
|
132
|
+
// A streamed content driven through the engine's digestStream / encryptStream reports a malformed chunk
|
|
133
|
+
// or iterator in the ENGINE's domain: a non-byte chunk is webcrypto/data, and a malformed async-iterator
|
|
134
|
+
// protocol (a non-callable next, or a factory returning a non-iterator) is webcrypto/syntax. Rethrow both
|
|
135
|
+
// in the CALLER's domain through its typed factory E, so the public verb keeps its own <ns>/bad-input
|
|
136
|
+
// contract for malformed streamed content rather than leaking the engine code; a caller's own next()
|
|
137
|
+
// fault (any other error) is rethrown unchanged. E(code, msg, cause) is the caller's error factory. Always
|
|
138
|
+
// throws. The digest / cipher algorithm names each verb passes are its own, so webcrypto/syntax here is
|
|
139
|
+
// never an algorithm fault.
|
|
140
|
+
function translateStreamError(e, E, code) {
|
|
141
|
+
if (e && e.code === "webcrypto/data") throw E(code, "a streamed content chunk is not a byte source", e);
|
|
142
|
+
if (e && e.code === "webcrypto/syntax") throw E(code, "the streamed content is not a valid async iterable of byte chunks", e);
|
|
143
|
+
throw e;
|
|
144
|
+
}
|
|
145
|
+
|
|
132
146
|
// Is this value a byte store, asked of the internal slot rather than the prototype?
|
|
133
147
|
//
|
|
134
148
|
// `v instanceof ArrayBuffer` answers what a value inherits from, which is a different question
|
|
@@ -1113,6 +1127,6 @@ function fixedCall(ErrorClass, code, args, body) {
|
|
|
1113
1127
|
// call, so a writable export would let a caller replace the check rather than pass it.
|
|
1114
1128
|
module.exports = intrinsic.freeze({
|
|
1115
1129
|
view: view, source: source, snapshot: snapshot, snapshotSource: snapshotSource,
|
|
1116
|
-
isByteSource: isByteSource, asyncStreamOf: asyncStreamOf, lengthOf: lengthOf, outputView: outputView,
|
|
1130
|
+
isByteSource: isByteSource, asyncStreamOf: asyncStreamOf, translateStreamError: translateStreamError, lengthOf: lengthOf, outputView: outputView,
|
|
1117
1131
|
snapshotDeep: snapshotDeep, fixArguments: fixArguments, fixedCall: fixedCall,
|
|
1118
1132
|
});
|
package/lib/webcrypto.js
CHANGED
|
@@ -62,6 +62,15 @@ var _bufToString = intrinsic.uncurry(Buffer.prototype.toString);
|
|
|
62
62
|
// one-shot digest needs no such capture: its single update and digest run with no suspension between.
|
|
63
63
|
var _hashUpdate = intrinsic.uncurry(nodeCrypto.Hash.prototype.update);
|
|
64
64
|
var _hashDigest = intrinsic.uncurry(nodeCrypto.Hash.prototype.digest);
|
|
65
|
+
// The node Cipheriv instance methods, captured at load for the same reason as the hash methods above:
|
|
66
|
+
// encryptStream feeds plaintext chunks through the cipher across `await` points, and a co-resident that
|
|
67
|
+
// replaced Cipheriv.prototype.update while the stream was suspended between chunks could drop or alter a
|
|
68
|
+
// chunk, so the emitted ciphertext would not be the encryption of the plaintext the caller streamed.
|
|
69
|
+
// Calling the captured update/final keeps the ciphertext bound to the bytes the stream actually yielded.
|
|
70
|
+
var _cipherUpdate = intrinsic.uncurry(nodeCrypto.Cipheriv.prototype.update);
|
|
71
|
+
var _cipherFinal = intrinsic.uncurry(nodeCrypto.Cipheriv.prototype.final);
|
|
72
|
+
var _cipherGetAuthTag = intrinsic.uncurry(nodeCrypto.Cipheriv.prototype.getAuthTag);
|
|
73
|
+
var _cipherSetAAD = intrinsic.uncurry(nodeCrypto.Cipheriv.prototype.setAAD);
|
|
65
74
|
var _bufferConcat = intrinsic.bufferConcat;
|
|
66
75
|
var _bufferAlloc = intrinsic.bufferAlloc;
|
|
67
76
|
var _isBuffer = intrinsic.isBuffer;
|
|
@@ -413,6 +422,46 @@ SubtleCrypto.prototype.digestStream = async function digestStream(algorithms, so
|
|
|
413
422
|
return _map(hashes, function (h) { return _toArrayBuffer(_hashDigest(h)); });
|
|
414
423
|
};
|
|
415
424
|
|
|
425
|
+
// encryptStream(spec, source) -> { ciphertext, tag }. Runs the plaintext chunks of an async iterable
|
|
426
|
+
// through the content cipher incrementally, assembling the ciphertext -- its definite length is needed
|
|
427
|
+
// for the EnvelopedData encryptedContent OCTET STRING, and the plaintext is never held whole (the memory
|
|
428
|
+
// win of streaming encrypt). Mirrors digestStream's captured-method + acquire-iterator-once discipline so
|
|
429
|
+
// a chunk-boundary prototype swap cannot steer the ciphertext, and drives the iterator's return() on any
|
|
430
|
+
// exit. spec: { algNode, key, iv, aad (optional), authTagLength (optional, AEAD -> a tag is returned) }.
|
|
431
|
+
SubtleCrypto.prototype.encryptStream = async function encryptStream(spec, source) {
|
|
432
|
+
var cipher = spec.authTagLength
|
|
433
|
+
? nodeCrypto.createCipheriv(spec.algNode, spec.key, spec.iv, { authTagLength: spec.authTagLength })
|
|
434
|
+
: nodeCrypto.createCipheriv(spec.algNode, spec.key, spec.iv);
|
|
435
|
+
if (spec.aad && spec.aad.length) _cipherSetAAD(cipher, spec.aad);
|
|
436
|
+
var acquire = source == null ? undefined : source[_asyncIterator];
|
|
437
|
+
if (typeof acquire !== "function") {
|
|
438
|
+
throw new WebCryptoError("webcrypto/syntax", "encryptStream: source must be an async iterable of byte chunks");
|
|
439
|
+
}
|
|
440
|
+
var iterator = _apply(acquire, source, _NO_ARGS);
|
|
441
|
+
var out = [];
|
|
442
|
+
try {
|
|
443
|
+
var nextMethod = iterator == null ? undefined : iterator.next;
|
|
444
|
+
if (typeof nextMethod !== "function") {
|
|
445
|
+
throw new WebCryptoError("webcrypto/syntax", "encryptStream: source must be an async iterable of byte chunks");
|
|
446
|
+
}
|
|
447
|
+
for (;;) {
|
|
448
|
+
var step = await _apply(nextMethod, iterator, _NO_ARGS);
|
|
449
|
+
if (step && step.done) break;
|
|
450
|
+
var buf = _toBuf(step == null ? undefined : step.value, "encryptStream chunk");
|
|
451
|
+
var piece = _cipherUpdate(cipher, buf);
|
|
452
|
+
if (piece && piece.length) out[out.length] = piece;
|
|
453
|
+
}
|
|
454
|
+
} catch (e) {
|
|
455
|
+
try {
|
|
456
|
+
var ret = iterator == null ? undefined : iterator.return;
|
|
457
|
+
if (typeof ret === "function") await _apply(ret, iterator, _NO_ARGS);
|
|
458
|
+
} catch (_r) { /* cleanup is best-effort */ }
|
|
459
|
+
throw e;
|
|
460
|
+
}
|
|
461
|
+
out[out.length] = _cipherFinal(cipher);
|
|
462
|
+
return { ciphertext: _bufferConcat(out), tag: spec.authTagLength ? _cipherGetAuthTag(cipher) : null };
|
|
463
|
+
};
|
|
464
|
+
|
|
416
465
|
SubtleCrypto.prototype.generateKey = async function generateKey(algorithm, extractable, keyUsages) {
|
|
417
466
|
var alg = _normalizeAlg(algorithm, "generateKey");
|
|
418
467
|
// Before the partition below, not only in the CryptoKey constructor: the asymmetric branch splits
|
package/package.json
CHANGED
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:
|
|
5
|
+
"serialNumber": "urn:uuid:ad664181-2b29-47c9-9841-12e12097a2ea",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-08-
|
|
8
|
+
"timestamp": "2026-08-29T23:29:58.331Z",
|
|
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.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.5.36",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.5.
|
|
25
|
+
"version": "0.5.36",
|
|
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.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/pki@0.5.36",
|
|
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.
|
|
57
|
+
"ref": "@blamejs/pki@0.5.36",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|