@blamejs/pki 0.6.47 → 0.6.48

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,19 @@ All notable changes to `@blamejs/pki` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## v0.6.48 — 2026-09-07
8
+
9
+ A CMC enrollment request can be authenticated by a shared secret instead of a signature.
10
+
11
+ ### Added
12
+
13
+ - pki.cmc.build(spec, { mac: { identifier, secret } }) carries a Full PKI Request in a CMS AuthenticatedData rather than a SignedData (RFC 5272 section 3.2). The recipient is the PasswordRecipientInfo that section requires, the MAC key is generated for the message, and the encapsulated content type stays id-cct-PKIData. The secret is taken as a string or as bytes. The request carries the identifier in an Identification control, since a PasswordRecipientInfo names no recipient and that control is what lets an authority holding secrets for many clients find the right one (RFC 5272 section 6.2.3). A name given anywhere else in the same request, through spec.identityProof.identity or an Identification control written into spec.controls, must be that same name: one request names one client, so a second name is refused rather than chosen between, and a control the caller already wrote is kept rather than duplicated. Because carrying that control also changes how an Identity Proof witness is derived, from the secret alone to the secret and the identity together (RFC 5272 section 6.2.3), a request that carries both derives the witness with the name it carries, whichever of the three places named it. A request also carries one secret: the one its MAC is keyed from and the one its Identity Proof is computed from are the same, and two different ones are refused. Naming a signature and a shared secret in the same call is refused: a request has one carrier, and a client with a key to sign with does not need the other. A renewal cannot use the shared-secret carrier at all, because a renewal carries no Identification or Identity Proof control and its identity comes instead from being signed with the certificate being renewed (RFC 5272 section 3.2(a)); a shared secret names no certificate, so that request would assert an identity by nothing. Every copy the toolkit makes of the secret and of the derived key is wiped once the message is built.
14
+ - The key is derived from the identifier encoded as UTF-8 followed by the shared secret (RFC 5272 section 3.2(c)), and pki.cmc.verify applies the same derivation to an opts.recipient given as { identifier, secret }. An implementation that derived the key itself still passes raw key material and is read as before. Deriving it in one place is what keeps a request this toolkit builds and a response it authenticates agreeing about the key: the secret alone is not it, and neither is the identifier alone.
15
+
16
+ ### Changed
17
+
18
+ - An AuthenticatedData Full PKI Request this toolkit emits is read by OpenSSL: the interop suite checks that openssl cms accepts the message and that openssl names the AuthenticatedData carrier, the id-cct-PKIData content type and the password recipient's key-encryption algorithm from its own tables.
19
+
7
20
  ## v0.6.47 — 2026-09-06
8
21
 
9
22
  A CMP enrollment left waiting can be picked up by a later process instead of started again.
package/README.md CHANGED
@@ -227,7 +227,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
227
227
  | `pki.jose` | Flattened JWS (RFC 7515) and JWK thumbprints (RFC 7638). `sign` and `verify` run a Flattened JWS against declarative profiles (ACME outer, EAB inner, keyChange inner) that carry the required and forbidden header rules as data. `base64url` is the strict RFC 4648 §5 codec, rejecting padding, non-alphabet characters, and non-canonical trailing bits. `parseJson` is a bounded reader that refuses duplicate members at any depth. `thumbprint` is the RFC 7638 / 8037 / 9964 canonical digest. The algorithm registry binds each `alg` to its key type (ES/RS/PS/EdDSA/ML-DSA), leaving no code path for `alg:none`, an RS256→HS256 key confusion, or an all-zero ECDSA signature; `assertPublicJwk` refuses a JWK carrying private material, so an exported private key is never published. `opts.key` names the key a message must be signed under and governs: where the profile also permits an embedded header `jwk`, the two must be the same key — compared as RFC 7638 thumbprints, so member order cannot make equal keys differ — and a disagreement is refused rather than resolved in the message's favor. `keySource` reports which key answered, since a signature checked against a key you named is a different claim from one checked against the key the message carried — `sign`, `verify`, `base64url`, `parseJson`, `thumbprint`, `assertPublicJwk` |
228
228
  | `pki.acme` | ACME (RFC 8555 / 8737 / 8738 / 9773). `client(directoryUrl, opts)` is a stateful client driving a live CA directory over `pki.transport`: `newAccount`, `newOrder`, `newAuthz`, `getOrder`, `getAuthorization`, `getChallenge`, `respondToChallenge`, `finalize`, `pollOrder`, `pollAuthorization`, and `downloadCertificate` walk the issuance flow, with `newAuthz` pre-authorizing a single identifier (§7.4.1) and `downloadCertificate` binding the issued certificate to the order — its key, its identifiers, or both; at least one is required by default and the result reports `boundToKey` / `boundToIdentifiers` — before choosing among alternate chains (`Link rel="alternate"`, §7.4.2, via a `selectChain` predicate bounded by `maxAlternates`). `revokeCert` (account-key or certificate-key signed), `keyChange`, `updateAccount` (change the account contacts, §7.3.2), `listOrders` (the account's orders list, following the §7.1.2.1 `Link rel="next"` pagination bounded by a page cap and confined to the orders origin), `deactivateAccount`, `deactivateAuthorization`, `renewalInfo` (ARI), `renewalWindow` (the RFC 9773 §4.2/4.3 renewal decision), and `scheduleRenewal` (the §4.1 auto-sleeping renewal loop that sleeps until the selected instant and refetches until it is time to renew, stopping at the certificate's notAfter) 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 (and, when `opts.resignKeys` supplies caller-approved alternative account-key algorithms, a bounded RFC 8555 §6.2 badSignatureAlgorithm re-sign that the CA's advertised list can only filter, never widen, so it cannot force a weaker algorithm), reads are POST-as-GET, polling is bounded and sleeps on a Retry-After via an injectable sleeper capped by a poll count and a total-wait budget, and every response body is size-capped. The transport is injectable via `opts.transport`. Over the message layer it composes resource-object validators (closed status enums, conditional-required fields, unknown fields ignored), the three §7.1.6 state machines, the request builders (newAccount with External Account Binding, newOrder with `replaces`, finalize with a CSR identifier-set match and account-key-reuse rejection, challenge responses, deactivation, revokeCert in both key modes, the keyChange nested JWS, POST-as-GET), the http-01 / dns-01 / tls-alpn-01 challenge computations, the dns and ip identifier validators, and the ARI certID with serial sign-padding preserved — `client`, `validate`, `identify`, `assertTransition`, the builders, `keyAuthorization`, `http01`, `dns01`, `tlsAlpn01Extension`, `verifyTlsAlpn01`, `ariCertId` |
229
229
  | `pki.schema.smime` | S/MIME ESS signed-attribute values (RFC 5035 / RFC 8551). `parseSigningCertificate` and `parseSigningCertificateV2` bind a signature to its signing certificate (cert hash, hash algorithm, issuer `GeneralNames` and serial); `parseSmimeCapabilities` decodes the ordered capability list; `decodeAttribute` dispatches a CMS attribute by OID, enforcing the single-value rule and deferring on unknown types. A companion decoder for CMS signed attributes rather than an auto-routed format — `parseSigningCertificate`, `parseSigningCertificateV2`, `parseSmimeCapabilities`, `decodeAttribute` |
230
- | `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` |
230
+ | `pki.cmc` | Build and interpret CMC messages (RFC 5272). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and carries it either way RFC 5272 §3.2 allows: `{ cert, key }` signs it, while `{ mac: { identifier, secret } }` authenticates it under a shared secret for a client that holds no key yet, using the PasswordRecipientInfo that section requires and deriving the key from the identifier followed by the secret. A signed request goes through `pki.cms.sign` under `id-cct-PKIData`. A PKCS#10 (`tcr`) request is verified against its own proof-of-possession before signing, so a request whose self-signature does not verify under its subject public key is refused rather than signed into a message a CA would reject. Body-part identifiers are unique across the whole message and never the reserved 0; a caller's clash is refused rather than renumbered, since a control may already reference it. An Identity Proof V2 witness is computed over the `reqSequence` bytes exactly as emitted (§6.2.1 step 1) rather than a re-serialization, a POP Link Witness is emitted only alongside the POP Link Random control §6.3.1.1 requires beside it, and a renewal carries neither Identification nor Identity Proof in either version. `verify(response, sent)` takes what the CA returned plus the state the client retained and reduces it to one terminal outcome: `issued`, `pending`, `confirm-required`, `pop-required`, or `rejected`. It binds the exchange first — Transaction Identifier, the Sender and Recipient Nonce echo compared in constant time and by full value so a truncation cannot match, and the Data Return echo — with each check applying only if the client sent that half, and, once sent, an absent or differing echo being a refusal, which is the replay defense. `bodyPartIDs` extends the same rule to what the response is about: a status reporting on a body part the request never sent is refused, which the transaction and nonce cannot catch, because a server can echo both correctly while answering about a different message. Several status controls are permitted and the worst governs, so a failure cannot hide behind an earlier success; the absence of any status control is success, per §6.1.2. The carrier's signature must verify (§3.2.1.3.4): a conforming SignedData carries its own signer certificate, so the ordinary build-then-verify flow needs nothing extra and the verdict reports `signatureVerified: true`. Where the signer is found nowhere the posture is fail-closed with a named opt-out — supply `certs` with the responder's certificate, or `allowUnverified: true`, in which case the verdict reports `signatureVerified: false`. Doing neither is refused, the opt-out never excuses a signature that is present and wrong, and a carrier with no signer at all is refused outright. The response's own `cmsSequence` and `otherMsgs` come back raw, since a request whose only arm was the other-message form has no certificate to return and §4.1 puts its answer there. Nothing is trusted: issued certificates are read from the CMS certificate bag (§4.2) and surfaced raw for `pki.path.validate`, and a Publish Trust Anchors control is surfaced with `trusted: false` rather than added to a store — `build`, `verify` |
231
231
  | `pki.schema.cmc` | Decode CMC messages (RFC 5272 as updated by RFC 6402): a Full PKI Request (`PKIData`) or Full PKI Response (`PKIResponse`) riding inside a CMS SignedData, reached by the encapsulated content type (`id-cct-PKIData` / `id-cct-PKIResponse`). Controls are surfaced in wire order with their values raw, so an unrecognized one is data rather than a fault. Tagged requests decode across all three arms. The status verdicts (`CMCStatusInfo` v1 and `CMCStatusInfoV2`) are collected as an ordered list, and the RFC 6402 two-module `OtherStatusInfo` ambiguity — `pendInfo` and `extendedFailInfo` are both untagged SEQUENCEs in the 1988 module, told apart only by their first element — is resolved by inspection and refused when it cannot be told apart. Body-part identity is unique across the whole message rather than per sequence, 0 is reserved as the reference to the enclosing PKIData, and the `reqSequence` bytes are surfaced exactly as they appeared so an Identity Proof witness is computed over the wire bytes. A companion decoder for CMS content rather than an auto-routed format — `parse`, `parsePkiData`, `parsePkiResponse` |
232
232
  | `pki.schema.engine` | The declarative ASN.1 structure-schema engine every format parser composes — `walk`, `encode`, `embeddedDer`, and the schema combinators |
233
233
  | `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. An `opts.direction` of `"reverse"` searches from a trust anchor toward the leaf (RFC 4158 §3.1), narrower when the anchor set is small and the leaf's issuer options fan out, and `"auto"` picks the direction by first-hop fan-out; reverse building reuses the same pool, visited set, caps, and `validate` gate, so the direction changes only search order, and the anchor is excluded from the returned path. Reverse building is pool-only and does not combine with `fetchAia`. When `opts.userInitialPolicySet` names acceptable certificate-policy OIDs and more than one path validates, build returns the accepted path whose user-constrained policy set best satisfies that set (RFC 4158 §4) rather than the first accepted path, the ranking bounded by the same candidate cap and a malformed set refused with `path/bad-input`; an `anyPolicy` entry is unconstrained and returns the first accepted path. In a mesh of cross-certified domains, where many candidates chain by name to the same place, a candidate is ranked by how many leading relative distinguished names it shares with the name the search is heading for (§3.5.16 and the §3.5.19 reverse method), so a certificate in the target's own domain is tried before one from a cross-certified domain, and forward building sorts a candidate under every candidate that can complete the path when its path length constraint cannot cover the certificates already below it (§3.5.7), an ordering that outranks the other hints rather than competing with them. No candidate is removed and an unbounded search still reaches every path the pool holds; a bounded one spends `maxCandidatesConsidered` on whichever branches the order steers it to. Pure and re-entrant — `validate`, `build`, `crlChecker`, `ocspChecker` |
package/lib/cmc-build.js CHANGED
@@ -15,9 +15,14 @@ var crmf = require("./schema-crmf");
15
15
  var cmcFmt = require("./schema-cmc");
16
16
  var oid = require("./oid");
17
17
  var cmsSign = require("./cms-sign");
18
+ var cmsEncrypt = require("./cms-encrypt");
18
19
  var guard = require("./guard-all");
19
20
  var intrinsic = require("./guard-intrinsic");
20
21
  var _hasOwn = intrinsic.hasOwn;
22
+ var _isArray = intrinsic.isArray;
23
+ var _isBuffer = intrinsic.isBuffer;
24
+ var _bufferFrom = intrinsic.bufferFrom;
25
+ var _bufferConcat = intrinsic.bufferConcat;
21
26
  var frameworkError = require("./framework-error");
22
27
 
23
28
  var CmcError = frameworkError.CmcError;
@@ -100,6 +105,61 @@ var KNOWN_REQUEST_KEYS = intrinsic.assign(intrinsic.create(null), { tcr: 1, crm:
100
105
  var KNOWN_CONTROL_KEYS = intrinsic.assign(intrinsic.create(null), { type: 1, value: 1 });
101
106
  var KNOWN_IDENTITY_PROOF_KEYS = intrinsic.assign(intrinsic.create(null), { identity: 1, secret: 1 });
102
107
  var KNOWN_POP_LINK_KEYS = intrinsic.assign(intrinsic.create(null), { secret: 1 });
108
+ var KNOWN_MAC_KEYS = intrinsic.assign(intrinsic.create(null), { identifier: 1, secret: 1 });
109
+ var KNOWN_MAC_CARRIER_KEYS = intrinsic.assign(intrinsic.create(null), { mac: 1 });
110
+ var UTF8_STRING_TAG = 12;
111
+
112
+ /** @internal Whether two caller-supplied secrets are the same secret, comparing the bytes each spells
113
+ * out so a string and the same bytes are not read as two different credentials. Compared in constant
114
+ * time: the two values come from one caller here, but the primitive is the one this toolkit compares
115
+ * secret-derived bytes with everywhere. */
116
+ function _sameSecret(a, byIdentity) {
117
+ var ab = null, bb = null;
118
+ try {
119
+ ab = _secretCopy(a, "the shared secret");
120
+ bb = _secretCopy(byIdentity, "the identityProof secret");
121
+ return ab !== null && bb !== null && ab.length === bb.length && guard.crypto.constantTimeEqual(ab, bb);
122
+ } finally {
123
+ /** @internal Both copies, on every exit: one input being unusable is the path that leaves the other
124
+ * one allocated, and a comparison that refuses is still a comparison that copied. */
125
+ var made = [];
126
+ if (ab) guard.list.append(made, ab);
127
+ if (bb) guard.list.append(made, bb);
128
+ if (made.length) guard.secret.zeroizeAll(made, CmcError, "cmc/bad-input", "the compared shared-secret copies");
129
+ }
130
+ }
131
+ function _secretCopy(v, what) {
132
+ if (typeof v === "string") return _bufferFrom(v, "utf8");
133
+ if (guard.bytes.isByteSource(v)) return guard.bytes.snapshotSource(v, CmcError, "cmc/bad-input", what);
134
+ return null;
135
+ }
136
+
137
+ /** @internal The key a shared-secret carrier derives its MAC key from: the identifier encoded as UTF-8
138
+ * followed by the shared secret (RFC 5272 sec. 3.2(c)). Both halves of the toolkit read this one
139
+ * function, so a request it builds and a message it authenticates derive the same bytes. The caller
140
+ * owns the returned buffer and wipes it. */
141
+ function macPassword(mac) {
142
+ if (!mac || typeof mac !== "object" || _isArray(mac) || _isBuffer(mac)) {
143
+ throw E("cmc/bad-input", "a shared-secret carrier is { identifier, secret } (RFC 5272 sec. 3.2)");
144
+ }
145
+ guard.identifier.assertKnownKeys(mac, KNOWN_MAC_KEYS, E, "cmc/bad-input", "unknown shared-secret field ");
146
+ if (typeof mac.identifier !== "string" || mac.identifier.length === 0) {
147
+ throw E("cmc/bad-input", "a shared-secret carrier needs the identifier the authority knows the client by, as a non-empty string (RFC 5272 sec. 3.2)");
148
+ }
149
+ if (typeof mac.secret !== "string" && !guard.bytes.isByteSource(mac.secret)) {
150
+ throw E("cmc/bad-input", "a shared-secret carrier needs the secret as a string or bytes (RFC 5272 sec. 3.2)");
151
+ }
152
+ var secretBytes = typeof mac.secret === "string" ? _bufferFrom(mac.secret, "utf8")
153
+ : guard.bytes.snapshotSource(mac.secret, CmcError, "cmc/bad-input", "the shared secret");
154
+ if (secretBytes.length === 0) {
155
+ guard.secret.zeroize(secretBytes, CmcError, "cmc/bad-input", "the shared secret");
156
+ throw E("cmc/bad-input", "a shared-secret carrier needs a non-empty secret (RFC 5272 sec. 3.2)");
157
+ }
158
+ var idBytes = _bufferFrom(mac.identifier, "utf8");
159
+ var joined = _bufferConcat([idBytes, secretBytes]);
160
+ guard.secret.zeroizeAll([idBytes, secretBytes], CmcError, "cmc/bad-input", "the shared-secret encoding");
161
+ return joined;
162
+ }
103
163
 
104
164
  function fixedRequestId(req, index) {
105
165
  if (!req || typeof req !== "object") throw E("cmc/bad-input", "each request must be an object");
@@ -373,7 +433,17 @@ async function _build(spec, signer, opts) {
373
433
  "a renewal request carries no " + forbidden + " control (RFC 5272 sec. 3.2 (a))");
374
434
  }
375
435
  }
376
- var renewalSigners = Array.isArray(signer) ? signer : [signer];
436
+ /** @internal A renewal carries no Identification or Identity Proof control because, in sec. 3.2(a)'s
437
+ * words, "the same information is provided by the use of an existing certificate from a CA when
438
+ * signing the PKI Request". A shared secret authenticates the message without naming any
439
+ * certificate, so a renewal carried that way would assert an identity by nothing at all. */
440
+ if (signer && typeof signer === "object" && !_isArray(signer) && signer.mac != null) {
441
+ throw E("cmc/bad-signer",
442
+ "a renewal request is signed with the certificate being renewed, which is what carries the " +
443
+ "original identity in place of the Identification and Identity Proof controls (RFC 5272 sec. 3.2 (a)); " +
444
+ "a shared secret names no certificate, so it cannot renew");
445
+ }
446
+ var renewalSigners = _isArray(signer) ? signer : [signer];
377
447
  for (var si = 0; si < renewalSigners.length; si++) {
378
448
  var rs = renewalSigners[si];
379
449
  if (rs && rs.cert == null && rs.spki != null) {
@@ -385,6 +455,9 @@ async function _build(spec, signer, opts) {
385
455
  }
386
456
 
387
457
  var controls = [];
458
+ /** @internal The names a caller-written Identification control gives this client, collected as those
459
+ * controls are encoded so the name checked is the name carried (RFC 5272 sec. 6.2.3). */
460
+ var controlIdentifiers = [], controlIdentificationCount = 0, controlIdentifierUnreadable = false;
388
461
  callerControls.forEach(function (c) {
389
462
  if (!c || typeof c !== "object" || c.type == null || c.value == null) {
390
463
  throw E("cmc/bad-input", "each control is { type, value }");
@@ -393,7 +466,26 @@ async function _build(spec, signer, opts) {
393
466
  return "unknown field " + JSON.stringify(k) + " on a control -- a control is { type, value }, " +
394
467
  "and its bodyPartID is allocated by the builder";
395
468
  });
396
- controls.push(encodeControl(_oidOf(c.type), [_der(c.value, "a control value")], ids));
469
+ /** @internal Taken once. A control is a caller object, so reading `type` or `value` a second time
470
+ * can answer differently than it did here, and what this request is checked against has to be what
471
+ * it carries. The Identification name below is read off THESE bytes for the same reason. */
472
+ var controlType = _oidOf(c.type);
473
+ var controlValue = _der(c.value, "a control value");
474
+ if (controlType === OID_IDENTIFICATION) {
475
+ controlIdentificationCount += 1;
476
+ var idNode;
477
+ try { idNode = asn1.decode(controlValue); }
478
+ catch (_e) { controlIdentifierUnreadable = true; }
479
+ /** @internal The control is a UTF8String (RFC 5272 sec. 6.2.3). Another string type carrying the
480
+ * same characters is a different value on the wire, so it cannot stand in for the control this
481
+ * request needs while a strict authority refuses the message. */
482
+ if (idNode && idNode.tagClass === "universal" && idNode.tagNumber === UTF8_STRING_TAG) {
483
+ guard.list.append(controlIdentifiers, asn1.read.string(idNode));
484
+ } else {
485
+ controlIdentifierUnreadable = true;
486
+ }
487
+ }
488
+ controls.push(encodeControl(controlType, [controlValue], ids));
397
489
  });
398
490
 
399
491
  _assertNoDuplicateBinding(callerControls, spec);
@@ -410,6 +502,22 @@ async function _build(spec, signer, opts) {
410
502
  [b.octetString(_der(spec.dataReturn, "spec.dataReturn"))], ids));
411
503
  }
412
504
 
505
+ /** @internal The name the request gives the authority for this client, from whichever of the two
506
+ * places names it. Read before either control is emitted, so the pair can be compared. */
507
+ var macIdentifier = signer && typeof signer === "object" && !_isArray(signer) && signer.mac != null &&
508
+ typeof signer.mac === "object" && typeof signer.mac.identifier === "string" ? signer.mac.identifier : null;
509
+ var identityIdentifier = spec.identityProof && typeof spec.identityProof.identity === "string"
510
+ ? spec.identityProof.identity : null;
511
+
512
+ /** @internal Settled BEFORE the Identity Proof witness is computed, because the presence of an
513
+ * Identification control changes how that witness is derived: with one, the hash is over the secret
514
+ * and the identity together rather than the secret alone (RFC 5272 sec. 6.2.3). A name reaching the
515
+ * request from anywhere therefore has to be known here, or the witness is derived one way and the
516
+ * request carries the control that demands the other. */
517
+ var carriedIdentity = identityIdentifier;
518
+ if (carriedIdentity == null && controlIdentifiers.length > 0) carriedIdentity = controlIdentifiers[0];
519
+ if (carriedIdentity == null) carriedIdentity = macIdentifier;
520
+
413
521
  if (spec.identityProof) {
414
522
  guard.identifier.assertKnownKeys(spec.identityProof, KNOWN_IDENTITY_PROOF_KEYS, E, "cmc/bad-input",
415
523
  function (k) { return "unknown field " + JSON.stringify(k) + " on identityProof -- it is { secret, identity? }"; });
@@ -419,7 +527,49 @@ async function _build(spec, signer, opts) {
419
527
  }
420
528
  if (identity != null) controls.push(encodeControl(OID_IDENTIFICATION, [b.utf8(identity)], ids));
421
529
  controls.push(encodeControl(OID_IDENTITY_PROOF_V2,
422
- [identityProofV2(spec.identityProof.secret, reqSequenceBytes, identity)], ids));
530
+ [identityProofV2(spec.identityProof.secret, reqSequenceBytes, carriedIdentity)], ids));
531
+ }
532
+
533
+ /** @internal A PasswordRecipientInfo names no recipient, so an authority holding secrets for many
534
+ * clients has nothing in the carrier to select one by. The Identification control is what carries
535
+ * that name: it "assists the server in locating the shared-secret" (RFC 5272 sec. 6.2.3), so a
536
+ * request authenticated by a secret says whose secret it is. Two names for one client is refused
537
+ * rather than picked between. */
538
+ if (macIdentifier != null) {
539
+ var named = [];
540
+ for (var nc = 0; nc < controlIdentifiers.length; nc++) guard.list.append(named, controlIdentifiers[nc]);
541
+ if (identityIdentifier != null) guard.list.append(named, identityIdentifier);
542
+ for (var ni = 0; ni < named.length; ni++) {
543
+ if (named[ni] !== macIdentifier) {
544
+ throw E("cmc/bad-input",
545
+ "the shared-secret identifier and the Identification the request already carries name the same " +
546
+ "client to the authority, so a request cannot carry two different ones (RFC 5272 sec. 6.2.3)");
547
+ }
548
+ }
549
+ if (controlIdentifierUnreadable) {
550
+ throw E("cmc/bad-input",
551
+ "the Identification control this request carries does not read as the UTF8String the client is " +
552
+ "named by, so it cannot be confirmed to name the client whose secret authenticates the request (RFC 5272 sec. 6.2.3)");
553
+ }
554
+ /** @internal One client, one shared secret. The carrier's MAC and an Identity Proof witness are both
555
+ * keyed from "the shared-secret" (RFC 5272 sec. 3.2 and 6.2.1), so two different ones would leave an
556
+ * authority able to check one and not the other, and unable to tell which credential is the client's. */
557
+ if (spec.identityProof && !_sameSecret(signer.mac.secret, spec.identityProof.secret)) {
558
+ throw E("cmc/bad-input",
559
+ "the shared secret that authenticates this request and the one its Identity Proof is computed " +
560
+ "from are the same secret, so a request cannot carry two different ones (RFC 5272 sec. 3.2 / 6.2.1)");
561
+ }
562
+ /** @internal One request names one client once. Two controls saying the same thing still leave an
563
+ * authority choosing between them, so the request carries exactly one however it was assembled. */
564
+ var alreadyNamed = controlIdentificationCount + (identityIdentifier == null ? 0 : 1);
565
+ if (alreadyNamed > 1) {
566
+ throw E("cmc/bad-input",
567
+ "a request names its client once, and this one carries " + alreadyNamed + " Identification controls " +
568
+ "(RFC 5272 sec. 6.2.3)");
569
+ }
570
+ if (alreadyNamed === 0) {
571
+ guard.list.append(controls, encodeControl(OID_IDENTIFICATION, [b.utf8(macIdentifier)], ids));
572
+ }
423
573
  }
424
574
 
425
575
  if (spec.popLink) {
@@ -450,6 +600,27 @@ async function _build(spec, signer, opts) {
450
600
  (e && e.message ? e.message : "malformed"), e);
451
601
  }
452
602
 
603
+ /** @internal RFC 5272 sec. 3.2 gives a Full PKI Request two carriers, and a request uses one: a
604
+ * SignedData signed by a key, or an AuthenticatedData whose MAC a shared secret keys. A client
605
+ * enrolling under a secret has no key to sign with, so naming both is a contradiction rather than a
606
+ * preference. */
607
+ if (signer && typeof signer === "object" && !_isArray(signer) && signer.mac != null) {
608
+ if (signer.key != null || signer.cert != null || signer.spki != null || signer.keyIdentifier != null) {
609
+ throw E("cmc/bad-input", "a request is carried by a signature or by a shared secret, not both (RFC 5272 sec. 3.2)");
610
+ }
611
+ guard.identifier.assertKnownKeys(signer, KNOWN_MAC_CARRIER_KEYS, E, "cmc/bad-input", "unknown shared-secret carrier field ");
612
+ var macBytes = macPassword(signer.mac);
613
+ try {
614
+ await _assertTcrPops(requests);
615
+ /** @internal The Password Recipient Info option, which sec. 3.2(a) requires, is what the CMS
616
+ * producer selects for a password recipient, and it generates the MAC key sec. 3.2(b) calls for. */
617
+ return await cmsEncrypt.authenticate(pkiData, [{ password: macBytes }],
618
+ { contentType: "id-cct-PKIData", pem: opts.pem });
619
+ } finally {
620
+ guard.secret.zeroize(macBytes, CmcError, "cmc/bad-input", "the derived shared-secret key");
621
+ }
622
+ }
623
+
453
624
  _assertKeyOnlySigner(signer, requests);
454
625
 
455
626
  var ownedKeyBytes = [];
@@ -582,4 +753,4 @@ function _csrKeyIdentity(csrDer) {
582
753
  return { ski: found, spki: (spki && spki.bytes) || null };
583
754
  }
584
755
 
585
- module.exports = { build: build };
756
+ module.exports = { build: build, macPassword: macPassword };
package/lib/cmc-verify.js CHANGED
@@ -261,7 +261,9 @@ function _governingStatus(statuses, outcome) {
261
261
  * - `dataReturn` (Buffer) -- the Data Return payload the request sent, echoed verbatim.
262
262
  * - `certs` (Buffer[]) -- extra certificates for signer lookup, for a message that does not carry
263
263
  * its own signer; the certificates the message carries are searched either way.
264
- * - `recipient` (object) -- key material for an AuthenticatedData carrier, in the shape
264
+ * - `recipient` (object) -- `{ identifier, secret }` for a response MACed under the shared secret
265
+ * the client enrolled with, which derives the key the way RFC 5272 sec. 3.2(c) states, or key
266
+ * material for an AuthenticatedData carrier, in the shape
265
267
  * `pki.cms.decrypt` takes. Its MAC is then checked and the verdict reports
266
268
  * `signatureVerified: true`; the content it authenticates is bound to the content the verdict
267
269
  * was read from, so a MAC over other bytes cannot stand in for it.
@@ -288,14 +290,29 @@ function _governingStatus(statuses, outcome) {
288
290
  * v.boundToRequest; // false: nothing ties this response to a request either
289
291
  */
290
292
  function verify(response, sent) {
291
- var frozenResponse, frozenSent;
293
+ var frozenResponse, frozenSent, ownedSecret = null;
294
+ /** @internal The options snapshot owns a copy of a byte-valued shared secret from the moment it is
295
+ * taken, so it is wiped when the verification settles however it settles: a malformed response, a
296
+ * carrier that never needed the secret, a refusal on the way to the MAC, and a failure in the rest
297
+ * of this prologue all reach here. A failure DURING the snapshot is cleared by the snapshot itself,
298
+ * which is the only place that can still reach a half-built copy. The caller's own buffer is theirs
299
+ * and is never touched. */
300
+ function _wipeOwnedSecret() {
301
+ if (ownedSecret) guard.secret.zeroize(ownedSecret, CmcError, "cmc/bad-input", "the shared-secret copy");
302
+ ownedSecret = null;
303
+ }
292
304
  try {
293
305
  frozenSent = _snapshotSent(_assertOpts(sent));
306
+ ownedSecret = frozenSent.recipient && guard.bytes.isByteSource(frozenSent.recipient.secret)
307
+ ? frozenSent.recipient.secret : null;
294
308
  frozenResponse = _snapshotIfBytes(response);
295
309
  } catch (e) {
310
+ _wipeOwnedSecret();
296
311
  return Promise.reject(e);
297
312
  }
298
- return guard.async.deferred(function () { return _verify(frozenResponse, frozenSent); });
313
+ return guard.async.deferred(function () { return _verify(frozenResponse, frozenSent); })
314
+ .then(function (v) { _wipeOwnedSecret(); return v; },
315
+ function (e) { _wipeOwnedSecret(); throw e; });
299
316
  }
300
317
 
301
318
  function _assertOpts(sent) {
@@ -330,18 +347,30 @@ function _snapshotSent(sent) {
330
347
  if (Array.isArray(out.bodyPartPaths)) {
331
348
  out.bodyPartPaths = out.bodyPartPaths.map(function (p) { return Array.isArray(p) ? p.slice() : p; });
332
349
  }
333
- if (out.recipient && typeof out.recipient === "object") {
334
- var r = intrinsic.create(null), rk;
335
- for (rk in out.recipient) {
336
- if (!_hasOwn(out.recipient, rk)) continue;
337
- r[rk] = _copyAnyBytes(out.recipient[rk]);
350
+ /** @internal Once a copy of a shared secret exists, EVERYTHING that follows is protected, to the
351
+ * return: the remaining copies, the last option reads, all of it. A caller field is read through
352
+ * whatever accessor the caller wrote, so any of these steps can throw, and the copy would then be
353
+ * left behind with nothing holding it. Guarding one step at a time is what let three earlier
354
+ * versions of this each miss the next one. */
355
+ var takenSecret = null;
356
+ try {
357
+ if (out.recipient && typeof out.recipient === "object") {
358
+ var r = intrinsic.create(null), rk;
359
+ for (rk in out.recipient) {
360
+ if (!_hasOwn(out.recipient, rk)) continue;
361
+ r[rk] = _copyAnyBytes(out.recipient[rk]);
362
+ if (rk === "secret" && guard.bytes.isByteSource(r[rk])) takenSecret = r[rk];
363
+ }
364
+ out.recipient = r;
338
365
  }
339
- out.recipient = r;
366
+ if (Array.isArray(out.certs)) out.certs = out.certs.map(_copyAnyBytes);
367
+ out.allowUnverified = sent.allowUnverified === true;
368
+ out.allowUnbound = sent.allowUnbound === true;
369
+ return out;
370
+ } catch (e) {
371
+ if (takenSecret) guard.secret.zeroize(takenSecret, CmcError, "cmc/bad-input", "the shared-secret copy");
372
+ throw e;
340
373
  }
341
- if (Array.isArray(out.certs)) out.certs = out.certs.map(_copyAnyBytes);
342
- out.allowUnverified = sent.allowUnverified === true;
343
- out.allowUnbound = sent.allowUnbound === true;
344
- return out;
345
374
  }
346
375
 
347
376
  function _verify(response, sent) {
@@ -368,10 +397,28 @@ function _assertAuthentic(body, sent, responseBytes) {
368
397
  "authenticating an AuthenticatedData response needs the response as DER bytes or PEM, " +
369
398
  "because its MAC is computed over them -- pass the encoded response rather than a parsed one");
370
399
  }
371
- return cmsDecrypt.decrypt(responseBytes, sent.recipient).then(null, function (e) {
372
- throw E("cmc/unverified-response",
373
- "the AuthenticatedData response did not authenticate under the supplied recipient key", e);
374
- }).then(function (res) {
400
+ /** @internal A caller naming the shared secret it enrolled with gets the sec. 3.2(c) derivation
401
+ * from the same function the producer uses, rather than deriving it again by hand. Raw key
402
+ * material is still taken as it was, which is what an implementation that derived the key
403
+ * itself supplies. */
404
+ var recipient = sent.recipient, derivedKey = null;
405
+ /** @internal The concatenation this derivation owns. The secret copy it was built from belongs
406
+ * to the options snapshot, which `verify` wipes when the verification settles. */
407
+ function _wipeDerived() {
408
+ if (derivedKey) guard.secret.zeroize(derivedKey, CmcError, "cmc/bad-input", "the derived shared-secret key");
409
+ derivedKey = null;
410
+ }
411
+ if (recipient && typeof recipient === "object" && recipient.mac == null &&
412
+ (recipient.identifier != null || recipient.secret != null) && recipient.password == null) {
413
+ derivedKey = cmcBuild.macPassword(recipient);
414
+ recipient = { password: derivedKey };
415
+ }
416
+ return cmsDecrypt.decrypt(responseBytes, recipient).then(function (r) { _wipeDerived(); return r; },
417
+ function (e) {
418
+ _wipeDerived();
419
+ throw E("cmc/unverified-response",
420
+ "the AuthenticatedData response did not authenticate under the supplied recipient key", e);
421
+ }).then(function (res) {
375
422
  if (!res || res.authenticated !== true) {
376
423
  throw E("cmc/unverified-response", "the AuthenticatedData response did not authenticate under the supplied recipient key");
377
424
  }
@@ -470,7 +517,20 @@ function _shape(body, sent, signatureVerified, bound) {
470
517
  * requests, each naming exactly one arm: `tcr` (a PKCS#10 CSR), `crm` (a CRMF CertReqMsg, or the
471
518
  * CertReqMessages `pki.crmf.build` returns when it carries exactly one) or `orm`
472
519
  * (`{ type, value }`). `spec.controls` are additional controls as `{ type, value }`, and `signer`
473
- * is the `{ cert, key }` that signs the enclosing CMS SignedData. A `tcr` request is verified against
520
+ * is the `{ cert, key }` that signs the enclosing CMS SignedData. RFC 5272 sec. 3.2 gives a Full PKI
521
+ * Request a second carrier for a client that has no key to sign with: pass
522
+ * `{ mac: { identifier, secret } }` in place of `{ cert, key }` and the request is an
523
+ * AuthenticatedData whose MAC the shared secret keys, through the PasswordRecipientInfo sec. 3.2(a)
524
+ * requires. The key is derived from the identifier encoded as UTF-8 followed by the secret
525
+ * (sec. 3.2(c)), which is the derivation `pki.cmc.verify` reads a `recipient` under, so a caller names
526
+ * what it enrolled with at both ends rather than concatenating by hand. The request also carries the
527
+ * identifier in an Identification control, because a PasswordRecipientInfo names no recipient and that
528
+ * control is what "assists the server in locating the shared-secret" (RFC 5272 sec. 6.2.3); supplying
529
+ * a different name through `spec.identityProof.identity` is refused rather than chosen between. Since
530
+ * carrying that control also changes how an Identity Proof witness is derived (sec. 6.2.3), a request
531
+ * carrying both derives the witness with the name it carries, and its MAC and its Identity Proof are
532
+ * keyed from one secret rather than two. Naming a signature and a shared secret together is refused,
533
+ * since a request has one carrier. A `tcr` request is verified against
474
534
  * its own proof-of-possession first: a PKCS#10 whose self-signature does not verify under its subject
475
535
  * public key is refused (`cmc/bad-popo`) rather than signed into a message a CA would reject.
476
536
  *
@@ -511,6 +571,7 @@ function _shape(body, sent, signatureVerified, bound) {
511
571
  * var req = await pki.cmc.build({ requests: [{ tcr: csr }] }, { cert: cert, key: key });
512
572
  * pki.schema.cmc.parse(req).requests[0].arm; // "tcr"
513
573
  */
514
- var build = require("./cmc-build").build;
574
+ var cmcBuild = require("./cmc-build");
575
+ var build = cmcBuild.build;
515
576
 
516
577
  module.exports = { verify: verify, build: build };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.47",
3
+ "version": "0.6.48",
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:39d93a95-6e56-4af5-9029-94a73a8e00c4",
5
+ "serialNumber": "urn:uuid:2d1b2e87-6386-4481-940b-f4de0f1b9227",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-06T15:41:11.254Z",
8
+ "timestamp": "2026-09-06T18:47:52.624Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/pki@0.6.47",
22
+ "bom-ref": "@blamejs/pki@0.6.48",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.47",
25
+ "version": "0.6.48",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
29
- "purl": "pkg:npm/%40blamejs/pki@0.6.47",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.48",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/pki@0.6.47",
57
+ "ref": "@blamejs/pki@0.6.48",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]