@blamejs/pki 0.3.31 → 0.3.33

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 CHANGED
@@ -4,6 +4,32 @@ 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.3.33 — 2026-08-06
8
+
9
+ pki.schema.c509 encodes and decodes the compact certificatePolicies value form -- a C509 certificate's policy identifiers ride their draft-20 registry integers (or unwrapped OIDs) and their CPS-URI and UserNotice qualifiers ride the specific compact CBOR shape, interoperating with a conformant C509 implementation rather than only this decoder.
10
+
11
+ ### Added
12
+
13
+ - pki.schema.c509 encodes and decodes the compact value form for the certificatePolicies extension (draft-ietf-cose-cbor-encoded-cert-20 sec. 3.3): each policy identifier is a sec. 8.9 registry integer -- the CA/Browser Forum validation levels, the RFC 3779 id-cp-ipAddr resource-certificate policies, and the GSMA SGP.22 id-rspRole roles -- or an unwrapped OID for a policy outside the registry; each policy qualifier is a sec. 8.10 integer (id-qt-cps / id-qt-unotice) with its text, reconstructing the CPS pointer as a URI IA5String and the UserNotice as an explicit-text UTF8String. Both directions invert to the DER extnValue byte-for-byte, so a certificate carrying policies is the specific compact shape a conformant C509 implementation reads rather than an opaque DER byte string. The encoder is guarded: a UserNotice with a noticeRef, a non-UTF8String explicit text, or a policy-qualifier identifier outside the sec. 8.10 registry is not compact-representable and falls the whole extension back to the unwrapped-OID byte-string form instead of encoding lossily; a malformed compact value (an empty UserNotice text, a control-byte CPS URI, an unregistered policy or qualifier integer) fails closed with a typed C509Error.
14
+ - The OID registry gains the CA/Browser Forum certificate-policy identifiers (domain-, organization-, individual-validated, ev-guidelines), the RFC 3779 id-cp-ipAddr-asNumber policies, the GSMA SGP.22 id-rspRole roles, and the RFC 5280 id-qt policy qualifiers (cps, unotice), resolvable through pki.oid.byName / pki.oid.name.
15
+
16
+ ### Changed
17
+
18
+ - A C509 certificate carrying certificatePolicies now encodes to -- and decodes from -- its compact CBOR value shape rather than the unwrapped-OID byte-string form an earlier release emitted; both reconstruct the same DER, but the CBOR bytes differ, so re-encode any C509 produced by an earlier release.
19
+
20
+ ## v0.3.32 — 2026-08-05
21
+
22
+ pki.schema.c509 encodes and decodes the compact general-name extension values -- a C509 certificate's subjectAltName, issuer alternative name, name constraints, CRL distribution points, authority/subject information access, and the authority key identifier issuer form now ride their specific draft-20 CBOR shape and interoperate with a conformant C509 implementation, not only this decoder.
23
+
24
+ ### Added
25
+
26
+ - pki.schema.c509 encodes and decodes the compact value forms for the general-name-bearing extensions defined by draft-ietf-cose-cbor-encoded-cert-20 sec. 3.3: subjectAltName and issuerAltName (a flat array of (general-name type, value) pairs, or the bare dNSName as CBOR text for a single host name), nameConstraints (the permitted and excluded GeneralSubtrees, with the RFC 9549 sec. 2.2 address-plus-prefix-length form for an iPAddress constraint), cRLDistributionPoints and freshestCRL (each distribution point's URI full name with optional reasons and CRL issuer, or a single bare URI as CBOR text), authorityInfoAccess and subjectInfoAccess (each access description as a sec. 8.11 registry integer or unwrapped OID plus its URI), and the authorityKeyIdentifier key-identifier / authority-cert-issuer / serial form. One shared GeneralNames codec drives them all, covering every general-name form the sec. 8.13 registry defines -- rfc822Name, dNSName, directoryName, URI, iPAddress, registeredID, and otherName including the hardware-module-name (RFC 4108), SMTP UTF-8 mailbox (RFC 9598), and MAC-address specials. Each form inverts to the DER extnValue byte-for-byte in both directions, so a certificate carrying these extensions is the specific compact shape a conformant C509 implementation reads rather than an opaque DER byte string. The encoder is guarded: it emits the compact form only when it decodes back to the exact DER value, so a general name outside the registry (an X.400 address, an EDI party name), a non-canonical value, or a value the compact form cannot hold falls the whole extension back to the unwrapped-OID byte-string form instead of encoding a partial or lossy value; a malformed compact value fails closed with a typed C509Error.
27
+ - The OID registry gains the id-on other-name type identifiers (hardware module name, SMTP UTF-8 mailbox, MAC address), the id-ad access-description methods (time stamping, CA repository, RPKI manifest / signed object / notify), and subject information access, resolvable through pki.oid.byName / pki.oid.name.
28
+
29
+ ### Changed
30
+
31
+ - A C509 certificate carrying a general-name-bearing extension (subjectAltName, issuerAltName, nameConstraints, cRLDistributionPoints, freshestCRL, authorityInfoAccess, subjectInfoAccess, or the authorityKeyIdentifier issuer form) now encodes to -- and decodes from -- its compact CBOR value shape rather than the unwrapped-OID byte-string form an earlier release emitted; both reconstruct the same DER, but the CBOR bytes differ, so re-encode any C509 produced by an earlier release. A native C509 that carried a subjectAltName as a raw byte string under its extension integer, which is not a value form the draft defines, is now rejected.
32
+
7
33
  ## v0.3.31 — 2026-08-03
8
34
 
9
35
  pki.schema.c509 encodes and decodes the compact per-extension value forms -- a C509 certificate's keyUsage, basicConstraints, extended key usage, key identifiers, and other scalar extensions now ride in their specific draft-20 CBOR shape and interoperate with a conformant C509 implementation, not only this decoder.
package/README.md CHANGED
@@ -204,7 +204,7 @@ is callable today; nothing below is a stub.
204
204
  | `pki.webcrypto` | A W3C WebCrypto (`SubtleCrypto`) engine over `node:crypto` — `sign`/`verify`/`encrypt`/`decrypt`/`deriveBits`/`digest`/`generateKey`/`importKey`/`exportKey` across RSA, ECDSA, ECDH, Ed25519/Ed448, AES, HMAC, HKDF, PBKDF2, SHA — **and** post-quantum ML-DSA-44/65/87 and SLH-DSA signatures, plus ML-KEM-512/768/1024 key generation and certificate/PKCS#8 import — the RFC 9935 seed / expandedKey / both private-key CHOICE is validated fail-closed, so an OpenSSL-legacy bare-seed or an internally inconsistent key is rejected with a typed error (KEM encapsulation lands with CMS KEM-decrypt). Zero-dependency, OpenSSL-interoperable |
205
205
  | `pki.schema` | The schema family — `parse` detects which PKI format DER / PEM encodes and routes to the right parser, `all` enumerates the registered formats, and the engine + per-format members are grouped here |
206
206
  | `pki.schema.x509` | Parse DER / PEM certificates into structured, validated fields, with named + partly-decoded extensions — including the RFC 3739 / ETSI EN 319 412-5 qualified-certificate `qcStatements` (EU-qualified declaration, reliance limit, QSCD flag, certificate type, retention, PDS URLs, country of qualification; unknown statements preserved opaque) and the Microsoft Active Directory Certificate Services enrollment extensions (certificate template, CA version, previous-CA-certificate hash, application policies), fail-closed — `parse`, `pemDecode`, `pemEncode` |
207
- | `pki.schema.c509` | Parse **and encode** C509 CBOR-encoded certificates (draft-ietf-cose-cbor-encoded-cert) — the compact CBOR profile of X.509, decoded fail-closed under deterministic CBOR; an explicit `parse` call (CBOR, not DER, so not auto-routed). `encode(input)` is the byte-exact inverse: a DER X.509 v3 certificate forward-transforms to a compact type-3 C509 whose reconstruction reproduces the original DER byte for byte (so the original signature still verifies), or a `parse` result re-emits its native array — canonical deterministic CBOR with the registry integer shorthands, the C509 compressions, and the compact draft-20 per-extension value forms (keyUsage, basicConstraints, extended key usage, subject/authority key identifier, and the other scalar extensions); a certificate outside the invertible set throws a typed `C509Error` |
207
+ | `pki.schema.c509` | Parse **and encode** C509 CBOR-encoded certificates (draft-ietf-cose-cbor-encoded-cert) — the compact CBOR profile of X.509, decoded fail-closed under deterministic CBOR; an explicit `parse` call (CBOR, not DER, so not auto-routed). `encode(input)` is the byte-exact inverse: a DER X.509 v3 certificate forward-transforms to a compact type-3 C509 whose reconstruction reproduces the original DER byte for byte (so the original signature still verifies), or a `parse` result re-emits its native array — canonical deterministic CBOR with the registry integer shorthands, the C509 compressions, and the compact draft-20 per-extension value forms — the scalar extensions (keyUsage, basicConstraints, extended key usage, subject key identifier, and more), the general-name-bearing extensions (subjectAltName, issuer alt name, name constraints, CRL distribution points, authority/subject information access, and the full authority key identifier) over one shared GeneralNames value codec, and certificate policies (registry-integer or OID policy identifiers with their CPS-URI and UserNotice qualifiers); a certificate outside the invertible set throws a typed `C509Error` |
208
208
  | `pki.schema.crl` | Parse DER / PEM X.509 CRLs per RFC 5280 §5 — revoked serials with real-`Date` revocation times, named + partly-decoded extensions, fail-closed — `parse`, `pemDecode`, `pemEncode` |
209
209
  | `pki.schema.csr` | Parse DER / PEM PKCS#10 certification requests per RFC 2986 — subject DN, public key, requested attributes, signature, fail-closed — `parse`, `pemDecode`, `pemEncode` |
210
210
  | `pki.schema.pkcs8` | Parse DER / PEM PKCS#8 private keys per RFC 5208 / 5958 — algorithm, raw key bytes, attributes, optional public key, fail-closed; encrypted keys recognized (not decrypted) — `parse`, `parseEncrypted`, `pemDecode`, `pemEncode` |
package/lib/oid.js CHANGED
@@ -81,6 +81,8 @@ var FAMILIES = {
81
81
  pkixAccess: { base: [1, 3, 6, 1, 5, 5, 7, 1], of: {
82
82
  authorityInfoAccess: 1, acAuditIdentity: 4, aaControls: 6, acProxying: 10,
83
83
  acmeIdentifier: 31,
84
+ // id-pe-subjectInfoAccess (RFC 5280 sec. 4.2.2.2) -- the SIA extension companion to the AIA.
85
+ subjectInfoAccess: 11,
84
86
  // id-pe-tlsfeature (RFC 7633) -- the TLS Feature (formerly "must-staple") extension.
85
87
  tlsFeature: 24,
86
88
  // id-pe-qcStatements (RFC 3739 sec. 3.2.6) -- the qualified-certificate-statements extension.
@@ -119,8 +121,41 @@ var FAMILIES = {
119
121
 
120
122
  // PKIX Access Descriptor methods (id-ad, RFC 5280 sec. 4.2.2.1/sec. 4.2.2.2). id-ad-ocsp
121
123
  // is the arc the OCSP responder OIDs hang under; id-ad-caIssuers names the AIA
122
- // CA-issuers access method.
123
- adAccess: { base: [1, 3, 6, 1, 5, 5, 7, 48], of: { ocsp: 1, caIssuers: 2 } },
124
+ // CA-issuers access method. The remaining id-ad methods (timeStamping RFC 3161, caRepository
125
+ // + rpkiManifest/signedObject/rpkiNotify RFC 6487/8182) complete the C509 Information Access
126
+ // registry (draft-ietf-cose-cbor-encoded-cert sec. 8.11); they carry the id-ad- prefix so the
127
+ // name->OID reverse stays unambiguous next to the id-kp "timeStamping" purpose (a distinct arc).
128
+ adAccess: { base: [1, 3, 6, 1, 5, 5, 7, 48], of: { ocsp: 1, caIssuers: 2,
129
+ "id-ad-timeStamping": 3, "id-ad-caRepository": 5, "id-ad-rpkiManifest": 10,
130
+ "id-ad-signedObject": 11, "id-ad-rpkiNotify": 13 } },
131
+
132
+ // id-on -- RFC 5280 sec. 4.2.1.6 otherName type-ids the C509 sec. 8.13 registry gives their own
133
+ // negative ints: id-on-hardwareModuleName (RFC 4108), id-on-SmtpUTF8Mailbox (RFC 9598),
134
+ // id-on-MACAddress (I-D.ietf-lamps-macaddress-on) on the id-pkix 8 arc.
135
+ pkixOn: { base: [1, 3, 6, 1, 5, 5, 7, 8], of: { hardwareModuleName: 4, smtpUtf8Mailbox: 9, macAddress: 12 } },
136
+
137
+ // CA/Browser Forum certificate policies (draft-ietf-cose-cbor-encoded-cert sec. 8.9 ints 1-4) on the
138
+ // 2.23.140.1 arc: the id-cabf validation levels under .2, ev-guidelines under .1.
139
+ cabfPolicy: { base: [2, 23, 140, 1], of: {
140
+ "ev-guidelines": 1, "domain-validated": [2, 1], "organization-validated": [2, 2], "individual-validated": [2, 3] } },
141
+
142
+ // id-cp-ipAddr-asNumber (RFC 3779 / RFC 8360) on the id-pkix 14 arc -- the RPKI resource-certificate
143
+ // policy OIDs (sec. 8.9 ints 7-8).
144
+ idCp: { base: [1, 3, 6, 1, 5, 5, 7, 14], of: { "id-cp-ipAddr-asNumber": 2, "id-cp-ipAddr-asNumber-v2": 3 } },
145
+
146
+ // GSMA SGP.22 Remote SIM Provisioning roles (sec. 8.9 ints 24-38) on the 2.23.146.1.2.1 id-rspRole arc.
147
+ // The -v2 roles are shallow leaves .{1..7}; the non-v2 roles descend into deeper sub-arcs (draft-20).
148
+ gsmaRspRole: { base: [2, 23, 146, 1, 2, 1], of: {
149
+ "id-rspRole-ci": 0, "id-rspRole-euicc-v2": 1, "id-rspRole-euicc": [0, 0, 0, 0, 0],
150
+ "id-rspRole-eum-v2": 2, "id-rspRole-eum": [0, 0, 0],
151
+ "id-rspRole-dp-tls-v2": 3, "id-rspRole-dp-tls": [0, 0, 1, 0],
152
+ "id-rspRole-dp-auth-v2": 4, "id-rspRole-dp-auth": [0, 0, 1, 1],
153
+ "id-rspRole-dp-pb-v2": 5, "id-rspRole-dp-pb": [0, 0, 1, 2],
154
+ "id-rspRole-ds-tls-v2": 6, "id-rspRole-ds-tls": [0, 0, 2, 0],
155
+ "id-rspRole-ds-auth-v2": 7, "id-rspRole-ds-auth": [0, 0, 2, 1] } },
156
+
157
+ // id-qt policy qualifiers (RFC 5280 sec. 4.2.1.4) on the id-pkix 2 arc -- the C509 sec. 8.10 registry.
158
+ pkixQt: { base: [1, 3, 6, 1, 5, 5, 7, 2], of: { cps: 1, unotice: 2 } },
124
159
 
125
160
  // OCSP (RFC 6960) on the id-pkix-ocsp arc (= id-ad-ocsp). id-pkix-ocsp-basic is
126
161
  // the ResponseBytes.responseType this build decodes; id-pkix-ocsp-nonce (sec. 4.4.1)
@@ -19,6 +19,8 @@ var asn1 = require("./asn1-der");
19
19
  var oid = require("./oid");
20
20
  var x509 = require("./schema-x509");
21
21
  var pkix = require("./schema-pkix");
22
+ var schema = require("./schema-engine");
23
+ var guard = require("./guard-all");
22
24
  var constants = require("./constants");
23
25
  var frameworkError = require("./framework-error");
24
26
  var validator = require("./validator-all");
@@ -71,17 +73,25 @@ var ATTR_BY_INT = {
71
73
  10: _name("title"),
72
74
  };
73
75
  // sec. 8.8 extension types (abs(int) -> name; the sign selects criticality). The general-name-bearing
74
- // extensions (subjectAltName et al) carry an int extensionID only when their compact value is supported;
75
- // subjectAltName stays registered for the byte-string value form (the compact GeneralNames array awaits
76
- // the sec. 8.13 general-name codec and fails closed).
76
+ // extensions (subjectAltName / issuerAltName / nameConstraints / cRLDistributionPoints / freshestCRL /
77
+ // authorityInfoAccess / subjectInfoAccess) ride the shared sec. 8.13 GeneralNames value codec below; each
78
+ // carries a specific CBOR value form and falls back to ~oid + byte-string only when a member is outside
79
+ // the sec. 8.13 registry (an x400Address / ediPartyName general name, a non-URI access location, ...).
77
80
  var EXT_BY_INT = {
78
81
  1: _name("subjectKeyIdentifier"),
79
82
  2: _name("keyUsage"),
80
83
  3: _name("subjectAltName"),
81
84
  4: _name("basicConstraints"),
85
+ 5: _name("cRLDistributionPoints"),
86
+ 6: _name("certificatePolicies"),
82
87
  7: _name("authorityKeyIdentifier"),
83
88
  8: _name("extKeyUsage"),
89
+ 9: _name("authorityInfoAccess"),
90
+ 25: _name("issuerAltName"),
91
+ 26: _name("nameConstraints"),
92
+ 29: _name("freshestCRL"),
84
93
  30: _name("inhibitAnyPolicy"),
94
+ 31: _name("subjectInfoAccess"),
85
95
  36: _name("ocspNoCheck"),
86
96
  38: _name("tlsFeature"),
87
97
  };
@@ -90,6 +100,8 @@ var EXT_BY_INT = {
90
100
  var EXT_COMPACT = {
91
101
  subjectKeyIdentifier: 1, keyUsage: 1, basicConstraints: 1, authorityKeyIdentifier: 1,
92
102
  extKeyUsage: 1, inhibitAnyPolicy: 1, ocspNoCheck: 1, tlsFeature: 1,
103
+ subjectAltName: 1, issuerAltName: 1, nameConstraints: 1, cRLDistributionPoints: 1,
104
+ freshestCRL: 1, authorityInfoAccess: 1, subjectInfoAccess: 1, certificatePolicies: 1,
93
105
  };
94
106
  // sec. 8.12 Extended Key Usages registry (C509 int -> registered id-kp purpose name). A KeyPurposeId
95
107
  // outside this set encodes as an unwrapped ~oid; a C509 int outside it fails closed on decode.
@@ -103,6 +115,55 @@ var EKU_BY_INT = {
103
115
  var EKU_TO_INT = {}; // dotted OID -> C509 int (the encode inverse; keyed on the resolved OID)
104
116
  Object.keys(EKU_BY_INT).forEach(function (k) { EKU_TO_INT[oid.byName(EKU_BY_INT[k])] = Number(k); });
105
117
 
118
+ // The shared pkix namespace + GeneralName leaves the general-name value codec composes for the DER ->
119
+ // CBOR direction (the CVE-2009-2408 IA5 control-byte guard, the otherName/directoryName shape, the
120
+ // iPAddress length and RFC 9549 subtree-base length are all enforced there -- never re-validated by hand).
121
+ var NS = pkix.makeNS("c509", C509Error, oid);
122
+ var GN_LEAF = pkix.generalName(NS, { decodeValue: true }); // SAN-form GeneralName leaf
123
+ var GN_LEAF_SUBTREE = pkix.generalName(NS, { decodeValue: true, subtreeBase: true }); // name-constraints subtree base
124
+
125
+ // sec. 8.13 C509 General Names registry: for the standard forms the C509 int == the RFC 5280 sec. 4.2.1.6
126
+ // GeneralName CHOICE context tag (1 rfc822Name, 2 dNSName, 4 directoryName, 6 URI, 7 iPAddress, 8
127
+ // registeredID); the _generalNameToDer / _generalNameFromDer switches carry that mapping directly.
128
+ // x400Address [3] and ediPartyName [5] have no registry row -- a GeneralNames carrying either is not
129
+ // compact-encodable (the enclosing extension falls back to ~oid + byte-string).
130
+ // The id-on otherName specials get their own negative C509 ints (sec. 8.13 / sec. 3.3): int -> the id-on
131
+ // type-id OID name; the derived inverse keys on the resolved OID so a decode selects the negative int.
132
+ var ON_NAME_BY_INT = { "-1": _name("hardwareModuleName"), "-2": _name("smtpUtf8Mailbox"), "-3": _name("macAddress") };
133
+ var ON_INT_BY_OID = {};
134
+ Object.keys(ON_NAME_BY_INT).forEach(function (k) { ON_INT_BY_OID[oid.byName(ON_NAME_BY_INT[k])] = Number(k); });
135
+ // sec. 8.11 C509 Information Access registry (int -> registered access-method OID name; the id-ad methods
136
+ // keep the id-ad- prefix, see oid.js). A method OID outside the table encodes as ~oid; a C509 method int
137
+ // outside it fails closed. IA_TO_INT is the derived encode inverse, keyed on the resolved OID.
138
+ var IA_BY_INT = {
139
+ 1: _name("ocsp"), 2: _name("caIssuers"), 3: _name("id-ad-timeStamping"), 5: _name("id-ad-caRepository"),
140
+ 10: _name("id-ad-rpkiManifest"), 11: _name("id-ad-signedObject"), 13: _name("id-ad-rpkiNotify"),
141
+ };
142
+ var IA_TO_INT = {};
143
+ Object.keys(IA_BY_INT).forEach(function (k) { IA_TO_INT[oid.byName(IA_BY_INT[k])] = Number(k); });
144
+
145
+ // sec. 8.9 C509 Certificate Policies registry (int -> registered policy OID name; the CA/Browser Forum
146
+ // levels, the RFC 3779 id-cp-ipAddr policies, and the GSMA SGP.22 id-rspRole roles). A policy OID outside
147
+ // this set encodes as ~oid; a C509 policy int outside it fails closed. CP_TO_INT is the derived inverse.
148
+ var CP_BY_INT = {
149
+ 0: _name("anyPolicy"), 1: _name("domain-validated"), 2: _name("organization-validated"),
150
+ 3: _name("individual-validated"), 4: _name("ev-guidelines"),
151
+ 7: _name("id-cp-ipAddr-asNumber"), 8: _name("id-cp-ipAddr-asNumber-v2"),
152
+ 24: _name("id-rspRole-ci"), 25: _name("id-rspRole-euicc-v2"), 26: _name("id-rspRole-euicc"),
153
+ 27: _name("id-rspRole-eum-v2"), 28: _name("id-rspRole-eum"),
154
+ 29: _name("id-rspRole-dp-tls-v2"), 30: _name("id-rspRole-dp-tls"),
155
+ 31: _name("id-rspRole-dp-auth-v2"), 32: _name("id-rspRole-dp-auth"),
156
+ 33: _name("id-rspRole-dp-pb-v2"), 34: _name("id-rspRole-dp-pb"),
157
+ 35: _name("id-rspRole-ds-tls-v2"), 36: _name("id-rspRole-ds-tls"),
158
+ 37: _name("id-rspRole-ds-auth-v2"), 38: _name("id-rspRole-ds-auth"),
159
+ };
160
+ var CP_TO_INT = {};
161
+ Object.keys(CP_BY_INT).forEach(function (k) { CP_TO_INT[oid.byName(CP_BY_INT[k])] = Number(k); });
162
+ // sec. 8.10 C509 Policies Qualifiers registry (int -> id-qt qualifier OID name; the derived inverse).
163
+ var PQ_BY_INT = { 1: _name("cps"), 2: _name("unotice") };
164
+ var PQ_TO_INT = {};
165
+ Object.keys(PQ_BY_INT).forEach(function (k) { PQ_TO_INT[oid.byName(PQ_BY_INT[k])] = Number(k); });
166
+
106
167
  // ---- field readers (the unwrapped ~biguint / ~time / ~oid contracts; draft-20 sec. 3.1) ----
107
168
 
108
169
  // ~biguint (sec. 3.1.2): a BARE byte string (major type 2), big-endian magnitude, the non-negative
@@ -193,6 +254,12 @@ function _name509(node, isSubject) {
193
254
  // attribute type with no value -- reject rather than silently drop the trailing element.
194
255
  if (kids.length % 2 !== 0) throw _err("c509/bad-name", "a C509 Name array must be attribute-type/value pairs (dangling attribute type)");
195
256
  for (var i = 0; i + 1 < kids.length; i += 2) {
257
+ // The attributeType slot must be a CBOR integer (major type 0/1). Guard the major type BEFORE the read
258
+ // so a non-integer type slot fails in this module's own domain (c509/bad-name), matching the value slot,
259
+ // rather than leaking cbor.read.int's cbor/unexpected-major fault onto the parse surface. Reached with
260
+ // attacker-controlled bytes via the sec. 8.13 directoryName general name (subjectAltName, authorityKey-
261
+ // Identifier issuer, cRLDistributionPoints cRLIssuer, nameConstraints subtree base) and the top-level Name.
262
+ if (kids[i].majorType !== 0 && kids[i].majorType !== 1) throw _err("c509/bad-name", "a C509 Name attribute type must be a CBOR integer");
196
263
  var ti = Number(cbor.read.int(kids[i]));
197
264
  var tname = ATTR_BY_INT[Math.abs(ti)];
198
265
  if (tname === undefined) throw _err("c509/bad-name", "attribute type integer " + ti + " has no C509 registry row");
@@ -235,6 +302,377 @@ function _ekuPurposeOid(node) {
235
302
  return _oidName(node, "c509/bad-extensions", "an extKeyUsage KeyPurposeId").oid;
236
303
  }
237
304
 
305
+ // ---- the shared C509 GeneralNames value codec (draft-20 sec. 3.3 / sec. 8.13) ------------------
306
+ // One int <-> DER-context-tag pair (_generalNameToDer / _generalNameFromDer) drives every general-name-
307
+ // bearing extension (subjectAltName, nameConstraints, authorityKeyIdentifier, cRLDistributionPoints,
308
+ // authorityInfoAccess, ...), so a tag/int mapping bug cannot diverge across them. The DER -> CBOR side
309
+ // composes the shared pkix.generalName leaf; the CBOR -> DER side builds directly with asn1.build.*, the
310
+ // exact inverse. Every encode stays behind the extension-level byte-exact round-trip guard
311
+ // (_tryCompactExtValue), so a member the codec cannot invert byte-for-byte falls the WHOLE extension back
312
+ // to the conformant ~oid + byte-string form (sec. 3.7) -- never a partial GeneralNames.
313
+
314
+ // The unwrapped ~oid CBOR form (a bare byte string of the BER OID content octets; RFC 9090).
315
+ function _oidCbor(dotted) { return cbor.build.byteString(asn1.encodeOidContent(dotted)); }
316
+ // The CBOR simple value null (0xF6): the omitted permitted / excluded / reasons / cRLIssuer field.
317
+ function _isCborNull(node) { return node.majorType === 7 && node.ai === 22; }
318
+
319
+ // A CBOR text node -> the IA5String content octets of an IMPLICIT [n] GeneralName (rfc822Name/dNSName/URI).
320
+ // IA5String is 7-bit ASCII, so a code point > 0x7f cannot be one; a control byte (C0/DEL) is an injection
321
+ // vector (CVE-2009-2408) the shared name guard rejects -- matching the pkix.generalName decode side, so a
322
+ // value it rejects also fails the reconstruction direction (no round-trip guard runs on decode).
323
+ function _ia5Bytes(node, tag) {
324
+ if (node.majorType !== 3) throw _err("c509/bad-extensions", "a GeneralName [" + tag + "] value must be a CBOR text string (IA5String)");
325
+ var s = cbor.read.textString(node);
326
+ // An empty IA5 GeneralName is rejected by the shared pkix.generalName leaf (a non-empty rfc822Name /
327
+ // dNSName / URI), so reject it on the reconstruction side too rather than emit an empty [n] IA5String.
328
+ if (s.length === 0) throw _err("c509/bad-extensions", "a GeneralName [" + tag + "] IA5String must be non-empty");
329
+ for (var i = 0; i < s.length; i++) { if (s.charCodeAt(i) > 0x7f) throw _err("c509/bad-extensions", "a GeneralName [" + tag + "] IA5String has a non-ASCII code point"); }
330
+ var buf = Buffer.from(s, "latin1");
331
+ guard.name.assertPrintableIa5(buf, _err, "c509/bad-extensions", "GeneralName [" + tag + "]");
332
+ return buf;
333
+ }
334
+
335
+ // A named-bit-list value (bit i -> named bit i, MSB-first; the 9-bit keyUsage / ReasonFlags range) -> the
336
+ // DER BIT STRING content { unusedBits, bytes }, or null when the value is outside the 9 defined bits.
337
+ function _namedBitsToContent(value) {
338
+ if (!Number.isInteger(value) || value <= 0 || value > 0x1ff) return null;
339
+ var hi = 0; for (var t = value; t; t >>= 1) hi++; hi -= 1; // highest set bit index
340
+ var buf = Buffer.alloc((hi >> 3) + 1);
341
+ for (var bit = 0; bit <= hi; bit++) { if (value & (1 << bit)) buf[bit >> 3] |= 0x80 >> (bit & 7); }
342
+ return { unusedBits: 7 - (hi & 7), bytes: buf };
343
+ }
344
+ // The inverse: a DER BIT STRING content -> the named-bit value (bit i -> 2^i), or null when out of range.
345
+ function _namedBitsFromContent(bytes, unusedBits) {
346
+ var total = bytes.length * 8 - unusedBits, value = 0;
347
+ for (var bit = 0; bit < total && bit < 31; bit++) { if (bytes[bit >> 3] & (0x80 >> (bit & 7))) value |= (1 << bit); }
348
+ return value > 0 && value <= 0x1ff ? value : null;
349
+ }
350
+
351
+ // One C509 (int, value) general name -> one DER GeneralName TLV. `ipMode` (name-constraints subtree base)
352
+ // only changes the iPAddress arm: SAN is a bare 4/16-octet address, a subtree base is the RFC 9549 form.
353
+ function _generalNameToDer(intVal, valueNode, ipMode) {
354
+ if (intVal === 1 || intVal === 2 || intVal === 6) return b.contextPrimitive(intVal, _ia5Bytes(valueNode, intVal)); // IMPLICIT IA5String
355
+ if (intVal === 4) return b.explicit(4, _reconName(_name509(valueNode, true))); // directoryName [4] EXPLICIT Name
356
+ if (intVal === 7) return b.contextPrimitive(7, ipMode ? _ncIpToDer(valueNode) : _sanIpBytes(valueNode)); // iPAddress [7] IMPLICIT OCTET STRING
357
+ if (intVal === 8) return b.contextPrimitive(8, asn1.encodeOidContent(_oidName(valueNode, "c509/bad-extensions", "a registeredID [8]").oid)); // registeredID [8] IMPLICIT OID
358
+ if (intVal === 0 || intVal === -1 || intVal === -2 || intVal === -3) return _otherNameToDer(valueNode, intVal); // otherName [0]
359
+ throw _err("c509/bad-extensions", "GeneralName int " + intVal + " has no C509 sec. 8.13 registry row");
360
+ }
361
+ // The DER GeneralName leaf result { tagNumber, value, bytes } -> a [intCbor, valueCbor] pair, or null when
362
+ // the name is not compact-representable (x400Address [3] / ediPartyName [5], a directoryName the compact
363
+ // Name codec cannot hold, a non-canonical name-constraints IP mask).
364
+ function _generalNameFromDer(gn, ipMode) {
365
+ var t = gn.tagNumber;
366
+ if (t === 1 || t === 2 || t === 6) return [cbor.build.int(BigInt(t)), cbor.build.textString(gn.value)];
367
+ if (t === 4) { var nm = _dirNameToCbor(gn.bytes); return nm == null ? null : [cbor.build.int(4n), nm]; }
368
+ if (t === 7) {
369
+ if (!ipMode) return [cbor.build.int(7n), cbor.build.byteString(gn.value)];
370
+ var ip = _ncIpFromDer(gn.value); return ip == null ? null : [cbor.build.int(7n), cbor.build.byteString(ip)];
371
+ }
372
+ if (t === 8) return [cbor.build.int(8n), _oidCbor(gn.value)];
373
+ if (t === 0) return _otherNameFromDer(gn.value);
374
+ return null; // tags 3 / 5 (x400Address / ediPartyName) -- no sec. 8.13 registry row
375
+ }
376
+
377
+ // A flat CBOR array [int, value, int, value, ...] -> the list of DER GeneralName TLVs (the caller wraps
378
+ // them: a universal SEQUENCE for SAN/IAN, an implicit [n] for AKI issuer / DP cRLIssuer). These are always
379
+ // SAN-form (the RFC 9549 subtree-base iPAddress form is name-constraints-only and routes through
380
+ // _subtreesToDer / _subtreesFromDer, which call the singular codec with ipMode directly).
381
+ function _generalNamesToDer(node) {
382
+ if (node.majorType !== 4 || !node.children) throw _err("c509/bad-extensions", "a GeneralNames value must be a CBOR array");
383
+ var kids = node.children;
384
+ if (kids.length === 0 || kids.length % 2 !== 0) throw _err("c509/bad-extensions", "a GeneralNames array must be non-empty (int, value) pairs (sec. 3.3)");
385
+ var out = [];
386
+ for (var i = 0; i + 1 < kids.length; i += 2) out.push(_generalNameToDer(Number(_cborIntVal(kids[i], "a GeneralName type")), kids[i + 1], false));
387
+ return out;
388
+ }
389
+ // The inverse: a list of DER GeneralName nodes -> the flat CBOR items, or null if ANY member is not
390
+ // compact-representable (the whole enclosing extension then falls back -- never a partial GeneralNames).
391
+ function _generalNamesFromDer(gnNodes) {
392
+ var out = [];
393
+ for (var i = 0; i < gnNodes.length; i++) {
394
+ var pair = _generalNameFromDer(schema.walk(GN_LEAF, gnNodes[i], NS), false);
395
+ if (pair == null) return null;
396
+ out.push(pair[0]); out.push(pair[1]);
397
+ }
398
+ return out;
399
+ }
400
+
401
+ // otherName [0] IMPLICIT SEQUENCE { type-id OBJECT IDENTIFIER, value [0] EXPLICIT ANY } -- the context tag
402
+ // REPLACES the SEQUENCE tag (RFC 5280 IMPLICIT tagging), so the [0] node holds type-id then value directly
403
+ // (no inner universal SEQUENCE). The generic form (C509 int 0) carries [ ~oid(type-id), bytes(the [0]
404
+ // EXPLICIT inner value's raw TLV) ]; the id-on specials (-1/-2/-3) carry the RFC 4108 / RFC 9598 /
405
+ // lamps-macaddress value shapes and reconstruct the full OtherName.
406
+ function _otherNameToDer(node, intVal) {
407
+ var typeId, inner;
408
+ if (intVal === 0) {
409
+ if (node.majorType !== 4 || !node.children || node.children.length !== 2) throw _err("c509/bad-extensions", "a generic otherName value must be a CBOR [ ~oid, bytes ] pair");
410
+ typeId = _oidName(node.children[0], "c509/bad-extensions", "an otherName type-id").oid;
411
+ if (node.children[1].majorType !== 2) throw _err("c509/bad-extensions", "an otherName value must be a CBOR byte string (the [0] EXPLICIT inner TLV)");
412
+ inner = node.children[1].content;
413
+ try { asn1.decode(inner); } catch (e) { throw _err("c509/bad-extensions", "an otherName value is not a single well-formed DER element", e); }
414
+ } else if (intVal === -1) { // id-on-hardwareModuleName: [ ~oid(hwType), bytes(hwSerialNum) ] -> HardwareModuleName
415
+ if (node.majorType !== 4 || !node.children || node.children.length !== 2) throw _err("c509/bad-extensions", "an id-on-hardwareModuleName value must be a CBOR [ ~oid, bytes ] pair");
416
+ if (node.children[1].majorType !== 2) throw _err("c509/bad-extensions", "a hardwareModuleName hwSerialNum must be a CBOR byte string");
417
+ typeId = oid.byName("hardwareModuleName");
418
+ inner = b.sequence([b.oid(_oidName(node.children[0], "c509/bad-extensions", "a hardwareModuleName hwType").oid), b.octetString(node.children[1].content)]);
419
+ } else if (intVal === -2) { // id-on-SmtpUTF8Mailbox: text -> UTF8String (RFC 9598 SIZE (1..MAX))
420
+ if (node.majorType !== 3) throw _err("c509/bad-extensions", "an id-on-SmtpUTF8Mailbox value must be a CBOR text string");
421
+ var smtp = cbor.read.textString(node);
422
+ if (smtp.length === 0) throw _err("c509/bad-extensions", "an id-on-SmtpUTF8Mailbox value must be non-empty (RFC 9598 SIZE (1..MAX))");
423
+ typeId = oid.byName("smtpUtf8Mailbox");
424
+ inner = b.utf8(smtp);
425
+ } else { // intVal === -3, id-on-MACAddress: bytes (6 = EUI-48, 8 = EUI-64) -> OCTET STRING
426
+ if (node.majorType !== 2) throw _err("c509/bad-extensions", "an id-on-MACAddress value must be a CBOR byte string");
427
+ if (node.content.length !== 6 && node.content.length !== 8) throw _err("c509/bad-extensions", "an id-on-MACAddress value must be 6 (EUI-48) or 8 (EUI-64) octets");
428
+ typeId = oid.byName("macAddress");
429
+ inner = b.octetString(node.content);
430
+ }
431
+ return b.contextConstructed(0, Buffer.concat([b.oid(typeId), b.explicit(0, inner)])); // [0] IMPLICIT SEQUENCE
432
+ }
433
+ // The inverse: the pkix.generalName otherName value { typeId, valueBytes } -> a [intCbor, valueCbor] pair,
434
+ // or null when an id-on special's inner value is not its RFC-defined shape (the extension then falls back).
435
+ function _otherNameFromDer(v) {
436
+ var onInt = ON_INT_BY_OID[v.typeId];
437
+ if (onInt === undefined) return [cbor.build.int(0n), cbor.build.array([_oidCbor(v.typeId), cbor.build.byteString(v.valueBytes)])];
438
+ var inner;
439
+ try { inner = asn1.decode(v.valueBytes); } catch (_e) { return null; }
440
+ if (onInt === -1) { // HardwareModuleName ::= SEQUENCE { hwType OID, hwSerialNum OCTET STRING } (RFC 4108)
441
+ if (inner.tagClass !== "universal" || inner.tagNumber !== asn1.TAGS.SEQUENCE || !inner.children || inner.children.length !== 2) return null;
442
+ var hwType, hwSerial;
443
+ try { hwType = asn1.read.oid(inner.children[0]); hwSerial = asn1.read.octetString(inner.children[1]); } catch (_e2) { return null; }
444
+ return [cbor.build.int(-1n), cbor.build.array([_oidCbor(hwType), cbor.build.byteString(hwSerial)])];
445
+ }
446
+ if (onInt === -2) { // SmtpUTF8Mailbox ::= UTF8String (RFC 9598)
447
+ if (inner.tagClass !== "universal" || inner.tagNumber !== asn1.TAGS.UTF8_STRING) return null;
448
+ var txt; try { txt = asn1.read.string(inner); } catch (_e3) { return null; }
449
+ return [cbor.build.int(-2n), cbor.build.textString(txt)];
450
+ }
451
+ if (inner.tagClass !== "universal" || inner.tagNumber !== asn1.TAGS.OCTET_STRING) return null; // onInt === -3: MACAddress ::= OCTET STRING
452
+ var mac; try { mac = asn1.read.octetString(inner); } catch (_e4) { return null; }
453
+ // nosemgrep: pki-non-constant-time-secret-compare -- mac is a PUBLIC hardware MAC address (an EUI-48/64
454
+ // identifier, RFC 9542 / lamps-macaddress), not a MAC / HMAC / auth tag / secret; this is a length check.
455
+ if (mac.length !== 6 && mac.length !== 8) return null;
456
+ return [cbor.build.int(-3n), cbor.build.byteString(mac)];
457
+ }
458
+
459
+ // directoryName [4] EXPLICIT Name (a CHOICE, hence EXPLICIT) <-> the C509 compact Name. Reuses the file's
460
+ // Name codecs; a Name the compact form cannot hold (a multi-value RDN, an attribute outside sec. 8.6)
461
+ // returns null so the whole extension falls back to ~oid + byte-string.
462
+ function _dirNameToCbor(gnBytes) {
463
+ var node = asn1.decode(gnBytes); // the [4]-tagged EXPLICIT wrapper
464
+ if (!node.children || node.children.length !== 1) return null;
465
+ var name;
466
+ try { name = _c509NameFromDer(node.children[0].bytes); } catch (_e) { return null; }
467
+ try { return _encName(name, true); } catch (_e2) { return null; }
468
+ }
469
+
470
+ // iPAddress [7] (SAN form): a bare 4-octet (IPv4) or 16-octet (IPv6) address, CBOR bytes <-> DER content.
471
+ function _sanIpBytes(node) {
472
+ if (node.majorType !== 2) throw _err("c509/bad-extensions", "an iPAddress value must be a CBOR byte string");
473
+ if (node.content.length !== 4 && node.content.length !== 16) throw _err("c509/bad-extensions", "an iPAddress must be 4 (IPv4) or 16 (IPv6) octets");
474
+ return node.content;
475
+ }
476
+ // iPAddress [7] (name-constraints subtree base): RFC 9549 sec. 2.2. CBOR is address || prefix-length (5 or
477
+ // 17 octets, the last octet the prefix bit count); DER is address || mask (8 or 32 octets). CBOR -> DER
478
+ // expands the prefix length to a contiguous mask.
479
+ function _ncIpToDer(node) {
480
+ if (node.majorType !== 2) throw _err("c509/bad-extensions", "a name-constraints iPAddress value must be a CBOR byte string");
481
+ var buf = node.content, addrLen;
482
+ if (buf.length === 5) addrLen = 4; else if (buf.length === 17) addrLen = 16;
483
+ else throw _err("c509/bad-extensions", "a name-constraints iPAddress must be 5 (IPv4) or 17 (IPv6) octets (address + prefix length; RFC 9549 sec. 2.2)");
484
+ var prefixLen = buf[addrLen], maxBits = addrLen * 8;
485
+ if (prefixLen > maxBits) throw _err("c509/bad-extensions", "a name-constraints iPAddress prefix length " + prefixLen + " exceeds " + maxBits);
486
+ var mask = Buffer.alloc(addrLen);
487
+ for (var bit = 0; bit < prefixLen; bit++) mask[bit >> 3] |= 0x80 >> (bit & 7);
488
+ return Buffer.concat([buf.subarray(0, addrLen), mask]);
489
+ }
490
+ // DER -> CBOR: address || mask (8/32) -> address || prefix-length (5/17). The mask MUST be a canonical
491
+ // contiguous prefix mask (N leading 1-bits then all 0-bits); a non-prefix mask (host bits set,
492
+ // non-contiguous) is not representable in the prefix form -> null (the extension falls back, losing no bits).
493
+ function _ncIpFromDer(buf) {
494
+ var addrLen = buf.length >> 1, mask = buf.subarray(addrLen), prefixLen = 0, seenZero = false;
495
+ for (var i = 0; i < mask.length; i++) {
496
+ for (var bit = 0; bit < 8; bit++) {
497
+ if (mask[i] & (0x80 >> bit)) { if (seenZero) return null; prefixLen++; }
498
+ else seenZero = true;
499
+ }
500
+ }
501
+ return Buffer.concat([buf.subarray(0, addrLen), Buffer.from([prefixLen])]);
502
+ }
503
+
504
+ // GeneralSubtrees = [ + GeneralName ] (the flat int/value array) <-> the concatenated GeneralSubtree
505
+ // SEQUENCEs (RFC 5280 sec. 4.2.1.10: SEQUENCE { base, minimum [0] DEFAULT 0, maximum [1] OPTIONAL }); the
506
+ // C509 profile omits minimum/maximum, so each GeneralSubtree is base-only.
507
+ function _subtreesToDer(node) {
508
+ if (node.majorType !== 4 || !node.children) throw _err("c509/bad-extensions", "a GeneralSubtrees value must be a CBOR array");
509
+ var kids = node.children;
510
+ if (kids.length === 0 || kids.length % 2 !== 0) throw _err("c509/bad-extensions", "a GeneralSubtrees array must be non-empty (int, value) pairs");
511
+ var out = [];
512
+ for (var i = 0; i + 1 < kids.length; i += 2) out.push(b.sequence([_generalNameToDer(Number(_cborIntVal(kids[i], "a GeneralSubtree base type")), kids[i + 1], true)]));
513
+ return Buffer.concat(out);
514
+ }
515
+ function _subtreesFromDer(subtreeNodes) {
516
+ if (!subtreeNodes.length) return null;
517
+ var out = [];
518
+ for (var i = 0; i < subtreeNodes.length; i++) {
519
+ var st = subtreeNodes[i];
520
+ if (st.tagClass !== "universal" || st.tagNumber !== asn1.TAGS.SEQUENCE || !st.children || st.children.length !== 1) return null; // base only (minimum/maximum omitted)
521
+ var pair = _generalNameFromDer(schema.walk(GN_LEAF_SUBTREE, st.children[0], NS), true);
522
+ if (pair == null) return null;
523
+ out.push(pair[0]); out.push(pair[1]);
524
+ }
525
+ return out;
526
+ }
527
+
528
+ // A CBOR accessMethod (int, sec. 8.11 registry, or ~oid) -> the dotted access-method OID.
529
+ function _accessMethodOid(node) {
530
+ if (node.majorType === 0 || node.majorType === 1) {
531
+ var i = Number(cbor.read.int(node)), nm = IA_BY_INT[i];
532
+ if (nm === undefined) throw _err("c509/bad-extensions", "an accessMethod int " + i + " has no C509 sec. 8.11 registry row");
533
+ return oid.byName(nm);
534
+ }
535
+ return _oidName(node, "c509/bad-extensions", "an accessMethod").oid;
536
+ }
537
+ // A reasons uint (bit i -> named ReasonFlags bit i) -> the [1] IMPLICIT ReasonFlags BIT STRING TLV.
538
+ function _reasonsBitsToDer(value) {
539
+ // ReasonFlags bit 0 is reserved "unused" (RFC 5280 sec. 4.2.1.13; the reason bits are 1..8), so a value
540
+ // that sets it is not a valid ReasonFlags even though the shared 9-bit range check would accept it. Bit 0
541
+ // is a legitimate keyUsage bit (digitalSignature), so this reason-specific reject lives here, not in the
542
+ // shared named-bit helper -- a malformed native C509 reasons value fails closed rather than reconstructing
543
+ // a semantically invalid X.509 ReasonFlags.
544
+ if ((value & 1) !== 0) throw _err("c509/bad-extensions", "a cRLDistributionPoints reasons value must not set the reserved unused ReasonFlags bit 0 (RFC 5280 sec. 4.2.1.13)");
545
+ var c = _namedBitsToContent(value);
546
+ if (c == null) throw _err("c509/bad-extensions", "a cRLDistributionPoints reasons value must be within the 9 defined ReasonFlags bits");
547
+ return b.contextPrimitive(1, Buffer.concat([Buffer.from([c.unusedBits]), c.bytes]));
548
+ }
549
+ // A CBOR ~biguint serial node -> the DER INTEGER content octets (minimal two's-complement of the
550
+ // non-negative serial): the bare magnitude, prefixed with a 0x00 sign octet when its top bit is set.
551
+ function _serialIntContent(node) {
552
+ var mag = _minBytes(_biguint(node, "c509/bad-extensions", "an authorityKeyIdentifier serial"));
553
+ if (mag.length === 0) return Buffer.from([0x00]); // serial 0
554
+ return (mag[0] & 0x80) ? Buffer.concat([Buffer.from([0x00]), mag]) : mag;
555
+ }
556
+
557
+ // ---- certificatePolicies (draft-20 sec. 3.3 / sec. 8.9 / sec. 8.10; RFC 5280 sec. 4.2.1.4) ----
558
+ // A CBOR text -> a UNIVERSAL IA5String TLV, running the same 7-bit + CVE-2009-2408 control-byte guard the
559
+ // general-name IA5 arms use (never the bare b.ia5, which permits control bytes). Non-empty (the general-name
560
+ // IA5 arms reject empty too; a CPSuri parity tightening -- RFC 5280 sets no SIZE floor on CPSuri).
561
+ function _ia5Universal(text, label) {
562
+ if (text.length === 0) throw _err("c509/bad-extensions", label + " must be non-empty");
563
+ for (var i = 0; i < text.length; i++) { if (text.charCodeAt(i) > 0x7f) throw _err("c509/bad-extensions", label + " must be a 7-bit IA5String"); }
564
+ guard.name.assertPrintableIa5(Buffer.from(text, "latin1"), _err, "c509/bad-extensions", label);
565
+ return b.ia5(text);
566
+ }
567
+ // A CBOR policyIdentifier (a sec. 8.9 registry int, or an unwrapped ~oid) -> the dotted policy OID.
568
+ function _policyIdToDerOid(node) {
569
+ if (node.majorType === 0 || node.majorType === 1) {
570
+ var i = Number(cbor.read.int(node)), nm = CP_BY_INT[i];
571
+ if (nm === undefined) throw _err("c509/bad-extensions", "a certificatePolicies policy int " + i + " has no C509 sec. 8.9 registry row");
572
+ return oid.byName(nm);
573
+ }
574
+ return _oidName(node, "c509/bad-extensions", "a certificatePolicies policyIdentifier").oid;
575
+ }
576
+ // The inverse: a dotted policy OID -> CBOR (a sec. 8.9 int if registered, else an unwrapped ~oid).
577
+ function _policyIdFromDer(dotted) {
578
+ var i = CP_TO_INT[dotted];
579
+ return i !== undefined ? cbor.build.int(BigInt(i)) : _oidCbor(dotted);
580
+ }
581
+ // (qualifierId CBOR, qualifier-text CBOR) -> one DER PolicyQualifierInfo SEQUENCE { policyQualifierId OID,
582
+ // qualifier ANY DEFINED BY }. The qualifierId resolves to a sec. 8.10 int ONLY: a ~oid / unregistered
583
+ // qualifierId has no defined qualifier:text semantics, so it is not compact-representable (fail closed, never
584
+ // guess the ANY type). id-qt-cps -> CPSuri IA5String; id-qt-unotice -> UserNotice { explicitText utf8String }.
585
+ function _qualifierToDer(qidNode, qtextNode) {
586
+ if (qidNode.majorType !== 0 && qidNode.majorType !== 1) throw _err("c509/bad-extensions", "a policyQualifierId must be a C509 sec. 8.10 int (a ~oid qualifier is not compact-representable)");
587
+ var qi = Number(cbor.read.int(qidNode)), nm = PQ_BY_INT[qi];
588
+ if (nm === undefined) throw _err("c509/bad-extensions", "a policyQualifierId int " + qi + " has no C509 sec. 8.10 registry row");
589
+ if (qtextNode.majorType !== 3) throw _err("c509/bad-extensions", "a policyQualifier value must be a CBOR text string");
590
+ var text = cbor.read.textString(qtextNode);
591
+ if (qi === 1) return b.sequence([b.oid(oid.byName("cps")), _ia5Universal(text, "a CPSuri")]); // CPSuri ::= IA5String
592
+ // id-qt-unotice: UserNotice ::= SEQUENCE { explicitText utf8String } -- noticeRef omitted, DisplayText SIZE 1..200 floor.
593
+ if (text.length === 0) throw _err("c509/bad-extensions", "a UserNotice explicitText must be non-empty (DisplayText SIZE 1..200)");
594
+ return b.sequence([b.oid(oid.byName("unotice")), b.sequence([b.utf8(text)])]);
595
+ }
596
+ // One DER PolicyQualifierInfo node -> [ qidCbor, qtextCbor ], or null when not compact-representable: an
597
+ // unregistered qualifierId, a cps qualifier whose value is not a plain IA5String, or a UserNotice that is
598
+ // anything but SEQUENCE { explicitText utf8String } (a noticeRef, a non-UTF8String DisplayText arm, or more
599
+ // than the one explicitText child) -> whole-extension ~oid fallback.
600
+ function _qualifierFromDer(pq) {
601
+ var qid = asn1.read.oid(pq.children[0]), qi = PQ_TO_INT[qid];
602
+ if (qi === undefined) return null;
603
+ var q = pq.children[1];
604
+ if (qi === 1) { // CPSuri ::= IA5String
605
+ if (q.tagClass !== "universal" || q.tagNumber !== asn1.TAGS.IA5_STRING) return null;
606
+ var uri; try { uri = asn1.read.string(q); } catch (_e) { return null; }
607
+ return [cbor.build.int(1n), cbor.build.textString(uri)];
608
+ }
609
+ // id-qt-unotice: SEQUENCE { explicitText utf8String } ONLY (noticeRef absent).
610
+ if (q.tagClass !== "universal" || q.tagNumber !== asn1.TAGS.SEQUENCE || !q.children || q.children.length !== 1) return null;
611
+ var dt = q.children[0];
612
+ if (dt.tagClass !== "universal" || dt.tagNumber !== asn1.TAGS.UTF8_STRING) return null;
613
+ var txt; try { txt = asn1.read.string(dt); } catch (_e2) { return null; }
614
+ return [cbor.build.int(2n), cbor.build.textString(txt)];
615
+ }
616
+
617
+ // One CBOR DistributionPointName [ fullName, reasons, cRLIssuer ] -> one DER DistributionPoint SEQUENCE.
618
+ // distributionPoint [0] is EXPLICIT (it wraps the DistributionPointName CHOICE); fullName [0], reasons [1],
619
+ // cRLIssuer [2] are IMPLICIT (RFC 5280 sec. 4.2.1.13) -- mixing these is the classic byte-exactness trap.
620
+ function _dpToDer(dpNode) {
621
+ if (dpNode.majorType !== 4 || !dpNode.children || dpNode.children.length !== 3) throw _err("c509/bad-extensions", "a DistributionPoint must be a CBOR [ fullName, reasons, cRLIssuer ] array");
622
+ var fullName = dpNode.children[0], reasons = dpNode.children[1], crlIssuer = dpNode.children[2];
623
+ var uris;
624
+ if (fullName.majorType === 3) uris = [b.contextPrimitive(6, _ia5Bytes(fullName, 6))];
625
+ else if (fullName.majorType === 4 && fullName.children) {
626
+ if (fullName.children.length < 2) throw _err("c509/bad-extensions", "a DistributionPoint fullName array must hold 2 or more URIs (a single URI is a bare text; sec. 3.3)");
627
+ uris = fullName.children.map(function (u) { return b.contextPrimitive(6, _ia5Bytes(u, 6)); });
628
+ } else throw _err("c509/bad-extensions", "a DistributionPoint fullName must be a URI text or an array of URIs");
629
+ var fields = [b.explicit(0, b.contextConstructed(0, Buffer.concat(uris)))]; // distributionPoint [0] EXPLICIT { fullName [0] IMPLICIT GeneralNames }
630
+ if (!_isCborNull(reasons)) fields.push(_reasonsBitsToDer(Number(_cborUint(reasons, "cRLDistributionPoints reasons"))));
631
+ if (!_isCborNull(crlIssuer)) fields.push(b.contextConstructed(2, b.explicit(4, _reconName(_name509(crlIssuer, true))))); // cRLIssuer [2] { [4] directoryName }
632
+ return b.sequence(fields);
633
+ }
634
+ // One DER DistributionPoint SEQUENCE -> the pieces for the CBOR DistributionPointName, or null when the DP
635
+ // is not compact-representable (no fullName, a non-URI fullName member, a nameRelativeToCRLIssuer, or a
636
+ // cRLIssuer that is not a single directoryName). oneUri is set when fullName is exactly one URI, so the
637
+ // whole-extension bare-text shortcut can fire.
638
+ function _dpFromDer(dp) {
639
+ if (dp.tagClass !== "universal" || dp.tagNumber !== asn1.TAGS.SEQUENCE || !dp.children) return null;
640
+ var fullNameUris = null, reasonsVal = null, crlIssuerCbor = null, lastTag = -1;
641
+ for (var i = 0; i < dp.children.length; i++) {
642
+ var f = dp.children[i];
643
+ if (f.tagClass !== "context" || f.tagNumber <= lastTag) return null; // DER: unique + ascending
644
+ lastTag = f.tagNumber;
645
+ if (f.tagNumber === 0) {
646
+ if (!f.children || f.children.length !== 1) return null;
647
+ var dpn = f.children[0];
648
+ if (dpn.tagClass !== "context" || dpn.tagNumber !== 0 || !dpn.children || !dpn.children.length) return null; // fullName [0] only
649
+ fullNameUris = [];
650
+ for (var j = 0; j < dpn.children.length; j++) {
651
+ var mm = dpn.children[j];
652
+ if (mm.tagClass !== "context" || mm.tagNumber !== 6) return null; // non-URI fullName member
653
+ fullNameUris.push(schema.walk(GN_LEAF, mm, NS).value);
654
+ }
655
+ } else if (f.tagNumber === 1) {
656
+ var bs;
657
+ try { bs = asn1.read.bitStringImplicit(f, 1); } catch (_e) { return null; }
658
+ reasonsVal = _namedBitsFromContent(bs.bytes, bs.unusedBits);
659
+ if (reasonsVal == null) return null;
660
+ } else if (f.tagNumber === 2) {
661
+ if (!f.children || f.children.length !== 1) return null;
662
+ var ci = f.children[0];
663
+ if (ci.tagClass !== "context" || ci.tagNumber !== 4 || !ci.children || ci.children.length !== 1) return null; // one directoryName
664
+ try { crlIssuerCbor = _encName(_c509NameFromDer(ci.children[0].bytes), true); } catch (_e2) { return null; }
665
+ } else return null;
666
+ }
667
+ if (fullNameUris == null) return null; // C509 requires the fullName distributionPoint
668
+ var oneUri = fullNameUris.length === 1 ? fullNameUris[0] : null;
669
+ var fnCbor = oneUri != null ? cbor.build.textString(oneUri) : cbor.build.array(fullNameUris.map(function (u) { return cbor.build.textString(u); }));
670
+ return {
671
+ triple: cbor.build.array([fnCbor, reasonsVal == null ? cbor.build.nullValue() : cbor.build.uint(BigInt(reasonsVal)), crlIssuerCbor == null ? cbor.build.nullValue() : crlIssuerCbor]),
672
+ oneUri: oneUri, noReasons: reasonsVal == null, noIssuer: crlIssuerCbor == null,
673
+ };
674
+ }
675
+
238
676
  // Decode a compact extension value (a decoded CBOR node) to the DER extnValue inner content. Fails closed
239
677
  // (c509/bad-extensions) on a CBOR shape the named extension does not define.
240
678
  function _extValueToDer(name, node) {
@@ -251,9 +689,17 @@ function _extValueToDer(name, node) {
251
689
  if (iv >= 0n) return b.sequence([b.boolean(true), b.integer(iv)]); // cA true, pathLen
252
690
  throw _err("c509/bad-extensions", "a basicConstraints int " + iv + " is outside the -2/-1/pathLen range");
253
691
  }
254
- case "authorityKeyIdentifier": // keyId-only bytes -> SEQUENCE { [0] IMPLICIT keyIdentifier }
255
- if (node.majorType !== 2) throw _err("c509/bad-extensions", "an authorityKeyIdentifier value must be a CBOR byte string (keyId-only form; the 3-tuple form is not supported)");
256
- return b.sequence([b.contextPrimitive(0, node.content)]);
692
+ case "authorityKeyIdentifier": // keyId-only bytes, or [ keyId, authorityCertIssuer, serial ] (sec. 3.3)
693
+ if (node.majorType === 2) return b.sequence([b.contextPrimitive(0, node.content)]);
694
+ if (node.majorType === 4 && node.children && node.children.length === 3) {
695
+ if (node.children[0].majorType !== 2) throw _err("c509/bad-extensions", "an authorityKeyIdentifier keyIdentifier must be a CBOR byte string");
696
+ return b.sequence([
697
+ b.contextPrimitive(0, node.children[0].content), // keyIdentifier [0] IMPLICIT OCTET STRING
698
+ b.contextConstructed(1, Buffer.concat(_generalNamesToDer(node.children[1]))), // authorityCertIssuer [1] IMPLICIT GeneralNames
699
+ b.contextPrimitive(2, _serialIntContent(node.children[2])), // authorityCertSerialNumber [2] IMPLICIT INTEGER
700
+ ]);
701
+ }
702
+ throw _err("c509/bad-extensions", "an authorityKeyIdentifier value must be a keyId byte string or the [ keyId, authorityCertIssuer, serial ] array (sec. 3.3)");
257
703
  case "extKeyUsage": { // [2* KeyPurposeId] / KeyPurposeId -> SEQUENCE OF OID (draft-20 sec. 3.3)
258
704
  var items;
259
705
  if (node.majorType === 4) {
@@ -273,6 +719,57 @@ function _extValueToDer(name, node) {
273
719
  if (node.majorType !== 4) throw _err("c509/bad-extensions", "a tlsFeature value must be a CBOR array");
274
720
  return b.sequence((node.children || []).map(function (f) { return b.integer(_cborUint(f, "tlsFeature feature")); }));
275
721
  }
722
+ case "subjectAltName":
723
+ case "issuerAltName": // SubjectAltName = GeneralNames / text (exactly one dNSName -> bare text)
724
+ if (node.majorType === 3) return b.sequence([b.contextPrimitive(2, _ia5Bytes(node, 2))]);
725
+ return b.sequence(_generalNamesToDer(node));
726
+ case "nameConstraints": { // [ permittedSubtrees / null, excludedSubtrees / null ]
727
+ if (node.majorType !== 4 || !node.children || node.children.length !== 2) throw _err("c509/bad-extensions", "a nameConstraints value must be a 2-element CBOR array [ permitted, excluded ] (sec. 3.3)");
728
+ var ncFields = [];
729
+ if (!_isCborNull(node.children[0])) ncFields.push(b.contextConstructed(0, _subtreesToDer(node.children[0]))); // permittedSubtrees [0]
730
+ if (!_isCborNull(node.children[1])) ncFields.push(b.contextConstructed(1, _subtreesToDer(node.children[1]))); // excludedSubtrees [1]
731
+ if (ncFields.length === 0) throw _err("c509/bad-extensions", "nameConstraints must contain permittedSubtrees or excludedSubtrees (RFC 5280 sec. 4.2.1.10)");
732
+ return b.sequence(ncFields);
733
+ }
734
+ case "authorityInfoAccess":
735
+ case "subjectInfoAccess": { // [ accessMethod, uri, ... ] -> SEQUENCE OF AccessDescription { OID, [6] URI }
736
+ if (node.majorType !== 4 || !node.children) throw _err("c509/bad-extensions", "an " + name + " value must be a CBOR array");
737
+ var aiaKids = node.children;
738
+ if (aiaKids.length === 0 || aiaKids.length % 2 !== 0) throw _err("c509/bad-extensions", "an " + name + " array must be non-empty (accessMethod, uri) pairs (sec. 3.3)");
739
+ var descs = [];
740
+ for (var ai = 0; ai + 1 < aiaKids.length; ai += 2) descs.push(b.sequence([b.oid(_accessMethodOid(aiaKids[ai])), b.contextPrimitive(6, _ia5Bytes(aiaKids[ai + 1], 6))]));
741
+ return b.sequence(descs);
742
+ }
743
+ case "cRLDistributionPoints":
744
+ case "freshestCRL": // [ + DistributionPointName ] / text (one DP, one-URI fullName -> bare text)
745
+ if (node.majorType === 3) return b.sequence([b.sequence([b.explicit(0, b.contextConstructed(0, b.contextPrimitive(6, _ia5Bytes(node, 6))))])]);
746
+ if (node.majorType !== 4 || !node.children || node.children.length < 1) throw _err("c509/bad-extensions", "a " + name + " value must be a CBOR array of DistributionPoints or a bare URI text (sec. 3.3)");
747
+ return b.sequence(node.children.map(function (dp) { return _dpToDer(dp); }));
748
+ case "certificatePolicies": { // [ pid, [ *(qid, qtext) ], ... ] -> SEQUENCE OF PolicyInformation
749
+ if (node.majorType !== 4 || !node.children) throw _err("c509/bad-extensions", "a certificatePolicies value must be a CBOR array");
750
+ var cpKids = node.children;
751
+ if (cpKids.length === 0 || cpKids.length % 2 !== 0) throw _err("c509/bad-extensions", "a certificatePolicies array must be non-empty (policyIdentifier, qualifiers) pairs (sec. 3.3)");
752
+ var polInfos = [], seenPolicy = {};
753
+ for (var cpi = 0; cpi + 1 < cpKids.length; cpi += 2) {
754
+ var quals = cpKids[cpi + 1];
755
+ if (quals.majorType !== 4 || !quals.children) throw _err("c509/bad-extensions", "a certificatePolicies qualifiers slot must be a CBOR array");
756
+ // A policy OID MUST NOT appear more than once (RFC 5280 sec. 4.2.1.4); the toolkit's own DER decoder
757
+ // rejects a duplicate (schema-pkix certExtensionDecoders), so reconstruct fails closed rather than
758
+ // producing a certificatePolicies extension that decoder would reject.
759
+ var policyOid = _policyIdToDerOid(cpKids[cpi]);
760
+ if (seenPolicy[policyOid]) throw _err("c509/bad-extensions", "a certificatePolicies policy OID must not appear more than once (RFC 5280 sec. 4.2.1.4)");
761
+ seenPolicy[policyOid] = true;
762
+ var polFields = [b.oid(policyOid)];
763
+ if (quals.children.length) {
764
+ if (quals.children.length % 2 !== 0) throw _err("c509/bad-extensions", "a policyQualifiers array must be (policyQualifierId, qualifier) pairs");
765
+ var pqDers = [];
766
+ for (var qk = 0; qk + 1 < quals.children.length; qk += 2) pqDers.push(_qualifierToDer(quals.children[qk], quals.children[qk + 1]));
767
+ polFields.push(b.sequence(pqDers)); // policyQualifiers SEQUENCE OF PolicyQualifierInfo
768
+ }
769
+ polInfos.push(b.sequence(polFields));
770
+ }
771
+ return b.sequence(polInfos);
772
+ }
276
773
  default:
277
774
  throw _err("c509/bad-extensions", "extension " + name + " has no compact value decoder");
278
775
  }
@@ -303,10 +800,22 @@ function _extValueFromDer(name, der) {
303
800
  if (kids.length !== 2) return null;
304
801
  return cbor.build.uint(asn1.read.integer(kids[1])); // pathLen (>= 0; a negative INTEGER throws -> fall back)
305
802
  }
306
- case "authorityKeyIdentifier": { // SEQUENCE { [0] keyId } -> the bare key id
803
+ case "authorityKeyIdentifier": { // SEQUENCE { [0] keyId } or the 3-tuple form
307
804
  var akids = node.children || [];
308
- if (akids.length !== 1 || akids[0].tagNumber !== 0) return null; // 3-tuple / other forms fall back
309
- return cbor.build.byteString(akids[0].content);
805
+ if (akids.length === 1 && akids[0].tagClass === "context" && akids[0].tagNumber === 0) {
806
+ return cbor.build.byteString(asn1.read.octetStringImplicit(akids[0], 0)); // keyId-only
807
+ }
808
+ // the [ keyIdentifier [0], authorityCertIssuer [1], authorityCertSerialNumber [2] ] all-three form.
809
+ if (akids.length === 3 && akids[0].tagClass === "context" && akids[0].tagNumber === 0 &&
810
+ akids[1].tagClass === "context" && akids[1].tagNumber === 1 && akids[1].children &&
811
+ akids[2].tagClass === "context" && akids[2].tagNumber === 2) {
812
+ var akiIssuer = _generalNamesFromDer(akids[1].children);
813
+ if (akiIssuer == null) return null;
814
+ var akiSerial = asn1.read.integerImplicit(akids[2], 2);
815
+ if (akiSerial < 0n) return null; // C509 authorityCertSerialNumber is a non-negative ~biguint
816
+ return cbor.build.array([cbor.build.byteString(asn1.read.octetStringImplicit(akids[0], 0)), cbor.build.array(akiIssuer), cbor.build.byteString(_minBytes(akiSerial))]);
817
+ }
818
+ return null; // keyId+serial-without-issuer / issuer-only / other combinations fall back to ~oid
310
819
  }
311
820
  case "extKeyUsage": { // SEQUENCE OF OID -> [int/~oid ...] / single
312
821
  var purposes = node.children || [];
@@ -324,6 +833,79 @@ function _extValueFromDer(name, der) {
324
833
  return cbor.build.nullValue();
325
834
  case "tlsFeature": // SEQUENCE OF INTEGER -> [uint ...]
326
835
  return cbor.build.array((node.children || []).map(function (f) { return cbor.build.uint(asn1.read.integer(f)); }));
836
+ case "subjectAltName":
837
+ case "issuerAltName": { // SEQUENCE OF GeneralName -> flat array / dNSName text
838
+ if (node.tagClass !== "universal" || node.tagNumber !== asn1.TAGS.SEQUENCE || !node.children || node.children.length < 1) return null;
839
+ var sanMembers = node.children;
840
+ if (sanMembers.length === 1 && sanMembers[0].tagClass === "context" && sanMembers[0].tagNumber === 2) {
841
+ return cbor.build.textString(schema.walk(GN_LEAF, sanMembers[0], NS).value); // exactly one dNSName -> bare text
842
+ }
843
+ var sanItems = _generalNamesFromDer(sanMembers);
844
+ return sanItems == null ? null : cbor.build.array(sanItems);
845
+ }
846
+ case "nameConstraints": { // SEQUENCE { [0] permitted?, [1] excluded? } -> [perm, excl]
847
+ if (node.tagClass !== "universal" || node.tagNumber !== asn1.TAGS.SEQUENCE || !node.children || node.children.length < 1) return null;
848
+ var permCbor = cbor.build.nullValue(), exclCbor = cbor.build.nullValue(), sawNc = false, ncLast = -1;
849
+ for (var nci = 0; nci < node.children.length; nci++) {
850
+ var ncf = node.children[nci];
851
+ if (ncf.tagClass !== "context" || ncf.tagNumber <= ncLast) return null; // DER: unique + ascending
852
+ ncLast = ncf.tagNumber;
853
+ var subItems = _subtreesFromDer(ncf.children || []);
854
+ if (subItems == null) return null;
855
+ if (ncf.tagNumber === 0) { permCbor = cbor.build.array(subItems); sawNc = true; }
856
+ else if (ncf.tagNumber === 1) { exclCbor = cbor.build.array(subItems); sawNc = true; }
857
+ else return null;
858
+ }
859
+ return sawNc ? cbor.build.array([permCbor, exclCbor]) : null;
860
+ }
861
+ case "authorityInfoAccess":
862
+ case "subjectInfoAccess": { // SEQUENCE OF AccessDescription -> [method, uri, ...]
863
+ var aiaDescs = node.children || [];
864
+ if (node.tagClass !== "universal" || node.tagNumber !== asn1.TAGS.SEQUENCE || aiaDescs.length < 1) return null;
865
+ var aiaOut = [];
866
+ for (var adi = 0; adi < aiaDescs.length; adi++) {
867
+ var d = aiaDescs[adi];
868
+ if (d.tagClass !== "universal" || d.tagNumber !== asn1.TAGS.SEQUENCE || !d.children || d.children.length !== 2) return null;
869
+ var aiaLoc = d.children[1];
870
+ if (aiaLoc.tagClass !== "context" || aiaLoc.tagNumber !== 6) return null; // the compact form is URI-only
871
+ var methodDotted = asn1.read.oid(d.children[0]), mint = IA_TO_INT[methodDotted];
872
+ aiaOut.push(mint !== undefined ? cbor.build.int(BigInt(mint)) : _oidCbor(methodDotted));
873
+ aiaOut.push(cbor.build.textString(schema.walk(GN_LEAF, aiaLoc, NS).value));
874
+ }
875
+ return cbor.build.array(aiaOut);
876
+ }
877
+ case "cRLDistributionPoints":
878
+ case "freshestCRL": { // SEQUENCE OF DistributionPoint -> array / bare URI text
879
+ var dps = node.children || [];
880
+ if (node.tagClass !== "universal" || node.tagNumber !== asn1.TAGS.SEQUENCE || dps.length < 1) return null;
881
+ var dpResults = [];
882
+ for (var dpi = 0; dpi < dps.length; dpi++) { var dpr = _dpFromDer(dps[dpi]); if (dpr == null) return null; dpResults.push(dpr); }
883
+ if (dpResults.length === 1 && dpResults[0].oneUri != null && dpResults[0].noReasons && dpResults[0].noIssuer) return cbor.build.textString(dpResults[0].oneUri);
884
+ return cbor.build.array(dpResults.map(function (r) { return r.triple; }));
885
+ }
886
+ case "certificatePolicies": { // SEQUENCE OF PolicyInformation -> [ pid, [ *(qid, qtext) ], ... ]
887
+ if (node.tagClass !== "universal" || node.tagNumber !== asn1.TAGS.SEQUENCE || !node.children || node.children.length < 1) return null;
888
+ var cpOut = [];
889
+ for (var pli = 0; pli < node.children.length; pli++) {
890
+ var pol = node.children[pli];
891
+ if (pol.tagClass !== "universal" || pol.tagNumber !== asn1.TAGS.SEQUENCE || !pol.children || pol.children.length < 1 || pol.children.length > 2) return null;
892
+ cpOut.push(_policyIdFromDer(asn1.read.oid(pol.children[0])));
893
+ var qArr = [];
894
+ if (pol.children.length === 2) {
895
+ var qseq = pol.children[1];
896
+ if (qseq.tagClass !== "universal" || qseq.tagNumber !== asn1.TAGS.SEQUENCE || !qseq.children || !qseq.children.length) return null; // policyQualifiers SIZE 1..MAX
897
+ for (var qj = 0; qj < qseq.children.length; qj++) {
898
+ var pq = qseq.children[qj];
899
+ if (pq.tagClass !== "universal" || pq.tagNumber !== asn1.TAGS.SEQUENCE || !pq.children || pq.children.length !== 2) return null;
900
+ var qpair = _qualifierFromDer(pq);
901
+ if (qpair == null) return null; // any non-cps/unotice qualifier -> whole-ext fallback
902
+ qArr.push(qpair[0]); qArr.push(qpair[1]);
903
+ }
904
+ }
905
+ cpOut.push(cbor.build.array(qArr)); // empty [] when policyQualifiers absent
906
+ }
907
+ return cbor.build.array(cpOut);
908
+ }
327
909
  default:
328
910
  return null;
329
911
  }
@@ -334,12 +916,21 @@ function _extValueFromDer(name, der) {
334
916
 
335
917
  // Encode-side guard: emit the compact value only when it decodes back to the EXACT DER extnValue, so a
336
918
  // non-canonical or unrepresentable value can never produce a lossy compact form (it falls back to ~oid).
337
- // _extValueToDer is the exact inverse of _extValueFromDer, so the round-trip decode does not throw here;
338
- // the guard is the byte comparison (a canonical-equivalent DER differs and falls back).
919
+ // A value _extValueFromDer produced but _extValueToDer cannot reconstruct -- an empty GeneralNames the DER
920
+ // builder rejects (an AKI authorityCertIssuer [1] with no members), or any future codec asymmetry -- is
921
+ // NOT compact-representable: the round-trip reconstruction throwing is treated identically to a byte
922
+ // mismatch, so encode() falls back to the ~oid form rather than raising on a certificate x509.parse
923
+ // accepts. The final encode() self-verify still gates byte-exactness end to end.
339
924
  function _tryCompactExtValue(name, der) {
340
925
  var compact = _extValueFromDer(name, der);
341
926
  if (compact == null) return null;
342
- return _extValueToDer(name, cbor.decode(compact)).equals(der) ? compact : null;
927
+ var recon;
928
+ try {
929
+ recon = _extValueToDer(name, cbor.decode(compact));
930
+ } catch (_e) {
931
+ return null;
932
+ }
933
+ return recon.equals(der) ? compact : null;
343
934
  }
344
935
 
345
936
  // extensions (sec. 3.1.10/sec. 3.3/sec. 8.8): [ * Extension ] | a single keyUsage int-shortcut.
@@ -469,18 +1060,13 @@ function _reconSpki(spkAlg, keyBytes, rsaKey) {
469
1060
  }
470
1061
 
471
1062
  // The keyUsage int value -> the DER KeyUsage BIT STRING (RFC 5280 sec. 4.2.1.3): bit i of the value ->
472
- // BIT STRING named bit i (bit 0 = digitalSignature = the MSB of the first content octet).
1063
+ // BIT STRING named bit i (bit 0 = digitalSignature = the MSB of the first content octet). Composes the
1064
+ // shared named-bit content builder (also used by the cRLDistributionPoints reasons transform); a
1065
+ // non-positive, non-integer, or > 0x1FF value is not a valid KeyUsage and fails closed.
473
1066
  function _reconKeyUsageBits(value) {
474
- // The keyUsage value indexes the 9 named bits of RFC 5280 sec. 4.2.1.3 (digitalSignature..decipherOnly);
475
- // a non-positive, non-integer, or > 0x1FF value is not a valid KeyUsage and would also corrupt the
476
- // 32-bit bitwise re-encoding below (a value past 2^31 wraps). Fail closed before the bit walk.
477
- if (!Number.isInteger(value) || value <= 0 || value > 0x1ff) throw _err("c509/non-invertible", "a keyUsage value must be a positive integer within the 9 defined bits");
478
- var hi = 0; for (var t = value; t; t >>= 1) hi++; // number of significant bits
479
- hi -= 1; // highest set bit index
480
- var nbytes = (hi >> 3) + 1;
481
- var buf = Buffer.alloc(nbytes);
482
- for (var bit = 0; bit <= hi; bit++) { if (value & (1 << bit)) buf[bit >> 3] |= 0x80 >> (bit & 7); }
483
- return b.bitString(buf, 7 - (hi & 7));
1067
+ var c = _namedBitsToContent(value);
1068
+ if (c == null) throw _err("c509/non-invertible", "a keyUsage value must be a positive integer within the 9 defined bits");
1069
+ return b.bitString(c.bytes, c.unusedBits);
484
1070
  }
485
1071
 
486
1072
  // extensions -> the [3] EXPLICIT SEQUENCE OF Extension DER.
@@ -855,6 +1441,7 @@ function _c509NameFromDer(nameBytes) {
855
1441
  return { rdns: rdns };
856
1442
  }
857
1443
  // A keyUsage extnValue (a DER KeyUsage BIT STRING) -> the C509 integer whose bit i is the named bit i.
1444
+ // Composes the shared named-bit reader (also used by the cRLDistributionPoints reasons transform).
858
1445
  function _keyUsageBitsFromDer(extnValue) {
859
1446
  var bs;
860
1447
  try {
@@ -862,9 +1449,7 @@ function _keyUsageBitsFromDer(extnValue) {
862
1449
  } catch (_e) {
863
1450
  return null; // a malformed keyUsage BIT STRING cannot take the int shortcut -> encode it as a raw extension
864
1451
  }
865
- var total = bs.bytes.length * 8 - bs.unusedBits, value = 0;
866
- for (var bit = 0; bit < total && bit < 31; bit++) { if (bs.bytes[bit >> 3] & (0x80 >> (bit & 7))) value |= (1 << bit); }
867
- return value > 0 && value <= 0x1ff ? value : null;
1452
+ return _namedBitsFromContent(bs.bytes, bs.unusedBits);
868
1453
  }
869
1454
  var _NO_EXPIRY = Date.UTC(9999, 11, 31, 23, 59, 59);
870
1455
  // The C509 (OID/node) curve names <-> the WebCrypto namedCurve the P1363 converter expects, and the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.3.31",
3
+ "version": "0.3.33",
4
4
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
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:1d3e8266-55f8-442b-877c-abe084a62726",
5
+ "serialNumber": "urn:uuid:d39fe4d9-9f98-4126-8a96-8660ce1805e0",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-08-03T23:07:28.101Z",
8
+ "timestamp": "2026-08-06T04:08:23.299Z",
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.3.31",
22
+ "bom-ref": "@blamejs/pki@0.3.33",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.3.31",
25
+ "version": "0.3.33",
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.3.31",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.3.33",
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.3.31",
57
+ "ref": "@blamejs/pki@0.3.33",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]