@blamejs/pki 0.6.46 → 0.6.47
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 +15 -0
- package/README.md +1 -1
- package/lib/cmp-session.js +422 -16
- package/lib/cmp-verify.js +2 -1
- package/lib/constants.js +2 -0
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,21 @@ 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.47 — 2026-09-06
|
|
8
|
+
|
|
9
|
+
A CMP enrollment left waiting can be picked up by a later process instead of started again.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- A pki.cmp.session poll-timeout verdict carries resumeToken, and session.resumePoll(token) continues that transaction in a later process. The authority's polling interval is waited out before the first resumed request, while the resuming session's own maxTotalWait still bounds it: a remainder longer than that budget times out immediately and hands the same due time on. A further timeout returns another token, so a wait can span any number of processes, and the polls each one spent accumulate across them. Each timeout reports the waiting status, whether or not that process read a certificate response of its own, so a wait split across processes reads the same as one held in a single process. The authority's own statusString and failInfo are not reproduced from the token, so a verdict never presents text as the authority's that it did not send in that exchange. A session that has already run a transaction refuses to resume one, since RFC 9810 section 5.1.1 gives each transaction its own identifier.
|
|
14
|
+
- The token is plain JSON, so it survives being written to disk and read back. It names the transaction identifier the exchange is keyed by, the nonce the next request must echo (RFC 9810 section 5.1.1), which request is being polled as a decimal string so an identifier of any width survives, the response arm its grant arrives on, whether the request that opened the transaction asked for implicit confirmation, the polls already spent, the public key the granted certificate must certify, the signer identity the first process authenticated and, separately, the certificate it currently verifies a response with when that response omits its extraCerts, the certificates the authority had already sent including any it delivered only on a waiting leg, and the instant its own checkAfter allows the next poll. It carries no secret, because the protection material, the trust anchors and the endpoint come from the session the caller builds to resume with.
|
|
15
|
+
- A resumed poll grants nothing the first process would not have accepted. It protection-verifies and nonce-binds every response before reading it, holds every response to the signer identity the token names, refuses a granted certificate that certifies a different key, and confirms the grant with the same certConf handshake. Those fields are what the resumed session holds the exchange to, so a token is integrity-sensitive and belongs in storage the caller controls: someone who can rewrite it can widen what the resumed session accepts, up to the limit of that session's own trust anchors and the authority's protection, which a rewritten token cannot reach past. Store it where the enrollment's own state is stored, and read it back into a session configured the way the first one was. The token carries what the transaction established and the session supplies the rest, so the protection material, the trust anchors, the endpoint and a sender pinned with opts.expectedSender are all given again: a resumed poll accepts and refuses exactly what an uninterrupted one in the same session would, which means it also refuses a response that session has no way to authenticate.
|
|
16
|
+
- A token that cannot carry the transaction is refused with cmp/bad-input before any request is sent, so stored state that cannot be used never spends the nonce the token is the only copy of. That covers a value that is not an object, one that names no transaction, a non-hex transaction identifier or non-canonical base64 nonce, a transaction identifier that is not the 128 bits a first message opens one with or a nonce shorter than the 128 bits a response must carry (RFC 9483 section 3.1 and 3.5), both of which name state no exchange could have produced, a request identifier written in any spelling other than the decimal one a session writes, a response arm that is not an enrollment arm, an unknown field, a key that is not a SubjectPublicKeyInfo, a field that names a certificate and is not one, and more certificates than the list it restores can hold. The two fields that bind the transaction are required rather than optional, since a token lives in storage where it can be edited and dropping a field must not drop the check it feeds: the key the grant is held to, and, for a signature session, the identity every response is held to. A shared-secret session pins no certificate, and its secret is the binding instead. The token also names how the transaction authenticates, and a session that authenticates the other way is refused: a signature transaction is bound by the pinned signer identity and a shared-secret one by the secret, so neither resumes the other's. A token trimmed of that field is read from its own contents, never from the session reading it, since a signature transaction pins the signer it authenticated and a shared-secret one has none to pin. How the grant is confirmed comes from the token rather than from the resuming session's own opts.implicitConfirm, since it was negotiated in the request the token continues: a session that never set the option still confirms an implicitly confirmed grant without a certConf, and one that sets it cannot make a transaction whose request never asked for it accept an implicit-confirm indication. A token that omits the field resumes as though the request asked for nothing. A token that asked for it is refused by a session carrying opts.acceptCert, the same pairing the constructor refuses, since an implicitly confirmed grant leaves no certConf leg for a policy to reject on.
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- pki.cmp.session refuses an opts.maxResponseBytes that is not a whole number of bytes between 1 and the 24 MiB transport ceiling, at construction, with cmp/bad-input. It is the bound the response reads and the restored certificate pools are measured against, and pki.acme.client already held the option to the same range. A session that passed a fractional or out-of-range value previously carried it as far as the first read.
|
|
21
|
+
|
|
7
22
|
## v0.6.46 — 2026-09-06
|
|
8
23
|
|
|
9
24
|
A Sigstore bundle can be checked against the certificate-transparency logs that recorded the signing certificate.
|
package/README.md
CHANGED
|
@@ -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`, `krr` (key recovery, §5.3.7), `ccr` (cross-certification, §5.3.11: a `CertReqMessages` at the normative floor, where the requesting CA keeps its private key so a private-key-transport encryptedKey proof-of-possession is refused, and the optional App. D.6 single-request cardinality is not enforced), `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), `ccr` (cross-certification, §5.3.11: a `CertReqMessages` at the normative floor, where the requesting CA keeps its private key so a private-key-transport encryptedKey proof-of-possession is refused, and the optional App. D.6 single-request cardinality is not enforced), `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 }`. A certification authority can take longer to answer than a process is held open, so a `poll-timeout` carries a `resumeToken` and `resumePoll(token)` continues the same transaction in a later process: the token is plain JSON naming the transaction, the nonce the next request echoes, the polled request and the arm its grant arrives on, and the key the grant must certify. It carries no secret and grants nothing, since the protection material and the endpoint come from the session built to resume with, and the resumed poll verifies, nonce-binds, and key-binds every response. Its fields are what the resumed exchange is held to, so store it where the enrollment's own state is stored: someone who can rewrite it can widen what the resumed session accepts, as far as that session's trust anchors and the authority's protection allow and no further. 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/cmp-session.js
CHANGED
|
@@ -49,6 +49,12 @@ var OID_KEY_USAGE = oid.byName("keyUsage");
|
|
|
49
49
|
var HASH_OID_TO_DIGEST = Object.create(null);
|
|
50
50
|
[["sha256", "SHA-256"], ["sha384", "SHA-384"], ["sha512", "SHA-512"]].forEach(function (row) { var o = oid.byName(row[0]); if (o) HASH_OID_TO_DIGEST[o] = row[1]; });
|
|
51
51
|
var COMPOSITE_PH_HASHALG = Object.assign(Object.create(null), { "SHA-256": "sha256", "SHA-384": "sha384", "SHA-512": "sha512" });
|
|
52
|
+
var RESUMABLE_ARMS = Object.assign(Object.create(null), { ip: 1, cp: 1, kup: 1 });
|
|
53
|
+
var RESUME_TOKEN_KEYS = Object.assign(Object.create(null), {
|
|
54
|
+
transactionId: 1, recipNonce: 1, certReqId: 1, arm: 1, polls: 1, requestedSpki: 1,
|
|
55
|
+
signer: 1, signerCache: 1, chain: 1, caPubs: 1, nextPollAt: 1, implicitConfirm: 1, protection: 1,
|
|
56
|
+
});
|
|
57
|
+
var RESUMABLE_PROTECTION = Object.assign(Object.create(null), { signature: 1, mac: 1 });
|
|
52
58
|
|
|
53
59
|
var KNOWN_SESSION_OPTS = Object.assign(Object.create(null), {
|
|
54
60
|
url: 1, key: 1, cert: 1, mac: 1, trustAnchors: 1, intermediates: 1, recipient: 1, sender: 1,
|
|
@@ -98,6 +104,16 @@ Object.keys(constants.NAMES.CRL_REASON).forEach(function (v) { CRL_REASON_NAMES[
|
|
|
98
104
|
|
|
99
105
|
function _isGranted(code) { return code === 0 || code === 1; }
|
|
100
106
|
var PKI_STATUS_NAMES = Object.assign(Object.create(null), { 0: "accepted", 1: "grantedWithMods", 2: "rejection", 3: "waiting" });
|
|
107
|
+
var PKI_STATUS_WAITING = 3;
|
|
108
|
+
/** @internal The status a transaction a token can continue is in, by construction: a token exists only
|
|
109
|
+
* because a response said waiting, and a poll that times out is still waiting. A process that read no
|
|
110
|
+
* CertResponse of its own reports this, so a wait split across processes reads the same as one held in a
|
|
111
|
+
* single process. The authority's own diagnostic strings are not reproduced from stored state, since a
|
|
112
|
+
* verdict must not present text the authority did not sign in this exchange as though it had. */
|
|
113
|
+
function _waitingStatus() {
|
|
114
|
+
return { status: { code: PKI_STATUS_WAITING, name: PKI_STATUS_NAMES[PKI_STATUS_WAITING] },
|
|
115
|
+
statusString: null, failInfo: null };
|
|
116
|
+
}
|
|
101
117
|
|
|
102
118
|
function _certReqIdEq(a, b) { return a != null && b != null && BigInt(a) === BigInt(b); }
|
|
103
119
|
|
|
@@ -125,8 +141,12 @@ function _certIdentity(cert) {
|
|
|
125
141
|
|
|
126
142
|
function _spkiKeyIdentity(spkiDer) {
|
|
127
143
|
var node = asn1.decode(spkiDer);
|
|
144
|
+
_expectSeq(node, 2, 2);
|
|
128
145
|
var algId = node.children[0];
|
|
146
|
+
_expectSeq(algId, 1, 2);
|
|
129
147
|
var algOid = asn1.read.oid(algId.children[0]);
|
|
148
|
+
var key = guard.crypto.assertOctetAligned(asn1.read.bitString(node.children[1]), _err,
|
|
149
|
+
"cmp/bad-input", "a SubjectPublicKeyInfo subjectPublicKey");
|
|
130
150
|
var pn = algId.children[1];
|
|
131
151
|
var params;
|
|
132
152
|
if (algOid === OID_RSA_ENCRYPTION) {
|
|
@@ -134,10 +154,40 @@ function _spkiKeyIdentity(spkiDer) {
|
|
|
134
154
|
} else {
|
|
135
155
|
params = pn ? pn.bytes.toString("latin1") : "";
|
|
136
156
|
}
|
|
137
|
-
return algOid + "|" + params + "|" +
|
|
157
|
+
return algOid + "|" + params + "|" + key.bytes.toString("latin1");
|
|
158
|
+
}
|
|
159
|
+
/** @internal A SubjectPublicKeyInfo and the AlgorithmIdentifier inside it are SEQUENCEs of a known
|
|
160
|
+
* width. Reading a child without asking for the shape reads whatever sits in that position, which is
|
|
161
|
+
* how DER that is not a public key at all is fingerprinted as one. */
|
|
162
|
+
function _expectSeq(node, min, max) {
|
|
163
|
+
if (node.tagClass !== "universal" || node.tagNumber !== 16 || !node.children ||
|
|
164
|
+
node.children.length < min || node.children.length > max) {
|
|
165
|
+
throw _err("cmp/bad-input", "a SubjectPublicKeyInfo is a SEQUENCE of an AlgorithmIdentifier and a BIT STRING (RFC 5280 sec. 4.1.2.7)");
|
|
166
|
+
}
|
|
138
167
|
}
|
|
139
168
|
function _isDerNull(pn) { return pn.tagClass === "universal" && pn.tagNumber === 5 && pn.content.length === 0; }
|
|
140
169
|
|
|
170
|
+
var CERT_MAX_BYTES = constants.LIMITS.DER_MAX_BYTES;
|
|
171
|
+
/** @internal The spelling `String(BigInt)` produces, and only that one: an optional leading minus
|
|
172
|
+
* (0x2d), then ASCII digits (0x30 to 0x39), with a leading zero only when the value is zero itself, so
|
|
173
|
+
* `007` and `-0` are refused along with every non-digit. */
|
|
174
|
+
function _isCanonicalDecimal(s) {
|
|
175
|
+
var i = s.charCodeAt(0) === CH_MINUS ? 1 : 0;
|
|
176
|
+
if (i >= s.length) return false;
|
|
177
|
+
for (var j = i; j < s.length; j++) {
|
|
178
|
+
var c = s.charCodeAt(j);
|
|
179
|
+
if (c < CH_ZERO || c > CH_NINE) return false;
|
|
180
|
+
}
|
|
181
|
+
var leadingZero = s.charCodeAt(i) === CH_ZERO;
|
|
182
|
+
if (leadingZero && s.length - i > 1) return false;
|
|
183
|
+
return !(leadingZero && i === 1);
|
|
184
|
+
}
|
|
185
|
+
var CH_MINUS = 0x2d, CH_ZERO = 0x30, CH_NINE = 0x39;
|
|
186
|
+
/** @internal A ceiling on the decimal string, not on the identifier: converting one to a BigInt costs
|
|
187
|
+
* more than linear time, so the length is bounded before the conversion runs. It sits above the widest
|
|
188
|
+
* identifier the codec encodes (an INTEGER of the maximum width takes about 2.41 digits per byte), and
|
|
189
|
+
* the encoder itself is what the door then holds the converted value to. */
|
|
190
|
+
var CERTREQID_MAX_DIGITS = constants.LIMITS.DER_MAX_INTEGER_BYTES * 3;
|
|
141
191
|
var MAX_EXTRA_CERTS = 32, MAX_EXTRA_SCAN = 256;
|
|
142
192
|
var CAPUBS_MAX = 2 * MAX_EXTRA_CERTS;
|
|
143
193
|
var SESSION_MAX_INTERMEDIATES = constants.LIMITS.PATH_BUILD_MAX_CANDIDATES - CAPUBS_MAX - MAX_EXTRA_CERTS;
|
|
@@ -229,11 +279,42 @@ function _certConfHash(certDer) {
|
|
|
229
279
|
* confirms it (`certConf` -> `pkiConf`, unless an `implicitConfirm` was granted). A verified `rejection` /
|
|
230
280
|
* `error` or a poll-budget timeout is a terminal typed verdict the caller reads (`outcome`:
|
|
231
281
|
* `issued` / `rejected` / `poll-timeout`); a tampered / unverifiable / desynchronized response is a
|
|
232
|
-
* hard-stop `CmpError` throw.
|
|
282
|
+
* hard-stop `CmpError` throw.
|
|
283
|
+
*
|
|
284
|
+
* A certification authority can take longer to answer than a process is held open, so a `poll-timeout`
|
|
285
|
+
* carries a `resumeToken` and `session.resumePoll(token)` continues the same transaction in a later
|
|
286
|
+
* one. The token is plain JSON: the transaction identifier, the nonce the next request must echo, the
|
|
287
|
+
* polled request identifier (a decimal string, so an identifier of any width survives) and the arm its
|
|
288
|
+
* grant arrives on, whether the request that opened the transaction asked for implicit confirmation,
|
|
289
|
+
* how the transaction authenticates, the polls already spent, the key the grant must certify, the signer identity the
|
|
290
|
+
* first process authenticated and, separately, the certificate it currently verifies a response with
|
|
291
|
+
* when that response omits its extraCerts, the certificates the authority had already sent, and the
|
|
292
|
+
* instant its own `checkAfter` allows the next poll. It carries no secret, because the protection material and the
|
|
293
|
+
* endpoint come from the session built to resume with, and it grants nothing: the resumed poll verifies
|
|
294
|
+
* and nonce-binds every response, holds it to the signer identity the token names, and holds the grant to
|
|
295
|
+
* the key the token names. Those fields are what the exchange is held to, so the token is
|
|
296
|
+
* integrity-sensitive: someone who can rewrite it can widen what the resumed session accepts, as far as
|
|
297
|
+
* that session's trust anchors and the authority's protection allow and no further. Store it the way the
|
|
298
|
+
* enrollment's own state is stored, and resume it in a session configured the way the first one was: the
|
|
299
|
+
* token carries what the transaction established, and the protection material, the trust anchors, the
|
|
300
|
+
* endpoint and an `expectedSender` pin are given again, so a resumed poll accepts and refuses exactly
|
|
301
|
+
* what an uninterrupted one in the same session would. The authority's polling interval is waited out
|
|
302
|
+
* before the first resumed request, while this session's own `maxTotalWait` still bounds it: a
|
|
303
|
+
* remainder longer than the budget times out now and hands the same due time on. A further timeout
|
|
304
|
+
* hands back a token again, so a wait can span any number of processes, and each timeout reports the
|
|
305
|
+
* waiting status whether or not that process read a CertResponse of its own. The authority's own
|
|
306
|
+
* diagnostic strings are not reproduced from the token, so a verdict never presents text as the
|
|
307
|
+
* authority's that it did not send in that exchange. A token is refused before a
|
|
308
|
+
* request is sent when it is mis-shaped, when the key it names is not a `SubjectPublicKeyInfo`, when a
|
|
309
|
+
* field that names a certificate is not one, or when it carries more certificates than the list it
|
|
310
|
+
* restores is built under. The two fields that bind the transaction are required rather than
|
|
311
|
+
* optional, since a token lives in storage where it can be edited and dropping a field must not drop
|
|
312
|
+
* the check it feeds: the key the grant is held to, and, for a signature session, the identity every
|
|
313
|
+
* response is held to. A shared-secret session pins no certificate, and its secret is the binding. Exactly one protection flavor: `{ key, cert }` (signature) XOR `{ mac }`
|
|
233
314
|
* (PBMAC1). A crypto-valid response is not enough: the signer must chain to a supplied trust anchor
|
|
234
315
|
* (signature) or the shared secret must match (MAC); a valid-but-untrusted response is a hard stop, so the
|
|
235
316
|
* signature flavor REQUIRES `opts.trustAnchors` at construction. Returns a session with `enroll(request)`,
|
|
236
|
-
* `revoke(request)`, `info(request)`,
|
|
317
|
+
* `resumePoll(token)`, `revoke(request)`, `info(request)`,
|
|
237
318
|
* and read-only `transactionID` + `transcript` (each leg's request/response bytes, retained up to a
|
|
238
319
|
* transaction-wide cap; a later leg beyond the cap keeps its metadata + `byteLength` but drops the payload as
|
|
239
320
|
* `bytes: null, truncated: true`, so a padded-response flood across polls cannot exhaust memory). The granted certificate must be valid X.509, carry the key
|
|
@@ -361,11 +442,11 @@ function session(opts) {
|
|
|
361
442
|
var maxTotalWait = guard.limits.cap(opts.maxTotalWait, "opts.maxTotalWait", DEFAULT_MAX_TOTAL_WAIT, { E: _err, code: "cmp/bad-input", min: 0, max: retryAfter.MAX_RETRY_AFTER_SECONDS });
|
|
362
443
|
var sleep = opts.sleep || sleepUtil.sleep;
|
|
363
444
|
|
|
364
|
-
var transactionID = Buffer.from(webcrypto.webcrypto.getRandomValues(new Uint8Array(
|
|
445
|
+
var transactionID = Buffer.from(webcrypto.webcrypto.getRandomValues(new Uint8Array(constants.LIMITS.CMP_TRANSACTION_ID_BYTES)));
|
|
365
446
|
var lastPeerNonce = null;
|
|
366
447
|
var haveResponse = false;
|
|
367
448
|
var cachedSignerCert = null;
|
|
368
|
-
var pinnedSignerCert = null, signerPinned = false;
|
|
449
|
+
var pinnedSignerCert = null, pinnedSignerDer = null, signerPinned = false;
|
|
369
450
|
var cachedChain = [];
|
|
370
451
|
var caPubsAccum = [];
|
|
371
452
|
var caPubsSeen = Object.create(null);
|
|
@@ -377,12 +458,32 @@ function session(opts) {
|
|
|
377
458
|
var expectedInfoOp = null;
|
|
378
459
|
var crlQuery = null;
|
|
379
460
|
var requestedSpki = null;
|
|
461
|
+
/** @internal What the request asked for, not what this session was configured with. A resumed poll
|
|
462
|
+
* finishes a transaction whose confirmation was negotiated in a request an earlier process sent, so
|
|
463
|
+
* the grant is confirmed the way that request asked and not the way this session's options read. */
|
|
464
|
+
var requestedImplicitConfirm = opts.implicitConfirm === true;
|
|
380
465
|
var inFlight = false, completed = false, started = false;
|
|
381
466
|
var transcript = [];
|
|
382
467
|
var transcriptBytes = 0;
|
|
383
|
-
|
|
468
|
+
/** @internal The response size is a bound the token decode and the certificate pools are measured
|
|
469
|
+
* against, so it is checked here rather than at the first transfer: a value that is not a positive
|
|
470
|
+
* whole number of bytes is refused where it is supplied, not carried into whatever reads it first. */
|
|
471
|
+
var _perRespCap = opts.maxResponseBytes == null ? constants.LIMITS.HTTP_MAX_RESPONSE_BYTES
|
|
472
|
+
: guard.limits.cap(opts.maxResponseBytes, "opts.maxResponseBytes", constants.LIMITS.HTTP_MAX_RESPONSE_BYTES,
|
|
473
|
+
{ E: _err, code: "cmp/bad-input", min: 1, max: constants.LIMITS.HTTP_MAX_RESPONSE_BYTES });
|
|
384
474
|
var transcriptCap = _perRespCap * TRANSCRIPT_RETAIN_RESPONSES;
|
|
385
475
|
var caPubsByteBudget = _perRespCap * TRANSCRIPT_RETAIN_RESPONSES;
|
|
476
|
+
/** @internal What a restored token's certificates are held to, which is what the list it restores can
|
|
477
|
+
* hold. Every bound below is a module constant or the response size, which `guard.limits.cap` has
|
|
478
|
+
* already refused unless it is a positive whole number, so none can arrive unusable. The authority's
|
|
479
|
+
* own pool arrives in responses, so it keeps both the response size and the
|
|
480
|
+
* total the session accumulates under. The chain that validates the signer is also built from
|
|
481
|
+
* `opts.intermediates`, whose certificates never crossed the wire and are bounded only by the path
|
|
482
|
+
* length and the codec, so those two are its bounds and it carries no third one: a session holds a
|
|
483
|
+
* caller's intermediates at that same size already, and a total below the two would refuse a token
|
|
484
|
+
* the session itself issued. */
|
|
485
|
+
var CAPUBS_LIMIT = { count: CAPUBS_MAX, each: _perRespCap, total: caPubsByteBudget };
|
|
486
|
+
var CHAIN_LIMIT = { count: constants.LIMITS.PATH_MAX_CERTS, each: CERT_MAX_BYTES, total: null };
|
|
386
487
|
|
|
387
488
|
var NULL_DN = { directoryName: [] };
|
|
388
489
|
var defaultSender = NULL_DN;
|
|
@@ -443,7 +544,7 @@ function session(opts) {
|
|
|
443
544
|
|
|
444
545
|
async function _send(bodySpec, arm) {
|
|
445
546
|
var fresh = Buffer.from(webcrypto.webcrypto.getRandomValues(new Uint8Array(16)));
|
|
446
|
-
var header = Object.assign(_baseHeader(fresh), ENROLL_ARMS[arm] &&
|
|
547
|
+
var header = Object.assign(_baseHeader(fresh), ENROLL_ARMS[arm] && requestedImplicitConfirm ? { generalInfo: [{ infoType: "implicitConfirm" }] } : {});
|
|
447
548
|
var reqDer = await cmp.build({ header: header, body: bodySpec }, _buildOpts());
|
|
448
549
|
_recordTranscript({ direction: "out", arm: arm, bytes: reqDer });
|
|
449
550
|
var engaged = false;
|
|
@@ -476,7 +577,7 @@ function session(opts) {
|
|
|
476
577
|
if (_expectedSenderCert && !cmp.senderBoundToCert(verdict.header.sender, _expectedSenderCert)) {
|
|
477
578
|
throw _err("cmp/untrusted-signer", "the response signer does not match the expected CA identity (opts.expectedSender) -- refusing a response from a different trusted signer", null);
|
|
478
579
|
}
|
|
479
|
-
if (!signerPinned) { pinnedSignerCert = x509.parse(verdict.signer.cert); signerPinned = true; }
|
|
580
|
+
if (!signerPinned) { pinnedSignerCert = x509.parse(verdict.signer.cert); pinnedSignerDer = Buffer.from(verdict.signer.cert); signerPinned = true; }
|
|
480
581
|
else if (!cmp.senderBoundToCert(verdict.header.sender, pinnedSignerCert)) {
|
|
481
582
|
throw _err("cmp/untrusted-signer", "the response signer identity changed mid-transaction -- a different trusted signer, not a same-identity certificate rotation; the transaction is NOT advanced", null);
|
|
482
583
|
}
|
|
@@ -610,6 +711,60 @@ function session(opts) {
|
|
|
610
711
|
return c;
|
|
611
712
|
});
|
|
612
713
|
}
|
|
714
|
+
/** @internal What a later process needs to carry THIS transaction on: the identifier the exchange is
|
|
715
|
+
* keyed by, the nonce the next request must echo, which request is being polled and on which arm its
|
|
716
|
+
* grant will arrive, and the key the grant must certify (RFC 9810 sec. 5.1.1). Plain JSON values, since
|
|
717
|
+
* it crosses a process boundary. Everything else, the protection material and the endpoint, comes from
|
|
718
|
+
* the session the caller builds to resume with, so the token carries no secret. */
|
|
719
|
+
/** @internal The instant an outstanding checkAfter falls due, or null when the authority named none. */
|
|
720
|
+
function _pollDueAt(dueInSeconds) {
|
|
721
|
+
if (typeof dueInSeconds !== "number" || !isFinite(dueInSeconds) || dueInSeconds <= 0) return null;
|
|
722
|
+
return guard.time.instantOf(new Date()) + constants.TIME.seconds(dueInSeconds);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function _resumeToken(polls, nextPollAt) {
|
|
726
|
+
/** @internal Only an enrollment reaches here, and only after a response, so the nonce to echo is the
|
|
727
|
+
* one thing that could still be missing: a responder that omitted its senderNonce leaves the chain
|
|
728
|
+
* unable to continue, and a token that cannot be continued is not offered. */
|
|
729
|
+
if (!Buffer.isBuffer(lastPeerNonce) || lastPeerNonce.length === 0) return null;
|
|
730
|
+
/** @internal Two different certificates: the identity pinned on the FIRST response, which every
|
|
731
|
+
* later response is bound to, and the one currently used to verify when a response omits its
|
|
732
|
+
* extraCerts. A same-identity rotation moves the second and never the first, so collapsing them
|
|
733
|
+
* would let a restart accept an identity the uninterrupted transaction refuses. */
|
|
734
|
+
var pinDer = pinnedSignerDer;
|
|
735
|
+
return {
|
|
736
|
+
transactionId: transactionID.toString("hex"),
|
|
737
|
+
recipNonce: lastPeerNonce.toString("base64"),
|
|
738
|
+
/** @internal A request identifier is an INTEGER of any width, so it travels as a decimal string:
|
|
739
|
+
* a BigInt is not JSON, and a token that cannot be serialized is not a resumable one. */
|
|
740
|
+
certReqId: activeCertReqId.toString(),
|
|
741
|
+
arm: expectedRespArm,
|
|
742
|
+
polls: polls,
|
|
743
|
+
/** @internal Negotiated in the request this token continues, so it travels with the transaction:
|
|
744
|
+
* a later process confirms the grant the way that request asked, whatever its own options say. */
|
|
745
|
+
implicitConfirm: requestedImplicitConfirm,
|
|
746
|
+
/** @internal How the exchange authenticates. The signer identity below is only a binding under
|
|
747
|
+
* signature protection; under a shared secret the secret is the binding, so a session resuming
|
|
748
|
+
* this transaction has to authenticate it the way the transaction already does. */
|
|
749
|
+
protection: isSig ? "signature" : "mac",
|
|
750
|
+
requestedSpki: requestedSpki ? Buffer.from(requestedSpki).toString("base64") : null,
|
|
751
|
+
/** @internal The identity the first process pinned on the first response it verified. Restoring it
|
|
752
|
+
* is what keeps a restart from admitting a DIFFERENT trusted signer, which an uninterrupted
|
|
753
|
+
* transaction refuses (RFC 9483 sec. 3.1), and it carries the certificate a responder that sent
|
|
754
|
+
* its chain only once would not send again. */
|
|
755
|
+
signer: pinDer ? Buffer.from(pinDer).toString("base64") : null,
|
|
756
|
+
signerCache: cachedSignerCert != null ? Buffer.from(cachedSignerCert).toString("base64") : null,
|
|
757
|
+
chain: cachedChain.map(function (c) { return Buffer.from(c).toString("base64"); }),
|
|
758
|
+
/** @internal An authority may deliver the issued certificate's intermediate in a WAITING response
|
|
759
|
+
* and omit it from the grant, so the certificates accumulated before the timeout travel too, or
|
|
760
|
+
* the resumed grant would fail a validation the uninterrupted transaction passes. */
|
|
761
|
+
caPubs: caPubsAccum.map(function (c) { return Buffer.from(c).toString("base64"); }),
|
|
762
|
+
/** @internal The instant the authority's own checkAfter allows the next poll. Resuming earlier
|
|
763
|
+
* would poll faster than it asked to be polled. */
|
|
764
|
+
nextPollAt: nextPollAt != null ? nextPollAt : null,
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
|
|
613
768
|
function _terminal(outcome, extra) {
|
|
614
769
|
return guard.verdict.of({
|
|
615
770
|
outcome: outcome, certificate: null, chain: [], status: null, trusted: true,
|
|
@@ -618,8 +773,8 @@ function session(opts) {
|
|
|
618
773
|
}, extra);
|
|
619
774
|
}
|
|
620
775
|
|
|
621
|
-
async function _pollLoop(lastWaitingResp) {
|
|
622
|
-
var polls = 0, waited = 0, lastStatus = _statusOf(lastWaitingResp);
|
|
776
|
+
async function _pollLoop(lastWaitingResp, alreadyWaited) {
|
|
777
|
+
var polls = 0, waited = alreadyWaited || 0, lastStatus = _statusOf(lastWaitingResp);
|
|
623
778
|
for (;;) {
|
|
624
779
|
if (polls >= maxPolls || waited > maxTotalWait) return { timeout: true, polls: polls, status: lastStatus };
|
|
625
780
|
var verdict = await _send({ pollReq: [{ certReqId: activeCertReqId }] }, "pollReq");
|
|
@@ -632,8 +787,11 @@ function session(opts) {
|
|
|
632
787
|
if (!entry) return { done: { state: "unexpected", reason: "a pollRep carried no entry for certReqId " + activeCertReqId }, polls: polls, header: verdict.header };
|
|
633
788
|
var checkAfter = typeof entry.checkAfter === "number" ? entry.checkAfter : 0;
|
|
634
789
|
waited += checkAfter;
|
|
635
|
-
|
|
636
|
-
|
|
790
|
+
/** @internal The authority asked to be polled again after `checkAfter`, and the budget ran out
|
|
791
|
+
* before that wait was taken. Reporting it lets a resumed poll honor the interval rather than
|
|
792
|
+
* poll immediately in a new process. */
|
|
793
|
+
if (waited > maxTotalWait) return { timeout: true, polls: polls, status: lastStatus, dueIn: checkAfter };
|
|
794
|
+
if (polls >= maxPolls) return { timeout: true, polls: polls, status: lastStatus, dueIn: checkAfter };
|
|
637
795
|
await sleep(checkAfter * constants.TIME.seconds(1));
|
|
638
796
|
continue;
|
|
639
797
|
}
|
|
@@ -643,7 +801,7 @@ function session(opts) {
|
|
|
643
801
|
}
|
|
644
802
|
|
|
645
803
|
async function _confirm(certDer, header, info) {
|
|
646
|
-
if (
|
|
804
|
+
if (requestedImplicitConfirm && _implicitConfirmGranted(header)) return { confirmed: true, implicit: true };
|
|
647
805
|
var accept = true;
|
|
648
806
|
if (typeof opts.acceptCert === "function") accept = (await opts.acceptCert(Buffer.from(certDer), info)) === true;
|
|
649
807
|
var h = _certConfHash(certDer);
|
|
@@ -664,8 +822,13 @@ function session(opts) {
|
|
|
664
822
|
var parsed;
|
|
665
823
|
try { parsed = x509.parse(cert); }
|
|
666
824
|
catch (e) { throw _err("cmp/bad-cert-response", "the granted CertResponse's certificate is not a valid X.509 certificate", e); }
|
|
667
|
-
if (requestedSpki != null
|
|
668
|
-
|
|
825
|
+
if (requestedSpki != null) {
|
|
826
|
+
var granted, wanted;
|
|
827
|
+
try { granted = _spkiKeyIdentity(parsed.subjectPublicKeyInfo.bytes); wanted = _spkiKeyIdentity(requestedSpki); }
|
|
828
|
+
catch (e) { throw _err("cmp/bad-cert-response", "the issued certificate's public key cannot be compared with the requested key", e); }
|
|
829
|
+
if (granted !== wanted) {
|
|
830
|
+
throw _err("cmp/bad-cert-response", "the issued certificate's public key does not match the requested key -- a misrouted certificate the caller has no private key for");
|
|
831
|
+
}
|
|
669
832
|
}
|
|
670
833
|
return cert;
|
|
671
834
|
}
|
|
@@ -780,7 +943,7 @@ function session(opts) {
|
|
|
780
943
|
if (t.state === "waiting") {
|
|
781
944
|
var polled = await _pollLoop(t.resp);
|
|
782
945
|
pollCount = polled.polls;
|
|
783
|
-
if (polled.timeout) return _terminal("poll-timeout", { status: polled.status, polls: pollCount });
|
|
946
|
+
if (polled.timeout) return _terminal("poll-timeout", { status: polled.status, polls: pollCount, resumeToken: _resumeToken(pollCount, _pollDueAt(polled.dueIn)) });
|
|
784
947
|
t = polled.done;
|
|
785
948
|
grantHeader = polled.header;
|
|
786
949
|
t.polls = pollCount;
|
|
@@ -794,6 +957,248 @@ function session(opts) {
|
|
|
794
957
|
}
|
|
795
958
|
}
|
|
796
959
|
|
|
960
|
+
/** @internal The state a poll-timeout handed the caller, read back. It is the caller's own record of
|
|
961
|
+
* a transaction it started, so it says WHICH exchange to continue, never who may continue it: the
|
|
962
|
+
* protection material and the endpoint come from this session, every response is verified the way the
|
|
963
|
+
* first process verified them, and the grant is still bound to the key the token names. */
|
|
964
|
+
function _readResumeToken(token) {
|
|
965
|
+
if (token === null || typeof token !== "object" || Array.isArray(token)) {
|
|
966
|
+
throw _err("cmp/bad-input", "resumePoll expects the resumeToken a poll-timeout verdict carried");
|
|
967
|
+
}
|
|
968
|
+
guard.identifier.assertKnownKeys(token, RESUME_TOKEN_KEYS, _err, "cmp/bad-input", "the resumeToken has an unknown field ");
|
|
969
|
+
/** @internal Every field is taken once, here, and the checks below run on what was taken. A token is
|
|
970
|
+
* any object a caller hands in, so a field read a second time can answer differently than it did when
|
|
971
|
+
* it was checked, and the restored state would carry the second answer past the check. */
|
|
972
|
+
var raw = {
|
|
973
|
+
transactionId: token.transactionId, recipNonce: token.recipNonce, certReqId: token.certReqId,
|
|
974
|
+
arm: token.arm, polls: token.polls, requestedSpki: token.requestedSpki, signer: token.signer,
|
|
975
|
+
signerCache: token.signerCache, chain: token.chain, caPubs: token.caPubs,
|
|
976
|
+
nextPollAt: token.nextPollAt, implicitConfirm: token.implicitConfirm,
|
|
977
|
+
protection: token.protection,
|
|
978
|
+
};
|
|
979
|
+
var txn = _hexField(raw.transactionId, "transactionId");
|
|
980
|
+
/** @internal The width a first message opens a transaction with (RFC 9483 sec. 3.1), which is the
|
|
981
|
+
* width this session writes, so a token naming any other names a transaction it cannot have opened. */
|
|
982
|
+
if (txn.length !== constants.LIMITS.CMP_TRANSACTION_ID_BYTES) {
|
|
983
|
+
throw _err("cmp/bad-input", "the resumeToken transactionId must name the transaction to continue, as the " + constants.LIMITS.CMP_TRANSACTION_ID_BYTES + " bytes a first message opens one with (RFC 9483 sec. 3.1)");
|
|
984
|
+
}
|
|
985
|
+
var nonce = _b64Field(raw.recipNonce, "recipNonce");
|
|
986
|
+
/** @internal The same floor a received message is held to, so a nonce no response could have carried
|
|
987
|
+
* is refused here rather than echoed into a request that cannot continue the chain. */
|
|
988
|
+
if (nonce.length < constants.LIMITS.CMP_MIN_NONCE_BYTES) {
|
|
989
|
+
throw _err("cmp/bad-input", "the resumeToken recipNonce must carry the nonce the next request echoes, at least " + constants.LIMITS.CMP_MIN_NONCE_BYTES + " bytes of it (RFC 9483 sec. 3.5)");
|
|
990
|
+
}
|
|
991
|
+
/** @internal A decimal string, so an identifier of any width a request can carry survives the round
|
|
992
|
+
* trip, including the PKCS#10 sentinel (-1, which names the whole message rather than one request).
|
|
993
|
+
* The reader accepts every identifier an enrollment can put in a token: it names which response to
|
|
994
|
+
* match, and the grant is bound by the nonce, the protection, the signer and the key. */
|
|
995
|
+
var certReqId;
|
|
996
|
+
if (typeof raw.certReqId !== "string" || raw.certReqId.length === 0 || raw.certReqId.length > CERTREQID_MAX_DIGITS) {
|
|
997
|
+
throw _err("cmp/bad-input", "the resumeToken certReqId must be a decimal string identifying the polled request, of at most " + CERTREQID_MAX_DIGITS + " characters");
|
|
998
|
+
}
|
|
999
|
+
/** @internal `BigInt` also reads a hexadecimal, binary or octal literal, a leading plus and
|
|
1000
|
+
* surrounding whitespace, none of which a token carries: the identifier is written the way the
|
|
1001
|
+
* emitting session writes it, so anything else names a different request than it appears to. */
|
|
1002
|
+
if (!_isCanonicalDecimal(raw.certReqId)) {
|
|
1003
|
+
throw _err("cmp/bad-input", "the resumeToken certReqId must be written as the emitting session writes it, in decimal with no sign but a leading minus, no leading zero and no surrounding space");
|
|
1004
|
+
}
|
|
1005
|
+
try { certReqId = BigInt(raw.certReqId); }
|
|
1006
|
+
catch (_e) { throw _err("cmp/bad-input", "the resumeToken certReqId must be a decimal string identifying the polled request"); }
|
|
1007
|
+
/** @internal The identifier is encoded again on the next request, so the door asks the encoder what
|
|
1008
|
+
* it accepts rather than approximating it from a digit count: a width the encoder refuses would
|
|
1009
|
+
* otherwise pass here and fail after the restored state had already consumed the session. */
|
|
1010
|
+
try { asn1.build.integer(certReqId); }
|
|
1011
|
+
catch (e) { throw _err("cmp/bad-input", "the resumeToken certReqId is wider than a CertReqMsg request identifier can encode", e); }
|
|
1012
|
+
var arm = raw.arm;
|
|
1013
|
+
if (typeof arm !== "string" || RESUMABLE_ARMS[arm] !== 1) {
|
|
1014
|
+
throw _err("cmp/bad-input", "the resumeToken arm must be an enrollment response arm (ip, cp or kup), got " + guard.text.showValue(arm));
|
|
1015
|
+
}
|
|
1016
|
+
var polls = raw.polls;
|
|
1017
|
+
if (polls != null && (!Number.isInteger(polls) || polls < 0)) {
|
|
1018
|
+
throw _err("cmp/bad-input", "the resumeToken polls must be a non-negative integer count of the polls already spent");
|
|
1019
|
+
}
|
|
1020
|
+
/** @internal A token is state a caller stored, and storage is where it can be edited. Dropping a
|
|
1021
|
+
* field must not drop the check that field feeds, so the two that bind the transaction are required:
|
|
1022
|
+
* the key the grant is held to, and, for a signature session, the identity every response is held
|
|
1023
|
+
* to. A shared-secret session pins no certificate, and its secret is the binding instead. */
|
|
1024
|
+
if (raw.requestedSpki == null) {
|
|
1025
|
+
throw _err("cmp/bad-input", "the resumeToken requestedSpki must name the key the granted certificate certifies -- without it the grant would be bound to nothing");
|
|
1026
|
+
}
|
|
1027
|
+
var spki = _b64Field(raw.requestedSpki, "requestedSpki", CERT_MAX_BYTES);
|
|
1028
|
+
/** @internal Read at the door, not when the grant arrives: stored state that is not a public key
|
|
1029
|
+
* would otherwise advance the exchange with the authority before it was found to be unusable. */
|
|
1030
|
+
try { _spkiKeyIdentity(spki); }
|
|
1031
|
+
catch (e) { throw _err("cmp/bad-input", "the resumeToken requestedSpki is not a SubjectPublicKeyInfo", e); }
|
|
1032
|
+
var signer = null;
|
|
1033
|
+
if (raw.signer != null) signer = _certField(raw.signer, "signer", CERT_MAX_BYTES);
|
|
1034
|
+
else if (isSig) {
|
|
1035
|
+
throw _err("cmp/bad-input", "the resumeToken signer must name the identity the transaction authenticated -- without it a resumed response from a different trusted signer would be accepted (RFC 9483 sec. 3.1)");
|
|
1036
|
+
}
|
|
1037
|
+
var signerCache = null;
|
|
1038
|
+
if (raw.signerCache != null) signerCache = _certField(raw.signerCache, "signerCache", CERT_MAX_BYTES);
|
|
1039
|
+
var chain = _certListField(raw.chain, "chain", CHAIN_LIMIT);
|
|
1040
|
+
var caPubs = _certListField(raw.caPubs, "caPubs", CAPUBS_LIMIT);
|
|
1041
|
+
/** @internal How the transaction authenticates is fixed by the request that opened it, and the two
|
|
1042
|
+
* flavors bind a response differently: under signature protection the pinned signer identity is the
|
|
1043
|
+
* binding, and under a shared secret the secret is. A session that authenticates the other way would
|
|
1044
|
+
* carry the transaction on under a binding it never had, so it is refused rather than adapted to.
|
|
1045
|
+
* A token trimmed of the field is read from its own contents rather than from this session, since
|
|
1046
|
+
* taking it from the session would let either flavor answer for the other: a signature transaction
|
|
1047
|
+
* pins the signer it authenticated, and a shared-secret one has none to pin. */
|
|
1048
|
+
var protection = raw.protection == null ? (raw.signer != null ? "signature" : "mac") : raw.protection;
|
|
1049
|
+
if (typeof protection !== "string" || RESUMABLE_PROTECTION[protection] !== 1) {
|
|
1050
|
+
throw _err("cmp/bad-input", "the resumeToken protection must name how the transaction authenticates, either signature or mac, got " + guard.text.showValue(raw.protection));
|
|
1051
|
+
}
|
|
1052
|
+
if ((protection === "signature") !== isSig) {
|
|
1053
|
+
throw _err("cmp/bad-input", "the resumeToken continues a transaction protected by " + protection + ", so it cannot be resumed by a session protected by " + (isSig ? "signature" : "mac") + " (RFC 9483 sec. 3.1 binds a transaction to how its sender authenticates)");
|
|
1054
|
+
}
|
|
1055
|
+
/** @internal Read from the token, never from this session's option, since it is what the request
|
|
1056
|
+
* that opened the transaction asked for. A token that omits it resumes as though the request asked
|
|
1057
|
+
* for nothing, which sends a certConf the authority may already have made unnecessary but never
|
|
1058
|
+
* accepts an implicit confirmation the request did not solicit. */
|
|
1059
|
+
var implicitConfirm = raw.implicitConfirm == null ? false : raw.implicitConfirm;
|
|
1060
|
+
if (typeof implicitConfirm !== "boolean") {
|
|
1061
|
+
throw _err("cmp/bad-input", "the resumeToken implicitConfirm must be a boolean saying whether the request that opened this transaction asked for implicit confirmation");
|
|
1062
|
+
}
|
|
1063
|
+
/** @internal The same pairing the constructor refuses, refused again where the token can reintroduce
|
|
1064
|
+
* it: an implicitly confirmed grant has no certConf leg, so a policy that vets one would never run. */
|
|
1065
|
+
if (implicitConfirm === true && typeof opts.acceptCert === "function") {
|
|
1066
|
+
throw _err("cmp/bad-input", "the resumeToken continues a transaction that asked for implicit confirmation, which leaves no certConf leg for opts.acceptCert to reject on -- resume it with a session that vets no grant");
|
|
1067
|
+
}
|
|
1068
|
+
var nextPollAt = raw.nextPollAt;
|
|
1069
|
+
if (nextPollAt != null && (typeof nextPollAt !== "number" || !isFinite(nextPollAt) || nextPollAt < 0)) {
|
|
1070
|
+
throw _err("cmp/bad-input", "the resumeToken nextPollAt must be the instant the next poll is due, in milliseconds since the epoch");
|
|
1071
|
+
}
|
|
1072
|
+
return { transactionID: txn, recipNonce: nonce, certReqId: certReqId, arm: arm,
|
|
1073
|
+
implicitConfirm: implicitConfirm,
|
|
1074
|
+
polls: polls || 0, requestedSpki: spki, signer: signer, signerCache: signerCache,
|
|
1075
|
+
chain: chain, caPubs: caPubs,
|
|
1076
|
+
nextPollAt: nextPollAt != null ? nextPollAt : null };
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
/** @internal The token crosses a process boundary as text, so each field is decoded through the
|
|
1080
|
+
* canonical readers, which refuse a non-alphabet character, a short group and a re-encoding that does
|
|
1081
|
+
* not reproduce the input, and cap the size before allocating. */
|
|
1082
|
+
function _hexField(v, name) {
|
|
1083
|
+
return guard.encoding.hex(v, _perRespCap, _err, "cmp/bad-input", "the resumeToken " + name);
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
function _b64Field(v, name, cap) {
|
|
1087
|
+
return guard.encoding.base64(v, cap || _perRespCap, _err, "cmp/bad-input", "the resumeToken " + name);
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
/** @internal A certificate the token carries. Parsed at the door, not when it is first needed: stored
|
|
1091
|
+
* bytes that are not a certificate would otherwise advance the exchange with the authority, spending a
|
|
1092
|
+
* nonce the token cannot be used again after, before they were found to be unusable. The cap is the
|
|
1093
|
+
* one the bytes were admitted under. A response-borne certificate is held to the response size, while
|
|
1094
|
+
* the signer identity and the chain that validates it can be a certificate the caller supplied through
|
|
1095
|
+
* `opts.intermediates`, which never crossed the wire and is bounded by the codec instead. */
|
|
1096
|
+
function _certField(v, name, cap) {
|
|
1097
|
+
var der = _b64Field(v, name, cap);
|
|
1098
|
+
try { x509.parse(der); }
|
|
1099
|
+
catch (e) { throw _err("cmp/bad-input", "the resumeToken " + name + " is not a certificate", e); }
|
|
1100
|
+
return der;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/** @internal A list of certificates the token carries, held to the count and the total size the list it
|
|
1104
|
+
* restores is built under, so a token cannot hand a resumed transaction a larger pool than the
|
|
1105
|
+
* transaction itself could reach. */
|
|
1106
|
+
function _certListField(v, name, limit) {
|
|
1107
|
+
if (v == null) return [];
|
|
1108
|
+
if (!Array.isArray(v)) throw _err("cmp/bad-input", "the resumeToken " + name + " must be an array of base64 certificates");
|
|
1109
|
+
if (v.length > limit.count) throw _err("cmp/bad-input", "the resumeToken " + name + " carries more than the " + limit.count + " certificates a transaction holds");
|
|
1110
|
+
var out = [], total = 0;
|
|
1111
|
+
for (var i = 0; i < v.length; i++) {
|
|
1112
|
+
var der = _certField(v[i], name + "[" + i + "]", limit.each);
|
|
1113
|
+
total += der.length;
|
|
1114
|
+
if (limit.total !== null && total > limit.total) {
|
|
1115
|
+
throw _err("cmp/bad-input", "the resumeToken " + name + " exceeds the " + limit.total + "-byte pool a transaction holds");
|
|
1116
|
+
}
|
|
1117
|
+
out.push(der);
|
|
1118
|
+
}
|
|
1119
|
+
return out;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
/** @internal Continue polling a transaction an earlier process started, and finish it the way that
|
|
1123
|
+
* process would have: the grant is confirmed, bound to the requested key, and returned as the same
|
|
1124
|
+
* verdict `enroll` returns. A further timeout hands back a token again, so a long wait can span any
|
|
1125
|
+
* number of processes. */
|
|
1126
|
+
async function resumePoll(token) {
|
|
1127
|
+
_assertFresh("resumed poll");
|
|
1128
|
+
var t = _readResumeToken(token);
|
|
1129
|
+
inFlight = true;
|
|
1130
|
+
try {
|
|
1131
|
+
txnKind = "enroll";
|
|
1132
|
+
/** @internal Installing the restored state consumes the session, whether or not a request follows:
|
|
1133
|
+
* this session now holds another transaction's identifier and nonce, and a later enroll on it would
|
|
1134
|
+
* open a new enrollment under them (RFC 9810 sec. 5.1.1 gives each transaction its own identifier). */
|
|
1135
|
+
started = true;
|
|
1136
|
+
transactionID = t.transactionID;
|
|
1137
|
+
lastPeerNonce = t.recipNonce;
|
|
1138
|
+
haveResponse = true;
|
|
1139
|
+
activeCertReqId = t.certReqId;
|
|
1140
|
+
expectedRespArm = t.arm;
|
|
1141
|
+
requestedSpki = t.requestedSpki;
|
|
1142
|
+
requestedImplicitConfirm = t.implicitConfirm;
|
|
1143
|
+
/** @internal Restoring the pinned identity is what makes a restart no weaker than staying in one
|
|
1144
|
+
* process: the resumed responses are held to the signer the first process authenticated, and the
|
|
1145
|
+
* certificates it had already been sent are available to verify them with. */
|
|
1146
|
+
if (t.signer != null) {
|
|
1147
|
+
try { pinnedSignerCert = x509.parse(t.signer); pinnedSignerDer = t.signer; signerPinned = true; }
|
|
1148
|
+
catch (e) { throw _err("cmp/bad-input", "the resumeToken signer is not a valid X.509 certificate", e); }
|
|
1149
|
+
}
|
|
1150
|
+
/** @internal The pin and the cache are separate state and stay separate here. The pin says which
|
|
1151
|
+
* identity every response is held to; the cache is the certificate the first process had actually
|
|
1152
|
+
* been sent to verify one with, and a token that names no cache is a transaction that had none, so
|
|
1153
|
+
* standing the pin in for it would let a resumed poll read a response, and validate a grant, that
|
|
1154
|
+
* the same exchange in one process refuses. */
|
|
1155
|
+
cachedSignerCert = t.signerCache;
|
|
1156
|
+
cachedChain = t.chain;
|
|
1157
|
+
/** @internal The certificates the earlier process was sent, restored under the same bookkeeping the
|
|
1158
|
+
* session accumulates with, so the pool stays bounded across the restart. */
|
|
1159
|
+
for (var ci = 0; ci < t.caPubs.length; ci++) {
|
|
1160
|
+
var pub = t.caPubs[ci];
|
|
1161
|
+
var pk = pub.toString("base64");
|
|
1162
|
+
if (caPubsSeen[pk]) continue;
|
|
1163
|
+
caPubsSeen[pk] = true;
|
|
1164
|
+
caPubsBytes += pub.length;
|
|
1165
|
+
guard.list.append(caPubsAccum, pub);
|
|
1166
|
+
}
|
|
1167
|
+
/** @internal Every restored certificate arrived on a waiting leg, so it is evictable the same way:
|
|
1168
|
+
* leaving the count at zero would stop the grant's own issuer displacing one when the pool is full. */
|
|
1169
|
+
caPubsWaitingCount = caPubsAccum.length;
|
|
1170
|
+
/** @internal The authority's own interval is honored, but the CALLER's wait budget still bounds
|
|
1171
|
+
* this process: a remainder longer than the budget is a timeout now, carrying the same due time on
|
|
1172
|
+
* so a later process with more room can still wait it out. */
|
|
1173
|
+
var restWaited = 0;
|
|
1174
|
+
if (t.nextPollAt != null) {
|
|
1175
|
+
var waitMs = t.nextPollAt - guard.time.instantOf(new Date());
|
|
1176
|
+
if (waitMs > 0) {
|
|
1177
|
+
var waitSeconds = Math.ceil(waitMs / constants.TIME.seconds(1));
|
|
1178
|
+
if (waitSeconds > maxTotalWait) {
|
|
1179
|
+
return _terminal("poll-timeout", { status: _waitingStatus(), polls: t.polls, resumeToken: _resumeToken(t.polls, t.nextPollAt) });
|
|
1180
|
+
}
|
|
1181
|
+
await sleep(waitMs);
|
|
1182
|
+
restWaited = waitSeconds;
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
var polled = await _pollLoop(null, restWaited);
|
|
1186
|
+
var spent = t.polls + polled.polls;
|
|
1187
|
+
if (polled.timeout) return _terminal("poll-timeout", { status: polled.status || _waitingStatus(), polls: spent, resumeToken: _resumeToken(spent, _pollDueAt(polled.dueIn)) });
|
|
1188
|
+
var done = polled.done;
|
|
1189
|
+
if (done.state === "granted") {
|
|
1190
|
+
var r = await _finish({ resp: done.resp, polls: spent, code: done.code }, polled.header);
|
|
1191
|
+
r.polls = spent;
|
|
1192
|
+
return r;
|
|
1193
|
+
}
|
|
1194
|
+
if (done.state === "rejected") return _terminal("rejected", { status: done.status || _statusOf(done.resp), polls: spent });
|
|
1195
|
+
throw _err("cmp/unexpected-arm", done.reason || "the resumed enrollment reached an unexpected state");
|
|
1196
|
+
} finally {
|
|
1197
|
+
inFlight = false;
|
|
1198
|
+
completed = started;
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
|
|
797
1202
|
function _assertRevokingOwnCertificate(certTemplateDer) {
|
|
798
1203
|
var own;
|
|
799
1204
|
try {
|
|
@@ -1123,6 +1528,7 @@ function session(opts) {
|
|
|
1123
1528
|
|
|
1124
1529
|
return {
|
|
1125
1530
|
enroll: enroll,
|
|
1531
|
+
resumePoll: resumePoll,
|
|
1126
1532
|
revoke: revoke,
|
|
1127
1533
|
info: info,
|
|
1128
1534
|
get transactionID() { return Buffer.from(transactionID); },
|
package/lib/cmp-verify.js
CHANGED
|
@@ -349,7 +349,8 @@ function _headerChecks(m, opts) {
|
|
|
349
349
|
if (!guard.bytes.isByteSource(m.header.transactionID)) {
|
|
350
350
|
return { code: "cmp/bad-transaction-id", reason: "the header transactionID is absent; a received PKIMessage MUST carry one (RFC 9483 sec. 3.5)" };
|
|
351
351
|
}
|
|
352
|
-
if (!guard.bytes.isByteSource(m.header.senderNonce) ||
|
|
352
|
+
if (!guard.bytes.isByteSource(m.header.senderNonce) ||
|
|
353
|
+
guard.bytes.lengthOf(m.header.senderNonce) < constants.LIMITS.CMP_MIN_NONCE_BYTES) {
|
|
353
354
|
return { code: "cmp/bad-sender-nonce", reason: "the header senderNonce is absent or shorter than 128 bits (RFC 9483 sec. 3.5)" };
|
|
354
355
|
}
|
|
355
356
|
if (opts.transactionID != null && !_bufEq(m.header.transactionID, opts.transactionID)) {
|
package/lib/constants.js
CHANGED
|
@@ -161,6 +161,8 @@ var LIMITS = Object.assign(Object.create(null), {
|
|
|
161
161
|
SAFETYNET_JWS_MAX_BYTES: BYTES.kib(64),
|
|
162
162
|
SAFETYNET_CERT_MAX_BYTES: BYTES.kib(64),
|
|
163
163
|
ACME_TOKEN_MIN_CHARS: 22,
|
|
164
|
+
CMP_MIN_NONCE_BYTES: 16,
|
|
165
|
+
CMP_TRANSACTION_ID_BYTES: 16,
|
|
164
166
|
SCEP_TRANSACTION_ID_MAX: 255,
|
|
165
167
|
OCSP_MAX_CERTS: 32,
|
|
166
168
|
HSS_MAX_LEVELS: 8,
|
package/package.json
CHANGED
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:
|
|
5
|
+
"serialNumber": "urn:uuid:39d93a95-6e56-4af5-9029-94a73a8e00c4",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-09-
|
|
8
|
+
"timestamp": "2026-09-06T15:41:11.254Z",
|
|
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.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.6.47",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.6.
|
|
25
|
+
"version": "0.6.47",
|
|
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.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/pki@0.6.47",
|
|
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.
|
|
57
|
+
"ref": "@blamejs/pki@0.6.47",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|