@blamejs/pki 0.6.43 → 0.6.45

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,26 @@ 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.6.45 — 2026-09-06
8
+
9
+ A certification path reaching a certificate signed with a stateful hash-based key validates without a separate call.
10
+
11
+ ### Added
12
+
13
+ - pki.path.validate verifies a certificate signed with the RFC 9802 stateful hash-based algorithm id-alg-hss-lms-hashsig, and pki.crl.verify a certificate revocation list signed with it, which RFC 9802 section 6 provides for alongside the certificate. The signature covers the whole tbsCertificate rather than a digest of it (section 7.1); the RFC 8554 public key is read from the subjectPublicKey BIT STRING and the signature from signatureValue, neither carrying further ASN.1 wrapping (sections 5 and 6); the algorithm identifier carries no parameters; and the subject public key must name the algorithm the signature names, so a certificate advertising one algorithm over a key of another is refused. A key or signature the engine cannot read is a path/bad-signature verdict, never a pass. Every other section 6.1 check is unchanged, so an expired or otherwise faulty HSS certificate fails for the reason it should. A certificate carrying any of the three stateful hash-based keys, HSS, XMSS or XMSS^MT, is also held to the RFC 9802 section 6 key-usage rule whichever algorithm signed it, reported as the hbsKeyUsage check and refused with path/hbs-key-usage: a certification authority's certificate must assert at least one of digitalSignature, nonRepudiation, keyCertSign or cRLSign, an end entity's at least one of digitalSignature, nonRepudiation or cRLSign, and neither may assert any value outside its own list, so a key offered for encryption is refused. An absent keyUsage extension is unrestricted. The end-to-end proof is the self-signed certificate published in RFC 9802 Appendix A, which now validates through pki.path.validate. Signing remains out of scope: a stateful key's one-time state belongs in hardware that owns it.
14
+
15
+ ## v0.6.44 — 2026-09-06
16
+
17
+ An enrollment client reaches a certification authority through a proxy that demands Digest authentication.
18
+
19
+ ### Added
20
+
21
+ - opts.proxy.auth.scheme accepts "digest" alongside "basic", so a client reaches a certification authority through a forward proxy that authenticates with RFC 7616 Digest. The first CONNECT carries no credential; the proxy's 407 carries its Proxy-Authenticate challenge, and the client answers it once, hashing the method CONNECT over the authority-form target (RFC 9112 section 3.2.3) that the proxy checks it against. The challenge is read by the same parser the origin verbs use and held to the same policy, so MD5 and a challenge carrying no qop are refused unless opts.proxy.auth.allowMD5 or allowLegacyQop says otherwise, surfacing transport/proxy-digest-weak-algorithm, transport/proxy-digest-unsupported-algorithm, transport/proxy-digest-no-qop, and transport/proxy-digest-bad-challenge (each under the calling client's own prefix, so a SCEP call reports scep/...). A proxy that offers no Digest challenge while digest is configured is transport/proxy-auth-required naming what it offered, and a rejected credential is transport/proxy-auth-failed after that single answer. Digest requires an https proxy on the same terms as Basic: credentials ride the authenticated channel to the proxy, and a plaintext http proxy carrying auth stays refused with transport/proxy-auth-requires-tls.
22
+
23
+ ### Removed
24
+
25
+ - transport/proxy-unsupported-scheme is no longer raised. It reported that Digest proxy authentication was unavailable, and Digest is now supported; an unknown scheme is transport/bad-proxy, as it was before.
26
+
7
27
  ## v0.6.43 — 2026-09-06
8
28
 
9
29
  Path building finds a path through a mesh of cross-certified domains without walking the foreign branches first.
package/README.md CHANGED
@@ -223,7 +223,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
223
223
  | `pki.schema.csrattrs` | EST CSR Attributes (`CsrAttrs`, RFC 8951 §3.5 / RFC 9908) — the `AttrOrOID` items a server sends to shape an enrollment: bare OIDs, attributes with raw values, and decoded views of the RFC 9908 meaningful types (extension requests, EC and RSA key-type conventions, the certification-request-info template). Unknown types are surfaced raw; structure and the RFC 9908 semantic MUSTs are fail-closed — `parse` |
224
224
  | `pki.est` | Enrollment over Secure Transport (RFC 7030 / 8951 / 9908 / 7616). The client verbs `cacerts`, `simpleenroll`, `simplereenroll`, `serverkeygen`, `csrattrs`, and `fullcmc` drive the RFC 7030 flow over `pki.transport` (inject your own via `opts.transport`, or take the fail-closed default): HTTPS only, an explicit trust anchor required, same-origin redirects followed while a downgrade or loop is refused, a 202 Retry-After surfaced but never slept, HTTP Basic or Digest (RFC 7616, SHA-256 / SHA-512-256; MD5 and no-qop refused by default) answered only after the server is authenticated, and the issued certificate chosen by public-key match. `serverkeygen` requests a server-generated key, cleartext or an opaque CMS EnvelopedData, with encryption bound to the CSR's key-identifier attribute over a confidentiality-bearing cipher. `csrattrs` fetches the CA's RFC 9908 attributes policy. For §3.5 channel binding, `simpleenroll` and `simplereenroll` accept a CSR builder `(tls) -> csr` instead of a CSR: it runs after the handshake with that connection's `tlsUnique`, so the request is signed over the session it is sent on, and it re-runs on any new connection a redirect or auth retry opens, recreating the CSR for that session (§3.2.1). A builder alongside Digest authentication is refused, since that header is computed over the body before the handshake. `fullcmc` (§4.3) carries a CMC Full PKI Request and reduces the CA's answer through `pki.cmc.verify` to one terminal outcome, refusing a response that fails to echo the transaction and nonce the request carried, or that covers a key the request never asked for; a certs-only reply to a bound request is refused rather than read as an issuance. Under the verbs sit the transport-agnostic codecs they compose: the RFC 8951 base64 transfer codec (which ignores Content-Transfer-Encoding), the `multipart/mixed` splitter, the certs-only and serverkeygen response validators over CMS, the enroll-attribute builders, and the HTTP response classifier — `transferDecode`/`transferEncode`, `parseCertsOnly`, `splitMultipartMixed`, `parseServerKeygenResponse`, `findIssuedCert`, `classifyResponse`, `paths`, and the builders |
225
225
  | `pki.scep` | SCEP pkiMessage codec (RFC 8894), the client side of Simple Certificate Enrollment. `build(spec)` assembles a request: a `PKCSReq` or `RenewalReq` wraps a PKCS#10 certification request, whose own proof-of-possession it verifies first; a `CertPoll` wraps an IssuerAndSubject naming the issuing CA and the request subject; and a `GetCert` or `GetCRL` wraps an IssuerAndSerialNumber naming a certificate by its issuer and a positive serial of at most 20 octets. It encrypts the messageData to the CA as the inner EnvelopedData (`pkcsPKIEnvelope`, AES-128-CBC), and signs that under the transaction attributes RFC 8894 §3.2 defines, a messageType, a caller-unique transactionId, and a 16-byte senderNonce. The recipient CA certificate must assert `keyEncipherment`. `build` also issues the CA-side `CertRep` response (§3.3.2): a SUCCESS envelopes a certs-only SignedData of the issued certificate (or the CRL for a GetCRL) to the requester and signs it under the CA key, while a FAILURE (carrying a `failInfo`) or a PENDING omits the pkcsPKIEnvelope and is signed detached, each echoing the request's senderNonce as `recipientNonce`. `parse(bytes, opts?)` reads a `PKCSReq`, `RenewalReq`, `CertPoll`, `GetCert`, `GetCRL`, or `CertRep` back (a messageType outside the RFC 8894 registry is refused): it verifies the outer signature first and refuses a message whose signature does not check, so the transaction attributes it returns come only from a verified signer, never alongside a false verdict. Because a valid signature only proves self-consistency with the embedded certificate, pass `opts.signerCert` to authenticate a CA response against the CA certificate you hold (a public-key mismatch is refused, `signerAuthenticated` reports the result); a caller that omits it gets a crypto-only verdict and must authenticate the surfaced `signerCert` itself. It maps the messageType, pkiStatus, failInfo, and the nonces from their RFC 8894 enumerants and refuses an unknown one; given `recipientKey` it decrypts the `pkcsPKIEnvelope` to the messageData, and given `expectedSenderNonce` it refuses a response whose recipientNonce does not echo it. It reads a CA's CertRep in full. `getCACaps(baseUrl, opts?)`, `getCACert(baseUrl, opts?)`, `getNextCACert(baseUrl, opts)`, `enroll(baseUrl, opts)`, `renew(baseUrl, opts)`, `getCert(baseUrl, opts)`, and `getCrl(baseUrl, opts)` carry that codec to a live CA over HTTP (RFC 8894 §4) through an injectable transport (`pki.transport.https` by default): `getCACaps` reports the CA's advertised capabilities and never lowers the client's algorithm choice on the unauthenticated response, `getCACert` pins the CA certificate to an out-of-band `expectedFingerprint` a returned certificate must match, `getNextCACert` fetches the CA's next (rollover) certificate and verifies the SignedData response against the current CA certificate (`caCertificate`) before returning it, refusing a response signed by any other key, and `enroll` and `renew` POST a PKCSReq or RenewalReq, authenticate the CertRep against the CA certificate and its nonce echo, select the issued certificate by public-key match, throw on a FAILURE with the CA's failInfo, and poll a PENDING response with CertPoll requests until the CA answers or a bounded poll-count and total-wait budget is spent. `getCert` and `getCrl` retrieve an already-issued certificate or a CA CRL by issuer and serial number, authenticated the same way; RFC 8894 §2.6, §2.7, and §3.3.4 recommend these queries only where HTTP certificate-store access (RFC 4387), LDAP, or a CRL distribution point is unavailable, so prefer those where a CA offers them. A PKIOperation goes over HTTP POST by default; `httpMethod: "GET"` carries it base64-encoded in the URL query for a legacy CA that accepts only GET (RFC 8894 §4.1). Every verb reaches an https CA through a forward proxy with `opts.proxy = { url, auth?, tls? }`: a `CONNECT` tunnel is opened to the proxy and the origin TLS is negotiated inside it, so the proxy carries the enrollment without being able to read it or substitute the origin certificate. Basic proxy authentication (RFC 7617) is sent only over an `https://` proxy, where it rides the authenticated TLS-to-proxy channel; an `http://` proxy is tunnel-only, and credentials over a plaintext proxy are refused rather than exposed (see `pki.transport`) — `build`, `parse`, `parseCapabilities`, `getCACaps`, `getCACert`, `getNextCACert`, `enroll`, `renew`, `getCert`, `getCrl` |
226
- | `pki.transport` | The shared, fail-closed `node:https` transport the enrollment clients drive. `pki.transport.https(defaults)` returns a `transport(request) → { status, headers, body, tls }`, where `tls` carries the negotiated `protocol`, `cipher`, raw `peerCertificate`, and one channel binding per TLS version: on TLS 1.2 the RFC 5929 `tlsUnique` that `pki.est.challengePasswordFromTlsUnique` links to an EST enrollment (RFC 7030 §3.5), and on TLS 1.3 the RFC 9266 `tlsExporter` (32 bytes under the label `EXPORTER-Channel-Binding`, zero-length context). Each is `null` on the version that does not define it, and `tlsExporter` is withheld below TLS 1.3 because RFC 9266 §2 also requires the RFC 7627 extended master secret, which Node gives no way to confirm. Since `tlsUnique` on the response arrives after the body was sent, a request `body` may instead be a function `(tls) -> bytes` the transport invokes after the handshake and before it writes the body, so the caller builds a channel-bound CSR from `tlsUnique` on the same connection it posts over. It may return a promise, so the CSR can be signed with `pki.csr.sign` while the connection is held open; a callback that throws, rejects, or returns anything other than bytes or a string fails the request closed rather than posting an empty enrollment. This is the toolkit's only socket choke point: an explicit trust anchor (or an opt-in to the system store) is required, `rejectUnauthorized` is always on, TLS is floored at 1.2, the response body is capped while it streams, and a stalled socket times out. The EST, ACME, and CMP clients reuse it verbatim. A `request.proxy = { url, auth?, tls? }` reaches the origin through a forward proxy: a `CONNECT` tunnel is opened to the proxy and the origin TLS is negotiated inside it under the identical origin trust policy, so the proxy cannot read the origin's encrypted session or substitute an authenticated origin certificate. Basic proxy credentials are sent only over an `https://` proxy, whose own certificate is verified against `proxy.tls`, so they ride an authenticated channel; a plaintext `http://` proxy is tunnel-only and carrying `auth` on one is refused (`proxy-auth-requires-tls`) rather than exposing the credentials to the proxy hop. A malformed option, a failed CONNECT, an unverified proxy certificate, or an unaccepted credential fails closed. The SCEP, EST, ACME, and CMP clients each thread it through as `opts.proxy`. If you inject your own transport, return `tls` too: `pki.est.serverkeygen` asserts the negotiated cipher can protect the delivered private key, and a transport that reports no cipher is trusted rather than refused, so omitting the field silently skips that check — `https` |
226
+ | `pki.transport` | The shared, fail-closed `node:https` transport the enrollment clients drive. `pki.transport.https(defaults)` returns a `transport(request) → { status, headers, body, tls }`, where `tls` carries the negotiated `protocol`, `cipher`, raw `peerCertificate`, and one channel binding per TLS version: on TLS 1.2 the RFC 5929 `tlsUnique` that `pki.est.challengePasswordFromTlsUnique` links to an EST enrollment (RFC 7030 §3.5), and on TLS 1.3 the RFC 9266 `tlsExporter` (32 bytes under the label `EXPORTER-Channel-Binding`, zero-length context). Each is `null` on the version that does not define it, and `tlsExporter` is withheld below TLS 1.3 because RFC 9266 §2 also requires the RFC 7627 extended master secret, which Node gives no way to confirm. Since `tlsUnique` on the response arrives after the body was sent, a request `body` may instead be a function `(tls) -> bytes` the transport invokes after the handshake and before it writes the body, so the caller builds a channel-bound CSR from `tlsUnique` on the same connection it posts over. It may return a promise, so the CSR can be signed with `pki.csr.sign` while the connection is held open; a callback that throws, rejects, or returns anything other than bytes or a string fails the request closed rather than posting an empty enrollment. This is the toolkit's only socket choke point: an explicit trust anchor (or an opt-in to the system store) is required, `rejectUnauthorized` is always on, TLS is floored at 1.2, the response body is capped while it streams, and a stalled socket times out. The EST, ACME, and CMP clients reuse it verbatim. A `request.proxy = { url, auth?, tls? }` reaches the origin through a forward proxy: a `CONNECT` tunnel is opened to the proxy and the origin TLS is negotiated inside it under the identical origin trust policy, so the proxy cannot read the origin's encrypted session or substitute an authenticated origin certificate. Proxy credentials are sent only over an `https://` proxy, whose own certificate is verified against `proxy.tls`, so they ride an authenticated channel; a plaintext `http://` proxy is tunnel-only and carrying `auth` on one is refused (`proxy-auth-requires-tls`) rather than exposing the credentials to the proxy hop. `auth.scheme` is `"basic"` (RFC 7617), which sends its credential on the first CONNECT, or `"digest"` (RFC 7616), which answers the proxy's `Proxy-Authenticate` challenge on a `407` by hashing the method `CONNECT` over the authority-form target, and answers exactly once, so a proxy repeating its challenge has rejected the credential rather than obtained another attempt. Digest runs the policy the origin verbs apply, refusing MD5 and a challenge carrying no `qop` unless `auth.allowMD5` / `auth.allowLegacyQop` says otherwise. A malformed option, a failed CONNECT, an unverified proxy certificate, or an unaccepted credential fails closed. The SCEP, EST, ACME, and CMP clients each thread it through as `opts.proxy`. If you inject your own transport, return `tls` too: `pki.est.serverkeygen` asserts the negotiated cipher can protect the delivered private key, and a transport that reports no cipher is trusted rather than refused, so omitting the field silently skips that check — `https` |
227
227
  | `pki.jose` | Flattened JWS (RFC 7515) and JWK thumbprints (RFC 7638). `sign` and `verify` run a Flattened JWS against declarative profiles (ACME outer, EAB inner, keyChange inner) that carry the required and forbidden header rules as data. `base64url` is the strict RFC 4648 §5 codec, rejecting padding, non-alphabet characters, and non-canonical trailing bits. `parseJson` is a bounded reader that refuses duplicate members at any depth. `thumbprint` is the RFC 7638 / 8037 / 9964 canonical digest. The algorithm registry binds each `alg` to its key type (ES/RS/PS/EdDSA/ML-DSA), leaving no code path for `alg:none`, an RS256→HS256 key confusion, or an all-zero ECDSA signature; `assertPublicJwk` refuses a JWK carrying private material, so an exported private key is never published. `opts.key` names the key a message must be signed under and governs: where the profile also permits an embedded header `jwk`, the two must be the same key — compared as RFC 7638 thumbprints, so member order cannot make equal keys differ — and a disagreement is refused rather than resolved in the message's favor. `keySource` reports which key answered, since a signature checked against a key you named is a different claim from one checked against the key the message carried — `sign`, `verify`, `base64url`, `parseJson`, `thumbprint`, `assertPublicJwk` |
228
228
  | `pki.acme` | ACME (RFC 8555 / 8737 / 8738 / 9773). `client(directoryUrl, opts)` is a stateful client driving a live CA directory over `pki.transport`: `newAccount`, `newOrder`, `newAuthz`, `getOrder`, `getAuthorization`, `getChallenge`, `respondToChallenge`, `finalize`, `pollOrder`, `pollAuthorization`, and `downloadCertificate` walk the issuance flow, with `newAuthz` pre-authorizing a single identifier (§7.4.1) and `downloadCertificate` binding the issued certificate to the order — its key, its identifiers, or both; at least one is required by default and the result reports `boundToKey` / `boundToIdentifiers` — before choosing among alternate chains (`Link rel="alternate"`, §7.4.2, via a `selectChain` predicate bounded by `maxAlternates`). `revokeCert` (account-key or certificate-key signed), `keyChange`, `updateAccount` (change the account contacts, §7.3.2), `listOrders` (the account's orders list, following the §7.1.2.1 `Link rel="next"` pagination bounded by a page cap and confined to the orders origin), `deactivateAccount`, `deactivateAuthorization`, `renewalInfo` (ARI), `renewalWindow` (the RFC 9773 §4.2/4.3 renewal decision), and `scheduleRenewal` (the §4.1 auto-sleeping renewal loop that sleeps until the selected instant and refetches until it is time to renew, stopping at the certificate's notAfter) complete the lifecycle. Every URL is HTTPS only, an explicit trust anchor is required, each request carries a fresh single-use nonce with a bounded badNonce retry (and, when `opts.resignKeys` supplies caller-approved alternative account-key algorithms, a bounded RFC 8555 §6.2 badSignatureAlgorithm re-sign that the CA's advertised list can only filter, never widen, so it cannot force a weaker algorithm), reads are POST-as-GET, polling is bounded and sleeps on a Retry-After via an injectable sleeper capped by a poll count and a total-wait budget, and every response body is size-capped. The transport is injectable via `opts.transport`. Over the message layer it composes resource-object validators (closed status enums, conditional-required fields, unknown fields ignored), the three §7.1.6 state machines, the request builders (newAccount with External Account Binding, newOrder with `replaces`, finalize with a CSR identifier-set match and account-key-reuse rejection, challenge responses, deactivation, revokeCert in both key modes, the keyChange nested JWS, POST-as-GET), the http-01 / dns-01 / tls-alpn-01 challenge computations, the dns and ip identifier validators, and the ARI certID with serial sign-padding preserved — `client`, `validate`, `identify`, `assertTransition`, the builders, `keyAuthorization`, `http01`, `dns01`, `tlsAlpn01Extension`, `verifyTlsAlpn01`, `ariCertId` |
229
229
  | `pki.schema.smime` | S/MIME ESS signed-attribute values (RFC 5035 / RFC 8551). `parseSigningCertificate` and `parseSigningCertificateV2` bind a signature to its signing certificate (cert hash, hash algorithm, issuer `GeneralNames` and serial); `parseSmimeCapabilities` decodes the ordered capability list; `decodeAttribute` dispatches a CMS attribute by OID, enforcing the single-value rule and deferring on unknown types. A companion decoder for CMS signed attributes rather than an auto-routed format — `parseSigningCertificate`, `parseSigningCertificateV2`, `parseSmimeCapabilities`, `decodeAttribute` |
@@ -246,7 +246,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
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` |
248
248
  | `pki.trust` | Mozilla and CCADB trust-store ingestion. `parseCertdata` reads the NSS `certdata.txt` object stream and `parseCcadbCsv` the CCADB CSV export, both into one constraint-carrying anchor shape: the per-purpose trust bits, where only `CKT_NSS_TRUSTED_DELEGATOR` grants, and the per-purpose distrust-after dates the bare root list omits. Certificate and trust objects pair by byte-exact issuer and serial rather than adjacency and are cross-checked against the parsed DER, so metadata cannot attach to the wrong root. `anchor()` hands an entry to `pki.path.validate({ trustAnchors, checkPurpose })`, and `anchor(entry, { nameConstraints })` attaches the namespace a root program trusts a root for when that is narrower than the root certificate states, a `{ permitted, excluded }` pair of `{ tag, base }` subtrees that `validate` seeds as the RFC 5280 §6.1.1(h)(i) initial value, intersecting with each certificate's own constraints. Offline, fail-closed, bounded — `parseCertdata`, `parseCcadbCsv`, `anchor` |
249
- | `pki.shbs` | Stateful hash-based signature verification: HSS/LMS (RFC 8554), carried in X.509 by RFC 9802 and in CMS by RFC 9708, profiled by NIST SP 800-208 for CNSA 2.0 firmware signing. `verify` checks an HSS signature, where every level must pass, and `verifyLms` a single-tree LMS, over the raw public-key and signature blobs the parsers already surface. Pure public-input SHA-256 and SHAKE256 hashing, a data-driven typecode registry, and bounds-before-slice reads; a malformed blob throws a typed `ShbsError` while a well-formed but wrong signature returns `false`. Verification only by design, since stateful signing needs atomic one-time-key state that belongs in an HSM — `verify`, `verifyLms` |
249
+ | `pki.shbs` | Stateful hash-based signature verification: HSS/LMS (RFC 8554), carried in X.509 by RFC 9802 and in CMS by RFC 9708, profiled by NIST SP 800-208 for CNSA 2.0 firmware signing. `verify` checks an HSS signature, where every level must pass, and `verifyLms` a single-tree LMS, over the raw public-key and signature blobs the parsers already surface. Pure public-input SHA-256 and SHAKE256 hashing, a data-driven typecode registry, and bounds-before-slice reads; a malformed blob throws a typed `ShbsError` while a well-formed but wrong signature returns `false`. Verification only by design, since stateful signing needs atomic one-time-key state that belongs in an HSM. `pki.path.validate` verifies an HSS-signed certificate on its own, so a chain reaching one needs no separate call: the signature covers the whole tbsCertificate rather than a digest of it (RFC 9802 §7.1), and a CertificateList naming the algorithm takes the same route. It is proven against the self-signed certificate RFC 9802 Appendix A publishes — `verify`, `verifyLms` |
250
250
  | `pki.hpke` | Hybrid Public Key Encryption (RFC 9180), the encrypt-to-a-public-key primitive behind TLS ECH, MLS, and OHTTP. `setupS` and `setupR` establish a sender or recipient context (KEM encapsulation plus the HKDF key schedule); the context's `seal` and `open` AEAD-encrypt with a sequence-counter nonce, and `export` derives further secrets; the module-level `seal` and `open` are single-shot wrappers. DHKEM (P-256, P-521, X25519, X448) by HKDF-SHA256/SHA512 by AES-GCM / ChaCha20Poly1305 / export-only, across all four modes, proven against the RFC 9180 Appendix A vectors. DHKEM(P-384) and HKDF-SHA384 are RFC-registered but Appendix A ships no vector for them, so they fail closed until an authoritative KAT exists. Pure composition over `node:crypto`; ML-KEM and X-Wing are a registry data-row extension pending stable drafts — `suites`, `setupS`, `setupR`, `seal`, `open` |
251
251
  | `pki.kem` | Composite ML-KEM key establishment (draft-ietf-lamps-pq-composite-kem), a post-quantum ML-KEM hybridized with a traditional RSA-OAEP, ECDH, X25519, or X448 so the established secret holds if either component is later broken. `encapsulate` turns a recipient's composite `SubjectPublicKeyInfo` into a 256-bit shared secret and a ciphertext; `decapsulate` recovers the same secret from the ciphertext and the composite PKCS#8 private key. Each component KEM runs independently and the two secrets are mixed through a SHA3-256 combiner that binds the traditional ciphertext, the traditional public key, and a per-algorithm label. The twelve algorithms pair ML-KEM-768 and ML-KEM-1024 with RSA-OAEP 2048/3072/4096, ECDH over P-256/P-384/P-521 and brainpoolP256r1/P384r1, X25519, and X448, each verified against the draft Appendix G known-answer vectors; a malformed key or ciphertext, an unsupported algorithm, or a component decapsulation failure throws a typed `KemError` — `encapsulate`, `decapsulate` |
252
252
  | `pki.sigstore` | Offline verifier for a Sigstore bundle, the artifact `npm publish --provenance` produces and the registry serves. `verifyBundle` composes five fail-closed legs against caller-pinned trust (Fulcio CA roots and Rekor log keys, never trusted from the bundle): the DSSE signature over its PAE preimage under the Fulcio leaf key, the ephemeral Fulcio certificate chain validated as of the Rekor log time, the RFC 9162 inclusion proof folded to a Rekor-signed tree root, the log entry bound to this exact signature, and the in-toto SLSA subject digest the caller confirms against the published artifact. It reuses the X.509 parser, the RFC 5280 path validator, and the Merkle verifier; the net-new codecs are the DSSE PAE byte-builder and a fail-closed JSON reader. `verified: true` says the artifact was signed and logged, not that a party you trust signed it — Fulcio issues to anyone who completes an OIDC flow, so who signed is decided only by `opts.identity`, and `identityChecked` reports which of its fields were compared. An identity policy naming no field, or a field name that is not one of the three, is refused rather than satisfied — either would accept every signer while reading as a policy in force — `pae`, `parseBundle`, `verifyBundle` |
@@ -8,6 +8,7 @@ var oid = require("./oid");
8
8
  var webcrypto = require("./webcrypto");
9
9
  var validator = require("./validator-all");
10
10
  var edwardsPoint = require("./edwards-point");
11
+ var _verdictOf = require("./guard-verdict").of;
11
12
  var subtle = webcrypto.webcrypto.subtle;
12
13
  var _b = asn1.build;
13
14
 
@@ -96,20 +97,23 @@ function _verifyTradComponent(trad, tradPK, tradSig, mprime, E, badSig) {
96
97
  return Promise.resolve(false);
97
98
  }
98
99
 
100
+ /** @internal Every verdict this returns carries its own `then`: resolving a promise reads that property
101
+ * off the value, so an inherited accessor would run with the verdict as its receiver and could hand the
102
+ * caller a different object than the one the comparison produced (see guard-verdict). */
99
103
  function compositeVerify(spkiBytes, sigBytes, message, d, E, unsupported, badSig) {
100
104
  if (d.trad.unsupported) {
101
- return Promise.resolve({ ok: false, code: unsupported,
102
- error: new E(unsupported, "composite " + d.name + ": " + d.trad.unsupported) });
105
+ return Promise.resolve(_verdictOf({ ok: false, code: unsupported,
106
+ error: new E(unsupported, "composite " + d.name + ": " + d.trad.unsupported) }));
103
107
  }
104
108
  var rawKey;
105
109
  try {
106
110
  var bs = asn1.read.bitString(asn1.decode(spkiBytes).children[1]);
107
111
  if (bs.unusedBits !== 0) throw new E(badSig, "composite subjectPublicKey has unused bits");
108
112
  rawKey = bs.bytes;
109
- } catch (e) { return Promise.resolve({ ok: false, code: _codeOf(e, badSig), error: e }); }
113
+ } catch (e) { return Promise.resolve(_verdictOf({ ok: false, code: _codeOf(e, badSig), error: e })); }
110
114
  if (rawKey.length <= d.mldsaPk || sigBytes.length <= d.mldsaSig) {
111
- return Promise.resolve({ ok: false, code: badSig,
112
- error: new E(badSig, "composite key/signature shorter than the fixed ML-DSA component") });
115
+ return Promise.resolve(_verdictOf({ ok: false, code: badSig,
116
+ error: new E(badSig, "composite key/signature shorter than the fixed ML-DSA component") }));
113
117
  }
114
118
  var mldsaPK = rawKey.subarray(0, d.mldsaPk), tradPK = rawKey.subarray(d.mldsaPk);
115
119
  var mldsaSig = sigBytes.subarray(0, d.mldsaSig), tradSig = sigBytes.subarray(d.mldsaSig);
@@ -118,8 +122,8 @@ function compositeVerify(spkiBytes, sigBytes, message, d, E, unsupported, badSig
118
122
  var mldsaP = subtle.importKey("spki", _mldsaSpki(d.mldsaOid, mldsaPK), { name: d.mldsa }, false, ["verify"])
119
123
  .then(function (mk) { return subtle.verify({ name: d.mldsa, context: d.label }, mk, mldsaSig, mprime); });
120
124
  var tradP = _verifyTradComponent(d.trad, tradPK, tradSig, mprime, E, badSig);
121
- return Promise.all([mldsaP, tradP]).then(function (r) { return { ok: r[0] === true && r[1] === true }; });
122
- }).catch(function (e) { return { ok: false, code: _codeOf(e, badSig), error: e }; });
125
+ return Promise.all([mldsaP, tradP]).then(function (r) { return _verdictOf({ ok: r[0] === true && r[1] === true }); });
126
+ }).catch(function (e) { return _verdictOf({ ok: false, code: _codeOf(e, badSig), error: e }); });
123
127
  }
124
128
 
125
129
  function resolveCompositeDescriptor(sigAlg, E, unsupported) {
@@ -239,7 +239,8 @@ function _classifyError(e, C) {
239
239
 
240
240
  function _keySet(names) { var m = Object.create(null); for (var i = 0; i < names.length; i++) m[names[i]] = true; return m; }
241
241
  var PROXY_KEYS = _keySet(["url", "auth", "tls"]);
242
- var PROXY_AUTH_KEYS = _keySet(["scheme", "username", "password"]);
242
+ var PROXY_AUTH_KEYS = _keySet(["scheme", "username", "password", "allowMD5", "allowLegacyQop"]);
243
+ var PROXY_DIGEST_KNOBS = ["allowMD5", "allowLegacyQop"];
243
244
  var PROXY_TLS_KEYS = _keySet(["anchors", "useSystemStore", "servername", "minVersion"]);
244
245
 
245
246
  function _copyAnchor(a) { return (a !== null && typeof a === "object" && nodeUtil.types.isProxy(a)) ? a : (Buffer.isBuffer(a) ? Buffer.from(a) : a); }
@@ -319,11 +320,17 @@ function _validateProxy(request, defaults, E, C, url) {
319
320
  if (!_copyableRecord(proxy.auth)) throw E(C("bad-proxy"), "opts.proxy.auth must be a plain object with only own enumerable data properties");
320
321
  guard.identifier.assertKnownKeys(proxy.auth, PROXY_AUTH_KEYS, E, C("bad-proxy"), "opts.proxy.auth has an unknown option ");
321
322
  var scheme = proxy.auth.scheme;
322
- if (scheme === "digest") throw E(C("proxy-unsupported-scheme"), "Digest proxy authentication is not supported in this release; use 'basic' over an https proxy");
323
- if (scheme !== "basic") throw E(C("bad-proxy"), "opts.proxy.auth.scheme must be 'basic', got " + guard.text.showValue(scheme));
323
+ if (scheme !== "basic" && scheme !== "digest") throw E(C("bad-proxy"), "opts.proxy.auth.scheme must be 'basic' or 'digest', got " + guard.text.showValue(scheme));
324
324
  if (typeof proxy.auth.username !== "string" || typeof proxy.auth.password !== "string") throw E(C("bad-proxy"), "opts.proxy.auth requires a string username and password");
325
- if (proxy.auth.username.indexOf(":") !== -1) throw E(C("bad-proxy"), "a Basic proxy user-id must not contain a colon (RFC 7617 sec. 2)");
326
- auth = { scheme: "basic", username: proxy.auth.username, password: proxy.auth.password };
325
+ for (var ki = 0; ki < PROXY_DIGEST_KNOBS.length; ki++) {
326
+ var kn = PROXY_DIGEST_KNOBS[ki], kv = proxy.auth[kn];
327
+ if (kv === undefined) continue;
328
+ if (scheme !== "digest") throw E(C("bad-proxy"), "opts.proxy.auth." + kn + " applies only to Digest authentication");
329
+ if (typeof kv !== "boolean") throw E(C("bad-proxy"), "opts.proxy.auth." + kn + " must be a boolean, got " + guard.text.showValue(kv));
330
+ }
331
+ if (scheme === "basic" && proxy.auth.username.indexOf(":") !== -1) throw E(C("bad-proxy"), "a Basic proxy user-id must not contain a colon (RFC 7617 sec. 2)");
332
+ auth = { scheme: scheme, username: proxy.auth.username, password: proxy.auth.password,
333
+ allowMD5: proxy.auth.allowMD5 === true, allowLegacyQop: proxy.auth.allowLegacyQop === true };
327
334
  }
328
335
 
329
336
  var proxyTls = null;
@@ -365,6 +372,30 @@ function _validateProxy(request, defaults, E, C, url) {
365
372
  function _basicProxyHeader(auth) {
366
373
  return "Basic " + Buffer.from(auth.username + ":" + auth.password, "utf8").toString("base64");
367
374
  }
375
+
376
+ /** @internal The `Proxy-Authorization` value answering a proxy's `Proxy-Authenticate: Digest` challenge
377
+ * (RFC 7616 sec. 3.3, RFC 9110 sec. 11.7.1). The challenge grammar is the one the origin uses, so the
378
+ * shipped parser reads it unchanged; a CONNECT hashes the method `CONNECT` over the authority-form target
379
+ * the request line carries (RFC 9112 sec. 3.2.3), which is the pair the proxy checks it against. */
380
+ function _digestProxyCredential(headers, pinfo, C, E) {
381
+ var httpDigest = require("./http-digest"); // allow:inline-require -- circular load: http-digest -> schema-pkix -> ct -> this module
382
+ var offered = String((headers && headers["proxy-authenticate"]) || "");
383
+ var policy = {
384
+ allowMD5: pinfo.auth.allowMD5, allowLegacyQop: pinfo.auth.allowLegacyQop,
385
+ codes: {
386
+ unsupportedAlgorithm: C("proxy-digest-unsupported-algorithm"), weakAlgorithm: C("proxy-digest-weak-algorithm"),
387
+ noQop: C("proxy-digest-no-qop"), badChallenge: C("proxy-digest-bad-challenge"),
388
+ },
389
+ };
390
+ var challenge = httpDigest.parseChallenge(offered, E, C("proxy-digest-bad-challenge"), policy);
391
+ if (!challenge) {
392
+ throw E(C("proxy-auth-required"), "opts.proxy.auth.scheme is \"digest\" but the proxy offered no usable Digest challenge: " + guard.text.showValue(offered));
393
+ }
394
+ return httpDigest.answer(challenge, {
395
+ method: "CONNECT", uri: pinfo.originAuthority,
396
+ username: pinfo.auth.username, password: pinfo.auth.password, nc: 1, policy: policy,
397
+ }, E);
398
+ }
368
399
  function _proxyErrorClass(e, C) {
369
400
  var code = String((e && e.code) || "");
370
401
  if (code.indexOf("ERR_TLS") === 0 || code.indexOf("ERR_SSL") === 0 || code.indexOf("SSL") !== -1 ||
@@ -405,7 +436,7 @@ function _proxyErrorClass(e, C) {
405
436
  * - `tls.servername` / `tls.checkServerIdentity` -- SNI + RFC 6125 identity; may tighten, never disable.
406
437
  * - `timeout` -- ms (default C.TIME.seconds(30)); `maxResponseBytes` -- default LIMITS.HTTP_MAX_RESPONSE_BYTES, tightenable downward only.
407
438
  * - `blockPrivateAddresses` -- boolean; when true, an IP-literal host OR a hostname resolving to a private / loopback / link-local address is refused (`transport/blocked-address`), and a resolved address is pinned for the connection. For fetching an untrusted-certificate URL (AIA caIssuers); default false. It cannot be combined with `proxy`: a forward proxy resolves the origin itself, so the transport cannot enforce the block on it, and the combination is refused (`transport/bad-proxy`).
408
- * - `proxy` -- reach the https origin through a forward HTTP proxy: `{ url: "http://proxy:3128" | "https://proxy:3128", auth?: { scheme: "basic", username, password }, tls?: { anchors, useSystemStore, servername, minVersion } }`. A CONNECT tunnel is opened to the proxy and the origin's TLS is negotiated inside it under the identical origin trust policy, so the proxy cannot read the origin's encrypted session or substitute the origin certificate. `auth` requires an `https://` proxy: Basic credentials ride the authenticated TLS-to-proxy channel (verified against `proxy.tls`, which is required for an https proxy), so a plaintext `http://` proxy carrying `auth` is refused (`transport/proxy-auth-requires-tls`) rather than leaking the credentials to the proxy hop. An `http://` proxy is tunnel-only. Digest is not supported (`transport/proxy-unsupported-scheme`). A `407` is `transport/proxy-auth-failed` (credentials rejected) or `transport/proxy-auth-required` (none supplied); a proxy certificate that does not verify is `transport/proxy-tls-failed`; a non-2xx CONNECT is `transport/proxy-connect-failed`; a malformed option is `transport/bad-proxy`. Off by default (a direct connection).
439
+ * - `proxy` -- reach the https origin through a forward HTTP proxy: `{ url: "http://proxy:3128" | "https://proxy:3128", auth?: { scheme: "basic" | "digest", username, password, allowMD5?, allowLegacyQop? }, tls?: { anchors, useSystemStore, servername, minVersion } }`. A CONNECT tunnel is opened to the proxy and the origin's TLS is negotiated inside it under the identical origin trust policy, so the proxy cannot read the origin's encrypted session or substitute the origin certificate. `auth` requires an `https://` proxy: the credentials ride the authenticated TLS-to-proxy channel (verified against `proxy.tls`, which is required for an https proxy), so a plaintext `http://` proxy carrying `auth` is refused (`transport/proxy-auth-requires-tls`) rather than exposing them to the proxy hop. An `http://` proxy is tunnel-only. Basic (RFC 7617) sends its credential on the first CONNECT. Digest (RFC 7616) answers the proxy's `Proxy-Authenticate` challenge on a `407`, hashing the method `CONNECT` over the authority-form target, and answers exactly once: a proxy that repeats its challenge has rejected the credential. The Digest policy is the one the origin verbs use, so MD5 and a challenge carrying no `qop` are refused unless `allowMD5` / `allowLegacyQop` says otherwise (`transport/proxy-digest-weak-algorithm`, `transport/proxy-digest-unsupported-algorithm`, `transport/proxy-digest-no-qop`, `transport/proxy-digest-bad-challenge`). A `407` is `transport/proxy-auth-failed` (credentials rejected) or `transport/proxy-auth-required` (none supplied, or none of the offered schemes is the configured one); a proxy certificate that does not verify is `transport/proxy-tls-failed`; a non-2xx CONNECT is `transport/proxy-connect-failed`; a malformed option is `transport/bad-proxy`. Off by default (a direct connection).
409
440
  * @example
410
441
  * var t = pki.transport.https({ tls: { anchors: [caPem] } });
411
442
  * var res = await t({ method: "GET", url: "https://ca.example/.well-known/est/cacerts" });
@@ -485,7 +516,7 @@ function httpsTransport(defaults) {
485
516
  var typedProxyError = false;
486
517
  try {
487
518
  var ec = (e instanceof Error) && !nodeUtil.types.isProxy(e) ? e.code : undefined;
488
- typedProxyError = ec === C("bad-proxy") || ec === C("proxy-auth-requires-tls") || ec === C("proxy-unsupported-scheme");
519
+ typedProxyError = ec === C("bad-proxy") || ec === C("proxy-auth-requires-tls");
489
520
  } catch (_ie) { /* allow:swallow-unverified reading .code on a hostile error object can throw; treat any such failure as untyped */ }
490
521
  if (typedProxyError) throw e;
491
522
  throw E(C("bad-proxy"), "opts.proxy could not be validated", e);
@@ -595,25 +626,43 @@ function httpsTransport(defaults) {
595
626
  if (!prep.proxy) { issue(prep.options); return; }
596
627
 
597
628
  var pinfo = prep.proxy;
598
- var pheaders = Object.assign(Object.create(null), { Host: pinfo.originAuthority, Connection: "keep-alive" });
599
- if (pinfo.auth) pheaders["Proxy-Authorization"] = _basicProxyHeader(pinfo.auth);
600
- var connectOpts = { host: pinfo.host, port: pinfo.port, method: "CONNECT", path: pinfo.originAuthority, headers: pheaders, agent: false };
601
- var cr;
602
- try {
603
- if (pinfo.secure) {
604
- connectOpts.ca = pinfo.proxyTls.ca;
605
- connectOpts.rejectUnauthorized = true;
606
- connectOpts.minVersion = pinfo.proxyTls.minVersion;
607
- var pIdentity = pinfo.proxyTls.servername || pinfo.host;
608
- connectOpts.servername = (pIdentity && !nodeNet.isIP(pIdentity)) ? pIdentity : "";
609
- connectOpts.checkServerIdentity = function (host, cert) { return nodeTls.checkServerIdentity(pIdentity, cert); };
610
- cr = nodeHttps.request(connectOpts);
611
- } else {
612
- cr = nodeHttp.request(connectOpts);
613
- }
614
- } catch (e) { fail(C("proxy-connect-failed"), "the CONNECT request could not be initiated: " + ((e && e.message) || String(e)), e); return; }
615
- creq = cr;
616
- var done = false;
629
+ /** @internal The client counts its own attempts. A 407 is answered once, from the challenge the proxy
630
+ * sent; a proxy that answers the credentialed CONNECT with another 407 has rejected the credential,
631
+ * and repeating its challenge cannot obtain a further attempt. */
632
+ var digestAnswered = false;
633
+ var cr, done;
634
+
635
+ function issueConnect(credential) {
636
+ var pheaders = Object.assign(Object.create(null), { Host: pinfo.originAuthority, Connection: "keep-alive" });
637
+ if (credential) pheaders["Proxy-Authorization"] = credential;
638
+ var connectOpts = { host: pinfo.host, port: pinfo.port, method: "CONNECT", path: pinfo.originAuthority, headers: pheaders, agent: false };
639
+ try {
640
+ if (pinfo.secure) {
641
+ connectOpts.ca = pinfo.proxyTls.ca;
642
+ connectOpts.rejectUnauthorized = true;
643
+ connectOpts.minVersion = pinfo.proxyTls.minVersion;
644
+ var pIdentity = pinfo.proxyTls.servername || pinfo.host;
645
+ connectOpts.servername = (pIdentity && !nodeNet.isIP(pIdentity)) ? pIdentity : "";
646
+ connectOpts.checkServerIdentity = function (host, cert) { return nodeTls.checkServerIdentity(pIdentity, cert); };
647
+ cr = nodeHttps.request(connectOpts);
648
+ } else {
649
+ cr = nodeHttp.request(connectOpts);
650
+ }
651
+ } catch (e) { fail(C("proxy-connect-failed"), "the CONNECT request could not be initiated: " + ((e && e.message) || String(e)), e); return; }
652
+ creq = cr;
653
+ done = false;
654
+ cr.on("connect", function (res, socket) { onProxyResponse(res, socket); });
655
+ cr.on("response", function (res) {
656
+ // allow:swallow-unverified draining the proxy error body is best-effort; the verdict is the status
657
+ res.on("data", function () { });
658
+ res.on("error", function () { });
659
+ res.on("end", function () { });
660
+ onProxyResponse(res, null);
661
+ });
662
+ cr.on("error", function (e) { fail(pinfo.secure ? _proxyErrorClass(e, C) : C("proxy-connect-failed"), "the CONNECT request failed: " + ((e && e.message) || String(e)), e); });
663
+ cr.end();
664
+ }
665
+
617
666
  function onProxyResponse(res, socket) {
618
667
  if (done) { if (socket) _quietDestroy(socket); return; }
619
668
  done = true;
@@ -646,19 +695,22 @@ function httpsTransport(defaults) {
646
695
  return;
647
696
  }
648
697
  if (socket) _quietDestroy(socket);
649
- if (sc === 407) { fail(C(pinfo.auth ? "proxy-auth-failed" : "proxy-auth-required"), pinfo.auth ? "the proxy rejected the supplied credentials (HTTP 407)" : "the proxy requires authentication; supply proxy.auth over an https proxy (HTTP 407)"); return; }
698
+ if (sc === 407) {
699
+ if (pinfo.auth && pinfo.auth.scheme === "digest" && !digestAnswered) {
700
+ digestAnswered = true;
701
+ var credential;
702
+ try { credential = _digestProxyCredential(res.headers, pinfo, C, E); }
703
+ catch (e) { fail(e.code || C("proxy-auth-failed"), e.message, e); return; }
704
+ issueConnect(credential);
705
+ return;
706
+ }
707
+ fail(C(pinfo.auth ? "proxy-auth-failed" : "proxy-auth-required"), pinfo.auth ? "the proxy rejected the supplied credentials (HTTP 407)" : "the proxy requires authentication; supply proxy.auth over an https proxy (HTTP 407)");
708
+ return;
709
+ }
650
710
  fail(C("proxy-connect-failed"), "the proxy answered CONNECT with HTTP " + sc);
651
711
  }
652
- cr.on("connect", function (res, socket) { onProxyResponse(res, socket); });
653
- cr.on("response", function (res) {
654
- // allow:swallow-unverified draining the proxy error body is best-effort; the verdict is the status
655
- res.on("data", function () { });
656
- res.on("error", function () { });
657
- res.on("end", function () { });
658
- onProxyResponse(res, null);
659
- });
660
- cr.on("error", function (e) { fail(pinfo.secure ? _proxyErrorClass(e, C) : C("proxy-connect-failed"), "the CONNECT request failed: " + ((e && e.message) || String(e)), e); });
661
- cr.end();
712
+
713
+ issueConnect(pinfo.auth && pinfo.auth.scheme === "basic" ? _basicProxyHeader(pinfo.auth) : null);
662
714
  });
663
715
  };
664
716
  _transportFn.blocksPrivateAddresses = true;
@@ -52,12 +52,17 @@ var cmpSession = require("./cmp-session");
52
52
  var guard = require("./guard-all");
53
53
  var intrinsic = require("./guard-intrinsic");
54
54
  var _charCodeAt = intrinsic.uncurry(String.prototype.charCodeAt);
55
+ var _resolve = intrinsic.uncurry(intrinsic.promiseResolve);
55
56
  var constants = require("./constants");
56
57
  var validator = require("./validator-all");
57
58
  var cms = require("./schema-cms");
58
59
  var httpTransport = require("./http-transport");
59
60
  var net = require("net");
60
61
  var compositeSig = require("./composite-sig");
62
+ /** @internal Captured at load: `pki.shbs` is the same module object the public surface exposes, and its
63
+ * `verify` is a writable property, so reading it when a signature is checked would let whoever wrote it
64
+ * last decide the verdict. */
65
+ var _shbsHssVerify = require("./shbs").verify;
61
66
  var edwardsPoint = require("./edwards-point");
62
67
 
63
68
  var PathError = errors.PathError;
@@ -116,6 +121,7 @@ function _sig(name, verify, imp, params, ecdsa, sameKeyOid) {
116
121
  if (verify.name === "Ed25519") entry.eddsa = 6;
117
122
  else if (verify.name === "Ed448") entry.eddsa = 7;
118
123
  SIG_ALGS[oid.byName(name)] = entry;
124
+ return entry;
119
125
  }
120
126
  _sig("sha256WithRSAEncryption", { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, "null");
121
127
  _sig("sha384WithRSAEncryption", { name: "RSASSA-PKCS1-v1_5", hash: "SHA-384" }, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-384" }, "null");
@@ -135,6 +141,13 @@ _sig("id-ml-dsa-87", { name: "ML-DSA-87" }, { name: "ML-DSA-87" }, "absent", fal
135
141
  _sig("id-slh-dsa-" + set, { name: wc }, { name: wc }, "absent", false, true);
136
142
  });
137
143
 
144
+ /** @internal RFC 9802: a stateful hash-based signature over the whole tbsCertificate rather than a digest
145
+ * of it (sec. 7.1), with the RFC 8554 public key carried directly in the subjectPublicKey BIT STRING and the
146
+ * signature directly in signatureValue, neither with any further ASN.1 wrapping (sec. 5, sec. 6). It verifies
147
+ * through the toolkit's own engine rather than the crypto engine, so the descriptor names that route instead
148
+ * of an import. Verification only: signing a stateful key belongs in hardware that owns the state. */
149
+ _sig("id-alg-hss-lms-hashsig", { name: "HSS-LMS" }, null, "absent", false, true).shbs = true;
150
+
138
151
  var OID_RSA_PSS = oid.byName("rsassaPss");
139
152
  var OID_MGF1 = oid.byName("mgf1");
140
153
  var HASH_BY_OID = intrinsic.create(null);
@@ -244,6 +257,46 @@ function compositeKeyUsageCheck(cert) {
244
257
  return { ok: true };
245
258
  }
246
259
 
260
+ var STATEFUL_HBS_OIDS = intrinsic.create(null);
261
+ ["id-alg-hss-lms-hashsig", "id-alg-xmss-hashsig", "id-alg-xmssmt-hashsig"].forEach(function (n) { STATEFUL_HBS_OIDS[oid.byName(n)] = true; });
262
+
263
+ /** @internal RFC 9802 sec. 6 states the rule twice, and the two differ: a certification authority's
264
+ * certificate may assert keyCertSign, an end entity's may not. Both must assert at least one of the values
265
+ * their list names, and neither may assert any value outside it. An absent extension is unrestricted, as
266
+ * RFC 5280 sec. 4.2.1.3 has it. */
267
+ /** @internal Whether the certificate states that it is a certification authority. An extension that does
268
+ * not decode leaves the stricter end-entity rule in force. */
269
+ function _isCaCert(cert) {
270
+ var bc;
271
+ try { bc = decodeExt(cert, OID.basicConstraints); }
272
+ // allow:swallow-unverified a basicConstraints that cannot be read is refused by its own check
273
+ catch (_e) { return false; }
274
+ return !!(bc && bc.value && bc.value.cA === true);
275
+ }
276
+
277
+ function statefulHbsKeyUsageCheck(cert, isCa) {
278
+ var ku;
279
+ try { ku = decodeExt(cert, OID.keyUsage); }
280
+ catch (e) { return { ok: false, code: "path/hbs-key-usage", error: e }; }
281
+ if (!ku) return { ok: true };
282
+ var v = ku.value;
283
+ var where = isCa ? "a certification authority" : "an end entity";
284
+ var allowed = isCa ? "digitalSignature, nonRepudiation, keyCertSign or cRLSign"
285
+ : "digitalSignature, nonRepudiation or cRLSign";
286
+ var asserted = v.digitalSignature || v.nonRepudiation || v.cRLSign || v.keyCertSign;
287
+ if (!asserted) {
288
+ return { ok: false, code: "path/hbs-key-usage",
289
+ error: E("path/hbs-key-usage", "a stateful hash-based key in " + where + " certificate must assert at least one of " + allowed + " (RFC 9802 sec. 6)") };
290
+ }
291
+ var forbidden = v.keyEncipherment || v.dataEncipherment || v.keyAgreement || v.encipherOnly ||
292
+ v.decipherOnly || (!isCa && v.keyCertSign) || (v.reservedBitsSet === true);
293
+ if (forbidden) {
294
+ return { ok: false, code: "path/hbs-key-usage",
295
+ error: E("path/hbs-key-usage", "a stateful hash-based key in " + where + " certificate must assert no keyUsage value outside " + allowed + " (RFC 9802 sec. 6)") };
296
+ }
297
+ return { ok: true };
298
+ }
299
+
247
300
  var ML_KEM_OIDS = intrinsic.create(null);
248
301
  ["id-ml-kem-512", "id-ml-kem-768", "id-ml-kem-1024"].forEach(function (n) { ML_KEM_OIDS[oid.byName(n)] = true; });
249
302
 
@@ -269,14 +322,38 @@ function _importVerifyKey(spkiBytes, d) {
269
322
  return subtle.importKey("spki", spkiBytes, d.imp, false, ["verify"]);
270
323
  }
271
324
 
325
+ /** @internal The RFC 8554 public key the SubjectPublicKeyInfo carries, and the verdict on a signature over
326
+ * `message`. A key or signature the engine cannot read is a refusal, never a pass. */
327
+ function _shbsVerify(spkiBytes, sigBytes, message) {
328
+ var rawKey;
329
+ /** @internal An RFC 8554 public key is a whole number of octets, and the codec accepts a BIT STRING that
330
+ * declares unused bits as long as they are zero, so the same key admits a second encoding unless the
331
+ * count is checked. The signature is held to the same rule by its caller. */
332
+ try {
333
+ var bits = asn1.read.bitString(asn1.decode(spkiBytes).children[1]);
334
+ if (!guard.crypto.isOctetAligned(bits)) {
335
+ return guard.verdict.of({ ok: false, code: "path/bad-signature",
336
+ error: E("path/bad-signature", "an HSS subjectPublicKey must be a whole number of octets, and this one declares " + bits.unusedBits + " unused bits") });
337
+ }
338
+ rawKey = bits.bytes;
339
+ } catch (e) { return guard.verdict.of({ ok: false, code: pathCode(e, "path/bad-signature"), error: e }); }
340
+ try {
341
+ return guard.verdict.of({ ok: _shbsHssVerify(rawKey, message, sigBytes) === true });
342
+ } catch (e) { return guard.verdict.of({ ok: false, code: pathCode(e, "path/bad-signature"), error: e }); }
343
+ }
344
+
272
345
  function builtinVerify(state, cert) {
273
346
  var d;
274
347
  try {
275
348
  d = resolveDescriptor(cert.signatureAlgorithm);
276
349
  assertKeyMatchesSigAlg(state.workingPublicKey, cert.signatureAlgorithm.oid, d);
277
- } catch (e) { return Promise.resolve({ ok: false, code: pathCode(e, "path/unsupported-algorithm"), error: e }); }
278
- if (!guard.crypto.isOctetAligned(cert.signatureValue)) return Promise.resolve({ ok: false, code: "path/bad-signature" });
350
+ /** @internal Resolving reads `then` off the value, so a synchronous verdict is built with an own one:
351
+ * an inherited accessor would otherwise run with the verdict as its receiver and hand the caller a
352
+ * different object (see guard-verdict). */
353
+ } catch (e) { return _resolve(Promise, guard.verdict.of({ ok: false, code: pathCode(e, "path/unsupported-algorithm"), error: e })); }
354
+ if (!guard.crypto.isOctetAligned(cert.signatureValue)) return _resolve(Promise, guard.verdict.of({ ok: false, code: "path/bad-signature" }));
279
355
  if (d.composite) return compositeSig.compositeVerify(state.workingPublicKey, cert.signatureValue.bytes, cert.tbsBytes, d.composite, PathError, "path/unsupported-algorithm", "path/bad-signature");
356
+ if (d.shbs) return _resolve(Promise, _shbsVerify(state.workingPublicKey, cert.signatureValue.bytes, cert.tbsBytes));
280
357
  var key;
281
358
  return _importVerifyKey(state.workingPublicKey, d).then(function (k) {
282
359
  key = k;
@@ -875,6 +952,26 @@ function validateCriticalExtensionStructure(cert) {
875
952
  * re-entrant: no input object is mutated. An empty path or a missing anchor
876
953
  * throws a typed `PathError`.
877
954
  *
955
+ * A certificate signed with the RFC 9802 stateful hash-based algorithm
956
+ * `id-alg-hss-lms-hashsig` is verified like any other, through the toolkit's own
957
+ * HSS engine rather than the crypto engine. The signature covers the whole
958
+ * tbsCertificate rather than a digest of it (RFC 9802 7.1), the RFC 8554 public
959
+ * key is read from the subjectPublicKey BIT STRING and the signature from
960
+ * signatureValue with no further ASN.1 wrapping (5, 6), the algorithm identifier
961
+ * carries no parameters, and the subject public key must name the algorithm the
962
+ * signature names. A `pki.crl.verify` CertificateList naming it takes the same
963
+ * route, which 6 provides for. Signing is out of scope: a stateful key's
964
+ * one-time state belongs in hardware that owns it.
965
+ *
966
+ * A certificate carrying any of the three stateful hash-based keys, HSS, XMSS or
967
+ * XMSS^MT, is held to the RFC 9802 6 key-usage rule whichever algorithm signed
968
+ * it, reported as the `hbsKeyUsage` check and refused with `path/hbs-key-usage`.
969
+ * The rule differs by role: a certification authority's certificate must assert
970
+ * at least one of digitalSignature, nonRepudiation, keyCertSign or cRLSign, an
971
+ * end entity's at least one of digitalSignature, nonRepudiation or cRLSign, and
972
+ * neither may assert any value outside its own list. An absent keyUsage is
973
+ * unrestricted, as RFC 5280 4.2.1.3 has it.
974
+ *
878
975
  * `valid` alone cannot say whether revocation was ever established, so
879
976
  * `revocationChecked` answers separately, taking the WEAKEST outcome on the
880
977
  * path: `false` when no `revocationChecker` was supplied, `"determined"` when
@@ -1077,6 +1174,12 @@ async function validate(path, opts) {
1077
1174
  if (!cku.ok) failed = true;
1078
1175
  }
1079
1176
 
1177
+ if (STATEFUL_HBS_OIDS[cert.subjectPublicKeyInfo.algorithm.oid]) {
1178
+ var hku = statefulHbsKeyUsageCheck(cert, _isCaCert(cert));
1179
+ guard.list.append(checks, { name: "hbsKeyUsage", ok: hku.ok, code: hku.ok ? undefined : hku.code });
1180
+ if (!hku.ok) failed = true;
1181
+ }
1182
+
1080
1183
  if (ML_KEM_OIDS[cert.subjectPublicKeyInfo.algorithm.oid]) {
1081
1184
  var kku = kemKeyUsageCheck(cert);
1082
1185
  guard.list.append(checks,{ name: "kemKeyUsage", ok: kku.ok, code: kku.ok ? undefined : kku.code });
@@ -1653,6 +1756,9 @@ function _verifyWithSpki(sigAlg, rawSig, spkiBytes, tbsBytes) {
1653
1756
  assertKeyMatchesSigAlg(spkiBytes, sigAlg.oid, d);
1654
1757
  } catch (_e) { return Promise.resolve(false); }
1655
1758
  if (d.composite) return compositeSig.compositeVerify(spkiBytes, rawSig, tbsBytes, d.composite, PathError, "path/unsupported-algorithm", "path/bad-signature").then(function (r) { return r.ok === true; });
1759
+ /** @internal RFC 9802 sec. 6 names the CertificateList as well as the Certificate, so a revocation list
1760
+ * signed with a stateful hash-based key reaches the same engine the certificate path uses. */
1761
+ if (d.shbs) return _resolve(Promise, _shbsVerify(spkiBytes, rawSig, tbsBytes).ok === true);
1656
1762
  return _importVerifyKey(spkiBytes, d).then(function (key) {
1657
1763
  var sig = rawSig;
1658
1764
  if (d.ecdsa) sig = validator.sig.ecdsaDerToP1363(sig, key.algorithm.namedCurve, PathError, "path/bad-signature");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.43",
3
+ "version": "0.6.45",
4
4
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:226aab27-22ce-4c29-9028-5849c0bf6587",
5
+ "serialNumber": "urn:uuid:4620569f-fe72-4f1e-9c26-386a3869ff76",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-06T06:39:34.959Z",
8
+ "timestamp": "2026-09-06T09:29:44.881Z",
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.6.43",
22
+ "bom-ref": "@blamejs/pki@0.6.45",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.43",
25
+ "version": "0.6.45",
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.6.43",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.45",
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.6.43",
57
+ "ref": "@blamejs/pki@0.6.45",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]