@blamejs/pki 0.7.19 → 0.7.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,19 @@ All notable changes to `@blamejs/pki` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## v0.7.20 — 2026-09-11
8
+
9
+ Certificate policies carry their qualifiers, and the authority key identifier names the issuing certificate.
10
+
11
+ ### Added
12
+
13
+ - extensions.certificatePolicies takes an entry object { oid, cps, userNotice } beside the registered name or dotted OID it already took. cps is the certification-practice-statement URI (RFC 5280 section 4.2.1.4 id-qt-cps), and userNotice takes { noticeRef, explicitText }, either or both, where noticeRef is { organization, noticeNumbers }. Every DisplayText is emitted as a UTF8String, the encoding section 4.2.1.4 names for a conforming CA and the one it forbids replacing with VisibleString or BMPString, and is held to its SIZE (1..200) bound counted the way the reader counts it. The qualifiers sequence is written only when a qualifier is named, since the reader refuses an empty one. It is accepted on the pki.csr.sign extensionRequest as well.
14
+ - extensions.authorityKeyIdentifier takes an object { keyIdentifier, authorityCertIssuer, authorityCertSerialNumber } beside true and a BufferSource key id, so a certificate can name its issuing certificate by name and serial (RFC 5280 section 4.2.1.1). The issuer name and the serial are both present or both absent, the rule the reader already applied. Each of the two also takes true, which reads it from the issuing certificate, so the pair identifies the certificate that actually signed this one.
15
+
16
+ ### Fixed
17
+
18
+ - pki.asn1.build.utf8 refused nothing for an unpaired UTF-16 surrogate and converted it to U+FFFD, so a certificate carried text its issuer never wrote. A distinguished-name attribute was the reachable case: a common name holding a lone surrogate was signed with the replacement character in place of it. The encoder now refuses ill-formed UTF-16 with asn1/bad-utf8-string, the same verdict the decoder already returned for those bytes and the rule build.bmpString already applied. A well-formed surrogate pair is unaffected.
19
+
7
20
  ## v0.7.19 — 2026-09-11
8
21
 
9
22
  Certificate transparency can be issued, not only verified.
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), 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), 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, 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` |
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/asn1-der.js CHANGED
@@ -515,6 +515,23 @@ function readNumericString(node) {
515
515
  return s;
516
516
  }
517
517
 
518
+ /** @internal An unpaired surrogate has no UTF-8 encoding. Converting one anyway substitutes U+FFFD,
519
+ * so the bytes written would not carry the string the caller handed in, and `_decodeUtf8Strict`
520
+ * refuses exactly those bytes on the way back. The builder answers the same way rather than
521
+ * silently changing the text, which is the rule `_decodeUtf16be` already applies to BMPString. */
522
+ function _assertWellFormedUtf16(s) {
523
+ for (var i = 0; i < s.length; i++) {
524
+ var c = _charCodeAt(s, i);
525
+ if (c >= 0xD800 && c <= 0xDBFF) {
526
+ var n = (i + 1) < s.length ? _charCodeAt(s, i + 1) : -1;
527
+ if (!(n >= 0xDC00 && n <= 0xDFFF)) throw new Asn1Error("asn1/bad-utf8-string", "UTF8String has an unpaired high surrogate");
528
+ i++;
529
+ } else if (c >= 0xDC00 && c <= 0xDFFF) {
530
+ throw new Asn1Error("asn1/bad-utf8-string", "UTF8String has an unpaired low surrogate");
531
+ }
532
+ }
533
+ }
534
+
518
535
  function _decodeUtf8Strict(buf) {
519
536
  try {
520
537
  return new TextDecoder("utf-8", { fatal: true }).decode(buf);
@@ -849,7 +866,7 @@ var build = intrinsic.assign(intrinsic.create(null), {
849
866
  for (i = 0; i < positions.length; i++) { p = positions[i]; buf[p >> 3] |= 0x80 >> (p & 7); }
850
867
  return build.bitString(buf, 7 - (hi & 7));
851
868
  },
852
- utf8: function (s) { return _universal(TAGS.UTF8_STRING, false, Buffer.from(String(s), "utf8")); },
869
+ utf8: function (s) { var v = String(s); _assertWellFormedUtf16(v); return _universal(TAGS.UTF8_STRING, false, Buffer.from(v, "utf8")); },
853
870
  ia5: function (s) {
854
871
  s = String(s);
855
872
  for (var i = 0; i < s.length; i++) {
package/lib/pki-build.js CHANGED
@@ -12,6 +12,7 @@ var _isArray = intrinsic.isArray;
12
12
  var _bufferFrom = intrinsic.bufferFrom;
13
13
  var _bufferEquals = intrinsic.bufferEquals;
14
14
  var oid = require("./oid");
15
+ var pkix = require("./schema-pkix");
15
16
  var ipUtils = require("./ip-utils");
16
17
  var _packIpLiteral = ipUtils.packIpLiteral;
17
18
  var nodeCrypto = require("crypto");
@@ -261,6 +262,14 @@ var AIA_KEYS = intrinsic.assign(intrinsic.create(null), { accessMethod: 1, acces
261
262
  var PC_KEYS = intrinsic.assign(intrinsic.create(null), { requireExplicitPolicy: 1, inhibitPolicyMapping: 1 });
262
263
  var PM_KEYS = intrinsic.assign(intrinsic.create(null), { issuerDomainPolicy: 1, subjectDomainPolicy: 1 });
263
264
  var QC_STATEMENT_KEYS = intrinsic.assign(intrinsic.create(null), { statementId: 1, info: 1 });
265
+ /** @internal The fields of a certificate-policy entry and of the qualifiers it may carry (RFC 5280
266
+ * sec. 4.2.1.4), and of the authority key identifier (sec. 4.2.1.1). A key outside its object's set
267
+ * is refused rather than ignored: a misspelled field would otherwise be dropped and the certificate
268
+ * would carry a policy or an identifier the caller did not write. */
269
+ var POLICY_ENTRY_KEYS = intrinsic.assign(intrinsic.create(null), { oid: 1, cps: 1, userNotice: 1 });
270
+ var USER_NOTICE_KEYS = intrinsic.assign(intrinsic.create(null), { noticeRef: 1, explicitText: 1 });
271
+ var NOTICE_REF_KEYS = intrinsic.assign(intrinsic.create(null), { organization: 1, noticeNumbers: 1 });
272
+ var AKI_KEYS = intrinsic.assign(intrinsic.create(null), { keyIdentifier: 1, authorityCertIssuer: 1, authorityCertSerialNumber: 1 });
264
273
  /** @internal The fields each typed statementInfo defines, by statement id. A key outside its
265
274
  * statement's set is refused rather than ignored: a misspelled field would otherwise be dropped and
266
275
  * the certificate would carry a statement the caller did not write. */
@@ -482,7 +491,25 @@ function makeBuilder(ctx) {
482
491
  return BigInt(v);
483
492
  }
484
493
  function extSki(keyid) { return b.octetString(keyid); }
485
- function extAki(keyid) { return b.sequence([b.contextPrimitive(0, keyid)]); }
494
+ /** @internal AuthorityKeyIdentifier ::= SEQUENCE { keyIdentifier [0] OPTIONAL, authorityCertIssuer
495
+ * [1] OPTIONAL, authorityCertSerialNumber [2] OPTIONAL } (RFC 5280 sec. 4.2.1.1), in that order.
496
+ * The reader requires the issuer name and the serial to be both present or both absent, so the
497
+ * builder is held to the same rule: one structure drives both directions. */
498
+ function extAki(keyid, issuerNames, serial) {
499
+ if ((issuerNames == null) !== (serial == null)) {
500
+ throw E("bad-input", "authorityKeyIdentifier authorityCertIssuer and authorityCertSerialNumber must both be present or both absent (RFC 5280 sec. 4.2.1.1)");
501
+ }
502
+ var fields = [];
503
+ if (keyid != null) guard.list.append(fields, b.contextPrimitive(0, keyid));
504
+ if (issuerNames != null) {
505
+ guard.list.append(fields, encodeGeneralNames(reqDenseArray(issuerNames, "authorityKeyIdentifier authorityCertIssuer"), 1));
506
+ guard.list.append(fields, b.contextPrimitive(2, asn1.decode(serialInteger(serial)).content));
507
+ }
508
+ if (!fields.length) {
509
+ throw E("bad-input", "authorityKeyIdentifier must name a keyIdentifier, or an authorityCertIssuer with its authorityCertSerialNumber");
510
+ }
511
+ return b.sequence(fields);
512
+ }
486
513
  function encodeGeneralNames(entries, implicitTag) {
487
514
  if (!_isArray(entries) || !entries.length) throw E("bad-input", "a GeneralNames must carry at least one GeneralName");
488
515
  var members = entries.map(encodeGeneralName);
@@ -851,14 +878,85 @@ function makeBuilder(ctx) {
851
878
  }
852
879
  return b.sequence(kids);
853
880
  }
881
+ /** @internal DisplayText is SIZE (1..200) counted in characters, and sec. 4.2.1.4 forbids a
882
+ * conforming CA from encoding it as VisibleString or BMPString while naming UTF8String as the form
883
+ * such a CA uses. Emitting UTF8String settles the encoding rule by construction; the size is
884
+ * counted with the reader's own counter so the two can never disagree, and a control character is
885
+ * refused because the section says the string should carry none. */
886
+ function displayText(v, who) {
887
+ if (typeof v !== "string") throw E("bad-input", who + " must be a string");
888
+ var chars = pkix.displayTextChars(v);
889
+ if (chars < 1 || chars > pkix.DISPLAY_TEXT_MAX) {
890
+ throw E("bad-input", who + " must be 1 to " + pkix.DISPLAY_TEXT_MAX + " characters (RFC 5280 sec. 4.2.1.4)");
891
+ }
892
+ for (var i = 0; i < v.length; i++) {
893
+ var c = _charCodeAt(v, i);
894
+ if (c <= 0x1F || (c >= 0x7F && c <= 0x9F)) {
895
+ throw E("bad-input", who + " must not carry a control character (RFC 5280 sec. 4.2.1.4)");
896
+ }
897
+ }
898
+ /** @internal The text is named in a TYPED spec, so text the codec cannot encode is a fault in
899
+ * the spec this verb was handed, reported against this verb rather than as an asn1/* code. */
900
+ try { return b.utf8(v); }
901
+ catch (e) {
902
+ if (e instanceof ErrorClass) throw e;
903
+ throw E("bad-input", who + " must be text the UTF8String encoding can carry", e);
904
+ }
905
+ }
906
+ /** @internal UserNotice ::= SEQUENCE { noticeRef OPTIONAL, explicitText OPTIONAL }, in that order.
907
+ * Both fields are optional, which is the form the reader accepts, so a notice naming neither is
908
+ * an empty SEQUENCE rather than a fault. */
909
+ function userNoticeDer(notice, who) {
910
+ guard.identifier.assertKnownKeys(notice, USER_NOTICE_KEYS, E, "bad-input", function (k) {
911
+ return "unknown " + who + " field " + _stringify(k) + " (accepted: noticeRef, explicitText)";
912
+ });
913
+ var fields = [];
914
+ if (notice.noticeRef != null) {
915
+ var ref = notice.noticeRef;
916
+ if (typeof ref !== "object" || _isArray(ref) || _isBufferChk(ref)) throw E("bad-input", who + " noticeRef must be an object { organization, noticeNumbers }");
917
+ guard.identifier.assertKnownKeys(ref, NOTICE_REF_KEYS, E, "bad-input", function (k) {
918
+ return "unknown " + who + " noticeRef field " + _stringify(k) + " (accepted: organization, noticeNumbers)";
919
+ });
920
+ if (ref.organization == null) throw E("bad-input", who + " noticeRef requires an organization");
921
+ if (!_isArray(ref.noticeNumbers)) throw E("bad-input", who + " noticeRef requires a noticeNumbers array");
922
+ var nums = _mapIntrinsic(reqDenseArray(ref.noticeNumbers, who + " noticeRef noticeNumbers"), function (n, i) {
923
+ return b.integer(guard.range.authoredInteger(n, rawErr, ctx.prefix + "/bad-input", who + " noticeRef noticeNumber " + i));
924
+ });
925
+ guard.list.append(fields, b.sequence([displayText(ref.organization, who + " noticeRef organization"), b.sequence(nums)]));
926
+ }
927
+ if (notice.explicitText != null) guard.list.append(fields, displayText(notice.explicitText, who + " explicitText"));
928
+ return b.sequence(fields);
929
+ }
930
+ /** @internal PolicyInformation ::= SEQUENCE { policyIdentifier, policyQualifiers SIZE (1..MAX)
931
+ * OPTIONAL }. The qualifiers sequence is emitted only when a qualifier is named, because the
932
+ * reader refuses an empty one. A bare name or dotted OID stays the shipped shorthand. */
854
933
  function extCertPolicies(names) {
855
934
  if (!_isArray(names) || !names.length) throw E("bad-input", "certificatePolicies must list at least one policy OID");
856
935
  var seen = intrinsic.create(null);
857
- return b.sequence(names.map(function (n) {
858
- var pOid = _resolveOid(n, "certificate policy");
859
- if (seen[pOid]) throw E("bad-input", "duplicate certificate policy " + guard.text.showValue(n) + " (RFC 5280 sec. 4.2.1.4)");
936
+ return b.sequence(_mapIntrinsic(names, function (n, i) {
937
+ var entry = n, quals = [];
938
+ if (n != null && typeof n === "object" && !_isArray(n) && !_isBufferChk(n)) {
939
+ guard.identifier.assertKnownKeys(n, POLICY_ENTRY_KEYS, E, "bad-input", function (k) {
940
+ return "unknown certificatePolicies entry " + i + " field " + _stringify(k) + " (accepted: oid, cps, userNotice)";
941
+ });
942
+ entry = n.oid;
943
+ if (n.cps != null) {
944
+ if (typeof n.cps !== "string" || !n.cps.length) throw E("bad-input", "certificatePolicies entry " + i + " cps must be a non-empty URI string");
945
+ ia5Content(n.cps);
946
+ guard.list.append(quals, b.sequence([b.oid(oid.byName("cps")), b.ia5(n.cps)]));
947
+ }
948
+ if (n.userNotice != null) {
949
+ if (typeof n.userNotice !== "object" || _isArray(n.userNotice) || _isBufferChk(n.userNotice)) {
950
+ throw E("bad-input", "certificatePolicies entry " + i + " userNotice must be an object { noticeRef?, explicitText? }");
951
+ }
952
+ guard.list.append(quals, b.sequence([b.oid(oid.byName("unotice")),
953
+ userNoticeDer(n.userNotice, "certificatePolicies entry " + i + " userNotice")]));
954
+ }
955
+ }
956
+ var pOid = _resolveOid(entry, "certificate policy");
957
+ if (seen[pOid]) throw E("bad-input", "duplicate certificate policy " + guard.text.showValue(entry) + " (RFC 5280 sec. 4.2.1.4)");
860
958
  seen[pOid] = true;
861
- return b.sequence([b.oid(pOid)]);
959
+ return quals.length ? b.sequence([b.oid(pOid), b.sequence(quals)]) : b.sequence([b.oid(pOid)]);
862
960
  }));
863
961
  }
864
962
  function ext(oidStr, critical, valueDer) {
@@ -1046,7 +1144,7 @@ function makeBuilder(ctx) {
1046
1144
  encodeGeneralNames: encodeGeneralNames, serialInteger: serialInteger, timeDer: timeDer,
1047
1145
  requestedExtensions: requestedExtensions,
1048
1146
  extKeyUsage: extKeyUsage, extExtKeyUsage: extExtKeyUsage, validateBcSpec: validateBcSpec,
1049
- extBasicConstraints: extBasicConstraints, pathLen: pathLen, extSki: extSki, extAki: extAki,
1147
+ extBasicConstraints: extBasicConstraints, pathLen: pathLen, extSki: extSki, extAki: extAki, AKI_KEYS: AKI_KEYS,
1050
1148
  extSan: extSan, extCertPolicies: extCertPolicies, ext: ext,
1051
1149
  spkiKeyId: spkiKeyId, skiKeyId: skiKeyId,
1052
1150
  reqDer: reqDer, reqDenseArray: reqDenseArray, reqDerSequence: reqDerSequence, assertValidSpki: assertValidSpki, assertValidExtension: assertValidExtension,
package/lib/x509-sign.js CHANGED
@@ -88,6 +88,33 @@ function _akiKeyId(val, ctx) {
88
88
  throw _err("x509/bad-input", "authorityKeyIdentifier must be true (auto-derive from the issuer) or a Buffer key id");
89
89
  }
90
90
 
91
+ /** @internal The extension also names the issuing certificate directly (RFC 5280 sec. 4.2.1.1), so
92
+ * the spec takes the object form beside the `true` and key-id shorthands. The key id is resolved
93
+ * here because only this verb knows the issuer being signed under. */
94
+ function _akiFields(val, ctx) {
95
+ if (val === true || guard.bytes.isByteSource(val)) return [_akiKeyId(val, ctx), null, null];
96
+ if (typeof val !== "object" || _isArray(val)) {
97
+ throw _err("x509/bad-input", "authorityKeyIdentifier must be true, a Buffer key id, or an object { keyIdentifier, authorityCertIssuer, authorityCertSerialNumber }");
98
+ }
99
+ guard.identifier.assertKnownKeys(val, _b.AKI_KEYS, _err, "x509/bad-input", function (k) {
100
+ return "unknown authorityKeyIdentifier field " + guard.text.showValue(k) + " (accepted: keyIdentifier, authorityCertIssuer, authorityCertSerialNumber)";
101
+ });
102
+ /** @internal The pair identifies the certificate whose key signed this one, so when that
103
+ * certificate is the issuer being signed under, `true` takes its issuer name and serial from it.
104
+ * A caller that states the values itself keeps them, since an issuer given as a bare name and key
105
+ * carries no certificate to read them from. */
106
+ var issuerName = val.authorityCertIssuer, serial = val.authorityCertSerialNumber;
107
+ if (issuerName === true || serial === true) {
108
+ if (!ctx.issuerCert) {
109
+ throw _err("x509/bad-input", "authorityCertIssuer and authorityCertSerialNumber derive from the issuing certificate, so they are named directly when the issuer is given as a name and key");
110
+ }
111
+ if (issuerName === true) issuerName = [{ directoryName: ctx.issuerCert.issuer.bytes }];
112
+ if (serial === true) serial = "0x" + ctx.issuerCert.serialNumberHex;
113
+ }
114
+ return [val.keyIdentifier == null ? null : _akiKeyId(val.keyIdentifier, ctx),
115
+ issuerName == null ? null : issuerName, serial == null ? null : serial];
116
+ }
117
+
91
118
  function _buildExtensions(extSpec, ctx) {
92
119
  if (extSpec == null) return [];
93
120
  if (_isArray(extSpec)) {
@@ -142,7 +169,10 @@ function _buildExtensions(extSpec, ctx) {
142
169
 
143
170
  var out = [];
144
171
  if (extSpec.subjectKeyIdentifier != null) out.push(_ext(O("subjectKeyIdentifier"), false, _extSki(_skiKeyId(extSpec.subjectKeyIdentifier, ctx.spki))));
145
- if (extSpec.authorityKeyIdentifier != null) out.push(_ext(O("authorityKeyIdentifier"), false, _extAki(_akiKeyId(extSpec.authorityKeyIdentifier, ctx))));
172
+ if (extSpec.authorityKeyIdentifier != null) {
173
+ var akiF = _akiFields(extSpec.authorityKeyIdentifier, ctx);
174
+ out.push(_ext(O("authorityKeyIdentifier"), false, _extAki(akiF[0], akiF[1], akiF[2])));
175
+ }
146
176
  if (ku != null) out.push(_ext(O("keyUsage"), extSpec.keyUsageCritical !== false, _extKeyUsage(ku)));
147
177
  if (extSpec.extendedKeyUsage != null) out.push(_ext(O("extKeyUsage"), !!extSpec.extendedKeyUsageCritical, _extExtKeyUsage(extSpec.extendedKeyUsage)));
148
178
  if (bc != null) {
@@ -329,6 +359,20 @@ function _hasCriticalSan(extSpec) {
329
359
  * `extensions.issuerAltName` takes the `GeneralName` forms `subjectAltName` takes and is emitted
330
360
  * non-critical (sec. 4.2.1.7).
331
361
  *
362
+ * `extensions.certificatePolicies` takes a policy as a registered name, a dotted OID, or an entry
363
+ * object `{ oid, cps, userNotice }` carrying the RFC 5280 sec. 4.2.1.4 qualifiers: `cps` is the
364
+ * certification-practice-statement URI, and `userNotice` takes `{ noticeRef, explicitText }`, either
365
+ * or both, where `noticeRef` is `{ organization, noticeNumbers }`. Every DisplayText is emitted as a
366
+ * UTF8String, the encoding the section names for a conforming CA, and is held to its SIZE (1..200)
367
+ * bound counted in characters.
368
+ *
369
+ * `extensions.authorityKeyIdentifier` takes `true` to derive the key id from the issuer, a
370
+ * `BufferSource` key id, or an object `{ keyIdentifier, authorityCertIssuer, authorityCertSerialNumber }`
371
+ * naming the issuing certificate directly (RFC 5280 sec. 4.2.1.1). The issuer name and the serial are
372
+ * both present or both absent, which is the rule the reader applies. Each of the two also takes
373
+ * `true`, which reads it from the issuing certificate, so the pair identifies the certificate that
374
+ * actually signed this one; `true` requires an issuer given as a certificate.
375
+ *
332
376
  * `extensions.qcStatements` builds the RFC 3739 sec. 3.2.6 qualified-certificate statements, as a
333
377
  * list of `{ statementId, info? }`. A statement the toolkit knows encodes its own value syntax:
334
378
  * `qcCompliance` and `qcSSCD` carry no `info` at all; `qcType` and `qcIdentMethod` take
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.7.19",
3
+ "version": "0.7.20",
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:9a8b346d-38b9-4792-b70f-f2986d11bd89",
5
+ "serialNumber": "urn:uuid:7119a676-9de0-44f7-b083-f8da3c2fc5dd",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-11T12:04:27.448Z",
8
+ "timestamp": "2026-09-11T17:28:39.353Z",
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.19",
22
+ "bom-ref": "@blamejs/pki@0.7.20",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.7.19",
25
+ "version": "0.7.20",
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.19",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.7.20",
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.19",
57
+ "ref": "@blamejs/pki@0.7.20",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]