@blamejs/pki 0.8.26 → 0.8.28
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 +46 -0
- package/README.md +2 -2
- package/index.js +14 -1
- package/lib/composite-sig.js +5 -0
- package/lib/crl-sign.js +22 -3
- package/lib/csr-sign.js +17 -2
- package/lib/http-retry-after.js +28 -7
- package/lib/inspect.js +3 -2
- package/lib/lint.js +942 -41
- package/lib/rfc3339.js +12 -5
- package/lib/schema-crl.js +12 -7
- package/lib/x509-sign.js +20 -1
- package/package.json +2 -2
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,52 @@ All notable changes to `@blamejs/pki` are documented here. The format
|
|
|
4
4
|
follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
|
|
5
5
|
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
6
|
|
|
7
|
+
## v0.8.28 — 2026-09-28
|
|
8
|
+
|
|
9
|
+
The three signing verbs lint what they are about to emit, and refuse it before the key is used.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `pki.x509.sign` refuses a spec whose certificate violates an error-severity rule of the RFC 5280 profile, with `x509/profile-violation` naming the rule and its clause. `pki.csr.sign` does the same against RFC 2986 with `csr/profile-violation`, and `pki.crl.sign` against the RFC 5280 section 5 profile with `crl/profile-violation`. The check runs on the assembled artifact rather than on the spec, so it reports what would have reached the wire.
|
|
14
|
+
- The refusal precedes the signature. A spec that violates a rule never reaches the signing key, which matters where that key is a hardware token, a remote signer, or anything that counts or logs a use.
|
|
15
|
+
- `opts.profile` on all three verbs names a further profile from `pki.lint.profiles()` whose error-severity rules run beside the always-on set, so a certificate can be held to `cabf-tls` or `cnsa-2.0` at the moment it is built rather than after. A name that verb does not run is refused with its own `bad-input` code and the sentence `pki.lint.rules` gives for the same name.
|
|
16
|
+
- `opts.profile: "none"` runs no rules and emits what the spec describes. A toolkit that cannot emit a non-conforming artifact cannot produce a test corpus, reproduce a real misissuance, or build the fixtures a linter is exercised against, so the escape is a name the caller writes rather than a default: the gate is closed unless somebody asked for it, and every refusal names it.
|
|
17
|
+
- Two kinds of finding are passed over. A rule reading the signature value cannot apply, because at the moment of the check the signature does not exist. `lint/rfc5280/unknown-critical-extension` does not apply either: RFC 5280 section 4.2 places that requirement on a certificate-using system, and the same section states that conforming CAs may support extensions the specification does not identify, so a private critical extension signs and the relying party still decides what to do with it.
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
|
|
21
|
+
- A spec that describes a non-conforming artifact is now refused rather than signed. What changes in practice: a CRL spec with no `crlNumber` or no `nextUpdate` is refused, since RFC 5280 section 5.2.3 and section 5.1.2.5 require both of a conforming CRL issuer and neither can be derived, a CRL number being issuer state; a certificate whose basicConstraints sets cA without a keyUsage asserting keyCertSign is refused, per section 4.2.1.3; a request with an empty subject that does not ask for a subjectAltName is refused, since it names nothing to certify; and a certificate or CRL built through the pre-encoded extension array is refused when that array carries no key identifier the artifact needs, because that form emits only what is written into it. The object form still derives what its RFC places on the issuer: a subjectKeyIdentifier on every certificate, an authorityKeyIdentifier on every certificate that is not self-signed and on every CRL. To upgrade: add the missing field, write the identifier into the array, or pass `{ profile: "none" }` where the artifact is meant to be non-conforming. The refusal message names the rule and the clause in every case.
|
|
22
|
+
- `pki.lint` is assembled from its public verbs rather than passed through as a module, so the namespace holds `certificate`, `csr`, `crl`, `ocsp`, `cms`, `tsp`, `attrcert`, `rules` and `profiles` and nothing else. No name was removed.
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- The documented examples for `pki.crl.verify`, `pki.crl.isRevoked`, `pki.inspect.crl`, `pki.schema.crl.parse`, `pki.schema.crl.pemDecode`, `pki.schema.crl.pemEncode`, `pki.schema.crl.decodeExtension` and `pki.schema.crl.decodeExtensions` built artifacts this toolkit's linter grades an error, and an operator copying one got a CRL with no nextUpdate or a CA certificate asserting no keyCertSign. Each now carries what its RFC requires.
|
|
27
|
+
|
|
28
|
+
## v0.8.27 — 2026-09-28
|
|
29
|
+
|
|
30
|
+
Two algorithm-policy profiles, and a two-digit year read against the clock rather than a constant.
|
|
31
|
+
|
|
32
|
+
### Added
|
|
33
|
+
|
|
34
|
+
- `pki.lint.certificate(der, { profile: "nist-pqc-transition" })` reports NIST IR 8547's two transitions. A classical subject public key or signature algorithm in a certificate issued from 2036 is an error, which Table 2 and Table 4 make disallowed at every parameter set they list. A classical subject key at or below the 112-bit security strength issued from 2031 is a warning, which is the strength those tables deprecate and which SP 800-57 Part 1 Rev 5 Table 2 maps onto an RSA modulus of 2048 bits, a curve whose field is 224 to 255 bits, and a finite-field group stated as a pair, L of 2048 with N of 224. Either finite-field parameter caps the strength, so a group with a 3072-bit prime and a 224-bit subgroup order is reported, and a group whose encoding states no subgroup order is read on its prime. "After 2030" and "after 2035" name whole years, so each transition begins on 1 January of the year that follows and is compared against the certificate's own notBefore. IR 8547 is an initial public draft, so these are a draft's dates and the citation says so.
|
|
35
|
+
- Ed25519 is deliberately outside the 2031 row. Its field is 255 bits, which SP 800-57's ECC column places at the 112-bit strength, so reading the two documents together would deprecate it after 2030; IR 8547's own EdDSA row carries a 128-bit entry alone, with no 112-bit entry and no 2030 date, and the profile follows the document it cites. A composite signature or subject key is passed over in both rows, because the tables list pure families and the same guidance endorses dual-algorithm operation through the transition.
|
|
36
|
+
- `pki.lint.certificate(der, { profile: "cnsa-2.0" })` reports the CNSA 2.0 certificate profile of `draft-jenkins-cnsa2-pkix-profile-05`, which states what a certificate must carry where the NSA algorithm notice lists algorithms. Seventeen rows: the certificate must be X.509 version 3, the subject public key must be ML-DSA-87 or ML-KEM-1024 and the signature must be id-ml-dsa-87, which also answers the clause forbidding HashML-DSA, since a HashML-DSA identifier is not that one; a keyUsage extension must be critical in all three scopes; a self-signed CA must carry a subjectKeyIdentifier, a keyUsage and a basicConstraints, a non-self-signed CA an authorityKeyIdentifier, a keyUsage and a basicConstraints, where a certificate whose keyUsage asserts keyCertSign is read as a CA whether or not it carries basicConstraints, since RFC 5280 section 4.2.1.3 requires the cA boolean of any certificate asserting that bit and a certificate omitting the extension is the one this requirement is about; a CA reissued in its own name under a new key is read as the second of the two CA kinds, since its authorityKeyIdentifier names a key other than its own subjectKeyIdentifier and the section governing it permits the pathLenConstraint the self-signed section forbids; and an end entity an authorityKeyIdentifier and a keyUsage, with a missing subjectKeyIdentifier on an end entity reported as a warning where that clause says SHOULD; a CA's basicConstraints must be critical and must set the cA boolean, and a self-signed CA's must carry no pathLenConstraint, which the non-self-signed section calls optional; a CA's keyUsage must set keyCertSign and cRLSign, may set digitalSignature and nonRepudiation, and must set nothing else; an end entity's extKeyUsage must be present and must not name anyExtendedKeyUsage; and a certificatePolicies extension must be non-critical and should carry no policy qualifiers. Each departure from a closed key-usage set is its own finding, so a certificate setting two forbidden bits reports both.
|
|
37
|
+
- The end entity key-usage set follows the kind the subject public key declares, which is what makes that clause readable from the bytes: an ML-DSA-87 certificate must set digitalSignature and may set nonRepudiation, an ML-KEM-1024 certificate must set keyEncipherment alone, and a key outside the suite has no set to be held to and is reported as the key instead.
|
|
38
|
+
- `pki.lint.crl` and `pki.lint.ocsp` take the same `cnsa-2.0` name for the one rule the document states about them: the signature on a CRL and on an OCSP response follows the same rule as a certificate's. Both halves of it reach them, the algorithm the artifact was signed with and the length FIPS 204 fixes for a signature of that algorithm, the second of which a certificate is told by the RFC 9881 row its own profile runs.
|
|
39
|
+
- The profile also runs the RFC 9881 and RFC 9935 subject-key rows, which section 4 of the draft names for "the algorithm identifier, and the syntax and semantics for the Subject Public Key Information field" of the two keys the suite fixes. So a subject key whose algorithm says ML-KEM-1024 or ML-DSA-87 while its bytes are not a key of the size FIPS 203 or FIPS 204 gives that parameter set is reported, where reading the algorithm identifier alone called it conforming.
|
|
40
|
+
- `pki.lint.certificate` gains `lint/rfc9881/mldsa-key-length` and `lint/rfc9881/mldsa-signature-length` for that second half, under every profile that carries the RFC 9881 rows. FIPS 204 fixes both an ML-DSA public key's length and a signature's per parameter set, and RFC 9881 section 4 carries each directly in its BIT STRING, so a value of any other length is not what the identifier names. The ML-KEM row beside them has read its own sizes since that profile shipped.
|
|
41
|
+
- Every clause of that profile which this toolkit's parsers settle before a row could read it has a conformance vector asserting the parser's verdict instead: a present parameters field on either suite algorithm arrives as `x509/bad-algorithm-parameters`, and an inner TBSCertificate or TBSCertList signature identifier that differs from the outer signatureAlgorithm as `x509/bad-signature-algorithm` or `crl/bad-signature-algorithm`, so the row reading one of those two fields answers for both. Four further clauses are recorded without a row, because the bytes do not settle them: which extended key purposes are consistent with which key-usage bits is enumerated nowhere in the document, a certificatePolicies extension that is present asserts a policy, the responder authorization an OCSP response also owes is a trust decision over a chain that `pki.ocsp.verify` makes, and a CA reissued in its own name that carries no authorityKeyIdentifier at all cannot be told from a root, since a root omits that extension legitimately and RFC 5280 section 4.2.1.1 permits its absence only there, which the default rule set reports.
|
|
42
|
+
|
|
43
|
+
### Changed
|
|
44
|
+
|
|
45
|
+
- `pki.lint.profiles()` lists `nist-pqc-transition` and `cnsa-2.0` beside the others. `cnsa-2.0` appears once although three verbs run it, because that call enumerates profile names rather than the places they are registered.
|
|
46
|
+
|
|
47
|
+
### Fixed
|
|
48
|
+
|
|
49
|
+
- `pki.lint.certificate`, `pki.lint.crl`, `pki.lint.ocsp`, `pki.lint.csr`, `pki.lint.cms`, `pki.lint.tsp` and `pki.lint.attrcert` all answer the same way about where a profile name lives. A verb handed a profile it does not run refuses it with `lint/unknown-profile` naming every verb that does run it, read from the registry rather than from a list written into each verb. Before, each verb carried its own chain of checks in its own order, so a name carried by more than one artifact drew a different answer depending on which verb was asked, and each chain omitted the artifacts nobody had added a branch for: a CMS profile name reached `pki.lint.crl` as simply unknown. `pki.lint.rules(profile, artifact)` gives that same sentence, so asking where a profile lives and asking a verb to run it are one answer.
|
|
50
|
+
- An HTTP `Retry-After` header carrying an rfc850-date, the obsolete format with a two-digit year, is read against the time the value arrives. RFC 7231 section 7.1.1.1 requires a recipient to read a year more than 50 years in the future as the most recent past year with the same two digits, which depends on when the value is received. A caller that supplied a reference time already got that; one that did not fell back to a fixed cutoff at 70, which is the same rule evaluated once for a reference year around 2020 and which misreads a band of years that widens by one every year. At a 2026 receipt the years 70 through 76 were read a century early. `pki.est`'s retry handling is the reachable caller, since its own `now` option is optional. The four-digit formats are unaffected.
|
|
51
|
+
- `pki.rfc3339`'s description of why it validates the calendar names the case that needs it. `2026-02-30T00:00:00Z` is the one the runtime accepts and reads as 2 March, two days from the date the value names; month 13, hour 25 and a `+25:00` offset are refused by the runtime as well, so the check agrees with it there. A `:60` leap second, which the description gave as its example, is one of those, and refusing it is a decision rather than a malformation: RFC 3339 section 5.7 permits the value and JavaScript cannot represent it. Each of those statements now has a vector asserting it against the runtime, so the reason the check exists cannot quietly stop being true. No behavior changed.
|
|
52
|
+
|
|
7
53
|
## v0.8.26 — 2026-09-28
|
|
8
54
|
|
|
9
55
|
Three lint verbs, and each is short because the parser that feeds it is strict.
|
package/README.md
CHANGED
|
@@ -268,7 +268,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
268
268
|
| `pki.schema.engine` | The declarative ASN.1 structure-schema engine every format parser composes — `walk`, `encode`, `embeddedDer`, and the schema combinators |
|
|
269
269
|
| `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 policies, processed as the RFC 9618 `valid_policy_graph` in place of the RFC 5280 §6.1 policy tree. The graph holds one node per depth and policy identifier and gives it several parents where the tree made a separate node under each, so its size is linear in the policies and mappings on the path rather than exponential in the path length: a six-certificate chain whose policies map to each other needs 25 nodes where the tree needed 5461, and chains the tree could not hold inside `maxPolicyNodes` now validate. 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` |
|
|
270
270
|
| `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` |
|
|
271
|
-
| `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` |
|
|
271
|
+
| `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`. Before the signing key is reached it lints the certificate the spec describes against the RFC 5280 profile and refuses an error-severity finding with `x509/profile-violation` naming the rule and its clause, so a non-conforming certificate is never signed rather than signed and discarded; `opts.profile` names a further profile from `pki.lint.profiles()` to hold it to at build time, and `opts.profile: "none"` runs no rules and emits what the spec describes. `pki.csr.sign` and `pki.crl.sign` carry the same gate against RFC 2986 and the RFC 5280 §5 profile. 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` |
|
|
272
272
|
| `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` |
|
|
273
273
|
| `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; a `baseCertificateID` names its issuer as one non-empty directoryName, which sec. 4.2.2 requires in the same words sec. 4.2.3 uses for the AC issuer, and `pki.schema.attrcert.parse` refuses any other shape), 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
274
|
| `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named. `pop.method: 'agreeMAC'` completes the four: `pop.key` is the requester's finite-field Diffie-Hellman private key, as a PKCS#8 DER, a PEM `PRIVATE KEY` block or a `KeyObject`, and `pop.caCert` the authority's certificate it already holds; the two agree a static secret (RFC 2875 sec. 3, obsoleted by RFC 6955), and the key derived from it MACs the DER `certReq` under `id-dhPop-static-HMAC-SHA1`. Either key may name its group in the PKCS#3 or the X9.42 encoding. `pop.key` must be the private half of `certTemplate.publicKey`, and the template must name both a subject and a public key. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
|
|
@@ -290,7 +290,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
290
290
|
| `pki.sigstore` | Offline verifier for a Sigstore bundle, the artifact `npm publish --provenance` produces and the registry serves. `verifyBundle` composes five fail-closed legs against caller-pinned trust (Fulcio CA roots and Rekor log keys, never trusted from the bundle): the DSSE signature over its PAE preimage under the Fulcio leaf key, the ephemeral Fulcio certificate chain validated as of the Rekor log time, the RFC 9162 inclusion proof folded to a Rekor-signed tree root, the log entry bound to this exact signature, and the in-toto SLSA subject digest the caller confirms against the published artifact. It reuses the X.509 parser, the RFC 5280 path validator, and the Merkle verifier; the net-new codecs are the DSSE PAE byte-builder and a fail-closed JSON reader. `verified: true` says the artifact was signed and logged, not that a party you trust signed it — Fulcio issues to anyone who completes an OIDC flow, so who signed is decided only by `opts.identity`, and `identityChecked` reports which of its fields were compared. An identity policy naming no field, or a field name that is not one of the three, is refused rather than satisfied — either would accept every signer while reading as a policy in force. A sixth leg is opt-in: pinning the certificate-transparency logs in `opts.ctLogs` checks the receipt Fulcio embeds in the certificate it issues (RFC 6962 §3.2), verified over the certificate as it stood before the receipt was added and under the key of the log that issued it, so the verdict says the signing certificate was public when it was issued rather than handed out quietly. At least one receipt must verify against a pinned log, the verdict reports `sctChecked` and `validScts`, and an empty log set is refused rather than read as a policy that checks nothing. Both content arms are read: a DSSE-wrapped in-toto attestation, and a message signature over an artifact's own bytes, which `cosign sign-blob` produces. For that arm `opts.artifact` supplies the bytes, and they are held to the hash the Rekor `hashedrekord` entry records before the signature is checked over them; the `messageDigest` the bundle carries is covered by no signature, so it is compared against the computed digest and never used in its place. `contentType` names the arm and the verdict has one shape for both — `pae`, `parseBundle`, `verifyBundle` |
|
|
291
291
|
| `pki.inspect` | Human-readable inspection, the pure-JS equivalent of `openssl x509/crl/req/cms -text`. `certificate(pem \| der \| parsed)` renders an OpenSSL-style report: version, serial, signature algorithm, issuer and subject distinguished names, validity, public-key details (curve or modulus size plus the raw point or modulus), every decoded extension with its critical flag, and the signature. `crl`, `csr`, and `cms` render the other formats the same way — a CRL like `openssl crl -text`, a CSR like `openssl req -text`, and a CMS message like `openssl cms -cmsout -print`, with a stable summary for a non-SignedData ContentInfo — and `any(input)` detects the format and routes to the right report. Built over the strict parsers and the two-way OID registry with one set of field renderers, it names extension and algorithm OIDs an OpenSSL build shows only as raw bytes. No OpenSSL dependency, and the format is stable and OpenSSL-familiar rather than pinned to one OpenSSL version. A certificate policy's user notice renders as text, both its explicit text and a notice reference with the notice numbers that identify it, rather than hex, and a malformed part falls back to a hex dump rather than throwing — `certificate`, `crl`, `csr`, `cms`, `any` |
|
|
292
292
|
| `pki.webauthn` | WebAuthn and passkey verification, both halves: offline trust evaluation of a W3C WebAuthn (Level 3) registration, and signature verification of the assertion every login returns. `parseAttestationObject(bytes)` decodes the CBOR attestation object, authenticatorData, and COSE credential key over the strict `pki.cbor` codec; `parseAuthenticatorData(bytes)` reads the bare form an assertion carries through the same parser; `parseClientData(bytes, opts)` decodes the `clientDataJSON` no signature check looks inside, through the shared JSON guard since these are attacker-chosen bytes, returning the challenge decoded so a caller compares bytes rather than spellings, and checking the ceremony type, challenge, and origin when the relying party supplies what it issued. `verifyAssertion(input)` verifies an assertion signature over `authenticatorData \|\| SHA-256(clientDataJSON)` — raw bytes, no COSE_Sign1, an ES256 signature in ASN.1 DER — and applies the §7.2 step 21 counter rule when a stored `previousSignCount` is given, so a counter that fails to advance is refused as a cloned authenticator. `verify(attestationObject, clientDataHash, opts)` checks the attestation-statement signature and each format's structural bindings for packed, tpm, android-key, apple, fido-u2f, and none: the x5c leaf key, the apple nonce, the tpm `certInfo` Name and `extraData` over the `pubArea`, the android `KeyDescription`, and the fido-u2f `verificationData`. It binds the credential public key to each attestation, through the signed authenticatorData for packed and fido-u2f or a cert or `pubArea`-key equality check for android-key, apple, and tpm, and enforces each leaf's certificate requirements. The credential-key check covers the full WebAuthn COSE algorithm set — ES256/384/512, RS256/384/512, PS256/384/512, EdDSA (Ed25519), and the RFC 9864 fully-specified identifiers ESP256/384/512, Ed25519, and Ed448 — validating the public-key point on its curve, rejecting the compressed EC point form, and enforcing a minimally encoded DER ECDSA signature. The verdict field is `attestationVerified`, and `signatureVerified` for an assertion, rather than a bare `verified`, because a sound statement is a different claim from an acceptable ceremony: an attestation naming another origin's RP ID with user presence clear is perfectly sound and must not be registered. Pass `expectedRpId`, `requireUserPresence`, `requireUserVerification`, or `allowedAlgorithms` and those are checked, with `bindingChecked` reporting which ran, so a check that passed can be told from one that never happened. Pass `opts.clientDataJSON` instead of the digest and the client data is read here too: the ceremony type is checked unconditionally, since a login response replayed into a registration is what that rule stops, and the challenge, origin, and top-level origin are checked against what the relying party issued, with `clientData.checked` reporting which comparisons ran. A registration verdict also carries the `credentialId`, `credentialPublicKey`, and initial `signCount` a later login needs. A credential key declaring COSE algorithm `-65535` (RSASSA-PKCS1-v1_5 with SHA-1) is refused unless `allowedAlgorithms` names it, since every signature that credential ever makes would use SHA-1. Anchoring the trust path has two routes: `opts.metadata` resolves the roots the authenticator's own model registered, and `opts.rootCertificates` pins roots directly, which is what anchors the formats FIDO MDS does not cover, Apple's authenticators and the Google hardware-attestation roots among them. `metadata` governs when both are given, and `anchoredTo` names every route that anchored the path, joined with `+` when more than one did: `"metadata"`, `"rootCertificates"`, and `"safetyNetRoots"` for the android-safetynet chain, which anchors through the roots that format requires whether or not either other route was asked for. It is `null` only when nothing anchored the path. `verifyMetadataBlob(blob, opts)` reads a FIDO Metadata Service (MDS v3) BLOB, the signed catalogue of registered authenticator models, verifying its JWS and chaining its signer to an operator-supplied FIDO root before the payload is parsed, with sequence-number rollback and `nextUpdate` freshness checks. Passing the result as `opts.metadata` to `verify` resolves the authenticator's registered attestation roots from its identifier and requires the trust path to fully validate to one of them, refusing an unlisted or revoked model. `metadataAnchors(entry, opts)` applies the same status gate for a caller anchoring the path themselves: a model the catalogue has disqualified registers no anchors. Both of the catalogue's key spaces are covered: an aaguid, and the attestation-certificate key identifiers a U2F authenticator is listed under instead. No FIDO root is bundled, there is no trust-on-first-use, and retrieving the BLOB is out of scope. Fail-closed with typed `webauthn/*` errors — `parseAttestationObject`, `verify`, `verifyMetadataBlob`, `metadataFor`, `metadataAnchors` |
|
|
293
|
-
| `pki.lint` | Certificate linting, the zlint or pkilint of JavaScript. `certificate(pem \| der \| parsed, opts)` walks a parsed certificate and emits graded advisory findings, each with a stable id, a severity (`fatal`, `error`, `warn`, `notice`), a source, a spec-clause citation, and a message, against the RFC 5280 profile, the post-quantum certificate profiles, and a representative CA/Browser Forum TLS BR subset: serial sign and size, validity ordering and the SC081v3 reducing validity schedule, keyCertSign coherence, extension criticality (basicConstraints, nameConstraints, policyConstraints and inhibitAnyPolicy must be critical, and keyUsage should be), nameConstraints CA-scope, unknown critical extensions, empty-subject SAN, SKI and AKI presence including the end-entity subjectKeyIdentifier, the six extensions a conforming CA must mark non-critical (reported by clause rather than as unrecognized) and the two it should (issuerAltName, cRLDistributionPoints), a policy mapping to or from anyPolicy, a unique identifier a conforming CA must not generate, a critical subjectAltName beside a non-empty subject, a critical extKeyUsage naming anyExtendedKeyUsage, a userNotice noticeRef, SAN required and CN-in-SAN, dNSName syntax, serverAuth EKU, weak keys, the CA/Browser Forum subscriber certificate profile of §7.1.2.7 (the extension presence and criticality table, the authorityInformationAccess accessMethod and accessLocation tables, basicConstraints cA and pathLenConstraint, certificatePolicies against anyPolicy and the exactly-one reserved identifier rule and the permitted-qualifier table, the forbidden extended key purposes, the two Key Usage tables that differ by key type, and the subjectAltName GeneralName table with its criticality rule in both directions), the CA/Browser Forum S/MIME BR subscriber profile of §7.1.2.3 (a) through (n) as `cabf-smime`, whose requirements follow the generation a certificate declares through its reserved policy identifier (the distribution-point and accessMethod URI scheme rules, the policy qualifier rules for an id-qt-cps URL and an id-qt-unotice explicitText and noticeRef, the key-usage table for the certificate's own key algorithm including a bit set past the nine named positions, the extended key purposes forbidden at every generation and the ones Strict alone forbids, the authorityKeyIdentifier field rules, a required mailbox in the subjectAltName as an rfc822Name or an id-on-SmtpUTF8Mailbox otherName, the criticality each extension must carry, the subjectDirectoryAttributes and Adobe extensions the Strict generation prohibits, the Legal Entity Identifier extensions keyed on the certificate type rather than the generation, and the Legacy generation retired on 15 July 2025), the CA/Browser Forum Code Signing BR subscriber profile of §7.1.2.3 as `cabf-cs`, whose rows follow the kind a certificate declares through one of the three reserved identifiers of §7.1.6.1 (the extension presence and criticality rules at the strengths this document states them, a HTTP URL required in the distribution points and in each accessMethod location, a critical keyUsage asserting digitalSignature with `keyCertSign` and `cRLSign` forbidden and every other bit discouraged, the extended key purpose each kind must carry with the critical extKeyUsage a timestamp certificate needs, the §7.1.6.4 exactly-one-identifier rule gated to 15 September 2026, the §6.3.2 ceilings of 39 months, 460 days and 135 months, and the §6.1.5.2 floors of a 3072-bit RSA modulus, NIST P-256, P-384 or P-521, or DSA parameters of 2048 bits with a 224- or 256-bit modulus length, and the §7.1.4.2 subject distinguished name rows: a required commonName, a prohibited domainComponent, a subject attribute made only of the metadata characters the clause names, a required organizationName and two-letter countryName, one of localityName and stateOrProvinceName, and on an EV certificate a businessCategory from the four strings the clause names, a jurisdictionCountryName and a serialNumber), the ETSI qualified-certificate profile of EN 319 412-5 as `etsi-qc` (a non-critical qcStatements extension, a QcType naming one and only one of the three purposes the clause defines, a QcPDS providing an https URL and, on an EU qualified certificate, a document in English and no more than one per language, plus the EN 319 412-1 semantics identifiers holding a subject serialNumber or organizationIdentifier to a three-character identity type reference, a two-character country code, a hyphen-minus and an identifier, with XG required of an LEI value and a name registration authority URI required of a locally defined reference), the Mozilla Root Store Policy as `mozilla-root`, which is named rather than detected because a root program's requirements apply by virtue of the store a certificate chains to (the §5.1 AlgorithmIdentifier encodings compared as DER, an RSA modulus of at least 2048 bits and a whole number of octets, a public exponent above 1, an EdDSA key only beside id-kp-emailProtection, the §5.1.3 SHA-1 prohibitions on their own dates, a serial greater than zero with a short magnitude reported as a warning, an extKeyUsage on every end entity without anyExtendedKeyUsage, and the §5.3 intermediate rules from 2019, which pass over a certificate issued in its own name), the Chrome Root Program Policy v1.8 as `chrome-root`, named on the same grounds (the §1.3.2 dedicated-hierarchy rules holding a subordinate CA certificate's extKeyUsage to id-kp-serverAuth with id-kp-clientAuth reported as a warning, scoped to the unexpired certificates the clause names by passing over a notAfter before 15 June 2026, the same rules over a subscriber certificate issued on or after 15 March 2027 where id-kp-serverAuth stands alone and an extKeyUsage naming id-kp-OCSPSigning and nothing else is a delegated OCSP responder rather than a subscriber, the §1.3.1.3 three-year subordinate CA validity ceiling, and the §1.3.1.2 root term limit, which reports a self-signed CA certificate whose validity runs past the removal date its own notBefore fixes and passes over a CA reissued in its own name whose authorityKeyIdentifier names a key other than its own subjectKeyIdentifier), the Microsoft Trusted Root Program requirements as `microsoft-root`, named on the same grounds (the §3.A.1 root commonName and the keyUsage that must be present, critical and set keyCertSign and cRLSign, the §3.A.3 term of eight to 25 years, the §3.A.5 revocation pointer and §3.A.8 separation of uses on an issuing CA, the §3.A.10 seventeen reserved policy identifiers on an end entity, the §3.A.14 exclusivity of id-kp-OCSPSigning, the §3.B signature and key table including its code signing column, and the §3.E.2 extended key usages the program enables on a root), the Apple Root Program Policy as `apple-root`, named on the same grounds (its Appendix A trust purposes read as extended key usage sets, the §1.5 root key floor of RSA 4096 or NIST P-384, the §1.7 subordinate CA rules gated to 1 August 2026 and 1 July 2027, the §2.3 rfc822Name an S/MIME subscriber needs from 1 February 2027, and the subscriber purpose scoping that binds when its permission expires on 1 July 2027), the post-quantum key-usage rules binding a certificate's keyUsage bits to its subject key type (ML-KEM under RFC 9935 §5, ML-DSA under RFC 9881 §5, and SLH-DSA under RFC 9909 §6 across both its pure and prehash identifiers) together with the ML-KEM encapsulation-key encoding and size, and the §4.2.1.4 certificate-policy user-notice rules (a VisibleString or BMPString explicitText, a notice past 200 characters, an empty notice, control characters, and a non-NFC UTF8String notice, each at the strength the clause states). Alone among these entries the data path never throws: hostile bytes return a `fatal` `lint/unparseable` finding carrying the strict parser's code, so a whole directory lints without a try/catch, and only config-time misuse throws a typed `LintError` — `certificate`, `crl` (the RFC 5280 §5 revocation-list profile: nextUpdate presence, update ordering, cRLNumber presence and its 20-octet ceiling, authorityKeyIdentifier presence, the criticality each profiled CRL and entry extension must carry, freshestCRL in a delta CRL, and unrecognized critical extensions), `ocsp` (the RFC 6960 response profile: an empty signature, each SingleResponse's update ordering and its relation to producedAt, an empty `certs` field, the extended revoked definition and the fixed shape of a revoked answer for a non-issued certificate, the list each extension belongs in, the criticality and value syntax of the CRL entry extensions a SingleResponse may carry, unrecognized critical extensions, the reasons unspecified and removeFromCRL, and two answers for one CertID; the RFC 5019 lightweight rows run on request), `csr` (the artifact a CA reads before it issues: an empty subject naming no identity, an empty subject whose subjectAltName is not critical, a request for an extension the issuer determines, a request asking for a CA certificate, a broken signing digest, and a challengePassword traveling with the request; `opts.profile: "cabf-tls"` adds the certificate profile's own commonName-in-SAN, dNSName syntax, SAN-required and key-strength rows, applied to what the request asks for, and they run only when named because a request carries no extKeyUsage. It does not check the request's signature, which is a cryptographic operation `pki.csr.verify` owns), `cms` (the RFC 5652 profile: a signing-time naming a year from 1950 to 2049 encoded as GeneralizedTime where §11.3 requires UTCTime, a signer digest the digestAlgorithms set does not list, a version 1 attribute certificate, and notices for a SignedData with no signers and for a detached signature), `tsp` (the RFC 3161 profile: a tsa hint naming a subject the token's own certificate does not carry, a serial wider than 160 bits, and a token stating no accuracy), `attrcert` (the RFC 5755 profile: the §4.3 criticality table, a critical extension the profile does not define, a Holder naming more than one option, and an issuerUniqueID), each short because the strict parser behind it already refuses most of what its document requires and those clauses arrive as `lint/unparseable` carrying the parser's own code, `rules`, `profiles` |
|
|
293
|
+
| `pki.lint` | Certificate linting, the zlint or pkilint of JavaScript. `certificate(pem \| der \| parsed, opts)` walks a parsed certificate and emits graded advisory findings, each with a stable id, a severity (`fatal`, `error`, `warn`, `notice`), a source, a spec-clause citation, and a message, against the RFC 5280 profile, the post-quantum certificate profiles, and a representative CA/Browser Forum TLS BR subset: serial sign and size, validity ordering and the SC081v3 reducing validity schedule, keyCertSign coherence, extension criticality (basicConstraints, nameConstraints, policyConstraints and inhibitAnyPolicy must be critical, and keyUsage should be), nameConstraints CA-scope, unknown critical extensions, empty-subject SAN, SKI and AKI presence including the end-entity subjectKeyIdentifier, the six extensions a conforming CA must mark non-critical (reported by clause rather than as unrecognized) and the two it should (issuerAltName, cRLDistributionPoints), a policy mapping to or from anyPolicy, a unique identifier a conforming CA must not generate, a critical subjectAltName beside a non-empty subject, a critical extKeyUsage naming anyExtendedKeyUsage, a userNotice noticeRef, SAN required and CN-in-SAN, dNSName syntax, serverAuth EKU, weak keys, the CA/Browser Forum subscriber certificate profile of §7.1.2.7 (the extension presence and criticality table, the authorityInformationAccess accessMethod and accessLocation tables, basicConstraints cA and pathLenConstraint, certificatePolicies against anyPolicy and the exactly-one reserved identifier rule and the permitted-qualifier table, the forbidden extended key purposes, the two Key Usage tables that differ by key type, and the subjectAltName GeneralName table with its criticality rule in both directions), the CA/Browser Forum S/MIME BR subscriber profile of §7.1.2.3 (a) through (n) as `cabf-smime`, whose requirements follow the generation a certificate declares through its reserved policy identifier (the distribution-point and accessMethod URI scheme rules, the policy qualifier rules for an id-qt-cps URL and an id-qt-unotice explicitText and noticeRef, the key-usage table for the certificate's own key algorithm including a bit set past the nine named positions, the extended key purposes forbidden at every generation and the ones Strict alone forbids, the authorityKeyIdentifier field rules, a required mailbox in the subjectAltName as an rfc822Name or an id-on-SmtpUTF8Mailbox otherName, the criticality each extension must carry, the subjectDirectoryAttributes and Adobe extensions the Strict generation prohibits, the Legal Entity Identifier extensions keyed on the certificate type rather than the generation, and the Legacy generation retired on 15 July 2025), the CA/Browser Forum Code Signing BR subscriber profile of §7.1.2.3 as `cabf-cs`, whose rows follow the kind a certificate declares through one of the three reserved identifiers of §7.1.6.1 (the extension presence and criticality rules at the strengths this document states them, a HTTP URL required in the distribution points and in each accessMethod location, a critical keyUsage asserting digitalSignature with `keyCertSign` and `cRLSign` forbidden and every other bit discouraged, the extended key purpose each kind must carry with the critical extKeyUsage a timestamp certificate needs, the §7.1.6.4 exactly-one-identifier rule gated to 15 September 2026, the §6.3.2 ceilings of 39 months, 460 days and 135 months, and the §6.1.5.2 floors of a 3072-bit RSA modulus, NIST P-256, P-384 or P-521, or DSA parameters of 2048 bits with a 224- or 256-bit modulus length, and the §7.1.4.2 subject distinguished name rows: a required commonName, a prohibited domainComponent, a subject attribute made only of the metadata characters the clause names, a required organizationName and two-letter countryName, one of localityName and stateOrProvinceName, and on an EV certificate a businessCategory from the four strings the clause names, a jurisdictionCountryName and a serialNumber), the ETSI qualified-certificate profile of EN 319 412-5 as `etsi-qc` (a non-critical qcStatements extension, a QcType naming one and only one of the three purposes the clause defines, a QcPDS providing an https URL and, on an EU qualified certificate, a document in English and no more than one per language, plus the EN 319 412-1 semantics identifiers holding a subject serialNumber or organizationIdentifier to a three-character identity type reference, a two-character country code, a hyphen-minus and an identifier, with XG required of an LEI value and a name registration authority URI required of a locally defined reference), the Mozilla Root Store Policy as `mozilla-root`, which is named rather than detected because a root program's requirements apply by virtue of the store a certificate chains to (the §5.1 AlgorithmIdentifier encodings compared as DER, an RSA modulus of at least 2048 bits and a whole number of octets, a public exponent above 1, an EdDSA key only beside id-kp-emailProtection, the §5.1.3 SHA-1 prohibitions on their own dates, a serial greater than zero with a short magnitude reported as a warning, an extKeyUsage on every end entity without anyExtendedKeyUsage, and the §5.3 intermediate rules from 2019, which pass over a certificate issued in its own name), the Chrome Root Program Policy v1.8 as `chrome-root`, named on the same grounds (the §1.3.2 dedicated-hierarchy rules holding a subordinate CA certificate's extKeyUsage to id-kp-serverAuth with id-kp-clientAuth reported as a warning, scoped to the unexpired certificates the clause names by passing over a notAfter before 15 June 2026, the same rules over a subscriber certificate issued on or after 15 March 2027 where id-kp-serverAuth stands alone and an extKeyUsage naming id-kp-OCSPSigning and nothing else is a delegated OCSP responder rather than a subscriber, the §1.3.1.3 three-year subordinate CA validity ceiling, and the §1.3.1.2 root term limit, which reports a self-signed CA certificate whose validity runs past the removal date its own notBefore fixes and passes over a CA reissued in its own name whose authorityKeyIdentifier names a key other than its own subjectKeyIdentifier), the Microsoft Trusted Root Program requirements as `microsoft-root`, named on the same grounds (the §3.A.1 root commonName and the keyUsage that must be present, critical and set keyCertSign and cRLSign, the §3.A.3 term of eight to 25 years, the §3.A.5 revocation pointer and §3.A.8 separation of uses on an issuing CA, the §3.A.10 seventeen reserved policy identifiers on an end entity, the §3.A.14 exclusivity of id-kp-OCSPSigning, the §3.B signature and key table including its code signing column, and the §3.E.2 extended key usages the program enables on a root), the Apple Root Program Policy as `apple-root`, named on the same grounds (its Appendix A trust purposes read as extended key usage sets, the §1.5 root key floor of RSA 4096 or NIST P-384, the §1.7 subordinate CA rules gated to 1 August 2026 and 1 July 2027, the §2.3 rfc822Name an S/MIME subscriber needs from 1 February 2027, and the subscriber purpose scoping that binds when its permission expires on 1 July 2027), the two algorithm-policy profiles, named for the same reason a root program's are (which policy a certificate is held to is the caller's assertion): `nist-pqc-transition` carries NIST IR 8547's two transitions, an error for a classical subject key or signature algorithm in a certificate issued from 2036 and a warning for a subject key at or below the 112-bit security strength issued from 2031, with the strength read off SP 800-57 Part 1 Rev 5 Table 2 and a composite signature passed over as the dual-algorithm operation the guidance endorses; and `cnsa-2.0` carries the suite profile of `draft-jenkins-cnsa2-pkix-profile-05` (ML-DSA-87 or ML-KEM-1024 as the subject public key, ML-DSA-87 as the signature, and the extension, criticality and key-usage rules each of the three certificate kinds carries, where the key-usage set follows the kind the subject key declares), the same signature rule reaching `crl` and `ocsp` under that name because the document states it once for all three, the post-quantum key-usage rules binding a certificate's keyUsage bits to its subject key type (ML-KEM under RFC 9935 §5, ML-DSA under RFC 9881 §5, and SLH-DSA under RFC 9909 §6 across both its pure and prehash identifiers) together with the ML-KEM encapsulation-key encoding and size, and the §4.2.1.4 certificate-policy user-notice rules (a VisibleString or BMPString explicitText, a notice past 200 characters, an empty notice, control characters, and a non-NFC UTF8String notice, each at the strength the clause states). Alone among these entries the data path never throws: hostile bytes return a `fatal` `lint/unparseable` finding carrying the strict parser's code, so a whole directory lints without a try/catch, and only config-time misuse throws a typed `LintError` — `certificate`, `crl` (the RFC 5280 §5 revocation-list profile: nextUpdate presence, update ordering, cRLNumber presence and its 20-octet ceiling, authorityKeyIdentifier presence, the criticality each profiled CRL and entry extension must carry, freshestCRL in a delta CRL, and unrecognized critical extensions), `ocsp` (the RFC 6960 response profile: an empty signature, each SingleResponse's update ordering and its relation to producedAt, an empty `certs` field, the extended revoked definition and the fixed shape of a revoked answer for a non-issued certificate, the list each extension belongs in, the criticality and value syntax of the CRL entry extensions a SingleResponse may carry, unrecognized critical extensions, the reasons unspecified and removeFromCRL, and two answers for one CertID; the RFC 5019 lightweight rows run on request), `csr` (the artifact a CA reads before it issues: an empty subject naming no identity, an empty subject whose subjectAltName is not critical, a request for an extension the issuer determines, a request asking for a CA certificate, a broken signing digest, and a challengePassword traveling with the request; `opts.profile: "cabf-tls"` adds the certificate profile's own commonName-in-SAN, dNSName syntax, SAN-required and key-strength rows, applied to what the request asks for, and they run only when named because a request carries no extKeyUsage. It does not check the request's signature, which is a cryptographic operation `pki.csr.verify` owns), `cms` (the RFC 5652 profile: a signing-time naming a year from 1950 to 2049 encoded as GeneralizedTime where §11.3 requires UTCTime, a signer digest the digestAlgorithms set does not list, a version 1 attribute certificate, and notices for a SignedData with no signers and for a detached signature), `tsp` (the RFC 3161 profile: a tsa hint naming a subject the token's own certificate does not carry, a serial wider than 160 bits, and a token stating no accuracy), `attrcert` (the RFC 5755 profile: the §4.3 criticality table, a critical extension the profile does not define, a Holder naming more than one option, and an issuerUniqueID), each short because the strict parser behind it already refuses most of what its document requires and those clauses arrive as `lint/unparseable` carrying the parser's own code, `rules`, `profiles` |
|
|
294
294
|
| `pki.C` / `pki.constants` | Version-stable constants: the functional scale helpers `C.TIME.*` and `C.BYTES.*`, the codec `LIMITS`, and `version` |
|
|
295
295
|
| `pki.errors` | The `PkiError` taxonomy — `defineClass` plus `ConstantsError`, `Asn1Error`, `OidError`, `PemError`, `CertificateError`, `CrlError`, `CsrError`, `Pkcs8Error`, `CmsError`, `OcspError`, `TspError`, `AttrCertError`, `CrmfError`, `Pkcs12Error`, `CmpError`, `PathError`, `CtError`, `JoseError`, `AcmeError`, `WebauthnError`, and `LintError`, each carrying a stable `code` in `domain/reason` form |
|
|
296
296
|
| `pki` CLI | `pki version`, `pki oid <dotted\|name>`, `pki parse <cert>`, `pki inspect <cert>`, `pki lint <cert\|crl\|ocsp-response>`, `pki convert <file> --to der\|pem`, `pki verify <cert>... --anchor <cert>`, `pki sign <file> --cert <c> --key <k>` |
|
package/index.js
CHANGED
|
@@ -224,7 +224,20 @@ module.exports = {
|
|
|
224
224
|
// OID registry, naming extension/algorithm OIDs OpenSSL shows only as raw bytes.
|
|
225
225
|
// Pure, no OpenSSL dependency; best-effort (a bad extension falls back to hex).
|
|
226
226
|
inspect: inspect,
|
|
227
|
-
lint
|
|
227
|
+
// `lint` is named member by member rather than passed through, because the module also exports the
|
|
228
|
+
// build-time gate the authoring verbs call and the two readers its conformance vectors use. Those
|
|
229
|
+
// are internal plumbing, so they stay off the public namespace.
|
|
230
|
+
lint: {
|
|
231
|
+
certificate: lint.certificate,
|
|
232
|
+
csr: lint.csr,
|
|
233
|
+
crl: lint.crl,
|
|
234
|
+
ocsp: lint.ocsp,
|
|
235
|
+
cms: lint.cms,
|
|
236
|
+
tsp: lint.tsp,
|
|
237
|
+
attrcert: lint.attrcert,
|
|
238
|
+
rules: lint.rules,
|
|
239
|
+
profiles: lint.profiles,
|
|
240
|
+
},
|
|
228
241
|
// `webauthn` verifies a W3C WebAuthn / passkey attestation -- pki.webauthn.verify
|
|
229
242
|
// checks the attestation-statement signature + each format's structural bindings
|
|
230
243
|
// (packed / tpm / android-key / apple / fido-u2f / none) and surfaces the x5c chain
|
package/lib/composite-sig.js
CHANGED
|
@@ -160,6 +160,11 @@ function _signTradComponent(trad, pkcs8, mprime) {
|
|
|
160
160
|
}
|
|
161
161
|
|
|
162
162
|
module.exports = {
|
|
163
|
+
/** @internal The FIPS 204 public-key and signature sizes of each ML-DSA parameter set, keyed by the
|
|
164
|
+
* name the engine knows it by and carrying the identifier the registry names it with. The composite
|
|
165
|
+
* arms are built from it, and a caller holding a certificate to those sizes reads them here rather
|
|
166
|
+
* than restating a figure that must agree with the one the arms use. */
|
|
167
|
+
MLDSA_COMPONENT: MLDSA_COMPONENT,
|
|
163
168
|
COMPOSITE_ALGS: COMPOSITE_ALGS,
|
|
164
169
|
compositeVerify: compositeVerify,
|
|
165
170
|
resolveCompositeDescriptor: resolveCompositeDescriptor,
|
package/lib/crl-sign.js
CHANGED
|
@@ -32,6 +32,7 @@ var pkiBuild = require("./pki-build");
|
|
|
32
32
|
var constants = require("./constants");
|
|
33
33
|
require("./path-validate");
|
|
34
34
|
var crlVerify = require("./crl-verify");
|
|
35
|
+
var lint = require("./lint");
|
|
35
36
|
|
|
36
37
|
var CrlError = frameworkError.CrlError;
|
|
37
38
|
var NS = pkix.makeNS("crl", CrlError, oid);
|
|
@@ -85,7 +86,11 @@ var KNOWN_SPEC_KEYS_ISSUER_NAMED = intrinsic.assign(intrinsic.create(null), {
|
|
|
85
86
|
});
|
|
86
87
|
var KNOWN_ISSUER_CERT_KEYS = intrinsic.assign(intrinsic.create(null), { key: 1, cert: 1 });
|
|
87
88
|
var KNOWN_ISSUER_EXPLICIT_KEYS = intrinsic.assign(intrinsic.create(null), { key: 1, name: 1, publicKey: 1 });
|
|
88
|
-
var KNOWN_SIGN_OPTS = intrinsic.assign(intrinsic.create(null), { digestAlgorithm: 1, pem: 1, pss: 1 });
|
|
89
|
+
var KNOWN_SIGN_OPTS = intrinsic.assign(intrinsic.create(null), { digestAlgorithm: 1, pem: 1, pss: 1, profile: 1 });
|
|
90
|
+
|
|
91
|
+
/** @internal The signature the build-time gate lints against, standing in for one that does not exist
|
|
92
|
+
* until the key is used. It is non-empty so the gate is not answering a rule about its own placeholder. */
|
|
93
|
+
var GATE_PLACEHOLDER_SIG = intrinsic.bufferAlloc(64, 0xff);
|
|
89
94
|
|
|
90
95
|
var KNOWN_IDP_KEYS = intrinsic.assign(intrinsic.create(null), { fullName: 1, onlyContainsUserCerts: 1, onlyContainsCACerts: 1, onlyContainsAttributeCerts: 1, indirectCRL: 1 });
|
|
91
96
|
|
|
@@ -384,6 +389,7 @@ function _sign(spec, issuer, opts) {
|
|
|
384
389
|
: "explicit form; the issuer takes { key, name, publicKey }, or { key, cert } to take both from a certificate");
|
|
385
390
|
});
|
|
386
391
|
guard.identifier.assertKnownKeys(opts, KNOWN_SIGN_OPTS, _err, "crl/bad-input", "pki.crl.sign has an unknown option ");
|
|
392
|
+
lint.assertKnownBuildProfile("crl", opts.profile, _err, "crl/bad-input");
|
|
387
393
|
if (issuer.key == null) throw _err("crl/bad-input", "a signing key (issuer.key, a WebCrypto CryptoKey or a PKCS#8 private key DER/PEM) is required");
|
|
388
394
|
|
|
389
395
|
var issuerDer, issuerSpki, issuerCert = null;
|
|
@@ -426,6 +432,9 @@ function _sign(spec, issuer, opts) {
|
|
|
426
432
|
if (revoked.entries.length) tbsChildren.push(b.sequence(revoked.entries));
|
|
427
433
|
if (crlExts.length) tbsChildren.push(b.explicit(0, b.sequence(crlExts)));
|
|
428
434
|
var tbsDer = b.sequence(tbsChildren);
|
|
435
|
+
lint.assertBuildClean("crl",
|
|
436
|
+
b.sequence([tbsDer, scheme.sigAlgId, b.bitString(GATE_PLACEHOLDER_SIG, 0)]),
|
|
437
|
+
opts.profile, _err, "crl/profile-violation");
|
|
429
438
|
|
|
430
439
|
return signScheme.signOverTbs(scheme, issuer.key, tbsDer, _signE).then(function (sig) {
|
|
431
440
|
return Promise.resolve(_assertSignatureVerifies(tbsDer, sig, issuerSpki, scheme)).then(function () {
|
|
@@ -474,10 +483,18 @@ function _sign(spec, issuer, opts) {
|
|
|
474
483
|
* key before return. A violation throws a typed `CrlError`; where the spec carries raw DER (an issuer
|
|
475
484
|
* `Name` Buffer or a pre-encoded `Extension`), a malformed leaf inside those bytes throws `Asn1Error`.
|
|
476
485
|
*
|
|
486
|
+
* Before the key is used, the CRL the spec describes is linted against the RFC 5280 section 5 profile
|
|
487
|
+
* and refused with `crl/profile-violation` if any rule grades it `error`, naming the rule and its
|
|
488
|
+
* clause. A `crlNumber` and a `nextUpdate` are what a spec most often lacks, and sec. 5.2.3 and
|
|
489
|
+
* sec. 5.1.2.5 require both of a conforming CRL issuer.
|
|
490
|
+
*
|
|
477
491
|
* @opts
|
|
478
492
|
* - `pem` (boolean) -- return a PEM `X509 CRL` string instead of DER.
|
|
479
493
|
* - `pss` (boolean) -- sign an RSA key with RSASSA-PSS instead of PKCS#1 v1.5.
|
|
480
494
|
* - `digestAlgorithm` (string) -- override the message digest where the algorithm permits a choice.
|
|
495
|
+
* - `profile` (string) -- a second lint profile to hold the CRL to beside RFC 5280 section 5, named
|
|
496
|
+
* from `pki.lint.profiles()`. `"none"` runs no rules at all and emits what the spec describes,
|
|
497
|
+
* which is how a deliberately non-conforming CRL is produced.
|
|
481
498
|
* @example
|
|
482
499
|
* var pair = await pki.key.generate("Ed25519");
|
|
483
500
|
* var signerKeyPkcs8 = await pki.key.export(pair.privateKey);
|
|
@@ -556,7 +573,8 @@ function _issuerMaySign(parsed, cert) {
|
|
|
556
573
|
* var signerCertDer = await pki.x509.sign({ subject: "Issuing CA", subjectPublicKey: signerSpki,
|
|
557
574
|
* notBefore: new Date("2026-01-01T00:00:00Z"), notAfter: new Date("2036-01-01T00:00:00Z"),
|
|
558
575
|
* extensions: { basicConstraints: { cA: true }, keyUsage: ["keyCertSign", "cRLSign"] } }, { key: signerKeyPkcs8 });
|
|
559
|
-
* var crlDer = await pki.crl.sign({ thisUpdate: new Date("2026-01-01T00:00:00Z"),
|
|
576
|
+
* var crlDer = await pki.crl.sign({ thisUpdate: new Date("2026-01-01T00:00:00Z"),
|
|
577
|
+
* nextUpdate: new Date("2026-02-01T00:00:00Z"), crlNumber: 1n, revoked: [] },
|
|
560
578
|
* { cert: signerCertDer, key: signerKeyPkcs8 });
|
|
561
579
|
* var res = await pki.crl.verify(crlDer, { publicKey: signerSpki }); // { valid, signatureValid, issuerMaySign, issuer }
|
|
562
580
|
*/
|
|
@@ -640,7 +658,8 @@ function _serialHexOf(serial) {
|
|
|
640
658
|
* var signerCertDer = await pki.x509.sign({ subject: "Issuing CA", subjectPublicKey: await pki.key.export(pair.publicKey),
|
|
641
659
|
* notBefore: new Date("2026-01-01T00:00:00Z"), notAfter: new Date("2036-01-01T00:00:00Z"),
|
|
642
660
|
* extensions: { basicConstraints: { cA: true }, keyUsage: ["keyCertSign", "cRLSign"] } }, { key: signerKeyPkcs8 });
|
|
643
|
-
* var crlDer = await pki.crl.sign({ thisUpdate: new Date("2026-01-01T00:00:00Z"),
|
|
661
|
+
* var crlDer = await pki.crl.sign({ thisUpdate: new Date("2026-01-01T00:00:00Z"),
|
|
662
|
+
* nextUpdate: new Date("2026-02-01T00:00:00Z"), crlNumber: 1n,
|
|
644
663
|
* revoked: [{ serialNumber: 0x1234n, revocationDate: new Date("2026-01-15T00:00:00Z") }] },
|
|
645
664
|
* { cert: signerCertDer, key: signerKeyPkcs8 });
|
|
646
665
|
* pki.crl.isRevoked(crlDer, 0x1234n) ? "revoked" : "not listed";
|
package/lib/csr-sign.js
CHANGED
|
@@ -27,13 +27,18 @@ var frameworkError = require("./framework-error");
|
|
|
27
27
|
var guard = require("./guard-all");
|
|
28
28
|
require("./path-validate");
|
|
29
29
|
var csrVerify = require("./csr-verify");
|
|
30
|
+
var lint = require("./lint");
|
|
30
31
|
|
|
31
32
|
var CsrError = frameworkError.CsrError;
|
|
32
33
|
var KNOWN_SPEC_KEYS = Object.assign(Object.create(null), { subject: 1, subjectPublicKey: 1, extensionRequest: 1, challengePassword: 1, attributes: 1 });
|
|
33
|
-
/** @internal The
|
|
34
|
+
/** @internal The four this verb reads, which are the four `pki.x509.sign` reads. A name outside
|
|
34
35
|
* them was accepted and dropped, so asking for PEM and misspelling the option returned DER and
|
|
35
36
|
* reported nothing. */
|
|
36
|
-
var KNOWN_SIGN_OPTS = Object.assign(Object.create(null), { digestAlgorithm: 1, pem: 1, pss: 1 });
|
|
37
|
+
var KNOWN_SIGN_OPTS = Object.assign(Object.create(null), { digestAlgorithm: 1, pem: 1, pss: 1, profile: 1 });
|
|
38
|
+
|
|
39
|
+
/** @internal The signature the build-time gate lints against, standing in for one that does not exist
|
|
40
|
+
* until the key is used. It is non-empty so the gate is not answering a rule about its own placeholder. */
|
|
41
|
+
var GATE_PLACEHOLDER_SIG = Buffer.alloc(64, 0xff);
|
|
37
42
|
var KNOWN_KEY_WRAPPER_KEYS = Object.assign(Object.create(null), { key: 1 });
|
|
38
43
|
var b = asn1.build;
|
|
39
44
|
function _err(code, message, cause) { return new CsrError(code, message, cause); }
|
|
@@ -86,10 +91,16 @@ function _challengePassword(pw) {
|
|
|
86
91
|
* Buffer, a pre-encoded requested `Extension` or `Attribute`) a malformed leaf inside those bytes
|
|
87
92
|
* throws `Asn1Error` instead. Certificate-request parsing is `pki.schema.csr.parse`.
|
|
88
93
|
*
|
|
94
|
+
* Before the key is used, the request the spec describes is linted against the RFC 2986 profile and
|
|
95
|
+
* refused with `csr/profile-violation` if any rule grades it `error`, naming the rule and its clause.
|
|
96
|
+
*
|
|
89
97
|
* @opts
|
|
90
98
|
* - `pem` (boolean) -- return a PEM `CERTIFICATE REQUEST` string instead of DER.
|
|
91
99
|
* - `pss` (boolean) -- sign an RSA key with RSASSA-PSS instead of PKCS#1 v1.5.
|
|
92
100
|
* - `digestAlgorithm` (string) -- override the message digest where the algorithm permits a choice.
|
|
101
|
+
* - `profile` (string) -- a second lint profile to hold the request to beside RFC 2986, named from
|
|
102
|
+
* `pki.lint.profiles()`. `"none"` runs no rules at all and emits what the spec describes, which is
|
|
103
|
+
* how a deliberately non-conforming request is produced.
|
|
93
104
|
* @example
|
|
94
105
|
* var pair = await pki.key.generate("Ed25519");
|
|
95
106
|
* var signerSpki = await pki.key.export(pair.publicKey);
|
|
@@ -111,6 +122,7 @@ function _sign(spec, key, opts) {
|
|
|
111
122
|
if (!spec || typeof spec !== "object" || Buffer.isBuffer(spec)) throw _err("csr/bad-input", "the certification-request spec must be an object");
|
|
112
123
|
guard.identifier.assertKnownKeys(spec, KNOWN_SPEC_KEYS, _err, "csr/bad-input", "unknown spec field ");
|
|
113
124
|
guard.identifier.assertKnownKeys(opts, KNOWN_SIGN_OPTS, _err, "csr/bad-input", "pki.csr.sign has an unknown option ");
|
|
125
|
+
lint.assertKnownBuildProfile("csr", opts.profile, _err, "csr/bad-input");
|
|
114
126
|
var wrapped = key && typeof key === "object" && !Buffer.isBuffer(key) && !(key instanceof Uint8Array) && key.type == null && "key" in key;
|
|
115
127
|
if (wrapped) guard.identifier.assertKnownKeys(key, KNOWN_KEY_WRAPPER_KEYS, _err, "csr/bad-input", "unknown field in the { key } wrapper (a signing option belongs in the third argument): ");
|
|
116
128
|
var signingKey = wrapped ? key.key : key;
|
|
@@ -151,6 +163,9 @@ function _sign(spec, key, opts) {
|
|
|
151
163
|
var scheme = signScheme.resolveSignScheme(_b.certLikeFromSpki(subjectSpki), { combinedRsaSig: true, pss: opts.pss, digestAlgorithm: opts.digestAlgorithm }, true, _signE);
|
|
152
164
|
|
|
153
165
|
var criDer = b.sequence([b.integer(0n), subjectDer, b.raw(subjectSpki), _implicitSetOf0(attrs)]);
|
|
166
|
+
lint.assertBuildClean("csr",
|
|
167
|
+
b.sequence([criDer, scheme.sigAlgId, b.bitString(GATE_PLACEHOLDER_SIG, 0)]),
|
|
168
|
+
opts.profile, _err, "csr/profile-violation");
|
|
154
169
|
|
|
155
170
|
return signScheme.signOverTbs(scheme, signingKey, criDer, _signE).then(function (sig) {
|
|
156
171
|
return Promise.resolve(_b.assertSignatureVerifies(criDer, sig, subjectSpki, scheme)).then(function () {
|
package/lib/http-retry-after.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// @internal
|
|
5
5
|
|
|
6
6
|
var constants = require("./constants");
|
|
7
|
+
var guard = require("./guard-all");
|
|
7
8
|
|
|
8
9
|
var MAX_RETRY_AFTER_SECONDS = constants.TIME.days(365) / constants.TIME.seconds(1);
|
|
9
10
|
|
|
@@ -28,12 +29,27 @@ function _isAllDigits(s) {
|
|
|
28
29
|
return true;
|
|
29
30
|
}
|
|
30
31
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
32
|
+
/** @internal RFC 7231 sec. 7.1.1.1: a recipient "MUST interpret a timestamp that appears to be more
|
|
33
|
+
* than 50 years in the future as representing the most recent year in the past that had the same last
|
|
34
|
+
* two digits". The reading therefore depends on when the value is received, and a caller that does not
|
|
35
|
+
* say when that was is receiving it now. A fixed cutoff instead is this rule evaluated once, for the
|
|
36
|
+
* year the cutoff was chosen in, and it misreads a widening band of two-digit years for every year
|
|
37
|
+
* that passes after it.
|
|
38
|
+
* THE CLAUSE COMPARES TIMESTAMPS, so this compares timestamps, which is why it runs once the month, day
|
|
39
|
+
* and time are read. A comparison of years alone reads a timestamp in the fiftieth year ahead as inside
|
|
40
|
+
* the window whatever its month: received on 28 September 2026, `31-Dec-76` is fifty years and three
|
|
41
|
+
* months ahead, which is more than fifty, and names 1976. */
|
|
42
|
+
function _rfc850Year(yy, mon, day, hh, mi, ss, refMs) {
|
|
43
|
+
var ref = (typeof refMs === "number" && isFinite(refMs)) ? refMs : Date.now();
|
|
44
|
+
var refDate = new Date(ref);
|
|
45
|
+
var refInstant = guard.time.instantOf(refDate);
|
|
46
|
+
if (isNaN(refInstant)) return yy + (yy < 70 ? 2000 : 1900);
|
|
47
|
+
var full = Math.floor(refDate.getUTCFullYear() / 100) * 100 + yy;
|
|
48
|
+
var horizon = new Date(refInstant);
|
|
49
|
+
horizon.setUTCFullYear(horizon.getUTCFullYear() + 50);
|
|
50
|
+
var horizonInstant = guard.time.instantOf(horizon);
|
|
51
|
+
if (isNaN(horizonInstant)) return full;
|
|
52
|
+
return Date.UTC(full, mon, day, hh, mi, ss) > horizonInstant ? full - 100 : full;
|
|
37
53
|
}
|
|
38
54
|
|
|
39
55
|
function _scanImf(s) {
|
|
@@ -52,7 +68,12 @@ function _scanRfc850(s, refMs) {
|
|
|
52
68
|
var mo = _monthAt(s, p); if (!mo || s.charAt(p + 3) !== "-") return null; p += 4;
|
|
53
69
|
var yy = _digits2(s, p); if (yy < 0 || s.charAt(p + 2) !== " ") return null; p += 3;
|
|
54
70
|
var t = _timeAt(s, p); if (!t || s.slice(t.next, t.next + 4) !== " GMT" || t.next + 4 !== s.length) return null;
|
|
55
|
-
|
|
71
|
+
/** @internal The century is resolved once the whole timestamp is read, since the clause compares the
|
|
72
|
+
* timestamp rather than its year. A month the calendar does not hold is refused by the round-trip
|
|
73
|
+
* check in `httpDateMs`, which reads the resolved year this returns. */
|
|
74
|
+
var mon = MONTHS.indexOf(mo);
|
|
75
|
+
var year = _rfc850Year(yy, mon, dd, t.hh, t.mi, t.ss, refMs);
|
|
76
|
+
return { day: dd, monName: mo, year: year, hh: t.hh, mi: t.mi, ss: t.ss };
|
|
56
77
|
}
|
|
57
78
|
function _scanAsctime(s) {
|
|
58
79
|
var p = _matchName(s, 0, DOW_SHORT);
|
package/lib/inspect.js
CHANGED
|
@@ -648,8 +648,9 @@ function _crlExtension(ext, pad) {
|
|
|
648
648
|
* var key = await pki.key.export(pair.privateKey);
|
|
649
649
|
* var caCert = await pki.x509.sign({ subject: "Issuing CA", subjectPublicKey: await pki.key.export(pair.publicKey),
|
|
650
650
|
* notBefore: new Date("2026-01-01T00:00:00Z"), notAfter: new Date("2036-01-01T00:00:00Z"),
|
|
651
|
-
* extensions: { basicConstraints: { cA: true }, keyUsage: ["cRLSign"] } }, { key: key });
|
|
652
|
-
* var crlDer = await pki.crl.sign({ thisUpdate: new Date("2026-01-01T00:00:00Z"),
|
|
651
|
+
* extensions: { basicConstraints: { cA: true }, keyUsage: ["keyCertSign", "cRLSign"] } }, { key: key });
|
|
652
|
+
* var crlDer = await pki.crl.sign({ thisUpdate: new Date("2026-01-01T00:00:00Z"),
|
|
653
|
+
* nextUpdate: new Date("2026-02-01T00:00:00Z"), crlNumber: 1n, revoked: [] },
|
|
653
654
|
* { cert: caCert, key: key });
|
|
654
655
|
* pki.inspect.crl(crlDer).split("\n")[0]; // "Certificate Revocation List (CRL):"
|
|
655
656
|
*/
|