@blamejs/pki 0.7.16 → 0.7.18

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,31 @@ 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.7.18 — 2026-09-11
8
+
9
+ Qualified-certificate statements can be issued from a plain spec.
10
+
11
+ ### Added
12
+
13
+ - extensions.qcStatements takes a list of { statementId, info? } (RFC 3739 section 3.2.6). Each statement the toolkit knows encodes its own value syntax: qcCompliance and qcSSCD carry no info; qcType and qcIdentMethod take { types } or { methods } of object identifiers, including the registered ETSI names qctEsign, qctEseal and qctWeb; qcCClegislation and qcQSCDlegislation take { countries } of two-letter ISO 3166-1 codes; qcRetentionPeriod takes { years }; qcLimitValue takes { currency, amount, exponent } with an alphabetic three-letter or numeric 1 to 999 ISO 4217 currency; qcPDS takes { locations } of { url, language }; and qcsPkixQCSyntaxV1 and V2 take { semanticsIdentifier, nameRegistrationAuthorities }, at least one of the two. That is every statement type the parser reads back, so a certificate this builder emits decodes under the same syntax that reads it.
14
+ - A statement id the toolkit does not know carries its value as pre-encoded DER, or carries no value at all, since RFC 3739 makes statementInfo optional on every statement. It is refused a typed object, because nothing can infer the syntax of an unknown statement. Each typed info accepts only the fields its own statement defines, so a misspelled key is reported rather than dropped from the issued certificate. The extension is emitted non-critical unless qcStatementsCritical is set: pki.path.validate does not process qcStatements, so a critical one is rejected as an unrecognized critical extension and pki.lint.certificate grades it lint/rfc5280/unknown-critical-extension.
15
+ - qcStatements is accepted on the pki.csr.sign extensionRequest object as well, so a request and an issued certificate are written the same way.
16
+
17
+ ## v0.7.17 — 2026-09-11
18
+
19
+ The certificate-policy machinery can be issued from a plain spec.
20
+
21
+ ### Added
22
+
23
+ - extensions.policyConstraints takes { requireExplicitPolicy, inhibitPolicyMapping } skip counts and extensions.inhibitAnyPolicy takes a bare skip count. RFC 5280 section 4.2.1.11 forbids an empty policy-constraints sequence, so naming neither field is refused, and both extensions are emitted critical, which sections 4.2.1.11 and 4.2.1.14 require. A skip count is held to the same bound the decoders read it back through, so a negative or non-integer value is refused with x509/bad-input or csr/bad-input.
24
+ - extensions.policyMappings takes a list of { issuerDomainPolicy, subjectDomainPolicy }, each naming a registered policy or a dotted OID. A mapping to or from anyPolicy is refused, which RFC 5280 section 4.2.1.5 forbids and which pki.path.validate applies at section 6.1.4(a). That section states a SHOULD for marking the extension critical. The validator processes the extension on an intermediate certificate, applying the mappings to the policy tree, and treats a critical one on the target certificate as unprocessed and rejects it. A spec does not say where the certificate will sit in a chain, so it is emitted non-critical unless policyMappingsCritical is set, the same shape certificatePolicies already uses.
25
+ - extensions.issuerAltName takes the GeneralName forms subjectAltName takes, including a bare string classified into its form, and is emitted non-critical (RFC 5280 section 4.2.1.7).
26
+ - All four are accepted on the pki.csr.sign extensionRequest object as well, so a request and an issued certificate are written the same way. OpenSSL reads each of them back in the release gates, including both policy-constraint skip counts.
27
+
28
+ ### Fixed
29
+
30
+ - A spec that names an object identifier with a non-string value now raises the signer's own x509/bad-input or csr/bad-input rather than the OID registry's oid/bad-input. This reached certificatePolicies and extendedKeyUsage as well as the new policy mappings, so a caller branching on the documented signer code missed a malformed policy or key-purpose entry. A registered name and a dotted-decimal OID are unaffected, and the already-correct treatment of a lexically-dotted but out-of-range OID is unchanged.
31
+
7
32
  ## v0.7.16 — 2026-09-11
8
33
 
9
34
  Where to fetch the issuer and the CRL can be named in a plain spec.
package/README.md CHANGED
@@ -231,8 +231,8 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
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` |
234
- | `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. `randomSerial()` draws the same 20-octet CSPRNG serial the signer uses when the spec names none, so a serial can be reserved or logged before the certificate is issued. 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, certificate policies, name constraints, authority information access, CRL distribution points, and the freshest CRL from the spec, taking any other extension as pre-encoded DER. `extensions.nameConstraints` takes `{ permitted, excluded }` lists of GeneralName-form objects, restricting what the CA being issued may itself issue; each base is held to the rule for a constraint base, and the extension is emitted critical as §4.2.1.10 requires. 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` |
235
- | `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
234
+ | `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. `randomSerial()` draws the same 20-octet CSPRNG serial the signer uses when the spec names none, so a serial can be reserved or logged before the certificate is issued. 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, certificate policies, name constraints, authority information access, CRL distribution points, the freshest CRL, issuer alternative names, the policy machinery path validation acts on (policy constraints, inhibit anyPolicy, policy mappings), and the RFC 3739 qualified-certificate statements including the ETSI EN 319 412-5 set, from the spec, taking any other extension as pre-encoded DER. `extensions.nameConstraints` takes `{ permitted, excluded }` lists of GeneralName-form objects, restricting what the CA being issued may itself issue; each base is held to the rule for a constraint base, and the extension is emitted critical as §4.2.1.10 requires. 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` |
235
+ | `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, the RFC 3739 qualified-certificate statements, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
236
236
  | `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
237
237
  | `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named. `pop.method: 'agreeMAC'` completes the four: `pop.key` is the requester's finite-field Diffie-Hellman private key, as a PKCS#8 DER, a PEM `PRIVATE KEY` block or a `KeyObject`, and `pop.caCert` the authority's certificate it already holds; the two agree a static secret (RFC 2875 sec. 3), and the key derived from it MACs the DER `certReq` under `id-dhPop-static-HMAC-SHA1`. Either key may name its group in the PKCS#3 or the X9.42 encoding. `pop.key` must be the private half of `certTemplate.publicKey`, and the template must name both a subject and a public key. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
238
238
  | `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `krr` (key recovery, §5.3.7), `ccr` (cross-certification, §5.3.11: a `CertReqMessages` at the normative floor, where the requesting CA keeps its private key so a private-key-transport encryptedKey proof-of-possession is refused, and the optional App. D.6 single-request cardinality is not enforced), `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). Protection is exactly one of `opts.{ key, cert }`, a signature under the sender key with the algorithm resolved from the signer certificate so RSA (PKCS#1 v1.5 / PSS), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived), or `opts.kem`, a KEM-based MAC for a client whose key can only establish secrets (RFC 9810 §5.1.3.4): the ciphertext a peer encapsulated to its ML-KEM key is decapsulated, the key is derived under HKDF-SHA256 with a context bound to the transaction identifier of the message that carried the ciphertext, and `pki.cmp.verify` checks it from the shared secret. Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. A certification authority can take longer to answer than a process is held open, so a `poll-timeout` carries a `resumeToken` and `resumePoll(token)` continues the same transaction in a later process: the token is plain JSON naming the transaction, the nonce the next request echoes, the polled request and the arm its grant arrives on, and the key the grant must certify. It carries no secret and grants nothing, since the protection material and the endpoint come from the session built to resume with, and the resumed poll verifies, nonce-binds, and key-binds every response. Its fields are what the resumed exchange is held to, so store it where the enrollment's own state is stored: someone who can rewrite it can widen what the resumed session accepts, as far as that session's trust anchors and the authority's protection allow and no further. The same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. `openKeyPackage(container, opts)` opens a private key the CA generated centrally and delivered in the `privateKey` field of a granted `CertifiedKeyPair` (RFC 9483 §4.1.6): a CMS `SignedData` over an RFC 5958 `AsymmetricKeyPackage`, sealed in a CMS `EnvelopedData`. `opts.key` (with `opts.cert`) opens the key transport and key agreement containers a signature-protected request selects, `opts.password` the password container a MAC-protected request selects. The authority is authorized before any key material is returned: its certificate must chain to an anchor in `opts.trustAnchors` AND assert the `id-kp-cmKGA` extended key usage, since a certificate with no `extendedKeyUsage` permits every purpose and so authorizes nothing; `opts.authorizedBySharedSecret` states §4.1.6's exemption for an entity that authorizes by the secret that protected its request. Returns `{ keys, kga, trusted }`, where each key is a PKCS#8 `PrivateKeyInfo` ready for `pki.key.import`; `keys` is the whole RFC 5958 `AsymmetricKeyPackage` (`SIZE (1..MAX)`), while a session enrollment requires the sequence of one §4.1.6 profiles it to. Both CMS layers are read as a ContentInfo or as the bare structure, told apart by what the SEQUENCE opens with. `session(opts)` drives the whole exchange under `opts.acceptCentralKeyGeneration`: the request omits `certTemplate.publicKey`, carries no proof of possession, and goes out as `cmp2021`; the session opens the delivered container with the credential it enrolled under and surfaces it as `deliveredKey`, having first checked that the issued certificate certifies the delivered key. Without the option, such a request and such a grant are both refused. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `openKeyPackage`, `session` |
package/lib/csr-sign.js CHANGED
@@ -70,7 +70,8 @@ function _challengePassword(pw) {
70
70
  * (a common-name string, an array of RDNs, or raw Name DER; MAY be empty), `subjectPublicKey` (the SPKI
71
71
  * DER of the key being certified), and optional `extensionRequest` (requested v3 extensions, as an object
72
72
  * of subjectAltName / keyUsage / extendedKeyUsage / basicConstraints / certificatePolicies /
73
- * subjectKeyIdentifier, or an array of pre-encoded Extension DER) and `challengePassword`. `key` (or
73
+ * subjectKeyIdentifier / qcStatements, or an array of pre-encoded Extension DER) and
74
+ * `challengePassword`. `key` (or
74
75
  * `{ key }`) is the subject's own PKCS#8 private key / WebCrypto CryptoKey, so the request is self-signed
75
76
  * to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the
76
77
  * request is returned. The signature algorithm is resolved from the subject key (RSA PKCS#1 v1.5 or PSS,
package/lib/pki-build.js CHANGED
@@ -258,6 +258,22 @@ var REASON_FLAG_BIT = intrinsic.assign(intrinsic.create(null), {
258
258
  cessationOfOperation: 5, certificateHold: 6, privilegeWithdrawn: 7, aACompromise: 8,
259
259
  });
260
260
  var AIA_KEYS = intrinsic.assign(intrinsic.create(null), { accessMethod: 1, accessLocation: 1 });
261
+ var PC_KEYS = intrinsic.assign(intrinsic.create(null), { requireExplicitPolicy: 1, inhibitPolicyMapping: 1 });
262
+ var PM_KEYS = intrinsic.assign(intrinsic.create(null), { issuerDomainPolicy: 1, subjectDomainPolicy: 1 });
263
+ var QC_STATEMENT_KEYS = intrinsic.assign(intrinsic.create(null), { statementId: 1, info: 1 });
264
+ /** @internal The fields each typed statementInfo defines, by statement id. A key outside its
265
+ * statement's set is refused rather than ignored: a misspelled field would otherwise be dropped and
266
+ * the certificate would carry a statement the caller did not write. */
267
+ var QC_INFO_KEYS = intrinsic.create(null);
268
+ [["qcType", { types: 1 }], ["qcIdentMethod", { methods: 1 }],
269
+ ["qcCClegislation", { countries: 1 }], ["qcQSCDlegislation", { countries: 1 }],
270
+ ["qcRetentionPeriod", { years: 1 }], ["qcLimitValue", { currency: 1, amount: 1, exponent: 1 }],
271
+ ["qcPDS", { locations: 1 }],
272
+ ["qcsPkixQCSyntaxV1", { semanticsIdentifier: 1, nameRegistrationAuthorities: 1 }],
273
+ ["qcsPkixQCSyntaxV2", { semanticsIdentifier: 1, nameRegistrationAuthorities: 1 }]].forEach(function (r) {
274
+ QC_INFO_KEYS[oid.byName(r[0])] = intrinsic.assign(intrinsic.create(null), r[1]);
275
+ });
276
+ var QC_PDS_LOCATION_KEYS = intrinsic.assign(intrinsic.create(null), { url: 1, language: 1 });
261
277
  var DP_KEYS = intrinsic.assign(intrinsic.create(null), { fullName: 1, reasons: 1, cRLIssuer: 1 });
262
278
 
263
279
  /** @internal The serial a certificate gets when the caller names none: 20 CSPRNG octets read as a
@@ -428,6 +444,13 @@ function makeBuilder(ctx) {
428
444
  return b.namedBitString(positions);
429
445
  }
430
446
  function _resolveOid(n, label) {
447
+ /** @internal A fault in a producer spec is this module's, so the name is typed BEFORE the OID
448
+ * registry sees it: `oid.byName` raises its own oid/* error for a non-string, which names a
449
+ * different domain than the one a caller of this verb branches on. The dotted-but-invalid case
450
+ * is caught below for the same reason. */
451
+ if (typeof n !== "string" || !n.length) {
452
+ throw E("bad-input", "unknown " + label + " " + guard.text.showValue(n) + " (expected a registered name or a dotted-decimal OID)");
453
+ }
431
454
  var dotted = O(n);
432
455
  if (dotted != null) return dotted;
433
456
  if (typeof n === "string" && _isDottedOid(n)) {
@@ -466,6 +489,218 @@ function makeBuilder(ctx) {
466
489
  return b.contextConstructed(implicitTag, Buffer.concat(members));
467
490
  }
468
491
  function extSan(entries) { return encodeGeneralNames(entries); }
492
+ /** @internal One QCStatement statementInfo, by statement id (RFC 3739 sec. 3.2.6, ETSI EN 319
493
+ * 412-5). Each entry mirrors the decoder that reads the value back, so a statement this builder
494
+ * emits is one `pki.schema.x509.parse` decodes under the same syntax. A `null` encoder means the
495
+ * statement is presence-only and carries no statementInfo at all. */
496
+ /** @internal A PrintableString carries digits, spaces and punctuation, so the string type alone
497
+ * does not make a value an ISO code. The alphabetic codes these statements declare are checked for
498
+ * letters, in either case, before the value is encoded. */
499
+ function _alphaCode(s, n, at, what) {
500
+ var ok = typeof s === "string" && s.length === n;
501
+ for (var i = 0; ok && i < n; i++) {
502
+ var c = _charCodeAt(s, i);
503
+ ok = (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A);
504
+ }
505
+ if (!ok) throw E("bad-input", at + " " + guard.text.showValue(s) + " must be " + what);
506
+ return b.printable(s);
507
+ }
508
+ function _qcCountrySeq(info, who) {
509
+ if (!info || !_isArray(info.countries) || !info.countries.length) {
510
+ throw E("bad-input", who + " requires a non-empty countries array of 2-letter ISO 3166-1 codes");
511
+ }
512
+ return b.sequence(_mapIntrinsic(reqDenseArray(info.countries, who + " countries"), function (c) {
513
+ return _alphaCode(c, 2, who + " country", "a 2-letter ISO 3166-1 code");
514
+ }));
515
+ }
516
+ function _qcOidSeqOf(list, who) {
517
+ if (!_isArray(list) || !list.length) throw E("bad-input", who + " requires a non-empty array of object identifiers");
518
+ return b.sequence(_mapIntrinsic(reqDenseArray(list, who), function (n) { return b.oid(_resolveOid(n, who + " entry")); }));
519
+ }
520
+ var QC_INFO = intrinsic.create(null);
521
+ QC_INFO[oid.byName("qcCompliance")] = null;
522
+ QC_INFO[oid.byName("qcSSCD")] = null;
523
+ QC_INFO[oid.byName("qcType")] = function (info, who) { return _qcOidSeqOf(info && info.types, who + " types"); };
524
+ QC_INFO[oid.byName("qcIdentMethod")] = function (info, who) { return _qcOidSeqOf(info && info.methods, who + " methods"); };
525
+ QC_INFO[oid.byName("qcCClegislation")] = _qcCountrySeq;
526
+ QC_INFO[oid.byName("qcQSCDlegislation")] = _qcCountrySeq;
527
+ QC_INFO[oid.byName("qcRetentionPeriod")] = function (info, who) {
528
+ if (!info || info.years == null) throw E("bad-input", who + " requires a years count");
529
+ return b.integer(skipCount(info.years, who + " years"));
530
+ };
531
+ QC_INFO[oid.byName("qcLimitValue")] = function (info, who) {
532
+ if (!info || info.amount == null || info.exponent == null || info.currency == null) {
533
+ throw E("bad-input", who + " requires currency, amount and exponent (a MonetaryValue)");
534
+ }
535
+ var cur;
536
+ if (typeof info.currency === "string") {
537
+ cur = _alphaCode(info.currency, 3, who + " alphabetic currency", "a 3-letter ISO 4217 code");
538
+ } else {
539
+ cur = b.integer(guard.range.int(guard.range.authoredInteger(info.currency, rawErr, ctx.prefix + "/bad-input", who + " currency"),
540
+ 1n, 999n, rawErr, ctx.prefix + "/bad-input", who + " numeric currency (ISO 4217, 1..999)"));
541
+ }
542
+ /** @internal The decoder reads amount as 0..2^53-1 and exponent as its signed range, so the
543
+ * builder is held to the same bounds; a wider one would emit a MonetaryValue this toolkit's own
544
+ * reader refuses. */
545
+ var code = ctx.prefix + "/bad-input";
546
+ var amount = guard.range.int(guard.range.authoredInteger(info.amount, rawErr, code, who + " amount"),
547
+ 0n, 9007199254740991n, rawErr, code, who + " amount");
548
+ var exponent = guard.range.int(guard.range.authoredInteger(info.exponent, rawErr, code, who + " exponent"),
549
+ -9007199254740991n, 9007199254740991n, rawErr, code, who + " exponent");
550
+ return b.sequence([cur, b.integer(amount), b.integer(exponent)]);
551
+ };
552
+ QC_INFO[oid.byName("qcPDS")] = function (info, who) {
553
+ if (!info || !_isArray(info.locations) || !info.locations.length) {
554
+ throw E("bad-input", who + " requires a non-empty locations array of { url, language }");
555
+ }
556
+ return b.sequence(_mapIntrinsic(reqDenseArray(info.locations, who + " locations"), function (loc, i) {
557
+ var at = who + " location " + i;
558
+ if (!loc || typeof loc !== "object" || _isArray(loc) || _isBufferChk(loc)) throw E("bad-input", at + " must be an object { url, language }");
559
+ guard.identifier.assertKnownKeys(loc, QC_PDS_LOCATION_KEYS, E, "bad-input", function (k) {
560
+ return "unknown " + at + " field " + _stringify(k) + " (accepted: url, language)";
561
+ });
562
+ if (typeof loc.url !== "string" || !loc.url.length) throw E("bad-input", at + " requires a url");
563
+ return b.sequence([b.ia5(loc.url), _alphaCode(loc.language, 2, at + " language", "a 2-letter ISO 639-1 code")]);
564
+ }));
565
+ };
566
+ function _qcSemanticsInfo(info, who) {
567
+ /** @internal SemanticsInformation is OPTIONAL on this statement, which is the form the decoder
568
+ * accepts for a null statementInfo, so an omitted info emits the statementId alone. An info
569
+ * object that IS present must carry at least one of the two fields. */
570
+ if (info == null) return null;
571
+ if (info.semanticsIdentifier == null && info.nameRegistrationAuthorities == null) {
572
+ throw E("bad-input", who + " requires a semanticsIdentifier, nameRegistrationAuthorities, or both (RFC 3739 sec. 3.2.6.1)");
573
+ }
574
+ var fields = [];
575
+ if (info.semanticsIdentifier != null) guard.list.append(fields, b.oid(_resolveOid(info.semanticsIdentifier, who + " semanticsIdentifier")));
576
+ if (info.nameRegistrationAuthorities != null) {
577
+ guard.list.append(fields, encodeGeneralNames(reqDenseArray(info.nameRegistrationAuthorities, who + " nameRegistrationAuthorities")));
578
+ }
579
+ return b.sequence(fields);
580
+ }
581
+ QC_INFO[oid.byName("qcsPkixQCSyntaxV1")] = _qcSemanticsInfo;
582
+ QC_INFO[oid.byName("qcsPkixQCSyntaxV2")] = _qcSemanticsInfo;
583
+
584
+ /** @internal QCStatements (RFC 3739 sec. 3.2.6): SEQUENCE OF QCStatement { statementId, info? }.
585
+ * A statement id the toolkit knows encodes its own value syntax; any other id is reachable only
586
+ * with pre-encoded DER, since nothing here can know what its statementInfo should look like. */
587
+ function extQcStatements(list) {
588
+ if (!_isArray(list) || !list.length) {
589
+ throw E("bad-input", "qcStatements must name at least one statement (RFC 3739 sec. 3.2.6)");
590
+ }
591
+ var dense = reqDenseArray(list, "qcStatements");
592
+ return b.sequence(_mapIntrinsic(dense, function (st, i) {
593
+ var who = "qcStatements entry " + i;
594
+ if (!st || typeof st !== "object" || _isArray(st) || _isBufferChk(st)) {
595
+ throw E("bad-input", who + " must be an object { statementId, info? }");
596
+ }
597
+ guard.identifier.assertKnownKeys(st, QC_STATEMENT_KEYS, E, "bad-input", function (k) {
598
+ return "unknown " + who + " field " + _stringify(k) + " (accepted: statementId, info)";
599
+ });
600
+ var id = _resolveOid(st.statementId, who + " statementId");
601
+ var known = intrinsic.hasOwn(QC_INFO, id);
602
+ /** @internal The pre-encoded escape hatch is for an id whose syntax is NOT known here. A known
603
+ * id routed through it would skip the rule its typed form is held to and emit a statement the
604
+ * reader cannot decode, so it is refused rather than passed through. */
605
+ if (guard.bytes.isByteSource(st.info)) {
606
+ if (known) {
607
+ throw E("bad-input", who + " statementId " + guard.text.showValue(st.statementId) +
608
+ " has a known statementInfo syntax, so its info is named as fields rather than pre-encoded DER");
609
+ }
610
+ return b.sequence([b.oid(id), b.raw(guard.der.tlv(guard.bytes.source(st.info, ErrorClass, ctx.prefix + "/bad-input", who + " info"),
611
+ rawErr, ctx.prefix + "/bad-input", who + " pre-encoded info"))]);
612
+ }
613
+ if (!known) {
614
+ /** @internal statementInfo is OPTIONAL on every QCStatement (RFC 3739 sec. 3.2.6), so a
615
+ * proprietary presence-only statement is a valid shape and emits its id alone. Only a
616
+ * statement that names a value needs a syntax this module does not have for an unknown id. */
617
+ if (st.info == null) return b.sequence([b.oid(id)]);
618
+ throw E("bad-input", who + " statementId " + guard.text.showValue(st.statementId) +
619
+ " has no known statementInfo syntax; supply the info as pre-encoded DER");
620
+ }
621
+ var encode = QC_INFO[id];
622
+ if (encode === null) {
623
+ if (st.info != null) throw E("bad-input", who + " statement carries no statementInfo, so info must be omitted");
624
+ return b.sequence([b.oid(id)]);
625
+ }
626
+ var infoKeys = QC_INFO_KEYS[id];
627
+ if (infoKeys && st.info != null && typeof st.info === "object" && !_isArray(st.info) && !_isBufferChk(st.info)) {
628
+ guard.identifier.assertKnownKeys(st.info, infoKeys, E, "bad-input", function (k) {
629
+ return "unknown " + who + " info field " + _stringify(k);
630
+ });
631
+ }
632
+ /** @internal An encoder returns null when the statement's info is OPTIONAL and omitted, which
633
+ * is the form the SemanticsInformation decoder accepts. */
634
+ var value;
635
+ /** @internal A statementInfo field is named in a typed spec, so a character its ASN.1 string
636
+ * type cannot carry is a fault in the spec this verb was handed rather than in bytes a caller
637
+ * supplied pre-encoded, and it is reported against this verb. */
638
+ try { value = encode(st.info, who); }
639
+ catch (e) {
640
+ if (e instanceof ErrorClass) throw e;
641
+ throw E("bad-input", who + " statementInfo has characters invalid for its string type", e);
642
+ }
643
+ return value === null ? b.sequence([b.oid(id)]) : b.sequence([b.oid(id), value]);
644
+ }));
645
+ }
646
+ /** @internal A path-validation skip count: a BaseDistance the decoders read back through
647
+ * guard.range.uint31, so the builder is held to the same bound rather than a wider one. */
648
+ function skipCount(v, label) {
649
+ var code = ctx.prefix + "/bad-input";
650
+ return guard.range.uint31(guard.range.authoredInteger(v, rawErr, code, label), rawErr, code, label);
651
+ }
652
+ /** @internal PolicyConstraints (RFC 5280 sec. 4.2.1.11): requireExplicitPolicy [0] and
653
+ * inhibitPolicyMapping [1], both IMPLICIT SkipCerts. The clause forbids an empty sequence, so one
654
+ * of the two is required. Emitted critical by its caller, which the same clause requires. */
655
+ function extPolicyConstraints(spec) {
656
+ if (!spec || typeof spec !== "object" || _isArray(spec) || _isBufferChk(spec)) {
657
+ throw E("bad-input", "policyConstraints must be an object naming requireExplicitPolicy and/or inhibitPolicyMapping");
658
+ }
659
+ guard.identifier.assertKnownKeys(spec, PC_KEYS, E, "bad-input", function (k) {
660
+ return "unknown policyConstraints field " + _stringify(k) + " (accepted: requireExplicitPolicy, inhibitPolicyMapping)";
661
+ });
662
+ var fields = [];
663
+ if (spec.requireExplicitPolicy != null) {
664
+ guard.list.append(fields, b.implicit(0, b.integer(skipCount(spec.requireExplicitPolicy, "policyConstraints.requireExplicitPolicy"))));
665
+ }
666
+ if (spec.inhibitPolicyMapping != null) {
667
+ guard.list.append(fields, b.implicit(1, b.integer(skipCount(spec.inhibitPolicyMapping, "policyConstraints.inhibitPolicyMapping"))));
668
+ }
669
+ if (!fields.length) {
670
+ throw E("bad-input", "policyConstraints must name requireExplicitPolicy or inhibitPolicyMapping (RFC 5280 sec. 4.2.1.11 forbids an empty sequence)");
671
+ }
672
+ return b.sequence(fields);
673
+ }
674
+ /** @internal InhibitAnyPolicy (RFC 5280 sec. 4.2.1.14): a bare SkipCerts INTEGER. */
675
+ function extInhibitAnyPolicy(v) { return b.integer(skipCount(v, "inhibitAnyPolicy")); }
676
+ /** @internal PolicyMappings (RFC 5280 sec. 4.2.1.5): SEQUENCE SIZE (1..MAX) OF
677
+ * { issuerDomainPolicy, subjectDomainPolicy }. The clause forbids mapping either to or from
678
+ * anyPolicy, so neither side may name it. */
679
+ function extPolicyMappings(list) {
680
+ if (!_isArray(list) || !list.length) {
681
+ throw E("bad-input", "policyMappings must name at least one { issuerDomainPolicy, subjectDomainPolicy } (RFC 5280 sec. 4.2.1.5)");
682
+ }
683
+ var anyPolicy = O("anyPolicy");
684
+ var dense = reqDenseArray(list, "policyMappings");
685
+ return b.sequence(_mapIntrinsic(dense, function (m, i) {
686
+ var who = "policyMappings entry " + i;
687
+ if (!m || typeof m !== "object" || _isArray(m) || _isBufferChk(m)) {
688
+ throw E("bad-input", who + " must be an object { issuerDomainPolicy, subjectDomainPolicy }");
689
+ }
690
+ guard.identifier.assertKnownKeys(m, PM_KEYS, E, "bad-input", function (k) {
691
+ return "unknown " + who + " field " + _stringify(k) + " (accepted: issuerDomainPolicy, subjectDomainPolicy)";
692
+ });
693
+ if (m.issuerDomainPolicy == null || m.subjectDomainPolicy == null) {
694
+ throw E("bad-input", who + " requires both issuerDomainPolicy and subjectDomainPolicy");
695
+ }
696
+ var idp = _resolveOid(m.issuerDomainPolicy, who + " issuerDomainPolicy");
697
+ var sdp = _resolveOid(m.subjectDomainPolicy, who + " subjectDomainPolicy");
698
+ if (idp === anyPolicy || sdp === anyPolicy) {
699
+ throw E("bad-input", who + " must not map to or from anyPolicy (RFC 5280 sec. 4.2.1.5)");
700
+ }
701
+ return b.sequence([b.oid(idp), b.oid(sdp)]);
702
+ }));
703
+ }
469
704
  /** @internal AuthorityInfoAccessSyntax (RFC 5280 sec. 4.2.2.1): SEQUENCE SIZE (1..MAX) OF
470
705
  * AccessDescription { accessMethod OBJECT IDENTIFIER, accessLocation GeneralName }. */
471
706
  function extAuthorityInfoAccess(list) {
@@ -692,6 +927,8 @@ function makeBuilder(ctx) {
692
927
  subjectAltName: 1, keyUsage: 1, keyUsageCritical: 1, extendedKeyUsage: 1, extendedKeyUsageCritical: 1,
693
928
  basicConstraints: 1, certificatePolicies: 1, certificatePoliciesCritical: 1, subjectKeyIdentifier: 1,
694
929
  nameConstraints: 1, authorityInfoAccess: 1, cRLDistributionPoints: 1, freshestCRL: 1,
930
+ policyConstraints: 1, inhibitAnyPolicy: 1, policyMappings: 1, policyMappingsCritical: 1,
931
+ issuerAltName: 1, qcStatements: 1, qcStatementsCritical: 1,
695
932
  };
696
933
  function requestedExtensions(extSpec, spki) {
697
934
  var EXT_DECODERS = ctx.EXT_DECODERS;
@@ -733,6 +970,11 @@ function makeBuilder(ctx) {
733
970
  if (extSpec.authorityInfoAccess != null) guard.list.append(out, ext(O("authorityInfoAccess"), false, extAuthorityInfoAccess(extSpec.authorityInfoAccess)));
734
971
  if (extSpec.cRLDistributionPoints != null) guard.list.append(out, ext(O("cRLDistributionPoints"), false, extCrlDistributionPoints(extSpec.cRLDistributionPoints, "cRLDistributionPoints")));
735
972
  if (extSpec.freshestCRL != null) guard.list.append(out, ext(O("freshestCRL"), false, extCrlDistributionPoints(extSpec.freshestCRL, "freshestCRL")));
973
+ if (extSpec.policyConstraints != null) guard.list.append(out, ext(O("policyConstraints"), true, extPolicyConstraints(extSpec.policyConstraints)));
974
+ if (extSpec.inhibitAnyPolicy != null) guard.list.append(out, ext(O("inhibitAnyPolicy"), true, extInhibitAnyPolicy(extSpec.inhibitAnyPolicy)));
975
+ if (extSpec.policyMappings != null) guard.list.append(out, ext(O("policyMappings"), !!extSpec.policyMappingsCritical, extPolicyMappings(extSpec.policyMappings)));
976
+ if (extSpec.issuerAltName != null) guard.list.append(out, ext(O("issuerAltName"), false, encodeGeneralNames(reqDenseArray(extSpec.issuerAltName, "issuerAltName"))));
977
+ if (extSpec.qcStatements != null) guard.list.append(out, ext(O("qcStatements"), !!extSpec.qcStatementsCritical, extQcStatements(extSpec.qcStatements)));
736
978
  if (!out.length) throw E("bad-input", "the requested extensions object must request at least one extension");
737
979
  return b.sequence(out);
738
980
  }
@@ -797,7 +1039,9 @@ function makeBuilder(ctx) {
797
1039
  E: E, code: code, KU_BIT: KU_BIT,
798
1040
  encodeName: encodeName, isEmptyName: isEmptyName, encodeGeneralName: encodeGeneralName,
799
1041
  extNameConstraints: extNameConstraints, extAuthorityInfoAccess: extAuthorityInfoAccess,
800
- extCrlDistributionPoints: extCrlDistributionPoints,
1042
+ extCrlDistributionPoints: extCrlDistributionPoints, extPolicyConstraints: extPolicyConstraints,
1043
+ extInhibitAnyPolicy: extInhibitAnyPolicy, extPolicyMappings: extPolicyMappings,
1044
+ extQcStatements: extQcStatements,
801
1045
  encodeGeneralNames: encodeGeneralNames, serialInteger: serialInteger, timeDer: timeDer,
802
1046
  requestedExtensions: requestedExtensions,
803
1047
  extKeyUsage: extKeyUsage, extExtKeyUsage: extExtKeyUsage, validateBcSpec: validateBcSpec,
package/lib/x509-sign.js CHANGED
@@ -52,6 +52,8 @@ var KNOWN_EXT_KEYS = intrinsic.assign(intrinsic.create(null), {
52
52
  extendedKeyUsage: 1, extendedKeyUsageCritical: 1, basicConstraints: 1, subjectAltName: 1,
53
53
  certificatePolicies: 1, certificatePoliciesCritical: 1, nameConstraints: 1,
54
54
  authorityInfoAccess: 1, cRLDistributionPoints: 1, freshestCRL: 1,
55
+ policyConstraints: 1, inhibitAnyPolicy: 1, policyMappings: 1, policyMappingsCritical: 1,
56
+ issuerAltName: 1, qcStatements: 1, qcStatementsCritical: 1,
55
57
  });
56
58
 
57
59
  var _b = pkiBuild.makeBuilder({ ErrorClass: CertificateError, prefix: "x509", O: O, NS: NS, NAME_SCHEMA: NAME_SCHEMA, SPKI_SCHEMA: SPKI_SCHEMA, EXT_DECODERS: EXT_DECODERS });
@@ -62,7 +64,10 @@ var _encodeName = _b.encodeName, _isEmptyName = _b.isEmptyName, _reqDer = _b.req
62
64
  _ext = _b.ext, _extBasicConstraints = _b.extBasicConstraints, _validateBcSpec = _b.validateBcSpec,
63
65
  _extKeyUsage = _b.extKeyUsage, _extExtKeyUsage = _b.extExtKeyUsage, _extSki = _b.extSki,
64
66
  _extNameConstraints = _b.extNameConstraints, _extAia = _b.extAuthorityInfoAccess,
65
- _extCrlDp = _b.extCrlDistributionPoints,
67
+ _extCrlDp = _b.extCrlDistributionPoints, _extPolicyConstraints = _b.extPolicyConstraints,
68
+ _extInhibitAnyPolicy = _b.extInhibitAnyPolicy, _extPolicyMappings = _b.extPolicyMappings,
69
+ _encodeGeneralNames = _b.encodeGeneralNames, _reqDenseArray = _b.reqDenseArray,
70
+ _extQcStatements = _b.extQcStatements,
66
71
  _extAki = _b.extAki, _extSan = _b.extSan, _extCertPolicies = _b.extCertPolicies,
67
72
  _skiKeyId = _b.skiKeyId, _spkiKeyId = _b.spkiKeyId, _serialInteger = _b.serialInteger;
68
73
 
@@ -148,6 +153,21 @@ function _buildExtensions(extSpec, ctx) {
148
153
  if (extSpec.authorityInfoAccess != null) guard.list.append(out, _ext(O("authorityInfoAccess"), false, _extAia(extSpec.authorityInfoAccess)));
149
154
  if (extSpec.cRLDistributionPoints != null) guard.list.append(out, _ext(O("cRLDistributionPoints"), false, _extCrlDp(extSpec.cRLDistributionPoints, "cRLDistributionPoints")));
150
155
  if (extSpec.freshestCRL != null) guard.list.append(out, _ext(O("freshestCRL"), false, _extCrlDp(extSpec.freshestCRL, "freshestCRL")));
156
+ /** @internal Sections 4.2.1.11 and 4.2.1.14 fix these critical; sec. 4.2.1.5 states a SHOULD for
157
+ * policyMappings and sec. 4.2.1.7 a SHOULD for issuerAltName, and the toolkit issues the
158
+ * conforming form of each. */
159
+ if (extSpec.policyConstraints != null) guard.list.append(out, _ext(O("policyConstraints"), true, _extPolicyConstraints(extSpec.policyConstraints)));
160
+ if (extSpec.inhibitAnyPolicy != null) guard.list.append(out, _ext(O("inhibitAnyPolicy"), true, _extInhibitAnyPolicy(extSpec.inhibitAnyPolicy)));
161
+ /** @internal Sec. 4.2.1.5 states a SHOULD for marking policyMappings critical, and pki.path.validate
162
+ * does not process the extension, so a critical one is a certificate this toolkit's own validator
163
+ * must reject and pki.lint.certificate grades `unknown-critical-extension`. The default is the
164
+ * usable form and the knob reaches the SHOULD-conforming one, as certificatePolicies does. */
165
+ if (extSpec.policyMappings != null) guard.list.append(out, _ext(O("policyMappings"), !!extSpec.policyMappingsCritical, _extPolicyMappings(extSpec.policyMappings)));
166
+ if (extSpec.issuerAltName != null) guard.list.append(out, _ext(O("issuerAltName"), false, _encodeGeneralNames(_reqDenseArray(extSpec.issuerAltName, "issuerAltName"))));
167
+ /** @internal pki.path.validate does not process qcStatements, so a critical one is rejected as an
168
+ * unrecognized critical extension; the default is the form that validates and the knob reaches
169
+ * the other, as policyMappings and certificatePolicies do. */
170
+ if (extSpec.qcStatements != null) guard.list.append(out, _ext(O("qcStatements"), !!extSpec.qcStatementsCritical, _extQcStatements(extSpec.qcStatements)));
151
171
  if (extSpec.nameConstraints != null) {
152
172
  if (!caTrue) throw _err("x509/bad-input", "nameConstraints appears only in a CA certificate, so it requires basicConstraints cA=TRUE (RFC 5280 sec. 4.2.1.10)");
153
173
  guard.list.append(out, _ext(O("nameConstraints"), true, _extNameConstraints(extSpec.nameConstraints)));
@@ -254,6 +274,35 @@ function _hasCriticalSan(extSpec) {
254
274
  * distribution point naming only `reasons` is refused, which that clause requires. All three are
255
275
  * emitted non-critical.
256
276
  *
277
+ * The policy machinery certification-path validation acts on is available the same way.
278
+ * `extensions.policyConstraints` takes `{ requireExplicitPolicy, inhibitPolicyMapping }` skip counts,
279
+ * at least one of which RFC 5280 sec. 4.2.1.11 requires; `extensions.inhibitAnyPolicy` takes a bare
280
+ * skip count (sec. 4.2.1.14); both are emitted critical, which those clauses require.
281
+ * `extensions.policyMappings` takes a list of `{ issuerDomainPolicy, subjectDomainPolicy }` naming
282
+ * registered policies or dotted OIDs, and refuses a mapping to or from `anyPolicy`, which sec.
283
+ * 4.2.1.5 forbids, the same rule `pki.path.validate` applies at sec. 6.1.4(a). That clause states a
284
+ * SHOULD for marking it critical. The validator processes the extension on an intermediate
285
+ * certificate, where sec. 6.1.4 applies the mappings to the policy tree, and treats a critical one on
286
+ * the TARGET certificate as unprocessed, rejecting it; `pki.lint.certificate` grades that case
287
+ * `unknown-critical-extension`. It is emitted non-critical unless `policyMappingsCritical` is set.
288
+ * `extensions.issuerAltName` takes the `GeneralName` forms `subjectAltName` takes and is emitted
289
+ * non-critical (sec. 4.2.1.7).
290
+ *
291
+ * `extensions.qcStatements` builds the RFC 3739 sec. 3.2.6 qualified-certificate statements, as a
292
+ * list of `{ statementId, info? }`. A statement the toolkit knows encodes its own value syntax:
293
+ * `qcCompliance` and `qcSSCD` carry no `info` at all; `qcType` and `qcIdentMethod` take
294
+ * `{ types }` / `{ methods }` of object identifiers, including the registered ETSI names `qctEsign`,
295
+ * `qctEseal` and `qctWeb`; `qcCClegislation` and `qcQSCDlegislation` take `{ countries }` of
296
+ * two-letter codes; `qcRetentionPeriod` takes `{ years }`; `qcLimitValue` takes
297
+ * `{ currency, amount, exponent }` with an alphabetic or numeric ISO 4217 currency; `qcPDS` takes
298
+ * `{ locations: [{ url, language }] }`; and `qcsPkixQCSyntaxV1` / `V2` take
299
+ * `{ semanticsIdentifier, nameRegistrationAuthorities }`, at least one of the two. Each typed `info`
300
+ * accepts only the fields its own statement defines, so a misspelled key is refused rather than
301
+ * dropped. Any other statement id takes `info` as pre-encoded DER, or omits `info` for a
302
+ * presence-only statement, since `statementInfo` is optional on every statement and nothing here can
303
+ * know an unknown syntax. `pki.path.validate` does not process this extension, so it is emitted
304
+ * non-critical unless `qcStatementsCritical` is set.
305
+ *
257
306
  * @opts
258
307
  * - `pem` (boolean) -- return a PEM `CERTIFICATE` string instead of DER.
259
308
  * - `pss` (boolean) -- sign an RSA key with RSASSA-PSS instead of PKCS#1 v1.5.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.7.16",
3
+ "version": "0.7.18",
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:cef547e4-7949-46e6-bb7a-f2379b60393e",
5
+ "serialNumber": "urn:uuid:e5fc1b31-83d1-4f0f-83e4-0165b7f928e9",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-11T04:59:20.784Z",
8
+ "timestamp": "2026-09-11T07:39:10.896Z",
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.7.16",
22
+ "bom-ref": "@blamejs/pki@0.7.18",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.7.16",
25
+ "version": "0.7.18",
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.7.16",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.7.18",
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.7.16",
57
+ "ref": "@blamejs/pki@0.7.18",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]