@blamejs/pki 0.8.7 → 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 +124 -76
- package/README.md +3 -2
- package/index.js +5 -0
- package/lib/acme.js +15 -78
- 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 +6 -0
- package/lib/guard-async.js +53 -2
- package/lib/guard-encoding.js +74 -0
- package/lib/guard-identifier.js +74 -1
- package/lib/guard-intrinsic.js +2 -0
- package/lib/guard-limits.js +40 -1
- package/lib/guard-list.js +25 -0
- package/lib/guard-name.js +133 -16
- 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/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` |
|
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");
|
|
@@ -87,6 +88,10 @@ module.exports = {
|
|
|
87
88
|
// `path` is RFC 5280 sec. 6 certification-path validation -- pki.path.validate
|
|
88
89
|
// runs the sec. 6.1 state machine over an already-parsed path + a trust anchor.
|
|
89
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 },
|
|
90
95
|
// `ct` is RFC 6962 Certificate Transparency -- pki.ct.parseSctList decodes the
|
|
91
96
|
// SCT-list extension a certificate / OCSP response carries; the signature is
|
|
92
97
|
// surfaced raw for external verification (pki.ct.reconstructSignedData).
|
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/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
|
@@ -216,6 +216,9 @@ var WebauthnError = defineClass("WebauthnError", { withCause: true });
|
|
|
216
216
|
var LintError = defineClass("LintError", { withCause: true });
|
|
217
217
|
var KeyError = defineClass("KeyError", { withCause: true });
|
|
218
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 });
|
|
219
222
|
|
|
220
223
|
module.exports = {
|
|
221
224
|
PkiError: PkiError,
|
|
@@ -260,4 +263,7 @@ module.exports = {
|
|
|
260
263
|
TrustError: TrustError,
|
|
261
264
|
KeyError: KeyError,
|
|
262
265
|
Pkcs11Error: Pkcs11Error,
|
|
266
|
+
Pkcs1Error: Pkcs1Error,
|
|
267
|
+
Sec1Error: Sec1Error,
|
|
268
|
+
IdentityError: IdentityError,
|
|
263
269
|
};
|
package/lib/guard-async.js
CHANGED
|
@@ -8,6 +8,13 @@ var _reject = _intrinsic.uncurry(_intrinsic.promiseReject);
|
|
|
8
8
|
var _apply = _intrinsic.apply;
|
|
9
9
|
var _String = _intrinsic.String;
|
|
10
10
|
var _Promise = Promise;
|
|
11
|
+
/** @internal Bound at load, like every other operation this module decides with: a replacement
|
|
12
|
+
* installed later would otherwise choose when a bound expires, or whether it ever does. */
|
|
13
|
+
var _setTimeout = setTimeout;
|
|
14
|
+
var _clearTimeout = clearTimeout;
|
|
15
|
+
/** @internal The losing side of a race is observed, not acted on: attaching this is what keeps an
|
|
16
|
+
* outcome nobody wants from becoming an unhandled rejection. */
|
|
17
|
+
function _ignore() { return undefined; }
|
|
11
18
|
// @internal
|
|
12
19
|
// @enforced-by behavioral -- the rule has no rename-proof code shape (it is the ABSENCE of a wrapper
|
|
13
20
|
function deferred(body) {
|
|
@@ -40,9 +47,53 @@ function invoked(fn, args, E, code, label) {
|
|
|
40
47
|
var out;
|
|
41
48
|
try { out = _apply(fn, undefined, args); }
|
|
42
49
|
catch (e) {
|
|
43
|
-
|
|
50
|
+
/** @internal The thrown value is the caller's, so describing it is a read of caller data: a
|
|
51
|
+
* `message` accessor that throws would leave this boundary by the one path it exists to close.
|
|
52
|
+
* @guard-via guard.text.describeThrown */
|
|
53
|
+
// allow:inline-require guard-text reaches guard-bytes, which reaches this module, so binding it at load leaves guard-bytes half-built for whichever of the two is required first; this line runs only after a producer has already thrown
|
|
54
|
+
throw E(code, label + " threw when it was called: " +
|
|
55
|
+
require("./guard-text").describeThrown(e), e);
|
|
44
56
|
}
|
|
45
57
|
return awaited(out, E, code, label);
|
|
46
58
|
}
|
|
47
59
|
|
|
48
|
-
|
|
60
|
+
// @internal
|
|
61
|
+
// @enforced-by behavioral -- a RED vector drives a never-settling caller operation through a client
|
|
62
|
+
/** @internal Await a caller-supplied operation under a bound this side controls. A request field
|
|
63
|
+
* naming a timeout is a request: an operation that does not implement it never settles, and the
|
|
64
|
+
* verb awaiting it never returns. The timer holds the event loop until it fires or is cleared,
|
|
65
|
+
* which is what keeps a process from exiting while a bound is still in flight and abandoning the
|
|
66
|
+
* await in silence. It is cleared on either outcome, so it holds the loop for at most `ms`. The
|
|
67
|
+
* losing side of the race is not cancelled, because a promise cannot be; the caller stops waiting.
|
|
68
|
+
*
|
|
69
|
+
* `ms` at or below zero is already past and refuses without awaiting anything. */
|
|
70
|
+
function bounded(value, ms, E, code, label) {
|
|
71
|
+
var settled = false;
|
|
72
|
+
return new _Promise(function (resolve, reject) {
|
|
73
|
+
if (!(ms > 0)) {
|
|
74
|
+
/** @internal The operation may already be running: a deadline can expire between the check
|
|
75
|
+
* that started it and the bound computed for it. Refusing without observing its promise
|
|
76
|
+
* leaves a rejection nobody handled, which ends the process on the default
|
|
77
|
+
* `unhandledRejection` behavior, and the caller catching this refusal does not help. */
|
|
78
|
+
_resolve(_Promise, value).then(_ignore, _ignore);
|
|
79
|
+
reject(E(code, label + " had no time left to run in"));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
var timer = _setTimeout(function () {
|
|
83
|
+
if (settled) return;
|
|
84
|
+
settled = true;
|
|
85
|
+
reject(E(code, label + " did not settle within " + ms + "ms"));
|
|
86
|
+
}, ms);
|
|
87
|
+
function done(fn) {
|
|
88
|
+
return function (x) {
|
|
89
|
+
if (settled) return;
|
|
90
|
+
settled = true;
|
|
91
|
+
_clearTimeout(timer);
|
|
92
|
+
fn(x);
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
_resolve(_Promise, value).then(done(resolve), done(reject));
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = _intrinsic.freeze({ deferred: deferred, awaited: awaited, invoked: invoked, bounded: bounded });
|
package/lib/guard-encoding.js
CHANGED
|
@@ -16,6 +16,9 @@ var _charCodeAt = _intrinsic.uncurry(String.prototype.charCodeAt);
|
|
|
16
16
|
var _strSlice = _intrinsic.uncurry(String.prototype.slice);
|
|
17
17
|
var _toLowerCase = _intrinsic.uncurry(String.prototype.toLowerCase);
|
|
18
18
|
var _isInteger = _intrinsic.isInteger;
|
|
19
|
+
var _charAt = _intrinsic.uncurry(String.prototype.charAt);
|
|
20
|
+
var _fromCharCode = String.fromCharCode;
|
|
21
|
+
var _guardBytes = require("./guard-bytes");
|
|
19
22
|
var _floor = _intrinsic.floor;
|
|
20
23
|
|
|
21
24
|
var UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", LOWER = "abcdefghijklmnopqrstuvwxyz", DIGITS = "0123456789";
|
|
@@ -103,7 +106,78 @@ function isAlphanumericByte(c) {
|
|
|
103
106
|
return (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) || (c >= 0x30 && c <= 0x39);
|
|
104
107
|
}
|
|
105
108
|
|
|
109
|
+
var _HEX_UPPER = "0123456789ABCDEF";
|
|
110
|
+
|
|
111
|
+
/** @internal Whether a byte is in RFC 3986 sec. 2.3's unreserved set: `ALPHA / DIGIT / "-" / "."
|
|
112
|
+
* / "_" / "~"`. Every other byte is written as a percent-triplet, which is what sec. 2.1 requires
|
|
113
|
+
* of a character that is not allowed where it sits. The set is deliberately the unreserved one
|
|
114
|
+
* and not the larger set a path segment also admits, so the output is safe wherever it is
|
|
115
|
+
* placed and a caller cannot reach a delimiter by choosing a component. */
|
|
116
|
+
function _isUnreservedByte(c) {
|
|
117
|
+
return (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) || (c >= 0x30 && c <= 0x39) ||
|
|
118
|
+
c === 0x2d || c === 0x2e || c === 0x5f || c === 0x7e;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** @internal Percent-encode bytes to RFC 3986 sec. 2.1, with the unreserved set of sec. 2.3 passed
|
|
122
|
+
* through and every other byte written as `%` and two upper-case hex digits. sec. 2.1 states that
|
|
123
|
+
* the hexadecimal digits of a triplet may be either case and that uppercase is the canonical form
|
|
124
|
+
* a producer emits.
|
|
125
|
+
*
|
|
126
|
+
* This is the only escaping in `lib/`. `encodeURIComponent` reads a JavaScript string, so bytes
|
|
127
|
+
* reach it only after a decode this cannot assume, and it leaves `!`, `*`, `'`, `(` and `)`
|
|
128
|
+
* unescaped, which are sub-delims in sec. 2.2 and therefore delimiters in some components. */
|
|
129
|
+
// @enforced-by guard-shape-reinlined
|
|
130
|
+
// @guard-shape %[0-9A-F]{2}|toString\(16\)[\s\S]{0,80}?padStart\(\s*2
|
|
131
|
+
// @guard-via guard\.encoding\.(?:percentEncode|uriPathSegment)\(
|
|
132
|
+
function percentEncode(bytes, E, code, label) {
|
|
133
|
+
var buf = _guardBytes.source(bytes, _rawError(E), code, label || "value to percent-encode");
|
|
134
|
+
var out = "";
|
|
135
|
+
for (var i = 0; i < buf.length; i++) {
|
|
136
|
+
var c = buf[i];
|
|
137
|
+
if (_isUnreservedByte(c)) { out += _fromCharCode(c); continue; }
|
|
138
|
+
out += "%" + _charAt(_HEX_UPPER, (c >> 4) & 0x0f) + _charAt(_HEX_UPPER, c & 0x0f);
|
|
139
|
+
}
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** @internal One path segment of a URI, built from `text` read as its latin1 bytes. Every byte
|
|
144
|
+
* outside the unreserved set becomes a triplet, so a value carrying `/`, `?`, `#` or a percent of
|
|
145
|
+
* its own cannot reach past the segment it was placed in. */
|
|
146
|
+
function uriPathSegment(text, E, code, label) {
|
|
147
|
+
if (typeof text !== "string") {
|
|
148
|
+
throw _rawError(E)(code, (label || "URI path segment") + " must be a string");
|
|
149
|
+
}
|
|
150
|
+
return percentEncode(_bufferFrom(text, "latin1"), E, code, label);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** @internal The guards take a `(code, message)` factory. A caller that passes an error CLASS is a
|
|
154
|
+
* configuration fault and not an input one, so it is refused here instead of producing
|
|
155
|
+
* `undefined is not a constructor` at the first refusal. */
|
|
156
|
+
function _rawError(E) {
|
|
157
|
+
if (typeof E !== "function") throw new TypeError("guard.encoding: an error factory (code, message) is required");
|
|
158
|
+
return E;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** @internal Whether a string is already the form that goes on the wire. RFC 3986 sec. 2 builds a
|
|
162
|
+
* URI out of US-ASCII alone, so a string carrying anything above it is an IRI (RFC 3987) and the
|
|
163
|
+
* bytes a transport would send are not the characters counted here. Every length a specification
|
|
164
|
+
* states about a URL is a byte count, which makes this the check a boundary needs before measuring
|
|
165
|
+
* one: a code point in U+0080..U+07FF is one character and two UTF-8 bytes, so a rule measured in
|
|
166
|
+
* characters passes a URL the rule was meant to refuse.
|
|
167
|
+
*
|
|
168
|
+
* @enforced-by guard-shape-reinlined
|
|
169
|
+
* @guard-shape /charCodeAt\s*\(\s*[\w$]+\s*,\s*[\w$]+\s*\)\s*>\s*(?:0x7f|127)\b/ */
|
|
170
|
+
function isAsciiText(s) {
|
|
171
|
+
if (typeof s !== "string") return false;
|
|
172
|
+
for (var i = 0; i < s.length; i++) {
|
|
173
|
+
if (_charCodeAt(s, i) > 0x7f) return false;
|
|
174
|
+
}
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
|
|
106
178
|
module.exports = _intrinsic.freeze({
|
|
107
179
|
base64url: base64url, base64: base64, hex: hex,
|
|
108
180
|
hexNibble: hexNibble, isAlphanumericByte: isAlphanumericByte,
|
|
181
|
+
isAsciiText: isAsciiText,
|
|
182
|
+
percentEncode: percentEncode, uriPathSegment: uriPathSegment,
|
|
109
183
|
});
|