@blamejs/pki 0.7.20 → 0.7.21

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,18 @@ 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.21 — 2026-09-11
8
+
9
+ Every certificate extension the toolkit reads, it can now also issue.
10
+
11
+ ### Added
12
+
13
+ - extensions.msCertificateTemplate takes { templateID, templateMajorVersion, templateMinorVersion }, the versions optional and each a DWORD. A minor version requires a major one, because the reader takes the two positionally and a minor alone would be read as the major.
14
+ - extensions.msEnrollCertType takes the legacy v1 template name, written as the BMPString its reader requires. A character outside the basic multilingual plane has no BMPString encoding and is refused rather than written as something else.
15
+ - extensions.msCaVersion takes { caKeyIndex, certIndex }, each a WORD, or the composed DWORD directly, matching the two ways its reader surfaces the value.
16
+ - extensions.msPreviousCertHash takes the 20-octet SHA-1 thumbprint of the previous CA certificate, and extensions.msApplicationPolicies takes the certificatePolicies spec, qualifiers included, since that is the syntax its reader applies.
17
+ - All five are emitted non-critical. Neither pki.path.validate nor pki.lint.certificate processes them, so a critical instance is refused as an unrecognized critical extension by the toolkit's own readers; a caller who needs one supplies the Extension pre-encoded.
18
+
7
19
  ## v0.7.20 — 2026-09-11
8
20
 
9
21
  Certificate policies carry their qualifiers, and the authority key identifier names the issuing certificate.
package/README.md CHANGED
@@ -231,7 +231,7 @@ 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; the AKI optionally naming the issuing certificate by name and serial), subject alternative names, certificate policies with their RFC 5280 section 4.2.1.4 qualifiers (a CPS pointer and a user notice), 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), the RFC 3739 qualified-certificate statements including the ETSI EN 319 412-5 set, and the RFC 6962 certificate-transparency pair (the precertificate poison and the embedded SCT list), 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` |
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; the AKI optionally naming the issuing certificate by name and serial), subject alternative names, certificate policies with their RFC 5280 section 4.2.1.4 qualifiers (a CPS pointer and a user notice), 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), the RFC 3739 qualified-certificate statements including the ETSI EN 319 412-5 set, the RFC 6962 certificate-transparency pair (the precertificate poison and the embedded SCT list), and the Active Directory Certificate Services enrollment extensions (certificate template, legacy template name, CA version, previous-CA-certificate hash, application policies), from the spec. That is every extension `pki.schema.x509.parse` decodes, so any certificate the toolkit reads back in full it can also issue; any other extension is taken 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
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` |
package/lib/pki-build.js CHANGED
@@ -270,6 +270,10 @@ var POLICY_ENTRY_KEYS = intrinsic.assign(intrinsic.create(null), { oid: 1, cps:
270
270
  var USER_NOTICE_KEYS = intrinsic.assign(intrinsic.create(null), { noticeRef: 1, explicitText: 1 });
271
271
  var NOTICE_REF_KEYS = intrinsic.assign(intrinsic.create(null), { organization: 1, noticeNumbers: 1 });
272
272
  var AKI_KEYS = intrinsic.assign(intrinsic.create(null), { keyIdentifier: 1, authorityCertIssuer: 1, authorityCertSerialNumber: 1 });
273
+ /** @internal The fields of the Active Directory Certificate Services enrollment extensions. These
274
+ * are proprietary, so the toolkit's own readers in schema-pkix define the shape the builder emits. */
275
+ var MS_TEMPLATE_KEYS = intrinsic.assign(intrinsic.create(null), { templateID: 1, templateMajorVersion: 1, templateMinorVersion: 1 });
276
+ var MS_CA_VERSION_KEYS = intrinsic.assign(intrinsic.create(null), { caKeyIndex: 1, certIndex: 1 });
273
277
  /** @internal The fields each typed statementInfo defines, by statement id. A key outside its
274
278
  * statement's set is refused rather than ignored: a misspelled field would otherwise be dropped and
275
279
  * the certificate would carry a statement the caller did not write. */
@@ -959,6 +963,62 @@ function makeBuilder(ctx) {
959
963
  return quals.length ? b.sequence([b.oid(pOid), b.sequence(quals)]) : b.sequence([b.oid(pOid)]);
960
964
  }));
961
965
  }
966
+ /** @internal A DWORD as the schema-pkix readers bound it: 0 to 2^32-1. */
967
+ function msDword(v, who) {
968
+ var code = ctx.prefix + "/bad-input";
969
+ return guard.range.int(guard.range.authoredInteger(v, rawErr, code, who), 0n, 4294967295n, rawErr, code, who);
970
+ }
971
+ /** @internal CertificateTemplateOID: SEQUENCE { templateID, templateMajorVersion OPTIONAL,
972
+ * templateMinorVersion OPTIONAL }. The reader takes the versions positionally, so a minor without
973
+ * a major has no encoding and is refused rather than silently written as the major. */
974
+ function extMsCertificateTemplate(spec) {
975
+ if (!spec || typeof spec !== "object" || _isArray(spec) || _isBufferChk(spec)) {
976
+ throw E("bad-input", "msCertificateTemplate must be an object { templateID, templateMajorVersion?, templateMinorVersion? }");
977
+ }
978
+ guard.identifier.assertKnownKeys(spec, MS_TEMPLATE_KEYS, E, "bad-input", function (k) {
979
+ return "unknown msCertificateTemplate field " + _stringify(k) + " (accepted: templateID, templateMajorVersion, templateMinorVersion)";
980
+ });
981
+ if (spec.templateID == null) throw E("bad-input", "msCertificateTemplate requires a templateID");
982
+ if (spec.templateMinorVersion != null && spec.templateMajorVersion == null) {
983
+ throw E("bad-input", "msCertificateTemplate templateMinorVersion follows templateMajorVersion, so a minor version requires a major one");
984
+ }
985
+ var fields = [b.oid(_resolveOid(spec.templateID, "msCertificateTemplate templateID"))];
986
+ if (spec.templateMajorVersion != null) guard.list.append(fields, b.integer(msDword(spec.templateMajorVersion, "msCertificateTemplate templateMajorVersion")));
987
+ if (spec.templateMinorVersion != null) guard.list.append(fields, b.integer(msDword(spec.templateMinorVersion, "msCertificateTemplate templateMinorVersion")));
988
+ return b.sequence(fields);
989
+ }
990
+ /** @internal CACertVersion is one DWORD the reader splits into a CA key index in the high word and
991
+ * a certificate index in the low word, so the spec names either the two indexes or the DWORD. */
992
+ function extMsCaVersion(spec) {
993
+ if (spec != null && typeof spec === "object" && !_isArray(spec) && !_isBufferChk(spec)) {
994
+ guard.identifier.assertKnownKeys(spec, MS_CA_VERSION_KEYS, E, "bad-input", function (k) {
995
+ return "unknown msCaVersion field " + _stringify(k) + " (accepted: caKeyIndex, certIndex)";
996
+ });
997
+ if (spec.caKeyIndex == null || spec.certIndex == null) throw E("bad-input", "msCaVersion requires both caKeyIndex and certIndex, or the composed DWORD");
998
+ var code = ctx.prefix + "/bad-input";
999
+ var hi = guard.range.int(guard.range.authoredInteger(spec.caKeyIndex, rawErr, code, "msCaVersion caKeyIndex"), 0n, 65535n, rawErr, code, "msCaVersion caKeyIndex");
1000
+ var lo = guard.range.int(guard.range.authoredInteger(spec.certIndex, rawErr, code, "msCaVersion certIndex"), 0n, 65535n, rawErr, code, "msCaVersion certIndex");
1001
+ return b.integer((hi * 65536) + lo);
1002
+ }
1003
+ return b.integer(msDword(spec, "msCaVersion"));
1004
+ }
1005
+ /** @internal CAPrevCertHash is the SHA-1 thumbprint of the previous CA certificate, and the reader
1006
+ * requires exactly twenty octets. */
1007
+ function extMsPreviousCertHash(v) {
1008
+ var hash = guard.bytes.snapshotSource(v, ErrorClass, ctx.prefix + "/bad-input", "msPreviousCertHash");
1009
+ if (hash.length !== 20) throw E("bad-input", "msPreviousCertHash must be a 20-octet SHA-1 certificate thumbprint");
1010
+ return b.octetString(hash);
1011
+ }
1012
+ /** @internal The legacy v1 template name is a BMPString, which is UCS-2, so a character outside the
1013
+ * basic multilingual plane has no encoding; `b.bmpString` refuses one and the fault is named here. */
1014
+ function extMsEnrollCertType(v) {
1015
+ if (typeof v !== "string" || !v.length) throw E("bad-input", "msEnrollCertType must be a non-empty template name");
1016
+ try { return b.bmpString(v); }
1017
+ catch (e) {
1018
+ if (e instanceof ErrorClass) throw e;
1019
+ throw E("bad-input", "msEnrollCertType must be text a BMPString can carry", e);
1020
+ }
1021
+ }
962
1022
  function ext(oidStr, critical, valueDer) {
963
1023
  var children = [b.oid(oidStr)];
964
1024
  if (critical) children.push(b.boolean(true));
@@ -1146,6 +1206,8 @@ function makeBuilder(ctx) {
1146
1206
  extKeyUsage: extKeyUsage, extExtKeyUsage: extExtKeyUsage, validateBcSpec: validateBcSpec,
1147
1207
  extBasicConstraints: extBasicConstraints, pathLen: pathLen, extSki: extSki, extAki: extAki, AKI_KEYS: AKI_KEYS,
1148
1208
  extSan: extSan, extCertPolicies: extCertPolicies, ext: ext,
1209
+ extMsCertificateTemplate: extMsCertificateTemplate, extMsCaVersion: extMsCaVersion,
1210
+ extMsPreviousCertHash: extMsPreviousCertHash, extMsEnrollCertType: extMsEnrollCertType,
1149
1211
  spkiKeyId: spkiKeyId, skiKeyId: skiKeyId,
1150
1212
  reqDer: reqDer, reqDenseArray: reqDenseArray, reqDerSequence: reqDerSequence, assertValidSpki: assertValidSpki, assertValidExtension: assertValidExtension,
1151
1213
  assertCertCriticality: assertCertCriticality,
package/lib/x509-sign.js CHANGED
@@ -56,6 +56,8 @@ var KNOWN_EXT_KEYS = intrinsic.assign(intrinsic.create(null), {
56
56
  policyConstraints: 1, inhibitAnyPolicy: 1, policyMappings: 1, policyMappingsCritical: 1,
57
57
  issuerAltName: 1, qcStatements: 1, qcStatementsCritical: 1,
58
58
  precertificatePoison: 1, signedCertificateTimestampList: 1,
59
+ msCertificateTemplate: 1, msEnrollCertType: 1, msCaVersion: 1, msPreviousCertHash: 1,
60
+ msApplicationPolicies: 1,
59
61
  });
60
62
 
61
63
  var _b = pkiBuild.makeBuilder({ ErrorClass: CertificateError, prefix: "x509", O: O, NS: NS, NAME_SCHEMA: NAME_SCHEMA, SPKI_SCHEMA: SPKI_SCHEMA, EXT_DECODERS: EXT_DECODERS });
@@ -220,6 +222,16 @@ function _buildExtensions(extSpec, ctx) {
220
222
  guard.list.append(out, _ext(O("signedCertificateTimestampList"), false,
221
223
  _encodeSctList(extSpec.signedCertificateTimestampList)));
222
224
  }
225
+ /** @internal The Active Directory Certificate Services enrollment extensions. Neither
226
+ * pki.path.validate nor pki.lint processes them, so a critical instance is refused as an
227
+ * unrecognized critical extension by this toolkit's own readers; they are emitted non-critical and
228
+ * no knob reaches the other form. msApplicationPolicies is read with the certificate-policies
229
+ * rules, so it takes that spec and shares its encoder. */
230
+ if (extSpec.msCertificateTemplate != null) guard.list.append(out, _ext(O("msCertificateTemplate"), false, _b.extMsCertificateTemplate(extSpec.msCertificateTemplate)));
231
+ if (extSpec.msEnrollCertType != null) guard.list.append(out, _ext(O("msEnrollCertType"), false, _b.extMsEnrollCertType(extSpec.msEnrollCertType)));
232
+ if (extSpec.msCaVersion != null) guard.list.append(out, _ext(O("msCaVersion"), false, _b.extMsCaVersion(extSpec.msCaVersion)));
233
+ if (extSpec.msPreviousCertHash != null) guard.list.append(out, _ext(O("msPreviousCertHash"), false, _b.extMsPreviousCertHash(extSpec.msPreviousCertHash)));
234
+ if (extSpec.msApplicationPolicies != null) guard.list.append(out, _ext(O("msApplicationPolicies"), false, _extCertPolicies(extSpec.msApplicationPolicies)));
223
235
  return out;
224
236
  }
225
237
 
@@ -388,6 +400,16 @@ function _hasCriticalSan(extSpec) {
388
400
  * know an unknown syntax. `pki.path.validate` does not process this extension, so it is emitted
389
401
  * non-critical unless `qcStatementsCritical` is set.
390
402
  *
403
+ * The Active Directory Certificate Services enrollment extensions are written from the same spec.
404
+ * `extensions.msCertificateTemplate` takes `{ templateID, templateMajorVersion, templateMinorVersion }`,
405
+ * the versions optional and each a DWORD, a minor version requiring a major one;
406
+ * `extensions.msEnrollCertType` takes the legacy v1 template name as a BMPString;
407
+ * `extensions.msCaVersion` takes `{ caKeyIndex, certIndex }` or the composed DWORD;
408
+ * `extensions.msPreviousCertHash` takes the 20-octet SHA-1 thumbprint of the previous CA certificate;
409
+ * and `extensions.msApplicationPolicies` takes the `certificatePolicies` spec, which is what its
410
+ * reader applies. All five are emitted non-critical, since neither `pki.path.validate` nor
411
+ * `pki.lint.certificate` processes them and a critical instance is refused as unrecognized.
412
+ *
391
413
  * `extensions.precertificatePoison: true` issues an RFC 6962 sec. 3.1 precertificate: the poison is
392
414
  * emitted critical with an ASN.1 NULL value, which is what stops a standard X.509v3 client from
393
415
  * validating the precertificate as an issued certificate. `extensions.signedCertificateTimestampList`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.7.20",
3
+ "version": "0.7.21",
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:7119a676-9de0-44f7-b083-f8da3c2fc5dd",
5
+ "serialNumber": "urn:uuid:8e02ed72-83e4-47e8-a838-add75caacb27",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-11T17:28:39.353Z",
8
+ "timestamp": "2026-09-11T18:14:13.702Z",
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.20",
22
+ "bom-ref": "@blamejs/pki@0.7.21",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.7.20",
25
+ "version": "0.7.21",
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.20",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.7.21",
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.20",
57
+ "ref": "@blamejs/pki@0.7.21",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]