@blamejs/pki 0.7.14 → 0.7.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +1 -1
- package/lib/pki-build.js +70 -0
- package/lib/x509-sign.js +20 -3
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,18 @@ All notable changes to `@blamejs/pki` are documented here. The format
|
|
|
4
4
|
follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
|
|
5
5
|
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
6
|
|
|
7
|
+
## v0.7.15 — 2026-09-11
|
|
8
|
+
|
|
9
|
+
Name constraints can be issued from a plain spec.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- extensions.nameConstraints takes { permitted, excluded }, with at least one side present, on pki.x509.sign and on the pki.csr.sign extensionRequest object. Each entry names one GeneralName form: { dNSName: ".example.com" }, { rfc822Name: "example.com" }, { uniformResourceIdentifier: ".example.com" }, { directoryName: [{ commonName: "Sub" }] }, or { iPAddress: buf } where buf is an address followed by its mask, 8 octets for IPv4 and 32 for IPv6. A base names a namespace rather than a subject, so it may carry a leading dot and is held to the rule for a constraint base, the same rule pki.trust.anchor applies to the subtrees it seeds. A bare string is refused, because the name form decides which namespace is constrained. The extension is emitted critical, which RFC 5280 section 4.2.1.10 requires. A subtree naming neither direction, an empty list, or a base that describes no namespace is refused with x509/bad-input or csr/bad-input. The constraint a certificate carries is enforced by OpenSSL as well as by pki.path.validate, checked in the release gates.
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- pki.x509.sign refuses a nameConstraints extension on a certificate that is not a CA. RFC 5280 section 4.2.1.10 states the extension is used only in a CA certificate, and pki.lint.certificate already graded such a certificate error as lint/rfc5280/name-constraints-not-ca; the signer emitted it anyway when the extension arrived as pre-encoded DER in the extensions array. A name constraint on an end-entity certificate restricts nothing, so a caller reading it as a restriction was reading one that no validator would apply. Supply it on a certificate whose basicConstraints sets cA true.
|
|
18
|
+
|
|
7
19
|
## v0.7.14 — 2026-09-11
|
|
8
20
|
|
|
9
21
|
Every option a verify verb decides with is taken once.
|
package/README.md
CHANGED
|
@@ -231,7 +231,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
|
|
|
231
231
|
| `pki.schema.cmc` | Decode CMC messages (RFC 5272 as updated by RFC 6402): 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` |
|
|
232
232
|
| `pki.schema.engine` | The declarative ASN.1 structure-schema engine every format parser composes — `walk`, `encode`, `embeddedDer`, and the schema combinators |
|
|
233
233
|
| `pki.path` | Certification-path validation (RFC 5280 §6). `validate` runs the §6.1 state machine over an ordered path and a trust anchor: signature chaining across RSA, ECDSA, EdDSA, ML-DSA, SLH-DSA and hybrid composite ML-DSA (a composite is accepted only when both its post-quantum and traditional components verify), validity windows, name chaining, basic constraints and path length, key usage, name constraints, and the certificate-policy tree. It returns a structured verdict with per-check reason codes and enforces a `pki.trust` anchor's per-purpose distrust-after dates and delegator purposes through `checkPurpose` — an anchor that carries either one with no purpose named to select by is refused as a configuration fault rather than validated as though it carried none. The verdict says what was established. `revocationChecked` takes the weakest outcome on the path: `false` with no checker supplied, `"determined"` when every certificate got an explicit good or revoked answer, `"waived"` when `softFail` turned an undetermined one into a pass, and `"undetermined"` when one could not be answered at all — which includes a checker that throws, a fault `softFail` does not waive because `softFail` opts into an undetermined answer, not into a broken checker. `anchorConstraints` names the purpose the anchor was judged under and whether each of its two constraints applied. `crlChecker` supplies CRL-based revocation, covering partitioned and sharded CRLs, whose §6.3.3 Distribution Point ↔ IDP correspondence lets corresponding shards accumulate reason coverage until all eight revocation reasons are covered, and delta CRLs, merged onto the complete CRL they may be combined with (§5.2.4) so a held certificate its delta releases reads good, while a delta that merges with nothing still reports what it lists and still withholds good. `ocspChecker` supplies OCSP-based revocation (RFC 6960: CertID binding, responder authorization, signature, currency) over the same pluggable hook. `build(leaf, opts)` is the discovering complement (RFC 4158): from a leaf, an untrusted pool of candidate CA certificates, and a trust store, it finds the ordered leaf-to-anchor path `validate` accepts, using name chaining plus the RFC 4158 §3.5 sort hints (an AKI/SKI match, an anchor-adjacent issuer, CA plus keyCertSign, validity at the check time — ordering hints, never filters), a depth-first search with backtracking so the first accepted path wins, and a bounded search (chain-length cap, candidate-expansion cap, identity-tuple visited set) so a cross-certificate cycle or Bridge-CA fan-out terminates deterministically. Every accept flows through `validate`, and its verdict is cross-checked against `openssl verify`. Opt-in AIA `caIssuers` fetching (`opts.fetchAia: true`) discovers a missing intermediate from a certificate's Authority Information Access URL (§4.2.2.1) over `pki.transport`, triggered only on a pool miss and bounded against SSRF and amplification: HTTPS only, a total fetch budget that caps fetching silently rather than throwing, a per-cert URL cap, a build-wide URL dedupe, a response-size and certificate-count cap, no redirect following, and every fault a silent skip. The TLS trust (`opts.tls`) stays distinct from the PKI `trustAnchors`, and every fetched certificate remains untrusted pool material that still flows through `validate` (never a trust anchor). It is off by default, so the default build is byte-identical offline. An `opts.direction` of `"reverse"` searches from a trust anchor toward the leaf (RFC 4158 §3.1), narrower when the anchor set is small and the leaf's issuer options fan out, and `"auto"` picks the direction by first-hop fan-out; reverse building reuses the same pool, visited set, caps, and `validate` gate, so the direction changes only search order, and the anchor is excluded from the returned path. Reverse building is pool-only and does not combine with `fetchAia`. When `opts.userInitialPolicySet` names acceptable certificate-policy OIDs and more than one path validates, build returns the accepted path whose user-constrained policy set best satisfies that set (RFC 4158 §4) rather than the first accepted path, the ranking bounded by the same candidate cap and a malformed set refused with `path/bad-input`; an `anyPolicy` entry is unconstrained and returns the first accepted path. In a mesh of cross-certified domains, where many candidates chain by name to the same place, a candidate is ranked by how many leading relative distinguished names it shares with the name the search is heading for (§3.5.16 and the §3.5.19 reverse method), so a certificate in the target's own domain is tried before one from a cross-certified domain, and forward building sorts a candidate under every candidate that can complete the path when its path length constraint cannot cover the certificates already below it (§3.5.7), an ordering that outranks the other hints rather than competing with them. No candidate is removed and an unbounded search still reaches every path the pool holds; a bounded one spends `maxCandidatesConsidered` on whichever branches the order steers it to. Pure and re-entrant — `validate`, `build`, `crlChecker`, `ocspChecker` |
|
|
234
|
-
| `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. `randomSerial()` draws the same 20-octet CSPRNG serial the signer uses when the spec names none, so a serial can be reserved or logged before the certificate is issued. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key), subject alternative names,
|
|
234
|
+
| `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. `randomSerial()` draws the same 20-octet CSPRNG serial the signer uses when the spec names none, so a serial can be reserved or logged before the certificate is issued. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key), subject alternative names, certificate policies, and name constraints from the spec, taking any other extension 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. Parsing stays at `pki.schema.x509.parse` — `sign` |
|
|
235
235
|
| `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
|
|
236
236
|
| `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
|
|
237
237
|
| `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named. `pop.method: 'agreeMAC'` completes the four: `pop.key` is the requester's finite-field Diffie-Hellman private key, as a PKCS#8 DER, a PEM `PRIVATE KEY` block or a `KeyObject`, and `pop.caCert` the authority's certificate it already holds; the two agree a static secret (RFC 2875 sec. 3), and the key derived from it MACs the DER `certReq` under `id-dhPop-static-HMAC-SHA1`. Either key may name its group in the PKCS#3 or the X9.42 encoding. `pop.key` must be the private half of `certTemplate.publicKey`, and the template must name both a subject and a public key. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
|
package/lib/pki-build.js
CHANGED
|
@@ -24,6 +24,8 @@ var _String = intrinsic.String;
|
|
|
24
24
|
var _objectKeys = intrinsic.keys;
|
|
25
25
|
var _isBufferChk = intrinsic.isBuffer;
|
|
26
26
|
var _stringify = intrinsic.stringify;
|
|
27
|
+
var _mapIntrinsic = intrinsic.map;
|
|
28
|
+
var _bufferConcatIntrinsic = intrinsic.bufferConcat;
|
|
27
29
|
|
|
28
30
|
function _isAlphaCode(c) { return (c >= 65 && c <= 90) || (c >= 97 && c <= 122); }
|
|
29
31
|
function _isDigitCode(c) { return c >= 48 && c <= 57; }
|
|
@@ -284,6 +286,13 @@ var CERT_FIXED_CRITICALITY = intrinsic.create(null);
|
|
|
284
286
|
CERT_FIXED_CRITICALITY[oid.byName(r[0])] = { critical: r[1], citation: r[2] };
|
|
285
287
|
});
|
|
286
288
|
|
|
289
|
+
var NC_KEYS = intrinsic.assign(intrinsic.create(null), { permitted: 1, excluded: 1 });
|
|
290
|
+
var NC_FORM_TAG = intrinsic.assign(intrinsic.create(null), {
|
|
291
|
+
rfc822Name: 1, dNSName: 2, directoryName: 4, uniformResourceIdentifier: 6, uri: 6, iPAddress: 7,
|
|
292
|
+
});
|
|
293
|
+
/** @internal permittedSubtrees is [0] and excludedSubtrees is [1], in that order. */
|
|
294
|
+
function _forEachNcSide(fn) { fn("permitted", 0); fn("excluded", 1); }
|
|
295
|
+
|
|
287
296
|
function makeBuilder(ctx) {
|
|
288
297
|
var ErrorClass = ctx.ErrorClass, O = ctx.O, NS = ctx.NS;
|
|
289
298
|
var NAME_SCHEMA = ctx.NAME_SCHEMA, SPKI_SCHEMA = ctx.SPKI_SCHEMA;
|
|
@@ -446,6 +455,63 @@ function makeBuilder(ctx) {
|
|
|
446
455
|
return b.contextConstructed(implicitTag, Buffer.concat(members));
|
|
447
456
|
}
|
|
448
457
|
function extSan(entries) { return encodeGeneralNames(entries); }
|
|
458
|
+
/** @internal One GeneralSubtree (RFC 5280 sec. 4.2.1.10). Within this profile minimum is 0 and
|
|
459
|
+
* maximum is absent, so a subtree is its base alone. A base names a NAMESPACE rather than a
|
|
460
|
+
* subject, so it is held to the constraint-base rule: it may carry a leading dot, and an
|
|
461
|
+
* iPAddress base is an address followed by its mask. */
|
|
462
|
+
function constraintSubtree(entry, where, idx) {
|
|
463
|
+
var who = "nameConstraints." + where + " entry " + idx;
|
|
464
|
+
if (!entry || typeof entry !== "object" || _isArray(entry) || _isBufferChk(entry)) {
|
|
465
|
+
throw E("bad-input", who + " must be an object naming one GeneralName form; a bare string does not say which namespace is constrained");
|
|
466
|
+
}
|
|
467
|
+
var keys = _objectKeys(entry);
|
|
468
|
+
if (keys.length !== 1) throw E("bad-input", who + " must name exactly one GeneralName form, got " + keys.length);
|
|
469
|
+
var k = keys[0], v = entry[k];
|
|
470
|
+
var tag = NC_FORM_TAG[k];
|
|
471
|
+
if (tag == null) {
|
|
472
|
+
throw E("bad-input", who + " names an unsupported constraint form " + _stringify(k) +
|
|
473
|
+
" (supported: rfc822Name, dNSName, directoryName, uniformResourceIdentifier, iPAddress)");
|
|
474
|
+
}
|
|
475
|
+
if (tag === 7) {
|
|
476
|
+
if (!guard.bytes.isByteSource(v)) throw E("bad-input", who + " iPAddress base must be a byte source");
|
|
477
|
+
var ip = guard.bytes.source(v, ErrorClass, ctx.prefix + "/bad-input", who + " iPAddress base");
|
|
478
|
+
if (ip.length !== 8 && ip.length !== 32) {
|
|
479
|
+
throw E("bad-input", who + " iPAddress base must be 8 octets (an IPv4 address and its mask) or 32 (IPv6), got " + ip.length);
|
|
480
|
+
}
|
|
481
|
+
return b.sequence([b.contextPrimitive(7, ip)]);
|
|
482
|
+
}
|
|
483
|
+
if (tag === 4) return b.sequence([b.explicit(4, encodeName(v))]);
|
|
484
|
+
if (typeof v !== "string") throw E("bad-input", who + " base must be a string for " + k);
|
|
485
|
+
var why = guard.name.constraintBaseRefusal(tag, v);
|
|
486
|
+
if (why !== null) throw E("bad-input", who + " base " + why);
|
|
487
|
+
return b.sequence([b.contextPrimitive(tag, ia5Content(v))]);
|
|
488
|
+
}
|
|
489
|
+
/** @internal NameConstraints (RFC 5280 sec. 4.2.1.10). permittedSubtrees [0] and excludedSubtrees
|
|
490
|
+
* [1] are IMPLICIT, so each replaces the GeneralSubtrees SEQUENCE tag and holds its members
|
|
491
|
+
* directly. The extension is emitted critical by its caller, which that clause requires. */
|
|
492
|
+
function extNameConstraints(spec) {
|
|
493
|
+
if (!spec || typeof spec !== "object" || _isArray(spec)) {
|
|
494
|
+
throw E("bad-input", "nameConstraints must be an object naming permitted and/or excluded subtrees");
|
|
495
|
+
}
|
|
496
|
+
guard.identifier.assertKnownKeys(spec, NC_KEYS, E, "bad-input", function (k) {
|
|
497
|
+
return "unknown nameConstraints field " + _stringify(k) + " (accepted: permitted, excluded)";
|
|
498
|
+
});
|
|
499
|
+
var kids = [];
|
|
500
|
+
_forEachNcSide(function (where, implicitTag) {
|
|
501
|
+
var list = spec[where];
|
|
502
|
+
if (list == null) return;
|
|
503
|
+
if (!_isArray(list) || !list.length) {
|
|
504
|
+
throw E("bad-input", "nameConstraints." + where + " must be a non-empty array of GeneralName-form objects");
|
|
505
|
+
}
|
|
506
|
+
var dense = reqDenseArray(list, "nameConstraints." + where);
|
|
507
|
+
var subs = _mapIntrinsic(dense, function (e, idx) { return constraintSubtree(e, where, idx); });
|
|
508
|
+
guard.list.append(kids, b.contextConstructed(implicitTag, _bufferConcatIntrinsic(subs)));
|
|
509
|
+
});
|
|
510
|
+
if (!kids.length) {
|
|
511
|
+
throw E("bad-input", "nameConstraints must name at least one of permitted or excluded (RFC 5280 sec. 4.2.1.10 forbids an empty sequence)");
|
|
512
|
+
}
|
|
513
|
+
return b.sequence(kids);
|
|
514
|
+
}
|
|
449
515
|
function extCertPolicies(names) {
|
|
450
516
|
if (!_isArray(names) || !names.length) throw E("bad-input", "certificatePolicies must list at least one policy OID");
|
|
451
517
|
var seen = intrinsic.create(null);
|
|
@@ -522,6 +588,7 @@ function makeBuilder(ctx) {
|
|
|
522
588
|
var REQ_EXT_KEYS = {
|
|
523
589
|
subjectAltName: 1, keyUsage: 1, keyUsageCritical: 1, extendedKeyUsage: 1, extendedKeyUsageCritical: 1,
|
|
524
590
|
basicConstraints: 1, certificatePolicies: 1, certificatePoliciesCritical: 1, subjectKeyIdentifier: 1,
|
|
591
|
+
nameConstraints: 1,
|
|
525
592
|
};
|
|
526
593
|
function requestedExtensions(extSpec, spki) {
|
|
527
594
|
var EXT_DECODERS = ctx.EXT_DECODERS;
|
|
@@ -558,6 +625,8 @@ function makeBuilder(ctx) {
|
|
|
558
625
|
if (extSpec.basicConstraints != null) { validateBcSpec(extSpec.basicConstraints); out.push(ext(O("basicConstraints"), extSpec.basicConstraints.critical !== false, extBasicConstraints(extSpec.basicConstraints))); }
|
|
559
626
|
if (extSpec.subjectAltName != null) out.push(ext(O("subjectAltName"), false, extSan(extSpec.subjectAltName)));
|
|
560
627
|
if (extSpec.certificatePolicies != null) out.push(ext(O("certificatePolicies"), !!extSpec.certificatePoliciesCritical, extCertPolicies(extSpec.certificatePolicies)));
|
|
628
|
+
/** @internal RFC 5280 sec. 4.2.1.10 fixes this extension critical, in a request as in the certificate. */
|
|
629
|
+
if (extSpec.nameConstraints != null) guard.list.append(out, ext(O("nameConstraints"), true, extNameConstraints(extSpec.nameConstraints)));
|
|
561
630
|
if (!out.length) throw E("bad-input", "the requested extensions object must request at least one extension");
|
|
562
631
|
return b.sequence(out);
|
|
563
632
|
}
|
|
@@ -621,6 +690,7 @@ function makeBuilder(ctx) {
|
|
|
621
690
|
return {
|
|
622
691
|
E: E, code: code, KU_BIT: KU_BIT,
|
|
623
692
|
encodeName: encodeName, isEmptyName: isEmptyName, encodeGeneralName: encodeGeneralName,
|
|
693
|
+
extNameConstraints: extNameConstraints,
|
|
624
694
|
encodeGeneralNames: encodeGeneralNames, serialInteger: serialInteger, timeDer: timeDer,
|
|
625
695
|
requestedExtensions: requestedExtensions,
|
|
626
696
|
extKeyUsage: extKeyUsage, extExtKeyUsage: extExtKeyUsage, validateBcSpec: validateBcSpec,
|
package/lib/x509-sign.js
CHANGED
|
@@ -50,7 +50,7 @@ var KNOWN_SIGN_OPTS = intrinsic.assign(intrinsic.create(null), { digestAlgorithm
|
|
|
50
50
|
var KNOWN_EXT_KEYS = intrinsic.assign(intrinsic.create(null), {
|
|
51
51
|
subjectKeyIdentifier: 1, authorityKeyIdentifier: 1, keyUsage: 1, keyUsageCritical: 1,
|
|
52
52
|
extendedKeyUsage: 1, extendedKeyUsageCritical: 1, basicConstraints: 1, subjectAltName: 1,
|
|
53
|
-
certificatePolicies: 1, certificatePoliciesCritical: 1,
|
|
53
|
+
certificatePolicies: 1, certificatePoliciesCritical: 1, nameConstraints: 1,
|
|
54
54
|
});
|
|
55
55
|
|
|
56
56
|
var _b = pkiBuild.makeBuilder({ ErrorClass: CertificateError, prefix: "x509", O: O, NS: NS, NAME_SCHEMA: NAME_SCHEMA, SPKI_SCHEMA: SPKI_SCHEMA, EXT_DECODERS: EXT_DECODERS });
|
|
@@ -60,6 +60,7 @@ var _encodeName = _b.encodeName, _isEmptyName = _b.isEmptyName, _reqDer = _b.req
|
|
|
60
60
|
_certLikeFromSpki = _b.certLikeFromSpki, _assertCertVerifies = _b.assertSignatureVerifies,
|
|
61
61
|
_ext = _b.ext, _extBasicConstraints = _b.extBasicConstraints, _validateBcSpec = _b.validateBcSpec,
|
|
62
62
|
_extKeyUsage = _b.extKeyUsage, _extExtKeyUsage = _b.extExtKeyUsage, _extSki = _b.extSki,
|
|
63
|
+
_extNameConstraints = _b.extNameConstraints,
|
|
63
64
|
_extAki = _b.extAki, _extSan = _b.extSan, _extCertPolicies = _b.extCertPolicies,
|
|
64
65
|
_skiKeyId = _b.skiKeyId, _spkiKeyId = _b.spkiKeyId, _serialInteger = _b.serialInteger;
|
|
65
66
|
|
|
@@ -81,8 +82,8 @@ function _akiKeyId(val, ctx) {
|
|
|
81
82
|
function _buildExtensions(extSpec, ctx) {
|
|
82
83
|
if (extSpec == null) return [];
|
|
83
84
|
if (_isArray(extSpec)) {
|
|
84
|
-
var seenExt = intrinsic.create(null), arrCa = false, arrKeyCertSign = false, arrPathLen = false;
|
|
85
|
-
var oidBc = O("basicConstraints"), oidKu = O("keyUsage");
|
|
85
|
+
var seenExt = intrinsic.create(null), arrCa = false, arrKeyCertSign = false, arrPathLen = false, arrNameConstraints = false;
|
|
86
|
+
var oidBc = O("basicConstraints"), oidKu = O("keyUsage"), oidNc = O("nameConstraints");
|
|
86
87
|
var arr = extSpec.map(function (e, i) {
|
|
87
88
|
var der = _reqDer(e, "extension");
|
|
88
89
|
_assertValidExtension(der, i);
|
|
@@ -90,6 +91,7 @@ function _buildExtensions(extSpec, ctx) {
|
|
|
90
91
|
var extnId = asn1.read.oid(n.children[0]);
|
|
91
92
|
if (seenExt[extnId]) throw _err("x509/bad-input", "duplicate extension " + extnId + " in the extensions array (RFC 5280 sec. 4.2 -- at most one instance of an extension)");
|
|
92
93
|
seenExt[extnId] = true;
|
|
94
|
+
if (extnId === oidNc) arrNameConstraints = true;
|
|
93
95
|
_assertCertCriticality(extnId, n.children.length === 3, "pre-encoded");
|
|
94
96
|
var dec = EXT_DECODERS[extnId];
|
|
95
97
|
if (dec) {
|
|
@@ -109,6 +111,7 @@ function _buildExtensions(extSpec, ctx) {
|
|
|
109
111
|
});
|
|
110
112
|
if (arrKeyCertSign && !arrCa) throw _err("x509/bad-input", "keyUsage keyCertSign requires basicConstraints cA=TRUE (RFC 5280 sec. 4.2.1.3)");
|
|
111
113
|
if (arrPathLen && (!arrCa || !arrKeyCertSign)) throw _err("x509/bad-input", "basicConstraints pathLenConstraint requires cA=TRUE and keyUsage keyCertSign (RFC 5280 sec. 4.2.1.9)");
|
|
114
|
+
if (arrNameConstraints && !arrCa) throw _err("x509/bad-input", "nameConstraints appears only in a CA certificate, so it requires basicConstraints cA=TRUE (RFC 5280 sec. 4.2.1.10)");
|
|
112
115
|
return arr;
|
|
113
116
|
}
|
|
114
117
|
if (typeof extSpec !== "object") throw _err("x509/bad-input", "extensions must be an object or an array of pre-encoded Extension DER");
|
|
@@ -138,6 +141,10 @@ function _buildExtensions(extSpec, ctx) {
|
|
|
138
141
|
}
|
|
139
142
|
if (extSpec.subjectAltName != null) out.push(_ext(O("subjectAltName"), ctx.subjectEmpty, _extSan(extSpec.subjectAltName)));
|
|
140
143
|
if (extSpec.certificatePolicies != null) out.push(_ext(O("certificatePolicies"), !!extSpec.certificatePoliciesCritical, _extCertPolicies(extSpec.certificatePolicies)));
|
|
144
|
+
if (extSpec.nameConstraints != null) {
|
|
145
|
+
if (!caTrue) throw _err("x509/bad-input", "nameConstraints appears only in a CA certificate, so it requires basicConstraints cA=TRUE (RFC 5280 sec. 4.2.1.10)");
|
|
146
|
+
guard.list.append(out, _ext(O("nameConstraints"), true, _extNameConstraints(extSpec.nameConstraints)));
|
|
147
|
+
}
|
|
141
148
|
return out;
|
|
142
149
|
}
|
|
143
150
|
|
|
@@ -219,6 +226,16 @@ function _hasCriticalSan(extSpec) {
|
|
|
219
226
|
* SPKI), a structural fault throws `CertificateError`, while a malformed leaf inside those bytes
|
|
220
227
|
* throws `Asn1Error`, the same two-error contract the parsers present.
|
|
221
228
|
*
|
|
229
|
+
* `extensions.nameConstraints` restricts what the CA being issued may itself issue, as
|
|
230
|
+
* `{ permitted: [...], excluded: [...] }` with at least one side present. Each entry names one
|
|
231
|
+
* GeneralName form: `{ dNSName: ".example.com" }`, `{ rfc822Name: "example.com" }`,
|
|
232
|
+
* `{ uniformResourceIdentifier: ".example.com" }`, `{ directoryName: [{ commonName: "Sub" }] }`, or
|
|
233
|
+
* `{ iPAddress: buf }` where `buf` is an address followed by its mask, 8 octets for IPv4 and 32 for
|
|
234
|
+
* IPv6. A base names a namespace rather than a subject, so it may carry a leading dot and is held to
|
|
235
|
+
* the rule for a constraint base. A bare string is refused here, since the name form decides which
|
|
236
|
+
* namespace is constrained. The extension is emitted critical, which RFC 5280 sec. 4.2.1.10 requires,
|
|
237
|
+
* and it appears only on a certificate whose `basicConstraints` sets `cA: true`.
|
|
238
|
+
*
|
|
222
239
|
* @opts
|
|
223
240
|
* - `pem` (boolean) -- return a PEM `CERTIFICATE` string instead of DER.
|
|
224
241
|
* - `pss` (boolean) -- sign an RSA key with RSASSA-PSS instead of PKCS#1 v1.5.
|
package/package.json
CHANGED
package/sbom.cdx.json
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
|
|
3
3
|
"bomFormat": "CycloneDX",
|
|
4
4
|
"specVersion": "1.5",
|
|
5
|
-
"serialNumber": "urn:uuid:
|
|
5
|
+
"serialNumber": "urn:uuid:fc3b3d3a-15d1-4ae3-8c33-4ac005977281",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-09-
|
|
8
|
+
"timestamp": "2026-09-11T03:40:35.055Z",
|
|
9
9
|
"lifecycles": [
|
|
10
10
|
{
|
|
11
11
|
"phase": "build"
|
|
@@ -19,14 +19,14 @@
|
|
|
19
19
|
}
|
|
20
20
|
],
|
|
21
21
|
"component": {
|
|
22
|
-
"bom-ref": "@blamejs/pki@0.7.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.7.15",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.7.
|
|
25
|
+
"version": "0.7.15",
|
|
26
26
|
"scope": "required",
|
|
27
27
|
"author": "blamejs contributors",
|
|
28
28
|
"description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
|
|
29
|
-
"purl": "pkg:npm/%40blamejs/pki@0.7.
|
|
29
|
+
"purl": "pkg:npm/%40blamejs/pki@0.7.15",
|
|
30
30
|
"properties": [],
|
|
31
31
|
"externalReferences": [
|
|
32
32
|
{
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"components": [],
|
|
55
55
|
"dependencies": [
|
|
56
56
|
{
|
|
57
|
-
"ref": "@blamejs/pki@0.7.
|
|
57
|
+
"ref": "@blamejs/pki@0.7.15",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|