@blamejs/pki 0.7.34 → 0.7.36

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,34 @@ 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.36 — 2026-09-12
8
+
9
+ The attribute-certificate signer holds its extensions and attributes to the RFC 5755 issuer rules, and emits the authority key identifier by default.
10
+
11
+ ### Added
12
+
13
+ - pki.attrcert.sign takes crlDistributionPoints and authorityInfoAccess in the list forms pki.x509.sign takes, each emitted non-critical as RFC 5755 sec. 4.3.4 and 4.3.5 require, so the sec. 6 "pointer in AC" revocation scheme needs no pre-encoded Extension DER.
14
+ - pki.schema.attrcert.parse decodes an attribute certificate's authorityKeyIdentifier, authorityInfoAccess and cRLDistributionPoints through the RFC 5280 readers, so a relying party running the "pointer in AC" scheme reads the distribution point and the OCSP location off the parse instead of off raw bytes.
15
+
16
+ ### Changed
17
+
18
+ - pki.attrcert.sign emits the authorityKeyIdentifier without being named (RFC 5755 sec. 4.3.3: "this extension SHOULD be included in ACs"). Its keyIdentifier is the AA certificate's subjectKeyIdentifier when issuer.cert is given, else the RFC 5280 method (1) value of the AA key; a stated keyIdentifier that differs from the AA certificate's is refused; authorityKeyIdentifier: false omits it. The pre-encoded array form of extensions emits exactly what it is given.
19
+ - pki.attrcert.sign refuses, with attrcert/bad-input and on both extension forms, what RFC 5755 forbids an issuer to produce: an auditIdentity that is not 1 to 20 octets (sec. 4.3.1); a targetInformation carrying more than one Targets element or a targetCert (sec. 4.3.2); an id-ad-ocsp accessLocation that is not a URI carrying an HTTP URL (sec. 4.3.4); a crlDistributionPoints that does not name exactly one distribution point as a fullName holding a single directoryName or an HTTP or LDAP URL, or whose cRLIssuer does not name the CRL issuer as a directoryName (sec. 4.3.5, RFC 5280 sec. 4.2.1.13); and a role whose roleName is not a uniformResourceIdentifier (sec. 4.4.5), on the object form and the pre-encoded Attribute form alike.
20
+
21
+ ## v0.7.35 — 2026-09-12
22
+
23
+ The timestamp signer refuses a TSA certificate its verifier would refuse, and keeps genTime's fraction of a second.
24
+
25
+ ### Changed
26
+
27
+ - pki.tsp.sign refuses a TSA certificate that does not satisfy RFC 3161 sec. 2.3: exactly one extendedKeyUsage extension, marked critical, naming id-kp-timeStamping alone, and a keyUsage that, when present, allows signing. The refusal carries the code pki.tsp.verify answers for the same certificate (tsp/bad-eku, tsp/eku-not-critical, tsp/eku-not-exclusive, tsp/bad-key-usage), so a TSA operator learns at signing time what a relying party would say.
28
+ - genTime keeps the Date's milliseconds as the sec. 2.4.2 fraction of a second, in the X.690 DER form (a point followed by the digits, trailing zeros omitted, no fraction for a whole second), which pki.schema.tsp.parseToken already read; a whole-second genTime encodes as before. pki.asn1.build.generalizedTime takes { fractional: true } for this form.
29
+ - accuracy given as an object naming none of seconds, millis, micros is refused with tsp/bad-input: sec. 2.4.2 reads an absent field as zero, so an empty Accuracy asserted a zero deviation; omit the option to make no claim.
30
+
31
+ ### Fixed
32
+
33
+ - pki.asn1.build.generalizedTime, pki.asn1.build.utcTime and pki.asn1.read.time read a Date's fields through the Date.prototype accessors captured when the module loaded. A getter overridden on the Date instance, or a Date.prototype method replaced after load, no longer changes the encoded time or the Date the reader returns.
34
+
7
35
  ## v0.7.34 — 2026-09-12
8
36
 
9
37
  The OCSP signer refuses what its own lint grades an error.
package/README.md CHANGED
@@ -233,7 +233,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
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
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; both emitted without being named, the SKI on every certificate and the AKI on every certificate that is not self-signed, which is what RFC 5280 §4.2.1.1 and §4.2.1.2 place on the issuing CA, and `false` declines each only where the RFC allows the omission), 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), the Active Directory Certificate Services enrollment extensions (certificate template, legacy template name, CA version, previous-CA-certificate hash, application policies), subject information access, subject directory attributes, and the RFC 6960 OCSP no-check responder marker, from the spec. That is every extension the shared certificate-extension decoders read, so any certificate `pki.lint.certificate` and `pki.inspect` can read in full the toolkit 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. `extension(name, value, opts)` encodes one Extension DER from the same plain value form, for the pre-encoded array form on the certificate, CSR, and CRL signers: the criticality follows what the signer emits, `opts.critical` reaches only the extensions whose criticality is the issuer's choice, and an unregistered dotted OID takes its extnValue as bytes. Parsing stays at `pki.schema.x509.parse` — `sign`, `randomSerial`, `extension` |
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, the Microsoft certificate template and application policies, subject information access, subject directory attributes, or an array of pre-encoded Extension DER; an extension the issuing CA assigns, such as the authority key identifier or the OCSP no-check marker, is refused by name rather than requested), 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
- | `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` |
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, crlDistributionPoints, authorityInfoAccess, or pre-encoded Extension DER) each with its RFC 5755 criticality. The authorityKeyIdentifier is emitted without being named (sec. 4.3.3) and holds the AA certificate's subject key identifier; both extension forms are held to the rules sec. 4.3 and 4.4 place on the issuer (an audit identity of 1 to 20 octets, one Targets element and no targetCert, an OCSP location that is an HTTP URL, one distribution point naming a single DN or HTTP / LDAP URL, a role name that is a URI). 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 MAC algorithm it does not compute (reported as MAC-protected under that algorithm, never as a failed signature), 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` |
239
239
  | `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuer alternative name, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access, which is every extension RFC 5280 §5.2 defines) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The authority key identifier is emitted on every CRL whether or not it is named, as §5.2.1 places it on every conforming issuer, from the issuer certificate's SKI or the issuer key. The signature algorithm is resolved from the issuer key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
@@ -241,7 +241,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
241
241
  | `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
242
242
  | `pki.cms` | CMS signing, verification, encryption, and compression (RFC 5652). `sign(content, signers, opts)` produces a SignedData (§5), attached or detached, with one or many signers over RSA, RSASSA-PSS, ECDSA, EdDSA, the post-quantum ML-DSA-44/65/87 (RFC 9882) and SLH-DSA (all twelve FIPS 205 sets, RFC 9814), and composite ML-DSA pairing ML-DSA with a traditional RSA, ECDSA, or EdDSA key (accepted only when both components verify, draft-ietf-lamps-cms-composite-sigs). It builds the signed attributes (content-type, message-digest, signing-time) as canonical DER, signs the exact §5.4 preimage, and emits a DER `Buffer` or PEM. The content may also be an async iterable of byte chunks, which signs a large detached payload without holding it in memory: the payload is hashed incrementally under every signer's digest algorithm in one pass, and `verify` accepts the same streamed form as its `content` option. A signer may also be key-only — `{ key, spki, keyIdentifier }` with no certificate — which RFC 5272 §3.2 requires when a Full PKI Request's signer is the key of a certification request that request carries: the signer identifier takes the subjectKeyIdentifier form carrying the identifier the request declares, the signature scheme resolves from the request's own public key, and no certificate is embedded. `verify(input, opts)` parses a SignedData over the strict `pki.schema.cms` codec, locates each SignerInfo's signer certificate by its issuerAndSerialNumber or subjectKeyIdentifier, and checks the signature over the exact §5.4 preimage: with signed attributes present it confirms the message-digest attribute equals the content digest and verifies over the DER re-encoding of the SignedAttributes (the on-wire `[0]` tag replaced by a universal SET OF), and otherwise directly over the content. It returns a per-signer verdict with the matched signer certificate. `valid` and `trusted` are separate claims and neither implies the other: a SignedData carries its own certificates, so `valid` says the signature is sound under one of them and nothing about who signed, while `trusted` says every signer chained to a root named in `opts.trustAnchors`, validated through the same RFC 5280 path engine `pki.path.validate` uses. Without anchors there is nothing to chain to and `trusted` is `false`; anchors that cannot be read throw, rather than reading as untrusted. An unrecognized option is refused rather than ignored. `countersign(cms, signers, opts)` adds a countersignature (§11.4) — a `SignerInfo` over the countersigned SignerInfo's signature value, any signer algorithm, nestable, with the primary bytes preserved so it still verifies — attached as the id-countersignature unsigned attribute; `verify` returns each countersignature's verdict under `signers[i].countersignatures` and every unsigned attribute — including an RFC 3161 timestamp token, attachable via `sign`'s `unsignedAttributes` — under `signers[i].unsignedAttrs`, surfaced unauthenticated. `encrypt(content, recipients, opts)` produces an EnvelopedData, AuthEnvelopedData (AES-GCM, the authenticated default), or EncryptedData, with recipients auto-dispatched off the certificate key to key transport (RSAES-OAEP; v1.5 is never emitted), key agreement (ephemeral-static ECDH over P-256/384/521 with the X9.63 KDF, and X25519/X448 with HKDF), symmetric key wrap, password (PBKDF2 with RFC 3211 PWRI-KEK), or the post-quantum ML-KEM (and composite ML-KEM, draft-lamps-pq-composite-kem) KEMRecipientInfo (RFC 9629/9936), wrapping one fresh content key for every recipient. The content may also be an async iterable of byte chunks, streamed through the AES-GCM or AES-CBC content cipher so a large plaintext is encrypted without being buffered whole; the ciphertext is assembled before the definite-length encryptedContent is emitted, byte-for-byte the buffered form. `decrypt(input, keyMaterial, opts)` recovers the content through the matching arm and returns it with an `authenticated` flag; every secret-dependent failure collapses to one uniform `cms/decrypt-failed` verdict (Bleichenbacher, EFAIL, and password-oracle freedom), and PKCS#1 v1.5 is decrypt-only under the RFC 3218 implicit-rejection countermeasure. With `opts.stream: true` the recovered `content` is an async iterable of plaintext chunks instead of a single Buffer, for a payload too large to hold whole; the authenticated modes (AuthEnvelopedData, AuthenticatedData, AES-GCM) verify integrity before the iterable yields, so a forged message throws before any plaintext is exposed, while a CBC EnvelopedData or EncryptedData yields the plaintext as the cipher produces it. Every key-establishment secret the toolkit allocates is wiped once used, on the failing path as well as the succeeding one: the KEM shared secret and its derived key-encryption key, the raw ECDH / X25519 / X448 agreement secret, a password-derived key-encryption key, and the content-encryption key itself, cleared once the message is complete since all recipients share it. Caller-supplied key material is never written to (best-effort; NIST SP 800-227 §4.2, RFC 9629 §7). `authenticate(content, recipients, opts)` produces an `id-ct-authData` (§9): cleartext content plus an HMAC-SHA-256/384/512 MAC, authenticated but not encrypted, with the fresh MAC key wrapped for every recipient through the same RecipientInfo model. The MAC covers the authenticated attributes (content-type and message-digest) re-tagged to the EXPLICIT SET OF (§9.2), or the content octets directly; `decrypt` recovers the MAC key, recomputes the MAC and independently the message-digest (§9.3), and releases the content only after both pass, with every secret-dependent failure collapsing to the uniform `cms/decrypt-failed`. `compress(content, opts)` and `decompress(input, opts)` produce and consume a CompressedData (RFC 3274; ZLIB, version 0, id-alg-zlibCompress); decompress bounds the uncompressed output at 16 MiB and stops before it is materialized, so a decompression bomb fails closed as `cms/decompress-too-large`. Compression is a size transform with no integrity or confidentiality (RFC 8551 §2.4.5). `certsOnly(certs, opts?)` builds a certs-only certificate-management message (RFC 8551 §3.8): a degenerate SignedData with an empty signerInfos and no eContent that conveys certificates and CRLs without signing anything, `parseCertsOnly(input, opts?)` reads one back to its raw certificate and CRL DER (a CRL-only message is valid here, unlike the cert-required RFC 5272 form that `pki.est.parseCertsOnly` reads), and `isCertsOnly(input)` recognizes one structurally. Fail-closed with typed `cms/*` errors — `sign`, `verify`, `countersign`, `encrypt`, `authenticate`, `decrypt`, `compress`, `decompress`, `certsOnly`, `parseCertsOnly`, `isCertsOnly` |
243
243
  | `pki.smime` | S/MIME message assembly, verification, encryption, and compression over the CMS layer (RFC 8551). `sign(content, signers, opts)` wraps a MIME entity in either form: `multipart/signed`, where the content stays readable in any MUA and a detached CMS SignedData rides alongside as `application/pkcs7-signature` with a matching `micalg`, or `application/pkcs7-mime; smime-type=signed-data`, where the whole entity is a base64 CMS SignedData. The signed bytes are the entity's §3.1.1 canonical form with CRLF line endings, and `verify(message, opts)` unwraps both forms and recomputes over the same canonicalizer, so a transport that re-wraps line endings still verifies while a tampered part fails. `encrypt(content, recipients, opts)` envelopes a MIME entity as an opaque `application/pkcs7-mime` message and `decrypt(message, keyMaterial, opts)` opens one, as `smime-type=authEnveloped-data` (AES-GCM, confidentiality and integrity, the default) or `smime-type=enveloped-data` (AES-CBC, confidentiality only, so `decrypt` reports `authenticated: false`, the §3.3 no-integrity caveat). The `smime-type` is derived from the CMS body rather than the header, and decryption is fail-closed and oracle-free. The crypto is entirely `pki.cms.sign` / `verify` / `encrypt` / `decrypt`, so it is algorithm-agnostic: any RSA / RSASSA-PSS / ECDSA / EdDSA / ML-DSA / SLH-DSA signer and any RSA-OAEP / ECDH / X25519 / X448 / AES-KW / PBKDF2 / ML-KEM recipient carries through. As with `cms.verify`, `verify` returns the per-signer verdict plus the recovered content, and `valid` and `trusted` are separate claims: `valid` says the signature is sound under a certificate the message carried, `trusted` says every signer chained to a root named in `opts.trustAnchors`. Anchoring here is validated for email at both ends of the chain — the signer certificate must carry `emailProtection` (RFC 8551 §4.4.4) and the anchor's own trust metadata must permit that purpose, since a root can be distrusted for email while remaining a good TLS root. Override either with `requiredEku` / `checkPurpose`. `compress(content, opts)` and `decompress(message, opts)` add the opaque `application/pkcs7-mime; smime-type=compressed-data; name=smime.p7z` frame (§3.6, RFC 3274), a size transform with no integrity or confidentiality (§2.4.5), bounded against a bomb; the recovered content, which may itself be signed or enveloped, is returned for the caller to re-verify. Header protection (RFC 9788): `sign` and `encrypt` take `opts.protectHeaders`, which inlines the caller's `opts.headers` on the Cryptographic Payload root (its Content-Type gaining `hp="clear"` when signed or `hp="cipher"` when encrypted) so the CMS signature or encryption covers them, defeating a transport that rewrites or reads Subject, From, and the rest. `verify` and `decrypt` surface the authenticated inner set as `protectedHeaders` plus `headerProtection { present, mode, fromMismatch, confidential, legacy }`, so a tampered outer header cannot alter it and `fromMismatch` flags an outer From that disagrees. Encryption applies a Header Confidentiality Policy: the default `hcp_baseline` obscures the outer Subject to `[...]` and removes Comments and Keywords, so the real values live only in the ciphertext, and `decrypt` recovers them. Every emitted header routes through a fail-closed injection guard that rejects a CR, LF, or NUL value and a non-ftext name, and a malformed or contradictory `hp` wrap fails closed as `smime/bad-header-protection` rather than silently downgrading. The CMS crypto is unchanged. Inbound legacy RFC 8551 header protection is recognized opt-in: `verify` and `decrypt` with `opts.legacyHeaderProtection` detect a legacy `message/rfc822`-wrapped payload by the RFC 9788 §4.10.1 four-condition identification and surface the inner headers under `headerProtection.legacy = { headers, mode, fromMismatch, confidential }`, where `headers` is an ordered `[{ name, value }]` array retaining legally repeated fields such as `Received`. Those never appear in `protectedHeaders` and never set `present: true`. Because a legacy message is structurally indistinguishable from an ordinary forwarded `message/rfc822`, this is an explicit heuristic (§4.10.2, "no strong end-to-end guarantees"): a caller keying trust off `present` or `protectedHeaders` is never misled, and only one that explicitly reads `headerProtection.legacy.headers` and cross-checks `legacy.fromMismatch` consumes it. It is off by default, and a nested crypto layer, an inner `hp=`, a non-`message/rfc822` payload, or a duplicate Content-Type reports `legacy: null`. Bidirectionally interoperable with `openssl smime` and `openssl cms`. `buildCertsOnly(certs, opts?)` wraps a `pki.cms.certsOnly` certificate-management message in one `application/pkcs7-mime; smime-type=certs-only; name=smime.p7c` entity, read back by OpenSSL's `pkcs7 -print_certs`. Fail-closed with typed `smime/*` errors — `sign`, `verify`, `encrypt`, `decrypt`, `compress`, `decompress`, `buildCertsOnly` |
244
- | `pki.tsp` | Time-Stamp Protocol (RFC 3161). `sign(messageImprint, tsa, opts)` produces a TimeStampToken: a CMS SignedData over `pki.cms.sign` whose content is a `TSTInfo` carrying the timestamped message imprint, the TSA policy, a serial number, and `genTime` with optional accuracy, nonce, and ordering, plus the §2.4.2 signing-certificate attribute binding the token to the TSA certificate (SHA-2 imprints, any `pki.cms.sign` TSA key). `request` and `parseRequest` build and parse the TimeStampReq a client sends (imprint, requested policy, nonce, certReq); `response` and `parseResponse` handle the TimeStampResp a TSA returns, either a granted status wrapping a token or a rejection with PKIStatus and failure info, with the §2.4.2 status-to-token coupling enforced in both directions. `verify(token, data, opts)` verifies a token fail-closed: the CMS signature over the exact signed bytes, the message imprint recomputed from the data, the TSTInfo content type, the ESSCertID(V2) binding to the TSA certificate, the §2.3 critical timeStamping-only extendedKeyUsage, the request nonce when used, and, with a trust anchor supplied, full certification-path validation of the TSA certificate at the token's `genTime` — judged under the `timeStamping` purpose, so an anchor's own per-purpose trust metadata reaches the decision rather than sitting inert. It returns `{ valid, trusted, genTime, serialNumber, tstInfo, ... }`, where `trusted` is the separate claim that the authority chained to an anchor you named: without one there is nothing to chain to and it is `false`, which is the distinction a timestamp re-read years later turns on — `sign`, `request`, `parseRequest`, `response`, `parseResponse`, `verify` |
244
+ | `pki.tsp` | Time-Stamp Protocol (RFC 3161). `sign(messageImprint, tsa, opts)` produces a TimeStampToken: a CMS SignedData over `pki.cms.sign` whose content is a `TSTInfo` carrying the timestamped message imprint, the TSA policy, a serial number, and `genTime` with optional accuracy, nonce, and ordering, plus the §2.4.2 signing-certificate attribute binding the token to the TSA certificate (SHA-2 imprints, any `pki.cms.sign` TSA key). The TSA certificate is held to §2.3 before signing (one critical extendedKeyUsage naming timeStamping alone) with the codes `verify` answers, `genTime` keeps its milliseconds as the §2.4.2 fraction of a second, and an accuracy naming no field is refused. `request` and `parseRequest` build and parse the TimeStampReq a client sends (imprint, requested policy, nonce, certReq); `response` and `parseResponse` handle the TimeStampResp a TSA returns, either a granted status wrapping a token or a rejection with PKIStatus and failure info, with the §2.4.2 status-to-token coupling enforced in both directions. `verify(token, data, opts)` verifies a token fail-closed: the CMS signature over the exact signed bytes, the message imprint recomputed from the data, the TSTInfo content type, the ESSCertID(V2) binding to the TSA certificate, the §2.3 critical timeStamping-only extendedKeyUsage, the request nonce when used, and, with a trust anchor supplied, full certification-path validation of the TSA certificate at the token's `genTime` — judged under the `timeStamping` purpose, so an anchor's own per-purpose trust metadata reaches the decision rather than sitting inert. It returns `{ valid, trusted, genTime, serialNumber, tstInfo, ... }`, where `trusted` is the separate claim that the authority chained to an anchor you named: without one there is nothing to chain to and it is `false`, which is the distinction a timestamp re-read years later turns on — `sign`, `request`, `parseRequest`, `response`, `parseResponse`, `verify` |
245
245
  | `pki.ocsp` | Online Certificate Status Protocol (RFC 6960), both the responder and relying-party surface. `buildRequest(query, opts)` builds an OCSPRequest for one or more `{ cert, issuer }` pairs, with the CertID hashed under SHA-1 by default per the RFC 5019 lightweight profile or under SHA-2, plus an optional RFC 9654 nonce and an optional requestor signature. `sign(responseData, responder, opts)` produces a signed BasicOCSPResponse over the exact `ResponseData` DER, from the issuing CA directly or a delegated responder, under any `pki.cms.sign` key including the post-quantum ML-DSA and SLH-DSA sets, with `good`, `revoked` (reason and time), or `unknown` per-certificate status, and per-response `singleExtensions` naming the §4.4.4 archive cutoff and the §4.4.2 CRL reference as fields, each read back by name by the parser. The signer refuses what its own lint would grade an error: a pre-encoded singleExtension that RFC 6960 places in requests or in responseExtensions, a CRL entry extension carried at the wrong criticality, and CRL references or entry extensions on a non-issued response, which itself places the §4.4.8 extended revoked definition in responseExtensions without being asked. `buildErrorResponse(status)` produces the unsigned §2.3 error (`tryLater`, `unauthorized`, and the rest). `verify(response, opts)` verifies a response fail-closed against the same hardened gates `pki.path.ocspChecker` runs: the CertID binding, responder authorization (the issuing CA, or a CA-issued delegate bearing id-kp-OCSPSigning and id-pkix-ocsp-nocheck and passing the full out-of-path certificate gates), the signature over `tbsResponseDataBytes`, currency against `thisUpdate` and `nextUpdate`, and the request-nonce echo. It returns `{ status: "good" / "revoked" / "unknown", ... }` and never silently accepts. `verifyRequest(request, opts)` is the responder-side inverse of `buildRequest`: it verifies a client's signed request (RFC 6960 §4.1.1) under the requestor certificate the request carries, trying each embedded certificate since the field is unordered, and reports `signed`, `signatureValid`, every certificate whose key verified (`signerCerts`, so a key carried under an expired certificate beside its renewal is not hidden behind ordering) with the first one's decoded subject, the full embedded certificate bag (`certs`, including intermediates for path building), and the request's CertIDs; an unsigned request is reported with `signed: false` rather than refused. Transport-free — `buildRequest`, `sign`, `buildErrorResponse`, `verify`, `verifyRequest` |
246
246
  | `pki.ct` | Certificate Transparency (RFC 6962). `parseSctList` decodes the `SignedCertificateTimestampList` a certificate or OCSP response carries, a TLS-presentation-language payload inside the §3.3 double DER wrap, into per-SCT log id, exact `timestamp` (BigInt), named signature algorithm, and raw signature. `reconstructSignedData` rebuilds the exact `digitally-signed` preimage, and `verifySct` verifies an SCT signature against a log's public key, routing an ECDSA signature through the strict DER-conformance gate and verifying through the crypto engine, resolving true or false and throwing a typed error on a structural fault. On the producing side, `encodeSctList` builds the extension value byte for byte as the exact inverse of `parseSctList`, and `signSct` performs a log's signing step. For trust, `parseLogList` ingests the CT log-list JSON into constraint-carrying trusted logs, recomputing each log's id as SHA-256 of its key and refusing a disagreeing id (a swapped key, §3.2) and decoding the state and temporal-interval constraints; `verifySctWithLogList` resolves the log key from an SCT's log id, enforces the state (usable, qualified, and readonly trusted; retired only before retirement; pending and rejected refused) and the temporal-interval window, then delegates the signature check to `verifySct`. `verifyLogListSignature(json, signature, publicKey)` verifies the detached `log_list.sig` over the raw log-list bytes against a caller-pinned signer key (RSASSA-PKCS1-v1.5/SHA-256 and an EC P-256 arm, with forgeable-key defenses failing closed), cross-checked against `openssl dgst`. `fetchLogList(opts)` turns that chain into a live client: it GETs the `log_list.json` and its detached `log_list.sig` over `pki.transport`, verifies the detached signature over the raw fetched bytes against a caller-pinned distributor key before parsing, so an unverified document is never parsed, read, cached, or surfaced, then ingests the same bytes through `parseLogList` and returns the trusted-log set plus the surfaced `version` and `timestamp`. Above the per-SCT layer, `verifySctList` renders a certificate-level verdict over every SCT a certificate carries (§3.3), reporting how many distinct trusted logs verified an SCT (so a duplicated SCT cannot inflate the count) and from how many distinct trusted operators against a caller's CT policy (`minScts` and `minOperators`, both defaulting to the RFC floor of one), where a policy shortfall is a verdict and a per-SCT failure is a recorded row rather than a thrown call; `x509CertEntry` reconstructs the precertificate log entry from a final certificate by removing the SCT-list extension from its TBSCertificate as byte surgery, so its embedded SCTs verify end to end (§3.2). The toolkit bakes in no vendor URL or key, TLS trust is explicit with `rejectUnauthorized` always on, each response is size-capped before the trust chain, and the transport is injectable so the whole path is testable offline — `parseSctList`, `reconstructSignedData`, `verifySct`, `encodeSctList`, `signSct`, `parseLogList`, `verifySctWithLogList`, `verifySctList`, `x509CertEntry`, `verifyLogListSignature`, `fetchLogList` |
247
247
  | `pki.merkle` | Merkle-tree proof verification (RFC 6962 / RFC 9162). `leafHash`, `nodeHash`, and `emptyRootHash` build the domain-separated (0x00 leaf, 0x01 node) SHA-256 tree hashes. `verifyInclusion` folds an audit proof back to a root, and `verifyConsistency` reconstructs both the old and new root, which is the append-only guarantee; each is constant-time-compared to a trusted checkpoint root. Fail-closed on bad geometry, sync hashing, transport-free — `leafHash`, `nodeHash`, `emptyRootHash`, `verifyInclusion`, `verifyConsistency` |
package/lib/asn1-der.js CHANGED
@@ -25,6 +25,11 @@
25
25
  * is canonical, each value the `build.*` helpers emit has exactly one
26
26
  * valid encoding, byte-identical to any other conformant DER encoder's
27
27
  * output, and decoding it reproduces the value it was built from.
28
+ * `build.generalizedTime(date)` emits whole seconds, the RFC 5280 form;
29
+ * `build.generalizedTime(date, { fractional: true })` keeps the Date's
30
+ * milliseconds in the X.690 DER fraction (no trailing zeros, no empty
31
+ * fraction), the form RFC 3161 allows a timestamp's genTime, which
32
+ * `read.time(node, { allowFractional: true })` reads back.
28
33
  *
29
34
  * @card
30
35
  * Strict, fail-closed DER decode / encode with a navigable node tree
@@ -37,6 +42,18 @@ var guard = require("./guard-all");
37
42
  var intrinsic = require("./guard-intrinsic");
38
43
  var _isArray = intrinsic.isArray;
39
44
  var _charCodeAt = intrinsic.uncurry(String.prototype.charCodeAt);
45
+ /** @internal A Date's fields are read through the prototype's own getters, captured at load, so
46
+ * a getter the instance carries or one replaced later cannot change what a time encodes to or
47
+ * what the reader's own Date reports back. */
48
+ var _dateGetUTCFullYear = intrinsic.uncurry(Date.prototype.getUTCFullYear);
49
+ var _dateGetUTCMonth = intrinsic.uncurry(Date.prototype.getUTCMonth);
50
+ var _dateGetUTCDate = intrinsic.uncurry(Date.prototype.getUTCDate);
51
+ var _dateGetUTCHours = intrinsic.uncurry(Date.prototype.getUTCHours);
52
+ var _dateGetUTCMinutes = intrinsic.uncurry(Date.prototype.getUTCMinutes);
53
+ var _dateGetUTCSeconds = intrinsic.uncurry(Date.prototype.getUTCSeconds);
54
+ var _dateGetUTCMilliseconds = intrinsic.uncurry(Date.prototype.getUTCMilliseconds);
55
+ var _dateSetUTCFullYear = intrinsic.uncurry(Date.prototype.setUTCFullYear);
56
+ var _dateSetUTCHours = intrinsic.uncurry(Date.prototype.setUTCHours);
40
57
 
41
58
  var Asn1Error = frameworkError.Asn1Error;
42
59
  var OidError = frameworkError.OidError;
@@ -649,11 +666,11 @@ function readTime(node, opts) {
649
666
  var sec = t.sec;
650
667
  var ms = (node.tagNumber === TAGS.GENERALIZED_TIME && t.hasFrac) ? t.ms : 0;
651
668
  var d = new Date(0);
652
- d.setUTCFullYear(year, month - 1, day);
653
- d.setUTCHours(hour, min, sec, ms);
669
+ _dateSetUTCFullYear(d, year, month - 1, day);
670
+ _dateSetUTCHours(d, hour, min, sec, ms);
654
671
  if (isNaN(guard.time.instantOf(d))) throw new Asn1Error("asn1/bad-time", "unparseable time " + JSON.stringify(s));
655
- if (d.getUTCFullYear() !== year || d.getUTCMonth() !== month - 1 || d.getUTCDate() !== day ||
656
- d.getUTCHours() !== hour || d.getUTCMinutes() !== min || d.getUTCSeconds() !== sec) {
672
+ if (_dateGetUTCFullYear(d) !== year || _dateGetUTCMonth(d) !== month - 1 || _dateGetUTCDate(d) !== day ||
673
+ _dateGetUTCHours(d) !== hour || _dateGetUTCMinutes(d) !== min || _dateGetUTCSeconds(d) !== sec) {
657
674
  throw new Asn1Error("asn1/bad-time", "time component out of range " + JSON.stringify(s));
658
675
  }
659
676
  return d;
@@ -800,22 +817,46 @@ function _isNumericString(s) {
800
817
 
801
818
  function _fmtTwo(n) { return (n < 10 ? "0" : "") + n; }
802
819
 
803
- function _generalizedTimeString(date) {
804
- var y = date.getUTCFullYear();
820
+ function _generalizedTimeString(date, fractional) {
821
+ var y = _dateGetUTCFullYear(date);
805
822
  if (y < 0 || y > 9999) throw new Asn1Error("asn1/bad-generalizedtime", "GeneralizedTime year " + y + " outside 0000..9999");
806
823
  var yyyy = ("000" + y).slice(-4);
807
824
  return yyyy +
808
- _fmtTwo(date.getUTCMonth() + 1) + _fmtTwo(date.getUTCDate()) +
809
- _fmtTwo(date.getUTCHours()) + _fmtTwo(date.getUTCMinutes()) + _fmtTwo(date.getUTCSeconds()) + "Z";
825
+ _fmtTwo(_dateGetUTCMonth(date) + 1) + _fmtTwo(_dateGetUTCDate(date)) +
826
+ _fmtTwo(_dateGetUTCHours(date)) + _fmtTwo(_dateGetUTCMinutes(date)) + _fmtTwo(_dateGetUTCSeconds(date)) +
827
+ (fractional ? _fractionString(_dateGetUTCMilliseconds(date)) : "") + "Z";
828
+ }
829
+ /** @internal X.690 sec. 11.7 as RFC 3161 sec. 2.4.2 restates it for a DER GeneralizedTime: the
830
+ * fraction, when present, follows a point and carries no trailing zeros; a zero fraction and its
831
+ * point are omitted. A Date resolves to milliseconds, so the fraction is at most three digits. */
832
+ function _fractionString(ms) {
833
+ if (ms === 0) return "";
834
+ var digits = (ms < 10 ? "00" : ms < 100 ? "0" : "") + ms;
835
+ var end = digits.length;
836
+ while (end > 0 && _charCodeAt(digits, end - 1) === 0x30) end--;
837
+ var out = ".";
838
+ for (var i = 0; i < end; i++) out += digits[i];
839
+ return out;
840
+ }
841
+ var _GENERALIZED_TIME_OPTS = intrinsic.create(null);
842
+ _GENERALIZED_TIME_OPTS.fractional = 1;
843
+ function _generalizedTimeOptions(opts) {
844
+ if (opts === undefined || opts === null) return false;
845
+ if (typeof opts !== "object") throw new Asn1Error("asn1/bad-generalizedtime", "build.generalizedTime options must be an object");
846
+ guard.identifier.assertKnownKeys(opts, _GENERALIZED_TIME_OPTS, function (code, message) { return new Asn1Error(code, message); },
847
+ "asn1/bad-generalizedtime", "build.generalizedTime has an unknown option ");
848
+ var fractional = opts.fractional;
849
+ if (fractional !== undefined && typeof fractional !== "boolean") throw new Asn1Error("asn1/bad-generalizedtime", "build.generalizedTime fractional must be a boolean");
850
+ return fractional === true;
810
851
  }
811
852
 
812
853
  function _utcTimeString(date) {
813
- var y = date.getUTCFullYear();
854
+ var y = _dateGetUTCFullYear(date);
814
855
  if (y < 1950 || y > 2049) throw new Asn1Error("asn1/bad-utctime", "UTCTime year " + y + " outside 1950..2049; use GeneralizedTime");
815
856
  var yy = y % 100;
816
857
  return _fmtTwo(yy) +
817
- _fmtTwo(date.getUTCMonth() + 1) + _fmtTwo(date.getUTCDate()) +
818
- _fmtTwo(date.getUTCHours()) + _fmtTwo(date.getUTCMinutes()) + _fmtTwo(date.getUTCSeconds()) + "Z";
858
+ _fmtTwo(_dateGetUTCMonth(date) + 1) + _fmtTwo(_dateGetUTCDate(date)) +
859
+ _fmtTwo(_dateGetUTCHours(date)) + _fmtTwo(_dateGetUTCMinutes(date)) + _fmtTwo(_dateGetUTCSeconds(date)) + "Z";
819
860
  }
820
861
 
821
862
  /**
@@ -891,7 +932,7 @@ var build = intrinsic.assign(intrinsic.create(null), {
891
932
  return _universal(TAGS.BMP_STRING, false, out);
892
933
  },
893
934
  utcTime: function (date) { return _universal(TAGS.UTC_TIME, false, Buffer.from(_utcTimeString(date), "latin1")); },
894
- generalizedTime: function (date) { return _universal(TAGS.GENERALIZED_TIME, false, Buffer.from(_generalizedTimeString(date), "latin1")); },
935
+ generalizedTime: function (date, opts) { return _universal(TAGS.GENERALIZED_TIME, false, Buffer.from(_generalizedTimeString(date, _generalizedTimeOptions(opts)), "latin1")); },
895
936
  sequence: function (children) {
896
937
  return encodeConstructed(CLASS_UNIVERSAL, TAGS.SEQUENCE, _asBufferArray(children, "build.sequence"));
897
938
  },
@@ -24,7 +24,7 @@ var x509 = require("./schema-x509");
24
24
  var signScheme = require("./sign-scheme");
25
25
  var guard = require("./guard-all");
26
26
  var intrinsic = require("./guard-intrinsic");
27
- var _hasOwn = intrinsic.hasOwn;
27
+ var _hasOwn = intrinsic.hasOwn, _bufferEquals = intrinsic.bufferEquals;
28
28
  var pkix = require("./schema-pkix");
29
29
  var schema = require("./schema-engine");
30
30
  require("./path-validate");
@@ -58,9 +58,85 @@ var EXT_META = intrinsic.assign(intrinsic.create(null), {
58
58
  aaControls: { name: "aaControls", critical: true },
59
59
  acProxying: { name: "acProxying", critical: true },
60
60
  authorityKeyIdentifier: { name: "authorityKeyIdentifier", critical: false },
61
+ crlDistributionPoints: { name: "cRLDistributionPoints", critical: false },
62
+ authorityInfoAccess: { name: "authorityInfoAccess", critical: false },
61
63
  });
62
64
  var REQUIRED_CRITICALITY = intrinsic.create(null);
63
65
  Object.keys(EXT_META).forEach(function (k) { REQUIRED_CRITICALITY[O(EXT_META[k].name)] = EXT_META[k].critical; });
66
+ var OID_AKI = O("authorityKeyIdentifier"), OID_OCSP = O("ocsp");
67
+
68
+ /** @internal RFC 5755 sets rules on the issuer that its parser reads past and its verifier does
69
+ * not grade: an audit identity is 1..20 octets (sec. 4.3.1), a conforming issuer produces one
70
+ * Targets element (sec. 4.3.2), a stated authority key identifier is the AA certificate's subject
71
+ * key identifier (sec. 4.3.3), an OCSP access location is a URI carrying an HTTP URL (sec. 4.3.4),
72
+ * and a CRL distribution point is one point naming a fullName of a single distinguished name or
73
+ * HTTP / LDAP URL (sec. 4.3.5). Each rule reads the DECODED value, so the object form and the
74
+ * pre-encoded form are held to one definition. */
75
+ var EXT_PROFILE = intrinsic.create(null);
76
+ EXT_PROFILE[O("acAuditIdentity")] = function (id) {
77
+ if (id.length < 1 || id.length > 20) throw _err("attrcert/bad-input", "auditIdentity must be 1 to 20 octets, got " + id.length + " (RFC 5755 sec. 4.3.1)");
78
+ };
79
+ EXT_PROFILE[O("targetInformation")] = function (groups) {
80
+ if (groups.length !== 1) throw _err("attrcert/bad-input", "targetInformation must carry exactly one Targets element, got " + groups.length + "; a conforming issuer lists every target in one (RFC 5755 sec. 4.3.2)");
81
+ for (var i = 0; i < groups[0].length; i++) {
82
+ if (groups[0][i].kind === "targetCert") throw _err("attrcert/bad-input", "targetInformation target " + i + " is a targetCert, which RFC 5755 sec. 4.3.2 says MUST NOT be used; name the target as a targetName or a targetGroup");
83
+ }
84
+ };
85
+ EXT_PROFILE[OID_AKI] = function (aki, ctx) {
86
+ if (aki.keyIdentifier !== null && ctx.aaSki !== null && !_bufferEquals(aki.keyIdentifier, ctx.aaSki)) {
87
+ throw _err("attrcert/bad-input", "the authorityKeyIdentifier keyIdentifier must equal the AA certificate's subjectKeyIdentifier (RFC 5755 sec. 4.3.3, RFC 5280 sec. 4.2.1.1); omit it to take that value");
88
+ }
89
+ };
90
+ EXT_PROFILE[O("authorityInfoAccess")] = function (descs) {
91
+ for (var i = 0; i < descs.length; i++) {
92
+ var d = descs[i];
93
+ if (d.accessMethod !== OID_OCSP) continue;
94
+ if (d.accessLocation.tag !== 6 || !pkiBuild.isHttpUrl(d.accessLocation.value)) {
95
+ throw _err("attrcert/bad-input", "authorityInfoAccess entry " + i + ": an id-ad-ocsp accessLocation must be a uniformResourceIdentifier carrying an HTTP URL (RFC 5755 sec. 4.3.4, RFC 2585)");
96
+ }
97
+ }
98
+ };
99
+ EXT_PROFILE[O("cRLDistributionPoints")] = function (points) {
100
+ if (points.length !== 1) throw _err("attrcert/bad-input", "crlDistributionPoints must carry exactly one distribution point, got " + points.length + " (RFC 5755 sec. 4.3.5)");
101
+ var dp = points[0].distributionPoint;
102
+ if (dp === null || dp.kind !== "fullName") throw _err("attrcert/bad-input", "the crlDistributionPoints entry must name its point as a fullName (RFC 5755 sec. 4.3.5)");
103
+ if (dp.names.length !== 1) throw _err("attrcert/bad-input", "the crlDistributionPoints fullName must contain a single name, got " + dp.names.length + " (RFC 5755 sec. 4.3.5)");
104
+ var gn = attrcert.readGeneralName(dp.names[0], "attrcert/bad-input");
105
+ if (gn.tagNumber !== 4 && (gn.tagNumber !== 6 || !(pkiBuild.isHttpUrl(gn.value) || pkiBuild.isLdapUrl(gn.value)))) {
106
+ throw _err("attrcert/bad-input", "the crlDistributionPoints name must be a directoryName or a uniformResourceIdentifier carrying an HTTP or LDAP URL (RFC 5755 sec. 4.3.5, RFC 2585, RFC 4516)");
107
+ }
108
+ /** @internal Sec. 4.3.5 profiles the RFC 5280 extension, whose sec. 4.2.1.13 has cRLIssuer carry
109
+ * the CRL issuer's Name; a GeneralNames holding no non-empty directoryName names no issuer. */
110
+ var issuer = points[0].cRLIssuer;
111
+ if (issuer !== null && !_namesAnIssuer(issuer.names)) {
112
+ throw _err("attrcert/bad-input", "the crlDistributionPoints cRLIssuer must name the CRL issuer as a non-empty directoryName (RFC 5280 sec. 4.2.1.13)");
113
+ }
114
+ };
115
+ function _namesAnIssuer(names) {
116
+ for (var i = 0; i < names.length; i++) {
117
+ if (names[i].tagNumber === 4 && names[i].value.rdns.length > 0) return true;
118
+ }
119
+ return false;
120
+ }
121
+
122
+ /** @internal Sec. 4.4.5: "roleName MUST use the uniformResourceIdentifier CHOICE of the
123
+ * GeneralName", read off the decoded attribute value on both routes. */
124
+ var ATTR_PROFILE = intrinsic.create(null);
125
+ ATTR_PROFILE[O("role")] = function (role) {
126
+ if (role.roleName.tagNumber !== 6) throw _err("attrcert/bad-input", "role.roleName must be a uniformResourceIdentifier (RFC 5755 sec. 4.4.5)");
127
+ };
128
+
129
+ function _decodeExtensionValue(extnId, valueDer) {
130
+ return EXT_DECODERS[extnId] ? EXT_DECODERS[extnId](valueDer) : attrcert.validateExtensionValue(extnId, valueDer);
131
+ }
132
+ function _assertExtensionProfile(extnId, decoded, ctx) {
133
+ var rule = EXT_PROFILE[extnId];
134
+ if (rule !== undefined) rule(decoded, ctx);
135
+ }
136
+ function _assertAttributeProfile(type, decoded) {
137
+ var rule = ATTR_PROFILE[type];
138
+ if (rule !== undefined) rule(decoded);
139
+ }
64
140
  var CLASSLIST_BIT = intrinsic.assign(intrinsic.create(null), { unmarked: 0, unclassified: 1, restricted: 2, confidential: 3, secret: 4, topSecret: 5 });
65
141
 
66
142
  var _tbsNameBytes = pkiBuild.tbsNameField;
@@ -236,7 +312,15 @@ function _encodeAAControls(aac) {
236
312
  else if (aac.permitUnSpecified != null && aac.permitUnSpecified !== true) throw _err("attrcert/bad-input", "aaControls.permitUnSpecified must be a boolean");
237
313
  return b.sequence(parts);
238
314
  }
239
- function _extensionValue(key, val, aaSpki) {
315
+ /** @internal Sec. 4.3.3 reads RFC 5280 sec. 4.2.1.1 with "CA" as "AC issuer": the keyIdentifier is
316
+ * the AA certificate's subjectKeyIdentifier when that certificate is at hand, else the method (1)
317
+ * value of the AA key. A stated one is held to the certificate's by the profile rule. */
318
+ function _akiKeyId(val, ctx) {
319
+ if (guard.bytes.isByteSource(val)) return guard.bytes.snapshotSource(val, AttrCertError, "attrcert/bad-input", "the authorityKeyIdentifier keyIdentifier");
320
+ if (val === true) return ctx.aaSki !== null ? ctx.aaSki : _b.spkiKeyId(ctx.aaSpki);
321
+ throw _err("attrcert/bad-input", "authorityKeyIdentifier must be true (derive from the AA), false (omit), or a Buffer key id");
322
+ }
323
+ function _extensionValue(key, val, ctx) {
240
324
  switch (key) {
241
325
  case "auditIdentity":
242
326
  if (!Buffer.isBuffer(val)) throw _err("attrcert/bad-input", "auditIdentity must be a Buffer (an OCTET STRING audit tag)");
@@ -245,7 +329,9 @@ function _extensionValue(key, val, aaSpki) {
245
329
  case "acProxying": return _encodeSeqOfTargets(val);
246
330
  case "noRevAvail": return b.nullValue();
247
331
  case "aaControls": return _encodeAAControls(val);
248
- case "authorityKeyIdentifier": return _b.extAki(_b.skiKeyId(val, aaSpki));
332
+ case "authorityKeyIdentifier": return _b.extAki(_akiKeyId(val, ctx));
333
+ case "crlDistributionPoints": return _b.extCrlDistributionPoints(val, "crlDistributionPoints");
334
+ case "authorityInfoAccess": return _b.extAuthorityInfoAccess(val);
249
335
  default: throw _err("attrcert/bad-input", "unknown extension " + JSON.stringify(key));
250
336
  }
251
337
  }
@@ -256,6 +342,7 @@ function _buildAttributes(attrSpec) {
256
342
  function add(type, valueTlv) {
257
343
  if (seen[type]) throw _err("attrcert/duplicate-attribute", "duplicate " + (oid.name(type) || type) + " attribute (RFC 5755 sec. 4.2.7)");
258
344
  seen[type] = true;
345
+ _assertAttributeProfile(type, attrcert.validateAttributeValue(type, valueTlv));
259
346
  attrs.push(b.sequence([b.oid(type), b.set([valueTlv])]));
260
347
  }
261
348
  if (Array.isArray(attrSpec)) {
@@ -270,8 +357,10 @@ function _buildAttributes(attrSpec) {
270
357
  if (seen[at]) throw _err("attrcert/duplicate-attribute", "duplicate " + (oid.name(at) || at) + " attribute (RFC 5755 sec. 4.2.7)");
271
358
  seen[at] = true;
272
359
  n.children[1].children.forEach(function (valNode) {
273
- try { attrcert.validateAttributeValue(at, valNode.bytes); }
360
+ var decoded;
361
+ try { decoded = attrcert.validateAttributeValue(at, valNode.bytes); }
274
362
  catch (err) { if (err instanceof AttrCertError) throw err; throw _err("attrcert/bad-input", "pre-encoded " + (oid.name(at) || at) + " attribute value is malformed", err); }
363
+ _assertAttributeProfile(at, decoded);
275
364
  });
276
365
  attrs.push(b.raw(der));
277
366
  });
@@ -300,8 +389,16 @@ function _assertRevocationSchemesExclusive(seen) {
300
389
  }
301
390
  }
302
391
 
303
- function _buildExtensions(extSpec, aaSpki) {
304
- if (extSpec == null) return null;
392
+ function _emitNamedExtension(out, seen, k, val, ctx) {
393
+ var meta = EXT_META[k], eOid = O(meta.name);
394
+ if (seen[eOid]) throw _err("attrcert/bad-input", "duplicate extension " + JSON.stringify(k) + " (RFC 5755 sec. 4.2.9)");
395
+ seen[eOid] = true;
396
+ var valueDer = _extensionValue(k, val, ctx);
397
+ _assertExtensionProfile(eOid, _decodeExtensionValue(eOid, valueDer), ctx);
398
+ out.push(_b.ext(eOid, meta.critical, valueDer));
399
+ }
400
+ function _buildExtensions(extSpec, ctx) {
401
+ if (extSpec == null) extSpec = {};
305
402
  if (Array.isArray(extSpec)) {
306
403
  if (!extSpec.length) return null;
307
404
  var seenA = intrinsic.create(null);
@@ -317,10 +414,10 @@ function _buildExtensions(extSpec, aaSpki) {
317
414
  throw _err("attrcert/bad-input", "pre-encoded " + (oid.name(extnId) || extnId) + " extension must be marked " + (required ? "critical" : "non-critical") + " (RFC 5755)");
318
415
  }
319
416
  var extnValue = asn1.read.octetString(n.children[n.children.length - 1]);
320
- try {
321
- if (EXT_DECODERS[extnId]) EXT_DECODERS[extnId](extnValue);
322
- else attrcert.validateExtensionValue(extnId, extnValue);
323
- } catch (err) { if (err instanceof AttrCertError) throw err; throw _err("attrcert/bad-input", "pre-encoded " + (oid.name(extnId) || extnId) + " extension value is malformed", err); }
417
+ var decoded;
418
+ try { decoded = _decodeExtensionValue(extnId, extnValue); }
419
+ catch (err) { if (err instanceof AttrCertError) throw err; throw _err("attrcert/bad-input", "pre-encoded " + (oid.name(extnId) || extnId) + " extension value is malformed", err); }
420
+ _assertExtensionProfile(extnId, decoded, ctx);
324
421
  return b.raw(der);
325
422
  });
326
423
  _assertRevocationSchemesExclusive(seenA);
@@ -331,13 +428,16 @@ function _buildExtensions(extSpec, aaSpki) {
331
428
  return "unknown extension " + JSON.stringify(k) + "; pass a pre-encoded Extension DER via the array form for a custom extension";
332
429
  });
333
430
  var out = [], seen = intrinsic.create(null);
431
+ var akiDeclined = false;
334
432
  Object.keys(extSpec).forEach(function (k) {
335
- if (extSpec[k] == null) return;
336
- var meta = EXT_META[k], eOid = O(meta.name);
337
- if (seen[eOid]) throw _err("attrcert/bad-input", "duplicate extension " + JSON.stringify(k) + " (RFC 5755 sec. 4.2.9)");
338
- seen[eOid] = true;
339
- out.push(_b.ext(eOid, meta.critical, _extensionValue(k, extSpec[k], aaSpki)));
433
+ var val = extSpec[k];
434
+ if (val == null) return;
435
+ if (k === "authorityKeyIdentifier" && val === false) { akiDeclined = true; return; }
436
+ _emitNamedExtension(out, seen, k, val, ctx);
340
437
  });
438
+ /** @internal Sec. 4.3.3: "As with PKCs, this extension SHOULD be included in ACs", so it is
439
+ * emitted without being named and `false` declines it, which a SHOULD allows. */
440
+ if (!seen[OID_AKI] && !akiDeclined) _emitNamedExtension(out, seen, "authorityKeyIdentifier", true, ctx);
341
441
  _assertRevocationSchemesExclusive(seen);
342
442
  if (!out.length) return null;
343
443
  return b.sequence(out);
@@ -359,13 +459,27 @@ function _buildExtensions(extSpec, aaSpki) {
359
459
  * a random 20-octet serial is generated when omitted), `attributes` (an object of the sec. 4.4 privilege
360
460
  * syntaxes (role / clearance / group / chargingIdentity / accessIdentity / authenticationInfo), or an
361
461
  * array of pre-encoded Attribute DER), and optional `extensions` (an object of auditIdentity /
362
- * targetInformation / noRevAvail / aaControls / acProxying / authorityKeyIdentifier, or an array of
363
- * pre-encoded Extension DER). `issuer` is the signing AA: `{ cert, key }` (the AA certificate DER/PEM
364
- * and its private key) or `{ name, publicKey, key }` (an explicit issuer DN, AA SPKI DER, and key); an
365
- * attribute certificate is never self-signed. RFC 5755 section 6 defines two revocation schemes and
366
- * makes them exclusive ("An AC MUST NOT contain both a noRevAvail extension and a 'pointer in AC'"),
367
- * so `noRevAvail` beside a `crlDistributionPoints` or `authorityInfoAccess` extension is refused,
368
- * in the named form and the pre-encoded form alike. The signature algorithm is resolved from the AA key (RSA
462
+ * targetInformation / noRevAvail / aaControls / acProxying / authorityKeyIdentifier /
463
+ * crlDistributionPoints / authorityInfoAccess, the last two in the list forms `pki.x509.sign`
464
+ * takes, or an array of pre-encoded Extension DER). `issuer` is the signing AA: `{ cert, key }` (the AA
465
+ * certificate DER/PEM and its private key) or `{ name, publicKey, key }` (an explicit issuer DN, AA
466
+ * SPKI DER, and key); an attribute certificate is never self-signed. RFC 5755 section 6 defines two
467
+ * revocation schemes and makes them exclusive ("An AC MUST NOT contain both a noRevAvail extension
468
+ * and a 'pointer in AC'"), so `noRevAvail` beside a `crlDistributionPoints` or `authorityInfoAccess`
469
+ * extension is refused, in the named form and the pre-encoded form alike.
470
+ *
471
+ * The `authorityKeyIdentifier` is emitted without being named (section 4.3.3: "this extension
472
+ * SHOULD be included in ACs"); its keyIdentifier is the AA certificate's subjectKeyIdentifier when
473
+ * `issuer.cert` is given, else the RFC 5280 method (1) value of the AA key, and a stated one is held
474
+ * to the certificate's. `authorityKeyIdentifier: false` omits it. The pre-encoded array form emits
475
+ * exactly what it is given. Both forms are held to the rules section 4.3 and 4.4 place on the
476
+ * issuer, read off the decoded value: an auditIdentity is 1 to 20 octets (4.3.1); a
477
+ * targetInformation carries one Targets element and never a targetCert (4.3.2); an id-ad-ocsp
478
+ * accessLocation is a URI carrying an HTTP URL (4.3.4); a crlDistributionPoints names one
479
+ * distribution point as a fullName holding a single directoryName or an HTTP or LDAP URL, and a
480
+ * cRLIssuer beside it names the CRL issuer as a directoryName (4.3.5, RFC 5280 sec. 4.2.1.13);
481
+ * and a role's roleName is a uniformResourceIdentifier (4.4.5). A violation is refused with
482
+ * `attrcert/bad-input`. The signature algorithm is resolved from the AA key (RSA
369
483
  * PKCS#1 v1.5 or PSS, ECDSA, EdDSA, ML-DSA, SLH-DSA, or a composite arm), and the signature is verified
370
484
  * under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE
371
485
  * CERTIFICATE` with `opts.pem`. Malformed input throws a typed `AttrCertError`; where the spec carries
@@ -404,11 +518,12 @@ function _sign(spec, issuer, opts) {
404
518
  issuer = issuer || {};
405
519
  if (issuer.key == null) throw _err("attrcert/bad-input", "a signing key (issuer.key, the AA's WebCrypto CryptoKey or PKCS#8 private key DER/PEM) is required");
406
520
 
407
- var issuerDnSpec, aaSpki;
521
+ var issuerDnSpec, aaSpki, aaSki = null;
408
522
  if (issuer.cert != null) {
409
523
  var aaCert = _parseCert(issuer.cert, "issuer.cert");
410
524
  issuerDnSpec = _tbsNameBytes(aaCert, "subject");
411
525
  aaSpki = aaCert.subjectPublicKeyInfo.bytes;
526
+ aaSki = pkiBuild.skiValueOf(aaCert);
412
527
  } else if (issuer.name != null && issuer.publicKey != null) {
413
528
  issuerDnSpec = issuer.name;
414
529
  aaSpki = _b.reqDer(issuer.publicKey, "issuer.publicKey (the AA SPKI DER)");
@@ -421,7 +536,7 @@ function _sign(spec, issuer, opts) {
421
536
  var holderDer = _encodeHolder(spec.holder);
422
537
  var validityDer = _encodeValidity(spec.notBeforeTime, spec.notAfterTime);
423
538
  var attributesDer = _buildAttributes(spec.attributes);
424
- var extsDer = _buildExtensions(spec.extensions, aaSpki);
539
+ var extsDer = _buildExtensions(spec.extensions, { aaSpki: aaSpki, aaSki: aaSki });
425
540
 
426
541
  var scheme = signScheme.resolveSignScheme(_b.certLikeFromSpki(aaSpki), { combinedRsaSig: true, pss: opts.pss, digestAlgorithm: opts.digestAlgorithm }, true, _signE);
427
542
 
@@ -634,7 +749,8 @@ function _unsupportedCritical(ac) {
634
749
  * AC carrying `noRevAvail` verifies with `revocationChecked: true` and `noRevAvail: true`, and one
635
750
  * without it is refused unless the caller supplies `opts.revocationStatus`. A caller running the
636
751
  * section's "pointer in AC" scheme reads the certificate's own `crlDistributionPoints` /
637
- * `authorityInfoAccess` from the verdict's `extensions`, establishes the status, and passes it back.
752
+ * `authorityInfoAccess` from the verdict's `extensions` (each carried decoded, as the RFC 5280
753
+ * readers return them), establishes the status, and passes it back.
638
754
  *
639
755
  * Items 1 and 3, and the issuer path in item 2, need certificates this verb is not given: the
640
756
  * holder's own public-key certificate and its chain, the AC issuer's chain, and the section 4.5
package/lib/cmp-verify.js CHANGED
@@ -44,6 +44,7 @@ var guard = require("./guard-all");
44
44
  var constants = require("./constants");
45
45
  var ipUtils = require("./ip-utils");
46
46
  var frameworkError = require("./framework-error");
47
+ var pkiBuild = require("./pki-build");
47
48
 
48
49
  var CmpError = frameworkError.CmpError;
49
50
  var b = asn1.build;
@@ -146,15 +147,7 @@ function _certDer(cert, what) {
146
147
  throw _err("cmp/bad-input", what + " must be a certificate DER BufferSource or PEM string");
147
148
  }
148
149
 
149
- function _certSki(parsed) {
150
- var skiOid = oid.byName("subjectKeyIdentifier");
151
- var exts = parsed.extensions;
152
- for (var i = 0; i < exts.length; i++) {
153
- if (exts[i].oid !== skiOid) continue;
154
- try { return asn1.read.octetString(asn1.decode(exts[i].value)); } catch (_e) { return null; } // allow:swallow-unverified -- fail-closed: a malformed subjectKeyIdentifier yields null, so no SKI is used to match
155
- }
156
- return null;
157
- }
150
+ var _certSki = pkiBuild.skiValueOf;
158
151
  function _subjectDn(parsed) { return parsed.subject.dn || null; }
159
152
 
160
153
  function _sanGeneralNames(parsed) {
package/lib/crl-sign.js CHANGED
@@ -72,8 +72,6 @@ function _assertExtensionValueDecodes(node, extnId, what) {
72
72
  }
73
73
  }
74
74
 
75
- var OID_SKI = O("subjectKeyIdentifier");
76
-
77
75
  var CRL_REASON = constants.NAMES.CRL_REASON;
78
76
  var REASON_BY_NAME = intrinsic.create(null);
79
77
  Object.keys(CRL_REASON).forEach(function (v) { REASON_BY_NAME[CRL_REASON[v]] = Number(v); });
@@ -146,14 +144,8 @@ function _resolveReason(reason, isDelta) {
146
144
  return codeNum;
147
145
  }
148
146
 
149
- function _issuerSkiOf(ctx) {
150
- if (!ctx.issuerCert) return null;
151
- var ski = (ctx.issuerCert.extensions || []).filter(function (e) { return e.oid === OID_SKI; })[0];
152
- if (ski) { try { return asn1.read.octetString(asn1.decode(ski.value)); } catch (_e) { } } // allow:swallow-unverified -- a malformed issuer SKI is read as absent; the authorityKeyIdentifier keyIdentifier is then derived from the issuer public key
153
- return null;
154
- }
155
147
  function _akiKeyId(val, ctx) {
156
- var issuerSki = _issuerSkiOf(ctx);
148
+ var issuerSki = ctx.issuerCert ? _b.skiValueOf(ctx.issuerCert) : null;
157
149
  if (guard.bytes.isByteSource(val)) {
158
150
  var given = guard.bytes.snapshotSource(val, CrlError, "crl/bad-input", "the authorityKeyIdentifier keyIdentifier");
159
151
  /** @internal Sec. 5.2.1 names the CRL signer certificate's subject key identifier as the value,
package/lib/guard-name.js CHANGED
@@ -218,6 +218,15 @@ function _allCharsIn(s, table) {
218
218
 
219
219
  function stripTrailingDot(s) { return _charAt(s, s.length - 1) === "." ? _strSlice(s, 0, -1) : s; }
220
220
 
221
+ /** @internal Whether `s` opens with `scheme` followed by a colon, the scheme compared without
222
+ * regard to ASCII case (RFC 3986 sec. 3.1). `scheme` is given in lower case. */
223
+ // @enforced-by behavioral -- a scheme comparison has no rename-proof code shape; the vectors refusing a location under the wrong scheme are the guard
224
+ function uriSchemeIs(s, scheme) {
225
+ if (typeof s !== "string" || s.length <= scheme.length) return false;
226
+ if (_charCodeAt(s, scheme.length) !== 0x3a) return false;
227
+ return lowerAscii(_strSlice(s, 0, scheme.length)) === scheme;
228
+ }
229
+
221
230
  /** @internal A host name of two or more labels that is not an address, which is the form a URI
222
231
  * name constraint is compared by (RFC 5280 sec. 4.2.1.10). */
223
232
  function isFqdnHost(host) {
@@ -527,7 +536,7 @@ module.exports = intrinsic.freeze({
527
536
  assertNoControlBytes: assertNoControlBytes, assertPrintableIa5: assertPrintableIa5,
528
537
  dnEqual: dnEqual, rdnEqual: rdnEqual, emailEqual: emailEqual, dpnCorresponds: dpnCorresponds,
529
538
  escapeControlBytes: escapeControlBytes, escapeDnValue: escapeDnValue,
530
- lowerAscii: lowerAscii,
539
+ lowerAscii: lowerAscii, uriSchemeIs: uriSchemeIs,
531
540
  stripTrailingDot: stripTrailingDot, isFqdnHost: isFqdnHost, splitMailbox: splitMailbox,
532
541
  constraintBaseRefusal: constraintBaseRefusal,
533
542
  constraintBaseUnreadable: constraintBaseUnreadable,
package/lib/lint.js CHANGED
@@ -749,18 +749,6 @@ function _crlDecodedExtension(crl, name) {
749
749
  }
750
750
  }
751
751
 
752
- /** @internal Whether a string opens with the given URI scheme followed by a colon, compared
753
- * without regard to case by scanning character codes. */
754
- function _uriSchemeIs(s, scheme) {
755
- if (typeof s !== "string" || s.length <= scheme.length) return false;
756
- for (var i = 0; i < scheme.length; i++) {
757
- var c = s.charCodeAt(i);
758
- if (c >= 65 && c <= 90) c += 32;
759
- if (c !== scheme.charCodeAt(i)) return false;
760
- }
761
- return s.charCodeAt(scheme.length) === 58;
762
- }
763
-
764
752
  /** @internal The schemes that satisfy the section 5.2.7 recommendation. The secured forms count:
765
753
  * warning about an https or ldaps location would report the more protected spelling of the two the
766
754
  * clause names. */
@@ -1201,7 +1189,7 @@ var RFC5280_CRL_RULES = [
1201
1189
  var reachable = descs.some(function (d) {
1202
1190
  var loc = d.accessLocation;
1203
1191
  if (!loc || loc.tag !== 6) return false;
1204
- return AIA_RECOMMENDED_SCHEMES.some(function (s) { return _uriSchemeIs(loc.value, s); });
1192
+ return AIA_RECOMMENDED_SCHEMES.some(function (s) { return guard.name.uriSchemeIs(loc.value, s); });
1205
1193
  });
1206
1194
  return reachable ? null : true;
1207
1195
  },
package/lib/pki-build.js CHANGED
@@ -28,6 +28,7 @@ var _isBufferChk = intrinsic.isBuffer;
28
28
  var _stringify = intrinsic.stringify;
29
29
  var _mapIntrinsic = intrinsic.map;
30
30
  var _bufferConcatIntrinsic = intrinsic.bufferConcat;
31
+ var OID_SKI = oid.byName("subjectKeyIdentifier");
31
32
 
32
33
  function _isAlphaCode(c) { return (c >= 65 && c <= 90) || (c >= 97 && c <= 122); }
33
34
  function _isDigitCode(c) { return c >= 48 && c <= 57; }
@@ -81,14 +82,14 @@ function _componentBytesOk(s, from, to, byteOk) {
81
82
  return true;
82
83
  }
83
84
 
84
- function _validUriHost(s, from, to) {
85
+ function _validUriHost(s, from, to, singleLabel) {
85
86
  if (to <= from) return false;
86
87
  var host = _sliceStr(s, from, to), len = host.length;
87
88
  if (_looksLikeIPv4Shape(host)) return _packIpLiteral(host) !== null;
88
89
  var end = _charCodeAt(host, len - 1) === 46 ? len - 1 : len;
89
90
  if (end > 253) return false;
90
91
  var firstDot = _stringIndexOf(host, ".", 0);
91
- if (firstDot === -1 || firstDot >= end) return false;
92
+ if (!singleLabel && (firstDot === -1 || firstDot >= end)) return false;
92
93
  return _labelsValid(host, 0, len, _isHostLabelRange, true);
93
94
  }
94
95
 
@@ -98,11 +99,11 @@ function _validUriIp6Host(s, from, to) {
98
99
  return packed !== null && intrinsic.sizeOf(packed) === 16;
99
100
  }
100
101
 
101
- function _validUriAuthority(s, from, to) {
102
+ function _validUriAuthority(s, from, to, shape) {
102
103
  var i, c, at = -1;
103
104
  for (i = from; i < to; i += 1) {
104
105
  c = _charCodeAt(s, i);
105
- if (c === 64) { if (at !== -1) return false; at = i; }
106
+ if (c === 64) { if (at !== -1 || !shape.userinfo) return false; at = i; }
106
107
  }
107
108
  var hostStart = at === -1 ? from : at + 1;
108
109
  if (at !== -1 && !_componentBytesOk(s, from, at, _isUserinfoByte)) return false;
@@ -120,14 +121,31 @@ function _validUriAuthority(s, from, to) {
120
121
  var colon = -1;
121
122
  for (i = hostStart; i < to; i += 1) { if (_charCodeAt(s, i) === 58) { colon = i; break; } }
122
123
  var hostEnd = colon === -1 ? to : colon;
123
- if (!_validUriHost(s, hostStart, hostEnd)) return false;
124
+ var portAlone = hostEnd === hostStart && colon !== -1 && shape.emptyHost;
125
+ if (!portAlone && !_validUriHost(s, hostStart, hostEnd, shape.singleLabel)) return false;
124
126
  if (colon !== -1) {
125
127
  for (i = colon + 1; i < to; i += 1) { if (!_isDigitCode(_charCodeAt(s, i))) return false; }
126
128
  }
127
129
  return true;
128
130
  }
129
131
 
130
- function _looksLikeUri(s) {
132
+ /** @internal The shape a bare string must have to be read as a URI GeneralName without being told:
133
+ * a scheme, "//", an authority naming a multi-label host (a single label reads as a dNSName), and
134
+ * a well-formed remainder, a fragment included. */
135
+ var _URI_SHAPE = intrinsic.assign(intrinsic.create(null), { singleLabel: false, userinfo: true, emptyAuthority: false, emptyHost: false, queryNeedsPath: false, fragment: true });
136
+ /** @internal An HTTP URL (RFC 2616 sec. 3.2.2: "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]):
137
+ * no userinfo, a host of one label or many, a query only after an absolute path, no fragment. */
138
+ var _HTTP_URL_SHAPE = intrinsic.assign(intrinsic.create(null), { singleLabel: true, userinfo: false, emptyAuthority: false, emptyHost: false, queryNeedsPath: true, fragment: false });
139
+ /** @internal An LDAP URL (RFC 4516 sec. 2: scheme "://" [host [":" port]] ["/" dn ...]): no
140
+ * userinfo, a host of any label count that may be left out, with or without a port, and no
141
+ * fragment. The dn, attributes, scope and filter after the "/" are not parsed. */
142
+ var _LDAP_URL_SHAPE = intrinsic.assign(intrinsic.create(null), { singleLabel: true, userinfo: false, emptyAuthority: true, emptyHost: true, queryNeedsPath: false, fragment: false });
143
+
144
+ function _looksLikeUri(s) { return _uriShape(s, _URI_SHAPE); }
145
+ function isHttpUrl(s) { return typeof s === "string" && guard.name.uriSchemeIs(s, "http") && _uriShape(s, _HTTP_URL_SHAPE); }
146
+ function isLdapUrl(s) { return typeof s === "string" && guard.name.uriSchemeIs(s, "ldap") && _uriShape(s, _LDAP_URL_SHAPE); }
147
+
148
+ function _uriShape(s, shape) {
131
149
  var n = s.length, i, c;
132
150
  if (n === 0 || !_isAlphaCode(_charCodeAt(s, 0))) return false;
133
151
  i = 1;
@@ -140,8 +158,9 @@ function _looksLikeUri(s) {
140
158
  i += 3;
141
159
  var authStart = i, authEnd = n;
142
160
  for (; i < n; i += 1) { c = _charCodeAt(s, i); if (c === 47 || c === 63 || c === 35) { authEnd = i; break; } }
143
- if (authEnd === authStart) return false;
144
- if (!_validUriAuthority(s, authStart, authEnd)) return false;
161
+ if (authEnd === authStart) { if (!shape.emptyAuthority) return false; }
162
+ else if (!_validUriAuthority(s, authStart, authEnd, shape)) return false;
163
+ if (authEnd < n && shape.queryNeedsPath && _charCodeAt(s, authEnd) === 63) return false;
145
164
  var sawHash = false;
146
165
  i = authEnd;
147
166
  while (i < n) {
@@ -151,7 +170,7 @@ function _looksLikeUri(s) {
151
170
  i += 3;
152
171
  continue;
153
172
  }
154
- if (c === 35) { if (sawHash) return false; sawHash = true; }
173
+ if (c === 35) { if (sawHash || !shape.fragment) return false; sawHash = true; }
155
174
  if (!_isUriByte(c)) return false;
156
175
  i += 1;
157
176
  }
@@ -1268,7 +1287,7 @@ function makeBuilder(ctx) {
1268
1287
  extSubjectInfoAccess: extSubjectInfoAccess, extSubjectDirectoryAttributes: extSubjectDirectoryAttributes,
1269
1288
  extMsCertificateTemplate: extMsCertificateTemplate, extMsCaVersion: extMsCaVersion,
1270
1289
  extMsPreviousCertHash: extMsPreviousCertHash, extMsEnrollCertType: extMsEnrollCertType,
1271
- spkiKeyId: spkiKeyId, skiKeyId: skiKeyId,
1290
+ spkiKeyId: spkiKeyId, skiKeyId: skiKeyId, skiValueOf: skiValueOf,
1272
1291
  reqDer: reqDer, reqDenseArray: reqDenseArray, reqDerSequence: reqDerSequence, assertValidSpki: assertValidSpki, assertValidExtension: assertValidExtension,
1273
1292
  assertExtnValueIsDer: assertExtnValueIsDer,
1274
1293
  assertCertCriticality: assertCertCriticality,
@@ -1289,4 +1308,15 @@ function tbsSerialNumber(cert) {
1289
1308
  return asn1.read.integer(tbs.children[hasVersion ? 1 : 0]);
1290
1309
  }
1291
1310
 
1292
- module.exports = intrinsic.freeze({ makeBuilder: makeBuilder, reqDenseArray: reqDenseArrayImpl, KU_BIT: KU_BIT, tbsNameField: tbsNameField, tbsSerialNumber: tbsSerialNumber, randomSerial: randomSerial });
1311
+ /** @internal The subjectKeyIdentifier a parsed certificate carries, or null without one. RFC 5280
1312
+ * sec. 4.2.1.1 names it as the authorityKeyIdentifier keyIdentifier of everything issued under
1313
+ * that certificate, so a signer reads it here before deriving one from the key, and a verifier
1314
+ * matches a signer by it. */
1315
+ function skiValueOf(parsedCert) {
1316
+ var exts = intrinsic.filter(parsedCert.extensions, function (e) { return e.oid === OID_SKI; });
1317
+ if (!exts.length) return null;
1318
+ try { return asn1.read.octetString(asn1.decode(exts[0].value)); }
1319
+ catch (_e) { return null; } // allow:swallow-unverified -- a malformed SKI is read as absent; a signer then derives the authorityKeyIdentifier keyIdentifier from the public key, and a verifier matches on nothing
1320
+ }
1321
+
1322
+ module.exports = intrinsic.freeze({ makeBuilder: makeBuilder, reqDenseArray: reqDenseArrayImpl, KU_BIT: KU_BIT, tbsNameField: tbsNameField, tbsSerialNumber: tbsSerialNumber, randomSerial: randomSerial, skiValueOf: skiValueOf, isHttpUrl: isHttpUrl, isLdapUrl: isLdapUrl });
@@ -577,6 +577,13 @@ _AC_EXT_DECODERS[_Oav("targetInformation")] = _targetInformation;
577
577
  _AC_EXT_DECODERS[_Oav("noRevAvail")] = _noRevAvail;
578
578
  _AC_EXT_DECODERS[_Oav("aaControls")] = _aaControls;
579
579
  _AC_EXT_DECODERS[_Oav("acProxying")] = _acProxying;
580
+ /** @internal The three RFC 5280 extensions RFC 5755 sec. 4.3.3 to 4.3.5 profile for an AC are read
581
+ * through the certificate decoders, so a relying party running the sec. 6 "pointer in AC" scheme
582
+ * reads the distribution point and the OCSP location off the parse rather than off raw bytes. */
583
+ var _CERT_EXT_DECODERS = pkix.certExtensionDecoders(NS).byOid;
584
+ _AC_EXT_DECODERS[_Oav("authorityKeyIdentifier")] = _CERT_EXT_DECODERS[_Oav("authorityKeyIdentifier")];
585
+ _AC_EXT_DECODERS[_Oav("authorityInfoAccess")] = _CERT_EXT_DECODERS[_Oav("authorityInfoAccess")];
586
+ _AC_EXT_DECODERS[_Oav("cRLDistributionPoints")] = _CERT_EXT_DECODERS[_Oav("cRLDistributionPoints")];
580
587
 
581
588
  // @internal
582
589
  function validateAttributeValue(type, valueDer) {
package/lib/tsp-sign.js CHANGED
@@ -101,13 +101,19 @@ function _signingCertV2(certDer, hashName) {
101
101
  * timestamp authority's `{ cert, key }` (as `pki.cms.sign` takes them). The token is a CMS
102
102
  * SignedData whose content is a `TSTInfo` carrying the imprint, the TSA policy, a serial
103
103
  * number, and `genTime`; the RFC 3161 sec. 2.4.2 signing-certificate attribute binding the
104
- * token to the TSA certificate is attached automatically.
104
+ * token to the TSA certificate is attached automatically. The TSA certificate is held to
105
+ * sec. 2.3 before anything is signed: one critical extendedKeyUsage naming id-kp-timeStamping
106
+ * alone, and a keyUsage, when present, that allows signing; a certificate that fails is refused
107
+ * with the code `pki.tsp.verify` would answer (`tsp/bad-eku`, `tsp/eku-not-critical`,
108
+ * `tsp/eku-not-exclusive`, `tsp/bad-key-usage`).
105
109
  *
106
110
  * @opts policy REQUIRED -- the TSA policy identifier (an OID name or dotted string).
107
111
  * @opts serialNumber REQUIRED -- a unique token serial number (a number or BigInt).
108
- * @opts genTime The trusted time (a `Date`). Default: now.
112
+ * @opts genTime The trusted time (a `Date`). Default: now. Milliseconds are kept as the
113
+ * sec. 2.4.2 fraction of a second, which `pki.schema.tsp.parseToken` reads back.
109
114
  * @opts nonce The request nonce to echo (a number or BigInt), for replay protection.
110
- * @opts accuracy The genTime +/- accuracy, as `{ seconds?, millis?, micros? }`.
115
+ * @opts accuracy The genTime +/- accuracy, as `{ seconds?, millis?, micros? }`, naming at
116
+ * least one field; omit it to make no accuracy claim.
111
117
  * @opts ordering Whether tokens from this TSA are strictly ordered in time (boolean).
112
118
  * @opts certHashAlgorithm The ESSCertIDv2 hash algorithm name. Default `sha256`.
113
119
  * @opts digestAlgorithm / pss Passed through to `pki.cms.sign` (the signer digest algorithm, RSA-PSS padding).
@@ -163,6 +169,12 @@ function _sign(messageImprint, tsa, opts) {
163
169
  if (opts.serialNumber == null) throw _err("tsp/bad-input", "a timestamp token requires a serialNumber (opts.serialNumber)");
164
170
 
165
171
  var certDer = _certDer(tsa && tsa.cert);
172
+ /** @internal Sec. 2.3 binds the TSA: its certificate carries one critical extendedKeyUsage naming
173
+ * id-kp-timeStamping alone, and a keyUsage, when present, that allows signing. The verifier
174
+ * refuses a token under any other certificate, so the same check runs here, with the same
175
+ * codes, before a token no relying party would accept is signed. */
176
+ var certFault = _checkTsaCertUsage(certDer);
177
+ if (certFault !== true) throw _err(certFault, "the TSA certificate does not satisfy RFC 3161 sec. 2.3 (" + certFault + "): a relying party would refuse every token signed under it");
166
178
  var certHashAlg = opts.certHashAlgorithm || "sha256";
167
179
  if (!NODE_DIGEST[guard.text.keyOf(certHashAlg)]) throw _err("tsp/unsupported-algorithm", "unsupported certHashAlgorithm " + guard.text.showValue(certHashAlg));
168
180
 
@@ -170,7 +182,9 @@ function _sign(messageImprint, tsa, opts) {
170
182
  if (opts.genTime != null) guard.time.assertEncodable(opts.genTime, _err, "tsp/bad-input", "genTime");
171
183
  var genTime = guard.time.isDate(opts.genTime) ? opts.genTime : new Date();
172
184
  var serial = guard.range.authoredInteger(opts.serialNumber, _err, "tsp/bad-input", "serialNumber");
173
- var fields = [b.integer(1n), _policy(opts.policy), imprint, b.integer(serial), b.generalizedTime(genTime)];
185
+ /** @internal Sec. 2.4.2 lets genTime carry a fraction of a second, which the parser reads, so a
186
+ * Date's milliseconds reach the token rather than being dropped at the encoder. */
187
+ var fields = [b.integer(1n), _policy(opts.policy), imprint, b.integer(serial), b.generalizedTime(genTime, { fractional: true })];
174
188
  if (opts.accuracy) guard.list.append(fields,_accuracy(opts.accuracy));
175
189
  if (opts.ordering === true) guard.list.append(fields,b.boolean(true));
176
190
  if (opts.nonce != null) guard.list.append(fields,b.integer(guard.range.authoredInteger(opts.nonce, _err, "tsp/bad-input", "nonce")));
@@ -203,6 +217,9 @@ function _accuracy(a) {
203
217
  }
204
218
  if (mil != null) guard.list.append(f,b.contextPrimitive(0, _subMilliBytes(mil, "millis")));
205
219
  if (mic != null) guard.list.append(f,b.contextPrimitive(1, _subMilliBytes(mic, "micros")));
220
+ /** @internal Sec. 2.4.2 reads an absent field as zero, so an Accuracy naming none asserts a zero
221
+ * deviation; a caller with no accuracy to state omits the option instead. */
222
+ if (!f.length) throw _err("tsp/bad-input", "accuracy must name at least one of seconds, millis, micros; omit it to make no accuracy claim (RFC 3161 sec. 2.4.2)");
206
223
  return b.sequence(f);
207
224
  }
208
225
  function _subMilliBytes(n, label) {
package/lib/x509-sign.js CHANGED
@@ -39,8 +39,6 @@ function _err(code, message, cause) { return new CertificateError(code, message,
39
39
  function _signE(kind, message, cause) { return new CertificateError("x509/" + kind, message, cause); }
40
40
  function O(n) { return oid.byName(n); }
41
41
 
42
- var OID_SKI = O("subjectKeyIdentifier");
43
-
44
42
  var KNOWN_SPEC_KEYS = intrinsic.assign(intrinsic.create(null), {
45
43
  subject: 1, subjectPublicKey: 1, notBefore: 1, notAfter: 1, serialNumber: 1, extensions: 1,
46
44
  });
@@ -77,13 +75,8 @@ var _encodeName = _b.encodeName, _isEmptyName = _b.isEmptyName, _reqDer = _b.req
77
75
  _skiKeyId = _b.skiKeyId, _spkiKeyId = _b.spkiKeyId, _serialInteger = _b.serialInteger;
78
76
 
79
77
 
80
- function _skiValueOf(caCert) {
81
- var ext = (caCert.extensions || []).filter(function (e) { return e.oid === OID_SKI; })[0];
82
- if (ext) { try { return asn1.read.octetString(asn1.decode(ext.value)); } catch (_e) { } } // allow:swallow-unverified -- a malformed CA SKI is read as absent; _akiKeyId then derives the authorityKeyIdentifier keyIdentifier from the issuer public key
83
- return null;
84
- }
85
78
  function _akiKeyId(val, ctx) {
86
- var issuerSki = ctx.issuerCert ? _skiValueOf(ctx.issuerCert) : null;
79
+ var issuerSki = ctx.issuerCert ? _b.skiValueOf(ctx.issuerCert) : null;
87
80
  if (guard.bytes.isByteSource(val)) {
88
81
  var given = guard.bytes.snapshotSource(val, CertificateError, "x509/bad-input", "the authorityKeyIdentifier keyIdentifier");
89
82
  /** @internal Sec. 4.2.1.2: the issuer certificate's subjectKeyIdentifier MUST be the value
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.7.34",
3
+ "version": "0.7.36",
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:0278421d-1579-47eb-90cb-53f880acc978",
5
+ "serialNumber": "urn:uuid:df652731-5ac1-4b9c-9b5f-05814b6a2cf7",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-12T09:51:26.213Z",
8
+ "timestamp": "2026-09-12T12:10:54.820Z",
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.34",
22
+ "bom-ref": "@blamejs/pki@0.7.36",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.7.34",
25
+ "version": "0.7.36",
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.34",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.7.36",
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.34",
57
+ "ref": "@blamejs/pki@0.7.36",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]