@blamejs/pki 0.8.6 → 0.8.9
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 +143 -76
- package/README.md +4 -2
- package/index.js +11 -0
- package/lib/acme.js +15 -78
- package/lib/asn1-der.js +58 -6
- package/lib/cbor-det.js +11 -1
- package/lib/cmc-build.js +1 -1
- package/lib/cmc-verify.js +3 -3
- package/lib/cmp-session.js +1 -1
- package/lib/cms-sign.js +3 -3
- package/lib/cms-verify.js +5 -5
- package/lib/constants.js +11 -0
- package/lib/est.js +1 -1
- package/lib/framework-error.js +8 -0
- package/lib/guard-async.js +53 -2
- package/lib/guard-encoding.js +105 -1
- package/lib/guard-identifier.js +74 -1
- package/lib/guard-intrinsic.js +2 -0
- package/lib/guard-json.js +1 -6
- package/lib/guard-limits.js +40 -1
- package/lib/guard-list.js +25 -0
- package/lib/guard-name.js +134 -22
- package/lib/guard-text.js +33 -1
- package/lib/http-transport.js +39 -7
- package/lib/identity-match.js +561 -0
- package/lib/ip-utils.js +52 -1
- package/lib/key.js +250 -5
- package/lib/ocsp.js +125 -22
- package/lib/oid.js +1 -1
- package/lib/path-validate.js +199 -61
- package/lib/pkcs11-uri.js +646 -0
- package/lib/pkcs12-build.js +6 -1
- package/lib/revocation-fetch.js +772 -0
- package/lib/schema-all.js +124 -0
- package/lib/schema-attrcert.js +4 -2
- package/lib/schema-crmf.js +4 -2
- package/lib/schema-pkcs1.js +335 -0
- package/lib/schema-pkcs8.js +15 -0
- package/lib/schema-pkix.js +322 -40
- package/lib/schema-sec1.js +244 -0
- package/lib/schema-tsp.js +4 -2
- package/lib/schema-x509.js +4 -2
- package/lib/trust.js +2 -2
- package/lib/tsp-sign.js +1 -1
- package/lib/webauthn.js +4 -4
- package/lib/webcrypto.js +17 -5
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/README.md
CHANGED
|
@@ -242,7 +242,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
242
242
|
| `pki.oid` | Two-way OID ↔ name registry, seeded with RFC 5280 and the NIST PQC arcs — `name`, `byName`, `register`, `toArcs`/`fromArcs`, `toDER`/`fromDER`, and the `isDottedDecimal` string predicate |
|
|
243
243
|
| `pki.webcrypto` | A W3C `SubtleCrypto` engine over `node:crypto` — `sign`/`verify`/`encrypt`/`decrypt`/`deriveBits`/`digest`/`generateKey`/`importKey`/`exportKey` across RSA, ECDSA, ECDH, Ed25519/Ed448, AES, HMAC, HKDF, PBKDF2 and SHA, plus post-quantum ML-DSA-44/65/87, SLH-DSA, and ML-KEM-512/768/1024 key generation with certificate and PKCS#8 import. The RFC 9935 seed / expandedKey / both private-key CHOICE is validated fail-closed, so an OpenSSL-legacy bare seed or an internally inconsistent key is rejected with a typed error. `encapsulateBits` and `decapsulateBits` are the ML-KEM key-establishment pair the CMS `KEMRecipientInfo` arm rides on, with the FIPS 203 §7.3 ciphertext-length check enforced here so a direct caller inherits it. Cross-implementation use is undefined in the specification, so a `CryptoKey` from a different WebCrypto implementation is refused here with a typed fault naming its origin; the `pki.*` verbs adopt such a key instead, whether it came from the platform or from a separately installed copy of this toolkit |
|
|
244
244
|
| `pki.tls` | RFC 8879 certificate compression and the RFC 8446 §4.4.2 Certificate message it carries (RFC 8446 is obsoleted by RFC 9846), which is the handshake's largest payload. `decompressCertificate` decodes a `CompressedCertificate` and returns the algorithm, the declared uncompressed length, the recovered message raw, and its per-entry certificate DER. Decompression carries the two-sided bound §5 requires: capped at the message's own declared length so a bomb is refused mid-stream, then compared to that declaration exactly, which catches the under-length direction a cap alone cannot see. An algorithm outside the RFC 8879 registry, one the runtime cannot decompress, or one the receiver never advertised is refused before any decompressor is handed the bytes; an empty compressed body is a framing violation (`tls/bad-framing`); and trailing bytes, after the message or after the compressed frame, are refused (`tls/trailing-data`), so one chain has exactly one encoding. `compressCertificate` is the inverse and round-trips its own output before returning. `parseCertificateMessage` decodes the RFC 8446 §4.4.2 message on its own, surfacing each entry's certificate DER ready for `pki.schema.x509.parse` alongside its raw extensions; a separate extension negotiates `certificate_type`, so it is declared, never guessed. All three registered algorithms (zlib, brotli, zstd) are implemented, each offered only where the running Node decompresses it safely — one whose decompressor answers a truncated frame with a short result instead of a fault is dropped at startup rather than advertised with a truncation it cannot detect. Structure only: no handshake is spoken and no certificate verified — `decompressCertificate`, `compressCertificate`, `parseCertificateMessage` |
|
|
245
|
-
| `pki.schema` | The schema family. `parse` detects which PKI format a DER or PEM input encodes and routes it to the right parser; `all` enumerates the registered formats; the engine and per-format members are grouped here |
|
|
245
|
+
| `pki.schema` | The schema family. `parse` detects which PKI format a DER or PEM input encodes and routes it to the right parser; `all` enumerates the registered formats; `pem.decodeBundle` reads every object in a multi-object PEM file (a `fullchain.pem`, a `ca-certificates.crt`, a key beside its certificate), carrying each object's label, DER and offset into the text, with explanatory text around the blocks read as text and the file bounded in both the number of objects and the bytes they decode to; `pem.encodeBundle` writes that list back; `pki.schema.pkcs1` reads and writes the RFC 8017 `RSA PRIVATE KEY` and `RSA PUBLIC KEY` encodings, with every component relation the specification states checked; `pki.schema.sec1` reads and writes the RFC 5915 `EC PRIVATE KEY` encoding, holding the scalar to its curve's width and the parameters field to a named curve; the engine and per-format members are grouped here |
|
|
246
246
|
| `pki.schema.x509` | Certificates (RFC 5280) parsed into structured, validated fields. Each extension is surfaced by name with its `extnValue` bytes; the shared extension decoders that read those bytes are what `pki.lint.certificate`, `pki.inspect` and `pki.path.validate` consume, and they cover the RFC 3739 / ETSI EN 319 412-5 qualified-certificate `qcStatements` (EU-qualified declaration, reliance limit, QSCD flag, certificate type, retention, PDS URLs, country of qualification), the Microsoft Active Directory Certificate Services enrollment extensions (certificate template, CA version, previous-CA-certificate hash, application policies), subject information access, subject directory attributes, and the RFC 6960 OCSP no-check responder marker. Unknown statements stay opaque, fail-closed Fail-closed — `parse`, `pemDecode`, `pemEncode` |
|
|
247
247
|
| `pki.schema.c509` | C509 certificates (draft-ietf-cose-cbor-encoded-cert), the compact CBOR profile of X.509, decoded fail-closed under deterministic CBOR. `encode` is the byte-exact inverse: a DER X.509 v3 certificate forward-transforms to a compact type-3 C509 whose reconstruction reproduces the original DER byte for byte, so the original signature still verifies. A `parse` result re-emits its native array in canonical deterministic CBOR, with the registry integer shorthands, the C509 compressions, and the compact draft-20 per-extension value forms: the scalar extensions (keyUsage, basicConstraints, extended key usage, subject key identifier, inhibitAnyPolicy, OCSP No Check, TLS Feature), the general-name-bearing extensions (subjectAltName, issuer alternative name, name constraints, CRL distribution points, freshest CRL, authority and subject information access, and the full authority key identifier) over one shared GeneralNames codec, certificate policies with their CPS-URI and UserNotice qualifiers, policy mappings and policy constraints, subject directory attributes, and the RFC 3779 resource-delegation extensions (IP address blocks and AS identifiers) with their RFC 8360 v2 twins, whose addresses ride either the delta-coded integer form or the byte-string form the specification mandates once an address exceeds eight octets. A value the compact form cannot carry exactly falls back to the byte-string form with its bytes intact; a certificate outside the invertible set throws a typed `C509Error`. Called explicitly, since it is CBOR rather than DER and so is not auto-routed |
|
|
248
248
|
| `pki.schema.crl` | X.509 CRLs (RFC 5280 §5): revoked serials with real-`Date` revocation times, named and partly decoded extensions Fail-closed — `parse`, `pemDecode`, `pemEncode` |
|
|
@@ -265,7 +265,8 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
265
265
|
| `pki.cmc` | Build and interpret CMC messages (RFC 5272, obsoleted by RFC 10002). `build(spec, signer)` assembles a Full PKI Request across all three request arms (PKCS#10, CRMF, other) and carries it either way RFC 5272 §3.2 allows: `{ cert, key }` signs it, while `{ mac: { identifier, secret } }` authenticates it under a shared secret for a client that holds no key yet, using the PasswordRecipientInfo that section requires and deriving the key from the identifier followed by the secret. A key that cannot sign for itself proves possession another way: `spec.popChallenge` answers the authority's encrypted challenge (RFC 5272 §6.7), decrypting the proof value, confirming it hashes to the witness the challenge carries, and returning the MAC the authority asked for, with `cmc/pop-failed` when the value is not the one issued. A signed request goes through `pki.cms.sign` under `id-cct-PKIData`. A PKCS#10 (`tcr`) request is verified against its own proof-of-possession before signing, so a request whose self-signature does not verify under its subject public key is refused rather than signed into a message a CA would reject. Body-part identifiers are unique across the whole message and never the reserved 0; a caller's clash is refused rather than renumbered, since a control may already reference it. An Identity Proof V2 witness is computed over the `reqSequence` bytes exactly as emitted (§6.2.1 step 1) rather than a re-serialization, a POP Link Witness is emitted only alongside the POP Link Random control §6.3.1.1 requires beside it, and a renewal carries neither Identification nor Identity Proof in either version. `verify(response, sent)` takes what the CA returned plus the state the client retained and reduces it to one terminal outcome: `issued`, `pending`, `confirm-required`, `pop-required`, or `rejected`. It binds the exchange first — Transaction Identifier, the Sender and Recipient Nonce echo compared in constant time and by full value so a truncation cannot match, and the Data Return echo — with each check applying only if the client sent that half, and, once sent, an absent or differing echo being a refusal, which is the replay defense. `bodyPartIDs` extends the same rule to what the response is about: a status reporting on a body part the request never sent is refused, which the transaction and nonce cannot catch, because a server can echo both correctly while answering about a different message. Several status controls are permitted and the worst governs, so a failure cannot hide behind an earlier success; the absence of any status control is success, per §6.1.2. The carrier's signature must verify (§3.2.1.3.4): a conforming SignedData carries its own signer certificate, so the ordinary build-then-verify flow needs nothing extra and the verdict reports `signatureVerified: true`. Where the signer is found nowhere the posture is fail-closed with a named opt-out — supply `certs` with the responder's certificate, or `allowUnverified: true`, in which case the verdict reports `signatureVerified: false`. Doing neither is refused, the opt-out never excuses a signature that is present and wrong, and a carrier with no signer at all is refused outright. The response's own `cmsSequence` and `otherMsgs` come back raw, since a request whose only arm was the other-message form has no certificate to return and §4.1 puts its answer there. Nothing is trusted: issued certificates are read from the CMS certificate bag (§4.2) and surfaced raw for `pki.path.validate`, and a Publish Trust Anchors control is surfaced with `trusted: false` rather than added to a store — `build`, `verify` |
|
|
266
266
|
| `pki.schema.cmc` | Decode CMC messages (RFC 5272 as updated by RFC 6402, the pair obsoleted by RFC 10002 / 10003 / 10004): a Full PKI Request (`PKIData`) or Full PKI Response (`PKIResponse`) riding inside a CMS SignedData, reached by the encapsulated content type (`id-cct-PKIData` / `id-cct-PKIResponse`). Controls are surfaced in wire order with their values raw, so an unrecognized one is data rather than a fault. Tagged requests decode across all three arms. The status verdicts (`CMCStatusInfo` v1 and `CMCStatusInfoV2`) are collected as an ordered list, and the RFC 6402 two-module `OtherStatusInfo` ambiguity — `pendInfo` and `extendedFailInfo` are both untagged SEQUENCEs in the 1988 module, told apart only by their first element — is resolved by inspection and refused when it cannot be told apart. Body-part identity is unique across the whole message rather than per sequence, 0 is reserved as the reference to the enclosing PKIData, and the `reqSequence` bytes are surfaced exactly as they appeared so an Identity Proof witness is computed over the wire bytes. A companion decoder for CMS content rather than an auto-routed format — `parse`, `parsePkiData`, `parsePkiResponse` |
|
|
267
267
|
| `pki.schema.engine` | The declarative ASN.1 structure-schema engine every format parser composes — `walk`, `encode`, `embeddedDer`, and the schema combinators |
|
|
268
|
-
| `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` |
|
|
268
|
+
| `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. `fetchingChecker(opts)` is the checker that goes and gets what it needs: it reads the cRLDistributionPoints and id-ad-ocsp locations out of the certificate and asks for them over `opts.transport`, OCSP first and a CRL after (RFC 5019 §3.1). It is off unless an operator builds it and passes it, so the default validation touches no network, and it runs during `validate` and not during `build`, because §3.2 has a status check requested only after the chain signatures are validated. A distribution point is fetched only as a `fullName` carrying a URI whose scheme this client speaks; ldap, ftp, a `nameRelativeToCRLIssuer` and a point naming a cRLIssuer and no location are counted as skips, so a certificate naming nothing fetchable reads as that rather than as a failed fetch. Nothing is trusted by having been fetched: a CRL goes to `crlChecker` and a response to `verifyOcspResponse`, and the structure a body parses as is decided by which extension named the URL, so a Content-Type mismatch is reported and never selects a parser. Every fault is an undetermined status carrying its reason and `check` throws nothing, which is what leaves `softFail` able to waive one. Plaintext `http` is accepted by default, these being signed objects the toolkit verifies, with `allowPlaintextHttp: false` to narrow it; the SSRF guards hold either way (no private, loopback or link-local destination, no redirect following, a response-size cap, a per-certificate URL cap, a total fetch count, and a wall-clock deadline across the validation). A verified response is cached in process on its CertID and responder URL and a CRL on its request URL and issuer name, with reuse decided from the signed thisUpdate and nextUpdate alone. Pure and re-entrant — `validate`, `build`, `crlChecker`, `ocspChecker`, `fetchingChecker` |
|
|
269
|
+
| `pki.identity` | Service identity (RFC 9525, which obsoletes RFC 6125). `match(cert, references, opts)` says whether a certificate presents a name the client was trying to reach, which is a separate answer from whether it chains: §1.2 has an application need both, and `pki.path.validate` takes `opts.identity` to run them together and report each. A reference identity is a domain name (DNS-ID), a textual IP address or a 4- or 16-octet `BufferSource` (IP-ID), `{ type: "srv", service: "_imap", value: "example.com" }` (SRV-ID, RFC 4985), or `{ type: "uri", scheme: "https", value: "www.example.com" }` (URI-ID). A record carries its service type and its domain together, so no comparison can pair the service of one reference with the domain of another (§6.5). The subject `commonName` is never read, under any option or fallback, including when the certificate carries no subjectAltName at all (§2). Names are compared label by label under an ASCII-only fold with one trailing dot normalized on both sides; an A-label is compared as the ASCII it is and never decoded, so a reference carrying a character outside ASCII is refused rather than guessed at, this toolkit shipping no IDNA implementation. An IP-ID is compared octet for octet against an `iPAddress` entry, never against a `dNSName` holding the same address as text, and no prefix or mask applies (§6.2, §6.4). Wildcards are on and `opts.wildcards: false` turns them off, which §3 requires stating either way: one wildcard, the whole of the left-most label, reaching exactly one reference label, and a presented name failing those rules is ignored with the search continuing rather than refusing the certificate (§6.3). A wildcard spanning an administrative boundary such as `*.co.uk` is out of scope as it is in §7.1, since no public-suffix list ships here. The verdict names which reference matched, so a caller can use it as the validated identity (§6.6), and lists every entry that was skipped with the reason — `match` |
|
|
269
270
|
| `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. `parseDn(dn)` reads a distinguished-name string into `{ rdns, dn, bytes }`, the inverse of the `dn` every parsed name carries, with `bytes` being the raw Name DER `spec.subject` and `spec.issuer` take. 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`, `parseDn` |
|
|
270
271
|
| `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` |
|
|
271
272
|
| `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` |
|
|
@@ -274,6 +275,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
274
275
|
| `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` |
|
|
275
276
|
| `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
|
|
276
277
|
| `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579, the latter obsoleted by RFC 9879). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, a key paired with a certificate (the `{ key, cert }` form, or bags sharing a `localKeyId`) must be the private half of that certificate's public key, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
|
|
278
|
+
| `pki.pkcs11` | PKCS #11 URIs (RFC 7512), the syntax an operator names a token and an object on it with instead of a file path. `parseUri(uri)` reads one into `{ path, vendorPath, query, vendorQuery }`, each a prototype-less record: the path carries `token`, `manufacturer`, `serial`, `model`, the three `library-*` and three `slot-*` attributes, `object`, `type` and `id`, and the query carries `pin-source`, `pin-value`, `module-name` and `module-path`, with a vendor attribute in either component kept under its own name. A vendor query attribute carries a list of its values, which §2.4 permits to repeat; a vendor path attribute carries one value. `id` is a `Buffer`, since the attribute names bytes rather than text, and `slot-id` and `library-version` are numbers. `formatUri(record)` writes the record back, percent-encoding each value to what its own component admits unencoded and encoding `id` whole with uppercase hexadecimal, so two URIs naming one identifier compare equal. Parsing follows the §2.3 / §2.4 ABNF rather than a general URI reader and is fail-closed: a character the component admits only percent-encoded, a truncated or non-hexadecimal escape, a value that is not valid UTF-8, an attribute repeated where the RFC admits it once, a `type` outside the five the RFC enumerates, a URI carrying both `pin-source` and `pin-value`, and a relative `module-path` are each refused with their own `pkcs11/*` code. Syntax only: nothing here loads a PKCS #11 module or talks to a token — `parseUri`, `formatUri` |
|
|
277
279
|
| `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 the PWRI-KEK of RFC 3211, carried forward by RFC 3370), 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` |
|
|
278
280
|
| `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 8550 §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. `sign` refuses a signer certificate a conforming reader would reject: a `keyUsage` extension without `digitalSignature` or `nonRepudiation` (RFC 8550 §4.4.2), or an `extendedKeyUsage` extension without `emailProtection` or `anyExtendedKeyUsage` (§4.4.4); a certificate carrying neither extension signs. 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` |
|
|
279
281
|
| `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` |
|
package/index.js
CHANGED
|
@@ -35,6 +35,7 @@ var oid = require("./lib/oid");
|
|
|
35
35
|
var webcrypto = require("./lib/webcrypto");
|
|
36
36
|
var schema = require("./lib/schema-all");
|
|
37
37
|
var path = require("./lib/path-validate");
|
|
38
|
+
var identity = require("./lib/identity-match");
|
|
38
39
|
var ct = require("./lib/ct");
|
|
39
40
|
var tls = require("./lib/tls-cert-compress");
|
|
40
41
|
var cms = require("./lib/cms-verify");
|
|
@@ -50,6 +51,7 @@ var cmp = require("./lib/cmp-session");
|
|
|
50
51
|
var crl = require("./lib/crl-sign");
|
|
51
52
|
var key = require("./lib/key");
|
|
52
53
|
var pkcs12 = require("./lib/pkcs12-build");
|
|
54
|
+
var pkcs11 = require("./lib/pkcs11-uri");
|
|
53
55
|
var merkle = require("./lib/merkle");
|
|
54
56
|
var shbs = require("./lib/shbs");
|
|
55
57
|
var hpke = require("./lib/hpke");
|
|
@@ -86,6 +88,10 @@ module.exports = {
|
|
|
86
88
|
// `path` is RFC 5280 sec. 6 certification-path validation -- pki.path.validate
|
|
87
89
|
// runs the sec. 6.1 state machine over an already-parsed path + a trust anchor.
|
|
88
90
|
path: path,
|
|
91
|
+
// `identity` is RFC 9525 service identity -- pki.identity.match says whether a certificate
|
|
92
|
+
// presents a name the client was trying to reach. A separate answer from path validation,
|
|
93
|
+
// which pki.path.validate gives; sec. 1.2 has an application need both.
|
|
94
|
+
identity: { match: identity.match },
|
|
89
95
|
// `ct` is RFC 6962 Certificate Transparency -- pki.ct.parseSctList decodes the
|
|
90
96
|
// SCT-list extension a certificate / OCSP response carries; the signature is
|
|
91
97
|
// surfaced raw for external verification (pki.ct.reconstructSignedData).
|
|
@@ -148,6 +154,11 @@ module.exports = {
|
|
|
148
154
|
// under PBES2, a classic HMAC or PBMAC1 MAC), and pki.pkcs12.verifyMac checks a store's MAC. Parsing lives
|
|
149
155
|
// at pki.schema.pkcs12.parse.
|
|
150
156
|
pkcs12: pkcs12,
|
|
157
|
+
// `pkcs11` is the RFC 7512 PKCS #11 URI syntax -- pki.pkcs11.parseUri reads a URI naming a token,
|
|
158
|
+
// a slot, a library and an object on a PKCS #11 device into a prototype-less record, and
|
|
159
|
+
// pki.pkcs11.formatUri writes one back. Syntax only: nothing here loads a module or talks to a
|
|
160
|
+
// token, and `id` is carried as bytes rather than text so two spellings of one identifier compare.
|
|
161
|
+
pkcs11: pkcs11,
|
|
151
162
|
// `merkle` is the RFC 6962 / RFC 9162 Merkle-tree proof-verification core --
|
|
152
163
|
// pki.merkle.leafHash / nodeHash / emptyRootHash build the domain-separated
|
|
153
164
|
// (0x00 leaf / 0x01 node) SHA-256 tree hashes; pki.merkle.verifyInclusion and
|
package/lib/acme.js
CHANGED
|
@@ -47,6 +47,7 @@ var wcEngine = require("./webcrypto");
|
|
|
47
47
|
var webcrypto = wcEngine.webcrypto;
|
|
48
48
|
var subtle = webcrypto.subtle;
|
|
49
49
|
var frameworkError = require("./framework-error");
|
|
50
|
+
var ipUtils = require("./ip-utils");
|
|
50
51
|
var httpTransport = require("./http-transport");
|
|
51
52
|
var retryAfter = require("./http-retry-after");
|
|
52
53
|
var guard = require("./guard-all");
|
|
@@ -76,12 +77,6 @@ var pkgVersion = require("../package.json").version;
|
|
|
76
77
|
|
|
77
78
|
var _TOKEN_TABLE = pkix.charTable("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-");
|
|
78
79
|
var _LINK_TOKEN_TABLE = pkix.charTable("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+.^_`|~-");
|
|
79
|
-
function _isHex1to4(s) {
|
|
80
|
-
var n = s.length;
|
|
81
|
-
if (n < 1 || n > 4) return false;
|
|
82
|
-
for (var i = 0; i < n; i++) { var c = _charCodeAt(s, i); if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 102))) return false; }
|
|
83
|
-
return true;
|
|
84
|
-
}
|
|
85
80
|
function _looksLikeIpv4(s) {
|
|
86
81
|
var n = s.length, i = 0, octet, d;
|
|
87
82
|
for (octet = 0; octet < 4; octet++) {
|
|
@@ -147,20 +142,7 @@ function _isLdhLabel(l) {
|
|
|
147
142
|
for (var i = 1; i < n - 1; i++) { var c = _charCodeAt(l, i); if (!(_isAlnumLower(c) || c === 0x2d)) return false; }
|
|
148
143
|
return true;
|
|
149
144
|
}
|
|
150
|
-
|
|
151
|
-
var n = l.length;
|
|
152
|
-
if (!(n >= 4 && _charCodeAt(l, 0) === 0x78 && _charCodeAt(l, 1) === 0x6e && _charCodeAt(l, 2) === 0x2d && _charCodeAt(l, 3) === 0x2d)) return false;
|
|
153
|
-
var i = 4, g = 0;
|
|
154
|
-
while (i < n && _isAlnumLower(_charCodeAt(l, i))) { i++; g++; }
|
|
155
|
-
if (g < 1) return false;
|
|
156
|
-
while (i < n) {
|
|
157
|
-
if (_charCodeAt(l, i) !== 0x2d) return false;
|
|
158
|
-
i++; var g2 = 0;
|
|
159
|
-
while (i < n && _isAlnumLower(_charCodeAt(l, i))) { i++; g2++; }
|
|
160
|
-
if (g2 < 1) return false;
|
|
161
|
-
}
|
|
162
|
-
return true;
|
|
163
|
-
}
|
|
145
|
+
var _isXnLabel = guard.name.isXnLabel;
|
|
164
146
|
function _isCanonicalOctet(s) {
|
|
165
147
|
var n = s.length;
|
|
166
148
|
if (n === 0 || n > 3) return false;
|
|
@@ -375,38 +357,7 @@ function _assertIpAddress(value) {
|
|
|
375
357
|
throw E("acme/bad-identifier", "an ip identifier value must be an IPv4 or IPv6 textual address (RFC 8738 sec. 3)");
|
|
376
358
|
}
|
|
377
359
|
|
|
378
|
-
|
|
379
|
-
var groups;
|
|
380
|
-
if (value.indexOf("::") !== -1) {
|
|
381
|
-
if (value.indexOf("::") !== value.lastIndexOf("::")) return null;
|
|
382
|
-
var halves = _split(value, "::");
|
|
383
|
-
var left = halves[0] ? _split(halves[0], ":") : [];
|
|
384
|
-
var right = halves[1] ? _split(halves[1], ":") : [];
|
|
385
|
-
var fill = 8 - left.length - right.length;
|
|
386
|
-
if (fill < 1) return null;
|
|
387
|
-
var zeros = [];
|
|
388
|
-
for (var z = 0; z < fill; z++) _push(zeros, "0");
|
|
389
|
-
groups = _concat(_concat(left, zeros), right);
|
|
390
|
-
} else {
|
|
391
|
-
groups = _split(value, ":");
|
|
392
|
-
}
|
|
393
|
-
if (groups.length !== 8) return null;
|
|
394
|
-
var nums = [];
|
|
395
|
-
for (var i = 0; i < 8; i++) {
|
|
396
|
-
if (!_isHex1to4(groups[i])) return null;
|
|
397
|
-
_push(nums, _parseIntI(groups[i], 16));
|
|
398
|
-
}
|
|
399
|
-
var hex = _mapI(nums, function (n) { return _numToString(n, 16); });
|
|
400
|
-
var bestStart = -1, bestLen = 0, curStart = -1, curLen = 0;
|
|
401
|
-
for (var g = 0; g < 8; g++) {
|
|
402
|
-
if (nums[g] === 0) { if (curStart === -1) curStart = g; curLen++; if (curLen > bestLen) { bestLen = curLen; bestStart = curStart; } }
|
|
403
|
-
else { curStart = -1; curLen = 0; }
|
|
404
|
-
}
|
|
405
|
-
if (bestLen < 2) return _join(hex, ":");
|
|
406
|
-
var head = _join(intrinsic.arraySlice(hex, 0, bestStart), ":");
|
|
407
|
-
var tail = _join(intrinsic.arraySlice(hex, bestStart + bestLen), ":");
|
|
408
|
-
return head + "::" + tail;
|
|
409
|
-
}
|
|
360
|
+
var _canonicalizeIpv6 = ipUtils.canonicalizeIpv6;
|
|
410
361
|
|
|
411
362
|
|
|
412
363
|
var TRANSITIONS = intrinsic.assign(intrinsic.create(null), {
|
|
@@ -954,14 +905,7 @@ function _subjectCommonNames(subject) {
|
|
|
954
905
|
}
|
|
955
906
|
|
|
956
907
|
function _ipBytesToText(buf) {
|
|
957
|
-
|
|
958
|
-
if (buf.length === 4) return buf[0] + "." + buf[1] + "." + buf[2] + "." + buf[3];
|
|
959
|
-
if (buf.length === 16) {
|
|
960
|
-
var groups = [];
|
|
961
|
-
for (var i = 0; i < 16; i += 2) _push(groups, _numToString((buf[i] << 8) | buf[i + 1], 16));
|
|
962
|
-
return _canonicalizeIpv6(_join(groups, ":"));
|
|
963
|
-
}
|
|
964
|
-
return null;
|
|
908
|
+
return _isBuffer(buf) ? ipUtils.textFromOctets(buf) : null;
|
|
965
909
|
}
|
|
966
910
|
|
|
967
911
|
function _csrIdentifierSet(parsedCsr) {
|
|
@@ -1414,25 +1358,18 @@ function _clientTls(o) {
|
|
|
1414
1358
|
var t = o.tls || {};
|
|
1415
1359
|
return { anchors: t.anchors, useSystemStore: t.useSystemStore, cert: t.cert, key: t.key, minVersion: t.minVersion, servername: t.servername, checkServerIdentity: t.checkServerIdentity };
|
|
1416
1360
|
}
|
|
1417
|
-
var PEM_CERT_BEGIN = "-----BEGIN CERTIFICATE-----";
|
|
1418
|
-
var PEM_CERT_END = "-----END CERTIFICATE-----";
|
|
1419
1361
|
function _splitPemChain(text) {
|
|
1420
|
-
var
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
try {
|
|
1428
|
-
catch (
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
from = blockEnd;
|
|
1432
|
-
}
|
|
1433
|
-
if (text.slice(lastEnd).trim() !== "") throw E("acme/bad-certificate-chain", "the certificate chain contained trailing non-whitespace text outside a PEM block (RFC 8555 sec. 7.4.2)");
|
|
1434
|
-
if (!out.length) throw E("acme/bad-certificate-chain", "the certificate download carried no PEM certificate (RFC 8555 sec. 7.4.2)");
|
|
1435
|
-
return out;
|
|
1362
|
+
var ders;
|
|
1363
|
+
try { ders = pkix.pemDecodeAll(text, "CERTIFICATE", frameworkError.PemError); }
|
|
1364
|
+
catch (e) {
|
|
1365
|
+
throw E("acme/bad-certificate-chain",
|
|
1366
|
+
"the certificate download is not a chain of PEM CERTIFICATE blocks (RFC 8555 sec. 7.4.2): " + e.message, e);
|
|
1367
|
+
}
|
|
1368
|
+
for (var i = 0; i < ders.length; i++) {
|
|
1369
|
+
try { x509.parse(ders[i]); }
|
|
1370
|
+
catch (e2) { throw E("acme/bad-certificate-chain", "a downloaded certificate did not decode as a valid X.509 certificate (RFC 8555 sec. 7.4.2)", e2); }
|
|
1371
|
+
}
|
|
1372
|
+
return ders;
|
|
1436
1373
|
}
|
|
1437
1374
|
|
|
1438
1375
|
var LINK_HEADER_MAX_BYTES = constants.BYTES.kib(8);
|
package/lib/asn1-der.js
CHANGED
|
@@ -750,7 +750,7 @@ function encodeIdentifier(classBits, constructed, tagNumber) {
|
|
|
750
750
|
* pki.asn1.encode(0x00, false, pki.asn1.TAGS.NULL, Buffer.alloc(0));
|
|
751
751
|
*/
|
|
752
752
|
function encodeTLV(classBits, constructed, tagNumber, content) {
|
|
753
|
-
var body =
|
|
753
|
+
var body = _contentBytes(content);
|
|
754
754
|
var id = encodeIdentifier(classBits, constructed, tagNumber);
|
|
755
755
|
return Buffer.concat([id, encodeLength(body.length), body]);
|
|
756
756
|
}
|
|
@@ -759,6 +759,53 @@ function _universal(tagNumber, constructed, content) {
|
|
|
759
759
|
return encodeTLV(CLASS_UNIVERSAL, constructed, tagNumber, content);
|
|
760
760
|
}
|
|
761
761
|
|
|
762
|
+
/** @internal Content is bytes. A value that is not bytes reaches the structure as whatever the
|
|
763
|
+
* byte conversion makes of it: a string as its UTF-8 encoding, an object through its `valueOf`,
|
|
764
|
+
* an array element past 255 as that element modulo 256. A byte source and a list of byte values
|
|
765
|
+
* are the two spellings this takes; an omitted content is the empty one. */
|
|
766
|
+
function _contentBytes(content) {
|
|
767
|
+
if (content == null) return intrinsic.bufferAlloc(0);
|
|
768
|
+
if (guard.bytes.isByteSource(content)) {
|
|
769
|
+
return guard.bytes.source(content, Asn1Error, "asn1/not-buffer", "encodeTLV content");
|
|
770
|
+
}
|
|
771
|
+
if (!intrinsic.isArray(content)) {
|
|
772
|
+
throw new Asn1Error("asn1/not-buffer", "encodeTLV content: the content must be bytes, got " + _typeOf(content));
|
|
773
|
+
}
|
|
774
|
+
/** @internal Each element is read ONCE, into the byte the check and the content both use. Read
|
|
775
|
+
* again to copy, an element answering from a getter could pass the check as 2 and be written
|
|
776
|
+
* as 300, which the copy would narrow to 44. */
|
|
777
|
+
var n = content.length;
|
|
778
|
+
var out = intrinsic.bufferAlloc(n);
|
|
779
|
+
for (var i = 0; i < n; i++) {
|
|
780
|
+
var b = content[i];
|
|
781
|
+
if (typeof b !== "number" || !intrinsic.isSafeInteger(b) || b < 0 || b > 255) {
|
|
782
|
+
throw new Asn1Error("asn1/not-buffer", "encodeTLV content: element " + i + " is not a byte value 0 to 255");
|
|
783
|
+
}
|
|
784
|
+
out[i] = b;
|
|
785
|
+
}
|
|
786
|
+
return out;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** @internal A string builder encodes the caller's text. Turning something else into text encodes
|
|
790
|
+
* a value the caller never named: an object arrives as its default string form, a list as its
|
|
791
|
+
* members joined with a comma, and the structure carries that. The value is required to be a
|
|
792
|
+
* string rather than made into one, which also settles what a value with a `toString` answers,
|
|
793
|
+
* since a string cannot answer differently between a check and the encoding. */
|
|
794
|
+
function _asString(s, who) {
|
|
795
|
+
if (typeof s !== "string") {
|
|
796
|
+
throw new Asn1Error("asn1/bad-string", who + ": the value must be a string, got " + _typeOf(s));
|
|
797
|
+
}
|
|
798
|
+
return s;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function _typeOf(v) {
|
|
802
|
+
if (v === null) return "null";
|
|
803
|
+
if (intrinsic.isBuffer(v)) return "a Buffer";
|
|
804
|
+
if (intrinsic.isArray(v)) return "an array";
|
|
805
|
+
var t = typeof v;
|
|
806
|
+
return (t === "object" || t === "undefined" ? "an " : "a ") + t;
|
|
807
|
+
}
|
|
808
|
+
|
|
762
809
|
function intToDer(v) {
|
|
763
810
|
if (typeof v === "number") {
|
|
764
811
|
if (!Number.isSafeInteger(v)) throw new Asn1Error("asn1/bad-integer", "unsafe integer; pass a BigInt");
|
|
@@ -911,21 +958,21 @@ var build = intrinsic.assign(intrinsic.create(null), {
|
|
|
911
958
|
for (i = 0; i < positions.length; i++) { p = positions[i]; buf[p >> 3] |= 0x80 >> (p & 7); }
|
|
912
959
|
return build.bitString(buf, 7 - (hi & 7));
|
|
913
960
|
},
|
|
914
|
-
utf8: function (s) { var v =
|
|
961
|
+
utf8: function (s) { var v = _asString(s, "build.utf8"); _assertWellFormedUtf16(v); return _universal(TAGS.UTF8_STRING, false, Buffer.from(v, "utf8")); },
|
|
915
962
|
ia5: function (s) {
|
|
916
|
-
s =
|
|
963
|
+
s = _asString(s, "build.ia5");
|
|
917
964
|
for (var i = 0; i < s.length; i++) {
|
|
918
965
|
if (_charCodeAt(s, i) > 0x7F) throw new Asn1Error("asn1/bad-ia5-string", "IA5String requires 7-bit ASCII");
|
|
919
966
|
}
|
|
920
967
|
return _universal(TAGS.IA5_STRING, false, Buffer.from(s, "latin1"));
|
|
921
968
|
},
|
|
922
969
|
printable: function (s) {
|
|
923
|
-
s =
|
|
970
|
+
s = _asString(s, "build.printable");
|
|
924
971
|
if (!isPrintableString(s)) throw new Asn1Error("asn1/bad-printable-string", "value has characters outside the PrintableString set");
|
|
925
972
|
return _universal(TAGS.PRINTABLE_STRING, false, Buffer.from(s, "latin1"));
|
|
926
973
|
},
|
|
927
974
|
bmpString: function (s) {
|
|
928
|
-
s =
|
|
975
|
+
s = _asString(s, "build.bmpString");
|
|
929
976
|
var out = Buffer.alloc(s.length * 2);
|
|
930
977
|
for (var i = 0; i < s.length; i++) {
|
|
931
978
|
var u = _charCodeAt(s, i);
|
|
@@ -977,9 +1024,14 @@ function _intContent(v, who) {
|
|
|
977
1024
|
return content;
|
|
978
1025
|
}
|
|
979
1026
|
|
|
1027
|
+
/** @internal Walked by index rather than through the array's own `map`, which a caller can define
|
|
1028
|
+
* to answer with children this never checked. Each element is read once, into the buffer the
|
|
1029
|
+
* check and the encoding both use. */
|
|
980
1030
|
function _asBufferArray(arr, who) {
|
|
981
1031
|
if (!_isArray(arr)) throw new Asn1Error("asn1/bad-children", who + ": expected an array of TLV buffers");
|
|
982
|
-
|
|
1032
|
+
var n = arr.length, out = [];
|
|
1033
|
+
for (var i = 0; i < n; i++) out[i] = _asBuffer(arr[i], who);
|
|
1034
|
+
return out;
|
|
983
1035
|
}
|
|
984
1036
|
|
|
985
1037
|
module.exports = {
|
package/lib/cbor-det.js
CHANGED
|
@@ -627,6 +627,16 @@ function _capString(out, who) {
|
|
|
627
627
|
if (out.length > constants.LIMITS.CBOR_MAX_BYTES) throw new CborError("cbor/too-large", who + ": encoded " + out.length + " bytes exceeds cap " + constants.LIMITS.CBOR_MAX_BYTES);
|
|
628
628
|
return out;
|
|
629
629
|
}
|
|
630
|
+
/** @internal A text builder encodes the caller's text. Turning something else into text encodes a
|
|
631
|
+
* value the caller never named: an object arrives as its default string form and a list as its
|
|
632
|
+
* members joined with a comma. */
|
|
633
|
+
function _asText(s, who) {
|
|
634
|
+
if (typeof s !== "string") {
|
|
635
|
+
throw new CborError("cbor/bad-argument", who + ": the value must be a string, got " + (s === null ? "null" : "a " + typeof s));
|
|
636
|
+
}
|
|
637
|
+
return s;
|
|
638
|
+
}
|
|
639
|
+
|
|
630
640
|
function _assertWellFormedText(str, who) {
|
|
631
641
|
for (var i = 0; i < str.length; i++) {
|
|
632
642
|
var c = str.charCodeAt(i);
|
|
@@ -650,7 +660,7 @@ var build = Object.assign(Object.create(null), {
|
|
|
650
660
|
nint: function (n) { var a = typeof n === "bigint" ? n : BigInt(n); if (a >= 0n) throw new CborError("cbor/bad-argument", "build.nint: value must be negative"); return _head(1, -1n - a, "build.nint"); },
|
|
651
661
|
int: function (n) { var a = typeof n === "bigint" ? n : BigInt(n); return a >= 0n ? _head(0, a, "build.int") : _head(1, -1n - a, "build.int"); },
|
|
652
662
|
byteString: function (buf) { var b = _asBuffer(buf, "build.byteString"); return _capString(Buffer.concat([_head(2, b.length, "build.byteString"), b]), "build.byteString"); },
|
|
653
|
-
textString: function (s) { var str =
|
|
663
|
+
textString: function (s) { var str = _asText(s, "build.textString"); _assertWellFormedText(str, "build.textString"); var b = Buffer.from(str, "utf8"); return _capString(Buffer.concat([_head(3, b.length, "build.textString"), b]), "build.textString"); },
|
|
654
664
|
array: function (items) {
|
|
655
665
|
if (!Array.isArray(items)) throw new CborError("cbor/bad-argument", "build.array: expected an array of pre-encoded items");
|
|
656
666
|
var parts = items.map(function (x, i) { return _cbItem(x, "build.array[" + i + "]"); });
|
package/lib/cmc-build.js
CHANGED
|
@@ -1009,7 +1009,7 @@ function _copySigners(signer, owned) {
|
|
|
1009
1009
|
if (isSecret && owned) owned.push(buf);
|
|
1010
1010
|
return buf;
|
|
1011
1011
|
}
|
|
1012
|
-
return Array.isArray(signer) ?
|
|
1012
|
+
return Array.isArray(signer) ? guard.list.copyMap(signer, one) : one(signer);
|
|
1013
1013
|
}
|
|
1014
1014
|
|
|
1015
1015
|
|
package/lib/cmc-verify.js
CHANGED
|
@@ -343,9 +343,9 @@ function _snapshotSent(sent) {
|
|
|
343
343
|
}
|
|
344
344
|
out.senderNonce = _copyAnyBytes(out.senderNonce);
|
|
345
345
|
out.dataReturn = _copyAnyBytes(out.dataReturn);
|
|
346
|
-
if (Array.isArray(out.bodyPartIDs)) out.bodyPartIDs = out.bodyPartIDs
|
|
346
|
+
if (Array.isArray(out.bodyPartIDs)) out.bodyPartIDs = guard.list.snapshot(out.bodyPartIDs);
|
|
347
347
|
if (Array.isArray(out.bodyPartPaths)) {
|
|
348
|
-
out.bodyPartPaths = out.bodyPartPaths
|
|
348
|
+
out.bodyPartPaths = guard.list.copyMap(out.bodyPartPaths, function (p) { return Array.isArray(p) ? guard.list.snapshot(p) : p; });
|
|
349
349
|
}
|
|
350
350
|
/** @internal Once a copy of a shared secret exists, EVERYTHING that follows is protected, to the
|
|
351
351
|
* return: the remaining copies, the last option reads, all of it. A caller field is read through
|
|
@@ -363,7 +363,7 @@ function _snapshotSent(sent) {
|
|
|
363
363
|
}
|
|
364
364
|
out.recipient = r;
|
|
365
365
|
}
|
|
366
|
-
if (Array.isArray(out.certs)) out.certs = out.certs
|
|
366
|
+
if (Array.isArray(out.certs)) out.certs = guard.list.copyMap(out.certs, _copyAnyBytes);
|
|
367
367
|
out.allowUnverified = sent.allowUnverified === true;
|
|
368
368
|
out.allowUnbound = sent.allowUnbound === true;
|
|
369
369
|
return out;
|
package/lib/cmp-session.js
CHANGED
|
@@ -131,7 +131,7 @@ function _waitingStatus() {
|
|
|
131
131
|
|
|
132
132
|
function _certReqIdEq(a, b) { return a != null && b != null && BigInt(a) === BigInt(b); }
|
|
133
133
|
|
|
134
|
-
function _asCertList(v) { return v == null ? [] : (Array.isArray(v) ?
|
|
134
|
+
function _asCertList(v) { return v == null ? [] : (Array.isArray(v) ? guard.list.snapshot(v) : [v]); }
|
|
135
135
|
|
|
136
136
|
function _boundedPool(base, added) {
|
|
137
137
|
var ceiling = constants.LIMITS.PATH_BUILD_MAX_CANDIDATES;
|
package/lib/cms-sign.js
CHANGED
|
@@ -240,7 +240,7 @@ function _normCertDer(c) {
|
|
|
240
240
|
throw _err("cms/bad-input", "a signer certificate must be a DER Buffer or a PEM string");
|
|
241
241
|
}
|
|
242
242
|
function _pemToDer(text) {
|
|
243
|
-
var der = pkix.pemDecodeLenient(text, "CERTIFICATE");
|
|
243
|
+
var der = pkix.pemDecodeLenient(text, "CERTIFICATE", _err, "cms/bad-input");
|
|
244
244
|
if (der === null) throw _err("cms/bad-input", "a signer certificate PEM is not a CERTIFICATE block");
|
|
245
245
|
return der;
|
|
246
246
|
}
|
|
@@ -367,12 +367,12 @@ function _normEntityDer(v, what, pemLabel, parseFn) {
|
|
|
367
367
|
if (guard.bytes.isByteSource(v)) {
|
|
368
368
|
der = guard.bytes.snapshotSource(v, CmsError, "cms/bad-input", what);
|
|
369
369
|
if (der[0] !== 0x30) {
|
|
370
|
-
var decoded = pkix.pemDecodeLenient(intrinsic.bufToString(der, "latin1"), pemLabel);
|
|
370
|
+
var decoded = pkix.pemDecodeLenient(intrinsic.bufToString(der, "latin1"), pemLabel, _err, "cms/bad-input");
|
|
371
371
|
if (decoded === null) throw _err("cms/bad-input", what + " must be a plain DER " + pemLabel + " (a tagged alternative is not permitted) or a PEM block");
|
|
372
372
|
der = decoded;
|
|
373
373
|
}
|
|
374
374
|
} else if (typeof v === "string") {
|
|
375
|
-
var d2 = pkix.pemDecodeLenient(v, pemLabel);
|
|
375
|
+
var d2 = pkix.pemDecodeLenient(v, pemLabel, _err, "cms/bad-input");
|
|
376
376
|
if (d2 === null) throw _err("cms/bad-input", what + " PEM is not a " + pemLabel + " block");
|
|
377
377
|
der = d2;
|
|
378
378
|
} else {
|
package/lib/cms-verify.js
CHANGED
|
@@ -607,7 +607,7 @@ function _cloneAnchorValue(v, depth) {
|
|
|
607
607
|
throw _err("cms/bad-input", "an opts.trustAnchors entry nests deeper than " + _ANCHOR_CLONE_DEPTH +
|
|
608
608
|
" levels, so it cannot be copied before the chain is walked; pass the anchor as certificate DER or a { name, publicKey, algorithm } tuple");
|
|
609
609
|
}
|
|
610
|
-
if (Array.isArray(v)) return
|
|
610
|
+
if (Array.isArray(v)) return guard.list.copyMap(v, function (e) { return _cloneAnchorValue(e, depth + 1); });
|
|
611
611
|
var out = intrinsic.create(null), k;
|
|
612
612
|
for (k in v) {
|
|
613
613
|
if (!intrinsic.hasOwn(v, k)) continue;
|
|
@@ -619,14 +619,14 @@ function _snapshotTrust(opts) {
|
|
|
619
619
|
var raw = opts.trustAnchors;
|
|
620
620
|
var anchors = null;
|
|
621
621
|
if (raw != null) {
|
|
622
|
-
anchors = (Array.isArray(raw) ? raw : [raw]
|
|
622
|
+
anchors = guard.list.copyMap(Array.isArray(raw) ? raw : [raw], function (a) {
|
|
623
623
|
return typeof a === "string" ? a : _cloneAnchorValue(a, 0);
|
|
624
624
|
});
|
|
625
625
|
}
|
|
626
626
|
return {
|
|
627
627
|
trustAnchors: anchors,
|
|
628
628
|
time: guard.time.isDate(opts.time) ? new intrinsic.Date(guard.time.instantOf(opts.time)) : (opts.time === undefined ? new intrinsic.Date() : opts.time),
|
|
629
|
-
requiredEku: Array.isArray(opts.requiredEku) ? opts.requiredEku
|
|
629
|
+
requiredEku: Array.isArray(opts.requiredEku) ? guard.list.snapshot(opts.requiredEku) : opts.requiredEku,
|
|
630
630
|
checkPurpose: opts.checkPurpose,
|
|
631
631
|
};
|
|
632
632
|
}
|
|
@@ -1019,8 +1019,8 @@ function _certsOnlyInputDer(input, verb) {
|
|
|
1019
1019
|
input = intrinsic.bufToString(buf, "latin1");
|
|
1020
1020
|
}
|
|
1021
1021
|
if (typeof input === "string") {
|
|
1022
|
-
var der = pkix.pemDecodeLenient(input, "CMS");
|
|
1023
|
-
if (der === null) der = pkix.pemDecodeLenient(input, "PKCS7");
|
|
1022
|
+
var der = pkix.pemDecodeLenient(input, "CMS", _err, "cms/bad-input");
|
|
1023
|
+
if (der === null) der = pkix.pemDecodeLenient(input, "PKCS7", _err, "cms/bad-input");
|
|
1024
1024
|
if (der === null) throw _err("cms/bad-input", verb + " input is neither DER nor a PEM CMS/PKCS7 block");
|
|
1025
1025
|
return der;
|
|
1026
1026
|
}
|
package/lib/constants.js
CHANGED
|
@@ -115,6 +115,8 @@ var LIMITS = Object.assign(Object.create(null), {
|
|
|
115
115
|
NAMED_SCAN_MAX_ELEMENTS: 16777216,
|
|
116
116
|
MAX_DECODE_DEPTH_CEILING: 256,
|
|
117
117
|
PEM_MAX_BYTES: BYTES.mib(16),
|
|
118
|
+
PEM_MAX_BLOCKS: 512,
|
|
119
|
+
PEM_MAX_DECODED_BYTES: BYTES.mib(16),
|
|
118
120
|
DER_MAX_INTEGER_BYTES: BYTES.kib(16),
|
|
119
121
|
DH_MAX_MODULUS_BYTES: 512,
|
|
120
122
|
DH_MIN_SUBGROUP_BYTES: 20,
|
|
@@ -131,6 +133,15 @@ var LIMITS = Object.assign(Object.create(null), {
|
|
|
131
133
|
CBOR_MAX_ITEMS: 1000000,
|
|
132
134
|
SCT_MAX_BYTES: BYTES.kib(64) + 1,
|
|
133
135
|
SCT_MAX_COUNT: 256,
|
|
136
|
+
SAN_MAX_ENTRIES: 256,
|
|
137
|
+
IDENTITY_MAX_REFERENCES: 64,
|
|
138
|
+
REVOCATION_MAX_FETCHES: 12,
|
|
139
|
+
REVOCATION_MAX_PER_CERT: 6,
|
|
140
|
+
REVOCATION_MAX_RESPONSE_BYTES: BYTES.mib(8),
|
|
141
|
+
REVOCATION_TOTAL_DEADLINE_MS: TIME.seconds(20),
|
|
142
|
+
REVOCATION_SOURCE_TIMEOUT_MS: TIME.seconds(5),
|
|
143
|
+
REVOCATION_CACHE_MAX_ENTRIES: 256,
|
|
144
|
+
REVOCATION_CACHE_MAX_BYTES: BYTES.mib(32),
|
|
134
145
|
TLOG_MAX_COUNT: 32,
|
|
135
146
|
CMS_MAX_KARI_ENCRYPTED_KEYS: 64,
|
|
136
147
|
CMP_KEM_MAX_KEY_BYTES: 1024,
|
package/lib/est.js
CHANGED
|
@@ -1224,7 +1224,7 @@ function _cmcSent(opts, der) {
|
|
|
1224
1224
|
dataReturn: _copyBytes(carried.dataReturn),
|
|
1225
1225
|
bodyPartIDs: carried.bodyPartIDs,
|
|
1226
1226
|
bodyPartPaths: carried.bodyPartPaths,
|
|
1227
|
-
certs: Array.isArray(opts.responderCerts) ? opts.responderCerts
|
|
1227
|
+
certs: Array.isArray(opts.responderCerts) ? guard.list.copyMap(opts.responderCerts, _copyBytes) : opts.responderCerts,
|
|
1228
1228
|
recipient: _copyRecipient(opts.responseRecipient),
|
|
1229
1229
|
allowUnverified: opts.allowUnverifiedResponse === true,
|
|
1230
1230
|
allowUnbound: opts.allowUnboundResponse === true,
|
package/lib/framework-error.js
CHANGED
|
@@ -215,6 +215,10 @@ var InspectError = defineClass("InspectError", { withCause: true });
|
|
|
215
215
|
var WebauthnError = defineClass("WebauthnError", { withCause: true });
|
|
216
216
|
var LintError = defineClass("LintError", { withCause: true });
|
|
217
217
|
var KeyError = defineClass("KeyError", { withCause: true });
|
|
218
|
+
var Pkcs11Error = defineClass("Pkcs11Error", { withCause: true });
|
|
219
|
+
var Pkcs1Error = defineClass("Pkcs1Error", { withCause: true });
|
|
220
|
+
var Sec1Error = defineClass("Sec1Error", { withCause: true });
|
|
221
|
+
var IdentityError = defineClass("IdentityError", { withCause: true });
|
|
218
222
|
|
|
219
223
|
module.exports = {
|
|
220
224
|
PkiError: PkiError,
|
|
@@ -258,4 +262,8 @@ module.exports = {
|
|
|
258
262
|
AcmeError: AcmeError,
|
|
259
263
|
TrustError: TrustError,
|
|
260
264
|
KeyError: KeyError,
|
|
265
|
+
Pkcs11Error: Pkcs11Error,
|
|
266
|
+
Pkcs1Error: Pkcs1Error,
|
|
267
|
+
Sec1Error: Sec1Error,
|
|
268
|
+
IdentityError: IdentityError,
|
|
261
269
|
};
|