@blamejs/pki 0.5.22 → 0.5.24

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,7 +4,36 @@ 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.5.22 — 2026-08-21
7
+ ## v0.5.24 — 2026-08-21
8
+
9
+ An ACME certificate download is now bound to the order that asked for it, so a certificate for another key or another name is refused instead of returned as the issued one.
10
+
11
+ ### Changed
12
+
13
+ - `downloadCertificate` requires the material that makes that check possible: `expectedSpki`, `identifiers`, or both. A call supplying neither is refused with `acme/binding-required` rather than returning a certificate nothing looked at. Passing `requireBinding: false` waives the requirement to supply material and never the check on material that is supplied, and the result reports `boundToKey` and `boundToIdentifiers` so an unchecked download cannot read as a checked one. See MIGRATING.md.
14
+
15
+ ### Fixed
16
+
17
+ - `downloadCertificate` checks the end-entity certificate it received against the order: its subject public key must be the one this order's CSR asked to have certified (`acme/certificate-key-mismatch`), and its identifier set must equal the order's identifiers (`acme/certificate-identifier-mismatch`). A certificate's identifiers are its dNSName and iPAddress subject alternative names, with its subject common name read only where it asserts none: where an alternative name is present the common name is not an additional identity, and an address in a common name is never an IP identity, because name matching reads the alternative names and does not fall back. The binding runs on whichever chain is returned, including a chain chosen through `selectChain`.
18
+ - An identifier that maps to no certificate name is refused as `acme/unsupported-identifier-type` rather than dropped from the comparison, on both sides of it. The ACME identifier registry is open and only `dns` and `ip` name something a certificate carries, so an order identifier of another 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, would otherwise be skipped while the comparison still reported the whole set as checked: an order for a name plus one other identifier was satisfied by a certificate covering only the name, a certificate additionally naming a mailbox compared equal to an order that covered no mailbox, and a certificate naming both the order's name and a trailing-dot spelling of another compared equal on the strength of the first. The outbound `finalize` check refuses the same names, and reads every common name the request carries whether or not it also asserts alternative names -- a request naming the order's identifier in an alternative name and an unauthorized one in its subject is a request for a name the order does not cover, since a CA may carry that common name through into the certificate it issues.
19
+ - Names fold with ASCII case rules rather than the Unicode mapping, so a character whose Unicode lowercase is ASCII -- U+212A KELVIN SIGN folds to `k` -- is not read as the ASCII name it would fold to. That fold now has one definition the host-part rule, the CMP domain comparison and this one share.
20
+ - The names a certificate carries survive a replaced built-in. Every operation the shared PKIX decoders traverse, convert, copy and compare names with is bound when the module loads, and the tables that decide which GeneralName alternative a tag selects, which string types are DisplayText, and which decoder an extension OID resolves to hold no prototype. Replacing `Array.prototype.map`, `Buffer.prototype.toString`, `Buffer.concat`, `Array.prototype.push` or `Array.prototype.forEach` after load, or planting a name on `Object.prototype`, could otherwise present a subject alternative name or a subject common name the encoded certificate does not carry -- which any comparison downstream, including the certificate binding above, would then answer about.
21
+ - Every guard module freezes its exports. A boundary reaches its fail-closed check as a property of the guard object at the moment of the call, and the module registry hands every caller the same object, so a single assignment would have replaced a check -- a constant-time comparison, a size cap, a secret wipe -- in every module at once.
22
+
23
+ ## v0.5.23 — 2026-08-20
24
+
25
+ The tables that decide which status codes, revocation reasons, trust bits and extensions this toolkit recognizes now answer from an operation taken at load, and an unsupported HTTP Digest algorithm is refused rather than read off a prototype.
26
+
27
+ ### Changed
28
+
29
+ - Eighteen further modules -- ACME, EST, CMC, WebAuthn and its metadata reader, Certificate Transparency, trust-store ingest, TLS certificate compression, HPKE, HTTP Digest, the CRL and attribute-certificate signers, and the OCSP, CRL, attribute-certificate and shared PKIX schemas -- are held to the live-read rule, each declaring the reads it still carries as a count that can only fall.
30
+
31
+ ### Fixed
32
+
33
+ - An HTTP Digest challenge naming an unsupported algorithm is refused with a typed error. The algorithm registry was an ordinary object, so a name matching any member of `Object.prototype` answered the supported-algorithm gate with a value the registry never held: the refusal was skipped and the call ended in an untyped `TypeError`. The registry now carries a null prototype.
34
+ - OCSP response statuses and revocation reasons, CRL reason codes, CCADB trust bits, attribute-certificate critical extensions and object-digest types, Certificate Transparency log states, and the repeated-parameter check on an HTTP Digest challenge all decide membership through a captured operation, so replacing the runtime's own membership test after load cannot widen what they accept.
35
+
36
+ ## v0.5.22 — 2026-08-20
8
37
 
9
38
  The list tests that decide whether a caller's argument is refused, and which form an extension spec is in, now answer from operations taken at load rather than read when they run.
10
39
 
package/MIGRATING.md CHANGED
@@ -14,6 +14,37 @@ The toolkit has no `deprecate()`-marked surface awaiting removal.
14
14
 
15
15
  Listed newest-first.
16
16
 
17
+ ### v0.5.24 — `pki.acme.client(...).downloadCertificate(url, opts)`
18
+
19
+ The verb needs to be told which certificate the download is allowed to be, and refuses with acme/binding-required when it is not.
20
+
21
+ Pass `expectedSpki` (the DER SubjectPublicKeyInfo this order's CSR asked to have certified) and
22
+ `identifiers` (the order's own identifier array). Either alone is accepted, and each is checked
23
+ on its own.
24
+
25
+ Nothing previously bound the certificate a CA returned to the order that was placed, so a
26
+ certificate resource answering with a certificate for another key, or another name, came back as
27
+ the issued certificate for that order. The outbound half of the exchange already refuses a CSR
28
+ whose identifier set is not the order's, and the other enrollment clients bind the issued
29
+ certificate to the requested key, so this closes the one direction that did not.
30
+
31
+ ```js
32
+ var order = await client.pollOrder(orderUrl);
33
+ var res = await client.downloadCertificate(order.certificate); // used to accept any answer
34
+
35
+ var res = await client.downloadCertificate(order.certificate,
36
+ { expectedSpki: csrSpki, identifiers: order.identifiers });
37
+ // res.boundToKey === true, res.boundToIdentifiers === true
38
+ ```
39
+
40
+ A mismatch is `acme/certificate-key-mismatch` or `acme/certificate-identifier-mismatch`.
41
+
42
+ Where the material genuinely is not available -- reading a certificate resource outside an
43
+ enrollment -- pass `requireBinding: false`. The result then reports `boundToKey: false` and
44
+ `boundToIdentifiers: false` rather than reading as a checked download. That waiver drops the
45
+ requirement to supply material and never the check on material that is supplied, so a value
46
+ passed alongside it is still compared.
47
+
17
48
  ### v0.5.8 — `pki.smime.verify(...).headerProtection.fromMismatch`
18
49
 
19
50
  Now null when there was no protected From to compare against, where it used to be false.
package/README.md CHANGED
@@ -223,7 +223,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
223
223
  | `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 |
224
224
  | `pki.transport` | The shared, fail-closed `node:https` transport the enrollment clients drive. `pki.transport.https(defaults)` returns a `transport(request) → { status, headers, body, tls }`, where `tls` carries the negotiated `protocol`, `cipher`, and raw `peerCertificate`. This is the toolkit's only socket choke point: an explicit trust anchor (or an opt-in to the system store) is required, `rejectUnauthorized` is always on, TLS is floored at 1.2, the response body is capped while it streams, and a stalled socket times out. The EST, ACME, and CMP clients reuse it verbatim. If you inject your own transport, return `tls` too: `pki.est.serverkeygen` asserts the negotiated cipher can protect the delivered private key, and a transport that reports no cipher is trusted rather than refused, so omitting the field silently skips that check — `https` |
225
225
  | `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` |
226
- | `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` 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`, `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, 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` |
226
+ | `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`, `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, 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` |
227
227
  | `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` |
228
228
  | `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`. 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` |
229
229
  | `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
@@ -49,6 +49,35 @@ var frameworkError = require("./framework-error");
49
49
  var httpTransport = require("./http-transport");
50
50
  var retryAfter = require("./http-retry-after");
51
51
  var guard = require("./guard-all");
52
+ var intrinsic = require("./guard-intrinsic");
53
+ // Membership is asked through an operation taken at load. Written out, the question reads two
54
+ // replaceable properties to answer one thing, and either answering wrongly changes whether a field
55
+ // counts as present in a document this client is deciding how to act on.
56
+ var _hasOwn = intrinsic.hasOwn;
57
+ // The operations the issued-certificate binding decides with, taken at load. That check runs on bytes
58
+ // a server chose, at a moment a caller controls, and it is the only thing standing between an
59
+ // enrollment and a certificate for someone else's name -- so what it decides with cannot be a property
60
+ // read when it runs. See guard-intrinsic for the whole captured set.
61
+ var _isBuffer = intrinsic.isBuffer;
62
+ var _isArrayI = intrinsic.isArray;
63
+ var _forEach = intrinsic.forEach;
64
+ var _mapI = intrinsic.map;
65
+ var _someI = intrinsic.some;
66
+ var _sortI = intrinsic.sort;
67
+ var _objectKeys = intrinsic.keys;
68
+ var _lower = intrinsic.toLowerCase;
69
+ var _StringI = intrinsic.String;
70
+ var _stringify = intrinsic.stringify;
71
+ var _push = intrinsic.push;
72
+ var _join = intrinsic.join;
73
+ var _concat = intrinsic.concat;
74
+ var _split = intrinsic.uncurry(String.prototype.split);
75
+ var _parseIntI = intrinsic.parseInt;
76
+ var _numToString = intrinsic.numberToString;
77
+ var _reTest = intrinsic.uncurry(RegExp.prototype.test);
78
+ var _strSlice = intrinsic.uncurry(String.prototype.slice);
79
+ var _charCodeAt = intrinsic.uncurry(String.prototype.charCodeAt);
80
+ var _charAt = intrinsic.uncurry(String.prototype.charAt);
52
81
  var pkgVersion = require("../package.json").version;
53
82
 
54
83
  var AcmeError = frameworkError.AcmeError;
@@ -211,7 +240,7 @@ function _validate(kind, obj) {
211
240
  var spec = SPECS[kind];
212
241
  for (var f = 0; f < spec.length; f++) {
213
242
  var field = spec[f];
214
- var present = Object.prototype.hasOwnProperty.call(obj, field.name);
243
+ var present = _hasOwn(obj, field.name);
215
244
  var required = field.required || (field.requiredWhen && field.requiredWhen(obj));
216
245
  if (!present) {
217
246
  if (required) throw E("acme/missing-field", "an ACME " + kind + " is missing the required field " + JSON.stringify(field.name));
@@ -294,31 +323,33 @@ function _canonicalizeIpv6(value) {
294
323
  var groups;
295
324
  if (value.indexOf("::") !== -1) {
296
325
  if (value.indexOf("::") !== value.lastIndexOf("::")) return null; // only one ::
297
- var halves = value.split("::");
298
- var left = halves[0] ? halves[0].split(":") : [];
299
- var right = halves[1] ? halves[1].split(":") : [];
326
+ var halves = _split(value, "::");
327
+ var left = halves[0] ? _split(halves[0], ":") : [];
328
+ var right = halves[1] ? _split(halves[1], ":") : [];
300
329
  var fill = 8 - left.length - right.length;
301
330
  if (fill < 1) return null;
302
- groups = left.concat(new Array(fill).fill("0")).concat(right);
331
+ var zeros = [];
332
+ for (var z = 0; z < fill; z++) _push(zeros, "0");
333
+ groups = _concat(_concat(left, zeros), right);
303
334
  } else {
304
- groups = value.split(":");
335
+ groups = _split(value, ":");
305
336
  }
306
337
  if (groups.length !== 8) return null;
307
338
  var nums = [];
308
339
  for (var i = 0; i < 8; i++) {
309
- if (!/^[0-9a-f]{1,4}$/.test(groups[i])) return null;
310
- nums.push(parseInt(groups[i], 16));
340
+ if (!_reTest(/^[0-9a-f]{1,4}$/, groups[i])) return null;
341
+ _push(nums, _parseIntI(groups[i], 16));
311
342
  }
312
- var hex = nums.map(function (n) { return n.toString(16); });
343
+ var hex = _mapI(nums, function (n) { return _numToString(n, 16); });
313
344
  // Longest run of zero groups (>= 2) -> "::"; leftmost on a tie.
314
345
  var bestStart = -1, bestLen = 0, curStart = -1, curLen = 0;
315
346
  for (var g = 0; g < 8; g++) {
316
347
  if (nums[g] === 0) { if (curStart === -1) curStart = g; curLen++; if (curLen > bestLen) { bestLen = curLen; bestStart = curStart; } }
317
348
  else { curStart = -1; curLen = 0; }
318
349
  }
319
- if (bestLen < 2) return hex.join(":");
320
- var head = hex.slice(0, bestStart).join(":");
321
- var tail = hex.slice(bestStart + bestLen).join(":");
350
+ if (bestLen < 2) return _join(hex, ":");
351
+ var head = _join(intrinsic.arraySlice(hex, 0, bestStart), ":");
352
+ var tail = _join(intrinsic.arraySlice(hex, bestStart + bestLen), ":");
322
353
  return head + "::" + tail;
323
354
  }
324
355
 
@@ -383,9 +414,9 @@ var ERROR_NAMESPACE = "urn:ietf:params:acme:error:";
383
414
  */
384
415
  function validateProblem(obj) {
385
416
  if (!_isObject(obj)) throw E("acme/bad-problem", "a problem document must be a JSON object");
386
- if (Object.prototype.hasOwnProperty.call(obj, "identifier")) throw E("acme/bad-problem", "a top-level problem document must not carry an identifier (RFC 8555 sec. 6.7.1)");
417
+ if (_hasOwn(obj, "identifier")) throw E("acme/bad-problem", "a top-level problem document must not carry an identifier (RFC 8555 sec. 6.7.1)");
387
418
  if (!_isString(obj.type) || obj.type.indexOf(ERROR_NAMESPACE) !== 0) throw E("acme/bad-problem", "an ACME problem type must be in the " + ERROR_NAMESPACE + " namespace (RFC 8555 sec. 6.7)");
388
- if (Object.prototype.hasOwnProperty.call(obj, "subproblems")) {
419
+ if (_hasOwn(obj, "subproblems")) {
389
420
  if (!Array.isArray(obj.subproblems)) throw E("acme/bad-problem", "subproblems must be an array");
390
421
  for (var i = 0; i < obj.subproblems.length; i++) {
391
422
  var sub = obj.subproblems[i];
@@ -393,7 +424,7 @@ function validateProblem(obj) {
393
424
  // A subproblem identifier reflects a submitted order identifier, which MAY be a
394
425
  // wildcard (a rejectedIdentifier for a *.example.org order), so it is validated
395
426
  // with the order-identifier rule, not the stricter authorization one.
396
- if (Object.prototype.hasOwnProperty.call(sub, "identifier")) _validateOrderIdentifier(sub.identifier);
427
+ if (_hasOwn(sub, "identifier")) _validateOrderIdentifier(sub.identifier);
397
428
  }
398
429
  }
399
430
  return obj;
@@ -455,7 +486,7 @@ function validate(kind, obj) {
455
486
  */
456
487
  function identify(obj) {
457
488
  if (!_isObject(obj)) return "unknown";
458
- var has = function (k) { return Object.prototype.hasOwnProperty.call(obj, k); };
489
+ var has = function (k) { return _hasOwn(obj, k); };
459
490
  if (has("protected") && has("signature") && _isString(obj.protected) && _isString(obj.signature)) return "jws";
460
491
  if (_isString(obj.type) && obj.type.indexOf(ERROR_NAMESPACE) === 0) return "problem";
461
492
  if (has("newNonce") && has("newAccount")) return "directory";
@@ -677,8 +708,8 @@ async function verifyTlsAlpn01(certDer, token, accountJwk, identifier) {
677
708
  // `url`, and either `kid` (an account URL) or `jwk` (an embedded public JWK).
678
709
  function _outerHeader(o) {
679
710
  var h = { alg: o.alg, nonce: o.nonce, url: o.url };
680
- if (Object.prototype.hasOwnProperty.call(o, "kid")) h.kid = o.kid;
681
- if (Object.prototype.hasOwnProperty.call(o, "jwk")) h.jwk = o.jwk;
711
+ if (_hasOwn(o, "kid")) h.kid = o.kid;
712
+ if (_hasOwn(o, "jwk")) h.jwk = o.jwk;
682
713
  return h;
683
714
  }
684
715
  function _payloadBuf(obj) {
@@ -922,12 +953,17 @@ async function _jwkToSpki(jwk) {
922
953
 
923
954
  // EVERY common name in the subject (a DN may carry more than one CN RDN) -- taking
924
955
  // only the first would let a second CN smuggle an identifier past the order-set match.
956
+ // Walked through the captured operations, because this feeds the issued-certificate binding: the set
957
+ // it builds is what says the certificate names what the order asked for, and it is built after the
958
+ // download returns. A replaced traversal could present a name the certificate does not carry, and the
959
+ // comparison would agree that the two sets are equal.
925
960
  function _subjectCommonNames(subject) {
926
961
  var names = [];
927
- if (!subject || !Array.isArray(subject.rdns)) return names;
928
- subject.rdns.forEach(function (atvs) {
929
- atvs.forEach(function (atv) {
930
- if ((atv.name === "commonName" || atv.type === OID_CN) && _isString(atv.value)) names.push(atv.value);
962
+ if (!subject || !_isArrayI(subject.rdns)) return names;
963
+ _forEach(subject.rdns, function (atvs) {
964
+ if (!_isArrayI(atvs)) return;
965
+ _forEach(atvs, function (atv) {
966
+ if ((atv.name === "commonName" || atv.type === OID_CN) && _isString(atv.value)) _push(names, atv.value);
931
967
  });
932
968
  });
933
969
  return names;
@@ -936,12 +972,12 @@ function _subjectCommonNames(subject) {
936
972
  // An iPAddress SAN octet string (4 = IPv4, 16 = IPv6) to its RFC 8738 canonical
937
973
  // text -- the same form an order ip identifier carries -- or null on a bad length.
938
974
  function _ipBytesToText(buf) {
939
- if (!Buffer.isBuffer(buf)) return null;
975
+ if (!_isBuffer(buf)) return null;
940
976
  if (buf.length === 4) return buf[0] + "." + buf[1] + "." + buf[2] + "." + buf[3];
941
977
  if (buf.length === 16) {
942
978
  var groups = [];
943
- for (var i = 0; i < 16; i += 2) groups.push(((buf[i] << 8) | buf[i + 1]).toString(16));
944
- return _canonicalizeIpv6(groups.join(":"));
979
+ for (var i = 0; i < 16; i += 2) _push(groups, _numToString((buf[i] << 8) | buf[i + 1], 16));
980
+ return _canonicalizeIpv6(_join(groups, ":"));
945
981
  }
946
982
  return null;
947
983
  }
@@ -950,44 +986,167 @@ function _ipBytesToText(buf) {
950
986
  // SAN dNSName / iPAddress entries in the extensionRequest attribute, keyed
951
987
  // "dns:<lower>" / "ip:<canonical>" for an order-insensitive compare.
952
988
  function _csrIdentifierSet(parsedCsr) {
953
- var set = {};
954
- _subjectCommonNames(parsedCsr.subject).forEach(function (cn) { set["dns:" + cn.toLowerCase()] = true; });
989
+ // Null prototype: membership below is asked as `set[k]`, and against an ordinary object that question
990
+ // reaches Object.prototype, so a name planted there would read as an identifier the request carried.
991
+ var set = intrinsic.create(null);
955
992
  // PKCS#10 permits duplicate attribute types, so aggregate EVERY extensionRequest
956
993
  // attribute and EVERY subjectAltName within each -- taking only the first would let
957
994
  // a second extensionRequest smuggle identifiers past the order-set comparison.
958
- (parsedCsr.attributes || []).forEach(function (a) {
959
- if (a.type !== oid.byName("extensionRequest") || !Array.isArray(a.extensions)) return;
960
- a.extensions.forEach(function (e) {
995
+ _forEach(parsedCsr.attributes || [], function (a) {
996
+ if (a.type !== oid.byName("extensionRequest") || !_isArrayI(a.extensions)) return;
997
+ _forEach(a.extensions, function (e) {
961
998
  if (e.oid !== OID_SAN) return;
962
999
  var dec = _extDecoders.byOid[OID_SAN](e.value, _extCtx);
963
- (dec.names || []).forEach(function (n) {
964
- if (n.tagNumber === 2) set["dns:" + String(n.value).toLowerCase()] = true;
965
- else if (n.tagNumber === 7) { var t = _ipBytesToText(n.value); if (t) set["ip:" + t] = true; }
966
- });
1000
+ _forEach(dec.names || [], function (n) { _addSanName(set, n, "the finalize CSR"); });
967
1001
  });
968
1002
  });
1003
+ // EVERY common name, alternative names present or not -- which is where this side parts from the
1004
+ // issued-certificate set, because the two answer different questions. That set asks what a
1005
+ // certificate authenticates, and no matcher reads a common name for that. This one asks what the
1006
+ // request is ASKING to have certified, and a CA may carry a common name through into the issued
1007
+ // certificate, so a CSR naming the order's name in a SAN and an unauthorized one in its subject is
1008
+ // a request for a name the order does not cover.
1009
+ _forEach(_subjectCommonNames(parsedCsr.subject), function (cn) { _addCommonName(set, cn, "the finalize CSR"); });
969
1010
  return set;
970
1011
  }
971
1012
 
1013
+ // One subjectAltName entry folded into an identifier set, for the CSR and the issued certificate
1014
+ // alike. A dNSName or iPAddress maps to an ACME order identifier; anything else -- rfc822Name,
1015
+ // otherName, directoryName, uniformResourceIdentifier, registeredID -- does not, and is REFUSED
1016
+ // rather than skipped. Skipping it would leave a name in the certificate that the set-equality
1017
+ // comparison never saw, so a certificate additionally naming a mailbox or a URI would compare equal
1018
+ // to an order covering neither. A malformed iPAddress is the same case: unmappable, so unbindable.
1019
+ // One subject common name folded into an identifier set. A CN holding an IP literal is an IP
1020
+ // identifier, not a dns one: CABF TLS BR 7.1.4.2.2 lets a commonName match either a dNSName or an
1021
+ // iPAddress SAN, so an IP certificate routinely carries the address in both places while the order
1022
+ // carries it once as `ip`. Counting the CN as `dns:` there would make a correct issuance compare as
1023
+ // two identifiers against the order's one. A CN that looks like an address but is not the canonical
1024
+ // RFC 5952 / RFC 8738 form is neither a usable dns name nor a canonical ip identifier, and it is
1025
+ // refused rather than normalized -- the same rule the ip identifier validator applies.
1026
+ function _addCommonName(set, cn, what) {
1027
+ var looksIp = _reTest(/^\d{1,3}(\.\d{1,3}){3}$/, cn) || intrinsic.stringIndexOf(cn, ":") !== -1;
1028
+ // An address in a common name adds no identity of its own. Address matching reads the iPAddress
1029
+ // subjectAltName and never falls back to the common name, so a subject naming the ordered address
1030
+ // only there cannot authenticate it. What the ordinary IP certificate does -- CABF TLS BR
1031
+ // 7.1.4.2.2 permits a common name to match an iPAddress SAN, and issuers write the address in both
1032
+ // places -- is repeat an address the alternative names ALREADY carry, and that is a duplicate of an
1033
+ // authorized name rather than a new one. So: accepted where the set already holds it, refused
1034
+ // otherwise, which covers the address carried only in the subject and the one naming a DIFFERENT
1035
+ // address than the alternative names do. The alternative names are folded in before the common
1036
+ // names on both sides, so the set is complete by the time this reads it.
1037
+ if (looksIp) {
1038
+ var canonical = true;
1039
+ try { _assertIpAddress(cn); }
1040
+ catch (_e) {
1041
+ canonical = false;
1042
+ }
1043
+ if (canonical && set["ip:" + cn] === true) return;
1044
+ throw _unmappableName(what, cn, null);
1045
+ }
1046
+ // ASCII case folding, never the Unicode mapping. A DirectoryString common name may hold characters
1047
+ // whose Unicode lowercase IS ASCII -- U+212A KELVIN SIGN folds to "k" -- so a full fold turns a name
1048
+ // the certificate does not carry as a DNS label into one that compares equal to an order identifier.
1049
+ var folded = _asciiLower(cn);
1050
+ // A single leading `*.` is a wildcard name, which an order identifier carries verbatim (sec. 7.1.3)
1051
+ // and a certificate carries as a SAN, so it is validated the way the order validator validates one:
1052
+ // strip the one wildcard label, then hold the rest to the A-label rule.
1053
+ var base = intrinsic.stringIndexOf(folded, "*.") === 0 ? _strSlice(folded, 2) : folded;
1054
+ if (intrinsic.stringIndexOf(base, "*") !== -1) throw _unmappableName(what, cn, null);
1055
+ try { _assertDnsName(base); }
1056
+ catch (e2) {
1057
+ throw _unmappableName(what, cn, e2);
1058
+ }
1059
+ set["dns:" + folded] = true;
1060
+ }
1061
+
1062
+ // A name the comparison cannot express, refused rather than left out. Dropping it is unsafe even
1063
+ // though a smaller certificate set can only fail equality: a certificate may carry SEVERAL common
1064
+ // names, and dropping the unmappable one while another supplies the match reports the set as bound
1065
+ // while the certificate still names something the order never covered -- `CN=example.org,
1066
+ // CN=victim.example.`, where the trailing-dot spelling is one a hostname matcher will accept.
1067
+ function _unmappableName(what, name, cause) {
1068
+ return E("acme/unsupported-identifier-type",
1069
+ what + " carries the name " + _stringify(name) + " in its subject, which maps to no ACME order " +
1070
+ "identifier (only a dns name or a canonical IP address does), so the identifier set cannot be " +
1071
+ "compared", cause || undefined);
1072
+ }
1073
+
1074
+ // A-Z to a-z and nothing else, through the toolkit's one definition of that fold. String.prototype
1075
+ // .toLowerCase applies the full Unicode mapping, under which several non-ASCII characters fold INTO
1076
+ // ASCII, and a name folded that way is one the certificate does not carry.
1077
+ var _asciiLower = guard.name.lowerAscii;
1078
+
1079
+ function _addSanName(set, n, what) {
1080
+ // ASCII case folding on both sides of the comparison, never the Unicode mapping: a character whose
1081
+ // Unicode lowercase IS ASCII would otherwise fold into a name the certificate does not carry.
1082
+ if (n.tagNumber === 2) { set["dns:" + _asciiLower(_StringI(n.value))] = true; return; }
1083
+ if (n.tagNumber === 7) {
1084
+ var t = _ipBytesToText(n.value);
1085
+ if (t === null) throw E("acme/unsupported-identifier-type", what + " carries an iPAddress subjectAltName that is neither 4 nor 16 octets, so it maps to no order identifier");
1086
+ set["ip:" + t] = true;
1087
+ return;
1088
+ }
1089
+ throw E("acme/unsupported-identifier-type",
1090
+ what + " carries a subjectAltName of GeneralName type [" + n.tagNumber + "], which maps to no ACME " +
1091
+ "order identifier (only dNSName and iPAddress do), so the identifier set cannot be compared");
1092
+ }
1093
+
1094
+ // The order's own identifiers as the same keyed set. Built through the captured operations and with a
1095
+ // null prototype for the same two reasons its siblings are: this set is computed AFTER the certificate
1096
+ // download returns, so what walks the array and folds each name must not be replaceable in between,
1097
+ // and membership is asked as `set[k]`, which against an ordinary object would answer for a name planted
1098
+ // on Object.prototype rather than one the order carried.
972
1099
  function _orderIdentifierSet(identifiers) {
973
- var set = {};
974
- identifiers.forEach(function (id) {
975
- if (id.type === "dns") set["dns:" + id.value.toLowerCase()] = true;
1100
+ var set = intrinsic.create(null);
1101
+ _forEach(identifiers, function (id) {
1102
+ if (id.type === "dns") set["dns:" + _asciiLower(id.value)] = true;
976
1103
  else if (id.type === "ip") set["ip:" + id.value] = true;
1104
+ // A registered identifier type this comparison cannot map to a certificate name is REFUSED, not
1105
+ // dropped. Dropping it would leave the comparison answering about the identifiers it happens to
1106
+ // understand while reporting a check of the whole set: an order for a dns name and one other type
1107
+ // would be satisfied by a certificate naming only the dns name. The ACME identifier registry
1108
+ // (RFC 8555 sec. 9.7.7) is open, so this is the shape a new type arrives in.
1109
+ else throw E("acme/unsupported-identifier-type",
1110
+ "this build cannot bind a certificate to an order identifier of type " + _stringify(id.type) +
1111
+ " (only dns and ip map to a certificate name), so it cannot report the identifier set as checked");
1112
+ });
1113
+ return set;
1114
+ }
1115
+
1116
+ // The set of identifiers an ISSUED certificate carries, keyed the same way as the CSR and order sets
1117
+ // so the three are comparable. The subjectAltName entries are the names a certificate asserts; the
1118
+ // subject common name is consulted ONLY when there is no such entry. Where a SAN is present the
1119
+ // common name is not an additional identity -- name matching has read the SAN and ignored the common
1120
+ // name for many years, and CABF TLS BR 7.1.4.2.2 requires any common name to appear among the SAN
1121
+ // values anyway, so counting it again would make a certificate whose SAN set is exactly the order's
1122
+ // compare unequal because of a legacy or organizational common name beside it.
1123
+ //
1124
+ // A certificate may carry several SAN extensions in a non-conformant encoding, so every one is
1125
+ // aggregated rather than the first -- taking one would let a second smuggle a name past the
1126
+ // comparison.
1127
+ function _certIdentifierSet(parsedCert) {
1128
+ var set = intrinsic.create(null);
1129
+ _forEach(parsedCert.extensions || [], function (e) {
1130
+ if (e.oid !== OID_SAN) return;
1131
+ var dec = _extDecoders.byOid[OID_SAN](e.value, _extCtx);
1132
+ _forEach(dec.names || [], function (n) { _addSanName(set, n, "the downloaded certificate"); });
977
1133
  });
1134
+ if (_objectKeys(set).length === 0) {
1135
+ _forEach(_subjectCommonNames(parsedCert.subject), function (cn) { _addCommonName(set, cn, "the downloaded certificate"); });
1136
+ }
978
1137
  return set;
979
1138
  }
980
1139
 
981
1140
  function _assertCsrIdentifiers(parsedCsr, identifiers) {
982
1141
  var have = _csrIdentifierSet(parsedCsr);
983
1142
  var want = _orderIdentifierSet(identifiers);
984
- var haveKeys = Object.keys(have), wantKeys = Object.keys(want);
1143
+ var haveKeys = _objectKeys(have), wantKeys = _objectKeys(want);
985
1144
  var mismatch = haveKeys.length !== wantKeys.length ||
986
- wantKeys.some(function (k) { return !have[k]; }) ||
987
- haveKeys.some(function (k) { return !want[k]; });
1145
+ _someI(wantKeys, function (k) { return !have[k]; }) ||
1146
+ _someI(haveKeys, function (k) { return !want[k]; });
988
1147
  if (mismatch) {
989
- throw E("acme/csr-identifier-mismatch", "the finalize CSR identifier set " + JSON.stringify(haveKeys.sort()) +
990
- " does not equal the order identifiers " + JSON.stringify(wantKeys.sort()) + " (RFC 8555 sec. 7.4)");
1148
+ throw E("acme/csr-identifier-mismatch", "the finalize CSR identifier set " + _stringify(_sortI(haveKeys)) +
1149
+ " does not equal the order identifiers " + _stringify(_sortI(wantKeys)) + " (RFC 8555 sec. 7.4)");
991
1150
  }
992
1151
  }
993
1152
 
@@ -1113,8 +1272,8 @@ function revokeCert(o) {
1113
1272
  return _promised(function () {
1114
1273
  if (!_isObject(o) || !Buffer.isBuffer(o.certificate)) throw E("acme/bad-input", "revokeCert requires a DER certificate Buffer (opts.certificate)");
1115
1274
  x509.parse(o.certificate); // structural validation of the target
1116
- var hasKid = Object.prototype.hasOwnProperty.call(o, "kid");
1117
- var hasJwk = Object.prototype.hasOwnProperty.call(o, "jwk");
1275
+ var hasKid = _hasOwn(o, "kid");
1276
+ var hasJwk = _hasOwn(o, "jwk");
1118
1277
  if (hasKid === hasJwk) throw E("acme/bad-input", "revokeCert must be signed with EXACTLY ONE of the account kid or the certificate jwk (RFC 8555 sec. 7.6)");
1119
1278
  var payload = { certificate: jose.base64url.encode(o.certificate) };
1120
1279
  if (o.reason !== undefined) {
@@ -1675,7 +1834,7 @@ function _parseLinkValue(raw) {
1675
1834
  // unresolvable target fails closed as acme/bad-link. Scoped to the alternate relation the download consumes.
1676
1835
  function _parseLinkAlternates(headers, base) {
1677
1836
  var raw = null;
1678
- for (var k in headers) { if (Object.prototype.hasOwnProperty.call(headers, k) && k.toLowerCase() === "link") { raw = headers[k]; break; } }
1837
+ for (var k in headers) { if (_hasOwn(headers, k) && k.toLowerCase() === "link") { raw = headers[k]; break; } }
1679
1838
  if (raw == null) return [];
1680
1839
  var baseUrl = new URL(base), baseOrigin = baseUrl.origin, baseHref = baseUrl.href; // the download URL
1681
1840
  var fields = Array.isArray(raw) ? raw : [raw], out = [], seen = Object.create(null), totalBytes = 0;
@@ -1781,7 +1940,7 @@ function _parseLinkAlternates(headers, base) {
1781
1940
  * - `timeout` / `maxResponseBytes` / `maxRedirects` -- transport budgets; `maxNonceRetries` -- badNonce retry cap (default 1).
1782
1941
  * - `maxPolls` / `maxTotalWait` / `sleep` -- poll-loop budgets + an injectable sleeper; `clock` -- an injectable receipt clock (default Date.now) for a Retry-After HTTP-date.
1783
1942
  * - `newAuthz(identifier)` -- pre-authorize a single identifier (RFC 8555 sec. 7.4.1) -> { authorization, url }.
1784
- * - `downloadCertificate(url, { selectChain, maxAlternates })` -- pick among RFC 8555 sec. 7.4.2 alternate chains: `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).
1943
+ * - `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).
1785
1944
  * - `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.
1786
1945
  * @example
1787
1946
  * var acme = pki.acme.client("https://acme.example/directory", { accountKey, accountJwk, alg: "ES256", transport });
@@ -2112,6 +2271,71 @@ function client(directoryUrl, opts) {
2112
2271
  }
2113
2272
  function _fetchCertChain(url) { return _post(url, postAsGet, null, "kid", "application/pem-certificate-chain").then(_readCertChain); }
2114
2273
 
2274
+ // The material that says which certificate this download is allowed to be, reduced ONCE at the
2275
+ // door: the caller's options object is read here and never again, so a value that changes between
2276
+ // the check and the use cannot be what the check ran on. Returns { spki, ids, require }.
2277
+ function _bindingSpec(opts) {
2278
+ var spki = opts.expectedSpki, ids = opts.identifiers, req = opts.requireBinding;
2279
+ if (spki !== undefined) {
2280
+ if (!_isBuffer(spki)) throw E("acme/bad-input", "downloadCertificate opts.expectedSpki must be a DER SubjectPublicKeyInfo Buffer");
2281
+ // SNAPSHOT: the comparison happens after a network round trip, so a retained reference would let
2282
+ // the caller rewrite the key the certificate is checked against once the request had gone out --
2283
+ // rejecting the right certificate, or accepting one minted for the replacement bytes.
2284
+ spki = guard.bytes.snapshot(spki, AcmeError, "acme/bad-input", "downloadCertificate expectedSpki");
2285
+ }
2286
+ if (ids !== undefined) {
2287
+ if (!_isArrayI(ids) || ids.length === 0) throw E("acme/bad-input", "downloadCertificate opts.identifiers must be the non-empty order identifier array");
2288
+ // Reduced to this module's OWN validated copy at the door: the array and its entries are the
2289
+ // caller's, and the comparison below happens after a network round trip.
2290
+ ids = _mapI(ids, _validateOrderIdentifier);
2291
+ }
2292
+ if (req !== undefined && typeof req !== "boolean") throw E("acme/bad-input", "downloadCertificate opts.requireBinding must be a boolean");
2293
+ var require_ = req === undefined ? true : req;
2294
+ // Required by default, because a download nobody checked is the one an operator installs. The
2295
+ // waiver is explicit and it waives only the REQUIREMENT to supply material: anything supplied is
2296
+ // still checked below, so the waiver cannot become the place a mismatch hides.
2297
+ if (require_ && spki === undefined && ids === undefined) {
2298
+ throw E("acme/binding-required",
2299
+ "downloadCertificate needs the material that binds the issued certificate to this order -- " +
2300
+ "opts.expectedSpki (the DER SubjectPublicKeyInfo the CSR asked to have certified) and/or " +
2301
+ "opts.identifiers (the order's identifiers). Pass opts.requireBinding false to download without " +
2302
+ "either, in which case the result reports boundToKey and boundToIdentifiers false");
2303
+ }
2304
+ return { spki: spki, ids: ids, require: require_ };
2305
+ }
2306
+
2307
+ // Bind the certificate that came back to the request that was made. RFC 8555 sec. 7.4.2 says nothing
2308
+ // about what the certificate resource may return, so nothing on the wire stops a CA -- or anything
2309
+ // that can answer that URL -- from handing back a certificate for another key or another name. The
2310
+ // OUTBOUND direction already refuses a CSR whose identifier set is not the order's (sec. 7.4); this
2311
+ // is the same relation read back off the issued certificate. The sibling enrollment client makes the
2312
+ // same check: pki.est picks the issued certificate by public-key match against the submitted CSR.
2313
+ function _assertCertBinding(leafDer, spec) {
2314
+ var leaf;
2315
+ try { leaf = x509.parse(leafDer); }
2316
+ catch (e) { throw E("acme/bad-certificate-chain", "the downloaded end-entity certificate did not parse (RFC 8555 sec. 7.4.2)", e); }
2317
+ if (spec.spki !== undefined) {
2318
+ var got = leaf.subjectPublicKeyInfo && leaf.subjectPublicKeyInfo.bytes;
2319
+ if (!_isBuffer(got) || !guard.crypto.constantTimeEqual(got, spec.spki)) {
2320
+ throw E("acme/certificate-key-mismatch",
2321
+ "the downloaded certificate certifies a different public key than the one this order's CSR asked " +
2322
+ "to have certified, so it cannot be used with the private key held here (RFC 8555 sec. 7.4)");
2323
+ }
2324
+ }
2325
+ if (spec.ids !== undefined) {
2326
+ var have = _certIdentifierSet(leaf), want = _orderIdentifierSet(spec.ids);
2327
+ var haveKeys = _objectKeys(have), wantKeys = _objectKeys(want);
2328
+ var mismatch = haveKeys.length !== wantKeys.length ||
2329
+ _someI(wantKeys, function (k) { return !have[k]; }) ||
2330
+ _someI(haveKeys, function (k) { return !want[k]; });
2331
+ if (mismatch) {
2332
+ throw E("acme/certificate-identifier-mismatch",
2333
+ "the downloaded certificate's identifier set " + _stringify(_sortI(haveKeys)) +
2334
+ " is not the order's " + _stringify(_sortI(wantKeys)) + " (RFC 8555 sec. 7.4)");
2335
+ }
2336
+ }
2337
+ }
2338
+
2115
2339
  function _downloadCertificate(url, opts) {
2116
2340
  opts = opts || {};
2117
2341
  // Prelude in a resolved-promise .then so a bad opt / URL is a REJECTION, uniform for a .catch caller.
@@ -2119,6 +2343,7 @@ function client(directoryUrl, opts) {
2119
2343
  var select = opts.selectChain;
2120
2344
  if (select !== undefined && typeof select !== "function") throw E("acme/bad-input", "downloadCertificate opts.selectChain must be a function");
2121
2345
  var maxAlt = guard.limits.cap(opts.maxAlternates, "maxAlternates", DEFAULT_MAX_ALTERNATES, { E: E, code: "acme/bad-input", min: 0, max: 64 });
2346
+ var binding = _bindingSpec(opts);
2122
2347
  var dlUrl = _clientUrl(url);
2123
2348
  return _post(dlUrl, postAsGet, null, "kid", "application/pem-certificate-chain").then(function (res) {
2124
2349
  var primary = _readCertChain(res);
@@ -2128,7 +2353,19 @@ function client(directoryUrl, opts) {
2128
2353
  var alternates = [], linkError = null;
2129
2354
  try { alternates = _parseLinkAlternates(res.headers, dlUrl); }
2130
2355
  catch (e) { linkError = e; }
2131
- function result(cand) { return { certificate: cand.certificate, chain: cand.chain, certificates: cand.certificates, alternates: alternates }; }
2356
+ // Bind the primary leaf NOW, before a rejected primary can drive alternate fetches: an
2357
+ // unbindable certificate fails on the response that carried it rather than after up to
2358
+ // maxAlternates further signed POSTs.
2359
+ _assertCertBinding(primary.certificate, binding);
2360
+ // The same assertion again on whatever is actually returned. Every candidate must carry the
2361
+ // primary's own end-entity certificate (sec. 7.4.2, enforced below), so today this can only
2362
+ // re-confirm what the line above settled; it is here because `result` is the one door every
2363
+ // return passes through, and a candidate that stopped sharing that leaf would still be bound.
2364
+ function result(cand) {
2365
+ _assertCertBinding(cand.certificate, binding);
2366
+ return { certificate: cand.certificate, chain: cand.chain, certificates: cand.certificates, alternates: alternates,
2367
+ boundToKey: binding.spki !== undefined, boundToIdentifiers: binding.ids !== undefined };
2368
+ }
2132
2369
  if (!select) return result(primary);
2133
2370
  // Selection: consider the PRIMARY first, then each alternate in header order, bounded by maxAlt
2134
2371
  // (CWE-770 fetch amplification). selectChain MAY be async -- await its result (Promise.resolve wraps a