@blamejs/pki 0.7.35 → 0.7.37
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 +26 -0
- package/README.md +2 -2
- package/lib/attrcert-sign.js +184 -33
- package/lib/cmp-verify.js +2 -9
- package/lib/cms-sign.js +3 -0
- package/lib/crl-sign.js +1 -9
- package/lib/csr-sign.js +4 -1
- package/lib/ct.js +10 -1
- package/lib/guard-name.js +10 -1
- package/lib/lint.js +1 -13
- package/lib/ocsp.js +96 -31
- package/lib/pki-build.js +41 -11
- package/lib/schema-attrcert.js +7 -0
- package/lib/schema-ocsp.js +4 -2
- package/lib/x509-sign.js +1 -8
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,32 @@ 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.37 — 2026-09-12
|
|
8
|
+
|
|
9
|
+
Every object a signer reads refuses a field it does not read, a signed OCSP request names its signer, and the requester nonce meets the RFC 9654 floor.
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- pki.ocsp.sign refuses an unknown field in responseData (accepted: responderID, responses, producedAt), in each response entry (cert, issuer, certID, hashAlgorithm, status, thisUpdate, nextUpdate, singleExtensions), in the responder ({ cert, key }) and in a revoked status ({ revoked, revocationReason }); pki.ocsp.buildRequest refuses one in a query entry ({ cert, issuer, singleRequestExtensions }) and in the signer ({ cert, key }). A signing option such as extendedRevoke given in responseData was silently ignored before; it is now refused with the message naming where it belongs.
|
|
14
|
+
- pki.attrcert.sign refuses an unknown option (accepted: pem, pss, digestAlgorithm) and an unknown field in a role, clearance, securityCategory, group / chargingIdentity (IetfAttrSyntax) and its values, authenticationInfo / accessIdentity, target, aaControls, objectDigestInfo or baseCertificateID object. The CRL distribution points extension key is spelled cRLDistributionPoints, as pki.x509.sign spells it; the spelling crlDistributionPoints is refused with a message naming the key.
|
|
15
|
+
- pki.csr.sign refuses an unknown field beside key in the { key } wrapper; pki.ct.signSct refuses an unknown option (accepted: timestamp, extensions, logId), and a log entry carrying a field its arm does not read (a leafCert on a precert_entry, an unknown name on either) is refused by signSct and verifySct alike; a CMS signed or unsigned attribute entry is { type, values } and nothing else.
|
|
16
|
+
- pki.ocsp.buildRequest with a signer takes the signer certificate's subject as the requestorName when none is stated (RFC 6960 sec. 4.1.2: a requestor that signs SHALL specify its name), and pki.ocsp.verifyRequest holds the requestorName of a signed request to the subject of a certificate that verified the signature, compared as a distinguished name; the verdict reports it as requestorNamed and valid requires it. A requestorName given as a GeneralName form other than directoryName is not compared and never passes. The parsed request carries the requestorName's decoded value.
|
|
17
|
+
- pki.ocsp.buildRequest refuses a caller nonce shorter than 32 octets (RFC 9654 sec. 2.1: an OCSP requester MUST use a minimum length of 32 octets); the responder side keeps the section's 1..128 octet bounds for the nonce it echoes.
|
|
18
|
+
|
|
19
|
+
## v0.7.36 — 2026-09-12
|
|
20
|
+
|
|
21
|
+
The attribute-certificate signer holds its extensions and attributes to the RFC 5755 issuer rules, and emits the authority key identifier by default.
|
|
22
|
+
|
|
23
|
+
### Added
|
|
24
|
+
|
|
25
|
+
- 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.
|
|
26
|
+
- 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.
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
|
|
30
|
+
- 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.
|
|
31
|
+
- 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.
|
|
32
|
+
|
|
7
33
|
## v0.7.35 — 2026-09-12
|
|
8
34
|
|
|
9
35
|
The timestamp signer refuses a TSA certificate its verifier would refuse, and keeps genTime's fraction of a second.
|
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` |
|
|
@@ -242,7 +242,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
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
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
|
-
| `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` |
|
|
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 (32 to 128 octets, the requester floor that section sets) and an optional requestor signature, under which the signer certificate's subject is the requestorName unless one is stated (RFC 6960 §4.1.2). `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 the signature and whose subject is the `requestorName` the request states (`signerCerts`, so a key carried under an expired certificate beside its renewal is not hidden behind ordering, while a same-key certificate under another name is not the requestor) with the first one's decoded subject, the full embedded certificate bag (`certs`, including intermediates for path building), and the request's CertIDs; the name check is reported as `requestorNamed` (RFC 6960 §4.1.2) and `valid` requires it, a request no verifying certificate names falls back to listing the verifying ones with `valid: false`, and 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` |
|
|
248
248
|
| `pki.trust` | Mozilla and CCADB trust-store ingestion. `parseCertdata` reads the NSS `certdata.txt` object stream and `parseCcadbCsv` the CCADB CSV export, both into one constraint-carrying anchor shape: the per-purpose trust bits, where only `CKT_NSS_TRUSTED_DELEGATOR` grants, and the per-purpose distrust-after dates the bare root list omits. Certificate and trust objects pair by byte-exact issuer and serial rather than adjacency and are cross-checked against the parsed DER, so metadata cannot attach to the wrong root. `anchor()` hands an entry to `pki.path.validate({ trustAnchors, checkPurpose })`, and `anchor(entry, { nameConstraints })` attaches the namespace a root program trusts a root for when that is narrower than the root certificate states, a `{ permitted, excluded }` pair of `{ tag, base }` subtrees that `validate` seeds as the RFC 5280 §6.1.1(h)(i) initial value, intersecting with each certificate's own constraints. Offline, fail-closed, bounded — `parseCertdata`, `parseCcadbCsv`, `anchor` |
|
package/lib/attrcert-sign.js
CHANGED
|
@@ -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");
|
|
@@ -47,6 +47,24 @@ var _b = pkiBuild.makeBuilder({
|
|
|
47
47
|
|
|
48
48
|
var KNOWN_SPEC_KEYS = intrinsic.assign(intrinsic.create(null), { holder: 1, notBeforeTime: 1, notAfterTime: 1, serialNumber: 1, attributes: 1, extensions: 1 });
|
|
49
49
|
var KNOWN_HOLDER_KEYS = intrinsic.assign(intrinsic.create(null), { entityName: 1, baseCertificateID: 1, fromCertificate: 1, objectDigestInfo: 1 });
|
|
50
|
+
/** @internal Every object this verb reads fields from is held to the fields it reads, so a
|
|
51
|
+
* misspelled one is refused rather than left as a default with nothing reported. */
|
|
52
|
+
var KNOWN_SIGN_OPTS = intrinsic.assign(intrinsic.create(null), { pem: 1, pss: 1, digestAlgorithm: 1 });
|
|
53
|
+
var KNOWN_ISSUER_SERIAL_KEYS = intrinsic.assign(intrinsic.create(null), { issuer: 1, serial: 1, issuerUID: 1 });
|
|
54
|
+
var KNOWN_ODI_KEYS = intrinsic.assign(intrinsic.create(null), { digestedObjectType: 1, digestAlgorithm: 1, objectDigest: 1 });
|
|
55
|
+
var KNOWN_ROLE_KEYS = intrinsic.assign(intrinsic.create(null), { roleAuthority: 1, roleName: 1 });
|
|
56
|
+
var KNOWN_CLEARANCE_KEYS = intrinsic.assign(intrinsic.create(null), { policyId: 1, classList: 1, securityCategories: 1 });
|
|
57
|
+
var KNOWN_SECURITY_CATEGORY_KEYS = intrinsic.assign(intrinsic.create(null), { type: 1, value: 1 });
|
|
58
|
+
var KNOWN_IETF_ATTR_KEYS = intrinsic.assign(intrinsic.create(null), { policyAuthority: 1, values: 1 });
|
|
59
|
+
var KNOWN_IETF_ATTR_VALUE_KEYS = intrinsic.assign(intrinsic.create(null), { octets: 1, oid: 1, string: 1 });
|
|
60
|
+
var KNOWN_SVCE_AUTH_INFO_KEYS = intrinsic.assign(intrinsic.create(null), { service: 1, ident: 1, authInfo: 1 });
|
|
61
|
+
var KNOWN_TARGET_KEYS = intrinsic.assign(intrinsic.create(null), { targetName: 1, targetGroup: 1 });
|
|
62
|
+
var KNOWN_AA_CONTROLS_KEYS = intrinsic.assign(intrinsic.create(null), { pathLenConstraint: 1, permittedAttrs: 1, excludedAttrs: 1, permitUnSpecified: 1 });
|
|
63
|
+
function _assertFields(obj, known, what) {
|
|
64
|
+
guard.identifier.assertKnownKeys(obj, known, _err, "attrcert/bad-input", function (k) {
|
|
65
|
+
return "unknown " + what + " field " + guard.text.showValue(k) + " (accepted: " + intrinsic.join(intrinsic.keys(known), ", ") + ")";
|
|
66
|
+
});
|
|
67
|
+
}
|
|
50
68
|
var ATTR_OID_NAME = intrinsic.assign(intrinsic.create(null), {
|
|
51
69
|
role: "role", clearance: "clearance", group: "group", chargingIdentity: "chargingIdentity",
|
|
52
70
|
accessIdentity: "accessIdentity", authenticationInfo: "authenticationInfo",
|
|
@@ -58,9 +76,85 @@ var EXT_META = intrinsic.assign(intrinsic.create(null), {
|
|
|
58
76
|
aaControls: { name: "aaControls", critical: true },
|
|
59
77
|
acProxying: { name: "acProxying", critical: true },
|
|
60
78
|
authorityKeyIdentifier: { name: "authorityKeyIdentifier", critical: false },
|
|
79
|
+
cRLDistributionPoints: { name: "cRLDistributionPoints", critical: false },
|
|
80
|
+
authorityInfoAccess: { name: "authorityInfoAccess", critical: false },
|
|
61
81
|
});
|
|
62
82
|
var REQUIRED_CRITICALITY = intrinsic.create(null);
|
|
63
83
|
Object.keys(EXT_META).forEach(function (k) { REQUIRED_CRITICALITY[O(EXT_META[k].name)] = EXT_META[k].critical; });
|
|
84
|
+
var OID_AKI = O("authorityKeyIdentifier"), OID_OCSP = O("ocsp");
|
|
85
|
+
|
|
86
|
+
/** @internal RFC 5755 sets rules on the issuer that its parser reads past and its verifier does
|
|
87
|
+
* not grade: an audit identity is 1..20 octets (sec. 4.3.1), a conforming issuer produces one
|
|
88
|
+
* Targets element (sec. 4.3.2), a stated authority key identifier is the AA certificate's subject
|
|
89
|
+
* key identifier (sec. 4.3.3), an OCSP access location is a URI carrying an HTTP URL (sec. 4.3.4),
|
|
90
|
+
* and a CRL distribution point is one point naming a fullName of a single distinguished name or
|
|
91
|
+
* HTTP / LDAP URL (sec. 4.3.5). Each rule reads the DECODED value, so the object form and the
|
|
92
|
+
* pre-encoded form are held to one definition. */
|
|
93
|
+
var EXT_PROFILE = intrinsic.create(null);
|
|
94
|
+
EXT_PROFILE[O("acAuditIdentity")] = function (id) {
|
|
95
|
+
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)");
|
|
96
|
+
};
|
|
97
|
+
EXT_PROFILE[O("targetInformation")] = function (groups) {
|
|
98
|
+
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)");
|
|
99
|
+
for (var i = 0; i < groups[0].length; i++) {
|
|
100
|
+
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");
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
EXT_PROFILE[OID_AKI] = function (aki, ctx) {
|
|
104
|
+
if (aki.keyIdentifier !== null && ctx.aaSki !== null && !_bufferEquals(aki.keyIdentifier, ctx.aaSki)) {
|
|
105
|
+
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");
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
EXT_PROFILE[O("authorityInfoAccess")] = function (descs) {
|
|
109
|
+
for (var i = 0; i < descs.length; i++) {
|
|
110
|
+
var d = descs[i];
|
|
111
|
+
if (d.accessMethod !== OID_OCSP) continue;
|
|
112
|
+
if (d.accessLocation.tag !== 6 || !pkiBuild.isHttpUrl(d.accessLocation.value)) {
|
|
113
|
+
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)");
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
EXT_PROFILE[O("cRLDistributionPoints")] = function (points) {
|
|
118
|
+
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)");
|
|
119
|
+
var dp = points[0].distributionPoint;
|
|
120
|
+
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)");
|
|
121
|
+
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)");
|
|
122
|
+
var gn = attrcert.readGeneralName(dp.names[0], "attrcert/bad-input");
|
|
123
|
+
if (gn.tagNumber !== 4 && (gn.tagNumber !== 6 || !(pkiBuild.isHttpUrl(gn.value) || pkiBuild.isLdapUrl(gn.value)))) {
|
|
124
|
+
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)");
|
|
125
|
+
}
|
|
126
|
+
/** @internal Sec. 4.3.5 profiles the RFC 5280 extension, whose sec. 4.2.1.13 has cRLIssuer carry
|
|
127
|
+
* the CRL issuer's Name; a GeneralNames holding no non-empty directoryName names no issuer. */
|
|
128
|
+
var issuer = points[0].cRLIssuer;
|
|
129
|
+
if (issuer !== null && !_namesAnIssuer(issuer.names)) {
|
|
130
|
+
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)");
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
function _namesAnIssuer(names) {
|
|
134
|
+
for (var i = 0; i < names.length; i++) {
|
|
135
|
+
if (names[i].tagNumber === 4 && names[i].value.rdns.length > 0) return true;
|
|
136
|
+
}
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** @internal Sec. 4.4.5: "roleName MUST use the uniformResourceIdentifier CHOICE of the
|
|
141
|
+
* GeneralName", read off the decoded attribute value on both routes. */
|
|
142
|
+
var ATTR_PROFILE = intrinsic.create(null);
|
|
143
|
+
ATTR_PROFILE[O("role")] = function (role) {
|
|
144
|
+
if (role.roleName.tagNumber !== 6) throw _err("attrcert/bad-input", "role.roleName must be a uniformResourceIdentifier (RFC 5755 sec. 4.4.5)");
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
function _decodeExtensionValue(extnId, valueDer) {
|
|
148
|
+
return EXT_DECODERS[extnId] ? EXT_DECODERS[extnId](valueDer) : attrcert.validateExtensionValue(extnId, valueDer);
|
|
149
|
+
}
|
|
150
|
+
function _assertExtensionProfile(extnId, decoded, ctx) {
|
|
151
|
+
var rule = EXT_PROFILE[extnId];
|
|
152
|
+
if (rule !== undefined) rule(decoded, ctx);
|
|
153
|
+
}
|
|
154
|
+
function _assertAttributeProfile(type, decoded) {
|
|
155
|
+
var rule = ATTR_PROFILE[type];
|
|
156
|
+
if (rule !== undefined) rule(decoded);
|
|
157
|
+
}
|
|
64
158
|
var CLASSLIST_BIT = intrinsic.assign(intrinsic.create(null), { unmarked: 0, unclassified: 1, restricted: 2, confidential: 3, secret: 4, topSecret: 5 });
|
|
65
159
|
|
|
66
160
|
var _tbsNameBytes = pkiBuild.tbsNameField;
|
|
@@ -84,6 +178,7 @@ function _gnList(spec) {
|
|
|
84
178
|
|
|
85
179
|
function _issuerSerialContent(is) {
|
|
86
180
|
if (!is || typeof is !== "object" || Buffer.isBuffer(is)) throw _err("attrcert/bad-input", "baseCertificateID must be an object { issuer, serial, issuerUID? }");
|
|
181
|
+
_assertFields(is, KNOWN_ISSUER_SERIAL_KEYS, "baseCertificateID");
|
|
87
182
|
if (is.issuer == null) throw _err("attrcert/bad-input", "baseCertificateID.issuer (a GeneralNames) is required");
|
|
88
183
|
var parts = [_b.encodeGeneralNames(_gnList(is.issuer)), _b.serialInteger(is.serial)];
|
|
89
184
|
if (is.issuerUID != null) {
|
|
@@ -95,6 +190,7 @@ function _issuerSerialContent(is) {
|
|
|
95
190
|
var ODT_CODE = intrinsic.assign(intrinsic.create(null), { publicKey: 0, publicKeyCert: 1 });
|
|
96
191
|
function _objectDigestInfoContent(odi) {
|
|
97
192
|
if (!odi || typeof odi !== "object" || Buffer.isBuffer(odi)) throw _err("attrcert/bad-input", "objectDigestInfo must be an object");
|
|
193
|
+
_assertFields(odi, KNOWN_ODI_KEYS, "objectDigestInfo");
|
|
98
194
|
var code = ODT_CODE[guard.text.keyOf(odi.digestedObjectType)];
|
|
99
195
|
if (code == null) throw _err("attrcert/bad-input", "objectDigestInfo.digestedObjectType must be 'publicKey' or 'publicKeyCert' (otherObjectTypes is forbidden, RFC 5755 sec. 7.3)");
|
|
100
196
|
if (!Buffer.isBuffer(odi.objectDigest)) throw _err("attrcert/bad-input", "objectDigestInfo.objectDigest must be a Buffer (the whole-octet digest)");
|
|
@@ -139,14 +235,18 @@ function _encodeValidity(notBefore, notAfter) {
|
|
|
139
235
|
|
|
140
236
|
|
|
141
237
|
function _encodeRole(role) {
|
|
142
|
-
if (!role || typeof role !== "object"
|
|
238
|
+
if (!role || typeof role !== "object") throw _err("attrcert/bad-input", "role must be an object with a roleName GeneralName");
|
|
239
|
+
_assertFields(role, KNOWN_ROLE_KEYS, "role");
|
|
240
|
+
if (role.roleName == null) throw _err("attrcert/bad-input", "role must be an object with a roleName GeneralName");
|
|
143
241
|
var parts = [];
|
|
144
242
|
if (role.roleAuthority != null) parts.push(_b.encodeGeneralNames(_gnList(role.roleAuthority), 0));
|
|
145
243
|
parts.push(b.explicit(1, _b.encodeGeneralName(role.roleName)));
|
|
146
244
|
return b.sequence(parts);
|
|
147
245
|
}
|
|
148
246
|
function _encodeClearance(cl) {
|
|
149
|
-
if (!cl || typeof cl !== "object"
|
|
247
|
+
if (!cl || typeof cl !== "object") throw _err("attrcert/bad-input", "clearance must be an object with a policyId OID");
|
|
248
|
+
_assertFields(cl, KNOWN_CLEARANCE_KEYS, "clearance");
|
|
249
|
+
if (cl.policyId == null) throw _err("attrcert/bad-input", "clearance must be an object with a policyId OID");
|
|
150
250
|
var parts;
|
|
151
251
|
try { parts = [b.oid(O(cl.policyId) || cl.policyId)]; } catch (e) { throw _err("attrcert/bad-input", "clearance.policyId is not a valid object identifier", e); }
|
|
152
252
|
if (cl.classList != null) {
|
|
@@ -166,18 +266,23 @@ function _encodeClearance(cl) {
|
|
|
166
266
|
return b.sequence(parts);
|
|
167
267
|
}
|
|
168
268
|
function _encodeSecurityCategory(sc) {
|
|
169
|
-
if (!sc || typeof sc !== "object"
|
|
269
|
+
if (!sc || typeof sc !== "object") throw _err("attrcert/bad-input", "each securityCategory must be { type: OID, value: DER Buffer }");
|
|
270
|
+
_assertFields(sc, KNOWN_SECURITY_CATEGORY_KEYS, "securityCategory");
|
|
271
|
+
if (sc.type == null || !Buffer.isBuffer(sc.value)) throw _err("attrcert/bad-input", "each securityCategory must be { type: OID, value: DER Buffer }");
|
|
170
272
|
var node;
|
|
171
273
|
try { node = asn1.decode(sc.value); } catch (e) { throw _err("attrcert/bad-input", "securityCategory value must be a single well-formed DER element", e); }
|
|
172
274
|
if (node.bytes.length !== sc.value.length) throw _err("attrcert/bad-input", "securityCategory value must be exactly one DER element (no trailing bytes)");
|
|
173
275
|
return b.sequence([b.contextPrimitive(0, _oidContent(sc.type)), b.explicit(1, sc.value)]);
|
|
174
276
|
}
|
|
175
277
|
function _encodeIetfAttrSyntax(ia) {
|
|
176
|
-
if (!ia || typeof ia !== "object"
|
|
278
|
+
if (!ia || typeof ia !== "object") throw _err("attrcert/bad-input", "an IetfAttrSyntax attribute must be an object with a non-empty values array");
|
|
279
|
+
_assertFields(ia, KNOWN_IETF_ATTR_KEYS, "IetfAttrSyntax");
|
|
280
|
+
if (!Array.isArray(ia.values) || !ia.values.length) throw _err("attrcert/bad-input", "an IetfAttrSyntax attribute must be an object with a non-empty values array");
|
|
177
281
|
var parts = [];
|
|
178
282
|
if (ia.policyAuthority != null) parts.push(_b.encodeGeneralNames(_gnList(ia.policyAuthority), 0));
|
|
179
283
|
parts.push(b.sequence(ia.values.map(function (v) {
|
|
180
284
|
if (v == null || typeof v !== "object") throw _err("attrcert/bad-input", "each IetfAttrSyntax value must be { octets }, { oid }, or { string }");
|
|
285
|
+
_assertFields(v, KNOWN_IETF_ATTR_VALUE_KEYS, "IetfAttrSyntax value");
|
|
181
286
|
if (v.octets != null) { if (!Buffer.isBuffer(v.octets)) throw _err("attrcert/bad-input", "IetfAttrSyntax octets must be a Buffer"); return b.octetString(v.octets); }
|
|
182
287
|
if (v.oid != null) { try { return b.oid(O(v.oid) || v.oid); } catch (e) { throw _err("attrcert/bad-input", "IetfAttrSyntax oid is not a valid object identifier", e); } }
|
|
183
288
|
if (v.string != null) return b.utf8(String(v.string));
|
|
@@ -186,7 +291,9 @@ function _encodeIetfAttrSyntax(ia) {
|
|
|
186
291
|
return b.sequence(parts);
|
|
187
292
|
}
|
|
188
293
|
function _encodeSvceAuthInfo(sai, authInfoAllowed, label) {
|
|
189
|
-
if (!sai || typeof sai !== "object"
|
|
294
|
+
if (!sai || typeof sai !== "object") throw _err("attrcert/bad-input", label + " must be an object with a service and an ident GeneralName");
|
|
295
|
+
_assertFields(sai, KNOWN_SVCE_AUTH_INFO_KEYS, label);
|
|
296
|
+
if (sai.service == null || sai.ident == null) throw _err("attrcert/bad-input", label + " must be an object with a service and an ident GeneralName");
|
|
190
297
|
var parts = [_b.encodeGeneralName(sai.service), _b.encodeGeneralName(sai.ident)];
|
|
191
298
|
if (sai.authInfo != null) {
|
|
192
299
|
if (!authInfoAllowed) throw _err("attrcert/bad-input", "accessIdentity must not carry authInfo (RFC 5755 sec. 4.4.2)");
|
|
@@ -208,6 +315,7 @@ var ATTR_VALUE_ENCODER = intrinsic.assign(intrinsic.create(null), {
|
|
|
208
315
|
|
|
209
316
|
function _encodeTarget(t) {
|
|
210
317
|
if (!t || typeof t !== "object") throw _err("attrcert/bad-input", "each target must be { targetName } or { targetGroup }");
|
|
318
|
+
_assertFields(t, KNOWN_TARGET_KEYS, "target");
|
|
211
319
|
if (t.targetName != null) return b.explicit(0, _b.encodeGeneralName(t.targetName));
|
|
212
320
|
if (t.targetGroup != null) return b.explicit(1, _b.encodeGeneralName(t.targetGroup));
|
|
213
321
|
throw _err("attrcert/bad-input", "each target must be { targetName } or { targetGroup }");
|
|
@@ -225,6 +333,7 @@ function _attrSpec(names, tag, label) {
|
|
|
225
333
|
}
|
|
226
334
|
function _encodeAAControls(aac) {
|
|
227
335
|
if (!aac || typeof aac !== "object" || Buffer.isBuffer(aac)) throw _err("attrcert/bad-input", "aaControls must be an object");
|
|
336
|
+
_assertFields(aac, KNOWN_AA_CONTROLS_KEYS, "aaControls");
|
|
228
337
|
var parts = [];
|
|
229
338
|
if (aac.pathLenConstraint != null) {
|
|
230
339
|
if (typeof aac.pathLenConstraint !== "number" || !Number.isInteger(aac.pathLenConstraint) || aac.pathLenConstraint < 0 || aac.pathLenConstraint > 0x7fffffff) throw _err("attrcert/bad-input", "aaControls.pathLenConstraint must be an integer in 0..2147483647 (RFC 5755 sec. 7.4)");
|
|
@@ -236,7 +345,15 @@ function _encodeAAControls(aac) {
|
|
|
236
345
|
else if (aac.permitUnSpecified != null && aac.permitUnSpecified !== true) throw _err("attrcert/bad-input", "aaControls.permitUnSpecified must be a boolean");
|
|
237
346
|
return b.sequence(parts);
|
|
238
347
|
}
|
|
239
|
-
|
|
348
|
+
/** @internal Sec. 4.3.3 reads RFC 5280 sec. 4.2.1.1 with "CA" as "AC issuer": the keyIdentifier is
|
|
349
|
+
* the AA certificate's subjectKeyIdentifier when that certificate is at hand, else the method (1)
|
|
350
|
+
* value of the AA key. A stated one is held to the certificate's by the profile rule. */
|
|
351
|
+
function _akiKeyId(val, ctx) {
|
|
352
|
+
if (guard.bytes.isByteSource(val)) return guard.bytes.snapshotSource(val, AttrCertError, "attrcert/bad-input", "the authorityKeyIdentifier keyIdentifier");
|
|
353
|
+
if (val === true) return ctx.aaSki !== null ? ctx.aaSki : _b.spkiKeyId(ctx.aaSpki);
|
|
354
|
+
throw _err("attrcert/bad-input", "authorityKeyIdentifier must be true (derive from the AA), false (omit), or a Buffer key id");
|
|
355
|
+
}
|
|
356
|
+
function _extensionValue(key, val, ctx) {
|
|
240
357
|
switch (key) {
|
|
241
358
|
case "auditIdentity":
|
|
242
359
|
if (!Buffer.isBuffer(val)) throw _err("attrcert/bad-input", "auditIdentity must be a Buffer (an OCTET STRING audit tag)");
|
|
@@ -245,7 +362,9 @@ function _extensionValue(key, val, aaSpki) {
|
|
|
245
362
|
case "acProxying": return _encodeSeqOfTargets(val);
|
|
246
363
|
case "noRevAvail": return b.nullValue();
|
|
247
364
|
case "aaControls": return _encodeAAControls(val);
|
|
248
|
-
case "authorityKeyIdentifier": return _b.extAki(
|
|
365
|
+
case "authorityKeyIdentifier": return _b.extAki(_akiKeyId(val, ctx));
|
|
366
|
+
case "cRLDistributionPoints": return _b.extCrlDistributionPoints(val, "cRLDistributionPoints");
|
|
367
|
+
case "authorityInfoAccess": return _b.extAuthorityInfoAccess(val);
|
|
249
368
|
default: throw _err("attrcert/bad-input", "unknown extension " + JSON.stringify(key));
|
|
250
369
|
}
|
|
251
370
|
}
|
|
@@ -256,6 +375,7 @@ function _buildAttributes(attrSpec) {
|
|
|
256
375
|
function add(type, valueTlv) {
|
|
257
376
|
if (seen[type]) throw _err("attrcert/duplicate-attribute", "duplicate " + (oid.name(type) || type) + " attribute (RFC 5755 sec. 4.2.7)");
|
|
258
377
|
seen[type] = true;
|
|
378
|
+
_assertAttributeProfile(type, attrcert.validateAttributeValue(type, valueTlv));
|
|
259
379
|
attrs.push(b.sequence([b.oid(type), b.set([valueTlv])]));
|
|
260
380
|
}
|
|
261
381
|
if (Array.isArray(attrSpec)) {
|
|
@@ -270,8 +390,10 @@ function _buildAttributes(attrSpec) {
|
|
|
270
390
|
if (seen[at]) throw _err("attrcert/duplicate-attribute", "duplicate " + (oid.name(at) || at) + " attribute (RFC 5755 sec. 4.2.7)");
|
|
271
391
|
seen[at] = true;
|
|
272
392
|
n.children[1].children.forEach(function (valNode) {
|
|
273
|
-
|
|
393
|
+
var decoded;
|
|
394
|
+
try { decoded = attrcert.validateAttributeValue(at, valNode.bytes); }
|
|
274
395
|
catch (err) { if (err instanceof AttrCertError) throw err; throw _err("attrcert/bad-input", "pre-encoded " + (oid.name(at) || at) + " attribute value is malformed", err); }
|
|
396
|
+
_assertAttributeProfile(at, decoded);
|
|
275
397
|
});
|
|
276
398
|
attrs.push(b.raw(der));
|
|
277
399
|
});
|
|
@@ -300,8 +422,16 @@ function _assertRevocationSchemesExclusive(seen) {
|
|
|
300
422
|
}
|
|
301
423
|
}
|
|
302
424
|
|
|
303
|
-
function
|
|
304
|
-
|
|
425
|
+
function _emitNamedExtension(out, seen, k, val, ctx) {
|
|
426
|
+
var meta = EXT_META[k], eOid = O(meta.name);
|
|
427
|
+
if (seen[eOid]) throw _err("attrcert/bad-input", "duplicate extension " + JSON.stringify(k) + " (RFC 5755 sec. 4.2.9)");
|
|
428
|
+
seen[eOid] = true;
|
|
429
|
+
var valueDer = _extensionValue(k, val, ctx);
|
|
430
|
+
_assertExtensionProfile(eOid, _decodeExtensionValue(eOid, valueDer), ctx);
|
|
431
|
+
out.push(_b.ext(eOid, meta.critical, valueDer));
|
|
432
|
+
}
|
|
433
|
+
function _buildExtensions(extSpec, ctx) {
|
|
434
|
+
if (extSpec == null) extSpec = {};
|
|
305
435
|
if (Array.isArray(extSpec)) {
|
|
306
436
|
if (!extSpec.length) return null;
|
|
307
437
|
var seenA = intrinsic.create(null);
|
|
@@ -317,10 +447,10 @@ function _buildExtensions(extSpec, aaSpki) {
|
|
|
317
447
|
throw _err("attrcert/bad-input", "pre-encoded " + (oid.name(extnId) || extnId) + " extension must be marked " + (required ? "critical" : "non-critical") + " (RFC 5755)");
|
|
318
448
|
}
|
|
319
449
|
var extnValue = asn1.read.octetString(n.children[n.children.length - 1]);
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
450
|
+
var decoded;
|
|
451
|
+
try { decoded = _decodeExtensionValue(extnId, extnValue); }
|
|
452
|
+
catch (err) { if (err instanceof AttrCertError) throw err; throw _err("attrcert/bad-input", "pre-encoded " + (oid.name(extnId) || extnId) + " extension value is malformed", err); }
|
|
453
|
+
_assertExtensionProfile(extnId, decoded, ctx);
|
|
324
454
|
return b.raw(der);
|
|
325
455
|
});
|
|
326
456
|
_assertRevocationSchemesExclusive(seenA);
|
|
@@ -328,16 +458,20 @@ function _buildExtensions(extSpec, aaSpki) {
|
|
|
328
458
|
}
|
|
329
459
|
if (typeof extSpec !== "object") throw _err("attrcert/bad-input", "extensions must be an object or an array of pre-encoded Extension DER");
|
|
330
460
|
guard.identifier.assertKnownKeys(extSpec, EXT_META, _err, "attrcert/bad-input", function (k) {
|
|
461
|
+
if (k === "crlDistributionPoints") return "the extension key is cRLDistributionPoints, spelled as pki.x509.sign spells it";
|
|
331
462
|
return "unknown extension " + JSON.stringify(k) + "; pass a pre-encoded Extension DER via the array form for a custom extension";
|
|
332
463
|
});
|
|
333
464
|
var out = [], seen = intrinsic.create(null);
|
|
465
|
+
var akiDeclined = false;
|
|
334
466
|
Object.keys(extSpec).forEach(function (k) {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
if (
|
|
338
|
-
seen
|
|
339
|
-
out.push(_b.ext(eOid, meta.critical, _extensionValue(k, extSpec[k], aaSpki)));
|
|
467
|
+
var val = extSpec[k];
|
|
468
|
+
if (val == null) return;
|
|
469
|
+
if (k === "authorityKeyIdentifier" && val === false) { akiDeclined = true; return; }
|
|
470
|
+
_emitNamedExtension(out, seen, k, val, ctx);
|
|
340
471
|
});
|
|
472
|
+
/** @internal Sec. 4.3.3: "As with PKCs, this extension SHOULD be included in ACs", so it is
|
|
473
|
+
* emitted without being named and `false` declines it, which a SHOULD allows. */
|
|
474
|
+
if (!seen[OID_AKI] && !akiDeclined) _emitNamedExtension(out, seen, "authorityKeyIdentifier", true, ctx);
|
|
341
475
|
_assertRevocationSchemesExclusive(seen);
|
|
342
476
|
if (!out.length) return null;
|
|
343
477
|
return b.sequence(out);
|
|
@@ -359,13 +493,27 @@ function _buildExtensions(extSpec, aaSpki) {
|
|
|
359
493
|
* a random 20-octet serial is generated when omitted), `attributes` (an object of the sec. 4.4 privilege
|
|
360
494
|
* syntaxes (role / clearance / group / chargingIdentity / accessIdentity / authenticationInfo), or an
|
|
361
495
|
* array of pre-encoded Attribute DER), and optional `extensions` (an object of auditIdentity /
|
|
362
|
-
* targetInformation / noRevAvail / aaControls / acProxying / authorityKeyIdentifier
|
|
363
|
-
*
|
|
364
|
-
*
|
|
365
|
-
*
|
|
366
|
-
*
|
|
367
|
-
*
|
|
368
|
-
*
|
|
496
|
+
* targetInformation / noRevAvail / aaControls / acProxying / authorityKeyIdentifier /
|
|
497
|
+
* cRLDistributionPoints / authorityInfoAccess, the last two in the list forms `pki.x509.sign`
|
|
498
|
+
* takes, or an array of pre-encoded Extension DER). `issuer` is the signing AA: `{ cert, key }` (the AA
|
|
499
|
+
* certificate DER/PEM and its private key) or `{ name, publicKey, key }` (an explicit issuer DN, AA
|
|
500
|
+
* SPKI DER, and key); an attribute certificate is never self-signed. RFC 5755 section 6 defines two
|
|
501
|
+
* revocation schemes and makes them exclusive ("An AC MUST NOT contain both a noRevAvail extension
|
|
502
|
+
* and a 'pointer in AC'"), so `noRevAvail` beside a `cRLDistributionPoints` or `authorityInfoAccess`
|
|
503
|
+
* extension is refused, in the named form and the pre-encoded form alike.
|
|
504
|
+
*
|
|
505
|
+
* The `authorityKeyIdentifier` is emitted without being named (section 4.3.3: "this extension
|
|
506
|
+
* SHOULD be included in ACs"); its keyIdentifier is the AA certificate's subjectKeyIdentifier when
|
|
507
|
+
* `issuer.cert` is given, else the RFC 5280 method (1) value of the AA key, and a stated one is held
|
|
508
|
+
* to the certificate's. `authorityKeyIdentifier: false` omits it. The pre-encoded array form emits
|
|
509
|
+
* exactly what it is given. Both forms are held to the rules section 4.3 and 4.4 place on the
|
|
510
|
+
* issuer, read off the decoded value: an auditIdentity is 1 to 20 octets (4.3.1); a
|
|
511
|
+
* targetInformation carries one Targets element and never a targetCert (4.3.2); an id-ad-ocsp
|
|
512
|
+
* accessLocation is a URI carrying an HTTP URL (4.3.4); a cRLDistributionPoints names one
|
|
513
|
+
* distribution point as a fullName holding a single directoryName or an HTTP or LDAP URL, and a
|
|
514
|
+
* cRLIssuer beside it names the CRL issuer as a directoryName (4.3.5, RFC 5280 sec. 4.2.1.13);
|
|
515
|
+
* and a role's roleName is a uniformResourceIdentifier (4.4.5). A violation is refused with
|
|
516
|
+
* `attrcert/bad-input`. The signature algorithm is resolved from the AA key (RSA
|
|
369
517
|
* PKCS#1 v1.5 or PSS, ECDSA, EdDSA, ML-DSA, SLH-DSA, or a composite arm), and the signature is verified
|
|
370
518
|
* under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE
|
|
371
519
|
* CERTIFICATE` with `opts.pem`. Malformed input throws a typed `AttrCertError`; where the spec carries
|
|
@@ -398,17 +546,19 @@ function sign(spec, issuer, opts) {
|
|
|
398
546
|
}
|
|
399
547
|
|
|
400
548
|
function _sign(spec, issuer, opts) {
|
|
401
|
-
opts = opts
|
|
549
|
+
opts = guard.identifier.optionsObject(opts, _err, "attrcert/bad-input", "pki.attrcert.sign options");
|
|
550
|
+
guard.identifier.assertKnownKeys(opts, KNOWN_SIGN_OPTS, _err, "attrcert/bad-input", "unknown pki.attrcert.sign option (accepted: pem, pss, digestAlgorithm): ");
|
|
402
551
|
if (!spec || typeof spec !== "object" || Buffer.isBuffer(spec)) throw _err("attrcert/bad-input", "the attribute-certificate spec must be an object");
|
|
403
552
|
guard.identifier.assertKnownKeys(spec, KNOWN_SPEC_KEYS, _err, "attrcert/bad-input", "unknown spec field ");
|
|
404
553
|
issuer = issuer || {};
|
|
405
554
|
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
555
|
|
|
407
|
-
var issuerDnSpec, aaSpki;
|
|
556
|
+
var issuerDnSpec, aaSpki, aaSki = null;
|
|
408
557
|
if (issuer.cert != null) {
|
|
409
558
|
var aaCert = _parseCert(issuer.cert, "issuer.cert");
|
|
410
559
|
issuerDnSpec = _tbsNameBytes(aaCert, "subject");
|
|
411
560
|
aaSpki = aaCert.subjectPublicKeyInfo.bytes;
|
|
561
|
+
aaSki = pkiBuild.skiValueOf(aaCert);
|
|
412
562
|
} else if (issuer.name != null && issuer.publicKey != null) {
|
|
413
563
|
issuerDnSpec = issuer.name;
|
|
414
564
|
aaSpki = _b.reqDer(issuer.publicKey, "issuer.publicKey (the AA SPKI DER)");
|
|
@@ -421,7 +571,7 @@ function _sign(spec, issuer, opts) {
|
|
|
421
571
|
var holderDer = _encodeHolder(spec.holder);
|
|
422
572
|
var validityDer = _encodeValidity(spec.notBeforeTime, spec.notAfterTime);
|
|
423
573
|
var attributesDer = _buildAttributes(spec.attributes);
|
|
424
|
-
var extsDer = _buildExtensions(spec.extensions, aaSpki);
|
|
574
|
+
var extsDer = _buildExtensions(spec.extensions, { aaSpki: aaSpki, aaSki: aaSki });
|
|
425
575
|
|
|
426
576
|
var scheme = signScheme.resolveSignScheme(_b.certLikeFromSpki(aaSpki), { combinedRsaSig: true, pss: opts.pss, digestAlgorithm: opts.digestAlgorithm }, true, _signE);
|
|
427
577
|
|
|
@@ -633,8 +783,9 @@ function _unsupportedCritical(ac) {
|
|
|
633
783
|
* verdict that skipped one would grant privileges the issuer expected to be able to withdraw. So an
|
|
634
784
|
* AC carrying `noRevAvail` verifies with `revocationChecked: true` and `noRevAvail: true`, and one
|
|
635
785
|
* without it is refused unless the caller supplies `opts.revocationStatus`. A caller running the
|
|
636
|
-
* section's "pointer in AC" scheme reads the certificate's own `
|
|
637
|
-
* `authorityInfoAccess` from the verdict's `extensions
|
|
786
|
+
* section's "pointer in AC" scheme reads the certificate's own `cRLDistributionPoints` /
|
|
787
|
+
* `authorityInfoAccess` from the verdict's `extensions` (each carried decoded, as the RFC 5280
|
|
788
|
+
* readers return them), establishes the status, and passes it back.
|
|
638
789
|
*
|
|
639
790
|
* Items 1 and 3, and the issuer path in item 2, need certificates this verb is not given: the
|
|
640
791
|
* holder's own public-key certificate and its chain, the AC issuer's chain, and the section 4.5
|
|
@@ -697,7 +848,7 @@ function _fixVerifyOptions(opts) {
|
|
|
697
848
|
}
|
|
698
849
|
|
|
699
850
|
var REVOCATION_POINTERS = Object.create(null);
|
|
700
|
-
REVOCATION_POINTERS[O("cRLDistributionPoints")] = "
|
|
851
|
+
REVOCATION_POINTERS[O("cRLDistributionPoints")] = "cRLDistributionPoints";
|
|
701
852
|
REVOCATION_POINTERS[O("authorityInfoAccess")] = "authorityInfoAccess";
|
|
702
853
|
|
|
703
854
|
function _revocationScheme(ac) {
|
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
|
-
|
|
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) {
|