@blamejs/pki 0.7.36 → 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 +12 -0
- package/README.md +2 -2
- package/lib/attrcert-sign.js +53 -18
- package/lib/cms-sign.js +3 -0
- package/lib/csr-sign.js +4 -1
- package/lib/ct.js +10 -1
- package/lib/ocsp.js +96 -31
- package/lib/schema-ocsp.js +4 -2
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,18 @@ All notable changes to `@blamejs/pki` are documented here. The format
|
|
|
4
4
|
follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
|
|
5
5
|
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
6
|
|
|
7
|
+
## v0.7.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
|
+
|
|
7
19
|
## v0.7.36 — 2026-09-12
|
|
8
20
|
|
|
9
21
|
The attribute-certificate signer holds its extensions and attributes to the RFC 5755 issuer rules, and emits the authority key identifier by default.
|
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,
|
|
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
|
@@ -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,7 +76,7 @@ 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 },
|
|
61
|
-
|
|
79
|
+
cRLDistributionPoints: { name: "cRLDistributionPoints", critical: false },
|
|
62
80
|
authorityInfoAccess: { name: "authorityInfoAccess", critical: false },
|
|
63
81
|
});
|
|
64
82
|
var REQUIRED_CRITICALITY = intrinsic.create(null);
|
|
@@ -97,19 +115,19 @@ EXT_PROFILE[O("authorityInfoAccess")] = function (descs) {
|
|
|
97
115
|
}
|
|
98
116
|
};
|
|
99
117
|
EXT_PROFILE[O("cRLDistributionPoints")] = function (points) {
|
|
100
|
-
if (points.length !== 1) throw _err("attrcert/bad-input", "
|
|
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)");
|
|
101
119
|
var dp = points[0].distributionPoint;
|
|
102
|
-
if (dp === null || dp.kind !== "fullName") throw _err("attrcert/bad-input", "the
|
|
103
|
-
if (dp.names.length !== 1) throw _err("attrcert/bad-input", "the
|
|
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)");
|
|
104
122
|
var gn = attrcert.readGeneralName(dp.names[0], "attrcert/bad-input");
|
|
105
123
|
if (gn.tagNumber !== 4 && (gn.tagNumber !== 6 || !(pkiBuild.isHttpUrl(gn.value) || pkiBuild.isLdapUrl(gn.value)))) {
|
|
106
|
-
throw _err("attrcert/bad-input", "the
|
|
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)");
|
|
107
125
|
}
|
|
108
126
|
/** @internal Sec. 4.3.5 profiles the RFC 5280 extension, whose sec. 4.2.1.13 has cRLIssuer carry
|
|
109
127
|
* the CRL issuer's Name; a GeneralNames holding no non-empty directoryName names no issuer. */
|
|
110
128
|
var issuer = points[0].cRLIssuer;
|
|
111
129
|
if (issuer !== null && !_namesAnIssuer(issuer.names)) {
|
|
112
|
-
throw _err("attrcert/bad-input", "the
|
|
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)");
|
|
113
131
|
}
|
|
114
132
|
};
|
|
115
133
|
function _namesAnIssuer(names) {
|
|
@@ -160,6 +178,7 @@ function _gnList(spec) {
|
|
|
160
178
|
|
|
161
179
|
function _issuerSerialContent(is) {
|
|
162
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");
|
|
163
182
|
if (is.issuer == null) throw _err("attrcert/bad-input", "baseCertificateID.issuer (a GeneralNames) is required");
|
|
164
183
|
var parts = [_b.encodeGeneralNames(_gnList(is.issuer)), _b.serialInteger(is.serial)];
|
|
165
184
|
if (is.issuerUID != null) {
|
|
@@ -171,6 +190,7 @@ function _issuerSerialContent(is) {
|
|
|
171
190
|
var ODT_CODE = intrinsic.assign(intrinsic.create(null), { publicKey: 0, publicKeyCert: 1 });
|
|
172
191
|
function _objectDigestInfoContent(odi) {
|
|
173
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");
|
|
174
194
|
var code = ODT_CODE[guard.text.keyOf(odi.digestedObjectType)];
|
|
175
195
|
if (code == null) throw _err("attrcert/bad-input", "objectDigestInfo.digestedObjectType must be 'publicKey' or 'publicKeyCert' (otherObjectTypes is forbidden, RFC 5755 sec. 7.3)");
|
|
176
196
|
if (!Buffer.isBuffer(odi.objectDigest)) throw _err("attrcert/bad-input", "objectDigestInfo.objectDigest must be a Buffer (the whole-octet digest)");
|
|
@@ -215,14 +235,18 @@ function _encodeValidity(notBefore, notAfter) {
|
|
|
215
235
|
|
|
216
236
|
|
|
217
237
|
function _encodeRole(role) {
|
|
218
|
-
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");
|
|
219
241
|
var parts = [];
|
|
220
242
|
if (role.roleAuthority != null) parts.push(_b.encodeGeneralNames(_gnList(role.roleAuthority), 0));
|
|
221
243
|
parts.push(b.explicit(1, _b.encodeGeneralName(role.roleName)));
|
|
222
244
|
return b.sequence(parts);
|
|
223
245
|
}
|
|
224
246
|
function _encodeClearance(cl) {
|
|
225
|
-
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");
|
|
226
250
|
var parts;
|
|
227
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); }
|
|
228
252
|
if (cl.classList != null) {
|
|
@@ -242,18 +266,23 @@ function _encodeClearance(cl) {
|
|
|
242
266
|
return b.sequence(parts);
|
|
243
267
|
}
|
|
244
268
|
function _encodeSecurityCategory(sc) {
|
|
245
|
-
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 }");
|
|
246
272
|
var node;
|
|
247
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); }
|
|
248
274
|
if (node.bytes.length !== sc.value.length) throw _err("attrcert/bad-input", "securityCategory value must be exactly one DER element (no trailing bytes)");
|
|
249
275
|
return b.sequence([b.contextPrimitive(0, _oidContent(sc.type)), b.explicit(1, sc.value)]);
|
|
250
276
|
}
|
|
251
277
|
function _encodeIetfAttrSyntax(ia) {
|
|
252
|
-
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");
|
|
253
281
|
var parts = [];
|
|
254
282
|
if (ia.policyAuthority != null) parts.push(_b.encodeGeneralNames(_gnList(ia.policyAuthority), 0));
|
|
255
283
|
parts.push(b.sequence(ia.values.map(function (v) {
|
|
256
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");
|
|
257
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); }
|
|
258
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); } }
|
|
259
288
|
if (v.string != null) return b.utf8(String(v.string));
|
|
@@ -262,7 +291,9 @@ function _encodeIetfAttrSyntax(ia) {
|
|
|
262
291
|
return b.sequence(parts);
|
|
263
292
|
}
|
|
264
293
|
function _encodeSvceAuthInfo(sai, authInfoAllowed, label) {
|
|
265
|
-
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");
|
|
266
297
|
var parts = [_b.encodeGeneralName(sai.service), _b.encodeGeneralName(sai.ident)];
|
|
267
298
|
if (sai.authInfo != null) {
|
|
268
299
|
if (!authInfoAllowed) throw _err("attrcert/bad-input", "accessIdentity must not carry authInfo (RFC 5755 sec. 4.4.2)");
|
|
@@ -284,6 +315,7 @@ var ATTR_VALUE_ENCODER = intrinsic.assign(intrinsic.create(null), {
|
|
|
284
315
|
|
|
285
316
|
function _encodeTarget(t) {
|
|
286
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");
|
|
287
319
|
if (t.targetName != null) return b.explicit(0, _b.encodeGeneralName(t.targetName));
|
|
288
320
|
if (t.targetGroup != null) return b.explicit(1, _b.encodeGeneralName(t.targetGroup));
|
|
289
321
|
throw _err("attrcert/bad-input", "each target must be { targetName } or { targetGroup }");
|
|
@@ -301,6 +333,7 @@ function _attrSpec(names, tag, label) {
|
|
|
301
333
|
}
|
|
302
334
|
function _encodeAAControls(aac) {
|
|
303
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");
|
|
304
337
|
var parts = [];
|
|
305
338
|
if (aac.pathLenConstraint != null) {
|
|
306
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)");
|
|
@@ -330,7 +363,7 @@ function _extensionValue(key, val, ctx) {
|
|
|
330
363
|
case "noRevAvail": return b.nullValue();
|
|
331
364
|
case "aaControls": return _encodeAAControls(val);
|
|
332
365
|
case "authorityKeyIdentifier": return _b.extAki(_akiKeyId(val, ctx));
|
|
333
|
-
case "
|
|
366
|
+
case "cRLDistributionPoints": return _b.extCrlDistributionPoints(val, "cRLDistributionPoints");
|
|
334
367
|
case "authorityInfoAccess": return _b.extAuthorityInfoAccess(val);
|
|
335
368
|
default: throw _err("attrcert/bad-input", "unknown extension " + JSON.stringify(key));
|
|
336
369
|
}
|
|
@@ -425,6 +458,7 @@ function _buildExtensions(extSpec, ctx) {
|
|
|
425
458
|
}
|
|
426
459
|
if (typeof extSpec !== "object") throw _err("attrcert/bad-input", "extensions must be an object or an array of pre-encoded Extension DER");
|
|
427
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";
|
|
428
462
|
return "unknown extension " + JSON.stringify(k) + "; pass a pre-encoded Extension DER via the array form for a custom extension";
|
|
429
463
|
});
|
|
430
464
|
var out = [], seen = intrinsic.create(null);
|
|
@@ -460,12 +494,12 @@ function _buildExtensions(extSpec, ctx) {
|
|
|
460
494
|
* syntaxes (role / clearance / group / chargingIdentity / accessIdentity / authenticationInfo), or an
|
|
461
495
|
* array of pre-encoded Attribute DER), and optional `extensions` (an object of auditIdentity /
|
|
462
496
|
* targetInformation / noRevAvail / aaControls / acProxying / authorityKeyIdentifier /
|
|
463
|
-
*
|
|
497
|
+
* cRLDistributionPoints / authorityInfoAccess, the last two in the list forms `pki.x509.sign`
|
|
464
498
|
* takes, or an array of pre-encoded Extension DER). `issuer` is the signing AA: `{ cert, key }` (the AA
|
|
465
499
|
* certificate DER/PEM and its private key) or `{ name, publicKey, key }` (an explicit issuer DN, AA
|
|
466
500
|
* SPKI DER, and key); an attribute certificate is never self-signed. RFC 5755 section 6 defines two
|
|
467
501
|
* revocation schemes and makes them exclusive ("An AC MUST NOT contain both a noRevAvail extension
|
|
468
|
-
* and a 'pointer in AC'"), so `noRevAvail` beside a `
|
|
502
|
+
* and a 'pointer in AC'"), so `noRevAvail` beside a `cRLDistributionPoints` or `authorityInfoAccess`
|
|
469
503
|
* extension is refused, in the named form and the pre-encoded form alike.
|
|
470
504
|
*
|
|
471
505
|
* The `authorityKeyIdentifier` is emitted without being named (section 4.3.3: "this extension
|
|
@@ -475,7 +509,7 @@ function _buildExtensions(extSpec, ctx) {
|
|
|
475
509
|
* exactly what it is given. Both forms are held to the rules section 4.3 and 4.4 place on the
|
|
476
510
|
* issuer, read off the decoded value: an auditIdentity is 1 to 20 octets (4.3.1); a
|
|
477
511
|
* targetInformation carries one Targets element and never a targetCert (4.3.2); an id-ad-ocsp
|
|
478
|
-
* accessLocation is a URI carrying an HTTP URL (4.3.4); a
|
|
512
|
+
* accessLocation is a URI carrying an HTTP URL (4.3.4); a cRLDistributionPoints names one
|
|
479
513
|
* distribution point as a fullName holding a single directoryName or an HTTP or LDAP URL, and a
|
|
480
514
|
* cRLIssuer beside it names the CRL issuer as a directoryName (4.3.5, RFC 5280 sec. 4.2.1.13);
|
|
481
515
|
* and a role's roleName is a uniformResourceIdentifier (4.4.5). A violation is refused with
|
|
@@ -512,7 +546,8 @@ function sign(spec, issuer, opts) {
|
|
|
512
546
|
}
|
|
513
547
|
|
|
514
548
|
function _sign(spec, issuer, opts) {
|
|
515
|
-
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): ");
|
|
516
551
|
if (!spec || typeof spec !== "object" || Buffer.isBuffer(spec)) throw _err("attrcert/bad-input", "the attribute-certificate spec must be an object");
|
|
517
552
|
guard.identifier.assertKnownKeys(spec, KNOWN_SPEC_KEYS, _err, "attrcert/bad-input", "unknown spec field ");
|
|
518
553
|
issuer = issuer || {};
|
|
@@ -748,7 +783,7 @@ function _unsupportedCritical(ac) {
|
|
|
748
783
|
* verdict that skipped one would grant privileges the issuer expected to be able to withdraw. So an
|
|
749
784
|
* AC carrying `noRevAvail` verifies with `revocationChecked: true` and `noRevAvail: true`, and one
|
|
750
785
|
* without it is refused unless the caller supplies `opts.revocationStatus`. A caller running the
|
|
751
|
-
* section's "pointer in AC" scheme reads the certificate's own `
|
|
786
|
+
* section's "pointer in AC" scheme reads the certificate's own `cRLDistributionPoints` /
|
|
752
787
|
* `authorityInfoAccess` from the verdict's `extensions` (each carried decoded, as the RFC 5280
|
|
753
788
|
* readers return them), establishes the status, and passes it back.
|
|
754
789
|
*
|
|
@@ -813,7 +848,7 @@ function _fixVerifyOptions(opts) {
|
|
|
813
848
|
}
|
|
814
849
|
|
|
815
850
|
var REVOCATION_POINTERS = Object.create(null);
|
|
816
|
-
REVOCATION_POINTERS[O("cRLDistributionPoints")] = "
|
|
851
|
+
REVOCATION_POINTERS[O("cRLDistributionPoints")] = "cRLDistributionPoints";
|
|
817
852
|
REVOCATION_POINTERS[O("authorityInfoAccess")] = "authorityInfoAccess";
|
|
818
853
|
|
|
819
854
|
function _revocationScheme(ac) {
|
package/lib/cms-sign.js
CHANGED
|
@@ -84,8 +84,11 @@ function _buildSignedAttrs(pairs) {
|
|
|
84
84
|
return { setOf: setOf, wire: wire };
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
var KNOWN_ATTRIBUTE_KEYS = intrinsic.assign(intrinsic.create(null), { type: 1, values: 1 });
|
|
87
88
|
function _resolveAttrPairs(list, what) {
|
|
88
89
|
return intrinsic.map(list || [], function (a) {
|
|
90
|
+
if (!a || typeof a !== "object") throw _err("cms/bad-input", "an attribute must be { type, values }");
|
|
91
|
+
guard.identifier.assertKnownKeys(a, KNOWN_ATTRIBUTE_KEYS, _err, "cms/bad-input", "unknown attribute field (an attribute is { type, values }): ");
|
|
89
92
|
var vals = intrinsic.map(a.values || [], function (v) { return _toBuf(v, what); });
|
|
90
93
|
if (!vals.length) throw _err("cms/bad-input", "a signed attribute must carry at least one value (RFC 5652 -- Attribute values is SET SIZE (1..MAX))");
|
|
91
94
|
return { type: oid.isDottedDecimal(a.type) ? a.type : O(a.type), values: vals };
|
package/lib/csr-sign.js
CHANGED
|
@@ -34,6 +34,7 @@ var KNOWN_SPEC_KEYS = Object.assign(Object.create(null), { subject: 1, subjectPu
|
|
|
34
34
|
* them was accepted and dropped, so asking for PEM and misspelling the option returned DER and
|
|
35
35
|
* reported nothing. */
|
|
36
36
|
var KNOWN_SIGN_OPTS = Object.assign(Object.create(null), { digestAlgorithm: 1, pem: 1, pss: 1 });
|
|
37
|
+
var KNOWN_KEY_WRAPPER_KEYS = Object.assign(Object.create(null), { key: 1 });
|
|
37
38
|
var b = asn1.build;
|
|
38
39
|
function _err(code, message, cause) { return new CsrError(code, message, cause); }
|
|
39
40
|
function _signE(kind, message, cause) { return new CsrError("csr/" + kind, message, cause); }
|
|
@@ -109,7 +110,9 @@ function _sign(spec, key, opts) {
|
|
|
109
110
|
if (!spec || typeof spec !== "object" || Buffer.isBuffer(spec)) throw _err("csr/bad-input", "the certification-request spec must be an object");
|
|
110
111
|
guard.identifier.assertKnownKeys(spec, KNOWN_SPEC_KEYS, _err, "csr/bad-input", "unknown spec field ");
|
|
111
112
|
guard.identifier.assertKnownKeys(opts, KNOWN_SIGN_OPTS, _err, "csr/bad-input", "pki.csr.sign has an unknown option ");
|
|
112
|
-
var
|
|
113
|
+
var wrapped = key && typeof key === "object" && !Buffer.isBuffer(key) && !(key instanceof Uint8Array) && key.type == null && "key" in key;
|
|
114
|
+
if (wrapped) guard.identifier.assertKnownKeys(key, KNOWN_KEY_WRAPPER_KEYS, _err, "csr/bad-input", "unknown field in the { key } wrapper (a signing option belongs in the third argument): ");
|
|
115
|
+
var signingKey = wrapped ? key.key : key;
|
|
113
116
|
if (signingKey == null) throw _err("csr/bad-input", "a signing key (the subject's private key) is required");
|
|
114
117
|
|
|
115
118
|
var subjectSpki = _b.reqDer(spec.subjectPublicKey, "spec.subjectPublicKey (the SPKI DER of the requested key)");
|
package/lib/ct.js
CHANGED
|
@@ -255,12 +255,19 @@ function _u24Bytes(n) {
|
|
|
255
255
|
* var preimage = pki.ct.reconstructSignedData({ entryType: 0, leafCert: der }, sct);
|
|
256
256
|
* // hash `preimage` + verify against the log's public key at the verify layer
|
|
257
257
|
*/
|
|
258
|
+
/** @internal The two log-entry arms read different fields, and a field belonging to the other arm
|
|
259
|
+
* is refused the same way a misspelled one is: a value the arm never reads cannot be in the entry. */
|
|
260
|
+
var _X509_ENTRY_KEYS = intrinsic.assign(intrinsic.create(null), { entryType: 1, leafCert: 1 });
|
|
261
|
+
var _PRECERT_ENTRY_KEYS = intrinsic.assign(intrinsic.create(null), { entryType: 1, tbsCertificate: 1, issuerKeyHash: 1 });
|
|
258
262
|
function reconstructSignedData(entry, sct) {
|
|
259
263
|
entry = entry || {};
|
|
264
|
+
if (typeof entry !== "object") throw new CtError("ct/bad-input", "the log entry must be an object { entryType, ... } (RFC 6962 sec. 3.1)");
|
|
260
265
|
var entryType = entry.entryType;
|
|
261
266
|
if (entryType !== 0 && entryType !== 1) {
|
|
262
267
|
throw new CtError("ct/bad-entry-type", "entryType must be x509_entry(0) or precert_entry(1), got " + guard.text.showValue(entryType) + " (RFC 6962 sec. 3.1)");
|
|
263
268
|
}
|
|
269
|
+
guard.identifier.assertKnownKeys(entry, entryType === 0 ? _X509_ENTRY_KEYS : _PRECERT_ENTRY_KEYS, _ctErr, "ct/bad-input",
|
|
270
|
+
entryType === 0 ? "unknown x509_entry field (accepted: entryType, leafCert): " : "unknown precert_entry field (accepted: entryType, tbsCertificate, issuerKeyHash): ");
|
|
264
271
|
if (!sct || typeof sct.timestamp !== "bigint" || sct.version !== 0) {
|
|
265
272
|
throw new CtError("ct/bad-input", "reconstructSignedData expects a decoded v1 SCT from parseSctList().scts[]");
|
|
266
273
|
}
|
|
@@ -522,8 +529,10 @@ function _logKeyMaterial(logKey) {
|
|
|
522
529
|
* var sct = await pki.ct.signSct({ entryType: 0, leafCert: der }, signerKeyPkcs8);
|
|
523
530
|
* var ext = pki.ct.encodeSctList([sct]);
|
|
524
531
|
*/
|
|
532
|
+
var _SIGN_SCT_OPTS = intrinsic.assign(intrinsic.create(null), { timestamp: 1, extensions: 1, logId: 1 });
|
|
525
533
|
async function signSct(entry, logKey, opts) {
|
|
526
|
-
opts = opts
|
|
534
|
+
opts = guard.identifier.optionsObject(opts, _ctErr, "ct/bad-input", "pki.ct.signSct options");
|
|
535
|
+
guard.identifier.assertKnownKeys(opts, _SIGN_SCT_OPTS, _ctErr, "ct/bad-input", "unknown pki.ct.signSct option (accepted: timestamp, extensions, logId): ");
|
|
527
536
|
var mat = _logKeyMaterial(logKey);
|
|
528
537
|
var alg = _spkiAlg(mat.spki);
|
|
529
538
|
var hashAlg = 4, sigAlg, imp, sign, ecdsaDer = false, coordLen;
|
package/lib/ocsp.js
CHANGED
|
@@ -84,11 +84,15 @@ function _toDer(input, what) {
|
|
|
84
84
|
}
|
|
85
85
|
function _keyValue(spkiDer) { return ocspVerify.ocspKeyValue(spkiDer); }
|
|
86
86
|
function _nonceExt(nonceBytes) { return b.sequence([b.oid(OID_OCSP_NONCE), b.octetString(b.octetString(nonceBytes))]); }
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
87
|
+
/** @internal RFC 9654 sec. 2.1 bounds a nonce at 1..128 octets, and adds for the requester: "An OCSP
|
|
88
|
+
* requester that implements the extension in this document MUST use a minimum length of 32
|
|
89
|
+
* octets". A responder echoes what it was sent, so its floor stays at the section's 1. */
|
|
90
|
+
function _assertNonce(nonceBytes, floor) {
|
|
91
|
+
if (!Buffer.isBuffer(nonceBytes) || nonceBytes.length < floor || nonceBytes.length > 128) {
|
|
92
|
+
throw _err("ocsp/bad-input", "a nonce must be a Buffer of " + floor + "..128 octets (RFC 9654 sec. 2.1)");
|
|
90
93
|
}
|
|
91
94
|
}
|
|
95
|
+
var REQUESTER_NONCE_FLOOR = 32, RESPONDER_NONCE_FLOOR = 1;
|
|
92
96
|
function _buildCertID(cert, issuer, hashName) {
|
|
93
97
|
var wc = HASH_WC[guard.text.keyOf(hashName)];
|
|
94
98
|
if (!wc) throw _err("ocsp/bad-input", "unsupported CertID hashAlgorithm " + guard.text.showValue(hashName) + " (sha1 / sha256 / sha384 / sha512)");
|
|
@@ -122,9 +126,12 @@ function _buildCertID(cert, issuer, hashName) {
|
|
|
122
126
|
*
|
|
123
127
|
* @opts
|
|
124
128
|
* hashAlgorithm `"sha1"` (default) / `"sha256"` / `"sha384"` / `"sha512"`; the CertID identity hash.
|
|
125
|
-
* nonce `true` for a fresh 32-octet CSPRNG nonce (RFC 9654), or a caller Buffer
|
|
126
|
-
*
|
|
127
|
-
*
|
|
129
|
+
* nonce `true` for a fresh 32-octet CSPRNG nonce (RFC 9654), or a caller Buffer of 32..128
|
|
130
|
+
* octets (RFC 9654 sec. 2.1: a requester MUST use at least 32).
|
|
131
|
+
* requestorName a Name (DER `BufferSource`, or a parsed Name) placed in the [1] requestorName as a
|
|
132
|
+
* directoryName. With `signer`, the signer certificate's subject is taken when none
|
|
133
|
+
* is stated (RFC 6960 sec. 4.1.2: a requestor that signs SHALL specify its name).
|
|
134
|
+
* signer `{ cert, key }` to sign the request.
|
|
128
135
|
* profile `"lightweight"`: one Request, SHA-1 CertID, nonce-only extensions (RFC 5019).
|
|
129
136
|
* pem emit a PEM `OCSP REQUEST` string instead of DER.
|
|
130
137
|
* @example
|
|
@@ -148,6 +155,8 @@ function buildRequest(query, opts) {
|
|
|
148
155
|
var _BUILD_REQUEST_OPTS = Object.assign(Object.create(null), {
|
|
149
156
|
hashAlgorithm: 1, nonce: 1, pem: 1, profile: 1, requestorName: 1, signer: 1
|
|
150
157
|
});
|
|
158
|
+
var _QUERY_KEYS = Object.assign(Object.create(null), { cert: 1, issuer: 1, singleRequestExtensions: 1 });
|
|
159
|
+
var _REQUEST_SIGNER_KEYS = Object.assign(Object.create(null), { cert: 1, key: 1 });
|
|
151
160
|
|
|
152
161
|
function _buildRequest(query, opts) {
|
|
153
162
|
opts = guard.identifier.optionsObject(opts, _err, "ocsp/bad-input", "pki.ocsp.buildRequest options");
|
|
@@ -159,10 +168,27 @@ function _buildRequest(query, opts) {
|
|
|
159
168
|
var queries = Array.isArray(query) ? pkiBuild.reqDenseArray(query, "queries", _err, "ocsp/bad-input") : [query];
|
|
160
169
|
if (!queries.length) throw _err("ocsp/bad-input", "buildRequest needs at least one { cert, issuer } query");
|
|
161
170
|
if (lightweight && queries.length !== 1) throw _err("ocsp/bad-input", "the lightweight profile permits exactly one Request (RFC 5019 sec. 2.1.1)");
|
|
162
|
-
|
|
171
|
+
var signerCertDer = null, signerCert = null;
|
|
172
|
+
if (opts.signer) {
|
|
173
|
+
guard.identifier.assertKnownKeys(opts.signer, _REQUEST_SIGNER_KEYS, _err, "ocsp/bad-input", "unknown request signer field (the signer is { cert, key }): ");
|
|
174
|
+
signerCertDer = _normCertDer(opts.signer.cert, "the request signer certificate");
|
|
175
|
+
signerCert = _certOf(signerCertDer, "the request signer certificate");
|
|
176
|
+
}
|
|
177
|
+
/** @internal Sec. 4.1.2: "If the request is signed, the requestor SHALL specify its name in the
|
|
178
|
+
* requestorName field." The signer certificate names the requestor, so its subject is the name
|
|
179
|
+
* when none is stated. A certificate with an empty subject names its holder in a critical
|
|
180
|
+
* subjectAltName (RFC 5280 sec. 4.1.2.6); an empty Name names nobody, so it is not derived. */
|
|
181
|
+
var requestorNameDer = null;
|
|
182
|
+
if (opts.requestorName != null) requestorNameDer = _nameDer(opts.requestorName);
|
|
183
|
+
else if (signerCert !== null) {
|
|
184
|
+
if (!signerCert.subject.rdns.length) throw _err("ocsp/bad-input", "the request signer certificate has an empty subject, so no requestorName can be taken from it; state requestorName (RFC 6960 sec. 4.1.2)");
|
|
185
|
+
requestorNameDer = signerCert.subject.bytes;
|
|
186
|
+
}
|
|
163
187
|
|
|
164
188
|
return Promise.all(queries.map(function (q) {
|
|
165
|
-
if (!q ||
|
|
189
|
+
if (!q || typeof q !== "object") throw _err("ocsp/bad-input", "each query must be { cert, issuer }");
|
|
190
|
+
guard.identifier.assertKnownKeys(q, _QUERY_KEYS, _err, "ocsp/bad-input", "unknown query field (a query is { cert, issuer, singleRequestExtensions? }): ");
|
|
191
|
+
if (q.cert == null || q.issuer == null) throw _err("ocsp/bad-input", "each query must be { cert, issuer }");
|
|
166
192
|
var cert = _certOf(q.cert, "the query certificate");
|
|
167
193
|
var issuer = _certOf(q.issuer, "the issuer certificate");
|
|
168
194
|
return _buildCertID(cert, issuer, hashName).then(function (certID) {
|
|
@@ -175,22 +201,17 @@ function _buildRequest(query, opts) {
|
|
|
175
201
|
});
|
|
176
202
|
})).then(function (requests) {
|
|
177
203
|
var tbsChildren = [];
|
|
178
|
-
if (
|
|
179
|
-
var nameDer = _nameDer(opts.requestorName);
|
|
180
|
-
tbsChildren.push(b.explicit(1, b.contextConstructed(4, nameDer)));
|
|
181
|
-
}
|
|
204
|
+
if (requestorNameDer !== null) tbsChildren.push(b.explicit(1, b.contextConstructed(4, requestorNameDer)));
|
|
182
205
|
tbsChildren.push(b.sequence(requests));
|
|
183
206
|
var reqExts = [];
|
|
184
207
|
if (opts.nonce) {
|
|
185
208
|
var nonceBytes = opts.nonce === true ? nodeCrypto.randomBytes(32) : opts.nonce;
|
|
186
|
-
_assertNonce(nonceBytes);
|
|
209
|
+
_assertNonce(nonceBytes, REQUESTER_NONCE_FLOOR);
|
|
187
210
|
reqExts.push(_nonceExt(nonceBytes));
|
|
188
211
|
}
|
|
189
212
|
if (reqExts.length) tbsChildren.push(b.explicit(2, b.sequence(reqExts)));
|
|
190
213
|
var tbsRequest = b.sequence(tbsChildren);
|
|
191
|
-
if (
|
|
192
|
-
var signerCertDer = _normCertDer(opts.signer.cert, "the request signer certificate");
|
|
193
|
-
var signerCert = _certOf(signerCertDer, "the request signer certificate");
|
|
214
|
+
if (signerCert === null) return _emitReq(b.sequence([tbsRequest]), opts);
|
|
194
215
|
var scheme = signScheme.resolveSignScheme(signerCert, { combinedRsaSig: true }, true, _signE);
|
|
195
216
|
return signScheme.signOverTbs(scheme, opts.signer.key, tbsRequest, _signE).then(function (sig) {
|
|
196
217
|
var optionalSignature = b.sequence([scheme.sigAlgId, b.bitString(sig, 0), b.explicit(0, b.sequence([b.raw(signerCertDer)]))]);
|
|
@@ -275,13 +296,21 @@ function sign(responseData, responder, opts) {
|
|
|
275
296
|
}
|
|
276
297
|
|
|
277
298
|
var _SIGN_OPTS = Object.assign(Object.create(null), { embedCert: 1, extendedRevoke: 1, nonce: 1, pem: 1 });
|
|
299
|
+
var _RESPONSE_DATA_KEYS = Object.assign(Object.create(null), { responderID: 1, responses: 1, producedAt: 1 });
|
|
300
|
+
var _SINGLE_RESPONSE_KEYS = Object.assign(Object.create(null), { cert: 1, issuer: 1, certID: 1, hashAlgorithm: 1, status: 1, thisUpdate: 1, nextUpdate: 1, singleExtensions: 1 });
|
|
301
|
+
var _RESPONDER_KEYS = Object.assign(Object.create(null), { cert: 1, key: 1 });
|
|
302
|
+
var _STATUS_KEYS = Object.assign(Object.create(null), { revoked: 1, revocationReason: 1 });
|
|
278
303
|
|
|
279
304
|
function _sign(responseData, responder, opts) {
|
|
280
305
|
opts = guard.identifier.optionsObject(opts, _err, "ocsp/bad-input", "pki.ocsp.sign options");
|
|
281
306
|
guard.identifier.assertKnownKeys(opts, _SIGN_OPTS, _err, "ocsp/bad-input",
|
|
282
307
|
"pki.ocsp.sign has an unknown option (the nonce to echo back is `nonce`): ");
|
|
283
308
|
responseData = responseData || {};
|
|
284
|
-
if (
|
|
309
|
+
if (typeof responseData !== "object") throw _err("ocsp/bad-input", "the responseData must be an object { responderID, responses, producedAt? }");
|
|
310
|
+
guard.identifier.assertKnownKeys(responseData, _RESPONSE_DATA_KEYS, _err, "ocsp/bad-input", "unknown responseData field (accepted: responderID, responses, producedAt): ");
|
|
311
|
+
if (!responder || typeof responder !== "object") throw _err("ocsp/bad-input", "a responder must be { cert, key }");
|
|
312
|
+
guard.identifier.assertKnownKeys(responder, _RESPONDER_KEYS, _err, "ocsp/bad-input", "unknown responder field (the responder is { cert, key }; a signing option belongs in the third argument): ");
|
|
313
|
+
if (responder.cert == null || responder.key == null) throw _err("ocsp/bad-input", "a responder must be { cert, key }");
|
|
285
314
|
var respCertDer = _normCertDer(responder.cert, "the responder certificate");
|
|
286
315
|
var respCert = _certOf(respCertDer, "the responder certificate");
|
|
287
316
|
var ownedKeyBytes = [];
|
|
@@ -314,7 +343,7 @@ function _signResponse(responseData, responder, respCert, respCertDer, responder
|
|
|
314
343
|
}
|
|
315
344
|
var rdChildren = [ridNode, b.generalizedTime(_asEncodableDate(responseData.producedAt, "producedAt") || new Date()), b.sequence(srNodes)];
|
|
316
345
|
var respExts = [];
|
|
317
|
-
if (opts.nonce != null) { _assertNonce(opts.nonce); respExts.push(_nonceExt(opts.nonce)); }
|
|
346
|
+
if (opts.nonce != null) { _assertNonce(opts.nonce, RESPONDER_NONCE_FLOOR); respExts.push(_nonceExt(opts.nonce)); }
|
|
318
347
|
if (opts.extendedRevoke || anyNonIssued) respExts.push(b.sequence([b.oid(OID_EXTENDED_REVOKE), b.octetString(b.nullValue())]));
|
|
319
348
|
if (respExts.length) rdChildren.push(b.explicit(1, b.sequence(respExts)));
|
|
320
349
|
var responseDataDer = b.sequence(rdChildren);
|
|
@@ -362,6 +391,9 @@ function _responderID(rid, respCert) {
|
|
|
362
391
|
function _buildSingleResponse(r, opts) {
|
|
363
392
|
r = r || {};
|
|
364
393
|
var certIdP;
|
|
394
|
+
if (typeof r !== "object") return Promise.reject(_err("ocsp/bad-input", "each response entry must be an object"));
|
|
395
|
+
try { guard.identifier.assertKnownKeys(r, _SINGLE_RESPONSE_KEYS, _err, "ocsp/bad-input", "unknown response entry field (accepted: cert, issuer, certID, hashAlgorithm, status, thisUpdate, nextUpdate, singleExtensions): "); }
|
|
396
|
+
catch (e) { return Promise.reject(e); }
|
|
365
397
|
if (r.certID != null) certIdP = Promise.resolve(b.raw(guard.bytes.view(r.certID, OcspError, "ocsp/bad-input", "a response entry's certID")));
|
|
366
398
|
else if (r.cert != null && r.issuer != null) certIdP = _buildCertID(_certOf(r.cert, "a response certificate"), _certOf(r.issuer, "a response issuer"), r.hashAlgorithm || "sha1");
|
|
367
399
|
else return Promise.reject(_err("ocsp/bad-input", "each response entry needs { certID } or { cert, issuer }"));
|
|
@@ -505,6 +537,7 @@ function _certStatusNode(status, opts) {
|
|
|
505
537
|
if (status == null || status === "good") return b.contextPrimitive(0, Buffer.alloc(0));
|
|
506
538
|
if (status === "unknown") return b.contextPrimitive(2, Buffer.alloc(0));
|
|
507
539
|
if (typeof status === "object" && status.revoked != null) {
|
|
540
|
+
guard.identifier.assertKnownKeys(status, _STATUS_KEYS, _err, "ocsp/bad-input", "unknown revoked status field (a revoked status is { revoked, revocationReason? }): ");
|
|
508
541
|
var ri = [b.generalizedTime(_asEncodableDate(status.revoked, "the revocation time"))];
|
|
509
542
|
if (status.revocationReason != null) {
|
|
510
543
|
var code = typeof status.revocationReason === "number" ? status.revocationReason : REASON_CODE[guard.text.keyOf(status.revocationReason)];
|
|
@@ -638,8 +671,8 @@ function _requestFromBytes(request) {
|
|
|
638
671
|
}
|
|
639
672
|
function _reqVerdict(parsed, extra) {
|
|
640
673
|
return guard.verdict.of({
|
|
641
|
-
valid: extra.signed === true && extra.signatureValid === true,
|
|
642
|
-
signed: extra.signed, signatureValid: extra.signatureValid,
|
|
674
|
+
valid: extra.signed === true && extra.signatureValid === true && extra.requestorNamed === true,
|
|
675
|
+
signed: extra.signed, signatureValid: extra.signatureValid, requestorNamed: extra.requestorNamed === true,
|
|
643
676
|
signerCert: extra.signerCert != null ? extra.signerCert : null,
|
|
644
677
|
signerCerts: extra.signerCerts != null ? extra.signerCerts : [],
|
|
645
678
|
certs: extra.certs != null ? extra.certs : [],
|
|
@@ -664,18 +697,44 @@ async function _findRequestSigners(candidates, strict, parsed, sig, sigBits) {
|
|
|
664
697
|
}
|
|
665
698
|
return { matches: matches, parseable: parseable };
|
|
666
699
|
}
|
|
700
|
+
/** @internal RFC 6960 sec. 4.1.2: "If the request is signed, the requestor SHALL specify its name
|
|
701
|
+
* in the requestorName field." The requestor is whoever holds the key that signed, so the name is
|
|
702
|
+
* held to the subject of a certificate that verified the signature, compared as a distinguished
|
|
703
|
+
* name (RFC 5280 sec. 7.1). The parser refuses a signed request that names nobody
|
|
704
|
+
* (ocsp/missing-requestor-name); one naming its requestor by a GeneralName form other than
|
|
705
|
+
* directoryName leaves the check unperformed and never a pass. */
|
|
706
|
+
function _requestorNamed(parsed, matches) {
|
|
707
|
+
var rn = parsed.requestorName;
|
|
708
|
+
if (rn.tagNumber !== 4) {
|
|
709
|
+
return { named: [], reason: "the signed OCSP request names its requestor by a GeneralName form [" + rn.tagNumber + "] this responder does not compare to a certificate subject; a directoryName is compared (RFC 6960 sec. 4.1.2)" };
|
|
710
|
+
}
|
|
711
|
+
if (!rn.value.rdns.length) return { named: [], reason: "the signed OCSP request's requestorName is an empty distinguished name, which names nobody (RFC 6960 sec. 4.1.2)" };
|
|
712
|
+
var named = [];
|
|
713
|
+
for (var i = 0; i < matches.length; i++) {
|
|
714
|
+
if (guard.name.dnEqual(matches[i].subject.rdns, rn.value.rdns, _err, "ocsp/bad-input", "the requestorName")) named.push(matches[i]);
|
|
715
|
+
}
|
|
716
|
+
if (named.length) return { named: named, reason: null };
|
|
717
|
+
return { named: [], reason: "the requestorName " + guard.text.showValue(rn.value.dn) + " is not the subject of a certificate that signed the request (RFC 6960 sec. 4.1.2)" };
|
|
718
|
+
}
|
|
719
|
+
/** @internal Several certificates can carry the signing key (a renewal beside the certificate it
|
|
720
|
+
* replaced), and one of them may carry another subject. The signer the verdict names, and the set
|
|
721
|
+
* the responder builds its trusted path from, are the certificates that both verified the signature
|
|
722
|
+
* AND carry the name the request states; a same-key certificate under another name is not the
|
|
723
|
+
* requestor, whatever order the request embeds them in. */
|
|
667
724
|
function _signerVerdict(parsed, found, failReason) {
|
|
668
725
|
if (!found.matches.length) return _reqVerdict(parsed, { signed: true, signatureValid: false, certs: found.parseable, reason: failReason });
|
|
726
|
+
var bound = _requestorNamed(parsed, found.matches);
|
|
727
|
+
var signers = bound.named.length ? bound.named : found.matches;
|
|
669
728
|
return _reqVerdict(parsed, {
|
|
670
|
-
signed: true, signatureValid: true, signerCert:
|
|
671
|
-
signerCerts:
|
|
672
|
-
signerSubject: { dn:
|
|
729
|
+
signed: true, signatureValid: true, requestorNamed: bound.reason === null, signerCert: signers[0].der,
|
|
730
|
+
signerCerts: signers.map(function (m) { return m.der; }), certs: found.parseable,
|
|
731
|
+
signerSubject: { dn: signers[0].subject.dn, rdns: signers[0].subject.rdns }, reason: bound.reason,
|
|
673
732
|
});
|
|
674
733
|
}
|
|
675
734
|
|
|
676
735
|
/**
|
|
677
736
|
* @primitive pki.ocsp.verifyRequest
|
|
678
|
-
* @signature pki.ocsp.verifyRequest(request, opts?) -> Promise<{ valid, signed, signatureValid, signerCert, signerCerts, certs, signerSubject, requestorName, requestList, requestExtensions, version, reason }>
|
|
737
|
+
* @signature pki.ocsp.verifyRequest(request, opts?) -> Promise<{ valid, signed, signatureValid, requestorNamed, signerCert, signerCerts, certs, signerSubject, requestorName, requestList, requestExtensions, version, reason }>
|
|
679
738
|
* @since 0.6.0
|
|
680
739
|
* @status stable
|
|
681
740
|
* @spec RFC 6960
|
|
@@ -692,18 +751,24 @@ function _signerVerdict(parsed, found, failReason) {
|
|
|
692
751
|
*
|
|
693
752
|
* `signatureValid` means only that a certificate's key made this signature over this request. It
|
|
694
753
|
* says nothing about whether that certificate is trusted: `signerCerts` is every certificate the
|
|
695
|
-
* request carries whose key verified the signature
|
|
696
|
-
*
|
|
697
|
-
*
|
|
698
|
-
*
|
|
754
|
+
* request carries whose key verified the signature AND whose subject is the `requestorName` the
|
|
755
|
+
* request states (RFC 6960 sec. 4.1.1 certs is unordered, and a key may appear under an expired
|
|
756
|
+
* certificate beside its renewal; a same-key certificate under another name is not the requestor),
|
|
757
|
+
* so the responder builds a trusted path to one of them rather than depend on ordering. `signerCert`
|
|
758
|
+
* and the decoded `signerSubject` are the first of those, the common single-signer case; when no
|
|
759
|
+
* verifying certificate carries the name, they fall back to the verifying ones and `valid` is
|
|
760
|
+
* false. `certs` is every parseable certificate the
|
|
699
761
|
* request carried (or opts.certs supplied), including intermediates that do not sign and so are absent
|
|
700
762
|
* from `signerCerts`: the responder passes it as the `opts.candidates` pool to `pki.path.build`, which
|
|
701
763
|
* discovers and validates the ordered path from a `signerCerts` entry (leaf) up to a trust anchor.
|
|
702
764
|
* The responder then confirms that certificate is authorized to sign the request: its `keyUsage`,
|
|
703
765
|
* where present, must assert `digitalSignature` (RFC 5280 sec. 4.2.1.3, since the certificate signed
|
|
704
|
-
* the request).
|
|
705
|
-
*
|
|
706
|
-
*
|
|
766
|
+
* the request). The `requestorName` a signed request carries (RFC 6960 sec. 4.1.2: a requestor that
|
|
767
|
+
* signs SHALL specify its name) is held to the subject of a certificate that verified the signature,
|
|
768
|
+
* compared as a distinguished name (RFC 5280 sec. 7.1): `requestorNamed` is true when it is, `valid`
|
|
769
|
+
* requires it, and a name given as a GeneralName form other than directoryName is not compared and
|
|
770
|
+
* never passes. The decoded `requestorName` (with its `value` for a directoryName), `requestList`,
|
|
771
|
+
* `requestExtensions` and `version` are returned so the CertIDs being asked about need no re-parse.
|
|
707
772
|
*
|
|
708
773
|
* @opts
|
|
709
774
|
* - `certs` An array of certificates (DER `Buffer` / `Uint8Array` or PEM strings) supplying the
|
package/lib/schema-ocsp.js
CHANGED
|
@@ -85,7 +85,9 @@ function certificateBytes() {
|
|
|
85
85
|
return pkix.rawNonEmptySequence(NS, { code: "ocsp/bad-certs", message: "each certs element must be a non-empty Certificate SEQUENCE (RFC 6960 sec. 4.1.1/sec. 4.2.1)" });
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
|
|
88
|
+
/** @internal The requestorName is read with its value decoded, so a responder compares a
|
|
89
|
+
* directoryName to the signer certificate's subject (RFC 6960 sec. 4.1.2) off the parse. */
|
|
90
|
+
var GENERAL_NAME_RAW = pkix.generalName(NS, { code: "ocsp/bad-requestor-name", decodeValue: true });
|
|
89
91
|
|
|
90
92
|
function _rawSignature(field) {
|
|
91
93
|
var sig = field.value;
|
|
@@ -388,7 +390,7 @@ var TBS_REQUEST = schema.seq([
|
|
|
388
390
|
var rn = m.fields.requestorName;
|
|
389
391
|
return {
|
|
390
392
|
version: m.fields.version.value,
|
|
391
|
-
requestorName: rn.present ? { bytes: rn.value.bytes, tagClass: rn.value.tagClass, tagNumber: rn.value.tagNumber } : null,
|
|
393
|
+
requestorName: rn.present ? { bytes: rn.value.bytes, tagClass: rn.value.tagClass, tagNumber: rn.value.tagNumber, value: rn.value.value } : null,
|
|
392
394
|
requestList: m.fields.requestList.value.items.map(function (it) { return it.value.result; }),
|
|
393
395
|
requestExtensions: m.fields.requestExtensions.present ? _validateOcspExtensions(m.fields.requestExtensions.value.result) : null,
|
|
394
396
|
};
|
package/package.json
CHANGED
package/sbom.cdx.json
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
|
|
3
3
|
"bomFormat": "CycloneDX",
|
|
4
4
|
"specVersion": "1.5",
|
|
5
|
-
"serialNumber": "urn:uuid:
|
|
5
|
+
"serialNumber": "urn:uuid:6602edcd-778a-4204-8e53-1bc40ccb396c",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-09-
|
|
8
|
+
"timestamp": "2026-09-12T13:27:30.472Z",
|
|
9
9
|
"lifecycles": [
|
|
10
10
|
{
|
|
11
11
|
"phase": "build"
|
|
@@ -19,14 +19,14 @@
|
|
|
19
19
|
}
|
|
20
20
|
],
|
|
21
21
|
"component": {
|
|
22
|
-
"bom-ref": "@blamejs/pki@0.7.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.7.37",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.7.
|
|
25
|
+
"version": "0.7.37",
|
|
26
26
|
"scope": "required",
|
|
27
27
|
"author": "blamejs contributors",
|
|
28
28
|
"description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
|
|
29
|
-
"purl": "pkg:npm/%40blamejs/pki@0.7.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/pki@0.7.37",
|
|
30
30
|
"properties": [],
|
|
31
31
|
"externalReferences": [
|
|
32
32
|
{
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"components": [],
|
|
55
55
|
"dependencies": [
|
|
56
56
|
{
|
|
57
|
-
"ref": "@blamejs/pki@0.7.
|
|
57
|
+
"ref": "@blamejs/pki@0.7.37",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|