@blamejs/pki 0.3.23 → 0.3.24

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,19 @@ 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.3.24 — 2026-07-26
8
+
9
+ pki.smime.verify / decrypt can now recognize a legacy (RFC 8551) header-protected message -- opt in with `legacyHeaderProtection` and the real headers of an older `message/rfc822`-wrapped message are surfaced, safely separated from the authenticated header set.
10
+
11
+ ### Added
12
+
13
+ - pki.smime.verify and pki.smime.decrypt accept opts.legacyHeaderProtection: true to detect a legacy RFC 8551 header-protected message (RFC 9788 sec. 4.10) -- a signed or encrypted payload that is a bare message/rfc822 wrap with no hp= parameter. On a precise match the inner message's Non-Structural headers are surfaced under headerProtection.legacy = { headers, mode, fromMismatch, confidential }, with the mode inferred from the envelope and an encrypted message's confidential set computed against the visible outer headers. RFC 9788 sec. 4.10.1 / sec. 4.10.2, RFC 8551.
14
+ - headerProtection.legacy is null on every verify / decrypt result unless a legacy message was detected via legacyHeaderProtection. The inferred set is intentionally kept separate from the authenticated protectedHeaders (which stays null) and from present (which stays false), since a legacy message is indistinguishable from a forwarded message/rfc822 -- so a consumer keying trust off present/protectedHeaders is never misled by the opt-in heuristic, and consuming headerProtection.legacy.headers is an explicit, fromMismatch-checkable choice.
15
+
16
+ ### Changed
17
+
18
+ - Detection is opt-in and safe-by-default. Without legacyHeaderProtection the behavior is unchanged: a legacy-form message reads as protectedHeaders: null, present: false, legacy: null (never mis-authenticated). With the option set, a message that is not precisely identified -- an ordinary forwarded message/rfc822 that fails a condition, an inner part that is itself a signed/encrypted layer, an inner part declaring hp=, or a part with a duplicate Content-Type -- reports legacy: null. The signed-and-encrypted legacy form (RFC 9788 Appendix C.3.17) surfaces as clear via the caller's re-verify step, a documented limitation of the non-recursive layered API.
19
+
7
20
  ## v0.3.23 — 2026-07-26
8
21
 
9
22
  pki.pkcs12.open now reads legacy PKCS#12 stores -- decrypt the RFC 7292 Appendix C 3DES and RC2 bags an `openssl pkcs12 -legacy` (and NSS) store uses, so an older .p12/.pfx opens instead of being refused.
package/README.md CHANGED
@@ -232,7 +232,7 @@ is callable today; nothing below is a stub.
232
232
  | `pki.key` | RFC 5958 / RFC 8018 key-material lifecycle — `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 + AES-CBC-Pad): `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, scrypt refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), a malformed parameter set or wrong-length IV is a distinct typed error, and — because a MAC-less PBES2-CBC decrypt must not be 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)` / `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo, delegating the encoding to WebCrypto so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters (an ambiguous RSA/EC import requires `opts.algorithm`). `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards/Montgomery curves, and the FIPS post-quantum ML-DSA / ML-KEM, and `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM; fail-closed with typed `KeyError`. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt` / `decrypt` / `export` / `import` / `generate` / `publicFromPrivate` |
233
233
  | `pki.pkcs12` | RFC 7292 / RFC 9579 PKCS#12 (.p12/.pfx) issuance — `build(spec, opts)` assembles a password-integrity store. `spec` is 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 / nested `safeContents` bags. Keys and certs are validated before wrapping; `friendlyName` (BMPString) and `localKeyId` attributes are single-value. The store is protected by a classic Appendix B HMAC (default, max interop) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`), over SHA-256/384/512, with the 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 (what OpenSSL and NSS consume) — so a file it emits opens in OpenSSL and NSS, cross-checked bidirectionally. The MAC is computed over 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 store's 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 — a signature from any `pki.cms.sign` signer (RSA / ECDSA / EdDSA / ML-DSA / SLH-DSA / composite), no MacData (RFC 7292 §4); privacy stays independent, so the `password` still PBES2-encrypts the bags. **Public-key privacy** — per-safe `recipients` (or the `opts.recipientCerts` convenience) wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData` — never GCM) encrypting it to recipient public keys through the shipped `pki.cms.encrypt` recipient model, restricted to certificate recipients (RSA-OAEP / ECDH / X25519 / X448 / ML-KEM — a password or KEK recipient, which `open` could not reopen, is rejected); all four integrity × privacy combinations are permitted (RFC 7292 §3.1). **Legacy-PBE read** — `open` decrypts the RFC 7292 Appendix C 3DES and RC2 bags an `openssl pkcs12 -legacy` / NSS store uses (RC2 via an in-tree RFC 2268 cipher), so an older store opens; the legacy RC4 schemes are refused. Returns DER or a PEM `PKCS12`; fail-closed with typed `Pkcs12Error`. `open(pfx, password, opts)` reads a store back: it verifies the MAC **first** (a wrong password is the MAC verdict, not 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/secrets as raw DER, all with `friendlyName`/`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, the signer surfaced in `signers` but never trust-chained — the caller's `pki.path.validate` step); a legacy-PBE (App. C) store's 3DES / RC2 bags are decrypted (RC4 refused); an `id-envelopedData` (public-key privacy) safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` if absent, every recipient-side fault the uniform `pkcs12/decrypt-failed`); a post-integrity decrypt failure is the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`; it reads what OpenSSL and NSS produce. Parsing stays at `pki.schema.pkcs12.parse` — `build` / `verifyMac` / `open` |
234
234
  | `pki.cms` | RFC 5652 §5 CMS SignedData signing + signature verification — `sign(content, signers, opts)` produces a SignedData (attached or detached, one or many signers, 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 / EdDSA — 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. `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: when signed attributes are 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), otherwise directly over the content. It returns a per-signer verdict with the matched signer certificate; it does not chain that certificate to a trust anchor — that is the caller's step through `pki.path.validate`. **Countersignatures** (RFC 5652 §11.4): `countersign(cms, signers, opts)` adds a countersignature — a `SignerInfo` over the countersigned SignerInfo's signature value, any signer algorithm, nestable, 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 (an RFC 3161 timestamp token attachable via `sign`'s `unsignedAttributes`) under `signers[i].unsignedAttrs`, surfaced unauthenticated. **Content encryption** (RFC 5652/5083/5084/9629): `encrypt(content, recipients, opts)` produces an EnvelopedData, AuthEnvelopedData (AES-GCM, the authenticated default), or EncryptedData — recipients auto-dispatch off the certificate key to key-transport (RSAES-OAEP; v1.5 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 + RFC 3211 PWRI-KEK), or the post-quantum ML-KEM KEMRecipientInfo (RFC 9629/9936) — one fresh content key wrapped 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 / password-oracle freedom), and PKCS#1 v1.5 is decrypt-only under the RFC 3218 implicit-rejection countermeasure. **AuthenticatedData** (RFC 5652 §9): `authenticate(content, recipients, opts)` produces an `id-ct-authData` — cleartext content plus an HMAC-SHA-256/384/512 MAC (authenticated but not encrypted), the fresh MAC key wrapped for every recipient through the same RecipientInfo model as `encrypt`; the MAC covers the authenticated attributes (content-type + 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`. **Compression** (RFC 3274): `compress(content, opts)` / `decompress(input, opts)` produce and consume a CompressedData (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` — a size transform with no integrity/confidentiality (RFC 8551 §2.4.5). Fail-closed with typed `cms/*` errors — `sign`, `verify`, `countersign`, `encrypt`, `authenticate`, `decrypt`, `compress`, `decompress` |
235
- | `pki.smime` | RFC 8551 S/MIME message assembly, verification, encryption, and compression over the CMS layer — `sign(content, signers, opts)` wraps a MIME entity as a signed S/MIME message in either form: `multipart/signed` (clear-signed — the content stays readable in any MUA, a detached CMS SignedData rides alongside as `application/pkcs7-signature` with a matching `micalg`) or `application/pkcs7-mime; smime-type=signed-data` (opaque — the whole entity is a base64 CMS SignedData). The signed bytes are the entity's RFC 8551 §3.1.1 canonical form (CRLF line endings); `verify(message, opts)` unwraps both forms and recomputes over the same canonicalizer, so a transport that re-wraps line endings still verifies and 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 — `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, not the header, and decryption is fail-closed and oracle-free. The crypto is entirely `pki.cms.sign` / `verify` / `encrypt` / `decrypt` — 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 (algorithm-agnostic). Like `cms.verify`, `verify` returns the per-signer cryptographic verdict plus the recovered content; chaining a signer to a trust anchor is the caller's `pki.path.validate` step. `compress(content, opts)` / `decompress(message, opts)` add the opaque `application/pkcs7-mime; smime-type=compressed-data; name=smime.p7z` frame (RFC 8551 §3.6, RFC 3274) — a size transform with no integrity/confidentiality (§2.4.5), decompress 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` / `encrypt` gain `opts.protectHeaders` — the caller's `opts.headers` are inlined on the Cryptographic Payload root (its Content-Type gains `hp="clear"` signed / `hp="cipher"` encrypted) so the CMS signature/encryption covers them, defeating a transport that rewrites or reads Subject/From/… `verify` / `decrypt` surface the AUTHENTICATED inner set as `protectedHeaders` + `headerProtection { present, mode, fromMismatch }` (a tampered outer header cannot alter it; `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/Keywords, so the real values live only in the ciphertext; `decrypt` recovers them. Every emitted header routes through a fail-closed injection guard (a CR/LF/NUL value or a non-ftext name is rejected), and a malformed/contradictory `hp` wrap fails closed (`smime/bad-header-protection`), never a silent downgrade; the CMS crypto is unchanged. Bidirectionally interoperable with `openssl smime` / `openssl cms`. Fail-closed with typed `smime/*` errors — `sign`, `verify`, `encrypt`, `decrypt`, `compress`, `decompress` |
235
+ | `pki.smime` | RFC 8551 S/MIME message assembly, verification, encryption, and compression over the CMS layer — `sign(content, signers, opts)` wraps a MIME entity as a signed S/MIME message in either form: `multipart/signed` (clear-signed — the content stays readable in any MUA, a detached CMS SignedData rides alongside as `application/pkcs7-signature` with a matching `micalg`) or `application/pkcs7-mime; smime-type=signed-data` (opaque — the whole entity is a base64 CMS SignedData). The signed bytes are the entity's RFC 8551 §3.1.1 canonical form (CRLF line endings); `verify(message, opts)` unwraps both forms and recomputes over the same canonicalizer, so a transport that re-wraps line endings still verifies and 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 — `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, not the header, and decryption is fail-closed and oracle-free. The crypto is entirely `pki.cms.sign` / `verify` / `encrypt` / `decrypt` — 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 (algorithm-agnostic). Like `cms.verify`, `verify` returns the per-signer cryptographic verdict plus the recovered content; chaining a signer to a trust anchor is the caller's `pki.path.validate` step. `compress(content, opts)` / `decompress(message, opts)` add the opaque `application/pkcs7-mime; smime-type=compressed-data; name=smime.p7z` frame (RFC 8551 §3.6, RFC 3274) — a size transform with no integrity/confidentiality (§2.4.5), decompress 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` / `encrypt` gain `opts.protectHeaders` — the caller's `opts.headers` are inlined on the Cryptographic Payload root (its Content-Type gains `hp="clear"` signed / `hp="cipher"` encrypted) so the CMS signature/encryption covers them, defeating a transport that rewrites or reads Subject/From/… `verify` / `decrypt` surface the AUTHENTICATED inner set as `protectedHeaders` + `headerProtection { present, mode, fromMismatch, confidential, legacy }` (a tampered outer header cannot alter it; `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/Keywords, so the real values live only in the ciphertext; `decrypt` recovers them. Every emitted header routes through a fail-closed injection guard (a CR/LF/NUL value or a non-ftext name is rejected), and a malformed/contradictory `hp` wrap fails closed (`smime/bad-header-protection`), never a silent downgrade; the CMS crypto is unchanged. Inbound **legacy** RFC 8551 header protection is recognized opt-in: `verify` / `decrypt` with `opts.legacyHeaderProtection` detect a legacy `message/rfc822`-wrapped payload (the RFC 9788 §4.10.1 four-condition identification) and surface the inner message's headers under `headerProtection.legacy = { headers, mode, fromMismatch, confidential }` (`headers` an ordered `[{ name, value }]` array that retains legally-repeated fields like `Received`) — never in `protectedHeaders` and never setting `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`/`protectedHeaders` is never misled, and only one that explicitly reads `headerProtection.legacy.headers` (cross-checking `legacy.fromMismatch`) consumes it. Off by default; 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` / `openssl cms`. Fail-closed with typed `smime/*` errors — `sign`, `verify`, `encrypt`, `decrypt`, `compress`, `decompress` |
236
236
  | `pki.tsp` | RFC 3161 Time-Stamp Protocol — `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 / ordering), plus the RFC 3161 §2.4.2 signing-certificate attribute binding the token to the TSA certificate (SHA-2 imprints, any `pki.cms.sign` TSA key). `request` / `parseRequest` build and parse the TimeStampReq a client sends (imprint, requested policy, nonce, certReq), `response` / `parseResponse` the TimeStampResp a TSA returns — a granted status wrapping a token, or a rejection with PKIStatus and failure info, the §2.4.2 status↔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`, returning `{ valid, genTime, serialNumber, tstInfo, … }` — `sign`, `request`, `parseRequest`, `response`, `parseResponse`, `verify` |
237
237
  | `pki.ocsp` | RFC 6960 Online Certificate Status Protocol — the responder and relying-party surface. `buildRequest(query, opts)` builds an OCSPRequest for one or more `{ cert, issuer }` pairs (CertID hashed under SHA-1 by default per the RFC 5019 lightweight profile, or SHA-2; optional RFC 9654 nonce, optional requestor signature). `sign(responseData, responder, opts)` produces a signed BasicOCSPResponse over the exact `ResponseData` DER — the issuing CA directly or a delegated responder, any `pki.cms.sign` key including the post-quantum ML-DSA / SLH-DSA sets, with `good` / `revoked` (reason + time) / `unknown` per-certificate status, and `buildErrorResponse(status)` the unsigned §2.3 error (`tryLater` / `unauthorized` / …). `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, passing the full out-of-path certificate gates), the signature over `tbsResponseDataBytes`, currency (`thisUpdate`/`nextUpdate`), and the request-nonce echo — returning `{ status: "good" / "revoked" / "unknown", … }`, never a silent accept. Transport-free — `buildRequest`, `sign`, `buildErrorResponse`, `verify` |
238
238
  | `pki.ct` | RFC 6962 Certificate Transparency SCTs — `parseSctList` decodes the `SignedCertificateTimestampList` a certificate or OCSP response carries in the SCT extension (a TLS-presentation-language payload inside the §3.3 double DER wrap) into per-SCT log id, exact `timestamp` (BigInt), named signature algorithm, and raw signature; `reconstructSignedData` rebuilds the exact `digitally-signed` preimage; `verifySct` verifies an SCT signature against a log's public key by reconstructing the signed data, routing an ECDSA signature through the strict DER-conformance gate, and verifying through the crypto engine — resolving true or false, and throwing a typed error on a structural fault. The producing side: `encodeSctList` builds the extension value byte-for-byte (the exact inverse of `parseSctList`) and `signSct` performs a log's signing step (rebuilding the same signed-data preimage the verifier hashes and signing it with the log's ECDSA-P-256 / RSA key). The trust surface: `parseLogList` ingests the CT log-list JSON into constraint-carrying trusted logs — recomputing each log's id as SHA-256 of its key and refusing a disagreeing id (a swapped key, §3.2), decoding the state + temporal-interval constraints — and `verifySctWithLogList` resolves the log key from an SCT's log id, enforces the state (usable/qualified/readonly trusted; retired only before retirement; pending/rejected refused) and the temporal-interval window, then delegates the signature check to `verifySct`. `verifyLogListSignature(json, signature, publicKey)` verifies the detached `log_list.sig` over the raw log-list bytes against a caller-pinned signer key (RSASSA-PKCS1-v1.5/SHA-256, EC P-256 arm; forgeable-key defenses fail closed) — cross-checked against `openssl dgst`, completing the offline log-list trust chain. `fetchLogList(opts)` turns that chain into a live client: it GETs the `log_list.json` and its detached `log_list.sig` over the shared `pki.transport`, verifies the detached signature over the raw fetched bytes against a caller-pinned distributor key **before** parsing (verify-before-parse — an unverified document is never parsed, read, cached, or surfaced), then ingests the same bytes through `parseLogList` and returns the trusted-log set plus the surfaced `version`/`timestamp`. No baked-in vendor URL or key (both caller-pinned); explicit TLS trust with `rejectUnauthorized` always on; each response is size-capped before the trust chain; the transport is dependency-injectable so it is fully testable offline. Structure decoded, crypto fail-closed — `parseSctList`, `reconstructSignedData`, `verifySct`, `encodeSctList`, `signSct`, `parseLogList`, `verifySctWithLogList`, `verifyLogListSignature`, `fetchLogList` |
package/lib/smime.js CHANGED
@@ -228,32 +228,195 @@ function _declaresHp(content) {
228
228
  return false;
229
229
  }
230
230
 
231
+ // A fresh not-protected surface (returned when no header protection is present or detection fails soft). A NEW
232
+ // object each call -- the caller Object.assign()s it onto the verify/decrypt result, so it must not be shared.
233
+ // `present` + `protectedHeaders` describe ONLY cryptographically-declared (hp=) protection; `legacy` is null
234
+ // unless an opt-in legacy RFC8551HP inference succeeded (then it carries its own headers/mode/etc. -- see below).
235
+ function _noneSurface() { return { protectedHeaders: null, headerProtection: { present: false, mode: null, fromMismatch: false, confidential: [], legacy: null } }; }
236
+
237
+ // Count the Content-Type fields in a parsed header list. A structure with more than one is AMBIGUOUS: mime.parse
238
+ // surfaces only the FIRST via contentType, so an hp= parameter or a Cryptographic-Layer media type on a LATER
239
+ // field would be invisible to the classification -- both the standard HP path and the legacy path fail closed on it.
240
+ function _contentTypeCount(headers) { var n = 0; headers.forEach(function (h) { if (h.lname === "content-type") n++; }); return n; }
241
+
242
+ // Header fields that must not sensibly repeat: the RFC 5322 sec. 3.6 max-1 originator/destination/identification
243
+ // fields, plus Return-Path (the envelope sender -- RFC 5322 sec. 3.6 groups it under trace, but RFC 5321 sec. 4.4
244
+ // restricts a delivered message to a single one). A duplicate of one of these is a malformed / ambiguous set (a
245
+ // consumer could pick a different sender / subject); a duplicate of any OTHER field (Received and the other
246
+ // trace fields, Resent-*, Comments, Keywords, and optional / X-* fields) is legitimately repeatable in a real
247
+ // message. A Set (not a plain object) so an attacker-chosen field name like "constructor" / "__proto__" cannot
248
+ // match an inherited Object.prototype member and false-trip the singleton reject.
249
+ var RFC5322_SINGLETON = new Set(["date", "from", "sender", "reply-to", "to", "cc", "bcc", "message-id", "in-reply-to", "references", "subject", "return-path"]);
250
+
251
+ // Extract the Non-Structural protected fields from a recovered inner header list. Shared by the standard HP path
252
+ // (over the Cryptographic Payload root) and the legacy path (over the message/rfc822 inner message, sec. 4.10).
253
+ // Returns { protectedHeaders (UTF-8 map, last-wins -- the ergonomic single-value view surfaced by the standard
254
+ // path), entries (an ORDERED array of every { name, value, raw } occurrence -- a real message repeats trace
255
+ // fields, and a last-wins collapse would drop all but one), innerFrom, refouter (HP-Outer records), dup (any
256
+ // duplicate field name), dupSingleton (a duplicate of an RFC 5322 singleton field) }.
257
+ function _extractProtected(headerList) {
258
+ // mime.parse decodes the header block as latin1 (byte-preserving), so a protected value emitted as UTF-8
259
+ // (RFC 6532, the guard permits it) is re-decoded latin1->UTF-8 here to round-trip intact. protectedHeaders
260
+ // surfaces the exact authenticated field body (rawValue: leading/trailing whitespace preserved), NOT a
261
+ // trimmed value that would diverge from the signed octets.
262
+ var protectedHeaders = Object.create(null), innerFrom = null, seen = Object.create(null), dup = null, dupSingleton = null;
263
+ var entries = []; // every Non-Structural { name, value } occurrence, in order -- retains legally-repeated fields
264
+ var refouter = []; // RFC 9788 sec. 4.2.1: the HP-Outer records (name + the value the field had in the outer section)
265
+ headerList.forEach(function (h) {
266
+ if (_isStructural(h.lname)) return;
267
+ if (h.lname === "hp-outer") {
268
+ // RFC 9788 sec. 4.2.1 step 4.i: split the HP-Outer value on the FIRST colon into (name, outer-value)
269
+ // -> refouter. The value is kept BYTE-PRESERVING (latin1), never UTF-8-decoded, because the sec. 4.3.1
270
+ // confidentiality comparison must be octet-exact (a lossy decode maps distinct invalid octets 0x80/0x81
271
+ // to one replacement char, which would mis-classify an obscured field as exposed and drop it from the
272
+ // confidential set). HP-Outer is NEVER surfaced as a protected header nor counted toward the duplicate
273
+ // check (sec. 2.2: it "can appear multiple times"). A valueless HP-Outer (no inner colon) is ignored.
274
+ var ci = h.rawValue.indexOf(":");
275
+ if (ci >= 0) refouter.push({ name: h.rawValue.slice(0, ci).trim().toLowerCase(), value: h.rawValue.slice(ci + 1).trim() });
276
+ return;
277
+ }
278
+ var val = _utf8Header(h.rawValue); // the exact authenticated field body (RFC 6532 UTF-8)
279
+ entries.push({ name: h.name, value: val, raw: h.rawValue }); // EVERY occurrence: `value` (UTF-8) for surfacing, `raw` (latin1) for the octet-exact confidentiality match
280
+ if (seen[h.lname]) { dup = h.name; if (RFC5322_SINGLETON.has(h.lname)) dupSingleton = h.name; }
281
+ seen[h.lname] = 1;
282
+ protectedHeaders[h.name] = val; // SURFACE (map, last-wins -- the ergonomic single-value view; `entries` keeps every occurrence + the octet-exact `raw`)
283
+ // innerFrom uses the byte-preserving value: a lossy UTF-8 decode maps distinct invalid 8-bit sequences (0x80
284
+ // vs 0x81) to the same replacement char, which would let an attacker alter the displayed From without
285
+ // tripping fromMismatch. Compare the raw octets instead.
286
+ if (h.lname === "from") innerFrom = h.value;
287
+ });
288
+ return { protectedHeaders: protectedHeaders, entries: entries, innerFrom: innerFrom, refouter: refouter, dup: dup, dupSingleton: dupSingleton };
289
+ }
290
+
291
+ // RFC 9788 sec. 4.3.1: a protected field occurrence is end-to-end confidential (encrypted-only) unless a
292
+ // `refouter` record carries its EXACT name + value -- i.e. that value was copied verbatim to the visible outer
293
+ // section. The match is per-OCCURRENCE and MULTISET (each outer record accounts for at most one inside
294
+ // occurrence), so a legally-repeated field with one obscured value and one exposed value (Keywords: secret then
295
+ // Keywords: public, outer exposing only "public") still reports the name confidential -- a last-wins collapse
296
+ // would drop the hidden "secret" and let a caller leak it. A field name is confidential if ANY of its
297
+ // occurrences is unexposed. The comparison is octet-exact (latin1 raw), never lossy-decoded. For the standard
298
+ // path `refouter` is the HP-Outer records; for the legacy path it is the actual outer Header Section (part A).
299
+ function _computeConfidential(entries, refouter) {
300
+ // Index the outer occurrences by (normalized name -> value -> available count) so the multiset comparison is
301
+ // O(N + M), not a per-occurrence rescan of the outer array: matching N identical exposed occurrences would
302
+ // otherwise be N(N+1)/2 comparisons -- a DoS an attacker could drive toward the 16 MiB section cap. A two-level
303
+ // Map (never a plain object) so an attacker-chosen name/value like "__proto__" cannot confuse the lookup.
304
+ var byName = new Map();
305
+ refouter.forEach(function (r) {
306
+ var m = byName.get(r.name); if (!m) { m = new Map(); byName.set(r.name, m); }
307
+ m.set(r.value, (m.get(r.value) || 0) + 1);
308
+ });
309
+ var confidential = [], seen = Object.create(null);
310
+ entries.forEach(function (e) {
311
+ var m = byName.get(e.name.toLowerCase()), val = e.raw.trim(), n = (m && m.get(val)) || 0;
312
+ if (n > 0) { m.set(val, n - 1); return; } // an outer occurrence accounts for (exposes) this one
313
+ if (!seen[e.name]) { seen[e.name] = 1; confidential.push(e.name); }
314
+ });
315
+ return confidential;
316
+ }
317
+
318
+ // Inspect EVERY outer From (outerEnt.header returns only the FIRST; an attacker may append a second, forged From
319
+ // that a MUA displays). A mismatch is ANYTHING but exactly one outer From equal to the protected one: a removed
320
+ // outer From, a duplicate, or a differing value all flag tampering of the displayed sender.
321
+ function _computeFromMismatch(innerFrom, outerEnt) {
322
+ var outerFroms = [];
323
+ outerEnt.headers.forEach(function (h) { if (h.lname === "from") outerFroms.push(h.value.trim()); }); // byte-preserving (latin1)
324
+ return innerFrom != null && (outerFroms.length !== 1 || outerFroms[0] !== innerFrom.trim());
325
+ }
326
+
327
+ // Is this (lowercased) media type a Cryptographic Layer (RFC 9788 sec. 4.10.1)? Conservative: any
328
+ // application/pkcs7-mime (incl. an OpenSSL x-pkcs7-mime, or a compressed-data layer) plus multipart/signed and
329
+ // multipart/encrypted. Mis-classifying part D as a layer only degrades legacy detection to none -- the safe direction.
330
+ function _isCryptoLayer(type) {
331
+ // `type` is the already-lowercased media type from mime.parse's _parseStructured; _isPkcs7 guards the
332
+ // null/undefined case internally, so no local `|| ""` fallback is needed (and no dead branch is introduced).
333
+ return _isPkcs7(type, "mime") || type === "multipart/signed" || type === "multipart/encrypted";
334
+ }
335
+
336
+ // The legacy `refouter`: the actual visible outer Header Section (part A) as name+value records, so the sec.
337
+ // 4.3.1 confidentiality comparison runs against the real outer values (a legacy message carries no HP-Outer).
338
+ function _outerRefouter(outerEnt) {
339
+ var r = [];
340
+ outerEnt.headers.forEach(function (h) { if (!_isStructural(h.lname) && h.lname !== "hp-outer") r.push({ name: h.lname, value: h.rawValue.trim() }); });
341
+ return r;
342
+ }
343
+
344
+ // RFC 9788 sec. 4.10 backward compatibility: identify + surface a LEGACY RFC8551HP message -- a Cryptographic
345
+ // Envelope whose payload is a bare message/rfc822 object carrying the real headers, with NO hp= parameter. This
346
+ // is DETECT-ONLY (sec. 4.10: "An MUA MUST NOT generate an RFC8551HP message ... MAY try to render") and OPT-IN
347
+ // (`enabled`). Identification (sec. 4.10.1) is the four conjunctive conditions C1-C4; every failure -- an
348
+ // unparseable inner message, a non-message/rfc822 payload, a nested Cryptographic Layer, an hp= on part D, or an
349
+ // ambiguous/empty protected set -- fails SOFT to none (never throws), because the message is not PRECISELY
350
+ // identified. On identification (sec. 4.10.2) the inner message's (part D's) Non-Structural fields are surfaced,
351
+ // the mode is inferred from the envelope (clear for signed, cipher for encrypted), and the confidential set is
352
+ // derived from the actual outer section (part A). CRUCIAL: a legacy RFC8551HP message is structurally
353
+ // INDISTINGUISHABLE from an ordinary signed/forwarded message/rfc822 (sec. 4.10.2: the inference is "not based
354
+ // on any strong end-to-end guarantees"), so the inferred set is NEVER placed in `protectedHeaders` and NEVER
355
+ // sets `present:true` -- those describe only cryptographically-declared hp= protection a caller may trust. The
356
+ // inference is surfaced ONLY under `headerProtection.legacy` (its own { headers, mode, fromMismatch, confidential }
357
+ // object), so a caller keying trust off `present` / `protectedHeaders` can never mistake an opted-in heuristic --
358
+ // possibly a forwarded attachment -- for this message's authenticated headers; consuming it is an explicit choice.
359
+ function _legacyHpSurface(canon, outerEnt, mode, enabled) {
360
+ if (!enabled) return _noneSurface();
361
+ var partC, partD;
362
+ try {
363
+ // C1 (outermost object is a Cryptographic Layer) holds by construction: _hpSurface only reaches here after a
364
+ // successful, AUTHENTICATED verify/decrypt. C2: the Cryptographic Payload must be a SINGLE message/rfc822 object.
365
+ partC = mime.parse(canon, SmimeError, "smime/bad-header-protection");
366
+ if (partC.contentType.type !== "message/rfc822") return _noneSurface();
367
+ partD = mime.parse(partC.body, SmimeError, "smime/bad-header-protection");
368
+ } catch (_e) { return _noneSurface(); } // an unparseable legacy candidate is not precisely identified -- fail soft
369
+ // The C2-C4 classification reads only the FIRST Content-Type of each part (mime.parse surfaces that one). A
370
+ // duplicate Content-Type on part C or part D is ambiguous -- a later field could carry hp= or a Cryptographic
371
+ // Layer media type the checks below would miss -- so fail soft, matching the standard path's duplicate reject.
372
+ if (_contentTypeCount(partC.headers) > 1 || _contentTypeCount(partD.headers) > 1) return _noneSurface();
373
+ // C4: an hp= on part D means the message is NOT legacy (sec. 4.1: a consumer MUST ignore hp outside the payload
374
+ // root). C3: part D must not itself be a Cryptographic Layer (a genuinely nested signed/encrypted message).
375
+ if (mime.hasParam(partD.contentType.value, "hp")) return _noneSurface();
376
+ if (_isCryptoLayer(partD.contentType.type)) return _noneSurface();
377
+ var ex = _extractProtected(partD.headers);
378
+ // Only a duplicate SINGLETON field (RFC 5322 sec. 3.6) is the ambiguous case -- part D is an ordinary received
379
+ // message whose trace fields (Received, ...) and other repeatable fields legitimately recur, so a repeatable
380
+ // duplicate must NOT reject the inference (else legacy detection fails on essentially all delivered mail).
381
+ if (ex.dupSingleton) return _noneSurface();
382
+ if (!ex.entries.length) return _noneSurface(); // no Non-Structural fields -- nothing to surface
383
+ var confidential = mode === "cipher" ? _computeConfidential(ex.entries, _outerRefouter(outerEnt)) : [];
384
+ // present stays false + protectedHeaders stays null: the inferred set is surfaced ONLY under `legacy` so a
385
+ // caller cannot mistake an opt-in heuristic (indistinguishable from a forwarded message/rfc822) for authenticated
386
+ // headers. `headers` is the ORDERED [{ name, value }] list (every occurrence -- a real message repeats trace
387
+ // fields); the internal `raw` per occurrence is dropped from the public shape.
388
+ var headers = ex.entries.map(function (e) { return { name: e.name, value: e.value }; });
389
+ return { protectedHeaders: null, headerProtection: { present: false, mode: null, fromMismatch: false, confidential: [], legacy: { headers: headers, mode: mode, fromMismatch: _computeFromMismatch(ex.innerFrom, outerEnt), confidential: confidential } } };
390
+ }
391
+
231
392
  // Detect + surface RFC 9788 header protection on a recovered inner entity, FAIL-CLOSED. A payload that does
232
- // not declare hp surfaces protectedHeaders:null. A payload that DECLARES hp is validated: a malformed block,
233
- // an invalid hp value, or an hp mode that CONTRADICTS the cryptographic envelope (expectedMode "clear" for a
234
- // signed message, "cipher" for a decrypted one) throws smime/bad-header-protection -- never a silent
235
- // downgrade. Otherwise the inline Non-Structural fields ARE the authenticated set; a From that differs from
236
- // the untrusted OUTER From is flagged fromMismatch.
237
- function _hpSurface(content, outerEnt, expectedMode, authenticated) {
238
- var none = { protectedHeaders: null, headerProtection: { present: false, mode: null, fromMismatch: false, confidential: [] } };
393
+ // not declare hp surfaces protectedHeaders:null -- UNLESS opts.legacyHeaderProtection is set and it is a legacy
394
+ // RFC8551HP message/rfc822 wrap (sec. 4.10), which _legacyHpSurface then surfaces (opt-in, fail-soft). A payload
395
+ // that DECLARES hp is validated: a malformed block, an invalid hp value, or an hp mode that CONTRADICTS the
396
+ // cryptographic envelope (expectedMode "clear" for a signed message, "cipher" for a decrypted one) throws
397
+ // smime/bad-header-protection -- never a silent downgrade. Otherwise the inline Non-Structural fields ARE the
398
+ // authenticated set; a From that differs from the untrusted OUTER From is flagged fromMismatch.
399
+ function _hpSurface(content, outerEnt, expectedMode, authenticated, legacyEnabled) {
239
400
  // Header protection is an AUTHENTICATED property: surface the inner headers as protected ONLY when the
240
401
  // cryptographic verdict succeeded (a valid signature, or an authenticated-encryption decrypt). An invalid
241
402
  // signature or an unauthenticated (AES-CBC, no integrity) decrypt yields attacker-influenced bytes -- they
242
403
  // are never marked or exposed as protected (a caller must not treat protectedHeaders as a trust signal
243
404
  // unless integrity held).
244
- if (!authenticated) return none;
405
+ if (!authenticated) return _noneSurface();
245
406
  // Detect + parse the CANONICAL entity -- the exact bytes the signature covers. A transport may rewrite a
246
407
  // CRLF fold OR the header/body separator to bare CR/LF; canonicalize repairs them (so verification still
247
408
  // succeeds), and BOTH the hp detection and the parse must run on the repaired bytes, or they diverge from
248
409
  // the signed content -- stripping the signal, or false-rejecting a valid message as an unparseable block.
249
410
  // The returned `content` stays the raw recovered bytes; only this HP inspection uses the canonical copy.
250
411
  var canon = mime.canonicalizeText(content);
251
- if (!_declaresHp(canon)) return none;
412
+ // A payload that does not declare hp is either non-protected (protectedHeaders:null) or a legacy RFC8551HP
413
+ // message/rfc822 wrap the caller opted into detecting (sec. 4.10). Both are mutually exclusive with the
414
+ // standard path below by construction: it runs ONLY when a real hp= is present on the payload root.
415
+ if (!_declaresHp(canon)) return _legacyHpSurface(canon, outerEnt, expectedMode, legacyEnabled);
252
416
  var inner = mime.parse(canon, SmimeError, "smime/bad-header-protection"); // a malformed HP block fails closed
253
417
  // A duplicate Content-Type makes the hp declaration ambiguous (a parser reads params from the FIRST field,
254
418
  // but an hp= may sit on a later one) -- a malformed wrap that fails closed, never a silent downgrade.
255
- var ctCount = 0;
256
- inner.headers.forEach(function (h) { if (h.lname === "content-type") ctCount++; });
419
+ var ctCount = _contentTypeCount(inner.headers);
257
420
  if (ctCount > 1) throw _err("smime/bad-header-protection", "a header-protected payload must carry exactly one Content-Type field (found " + ctCount + ")");
258
421
  // A duplicate hp attribute is ambiguous (mime.parse keeps the LAST value, but a recipient honoring the
259
422
  // first would see a different mode) -- fail closed, like the duplicate Content-Type. Counted by attribute
@@ -275,58 +438,14 @@ function _hpSurface(content, outerEnt, expectedMode, authenticated) {
275
438
  var hp = raw.toLowerCase();
276
439
  if (hp !== "clear" && hp !== "cipher") throw _err("smime/bad-header-protection", "the header-protected payload declares an invalid hp value " + JSON.stringify(raw) + " (only clear / cipher)");
277
440
  if (hp !== expectedMode) throw _err("smime/bad-header-protection", "the payload hp=" + JSON.stringify(hp) + " contradicts the cryptographic envelope (a " + (expectedMode === "cipher" ? "decrypted" : "signed") + " message requires hp=" + JSON.stringify(expectedMode) + ")");
278
- // mime.parse decodes the header block as latin1 (byte-preserving), so a protected value emitted as UTF-8
279
- // (RFC 6532, the guard permits it) is re-decoded latin1->UTF-8 here to round-trip intact. protectedHeaders
280
- // surfaces the exact authenticated field body (rawValue: leading/trailing whitespace preserved), NOT a
281
- // trimmed value that would diverge from the signed octets.
282
- var protectedHeaders = Object.create(null), protectedRaw = Object.create(null), innerFrom = null, seen = Object.create(null), dup = null;
283
- var refouter = []; // RFC 9788 sec. 4.2.1: the HP-Outer records (name + the value the field had in the outer section)
284
- inner.headers.forEach(function (h) {
285
- if (_isStructural(h.lname)) return;
286
- if (h.lname === "hp-outer") {
287
- // RFC 9788 sec. 4.2.1 step 4.i: split the HP-Outer value on the FIRST colon into (name, outer-value)
288
- // -> refouter. The value is kept BYTE-PRESERVING (latin1), never UTF-8-decoded, because the sec. 4.3.1
289
- // confidentiality comparison must be octet-exact (a lossy decode maps distinct invalid octets 0x80/0x81
290
- // to one replacement char, which would mis-classify an obscured field as exposed and drop it from the
291
- // confidential set). HP-Outer is NEVER surfaced as a protected header nor counted toward the duplicate
292
- // check (sec. 2.2: it "can appear multiple times"). A valueless HP-Outer (no inner colon) is ignored.
293
- var ci = h.rawValue.indexOf(":");
294
- if (ci >= 0) refouter.push({ name: h.rawValue.slice(0, ci).trim().toLowerCase(), value: h.rawValue.slice(ci + 1).trim() });
295
- return;
296
- }
297
- if (seen[h.lname]) dup = h.name;
298
- seen[h.lname] = 1;
299
- protectedHeaders[h.name] = _utf8Header(h.rawValue); // SURFACE the exact authenticated field body (RFC 6532 UTF-8)
300
- protectedRaw[h.name] = h.rawValue; // ...but retain the BYTE-PRESERVING (latin1) body for the octet-exact confidentiality comparison
301
- // ...and for the mismatch comparison: a lossy UTF-8 decode maps distinct invalid 8-bit sequences (0x80 vs
302
- // 0x81) to the same replacement char, which would let an attacker alter the displayed From without
303
- // tripping fromMismatch. Compare the raw octets instead.
304
- if (h.lname === "from") innerFrom = h.value;
305
- });
441
+ var ex = _extractProtected(inner.headers);
306
442
  // A duplicate protected field is ambiguous (the last-wins overwrite hides an earlier value a different
307
443
  // parser might select) -- fail closed rather than surface an ambiguous authenticated set.
308
- if (dup) throw _err("smime/bad-header-protection", "a header-protected payload has a duplicate protected header field " + JSON.stringify(dup));
309
- // RFC 9788 sec. 4.3.1: for an ENCRYPTED payload (hp="cipher"), a protected field is end-to-end confidential
310
- // (encrypted-only) unless an HP-Outer record carries its EXACT name + value -- i.e. it was copied verbatim
311
- // to the visible outer section. A field with no matching HP-Outer (removed, or obscured to a different outer
312
- // value) was made confidential. This authenticated set lets a caller reply/forward without leaking it
313
- // (sec. 6.1). Signed-only (clear) payloads carry no HP-Outer, so nothing is confidential.
314
- var confidential = [];
315
- if (hp === "cipher") {
316
- Object.keys(protectedHeaders).forEach(function (name) {
317
- var ln = name.toLowerCase(), val = protectedRaw[name].trim(), exposed = false; // octet-exact (latin1), not lossy-decoded
318
- for (var i = 0; i < refouter.length; i++) { if (refouter[i].name === ln && refouter[i].value === val) { exposed = true; break; } }
319
- if (!exposed) confidential.push(name);
320
- });
321
- }
322
- // Inspect EVERY outer From (outerEnt.header returns only the FIRST; an attacker may append a second, forged
323
- // From that a MUA displays) -- a duplicate outer From, or any that disagrees with the protected From, is flagged.
324
- var outerFroms = [];
325
- outerEnt.headers.forEach(function (h) { if (h.lname === "from") outerFroms.push(h.value.trim()); }); // byte-preserving (latin1), compared octet-for-octet against the protected From
326
- // A mismatch is ANYTHING but exactly one outer From equal to the protected one: a removed outer From (a
327
- // transport/attacker strips it), a duplicate, or a differing value all flag tampering of the displayed sender.
328
- var fromMismatch = innerFrom != null && (outerFroms.length !== 1 || outerFroms[0] !== innerFrom.trim());
329
- return { protectedHeaders: protectedHeaders, headerProtection: { present: true, mode: hp, fromMismatch: fromMismatch, confidential: confidential } };
444
+ if (ex.dup) throw _err("smime/bad-header-protection", "a header-protected payload has a duplicate protected header field " + JSON.stringify(ex.dup));
445
+ // RFC 9788 sec. 4.3.1: for an ENCRYPTED payload (hp="cipher") the confidential set is the fields not copied
446
+ // verbatim to the outer section via an HP-Outer record. Signed-only (clear) payloads carry no HP-Outer.
447
+ var confidential = hp === "cipher" ? _computeConfidential(ex.entries, ex.refouter) : [];
448
+ return { protectedHeaders: ex.protectedHeaders, headerProtection: { present: true, mode: hp, fromMismatch: _computeFromMismatch(ex.innerFrom, outerEnt), confidential: confidential, legacy: null } };
330
449
  }
331
450
 
332
451
  // Map smime opts to cms.sign opts (the S/MIME layer is algorithm-agnostic -- it forwards any signer).
@@ -459,15 +578,22 @@ function _capped(msg) {
459
578
  * chaining a signer certificate to a trust anchor is the caller's `pki.path.validate` step. A `micalg`
460
579
  * that disagrees with the actual digest is advisory unless `opts.strictMicalg` (then `smime/micalg-mismatch`).
461
580
  * If the message is header-protected (RFC 9788), `protectedHeaders` is the AUTHENTICATED inner header set (a
462
- * tampered outer header cannot alter it) and `headerProtection` is `{ present, mode, fromMismatch, confidential }`
463
- * -- `fromMismatch` flags an outer From differing from the protected one; `confidential` lists the protected
464
- * fields the composer kept end-to-end confidential (per the authenticated HP-Outer records, RFC 9788 sec. 4.3;
465
- * only populated for an encrypted `hp="cipher"` payload). A non-protected message reports `protectedHeaders: null`.
466
- * A payload whose declared `hp` is malformed, invalid, or contradicts the envelope fails closed
467
- * (`smime/bad-header-protection`), never a silent downgrade.
581
+ * tampered outer header cannot alter it) and `headerProtection` is `{ present, mode, fromMismatch, confidential, legacy }`
582
+ * -- `present` is `true` only for cryptographically-DECLARED (`hp=`) protection you may trust; `fromMismatch` flags
583
+ * an outer From differing from the protected one; `confidential` lists the protected fields the composer kept
584
+ * end-to-end confidential (per the authenticated HP-Outer records, RFC 9788 sec. 4.3; only for an encrypted
585
+ * `hp="cipher"` payload). A non-protected message reports `protectedHeaders: null`, `present: false`. A payload
586
+ * whose declared `hp` is malformed, invalid, or contradicts the envelope fails closed (`smime/bad-header-protection`),
587
+ * never a silent downgrade. `legacy` is `null` unless `opts.legacyHeaderProtection` detected a legacy RFC 8551
588
+ * `message/rfc822` wrap (see that option), in which case it is its own `{ headers, mode, fromMismatch, confidential }`
589
+ * object (`headers` an ordered `[{ name, value }]` array that retains legally-repeated fields like `Received`) -- a
590
+ * legacy inference is NEVER placed in `protectedHeaders` and never sets `present: true`, because it is
591
+ * indistinguishable from an ordinary forwarded `message/rfc822`, so a caller keying trust off `present` /
592
+ * `protectedHeaders` cannot mistake the opt-in heuristic for authenticated headers.
468
593
  *
469
594
  * @opts certs extra signer certificates (DER `Buffer`s) to match, forwarded to `cms.verify`.
470
595
  * @opts strictMicalg reject a `multipart/signed` whose `micalg` disagrees with the SignerInfo digest.
596
+ * @opts legacyHeaderProtection opt in to detecting a LEGACY RFC 8551 header-protected message (RFC 9788 sec. 4.10): a Cryptographic Payload that is a bare `message/rfc822` wrap with no `hp=` parameter. When set, a precisely-identified legacy message surfaces the inner message's headers under `headerProtection.legacy = { headers, mode, fromMismatch, confidential }` -- `headers` an ordered `[{ name, value }]` array (retaining legally-repeated fields such as `Received`), the mode inferred from the envelope (`clear` here) -- NOT under `protectedHeaders`, and `present` stays `false`. Consuming `headerProtection.legacy.headers` is an explicit choice: a legacy message is structurally indistinguishable from an ordinary forwarded `message/rfc822`, so this is a heuristic (RFC 9788 sec. 4.10.2: "not based on any strong end-to-end guarantees") -- cross-check `legacy.fromMismatch`. Anything not precisely identified (a nested crypto layer, an `hp=` on the inner message, a non-`message/rfc822` payload, a duplicate of a singleton field, or a duplicate Content-Type) reports `legacy: null`. Off by default. The signed-and-encrypted form (RFC 9788 Appendix C.3.17) is a documented gap (`legacy: null` at `decrypt`; surfaces as `clear` only via the caller's re-`verify` step) -- the non-recursive layered API exposes no single seam holding both the inner signature verdict and the outer header section.
471
597
  * @example
472
598
  * var res = await pki.smime.verify(smimeMessageBytes);
473
599
  * if (res.valid) { res.content; res.signers[0].sid; }
@@ -485,7 +611,7 @@ async function verify(message, opts) {
485
611
  var inner;
486
612
  try { inner = _toBuf(schemaCms.parse(p7m).encapContentInfo.eContent); }
487
613
  catch (e) { throw _err("smime/bad-mime", "the pkcs7-mime SignedData has no encapsulated content", e); }
488
- return Object.assign({ valid: res.valid, signers: res.signers, form: "pkcs7-mime", content: inner, micalg: null }, _hpSurface(inner, ent, "clear", res.valid));
614
+ return Object.assign({ valid: res.valid, signers: res.signers, form: "pkcs7-mime", content: inner, micalg: null }, _hpSurface(inner, ent, "clear", res.valid, opts.legacyHeaderProtection === true));
489
615
  }
490
616
  if (ct.type === "multipart/signed") {
491
617
  if (ct.params.protocol && !_isPkcs7(ct.params.protocol, "signature")) throw _err("smime/bad-multipart", "multipart/signed protocol must be application/pkcs7-signature");
@@ -512,7 +638,7 @@ async function verify(message, opts) {
512
638
  if (opts.strictMicalg && micalg && _micalgSet(micalg) !== (_micalgOf(p7s) || "")) {
513
639
  throw _err("smime/micalg-mismatch", "the multipart/signed micalg " + JSON.stringify(micalg) + " disagrees with the SignerInfo digests");
514
640
  }
515
- return Object.assign({ valid: res2.valid, signers: res2.signers, form: "multipart/signed", content: parts[0], micalg: micalg }, _hpSurface(parts[0], ent, "clear", res2.valid));
641
+ return Object.assign({ valid: res2.valid, signers: res2.signers, form: "multipart/signed", content: parts[0], micalg: micalg }, _hpSurface(parts[0], ent, "clear", res2.valid, opts.legacyHeaderProtection === true));
516
642
  }
517
643
  throw _err("smime/unsupported-type", "not a signed S/MIME message (Content-Type " + JSON.stringify(ct.type) + ")");
518
644
  }
@@ -624,14 +750,18 @@ async function encrypt(content, recipients, opts) {
624
750
  * returned as-is for the caller to feed back to `pki.smime.verify` (no auto-recursion). Accepts OpenSSL's
625
751
  * legacy `application/x-pkcs7-mime` and a missing `smime-type`. If the decrypted payload is header-protected
626
752
  * (RFC 9788, `hp="cipher"`), `protectedHeaders` is the recovered REAL inner header set (the values the outer
627
- * Header Confidentiality Policy hid) and `headerProtection` is `{ present, mode, fromMismatch, confidential }`,
628
- * where `confidential` names the fields the composer kept end-to-end confidential (via the authenticated
629
- * HP-Outer records, RFC 9788 sec. 4.3) -- so a caller can reply/forward without leaking them (sec. 6.1); a
630
- * payload whose `hp` is malformed or contradicts the envelope fails closed (`smime/bad-header-protection`).
753
+ * Header Confidentiality Policy hid) and `headerProtection` is `{ present, mode, fromMismatch, confidential, legacy }`,
754
+ * where `present` is `true` only for a declared `hp=` payload, and `confidential` names the fields the composer
755
+ * kept end-to-end confidential (via the authenticated HP-Outer records, RFC 9788 sec. 4.3) -- so a caller can
756
+ * reply/forward without leaking them (sec. 6.1); a payload whose `hp` is malformed or contradicts the envelope
757
+ * fails closed (`smime/bad-header-protection`). `legacy` is `null` unless `opts.legacyHeaderProtection` detected a
758
+ * legacy RFC 8551 `message/rfc822` wrap (its own `{ headers, mode, fromMismatch, confidential }` object -- `headers`
759
+ * an ordered `[{ name, value }]` array -- never merged into `protectedHeaders` / `present`).
631
760
  *
632
761
  * @opts recipientIndex forwarded to cms.decrypt: explicitly select the recipient by index.
633
762
  * @opts maxIterations forwarded to cms.decrypt: lower the PBKDF2 iteration cap (downward only).
634
763
  * @opts strictSmimeType reject a header `smime-type` that disagrees with the CMS body (`smime/smime-type-mismatch`).
764
+ * @opts legacyHeaderProtection opt in to detecting a LEGACY RFC 8551 header-protected message (RFC 9788 sec. 4.10): an encrypted Cryptographic Payload that is a bare `message/rfc822` wrap with no `hp=` parameter. When set, a precisely-identified legacy message surfaces the inner headers under `headerProtection.legacy = { headers, mode: "cipher", fromMismatch, confidential }` -- `headers` an ordered `[{ name, value }]` array (retaining repeated fields), the `confidential` set derived from the actual visible outer Header Section -- NOT under `protectedHeaders`, and `present` stays `false`, since a legacy message is structurally indistinguishable from a forwarded `message/rfc822` (a heuristic; cross-check `legacy.fromMismatch`). Anything not precisely identified reports `legacy: null`. Off by default.
635
765
  * @example
636
766
  * var res = await pki.smime.decrypt(smimeMessageBytes, { key: recipientKeyPkcs8, cert: recipientCertDer });
637
767
  * res.content; // the recovered inner MIME entity
@@ -658,7 +788,7 @@ async function decrypt(message, keyMaterial, opts) {
658
788
  content: res.content, smimeType: smimeType, authenticated: res.authenticated,
659
789
  recipientType: res.recipientType, recipientIndex: res.recipientIndex,
660
790
  contentEncryptionAlgorithm: res.contentEncryptionAlgorithm,
661
- }, _hpSurface(res.content, ent, "cipher", res.authenticated));
791
+ }, _hpSurface(res.content, ent, "cipher", res.authenticated, opts.legacyHeaderProtection === true));
662
792
  }
663
793
 
664
794
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.3.23",
3
+ "version": "0.3.24",
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:e6deeec3-0517-4316-9e40-caa107241321",
5
+ "serialNumber": "urn:uuid:342eb0a5-bbfa-46f5-9b51-912a21d97f53",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-07-26T18:13:45.078Z",
8
+ "timestamp": "2026-07-26T21:06:05.598Z",
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.3.23",
22
+ "bom-ref": "@blamejs/pki@0.3.24",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.3.23",
25
+ "version": "0.3.24",
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.3.23",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.3.24",
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.3.23",
57
+ "ref": "@blamejs/pki@0.3.24",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]