@blamejs/pki 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,28 @@ All notable changes to `@blamejs/pki` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## v0.6.5 — 2026-08-31
8
+
9
+ pki.cmp.build assembles a CMP key-recovery request (krr) body: a CertReqMessages under PKIBody tag [9], the key-recovery counterpart of an initialization request (RFC 9810 sec. 5.3.7).
10
+
11
+ ### Added
12
+
13
+ - pki.cmp.build accepts a { krr } body arm (RFC 9810 sec. 5.3.7): a key-recovery request, a CertReqMessages built through pki.crmf.build under PKIBody tag [9], identical in syntax to an initialization request. The proof-of-possession key is a key field on the arm spec, and any proof-of-possession arm the CRMF builder produces is permitted, including a private-key-transport encryptedKey proof.
14
+
15
+ ## v0.6.4 — 2026-08-30
16
+
17
+ The ACME client gains account update and order listing: pki.acme.client updates an account's contacts (RFC 8555 sec. 7.3.2) and fetches the account's orders list, following the paginated Link: rel="next" chain (sec. 7.1.2.1).
18
+
19
+ ### Added
20
+
21
+ - pki.acme.client(...).updateAccount(opts) updates an ACME account (RFC 8555 sec. 7.3.2): a kid-signed POST to the account URL that sets opts.contact (RFC 6068 mailto hygiene applies; an empty array clears all contacts) and returns the resulting account object. The fields the server MUST ignore are refused at the door with a typed acme/bad-input naming the correct path: status (use deactivateAccount, sec. 7.3.6 is the only client-settable status), termsOfServiceAgreed (not client-updatable; a changed-terms CA answers a request with a userActionRequired problem, surfaced as acme/server-problem, rather than a client re-agreement), orders (server-assigned), and externalAccountBinding (not client-updatable). An unrecognized option is refused rather than sent.
22
+ - pki.acme.client(...).listOrders(ordersUrl, opts?) fetches an account's orders list (RFC 8555 sec. 7.1.2.1) via POST-as-GET and returns { orders, pages, truncated }: orders is the aggregated array of order URLs, pages is how many pages were read, and truncated is true when the list was cut short by the page cap. It follows the sec. 7.1.2.1 Link: rel="next" pagination, bounded by opts.maxPages (default 50) and a visited-page dedupe so a looping or over-long next chain stops rather than fetching without end. Because the next header is delivered over TLS but not signed, and it steers an account-key-signed POST-as-GET, each next is https-gated and confined to the orders URL's own origin; an off-origin or non-https next is refused with acme/bad-link, and two distinct next targets (a singleton relation, RFC 8288 sec. 3.3) are ambiguous and refused.
23
+ - pki.acme.updateAccount(opts) is a new message-layer builder (a top-level export alongside pki.acme.deactivate): it builds the kid-signed account-update JWS the client composes, so the message layer is usable without the stateful client.
24
+
25
+ ### Changed
26
+
27
+ - The RFC 8288 Link response-header parser is now relation-parameterized: the sec. 7.4.2 alternate certificate-chain reader and the sec. 7.1.2.1 next orders-page reader share one hardened scan (byte cap, control-octet reject, relation-type well-formedness, anchor-context check, resolve, https gate, origin gate, and dedupe), so the same untrusted-header defenses cover both relations. Behavior for the alternate relation is unchanged.
28
+
7
29
  ## v0.6.3 — 2026-08-30
8
30
 
9
31
  pki.cms builds and reads certs-only certificate-management messages: a degenerate CMS SignedData that conveys certificates and CRLs without signing anything (RFC 8551 sec. 3.8).
package/README.md CHANGED
@@ -225,7 +225,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
225
225
  | `pki.scep` | SCEP pkiMessage codec (RFC 8894), the client side of Simple Certificate Enrollment. `build(spec)` assembles a `PKCSReq` or `RenewalReq` request: it verifies the PKCS#10 certification request's own proof-of-possession, encrypts it to the CA as the inner EnvelopedData (`pkcsPKIEnvelope`, AES-128-CBC), and signs that under the transaction attributes RFC 8894 §3.2 defines, a messageType, a caller-unique transactionId, and a 16-byte senderNonce. The recipient CA certificate must assert `keyEncipherment`. `parse(bytes, opts?)` reads a `PKCSReq`, `RenewalReq`, or `CertRep` back (the `CertPoll`, `GetCert`, and `GetCRL` client queries are refused): it verifies the outer signature first and refuses a message whose signature does not check, so the transaction attributes it returns come only from a verified signer, never alongside a false verdict. Because a valid signature only proves self-consistency with the embedded certificate, pass `opts.signerCert` to authenticate a CA response against the CA certificate you hold (a public-key mismatch is refused, `signerAuthenticated` reports the result); a caller that omits it gets a crypto-only verdict and must authenticate the surfaced `signerCert` itself. It maps the messageType, pkiStatus, failInfo, and the nonces from their RFC 8894 enumerants and refuses an unknown one; given `recipientKey` it decrypts the `pkcsPKIEnvelope` to the messageData, and given `expectedSenderNonce` it refuses a response whose recipientNonce does not echo it. It reads a CA's CertRep in full. Issuing a CertRep is not yet built — `build`, `parse` |
226
226
  | `pki.transport` | The shared, fail-closed `node:https` transport the enrollment clients drive. `pki.transport.https(defaults)` returns a `transport(request) → { status, headers, body, tls }`, where `tls` carries the negotiated `protocol`, `cipher`, and raw `peerCertificate`. This is the toolkit's only socket choke point: an explicit trust anchor (or an opt-in to the system store) is required, `rejectUnauthorized` is always on, TLS is floored at 1.2, the response body is capped while it streams, and a stalled socket times out. The EST, ACME, and CMP clients reuse it verbatim. If you inject your own transport, return `tls` too: `pki.est.serverkeygen` asserts the negotiated cipher can protect the delivered private key, and a transport that reports no cipher is trusted rather than refused, so omitting the field silently skips that check — `https` |
227
227
  | `pki.jose` | Flattened JWS (RFC 7515) and JWK thumbprints (RFC 7638). `sign` and `verify` run a Flattened JWS against declarative profiles (ACME outer, EAB inner, keyChange inner) that carry the required and forbidden header rules as data. `base64url` is the strict RFC 4648 §5 codec, rejecting padding, non-alphabet characters, and non-canonical trailing bits. `parseJson` is a bounded reader that refuses duplicate members at any depth. `thumbprint` is the RFC 7638 / 8037 / 9964 canonical digest. The algorithm registry binds each `alg` to its key type (ES/RS/PS/EdDSA/ML-DSA), leaving no code path for `alg:none`, an RS256→HS256 key confusion, or an all-zero ECDSA signature; `assertPublicJwk` refuses a JWK carrying private material, so an exported private key is never published. `opts.key` names the key a message must be signed under and governs: where the profile also permits an embedded header `jwk`, the two must be the same key — compared as RFC 7638 thumbprints, so member order cannot make equal keys differ — and a disagreement is refused rather than resolved in the message's favor. `keySource` reports which key answered, since a signature checked against a key you named is a different claim from one checked against the key the message carried — `sign`, `verify`, `base64url`, `parseJson`, `thumbprint`, `assertPublicJwk` |
228
- | `pki.acme` | ACME (RFC 8555 / 8737 / 8738 / 9773). `client(directoryUrl, opts)` is a stateful client driving a live CA directory over `pki.transport`: `newAccount`, `newOrder`, `newAuthz`, `getOrder`, `getAuthorization`, `getChallenge`, `respondToChallenge`, `finalize`, `pollOrder`, `pollAuthorization`, and `downloadCertificate` walk the issuance flow, with `newAuthz` pre-authorizing a single identifier (§7.4.1) and `downloadCertificate` binding the issued certificate to the order — its key, its identifiers, or both; at least one is required by default and the result reports `boundToKey` / `boundToIdentifiers` — before choosing among alternate chains (`Link rel="alternate"`, §7.4.2, via a `selectChain` predicate bounded by `maxAlternates`). `revokeCert` (account-key or certificate-key signed), `keyChange`, `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` |
228
+ | `pki.acme` | ACME (RFC 8555 / 8737 / 8738 / 9773). `client(directoryUrl, opts)` is a stateful client driving a live CA directory over `pki.transport`: `newAccount`, `newOrder`, `newAuthz`, `getOrder`, `getAuthorization`, `getChallenge`, `respondToChallenge`, `finalize`, `pollOrder`, `pollAuthorization`, and `downloadCertificate` walk the issuance flow, with `newAuthz` pre-authorizing a single identifier (§7.4.1) and `downloadCertificate` binding the issued certificate to the order — its key, its identifiers, or both; at least one is required by default and the result reports `boundToKey` / `boundToIdentifiers` — before choosing among alternate chains (`Link rel="alternate"`, §7.4.2, via a `selectChain` predicate bounded by `maxAlternates`). `revokeCert` (account-key or certificate-key signed), `keyChange`, `updateAccount` (change the account contacts, §7.3.2), `listOrders` (the account's orders list, following the §7.1.2.1 `Link rel="next"` pagination bounded by a page cap and confined to the orders origin), `deactivateAccount`, `deactivateAuthorization`, `renewalInfo` (ARI), and `renewalWindow` (the RFC 9773 §4.2/4.3 renewal decision) complete the lifecycle. Every URL is HTTPS only, an explicit trust anchor is required, each request carries a fresh single-use nonce with a bounded badNonce retry, reads are POST-as-GET, polling is bounded and sleeps on a Retry-After via an injectable sleeper capped by a poll count and a total-wait budget, and every response body is size-capped. The transport is injectable via `opts.transport`. Over the message layer it composes resource-object validators (closed status enums, conditional-required fields, unknown fields ignored), the three §7.1.6 state machines, the request builders (newAccount with External Account Binding, newOrder with `replaces`, finalize with a CSR identifier-set match and account-key-reuse rejection, challenge responses, deactivation, revokeCert in both key modes, the keyChange nested JWS, POST-as-GET), the http-01 / dns-01 / tls-alpn-01 challenge computations, the dns and ip identifier validators, and the ARI certID with serial sign-padding preserved — `client`, `validate`, `identify`, `assertTransition`, the builders, `keyAuthorization`, `http01`, `dns01`, `tlsAlpn01Extension`, `verifyTlsAlpn01`, `ariCertId` |
229
229
  | `pki.schema.smime` | S/MIME ESS signed-attribute values (RFC 5035 / RFC 8551). `parseSigningCertificate` and `parseSigningCertificateV2` bind a signature to its signing certificate (cert hash, hash algorithm, issuer `GeneralNames` and serial); `parseSmimeCapabilities` decodes the ordered capability list; `decodeAttribute` dispatches a CMS attribute by OID, enforcing the single-value rule and deferring on unknown types. A companion decoder for CMS signed attributes rather than an auto-routed format — `parseSigningCertificate`, `parseSigningCertificateV2`, `parseSmimeCapabilities`, `decodeAttribute` |
230
230
  | `pki.cmc` | Build and interpret CMC messages (RFC 5272). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and signs it through `pki.cms.sign` under `id-cct-PKIData`. A PKCS#10 (`tcr`) request is verified against its own proof-of-possession before signing, so a request whose self-signature does not verify under its subject public key is refused rather than signed into a message a CA would reject. Body-part identifiers are unique across the whole message and never the reserved 0; a caller's clash is refused rather than renumbered, since a control may already reference it. An Identity Proof V2 witness is computed over the `reqSequence` bytes exactly as emitted (§6.2.1 step 1) rather than a re-serialization, a POP Link Witness is emitted only alongside the POP Link Random control §6.3.1.1 requires beside it, and a renewal carries neither Identification nor Identity Proof in either version. `verify(response, sent)` takes what the CA returned plus the state the client retained and reduces it to one terminal outcome: `issued`, `pending`, `confirm-required`, `pop-required`, or `rejected`. It binds the exchange first — Transaction Identifier, the Sender and Recipient Nonce echo compared in constant time and by full value so a truncation cannot match, and the Data Return echo — with each check applying only if the client sent that half, and, once sent, an absent or differing echo being a refusal, which is the replay defense. `bodyPartIDs` extends the same rule to what the response is about: a status reporting on a body part the request never sent is refused, which the transaction and nonce cannot catch, because a server can echo both correctly while answering about a different message. Several status controls are permitted and the worst governs, so a failure cannot hide behind an earlier success; the absence of any status control is success, per §6.1.2. The carrier's signature must verify (§3.2.1.3.4): a conforming SignedData carries its own signer certificate, so the ordinary build-then-verify flow needs nothing extra and the verdict reports `signatureVerified: true`. Where the signer is found nowhere the posture is fail-closed with a named opt-out — supply `certs` with the responder's certificate, or `allowUnverified: true`, in which case the verdict reports `signatureVerified: false`. Doing neither is refused, the opt-out never excuses a signature that is present and wrong, and a carrier with no signer at all is refused outright. The response's own `cmsSequence` and `otherMsgs` come back raw, since a request whose only arm was the other-message form has no certificate to return and §4.1 puts its answer there. Nothing is trusted: issued certificates are read from the CMS certificate bag (§4.2) and surfaced raw for `pki.path.validate`, and a Publish Trust Anchors control is surfaced with `trusted: false` rather than added to a store — `build`, `verify` |
231
231
  | `pki.schema.cmc` | Decode CMC messages (RFC 5272 as updated by RFC 6402): a Full PKI Request (`PKIData`) or Full PKI Response (`PKIResponse`) riding inside a CMS SignedData, reached by the encapsulated content type (`id-cct-PKIData` / `id-cct-PKIResponse`). Controls are surfaced in wire order with their values raw, so an unrecognized one is data rather than a fault. Tagged requests decode across all three arms. The status verdicts (`CMCStatusInfo` v1 and `CMCStatusInfoV2`) are collected as an ordered list, and the RFC 6402 two-module `OtherStatusInfo` ambiguity — `pendInfo` and `extendedFailInfo` are both untagged SEQUENCEs in the 1988 module, told apart only by their first element — is resolved by inspection and refused when it cannot be told apart. Body-part identity is unique across the whole message rather than per sequence, 0 is reserved as the reference to the enclosing PKIData, and the `reqSequence` bytes are surfaced exactly as they appeared so an Identity Proof witness is computed over the wire bytes. A companion decoder for CMS content rather than an auto-routed format — `parse`, `parsePkiData`, `parsePkiResponse` |
@@ -235,7 +235,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
235
235
  | `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` |
236
236
  | `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` |
237
237
  | `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` |
238
- | `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`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). 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. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `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 same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. 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` |
238
+ | `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`, `krr` (key recovery, §5.3.7), `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). 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. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `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 same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. 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` |
239
239
  | `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` |
240
240
  | `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` |
241
241
  | `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
package/lib/acme.js CHANGED
@@ -330,6 +330,9 @@ var SPECS = {
330
330
  { name: "suggestedWindow", type: "object", required: true },
331
331
  { name: "explanationURL", type: "url" },
332
332
  ],
333
+ ordersList: [
334
+ { name: "orders", type: "array", required: true, elemType: "url" }, // RFC 8555 sec. 7.1.2.1 -- an array of order URLs
335
+ ],
333
336
  };
334
337
 
335
338
  function _checkType(kind, field, value, obj) {
@@ -895,7 +898,13 @@ function postAsGet(o) {
895
898
  // as opaque strings (the server decides support via unsupportedContact).
896
899
  function _assertContacts(contacts) {
897
900
  if (!Array.isArray(contacts)) throw E("acme/bad-contact", "contact must be an array of URL strings");
898
- contacts.forEach(function (c) {
901
+ // An own-index loop, NOT forEach: forEach SKIPS a hole in a sparse array (`new Array(1)`), so the hole
902
+ // would never be validated and JSON serialization would sign `{"contact":[null]}`. Every index is
903
+ // read through an own-property check, so a sparse hole -- or a nullish entry -- is a typed
904
+ // acme/bad-contact rather than a silently-signed null.
905
+ for (var i = 0; i < contacts.length; i++) {
906
+ if (!_hasOwn(contacts, i)) throw E("acme/bad-contact", "contact[" + i + "] is missing (a sparse array is not allowed)");
907
+ var c = contacts[i];
899
908
  if (!_isUriString(c)) throw E("acme/bad-contact", "each contact must be a URI string (RFC 8555 sec. 7.1.2)");
900
909
  // URI schemes are case-insensitive (RFC 3986), so detect mailto regardless of
901
910
  // case -- "MAILTO:a@b?..." must still hit the RFC 6068 header-field guards.
@@ -905,7 +914,7 @@ function _assertContacts(contacts) {
905
914
  if (addr.indexOf(",") !== -1) throw E("acme/bad-contact", "a mailto contact must be a single addr-spec, not a comma list (RFC 8555 sec. 7.3)");
906
915
  if (_countAtSigns(addr) !== 1) throw E("acme/bad-contact", "a mailto contact must be exactly one addr-spec");
907
916
  }
908
- });
917
+ }
909
918
  }
910
919
 
911
920
  /**
@@ -1315,7 +1324,11 @@ async function finalize(o) {
1315
1324
  }
1316
1325
  if (o.identifiers !== undefined) {
1317
1326
  if (!Array.isArray(o.identifiers) || o.identifiers.length === 0) throw E("acme/bad-input", "finalize identifiers must be the non-empty order identifier array");
1318
- o.identifiers.forEach(_validateOrderIdentifier); // caller-supplied -> validate before comparing (no raw TypeError)
1327
+ // An own-index loop, NOT forEach: forEach skips a hole in a sparse array, leaving it unvalidated.
1328
+ for (var ii = 0; ii < o.identifiers.length; ii++) {
1329
+ if (!_hasOwn(o.identifiers, ii)) throw E("acme/bad-input", "finalize identifiers[" + ii + "] is missing (a sparse array is not allowed)");
1330
+ _validateOrderIdentifier(o.identifiers[ii]); // caller-supplied -> validate before comparing (no raw TypeError)
1331
+ }
1319
1332
  _assertCsrIdentifiers(parsed, o.identifiers);
1320
1333
  }
1321
1334
  var payload = { csr: jose.base64url.encode(csrBuf) };
@@ -1378,6 +1391,35 @@ function deactivate(o) {
1378
1391
  });
1379
1392
  }
1380
1393
 
1394
+ /**
1395
+ * @primitive pki.acme.updateAccount
1396
+ * @signature pki.acme.updateAccount(opts) -> Promise<object>
1397
+ * @since 0.6.4
1398
+ * @status stable
1399
+ * @spec RFC 8555
1400
+ * @related pki.acme.client, pki.acme.newAccount, pki.acme.deactivate
1401
+ *
1402
+ * Build an account-update POST (RFC 8555 sec. 7.3.2): a kid-signed JWS whose payload carries the
1403
+ * account fields a client may set. `contact` is that field (RFC 6068 mailto hygiene applies; an empty
1404
+ * array clears all contacts). `opts` = `{ key, alg, nonce, url, kid, contact }`. The server ignores
1405
+ * updates to `status`, `termsOfServiceAgreed`, `orders`, and unrecognized fields (sec. 7.3.2), so the
1406
+ * `pki.acme.client` wrapper refuses those at the door rather than emit a silently-discarded payload.
1407
+ *
1408
+ * @example
1409
+ * var ec = await pki.key.generate({ name: "ECDSA", namedCurve: "P-256" });
1410
+ * var key = ec.privateKey;
1411
+ * var nonce = "oFvnlFP1wIhRlYS2jTaXbA";
1412
+ * var kid = "https://ca.example/acct/1";
1413
+ * await pki.acme.updateAccount({ key, alg: "ES256", nonce, url: kid, kid, contact: ["mailto:admin@example.org"] });
1414
+ */
1415
+ function updateAccount(o) {
1416
+ return _promised(function () {
1417
+ if (!_isObject(o)) throw E("acme/bad-input", "a request options object is required");
1418
+ _assertContacts(o.contact); // RFC 6068 mailto hygiene; an empty array clears all contacts
1419
+ return _signOuter({ key: o.key, alg: o.alg, nonce: o.nonce, url: o.url, kid: o.kid }, { contact: o.contact });
1420
+ });
1421
+ }
1422
+
1381
1423
  /**
1382
1424
  * @primitive pki.acme.revokeCert
1383
1425
  * @signature pki.acme.revokeCert(opts) -> Promise<object>
@@ -2040,11 +2082,11 @@ function _splitLinkParams(rest) {
2040
2082
  }
2041
2083
  // Does an RFC 8288 rel value (a space-separated relation-type list) contain "alternate" as a WHOLE token,
2042
2084
  // case-insensitively (RFC 8288 sec. 3.3)? Never a substring -- "alternateX" / "xalternate" do not match.
2043
- function _relHasAlternate(rel) {
2085
+ function _relHas(rel, relName) {
2044
2086
  // The rel value is a SPACE-separated relation-type list (RFC 8288 sec. 3.3) -- split on SP only, NOT a tab
2045
- // or other whitespace, so "alternate<TAB>index" is a single (non-matching) relation-type, not a false match.
2087
+ // or other whitespace, so "next<TAB>index" is a single (non-matching) relation-type, not a false match.
2046
2088
  var toks = String(rel).split(" ");
2047
- for (var i = 0; i < toks.length; i++) { if (toks[i].toLowerCase() === "alternate") return true; }
2089
+ for (var i = 0; i < toks.length; i++) { if (toks[i].toLowerCase() === relName) return true; }
2048
2090
  return false;
2049
2091
  }
2050
2092
  // Parse one link-value `"<" URI-Reference ">" *( ";" link-param )` -> { uri, rel } (rel "" if absent);
@@ -2084,20 +2126,28 @@ function _parseLinkValue(raw) {
2084
2126
  }
2085
2127
  return { uri: uri, rel: rel, anchor: anchor, relSeen: relSeen };
2086
2128
  }
2087
- // Parse an RFC 8288 Link response header for rel="alternate" certificate-chain targets (RFC 8555 sec.
2088
- // 7.4.2): read the (case-insensitive, node-lower-cased) `link` field -- a combined string OR an array --
2089
- // bound its length, split into link-values, keep the alternate-rel ones, resolve each against the download
2090
- // URL, https-gate, and dedupe by resolved URL. An UNTRUSTED header: every malformed shape or non-https /
2091
- // unresolvable target fails closed as acme/bad-link. Scoped to the alternate relation the download consumes.
2092
- function _parseLinkAlternates(headers, base) {
2129
+ // Parse an RFC 8288 Link response header for the targets of ONE relation type -- the sec. 7.4.2
2130
+ // `alternate` certificate chains and the sec. 7.1.2.1 `next` orders page share every byte-cap /
2131
+ // control-octet / rel-well-formedness / anchor-context / resolve / https-gate / origin-gate / dedupe
2132
+ // rule, and only the matched relation and the singleton rule vary. Read the (case-insensitive,
2133
+ // node-lower-cased) `link` field -- a combined string OR an array -- bound its length, split into
2134
+ // link-values, keep the `relName`-rel ones, resolve each against `base`, https-gate, origin-gate to
2135
+ // `base`'s origin, and dedupe by resolved URL. An UNTRUSTED header: every malformed shape or non-https /
2136
+ // off-origin / unresolvable target fails closed as acme/bad-link. opts.singleton (RFC 8288 sec. 3.3)
2137
+ // makes >1 DISTINCT target ambiguous -> acme/bad-link, for a singleton relation such as `next`.
2138
+ function _parseLinkRelation(headers, base, relName, opts) {
2139
+ opts = opts || {};
2093
2140
  var raw = null;
2094
2141
  for (var k in headers) { if (_hasOwn(headers, k) && k.toLowerCase() === "link") { raw = headers[k]; break; } }
2095
2142
  if (raw == null) return [];
2096
- var baseUrl = new URL(base), baseOrigin = baseUrl.origin, baseHref = baseUrl.href; // the download URL
2097
- var fields = Array.isArray(raw) ? raw : [raw], out = [], seen = Object.create(null), totalBytes = 0;
2098
- // Seed the dedup set with the PRIMARY download URL: a CA that advertises the certificate URL itself as a
2099
- // rel="alternate" (it is not an alternate of itself, RFC 8555 sec. 7.4.2) must not cause a redundant re-fetch.
2100
- seen[_dedupKey(baseHref)] = true;
2143
+ var baseUrl = new URL(base), baseOrigin = baseUrl.origin, baseHref = baseUrl.href; // the request URL
2144
+ var baseKey = _dedupKey(baseHref);
2145
+ var fields = Array.isArray(raw) ? raw : [raw], out = [], seen = Object.create(null), distinctCount = 0, totalBytes = 0;
2146
+ // The base URL is not a relation OF itself -- a certificate advertised as its own rel="alternate" (RFC 8555
2147
+ // sec. 7.4.2), or an orders page advertised as its own rel="next" -- so it is excluded from the followable
2148
+ // set below and never causes a redundant re-fetch. It is still COUNTED toward the singleton test, so a
2149
+ // self-link plus a distinct target is the two distinct targets RFC 8288 sec. 3.3 makes ambiguous, rather
2150
+ // than one target with the self-link silently dropped.
2101
2151
  for (var fi = 0; fi < fields.length; fi++) {
2102
2152
  var field = String(fields[fi]);
2103
2153
  // Cap the AGGREGATE across every Link field (CWE-770): an injected transport / duplicate-Link array can
@@ -2123,7 +2173,7 @@ function _parseLinkAlternates(headers, base) {
2123
2173
  // list malformed, even if another token is "alternate". (Empty tokens are internal 1*SP -- skip them.)
2124
2174
  var relToks = lv.rel === "" ? [] : lv.rel.split(" ");
2125
2175
  for (var ri = 0; ri < relToks.length; ri++) { if (relToks[ri] !== "" && !_validRelType(relToks[ri])) throw E("acme/bad-link", "a Link rel value contains a token that is not a valid relation-type (RFC 8288 sec. 3.3): " + JSON.stringify(lv.rel)); }
2126
- if (!_relHasAlternate(lv.rel)) continue;
2176
+ if (!_relHas(lv.rel, relName)) continue;
2127
2177
  // RFC 8288 sec. 3.2: an `anchor` overrides the link's CONTEXT. A certificate alternate's context is the
2128
2178
  // certificate itself (the download URL); a link anchored to another resource is an alternate of THAT
2129
2179
  // resource, not this certificate -- skip it. No anchor, or one resolving to the download URL, is ours.
@@ -2143,12 +2193,15 @@ function _parseLinkAlternates(headers, base) {
2143
2193
  var resolved;
2144
2194
  try { resolved = _resolveLocation(lv.uri, base); } // resolves a relative ref + enforces the https gate
2145
2195
  catch (e) {
2146
- // A non-https alternate is a security-relevant anomaly -> fail the whole header closed. A target that is a
2196
+ // A non-https target is a security-relevant anomaly -> fail the whole header closed. A target that is a
2147
2197
  // valid RFC 3986 reference but not a canonical ACME request URL (literal dot-segments, or a sub-delim
2148
2198
  // WHATWG would re-encode in a special-scheme query) cannot be signed AND requested byte-identically
2149
- // (RFC 8555 sec. 6.4), so it is merely UNUSABLE -> skip THIS alternate and keep the others (sec. 7.4.2
2150
- // permits several), rather than discarding every valid alternate over one non-canonical spelling.
2151
- if (e && e.code === "acme/insecure-url") throw E("acme/bad-link", "a rel=\"alternate\" Link target is not an https URL: " + JSON.stringify(lv.uri), e);
2199
+ // (RFC 8555 sec. 6.4), so it is UNUSABLE. For a MULTI-target relation (alternate) it is skipped and the
2200
+ // others are kept (sec. 7.4.2 permits several), rather than discarding every valid alternate over one
2201
+ // non-canonical spelling. For a SINGLETON relation (next) there is only the one target, so skipping it
2202
+ // would silently END pagination and omit orders -- an unusable singleton fails closed instead.
2203
+ if (e && e.code === "acme/insecure-url") throw E("acme/bad-link", "a rel=\"" + relName + "\" Link target is not an https URL: " + JSON.stringify(lv.uri), e);
2204
+ if (opts.singleton) throw E("acme/bad-link", "a rel=\"" + relName + "\" Link target is not a usable ACME request URL: " + _stringify(lv.uri), e);
2152
2205
  continue;
2153
2206
  }
2154
2207
  // Origin-gate: an alternate is fetched with the ACCOUNT-KEY-signed POST-as-GET, so an untrusted (TLS-
@@ -2157,18 +2210,28 @@ function _parseLinkAlternates(headers, base) {
2157
2210
  // directory" threat the cross-origin mTLS-credential strip already defends (RFC 8555 sec. 7.4.2
2158
2211
  // alternates are the CA's own chains, served alongside the certificate).
2159
2212
  var parsed = new URL(resolved);
2160
- if (parsed.origin !== baseOrigin) throw E("acme/bad-link", "a rel=\"alternate\" Link target is not on the certificate download's origin (SSRF guard): " + JSON.stringify(lv.uri));
2213
+ if (parsed.origin !== baseOrigin) throw E("acme/bad-link", "a rel=\"" + relName + "\" Link target is not on the request URL's origin (SSRF guard): " + JSON.stringify(lv.uri));
2161
2214
  // Dedup by the RFC 3986 sec. 6.2.2-normalized href (lowercased scheme+host, no default :443, no dot-segments,
2162
2215
  // unreserved pct-escapes decoded), so equivalent spellings ("acme.example" vs "ACME.EXAMPLE:443", "/alt" vs
2163
2216
  // "/%61lt") collapse to one fetch (CWE-770 amplification) -- while the VERBATIM resolved string is what is
2164
2217
  // fetched + signed (RFC 8555 sec. 6.4 exact-URL match).
2165
2218
  var key = _dedupKey(parsed.href);
2166
- if (!seen[key]) { seen[key] = true; out.push(resolved); }
2219
+ if (seen[key]) continue; // an equivalent spelling of this target already counted
2220
+ seen[key] = true;
2221
+ distinctCount += 1; // every distinct matched target, INCLUDING a self-link
2222
+ if (key !== baseKey) out.push(resolved); // the base is not followable, but it still counted above
2167
2223
  }
2168
2224
  }
2225
+ // RFC 8288 sec. 3.3: `next` is a singleton relation-type, so more than one DISTINCT target is ambiguous.
2226
+ // The deduped set already collapses equivalent spellings, so this fires only on genuinely different URLs.
2227
+ if (opts.singleton && distinctCount > 1) throw E("acme/bad-link", "the Link header names more than one distinct rel=\"" + relName + "\" target (RFC 8288 sec. 3.3, a singleton relation)");
2169
2228
  return out;
2170
2229
  }
2171
2230
 
2231
+ function _parseLinkAlternates(headers, base) { return _parseLinkRelation(headers, base, "alternate", {}); }
2232
+ // The single sec. 7.1.2.1 `next` orders-page target resolved against `base`, or null when the header names none.
2233
+ function _parseLinkNext(headers, base) { var m = _parseLinkRelation(headers, base, "next", { singleton: true }); return m.length ? m[0] : null; }
2234
+
2172
2235
  /**
2173
2236
  * @primitive pki.acme.client
2174
2237
  * @signature pki.acme.client(directoryUrl, opts) -> client
@@ -2224,6 +2287,8 @@ var _METHOD_OPTS = {
2224
2287
  revoke: { certAlg: 1, certJwk: 1, certKey: 1, certificate: 1, reason: 1 },
2225
2288
  keyChange: { newAlg: 1, newJwk: 1, newKey: 1 },
2226
2289
  renewalWindow: { random: 1, clock: 1, replaced: 1, previous: 1 },
2290
+ updateAccount: { contact: 1 },
2291
+ listOrders: { maxPages: 1 },
2227
2292
  };
2228
2293
  // Settle a per-method options bag the way the constructor settles its own: guard.identifier.optionsObject
2229
2294
  // snapshots the bag and refuses one a getter rewrites mid-read (a `requireBinding` getter that grows a
@@ -2713,6 +2778,58 @@ function client(directoryUrl, opts) {
2713
2778
  function _deactivateAccount() { return _promised(function () { return _post(_requireKid(), deactivate, null, "kid").then(function (res) { return validate("account", _json(res)); }); }); }
2714
2779
  function _deactivateAuthorization(url) { return _promised(function () { return _post(_clientUrl(url), deactivate, null, "kid").then(function (res) { return validate("authorization", _json(res)); }); }); }
2715
2780
 
2781
+ // updateAccount (RFC 8555 sec. 7.3.2): a kid-signed POST to the account URL updating the caller's
2782
+ // contact set. The options bag is snapshotted FIRST (a getter that grows a key after the check cannot
2783
+ // slip past), then the fields the server MUST ignore are refused with guidance -- a caller that sends
2784
+ // one has silently not done what they asked, so the client will not emit a payload the CA discards.
2785
+ function _updateAccount(o) {
2786
+ return _promised(function () {
2787
+ o = guard.identifier.optionsObject(o, E, "acme/bad-input", "pki.acme updateAccount options");
2788
+ if (o.status !== undefined) throw E("acme/bad-input", "updateAccount cannot change the account status; use deactivateAccount (RFC 8555 sec. 7.3.6 is the only client-settable status)");
2789
+ // RFC 8555 sec. 7.3.2 says the server MUST IGNORE a termsOfServiceAgreed update to the account, so
2790
+ // sending it is a silently-dropped no-op; this client refuses it at the door instead. termsOfServiceAgreed
2791
+ // is set at account creation (sec. 7.3.1 newAccount), and a CA whose terms have changed answers with a
2792
+ // 403 userActionRequired problem (sec. 7.3.3) that directs a HUMAN to the terms URL -- it is not re-agreed
2793
+ // through an account update.
2794
+ if (o.termsOfServiceAgreed !== undefined) throw E("acme/bad-input", "the server MUST ignore a termsOfServiceAgreed update to the account (RFC 8555 sec. 7.3.2); it is set at account creation, and a changed-terms CA answers with a userActionRequired problem (sec. 7.3.3) directing a human to the terms URL");
2795
+ if (o.orders !== undefined) throw E("acme/bad-input", "the account orders URL is server-assigned and cannot be updated (RFC 8555 sec. 7.3.2)");
2796
+ if (o.externalAccountBinding !== undefined) throw E("acme/bad-input", "externalAccountBinding is not updateable by the client (RFC 8555 sec. 7.1.2 / 7.3.4)");
2797
+ guard.identifier.assertKnownKeys(o, _METHOD_OPTS.updateAccount, E, "acme/bad-input", "unknown updateAccount option ");
2798
+ var account = _requireKid();
2799
+ return _post(account, updateAccount, { contact: o.contact }, "kid").then(function (res) { return validate("account", _json(res)); });
2800
+ });
2801
+ }
2802
+
2803
+ // listOrders (RFC 8555 sec. 7.1.2.1): a POST-as-GET to the account's orders URL, aggregating the
2804
+ // sec. 7.1.2.1 `Link: rel="next"` pages. The `next` header is untrusted (TLS-delivered, unsigned) and
2805
+ // steers the next account-key-signed POST-as-GET, so it is https-gated, confined to the request URL's
2806
+ // origin (SSRF), deduped against a visited-page loop, and bounded by maxPages (CWE-770 amplification).
2807
+ function _listOrders(ordersUrl, o) {
2808
+ return _promised(function () {
2809
+ o = _gateOpts(o, _METHOD_OPTS.listOrders, "listOrders");
2810
+ var maxPages = guard.limits.cap(o.maxPages, "maxPages", 50, { E: E, code: "acme/bad-input", min: 1 });
2811
+ var out = [], seen = intrinsic.create(null), pages = 0, truncated = false;
2812
+ function fetchPage(pageUrl) {
2813
+ seen[_dedupKey(pageUrl)] = true; // pageUrl is a canonical _clientUrl output, so the dedup key is consistent
2814
+ return _postAsGet(pageUrl).then(function (res) {
2815
+ pages += 1;
2816
+ var body = validate("ordersList", _json(res));
2817
+ for (var i = 0; i < body.orders.length; i++) _push(out, body.orders[i]);
2818
+ var next = _parseLinkNext(res.headers, pageUrl); // resolved against this page, https + origin-gated, singleton
2819
+ if (next == null) return;
2820
+ var nextUrl = _clientUrl(next); // re-affirm the https gate on the followed target
2821
+ // The loop guard runs BEFORE the cap decision: a next to an already-visited page names nothing new,
2822
+ // so the list is COMPLETE (not truncated). Only a next to an unseen page that the cap forbids is a
2823
+ // truncation -- a cycle landing exactly on the cap must not be reported as one.
2824
+ if (seen[_dedupKey(nextUrl)]) return;
2825
+ if (pages >= maxPages) { truncated = true; return; }
2826
+ return fetchPage(nextUrl);
2827
+ });
2828
+ }
2829
+ return fetchPage(_clientUrl(ordersUrl)).then(function () { return { orders: out, pages: pages, truncated: truncated }; });
2830
+ });
2831
+ }
2832
+
2716
2833
  function _keyChange(o) { return _promised(function () { return _keyChangeBody(o); }); }
2717
2834
  function _keyChangeBody(o) {
2718
2835
  o = _gateOpts(o, _METHOD_OPTS.keyChange, "keyChange");
@@ -2878,6 +2995,8 @@ function client(directoryUrl, opts) {
2878
2995
  revokeCert: _revokeCert,
2879
2996
  deactivateAccount: _deactivateAccount,
2880
2997
  deactivateAuthorization: _deactivateAuthorization,
2998
+ updateAccount: _updateAccount,
2999
+ listOrders: _listOrders,
2881
3000
  keyChange: _keyChange,
2882
3001
  renewalInfo: _renewalInfo,
2883
3002
  renewalWindow: _renewalWindow,
@@ -2905,6 +3024,7 @@ module.exports = {
2905
3024
  finalize: finalize,
2906
3025
  challengeResponse: challengeResponse,
2907
3026
  deactivate: deactivate,
3027
+ updateAccount: updateAccount,
2908
3028
  revokeCert: revokeCert,
2909
3029
  keyChange: keyChange,
2910
3030
  // ARI (RFC 9773)
package/lib/cmp-build.js CHANGED
@@ -92,17 +92,17 @@ var KNOWN_HEADER_KEYS = {
92
92
  transactionID: 1, senderNonce: 1, recipNonce: 1, freeText: 1, generalInfo: 1,
93
93
  };
94
94
  var KNOWN_BODY_KEYS = {
95
- ir: 1, cr: 1, kur: 1, p10cr: 1, certConf: 1, pollReq: 1, genm: 1, rr: 1, // request-side
95
+ ir: 1, cr: 1, kur: 1, krr: 1, p10cr: 1, certConf: 1, pollReq: 1, genm: 1, rr: 1, // request-side
96
96
  ip: 1, cp: 1, kup: 1, ccp: 1, krp: 1, rp: 1, genp: 1, error: 1, pollRep: 1, pkiconf: 1, // CA/responder-side
97
97
  nested: 1, // an RA wrapper of complete, independently-protected PKIMessages (RFC 9810 sec. 5.1.3.5)
98
98
  };
99
99
  // The PKIBody arm -> its EXPLICIT context tag number (schema-cmp.js BODY_ARMS). rr is [11], not [15].
100
100
  var BODY_TAG = {
101
- ir: 0, cr: 2, p10cr: 4, kur: 7, rr: 11, genm: 21, certConf: 24, pollReq: 25,
101
+ ir: 0, cr: 2, p10cr: 4, kur: 7, krr: 9, rr: 11, genm: 21, certConf: 24, pollReq: 25,
102
102
  ip: 1, cp: 3, kup: 8, krp: 10, rp: 12, ccp: 14, pkiconf: 19, genp: 22, error: 23, pollRep: 26,
103
103
  nested: 20, // NestedMessageContent (schema-cmp.js BODY_ARMS [20])
104
104
  };
105
- var CRMF_BODY = { ir: 1, cr: 1, kur: 1 }; // arms whose content is a CertReqMessages via pki.crmf.build
105
+ var CRMF_BODY = { ir: 1, cr: 1, kur: 1, krr: 1 }; // arms whose content is a CertReqMessages via pki.crmf.build (RFC 9810 sec. 5.3.7 krr)
106
106
  var CERT_REP_ARM = { ip: 1, cp: 1, kup: 1, ccp: 1 }; // arms carrying a CertRepMessage
107
107
  // Protection has two mutually exclusive forms, and the signature parameters are read only by the
108
108
  // signature one: under PBMAC1 a requested pss or digestAlgorithm selects nothing and the message
@@ -896,7 +896,8 @@ function _collectExtraCerts(opts, protCertDer) {
896
896
  * Build an RFC 9810 CMP `PKIMessage` -- the producing-side inverse of `pki.schema.cmp.parse`. `message` is
897
897
  * `{ header, body }`: `header` carries the `sender` / `recipient` GeneralNames plus optional transaction
898
898
  * metadata (`transactionID`, `senderNonce`, `messageTime`, `freeText`, `generalInfo`, ...); `body` is a
899
- * single-key object naming the arm. Request-side: `{ ir }` / `{ cr }` / `{ kur }` (a `CertReqMessages` spec
899
+ * single-key object naming the arm. Request-side: `{ ir }` / `{ cr }` / `{ kur }` / `{ krr }` (key recovery,
900
+ * RFC 9810 sec. 5.3.7; a `CertReqMessages` spec
900
901
  * delegated to `pki.crmf.build`; the proof-of-possession key is `key` on the arm spec), `{ p10cr }` (a PKCS#10
901
902
  * CertificationRequest DER), `{ certConf }`, `{ pollReq }`, `{ genm }`, `{ rr }`. CA/responder-side: `{ ip }` /
902
903
  * `{ cp }` / `{ kup }` / `{ ccp }` (a `CertRepMessage`: `caPubs` plus `response` of `CertResponse` each with a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.3",
3
+ "version": "0.6.5",
4
4
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:85d92993-2810-4099-a38f-0556df923c66",
5
+ "serialNumber": "urn:uuid:8cbb4140-2f2a-4d8e-abac-1df0dc0526bf",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-08-30T22:55:28.945Z",
8
+ "timestamp": "2026-08-31T03:30:39.294Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/pki@0.6.3",
22
+ "bom-ref": "@blamejs/pki@0.6.5",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.3",
25
+ "version": "0.6.5",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
29
- "purl": "pkg:npm/%40blamejs/pki@0.6.3",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.5",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/pki@0.6.3",
57
+ "ref": "@blamejs/pki@0.6.5",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]