@blamejs/pki 0.6.25 → 0.6.27
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 +18 -0
- package/README.md +3 -3
- package/lib/http-transport.js +205 -46
- package/lib/path-validate.js +62 -13
- package/lib/scep.js +24 -8
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,24 @@ 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.27 — 2026-09-02
|
|
8
|
+
|
|
9
|
+
The SCEP client can reach a CA through a forward proxy, with Basic authentication over an https proxy.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- pki.transport gains forward-proxy support: request.proxy = { url, auth?, tls? } opens a CONNECT tunnel to the proxy and negotiates the origin's TLS inside the tunnel under the same trust anchors and rejectUnauthorized as a direct connection, so the proxy relays the encrypted origin session without being able to read it and cannot substitute the origin certificate.
|
|
14
|
+
- Basic proxy authentication (RFC 7617) is sent only over an https:// proxy, whose certificate is verified against proxy.tls (its own trust anchors, separate from the origin's), so credentials ride the authenticated TLS-to-proxy channel. A plaintext http:// proxy is tunnel-only; supplying auth for one is refused with transport/proxy-auth-requires-tls rather than exposing the credentials to the proxy hop. A proxy certificate that does not verify is transport/proxy-tls-failed.
|
|
15
|
+
- pki.scep threads opts.proxy through every network verb (getCACaps, getCACert, getNextCACert, enroll, renew, getCert, getCrl). A malformed proxy option (scep/bad-proxy), a non-2xx CONNECT (scep/proxy-connect-failed), a 407 with no or rejected credentials (scep/proxy-auth-required, scep/proxy-auth-failed), and a plaintext-http origin (scep/insecure-url) each fail closed. Digest proxy authentication is not included in this release.
|
|
16
|
+
|
|
17
|
+
## v0.6.26 — 2026-09-02
|
|
18
|
+
|
|
19
|
+
pki.path.build can prefer the certification path whose policies satisfy a caller-supplied policy set.
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- pki.path.build now uses opts.userInitialPolicySet to select the best-policy valid path across trust anchors and intermediates (RFC 4158 sec. 4), not only to constrain pki.path.validate's policy processing. It returns the accepted path whose user-constrained policy set best satisfies the requested set, with the existing candidate ordering as a deterministic tie-break; validate still gates every path. An anyPolicy entry is unconstrained (first accepted path); the ranking is bounded by maxCandidatesConsidered; a malformed userInitialPolicySet is refused with path/bad-input.
|
|
24
|
+
|
|
7
25
|
## v0.6.25 — 2026-09-02
|
|
8
26
|
|
|
9
27
|
pki.path.build can search from a trust anchor toward the leaf, not only from the leaf toward an anchor.
|
package/README.md
CHANGED
|
@@ -222,15 +222,15 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
222
222
|
| `pki.schema.cmp` | CMP messages (RFC 9810): the header (version, sender and recipient including the anonymous NULL-DN, nonces, transaction id, general info), the 27-arm body (certificate requests via the CRMF parser, an encrypted certificate's EnvelopedData via CMS, response / revocation / confirmation / error / support / polling arms structural, the rest raw), and the exact `headerBytes` and `bodyBytes` slices an external verifier reconstructs the protected part from. The CMP-before-OCSP dispatch order is enforced Fail-closed — `parse`, `pemDecode`, `pemEncode` |
|
|
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. `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
|
-
| `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).
|
|
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`, and raw `peerCertificate`. 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. 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` |
|
|
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`, and raw `peerCertificate`. 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. `pki.scep` threads 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` |
|
|
230
230
|
| `pki.cmc` | Build and interpret CMC messages (RFC 5272). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and signs it through `pki.cms.sign` under `id-cct-PKIData`. A PKCS#10 (`tcr`) request is verified against its own proof-of-possession before signing, so a request whose self-signature does not verify under its subject public key is refused rather than signed into a message a CA would reject. Body-part identifiers are unique across the whole message and never the reserved 0; a caller's clash is refused rather than renumbered, since a control may already reference it. An Identity Proof V2 witness is computed over the `reqSequence` bytes exactly as emitted (§6.2.1 step 1) rather than a re-serialization, a POP Link Witness is emitted only alongside the POP Link Random control §6.3.1.1 requires beside it, and a renewal carries neither Identification nor Identity Proof in either version. `verify(response, sent)` takes what the CA returned plus the state the client retained and reduces it to one terminal outcome: `issued`, `pending`, `confirm-required`, `pop-required`, or `rejected`. It binds the exchange first — Transaction Identifier, the Sender and Recipient Nonce echo compared in constant time and by full value so a truncation cannot match, and the Data Return echo — with each check applying only if the client sent that half, and, once sent, an absent or differing echo being a refusal, which is the replay defense. `bodyPartIDs` extends the same rule to what the response is about: a status reporting on a body part the request never sent is refused, which the transaction and nonce cannot catch, because a server can echo both correctly while answering about a different message. Several status controls are permitted and the worst governs, so a failure cannot hide behind an earlier success; the absence of any status control is success, per §6.1.2. The carrier's signature must verify (§3.2.1.3.4): a conforming SignedData carries its own signer certificate, so the ordinary build-then-verify flow needs nothing extra and the verdict reports `signatureVerified: true`. Where the signer is found nowhere the posture is fail-closed with a named opt-out — supply `certs` with the responder's certificate, or `allowUnverified: true`, in which case the verdict reports `signatureVerified: false`. Doing neither is refused, the opt-out never excuses a signature that is present and wrong, and a carrier with no signer at all is refused outright. The response's own `cmsSequence` and `otherMsgs` come back raw, since a request whose only arm was the other-message form has no certificate to return and §4.1 puts its answer there. Nothing is trusted: issued certificates are read from the CMS certificate bag (§4.2) and surfaced raw for `pki.path.validate`, and a Publish Trust Anchors control is surfaced with `trusted: false` rather than added to a store — `build`, `verify` |
|
|
231
231
|
| `pki.schema.cmc` | Decode CMC messages (RFC 5272 as updated by RFC 6402): a Full PKI Request (`PKIData`) or Full PKI Response (`PKIResponse`) riding inside a CMS SignedData, reached by the encapsulated content type (`id-cct-PKIData` / `id-cct-PKIResponse`). Controls are surfaced in wire order with their values raw, so an unrecognized one is data rather than a fault. Tagged requests decode across all three arms. The status verdicts (`CMCStatusInfo` v1 and `CMCStatusInfoV2`) are collected as an ordered list, and the RFC 6402 two-module `OtherStatusInfo` ambiguity — `pendInfo` and `extendedFailInfo` are both untagged SEQUENCEs in the 1988 module, told apart only by their first element — is resolved by inspection and refused when it cannot be told apart. Body-part identity is unique across the whole message rather than per sequence, 0 is reserved as the reference to the enclosing PKIData, and the `reqSequence` bytes are surfaced exactly as they appeared so an Identity Proof witness is computed over the wire bytes. A companion decoder for CMS content rather than an auto-routed format — `parse`, `parsePkiData`, `parsePkiResponse` |
|
|
232
232
|
| `pki.schema.engine` | The declarative ASN.1 structure-schema engine every format parser composes — `walk`, `encode`, `embeddedDer`, and the schema combinators |
|
|
233
|
-
| `pki.path` | Certification-path validation (RFC 5280 §6). `validate` runs the §6.1 state machine over an ordered path and a trust anchor: signature chaining across RSA, ECDSA, EdDSA, ML-DSA, SLH-DSA and hybrid composite ML-DSA (a composite is accepted only when both its post-quantum and traditional components verify), validity windows, name chaining, basic constraints and path length, key usage, name constraints, and the certificate-policy tree. It returns a structured verdict with per-check reason codes and enforces a `pki.trust` anchor's per-purpose distrust-after dates and delegator purposes through `checkPurpose` — an anchor that carries either one with no purpose named to select by is refused as a configuration fault rather than validated as though it carried none. The verdict says what was established. `revocationChecked` takes the weakest outcome on the path: `false` with no checker supplied, `"determined"` when every certificate got an explicit good or revoked answer, `"waived"` when `softFail` turned an undetermined one into a pass, and `"undetermined"` when one could not be answered at all — which includes a checker that throws, a fault `softFail` does not waive because `softFail` opts into an undetermined answer, not into a broken checker. `anchorConstraints` names the purpose the anchor was judged under and whether each of its two constraints applied. `crlChecker` supplies CRL-based revocation, covering partitioned and sharded CRLs, whose §6.3.3 Distribution Point ↔ IDP correspondence lets corresponding shards accumulate reason coverage until all eight revocation reasons are covered, and delta CRLs, merged onto the complete CRL they may be combined with (§5.2.4) so a held certificate its delta releases reads good, while a delta that merges with nothing still reports what it lists and still withholds good. `ocspChecker` supplies OCSP-based revocation (RFC 6960: CertID binding, responder authorization, signature, currency) over the same pluggable hook. `build(leaf, opts)` is the discovering complement (RFC 4158): from a leaf, an untrusted pool of candidate CA certificates, and a trust store, it finds the ordered leaf-to-anchor path `validate` accepts, using name chaining plus the RFC 4158 §3.5 sort hints (an AKI/SKI match, an anchor-adjacent issuer, CA plus keyCertSign, validity at the check time — ordering hints, never filters), a depth-first search with backtracking so the first accepted path wins, and a bounded search (chain-length cap, candidate-expansion cap, identity-tuple visited set) so a cross-certificate cycle or Bridge-CA fan-out terminates deterministically. Every accept flows through `validate`, and its verdict is cross-checked against `openssl verify`. Opt-in AIA `caIssuers` fetching (`opts.fetchAia: true`) discovers a missing intermediate from a certificate's Authority Information Access URL (§4.2.2.1) over `pki.transport`, triggered only on a pool miss and bounded against SSRF and amplification: HTTPS only, a total fetch budget that caps fetching silently rather than throwing, a per-cert URL cap, a build-wide URL dedupe, a response-size and certificate-count cap, no redirect following, and every fault a silent skip. The TLS trust (`opts.tls`) stays distinct from the PKI `trustAnchors`, and every fetched certificate remains untrusted pool material that still flows through `validate` (never a trust anchor). It is off by default, so the default build is byte-identical offline. An `opts.direction` of `"reverse"` searches from a trust anchor toward the leaf (RFC 4158 §3.1), narrower when the anchor set is small and the leaf's issuer options fan out, and `"auto"` picks the direction by first-hop fan-out; reverse building reuses the same pool, visited set, caps, and `validate` gate, so the direction changes only search order, and the anchor is excluded from the returned path. Reverse building is pool-only and does not combine with `fetchAia`. Pure and re-entrant — `validate`, `build`, `crlChecker`, `ocspChecker` |
|
|
233
|
+
| `pki.path` | Certification-path validation (RFC 5280 §6). `validate` runs the §6.1 state machine over an ordered path and a trust anchor: signature chaining across RSA, ECDSA, EdDSA, ML-DSA, SLH-DSA and hybrid composite ML-DSA (a composite is accepted only when both its post-quantum and traditional components verify), validity windows, name chaining, basic constraints and path length, key usage, name constraints, and the certificate-policy tree. It returns a structured verdict with per-check reason codes and enforces a `pki.trust` anchor's per-purpose distrust-after dates and delegator purposes through `checkPurpose` — an anchor that carries either one with no purpose named to select by is refused as a configuration fault rather than validated as though it carried none. The verdict says what was established. `revocationChecked` takes the weakest outcome on the path: `false` with no checker supplied, `"determined"` when every certificate got an explicit good or revoked answer, `"waived"` when `softFail` turned an undetermined one into a pass, and `"undetermined"` when one could not be answered at all — which includes a checker that throws, a fault `softFail` does not waive because `softFail` opts into an undetermined answer, not into a broken checker. `anchorConstraints` names the purpose the anchor was judged under and whether each of its two constraints applied. `crlChecker` supplies CRL-based revocation, covering partitioned and sharded CRLs, whose §6.3.3 Distribution Point ↔ IDP correspondence lets corresponding shards accumulate reason coverage until all eight revocation reasons are covered, and delta CRLs, merged onto the complete CRL they may be combined with (§5.2.4) so a held certificate its delta releases reads good, while a delta that merges with nothing still reports what it lists and still withholds good. `ocspChecker` supplies OCSP-based revocation (RFC 6960: CertID binding, responder authorization, signature, currency) over the same pluggable hook. `build(leaf, opts)` is the discovering complement (RFC 4158): from a leaf, an untrusted pool of candidate CA certificates, and a trust store, it finds the ordered leaf-to-anchor path `validate` accepts, using name chaining plus the RFC 4158 §3.5 sort hints (an AKI/SKI match, an anchor-adjacent issuer, CA plus keyCertSign, validity at the check time — ordering hints, never filters), a depth-first search with backtracking so the first accepted path wins, and a bounded search (chain-length cap, candidate-expansion cap, identity-tuple visited set) so a cross-certificate cycle or Bridge-CA fan-out terminates deterministically. Every accept flows through `validate`, and its verdict is cross-checked against `openssl verify`. Opt-in AIA `caIssuers` fetching (`opts.fetchAia: true`) discovers a missing intermediate from a certificate's Authority Information Access URL (§4.2.2.1) over `pki.transport`, triggered only on a pool miss and bounded against SSRF and amplification: HTTPS only, a total fetch budget that caps fetching silently rather than throwing, a per-cert URL cap, a build-wide URL dedupe, a response-size and certificate-count cap, no redirect following, and every fault a silent skip. The TLS trust (`opts.tls`) stays distinct from the PKI `trustAnchors`, and every fetched certificate remains untrusted pool material that still flows through `validate` (never a trust anchor). It is off by default, so the default build is byte-identical offline. An `opts.direction` of `"reverse"` searches from a trust anchor toward the leaf (RFC 4158 §3.1), narrower when the anchor set is small and the leaf's issuer options fan out, and `"auto"` picks the direction by first-hop fan-out; reverse building reuses the same pool, visited set, caps, and `validate` gate, so the direction changes only search order, and the anchor is excluded from the returned path. Reverse building is pool-only and does not combine with `fetchAia`. When `opts.userInitialPolicySet` names acceptable certificate-policy OIDs and more than one path validates, build returns the accepted path whose user-constrained policy set best satisfies that set (RFC 4158 §4) rather than the first accepted path, the ranking bounded by the same candidate cap and a malformed set refused with `path/bad-input`; an `anyPolicy` entry is unconstrained and returns the first accepted path. Pure and re-entrant — `validate`, `build`, `crlChecker`, `ocspChecker` |
|
|
234
234
|
| `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key), subject alternative names, and certificate policies from the spec, taking any other extension as pre-encoded DER. It derives the version from the field set and enforces the serial bounds, the UTCTime/GeneralizedTime cutover, the DER default omissions, and the CA cross-field rules; a violation throws a typed `CertificateError`. Returns DER, or a PEM `CERTIFICATE` with `opts.pem`. Every arm is independently verified by OpenSSL. Parsing stays at `pki.schema.x509.parse` — `sign` |
|
|
235
235
|
| `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
|
|
236
236
|
| `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
|
package/lib/http-transport.js
CHANGED
|
@@ -44,6 +44,7 @@
|
|
|
44
44
|
*/
|
|
45
45
|
|
|
46
46
|
var nodeHttps = require("node:https");
|
|
47
|
+
var nodeHttp = require("node:http");
|
|
47
48
|
var nodeNet = require("node:net");
|
|
48
49
|
var nodeTls = require("node:tls");
|
|
49
50
|
var nodeDns = require("node:dns");
|
|
@@ -191,6 +192,81 @@ function _classifyError(e, C) {
|
|
|
191
192
|
return C("transport-error");
|
|
192
193
|
}
|
|
193
194
|
|
|
195
|
+
function _keySet(names) { var m = Object.create(null); for (var i = 0; i < names.length; i++) m[names[i]] = true; return m; }
|
|
196
|
+
var PROXY_KEYS = _keySet(["url", "auth", "tls"]);
|
|
197
|
+
var PROXY_AUTH_KEYS = _keySet(["scheme", "username", "password"]);
|
|
198
|
+
var PROXY_TLS_KEYS = _keySet(["anchors", "useSystemStore", "servername", "minVersion"]);
|
|
199
|
+
|
|
200
|
+
function _validateProxy(request, defaults, E, C, url) {
|
|
201
|
+
var proxy = request.proxy !== undefined ? request.proxy : defaults.proxy;
|
|
202
|
+
if (proxy === undefined || proxy === null) return null;
|
|
203
|
+
guard.identifier.assertPlainRecord(proxy, E, C("bad-proxy"), "opts.proxy");
|
|
204
|
+
guard.identifier.assertKnownKeys(proxy, PROXY_KEYS, E, C("bad-proxy"), "opts.proxy has an unknown option ");
|
|
205
|
+
var purl;
|
|
206
|
+
try { purl = new URL(String(proxy.url)); }
|
|
207
|
+
catch (e) { throw E(C("bad-proxy"), "opts.proxy.url did not parse: " + guard.text.showValue(proxy.url), e); }
|
|
208
|
+
if (purl.protocol !== "http:" && purl.protocol !== "https:") throw E(C("bad-proxy"), "opts.proxy.url must be an http or https URL, got " + purl.protocol);
|
|
209
|
+
if (purl.username || purl.password) throw E(C("bad-proxy"), "opts.proxy.url must not carry credentials in its userinfo; supply opts.proxy.auth over an https proxy");
|
|
210
|
+
var secure = purl.protocol === "https:";
|
|
211
|
+
if (!secure && proxy.tls !== undefined && proxy.tls !== null) throw E(C("bad-proxy"), "opts.proxy.tls applies only to an https proxy; an http proxy connection is plaintext (a supplied tls policy would be silently ignored)");
|
|
212
|
+
|
|
213
|
+
var auth = null;
|
|
214
|
+
if (proxy.auth !== undefined && proxy.auth !== null) {
|
|
215
|
+
if (!secure) throw E(C("proxy-auth-requires-tls"), "proxy credentials cannot be sent over a plaintext http proxy, where the proxy hop would expose them; use an https proxy URL");
|
|
216
|
+
guard.identifier.assertPlainRecord(proxy.auth, E, C("bad-proxy"), "opts.proxy.auth");
|
|
217
|
+
guard.identifier.assertKnownKeys(proxy.auth, PROXY_AUTH_KEYS, E, C("bad-proxy"), "opts.proxy.auth has an unknown option ");
|
|
218
|
+
var scheme = proxy.auth.scheme;
|
|
219
|
+
if (scheme === "digest") throw E(C("proxy-unsupported-scheme"), "Digest proxy authentication is not supported in this release; use 'basic' over an https proxy");
|
|
220
|
+
if (scheme !== "basic") throw E(C("bad-proxy"), "opts.proxy.auth.scheme must be 'basic', got " + guard.text.showValue(scheme));
|
|
221
|
+
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");
|
|
222
|
+
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)");
|
|
223
|
+
auth = { scheme: "basic", username: proxy.auth.username, password: proxy.auth.password };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
var proxyTls = null;
|
|
227
|
+
if (secure) {
|
|
228
|
+
var ptls = proxy.tls;
|
|
229
|
+
if (ptls !== undefined && ptls !== null) {
|
|
230
|
+
guard.identifier.assertPlainRecord(ptls, E, C("bad-proxy"), "opts.proxy.tls");
|
|
231
|
+
guard.identifier.assertKnownKeys(ptls, PROXY_TLS_KEYS, E, C("bad-proxy"), "opts.proxy.tls has an unknown option ");
|
|
232
|
+
if (ptls.servername !== undefined && ptls.servername !== null && typeof ptls.servername !== "string") throw E(C("bad-proxy"), "opts.proxy.tls.servername must be a string");
|
|
233
|
+
}
|
|
234
|
+
var pAnchors = ptls ? ptls.anchors : undefined;
|
|
235
|
+
var pUseSystem = ptls ? ptls.useSystemStore === true : false;
|
|
236
|
+
var pHasAnchors = pAnchors !== undefined && pAnchors !== null && !(Array.isArray(pAnchors) && pAnchors.length === 0);
|
|
237
|
+
if (!pHasAnchors && !pUseSystem) throw E(C("bad-proxy"), "an https proxy requires explicit tls trust: set proxy.tls.anchors or proxy.tls.useSystemStore");
|
|
238
|
+
if (pHasAnchors) {
|
|
239
|
+
var pAnchorList = Array.isArray(pAnchors) ? pAnchors : [pAnchors];
|
|
240
|
+
for (var pai = 0; pai < pAnchorList.length; pai++) {
|
|
241
|
+
var pan = pAnchorList[pai];
|
|
242
|
+
if (typeof pan !== "string" && !Buffer.isBuffer(pan)) throw E(C("bad-proxy"), "opts.proxy.tls.anchors must be a PEM string or a DER Buffer (or an array of them)");
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
var pMinVersion = (ptls && ptls.minVersion) || DEFAULT_MIN_VERSION;
|
|
246
|
+
if (pMinVersion !== "TLSv1.2" && pMinVersion !== "TLSv1.3") throw E(C("bad-proxy"), "proxy.tls.minVersion must be 'TLSv1.2' or 'TLSv1.3', got " + pMinVersion);
|
|
247
|
+
var pCa = [];
|
|
248
|
+
if (pHasAnchors) pCa = pCa.concat(_pemifyAnchors(pAnchors));
|
|
249
|
+
if (pUseSystem) pCa = pCa.concat(_systemCa());
|
|
250
|
+
proxyTls = { ca: pCa.length ? pCa : undefined, minVersion: pMinVersion, servername: (ptls && ptls.servername) || null };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
var originHost = _stripIpv6Brackets(url.hostname);
|
|
254
|
+
var originAuthHost = nodeNet.isIP(originHost) === 6 ? "[" + originHost + "]" : originHost;
|
|
255
|
+
var phost = _stripIpv6Brackets(purl.hostname);
|
|
256
|
+
return { secure: secure, host: phost, port: purl.port ? +purl.port : (secure ? 443 : 80), originHost: originHost, originAuthority: originAuthHost + ":" + (url.port || 443), auth: auth, proxyTls: proxyTls };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function _basicProxyHeader(auth) {
|
|
260
|
+
return "Basic " + Buffer.from(auth.username + ":" + auth.password, "utf8").toString("base64");
|
|
261
|
+
}
|
|
262
|
+
function _proxyErrorClass(e, C) {
|
|
263
|
+
var code = String((e && e.code) || "");
|
|
264
|
+
if (code.indexOf("ERR_TLS") === 0 || code.indexOf("ERR_SSL") === 0 || code.indexOf("SSL") !== -1 ||
|
|
265
|
+
code.indexOf("CERT") !== -1 || code.indexOf("SELF_SIGNED") !== -1 || code.indexOf("VERIFY") !== -1 ||
|
|
266
|
+
code.indexOf("_SIGNATURE") !== -1 || code.indexOf("ALTNAME") !== -1) return C("proxy-tls-failed");
|
|
267
|
+
return C("proxy-connect-failed");
|
|
268
|
+
}
|
|
269
|
+
|
|
194
270
|
/**
|
|
195
271
|
* @primitive pki.transport.https
|
|
196
272
|
* @signature pki.transport.https(defaults?) -> transport
|
|
@@ -222,7 +298,8 @@ function _classifyError(e, C) {
|
|
|
222
298
|
* - `tls.minVersion` -- 'TLSv1.2' (default) or 'TLSv1.3'; never below the floor.
|
|
223
299
|
* - `tls.servername` / `tls.checkServerIdentity` -- SNI + RFC 6125 identity; may tighten, never disable.
|
|
224
300
|
* - `timeout` -- ms (default C.TIME.seconds(30)); `maxResponseBytes` -- default LIMITS.HTTP_MAX_RESPONSE_BYTES, tightenable downward only.
|
|
225
|
-
* - `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.
|
|
301
|
+
* - `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`).
|
|
302
|
+
* - `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).
|
|
226
303
|
* @example
|
|
227
304
|
* var t = pki.transport.https({ tls: { anchors: [caPem] } });
|
|
228
305
|
* var res = await t({ method: "GET", url: "https://ca.example/.well-known/est/cacerts" });
|
|
@@ -257,6 +334,7 @@ function httpsTransport(defaults) {
|
|
|
257
334
|
if (guard.bytes.isByteSource(body)) body = guard.bytes.source(body, E, C("bad-input"), "the request body");
|
|
258
335
|
|
|
259
336
|
var reqHeaders = Object.assign({}, request.headers || {});
|
|
337
|
+
Object.keys(reqHeaders).forEach(function (k) { var lk = k.toLowerCase(); if (lk === "proxy-authorization" || lk === "proxy-connection") delete reqHeaders[k]; });
|
|
260
338
|
if (body != null && body !== "") {
|
|
261
339
|
Object.keys(reqHeaders).forEach(function (k) { var lk = k.toLowerCase(); if (lk === "content-length" || lk === "transfer-encoding") delete reqHeaders[k]; });
|
|
262
340
|
reqHeaders["Content-Length"] = Buffer.byteLength(body);
|
|
@@ -292,13 +370,15 @@ function httpsTransport(defaults) {
|
|
|
292
370
|
return callerCsi(host, cert2);
|
|
293
371
|
};
|
|
294
372
|
}
|
|
373
|
+
var proxyInfo = _validateProxy(request, defaults, E, C, url);
|
|
295
374
|
var blockPrivate = (request.blockPrivateAddresses !== undefined ? request.blockPrivateAddresses : defaults.blockPrivateAddresses) === true;
|
|
375
|
+
if (blockPrivate && proxyInfo) throw E(C("bad-proxy"), "blockPrivateAddresses cannot be enforced through a forward proxy, which resolves the origin itself and would reach a private origin the transport never checks; use a direct connection for a private-address-blocked fetch");
|
|
296
376
|
if (blockPrivate) {
|
|
297
377
|
if (_isBlockedIp(host)) throw E(C("blocked-address"), "refusing to connect to the private / loopback / link-local address literal " + host);
|
|
298
378
|
options.lookup = _guardedLookup;
|
|
299
379
|
}
|
|
300
380
|
|
|
301
|
-
return { options: options, timeout: timeout, maxBytes: maxBytes, body: body };
|
|
381
|
+
return { options: options, timeout: timeout, maxBytes: maxBytes, body: body, proxy: proxyInfo, blockPrivate: blockPrivate, callerCsi: callerCsi };
|
|
302
382
|
}
|
|
303
383
|
|
|
304
384
|
var _transportFn = function transport(request) {
|
|
@@ -308,59 +388,138 @@ function httpsTransport(defaults) {
|
|
|
308
388
|
catch (e) { return Promise.reject(e); }
|
|
309
389
|
return new Promise(function (resolve, reject) {
|
|
310
390
|
var settled = false;
|
|
311
|
-
var req;
|
|
391
|
+
var req = null;
|
|
392
|
+
var creq = null;
|
|
393
|
+
var tunnelSocket = null;
|
|
312
394
|
var timer = null;
|
|
313
395
|
function clearTimer() { if (timer) { clearTimeout(timer); timer = null; } }
|
|
314
|
-
function
|
|
396
|
+
function _quietDestroy(x) {
|
|
397
|
+
// allow:swallow-unverified destroy() is idempotent and does not throw in practice; a
|
|
398
|
+
try { if (x) x.destroy(); } catch (_e) { }
|
|
399
|
+
}
|
|
400
|
+
function _settleReject(err) {
|
|
315
401
|
if (settled) return;
|
|
316
402
|
settled = true;
|
|
317
403
|
clearTimer();
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
404
|
+
_quietDestroy(req);
|
|
405
|
+
_quietDestroy(creq);
|
|
406
|
+
_quietDestroy(tunnelSocket);
|
|
407
|
+
reject(err);
|
|
321
408
|
}
|
|
409
|
+
function fail(code, msg, cause) { _settleReject(E(code, msg, cause)); }
|
|
322
410
|
timer = setTimeout(function () { fail(C("timeout"), "the request timed out after " + prep.timeout + "ms"); }, prep.timeout);
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
total
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
if (settled) return;
|
|
347
|
-
settled = true;
|
|
348
|
-
clearTimer();
|
|
349
|
-
var lower = {};
|
|
350
|
-
Object.keys(res.headers || {}).forEach(function (k) { lower[k.toLowerCase()] = res.headers[k]; });
|
|
351
|
-
resolve({
|
|
352
|
-
status: res.statusCode,
|
|
353
|
-
headers: lower,
|
|
354
|
-
body: Buffer.from(buf.subarray(0, len)),
|
|
355
|
-
tls: { protocol: proto, cipher: cipher, peerCertificate: peer && peer.raw ? peer.raw : null },
|
|
411
|
+
|
|
412
|
+
function issue(options) {
|
|
413
|
+
try {
|
|
414
|
+
req = nodeHttps.request(options, function (res) {
|
|
415
|
+
var proto = res.socket && res.socket.getProtocol ? res.socket.getProtocol() : null;
|
|
416
|
+
var cipher = res.socket && res.socket.getCipher ? res.socket.getCipher() : null;
|
|
417
|
+
var peer = res.socket && res.socket.getPeerCertificate ? res.socket.getPeerCertificate() : null;
|
|
418
|
+
var declared = parseInt((res.headers || {})["content-length"], 10);
|
|
419
|
+
if (Number.isFinite(declared) && declared > prep.maxBytes) { fail(C("response-too-large"), "the declared content-length " + declared + " exceeds the " + prep.maxBytes + "-byte cap (RFC 7030 sec. 6)"); return; }
|
|
420
|
+
var buf = Buffer.allocUnsafe(0);
|
|
421
|
+
var len = 0;
|
|
422
|
+
var total = 0;
|
|
423
|
+
res.on("data", function (chunk) {
|
|
424
|
+
total += chunk.length;
|
|
425
|
+
if (total > prep.maxBytes) { fail(C("response-too-large"), "the response exceeded the " + prep.maxBytes + "-byte cap (RFC 7030 sec. 6)"); return; }
|
|
426
|
+
if (len + chunk.length > buf.length) {
|
|
427
|
+
var want = Math.min(prep.maxBytes, Math.max(buf.length ? buf.length * 2 : 8192, len + chunk.length));
|
|
428
|
+
var grown = Buffer.allocUnsafe(want);
|
|
429
|
+
buf.copy(grown, 0, 0, len);
|
|
430
|
+
buf = grown;
|
|
431
|
+
}
|
|
432
|
+
chunk.copy(buf, len);
|
|
433
|
+
len += chunk.length;
|
|
356
434
|
});
|
|
435
|
+
res.on("end", function () {
|
|
436
|
+
if (settled) return;
|
|
437
|
+
settled = true;
|
|
438
|
+
clearTimer();
|
|
439
|
+
var lower = {};
|
|
440
|
+
Object.keys(res.headers || {}).forEach(function (k) { lower[k.toLowerCase()] = res.headers[k]; });
|
|
441
|
+
resolve({
|
|
442
|
+
status: res.statusCode,
|
|
443
|
+
headers: lower,
|
|
444
|
+
body: Buffer.from(buf.subarray(0, len)),
|
|
445
|
+
tls: { protocol: proto, cipher: cipher, peerCertificate: peer && peer.raw ? peer.raw : null },
|
|
446
|
+
});
|
|
447
|
+
});
|
|
448
|
+
res.on("error", function (e) { fail(C("transport-error"), "the response stream failed", e); });
|
|
357
449
|
});
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
450
|
+
req.on("error", function (e) { fail(_classifyError(e, C), "the request failed: " + ((e && e.message) || String(e)), e); });
|
|
451
|
+
if (prep.body != null && prep.body !== "") req.write(prep.body);
|
|
452
|
+
req.end();
|
|
453
|
+
} catch (e) { fail(C("transport-error"), "the request could not be initiated: " + ((e && e.message) || String(e)), e); }
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
if (!prep.proxy) { issue(prep.options); return; }
|
|
457
|
+
|
|
458
|
+
var pinfo = prep.proxy;
|
|
459
|
+
var pheaders = { Host: pinfo.originAuthority, Connection: "keep-alive" };
|
|
460
|
+
if (pinfo.auth) pheaders["Proxy-Authorization"] = _basicProxyHeader(pinfo.auth);
|
|
461
|
+
var connectOpts = { host: pinfo.host, port: pinfo.port, method: "CONNECT", path: pinfo.originAuthority, headers: pheaders, agent: false };
|
|
462
|
+
var cr;
|
|
463
|
+
try {
|
|
464
|
+
if (pinfo.secure) {
|
|
465
|
+
connectOpts.ca = pinfo.proxyTls.ca;
|
|
466
|
+
connectOpts.rejectUnauthorized = true;
|
|
467
|
+
connectOpts.minVersion = pinfo.proxyTls.minVersion;
|
|
468
|
+
var pIdentity = pinfo.proxyTls.servername || pinfo.host;
|
|
469
|
+
connectOpts.servername = (pIdentity && !nodeNet.isIP(pIdentity)) ? pIdentity : "";
|
|
470
|
+
connectOpts.checkServerIdentity = function (host, cert) { return nodeTls.checkServerIdentity(pIdentity, cert); };
|
|
471
|
+
cr = nodeHttps.request(connectOpts);
|
|
472
|
+
} else {
|
|
473
|
+
cr = nodeHttp.request(connectOpts);
|
|
474
|
+
}
|
|
475
|
+
} catch (e) { fail(C("proxy-connect-failed"), "the CONNECT request could not be initiated: " + ((e && e.message) || String(e)), e); return; }
|
|
476
|
+
creq = cr;
|
|
477
|
+
var done = false;
|
|
478
|
+
function onProxyResponse(res, socket) {
|
|
479
|
+
if (done) { if (socket) _quietDestroy(socket); return; }
|
|
480
|
+
done = true;
|
|
481
|
+
if (settled) { if (socket) _quietDestroy(socket); return; }
|
|
482
|
+
var sc = res.statusCode;
|
|
483
|
+
if (socket && sc >= 200 && sc < 300) {
|
|
484
|
+
tunnelSocket = socket;
|
|
485
|
+
creq = null;
|
|
486
|
+
socket.on("error", function (e) { fail(_classifyError(e, C), "the tunnel socket failed: " + ((e && e.message) || String(e)), e); });
|
|
487
|
+
var idHost = prep.options.servername || pinfo.originHost;
|
|
488
|
+
issue(Object.assign({}, prep.options, {
|
|
489
|
+
createConnection: function () {
|
|
490
|
+
return nodeTls.connect({
|
|
491
|
+
socket: socket,
|
|
492
|
+
host: prep.options.hostname,
|
|
493
|
+
servername: prep.options.servername,
|
|
494
|
+
ca: prep.options.ca,
|
|
495
|
+
minVersion: prep.options.minVersion,
|
|
496
|
+
rejectUnauthorized: true,
|
|
497
|
+
checkServerIdentity: function (host, cert) {
|
|
498
|
+
var baseErr = nodeTls.checkServerIdentity(idHost, cert);
|
|
499
|
+
if (baseErr) return baseErr;
|
|
500
|
+
return prep.callerCsi ? prep.callerCsi(idHost, cert) : undefined;
|
|
501
|
+
},
|
|
502
|
+
cert: prep.options.cert,
|
|
503
|
+
key: prep.options.key,
|
|
504
|
+
});
|
|
505
|
+
},
|
|
506
|
+
}));
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
if (socket) _quietDestroy(socket);
|
|
510
|
+
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; }
|
|
511
|
+
fail(C("proxy-connect-failed"), "the proxy answered CONNECT with HTTP " + sc);
|
|
512
|
+
}
|
|
513
|
+
cr.on("connect", function (res, socket) { onProxyResponse(res, socket); });
|
|
514
|
+
cr.on("response", function (res) {
|
|
515
|
+
// allow:swallow-unverified draining the proxy error body is best-effort; the verdict is the status
|
|
516
|
+
res.on("data", function () { });
|
|
517
|
+
res.on("error", function () { });
|
|
518
|
+
res.on("end", function () { });
|
|
519
|
+
onProxyResponse(res, null);
|
|
520
|
+
});
|
|
521
|
+
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); });
|
|
522
|
+
cr.end();
|
|
364
523
|
});
|
|
365
524
|
};
|
|
366
525
|
_transportFn.blocksPrivateAddresses = true;
|
package/lib/path-validate.js
CHANGED
|
@@ -964,14 +964,7 @@ async function validate(path, opts) {
|
|
|
964
964
|
var anchor = toAnchor(anchorList[0], "validate");
|
|
965
965
|
guard.time.assertValid(opts.time, E, "path/bad-input", "validate: opts.time (the always-on validity-window check date)");
|
|
966
966
|
guard.limits.cap(opts.maxPolicyNodes, "validate: opts.maxPolicyNodes", undefined, { E: E, code: "path/bad-input", min: 1 });
|
|
967
|
-
|
|
968
|
-
var uipsOk = intrinsic.isArray(opts.userInitialPolicySet) && opts.userInitialPolicySet.length > 0 &&
|
|
969
|
-
guard.list.allMatch(opts.userInitialPolicySet, function (p) { return typeof p === "string" && p.length > 0; });
|
|
970
|
-
if (!uipsOk) throw E("path/bad-input", "validate: opts.userInitialPolicySet must be a non-empty array of policy OID strings");
|
|
971
|
-
opts.userInitialPolicySet.forEach(function (p) {
|
|
972
|
-
guard.identifier.assertCanonicalOid(p, E, "path/bad-input", "validate: opts.userInitialPolicySet entry " + JSON.stringify(p));
|
|
973
|
-
});
|
|
974
|
-
}
|
|
967
|
+
_assertUserInitialPolicySet(opts.userInitialPolicySet, "validate");
|
|
975
968
|
var seeds = {
|
|
976
969
|
permitted: checkedSubtreeSeeds(opts.initialPermittedSubtrees, "initialPermittedSubtrees"),
|
|
977
970
|
excluded: checkedSubtreeSeeds(opts.initialExcludedSubtrees, "initialExcludedSubtrees"),
|
|
@@ -2136,6 +2129,37 @@ function _pickBuildDirection(leafCert, pool, anchors, fetchAia) {
|
|
|
2136
2129
|
return revFirstHop < fwdFirstHop ? "reverse" : "forward";
|
|
2137
2130
|
}
|
|
2138
2131
|
|
|
2132
|
+
function _policyScore(result, uips) {
|
|
2133
|
+
var ucps = result && result.userConstrainedPolicySet;
|
|
2134
|
+
if (!ucps) return 0;
|
|
2135
|
+
var n = 0;
|
|
2136
|
+
for (var i = 0; i < ucps.length; i++) {
|
|
2137
|
+
for (var j = 0; j < uips.length; j++) {
|
|
2138
|
+
if (ucps[i] === uips[j]) { n += 1; break; }
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
return n;
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
function _bestByPolicy(accepted, uips) {
|
|
2145
|
+
var best = accepted[0], bestScore = _policyScore(accepted[0].result, uips);
|
|
2146
|
+
for (var i = 1; i < accepted.length; i++) {
|
|
2147
|
+
var s = _policyScore(accepted[i].result, uips);
|
|
2148
|
+
if (s > bestScore) { best = accepted[i]; bestScore = s; }
|
|
2149
|
+
}
|
|
2150
|
+
return best;
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
function _assertUserInitialPolicySet(uips, prefix) {
|
|
2154
|
+
if (uips === undefined) return;
|
|
2155
|
+
var ok = intrinsic.isArray(uips) && uips.length > 0 &&
|
|
2156
|
+
guard.list.allMatch(uips, function (p) { return typeof p === "string" && p.length > 0; });
|
|
2157
|
+
if (!ok) throw E("path/bad-input", prefix + ": opts.userInitialPolicySet must be a non-empty array of policy OID strings");
|
|
2158
|
+
for (var i = 0; i < uips.length; i++) {
|
|
2159
|
+
guard.identifier.assertCanonicalOid(uips[i], E, "path/bad-input", prefix + ": opts.userInitialPolicySet entry " + guard.text.showValue(uips[i]));
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2139
2163
|
function _pushCandidates(frame, scored, stack, counter, down) {
|
|
2140
2164
|
scored.sort(function (a, b) { return a.score - b.score; });
|
|
2141
2165
|
var n = 0;
|
|
@@ -2281,7 +2305,7 @@ async function _fetchAiaIssuers(current, aia) {
|
|
|
2281
2305
|
* @opts maxAiaPerCert Cap on caIssuers URLs tried per certificate (default `C.LIMITS.PATH_AIA_MAX_PER_CERT`).
|
|
2282
2306
|
* @opts aiaTimeout Per-fetch timeout in ms, forwarded to the transport.
|
|
2283
2307
|
* @opts maxResponseBytes Per-fetch response size cap, forwarded to the transport (tightenable downward only).
|
|
2284
|
-
* @opts (validate options) Every `pki.path.validate` option (`requiredEku`, `revocationChecker`, `checkPurpose`, the initial policy inputs, ...) is forwarded unchanged.
|
|
2308
|
+
* @opts (validate options) Every `pki.path.validate` option (`requiredEku`, `revocationChecker`, `checkPurpose`, the initial policy inputs, ...) is forwarded unchanged. When `userInitialPolicySet` is supplied, build returns the accepted path whose user-constrained policy set best satisfies it (RFC 4158 sec. 4 forward policy chaining) rather than the first accepted path; `validate` still gates every path, so this changes only which valid path is chosen. The ranking explores more of the candidate graph than a first-accept build, so it is bounded by `maxCandidatesConsidered` like the rest of the search: a cap too tight for the ranking reaches `path/build-limit`. An `anyPolicy` entry makes the set unconstrained, so ranking is skipped and the first accepted path is returned.
|
|
2285
2309
|
* @example
|
|
2286
2310
|
* var pair = await pki.key.generate("Ed25519");
|
|
2287
2311
|
* var pemString = await pki.x509.sign({ subject: "Example Root", subjectPublicKey: await pki.key.export(pair.publicKey),
|
|
@@ -2384,6 +2408,21 @@ async function build(leaf, opts) {
|
|
|
2384
2408
|
var anyChainAssembled = false;
|
|
2385
2409
|
var bestFail = null;
|
|
2386
2410
|
var success = null;
|
|
2411
|
+
_assertUserInitialPolicySet(opts.userInitialPolicySet, "build");
|
|
2412
|
+
var uipsDistinct = null, selectByPolicy = false;
|
|
2413
|
+
if (doValidate && intrinsic.isArray(opts.userInitialPolicySet)) {
|
|
2414
|
+
uipsDistinct = [];
|
|
2415
|
+
var containsAny = false;
|
|
2416
|
+
for (var ui = 0; ui < opts.userInitialPolicySet.length; ui++) {
|
|
2417
|
+
var uip = opts.userInitialPolicySet[ui];
|
|
2418
|
+
if (uip === OID.anyPolicy) { containsAny = true; break; }
|
|
2419
|
+
var dupUip = false;
|
|
2420
|
+
for (var uj = 0; uj < uipsDistinct.length; uj++) { if (uipsDistinct[uj] === uip) { dupUip = true; break; } }
|
|
2421
|
+
if (!dupUip) intrinsic.push(uipsDistinct, uip);
|
|
2422
|
+
}
|
|
2423
|
+
selectByPolicy = !containsAny;
|
|
2424
|
+
}
|
|
2425
|
+
var accepted = selectByPolicy ? [] : null;
|
|
2387
2426
|
|
|
2388
2427
|
if (direction === "reverse") {
|
|
2389
2428
|
var rstack = [];
|
|
@@ -2397,8 +2436,12 @@ async function build(leaf, opts) {
|
|
|
2397
2436
|
if (!doValidate) { success = { path: rpath, trustAnchor: rframe.anchor }; break; }
|
|
2398
2437
|
anyChainAssembled = true;
|
|
2399
2438
|
var rres = await validate(rpath, validateOpts(rframe.anchor));
|
|
2400
|
-
if (rres.valid) {
|
|
2401
|
-
|
|
2439
|
+
if (rres.valid) {
|
|
2440
|
+
var racc = { valid: true, path: rpath, trustAnchor: rframe.anchor, result: rres };
|
|
2441
|
+
if (!selectByPolicy) { success = racc; break; }
|
|
2442
|
+
if (_policyScore(rres, uipsDistinct) >= uipsDistinct.length) { success = racc; break; }
|
|
2443
|
+
intrinsic.push(accepted, racc);
|
|
2444
|
+
} else if (!bestFail) bestFail = { path: rpath, trustAnchor: rframe.anchor, result: rres };
|
|
2402
2445
|
}
|
|
2403
2446
|
if (rframe.hop >= maxDepth) continue;
|
|
2404
2447
|
var rscored = [];
|
|
@@ -2457,8 +2500,12 @@ async function build(leaf, opts) {
|
|
|
2457
2500
|
if (!doValidate) { success = { path: frame.chain.slice(), trustAnchor: anchors[ai] }; break; }
|
|
2458
2501
|
anyChainAssembled = true;
|
|
2459
2502
|
var res = await validate(frame.chain, validateOpts(anchors[ai]));
|
|
2460
|
-
if (res.valid) {
|
|
2461
|
-
|
|
2503
|
+
if (res.valid) {
|
|
2504
|
+
var acc = { valid: true, path: frame.chain.slice(), trustAnchor: anchors[ai], result: res };
|
|
2505
|
+
if (!selectByPolicy) { success = acc; break; }
|
|
2506
|
+
if (_policyScore(res, uipsDistinct) >= uipsDistinct.length) { success = acc; break; }
|
|
2507
|
+
intrinsic.push(accepted, acc);
|
|
2508
|
+
} else if (!bestFail) bestFail = { path: frame.chain.slice(), trustAnchor: anchors[ai], result: res };
|
|
2462
2509
|
}
|
|
2463
2510
|
if (success || frame.hop >= maxDepth) continue;
|
|
2464
2511
|
|
|
@@ -2477,6 +2524,8 @@ async function build(leaf, opts) {
|
|
|
2477
2524
|
}
|
|
2478
2525
|
}
|
|
2479
2526
|
|
|
2527
|
+
if (selectByPolicy && !success && accepted.length) success = _bestByPolicy(accepted, uipsDistinct);
|
|
2528
|
+
|
|
2480
2529
|
var aiaFetches = aiaCtx ? aiaCtx.fetches : 0;
|
|
2481
2530
|
if (success) {
|
|
2482
2531
|
if (doValidate) return { valid: true, path: success.path, trustAnchor: success.trustAnchor, result: success.result, candidatesConsidered: considered, aiaFetches: aiaFetches };
|
package/lib/scep.js
CHANGED
|
@@ -685,6 +685,7 @@ function _pkiRequest(method, opUrl, reqMsg, clientOpts) {
|
|
|
685
685
|
}
|
|
686
686
|
function _drive(method, url, body, headers, opts, transport, budgets) {
|
|
687
687
|
var redirects = 0, curMethod = method, curBody = body, initialOrigin = url.origin;
|
|
688
|
+
var proxySnap = _snapshotProxy(opts.proxy);
|
|
688
689
|
var tlsBase = _tlsForRequest(opts);
|
|
689
690
|
var allowCrossOrigin = !!opts.allowCrossOriginRedirect;
|
|
690
691
|
function _hopTls(current) {
|
|
@@ -697,6 +698,7 @@ function _drive(method, url, body, headers, opts, transport, budgets) {
|
|
|
697
698
|
}
|
|
698
699
|
function step(current) {
|
|
699
700
|
var req = { method: curMethod, url: current.href, headers: headers, tls: _hopTls(current), timeout: budgets.timeout, maxResponseBytes: budgets.maxResponseBytes };
|
|
701
|
+
if (proxySnap != null) req.proxy = proxySnap;
|
|
700
702
|
if (curBody != null) req.body = curBody;
|
|
701
703
|
return transport(req).then(function (res) {
|
|
702
704
|
res = res || {};
|
|
@@ -715,6 +717,19 @@ function _drive(method, url, body, headers, opts, transport, budgets) {
|
|
|
715
717
|
}
|
|
716
718
|
return step(url);
|
|
717
719
|
}
|
|
720
|
+
function _copyAnchor(a) { return Buffer.isBuffer(a) ? Buffer.from(a) : a; }
|
|
721
|
+
function _snapshotProxy(p) {
|
|
722
|
+
if (p == null || typeof p !== "object" || Array.isArray(p)) return p;
|
|
723
|
+
var out = Object.assign({}, p);
|
|
724
|
+
if (p.auth != null && typeof p.auth === "object" && !Array.isArray(p.auth)) out.auth = Object.assign({}, p.auth);
|
|
725
|
+
if (p.tls != null && typeof p.tls === "object" && !Array.isArray(p.tls)) {
|
|
726
|
+
out.tls = Object.assign({}, p.tls);
|
|
727
|
+
var a = p.tls.anchors;
|
|
728
|
+
if (Array.isArray(a)) out.tls.anchors = a.map(_copyAnchor);
|
|
729
|
+
else if (a != null) out.tls.anchors = _copyAnchor(a);
|
|
730
|
+
}
|
|
731
|
+
return out;
|
|
732
|
+
}
|
|
718
733
|
function _client(method, url, body, headers, opts) {
|
|
719
734
|
var transport = opts.transport || httpTransport.https({ E: _err, errPrefix: "scep" });
|
|
720
735
|
var budgets = {
|
|
@@ -798,7 +813,7 @@ function _assertStrongProfile(caps, profile) {
|
|
|
798
813
|
* - `transport` -- an injected transport (defaults to `pki.transport.https`); the request is a GET with no body.
|
|
799
814
|
* - `expectSCEPStandard` -- refuse (`scep/weak-profile`) if the response does not advertise `SCEPStandard`.
|
|
800
815
|
* - `requireStrongProfile` -- refuse unless AES + SHA-256 + POSTPKIOperation are all advertised.
|
|
801
|
-
* - `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
|
|
816
|
+
* - `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` / `proxy` -- transport bounds (`proxy` reaches the CA through a forward HTTP proxy; see pki.transport).
|
|
802
817
|
* @example
|
|
803
818
|
* // requires: scepTransport -- an injected transport (omit to use pki.transport.https)
|
|
804
819
|
* var caps = await pki.scep.getCACaps("http://ca.example/scep", { transport: scepTransport });
|
|
@@ -870,7 +885,7 @@ function _normalizeFingerprint(fp, algName) {
|
|
|
870
885
|
* @opts
|
|
871
886
|
* - `expectedFingerprint` -- a hex string or Buffer; a returned certificate must hash to it, or the response is refused.
|
|
872
887
|
* - `fingerprintAlgorithm` -- the hash for the fingerprint (default "sha256").
|
|
873
|
-
* - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
|
|
888
|
+
* - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` / `proxy` -- transport bounds (`proxy` reaches the CA through a forward HTTP proxy; see pki.transport).
|
|
874
889
|
* @example
|
|
875
890
|
* // requires: scepCaCertTransport -- an injected transport returning a single CA certificate
|
|
876
891
|
* var ca = await pki.scep.getCACert("http://ca.example/scep", { transport: scepCaCertTransport });
|
|
@@ -925,7 +940,7 @@ async function getCACert(baseUrl, opts) {
|
|
|
925
940
|
*
|
|
926
941
|
* @opts
|
|
927
942
|
* - `caCertificate` -- the current SCEP CA certificate DER; the response is authenticated against its key (required).
|
|
928
|
-
* - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
|
|
943
|
+
* - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` / `proxy` -- transport bounds (`proxy` reaches the CA through a forward HTTP proxy; see pki.transport).
|
|
929
944
|
* @example
|
|
930
945
|
* // requires: caCertDer -- the current CA certificate (from getCACert), scepTransport
|
|
931
946
|
* var next = await pki.scep.getNextCACert("http://ca.example/scep", { caCertificate: caCertDer, transport: scepTransport });
|
|
@@ -1032,6 +1047,7 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
|
|
|
1032
1047
|
allowCrossOriginRedirect: opts.allowCrossOriginRedirect,
|
|
1033
1048
|
timeout: opts.timeout,
|
|
1034
1049
|
maxResponseBytes: opts.maxResponseBytes,
|
|
1050
|
+
proxy: _snapshotProxy(opts.proxy),
|
|
1035
1051
|
};
|
|
1036
1052
|
var postUrl = _scepUrl(baseUrl, "PKIOperation");
|
|
1037
1053
|
var httpMethod = _pkiMethod(opts);
|
|
@@ -1096,7 +1112,7 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
|
|
|
1096
1112
|
* - `sleep` -- an injectable sleeper `(ms) -> Promise` for the Retry-After wait (default a real timer).
|
|
1097
1113
|
* - `onRetryAfter` -- an optional observer `(delaySeconds) -> void` called before each poll sleep.
|
|
1098
1114
|
* - `httpMethod` -- `"POST"` (default) or `"GET"`. RFC 8894 sec. 4.1 sends the PKIOperation message over POST; `"GET"` carries it base64-encoded in the URL `message` query for a legacy CA that lacks POST.
|
|
1099
|
-
* - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
|
|
1115
|
+
* - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` / `proxy` -- transport bounds (`proxy` reaches the CA through a forward HTTP proxy; see pki.transport).
|
|
1100
1116
|
* @example
|
|
1101
1117
|
* // requires: scepCsr, caCertDer, clientCertDer, clientKeyPkcs8, scepTransport
|
|
1102
1118
|
* var out = await pki.scep.enroll("http://ca.example/scep", { csr: scepCsr, caCert: caCertDer,
|
|
@@ -1172,7 +1188,7 @@ async function _queryOperation(messageType, baseUrl, opts, verbName) {
|
|
|
1172
1188
|
var recipientKey = _captureRecipientKey(opts.recipientKey);
|
|
1173
1189
|
var signer = { cert: guard.bytes.snapshotSource(opts.signer.cert, ScepError, "scep/bad-input", "signer.cert"), key: opts.signer.key };
|
|
1174
1190
|
var want = _resolveQueryTarget(opts);
|
|
1175
|
-
var clientOpts = { transport: opts.transport, tls: opts.tls != null ? Object.assign({}, opts.tls) : opts.tls, maxRedirects: opts.maxRedirects, allowCrossOriginRedirect: opts.allowCrossOriginRedirect, timeout: opts.timeout, maxResponseBytes: opts.maxResponseBytes };
|
|
1191
|
+
var clientOpts = { transport: opts.transport, tls: opts.tls != null ? Object.assign({}, opts.tls) : opts.tls, maxRedirects: opts.maxRedirects, allowCrossOriginRedirect: opts.allowCrossOriginRedirect, timeout: opts.timeout, maxResponseBytes: opts.maxResponseBytes, proxy: _snapshotProxy(opts.proxy) };
|
|
1176
1192
|
var senderNonce = nodeCrypto.randomBytes(16);
|
|
1177
1193
|
var transactionId = opts.transactionId != null ? opts.transactionId : _defaultTransactionId();
|
|
1178
1194
|
var httpMethod = _pkiMethod(opts);
|
|
@@ -1211,7 +1227,7 @@ async function _queryOperation(messageType, baseUrl, opts, verbName) {
|
|
|
1211
1227
|
* - `responderCert` -- the certificate to authenticate the CA response signature against (defaults to `caCert`).
|
|
1212
1228
|
* - `transactionId` -- a caller-unique PrintableString (defaults to 16 random bytes, hex-encoded).
|
|
1213
1229
|
* - `httpMethod` -- `"POST"` (default) or `"GET"`. RFC 8894 sec. 4.1 sends the PKIOperation message over POST; `"GET"` carries it base64-encoded in the URL `message` query for a legacy CA that lacks POST.
|
|
1214
|
-
* - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
|
|
1230
|
+
* - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` / `proxy` -- transport bounds (`proxy` reaches the CA through a forward HTTP proxy; see pki.transport).
|
|
1215
1231
|
* @example
|
|
1216
1232
|
* // requires: clientCertDer, caCertDer, clientKeyPkcs8, scepTransport
|
|
1217
1233
|
* var out = await pki.scep.getCert("http://ca.example/scep", { certificate: clientCertDer, caCert: caCertDer,
|
|
@@ -1260,7 +1276,7 @@ async function getCert(baseUrl, opts) {
|
|
|
1260
1276
|
* - `responderCert` -- the certificate to authenticate the CA response against (defaults to `caCert`).
|
|
1261
1277
|
* - `transactionId` -- a caller-unique PrintableString (defaults to 16 random bytes, hex-encoded).
|
|
1262
1278
|
* - `httpMethod` -- `"POST"` (default) or `"GET"`. RFC 8894 sec. 4.1 sends the PKIOperation message over POST; `"GET"` carries it base64-encoded in the URL `message` query for a legacy CA that lacks POST.
|
|
1263
|
-
* - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
|
|
1279
|
+
* - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` / `proxy` -- transport bounds (`proxy` reaches the CA through a forward HTTP proxy; see pki.transport).
|
|
1264
1280
|
* @example
|
|
1265
1281
|
* // requires: clientCertDer, caCertDer, clientKeyPkcs8, scepTransport
|
|
1266
1282
|
* var out = await pki.scep.getCrl("http://ca.example/scep", { certificate: clientCertDer, caCert: caCertDer,
|
|
@@ -1283,7 +1299,7 @@ async function getCrl(baseUrl, opts) {
|
|
|
1283
1299
|
return { crl: match, crls: crls, transactionId: q.transactionId };
|
|
1284
1300
|
}
|
|
1285
1301
|
|
|
1286
|
-
var _TRANSPORT_KEYS = { transport: 1, timeout: 1, maxResponseBytes: 1, maxRedirects: 1, tls: 1, allowCrossOriginRedirect: 1 };
|
|
1302
|
+
var _TRANSPORT_KEYS = { transport: 1, timeout: 1, maxResponseBytes: 1, maxRedirects: 1, tls: 1, allowCrossOriginRedirect: 1, proxy: 1 };
|
|
1287
1303
|
function _withKeys(extra) { var o = {}, k; for (k in _TRANSPORT_KEYS) o[k] = 1; for (k in extra) o[k] = 1; return o; }
|
|
1288
1304
|
var _CACAPS_KEYS = _withKeys({ expectSCEPStandard: 1, requireStrongProfile: 1 });
|
|
1289
1305
|
var _CACERT_KEYS = _withKeys({ expectedFingerprint: 1, fingerprintAlgorithm: 1 });
|
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:9742df6c-59a0-4fce-a64b-ddc916ee2fba",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-09-
|
|
8
|
+
"timestamp": "2026-09-02T20:36:04.064Z",
|
|
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.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.6.27",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.6.
|
|
25
|
+
"version": "0.6.27",
|
|
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.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/pki@0.6.27",
|
|
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.
|
|
57
|
+
"ref": "@blamejs/pki@0.6.27",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|