@blamejs/pki 0.6.27 → 0.6.29

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,22 @@ 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.29 — 2026-09-03
8
+
9
+ The EST, ACME, and CMP clients reach a CA through a forward HTTP proxy, with the same opts.proxy the SCEP client already accepts.
10
+
11
+ ### Added
12
+
13
+ - pki.est.cacerts / simpleenroll / simplereenroll / serverkeygen / csrattrs / fullcmc, pki.acme.client, pki.cmp.transfer, and the pki.cmp.session client (which forwards it to every enrollment, polling, revocation, and confirmation leg) accept opts.proxy = { url, auth?, tls? } to reach the CA through a forward HTTP proxy, the same option pki.scep accepts. The origin TLS is negotiated inside the proxy's CONNECT tunnel under the identical origin trust policy; Basic authentication (RFC 7617) is sent only over an https:// proxy verified against proxy.tls, and an http:// proxy is tunnel-only. The option is deep-copied at the call so a later change to the caller's object cannot alter the proxy in use.
14
+
15
+ ## v0.6.28 — 2026-09-02
16
+
17
+ pki.path.build returns the best accepted path when the candidate cap is reached during policy ranking, instead of discarding it.
18
+
19
+ ### Fixed
20
+
21
+ - pki.path.build with userInitialPolicySet no longer throws path/build-limit after it has already accepted a valid path. When the candidate cap is reached during policy ranking, it returns the best-policy accepted path (forward and reverse directions), and candidatesConsidered reflects the full expansion count. It throws path/build-limit only when no valid path was accepted before the cap. This restores the pre-0.6.26 behavior for a policy set that no single path fully covers under a bounded search.
22
+
7
23
  ## v0.6.27 — 2026-09-02
8
24
 
9
25
  The SCEP client can reach a CA through a forward proxy, with Basic authentication over an https proxy.
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. `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`, 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` |
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. 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` |
package/lib/acme.js CHANGED
@@ -1765,6 +1765,7 @@ function _parseLinkNext(headers, base) { var m = _parseLinkRelation(headers, bas
1765
1765
  * - `transport` -- injectable transport(request) -> {status, headers, body}; default pki.transport.https.
1766
1766
  * - `tls` -- { anchors, useSystemStore, cert, key, minVersion, servername, checkServerIdentity } for the default transport.
1767
1767
  * - `timeout` / `maxResponseBytes` / `maxRedirects` -- transport budgets; `maxNonceRetries` -- badNonce retry cap (default 1).
1768
+ * - `proxy` -- reach the ACME server through a forward HTTP proxy (`{ url, auth?, tls? }`; see pki.transport).
1768
1769
  * - `maxPolls` / `maxTotalWait` / `sleep` -- poll-loop budgets + an injectable sleeper; `clock` -- an injectable receipt clock (default Date.now) for a Retry-After HTTP-date.
1769
1770
  * - `resignKeys` -- optional ordered `[{ alg, key }]` enabling the RFC 8555 sec. 6.2 badSignatureAlgorithm re-sign. When a CA rejects the account `alg` and advertises the algs it supports, the first entry whose `alg` the CA advertised re-signs the request once and retries. Each `key` is a CryptoKey for the SAME account key material under that `alg`: an RSA account key signs RS256 and PS256 from one key, and its registered public JWK verifies either. The caller's order selects and the CA's list only filters, so a spoofed badSignatureAlgorithm cannot force a weaker alg (sec. 10). Absent, or with no advertised match, the badSignatureAlgorithm surfaces unchanged.
1770
1771
  * - `newAuthz(identifier)` -- pre-authorize a single identifier (RFC 8555 sec. 7.4.1) -> { authorization, url }.
@@ -1778,7 +1779,7 @@ function _parseLinkNext(headers, base) { var m = _parseLinkRelation(headers, bas
1778
1779
  */
1779
1780
  var _CLIENT_OPTS = {
1780
1781
  accountKey: 1, accountJwk: 1, alg: 1, resignKeys: 1, transport: 1, tls: 1, timeout: 1, maxResponseBytes: 1,
1781
- maxRedirects: 1, maxNonceRetries: 1, maxPolls: 1, maxTotalWait: 1, sleep: 1, clock: 1,
1782
+ maxRedirects: 1, maxNonceRetries: 1, maxPolls: 1, maxTotalWait: 1, sleep: 1, clock: 1, proxy: 1,
1782
1783
  };
1783
1784
  var _METHOD_OPTS = {
1784
1785
  finalize: { csr: 1, identifiers: 1 },
@@ -1845,6 +1846,7 @@ function client(directoryUrl, opts) {
1845
1846
  }
1846
1847
  var budgets = {
1847
1848
  tls: _clientTls(opts),
1849
+ proxy: httpTransport.snapshotProxy(opts.proxy),
1848
1850
  timeout: guard.limits.cap(opts.timeout, "timeout", CLIENT_DEFAULT_TIMEOUT, { E: E, code: "acme/bad-input", min: 1, max: CLIENT_MAX_TIMEOUT }),
1849
1851
  maxResponseBytes: guard.limits.cap(opts.maxResponseBytes, "maxResponseBytes", constants.LIMITS.HTTP_MAX_RESPONSE_BYTES, { E: E, code: "acme/bad-input", min: 1, max: constants.LIMITS.HTTP_MAX_RESPONSE_BYTES }),
1850
1852
  maxRedirects: guard.limits.cap(opts.maxRedirects, "maxRedirects", 5, { E: E, code: "acme/bad-input", min: 0, max: 32 }),
@@ -1908,7 +1910,7 @@ function client(directoryUrl, opts) {
1908
1910
  function _send(method, url, headers, body) { return _sendFollowing(method, url, headers, body, 0); }
1909
1911
  function _sendFollowing(method, url, headers, body, redirects) {
1910
1912
  var reqHeaders = Object.assign({ "user-agent": CLIENT_USER_AGENT }, headers || {});
1911
- return transport({ method: method, url: url, headers: reqHeaders, body: body, tls: _tlsFor(url), timeout: budgets.timeout, maxResponseBytes: budgets.maxResponseBytes }).then(function (res) {
1913
+ return transport({ method: method, url: url, headers: reqHeaders, body: body, tls: _tlsFor(url), proxy: budgets.proxy, timeout: budgets.timeout, maxResponseBytes: budgets.maxResponseBytes }).then(function (res) {
1912
1914
  res = res || {};
1913
1915
  var h = {};
1914
1916
  Object.keys(res.headers || {}).forEach(function (k) { h[k.toLowerCase()] = res.headers[k]; });
package/lib/cmp-build.js CHANGED
@@ -735,7 +735,7 @@ var DEFAULT_TRANSFER_TIMEOUT = constants.TIME.seconds(30);
735
735
  var MAX_TRANSFER_TIMEOUT = constants.TIME.seconds(600);
736
736
  var PKIXCMP = "application/pkixcmp";
737
737
  var PKIXCMP_POLL = "application/pkixcmp-poll";
738
- var KNOWN_TRANSFER_OPTS = { transport: 1, tls: 1, headers: 1, timeout: 1, maxResponseBytes: 1 };
738
+ var KNOWN_TRANSFER_OPTS = { transport: 1, tls: 1, headers: 1, timeout: 1, maxResponseBytes: 1, proxy: 1 };
739
739
 
740
740
  function _cmpMessageDer(input) {
741
741
  var der;
@@ -799,6 +799,9 @@ function _transfer(url, message, opts) {
799
799
  }
800
800
  var timeout = guard.limits.cap(opts.timeout, "timeout", DEFAULT_TRANSFER_TIMEOUT, { E: _err, code: "cmp/bad-input", min: 1, max: MAX_TRANSFER_TIMEOUT });
801
801
  var maxResponseBytes = guard.limits.cap(opts.maxResponseBytes, "maxResponseBytes", constants.LIMITS.HTTP_MAX_RESPONSE_BYTES, { E: _err, code: "cmp/bad-input", min: 1, max: constants.LIMITS.HTTP_MAX_RESPONSE_BYTES });
802
+ var proxy;
803
+ try { proxy = httpTransport.snapshotProxy(opts.proxy); }
804
+ catch (e) { throw _err("cmp/bad-input", "the options object could not be read", e); }
802
805
  var headers = {};
803
806
  Object.keys(opts.headers || {}).forEach(function (k) {
804
807
  var lk = k.toLowerCase();
@@ -806,7 +809,7 @@ function _transfer(url, message, opts) {
806
809
  });
807
810
  headers["content-type"] = PKIXCMP;
808
811
  var tls = _tlsForTransfer(opts);
809
- return Promise.resolve(transport({ method: "POST", url: parsedUrl.href, headers: headers, body: der, tls: tls, timeout: timeout, maxResponseBytes: maxResponseBytes })).then(function (res) {
812
+ return Promise.resolve(transport({ method: "POST", url: parsedUrl.href, headers: headers, body: der, tls: tls, proxy: proxy, timeout: timeout, maxResponseBytes: maxResponseBytes })).then(function (res) {
810
813
  res = res || {};
811
814
  var h = {};
812
815
  Object.keys(res.headers || {}).forEach(function (k) { h[k.toLowerCase()] = res.headers[k]; });
@@ -900,6 +903,7 @@ function wellKnownUrl(base, opts) {
900
903
  * overridable (any casing), and the request-framing headers (`content-length`, `transfer-encoding`) are
901
904
  * stripped -- the transport computes Content-Length from the exact body, so a caller cannot desync framing.
902
905
  * - `timeout` -- ms (default 30s); `maxResponseBytes` -- streaming cap, tightenable downward only.
906
+ * - `proxy` -- reach the CA through a forward HTTP proxy (`{ url, auth?, tls? }`; see pki.transport).
903
907
  * @example
904
908
  * var reqDer = await pki.cmp.build(
905
909
  * { header: { sender: { directoryName: "CN=client" }, recipient: { directoryName: "CN=CA" } },
@@ -21,6 +21,7 @@ var webcrypto = require("./webcrypto");
21
21
  var frameworkError = require("./framework-error");
22
22
  var sleepUtil = require("./sleep");
23
23
  var retryAfter = require("./http-retry-after");
24
+ var httpTransport = require("./http-transport");
24
25
 
25
26
  var CmpError = frameworkError.CmpError;
26
27
  function _err(code, message, cause) { return new CmpError(code, message, cause); }
@@ -52,7 +53,7 @@ var COMPOSITE_PH_HASHALG = { "SHA-256": "sha256", "SHA-384": "sha384", "SHA-512"
52
53
  var KNOWN_SESSION_OPTS = {
53
54
  url: 1, key: 1, cert: 1, mac: 1, trustAnchors: 1, intermediates: 1, recipient: 1, sender: 1,
54
55
  extraCerts: 1, implicitConfirm: 1, maxPolls: 1, maxTotalWait: 1, sleep: 1, time: 1,
55
- transport: 1, tls: 1, headers: 1, timeout: 1, maxResponseBytes: 1, pss: 1, digestAlgorithm: 1,
56
+ transport: 1, tls: 1, headers: 1, timeout: 1, maxResponseBytes: 1, proxy: 1, pss: 1, digestAlgorithm: 1,
56
57
  acceptCert: 1, senderKID: 1, recipKID: 1, expectedSender: 1,
57
58
  };
58
59
 
@@ -286,6 +287,7 @@ function _certConfHash(certDer) {
286
287
  * - `acceptCert` -- an async policy `(certDer, { status, grantedWithMods }) => boolean` consulted before the certConf; return true to accept, anything else to veto (a `grantedWithMods` certificate the CA changed). A veto sends a rejecting certConf and yields `outcome: "rejected"` with the certificate still surfaced. Incompatible with `implicitConfirm` (no reject leg exists), so the combination throws at construction.
287
288
  * - `transport` -- injectable transport(request) -> {status, headers, body}; default pki.transport.https.
288
289
  * - `tls` / `headers` / `timeout` / `maxResponseBytes` -- transport config + budgets.
290
+ * - `proxy` -- reach the CA through a forward HTTP proxy (`{ url, auth?, tls? }`; see pki.transport).
289
291
  * - `maxPolls` / `maxTotalWait` / `sleep` -- poll-loop budgets + an injectable sleeper; `time` -- verify-time clock.
290
292
  * - `extraCerts` / `pss` / `digestAlgorithm` -- passed through to the request protection build.
291
293
  * @example
@@ -304,6 +306,7 @@ function _certConfHash(certDer) {
304
306
  function session(opts) {
305
307
  if (opts == null) opts = {};
306
308
  guard.identifier.assertPlainRecord(opts, _err, "cmp/bad-input", "opts");
309
+ guard.identifier.optionsObject(opts, _err, "cmp/bad-input", "opts");
307
310
  guard.identifier.assertKnownKeys(opts, KNOWN_SESSION_OPTS, _err, "cmp/bad-input", "unknown session opts field ");
308
311
  opts = Object.assign({}, opts);
309
312
  if (typeof opts.url !== "string" || !opts.url) throw _err("cmp/bad-input", "opts.url (the CMP endpoint) is required");
@@ -319,6 +322,7 @@ function session(opts) {
319
322
  if (isMac && Array.isArray(opts.trustAnchors) && opts.trustAnchors.length === 0) opts.trustAnchors = null;
320
323
  if (opts.trustAnchors != null && _engine && _engine.toAnchor) _asCertList(opts.trustAnchors).forEach(function (a) { try { _engine.toAnchor(a); } catch (e) { throw _err("cmp/bad-input", "opts.trustAnchors: each entry must be a certificate (DER/PEM/parsed) or a { name, publicKey, algorithm } anchor tuple -- " + ((e && e.message) || e), e); } });
321
324
  if (opts.intermediates != null && _engine && _engine.coerceCert) _asCertList(opts.intermediates).forEach(function (c) { try { _engine.coerceCert(c); } catch (e) { throw _err("cmp/bad-input", "opts.intermediates: each entry must be a certificate (DER/PEM/parsed) -- " + ((e && e.message) || e), e); } });
325
+ var _proxySnap = httpTransport.snapshotProxy(opts.proxy);
322
326
  var _expectedSenderCert = null;
323
327
  var _expectedSenderDer = null;
324
328
  if (opts.expectedSender != null) {
@@ -428,6 +432,7 @@ function session(opts) {
428
432
  function _transferOpts() {
429
433
  var o = {};
430
434
  ["transport", "tls", "headers", "timeout", "maxResponseBytes"].forEach(function (k) { if (opts[k] != null) o[k] = opts[k]; });
435
+ if (_proxySnap != null) o.proxy = _proxySnap;
431
436
  return o;
432
437
  }
433
438
 
package/lib/constants.js CHANGED
@@ -125,6 +125,7 @@ var LIMITS = {
125
125
  SCT_MAX_BYTES: BYTES.kib(64) + 1,
126
126
  SCT_MAX_COUNT: 256,
127
127
  MERKLE_MAX_PROOF_NODES: 65,
128
+ PROXY_MAX_TLS_ANCHORS: 256,
128
129
  PATH_MAX_CERTS: 100,
129
130
  PATH_MAX_POLICY_NODES: 4096,
130
131
  PATH_BUILD_MAX_DEPTH: 20,
package/lib/est.js CHANGED
@@ -100,7 +100,7 @@ var OPERATIONS = ["cacerts", "simpleenroll", "simplereenroll", "fullcmc", "serve
100
100
 
101
101
  var CLIENT_OPTS = {
102
102
  transport: 1, tls: 1, label: 1, timeout: 1, maxResponseBytes: 1, maxRedirects: 1, now: 1,
103
- auth: 1, username: 1, password: 1, allowCrossOriginRedirect: 1,
103
+ auth: 1, username: 1, password: 1, allowCrossOriginRedirect: 1, proxy: 1,
104
104
  };
105
105
  function _withClient(extra) {
106
106
  var out = {};
@@ -133,6 +133,9 @@ function _knownOpts(opts, known, verb) {
133
133
  });
134
134
  }
135
135
 
136
+ function _snapProxy(opts) { return httpTransport.snapshotProxy(opts.proxy); }
137
+ function _rej(e) { return Promise.reject(e); }
138
+
136
139
 
137
140
  /**
138
141
  * @primitive pki.est.transferDecode
@@ -846,7 +849,7 @@ function _drive(method, url, body, headers, opts, transport, budgets) {
846
849
  return hh;
847
850
  }
848
851
  function step() {
849
- return transport({ method: method, url: url.href, headers: _headersFor(url), body: body, tls: _tlsFor(url), timeout: budgets.timeout, maxResponseBytes: budgets.maxResponseBytes }).then(function (res) {
852
+ return transport({ method: method, url: url.href, headers: _headersFor(url), body: body, tls: _tlsFor(url), proxy: budgets.proxy, timeout: budgets.timeout, maxResponseBytes: budgets.maxResponseBytes }).then(function (res) {
850
853
  res = res || {};
851
854
  var blen = _bodyLen(res);
852
855
  if (blen > budgets.maxResponseBytes) throw E("est/response-too-large", "the response body (" + blen + " bytes) exceeds the " + budgets.maxResponseBytes + "-byte cap (RFC 7030 sec. 6)");
@@ -909,7 +912,7 @@ function _drive(method, url, body, headers, opts, transport, budgets) {
909
912
  return step();
910
913
  }
911
914
 
912
- function _client(op, method, baseUrl, body, headers, opts) {
915
+ function _client(op, method, baseUrl, body, headers, opts, proxySnap) {
913
916
  var base;
914
917
  try { base = new URL(String(baseUrl)); }
915
918
  catch (e) { throw E("est/bad-url", "the EST base URL did not parse: " + guard.text.showValue(baseUrl), e); }
@@ -924,6 +927,7 @@ function _client(op, method, baseUrl, body, headers, opts) {
924
927
  }
925
928
  var budgets = {
926
929
  tls: _tlsForRequest(opts),
930
+ proxy: proxySnap,
927
931
  timeout: guard.limits.cap(opts.timeout, "timeout", DEFAULT_TIMEOUT, { E: E, code: "est/bad-input", min: 1, max: MAX_TIMEOUT }),
928
932
  maxResponseBytes: guard.limits.cap(opts.maxResponseBytes, "maxResponseBytes", constants.LIMITS.HTTP_MAX_RESPONSE_BYTES, { E: E, code: "est/bad-input", min: 1, max: constants.LIMITS.HTTP_MAX_RESPONSE_BYTES }),
929
933
  maxRedirects: guard.limits.cap(opts.maxRedirects, "maxRedirects", 5, { E: E, code: "est/bad-input", min: 0, max: 32 }),
@@ -1012,7 +1016,7 @@ function _certsResult(op, res, opts, csrSpki) {
1012
1016
  * response is SURFACED, never acted on (RFC 5272 sec. 6.15 makes accepting one a manual decision).
1013
1017
  *
1014
1018
  * @opts
1015
- * - `transport` / `tls` / `label` / `timeout` / `maxResponseBytes` / `maxRedirects` / `now`, as in pki.est.cacerts.
1019
+ * - `transport` / `tls` / `label` / `timeout` / `maxResponseBytes` / `maxRedirects` / `proxy` / `now`, as in pki.est.cacerts.
1016
1020
  * - `transactionId` / `senderNonce` / `dataReturn`: what the request sent. The values are read out
1017
1021
  * of the request itself; supplying them here cross-checks that, and a disagreement is refused.
1018
1022
  * - `responderCerts`: extra certificates for CMC signer lookup, for a response that does not carry
@@ -1049,16 +1053,18 @@ function fullcmc(baseUrl, request, opts) {
1049
1053
  try {
1050
1054
  if (typeof opts !== "object" || Buffer.isBuffer(opts)) throw E("est/bad-input", "pki.est.fullcmc options must be an object");
1051
1055
  _knownOpts(opts, FULLCMC_OPTS, "fullcmc");
1056
+ var proxySnap;
1057
+ try { proxySnap = _snapProxy(opts); } catch (_pe) { throw E("est/bad-input", "the options object could not be read", _pe); }
1052
1058
  der = _cmcRequestDer(request);
1053
1059
  wanted = _requestedPublicKeys(der);
1054
1060
  sent = _cmcSent(opts, der);
1055
1061
  opts = _shallowCopy(opts);
1056
1062
  var body = transferEncode(der);
1057
1063
  return _client("fullcmc", "POST", baseUrl, body,
1058
- { accept: "application/pkcs7-mime", "content-type": "application/pkcs7-mime; smime-type=CMC-request" }, opts)
1064
+ { accept: "application/pkcs7-mime", "content-type": "application/pkcs7-mime; smime-type=CMC-request" }, opts, proxySnap)
1059
1065
  .then(function (res) { return _fullcmcResult(res, opts, wanted, sent); });
1060
1066
  } catch (e) {
1061
- return Promise.reject(e);
1067
+ return _rej(e);
1062
1068
  }
1063
1069
  }
1064
1070
 
@@ -1357,11 +1363,11 @@ function _tryDecodeCmcFault(res, sent) {
1357
1363
  }).then(null, function () { return null; });
1358
1364
  }
1359
1365
 
1360
- function _enroll(op, baseUrl, csrInput, opts) {
1366
+ function _enroll(op, baseUrl, csrInput, opts, proxySnap) {
1361
1367
  var csrDer = _csrDer(csrInput);
1362
1368
  var spki = csr.parse(csrDer).subjectPublicKeyInfo;
1363
1369
  var body = transferEncode(csrDer);
1364
- return _client(op, "POST", baseUrl, body, { accept: "application/pkcs7-mime", "content-type": "application/pkcs10" }, opts)
1370
+ return _client(op, "POST", baseUrl, body, { accept: "application/pkcs7-mime", "content-type": "application/pkcs10" }, opts, proxySnap)
1365
1371
  .then(function (res) { return _certsResult(op, res, opts, spki); });
1366
1372
  }
1367
1373
 
@@ -1386,6 +1392,7 @@ function _enroll(op, baseUrl, csrInput, opts) {
1386
1392
  * - `transport`: an injected transport(request) -> {status, headers, body, tls}; default pki.transport.https.
1387
1393
  * - `tls` -- { anchors, useSystemStore, cert, key, minVersion, servername, checkServerIdentity }.
1388
1394
  * - `label` -- an OPTIONAL CA label path segment; `timeout` / `maxResponseBytes` / `maxRedirects` -- budgets.
1395
+ * - `proxy` -- reach the CA through a forward HTTP proxy (`{ url, auth?, tls? }`; see pki.transport).
1389
1396
  * - `now` -- receipt time (epoch ms) to render a 202 Retry-After HTTP-date as seconds.
1390
1397
  * - `auth` -- HTTP authentication: `{ scheme: "basic" | "digest", username, password, allowMD5, allowLegacyQop, maxStaleRetries }`.
1391
1398
  * There is no `"auto"`: the scheme is chosen here, not by whatever a server offers. `username` / `password`
@@ -1399,9 +1406,10 @@ function _enroll(op, baseUrl, csrInput, opts) {
1399
1406
  */
1400
1407
  function cacerts(baseUrl, opts) {
1401
1408
  opts = opts || {};
1409
+ var proxySnap; try { proxySnap = _snapProxy(opts); } catch (_pe) { return _rej(E("est/bad-input", "the options object could not be read", _pe)); }
1402
1410
  return Promise.resolve().then(function () {
1403
1411
  _knownOpts(opts, CACERTS_OPTS, "cacerts");
1404
- return _client("cacerts", "GET", baseUrl, null, { accept: "application/pkcs7-mime" }, opts);
1412
+ return _client("cacerts", "GET", baseUrl, null, { accept: "application/pkcs7-mime" }, opts, proxySnap);
1405
1413
  }).then(function (res) { return _certsResult("cacerts", res, opts, null); });
1406
1414
  }
1407
1415
 
@@ -1424,7 +1432,7 @@ function cacerts(baseUrl, opts) {
1424
1432
  * the transport already authenticated the server.
1425
1433
  *
1426
1434
  * @opts
1427
- * - `transport` / `tls` / `label` / `timeout` / `maxResponseBytes` / `maxRedirects` / `now`, as in pki.est.cacerts.
1435
+ * - `transport` / `tls` / `label` / `timeout` / `maxResponseBytes` / `maxRedirects` / `proxy` / `now`, as in pki.est.cacerts.
1428
1436
  * - `strict`: reject an enroll response that carries more than the single issued certificate.
1429
1437
  * - `username` / `password` -- HTTP Basic credentials, answered only after server authorization (empty username allowed).
1430
1438
  * - `allowCrossOriginRedirect` -- opt in to following a cross-origin redirect on this POST.
@@ -1437,9 +1445,10 @@ function cacerts(baseUrl, opts) {
1437
1445
  */
1438
1446
  function simpleenroll(baseUrl, csrInput, opts) {
1439
1447
  opts = opts || {};
1448
+ var proxySnap; try { proxySnap = _snapProxy(opts); } catch (_pe) { return _rej(E("est/bad-input", "the options object could not be read", _pe)); }
1440
1449
  return Promise.resolve().then(function () {
1441
1450
  _knownOpts(opts, SIMPLEENROLL_OPTS, "simpleenroll");
1442
- return _enroll("simpleenroll", baseUrl, csrInput, opts);
1451
+ return _enroll("simpleenroll", baseUrl, csrInput, opts, proxySnap);
1443
1452
  });
1444
1453
  }
1445
1454
 
@@ -1470,11 +1479,12 @@ function simpleenroll(baseUrl, csrInput, opts) {
1470
1479
  */
1471
1480
  function simplereenroll(baseUrl, csrInput, opts) {
1472
1481
  opts = opts || {};
1482
+ var proxySnap; try { proxySnap = _snapProxy(opts); } catch (_pe) { return _rej(E("est/bad-input", "the options object could not be read", _pe)); }
1473
1483
  return Promise.resolve().then(function () {
1474
1484
  _knownOpts(opts, SIMPLEREENROLL_OPTS, "simplereenroll");
1475
1485
  if (!opts.oldCert) throw E("est/bad-input", "simplereenroll requires opts.oldCert (the certificate being renewed, RFC 7030 sec. 4.2.2)");
1476
1486
  reenrollGuard(opts.oldCert, _csrDer(csrInput));
1477
- return _enroll("simplereenroll", baseUrl, csrInput, opts);
1487
+ return _enroll("simplereenroll", baseUrl, csrInput, opts, proxySnap);
1478
1488
  });
1479
1489
  }
1480
1490
 
@@ -1613,6 +1623,7 @@ async function _serverkeygenResult(res, opts, derived) {
1613
1623
  */
1614
1624
  function serverkeygen(baseUrl, csrInput, opts) {
1615
1625
  opts = opts || {};
1626
+ var proxySnap; try { proxySnap = _snapProxy(opts); } catch (_pe) { return _rej(E("est/bad-input", "the options object could not be read", _pe)); }
1616
1627
  return Promise.resolve().then(function () {
1617
1628
  _knownOpts(opts, SERVERKEYGEN_OPTS, "serverkeygen");
1618
1629
  var csrDer = _csrDer(csrInput);
@@ -1631,7 +1642,7 @@ function serverkeygen(baseUrl, csrInput, opts) {
1631
1642
  if ((opts.expectedRecipientKeyId !== undefined || opts.expectedRecipientIssuerSerial != null) && !derived.requestedEncryption) {
1632
1643
  throw E("est/bad-input", "a recipient expectation (expectedRecipientKeyId / expectedRecipientIssuerSerial) implies an encrypted key, but the CSR advertised no DecryptKeyIdentifier / AsymmetricDecryptKeyIdentifier attribute (RFC 7030 sec. 4.4.1)");
1633
1644
  }
1634
- return _client("serverkeygen", "POST", baseUrl, transferEncode(csrDer), { accept: "multipart/mixed", "content-type": "application/pkcs10" }, opts)
1645
+ return _client("serverkeygen", "POST", baseUrl, transferEncode(csrDer), { accept: "multipart/mixed", "content-type": "application/pkcs10" }, opts, proxySnap)
1635
1646
  .then(function (res) { return _serverkeygenResult(res, opts, derived); });
1636
1647
  });
1637
1648
  }
@@ -1673,9 +1684,10 @@ function _csrattrsResult(res, opts) {
1673
1684
  */
1674
1685
  function csrattrs(baseUrl, opts) {
1675
1686
  opts = opts || {};
1687
+ var proxySnap; try { proxySnap = _snapProxy(opts); } catch (_pe) { return _rej(E("est/bad-input", "the options object could not be read", _pe)); }
1676
1688
  return Promise.resolve().then(function () {
1677
1689
  _knownOpts(opts, CSRATTRS_OPTS, "csrattrs");
1678
- return _client("csrattrs", "GET", baseUrl, null, { accept: "application/csrattrs" }, opts);
1690
+ return _client("csrattrs", "GET", baseUrl, null, { accept: "application/csrattrs" }, opts, proxySnap);
1679
1691
  }).then(function (res) { return _csrattrsResult(res, opts); });
1680
1692
  }
1681
1693
 
@@ -309,11 +309,27 @@ function _isBuiltinExotic(v) {
309
309
  t.isBoxedPrimitive(v) || t.isNativeError(v) || t.isArgumentsObject(v) || t.isGeneratorObject(v);
310
310
  }
311
311
 
312
+ function _proxyInChain(v) {
313
+ if (v === null || typeof v !== "object") return false;
314
+ var visited = new _Set();
315
+ for (var o = v; o && !_setHas(visited, o); o = _getPrototypeOf(o)) {
316
+ _setAdd(visited, o);
317
+ if (util.types.isProxy(o)) return true;
318
+ }
319
+ return false;
320
+ }
321
+ function isPlainRecord(v) {
322
+ if (v === null || typeof v !== "object") return false;
323
+ if (_proxyInChain(v)) return false;
324
+ if (_isNodeBuffer(v) || _isArray(v)) return false;
325
+ return !_isBuiltinExotic(v);
326
+ }
312
327
  // @enforced-by behavioral -- a plain-record refusal has no single rename-proof code shape worth a
313
328
  function assertPlainRecord(v, E, code, label) {
314
329
  _requireFactory(E);
315
- if (v === null || typeof v !== "object" || _isNodeBuffer(v) || _isArray(v)) throw E(code, label + " must be a plain object");
330
+ if (v === null || typeof v !== "object") throw E(code, label + " must be a plain object");
316
331
  _refuseUnenumerable(v, E, code, label);
332
+ if (_isNodeBuffer(v) || _isArray(v)) throw E(code, label + " must be a plain object");
317
333
  if (_isBuiltinExotic(v)) throw E(code, label + " must be a plain object (a built-in exotic such as a Date or Map is refused)");
318
334
  }
319
335
 
@@ -378,6 +394,7 @@ module.exports = intrinsic.freeze({
378
394
  assertCanonicalOid: assertCanonicalOid,
379
395
  assertKnownKeys: assertKnownKeys,
380
396
  assertPlainRecord: assertPlainRecord,
397
+ isPlainRecord: isPlainRecord,
381
398
  optionsObject: optionsObject,
382
399
  refuseAccessorFields: refuseAccessorFields,
383
400
  readableNames: readableNames,
@@ -49,6 +49,7 @@ function counter(max, E, code, label) {
49
49
  n += 1;
50
50
  if (n > max) throw E(code, (label || "decoded item") + " count exceeds the cap " + max);
51
51
  },
52
+ count: function () { return n; },
52
53
  };
53
54
  }
54
55
 
@@ -48,6 +48,7 @@ var nodeHttp = require("node:http");
48
48
  var nodeNet = require("node:net");
49
49
  var nodeTls = require("node:tls");
50
50
  var nodeDns = require("node:dns");
51
+ var nodeUtil = require("node:util");
51
52
  var constants = require("./constants");
52
53
  var guard = require("./guard-all");
53
54
  var frameworkError = require("./framework-error");
@@ -197,13 +198,70 @@ var PROXY_KEYS = _keySet(["url", "auth", "tls"]);
197
198
  var PROXY_AUTH_KEYS = _keySet(["scheme", "username", "password"]);
198
199
  var PROXY_TLS_KEYS = _keySet(["anchors", "useSystemStore", "servername", "minVersion"]);
199
200
 
201
+ function _copyAnchor(a) { return (a !== null && typeof a === "object" && nodeUtil.types.isProxy(a)) ? a : (Buffer.isBuffer(a) ? Buffer.from(a) : a); }
202
+ function _noopProxyErr(code, message) { var e = new Error(message); e.code = code; e.isPkiError = true; return e; }
203
+ function _copyableRecord(p) {
204
+ if (!guard.identifier.isPlainRecord(p)) return false;
205
+ var proto = Object.getPrototypeOf(p);
206
+ if (proto !== Object.prototype && proto !== null) return false;
207
+ if (Object.getOwnPropertySymbols(p).length !== 0) return false;
208
+ var ownEnumData = 0;
209
+ var names = Object.getOwnPropertyNames(p);
210
+ for (var i = 0; i < names.length; i++) {
211
+ var d = Object.getOwnPropertyDescriptor(p, names[i]);
212
+ if (!d.enumerable || d.get || d.set) return false;
213
+ ownEnumData++;
214
+ }
215
+ var readable = guard.identifier.readableNames(p, _noopProxyErr, "transport/bad-proxy", "opts.proxy");
216
+ if (readable.length !== ownEnumData) return false;
217
+ for (var j = 0; j < readable.length; j++) {
218
+ var rd = Object.getOwnPropertyDescriptor(p, readable[j]);
219
+ if (!rd || !rd.enumerable || rd.get || rd.set) return false;
220
+ }
221
+ return true;
222
+ }
223
+ function _copyableArray(a) {
224
+ if (a === null || typeof a !== "object" || nodeUtil.types.isProxy(a) || !Array.isArray(a) || Object.getPrototypeOf(a) !== Array.prototype) return false;
225
+ if (a.length > constants.LIMITS.PROXY_MAX_TLS_ANCHORS) return false;
226
+ if (Object.getOwnPropertySymbols(a).length !== 0) return false;
227
+ var names = Object.getOwnPropertyNames(a);
228
+ for (var i = 0; i < names.length; i++) {
229
+ var d = Object.getOwnPropertyDescriptor(a, names[i]);
230
+ if (d.get || d.set) return false;
231
+ }
232
+ return true;
233
+ }
234
+ function snapshotProxy(p) {
235
+ try {
236
+ if (!_copyableRecord(p)) return p;
237
+ var out = Object.assign(Object.create(null), p);
238
+ if (_copyableRecord(p.auth)) out.auth = Object.assign(Object.create(null), p.auth);
239
+ if (_copyableRecord(p.tls)) {
240
+ out.tls = Object.assign(Object.create(null), p.tls);
241
+ var a = p.tls.anchors;
242
+ if (_copyableArray(a)) {
243
+ var copied = [];
244
+ for (var i = 0; i < a.length; i++) copied[i] = _copyAnchor(a[i]);
245
+ out.tls.anchors = copied;
246
+ } else if (typeof a === "string") out.tls.anchors = a;
247
+ else if (a !== null && typeof a === "object" && !nodeUtil.types.isProxy(a) && Buffer.isBuffer(a)) out.tls.anchors = Buffer.from(a);
248
+ }
249
+ return out;
250
+ } catch (_e) {
251
+ // allow:swallow-unverified an input whose introspection throws (a revoked Proxy, a throwing trap) returns unchanged for _validateProxy to refuse
252
+ return p;
253
+ }
254
+ }
255
+
200
256
  function _validateProxy(request, defaults, E, C, url) {
201
257
  var proxy = request.proxy !== undefined ? request.proxy : defaults.proxy;
202
258
  if (proxy === undefined || proxy === null) return null;
203
259
  guard.identifier.assertPlainRecord(proxy, E, C("bad-proxy"), "opts.proxy");
260
+ if (!_copyableRecord(proxy)) throw E(C("bad-proxy"), "opts.proxy must be a plain object with only own enumerable data properties");
204
261
  guard.identifier.assertKnownKeys(proxy, PROXY_KEYS, E, C("bad-proxy"), "opts.proxy has an unknown option ");
262
+ if (typeof proxy.url !== "string") throw E(C("bad-proxy"), "opts.proxy.url must be a string, got " + guard.text.showValue(proxy.url));
205
263
  var purl;
206
- try { purl = new URL(String(proxy.url)); }
264
+ try { purl = new URL(proxy.url); }
207
265
  catch (e) { throw E(C("bad-proxy"), "opts.proxy.url did not parse: " + guard.text.showValue(proxy.url), e); }
208
266
  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
267
  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");
@@ -214,6 +272,7 @@ function _validateProxy(request, defaults, E, C, url) {
214
272
  if (proxy.auth !== undefined && proxy.auth !== null) {
215
273
  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
274
  guard.identifier.assertPlainRecord(proxy.auth, E, C("bad-proxy"), "opts.proxy.auth");
275
+ if (!_copyableRecord(proxy.auth)) throw E(C("bad-proxy"), "opts.proxy.auth must be a plain object with only own enumerable data properties");
217
276
  guard.identifier.assertKnownKeys(proxy.auth, PROXY_AUTH_KEYS, E, C("bad-proxy"), "opts.proxy.auth has an unknown option ");
218
277
  var scheme = proxy.auth.scheme;
219
278
  if (scheme === "digest") throw E(C("proxy-unsupported-scheme"), "Digest proxy authentication is not supported in this release; use 'basic' over an https proxy");
@@ -228,22 +287,25 @@ function _validateProxy(request, defaults, E, C, url) {
228
287
  var ptls = proxy.tls;
229
288
  if (ptls !== undefined && ptls !== null) {
230
289
  guard.identifier.assertPlainRecord(ptls, E, C("bad-proxy"), "opts.proxy.tls");
290
+ if (!_copyableRecord(ptls)) throw E(C("bad-proxy"), "opts.proxy.tls must be a plain object with only own enumerable data properties");
231
291
  guard.identifier.assertKnownKeys(ptls, PROXY_TLS_KEYS, E, C("bad-proxy"), "opts.proxy.tls has an unknown option ");
232
292
  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
293
  }
234
294
  var pAnchors = ptls ? ptls.anchors : undefined;
295
+ if (pAnchors !== undefined && pAnchors !== null && typeof pAnchors === "object" && nodeUtil.types.isProxy(pAnchors)) throw E(C("bad-proxy"), "opts.proxy.tls.anchors must not be a Proxy");
235
296
  var pUseSystem = ptls ? ptls.useSystemStore === true : false;
236
297
  var pHasAnchors = pAnchors !== undefined && pAnchors !== null && !(Array.isArray(pAnchors) && pAnchors.length === 0);
237
298
  if (!pHasAnchors && !pUseSystem) throw E(C("bad-proxy"), "an https proxy requires explicit tls trust: set proxy.tls.anchors or proxy.tls.useSystemStore");
238
299
  if (pHasAnchors) {
300
+ if (Array.isArray(pAnchors) && !_copyableArray(pAnchors)) throw E(C("bad-proxy"), "opts.proxy.tls.anchors must be a plain array of PEM strings or DER Buffers");
239
301
  var pAnchorList = Array.isArray(pAnchors) ? pAnchors : [pAnchors];
240
302
  for (var pai = 0; pai < pAnchorList.length; pai++) {
241
303
  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)");
304
+ if ((pan !== null && typeof pan === "object" && nodeUtil.types.isProxy(pan)) || (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
305
  }
244
306
  }
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);
307
+ var pMinVersion = (ptls && ptls.minVersion !== undefined && ptls.minVersion !== null) ? ptls.minVersion : DEFAULT_MIN_VERSION;
308
+ if (pMinVersion !== "TLSv1.2" && pMinVersion !== "TLSv1.3") throw E(C("bad-proxy"), "proxy.tls.minVersion must be 'TLSv1.2' or 'TLSv1.3', got " + guard.text.showValue(pMinVersion));
247
309
  var pCa = [];
248
310
  if (pHasAnchors) pCa = pCa.concat(_pemifyAnchors(pAnchors));
249
311
  if (pUseSystem) pCa = pCa.concat(_systemCa());
@@ -370,7 +432,17 @@ function httpsTransport(defaults) {
370
432
  return callerCsi(host, cert2);
371
433
  };
372
434
  }
373
- var proxyInfo = _validateProxy(request, defaults, E, C, url);
435
+ var proxyInfo;
436
+ try { proxyInfo = _validateProxy(request, defaults, E, C, url); }
437
+ catch (e) {
438
+ var typedProxyError = false;
439
+ try {
440
+ var ec = (e instanceof Error) && !nodeUtil.types.isProxy(e) ? e.code : undefined;
441
+ typedProxyError = ec === C("bad-proxy") || ec === C("proxy-auth-requires-tls") || ec === C("proxy-unsupported-scheme");
442
+ } catch (_ie) { /* allow:swallow-unverified reading .code on a hostile error object can throw; treat any such failure as untyped */ }
443
+ if (typedProxyError) throw e;
444
+ throw E(C("bad-proxy"), "opts.proxy could not be validated", e);
445
+ }
374
446
  var blockPrivate = (request.blockPrivateAddresses !== undefined ? request.blockPrivateAddresses : defaults.blockPrivateAddresses) === true;
375
447
  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");
376
448
  if (blockPrivate) {
@@ -526,4 +598,4 @@ function httpsTransport(defaults) {
526
598
  return _transportFn;
527
599
  }
528
600
 
529
- module.exports = { https: httpsTransport, isBlockedIp: _isBlockedIp, _makeGuardedLookup: _makeGuardedLookup, MAX_TIMEOUT: MAX_TIMEOUT };
601
+ module.exports = { https: httpsTransport, isBlockedIp: _isBlockedIp, _makeGuardedLookup: _makeGuardedLookup, MAX_TIMEOUT: MAX_TIMEOUT, snapshotProxy: snapshotProxy };
@@ -2305,7 +2305,7 @@ async function _fetchAiaIssuers(current, aia) {
2305
2305
  * @opts maxAiaPerCert Cap on caIssuers URLs tried per certificate (default `C.LIMITS.PATH_AIA_MAX_PER_CERT`).
2306
2306
  * @opts aiaTimeout Per-fetch timeout in ms, forwarded to the transport.
2307
2307
  * @opts maxResponseBytes Per-fetch response size cap, forwarded to the transport (tightenable downward only).
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.
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. Reaching that cap means stop looking, not nothing found: if a valid path was already accepted, build returns the best-policy one of those; it reaches `path/build-limit` only when the cap is hit before any valid path is accepted. An `anyPolicy` entry makes the set unconstrained, so ranking is skipped and the first accepted path is returned.
2309
2309
  * @example
2310
2310
  * var pair = await pki.key.generate("Ed25519");
2311
2311
  * var pemString = await pki.x509.sign({ subject: "Example Root", subjectPublicKey: await pki.key.export(pair.publicKey),
@@ -2424,6 +2424,7 @@ async function build(leaf, opts) {
2424
2424
  }
2425
2425
  var accepted = selectByPolicy ? [] : null;
2426
2426
 
2427
+ try {
2427
2428
  if (direction === "reverse") {
2428
2429
  var rstack = [];
2429
2430
  for (var rsi = 0; rsi < anchors.length; rsi++) intrinsic.push(rstack, { chain: [], hop: 0, keys: new Set([identityKey(leafCert)]), anchor: anchors[rsi] });
@@ -2523,6 +2524,11 @@ async function build(leaf, opts) {
2523
2524
  considered += _pushCandidates(frame, scored, stack, counter);
2524
2525
  }
2525
2526
  }
2527
+ } catch (_limitErr) {
2528
+ // allow:swallow-unverified the candidate cap means "stop looking", not "nothing found": once a valid path has
2529
+ if (!(selectByPolicy && accepted && accepted.length && _limitErr && _limitErr.code === "path/build-limit")) throw _limitErr;
2530
+ considered = counter.count();
2531
+ }
2526
2532
 
2527
2533
  if (selectByPolicy && !success && accepted.length) success = _bestByPolicy(accepted, uipsDistinct);
2528
2534
 
package/lib/scep.js CHANGED
@@ -717,19 +717,7 @@ function _drive(method, url, body, headers, opts, transport, budgets) {
717
717
  }
718
718
  return step(url);
719
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
- }
720
+ function _snapshotProxy(p) { return httpTransport.snapshotProxy(p); }
733
721
  function _client(method, url, body, headers, opts) {
734
722
  var transport = opts.transport || httpTransport.https({ E: _err, errPrefix: "scep" });
735
723
  var budgets = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.27",
3
+ "version": "0.6.29",
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:9742df6c-59a0-4fce-a64b-ddc916ee2fba",
5
+ "serialNumber": "urn:uuid:e72c9e5f-07a6-48ad-bf71-a361b1470bef",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-02T20:36:04.064Z",
8
+ "timestamp": "2026-09-03T05:34:38.589Z",
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.27",
22
+ "bom-ref": "@blamejs/pki@0.6.29",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.27",
25
+ "version": "0.6.29",
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.27",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.29",
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.27",
57
+ "ref": "@blamejs/pki@0.6.29",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]