@blamejs/pki 0.6.21 → 0.6.23

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.23 — 2026-09-02
8
+
9
+ The SCEP client can carry a PKIOperation over HTTP GET for a CA that does not support POST.
10
+
11
+ ### Added
12
+
13
+ - pki.scep.enroll / renew / getCert / getCrl accept httpMethod: "POST" (default) or "GET". Under "GET" the client sends the PKIOperation message as GET SCEPPATH?operation=PKIOperation&message=<base64-CMS> with no body (RFC 8894 sec. 4.1), for a CA that does not advertise POST support. POST stays the default and the recommended transport; a bad httpMethod is refused with scep/bad-input.
14
+
15
+ ## v0.6.22 — 2026-09-01
16
+
17
+ pki.acme.client gains scheduleRenewal, the RFC 9773 auto-sleeping certificate-renewal loop.
18
+
19
+ ### Added
20
+
21
+ - pki.acme.client(...).scheduleRenewal(certDer, { random, shouldStop, renew, maxChecks, maxWait, longTermRetrySeconds, temporaryBaseSeconds }) is the RFC 9773 sec. 4.1 auto-sleeping renewal loop. It composes renewalWindow and the client's injectable sleep/clock: fetch the ARI decision, sleep until the sooner of the selected instant and the clamped Retry-After, refetch until renewNow, then resolve { reason: "renew-now", decision }. It resolves { reason: "expired" } once the certificate passes its notAfter (a client must not check RenewalInfo after expiry, RFC 9773 sec. 4.3), { reason: "stopped" } when shouldStop() signals the certificate is replaced, and { reason: "budget" } at the optional maxChecks or maxWait bound. An invalid suggested window or a transport error retries on the sec. 4.3.3 schedule, with a 5xx backing off exponentially from temporaryBaseSeconds and every other error waiting longTermRetrySeconds (default six hours). A supplied renew(decision) callback is awaited at renew-now instead of resolving, and returning a new certificate DER reschedules on it.
22
+
7
23
  ## v0.6.21 — 2026-09-01
8
24
 
9
25
  WebCrypto and the signing and format builders refuse an algorithm, curve, digest, or profile name that collides with an inherited Object.prototype property name.
package/README.md CHANGED
@@ -222,10 +222,10 @@ 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. GET-carried PKIOperation and HTTP proxy authentication are not yet built — `build`, `parse`, `parseCapabilities`, `getCACaps`, `getCACert`, `getNextCACert`, `enroll`, `renew`, `getCert`, `getCrl` |
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). HTTP proxy authentication is not yet built — `build`, `parse`, `parseCapabilities`, `getCACaps`, `getCACert`, `getNextCACert`, `enroll`, `renew`, `getCert`, `getCrl` |
226
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` |
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
- | `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), and `renewalWindow` (the RFC 9773 §4.2/4.3 renewal decision) 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` |
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` |
package/lib/acme.js CHANGED
@@ -51,6 +51,7 @@ var httpTransport = require("./http-transport");
51
51
  var retryAfter = require("./http-retry-after");
52
52
  var guard = require("./guard-all");
53
53
  var intrinsic = require("./guard-intrinsic");
54
+ var _resolve = intrinsic.uncurry(intrinsic.promiseResolve);
54
55
  var _hasOwn = intrinsic.hasOwn;
55
56
  var _isBuffer = intrinsic.isBuffer;
56
57
  var _isArrayI = intrinsic.isArray;
@@ -1757,7 +1758,7 @@ function _parseLinkNext(headers, base) { var m = _parseLinkRelation(headers, bas
1757
1758
  * capped by a poll count and a total-wait budget. Returns a client
1758
1759
  * object: `directory`, `newAccount`, `newOrder`, `newAuthz`, `getOrder` / `getAuthorization` / `getChallenge`,
1759
1760
  * `respondToChallenge`, `finalize`, `pollOrder` / `pollAuthorization`, `downloadCertificate`,
1760
- * `revokeCert`, `deactivateAccount` / `deactivateAuthorization`, `keyChange`, `renewalInfo`, `renewalWindow`.
1761
+ * `revokeCert`, `deactivateAccount` / `deactivateAuthorization`, `keyChange`, `renewalInfo`, `renewalWindow`, `scheduleRenewal`.
1761
1762
  *
1762
1763
  * @opts
1763
1764
  * - `accountKey` / `accountJwk` / `alg` -- REQUIRED: the account private key, its public JWK, and the JWS alg.
@@ -1769,6 +1770,7 @@ function _parseLinkNext(headers, base) { var m = _parseLinkRelation(headers, bas
1769
1770
  * - `newAuthz(identifier)` -- pre-authorize a single identifier (RFC 8555 sec. 7.4.1) -> { authorization, url }.
1770
1771
  * - `downloadCertificate(url, { expectedSpki, identifiers, requireBinding, selectChain, maxAlternates })` -- bind the issued certificate to this order, then pick among RFC 8555 sec. 7.4.2 alternate chains. `expectedSpki` (the DER SubjectPublicKeyInfo this order's CSR asked to have certified) and `identifiers` (the order's own identifier array) are what the returned end-entity certificate is checked against: a different key is `acme/certificate-key-mismatch`, a different identifier set `acme/certificate-identifier-mismatch`. Only `dns` and `ip` identifiers map to a name a certificate carries, so an order identifier of another registered type, a certificate `subjectAltName` that is neither a dNSName nor an iPAddress, and a subject common name that is neither a dns name nor a canonical IP address, are each refused as `acme/unsupported-identifier-type` rather than dropped from the comparison. The certificate's alternative names are its identity; its common name is read only where it asserts none. At least one is required (`acme/binding-required`) unless `requireBinding: false`, which waives the requirement to supply material and never the check on material that is supplied. The result reports `boundToKey` / `boundToIdentifiers`. `selectChain({certificate, chain, certificates})` returns the first truthy candidate (primary first, then bounded `Link rel="alternate"` chains, confined to the download's own origin); the result adds `alternates` (the resolved alternate URLs).
1771
1772
  * - `renewalWindow(certDer, { random, clock, replaced, previous })` -- the RFC 9773 ARI renewal decision: composes `renewalInfo`, selects a uniform-random instant in the suggested window -> { suggestedWindow, selectedTime, renewNow, retryAfterSeconds, explanationURL }. Pass a prior result back as `previous` to REUSE its selectedTime while the CA's window is unchanged (RFC 9773 sec. 4.2), so repeated refreshes keep one stable renewal instant.
1773
+ * - `scheduleRenewal(certDer, { random, shouldStop, renew, maxChecks, maxWait, longTermRetrySeconds, temporaryBaseSeconds })` -- the RFC 9773 sec. 4.1 auto-sleeping renewal loop over `renewalWindow`. It fetches the ARI decision, sleeps via the client `sleep` until the sooner of the selected instant and the Retry-After, and refetches until the window says renew now, resolving `{ reason: "renew-now", decision }`. It stops early with `{ reason: "expired" }` once the certificate passes its notAfter (a client MUST NOT check RenewalInfo after expiry, sec. 4.3), `{ reason: "stopped" }` when `shouldStop()` returns true (the caller's certificate-replaced signal, sec. 4.3), and `{ reason: "budget" }` when the optional `maxChecks` or `maxWait` (seconds) bound is reached. A transient server or transport error retries on the sec. 4.3.3 schedule: a 5xx backs off exponentially from `temporaryBaseSeconds`, and every other transient error waits `longTermRetrySeconds` (default six hours). A caller or certificate error, including a certificate that carries no authorityKeyIdentifier and so cannot produce an ARI certID, rejects. When `renew(decision)` is supplied it is awaited at renew now instead of resolving; returning a new certificate DER reschedules on it, returning nothing resolves `{ reason: "renewed", decision }`.
1772
1774
  * @example
1773
1775
  * var acme = pki.acme.client("https://acme.example/directory", { accountKey, accountJwk, alg: "ES256", transport });
1774
1776
  * var acct = await acme.newAccount({ termsOfServiceAgreed: true });
@@ -1785,6 +1787,7 @@ var _METHOD_OPTS = {
1785
1787
  revoke: { certAlg: 1, certJwk: 1, certKey: 1, certificate: 1, reason: 1 },
1786
1788
  keyChange: { newAlg: 1, newJwk: 1, newKey: 1 },
1787
1789
  renewalWindow: { random: 1, clock: 1, replaced: 1, previous: 1 },
1790
+ scheduleRenewal: { random: 1, shouldStop: 1, renew: 1, maxChecks: 1, maxWait: 1, longTermRetrySeconds: 1, temporaryBaseSeconds: 1 },
1788
1791
  updateAccount: { contact: 1 },
1789
1792
  listOrders: { maxPages: 1 },
1790
1793
  };
@@ -2301,7 +2304,9 @@ function client(directoryUrl, opts) {
2301
2304
  if (!isFinite(prevMs)) throw E("acme/bad-input", "renewalWindow opts.previous.selectedTime must be an RFC 3339 date-time");
2302
2305
  selectedMs = Math.max(effStart, Math.min(effEnd, prevMs));
2303
2306
  } else {
2304
- var draw = o.random ? o.random() : _defaultRandom();
2307
+ var draw;
2308
+ if (o.random) { try { draw = o.random(); } catch (e) { throw E("acme/bad-input", "the renewalWindow random callback threw", e); } }
2309
+ else { draw = _defaultRandom(); }
2305
2310
  if (typeof draw !== "number" || !(draw >= 0 && draw <= 1)) throw E("acme/bad-input", "renewalWindow opts.random must return a number in [0, 1]");
2306
2311
  selectedMs = Math.round(effStart + draw * (effEnd - effStart));
2307
2312
  }
@@ -2318,6 +2323,79 @@ function client(directoryUrl, opts) {
2318
2323
  });
2319
2324
  }
2320
2325
 
2326
+ function _scheduleRenewal(certDer, o) {
2327
+ return _resolve(Promise).then(function () {
2328
+ o = _gateOpts(o, _METHOD_OPTS.scheduleRenewal, "scheduleRenewal");
2329
+ if (!guard.bytes.isByteSource(certDer)) throw E("acme/bad-input", "scheduleRenewal requires a DER certificate BufferSource");
2330
+ if (o.random !== undefined && typeof o.random !== "function") throw E("acme/bad-input", "scheduleRenewal opts.random must be a function returning a number in [0, 1]");
2331
+ if (o.shouldStop !== undefined && typeof o.shouldStop !== "function") throw E("acme/bad-input", "scheduleRenewal opts.shouldStop must be a function returning a boolean");
2332
+ if (o.renew !== undefined && typeof o.renew !== "function") throw E("acme/bad-input", "scheduleRenewal opts.renew must be an async function (decision) -> newCertDer | void");
2333
+ function optCount(v, name) {
2334
+ if (v === undefined) return null;
2335
+ if (typeof v !== "number" || !intrinsic.isFinite(v) || v < 1 || intrinsic.floor(v) !== v) throw E("acme/bad-input", "scheduleRenewal opts." + name + " must be a positive integer");
2336
+ return v;
2337
+ }
2338
+ var maxChecks = optCount(o.maxChecks, "maxChecks");
2339
+ var _mw = optCount(o.maxWait, "maxWait");
2340
+ var maxWaitMs = _mw == null ? null : constants.TIME.seconds(_mw);
2341
+ var longTermMs = constants.TIME.seconds(guard.limits.cap(o.longTermRetrySeconds, "longTermRetrySeconds", RENEWAL_RETRY_DEFAULT_SECONDS, { E: E, code: "acme/bad-input", min: RENEWAL_RETRY_MIN_SECONDS, max: RENEWAL_RETRY_MAX_SECONDS }));
2342
+ var tempBaseMs = constants.TIME.seconds(guard.limits.cap(o.temporaryBaseSeconds, "temporaryBaseSeconds", RENEWAL_RETRY_MIN_SECONDS, { E: E, code: "acme/bad-input", min: 1, max: RENEWAL_RETRY_MAX_SECONDS }));
2343
+ function _clk() { var t = clock(); if (typeof t !== "number" || !intrinsic.isFinite(t)) throw E("acme/bad-input", "the scheduleRenewal clock returned a non-finite value"); return t; }
2344
+ var startMs = _clk(), checks = 0, tempBackoffMs = tempBaseMs, previous = null;
2345
+ var cert = guard.bytes.snapshotSource(certDer, AcmeError, "acme/bad-input", "the scheduleRenewal certificate");
2346
+ function _boundedSleep(ms) { if (maxWaitMs != null) { ms = intrinsic.min(ms, intrinsic.max(0, maxWaitMs - (_clk() - startMs))); } return _resolve(Promise, sleep(ms)); }
2347
+ function _sleepThenLoop(ms) { return (maxChecks != null && checks >= maxChecks) ? { reason: "budget" } : _boundedSleep(ms).then(loop); }
2348
+ function _stop() {
2349
+ if (!o.shouldStop) return false;
2350
+ var s;
2351
+ try { s = o.shouldStop(); }
2352
+ catch (e) { throw E("acme/bad-input", "the scheduleRenewal shouldStop callback threw", e); }
2353
+ if (typeof s !== "boolean") throw E("acme/bad-input", "the scheduleRenewal shouldStop callback must return a boolean");
2354
+ return s;
2355
+ }
2356
+
2357
+ function loop() {
2358
+ if (_stop()) return { reason: "stopped" };
2359
+ if (maxChecks != null && checks >= maxChecks) return { reason: "budget" };
2360
+ if (maxWaitMs != null && (_clk() - startMs) >= maxWaitMs) return { reason: "budget" };
2361
+ checks += 1;
2362
+ return _renewalWindow(cert, { random: o.random, clock: clock, previous: previous == null ? undefined : previous }).then(function (decision) {
2363
+ if (_stop()) return { reason: "stopped" };
2364
+ if (maxWaitMs != null && (_clk() - startMs) >= maxWaitMs) return { reason: "budget" };
2365
+ tempBackoffMs = tempBaseMs;
2366
+ if (decision.renewNow) {
2367
+ if (o.renew) {
2368
+ var _rc;
2369
+ try { _rc = o.renew(decision); }
2370
+ catch (e) { throw E("acme/bad-input", "the scheduleRenewal renew callback threw", e); }
2371
+ return _resolve(Promise, _rc).then(function (next) {
2372
+ if (next == null) return { reason: "renewed", decision: decision };
2373
+ if (!guard.bytes.isByteSource(next)) throw E("acme/bad-input", "scheduleRenewal opts.renew must return a DER certificate BufferSource or a nullish value");
2374
+ cert = guard.bytes.snapshotSource(next, AcmeError, "acme/bad-input", "the scheduleRenewal renewed certificate"); previous = null; return loop();
2375
+ }, function (e) { throw E("acme/bad-input", "the scheduleRenewal renew callback rejected", e); });
2376
+ }
2377
+ return { reason: "renew-now", decision: decision };
2378
+ }
2379
+ previous = decision;
2380
+ var untilSelected = guard.time.instantOf(rfc3339.parse(decision.selectedTime, E, "acme/bad-input", "the renewalWindow selected time")) - _clk();
2381
+ var retryMs = constants.TIME.seconds(decision.retryAfterSeconds);
2382
+ return _sleepThenLoop(intrinsic.max(0, intrinsic.min(untilSelected, retryMs)));
2383
+ }, function (err) {
2384
+ var code = err && err.code;
2385
+ if (code === "acme/certificate-expired") return { reason: "expired" };
2386
+ if (code === "acme/certificate-replaced") return { reason: "replaced" };
2387
+ if (code === "acme/bad-input" || code === "acme/bad-certid" || code === "acme/resource-unavailable" || (typeof code === "string" && intrinsic.stringIndexOf(code, "x509/") === 0)) throw err;
2388
+ var temporary = code === "acme/server-problem" && typeof err.httpStatus === "number" && err.httpStatus >= 500;
2389
+ var waitMs;
2390
+ if (temporary) { waitMs = intrinsic.min(tempBackoffMs, longTermMs); tempBackoffMs = tempBackoffMs * 2; }
2391
+ else { tempBackoffMs = tempBaseMs; waitMs = longTermMs; }
2392
+ return _sleepThenLoop(waitMs);
2393
+ });
2394
+ }
2395
+ return loop();
2396
+ });
2397
+ }
2398
+
2321
2399
  return {
2322
2400
  directory: _directory,
2323
2401
  newAccount: _newAccount,
@@ -2339,6 +2417,7 @@ function client(directoryUrl, opts) {
2339
2417
  keyChange: _keyChange,
2340
2418
  renewalInfo: _renewalInfo,
2341
2419
  renewalWindow: _renewalWindow,
2420
+ scheduleRenewal: _scheduleRenewal,
2342
2421
  };
2343
2422
  }
2344
2423
 
package/lib/scep.js CHANGED
@@ -60,6 +60,12 @@ var _defaultSleep = require("./sleep").sleep;
60
60
  var nodeCrypto = require("node:crypto");
61
61
 
62
62
  function _err(code, msg, cause) { return new ScepError(code, msg, cause); }
63
+ function _showValue(v) {
64
+ if (typeof v === "string") return JSON.stringify(v);
65
+ if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint") return String(v);
66
+ if (v === null) return "null";
67
+ return "a value of type " + typeof v;
68
+ }
63
69
 
64
70
  var _KU_NS = pkix.makeNS("scep", ScepError, oid);
65
71
 
@@ -257,7 +263,7 @@ function _captureRecipientKey(rk) {
257
263
  async function build(spec) {
258
264
  spec = guard.identifier.optionsObject(spec, _err, "scep/bad-input", "pki.scep.build spec");
259
265
  var mtCode = MESSAGE_TYPE[spec.messageType];
260
- if (mtCode == null) throw _err("scep/bad-message-type", "unknown messageType " + JSON.stringify(spec.messageType) + " (RFC 8894 sec. 3.2.1.2)");
266
+ if (mtCode == null) throw _err("scep/bad-message-type", "unknown messageType " + _showValue(spec.messageType) + " (RFC 8894 sec. 3.2.1.2)");
261
267
  if (spec.messageType === "CertRep") {
262
268
  guard.identifier.assertKnownKeys(spec, _CERTREP_KEYS, _err, "scep/bad-input", "pki.scep.build (CertRep) has an unknown option: ");
263
269
  return await _buildCertRep(spec);
@@ -312,7 +318,7 @@ var _CERTREP_KEYS = { messageType: 1, signer: 1, transactionId: 1, senderNonce:
312
318
 
313
319
  async function _buildCertRep(spec) {
314
320
  if (spec.signer == null || typeof spec.signer !== "object") throw _err("scep/bad-input", "a signer { cert, key } is required");
315
- if (typeof spec.pkiStatus !== "string") throw _err("scep/bad-input", "a CertRep pkiStatus must be SUCCESS, FAILURE, or PENDING (RFC 8894 sec. 3.2.1.3), got " + JSON.stringify(spec.pkiStatus));
321
+ if (typeof spec.pkiStatus !== "string") throw _err("scep/bad-input", "a CertRep pkiStatus must be SUCCESS, FAILURE, or PENDING (RFC 8894 sec. 3.2.1.3), got " + _showValue(spec.pkiStatus));
316
322
  var statusCode = PKI_STATUS[spec.pkiStatus];
317
323
  if (statusCode == null) throw _err("scep/bad-input", "a CertRep pkiStatus must be SUCCESS, FAILURE, or PENDING (RFC 8894 sec. 3.2.1.3), got " + JSON.stringify(spec.pkiStatus));
318
324
  var txnId = _transactionId(spec.transactionId);
@@ -355,7 +361,7 @@ async function _buildCertRep(spec) {
355
361
  }
356
362
  if (spec.pkiStatus === "FAILURE") {
357
363
  var failCode = FAIL_INFO[spec.failInfo];
358
- if (failCode == null) throw _err("scep/bad-input", "a FAILURE CertRep must carry a failInfo of badAlg / badMessageCheck / badRequest / badTime / badCertId (RFC 8894 sec. 3.2.1.4), got " + JSON.stringify(spec.failInfo));
364
+ if (failCode == null) throw _err("scep/bad-input", "a FAILURE CertRep must carry a failInfo of badAlg / badMessageCheck / badRequest / badTime / badCertId (RFC 8894 sec. 3.2.1.4), got " + _showValue(spec.failInfo));
359
365
  attrs.push(_attr("scepFailInfo", b.printable(failCode)));
360
366
  if (spec.failInfoText != null) attrs.push(_attr("scepFailInfoText", b.utf8(String(spec.failInfoText))));
361
367
  }
@@ -395,7 +401,7 @@ function _serialToInteger(s) {
395
401
  else if (typeof s === "number") { if (!Number.isSafeInteger(s)) throw _err("scep/bad-input", "serialNumber as a number must be a safe integer"); n = BigInt(s); }
396
402
  else if (typeof s === "string" && s.length > 0) {
397
403
  var t = (s.slice(0, 2) === "0x" || s.slice(0, 2) === "0X") ? s.slice(2) : s;
398
- try { n = BigInt("0x" + t); } catch (_e) { throw _err("scep/bad-input", "serialNumber must be a hex string, a non-negative safe integer, or a BigInt: " + JSON.stringify(s)); }
404
+ try { n = BigInt("0x" + t); } catch (_e) { throw _err("scep/bad-input", "serialNumber must be a hex string, a non-negative safe integer, or a BigInt: " + _showValue(s)); }
399
405
  } else {
400
406
  throw _err("scep/bad-input", "serialNumber must be a hex string, a non-negative safe integer, or a BigInt");
401
407
  }
@@ -668,6 +674,20 @@ function _scepUrl(baseUrl, operation) {
668
674
  url.searchParams.set("operation", operation);
669
675
  return url;
670
676
  }
677
+ function _pkiMethod(opts) {
678
+ var m = opts.httpMethod;
679
+ if (m == null) return "POST";
680
+ if (m !== "POST" && m !== "GET") throw _err("scep/bad-input", "httpMethod must be \"POST\" or \"GET\" (RFC 8894 sec. 4.1), got " + _showValue(m));
681
+ return m;
682
+ }
683
+ function _pkiRequest(method, opUrl, reqMsg, clientOpts) {
684
+ if (method === "GET") {
685
+ var getUrl = new URL(opUrl.href);
686
+ getUrl.searchParams.set("message", Buffer.from(reqMsg).toString("base64"));
687
+ return _client("GET", getUrl, null, {}, clientOpts);
688
+ }
689
+ return _client("POST", opUrl, reqMsg, { "content-type": CT_PKI_MESSAGE }, clientOpts);
690
+ }
671
691
  function _drive(method, url, body, headers, opts, transport, budgets) {
672
692
  var redirects = 0, curMethod = method, curBody = body, initialOrigin = url.origin;
673
693
  var tlsBase = _tlsForRequest(opts);
@@ -816,7 +836,7 @@ function findIssuedCert(certs, wantSpki) {
816
836
  function _normalizeFingerprint(fp, algName) {
817
837
  var algorithm = _foldLower(String(algName == null ? "sha256" : algName));
818
838
  try { nodeCrypto.createHash(algorithm); }
819
- catch (_e) { throw _err("scep/bad-input", "fingerprintAlgorithm " + JSON.stringify(algorithm) + " is not an available hash"); }
839
+ catch (_e) { throw _err("scep/bad-input", "fingerprintAlgorithm " + _showValue(algorithm) + " is not an available hash"); }
820
840
  var value;
821
841
  if (Buffer.isBuffer(fp)) value = Buffer.from(fp);
822
842
  else if (typeof fp === "string") {
@@ -991,7 +1011,7 @@ async function _pollForIssuance(ctx) {
991
1011
  var sn = nodeCrypto.randomBytes(16);
992
1012
  lastNonce = sn;
993
1013
  var certPoll = await build({ messageType: "CertPoll", requestSubject: ctx.csrSubject, issuer: issuerName, recipient: ctx.caCert, signer: ctx.signer, transactionId: ctx.transactionId, senderNonce: sn });
994
- res = await _client("POST", ctx.postUrl, certPoll, { "content-type": CT_PKI_MESSAGE }, ctx.clientOpts);
1014
+ res = await _pkiRequest(ctx.httpMethod, ctx.postUrl, certPoll, ctx.clientOpts);
995
1015
  var body = _requireOk(res, [CT_PKI_MESSAGE], "PKIOperation");
996
1016
  var rep = await parse(body, { signerCert: ctx.signerCert, expectedSenderNonce: sn, recipientKey: ctx.recipientKey });
997
1017
  var d = _dispatchCertRep(rep, ctx.transactionId, ctx.spki);
@@ -1019,6 +1039,7 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
1019
1039
  maxResponseBytes: opts.maxResponseBytes,
1020
1040
  };
1021
1041
  var postUrl = _scepUrl(baseUrl, "PKIOperation");
1042
+ var httpMethod = _pkiMethod(opts);
1022
1043
  var csrView = guard.bytes.snapshotSource(opts.csr, ScepError, "scep/bad-input", "the csr");
1023
1044
  var spki, csrSubject;
1024
1045
  try { var _pcsr = schemaCsr.parse(csrView); spki = _pcsr.subjectPublicKeyInfo; csrSubject = _pcsr.subject.bytes; }
@@ -1030,14 +1051,14 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
1030
1051
  var senderNonce = nodeCrypto.randomBytes(16);
1031
1052
  var transactionId = opts.transactionId != null ? opts.transactionId : _defaultTransactionId();
1032
1053
  var reqMsg = await build({ messageType: messageType, messageData: csrView, recipient: caCert, signer: signer, transactionId: transactionId, senderNonce: senderNonce });
1033
- var res = await _client("POST", postUrl, reqMsg, { "content-type": CT_PKI_MESSAGE }, clientOpts);
1054
+ var res = await _pkiRequest(httpMethod, postUrl, reqMsg, clientOpts);
1034
1055
  var body = _requireOk(res, [CT_PKI_MESSAGE], "PKIOperation");
1035
1056
  var rep = await parse(body, { signerCert: signerCert, expectedSenderNonce: senderNonce, recipientKey: recipientKey });
1036
1057
  var d = _dispatchCertRep(rep, transactionId, spki);
1037
1058
  if (!d.pending) return d.result;
1038
1059
  if (pollCount <= 0) return { status: "PENDING", transactionId: rep.transactionId, senderNonce: senderNonce };
1039
1060
  return _pollForIssuance({
1040
- firstResponse: res, firstSenderNonce: senderNonce, postUrl: postUrl, clientOpts: clientOpts,
1061
+ firstResponse: res, firstSenderNonce: senderNonce, postUrl: postUrl, httpMethod: httpMethod, clientOpts: clientOpts,
1041
1062
  caCert: caCert, csrSubject: csrSubject, issuerCert: issuerCert, signer: signer, signerCert: signerCert, recipientKey: recipientKey,
1042
1063
  spki: spki, transactionId: transactionId, pollCount: pollCount, maxTotalWait: maxTotalWait,
1043
1064
  sleep: sleep, onRetryAfter: onRetryAfter,
@@ -1079,6 +1100,7 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
1079
1100
  * - `maxTotalWait` -- the total Retry-After sleep budget in seconds across all polls (default the Retry-After horizon).
1080
1101
  * - `sleep` -- an injectable sleeper `(ms) -> Promise` for the Retry-After wait (default a real timer).
1081
1102
  * - `onRetryAfter` -- an optional observer `(delaySeconds) -> void` called before each poll sleep.
1103
+ * - `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.
1082
1104
  * - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
1083
1105
  * @example
1084
1106
  * // requires: scepCsr, caCertDer, clientCertDer, clientKeyPkcs8, scepTransport
@@ -1158,8 +1180,9 @@ async function _queryOperation(messageType, baseUrl, opts, verbName) {
1158
1180
  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 };
1159
1181
  var senderNonce = nodeCrypto.randomBytes(16);
1160
1182
  var transactionId = opts.transactionId != null ? opts.transactionId : _defaultTransactionId();
1183
+ var httpMethod = _pkiMethod(opts);
1161
1184
  var reqMsg = await build(Object.assign({ messageType: messageType, recipient: caCert, signer: signer, transactionId: transactionId, senderNonce: senderNonce }, want.buildSpec));
1162
- var res = await _client("POST", _scepUrl(baseUrl, "PKIOperation"), reqMsg, { "content-type": CT_PKI_MESSAGE }, clientOpts);
1185
+ var res = await _pkiRequest(httpMethod, _scepUrl(baseUrl, "PKIOperation"), reqMsg, clientOpts);
1163
1186
  var body = _requireOk(res, [CT_PKI_MESSAGE], "PKIOperation");
1164
1187
  var rep = await parse(body, { signerCert: signerCert, expectedSenderNonce: senderNonce, recipientKey: recipientKey });
1165
1188
  _dispatchQueryRep(rep, transactionId);
@@ -1192,6 +1215,7 @@ async function _queryOperation(messageType, baseUrl, opts, verbName) {
1192
1215
  * - `recipientKey` -- `{ cert, key }`, the RSA key the CA encrypts the response to, to decrypt the CertRep.
1193
1216
  * - `responderCert` -- the certificate to authenticate the CA response signature against (defaults to `caCert`).
1194
1217
  * - `transactionId` -- a caller-unique PrintableString (defaults to 16 random bytes, hex-encoded).
1218
+ * - `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.
1195
1219
  * - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
1196
1220
  * @example
1197
1221
  * // requires: clientCertDer, caCertDer, clientKeyPkcs8, scepTransport
@@ -1240,6 +1264,7 @@ async function getCert(baseUrl, opts) {
1240
1264
  * - `recipientKey` -- `{ cert, key }`, the RSA key the CA encrypts the response to.
1241
1265
  * - `responderCert` -- the certificate to authenticate the CA response against (defaults to `caCert`).
1242
1266
  * - `transactionId` -- a caller-unique PrintableString (defaults to 16 random bytes, hex-encoded).
1267
+ * - `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.
1243
1268
  * - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
1244
1269
  * @example
1245
1270
  * // requires: clientCertDer, caCertDer, clientKeyPkcs8, scepTransport
@@ -1268,8 +1293,8 @@ function _withKeys(extra) { var o = {}, k; for (k in _TRANSPORT_KEYS) o[k] = 1;
1268
1293
  var _CACAPS_KEYS = _withKeys({ expectSCEPStandard: 1, requireStrongProfile: 1 });
1269
1294
  var _CACERT_KEYS = _withKeys({ expectedFingerprint: 1, fingerprintAlgorithm: 1 });
1270
1295
  var _NEXTCACERT_KEYS = _withKeys({ caCertificate: 1 });
1271
- var _ENROLL_KEYS = _withKeys({ csr: 1, caCert: 1, signer: 1, recipientKey: 1, responderCert: 1, issuerCert: 1, transactionId: 1, pollCount: 1, maxTotalWait: 1, sleep: 1, onRetryAfter: 1 });
1272
- var _QUERY_KEYS = _withKeys({ certificate: 1, issuer: 1, serialNumber: 1, caCert: 1, signer: 1, recipientKey: 1, responderCert: 1, transactionId: 1 });
1296
+ var _ENROLL_KEYS = _withKeys({ csr: 1, caCert: 1, signer: 1, recipientKey: 1, responderCert: 1, issuerCert: 1, transactionId: 1, pollCount: 1, maxTotalWait: 1, sleep: 1, onRetryAfter: 1, httpMethod: 1 });
1297
+ var _QUERY_KEYS = _withKeys({ certificate: 1, issuer: 1, serialNumber: 1, caCert: 1, signer: 1, recipientKey: 1, responderCert: 1, transactionId: 1, httpMethod: 1 });
1273
1298
 
1274
1299
  module.exports = {
1275
1300
  build: build,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.21",
3
+ "version": "0.6.23",
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:ba3e8f6b-69f8-4691-b5ee-3d227fe61113",
5
+ "serialNumber": "urn:uuid:8c346ebb-fdb5-431d-8bcb-e43e18ff74a7",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-01T20:36:49.754Z",
8
+ "timestamp": "2026-09-02T02:02:10.321Z",
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.21",
22
+ "bom-ref": "@blamejs/pki@0.6.23",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.21",
25
+ "version": "0.6.23",
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.21",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.23",
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.21",
57
+ "ref": "@blamejs/pki@0.6.23",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]