@blamejs/pki 0.5.13 → 0.5.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,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.14 — 2026-08-19
8
+
9
+ `pki.crmf.verifyPop` checks the proof of possession on an inbound certificate request message, the CRMF counterpart to the PKCS#10 check that shipped in 0.5.13.
10
+
11
+ ### Added
12
+
13
+ - `pki.crmf.verifyPop(messages)` verifies the RFC 4211 proof of possession on each `CertReqMsg`, returning one verdict per message plus a top-level `verified` that is true only when every message carried a proof that held. For the `signature` proof the covered bytes are the ones the RFC names: the DER of `poposkInput` when that field is present, and the DER of `certReq` when it is absent (sec. 4.1, and the ASN.1 module, which is where the two readings of that sentence are settled). Verification composes the one path-validation signature engine, with the same algorithm-confusion (RFC 9814 sec. 4) and EdDSA low-order-point gates as the certificate and CRL paths.
14
+ - The proofs that cannot be checked from the message are reported as such. `raVerified` is an RA's assertion that it confirmed possession out of band, so it yields `verified: false` with `method: "raVerified"`, and a caller who trusts that RA opts in by reading `method`. `keyEncipherment` and `keyAgreement` complete over a later protocol exchange, or need the CA's decryption key, so they yield `verified: false` naming the arm. Each verdict carries only what its preimage covers, re-derived from the message's own bytes, so a CA issues from what was checked. `publicKey` is the key possession was proven for. `subject` is the requested name when the signature was over `certReq`, which covers the whole template; a `poposkInput` preimage covers the key and the sender alone, so a subject sitting beside it in the message is unsigned and is withheld with `subjectBound: false` rather than reported next to a passing verdict.
15
+
16
+ ### Changed
17
+
18
+ - `pki.schema.crmf.parse` now records the bytes it read, joining the certificate, CRL, CMS and certification-request parsers, and `pki.crmf.verifyPop` accepts only a result carrying that record. A parsed message set presents the byte range a proof covers and the template a certificate would be issued from as separate properties, so a rebuilt one can hold a genuine requester's signed range beside a substituted subject. As with those parsers, the raw byte views on a parsed result now read from the parser's own copy of the input; passing DER is unaffected, and a parse result used as-is still works.
19
+
20
+ ### Fixed
21
+
22
+ - The `pki.csr.sign` example passed `subject: "CN=device-42"`, which asks for a commonName whose value is the string `CN=device-42` and so issues `CN=CN=device-42`. A bare string is the commonName value throughout the toolkit; the example now says so and passes `"device-42"`.
23
+
7
24
  ## v0.5.13 — 2026-08-19
8
25
 
9
26
  `pki.csr.verify` checks an inbound certification request's proof of possession, so a CA built on this toolkit can tell that the requester holds the key they are asking it to certify.
package/README.md CHANGED
@@ -232,7 +232,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
232
232
  | `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key), subject alternative names, and certificate policies from the spec, taking any other extension as pre-encoded DER. It derives the version from the field set and enforces the serial bounds, the UTCTime/GeneralizedTime cutover, the DER default omissions, and the CA cross-field rules; a violation throws a typed `CertificateError`. Returns DER, or a PEM `CERTIFICATE` with `opts.pem`. Every arm is independently verified by OpenSSL. Parsing stays at `pki.schema.x509.parse` — `sign` |
233
233
  | `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
234
234
  | `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. Parsing stays at `pki.schema.attrcert.parse` — `sign` |
235
- | `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. Parsing stays at `pki.schema.crmf.parse` — `build` |
235
+ | `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
236
236
  | `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, and responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`. Protection is exactly one of `opts.{ key, cert }`, a signature under the sender key with the algorithm resolved from the signer certificate so RSA (PKCS#1 v1.5 / PSS), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, or `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived). Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `session` |
237
237
  | `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the issuer key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
238
238
  | `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
package/lib/crl-verify.js CHANGED
@@ -4,30 +4,21 @@
4
4
  //
5
5
  // @internal -- the single CRL signature-verify seam, shared by pki.path.crlChecker and pki.crl.verify
6
6
  // so both route through one signature engine (algorithm-confusion + EdDSA low-order + composite
7
- // gates) and no second, weaker CRL verifier can drift. path-validate owns that engine
8
- // (_verifyWithSpki) and injects it here at its module load (setEngine). The seam lives in this
9
- // internal module, not on path-validate's module.exports, which keeps it off the public pki.path
10
- // surface: it takes the path-internal SubjectPublicKeyInfo bytes, not a documented issuer shape.
11
- // It is not wired into index.js and is reached only by require.
7
+ // gates) and no second, weaker CRL verifier can drift. The slot, the wiring assertion and the
8
+ // octet-alignment refusal are the shared seam (lib/verify-seam.js). The seam lives in this internal
9
+ // module, not on path-validate's module.exports, which keeps it off the public pki.path surface: it
10
+ // takes the path-internal SubjectPublicKeyInfo bytes, not a documented issuer shape. It is not
11
+ // wired into index.js and is reached only by require.
12
12
 
13
- var guard = require("./guard-all");
14
13
  var frameworkError = require("./framework-error");
14
+ var seam = require("./verify-seam");
15
15
 
16
- var CrlError = frameworkError.CrlError;
17
- var _engine = null; // path-validate's _verifyWithSpki, injected at path-validate's module load via setEngine.
16
+ var _seam = seam.makeSeam("crl-verify", frameworkError.CrlError, "crl/bad-input");
18
17
 
19
- function setEngine(verifyWithSpki) { _engine = verifyWithSpki; }
20
-
21
- // Verify a parsed CRL's signature over its raw tbsCertList bytes under the issuer SubjectPublicKeyInfo DER.
22
- // Fail-closed to false on a non-octet-aligned signature or any engine fault (the engine never throws out).
18
+ // Verify a parsed CRL's signature over its raw tbsCertList bytes under the issuer
19
+ // SubjectPublicKeyInfo DER.
23
20
  function verifyCrlSignature(crl, spkiBytes) {
24
- // pki.crl.sign requires path-validate for the injection side-effect, so the engine is set on every
25
- // route that reaches here through the public verb. A future internal consumer that requires this
26
- // module without it would otherwise call null and surface a raw TypeError out of a verify, which
27
- // names neither the defect nor a verdict, so the wiring is asserted rather than assumed.
28
- if (_engine == null) throw new CrlError("crl/bad-input", "the crl-verify signature engine is not initialized (require pki before use)");
29
- if (!guard.crypto.isOctetAligned(crl.signatureValue)) return Promise.resolve(false); // non-octet-aligned signature
30
- return _engine(crl.signatureAlgorithm, crl.signatureValue.bytes, spkiBytes, crl.tbsBytes);
21
+ return _seam.verify(crl.signatureAlgorithm, crl.signatureValue, spkiBytes, crl.tbsBytes);
31
22
  }
32
23
 
33
- module.exports = { setEngine: setEngine, verifyCrlSignature: verifyCrlSignature };
24
+ module.exports = { setEngine: _seam.setEngine, verifyCrlSignature: verifyCrlSignature };
package/lib/crmf-sign.js CHANGED
@@ -32,6 +32,8 @@ var pkix = require("./schema-pkix");
32
32
  var pkiBuild = require("./pki-build");
33
33
  var frameworkError = require("./framework-error");
34
34
  var guard = require("./guard-all");
35
+ require("./path-validate"); // side-effect: path-validate injects its signature engine into crmf-verify at load
36
+ var crmfVerify = require("./crmf-verify");
35
37
 
36
38
  var CrmfError = frameworkError.CrmfError;
37
39
  var b = asn1.build;
@@ -310,4 +312,126 @@ function _build(spec, key, opts) {
310
312
  */
311
313
  function buildCertTemplate(template) { return _encodeCertTemplate(template, { revocation: true }).der; }
312
314
 
313
- module.exports = { build: build, buildCertTemplate: buildCertTemplate };
315
+ function _coerceMessages(input) {
316
+ return guard.parsed.acceptDerived(input, "crmf", crmf.parse, _err, "crmf/bad-input", "the certificate request messages");
317
+ }
318
+
319
+ // One CertReqMsg's proof of possession, reduced to a verdict. Every return names a method and
320
+ // reports the requested identity, so a refusal is as informative as an acceptance.
321
+ function _verifyOne(msg) {
322
+ var t = msg.certReq && msg.certReq.certTemplate;
323
+ var base = {
324
+ certReqId: msg.certReq && msg.certReq.certReqId,
325
+ subject: (t && t.subject) || null,
326
+ subjectBound: false,
327
+ publicKey: (t && t.publicKey && t.publicKey.bytes) || null,
328
+ };
329
+ function settle(extra) { return Promise.resolve(Object.assign({}, base, extra)); }
330
+
331
+ var popo = msg.popo;
332
+ if (popo == null) {
333
+ return settle({ verified: false, method: null, cryptographicallyVerified: false,
334
+ reason: "the request carries no proof of possession" });
335
+ }
336
+ if (popo.type === "raVerified") {
337
+ // sec. 4: an assertion by the RA that it checked possession out of band. It is not a proof and
338
+ // must not read as one; a caller that trusts its RA opts in by reading `method`.
339
+ return settle({ verified: false, method: "raVerified", cryptographicallyVerified: false,
340
+ reason: "raVerified asserts the RA checked possession out of band -- this is not a proof and cannot be verified from the message" });
341
+ }
342
+ if (popo.type !== "signature") {
343
+ // keyEncipherment / keyAgreement complete over a later protocol exchange (a challenge the
344
+ // verifier does not hold) or need the CA's decryption key, so no verdict is available here.
345
+ return settle({ verified: false, method: popo.type, cryptographicallyVerified: false,
346
+ reason: "a " + popo.type + " proof of possession completes over an exchange this verifier does not hold (RFC 4211 sec. 4.2, 4.3)" });
347
+ }
348
+
349
+ // Which bytes the signature covers is fixed by whether poposkInput is present: the DER of
350
+ // poposkInput when it is, the DER of certReq when it is not (RFC 4211 sec. 4.1, and the ASN.1
351
+ // module on p.33 -- sec. 4.1's case-3 prose says "certificate template" where the field
352
+ // definition and the module both say certReq).
353
+ //
354
+ // The three conformance rules that decide which of those is legitimate are enforced ONE layer
355
+ // down, at parse: poposkInput MUST be omitted exactly when the template carries both subject and
356
+ // publicKey, and poposkInput.publicKey MUST equal the template's (schema-crmf.js, the CertReqMsg
357
+ // build). A message breaking either never reaches this function, and re-checking here would add
358
+ // a branch no input can take while implying the parser might let one through.
359
+ var pin = popo.poposkInput;
360
+ var preimage = pin ? pin.signedBytes : msg.certReq.certReqBytes;
361
+ // The key possession is proven for is the one inside the preimage. With poposkInput that is its
362
+ // own publicKey; sec. 4.1 requires the template to carry the same value, and the parser enforces
363
+ // that whenever the template has one at all. A template that omits it entirely still parses (the
364
+ // equality rule has nothing to compare), so reading the template here would report null for a key
365
+ // whose possession was just proven.
366
+ var spki = pin ? pin.publicKey : base.publicKey;
367
+ // Which fields the verdict may report follows from which bytes were signed. The certReq preimage
368
+ // is the whole CertRequest, so the template's subject rides with it. The poposkInput preimage
369
+ // covers the key and the authInfo sender and never the template, so a subject sitting in the
370
+ // message alongside it is unsigned: reporting it beside `verified: true` would let a CA issue a
371
+ // name the requester proved nothing about. It is withheld, and `subjectBound` says so rather than
372
+ // leaving the absence to look like a request that named no subject.
373
+ var bound = !pin;
374
+ return crmfVerify.verifyPopSignature(popo, spki, preimage).then(function (ok) {
375
+ return Object.assign({}, base, {
376
+ verified: ok === true, method: "signature", cryptographicallyVerified: ok === true,
377
+ subject: bound ? base.subject : null,
378
+ subjectBound: bound,
379
+ publicKey: spki || null,
380
+ reason: ok === true ? undefined : "the proof-of-possession signature does not verify under the requested public key",
381
+ });
382
+ });
383
+ }
384
+
385
+ /**
386
+ * @primitive pki.crmf.verifyPop
387
+ * @signature pki.crmf.verifyPop(messages) -> Promise<{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }>
388
+ * @since 0.5.14
389
+ * @status stable
390
+ * @spec RFC 4211 sec. 4.1
391
+ * @defends crmf-proof-of-possession-bypass (CWE-347)
392
+ * @related pki.crmf.build, pki.csr.verify, pki.schema.crmf.parse
393
+ *
394
+ * Verify the proof of possession on each `CertReqMsg` in a `CertReqMessages`. `messages` is a DER
395
+ * `Buffer` or a parsed result. A CA or RA that issues without this certifies a key the requester
396
+ * may not hold. One verdict is returned per message, in order, and the top-level `verified` is true
397
+ * only when every message carried a proof that verified.
398
+ *
399
+ * For the `signature` proof the covered bytes are the ones RFC 4211 names: the DER of `poposkInput`
400
+ * when that field is present, and the DER of `certReq` when it is absent. Two conformance rules ride
401
+ * with it, both refusals rather than warnings, because each lets a certificate be issued for
402
+ * something nobody signed: `poposkInput` MUST be omitted exactly when the template carries both
403
+ * subject and public key (its preimage covers the key and the sender, never the subject), and
404
+ * `poposkInput.publicKey` MUST be exactly the template's public key (sec. 4.1). Verification
405
+ * composes the one path-validation signature engine, with the same algorithm-confusion (RFC 9814
406
+ * sec. 4) and EdDSA low-order-point gates.
407
+ *
408
+ * The other proofs are reported, never guessed. `raVerified` is an RA's out-of-band assertion, so it
409
+ * returns `verified: false` with `method: "raVerified"` and a caller who trusts that RA opts in by
410
+ * reading `method`. `keyEncipherment` and `keyAgreement` complete over a later protocol exchange, or
411
+ * need the CA's decryption key, so they return `verified: false` naming the arm.
412
+ *
413
+ * Each verdict carries what the verified preimage covers, so a CA issues from what was checked.
414
+ * `publicKey` is the key possession was proven for. `subject` is the requested name when the
415
+ * preimage was the `certReq`, which covers the whole template; when the preimage was `poposkInput`
416
+ * it covers the key and the sender alone, so any subject in the message is unsigned and is withheld
417
+ * with `subjectBound: false`. Bind the name by other means before issuing in that case.
418
+ *
419
+ * @example
420
+ * var pair = await pki.key.generate("Ed25519");
421
+ * var spki = await pki.key.export(pair.publicKey);
422
+ * var pkcs8 = await pki.key.export(pair.privateKey);
423
+ * var req = await pki.crmf.build({ certReqId: 1n,
424
+ * certTemplate: { subject: "device-42", publicKey: spki } }, { key: pkcs8 }); // a bare string is the commonName VALUE
425
+ * var r = await pki.crmf.verifyPop(req);
426
+ * r.verified; // true
427
+ * r.messages[0].method; // "signature"
428
+ */
429
+ function verifyPop(messages) { return guard.async.deferred(function () { return _verifyPop(messages); }); }
430
+ function _verifyPop(messages) {
431
+ var parsed = _coerceMessages(messages);
432
+ return Promise.all(parsed.messages.map(_verifyOne)).then(function (out) {
433
+ return { verified: out.length > 0 && out.every(function (m) { return m.verified === true; }), messages: out };
434
+ });
435
+ }
436
+
437
+ module.exports = { build: build, buildCertTemplate: buildCertTemplate, verifyPop: verifyPop };
@@ -0,0 +1,26 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (c) blamejs contributors
3
+ "use strict";
4
+ //
5
+ // @internal -- the single RFC 4211 proof-of-possession signature seam for an INBOUND CertReqMsg,
6
+ // shared by pki.crmf.verifyPop and by every enrollment path that accepts one. The slot, the wiring
7
+ // assertion and the octet-alignment refusal are the shared seam (lib/verify-seam.js); what is
8
+ // domain-specific is the error class and which bytes the signature covers. It is not wired into
9
+ // index.js and is reached only by require.
10
+
11
+ var frameworkError = require("./framework-error");
12
+ var seam = require("./verify-seam");
13
+
14
+ var _seam = seam.makeSeam("crmf-verify", frameworkError.CrmfError, "crmf/bad-input");
15
+
16
+ // Verify one CertReqMsg's POPOSigningKey signature over `preimage` under `spkiBytes`.
17
+ //
18
+ // `preimage` is chosen by the caller from the two the RFC defines, because the choice is a
19
+ // conformance rule about the message rather than a property of the signature: the DER of
20
+ // poposkInput when that field is present, and the DER of `CertReqMsg certReq` when it is absent
21
+ // (RFC 4211 sec. 4.1 and the ASN.1 module on p.33).
22
+ function verifyPopSignature(popo, spkiBytes, preimage) {
23
+ return _seam.verify(popo.algorithmIdentifier, popo.signature, spkiBytes, preimage);
24
+ }
25
+
26
+ module.exports = { setEngine: _seam.setEngine, verifyPopSignature: verifyPopSignature };
package/lib/csr-sign.js CHANGED
@@ -219,7 +219,8 @@ function _coerceCsr(request) {
219
219
  * var pair = await pki.key.generate("Ed25519");
220
220
  * var spki = await pki.key.export(pair.publicKey);
221
221
  * var pkcs8 = await pki.key.export(pair.privateKey);
222
- * var req = await pki.csr.sign({ subject: "CN=device-42", subjectPublicKey: spki }, { key: pkcs8 });
222
+ * // A bare string is the commonName VALUE, so this asks for CN=device-42.
223
+ * var req = await pki.csr.sign({ subject: "device-42", subjectPublicKey: spki }, { key: pkcs8 });
223
224
  * var r = await pki.csr.verify(req);
224
225
  * // Issue from r.subject / r.subjectPublicKeyInfo / r.attributes, which are the verified fields.
225
226
  * var issued = r.verified
package/lib/csr-verify.js CHANGED
@@ -4,41 +4,24 @@
4
4
  //
5
5
  // @internal -- the single PKCS#10 proof-of-possession signature seam for an INBOUND request, shared
6
6
  // by pki.csr.verify and by every enrollment path that accepts one, so all of them route through one
7
- // signature engine (algorithm-confusion + EdDSA low-order + composite gates) and no second, weaker
8
- // verifier of untrusted requests can drift. The producing side runs its own check over what it just
9
- // signed (pki-build's assertSignatureVerifies, called from csr-sign), which is a different question
10
- // about a key the caller already controls. path-validate owns the engine (_verifyWithSpki) and
11
- // injects it here at its module load (setEngine). The seam lives in this internal module, not on
12
- // path-validate's module.exports, which keeps it off the public pki.path surface. It is not wired
13
- // into index.js and is reached only by require.
14
- //
15
- // It deliberately does NOT compose pki-build's assertSignatureVerifies. That helper is a producing-
16
- // side self-check over a key the caller already controls, and it waives the EdDSA low-order-point
17
- // gate on exactly that reasoning. An inbound request is untrusted input, where the gate is the
18
- // point.
7
+ // signature engine and no second, weaker verifier of untrusted requests can drift. The producing
8
+ // side runs its own check over what it just signed (pki-build's assertSignatureVerifies, called
9
+ // from csr-sign), which is a different question about a key the caller already controls. The slot,
10
+ // the wiring assertion and the octet-alignment refusal are the shared seam (lib/verify-seam.js). It
11
+ // is not wired into index.js and is reached only by require.
19
12
 
20
- var guard = require("./guard-all");
21
13
  var frameworkError = require("./framework-error");
14
+ var seam = require("./verify-seam");
22
15
 
23
- var CsrError = frameworkError.CsrError;
24
- var _engine = null; // path-validate's _verifyWithSpki, injected at path-validate's module load via setEngine.
25
-
26
- function setEngine(verifyWithSpki) { _engine = verifyWithSpki; }
16
+ var _seam = seam.makeSeam("csr-verify", frameworkError.CsrError, "csr/bad-input");
27
17
 
28
18
  // Verify a parsed certification request's signature over its exact certificationRequestInfo bytes
29
19
  // under the subjectPKInfo the request carries. A CSR has no issuer: the verifying key is the one
30
20
  // inside the signed preimage, which is what makes the signature a proof of possession and nothing
31
- // more. Fail-closed to false on a non-octet-aligned signature or any engine fault (the engine
32
- // never throws out).
21
+ // more.
33
22
  function verifyCsrSignature(parsed) {
34
- // pki.csr.sign requires path-validate for the injection side-effect, so the engine is set on every
35
- // route that reaches here through the public verb. A future internal consumer that requires this
36
- // module without it would otherwise call null and surface a raw TypeError out of a verify, which
37
- // names neither the defect nor a verdict, so the wiring is asserted rather than assumed.
38
- if (_engine == null) throw new CsrError("csr/bad-input", "the csr-verify signature engine is not initialized (require pki before use)");
39
- if (!guard.crypto.isOctetAligned(parsed.signatureValue)) return Promise.resolve(false); // non-octet-aligned signature
40
- return _engine(parsed.signatureAlgorithm, parsed.signatureValue.bytes,
23
+ return _seam.verify(parsed.signatureAlgorithm, parsed.signatureValue,
41
24
  parsed.subjectPublicKeyInfo.bytes, parsed.certificationRequestInfoBytes);
42
25
  }
43
26
 
44
- module.exports = { setEngine: setEngine, verifyCsrSignature: verifyCsrSignature };
27
+ module.exports = { setEngine: _seam.setEngine, verifyCsrSignature: verifyCsrSignature };
@@ -513,12 +513,14 @@ var _CLAIMS = {
513
513
  crl: ["tbsBytes", "revokedCertificates", "crlExtensions"],
514
514
  cms: ["signerInfos", "encapContentInfo"],
515
515
  csr: ["certificationRequestInfoBytes", "subjectPublicKeyInfo", "attributes"],
516
+ crmf: ["messages"],
516
517
  };
517
518
  var _WHY = {
518
519
  certificate: "the signed byte range, the signature and the fields that range encodes are separate properties of a parsed object, so a rebuilt certificate (Object.assign, spread, a JSON round-trip) could have them describe different certificates: keep a real CA certificate's signed bytes and signature, replace only its public key, and every field is still well-formed",
519
520
  crl: "the signed byte range, the revocation list and the scope extensions are separate properties of a parsed object, so a rebuilt CRL could have them describe different CRLs: empty the revocation list and a correctly signed CRL reports a revoked certificate as good",
520
521
  cms: "the signed attribute bytes, the signature, the encapsulated content and the certificates that verify it are separate properties of a parsed object, so a rebuilt SignedData could have them describe different messages: keep a genuine signer's signature and signed attributes, put other content beside them, and every part of the check passes for content that signer never signed",
521
522
  csr: "the signed byte range, the key it proves possession of and the subject and requested extensions that range encodes are separate properties of a parsed object, so a rebuilt request could have them describe different requests: keep a genuine requester's signed bytes and signature, replace only the subject or the extensionRequest, and the proof of possession still verifies while the certificate a CA issues from those fields is for a name and a set of extensions nobody signed",
523
+ crmf: "the byte range a proof of possession covers, the key that possession is proven for and the subject a CA will issue to are separate properties of a parsed object, so a rebuilt message set could have them describe different requests: keep a genuine requester's signed range and signature, replace only the certTemplate subject or public key, and the proof still verifies while the certificate is issued for a name and a key nobody proved anything about",
522
524
  };
523
525
  // @enforced-by guard-shape-reinlined -- shares the fromTrustedSource shape it composes: a door that
524
526
  // tests the claim fields itself, instead of routing here, is the re-inline both replace.
@@ -542,7 +544,7 @@ function acceptDerived(input, kind, parse, E, code, label) {
542
544
  throw E(code, who + " must be a " + kind + " DER Buffer, a PEM string, or a parsed " + kind);
543
545
  }
544
546
  }
545
- var ns = { certificate: "x509", crl: "crl", cms: "cms", csr: "csr" }[kind];
547
+ var ns = { certificate: "x509", crl: "crl", cms: "cms", csr: "csr", crmf: "crmf" }[kind];
546
548
  return fromTrustedSource(input, kind, claims, parse, E, code,
547
549
  who + " must be its DER bytes, a PEM string, or an unmodified pki.schema." + ns +
548
550
  ".parse result: " + _WHY[kind]);
@@ -41,6 +41,7 @@ var ocsp = require("./schema-ocsp");
41
41
  var ocspVerify = require("./ocsp-verify");
42
42
  var crlVerify = require("./crl-verify");
43
43
  var csrVerify = require("./csr-verify");
44
+ var crmfVerify = require("./crmf-verify");
44
45
  var cmpVerify = require("./cmp-verify");
45
46
  var cmsVerify = require("./cms-verify");
46
47
  var cmpSession = require("./cmp-session");
@@ -2275,6 +2276,10 @@ crlVerify.setEngine(_verifyWithSpki);
2275
2276
  // EdDSA low-order-point gate because it runs over a key the caller already controls.
2276
2277
  csrVerify.setEngine(_verifyWithSpki);
2277
2278
 
2279
+ // And for RFC 4211 proof of possession, so an inbound CertReqMsg is checked through the same one
2280
+ // engine as the PKCS#10 form of the same question.
2281
+ crmfVerify.setEngine(_verifyWithSpki);
2282
+
2278
2283
  // ---- the OCSP revocation checker (RFC 6960) -------------------------------
2279
2284
 
2280
2285
  // The OCSP response-verification core (responder authorization + CertID binding + currency +
@@ -489,10 +489,13 @@ var CERT_REQ_MESSAGES = schema.seqOf(CERT_REQ_MSG, {
489
489
  * var m = pki.schema.crmf.parse(der);
490
490
  * m.messages[0].certReq.certTemplate.subject.dn; // "CN=req.example"
491
491
  */
492
- var parse = pkix.makeParser({
492
+ // Recording, because pki.crmf.verifyPop reaches a verdict from this result: the byte range a
493
+ // proof of possession covers, the key that possession is proven for, and the subject the CA will
494
+ // issue to are separate properties here, so the record is what binds them to one another.
495
+ var parse = pkix.makeRecordingParser({
493
496
  pemLabel: null, PemError: PemError, ErrorClass: CrmfError, prefix: "crmf",
494
497
  what: "certificate request message", topSchema: CERT_REQ_MESSAGES, ns: NS,
495
- });
498
+ }, "crmf");
496
499
 
497
500
  /**
498
501
  * @primitive pki.schema.crmf.pemDecode
@@ -0,0 +1,47 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (c) blamejs contributors
3
+ "use strict";
4
+ //
5
+ // @internal -- the injected-signature-engine seam, once.
6
+ //
7
+ // A CRL, a PKCS#10 certification request and an RFC 4211 CertReqMsg all verify an untrusted
8
+ // signature through the same path-validation engine, which carries the algorithm-confusion, EdDSA
9
+ // low-order and composite gates. None of them may reach that engine through pki.path's public
10
+ // surface, so each holds a slot that path-validate fills at its module load. Each was writing the
11
+ // same slot, the same wiring assertion and the same octet-alignment refusal. That shape lives here
12
+ // now. A format module supplies what is its own: an error class, a code, and the preimage bytes.
13
+ //
14
+ // The producing side of each format asks a different question, through pki-build's
15
+ // assertSignatureVerifies: whether the signature it has just made verifies under a key the caller
16
+ // already controls. That check waives the EdDSA low-order-point gate for that reason, and is a
17
+ // separate mechanism from this one.
18
+
19
+ var guard = require("./guard-all");
20
+
21
+ // makeSeam(name, ErrorClass, code) -> { setEngine, verify }.
22
+ //
23
+ // `verify(sigAlg, signature, spkiBytes, preimage)` takes the signature as the parsed BIT STRING
24
+ // ({ unusedBits, bytes }), because the octet-alignment refusal is part of the contract: a signature
25
+ // carrying unused bits is malformed for every algorithm these formats admit, and a caller that had
26
+ // already discarded `unusedBits` could not be held to it.
27
+ function makeSeam(name, ErrorClass, code) {
28
+ var engine = null;
29
+
30
+ return {
31
+ setEngine: function (verifyWithSpki) { engine = verifyWithSpki; },
32
+
33
+ verify: function (sigAlg, signature, spkiBytes, preimage) {
34
+ // Each format's producing verb requires path-validate for the injection side-effect, so the
35
+ // engine is set on every route that reaches here through a public verb. A future internal
36
+ // consumer that required a seam without it would otherwise call null and surface a raw
37
+ // TypeError out of a verify, which names neither the defect nor a verdict.
38
+ if (engine == null) {
39
+ throw new ErrorClass(code, "the " + name + " signature engine is not initialized (require pki before use)");
40
+ }
41
+ if (!guard.crypto.isOctetAligned(signature)) return Promise.resolve(false);
42
+ return engine(sigAlg, signature.bytes, spkiBytes, preimage);
43
+ },
44
+ };
45
+ }
46
+
47
+ module.exports = { makeSeam: makeSeam };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.5.13",
3
+ "version": "0.5.14",
4
4
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:4bd2d60e-9fd1-4008-8d42-7a9d790812ac",
5
+ "serialNumber": "urn:uuid:0c7ff68d-1729-433b-af07-52f61820d0df",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-08-19T09:39:41.731Z",
8
+ "timestamp": "2026-08-19T11:05:15.498Z",
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.13",
22
+ "bom-ref": "@blamejs/pki@0.5.14",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.5.13",
25
+ "version": "0.5.14",
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.13",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.5.14",
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.13",
57
+ "ref": "@blamejs/pki@0.5.14",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]