@blamejs/pki 0.5.37 → 0.5.39
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 +17 -1
- package/README.md +2 -2
- package/lib/cmc-build.js +41 -9
- package/lib/cmc-verify.js +3 -1
- package/lib/cmp-build.js +52 -30
- package/lib/cms-encrypt.js +12 -4
- package/lib/crl-sign.js +8 -6
- package/lib/crmf-sign.js +2 -1
- package/lib/ocsp.js +5 -2
- package/lib/pkcs12-build.js +8 -3
- package/lib/pki-build.js +38 -18
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,23 @@ All notable changes to `@blamejs/pki` are documented here. The format
|
|
|
4
4
|
follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
|
|
5
5
|
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
6
|
|
|
7
|
-
## v0.5.
|
|
7
|
+
## v0.5.39 — 2026-08-30
|
|
8
|
+
|
|
9
|
+
pki.cmc.build and pki.cmp.build verify an embedded PKCS#10 request's proof-of-possession and refuse one whose self-signature does not verify.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- pki.cmc.build (`tcr` arm) and pki.cmp.build (`p10cr` arm) verify the embedded PKCS#10 request's proof-of-possession before signing or protecting the enrollment message: the request's self-signature must verify under the subject public key it carries (RFC 5272 sec. 6.3 for CMC; RFC 9810 sec. 5.3.3 for CMP, over the PKCS#10 structure of RFC 2986). A request whose signature does not verify is refused with a typed `cmc/bad-popo` or `cmp/bad-popo` error naming the offending request; a request with a valid proof-of-possession builds unchanged.
|
|
14
|
+
|
|
15
|
+
## v0.5.38 — 2026-08-29
|
|
16
|
+
|
|
17
|
+
Builder verbs reject a sparse or nullish array argument with a typed error instead of a native one.
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
|
|
21
|
+
- The array arguments of pki.pkcs12.build (SafeContents bags), pki.ocsp.buildRequest and pki.ocsp.sign (the query and response batches), pki.cmc.build (requests and the CMS and other-message sequences), pki.crl.sign (revoked entries and the issuing-distribution-point and freshest-CRL general names), pki.crmf.build (controls and registration info), and pki.cms.encrypt (authenticated attributes) are checked for holes and nullish entries up front. A sparse or nullish array is now the verb's own typed `<domain>/bad-input` error naming the index, in place of the native `TypeError` the hole previously produced at the encoder. A valid (dense) array is unaffected and its emitted structure is byte-for-byte identical.
|
|
22
|
+
|
|
23
|
+
## v0.5.37 — 2026-08-29
|
|
8
24
|
|
|
9
25
|
pki.cms.decrypt can return the recovered content as an async iterable of plaintext chunks.
|
|
10
26
|
|
package/README.md
CHANGED
|
@@ -225,7 +225,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
225
225
|
| `pki.jose` | Flattened JWS (RFC 7515) and JWK thumbprints (RFC 7638). `sign` and `verify` run a Flattened JWS against declarative profiles (ACME outer, EAB inner, keyChange inner) that carry the required and forbidden header rules as data. `base64url` is the strict RFC 4648 §5 codec, rejecting padding, non-alphabet characters, and non-canonical trailing bits. `parseJson` is a bounded reader that refuses duplicate members at any depth. `thumbprint` is the RFC 7638 / 8037 / 9964 canonical digest. The algorithm registry binds each `alg` to its key type (ES/RS/PS/EdDSA/ML-DSA), leaving no code path for `alg:none`, an RS256→HS256 key confusion, or an all-zero ECDSA signature; `assertPublicJwk` refuses a JWK carrying private material, so an exported private key is never published. `opts.key` names the key a message must be signed under and governs: where the profile also permits an embedded header `jwk`, the two must be the same key — compared as RFC 7638 thumbprints, so member order cannot make equal keys differ — and a disagreement is refused rather than resolved in the message's favor. `keySource` reports which key answered, since a signature checked against a key you named is a different claim from one checked against the key the message carried — `sign`, `verify`, `base64url`, `parseJson`, `thumbprint`, `assertPublicJwk` |
|
|
226
226
|
| `pki.acme` | ACME (RFC 8555 / 8737 / 8738 / 9773). `client(directoryUrl, opts)` is a stateful client driving a live CA directory over `pki.transport`: `newAccount`, `newOrder`, `newAuthz`, `getOrder`, `getAuthorization`, `getChallenge`, `respondToChallenge`, `finalize`, `pollOrder`, `pollAuthorization`, and `downloadCertificate` walk the issuance flow, with `newAuthz` pre-authorizing a single identifier (§7.4.1) and `downloadCertificate` binding the issued certificate to the order — its key, its identifiers, or both; at least one is required by default and the result reports `boundToKey` / `boundToIdentifiers` — before choosing among alternate chains (`Link rel="alternate"`, §7.4.2, via a `selectChain` predicate bounded by `maxAlternates`). `revokeCert` (account-key or certificate-key signed), `keyChange`, `deactivateAccount`, `deactivateAuthorization`, `renewalInfo` (ARI), and `renewalWindow` (the RFC 9773 §4.2/4.3 renewal decision) complete the lifecycle. Every URL is HTTPS only, an explicit trust anchor is required, each request carries a fresh single-use nonce with a bounded badNonce retry, reads are POST-as-GET, polling is bounded and sleeps on a Retry-After via an injectable sleeper capped by a poll count and a total-wait budget, and every response body is size-capped. The transport is injectable via `opts.transport`. Over the message layer it composes resource-object validators (closed status enums, conditional-required fields, unknown fields ignored), the three §7.1.6 state machines, the request builders (newAccount with External Account Binding, newOrder with `replaces`, finalize with a CSR identifier-set match and account-key-reuse rejection, challenge responses, deactivation, revokeCert in both key modes, the keyChange nested JWS, POST-as-GET), the http-01 / dns-01 / tls-alpn-01 challenge computations, the dns and ip identifier validators, and the ARI certID with serial sign-padding preserved — `client`, `validate`, `identify`, `assertTransition`, the builders, `keyAuthorization`, `http01`, `dns01`, `tlsAlpn01Extension`, `verifyTlsAlpn01`, `ariCertId` |
|
|
227
227
|
| `pki.schema.smime` | S/MIME ESS signed-attribute values (RFC 5035 / RFC 8551). `parseSigningCertificate` and `parseSigningCertificateV2` bind a signature to its signing certificate (cert hash, hash algorithm, issuer `GeneralNames` and serial); `parseSmimeCapabilities` decodes the ordered capability list; `decodeAttribute` dispatches a CMS attribute by OID, enforcing the single-value rule and deferring on unknown types. A companion decoder for CMS signed attributes rather than an auto-routed format — `parseSigningCertificate`, `parseSigningCertificateV2`, `parseSmimeCapabilities`, `decodeAttribute` |
|
|
228
|
-
| `pki.cmc` | Build and interpret CMC messages (RFC 5272). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and signs it through `pki.cms.sign` under `id-cct-PKIData`. Body-part identifiers are unique across the whole message and never the reserved 0; a caller's clash is refused rather than renumbered, since a control may already reference it. An Identity Proof V2 witness is computed over the `reqSequence` bytes exactly as emitted (§6.2.1 step 1) rather than a re-serialization, a POP Link Witness is emitted only alongside the POP Link Random control §6.3.1.1 requires beside it, and a renewal carries neither Identification nor Identity Proof in either version. `verify(response, sent)` takes what the CA returned plus the state the client retained and reduces it to one terminal outcome: `issued`, `pending`, `confirm-required`, `pop-required`, or `rejected`. It binds the exchange first — Transaction Identifier, the Sender and Recipient Nonce echo compared in constant time and by full value so a truncation cannot match, and the Data Return echo — with each check applying only if the client sent that half, and, once sent, an absent or differing echo being a refusal, which is the replay defense. `bodyPartIDs` extends the same rule to what the response is about: a status reporting on a body part the request never sent is refused, which the transaction and nonce cannot catch, because a server can echo both correctly while answering about a different message. Several status controls are permitted and the worst governs, so a failure cannot hide behind an earlier success; the absence of any status control is success, per §6.1.2. The carrier's signature must verify (§3.2.1.3.4): a conforming SignedData carries its own signer certificate, so the ordinary build-then-verify flow needs nothing extra and the verdict reports `signatureVerified: true`. Where the signer is found nowhere the posture is fail-closed with a named opt-out — supply `certs` with the responder's certificate, or `allowUnverified: true`, in which case the verdict reports `signatureVerified: false`. Doing neither is refused, the opt-out never excuses a signature that is present and wrong, and a carrier with no signer at all is refused outright. The response's own `cmsSequence` and `otherMsgs` come back raw, since a request whose only arm was the other-message form has no certificate to return and §4.1 puts its answer there. Nothing is trusted: issued certificates are read from the CMS certificate bag (§4.2) and surfaced raw for `pki.path.validate`, and a Publish Trust Anchors control is surfaced with `trusted: false` rather than added to a store — `build`, `verify` |
|
|
228
|
+
| `pki.cmc` | Build and interpret CMC messages (RFC 5272). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and signs it through `pki.cms.sign` under `id-cct-PKIData`. 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` |
|
|
229
229
|
| `pki.schema.cmc` | Decode CMC messages (RFC 5272 as updated by RFC 6402): a Full PKI Request (`PKIData`) or Full PKI Response (`PKIResponse`) riding inside a CMS SignedData, reached by the encapsulated content type (`id-cct-PKIData` / `id-cct-PKIResponse`). Controls are surfaced in wire order with their values raw, so an unrecognized one is data rather than a fault. Tagged requests decode across all three arms. The status verdicts (`CMCStatusInfo` v1 and `CMCStatusInfoV2`) are collected as an ordered list, and the RFC 6402 two-module `OtherStatusInfo` ambiguity — `pendInfo` and `extendedFailInfo` are both untagged SEQUENCEs in the 1988 module, told apart only by their first element — is resolved by inspection and refused when it cannot be told apart. Body-part identity is unique across the whole message rather than per sequence, 0 is reserved as the reference to the enclosing PKIData, and the `reqSequence` bytes are surfaced exactly as they appeared so an Identity Proof witness is computed over the wire bytes. A companion decoder for CMS content rather than an auto-routed format — `parse`, `parsePkiData`, `parsePkiResponse` |
|
|
230
230
|
| `pki.schema.engine` | The declarative ASN.1 structure-schema engine every format parser composes — `walk`, `encode`, `embeddedDer`, and the schema combinators |
|
|
231
231
|
| `pki.path` | Certification-path validation (RFC 5280 §6). `validate` runs the §6.1 state machine over an ordered path and a trust anchor: signature chaining across RSA, ECDSA, EdDSA, ML-DSA, SLH-DSA and hybrid composite ML-DSA (a composite is accepted only when both its post-quantum and traditional components verify), validity windows, name chaining, basic constraints and path length, key usage, name constraints, and the certificate-policy tree. It returns a structured verdict with per-check reason codes and enforces a `pki.trust` anchor's per-purpose distrust-after dates and delegator purposes through `checkPurpose` — an anchor that carries either one with no purpose named to select by is refused as a configuration fault rather than validated as though it carried none. The verdict says what was established. `revocationChecked` takes the weakest outcome on the path: `false` with no checker supplied, `"determined"` when every certificate got an explicit good or revoked answer, `"waived"` when `softFail` turned an undetermined one into a pass, and `"undetermined"` when one could not be answered at all — which includes a checker that throws, a fault `softFail` does not waive because `softFail` opts into an undetermined answer, not into a broken checker. `anchorConstraints` names the purpose the anchor was judged under and whether each of its two constraints applied. `crlChecker` supplies CRL-based revocation, covering partitioned and sharded CRLs, whose §6.3.3 Distribution Point ↔ IDP correspondence lets corresponding shards accumulate reason coverage until all eight revocation reasons are covered, and delta CRLs, merged onto the complete CRL they may be combined with (§5.2.4) so a held certificate its delta releases reads good, while a delta that merges with nothing still reports what it lists and still withholds good. `ocspChecker` supplies OCSP-based revocation (RFC 6960: CertID binding, responder authorization, signature, currency) over the same pluggable hook. `build(leaf, opts)` is the discovering complement (RFC 4158): from a leaf, an untrusted pool of candidate CA certificates, and a trust store, it finds the ordered leaf-to-anchor path `validate` accepts, using name chaining plus the RFC 4158 §3.5 sort hints (an AKI/SKI match, an anchor-adjacent issuer, CA plus keyCertSign, validity at the check time — ordering hints, never filters), a depth-first search with backtracking so the first accepted path wins, and a bounded search (chain-length cap, candidate-expansion cap, identity-tuple visited set) so a cross-certificate cycle or Bridge-CA fan-out terminates deterministically. Every accept flows through `validate`, and its verdict is cross-checked against `openssl verify`. Opt-in AIA `caIssuers` fetching (`opts.fetchAia: true`) discovers a missing intermediate from a certificate's Authority Information Access URL (§4.2.2.1) over `pki.transport`, triggered only on a pool miss and bounded against SSRF and amplification: HTTPS only, a total fetch budget that caps fetching silently rather than throwing, a per-cert URL cap, a build-wide URL dedupe, a response-size and certificate-count cap, no redirect following, and every fault a silent skip. The TLS trust (`opts.tls`) stays distinct from the PKI `trustAnchors`, and every fetched certificate remains untrusted pool material that still flows through `validate` (never a trust anchor). It is off by default, so the default build is byte-identical offline. Pure and re-entrant — `validate`, `build`, `crlChecker`, `ocspChecker` |
|
|
@@ -233,7 +233,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
233
233
|
| `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
|
|
234
234
|
| `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
|
|
235
235
|
| `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named, and `agreeMAC` is not built, since it needs the RFC 2875 static Diffie-Hellman secret against a CA certificate the requester already holds. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
|
|
236
|
-
| `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. `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` |
|
|
236
|
+
| `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, 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` |
|
|
237
237
|
| `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the issuer key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
|
|
238
238
|
| `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
|
|
239
239
|
| `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/cmc-build.js
CHANGED
|
@@ -27,7 +27,10 @@
|
|
|
27
27
|
|
|
28
28
|
var nodeCrypto = require("node:crypto");
|
|
29
29
|
var asn1 = require("./asn1-der");
|
|
30
|
+
var pkiBuild = require("./pki-build"); // reqDenseArray: reject a sparse/nullish caller array as a typed cmc/bad-input
|
|
30
31
|
var csr = require("./schema-csr"); // to read the Subject Key Identifier a tcr request declares
|
|
32
|
+
require("./path-validate"); // side-effect: path-validate injects its signature engine into csr-verify at load
|
|
33
|
+
var csrVerify = require("./csr-verify"); // verify an embedded tcr request's proof-of-possession before signing it
|
|
31
34
|
var crmf = require("./schema-crmf"); // ... and the one a crm request declares
|
|
32
35
|
var cmcFmt = require("./schema-cmc"); // to read the assembled message back before signing it
|
|
33
36
|
var oid = require("./oid");
|
|
@@ -207,6 +210,29 @@ function fixedRequestId(req, index) {
|
|
|
207
210
|
return req.bodyPartID == null ? null : req.bodyPartID;
|
|
208
211
|
}
|
|
209
212
|
|
|
213
|
+
// Verify each embedded PKCS#10 (tcr) request's proof-of-possession before the message is signed. A CSR
|
|
214
|
+
// whose self-signature does not verify under its own subjectPKInfo is one the CA will reject (RFC 5272
|
|
215
|
+
// sec. 4.1), so refusing it here -- through the shared inbound-PoP seam pki.csr.verify uses -- keeps the
|
|
216
|
+
// producer from signing a request that cannot be acted on, the same "do not sign what the recipient
|
|
217
|
+
// refuses" discipline the assembled-message readback already applies. The crm / orm arms carry their own
|
|
218
|
+
// POP structures (CRMF POPOSigningKey etc.), validated by their own parse; only tcr is a bare CSR.
|
|
219
|
+
// `await`, not `.then`: the PoP verdict is read through the native promise job, not the replaceable
|
|
220
|
+
// Promise.prototype.then a co-resident could swap to force `ok` true and slip an unverified request past.
|
|
221
|
+
async function _assertTcrPops(requests) {
|
|
222
|
+
for (var i = 0; i < requests.length; i++) {
|
|
223
|
+
if (requests[i] && requests[i].tcr != null) await _assertOneTcrPop(requests[i].tcr, i);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async function _assertOneTcrPop(tcr, i) {
|
|
227
|
+
// encodeRequest already validated this tcr's structure synchronously (it runs before this async pass),
|
|
228
|
+
// so the re-parse here only recovers the parse the PoP check verifies over; on the shipped path it
|
|
229
|
+
// cannot fail, and a sync throw surfaces as a rejection through build's async boundary regardless.
|
|
230
|
+
var parsed = csr.parse(_der(tcr, "a tcr certificationRequest"));
|
|
231
|
+
if (!(await csrVerify.verifyCsrSignature(parsed))) {
|
|
232
|
+
throw E("cmc/bad-popo", "a tcr request [" + i + "] failed its proof-of-possession: the PKCS#10 signature does not verify under the request's own subject public key (RFC 5272 sec. 6.3), so a CA would reject it -- refusing it here rather than signing it");
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
210
236
|
function encodeRequest(req, ids, index) {
|
|
211
237
|
if (req.tcr != null) {
|
|
212
238
|
// A tcr arm is a PKCS#10 CertificationRequest, so it is parsed and never
|
|
@@ -498,7 +524,7 @@ function build(spec, signer, opts) {
|
|
|
498
524
|
], _build);
|
|
499
525
|
}
|
|
500
526
|
|
|
501
|
-
function _build(spec, signer, opts) {
|
|
527
|
+
async function _build(spec, signer, opts) {
|
|
502
528
|
opts = opts || {};
|
|
503
529
|
if (!spec || typeof spec !== "object" || Array.isArray(spec) || Buffer.isBuffer(spec)) {
|
|
504
530
|
throw E("cmc/bad-input", "the CMC request spec must be an object");
|
|
@@ -510,7 +536,9 @@ function _build(spec, signer, opts) {
|
|
|
510
536
|
// them has no replay defense, and pki.cmc.verify cannot enforce a binding the
|
|
511
537
|
// client never sent, so the omission is invisible from both ends.
|
|
512
538
|
guard.identifier.assertKnownKeys(spec, KNOWN_SPEC_KEYS, E, "cmc/bad-input", "unknown spec field ");
|
|
513
|
-
|
|
539
|
+
// Density up front: requests is iterated by both the forEach below and the map that encodes it, and a
|
|
540
|
+
// hole would survive either (map/forEach skip it) to reach b.sequence as a native error.
|
|
541
|
+
var requests = spec.requests != null ? pkiBuild.reqDenseArray(spec.requests, "requests", E, "cmc/bad-input") : [];
|
|
514
542
|
if (!Array.isArray(requests)) throw E("cmc/bad-input", "spec.requests must be an array");
|
|
515
543
|
var callerControls = spec.controls || [];
|
|
516
544
|
if (!Array.isArray(callerControls)) throw E("cmc/bad-input", "spec.controls must be an array");
|
|
@@ -532,10 +560,10 @@ function _build(spec, signer, opts) {
|
|
|
532
560
|
var fixed = fixedRequestId(r, i);
|
|
533
561
|
if (fixed != null) ids.reserve(fixed, "request " + i);
|
|
534
562
|
});
|
|
535
|
-
var cmsSequence = (spec.cmsSequence
|
|
563
|
+
var cmsSequence = (spec.cmsSequence != null ? pkiBuild.reqDenseArray(spec.cmsSequence, "cmsSequence", E, "cmc/bad-input") : []).map(function (el, i) {
|
|
536
564
|
return _claimRawElement(el, ids, "a cmsSequence element (index " + i + ")");
|
|
537
565
|
});
|
|
538
|
-
var otherMsgSequence = (spec.otherMsgSequence
|
|
566
|
+
var otherMsgSequence = (spec.otherMsgSequence != null ? pkiBuild.reqDenseArray(spec.otherMsgSequence, "otherMsgSequence", E, "cmc/bad-input") : []).map(function (el, i) {
|
|
539
567
|
return _claimRawElement(el, ids, "an otherMsgSequence element (index " + i + ")");
|
|
540
568
|
});
|
|
541
569
|
|
|
@@ -692,12 +720,16 @@ function _build(spec, signer, opts) {
|
|
|
692
720
|
if (ownedKeyBytes.length) guard.secret.zeroizeAll(ownedKeyBytes, CmcError, "cmc/bad-input", "the signer key copy");
|
|
693
721
|
ownedKeyBytes.length = 0;
|
|
694
722
|
}
|
|
695
|
-
|
|
723
|
+
// Verify every embedded tcr proof-of-possession BEFORE signing: do not sign a request the CA will
|
|
724
|
+
// reject. `await`, not a `.then` chain, so the PoP gate and the sign are sequenced through native
|
|
725
|
+
// promise jobs a co-resident cannot swap; the finally clears the signer key copy on every path,
|
|
726
|
+
// the rejecting one included.
|
|
696
727
|
try {
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
728
|
+
await _assertTcrPops(requests);
|
|
729
|
+
return await cmsSign.sign(pkiData, copiedSigner, { eContentType: "id-cct-PKIData", pem: opts.pem });
|
|
730
|
+
} finally {
|
|
731
|
+
_wipeOwnedKeys();
|
|
732
|
+
}
|
|
701
733
|
}
|
|
702
734
|
|
|
703
735
|
// Each signer descriptor, and every byte value in it. cms.sign reads these inside
|
package/lib/cmc-verify.js
CHANGED
|
@@ -697,7 +697,9 @@ function _shape(body, sent, signatureVerified, bound) {
|
|
|
697
697
|
* requests, each naming exactly one arm: `tcr` (a PKCS#10 CSR), `crm` (a CRMF CertReqMsg, or the
|
|
698
698
|
* CertReqMessages `pki.crmf.build` returns when it carries exactly one) or `orm`
|
|
699
699
|
* (`{ type, value }`). `spec.controls` are additional controls as `{ type, value }`, and `signer`
|
|
700
|
-
* is the `{ cert, key }` that signs the enclosing CMS SignedData.
|
|
700
|
+
* is the `{ cert, key }` that signs the enclosing CMS SignedData. A `tcr` request is verified against
|
|
701
|
+
* its own proof-of-possession first: a PKCS#10 whose self-signature does not verify under its subject
|
|
702
|
+
* public key is refused (`cmc/bad-popo`) rather than signed into a message a CA would reject.
|
|
701
703
|
*
|
|
702
704
|
* Body part identifiers are allocated automatically, unique across the whole message and never 0
|
|
703
705
|
* (RFC 5272 sec. 3.2.2). A caller may pin one, and a clash is refused, never renumbered, because
|
package/lib/cmp-build.js
CHANGED
|
@@ -60,6 +60,8 @@ var _bigInt = intrinsic.BigInt;
|
|
|
60
60
|
// go through a Date a caller could have replaced after this module was read.
|
|
61
61
|
var _Date = intrinsic.Date;
|
|
62
62
|
var csr = require("./schema-csr");
|
|
63
|
+
require("./path-validate"); // side-effect: path-validate injects its signature engine into csr-verify at load
|
|
64
|
+
var csrVerify = require("./csr-verify"); // verify an embedded p10cr request's proof-of-possession before sending it
|
|
63
65
|
var crl = require("./schema-crl");
|
|
64
66
|
var x509 = require("./schema-x509");
|
|
65
67
|
var signScheme = require("./sign-scheme");
|
|
@@ -681,10 +683,17 @@ function _encodeBody(bodySpec, key, opts) {
|
|
|
681
683
|
var inner;
|
|
682
684
|
if (arm === "p10cr") {
|
|
683
685
|
var csrDer = _b.reqDerSequence(bodySpec.p10cr, "p10cr (a CertificationRequest DER)");
|
|
684
|
-
|
|
686
|
+
var parsedCsr;
|
|
687
|
+
try { parsedCsr = csr.parse(csrDer); } // validate structure via the real parser AND capture the parse for the PoP check
|
|
685
688
|
catch (e) { if (e instanceof CmpError) throw e; throw _err("cmp/bad-input", "p10cr is not a valid PKCS#10 CertificationRequest", e); }
|
|
686
|
-
|
|
687
|
-
|
|
689
|
+
// Verify the embedded request's proof-of-possession before it is protected and sent: a p10cr carries
|
|
690
|
+
// a PKCS#10 CertificationRequest (RFC 9810 sec. 5.3.3, whose structure is RFC 2986), and its
|
|
691
|
+
// self-signature under its own subject public key is that request's proof-of-possession. A CSR whose
|
|
692
|
+
// self-signature does not verify is one the CA will reject, so refuse it rather than send it -- through
|
|
693
|
+
// the shared inbound-PoP seam pki.csr.verify uses.
|
|
694
|
+
return _p10crBody(csrDer, parsedCsr, tag, state);
|
|
695
|
+
}
|
|
696
|
+
if (arm === "certConf") {
|
|
688
697
|
inner = _encodeCertConfirmContent(bodySpec.certConf, state);
|
|
689
698
|
} else if (arm === "pollReq") {
|
|
690
699
|
inner = _encodePollReqContent(bodySpec.pollReq);
|
|
@@ -713,6 +722,16 @@ function _encodeBody(bodySpec, key, opts) {
|
|
|
713
722
|
return Promise.resolve({ bodyTLV: b.explicit(tag, inner), usesCmp2021: state.usesCmp2021 });
|
|
714
723
|
}
|
|
715
724
|
|
|
725
|
+
// `await`, not a `.then` chain: the PoP verdict is read through the native promise job, not the
|
|
726
|
+
// replaceable Promise.prototype.then a co-resident could swap to force `ok` true and slip an
|
|
727
|
+
// unverified request past. The caller has already validated csrDer's structure synchronously.
|
|
728
|
+
async function _p10crBody(csrDer, parsedCsr, tag, state) {
|
|
729
|
+
if (!(await csrVerify.verifyCsrSignature(parsedCsr))) {
|
|
730
|
+
throw _err("cmp/bad-popo", "the p10cr CertificationRequest failed its proof-of-possession: its PKCS#10 signature does not verify under its own subject public key, so a CA would reject it");
|
|
731
|
+
}
|
|
732
|
+
return { bodyTLV: b.explicit(tag, b.raw(csrDer)), usesCmp2021: state.usesCmp2021 };
|
|
733
|
+
}
|
|
734
|
+
|
|
716
735
|
// ---- protection ----
|
|
717
736
|
|
|
718
737
|
|
|
@@ -803,7 +822,7 @@ function build(message, opts) {
|
|
|
803
822
|
], _build);
|
|
804
823
|
}
|
|
805
824
|
|
|
806
|
-
function _build(message, opts) {
|
|
825
|
+
async function _build(message, opts) {
|
|
807
826
|
opts = opts || {};
|
|
808
827
|
if (!message || typeof message !== "object" || Buffer.isBuffer(message)) throw _err("cmp/bad-input", "the PKIMessage spec must be an object { header, body }");
|
|
809
828
|
guard.identifier.assertKnownKeys(message, KNOWN_MESSAGE_KEYS, _err, "cmp/bad-input", function (k) {
|
|
@@ -824,30 +843,31 @@ function _build(message, opts) {
|
|
|
824
843
|
var prot = _resolveProtection(opts);
|
|
825
844
|
var senderKey = opts.key;
|
|
826
845
|
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
}
|
|
846
|
+
// `await`, not a `.then` chain: an embedded p10cr/crm proof-of-possession is enforced by _encodeBody
|
|
847
|
+
// REJECTING, so the verdict must reach here through the native promise job, not a Promise.prototype.then
|
|
848
|
+
// a co-resident could swap to fire this callback with a forged body and slip an unverified request past.
|
|
849
|
+
var bodyResult = await _encodeBody(message.body, senderKey, opts);
|
|
850
|
+
var bodyTLV = bodyResult.bodyTLV;
|
|
851
|
+
var pvno = message.header.pvno != null ? message.header.pvno : 2;
|
|
852
|
+
if (typeof pvno !== "number" || !Number.isInteger(pvno)) throw _err("cmp/bad-input", "header.pvno must be an integer");
|
|
853
|
+
if (bodyResult.usesCmp2021 && pvno < 3) pvno = 3; // a certConf hashAlg forces cmp2021(3)
|
|
854
|
+
|
|
855
|
+
var headerTLV = _encodeHeader(message.header, prot.protectionAlgDer, pvno); // built ONCE
|
|
856
|
+
var protectedPartDer = b.sequence([headerTLV, bodyTLV]); // virtual ProtectedPart ::= SEQUENCE { header, body }
|
|
857
|
+
|
|
858
|
+
var protectionBits = await prot.computeBits(protectedPartDer);
|
|
859
|
+
var msgChildren = [headerTLV, bodyTLV, b.explicit(0, protectionBits)]; // reuse the SAME header/body TLVs
|
|
860
|
+
var extraCertsDers = _collectExtraCerts(opts, prot.certDer);
|
|
861
|
+
if (extraCertsDers.length) msgChildren.push(b.explicit(1, b.sequence(extraCertsDers)));
|
|
862
|
+
var der = b.sequence(msgChildren);
|
|
863
|
+
|
|
864
|
+
cmp.parse(der); // round-trip re-validation: the emitted message MUST parse (protection<=>protectionAlg, pvno, freeText, etc.)
|
|
865
|
+
if (opts.pem != null) {
|
|
866
|
+
if (opts.pem === true) return cmp.pemEncode(der, "CMP");
|
|
867
|
+
if (typeof opts.pem !== "string" || !opts.pem) throw _err("cmp/bad-input", "opts.pem must be true or a non-empty PEM label string");
|
|
868
|
+
return cmp.pemEncode(der, opts.pem);
|
|
869
|
+
}
|
|
870
|
+
return der;
|
|
851
871
|
}
|
|
852
872
|
|
|
853
873
|
function _collectExtraCerts(opts, protCertDer) {
|
|
@@ -889,8 +909,10 @@ function _collectExtraCerts(opts, protCertDer) {
|
|
|
889
909
|
* one of `{ key, cert }` (a signature under the sender key over the message, using any registry algorithm: RSA
|
|
890
910
|
* / ECDSA / EdDSA / ML-DSA / SLH-DSA / composite, resolved from the certificate) or `{ mac }` (a PBMAC1
|
|
891
911
|
* shared-secret MAC). The protection is computed over the exact DER of the virtual
|
|
892
|
-
* `ProtectedPart ::= SEQUENCE { header, body }` and self-verified before the message is returned.
|
|
893
|
-
*
|
|
912
|
+
* `ProtectedPart ::= SEQUENCE { header, body }` and self-verified before the message is returned. An
|
|
913
|
+
* embedded `p10cr` request is checked against its own proof-of-possession first: a PKCS#10 whose
|
|
914
|
+
* self-signature does not verify under its subject public key is refused (`cmp/bad-popo`) rather than
|
|
915
|
+
* protected and sent. The emitted PKIMessage round-trips byte-identically through `pki.schema.cmp.parse`.
|
|
894
916
|
*
|
|
895
917
|
* @opts
|
|
896
918
|
* - `key` (Buffer|CryptoKey) + `cert` (Buffer): signature protection under the sender key; `cert` is
|
package/lib/cms-encrypt.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
|
|
18
18
|
var nodeCrypto = require("crypto");
|
|
19
19
|
var asn1 = require("./asn1-der");
|
|
20
|
+
var pkiBuild = require("./pki-build"); // reqDenseArray: reject a sparse/nullish caller array as a typed cms/bad-input
|
|
20
21
|
var oid = require("./oid");
|
|
21
22
|
var x509 = require("./schema-x509");
|
|
22
23
|
var schemaCms = require("./schema-cms");
|
|
@@ -589,8 +590,14 @@ async function _envelopedData(contentBytes, contentStream, cek, ca, contentType,
|
|
|
589
590
|
// design (RFC 5652 sec. 9.2), while for AuthEnvelopedData that value is the unencrypted hash of a
|
|
590
591
|
// plaintext the message exists to conceal (RFC 5083 sec. 2.1 / sec. 5).
|
|
591
592
|
function _assertAuthAttrs(pairs, forbidden) {
|
|
593
|
+
// Reject a sparse/nullish attribute array as a typed error before b.setOf reaches it as a native one.
|
|
594
|
+
// This gate runs before the setOf on both the AuthEnveloped and AuthenticatedData paths.
|
|
595
|
+
// Validate AND SNAPSHOT: reqDenseArray returns a fresh dense copy, and it is that copy the caller must
|
|
596
|
+
// iterate and encode. Iterating the original `pairs` would let an indexed getter that sparsified it
|
|
597
|
+
// during validation slip a hole into b.setOf as a native error; the returned snapshot cannot.
|
|
598
|
+
var dense = pkiBuild.reqDenseArray(pairs, "authAttrs", _err, "cms/bad-input");
|
|
592
599
|
var seenTypes = {};
|
|
593
|
-
|
|
600
|
+
dense.forEach(function (p) {
|
|
594
601
|
var node;
|
|
595
602
|
try { node = asn1.decode(p); } catch (e) { throw _err("cms/bad-input", "an authenticated attribute is not well-formed DER", e); }
|
|
596
603
|
if (node.tagClass !== "universal" || node.tagNumber !== asn1.TAGS.SEQUENCE || !node.children || node.children.length !== 2 ||
|
|
@@ -604,6 +611,7 @@ function _assertAuthAttrs(pairs, forbidden) {
|
|
|
604
611
|
seenTypes[t] = 1;
|
|
605
612
|
if (forbidden && t === forbidden.oid) throw _err("cms/bad-input", forbidden.why);
|
|
606
613
|
});
|
|
614
|
+
return dense;
|
|
607
615
|
}
|
|
608
616
|
|
|
609
617
|
// The one attribute AuthEnvelopedData declines to emit. Its value is the unencrypted one-way hash of
|
|
@@ -623,9 +631,9 @@ async function _authEnvelopedData(contentBytes, contentStream, cek, ca, contentT
|
|
|
623
631
|
throw _err("cms/bad-input", "AuthEnvelopedData with a non-data contentType requires authAttrs (RFC 5083 sec. 2.1)");
|
|
624
632
|
}
|
|
625
633
|
if (opts.authAttrs && opts.authAttrs.length) {
|
|
626
|
-
_assertAuthAttrs(opts.authAttrs, AUTH_ENVELOPED_FORBIDDEN);
|
|
634
|
+
var denseAttrs = _assertAuthAttrs(opts.authAttrs, AUTH_ENVELOPED_FORBIDDEN);
|
|
627
635
|
// authAttrs are transmitted [1] IMPLICIT but MACed under the EXPLICIT SET OF tag (RFC 5083 sec. 2.2).
|
|
628
|
-
var setOf = b.setOf(
|
|
636
|
+
var setOf = b.setOf(denseAttrs);
|
|
629
637
|
aad = setOf; authAttrsDer = b.contextConstructed(1, setOf.subarray(_tlvHeaderLen(setOf)));
|
|
630
638
|
}
|
|
631
639
|
// A 16-octet (128-bit) GCM tag, the strongest ICV and what OpenSSL emits, so the message
|
|
@@ -799,7 +807,7 @@ async function authenticate(content, recipients, opts) {
|
|
|
799
807
|
b.sequence([b.oid(O("messageDigest")), b.setOf([b.octetString(mdDigest)])]),
|
|
800
808
|
];
|
|
801
809
|
if (opts.authAttrs && opts.authAttrs.length) pairs = pairs.concat(opts.authAttrs);
|
|
802
|
-
_assertAuthAttrs(pairs, null);
|
|
810
|
+
pairs = _assertAuthAttrs(pairs, null);
|
|
803
811
|
var setOf = b.setOf(pairs);
|
|
804
812
|
preimage = setOf; // MAC over the 0x31 SET OF
|
|
805
813
|
authAttrsDer = b.contextConstructed(2, setOf.subarray(_tlvHeaderLen(setOf))); // [2] IMPLICIT on the wire
|
package/lib/crl-sign.js
CHANGED
|
@@ -203,7 +203,7 @@ function _idpValue(idp) {
|
|
|
203
203
|
if (idp.onlyContainsAttributeCerts === true) throw _err("crl/bad-idp", "onlyContainsAttributeCerts=TRUE is not permitted for a conforming CRL issuer (RFC 5280 sec. 5.2.5)");
|
|
204
204
|
var children = [];
|
|
205
205
|
if (idp.fullName != null) {
|
|
206
|
-
var entries = Array.isArray(idp.fullName) ? idp.fullName : [idp.fullName];
|
|
206
|
+
var entries = Array.isArray(idp.fullName) ? pkiBuild.reqDenseArray(idp.fullName, "issuingDistributionPoint.fullName", _err, "crl/bad-idp") : [idp.fullName];
|
|
207
207
|
if (!entries.length) throw _err("crl/bad-idp", "issuingDistributionPoint fullName must carry at least one GeneralName");
|
|
208
208
|
// distributionPoint [0] { fullName [0] IMPLICIT GeneralNames }
|
|
209
209
|
children.push(b.contextConstructed(0, b.contextConstructed(0, Buffer.concat(entries.map(_encodeGeneralName)))));
|
|
@@ -243,11 +243,12 @@ function _validatePreEncodedIdp(inner) {
|
|
|
243
243
|
// fullName) or an array of { fullName } distribution points.
|
|
244
244
|
function _freshestValue(spec) {
|
|
245
245
|
if (!Array.isArray(spec) || !spec.length) throw _err("crl/bad-input", "freshestCRL must be a non-empty array of GeneralNames (or { fullName } distribution points)");
|
|
246
|
-
var
|
|
247
|
-
|
|
248
|
-
|
|
246
|
+
var dense = _b.reqDenseArray(spec, "freshestCRL"); // density before every()/map() skip a hole into b.sequence
|
|
247
|
+
var dps = dense.every(function (e) { return e && typeof e === "object" && !Buffer.isBuffer(e) && Object.keys(e).length === 1 && e.fullName != null; })
|
|
248
|
+
? dense.map(function (dp) { return dp.fullName; })
|
|
249
|
+
: [dense];
|
|
249
250
|
return b.sequence(dps.map(function (fullName) {
|
|
250
|
-
var entries = Array.isArray(fullName) ? fullName : [fullName];
|
|
251
|
+
var entries = Array.isArray(fullName) ? _b.reqDenseArray(fullName, "a freshestCRL distribution point fullName") : [fullName];
|
|
251
252
|
if (!entries.length) throw _err("crl/bad-input", "a freshestCRL distribution point must carry at least one GeneralName (GeneralNames is SIZE(1..MAX), RFC 5280 sec. 4.2.1.13)");
|
|
252
253
|
return b.sequence([b.contextConstructed(0, b.contextConstructed(0, Buffer.concat(entries.map(_encodeGeneralName))))]);
|
|
253
254
|
}));
|
|
@@ -345,7 +346,8 @@ function _buildCrlExtensions(spec, ctx) {
|
|
|
345
346
|
function _buildRevoked(entryList, isDelta) {
|
|
346
347
|
if (!Array.isArray(entryList)) throw _err("crl/bad-input", "revoked must be an array of revoked-certificate entries");
|
|
347
348
|
var anyExt = false, seenSerials = {};
|
|
348
|
-
|
|
349
|
+
// Density before the map, which would otherwise skip a hole into b.sequence as a native error.
|
|
350
|
+
var entries = _b.reqDenseArray(entryList, "revoked").map(function (e, idx) {
|
|
349
351
|
if (!e || typeof e !== "object" || Buffer.isBuffer(e)) throw _err("crl/bad-input", "each revoked entry must be an object");
|
|
350
352
|
// Before any field of the entry is encoded, so an unrecognized name is a refusal rather than an
|
|
351
353
|
// entry signed without what it asked for.
|
package/lib/crmf-sign.js
CHANGED
|
@@ -148,7 +148,8 @@ function _buildAttrTypeAndValues(spec, code, label, valueMap) {
|
|
|
148
148
|
if (Array.isArray(spec)) {
|
|
149
149
|
if (!spec.length) throw _err(code, label + " must carry at least one entry");
|
|
150
150
|
var seenA = {};
|
|
151
|
-
|
|
151
|
+
// Density before the map, which would otherwise skip a hole into b.sequence as a native error.
|
|
152
|
+
return b.sequence(pkiBuild.reqDenseArray(spec, label, _err, code).map(function (e, i) {
|
|
152
153
|
var der = _b.reqDer(e, label + " [" + i + "]");
|
|
153
154
|
var n;
|
|
154
155
|
try { n = asn1.decode(der); } catch (err) { throw _err("crmf/bad-input", "pre-encoded " + label + " [" + i + "] is not valid DER", err); }
|
package/lib/ocsp.js
CHANGED
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
|
|
26
26
|
var nodeCrypto = require("crypto");
|
|
27
27
|
var asn1 = require("./asn1-der");
|
|
28
|
+
var pkiBuild = require("./pki-build"); // reqDenseArray: reject a sparse/nullish caller array as a typed ocsp/bad-input
|
|
28
29
|
var oid = require("./oid");
|
|
29
30
|
var x509 = require("./schema-x509");
|
|
30
31
|
var ocspSchema = require("./schema-ocsp");
|
|
@@ -176,7 +177,9 @@ function _buildRequest(query, opts) {
|
|
|
176
177
|
var lightweight = opts.profile === "lightweight";
|
|
177
178
|
var hashName = opts.hashAlgorithm || "sha1";
|
|
178
179
|
if (lightweight && hashName !== "sha1") throw _err("ocsp/bad-input", "the lightweight profile requires a SHA-1 CertID (RFC 5019 sec. 2.1.1)");
|
|
179
|
-
|
|
180
|
+
// A batch array is density-checked before the map below (which would otherwise skip a hole and reach
|
|
181
|
+
// Promise.all/b.sequence with an undefined); a single {cert,issuer} wraps to a dense one-element array.
|
|
182
|
+
var queries = Array.isArray(query) ? pkiBuild.reqDenseArray(query, "queries", _err, "ocsp/bad-input") : [query];
|
|
180
183
|
if (!queries.length) throw _err("ocsp/bad-input", "buildRequest needs at least one { cert, issuer } query");
|
|
181
184
|
if (lightweight && queries.length !== 1) throw _err("ocsp/bad-input", "the lightweight profile permits exactly one Request (RFC 5019 sec. 2.1.1)");
|
|
182
185
|
if (opts.signer && !opts.requestorName) throw _err("ocsp/bad-input", "a signed OCSP request MUST carry requestorName (RFC 6960 sec. 4.1.2)");
|
|
@@ -335,7 +338,7 @@ function _sign(responseData, responder, opts) {
|
|
|
335
338
|
// exit -- sync throw and async rejection alike -- rather than each fallible step needing to
|
|
336
339
|
// remember. `responderKey` is the private copy; it is never the caller's object.
|
|
337
340
|
function _signResponse(responseData, responder, respCert, respCertDer, responderKey, opts) {
|
|
338
|
-
var responses = responseData.responses
|
|
341
|
+
var responses = responseData.responses != null ? pkiBuild.reqDenseArray(responseData.responses, "responses", _err, "ocsp/bad-input") : [];
|
|
339
342
|
if (!responses.length) throw _err("ocsp/bad-input", "a response MUST include at least one SingleResponse (RFC 6960 sec. 4.2.1)");
|
|
340
343
|
|
|
341
344
|
return _responderID(responseData.responderID, respCert).then(function (ridNode) {
|
package/lib/pkcs12-build.js
CHANGED
|
@@ -47,6 +47,7 @@ var cmsSign = require("./cms-sign"); // the signer-descriptor field tables, fo
|
|
|
47
47
|
var cmsDecrypt = require("./cms-decrypt"); // the @internal decryptEnvelopedData seam -- opens a privacy safe off the pkcs12 parser's already-walked (BER-capable) EnvelopedData node
|
|
48
48
|
var schemaPkcs12 = require("./schema-pkcs12");
|
|
49
49
|
var pkix = require("./schema-pkix");
|
|
50
|
+
var pkiBuild = require("./pki-build"); // reqDenseArray: reject a sparse/nullish caller array as a typed pkcs12/bad-input
|
|
50
51
|
var guard = require("./guard-all");
|
|
51
52
|
var intrinsic = require("./guard-intrinsic");
|
|
52
53
|
var frameworkError = require("./framework-error");
|
|
@@ -463,9 +464,13 @@ function _pbeOpts(enc) {
|
|
|
463
464
|
|
|
464
465
|
// SafeContents ::= SEQUENCE OF SafeBag (ordered, and not a SET OF).
|
|
465
466
|
function _buildSafeContents(bags, opts, depth) {
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
467
|
+
// The element cap is enforced BEFORE the density scan, so a huge dense array is rejected in O(1) rather
|
|
468
|
+
// than walked. reqDenseArray then rejects a non-array, or a sparse hole / nullish entry that
|
|
469
|
+
// Array.prototype.map would skip into Buffer.concat as a native error, testing own-property presence
|
|
470
|
+
// and failing at the first bad index.
|
|
471
|
+
if (intrinsic.isArray(bags) && bags.length > C.LIMITS.PKCS12_MAX_ELEMENTS) throw _err("pkcs12/bad-input", "a SafeContents exceeds the element cap " + C.LIMITS.PKCS12_MAX_ELEMENTS);
|
|
472
|
+
var dense = pkiBuild.reqDenseArray(bags, "bags", _err, "pkcs12/bad-input");
|
|
473
|
+
return b.sequence(dense.map(function (bag) { return _buildBag(bag, opts, depth); }));
|
|
469
474
|
}
|
|
470
475
|
|
|
471
476
|
// One AuthenticatedSafe element: a plaintext id-data ContentInfo, an id-encryptedData ContentInfo whose
|
package/lib/pki-build.js
CHANGED
|
@@ -329,6 +329,34 @@ var KU_BIT = {
|
|
|
329
329
|
dataEncipherment: 3, keyAgreement: 4, keyCertSign: 5, cRLSign: 6, encipherOnly: 7, decipherOnly: 8,
|
|
330
330
|
};
|
|
331
331
|
|
|
332
|
+
// A caller-supplied array a builder is about to map over: reject a sparse hole or a nullish entry as a
|
|
333
|
+
// typed error. Array.prototype.map SKIPS a hole, which would otherwise reach Buffer.concat as a native
|
|
334
|
+
// ERR_INVALID_ARG_TYPE and, on a huge sparse length, traverse the empty slots. Tests OWN-property presence
|
|
335
|
+
// (intrinsic.hasOwn) at each index BEFORE reading it, so a polluted Array.prototype[i] cannot slip a hole
|
|
336
|
+
// past the check, and fails fast at the first bad index so the length alone can never force a walk. Takes
|
|
337
|
+
// the caller's error factory E (invoked E(fullCode, msg)) so a builder WITHOUT a makeBuilder instance
|
|
338
|
+
// routes its caller arrays through the same choke point; makeBuilder's own reqDenseArray delegates here.
|
|
339
|
+
function reqDenseArrayImpl(list, what, E, code) {
|
|
340
|
+
if (!_isArray(list)) throw E(code, what + " must be an array");
|
|
341
|
+
var n = list.length;
|
|
342
|
+
// Snapshot each own index into a FRESH dense array and return THAT, never `list`. Reading list[i] can
|
|
343
|
+
// fire a caller-defined indexed accessor that mutates `list` (extending it with holes past the captured
|
|
344
|
+
// n, or deleting an already-checked index); returning `list` would then hand the caller's map a
|
|
345
|
+
// newly-sparse array and the native error this guard exists to prevent. The copy captures the value as
|
|
346
|
+
// read, so a later mutation of `list` cannot reintroduce a hole into what the caller iterates.
|
|
347
|
+
var out = [];
|
|
348
|
+
for (var i = 0; i < n; i++) {
|
|
349
|
+
if (!intrinsic.hasOwn(list, i)) throw E(code, what + "[" + i + "] is missing (a sparse array is not allowed)");
|
|
350
|
+
var v = list[i];
|
|
351
|
+
if (v === undefined || v === null) throw E(code, what + "[" + i + "] is missing (a nullish array entry is not allowed)");
|
|
352
|
+
// defineProperty, not `out[i] = v`: a plain assignment invokes an inherited Array.prototype[i] SETTER
|
|
353
|
+
// ([[Set]]) if one is polluted in, which could leave `out` sparse; [[DefineOwnProperty]] always makes
|
|
354
|
+
// an own data property, so the snapshot is dense regardless of prototype pollution.
|
|
355
|
+
intrinsic.defineProperty(out, i, { value: v, writable: true, enumerable: true, configurable: true });
|
|
356
|
+
}
|
|
357
|
+
return out;
|
|
358
|
+
}
|
|
359
|
+
|
|
332
360
|
// makeBuilder(ctx) -> the bound producing primitives. ctx = { ErrorClass, prefix, O, NS, NAME_SCHEMA,
|
|
333
361
|
// SPKI_SCHEMA, EXT_DECODERS }. `E(kind, msg, cause)` builds a `<prefix>/<kind>` typed error.
|
|
334
362
|
function makeBuilder(ctx) {
|
|
@@ -593,23 +621,9 @@ function makeBuilder(ctx) {
|
|
|
593
621
|
if (guard.bytes.isByteSource(v)) return guard.bytes.snapshotSource(v, ErrorClass, ctx.prefix + "/bad-input", what);
|
|
594
622
|
throw E("bad-input", what + " must be a DER Buffer");
|
|
595
623
|
}
|
|
596
|
-
//
|
|
597
|
-
//
|
|
598
|
-
|
|
599
|
-
// presence at each index BEFORE reading it: a bare `list[i]` on a hole walks the prototype chain, so a
|
|
600
|
-
// polluted `Array.prototype[i]` would read as a value and slip a hole past the check while map still
|
|
601
|
-
// skips it. Fails fast at the first bad index, so the length alone can never force a walk. Returns the
|
|
602
|
-
// validated dense array for the caller to map normally.
|
|
603
|
-
function reqDenseArray(list, what) {
|
|
604
|
-
if (!_isArray(list)) throw E("bad-input", what + " must be an array");
|
|
605
|
-
var n = list.length;
|
|
606
|
-
for (var i = 0; i < n; i++) {
|
|
607
|
-
if (!intrinsic.hasOwn(list, i)) throw E("bad-input", what + "[" + i + "] is missing (a sparse array is not allowed)");
|
|
608
|
-
var v = list[i];
|
|
609
|
-
if (v === undefined || v === null) throw E("bad-input", what + "[" + i + "] is missing (a nullish array entry is not allowed)");
|
|
610
|
-
}
|
|
611
|
-
return list;
|
|
612
|
-
}
|
|
624
|
+
// The bound 2-arg form every makeBuilder consumer calls (`_b.reqDenseArray(list, what)`); it delegates
|
|
625
|
+
// to the standalone guard above with this builder's namespace, so the density rule lives in ONE place.
|
|
626
|
+
function reqDenseArray(list, what) { return reqDenseArrayImpl(list, what, rawErr, ctx.prefix + "/bad-input"); }
|
|
613
627
|
// A caller-supplied DER a builder validates with a PEM-accepting parser and then embeds verbatim with
|
|
614
628
|
// b.raw. Those parsers unwrap PEM from a byte source, so a PEM-armored input (a Buffer straight from
|
|
615
629
|
// fs.readFileSync) passes the parse, but b.raw embeds the raw ASCII armor -- which the enclosing
|
|
@@ -817,4 +831,10 @@ function tbsSerialNumber(cert) {
|
|
|
817
831
|
return asn1.read.integer(tbs.children[hasVersion ? 1 : 0]);
|
|
818
832
|
}
|
|
819
833
|
|
|
820
|
-
|
|
834
|
+
// Frozen so a co-resident cannot reassign an exported guard (e.g. reqDenseArray) to bypass it: the
|
|
835
|
+
// standalone consumers read reqDenseArray off this object at call time, so the object holding it must be
|
|
836
|
+
// immutable, the way the guard-* modules freeze their surfaces.
|
|
837
|
+
// Frozen so a co-resident cannot reassign an exported guard (e.g. reqDenseArray) to bypass it: the
|
|
838
|
+
// standalone consumers read reqDenseArray off this object at call time, so the object holding it must be
|
|
839
|
+
// immutable, the way the guard-* modules freeze their surfaces.
|
|
840
|
+
module.exports = intrinsic.freeze({ makeBuilder: makeBuilder, reqDenseArray: reqDenseArrayImpl, KU_BIT: KU_BIT, tbsNameField: tbsNameField, tbsSerialNumber: tbsSerialNumber });
|
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:fc9ede9f-ba2d-47e7-b43e-add5f0d3de40",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-08-
|
|
8
|
+
"timestamp": "2026-08-30T04:06:00.042Z",
|
|
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.5.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.5.39",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.5.
|
|
25
|
+
"version": "0.5.39",
|
|
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.5.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/pki@0.5.39",
|
|
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.5.
|
|
57
|
+
"ref": "@blamejs/pki@0.5.39",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|