@blamejs/pki 0.7.34 → 0.7.35
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 +14 -0
- package/README.md +1 -1
- package/lib/asn1-der.js +53 -12
- package/lib/tsp-sign.js +21 -4
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,20 @@ 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.7.35 — 2026-09-12
|
|
8
|
+
|
|
9
|
+
The timestamp signer refuses a TSA certificate its verifier would refuse, and keeps genTime's fraction of a second.
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- pki.tsp.sign refuses a TSA certificate that does not satisfy RFC 3161 sec. 2.3: exactly one extendedKeyUsage extension, marked critical, naming id-kp-timeStamping alone, and a keyUsage that, when present, allows signing. The refusal carries the code pki.tsp.verify answers for the same certificate (tsp/bad-eku, tsp/eku-not-critical, tsp/eku-not-exclusive, tsp/bad-key-usage), so a TSA operator learns at signing time what a relying party would say.
|
|
14
|
+
- genTime keeps the Date's milliseconds as the sec. 2.4.2 fraction of a second, in the X.690 DER form (a point followed by the digits, trailing zeros omitted, no fraction for a whole second), which pki.schema.tsp.parseToken already read; a whole-second genTime encodes as before. pki.asn1.build.generalizedTime takes { fractional: true } for this form.
|
|
15
|
+
- accuracy given as an object naming none of seconds, millis, micros is refused with tsp/bad-input: sec. 2.4.2 reads an absent field as zero, so an empty Accuracy asserted a zero deviation; omit the option to make no claim.
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- pki.asn1.build.generalizedTime, pki.asn1.build.utcTime and pki.asn1.read.time read a Date's fields through the Date.prototype accessors captured when the module loaded. A getter overridden on the Date instance, or a Date.prototype method replaced after load, no longer changes the encoded time or the Date the reader returns.
|
|
20
|
+
|
|
7
21
|
## v0.7.34 — 2026-09-12
|
|
8
22
|
|
|
9
23
|
The OCSP signer refuses what its own lint grades an error.
|
package/README.md
CHANGED
|
@@ -241,7 +241,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
241
241
|
| `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
|
|
242
242
|
| `pki.cms` | CMS signing, verification, encryption, and compression (RFC 5652). `sign(content, signers, opts)` produces a SignedData (§5), attached or detached, with one or many signers over RSA, RSASSA-PSS, ECDSA, EdDSA, the post-quantum ML-DSA-44/65/87 (RFC 9882) and SLH-DSA (all twelve FIPS 205 sets, RFC 9814), and composite ML-DSA pairing ML-DSA with a traditional RSA, ECDSA, or EdDSA key (accepted only when both components verify, draft-ietf-lamps-cms-composite-sigs). It builds the signed attributes (content-type, message-digest, signing-time) as canonical DER, signs the exact §5.4 preimage, and emits a DER `Buffer` or PEM. The content may also be an async iterable of byte chunks, which signs a large detached payload without holding it in memory: the payload is hashed incrementally under every signer's digest algorithm in one pass, and `verify` accepts the same streamed form as its `content` option. A signer may also be key-only — `{ key, spki, keyIdentifier }` with no certificate — which RFC 5272 §3.2 requires when a Full PKI Request's signer is the key of a certification request that request carries: the signer identifier takes the subjectKeyIdentifier form carrying the identifier the request declares, the signature scheme resolves from the request's own public key, and no certificate is embedded. `verify(input, opts)` parses a SignedData over the strict `pki.schema.cms` codec, locates each SignerInfo's signer certificate by its issuerAndSerialNumber or subjectKeyIdentifier, and checks the signature over the exact §5.4 preimage: with signed attributes present it confirms the message-digest attribute equals the content digest and verifies over the DER re-encoding of the SignedAttributes (the on-wire `[0]` tag replaced by a universal SET OF), and otherwise directly over the content. It returns a per-signer verdict with the matched signer certificate. `valid` and `trusted` are separate claims and neither implies the other: a SignedData carries its own certificates, so `valid` says the signature is sound under one of them and nothing about who signed, while `trusted` says every signer chained to a root named in `opts.trustAnchors`, validated through the same RFC 5280 path engine `pki.path.validate` uses. Without anchors there is nothing to chain to and `trusted` is `false`; anchors that cannot be read throw, rather than reading as untrusted. An unrecognized option is refused rather than ignored. `countersign(cms, signers, opts)` adds a countersignature (§11.4) — a `SignerInfo` over the countersigned SignerInfo's signature value, any signer algorithm, nestable, with the primary bytes preserved so it still verifies — attached as the id-countersignature unsigned attribute; `verify` returns each countersignature's verdict under `signers[i].countersignatures` and every unsigned attribute — including an RFC 3161 timestamp token, attachable via `sign`'s `unsignedAttributes` — under `signers[i].unsignedAttrs`, surfaced unauthenticated. `encrypt(content, recipients, opts)` produces an EnvelopedData, AuthEnvelopedData (AES-GCM, the authenticated default), or EncryptedData, with recipients auto-dispatched off the certificate key to key transport (RSAES-OAEP; v1.5 is never emitted), key agreement (ephemeral-static ECDH over P-256/384/521 with the X9.63 KDF, and X25519/X448 with HKDF), symmetric key wrap, password (PBKDF2 with RFC 3211 PWRI-KEK), or the post-quantum ML-KEM (and composite ML-KEM, draft-lamps-pq-composite-kem) KEMRecipientInfo (RFC 9629/9936), wrapping one fresh content key for every recipient. The content may also be an async iterable of byte chunks, streamed through the AES-GCM or AES-CBC content cipher so a large plaintext is encrypted without being buffered whole; the ciphertext is assembled before the definite-length encryptedContent is emitted, byte-for-byte the buffered form. `decrypt(input, keyMaterial, opts)` recovers the content through the matching arm and returns it with an `authenticated` flag; every secret-dependent failure collapses to one uniform `cms/decrypt-failed` verdict (Bleichenbacher, EFAIL, and password-oracle freedom), and PKCS#1 v1.5 is decrypt-only under the RFC 3218 implicit-rejection countermeasure. With `opts.stream: true` the recovered `content` is an async iterable of plaintext chunks instead of a single Buffer, for a payload too large to hold whole; the authenticated modes (AuthEnvelopedData, AuthenticatedData, AES-GCM) verify integrity before the iterable yields, so a forged message throws before any plaintext is exposed, while a CBC EnvelopedData or EncryptedData yields the plaintext as the cipher produces it. Every key-establishment secret the toolkit allocates is wiped once used, on the failing path as well as the succeeding one: the KEM shared secret and its derived key-encryption key, the raw ECDH / X25519 / X448 agreement secret, a password-derived key-encryption key, and the content-encryption key itself, cleared once the message is complete since all recipients share it. Caller-supplied key material is never written to (best-effort; NIST SP 800-227 §4.2, RFC 9629 §7). `authenticate(content, recipients, opts)` produces an `id-ct-authData` (§9): cleartext content plus an HMAC-SHA-256/384/512 MAC, authenticated but not encrypted, with the fresh MAC key wrapped for every recipient through the same RecipientInfo model. The MAC covers the authenticated attributes (content-type and message-digest) re-tagged to the EXPLICIT SET OF (§9.2), or the content octets directly; `decrypt` recovers the MAC key, recomputes the MAC and independently the message-digest (§9.3), and releases the content only after both pass, with every secret-dependent failure collapsing to the uniform `cms/decrypt-failed`. `compress(content, opts)` and `decompress(input, opts)` produce and consume a CompressedData (RFC 3274; ZLIB, version 0, id-alg-zlibCompress); decompress bounds the uncompressed output at 16 MiB and stops before it is materialized, so a decompression bomb fails closed as `cms/decompress-too-large`. Compression is a size transform with no integrity or confidentiality (RFC 8551 §2.4.5). `certsOnly(certs, opts?)` builds a certs-only certificate-management message (RFC 8551 §3.8): a degenerate SignedData with an empty signerInfos and no eContent that conveys certificates and CRLs without signing anything, `parseCertsOnly(input, opts?)` reads one back to its raw certificate and CRL DER (a CRL-only message is valid here, unlike the cert-required RFC 5272 form that `pki.est.parseCertsOnly` reads), and `isCertsOnly(input)` recognizes one structurally. Fail-closed with typed `cms/*` errors — `sign`, `verify`, `countersign`, `encrypt`, `authenticate`, `decrypt`, `compress`, `decompress`, `certsOnly`, `parseCertsOnly`, `isCertsOnly` |
|
|
243
243
|
| `pki.smime` | S/MIME message assembly, verification, encryption, and compression over the CMS layer (RFC 8551). `sign(content, signers, opts)` wraps a MIME entity in either form: `multipart/signed`, where the content stays readable in any MUA and a detached CMS SignedData rides alongside as `application/pkcs7-signature` with a matching `micalg`, or `application/pkcs7-mime; smime-type=signed-data`, where the whole entity is a base64 CMS SignedData. The signed bytes are the entity's §3.1.1 canonical form with CRLF line endings, and `verify(message, opts)` unwraps both forms and recomputes over the same canonicalizer, so a transport that re-wraps line endings still verifies while a tampered part fails. `encrypt(content, recipients, opts)` envelopes a MIME entity as an opaque `application/pkcs7-mime` message and `decrypt(message, keyMaterial, opts)` opens one, as `smime-type=authEnveloped-data` (AES-GCM, confidentiality and integrity, the default) or `smime-type=enveloped-data` (AES-CBC, confidentiality only, so `decrypt` reports `authenticated: false`, the §3.3 no-integrity caveat). The `smime-type` is derived from the CMS body rather than the header, and decryption is fail-closed and oracle-free. The crypto is entirely `pki.cms.sign` / `verify` / `encrypt` / `decrypt`, so it is algorithm-agnostic: any RSA / RSASSA-PSS / ECDSA / EdDSA / ML-DSA / SLH-DSA signer and any RSA-OAEP / ECDH / X25519 / X448 / AES-KW / PBKDF2 / ML-KEM recipient carries through. As with `cms.verify`, `verify` returns the per-signer verdict plus the recovered content, and `valid` and `trusted` are separate claims: `valid` says the signature is sound under a certificate the message carried, `trusted` says every signer chained to a root named in `opts.trustAnchors`. Anchoring here is validated for email at both ends of the chain — the signer certificate must carry `emailProtection` (RFC 8551 §4.4.4) and the anchor's own trust metadata must permit that purpose, since a root can be distrusted for email while remaining a good TLS root. Override either with `requiredEku` / `checkPurpose`. `compress(content, opts)` and `decompress(message, opts)` add the opaque `application/pkcs7-mime; smime-type=compressed-data; name=smime.p7z` frame (§3.6, RFC 3274), a size transform with no integrity or confidentiality (§2.4.5), bounded against a bomb; the recovered content, which may itself be signed or enveloped, is returned for the caller to re-verify. Header protection (RFC 9788): `sign` and `encrypt` take `opts.protectHeaders`, which inlines the caller's `opts.headers` on the Cryptographic Payload root (its Content-Type gaining `hp="clear"` when signed or `hp="cipher"` when encrypted) so the CMS signature or encryption covers them, defeating a transport that rewrites or reads Subject, From, and the rest. `verify` and `decrypt` surface the authenticated inner set as `protectedHeaders` plus `headerProtection { present, mode, fromMismatch, confidential, legacy }`, so a tampered outer header cannot alter it and `fromMismatch` flags an outer From that disagrees. Encryption applies a Header Confidentiality Policy: the default `hcp_baseline` obscures the outer Subject to `[...]` and removes Comments and Keywords, so the real values live only in the ciphertext, and `decrypt` recovers them. Every emitted header routes through a fail-closed injection guard that rejects a CR, LF, or NUL value and a non-ftext name, and a malformed or contradictory `hp` wrap fails closed as `smime/bad-header-protection` rather than silently downgrading. The CMS crypto is unchanged. Inbound legacy RFC 8551 header protection is recognized opt-in: `verify` and `decrypt` with `opts.legacyHeaderProtection` detect a legacy `message/rfc822`-wrapped payload by the RFC 9788 §4.10.1 four-condition identification and surface the inner headers under `headerProtection.legacy = { headers, mode, fromMismatch, confidential }`, where `headers` is an ordered `[{ name, value }]` array retaining legally repeated fields such as `Received`. Those never appear in `protectedHeaders` and never set `present: true`. Because a legacy message is structurally indistinguishable from an ordinary forwarded `message/rfc822`, this is an explicit heuristic (§4.10.2, "no strong end-to-end guarantees"): a caller keying trust off `present` or `protectedHeaders` is never misled, and only one that explicitly reads `headerProtection.legacy.headers` and cross-checks `legacy.fromMismatch` consumes it. It is off by default, and a nested crypto layer, an inner `hp=`, a non-`message/rfc822` payload, or a duplicate Content-Type reports `legacy: null`. Bidirectionally interoperable with `openssl smime` and `openssl cms`. `buildCertsOnly(certs, opts?)` wraps a `pki.cms.certsOnly` certificate-management message in one `application/pkcs7-mime; smime-type=certs-only; name=smime.p7c` entity, read back by OpenSSL's `pkcs7 -print_certs`. Fail-closed with typed `smime/*` errors — `sign`, `verify`, `encrypt`, `decrypt`, `compress`, `decompress`, `buildCertsOnly` |
|
|
244
|
-
| `pki.tsp` | Time-Stamp Protocol (RFC 3161). `sign(messageImprint, tsa, opts)` produces a TimeStampToken: a CMS SignedData over `pki.cms.sign` whose content is a `TSTInfo` carrying the timestamped message imprint, the TSA policy, a serial number, and `genTime` with optional accuracy, nonce, and ordering, plus the §2.4.2 signing-certificate attribute binding the token to the TSA certificate (SHA-2 imprints, any `pki.cms.sign` TSA key). `request` and `parseRequest` build and parse the TimeStampReq a client sends (imprint, requested policy, nonce, certReq); `response` and `parseResponse` handle the TimeStampResp a TSA returns, either a granted status wrapping a token or a rejection with PKIStatus and failure info, with the §2.4.2 status-to-token coupling enforced in both directions. `verify(token, data, opts)` verifies a token fail-closed: the CMS signature over the exact signed bytes, the message imprint recomputed from the data, the TSTInfo content type, the ESSCertID(V2) binding to the TSA certificate, the §2.3 critical timeStamping-only extendedKeyUsage, the request nonce when used, and, with a trust anchor supplied, full certification-path validation of the TSA certificate at the token's `genTime` — judged under the `timeStamping` purpose, so an anchor's own per-purpose trust metadata reaches the decision rather than sitting inert. It returns `{ valid, trusted, genTime, serialNumber, tstInfo, ... }`, where `trusted` is the separate claim that the authority chained to an anchor you named: without one there is nothing to chain to and it is `false`, which is the distinction a timestamp re-read years later turns on — `sign`, `request`, `parseRequest`, `response`, `parseResponse`, `verify` |
|
|
244
|
+
| `pki.tsp` | Time-Stamp Protocol (RFC 3161). `sign(messageImprint, tsa, opts)` produces a TimeStampToken: a CMS SignedData over `pki.cms.sign` whose content is a `TSTInfo` carrying the timestamped message imprint, the TSA policy, a serial number, and `genTime` with optional accuracy, nonce, and ordering, plus the §2.4.2 signing-certificate attribute binding the token to the TSA certificate (SHA-2 imprints, any `pki.cms.sign` TSA key). 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` |
|
|
245
245
|
| `pki.ocsp` | Online Certificate Status Protocol (RFC 6960), both the responder and relying-party surface. `buildRequest(query, opts)` builds an OCSPRequest for one or more `{ cert, issuer }` pairs, with the CertID hashed under SHA-1 by default per the RFC 5019 lightweight profile or under SHA-2, plus an optional RFC 9654 nonce and an optional requestor signature. `sign(responseData, responder, opts)` produces a signed BasicOCSPResponse over the exact `ResponseData` DER, from the issuing CA directly or a delegated responder, under any `pki.cms.sign` key including the post-quantum ML-DSA and SLH-DSA sets, with `good`, `revoked` (reason and time), or `unknown` per-certificate status, 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 (`signerCerts`, so a key carried under an expired certificate beside its renewal is not hidden behind ordering) with the first one's decoded subject, the full embedded certificate bag (`certs`, including intermediates for path building), and the request's CertIDs; an unsigned request is reported with `signed: false` rather than refused. Transport-free — `buildRequest`, `sign`, `buildErrorResponse`, `verify`, `verifyRequest` |
|
|
246
246
|
| `pki.ct` | Certificate Transparency (RFC 6962). `parseSctList` decodes the `SignedCertificateTimestampList` a certificate or OCSP response carries, 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, and `verifySct` verifies an SCT signature against a log's public key, 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. On the producing side, `encodeSctList` builds the extension value byte for byte as the exact inverse of `parseSctList`, and `signSct` performs a log's signing step. For trust, `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) and decoding the state and temporal-interval constraints; `verifySctWithLogList` resolves the log key from an SCT's log id, enforces the state (usable, qualified, and readonly trusted; retired only before retirement; pending and 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 and an EC P-256 arm, with forgeable-key defenses failing closed), cross-checked against `openssl dgst`. `fetchLogList(opts)` turns that chain into a live client: it GETs the `log_list.json` and its detached `log_list.sig` over `pki.transport`, verifies the detached signature over the raw fetched bytes against a caller-pinned distributor key before parsing, so 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` and `timestamp`. Above the per-SCT layer, `verifySctList` renders a certificate-level verdict over every SCT a certificate carries (§3.3), reporting how many distinct trusted logs verified an SCT (so a duplicated SCT cannot inflate the count) and from how many distinct trusted operators against a caller's CT policy (`minScts` and `minOperators`, both defaulting to the RFC floor of one), where a policy shortfall is a verdict and a per-SCT failure is a recorded row rather than a thrown call; `x509CertEntry` reconstructs the precertificate log entry from a final certificate by removing the SCT-list extension from its TBSCertificate as byte surgery, so its embedded SCTs verify end to end (§3.2). The toolkit bakes in no vendor URL or key, TLS trust is explicit with `rejectUnauthorized` always on, each response is size-capped before the trust chain, and the transport is injectable so the whole path is testable offline — `parseSctList`, `reconstructSignedData`, `verifySct`, `encodeSctList`, `signSct`, `parseLogList`, `verifySctWithLogList`, `verifySctList`, `x509CertEntry`, `verifyLogListSignature`, `fetchLogList` |
|
|
247
247
|
| `pki.merkle` | Merkle-tree proof verification (RFC 6962 / RFC 9162). `leafHash`, `nodeHash`, and `emptyRootHash` build the domain-separated (0x00 leaf, 0x01 node) SHA-256 tree hashes. `verifyInclusion` folds an audit proof back to a root, and `verifyConsistency` reconstructs both the old and new root, which is the append-only guarantee; each is constant-time-compared to a trusted checkpoint root. Fail-closed on bad geometry, sync hashing, transport-free — `leafHash`, `nodeHash`, `emptyRootHash`, `verifyInclusion`, `verifyConsistency` |
|
package/lib/asn1-der.js
CHANGED
|
@@ -25,6 +25,11 @@
|
|
|
25
25
|
* is canonical, each value the `build.*` helpers emit has exactly one
|
|
26
26
|
* valid encoding, byte-identical to any other conformant DER encoder's
|
|
27
27
|
* output, and decoding it reproduces the value it was built from.
|
|
28
|
+
* `build.generalizedTime(date)` emits whole seconds, the RFC 5280 form;
|
|
29
|
+
* `build.generalizedTime(date, { fractional: true })` keeps the Date's
|
|
30
|
+
* milliseconds in the X.690 DER fraction (no trailing zeros, no empty
|
|
31
|
+
* fraction), the form RFC 3161 allows a timestamp's genTime, which
|
|
32
|
+
* `read.time(node, { allowFractional: true })` reads back.
|
|
28
33
|
*
|
|
29
34
|
* @card
|
|
30
35
|
* Strict, fail-closed DER decode / encode with a navigable node tree
|
|
@@ -37,6 +42,18 @@ var guard = require("./guard-all");
|
|
|
37
42
|
var intrinsic = require("./guard-intrinsic");
|
|
38
43
|
var _isArray = intrinsic.isArray;
|
|
39
44
|
var _charCodeAt = intrinsic.uncurry(String.prototype.charCodeAt);
|
|
45
|
+
/** @internal A Date's fields are read through the prototype's own getters, captured at load, so
|
|
46
|
+
* a getter the instance carries or one replaced later cannot change what a time encodes to or
|
|
47
|
+
* what the reader's own Date reports back. */
|
|
48
|
+
var _dateGetUTCFullYear = intrinsic.uncurry(Date.prototype.getUTCFullYear);
|
|
49
|
+
var _dateGetUTCMonth = intrinsic.uncurry(Date.prototype.getUTCMonth);
|
|
50
|
+
var _dateGetUTCDate = intrinsic.uncurry(Date.prototype.getUTCDate);
|
|
51
|
+
var _dateGetUTCHours = intrinsic.uncurry(Date.prototype.getUTCHours);
|
|
52
|
+
var _dateGetUTCMinutes = intrinsic.uncurry(Date.prototype.getUTCMinutes);
|
|
53
|
+
var _dateGetUTCSeconds = intrinsic.uncurry(Date.prototype.getUTCSeconds);
|
|
54
|
+
var _dateGetUTCMilliseconds = intrinsic.uncurry(Date.prototype.getUTCMilliseconds);
|
|
55
|
+
var _dateSetUTCFullYear = intrinsic.uncurry(Date.prototype.setUTCFullYear);
|
|
56
|
+
var _dateSetUTCHours = intrinsic.uncurry(Date.prototype.setUTCHours);
|
|
40
57
|
|
|
41
58
|
var Asn1Error = frameworkError.Asn1Error;
|
|
42
59
|
var OidError = frameworkError.OidError;
|
|
@@ -649,11 +666,11 @@ function readTime(node, opts) {
|
|
|
649
666
|
var sec = t.sec;
|
|
650
667
|
var ms = (node.tagNumber === TAGS.GENERALIZED_TIME && t.hasFrac) ? t.ms : 0;
|
|
651
668
|
var d = new Date(0);
|
|
652
|
-
d
|
|
653
|
-
d
|
|
669
|
+
_dateSetUTCFullYear(d, year, month - 1, day);
|
|
670
|
+
_dateSetUTCHours(d, hour, min, sec, ms);
|
|
654
671
|
if (isNaN(guard.time.instantOf(d))) throw new Asn1Error("asn1/bad-time", "unparseable time " + JSON.stringify(s));
|
|
655
|
-
if (d
|
|
656
|
-
d
|
|
672
|
+
if (_dateGetUTCFullYear(d) !== year || _dateGetUTCMonth(d) !== month - 1 || _dateGetUTCDate(d) !== day ||
|
|
673
|
+
_dateGetUTCHours(d) !== hour || _dateGetUTCMinutes(d) !== min || _dateGetUTCSeconds(d) !== sec) {
|
|
657
674
|
throw new Asn1Error("asn1/bad-time", "time component out of range " + JSON.stringify(s));
|
|
658
675
|
}
|
|
659
676
|
return d;
|
|
@@ -800,22 +817,46 @@ function _isNumericString(s) {
|
|
|
800
817
|
|
|
801
818
|
function _fmtTwo(n) { return (n < 10 ? "0" : "") + n; }
|
|
802
819
|
|
|
803
|
-
function _generalizedTimeString(date) {
|
|
804
|
-
var y = date
|
|
820
|
+
function _generalizedTimeString(date, fractional) {
|
|
821
|
+
var y = _dateGetUTCFullYear(date);
|
|
805
822
|
if (y < 0 || y > 9999) throw new Asn1Error("asn1/bad-generalizedtime", "GeneralizedTime year " + y + " outside 0000..9999");
|
|
806
823
|
var yyyy = ("000" + y).slice(-4);
|
|
807
824
|
return yyyy +
|
|
808
|
-
_fmtTwo(date
|
|
809
|
-
_fmtTwo(date
|
|
825
|
+
_fmtTwo(_dateGetUTCMonth(date) + 1) + _fmtTwo(_dateGetUTCDate(date)) +
|
|
826
|
+
_fmtTwo(_dateGetUTCHours(date)) + _fmtTwo(_dateGetUTCMinutes(date)) + _fmtTwo(_dateGetUTCSeconds(date)) +
|
|
827
|
+
(fractional ? _fractionString(_dateGetUTCMilliseconds(date)) : "") + "Z";
|
|
828
|
+
}
|
|
829
|
+
/** @internal X.690 sec. 11.7 as RFC 3161 sec. 2.4.2 restates it for a DER GeneralizedTime: the
|
|
830
|
+
* fraction, when present, follows a point and carries no trailing zeros; a zero fraction and its
|
|
831
|
+
* point are omitted. A Date resolves to milliseconds, so the fraction is at most three digits. */
|
|
832
|
+
function _fractionString(ms) {
|
|
833
|
+
if (ms === 0) return "";
|
|
834
|
+
var digits = (ms < 10 ? "00" : ms < 100 ? "0" : "") + ms;
|
|
835
|
+
var end = digits.length;
|
|
836
|
+
while (end > 0 && _charCodeAt(digits, end - 1) === 0x30) end--;
|
|
837
|
+
var out = ".";
|
|
838
|
+
for (var i = 0; i < end; i++) out += digits[i];
|
|
839
|
+
return out;
|
|
840
|
+
}
|
|
841
|
+
var _GENERALIZED_TIME_OPTS = intrinsic.create(null);
|
|
842
|
+
_GENERALIZED_TIME_OPTS.fractional = 1;
|
|
843
|
+
function _generalizedTimeOptions(opts) {
|
|
844
|
+
if (opts === undefined || opts === null) return false;
|
|
845
|
+
if (typeof opts !== "object") throw new Asn1Error("asn1/bad-generalizedtime", "build.generalizedTime options must be an object");
|
|
846
|
+
guard.identifier.assertKnownKeys(opts, _GENERALIZED_TIME_OPTS, function (code, message) { return new Asn1Error(code, message); },
|
|
847
|
+
"asn1/bad-generalizedtime", "build.generalizedTime has an unknown option ");
|
|
848
|
+
var fractional = opts.fractional;
|
|
849
|
+
if (fractional !== undefined && typeof fractional !== "boolean") throw new Asn1Error("asn1/bad-generalizedtime", "build.generalizedTime fractional must be a boolean");
|
|
850
|
+
return fractional === true;
|
|
810
851
|
}
|
|
811
852
|
|
|
812
853
|
function _utcTimeString(date) {
|
|
813
|
-
var y = date
|
|
854
|
+
var y = _dateGetUTCFullYear(date);
|
|
814
855
|
if (y < 1950 || y > 2049) throw new Asn1Error("asn1/bad-utctime", "UTCTime year " + y + " outside 1950..2049; use GeneralizedTime");
|
|
815
856
|
var yy = y % 100;
|
|
816
857
|
return _fmtTwo(yy) +
|
|
817
|
-
_fmtTwo(date
|
|
818
|
-
_fmtTwo(date
|
|
858
|
+
_fmtTwo(_dateGetUTCMonth(date) + 1) + _fmtTwo(_dateGetUTCDate(date)) +
|
|
859
|
+
_fmtTwo(_dateGetUTCHours(date)) + _fmtTwo(_dateGetUTCMinutes(date)) + _fmtTwo(_dateGetUTCSeconds(date)) + "Z";
|
|
819
860
|
}
|
|
820
861
|
|
|
821
862
|
/**
|
|
@@ -891,7 +932,7 @@ var build = intrinsic.assign(intrinsic.create(null), {
|
|
|
891
932
|
return _universal(TAGS.BMP_STRING, false, out);
|
|
892
933
|
},
|
|
893
934
|
utcTime: function (date) { return _universal(TAGS.UTC_TIME, false, Buffer.from(_utcTimeString(date), "latin1")); },
|
|
894
|
-
generalizedTime: function (date) { return _universal(TAGS.GENERALIZED_TIME, false, Buffer.from(_generalizedTimeString(date), "latin1")); },
|
|
935
|
+
generalizedTime: function (date, opts) { return _universal(TAGS.GENERALIZED_TIME, false, Buffer.from(_generalizedTimeString(date, _generalizedTimeOptions(opts)), "latin1")); },
|
|
895
936
|
sequence: function (children) {
|
|
896
937
|
return encodeConstructed(CLASS_UNIVERSAL, TAGS.SEQUENCE, _asBufferArray(children, "build.sequence"));
|
|
897
938
|
},
|
package/lib/tsp-sign.js
CHANGED
|
@@ -101,13 +101,19 @@ function _signingCertV2(certDer, hashName) {
|
|
|
101
101
|
* timestamp authority's `{ cert, key }` (as `pki.cms.sign` takes them). The token is a CMS
|
|
102
102
|
* SignedData whose content is a `TSTInfo` carrying the imprint, the TSA policy, a serial
|
|
103
103
|
* number, and `genTime`; the RFC 3161 sec. 2.4.2 signing-certificate attribute binding the
|
|
104
|
-
* token to the TSA certificate is attached automatically.
|
|
104
|
+
* token to the TSA certificate is attached automatically. The TSA certificate is held to
|
|
105
|
+
* sec. 2.3 before anything is signed: one critical extendedKeyUsage naming id-kp-timeStamping
|
|
106
|
+
* alone, and a keyUsage, when present, that allows signing; a certificate that fails is refused
|
|
107
|
+
* with the code `pki.tsp.verify` would answer (`tsp/bad-eku`, `tsp/eku-not-critical`,
|
|
108
|
+
* `tsp/eku-not-exclusive`, `tsp/bad-key-usage`).
|
|
105
109
|
*
|
|
106
110
|
* @opts policy REQUIRED -- the TSA policy identifier (an OID name or dotted string).
|
|
107
111
|
* @opts serialNumber REQUIRED -- a unique token serial number (a number or BigInt).
|
|
108
|
-
* @opts genTime The trusted time (a `Date`). Default: now.
|
|
112
|
+
* @opts genTime The trusted time (a `Date`). Default: now. Milliseconds are kept as the
|
|
113
|
+
* sec. 2.4.2 fraction of a second, which `pki.schema.tsp.parseToken` reads back.
|
|
109
114
|
* @opts nonce The request nonce to echo (a number or BigInt), for replay protection.
|
|
110
|
-
* @opts accuracy The genTime +/- accuracy, as `{ seconds?, millis?, micros? }
|
|
115
|
+
* @opts accuracy The genTime +/- accuracy, as `{ seconds?, millis?, micros? }`, naming at
|
|
116
|
+
* least one field; omit it to make no accuracy claim.
|
|
111
117
|
* @opts ordering Whether tokens from this TSA are strictly ordered in time (boolean).
|
|
112
118
|
* @opts certHashAlgorithm The ESSCertIDv2 hash algorithm name. Default `sha256`.
|
|
113
119
|
* @opts digestAlgorithm / pss Passed through to `pki.cms.sign` (the signer digest algorithm, RSA-PSS padding).
|
|
@@ -163,6 +169,12 @@ function _sign(messageImprint, tsa, opts) {
|
|
|
163
169
|
if (opts.serialNumber == null) throw _err("tsp/bad-input", "a timestamp token requires a serialNumber (opts.serialNumber)");
|
|
164
170
|
|
|
165
171
|
var certDer = _certDer(tsa && tsa.cert);
|
|
172
|
+
/** @internal Sec. 2.3 binds the TSA: its certificate carries one critical extendedKeyUsage naming
|
|
173
|
+
* id-kp-timeStamping alone, and a keyUsage, when present, that allows signing. The verifier
|
|
174
|
+
* refuses a token under any other certificate, so the same check runs here, with the same
|
|
175
|
+
* codes, before a token no relying party would accept is signed. */
|
|
176
|
+
var certFault = _checkTsaCertUsage(certDer);
|
|
177
|
+
if (certFault !== true) throw _err(certFault, "the TSA certificate does not satisfy RFC 3161 sec. 2.3 (" + certFault + "): a relying party would refuse every token signed under it");
|
|
166
178
|
var certHashAlg = opts.certHashAlgorithm || "sha256";
|
|
167
179
|
if (!NODE_DIGEST[guard.text.keyOf(certHashAlg)]) throw _err("tsp/unsupported-algorithm", "unsupported certHashAlgorithm " + guard.text.showValue(certHashAlg));
|
|
168
180
|
|
|
@@ -170,7 +182,9 @@ function _sign(messageImprint, tsa, opts) {
|
|
|
170
182
|
if (opts.genTime != null) guard.time.assertEncodable(opts.genTime, _err, "tsp/bad-input", "genTime");
|
|
171
183
|
var genTime = guard.time.isDate(opts.genTime) ? opts.genTime : new Date();
|
|
172
184
|
var serial = guard.range.authoredInteger(opts.serialNumber, _err, "tsp/bad-input", "serialNumber");
|
|
173
|
-
|
|
185
|
+
/** @internal Sec. 2.4.2 lets genTime carry a fraction of a second, which the parser reads, so a
|
|
186
|
+
* Date's milliseconds reach the token rather than being dropped at the encoder. */
|
|
187
|
+
var fields = [b.integer(1n), _policy(opts.policy), imprint, b.integer(serial), b.generalizedTime(genTime, { fractional: true })];
|
|
174
188
|
if (opts.accuracy) guard.list.append(fields,_accuracy(opts.accuracy));
|
|
175
189
|
if (opts.ordering === true) guard.list.append(fields,b.boolean(true));
|
|
176
190
|
if (opts.nonce != null) guard.list.append(fields,b.integer(guard.range.authoredInteger(opts.nonce, _err, "tsp/bad-input", "nonce")));
|
|
@@ -203,6 +217,9 @@ function _accuracy(a) {
|
|
|
203
217
|
}
|
|
204
218
|
if (mil != null) guard.list.append(f,b.contextPrimitive(0, _subMilliBytes(mil, "millis")));
|
|
205
219
|
if (mic != null) guard.list.append(f,b.contextPrimitive(1, _subMilliBytes(mic, "micros")));
|
|
220
|
+
/** @internal Sec. 2.4.2 reads an absent field as zero, so an Accuracy naming none asserts a zero
|
|
221
|
+
* deviation; a caller with no accuracy to state omits the option instead. */
|
|
222
|
+
if (!f.length) throw _err("tsp/bad-input", "accuracy must name at least one of seconds, millis, micros; omit it to make no accuracy claim (RFC 3161 sec. 2.4.2)");
|
|
206
223
|
return b.sequence(f);
|
|
207
224
|
}
|
|
208
225
|
function _subMilliBytes(n, label) {
|
package/package.json
CHANGED
package/sbom.cdx.json
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
|
|
3
3
|
"bomFormat": "CycloneDX",
|
|
4
4
|
"specVersion": "1.5",
|
|
5
|
-
"serialNumber": "urn:uuid:
|
|
5
|
+
"serialNumber": "urn:uuid:ad5ed621-8770-42d9-80be-736cc92092a0",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-09-
|
|
8
|
+
"timestamp": "2026-09-12T11:00:49.561Z",
|
|
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.7.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.7.35",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.7.
|
|
25
|
+
"version": "0.7.35",
|
|
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.7.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/pki@0.7.35",
|
|
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.7.
|
|
57
|
+
"ref": "@blamejs/pki@0.7.35",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|