@blamejs/pki 0.6.15 → 0.6.17

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,33 @@ 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.17 — 2026-09-01
8
+
9
+ pki.scep.getCert and pki.scep.getCrl retrieve an already-issued certificate or a CA's CRL over SCEP, sending RFC 8894 GetCert and GetCRL queries and reading the result out of the CA's signed CertRep.
10
+
11
+ ### Added
12
+
13
+ - pki.scep.getCert(baseUrl, opts) retrieves an issued certificate over SCEP (RFC 8894 sec. 3.3.4). Name the target by { certificate } (the certificate whose issuer and serial identify it) or by { issuer, serialNumber } directly; the serial accepts a BigInt, a number, or a hex string. The CA response is verified against caCert (or responderCert), its recipientNonce must echo the query's fresh senderNonce, and the returned certificate is matched to the requested issuer and serial before it is handed back. A response carrying no matching certificate throws scep/cert-not-found; more than one throws scep/ambiguous-cert.
14
+ - pki.scep.getCrl(baseUrl, opts) retrieves a CA's CRL over SCEP (RFC 8894 sec. 3.3.4), named the same way as getCert. The response is authenticated identically, and the returned CRL is bound to the query: getCrl returns the CRL whose issuer matches the requested CA, throwing scep/no-crl when the response carries no such CRL and scep/ambiguous-crl when it carries more than one. Per RFC 8894 sec. 2.7 a client should compose a GetCRL only when the CA supports neither a CRL distribution point nor HTTP access; prefer those and pki.schema.crl.parse where available.
15
+ - pki.scep.build and pki.scep.parse now handle the GetCert (messageType 21) and GetCRL (messageType 22) queries: a pkcsPKIEnvelope carrying an IssuerAndSerialNumber (a CMS SEQUENCE of the issuer Name and the certificate serial), signed under the transaction attributes (RFC 8894 sec. 3.3.4).
16
+
17
+ ### Changed
18
+
19
+ - pki.scep.parse accepts every messageType the RFC 8894 registry defines, including GetCert and GetCRL. A messageType outside the registry is still refused with scep/bad-message-type.
20
+
21
+ ## v0.6.16 — 2026-09-01
22
+
23
+ pki.scep.enroll and pki.scep.renew poll a PENDING enrollment to its issued certificate, sending RFC 8894 CertPoll requests until the CA answers or a bounded poll-count and wait budget is exhausted.
24
+
25
+ ### Added
26
+
27
+ - pki.scep.build and pki.scep.parse now handle the CertPoll (GetCertInitial, messageType 20) request: a pkcsPKIEnvelope carrying an IssuerAndSubject (the CA's subject name and the request's subject name), signed under the transaction attributes with the original transactionID (RFC 8894 sec. 3.3.3).
28
+ - pki.scep.enroll and pki.scep.renew poll a PENDING response to a terminal status. New options bound the loop: pollCount (maximum CertPoll requests, default 5), maxTotalWait (total Retry-After sleep budget in seconds), sleep (an injectable (ms) -> Promise sleeper), and onRetryAfter (an observer of each delay). A budget exhausted with no terminal response throws scep/poll-exhausted carrying the transactionId to resume with. For a deployment whose request is encrypted to a separate RA certificate, issuerCert names the issuing CA the CertPoll must carry (default caCert).
29
+
30
+ ### Changed
31
+
32
+ - pki.scep.enroll and pki.scep.renew poll by default when the CA answers PENDING: a PENDING enrollment now resolves to the issued certificate or throws, rather than returning { status: "PENDING" } for the caller to retry. Pass pollCount: 0 to restore the single-shot PENDING return and drive the retry yourself.
33
+
7
34
  ## v0.6.15 — 2026-09-01
8
35
 
9
36
  Verifying a Sigstore bundle no longer matches a pinned identity against a non-text subjectAltName value; the value is surfaced as null so the policy fails closed instead of comparing raw bytes. The library source also ships without its explanatory comments, keeping the JSDoc that generates the API reference and the SPDX license headers.
package/README.md CHANGED
@@ -222,7 +222,7 @@ 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 `PKCSReq` or `RenewalReq` request: it verifies the PKCS#10 certification request's own proof-of-possession, encrypts it 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`. `parse(bytes, opts?)` reads a `PKCSReq`, `RenewalReq`, or `CertRep` back (the `CertPoll`, `GetCert`, and `GetCRL` client queries are 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)`, and `renew(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 return a PENDING to retry. Issuing a CertRep and automatic polling are not yet built — `build`, `parse`, `getCACaps`, `getCACert`, `getNextCACert`, `enroll`, `renew` |
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`. `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. Issuing a CertRep (the certification-authority side) 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
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` |
package/index.js CHANGED
@@ -171,7 +171,7 @@ module.exports = {
171
171
  // splitter, certs-only + serverkeygen validators over CMS, the enroll-attribute
172
172
  // builders, the HTTP response classifier). est opens no socket; fail-closed.
173
173
  est: est,
174
- scep: { build: scep.build, parse: scep.parse, getCACaps: scep.getCACaps, getCACert: scep.getCACert, getNextCACert: scep.getNextCACert, enroll: scep.enroll, renew: scep.renew, parseCapabilities: scep.parseCapabilities },
174
+ scep: { build: scep.build, parse: scep.parse, getCACaps: scep.getCACaps, getCACert: scep.getCACert, getNextCACert: scep.getNextCACert, enroll: scep.enroll, renew: scep.renew, getCert: scep.getCert, getCrl: scep.getCrl, parseCapabilities: scep.parseCapabilities },
175
175
  // `transport` is the shared fail-closed node:https transport the enrollment clients
176
176
  // drive -- pki.transport.https(defaults) returns a transport(request) -> {status,
177
177
  // headers, body}. The toolkit's sole socket choke point: explicit trust anchors,
package/lib/scep.js CHANGED
@@ -16,7 +16,8 @@
16
16
  * outer SignedData that signs it under a set of authenticated transaction
17
17
  * attributes -- messageType, transactionID, pkiStatus, failInfo, and the
18
18
  * sender/recipient nonces (RFC 8894 sec. 3). `pki.scep.build` assembles a
19
- * request pkiMessage (PKCSReq / RenewalReq); `pki.scep.parse` verifies the
19
+ * request pkiMessage (PKCSReq, RenewalReq, CertPoll, GetCert, or GetCRL);
20
+ * `pki.scep.parse` verifies the
20
21
  * outer signature, reads the transaction attributes BOUND to the verified
21
22
  * signer, and (given the recipient key) decrypts the pkcsPKIEnvelope to the
22
23
  * messageData.
@@ -28,10 +29,10 @@
28
29
  * pki.transport separately.
29
30
  *
30
31
  * @card
31
- * Build and read SCEP (RFC 8894) enrollment messages: a PKCSReq / RenewalReq
32
- * request wrapped in the signed-over-encrypted CMS layering, and a PKCSReq,
33
- * RenewalReq, or CertRep parsed back to its verified transaction attributes and
34
- * decrypted messageData.
32
+ * Build and read SCEP (RFC 8894) client messages: a PKCSReq, RenewalReq,
33
+ * CertPoll, GetCert, or GetCRL request wrapped in the signed-over-encrypted CMS
34
+ * layering, and any of those or a CertRep parsed back to its verified transaction
35
+ * attributes and decrypted messageData.
35
36
  */
36
37
 
37
38
  var frameworkError = require("./framework-error");
@@ -50,9 +51,12 @@ var schemaCsr = require("./schema-csr");
50
51
  var schemaX509 = require("./schema-x509");
51
52
  var schemaCrl = require("./schema-crl");
52
53
  var pkix = require("./schema-pkix");
54
+ var schema = require("./schema-engine");
53
55
  var guard = require("./guard-all");
54
56
  var C = require("./constants");
55
57
  var httpTransport = require("./http-transport");
58
+ var retryAfter = require("./http-retry-after");
59
+ var _defaultSleep = require("./sleep").sleep;
56
60
  var nodeCrypto = require("node:crypto");
57
61
 
58
62
  function _err(code, msg, cause) { return new ScepError(code, msg, cause); }
@@ -66,7 +70,7 @@ var FAIL_INFO = { badAlg: "0", badMessageCheck: "1", badRequest: "2", badTime: "
66
70
  function _invert(table) { var o = Object.create(null); for (var k in table) if (Object.prototype.hasOwnProperty.call(table, k)) o[table[k]] = k; return o; }
67
71
  var MESSAGE_TYPE_BY_CODE = _invert(MESSAGE_TYPE), PKI_STATUS_BY_CODE = _invert(PKI_STATUS), FAIL_INFO_BY_CODE = _invert(FAIL_INFO);
68
72
 
69
- var _PARSE_SUPPORTED = { PKCSReq: 1, RenewalReq: 1, CertRep: 1 };
73
+ var _PARSE_SUPPORTED = { PKCSReq: 1, RenewalReq: 1, CertRep: 1, CertPoll: 1, GetCert: 1, GetCRL: 1 };
70
74
 
71
75
  var ENVELOPE_CIPHER = "aes-128-cbc";
72
76
 
@@ -207,7 +211,10 @@ function _captureRecipientKey(rk) {
207
211
  * Assemble a SCEP pkiMessage (RFC 8894 sec. 3). A request (`PKCSReq` / `RenewalReq`) encrypts the
208
212
  * supplied PKCS#10 `messageData` to the recipient CA certificate as the inner EnvelopedData
209
213
  * (`pkcsPKIEnvelope`, AES-128-CBC), then signs it under the transaction attributes with the caller's
210
- * signer certificate and key. `transactionId` is a caller-unique PrintableString; `senderNonce` is a
214
+ * signer certificate and key. A `CertPoll` (GetCertInitial) query wraps an IssuerAndSubject that names
215
+ * the issuing CA and the request subject; a `GetCert` or `GetCRL` query wraps an IssuerAndSerialNumber
216
+ * that names a certificate by its issuer and serial. Every form is enveloped and signed the same way.
217
+ * `transactionId` is a caller-unique PrintableString; `senderNonce` is a
211
218
  * 16-byte value (a fresh random one is generated when omitted). The recipient CA certificate must
212
219
  * assert the `keyEncipherment` key usage (the EnvelopedData uses RSA key transport). The content key
213
220
  * is transported under RSAES-OAEP (SHA-256), the toolkit's key-transport algorithm; the legacy
@@ -219,8 +226,11 @@ function _captureRecipientKey(rk) {
219
226
  * match. The proof-of-possession over the PKCS#10 itself is verified regardless.
220
227
  *
221
228
  * @opts
222
- * - `messageType` -- "PKCSReq" | "RenewalReq" (this release's request set).
223
- * - `messageData` -- the PKCS#10 CertificationRequest DER to enrol.
229
+ * - `messageType` -- "PKCSReq" | "RenewalReq" | "CertPoll" | "GetCert" | "GetCRL".
230
+ * - `messageData` -- the PKCS#10 CertificationRequest DER, for a PKCSReq or RenewalReq.
231
+ * - `requestSubject` -- the request subject Name DER, for a CertPoll.
232
+ * - `certificate` -- for a GetCert or GetCRL, the certificate DER whose issuer and serial name the target (the convenience form).
233
+ * - `issuer` / `serialNumber` -- for a GetCert or GetCRL, the issuer Name DER and a positive serial (a BigInt, number, or hex string) naming the target directly. For a CertPoll, `issuer` alone names the issuing CA (defaulting to the recipient's subject) when the request is encrypted to a separate RA.
224
234
  * - `recipient` -- the CA (or RA) certificate DER the messageData is encrypted to (an RSA key-transport certificate; a non-RSA recipient is refused, since the envelope uses RSAES-OAEP).
225
235
  * - `signer` -- `{ cert, key }`, the outer SignedData signer (the client for a request).
226
236
  * - `transactionId` -- a caller-unique PrintableString identifying the transaction.
@@ -239,23 +249,30 @@ async function build(spec) {
239
249
  guard.identifier.assertKnownKeys(spec, _BUILD_KEYS, _err, "scep/bad-input", "pki.scep.build has an unknown option: ");
240
250
  var mtCode = MESSAGE_TYPE[spec.messageType];
241
251
  if (mtCode == null) throw _err("scep/bad-message-type", "unknown messageType " + JSON.stringify(spec.messageType) + " (RFC 8894 sec. 3.2.1.2)");
242
- if (spec.messageType !== "PKCSReq" && spec.messageType !== "RenewalReq") {
243
- throw _err("scep/bad-message-type", "pki.scep.build issues a request (PKCSReq / RenewalReq); " + spec.messageType + " is not built in this release");
252
+ if (spec.messageType !== "PKCSReq" && spec.messageType !== "RenewalReq" && spec.messageType !== "CertPoll" && spec.messageType !== "GetCert" && spec.messageType !== "GetCRL") {
253
+ throw _err("scep/bad-message-type", "pki.scep.build issues a request (PKCSReq / RenewalReq / CertPoll / GetCert / GetCRL); " + spec.messageType + " is not built in this release");
244
254
  }
245
255
  if (spec.signer == null || typeof spec.signer !== "object") throw _err("scep/bad-input", "a signer { cert, key } is required");
246
256
  var senderNonce = _nonce(spec.senderNonce, "senderNonce");
247
257
  var txnId = _transactionId(spec.transactionId);
248
- var messageData = guard.bytes.snapshotSource(spec.messageData, ScepError, "scep/bad-input", "messageData");
249
258
  var recipient = guard.bytes.snapshotSource(spec.recipient, ScepError, "scep/bad-input", "recipient");
250
259
  _assertRsaRecipient(recipient);
251
260
  var signerCert = guard.bytes.snapshotSource(spec.signer.cert, ScepError, "scep/bad-input", "signer.cert");
252
261
  _assertSigningKeyUsage(signerCert, "signer certificate");
253
262
  var signerKey = spec.signer.key;
254
- var parsedCsr;
255
- try { parsedCsr = schemaCsr.parse(messageData); }
256
- catch (e) { throw _err("scep/bad-input", "messageData is not a valid PKCS#10 CertificationRequest (RFC 8894 sec. 3.3.1): " + e.message, e); }
257
- if (!(await csrVerify.verifyCsrSignature(parsedCsr))) {
258
- throw _err("scep/bad-popo", "the PKCS#10 messageData failed its proof-of-possession: its self-signature does not verify under its own subject public key, so a CA would reject it");
263
+ var messageData;
264
+ if (spec.messageType === "CertPoll") {
265
+ messageData = _buildIssuerAndSubject(recipient, spec.requestSubject, spec.issuer);
266
+ } else if (spec.messageType === "GetCert" || spec.messageType === "GetCRL") {
267
+ messageData = _buildIssuerAndSerial(spec);
268
+ } else {
269
+ messageData = guard.bytes.snapshotSource(spec.messageData, ScepError, "scep/bad-input", "messageData");
270
+ var parsedCsr;
271
+ try { parsedCsr = schemaCsr.parse(messageData); }
272
+ catch (e) { throw _err("scep/bad-input", "messageData is not a valid PKCS#10 CertificationRequest (RFC 8894 sec. 3.3.1): " + e.message, e); }
273
+ if (!(await csrVerify.verifyCsrSignature(parsedCsr))) {
274
+ throw _err("scep/bad-popo", "the PKCS#10 messageData failed its proof-of-possession: its self-signature does not verify under its own subject public key, so a CA would reject it");
275
+ }
259
276
  }
260
277
  var pkcsPKIEnvelope;
261
278
  try {
@@ -276,7 +293,73 @@ async function build(spec) {
276
293
  throw e;
277
294
  }
278
295
  }
279
- var _BUILD_KEYS = { messageType: 1, messageData: 1, recipient: 1, signer: 1, transactionId: 1, senderNonce: 1 };
296
+ var _BUILD_KEYS = { messageType: 1, messageData: 1, recipient: 1, requestSubject: 1, issuer: 1, certificate: 1, serialNumber: 1, signer: 1, transactionId: 1, senderNonce: 1 };
297
+
298
+ function _buildIssuerAndSubject(recipientCertDer, requestSubjectSource, issuerOverride) {
299
+ var subject = guard.bytes.snapshotSource(requestSubjectSource, ScepError, "scep/bad-input", "requestSubject");
300
+ var issuer, issuerNode, subjNode;
301
+ try {
302
+ issuer = issuerOverride != null
303
+ ? guard.bytes.snapshotSource(issuerOverride, ScepError, "scep/bad-input", "issuer")
304
+ : schemaX509.parse(recipientCertDer).subject.bytes;
305
+ issuerNode = asn1.decode(issuer);
306
+ subjNode = asn1.decode(subject);
307
+ } catch (e) {
308
+ if (e instanceof ScepError) throw e;
309
+ throw _err("scep/bad-input", "the CertPoll IssuerAndSubject Names are not valid DER (RFC 8894 sec. 3.3.3): " + e.message, e);
310
+ }
311
+ _assertNameNode(issuerNode, "scep/bad-input", "the CertPoll issuer must be an X.509 Name DER (RFC 8894 sec. 3.3.3)", true);
312
+ _assertNameNode(subjNode, "scep/bad-input", "the CertPoll requestSubject must be an X.509 Name DER (RFC 8894 sec. 3.3.3)");
313
+ return b.sequence([issuer, subject]);
314
+ }
315
+
316
+ function _serialToInteger(s) {
317
+ var n;
318
+ if (typeof s === "bigint") n = s;
319
+ 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); }
320
+ else if (typeof s === "string" && s.length > 0) {
321
+ var t = (s.slice(0, 2) === "0x" || s.slice(0, 2) === "0X") ? s.slice(2) : s;
322
+ 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)); }
323
+ } else {
324
+ throw _err("scep/bad-input", "serialNumber must be a hex string, a non-negative safe integer, or a BigInt");
325
+ }
326
+ if (n <= 0n) throw _err("scep/bad-input", "serialNumber must be a positive integer (RFC 5280 sec. 4.1.2.2)");
327
+ return n;
328
+ }
329
+
330
+ function _assertNameNode(node, code, message, requireNonEmpty) {
331
+ var walked;
332
+ try { walked = schema.walk(pkix.name(_KU_NS), node, _KU_NS); }
333
+ catch (e) {
334
+ throw _err(code, message + " (RFC 5280 sec. 4.1.2.4): " + e.message, e);
335
+ }
336
+ if (requireNonEmpty && !walked.result.rdns.length) {
337
+ throw _err(code, message + ": a distinguished name naming a certificate issuer must be non-empty (RFC 5280 sec. 4.1.2.4)");
338
+ }
339
+ }
340
+
341
+ function _buildIssuerAndSerial(spec) {
342
+ var hasCert = spec.certificate != null;
343
+ var hasExplicit = spec.issuer != null || spec.serialNumber != null;
344
+ if (hasCert === hasExplicit) throw _err("scep/bad-input", "a GetCert / GetCRL query needs exactly one of { certificate } or { issuer, serialNumber } (RFC 8894 sec. 3.3.4)");
345
+ var issuer, serial;
346
+ if (hasCert) {
347
+ var cert = guard.bytes.snapshotSource(spec.certificate, ScepError, "scep/bad-input", "certificate");
348
+ try { var w = schemaX509.parse(cert); issuer = w.issuer.bytes; serial = w.serialNumber; }
349
+ catch (e) { throw _err("scep/bad-input", "certificate is not a parseable X.509 certificate (RFC 8894 sec. 3.3.4): " + e.message, e); }
350
+ } else {
351
+ if (spec.issuer == null || spec.serialNumber == null) throw _err("scep/bad-input", "the explicit form of a GetCert / GetCRL query needs both issuer and serialNumber (RFC 8894 sec. 3.3.4)");
352
+ serial = _serialToInteger(spec.serialNumber);
353
+ issuer = guard.bytes.snapshotSource(spec.issuer, ScepError, "scep/bad-input", "issuer");
354
+ var node;
355
+ try { node = asn1.decode(issuer); } catch (e) { throw _err("scep/bad-input", "issuer is not a valid Name DER (RFC 8894 sec. 3.3.4): " + e.message, e); }
356
+ _assertNameNode(node, "scep/bad-input", "issuer must be an X.509 Name DER (RFC 8894 sec. 3.3.4)", true);
357
+ }
358
+ if (serial <= 0n) throw _err("scep/bad-input", "the query serialNumber must be a positive integer; a certificate with a non-positive serial cannot be named in a conforming query (RFC 5280 sec. 4.1.2.2)");
359
+ var serialTlv = b.integer(serial);
360
+ if (asn1.decode(serialTlv).content.length > 20) throw _err("scep/bad-input", "the query serialNumber must not exceed 20 octets (RFC 5280 sec. 4.1.2.2)");
361
+ return b.sequence([issuer, serialTlv]);
362
+ }
280
363
 
281
364
  /**
282
365
  * @primitive pki.scep.parse
@@ -289,8 +372,8 @@ var _BUILD_KEYS = { messageType: 1, messageData: 1, recipient: 1, signer: 1, tra
289
372
  * Disassemble a SCEP pkiMessage (RFC 8894 sec. 3): verify the outer SignedData signature, read the
290
373
  * transaction attributes BOUND to the verified signer (never from a separate untrusted parse), and,
291
374
  * given the recipient key, decrypt the pkcsPKIEnvelope to recover the messageData. It reads the
292
- * enrollment message types PKCSReq, RenewalReq, and CertRep; the CertPoll, GetCert, and GetCRL client
293
- * queries a CA processes are refused (`scep/unsupported-message-type`). The verdict is
375
+ * message types PKCSReq, RenewalReq, CertRep, CertPoll, GetCert, and GetCRL; a messageType the RFC 8894
376
+ * registry does not define is refused (`scep/bad-message-type`). The verdict is
294
377
  * `{ signatureValid, signerAuthenticated, signerCert, messageType, transactionId, senderNonce,
295
378
  * recipientNonce, pkiStatus, failInfo, failInfoText, messageData, certificates, crls }` (fields null
296
379
  * when the message does not carry them). For a decrypted SUCCESS CertRep, `certificates` and `crls`
@@ -418,6 +501,26 @@ async function parse(bytes, opts) {
418
501
  } else if (messageType === "PKCSReq" || messageType === "RenewalReq") {
419
502
  try { schemaCsr.parse(dec.content); }
420
503
  catch (e) { throw _err("scep/bad-request-payload", "a " + messageType + " messageData must be a PKCS#10 CertificationRequest (RFC 8894 sec. 3.3.1)", e); }
504
+ } else if (messageType === "CertPoll") {
505
+ var ias;
506
+ try { ias = asn1.decode(dec.content); }
507
+ catch (e) { throw _err("scep/bad-request-payload", "a CertPoll messageData must be an IssuerAndSubject (RFC 8894 sec. 3.3.3)", e); }
508
+ var iasCh = pkix.rootSequenceChildren(ias, 2, 2);
509
+ if (!iasCh) throw _err("scep/bad-request-payload", "a CertPoll messageData must be an IssuerAndSubject: a SEQUENCE of two Name values (RFC 8894 sec. 3.3.3)");
510
+ _assertNameNode(iasCh[0], "scep/bad-request-payload", "a CertPoll messageData issuer must be an X.509 Name (RFC 8894 sec. 3.3.3)", true);
511
+ _assertNameNode(iasCh[1], "scep/bad-request-payload", "a CertPoll messageData requestSubject must be an X.509 Name (RFC 8894 sec. 3.3.3)");
512
+ } else if (messageType === "GetCert" || messageType === "GetCRL") {
513
+ var isn;
514
+ try { isn = asn1.decode(dec.content); }
515
+ catch (e) { throw _err("scep/bad-request-payload", "a " + messageType + " messageData must be an IssuerAndSerialNumber (RFC 8894 sec. 3.3.4)", e); }
516
+ var isnCh = pkix.rootSequenceChildren(isn, 2, 2);
517
+ if (!isnCh) throw _err("scep/bad-request-payload", "a " + messageType + " messageData must be an IssuerAndSerialNumber: a SEQUENCE of a Name and an INTEGER (RFC 8894 sec. 3.3.4)");
518
+ _assertNameNode(isnCh[0], "scep/bad-request-payload", "a " + messageType + " messageData issuer must be an X.509 Name (RFC 8894 sec. 3.3.4)", true);
519
+ var isnSerial;
520
+ try { isnSerial = asn1.read.integer(isnCh[1]); }
521
+ catch (e) { throw _err("scep/bad-request-payload", "a " + messageType + " messageData serialNumber must be a DER INTEGER (RFC 8894 sec. 3.3.4)", e); }
522
+ if (isnSerial <= 0n) throw _err("scep/bad-request-payload", "a " + messageType + " messageData serialNumber must be a positive integer (RFC 5280 sec. 4.1.2.2)");
523
+ if (isnCh[1].content.length > 20) throw _err("scep/bad-request-payload", "a " + messageType + " messageData serialNumber must not exceed 20 octets (RFC 5280 sec. 4.1.2.2)");
421
524
  }
422
525
  }
423
526
  return out;
@@ -763,6 +866,62 @@ async function getNextCACert(baseUrl, opts) {
763
866
  function _defaultTransactionId() {
764
867
  return nodeCrypto.randomBytes(16).toString("hex");
765
868
  }
869
+ var POLL_COUNT_MAX = 1000;
870
+
871
+ function _dispatchCertRep(rep, transactionId, spki) {
872
+ if (rep.messageType !== "CertRep") throw _err("scep/unexpected-message-type", "the SCEP response is a " + rep.messageType + ", not a CertRep");
873
+ if (rep.transactionId !== transactionId) throw _err("scep/transaction-id-mismatch", "the CertRep transactionID does not match the request (RFC 8894 sec. 3.2.1.1)");
874
+ if (rep.pkiStatus === "FAILURE") {
875
+ var failErr = _err("scep/enrollment-failed", "the CA refused the request with failInfo " + JSON.stringify(rep.failInfo) + (rep.failInfoText ? " (" + rep.failInfoText + ")" : ""));
876
+ failErr.failInfo = rep.failInfo;
877
+ failErr.failInfoText = rep.failInfoText;
878
+ throw failErr;
879
+ }
880
+ if (rep.pkiStatus === "PENDING") return { pending: true };
881
+ var repCerts = rep.certificates || [];
882
+ var issued = findIssuedCert(repCerts, spki.bytes);
883
+ if (issued == null) throw _err("scep/no-issued-cert", "the SUCCESS CertRep did not carry a certificate matching the request public key");
884
+ if (findIssuedCert(repCerts.filter(function (c) { return c !== issued; }), spki.bytes) != null) {
885
+ throw _err("scep/ambiguous-issued-cert", "the SUCCESS CertRep carried more than one certificate matching the request public key; the issued certificate is ambiguous (RFC 8894 sec. 3.3)");
886
+ }
887
+ return { pending: false, result: { status: "SUCCESS", certificate: issued, certificates: repCerts, transactionId: rep.transactionId } };
888
+ }
889
+
890
+ function _pollExhausted(which, transactionId, senderNonce) {
891
+ var e = _err("scep/poll-exhausted", "the CA kept the request PENDING and " + which + " was exhausted before it resolved (RFC 8894 sec. 4.4); resume the transaction later with this transactionId");
892
+ e.transactionId = transactionId;
893
+ e.senderNonce = senderNonce;
894
+ return e;
895
+ }
896
+
897
+ async function _pollForIssuance(ctx) {
898
+ var issuerName;
899
+ try { issuerName = schemaX509.parse(ctx.issuerCert).subject.bytes; }
900
+ catch (e) { throw _err("scep/bad-input", "the issuerCert whose subject names the CertPoll issuer is not a parseable certificate (RFC 8894 sec. 3.3.3)", e); }
901
+ var res = ctx.firstResponse, count = 0, waitedMs = 0, lastNonce = ctx.firstSenderNonce;
902
+ for (;;) {
903
+ var delaySec = 1;
904
+ var ra = _header(res.headers, "retry-after");
905
+ if (typeof ra === "string" && ra.trim() !== "") {
906
+ var parsed = retryAfter.parse(ra, { now: Date.now(), E: _err, code: "scep/bad-input", lenient: true });
907
+ if (parsed.retryAfterSeconds != null) delaySec = parsed.retryAfterSeconds;
908
+ }
909
+ count += 1;
910
+ if (count > ctx.pollCount) throw _pollExhausted("the poll count", ctx.transactionId, lastNonce);
911
+ waitedMs += delaySec * C.TIME.seconds(1);
912
+ if (waitedMs > ctx.maxTotalWait * C.TIME.seconds(1)) throw _pollExhausted("the total wait budget", ctx.transactionId, lastNonce);
913
+ if (ctx.onRetryAfter) ctx.onRetryAfter(delaySec);
914
+ await ctx.sleep(delaySec * C.TIME.seconds(1));
915
+ var sn = nodeCrypto.randomBytes(16);
916
+ lastNonce = sn;
917
+ var certPoll = await build({ messageType: "CertPoll", requestSubject: ctx.csrSubject, issuer: issuerName, recipient: ctx.caCert, signer: ctx.signer, transactionId: ctx.transactionId, senderNonce: sn });
918
+ res = await _client("POST", ctx.postUrl, certPoll, { "content-type": CT_PKI_MESSAGE }, ctx.clientOpts);
919
+ var body = _requireOk(res, [CT_PKI_MESSAGE], "PKIOperation");
920
+ var rep = await parse(body, { signerCert: ctx.signerCert, expectedSenderNonce: sn, recipientKey: ctx.recipientKey });
921
+ var d = _dispatchCertRep(rep, ctx.transactionId, ctx.spki);
922
+ if (!d.pending) return d.result;
923
+ }
924
+ }
766
925
  async function _pkiOperation(messageType, baseUrl, opts, verbName) {
767
926
  opts = guard.identifier.optionsObject(opts, _err, "scep/bad-input", "pki.scep." + verbName + " options");
768
927
  guard.identifier.assertKnownKeys(opts, _ENROLL_KEYS, _err, "scep/bad-input", "pki.scep." + verbName + " has an unknown option: ");
@@ -772,8 +931,9 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
772
931
  if (opts.recipientKey == null || typeof opts.recipientKey !== "object") throw _err("scep/bad-input", "a recipientKey { cert, key } is required to decrypt the CA response");
773
932
  var caCert = guard.bytes.snapshotSource(opts.caCert, ScepError, "scep/bad-input", "the caCert");
774
933
  var signerCert = opts.responderCert != null ? guard.bytes.snapshotSource(opts.responderCert, ScepError, "scep/bad-input", "the responderCert") : caCert;
934
+ var issuerCert = opts.issuerCert != null ? guard.bytes.snapshotSource(opts.issuerCert, ScepError, "scep/bad-input", "the issuerCert") : caCert;
775
935
  var recipientKey = _captureRecipientKey(opts.recipientKey);
776
- var signer = opts.signer;
936
+ var signer = { cert: guard.bytes.snapshotSource(opts.signer.cert, ScepError, "scep/bad-input", "signer.cert"), key: opts.signer.key };
777
937
  var clientOpts = {
778
938
  transport: opts.transport,
779
939
  tls: opts.tls != null ? Object.assign({}, opts.tls) : opts.tls,
@@ -784,31 +944,28 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
784
944
  };
785
945
  var postUrl = _scepUrl(baseUrl, "PKIOperation");
786
946
  var csrView = guard.bytes.snapshotSource(opts.csr, ScepError, "scep/bad-input", "the csr");
787
- var spki;
788
- try { spki = schemaCsr.parse(csrView).subjectPublicKeyInfo; }
947
+ var spki, csrSubject;
948
+ try { var _pcsr = schemaCsr.parse(csrView); spki = _pcsr.subjectPublicKeyInfo; csrSubject = _pcsr.subject.bytes; }
789
949
  catch (e) { throw _err("scep/bad-input", "the csr is not a valid PKCS#10 CertificationRequest", e); }
950
+ var pollCount = guard.limits.cap(opts.pollCount, "pollCount", 5, { E: _err, code: "scep/bad-input", min: 0, max: POLL_COUNT_MAX });
951
+ var maxTotalWait = guard.limits.cap(opts.maxTotalWait, "maxTotalWait", retryAfter.MAX_RETRY_AFTER_SECONDS, { E: _err, code: "scep/bad-input", min: 0, max: retryAfter.MAX_RETRY_AFTER_SECONDS });
952
+ var sleep = typeof opts.sleep === "function" ? opts.sleep : _defaultSleep;
953
+ var onRetryAfter = typeof opts.onRetryAfter === "function" ? opts.onRetryAfter : null;
790
954
  var senderNonce = nodeCrypto.randomBytes(16);
791
955
  var transactionId = opts.transactionId != null ? opts.transactionId : _defaultTransactionId();
792
956
  var reqMsg = await build({ messageType: messageType, messageData: csrView, recipient: caCert, signer: signer, transactionId: transactionId, senderNonce: senderNonce });
793
957
  var res = await _client("POST", postUrl, reqMsg, { "content-type": CT_PKI_MESSAGE }, clientOpts);
794
958
  var body = _requireOk(res, [CT_PKI_MESSAGE], "PKIOperation");
795
959
  var rep = await parse(body, { signerCert: signerCert, expectedSenderNonce: senderNonce, recipientKey: recipientKey });
796
- if (rep.messageType !== "CertRep") throw _err("scep/unexpected-message-type", "the SCEP response is a " + rep.messageType + ", not a CertRep");
797
- if (rep.transactionId !== transactionId) throw _err("scep/transaction-id-mismatch", "the CertRep transactionID does not match the request (RFC 8894 sec. 3.2.1.1)");
798
- if (rep.pkiStatus === "FAILURE") {
799
- var failErr = _err("scep/enrollment-failed", "the CA refused the request with failInfo " + JSON.stringify(rep.failInfo) + (rep.failInfoText ? " (" + rep.failInfoText + ")" : ""));
800
- failErr.failInfo = rep.failInfo;
801
- failErr.failInfoText = rep.failInfoText;
802
- throw failErr;
803
- }
804
- if (rep.pkiStatus === "PENDING") return { status: "PENDING", transactionId: rep.transactionId, senderNonce: senderNonce };
805
- var repCerts = rep.certificates || [];
806
- var issued = findIssuedCert(repCerts, spki.bytes);
807
- if (issued == null) throw _err("scep/no-issued-cert", "the SUCCESS CertRep did not carry a certificate matching the request public key");
808
- if (findIssuedCert(repCerts.filter(function (c) { return c !== issued; }), spki.bytes) != null) {
809
- throw _err("scep/ambiguous-issued-cert", "the SUCCESS CertRep carried more than one certificate matching the request public key; the issued certificate is ambiguous (RFC 8894 sec. 3.3)");
810
- }
811
- return { status: "SUCCESS", certificate: issued, certificates: repCerts, transactionId: rep.transactionId };
960
+ var d = _dispatchCertRep(rep, transactionId, spki);
961
+ if (!d.pending) return d.result;
962
+ if (pollCount <= 0) return { status: "PENDING", transactionId: rep.transactionId, senderNonce: senderNonce };
963
+ return _pollForIssuance({
964
+ firstResponse: res, firstSenderNonce: senderNonce, postUrl: postUrl, clientOpts: clientOpts,
965
+ caCert: caCert, csrSubject: csrSubject, issuerCert: issuerCert, signer: signer, signerCert: signerCert, recipientKey: recipientKey,
966
+ spki: spki, transactionId: transactionId, pollCount: pollCount, maxTotalWait: maxTotalWait,
967
+ sleep: sleep, onRetryAfter: onRetryAfter,
968
+ });
812
969
  }
813
970
 
814
971
  /**
@@ -824,8 +981,13 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
824
981
  * the CertRep. The CA response is authenticated against the CA certificate and its `recipientNonce` must
825
982
  * echo the request's fresh `senderNonce`. On SUCCESS the issued certificate is selected out of the
826
983
  * response by SubjectPublicKeyInfo byte-match against the request; a FAILURE throws
827
- * `scep/enrollment-failed` carrying the CA's failInfo; a PENDING returns `{ status: "PENDING",
828
- * transactionId }` for the caller to retry. The content key is transported under RSAES-OAEP, so the CA
984
+ * `scep/enrollment-failed` carrying the CA's failInfo. A CA that answers PENDING (manual enrollment, RFC
985
+ * 8894 sec. 2.5) is polled automatically: the client issues CertPoll (GetCertInitial) messages reusing
986
+ * the transactionID, each authenticated against the CA certificate with a fresh nonce it must echo,
987
+ * until the CA answers SUCCESS or FAILURE or a `pollCount` / `maxTotalWait` budget is exhausted
988
+ * (`scep/poll-exhausted`, carrying the `transactionId` to resume). Pass `pollCount: 0` to disable polling
989
+ * and get the single `{ status: "PENDING", transactionId }` return for a caller that drives the retry
990
+ * itself. The content key is transported under RSAES-OAEP, so the CA
829
991
  * certificate must be an RSA `keyEncipherment` certificate that accepts OAEP; the shared-secret
830
992
  * authenticator (RFC 8894 sec. 2.4) is the `challengePassword` the caller placed in the PKCS#10.
831
993
  *
@@ -835,14 +997,19 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
835
997
  * - `signer` -- `{ cert, key }`, the outer SignedData signer (for a PKCSReq, a self-signed certificate over the request key).
836
998
  * - `recipientKey` -- `{ cert, key }`, the RSA key the CA encrypts the response to, to decrypt the CertRep.
837
999
  * - `responderCert` -- the certificate to authenticate the CA's response signature against (defaults to `caCert`).
1000
+ * - `issuerCert` -- the issuing CA certificate whose subject names the CertPoll issuer (defaults to `caCert`; set it when the request is encrypted to a separate RA certificate, RFC 8894 sec. 3.3.3).
838
1001
  * - `transactionId` -- a caller-unique PrintableString (defaults to 16 random bytes, hex-encoded, unique per call).
1002
+ * - `pollCount` -- the maximum number of CertPoll requests on a PENDING response (default 5; `0` disables polling).
1003
+ * - `maxTotalWait` -- the total Retry-After sleep budget in seconds across all polls (default the Retry-After horizon).
1004
+ * - `sleep` -- an injectable sleeper `(ms) -> Promise` for the Retry-After wait (default a real timer).
1005
+ * - `onRetryAfter` -- an optional observer `(delaySeconds) -> void` called before each poll sleep.
839
1006
  * - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
840
1007
  * @example
841
1008
  * // requires: scepCsr, caCertDer, clientCertDer, clientKeyPkcs8, scepTransport
842
1009
  * var out = await pki.scep.enroll("http://ca.example/scep", { csr: scepCsr, caCert: caCertDer,
843
1010
  * signer: { cert: clientCertDer, key: clientKeyPkcs8 },
844
1011
  * recipientKey: { cert: clientCertDer, key: clientKeyPkcs8 }, transport: scepTransport });
845
- * out.status; // "SUCCESS", or "PENDING" to retry
1012
+ * out.status; // "SUCCESS" (a PENDING request is polled to a terminal status unless pollCount is 0)
846
1013
  */
847
1014
  function enroll(baseUrl, opts) { return _pkiOperation("PKCSReq", baseUrl, opts, "enroll"); }
848
1015
 
@@ -869,12 +1036,164 @@ function enroll(baseUrl, opts) { return _pkiOperation("PKCSReq", baseUrl, opts,
869
1036
  */
870
1037
  function renew(baseUrl, opts) { return _pkiOperation("RenewalReq", baseUrl, opts, "renew"); }
871
1038
 
1039
+ function _dispatchQueryRep(rep, transactionId) {
1040
+ if (rep.messageType !== "CertRep") throw _err("scep/unexpected-message-type", "the SCEP response is a " + rep.messageType + ", not a CertRep");
1041
+ if (rep.transactionId !== transactionId) throw _err("scep/transaction-id-mismatch", "the CertRep transactionID does not match the request (RFC 8894 sec. 3.2.1.1)");
1042
+ if (rep.pkiStatus === "FAILURE") {
1043
+ var e = _err("scep/query-failed", "the CA refused the query with failInfo " + JSON.stringify(rep.failInfo) + (rep.failInfoText ? " (" + rep.failInfoText + ")" : ""));
1044
+ e.failInfo = rep.failInfo;
1045
+ e.failInfoText = rep.failInfoText;
1046
+ throw e;
1047
+ }
1048
+ if (rep.pkiStatus === "PENDING") throw _err("scep/unexpected-pending", "a GetCert / GetCRL query cannot be answered PENDING; the CA grants or rejects it (RFC 8894 sec. 4.5.1)");
1049
+ }
1050
+
1051
+ function _resolveQueryTarget(opts) {
1052
+ var hasCert = opts.certificate != null;
1053
+ var hasExplicit = opts.issuer != null || opts.serialNumber != null;
1054
+ if (hasCert === hasExplicit) throw _err("scep/bad-input", "a GetCert / GetCRL query needs exactly one of { certificate } or { issuer, serialNumber } (RFC 8894 sec. 3.3.4)");
1055
+ if (hasCert) {
1056
+ var certDer = guard.bytes.snapshotSource(opts.certificate, ScepError, "scep/bad-input", "certificate");
1057
+ var w;
1058
+ try { w = schemaX509.parse(certDer); }
1059
+ catch (e) { throw _err("scep/bad-input", "certificate is not a parseable X.509 certificate (RFC 8894 sec. 3.3.4): " + e.message, e); }
1060
+ return { issuerRdns: w.issuer.rdns, serial: w.serialNumber, buildSpec: { certificate: certDer } };
1061
+ }
1062
+ if (opts.issuer == null || opts.serialNumber == null) throw _err("scep/bad-input", "the explicit form of a GetCert / GetCRL query needs both issuer and serialNumber (RFC 8894 sec. 3.3.4)");
1063
+ var serial = _serialToInteger(opts.serialNumber);
1064
+ var issuerDer = guard.bytes.snapshotSource(opts.issuer, ScepError, "scep/bad-input", "issuer");
1065
+ var issuerRdns;
1066
+ try { issuerRdns = schema.walk(pkix.name(_KU_NS), asn1.decode(issuerDer), _KU_NS).result.rdns; }
1067
+ catch (e) { throw _err("scep/bad-input", "issuer is not a valid Name DER (RFC 8894 sec. 3.3.4): " + e.message, e); }
1068
+ return { issuerRdns: issuerRdns, serial: serial, buildSpec: { issuer: issuerDer, serialNumber: opts.serialNumber } };
1069
+ }
1070
+
1071
+ async function _queryOperation(messageType, baseUrl, opts, verbName) {
1072
+ opts = guard.identifier.optionsObject(opts, _err, "scep/bad-input", "pki.scep." + verbName + " options");
1073
+ guard.identifier.assertKnownKeys(opts, _QUERY_KEYS, _err, "scep/bad-input", "pki.scep." + verbName + " has an unknown option: ");
1074
+ if (opts.caCert == null) throw _err("scep/bad-input", "a caCert (the SCEP CA certificate DER) is required");
1075
+ if (opts.signer == null || typeof opts.signer !== "object") throw _err("scep/bad-input", "a signer { cert, key } is required");
1076
+ if (opts.recipientKey == null || typeof opts.recipientKey !== "object") throw _err("scep/bad-input", "a recipientKey { cert, key } is required to decrypt the CA response");
1077
+ var caCert = guard.bytes.snapshotSource(opts.caCert, ScepError, "scep/bad-input", "the caCert");
1078
+ var signerCert = opts.responderCert != null ? guard.bytes.snapshotSource(opts.responderCert, ScepError, "scep/bad-input", "the responderCert") : caCert;
1079
+ var recipientKey = _captureRecipientKey(opts.recipientKey);
1080
+ var signer = { cert: guard.bytes.snapshotSource(opts.signer.cert, ScepError, "scep/bad-input", "signer.cert"), key: opts.signer.key };
1081
+ var want = _resolveQueryTarget(opts);
1082
+ 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 };
1083
+ var senderNonce = nodeCrypto.randomBytes(16);
1084
+ var transactionId = opts.transactionId != null ? opts.transactionId : _defaultTransactionId();
1085
+ var reqMsg = await build(Object.assign({ messageType: messageType, recipient: caCert, signer: signer, transactionId: transactionId, senderNonce: senderNonce }, want.buildSpec));
1086
+ var res = await _client("POST", _scepUrl(baseUrl, "PKIOperation"), reqMsg, { "content-type": CT_PKI_MESSAGE }, clientOpts);
1087
+ var body = _requireOk(res, [CT_PKI_MESSAGE], "PKIOperation");
1088
+ var rep = await parse(body, { signerCert: signerCert, expectedSenderNonce: senderNonce, recipientKey: recipientKey });
1089
+ _dispatchQueryRep(rep, transactionId);
1090
+ return { rep: rep, want: want, transactionId: transactionId };
1091
+ }
1092
+
1093
+ /**
1094
+ * @primitive pki.scep.getCert
1095
+ * @signature pki.scep.getCert(baseUrl, opts) -> Promise<{ certificate, certificates, transactionId }>
1096
+ * @since 0.6.17
1097
+ * @status stable
1098
+ * @spec RFC 8894
1099
+ * @related pki.scep.enroll, pki.scep.getCrl
1100
+ *
1101
+ * Retrieve an already-issued certificate over SCEP (RFC 8894 sec. 3.3.4): POST a GetCert query naming the
1102
+ * certificate's issuer and serial number, and select it out of the CA's certs-only CertRep by canonical
1103
+ * issuer-name and serial match. This is an OPTIONAL fallback: RFC 8894 sec. 3.3.4 advises a client to prefer
1104
+ * an HTTP certificate store (RFC 4387) or LDAP and to use this only against a CA that offers no such access.
1105
+ * The response is authenticated against the CA certificate and its recipientNonce must echo the request's
1106
+ * fresh senderNonce; a FAILURE throws `scep/query-failed`, a PENDING is refused (`scep/unexpected-pending`, a
1107
+ * query grants or rejects), and a SUCCESS not carrying the requested certificate throws `scep/cert-not-found`.
1108
+ * `certificate` is the one matched to the requested issuer and serial; `certificates` is every certificate the
1109
+ * authenticated response carried, raw, so a caller relies on `certificate` for the queried identity.
1110
+ *
1111
+ * @opts
1112
+ * - `certificate` -- the certificate DER whose issuer and serial name the one to retrieve (the convenience form).
1113
+ * - `issuer` / `serialNumber` -- the issuer Name DER and serial (a BigInt, number, or hex string) naming the certificate, for a caller that did not retain it.
1114
+ * - `caCert` -- the SCEP CA certificate DER the query is encrypted to.
1115
+ * - `signer` -- `{ cert, key }`, the outer SignedData signer.
1116
+ * - `recipientKey` -- `{ cert, key }`, the RSA key the CA encrypts the response to, to decrypt the CertRep.
1117
+ * - `responderCert` -- the certificate to authenticate the CA response signature against (defaults to `caCert`).
1118
+ * - `transactionId` -- a caller-unique PrintableString (defaults to 16 random bytes, hex-encoded).
1119
+ * - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
1120
+ * @example
1121
+ * // requires: clientCertDer, caCertDer, clientKeyPkcs8, scepTransport
1122
+ * var out = await pki.scep.getCert("http://ca.example/scep", { certificate: clientCertDer, caCert: caCertDer,
1123
+ * signer: { cert: clientCertDer, key: clientKeyPkcs8 },
1124
+ * recipientKey: { cert: clientCertDer, key: clientKeyPkcs8 }, transport: scepTransport });
1125
+ * out.certificate; // the retrieved certificate DER
1126
+ */
1127
+ async function getCert(baseUrl, opts) {
1128
+ var q = await _queryOperation("GetCert", baseUrl, opts, "getCert");
1129
+ var certs = q.rep.certificates || [];
1130
+ var match = null;
1131
+ for (var i = 0; i < certs.length; i++) {
1132
+ var w = schemaX509.parse(certs[i]);
1133
+ if (guard.name.dnEqual(w.issuer.rdns, q.want.issuerRdns, _err, "scep/bad-response", "the returned certificate issuer") && w.serialNumber === q.want.serial) {
1134
+ if (match != null) throw _err("scep/ambiguous-cert", "the CA returned more than one certificate matching the requested issuer and serial (RFC 8894 sec. 3.3.4)");
1135
+ match = certs[i];
1136
+ }
1137
+ }
1138
+ if (match == null) throw _err("scep/cert-not-found", "the CA response did not carry a certificate matching the requested issuer and serial (RFC 8894 sec. 3.3.4)");
1139
+ return { certificate: match, certificates: certs, transactionId: q.transactionId };
1140
+ }
1141
+
1142
+ /**
1143
+ * @primitive pki.scep.getCrl
1144
+ * @signature pki.scep.getCrl(baseUrl, opts) -> Promise<{ crl, crls, transactionId }>
1145
+ * @since 0.6.17
1146
+ * @status stable
1147
+ * @spec RFC 8894
1148
+ * @related pki.scep.getCert, pki.crl.verify
1149
+ *
1150
+ * Retrieve a CRL over SCEP (RFC 8894 sec. 3.3.4): POST a GetCRL query naming the CA by the issuer and serial
1151
+ * of a certificate it issued, and read the CRL out of the CA's CRL-only CertRep. This is an OPTIONAL fallback:
1152
+ * RFC 8894 sec. 2.7 says a client should compose a GetCRL only if the CA supports neither a CRL distribution
1153
+ * point nor HTTP access, and prefer those. The response is authenticated against the CA certificate and its
1154
+ * recipientNonce must echo the request's fresh senderNonce; a FAILURE throws `scep/query-failed`, and a PENDING is
1155
+ * refused. The returned CRL is bound to the query: `crl` is the one whose issuer matches the requested CA, so a
1156
+ * response carrying no such CRL throws `scep/no-crl` and one carrying more than one throws `scep/ambiguous-crl`.
1157
+ * The full response list is on `crls`, raw for the caller to validate with `pki.crl.verify`.
1158
+ *
1159
+ * @opts
1160
+ * - `certificate` -- a certificate DER the CA issued, whose issuer and serial name the CA to query (the convenience form).
1161
+ * - `issuer` / `serialNumber` -- the issuer Name DER and serial (a BigInt, number, or hex string) naming the CA, when the caller did not retain such a certificate.
1162
+ * - `caCert` -- the SCEP CA certificate DER the query is encrypted to.
1163
+ * - `signer` -- `{ cert, key }`, the outer SignedData signer.
1164
+ * - `recipientKey` -- `{ cert, key }`, the RSA key the CA encrypts the response to.
1165
+ * - `responderCert` -- the certificate to authenticate the CA response against (defaults to `caCert`).
1166
+ * - `transactionId` -- a caller-unique PrintableString (defaults to 16 random bytes, hex-encoded).
1167
+ * - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
1168
+ * @example
1169
+ * // requires: clientCertDer, caCertDer, clientKeyPkcs8, scepTransport
1170
+ * var out = await pki.scep.getCrl("http://ca.example/scep", { certificate: clientCertDer, caCert: caCertDer,
1171
+ * signer: { cert: clientCertDer, key: clientKeyPkcs8 },
1172
+ * recipientKey: { cert: clientCertDer, key: clientKeyPkcs8 }, transport: scepTransport });
1173
+ * out.crl; // the retrieved CRL DER
1174
+ */
1175
+ async function getCrl(baseUrl, opts) {
1176
+ var q = await _queryOperation("GetCRL", baseUrl, opts, "getCrl");
1177
+ var crls = q.rep.crls || [];
1178
+ var match = null;
1179
+ for (var i = 0; i < crls.length; i++) {
1180
+ var w = schemaCrl.parse(crls[i]);
1181
+ if (guard.name.dnEqual(w.issuer.rdns, q.want.issuerRdns, _err, "scep/bad-response", "the returned CRL issuer")) {
1182
+ if (match != null) throw _err("scep/ambiguous-crl", "the CA returned more than one CRL issued by the requested CA (RFC 8894 sec. 3.3.4)");
1183
+ match = crls[i];
1184
+ }
1185
+ }
1186
+ if (match == null) throw _err("scep/no-crl", "the CA response did not carry a CRL issued by the requested CA (RFC 8894 sec. 3.3.4)");
1187
+ return { crl: match, crls: crls, transactionId: q.transactionId };
1188
+ }
1189
+
872
1190
  var _TRANSPORT_KEYS = { transport: 1, timeout: 1, maxResponseBytes: 1, maxRedirects: 1, tls: 1, allowCrossOriginRedirect: 1 };
873
1191
  function _withKeys(extra) { var o = {}, k; for (k in _TRANSPORT_KEYS) o[k] = 1; for (k in extra) o[k] = 1; return o; }
874
1192
  var _CACAPS_KEYS = _withKeys({ expectSCEPStandard: 1, requireStrongProfile: 1 });
875
1193
  var _CACERT_KEYS = _withKeys({ expectedFingerprint: 1, fingerprintAlgorithm: 1 });
876
1194
  var _NEXTCACERT_KEYS = _withKeys({ caCertificate: 1 });
877
- var _ENROLL_KEYS = _withKeys({ csr: 1, caCert: 1, signer: 1, recipientKey: 1, responderCert: 1, transactionId: 1 });
1195
+ 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 });
1196
+ var _QUERY_KEYS = _withKeys({ certificate: 1, issuer: 1, serialNumber: 1, caCert: 1, signer: 1, recipientKey: 1, responderCert: 1, transactionId: 1 });
878
1197
 
879
1198
  module.exports = {
880
1199
  build: build,
@@ -884,6 +1203,8 @@ module.exports = {
884
1203
  getNextCACert: getNextCACert,
885
1204
  enroll: enroll,
886
1205
  renew: renew,
1206
+ getCert: getCert,
1207
+ getCrl: getCrl,
887
1208
  parseCapabilities: parseCapabilities,
888
1209
  MESSAGE_TYPES: MESSAGE_TYPE,
889
1210
  PKI_STATUS: PKI_STATUS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.15",
3
+ "version": "0.6.17",
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:b21c243d-9b6e-49ab-9c19-3427ff43e9bc",
5
+ "serialNumber": "urn:uuid:ea4426a6-da57-4694-9766-3f651e6423ae",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-01T08:58:18.522Z",
8
+ "timestamp": "2026-09-01T14:08:00.688Z",
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.15",
22
+ "bom-ref": "@blamejs/pki@0.6.17",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.15",
25
+ "version": "0.6.17",
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.15",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.17",
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.15",
57
+ "ref": "@blamejs/pki@0.6.17",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]