@blamejs/pki 0.8.51 → 0.8.52

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,28 @@ 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.8.52 — 2026-10-05
8
+
9
+ Stamp a signature with a time-stamping authority's token, verify the stamp beside the signature it covers, and build the signing-certificate attribute a CAdES signature carries.
10
+
11
+ ### Added
12
+
13
+ - `pki.cms.timestampImprint(der, opts?)` returns `{ imprint, signerIndex }` for one signer of a `SignedData`: `imprint` is the `{ hashAlgorithm, hashedMessage }` argument `pki.tsp.request` and `pki.tsp.sign` take, and `signerIndex` the signer it was taken for, which is what `pki.cms.attachTimestamp` is then given. The preimage is the contents octets of that signer's signature OCTET STRING with the tag and length excluded, which is what ETSI EN 319 122-1 clause 5.3 specifies and what RFC 5652 clause 11.4 states for the sibling countersignature. `opts.digestAlgorithm` chooses the digest (`sha256` by default) and `opts.signerIndex` the signer. The digest must be one a timestamp is verified under, so sha256, sha384 and sha512 are admitted and anything else is refused rather than producing an imprint whose token no verifier here would read.
14
+ - `pki.cms.attachTimestamp(der, token, opts?)` attaches an RFC 3161 `TimeStampToken` as the signature-time-stamp unsigned attribute `{ 1 2 840 113549 1 9 16 2 14 }`. It splices rather than re-signs: the encapsulated content and its type, and per signer the version, the signer identifier, the digest algorithm, the signed attributes, the signature algorithm and the signature, plus every embedded certificate and every attribute already present, are preserved byte for byte. Several tokens may be attached, one per authority, each as its own attribute carrying exactly one value. `opts.signerIndex` names the signer, `opts.pem` returns a PEM block.
15
+ - `pki.cms.verify` reports `signatureTimeStamps` on each signer, one row per attached token: `{ valid, trusted, genTime, accuracy, serialNumber, policy, revocationChecked, tsa, signer }`, or `{ valid: false, code, message }` where the token does not hold up. A token that fails does not take the signature's own verdict down, since the signature and the time it was made at are separate claims. Each row's imprint is checked against the signature octets the signer verdict was computed over, and a row is refused when its `genTime` precedes the `signing-time` the signature itself asserts or when the latest instant the token could have been created at falls after the signing certificate's `notAfter`, the half of EN 319 122-1 clause 6.3 requirement m that certificate bytes can decide. That bound is the instant the token names plus the accuracy it states, since RFC 3161 section 2.4.2 makes accuracy a window around `genTime` rather than a point, and it keeps the sub-second fraction a `Date` cannot hold. `timestampTrustAnchors`, `timestampCerts` and `timestampRevocationChecker` are the authority's own trust inputs, named apart from the signer's because anchoring a time-stamping authority is a different decision from anchoring a signer.
16
+ - `pki.cms.verify` reports `cadesBaseline` on each signer, `{ conformant, signingCertificateAttribute, findings, requirementsChecked }`, because a sound signature is not by itself a CAdES signature. The content-type attribute must have value `id-data` (ETSI EN 319 122-1 clause 6.3 requirement f) and the signing certificate must be protected by a `signing-certificate` or `signing-certificate-v2` attribute (clauses 5.2.2.2 and 5.2.2.3). That second requirement is the attribute's claim checked against the certificate the signer resolved to, by the certificate hash and by the issuer and serial where the identifier carries them (RFC 5035 clause 5), not the attribute's presence; a superseded v1 attribute is held to the same claim as the v2 beside it. Each attribute is also held to the digest it binds with, which is what defines the two forms: clause 5.2.2.2 is the attribute using SHA-1 and clause 5.2.2.3 the one using another algorithm, so a v2 identifier binding with SHA-1 is reported against requirement h. Every finding carries the `level` of the requirement it is against and `conformant` answers for the shall-level ones alone, so the two guidance requirements this verdict reads, the issuerSerial field that should not be included (requirement g) and the migration to the v2 form (requirement j), are reported without reading as non-conformance. `requirementsChecked` names the requirements the verdict answered for, so `conformant` is read against that list rather than as a full clause 6.3 audit, and it is reported beside a failed signature rather than withheld.
17
+ - `pki.schema.smime.buildSigningCertificateV2(certs, opts?)` encodes the ESS `SigningCertificateV2` attribute value (RFC 5035 clause 5.4.1) that binds a signature to the certificate that made it, which is what `openssl cms -verify -cades` requires a signature to carry. `opts.hashAlgorithm` selects `sha256` (the default), `sha384` or `sha512`; SHA-1 is refused, since the verifier reads a SHA-1 binding as a weak one. The SHA-256 form omits the DEFAULT algorithm field and the other two emit the identifier with its parameters field absent.
18
+
19
+ ### Changed
20
+
21
+ - `pki.cms.verify` selects the signer certificate an ESS signing-certificate attribute names where several certificates match the SignerInfo's identifier. A `subjectKeyIdentifier` names a key, so two certificates holding that key verify the same signature equally and the certificate reported was whichever matched first, taking with it every decision keyed to it: the validity window, the key usage, and the chain built from it. RFC 5035 clause 5.4 makes the attribute's first identifier the certificate used to verify the signature, which is this question; a named candidate must still verify the signature like any other, and a signature carrying no such attribute resolves as before.
22
+ - `pki.cms.attachTimestamp` refuses a token whose message imprint is a weak digest, and `allowWeakDigests: true` admits it. The verifier refuses such a token by default, so the attach verb holds the same posture rather than writing an attribute whose row would then be refused. An archived token needs the option at both ends.
23
+ - A time-stamp token whose `hashedMessage` is not the output length of the digest it names is refused as `tsp/imprint-length` rather than `tsp/imprint-mismatch`. The two are different faults: the first says the token is malformed, the second that it is well formed and stamps other bytes. A caller matching on the old code for a length fault reads the new one.
24
+
25
+ ### Fixed
26
+
27
+ - The SHA-2 algorithm identifiers `pki.tsp.sign` and `pki.tsp.request` write carried NULL parameters. RFC 5754 section 2 requires an implementation to generate SHA-2 algorithm identifiers with the parameters field absent, which is now what both emit, in the `TSTInfo` message imprint, the `TimeStampReq` message imprint, and the ESS signing-certificate identifier under SHA-384 or SHA-512. Both forms are still accepted on the wire, as that section also requires, and an imprint is matched by the algorithm it names and the digest it carries rather than by the identifier's bytes. The SHA-256 ESS identifier, where the field is the DEFAULT and must be omitted outright, is unchanged.
28
+
7
29
  ## v0.8.51 — 2026-10-05
8
30
 
9
31
  Issue and request the TLS Feature extension, hold a chain to the features its issuer advertises, and read a parsed destination through accessors taken at load.
package/README.md CHANGED
@@ -277,7 +277,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
277
277
  | `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` |
278
278
  | `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579, the latter obsoleted by RFC 9879). `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, a key paired with a certificate (the `{ key, cert }` form, or bags sharing a `localKeyId`) must be the private half of that certificate's public key, 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` |
279
279
  | `pki.pkcs11` | PKCS #11 URIs (RFC 7512), the syntax an operator names a token and an object on it with instead of a file path. `parseUri(uri)` reads one into `{ path, vendorPath, query, vendorQuery }`, each a prototype-less record: the path carries `token`, `manufacturer`, `serial`, `model`, the three `library-*` and three `slot-*` attributes, `object`, `type` and `id`, and the query carries `pin-source`, `pin-value`, `module-name` and `module-path`, with a vendor attribute in either component kept under its own name. A vendor query attribute carries a list of its values, which §2.4 permits to repeat; a vendor path attribute carries one value. `id` is a `Buffer`, since the attribute names bytes rather than text, and `slot-id` and `library-version` are numbers. `formatUri(record)` writes the record back, percent-encoding each value to what its own component admits unencoded and encoding `id` whole with uppercase hexadecimal, so two URIs naming one identifier compare equal. Parsing follows the §2.3 / §2.4 ABNF rather than a general URI reader and is fail-closed: a character the component admits only percent-encoded, a truncated or non-hexadecimal escape, a value that is not valid UTF-8, an attribute repeated where the RFC admits it once, a `type` outside the five the RFC enumerates, a URI carrying both `pin-source` and `pin-value`, and a relative `module-path` are each refused with their own `pkcs11/*` code. Syntax only: nothing here loads a PKCS #11 module or talks to a token — `parseUri`, `formatUri` |
280
- | `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 the PWRI-KEK of RFC 3211, carried forward by RFC 3370), or the post-quantum ML-KEM (and composite ML-KEM, draft-lamps-pq-composite-kem) KEMRecipientInfo (RFC 9629/9936), wrapping one fresh content key for every recipient. The content may also be an async iterable of byte chunks, streamed through the AES-GCM or AES-CBC content cipher so a large plaintext is encrypted without being buffered whole; the ciphertext is assembled before the definite-length encryptedContent is emitted, byte-for-byte the buffered form. `decrypt(input, keyMaterial, opts)` recovers the content through the matching arm and returns it with an `authenticated` flag; every secret-dependent failure collapses to one uniform `cms/decrypt-failed` verdict (Bleichenbacher, EFAIL, and password-oracle freedom), and PKCS#1 v1.5 is decrypt-only under the RFC 3218 implicit-rejection countermeasure. With `opts.stream: true` the recovered `content` is an async iterable of plaintext chunks instead of a single Buffer, for a payload too large to hold whole; the authenticated modes (AuthEnvelopedData, AuthenticatedData, AES-GCM) verify integrity before the iterable yields, so a forged message throws before any plaintext is exposed, while a CBC EnvelopedData or EncryptedData yields the plaintext as the cipher produces it. Every key-establishment secret the toolkit allocates is wiped once used, on the failing path as well as the succeeding one: the KEM shared secret and its derived key-encryption key, the raw ECDH / X25519 / X448 agreement secret, a password-derived key-encryption key, and the content-encryption key itself, cleared once the message is complete since all recipients share it. Caller-supplied key material is never written to (best-effort; NIST SP 800-227 §4.2, RFC 9629 §7). `authenticate(content, recipients, opts)` produces an `id-ct-authData` (§9): cleartext content plus an HMAC-SHA-256/384/512 MAC, authenticated but not encrypted, with the fresh MAC key wrapped for every recipient through the same RecipientInfo model. The MAC covers the authenticated attributes (content-type and message-digest) re-tagged to the EXPLICIT SET OF (§9.2), or the content octets directly; `decrypt` recovers the MAC key, recomputes the MAC and independently the message-digest (§9.3), and releases the content only after both pass, with every secret-dependent failure collapsing to the uniform `cms/decrypt-failed`. `compress(content, opts)` and `decompress(input, opts)` produce and consume a CompressedData (RFC 3274; ZLIB, version 0, id-alg-zlibCompress); decompress bounds the uncompressed output at 16 MiB and stops before it is materialized, so a decompression bomb fails closed as `cms/decompress-too-large`. Compression is a size transform with no integrity or confidentiality (RFC 8551 §2.4.5). `certsOnly(certs, opts?)` builds a certs-only certificate-management message (RFC 8551 §3.8): a degenerate SignedData with an empty signerInfos and no eContent that conveys certificates and CRLs without signing anything, `parseCertsOnly(input, opts?)` reads one back to its raw certificate and CRL DER (a CRL-only message is valid here, unlike the cert-required RFC 5272 form that `pki.est.parseCertsOnly` reads), and `isCertsOnly(input)` recognizes one structurally. Fail-closed with typed `cms/*` errors — `sign`, `verify`, `countersign`, `encrypt`, `authenticate`, `decrypt`, `compress`, `decompress`, `certsOnly`, `parseCertsOnly`, `isCertsOnly` |
280
+ | `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 under `signers[i].unsignedAttrs`, surfaced unauthenticated. The CAdES signature timestamp has verbs of its own: `timestampImprint(der, opts)` returns `{ imprint, signerIndex }`, where `imprint` is the `{ hashAlgorithm, hashedMessage }` argument `pki.tsp.request` takes, the hash of a signer's signature value with neither tag nor length (ETSI EN 319 122-1 clause 5.3), `attachTimestamp(der, token, opts)` splices the returned RFC 3161 token in as the signature-time-stamp unsigned attribute and refuses one whose imprint covers other bytes, and `verify` reports a row per attached token under `signers[i].signatureTimeStamps`, each carrying the generation time, the authority, and what the authority's chain established. A row is refused when its time precedes the signature's own `signing-time` or falls after the signing certificate's `notAfter`. `signers[i].cadesBaseline` reports which CAdES baseline requirements the signature meets. `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 the PWRI-KEK of RFC 3211, carried forward by RFC 3370), or the post-quantum ML-KEM (and composite ML-KEM, draft-lamps-pq-composite-kem) KEMRecipientInfo (RFC 9629/9936), wrapping one fresh content key for every recipient. The content may also be an async iterable of byte chunks, streamed through the AES-GCM or AES-CBC content cipher so a large plaintext is encrypted without being buffered whole; the ciphertext is assembled before the definite-length encryptedContent is emitted, byte-for-byte the buffered form. `decrypt(input, keyMaterial, opts)` recovers the content through the matching arm and returns it with an `authenticated` flag; every secret-dependent failure collapses to one uniform `cms/decrypt-failed` verdict (Bleichenbacher, EFAIL, and password-oracle freedom), and PKCS#1 v1.5 is decrypt-only under the RFC 3218 implicit-rejection countermeasure. With `opts.stream: true` the recovered `content` is an async iterable of plaintext chunks instead of a single Buffer, for a payload too large to hold whole; the authenticated modes (AuthEnvelopedData, AuthenticatedData, AES-GCM) verify integrity before the iterable yields, so a forged message throws before any plaintext is exposed, while a CBC EnvelopedData or EncryptedData yields the plaintext as the cipher produces it. Every key-establishment secret the toolkit allocates is wiped once used, on the failing path as well as the succeeding one: the KEM shared secret and its derived key-encryption key, the raw ECDH / X25519 / X448 agreement secret, a password-derived key-encryption key, and the content-encryption key itself, cleared once the message is complete since all recipients share it. Caller-supplied key material is never written to (best-effort; NIST SP 800-227 §4.2, RFC 9629 §7). `authenticate(content, recipients, opts)` produces an `id-ct-authData` (§9): cleartext content plus an HMAC-SHA-256/384/512 MAC, authenticated but not encrypted, with the fresh MAC key wrapped for every recipient through the same RecipientInfo model. The MAC covers the authenticated attributes (content-type and message-digest) re-tagged to the EXPLICIT SET OF (§9.2), or the content octets directly; `decrypt` recovers the MAC key, recomputes the MAC and independently the message-digest (§9.3), and releases the content only after both pass, with every secret-dependent failure collapsing to the uniform `cms/decrypt-failed`. `compress(content, opts)` and `decompress(input, opts)` produce and consume a CompressedData (RFC 3274; ZLIB, version 0, id-alg-zlibCompress); decompress bounds the uncompressed output at 16 MiB and stops before it is materialized, so a decompression bomb fails closed as `cms/decompress-too-large`. Compression is a size transform with no integrity or confidentiality (RFC 8551 §2.4.5). `certsOnly(certs, opts?)` builds a certs-only certificate-management message (RFC 8551 §3.8): a degenerate SignedData with an empty signerInfos and no eContent that conveys certificates and CRLs without signing anything, `parseCertsOnly(input, opts?)` reads one back to its raw certificate and CRL DER (a CRL-only message is valid here, unlike the cert-required RFC 5272 form that `pki.est.parseCertsOnly` reads), and `isCertsOnly(input)` recognizes one structurally. Fail-closed with typed `cms/*` errors — `sign`, `verify`, `countersign`, `encrypt`, `authenticate`, `decrypt`, `compress`, `decompress`, `certsOnly`, `parseCertsOnly`, `isCertsOnly` |
281
281
  | `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 8550 §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. `sign` refuses a signer certificate a conforming reader would reject: a `keyUsage` extension without `digitalSignature` or `nonRepudiation` (RFC 8550 §4.4.2), or an `extendedKeyUsage` extension without `emailProtection` or `anyExtendedKeyUsage` (§4.4.4); a certificate carrying neither extension signs. Override either with `requiredEku` / `checkPurpose`. `compress(content, opts)` and `decompress(message, opts)` add the opaque `application/pkcs7-mime; smime-type=compressed-data; name=smime.p7z` frame (§3.6, RFC 3274), a size transform with no integrity or confidentiality (§2.4.5), bounded against a bomb; the recovered content, which may itself be signed or enveloped, is returned for the caller to re-verify. Header protection (RFC 9788): `sign` and `encrypt` take `opts.protectHeaders`, which inlines the caller's `opts.headers` on the Cryptographic Payload root (its Content-Type gaining `hp="clear"` when signed or `hp="cipher"` when encrypted) so the CMS signature or encryption covers them, defeating a transport that rewrites or reads Subject, From, and the rest. `verify` and `decrypt` surface the authenticated inner set as `protectedHeaders` plus `headerProtection { present, mode, fromMismatch, confidential, legacy }`, so a tampered outer header cannot alter it and `fromMismatch` flags an outer From that disagrees. Encryption applies a Header Confidentiality Policy: the default `hcp_baseline` obscures the outer Subject to `[...]` and removes Comments and Keywords, so the real values live only in the ciphertext, and `decrypt` recovers them. Every emitted header routes through a fail-closed injection guard that rejects a CR, LF, or NUL value and a non-ftext name, and a malformed or contradictory `hp` wrap fails closed as `smime/bad-header-protection` rather than silently downgrading. The CMS crypto is unchanged. Inbound legacy RFC 8551 header protection is recognized opt-in: `verify` and `decrypt` with `opts.legacyHeaderProtection` detect a legacy `message/rfc822`-wrapped payload by the RFC 9788 §4.10.1 four-condition identification and surface the inner headers under `headerProtection.legacy = { headers, mode, fromMismatch, confidential }`, where `headers` is an ordered `[{ name, value }]` array retaining legally repeated fields such as `Received`. Those never appear in `protectedHeaders` and never set `present: true`. Because a legacy message is structurally indistinguishable from an ordinary forwarded `message/rfc822`, this is an explicit heuristic (§4.10.2, "no strong end-to-end guarantees"): a caller keying trust off `present` or `protectedHeaders` is never misled, and only one that explicitly reads `headerProtection.legacy.headers` and cross-checks `legacy.fromMismatch` consumes it. It is off by default, and a nested crypto layer, an inner `hp=`, a non-`message/rfc822` payload, or a duplicate Content-Type reports `legacy: null`. Bidirectionally interoperable with `openssl smime` and `openssl cms`. `buildCertsOnly(certs, opts?)` wraps a `pki.cms.certsOnly` certificate-management message in one `application/pkcs7-mime; smime-type=certs-only; name=smime.p7c` entity, read back by OpenSSL's `pkcs7 -print_certs`. Fail-closed with typed `smime/*` errors — `sign`, `verify`, `encrypt`, `decrypt`, `compress`, `decompress`, `buildCertsOnly` |
282
282
  | `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). The TSA certificate is held to §2.3 before signing (one critical extendedKeyUsage naming timeStamping alone) with the codes `verify` answers, `genTime` keeps its milliseconds as the §2.4.2 fraction of a second, and an accuracy naming no field is refused. `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` |
283
283
  | `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 (obsoleted by RFC 9919) or under SHA-2, plus an optional RFC 9654 nonce (32 to 128 octets, the requester floor that section sets) and an optional requestor signature, under which the signer certificate's subject is the requestorName unless one is stated (RFC 6960 §4.1.2). `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, and per-response `singleExtensions` naming the §4.4.4 archive cutoff and the §4.4.2 CRL reference as fields, each read back by name by the parser. The signer refuses what its own lint would grade an error: a pre-encoded singleExtension that RFC 6960 places in requests or in responseExtensions, a CRL entry extension carried at the wrong criticality, and CRL references or entry extensions on a non-issued response, which itself places the §4.4.8 extended revoked definition in responseExtensions without being asked. `buildErrorResponse(status)` produces the unsigned §2.3 error (`tryLater`, `unauthorized`, and the rest). `verify(response, opts)` verifies a response fail-closed against the same hardened gates `pki.path.ocspChecker` runs: the CertID binding, responder authorization (the issuing CA, or a CA-issued delegate bearing id-kp-OCSPSigning and id-pkix-ocsp-nocheck and passing the full out-of-path certificate gates), the signature over `tbsResponseDataBytes`, currency against `thisUpdate` and `nextUpdate`, and the request-nonce echo. It returns `{ status: "good" / "revoked" / "unknown", ... }` and never silently accepts. `verifyRequest(request, opts)` is the responder-side inverse of `buildRequest`: it verifies a client's signed request (RFC 6960 §4.1.1) under the requestor certificate the request carries, trying each embedded certificate since the field is unordered, and reports `signed`, `signatureValid`, every certificate whose key verified the signature and whose subject is the `requestorName` the request states (`signerCerts`, so a key carried under an expired certificate beside its renewal is not hidden behind ordering, while a same-key certificate under another name is not the requestor) with the first one's decoded subject, the full embedded certificate bag (`certs`, including intermediates for path building), and the request's CertIDs; the name check is reported as `requestorNamed` (RFC 6960 §4.1.2) and `valid` requires it, a request no verifying certificate names falls back to listing the verifying ones with `valid: false`, and an unsigned request is reported with `signed: false` rather than refused. Transport-free — `buildRequest`, `sign`, `buildErrorResponse`, `verify`, `verifyRequest` |
package/index.js CHANGED
@@ -116,7 +116,8 @@ module.exports = {
116
116
  cms: { verify: cms.verify, sign: cms.sign, countersign: cms.countersign, encrypt: cms.encrypt,
117
117
  authenticate: cms.authenticate, decrypt: cms.decrypt, compress: cms.compress, decompress: cms.decompress,
118
118
  digest: cms.digest, verifyDigest: cms.verifyDigest,
119
- certsOnly: cms.certsOnly, parseCertsOnly: cms.parseCertsOnly, isCertsOnly: cms.isCertsOnly },
119
+ certsOnly: cms.certsOnly, parseCertsOnly: cms.parseCertsOnly, isCertsOnly: cms.isCertsOnly,
120
+ timestampImprint: cms.timestampImprint, attachTimestamp: cms.attachTimestamp },
120
121
  smime: smime,
121
122
  // `cmc` interprets an RFC 5272 Full PKI Response into one terminal verdict;
122
123
  // `pki.schema.cmc` is the decoder underneath it.
package/lib/cms-sign.js CHANGED
@@ -25,6 +25,11 @@ var _promiseResolve = intrinsic.uncurry(intrinsic.promiseResolve);
25
25
  var _promiseAll = intrinsic.uncurry(intrinsic.promiseAll);
26
26
  var pkiBuild = require("./pki-build");
27
27
  var cms = require("./schema-cms");
28
+ var constants = require("./constants");
29
+ /** @internal The RFC 3161 structural layer, for the one thing this module asks of a token: which
30
+ * octets its message imprint claims to cover. `schema-tsp` reaches only the schema modules, so this
31
+ * is not the signing module's own cycle back through `tsp-sign`. */
32
+ var tsp = require("./schema-tsp");
28
33
 
29
34
  var subtle = webcrypto.webcrypto.subtle;
30
35
  var CmsError = frameworkError.CmsError;
@@ -628,8 +633,257 @@ function _countersign(cmsInput, signers, opts) {
628
633
  });
629
634
  }
630
635
 
636
+ /** @internal One Attribute appended to a SignerInfo's `[1] unsignedAttrs`, with every attribute
637
+ * already there kept byte for byte and the SET OF re-sorted. A NEW attribute member rather than a
638
+ * value merged into an existing one of the same type: ETSI EN 319 122-1 clause 5.3 reads "The
639
+ * signature-time-stamp attribute shall contain exactly one component of AttributeValue type", while
640
+ * RFC 5126 clause 6.1.1 has "Several instances of this attribute may occur with an electronic
641
+ * signature, from different TSAs", so n timestamps are n attribute instances each carrying a
642
+ * one-element SET. That is the opposite of the countersignature above, where RFC 5652 clause 11.4
643
+ * puts n signatures in one attribute's values, which is why the two do not share this helper.
644
+ *
645
+ * `build.set` sorts with the same comparison the parser's `derSetOrder` check applies, so the
646
+ * rebuilt SET OF cannot be in an order the reader refuses. The `0x31` to `0xA1` re-tag is sound
647
+ * because both identifiers are a single octet, leaving the length encoding untouched. */
648
+ function _appendUnsignedAttr(siNode, attrDer) {
649
+ var kids = siNode.children;
650
+ var last = kids[kids.length - 1];
651
+ var hasUa = last.tagClass === "context" && last.tagNumber === 1;
652
+ var base = intrinsic.map((hasUa ? intrinsic.arraySlice(kids, 0, kids.length - 1) : kids), function (k) { return k.bytes; });
653
+ var existing = hasUa ? intrinsic.map(last.children, function (a) { return a.bytes; }) : [];
654
+ var setOf = b.set(intrinsic.concat(existing, [attrDer]));
655
+ var wire = intrinsic.bufferFrom(setOf); wire[0] = 0xA1;
656
+ intrinsic.push(base, wire);
657
+ return b.sequence(base);
658
+ }
659
+
660
+ /** @internal The SignerInfo node a verb is targeting, with the index checked against what the message
661
+ * carries rather than against a caller's assertion. */
662
+ function _timestampTarget(der, signerIndex, who) {
663
+ var parsed = cms.parse(der);
664
+ if (!intrinsic.isArray(parsed.signerInfos)) throw _err("cms/bad-input", who + " input is not a CMS SignedData");
665
+ var idx = signerIndex == null ? 0 : signerIndex;
666
+ if (typeof idx !== "number" || !intrinsic.isInteger(idx) || idx < 0 || idx >= parsed.signerInfos.length) {
667
+ throw _err("cms/bad-input", who + " signerIndex out of range: " + guard.text.showValue(signerIndex) +
668
+ " (the message carries " + parsed.signerInfos.length + " signer" + (parsed.signerInfos.length === 1 ? "" : "s") + ")");
669
+ }
670
+ var root = asn1.decode(der);
671
+ var sd = root.children[1].children[0];
672
+ var siSet = sd.children[sd.children.length - 1];
673
+ return { parsed: parsed, root: root, sd: sd, siSet: siSet, idx: idx, siNode: siSet.children[idx] };
674
+ }
675
+
676
+ var KNOWN_IMPRINT_OPTS = intrinsic.assign(intrinsic.create(null), { signerIndex: 1, digestAlgorithm: 1 });
677
+
678
+ /**
679
+ * @primitive pki.cms.timestampImprint
680
+ * @signature pki.cms.timestampImprint(input, opts?) -> Promise<{ imprint, signerIndex }>
681
+ * @since 0.8.52
682
+ * @status stable
683
+ * @spec ETSI EN 319 122-1 clause 5.3, RFC 5126 clause 6.1.1, RFC 3161 clause 2.4.1
684
+ * @related pki.cms.attachTimestamp, pki.tsp.request, pki.tsp.verify, pki.cms.verify
685
+ *
686
+ * The message imprint a time-stamping authority is asked to sign over, for the CAdES
687
+ * signature-time-stamp attribute. EN 319 122-1 clause 5.3 fixes what it covers: "the hash value of
688
+ * the signature field (without the ASN.1 tag and length) within SignerInfo for which the
689
+ * signature-time-stamp attribute is created". So this is a digest of the contents octets of
690
+ * `SignerInfo.signature`, with the tag and length excluded, which is the same octet rule RFC 5652
691
+ * clause 11.4 states for a countersignature.
692
+ *
693
+ * `input` is the SignedData as a DER `Buffer` or a PEM `CMS` string, the same input
694
+ * `pki.cms.countersign` takes and for the same reason: the imprint covers exact octets of the
695
+ * message as it stands, so this reads the wire bytes rather than a representation of them. The
696
+ * result is `{ imprint, signerIndex }`: `imprint` is `{ hashAlgorithm, hashedMessage }`, the
697
+ * argument `pki.tsp.request` and `pki.tsp.sign` take, so a third-party authority can be driven
698
+ * without this package signing anything, and `signerIndex` is the signer it was taken for, which is
699
+ * what `pki.cms.attachTimestamp` is given when the token comes back.
700
+ *
701
+ * @opts signerIndex which signer to take the imprint for (default 0).
702
+ * @opts digestAlgorithm the digest to take (default `"sha256"`). MD5 is refused: EN 319 122-1
703
+ * clause 6.2.1 reads "In addition, MD5 algorithm shall not be used as digest
704
+ * algorithm".
705
+ * @example
706
+ * var pair = await pki.key.generate("Ed25519");
707
+ * var key = await pki.key.export(pair.privateKey);
708
+ * var cert = await pki.x509.sign({ subject: "Signer", subjectPublicKey: await pki.key.export(pair.publicKey),
709
+ * notBefore: new Date("2026-01-01T00:00:00Z"), notAfter: new Date("2036-01-01T00:00:00Z") }, { key: key });
710
+ * var signedDer = await pki.cms.sign(Buffer.from("hello"), { cert: cert, key: key });
711
+ * var taken = await pki.cms.timestampImprint(signedDer);
712
+ * var req = pki.tsp.request(taken.imprint, { certReq: true });
713
+ * taken.imprint.hashAlgorithm; // "sha256"
714
+ */
715
+ function timestampImprint(input, opts) {
716
+ return guard.bytes.fixedCall(CmsError, "cms/bad-input", [
717
+ [input, "the CMS message"], [opts, "pki.cms.timestampImprint options"],
718
+ ], _timestampImprint);
719
+ }
720
+
721
+ function _timestampImprint(input, opts) {
722
+ opts = guard.identifier.optionsObject(opts, _err, "cms/bad-input", "pki.cms.timestampImprint options");
723
+ guard.identifier.assertKnownKeys(opts, KNOWN_IMPRINT_OPTS, _err, "cms/bad-input", "unknown opts field ");
724
+ var name = opts.digestAlgorithm == null ? "sha256" : opts.digestAlgorithm;
725
+ /** @internal MD5 is answered before the build's own digest table, which does not carry it either:
726
+ * asked for by name, it gets the clause that forbids it rather than the generic "this build does
727
+ * not have that digest", which is a different thing to tell an operator. */
728
+ if (name === "md5") throw _err("cms/bad-input", "MD5 shall not be used as a digest algorithm (ETSI EN 319 122-1 clause 6.2.1)");
729
+ /** @internal Admitted against the digests a timestamp VERIFIER reads an imprint under, not the
730
+ * build's general digest table: a digest outside that set produces an imprint whose token every
731
+ * verifier here refuses, so taking one would hand an operator a request for an unusable token. */
732
+ if (typeof name !== "string" || !intrinsic.hasOwn(constants.NAMES.TIMESTAMP_IMPRINT_DIGESTS, name)) {
733
+ throw _err("cms/bad-input", "digestAlgorithm must name a digest a signature timestamp is read " +
734
+ "under (sha256, sha384 or sha512), got " + guard.text.showValue(opts.digestAlgorithm));
735
+ }
736
+ /** @internal A weak digest is refused outright here, with no opt-in beside it. `attachTimestamp`
737
+ * has one because a token that already exists may be archived under a digest that was current
738
+ * when it was made; a token this imprint would be sent for does not exist yet, so the only thing
739
+ * the option could buy is a request for a token this verb's own sibling then refuses. */
740
+ if (intrinsic.hasOwn(constants.NAMES.WEAK_DIGESTS, name)) {
741
+ throw _err("cms/bad-input", "the imprint digest " + name + " is one a signature timestamp is " +
742
+ "refused for, so a token taken over it could not be attached or verified");
743
+ }
744
+ var der = pkix.coerceToDer(input, { pemLabel: null, PemError: frameworkError.PemError, ErrorClass: CmsError, prefix: "cms" });
745
+ var t = _timestampTarget(der, opts.signerIndex, "pki.cms.timestampImprint");
746
+ /** @internal `imprint` is nested rather than spread across the result, so the object this returns
747
+ * is the one `pki.tsp.request` and `pki.tsp.sign` take: their message-imprint door admits
748
+ * `hashAlgorithm` and `hashedMessage` and refuses any other field, which a flat result carrying
749
+ * the signer index would trip. The index is what `pki.cms.attachTimestamp` is then given, so it
750
+ * is reported beside the imprint instead of inside it. */
751
+ return guard.verdict.of({
752
+ imprint: guard.verdict.of({
753
+ hashAlgorithm: name,
754
+ hashedMessage: guard.crypto.digest(name, _signatureOctets(t.siNode)),
755
+ }),
756
+ signerIndex: t.idx,
757
+ });
758
+ }
759
+
760
+ var KNOWN_ATTACH_OPTS = intrinsic.assign(intrinsic.create(null), { signerIndex: 1, pem: 1, allowWeakDigests: 1 });
761
+
762
+ /**
763
+ * @primitive pki.cms.attachTimestamp
764
+ * @signature pki.cms.attachTimestamp(input, token, opts?) -> Promise<Buffer>
765
+ * @since 0.8.52
766
+ * @status stable
767
+ * @spec ETSI EN 319 122-1 clause 5.3, RFC 5126 clause 6.1.1, RFC 3161
768
+ * @related pki.cms.timestampImprint, pki.cms.verify, pki.tsp.sign, pki.cms.countersign
769
+ *
770
+ * Attach an RFC 3161 `TimeStampToken` to a signature as the CAdES signature-time-stamp unsigned
771
+ * attribute `{ 1 2 840 113549 1 9 16 2 14 }`, taking a `SignedData` to the EN 319 122-1 B-T level.
772
+ * `input` is that SignedData as a DER `Buffer` or a PEM `CMS` string and `token` the token a
773
+ * time-stamping authority returned for the imprint `pki.cms.timestampImprint` produced, as DER or
774
+ * PEM. Both are read as wire bytes rather than as a parsed representation, because this verb
775
+ * rewrites the message's own octets.
776
+ *
777
+ * It SPLICES rather than re-signs. Re-signing produces a different signature value, so a token taken
778
+ * over the first one would no longer match it, which is measured and not reasoned: with ECDSA the
779
+ * second signature differs every time. What is preserved byte for byte is therefore everything the
780
+ * four signature inputs cover: the encapsulated content and its type, and per signer the `version`,
781
+ * `sid`, `digestAlgorithm`, `[0] signedAttrs`, `signatureAlgorithm` and `signature` TLVs, plus every
782
+ * embedded certificate, every revocation entry, and every attribute already in `unsignedAttrs`. What
783
+ * is re-encoded is the targeted signer's `[1] unsignedAttrs` SET OF and the five enclosing lengths,
784
+ * none of which appears in any signature input.
785
+ *
786
+ * Several instances may be attached, one per authority, which is what RFC 5126 clause 6.1.1 permits
787
+ * and EN 319 122-1 clause 5.3 shapes: each is its own attribute carrying exactly one value.
788
+ *
789
+ * `signerIndex` names a signer of the INPUT. `signerInfos` is a SET OF, whose members are emitted in
790
+ * DER order, so giving one member an attribute changes its encoding and can change its position:
791
+ * identify a signer of the OUTPUT by its signature value or its certificate, not by the index it
792
+ * held on the way in.
793
+ *
794
+ * The imprint is checked before anything is written, so this verb cannot produce a message its own
795
+ * verifier would reject: the token's imprint must be the hash of the targeted signer's signature
796
+ * value, and its digest must be one the verifier admits. Nothing else about the token is judged
797
+ * here; `pki.cms.verify` does that.
798
+ *
799
+ * @opts signerIndex which signer to attach to (default 0).
800
+ * @opts pem return a PEM `CMS` block rather than DER.
801
+ * @opts allowWeakDigests attach a token whose imprint is a weak digest, which both this verb and
802
+ * `pki.cms.verify` refuse by default. This is the archived-token path, and the
803
+ * same option is needed again at verification.
804
+ * @example
805
+ * var pair = await pki.key.generate("Ed25519");
806
+ * var key = await pki.key.export(pair.privateKey);
807
+ * var spki = await pki.key.export(pair.publicKey);
808
+ * var nb = new Date("2026-01-01T00:00:00Z"), na = new Date("2036-01-01T00:00:00Z");
809
+ * var cert = await pki.x509.sign({ subject: "Signer", subjectPublicKey: spki, notBefore: nb, notAfter: na }, { key: key });
810
+ * // RFC 3161 sec. 2.3: a TSA certificate's extendedKeyUsage MUST be critical and name timeStamping alone
811
+ * var tsaCert = await pki.x509.sign({ subject: "Example TSA", subjectPublicKey: spki, notBefore: nb, notAfter: na,
812
+ * extensions: { keyUsage: ["digitalSignature"], extendedKeyUsage: ["timeStamping"], extendedKeyUsageCritical: true } },
813
+ * { key: key });
814
+ * var signedDer = await pki.cms.sign(Buffer.from("hello"), { cert: cert, key: key });
815
+ * var taken = await pki.cms.timestampImprint(signedDer);
816
+ * var token = await pki.tsp.sign(taken.imprint, { cert: tsaCert, key: key },
817
+ * { policy: "1.3.6.1.4.1.1", serialNumber: 1 });
818
+ * var bT = await pki.cms.attachTimestamp(signedDer, token, { signerIndex: taken.signerIndex });
819
+ * (await pki.cms.verify(bT, { certs: [cert] })).signers[0].signatureTimeStamps[0].valid; // true
820
+ */
821
+ function attachTimestamp(input, token, opts) {
822
+ return guard.async.deferred(function () {
823
+ return guard.bytes.fixedCall(CmsError, "cms/bad-input", [
824
+ [input, "the CMS message"], [token, "the time-stamp token"], [opts, "pki.cms.attachTimestamp options"],
825
+ ], _attachTimestamp);
826
+ });
827
+ }
828
+
829
+ function _attachTimestamp(input, token, opts) {
830
+ opts = guard.identifier.optionsObject(opts, _err, "cms/bad-input", "pki.cms.attachTimestamp options");
831
+ guard.identifier.assertKnownKeys(opts, KNOWN_ATTACH_OPTS, _err, "cms/bad-input", "unknown opts field ");
832
+ var der = pkix.coerceToDer(input, { pemLabel: null, PemError: frameworkError.PemError, ErrorClass: CmsError, prefix: "cms" });
833
+ var tokenDer = pkix.coerceToDer(token, { pemLabel: null, PemError: frameworkError.PemError, ErrorClass: CmsError, prefix: "cms" });
834
+ var t = _timestampTarget(der, opts.signerIndex, "pki.cms.attachTimestamp");
835
+
836
+ /** @internal The imprint is checked HERE, before a byte is written, against the signature this
837
+ * attribute will hang on. A verb that wrote first would produce a message `pki.cms.verify` refuses
838
+ * on the row it just created, and the caller would have no way to tell a mis-addressed token from
839
+ * a corrupt one. The token's own structure, its authority's certificate and its chain are not
840
+ * judged here: those are the verifier's, and judging them twice in two places is two answers. */
841
+ var tst = tsp.parseToken(tokenDer);
842
+ var want = tst.tstInfo.messageImprint;
843
+ var name = want.hashAlgorithm && want.hashAlgorithm.name;
844
+ if (!name || !intrinsic.hasOwn(constants.NAMES.TIMESTAMP_IMPRINT_DIGESTS, name)) {
845
+ throw _err("cms/bad-input", "the token's message imprint names a digest a signature timestamp " +
846
+ "is not read under: " + guard.text.showValue(name || (want.hashAlgorithm && want.hashAlgorithm.oid)));
847
+ }
848
+ /** @internal The identifier is held to its own encoding as well as to its name: a digest
849
+ * AlgorithmIdentifier carries absent or DER NULL parameters (RFC 5754 clause 2), and the ANY
850
+ * field is carried through the parse unvalidated, so one naming sha256 beside arbitrary bytes
851
+ * would otherwise be hashed as a well-formed imprint. */
852
+ if (!guard.der.paramsAbsentOrNull(want.hashAlgorithm.parameters)) {
853
+ throw _err("cms/bad-input", "the token's message imprint algorithm identifier carries " +
854
+ "parameters other than DER NULL, which a digest identifier does not (RFC 5754 clause 2)");
855
+ }
856
+ /** @internal The same digest posture the verifier holds this attribute to, read from the one
857
+ * membership list: a token whose imprint is a weak digest is refused here too, under the option
858
+ * that admits it there, so the verb does not write an attribute whose row `pki.cms.verify` then
859
+ * refuses by default. The imprint carries the whole binding between the token and the signature,
860
+ * and a collision in it substitutes one signature under a genuine token. */
861
+ if (opts.allowWeakDigests !== true && intrinsic.hasOwn(constants.NAMES.WEAK_DIGESTS, name)) {
862
+ throw _err("cms/weak-timestamp-imprint", "the token's message imprint is a " + name + " digest, " +
863
+ "which a signature timestamp is refused for by default; pass allowWeakDigests: true to attach " +
864
+ "an archived token under it");
865
+ }
866
+ var have = guard.crypto.digest(name, _signatureOctets(t.siNode));
867
+ if (!guard.crypto.constantTimeEqual(have, want.hashedMessage)) {
868
+ throw _err("cms/timestamp-imprint-mismatch", "the token's message imprint is not the hash of this " +
869
+ "signer's signature value, so attaching it would produce a signature timestamp that does not " +
870
+ "verify (ETSI EN 319 122-1 clause 5.3)");
871
+ }
872
+
873
+ var attr = b.sequence([b.oid(O("timeStampToken")), b.set([tokenDer])]);
874
+ var newSiSet = b.set(intrinsic.map(t.siSet.children, function (siNode, i) {
875
+ return i === t.idx ? _appendUnsignedAttr(siNode, attr) : siNode.bytes;
876
+ }));
877
+ var sdKids = t.sd.children;
878
+ var newSdFields = intrinsic.map(intrinsic.arraySlice(sdKids, 0, sdKids.length - 1), function (k) { return k.bytes; });
879
+ intrinsic.push(newSdFields, newSiSet);
880
+ var out = b.sequence([t.root.children[0].bytes, b.explicit(0, b.sequence(newSdFields))]);
881
+ return opts.pem ? pkix.pemEncode(out, "CMS", frameworkError.PemError) : out;
882
+ }
883
+
631
884
  module.exports = {
632
885
  sign: sign, countersign: countersign, certsOnly: certsOnly,
886
+ timestampImprint: timestampImprint, attachTimestamp: attachTimestamp,
633
887
  // @internal
634
888
  KNOWN_SIGNER_CERT_KEYS: KNOWN_SIGNER_CERT_KEYS,
635
889
  KNOWN_SIGNER_KEY_ONLY_KEYS: KNOWN_SIGNER_KEY_ONLY_KEYS,