@blamejs/pki 0.5.23 → 0.5.25
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 +41 -1
- package/MIGRATING.md +31 -0
- package/README.md +2 -2
- package/lib/acme.js +269 -37
- package/lib/cmp-build.js +35 -1
- package/lib/cmp-verify.js +3 -8
- package/lib/crmf-sign.js +304 -1
- package/lib/guard-all.js +7 -2
- package/lib/guard-async.js +3 -1
- package/lib/guard-bytes.js +4 -2
- package/lib/guard-compress.js +3 -1
- package/lib/guard-crypto.js +4 -1
- package/lib/guard-der.js +4 -1
- package/lib/guard-encoding.js +3 -1
- package/lib/guard-header.js +4 -1
- package/lib/guard-identifier.js +4 -2
- package/lib/guard-intrinsic.js +7 -2
- package/lib/guard-json.js +4 -1
- package/lib/guard-limits.js +4 -1
- package/lib/guard-list.js +6 -2
- package/lib/guard-name.js +17 -7
- package/lib/guard-parsed.js +5 -2
- package/lib/guard-range.js +5 -2
- package/lib/guard-secret.js +3 -1
- package/lib/guard-text.js +3 -1
- package/lib/guard-time.js +5 -2
- package/lib/pki-build.js +29 -0
- package/lib/schema-pkix.js +136 -84
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,47 @@ 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.
|
|
7
|
+
## v0.5.25 — 2026-08-21
|
|
8
|
+
|
|
9
|
+
A key that cannot sign can now prove possession, so an ML-KEM certificate request has a proof to carry instead of no option at all.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `pki.crmf.build` emits a `POPOPrivKey` proof of possession under `pop.type` of `keyEncipherment` or `keyAgreement`. `pop.method: 'subsequentMessage'` with `pop.subsequentMessage` of `encrCert` or `challengeResp` declares which follow-up exchange completes the proof (RFC 9810 sec. 5.2.8.3.2 and sec. 5.2.8.3.3); no key material leaves the requester and every key type can produce it. `pop.method: 'encryptedKey'` encloses the requester's private key for the certification authority in a CMS `EnvelopedData` whose content type is `id-ct-encKeyWithID`, taking `pop.privateKey`, `pop.recipients`, `pop.identifier`, and `pop.archive: true`. `pki.cmp.build` carries either in an `ir`, `cr`, or `kur` body.
|
|
14
|
+
- The requested version follows what the message carries: a CMP request whose proof of possession uses `encryptedKey` or `agreeMAC` announces cmp2021(3), which RFC 9810 sec. 5.2.8.3 requires. Before this a request carrying an `encryptedKey` proof went out announcing cmp2000(2), and this toolkit's own reader refused the message it had just built.
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- `spec.pop` refuses a field it does not recognize. Each rule below is one a caller turns off by naming it, so a misspelled key must not read as an omitted one: `archve: true` would have withheld the archival consent while appearing to give it.
|
|
19
|
+
|
|
20
|
+
### Security
|
|
21
|
+
|
|
22
|
+
- An `encryptedKey` proof must enclose the private half of `certTemplate.publicKey`. RFC 4211 sec. 4.2 defines the field as "the encrypted private key matching the public key for which the certificate is to be issued"; enclosing any other key proves possession of something the request never asked to have certified, while every structural check still passes. The public key is derived from the supplied private key through the toolkit's own key engine and compared before the message is built.
|
|
23
|
+
- An `encryptedKey` proof requires `pop.identifier`. The ASN.1 marks `EncKeyWithID.identifier` OPTIONAL and RFC 4211 sec. 4.2.1 then makes it mandatory whenever the purpose is proving possession, for a reason the section states: without it a decrypting agent holds a key it cannot attribute, so an intercepted key can be wrapped in someone else's request and recovered.
|
|
24
|
+
- The two alternatives RFC 4211 sec. 4.2 deprecates as it defines them, `thisMessage` and `dhMAC`, are refused with their successors named. `pki.schema.crmf.parse` still reads both, since a peer may send one.
|
|
25
|
+
- A `keyEncipherment` proof cannot carry a MAC alternative. RFC 4211 sec. 4.2 lists three methods for an encipherment key and introduces the MAC alternatives only in sec. 4.3, "for keyAgreement (only)". The parser already refused such a message; the builder no longer produces one.
|
|
26
|
+
|
|
27
|
+
### Notes
|
|
28
|
+
|
|
29
|
+
- The `agreeMAC` proof is not built. It requires the RFC 2875 static Diffie-Hellman shared secret between the requester's key and a certification authority certificate the requester already holds, a classical key-agreement primitive this toolkit does not otherwise carry. `pki.crmf.verifyPop` continues to report an inbound `agreeMAC` as unverified, naming the arm. Use `subsequentMessage`, which any key type can produce.
|
|
30
|
+
|
|
31
|
+
## v0.5.24 — 2026-08-21
|
|
32
|
+
|
|
33
|
+
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.
|
|
34
|
+
|
|
35
|
+
### Changed
|
|
36
|
+
|
|
37
|
+
- `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.
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
|
|
41
|
+
- `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`.
|
|
42
|
+
- 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.
|
|
43
|
+
- 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.
|
|
44
|
+
- 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.
|
|
45
|
+
- 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.
|
|
46
|
+
|
|
47
|
+
## v0.5.23 — 2026-08-20
|
|
8
48
|
|
|
9
49
|
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.
|
|
10
50
|
|
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` |
|
|
@@ -232,7 +232,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
232
232
|
| `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key), subject alternative names, and certificate policies from the spec, taking any other extension as pre-encoded DER. It derives the version from the field set and enforces the serial bounds, the UTCTime/GeneralizedTime cutover, the DER default omissions, and the CA cross-field rules; a violation throws a typed `CertificateError`. Returns DER, or a PEM `CERTIFICATE` with `opts.pem`. Every arm is independently verified by OpenSSL. Parsing stays at `pki.schema.x509.parse` — `sign` |
|
|
233
233
|
| `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
|
|
234
234
|
| `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
|
|
235
|
-
| `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
|
|
235
|
+
| `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named, and `agreeMAC` is not built, since it needs the RFC 2875 static Diffie-Hellman secret against a CA certificate the requester already holds. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
|
|
236
236
|
| `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, and responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`. Protection is exactly one of `opts.{ key, cert }`, a signature under the sender key with the algorithm resolved from the signer certificate so RSA (PKCS#1 v1.5 / PSS), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, or `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived). Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `session` |
|
|
237
237
|
| `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the issuer key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
|
|
238
238
|
| `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
|
package/lib/acme.js
CHANGED
|
@@ -54,6 +54,30 @@ var intrinsic = require("./guard-intrinsic");
|
|
|
54
54
|
// replaceable properties to answer one thing, and either answering wrongly changes whether a field
|
|
55
55
|
// counts as present in a document this client is deciding how to act on.
|
|
56
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);
|
|
57
81
|
var pkgVersion = require("../package.json").version;
|
|
58
82
|
|
|
59
83
|
var AcmeError = frameworkError.AcmeError;
|
|
@@ -299,31 +323,33 @@ function _canonicalizeIpv6(value) {
|
|
|
299
323
|
var groups;
|
|
300
324
|
if (value.indexOf("::") !== -1) {
|
|
301
325
|
if (value.indexOf("::") !== value.lastIndexOf("::")) return null; // only one ::
|
|
302
|
-
var halves = value
|
|
303
|
-
var left = halves[0] ? halves[0]
|
|
304
|
-
var right = halves[1] ? halves[1]
|
|
326
|
+
var halves = _split(value, "::");
|
|
327
|
+
var left = halves[0] ? _split(halves[0], ":") : [];
|
|
328
|
+
var right = halves[1] ? _split(halves[1], ":") : [];
|
|
305
329
|
var fill = 8 - left.length - right.length;
|
|
306
330
|
if (fill < 1) return null;
|
|
307
|
-
|
|
331
|
+
var zeros = [];
|
|
332
|
+
for (var z = 0; z < fill; z++) _push(zeros, "0");
|
|
333
|
+
groups = _concat(_concat(left, zeros), right);
|
|
308
334
|
} else {
|
|
309
|
-
groups = value
|
|
335
|
+
groups = _split(value, ":");
|
|
310
336
|
}
|
|
311
337
|
if (groups.length !== 8) return null;
|
|
312
338
|
var nums = [];
|
|
313
339
|
for (var i = 0; i < 8; i++) {
|
|
314
|
-
if (
|
|
315
|
-
nums
|
|
340
|
+
if (!_reTest(/^[0-9a-f]{1,4}$/, groups[i])) return null;
|
|
341
|
+
_push(nums, _parseIntI(groups[i], 16));
|
|
316
342
|
}
|
|
317
|
-
var hex = nums
|
|
343
|
+
var hex = _mapI(nums, function (n) { return _numToString(n, 16); });
|
|
318
344
|
// Longest run of zero groups (>= 2) -> "::"; leftmost on a tie.
|
|
319
345
|
var bestStart = -1, bestLen = 0, curStart = -1, curLen = 0;
|
|
320
346
|
for (var g = 0; g < 8; g++) {
|
|
321
347
|
if (nums[g] === 0) { if (curStart === -1) curStart = g; curLen++; if (curLen > bestLen) { bestLen = curLen; bestStart = curStart; } }
|
|
322
348
|
else { curStart = -1; curLen = 0; }
|
|
323
349
|
}
|
|
324
|
-
if (bestLen < 2) return hex
|
|
325
|
-
var head =
|
|
326
|
-
var tail =
|
|
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), ":");
|
|
327
353
|
return head + "::" + tail;
|
|
328
354
|
}
|
|
329
355
|
|
|
@@ -927,12 +953,17 @@ async function _jwkToSpki(jwk) {
|
|
|
927
953
|
|
|
928
954
|
// EVERY common name in the subject (a DN may carry more than one CN RDN) -- taking
|
|
929
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.
|
|
930
960
|
function _subjectCommonNames(subject) {
|
|
931
961
|
var names = [];
|
|
932
|
-
if (!subject || !
|
|
933
|
-
subject.rdns
|
|
934
|
-
|
|
935
|
-
|
|
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);
|
|
936
967
|
});
|
|
937
968
|
});
|
|
938
969
|
return names;
|
|
@@ -941,12 +972,12 @@ function _subjectCommonNames(subject) {
|
|
|
941
972
|
// An iPAddress SAN octet string (4 = IPv4, 16 = IPv6) to its RFC 8738 canonical
|
|
942
973
|
// text -- the same form an order ip identifier carries -- or null on a bad length.
|
|
943
974
|
function _ipBytesToText(buf) {
|
|
944
|
-
if (!
|
|
975
|
+
if (!_isBuffer(buf)) return null;
|
|
945
976
|
if (buf.length === 4) return buf[0] + "." + buf[1] + "." + buf[2] + "." + buf[3];
|
|
946
977
|
if (buf.length === 16) {
|
|
947
978
|
var groups = [];
|
|
948
|
-
for (var i = 0; i < 16; i += 2) groups
|
|
949
|
-
return _canonicalizeIpv6(groups
|
|
979
|
+
for (var i = 0; i < 16; i += 2) _push(groups, _numToString((buf[i] << 8) | buf[i + 1], 16));
|
|
980
|
+
return _canonicalizeIpv6(_join(groups, ":"));
|
|
950
981
|
}
|
|
951
982
|
return null;
|
|
952
983
|
}
|
|
@@ -955,44 +986,167 @@ function _ipBytesToText(buf) {
|
|
|
955
986
|
// SAN dNSName / iPAddress entries in the extensionRequest attribute, keyed
|
|
956
987
|
// "dns:<lower>" / "ip:<canonical>" for an order-insensitive compare.
|
|
957
988
|
function _csrIdentifierSet(parsedCsr) {
|
|
958
|
-
|
|
959
|
-
|
|
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);
|
|
960
992
|
// PKCS#10 permits duplicate attribute types, so aggregate EVERY extensionRequest
|
|
961
993
|
// attribute and EVERY subjectAltName within each -- taking only the first would let
|
|
962
994
|
// a second extensionRequest smuggle identifiers past the order-set comparison.
|
|
963
|
-
(parsedCsr.attributes || []
|
|
964
|
-
if (a.type !== oid.byName("extensionRequest") || !
|
|
965
|
-
a.extensions
|
|
995
|
+
_forEach(parsedCsr.attributes || [], function (a) {
|
|
996
|
+
if (a.type !== oid.byName("extensionRequest") || !_isArrayI(a.extensions)) return;
|
|
997
|
+
_forEach(a.extensions, function (e) {
|
|
966
998
|
if (e.oid !== OID_SAN) return;
|
|
967
999
|
var dec = _extDecoders.byOid[OID_SAN](e.value, _extCtx);
|
|
968
|
-
(dec.names || []
|
|
969
|
-
if (n.tagNumber === 2) set["dns:" + String(n.value).toLowerCase()] = true;
|
|
970
|
-
else if (n.tagNumber === 7) { var t = _ipBytesToText(n.value); if (t) set["ip:" + t] = true; }
|
|
971
|
-
});
|
|
1000
|
+
_forEach(dec.names || [], function (n) { _addSanName(set, n, "the finalize CSR"); });
|
|
972
1001
|
});
|
|
973
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"); });
|
|
974
1010
|
return set;
|
|
975
1011
|
}
|
|
976
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.
|
|
977
1099
|
function _orderIdentifierSet(identifiers) {
|
|
978
|
-
var set =
|
|
979
|
-
identifiers
|
|
980
|
-
if (id.type === "dns") set["dns:" + id.value
|
|
1100
|
+
var set = intrinsic.create(null);
|
|
1101
|
+
_forEach(identifiers, function (id) {
|
|
1102
|
+
if (id.type === "dns") set["dns:" + _asciiLower(id.value)] = true;
|
|
981
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"); });
|
|
982
1133
|
});
|
|
1134
|
+
if (_objectKeys(set).length === 0) {
|
|
1135
|
+
_forEach(_subjectCommonNames(parsedCert.subject), function (cn) { _addCommonName(set, cn, "the downloaded certificate"); });
|
|
1136
|
+
}
|
|
983
1137
|
return set;
|
|
984
1138
|
}
|
|
985
1139
|
|
|
986
1140
|
function _assertCsrIdentifiers(parsedCsr, identifiers) {
|
|
987
1141
|
var have = _csrIdentifierSet(parsedCsr);
|
|
988
1142
|
var want = _orderIdentifierSet(identifiers);
|
|
989
|
-
var haveKeys =
|
|
1143
|
+
var haveKeys = _objectKeys(have), wantKeys = _objectKeys(want);
|
|
990
1144
|
var mismatch = haveKeys.length !== wantKeys.length ||
|
|
991
|
-
wantKeys
|
|
992
|
-
haveKeys
|
|
1145
|
+
_someI(wantKeys, function (k) { return !have[k]; }) ||
|
|
1146
|
+
_someI(haveKeys, function (k) { return !want[k]; });
|
|
993
1147
|
if (mismatch) {
|
|
994
|
-
throw E("acme/csr-identifier-mismatch", "the finalize CSR identifier set " +
|
|
995
|
-
" does not equal the order identifiers " +
|
|
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)");
|
|
996
1150
|
}
|
|
997
1151
|
}
|
|
998
1152
|
|
|
@@ -1786,7 +1940,7 @@ function _parseLinkAlternates(headers, base) {
|
|
|
1786
1940
|
* - `timeout` / `maxResponseBytes` / `maxRedirects` -- transport budgets; `maxNonceRetries` -- badNonce retry cap (default 1).
|
|
1787
1941
|
* - `maxPolls` / `maxTotalWait` / `sleep` -- poll-loop budgets + an injectable sleeper; `clock` -- an injectable receipt clock (default Date.now) for a Retry-After HTTP-date.
|
|
1788
1942
|
* - `newAuthz(identifier)` -- pre-authorize a single identifier (RFC 8555 sec. 7.4.1) -> { authorization, url }.
|
|
1789
|
-
* - `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).
|
|
1790
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.
|
|
1791
1945
|
* @example
|
|
1792
1946
|
* var acme = pki.acme.client("https://acme.example/directory", { accountKey, accountJwk, alg: "ES256", transport });
|
|
@@ -2117,6 +2271,71 @@ function client(directoryUrl, opts) {
|
|
|
2117
2271
|
}
|
|
2118
2272
|
function _fetchCertChain(url) { return _post(url, postAsGet, null, "kid", "application/pem-certificate-chain").then(_readCertChain); }
|
|
2119
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
|
+
|
|
2120
2339
|
function _downloadCertificate(url, opts) {
|
|
2121
2340
|
opts = opts || {};
|
|
2122
2341
|
// Prelude in a resolved-promise .then so a bad opt / URL is a REJECTION, uniform for a .catch caller.
|
|
@@ -2124,6 +2343,7 @@ function client(directoryUrl, opts) {
|
|
|
2124
2343
|
var select = opts.selectChain;
|
|
2125
2344
|
if (select !== undefined && typeof select !== "function") throw E("acme/bad-input", "downloadCertificate opts.selectChain must be a function");
|
|
2126
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);
|
|
2127
2347
|
var dlUrl = _clientUrl(url);
|
|
2128
2348
|
return _post(dlUrl, postAsGet, null, "kid", "application/pem-certificate-chain").then(function (res) {
|
|
2129
2349
|
var primary = _readCertChain(res);
|
|
@@ -2133,7 +2353,19 @@ function client(directoryUrl, opts) {
|
|
|
2133
2353
|
var alternates = [], linkError = null;
|
|
2134
2354
|
try { alternates = _parseLinkAlternates(res.headers, dlUrl); }
|
|
2135
2355
|
catch (e) { linkError = e; }
|
|
2136
|
-
|
|
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
|
+
}
|
|
2137
2369
|
if (!select) return result(primary);
|
|
2138
2370
|
// Selection: consider the PRIMARY first, then each alternate in header order, bounded by maxAlt
|
|
2139
2371
|
// (CWE-770 fetch amplification). selectChain MAY be async -- await its result (Promise.resolve wraps a
|