micro509 0.15.0 → 0.17.0

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.
Files changed (55) hide show
  1. package/CHANGELOG.md +130 -1
  2. package/dist/index.d.ts +2 -2
  3. package/dist/index.js +3 -3
  4. package/dist/internal/jose/base64url.js +40 -0
  5. package/dist/internal/jose/base64url.js.map +1 -0
  6. package/dist/internal/jose/strict-json.d.ts +9 -0
  7. package/dist/internal/jose/strict-json.js +155 -0
  8. package/dist/internal/jose/strict-json.js.map +1 -0
  9. package/dist/internal/verify/spki-distrust.js +23 -0
  10. package/dist/internal/verify/spki-distrust.js.map +1 -0
  11. package/dist/internal/verify/verify-path.js +77 -60
  12. package/dist/internal/verify/verify-path.js.map +1 -1
  13. package/dist/jose/errors.d.ts +44 -0
  14. package/dist/jose/errors.js +11 -0
  15. package/dist/jose/errors.js.map +1 -0
  16. package/dist/jose/jwks.d.ts +93 -0
  17. package/dist/jose/jwks.js +193 -0
  18. package/dist/jose/jwks.js.map +1 -0
  19. package/dist/jose/jws.d.ts +158 -0
  20. package/dist/jose/jws.js +362 -0
  21. package/dist/jose/jws.js.map +1 -0
  22. package/dist/jose/jwt.d.ts +91 -0
  23. package/dist/jose/jwt.js +187 -0
  24. package/dist/jose/jwt.js.map +1 -0
  25. package/dist/jose/remote-jwks.d.ts +95 -0
  26. package/dist/jose/remote-jwks.js +298 -0
  27. package/dist/jose/remote-jwks.js.map +1 -0
  28. package/dist/jose.d.ts +7 -0
  29. package/dist/jose.js +5 -0
  30. package/dist/kdf/argon2.d.ts +78 -0
  31. package/dist/kdf/argon2.js +167 -0
  32. package/dist/kdf/argon2.js.map +1 -0
  33. package/dist/kdf.d.ts +2 -0
  34. package/dist/kdf.js +1 -0
  35. package/dist/keys/keys.d.ts +11 -8
  36. package/dist/keys/keys.js.map +1 -1
  37. package/dist/revocation/crl.js +2 -7
  38. package/dist/revocation/crl.js.map +1 -1
  39. package/dist/ssh/ssh.d.ts +200 -0
  40. package/dist/ssh/ssh.js +648 -0
  41. package/dist/ssh/ssh.js.map +1 -0
  42. package/dist/ssh/wire.d.ts +3 -0
  43. package/dist/ssh/wire.js +105 -0
  44. package/dist/ssh/wire.js.map +1 -0
  45. package/dist/ssh.d.ts +3 -0
  46. package/dist/ssh.js +1 -0
  47. package/dist/verify/verify.d.ts +32 -1
  48. package/dist/verify/verify.js +100 -58
  49. package/dist/verify/verify.js.map +1 -1
  50. package/dist/x509/fingerprint.d.ts +11 -0
  51. package/dist/x509/fingerprint.js +19 -1
  52. package/dist/x509/fingerprint.js.map +1 -1
  53. package/dist/x509.d.ts +2 -2
  54. package/dist/x509.js +3 -3
  55. package/package.json +20 -6
@@ -127,84 +127,93 @@ function rebaseDiagnostic(e, t, n) {
127
127
  * step. Returns the first fully anchored path or the deepest partial path
128
128
  * with the best failure encountered.
129
129
  */
130
- async function buildChainInternal(e, t, r, a, o, l, u = c, d = s) {
131
- let f = [...t, ...r], p = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new Map(), h = new Set(r.map((e) => fingerprint(e))), g = /* @__PURE__ */ new Map();
130
+ async function buildChainInternal(e, t, r, a, o, l, u = c, d = s, f = () => Promise.resolve(void 0)) {
131
+ let p, m = [...t, ...r], h = /* @__PURE__ */ new Map(), g = /* @__PURE__ */ new Map(), _ = new Set(r.map((e) => fingerprint(e))), v = /* @__PURE__ */ new Map();
132
132
  for (let e of a) {
133
- let t = i(e.subject), n = g.get(t);
134
- n === void 0 ? g.set(t, [e]) : n.push(e);
133
+ let t = i(e.subject), n = v.get(t);
134
+ n === void 0 ? v.set(t, [e]) : n.push(e);
135
135
  }
136
- let _ = { current: {
136
+ let y = { current: {
137
137
  kind: "none",
138
138
  path: [e]
139
- } }, v = /* @__PURE__ */ new Map(), y = [], b = /* @__PURE__ */ new Map(), x = {
139
+ } }, b = /* @__PURE__ */ new Map(), x = [], S = /* @__PURE__ */ new Map(), C = {
140
140
  remaining: d,
141
141
  exhausted: !1
142
- }, S = /* @__PURE__ */ new Map();
143
- f.forEach((e, t) => {
144
- let n = i(e.subject), r = p.get(n);
145
- r === void 0 ? p.set(n, [e]) : r.push(e), m.set(fingerprint(e), t);
142
+ }, w = /* @__PURE__ */ new Map();
143
+ m.forEach((e, t) => {
144
+ let n = i(e.subject), r = h.get(n);
145
+ r === void 0 ? h.set(n, [e]) : r.push(e), g.set(fingerprint(e), t);
146
146
  });
147
- let C = f.length + 1, w = fingerprint(e), T = await search(e, [e], /* @__PURE__ */ new Set([w]), 0);
148
- if (T !== void 0) {
149
- let e = T[T.length - 1];
147
+ let T = m.length + 1, E = fingerprint(e), D = await search(e, [e], /* @__PURE__ */ new Set([E]), 0);
148
+ if (D !== void 0) {
149
+ let e = D[D.length - 1];
150
150
  return {
151
- chain: T,
151
+ chain: D,
152
152
  foundTrustedRoot: !0,
153
- anchorCertificateInChain: e !== void 0 && h.has(fingerprint(e))
153
+ ...p !== void 0 && { trustAnchor: p },
154
+ anchorCertificateInChain: e !== void 0 && _.has(fingerprint(e))
154
155
  };
155
156
  }
156
- let E = _.current;
157
- if (x.exhausted) return {
158
- chain: E.path,
157
+ let O = y.current;
158
+ if (C.exhausted) return {
159
+ chain: O.path,
159
160
  foundTrustedRoot: !1,
160
161
  failure: l.failure("path_building_limit_exceeded", "path building stopped at its work limit", void 0, l.detail({
161
162
  expected: `at most ${d} issuer and trust-anchor checks`,
162
163
  actual: "limit reached before a trusted path was found"
163
164
  }))
164
165
  };
165
- switch (E.kind) {
166
+ switch (O.kind) {
166
167
  case "specific-failure": return {
167
- chain: E.path,
168
+ chain: O.path,
168
169
  foundTrustedRoot: !1,
169
- failure: E.failure
170
+ failure: O.failure
170
171
  };
171
172
  case "missing-issuer": return {
172
- chain: E.path,
173
+ chain: O.path,
173
174
  foundTrustedRoot: !1,
174
- missingIssuerAt: E.missingIssuerAt
175
+ missingIssuerAt: O.missingIssuerAt
175
176
  };
176
177
  case "untrusted-anchor":
177
178
  case "none": return {
178
- chain: E.path,
179
+ chain: O.path,
179
180
  foundTrustedRoot: !1
180
181
  };
181
- default: throw Error(`unreachable diagnostic ${String(E)}`);
182
+ default: throw Error(`unreachable diagnostic ${String(O)}`);
182
183
  }
183
184
  async function search(e, t, n, r) {
184
- if (x.exhausted) return;
185
- if (h.has(fingerprint(e))) return t;
186
- let i = await matchTrustAnchor(e, g, l, t.length - 1, verifyAnchorOnce, chargeBudget);
187
- if (x.exhausted) return;
188
- if (i.failure !== void 0 && recordFailure(i.failure, t), i.matched) return t;
189
- if (t.length > C) return;
190
- let a = `${fingerprint(e)}:${r}`, o = v.get(a);
191
- if (o !== void 0) {
192
- consider(rebaseDiagnostic(o.diagnostic, o.nodeIndex, t));
185
+ if (C.exhausted) return;
186
+ let i = await f(e.subjectPublicKeyInfoDer);
187
+ if (i !== void 0) {
188
+ recordFailure(l.failure("public_key_distrusted", "certificate public key is explicitly distrusted", t.length - 1, l.detail({
189
+ subjectCommonName: e.subject.values.commonName,
190
+ actual: i
191
+ })), t);
193
192
  return;
194
193
  }
195
- let s = { best: {
194
+ if (_.has(fingerprint(e))) return t;
195
+ let a = await matchTrustAnchor(e, v, l, t.length - 1, verifyAnchorOnce, chargeBudget, f);
196
+ if (C.exhausted) return;
197
+ if (a.failure !== void 0 && recordFailure(a.failure, t), a.matched) return p = a.anchor, t;
198
+ if (t.length > T) return;
199
+ let o = `${fingerprint(e)}:${r}`, s = b.get(o);
200
+ if (s !== void 0) {
201
+ consider(rebaseDiagnostic(s.diagnostic, s.nodeIndex, t));
202
+ return;
203
+ }
204
+ let c = { best: {
196
205
  kind: "none",
197
206
  path: t
198
207
  } };
199
- y.push(s);
208
+ x.push(c);
200
209
  try {
201
210
  let i = await searchBelow(e, t, n, r);
202
211
  if (i !== void 0) return i;
203
212
  } finally {
204
- y.pop();
213
+ x.pop();
205
214
  }
206
- v.set(a, {
207
- diagnostic: s.best,
215
+ b.set(o, {
216
+ diagnostic: c.best,
208
217
  nodeIndex: t.length - 1
209
218
  });
210
219
  }
@@ -218,7 +227,7 @@ async function buildChainInternal(e, t, r, a, o, l, u = c, d = s) {
218
227
  if (n.has(o)) continue;
219
228
  let s = await searchIssuerCandidate(e, a, o, t, n, r);
220
229
  if (s !== void 0) return s;
221
- if (x.exhausted) return;
230
+ if (C.exhausted) return;
222
231
  }
223
232
  i ? consider({
224
233
  kind: "none",
@@ -227,8 +236,8 @@ async function buildChainInternal(e, t, r, a, o, l, u = c, d = s) {
227
236
  }
228
237
  /** Yields the issuer bucket for `current`: AKI matches first, then roots, then input order. */
229
238
  function* issuerCandidates(e) {
230
- let t = i(e.issuer), n = S.get(t);
231
- n === void 0 && (n = rankBucket(p.get(t) ?? [], m, h), S.set(t, n));
239
+ let t = i(e.issuer), n = w.get(t);
240
+ n === void 0 && (n = rankBucket(h.get(t) ?? [], g, _), w.set(t, n));
232
241
  let r = e.authorityKeyIdentifier;
233
242
  if (r === void 0) yield* n.ordered;
234
243
  else {
@@ -256,7 +265,7 @@ async function buildChainInternal(e, t, r, a, o, l, u = c, d = s) {
256
265
  return c.add(n), await search(t, [...r, t], c, s.nextCaBelowCount);
257
266
  }
258
267
  function chargeBudget() {
259
- return x.remaining === 0 ? (x.exhausted = !0, !1) : (--x.remaining, !0);
268
+ return C.remaining === 0 ? (C.exhausted = !0, !1) : (--C.remaining, !0);
260
269
  }
261
270
  function verifySignatureOnce(e, t) {
262
271
  return verifyOnce(`c:${fingerprint(e)}:${n(t.subjectPublicKeyInfoDer)}`, () => u.certificate(e, t));
@@ -267,12 +276,12 @@ async function buildChainInternal(e, t, r, a, o, l, u = c, d = s) {
267
276
  }
268
277
  /** One signature check per distinct certificate-and-key pair for the whole search. */
269
278
  function verifyOnce(e, t) {
270
- let n = b.get(e);
271
- return n === void 0 && (n = t(), b.set(e, n)), n;
279
+ let n = S.get(e);
280
+ return n === void 0 && (n = t(), S.set(e, n)), n;
272
281
  }
273
282
  function consider(e) {
274
- isMoreSignificant(e, _.current) && (_.current = e);
275
- for (let t of y) isMoreSignificant(e, t.best) && (t.best = e);
283
+ isMoreSignificant(e, y.current) && (y.current = e);
284
+ for (let t of x) isMoreSignificant(e, t.best) && (t.best = e);
276
285
  }
277
286
  function recordFailure(e, t) {
278
287
  consider({
@@ -375,27 +384,35 @@ function isIssuerOf(e, t) {
375
384
  return a(t.issuer, e.subject);
376
385
  }
377
386
  /** Attempts to verify `certificate` against each bare trust anchor whose subject DN matches. */
378
- async function matchTrustAnchor(e, t, n, r, o, s) {
379
- let c = t.get(i(e.issuer));
380
- if (c === void 0) return { matched: !1 };
381
- let l;
382
- for (let t of c) {
387
+ async function matchTrustAnchor(e, t, n, r, o, s, c) {
388
+ let l = t.get(i(e.issuer));
389
+ if (l === void 0) return { matched: !1 };
390
+ let u;
391
+ for (let t of l) {
383
392
  if (!s()) return { matched: !1 };
384
393
  if (trustAnchorAkiMismatch(e, t) || !a(e.issuer, t.subject)) continue;
385
- let i = await o(e, t);
386
- if (!i.ok) l === void 0 && (l = n.failure(i.code, i.reason, r, n.detail({
394
+ let i = await c(t.subjectPublicKeyInfoDer);
395
+ if (i !== void 0) {
396
+ u = n.failure("public_key_distrusted", "bare trust anchor public key is explicitly distrusted", void 0, n.detail({ actual: i }));
397
+ continue;
398
+ }
399
+ let l = await o(e, t);
400
+ if (!l.ok) u ??= n.failure(l.code, l.reason, r, n.detail({
387
401
  subjectCommonName: e.subject.values.commonName,
388
- actual: i.reason
389
- })));
390
- else if (!i.valid) l === void 0 && (l = n.failure("signature_invalid", "certificate signature does not verify", r, n.detail({
402
+ actual: l.reason
403
+ }));
404
+ else if (!l.valid) u === void 0 && (u = n.failure("signature_invalid", "certificate signature does not verify", r, n.detail({
391
405
  subjectCommonName: e.subject.values.commonName,
392
406
  actual: "certificate signature does not verify"
393
407
  })));
394
- else return { matched: !0 };
408
+ else return {
409
+ matched: !0,
410
+ anchor: t
411
+ };
395
412
  }
396
- return l === void 0 ? { matched: !1 } : {
413
+ return u === void 0 ? { matched: !1 } : {
397
414
  matched: !1,
398
- failure: l
415
+ failure: u
399
416
  };
400
417
  }
401
418
  function trustAnchorAkiMismatch(e, t) {
@@ -1 +1 @@
1
- {"version":3,"file":"verify-path.js","names":["_exhaustive","DEFAULT_MAX_PATH_BUILDING_CHECKS","limit","certificate","at","compareDistinguishedNames","total","cursor","index","chain","loaded","source","sources","first","verifySignedDataDetailed","issuer","result","verify","error","refusal","decodeRefusalOf","DECODE_LIMIT_CODES","DEFAULT_SIGNATURE_CHECKS","DIAGNOSTIC_TIER","candidateTier","candidate","incumbentTier","incumbent","suffix","diagnostic","nodeIndex","spent","prefix","path","shift","candidates","intermediates","roots","subjectIndex","order","rootFingerprints","anchorIndex","anchor","trustAnchors","key","canonicalDnKey","existing","best","leaf","deadEnds","subtrees","signatureResults","budget","maxIssuerChecks","rankedBuckets","maxDepth","startFingerprint","success","terminal","owner","callbacks","current","matchedAnchor","memoKey","caBelowCount","memoized","subtree","issuerPath","visited","sawIssuer","issuerFingerprint","bucket","aki","nextVisited","toHex","signatureChecks","anchorKey","pending","run","candidateFailure","issuerConstraints","signatureResult","verifySignature","nextCaBelowCount","pathLength","parseCertificatesFromSource","ordered","members","leftFp","left","rightFp","right","rootScore","bySubjectKeyIdentifier","ski","child","anchors","firstFailure","charge","verified","verifyAnchor","value","fingerprintCache","cached"],"sources":["../../../src/internal/verify/verify-path.ts"],"sourcesContent":["/**\n * Internal certificate path-building and signature-check helpers.\n *\n * Loads and parses candidate certificates, ranks issuer candidates by AKI/root\n * affinity, matches against bare {@linkcode TrustAnchor}s, and performs the\n * depth-first chain search used by the public verify APIs in `verify.ts`.\n *\n * @module\n */\n\nimport { toHex } from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, decodeRefusalOf } from '#micro509/internal/asn1/decode-refusal';\nimport type { VerifySignedDataResult } from '#micro509/internal/crypto/sig-verify';\nimport { verifySignedDataDetailed } from '#micro509/internal/crypto/sig-verify';\nimport { canonicalDnKey, compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport type {\n\tCertificateSource,\n\tTrustAnchor,\n\tVerifyChainFailure,\n\tVerifyErrorCode,\n\tVerifyFailureDetails,\n} from '#micro509/verify/verify';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificatesFromSource } from '#micro509/x509/parse';\n\n/** Outcome of verifying one certificate's signature against its issuer's key. */\nexport type VerifyCertificateSignatureResult =\n\t| { readonly ok: true; readonly valid: boolean }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly code:\n\t\t\t\t| 'signature_invalid'\n\t\t\t\t| 'unsupported_signature_algorithm_parameters'\n\t\t\t\t| 'limit_exceeded';\n\t\t\treadonly reason: string;\n\t };\n\n/** Result of the internal chain-building search. */\nexport interface InternalBuildResult {\n\t/** Deepest chain found (leaf-to-root order), may be partial if no root was reached. */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** `true` when the chain terminates at a trusted root or anchor. */\n\treadonly foundTrustedRoot: boolean;\n\t/**\n\t * `true` when the terminal certificate in `chain` is a trusted root cert (and\n\t * so is excluded from policy/name processing); `false` when a bare trust\n\t * anchor verified the terminal certificate, which then stays a path cert.\n\t */\n\treadonly anchorCertificateInChain?: boolean;\n\t/** Chain index where no issuer candidate existed, when the search dead-ended. */\n\treadonly missingIssuerAt?: number;\n\t/** Best failure encountered during the search, for diagnostic reporting. */\n\treadonly failure?: VerifyChainFailure;\n}\n\n/** Result of attempting to match a certificate against bare trust anchors. */\ninterface TrustAnchorMatchResult {\n\t/** `true` if a trust anchor verified the certificate's signature. */\n\treadonly matched: boolean;\n\t/** Failure to report when matching was attempted but signature verification failed. */\n\treadonly failure?: VerifyChainFailure;\n}\n\ntype IssuerCandidateEvaluation =\n\t| { readonly ok: true; readonly nextCaBelowCount: number }\n\t| { readonly ok: false; readonly failure: VerifyChainFailure };\n\n/**\n * The signature checks {@linkcode buildChainInternal} performs, injected per\n * call. A caller can wrap them to observe how much cryptographic work path\n * building costs; replacing a global would leak across concurrent searches.\n */\nexport interface VerifyPathSignatureChecks {\n\t/** Verifies a certificate against a candidate issuer certificate. */\n\treadonly certificate: (\n\t\tcertificate: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t) => Promise<VerifyCertificateSignatureResult>;\n\t/** Verifies a certificate against a bare trust anchor. */\n\treadonly trustAnchor: (\n\t\tcertificate: ParsedCertificate,\n\t\tanchor: TrustAnchor,\n\t) => Promise<VerifyCertificateSignatureResult>;\n}\n\n/** Default upper bound on issuer candidates and trust anchors one path search may try. */\nexport const DEFAULT_MAX_PATH_BUILDING_CHECKS = 100_000;\n\n/** Throws when a caller-supplied path-building limit is not a positive safe integer. */\nexport function assertPathBuildingChecks(limit: number | undefined): void {\n\tif (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) {\n\t\tthrow new RangeError(`Invalid maxPathBuildingChecks: must be an integer >= 1, got ${limit}`);\n\t}\n}\n\n/** Loose input for constructing failure detail objects during path building. */\nexport interface VerifyPathFailureDetailsInput {\n\t/** Common name of the certificate under evaluation, if known. */\n\treadonly subjectCommonName?: string | undefined;\n\t/** Common name of the expected issuer, if known. */\n\treadonly issuerCommonName?: string | undefined;\n\t/** Description of what the check expected. */\n\treadonly expected?: string | undefined;\n\t/** Description of what the check actually observed. */\n\treadonly actual?: string | undefined;\n\t/** Common names of every certificate in the candidate chain. */\n\treadonly chainCommonNames?: readonly string[] | undefined;\n}\n\n/** Callbacks injected by the caller to construct failure objects during path building. */\nexport interface VerifyPathCallbacks {\n\t/** Constructs a {@linkcode VerifyChainFailure} from a code, message, chain index, and details. */\n\treadonly failure: (\n\t\tcode: VerifyErrorCode,\n\t\tmessage: string,\n\t\tindex?: number,\n\t\tdetails?: VerifyFailureDetails,\n\t) => VerifyChainFailure;\n\t/** Constructs a {@linkcode VerifyFailureDetails} from loose inputs. */\n\treadonly detail: (input: VerifyPathFailureDetailsInput) => VerifyFailureDetails;\n}\n\n/** Returns `true` if `at` falls within the certificate's notBefore/notAfter window (inclusive). */\nexport function isWithinValidity(certificate: ParsedCertificate, at: Date): boolean {\n\treturn (\n\t\tcertificate.notBefore.getTime() <= at.getTime() &&\n\t\tat.getTime() <= certificate.notAfter.getTime()\n\t);\n}\n\n/** Returns `true` if the certificate's subject and issuer DNs are semantically equal (RFC 5280 §7.1). */\nexport function isSelfIssued(certificate: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(certificate.subject, certificate.issuer);\n}\n\n/** Counts non-self-issued CA certificates in positions 0..(index-1) for pathLength checking. */\nexport function countCaCertificatesBelowParsed(\n\tchain: readonly ParsedCertificate[],\n\tindex: number,\n): number {\n\tlet total = 0;\n\tfor (let cursor = 1; cursor < index; cursor += 1) {\n\t\tconst certificate = chain[cursor];\n\t\tif (certificate?.basicConstraints?.ca === true && !isSelfIssued(certificate)) {\n\t\t\ttotal += 1;\n\t\t}\n\t}\n\treturn total;\n}\n\n/** Parses an array of PEM/DER sources into parsed certificates, expanding multi-block PEM. */\nexport function loadCertificates(\n\tsources: readonly CertificateSource[],\n): readonly ParsedCertificate[] {\n\tconst loaded: ParsedCertificate[] = [];\n\tfor (const source of sources) {\n\t\tloaded.push(...expandSource(source));\n\t}\n\treturn loaded;\n}\n\n/** Parses exactly one certificate from a PEM/DER source. Throws if the source contains zero or multiple certificates. */\nexport function loadSingleCertificate(source: CertificateSource): ParsedCertificate {\n\tconst loaded = expandSource(source);\n\tconst first = loaded[0];\n\tif (first === undefined) {\n\t\tthrow new Error('No certificate found');\n\t}\n\tif (loaded.length !== 1) {\n\t\tthrow new Error('Expected a single certificate source');\n\t}\n\treturn first;\n}\n\n/** Verifies that `certificate` was signed by `issuer`'s public key. */\nexport function verifyCertificateSignature(\n\tcertificate: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): Promise<VerifyCertificateSignatureResult> {\n\treturn signatureCheck(() =>\n\t\tverifySignedDataDetailed(\n\t\t\tcertificate.signatureAlgorithmOid,\n\t\t\tcertificate.signatureAlgorithmParametersDer,\n\t\t\tissuer.publicKeyAlgorithmOid,\n\t\t\tissuer.publicKeyParametersOid,\n\t\t\tissuer.subjectPublicKeyInfoDer,\n\t\t\tcertificate.signatureValue,\n\t\t\tcertificate.tbsCertificateDer,\n\t\t),\n\t);\n}\n\n/** Runs `verify` as a path check, reporting a runtime failure as `signature_invalid` and a decoding limit as `limit_exceeded`. */\nasync function signatureCheck(\n\tverify: () => Promise<VerifySignedDataResult>,\n): Promise<VerifyCertificateSignatureResult> {\n\tlet result: VerifySignedDataResult;\n\ttry {\n\t\tresult = await verify();\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\tif (refusal === undefined) {\n\t\t\tthrow error;\n\t\t}\n\t\treturn { ok: false, code: refusal.code, reason: refusal.message };\n\t}\n\treturn !result.ok && result.code === 'verification_error'\n\t\t? { ok: false, code: 'signature_invalid', reason: result.reason }\n\t\t: result;\n}\n\n/** The real signature checks, used unless a caller injects its own. */\nconst DEFAULT_SIGNATURE_CHECKS: VerifyPathSignatureChecks = {\n\tcertificate: verifyCertificateSignature,\n\ttrustAnchor: verifyTrustAnchorSignature,\n};\n\nexport type PathDiagnostic =\n\t| { readonly kind: 'none'; readonly path: readonly ParsedCertificate[] }\n\t| { readonly kind: 'untrusted-anchor'; readonly path: readonly ParsedCertificate[] }\n\t| {\n\t\t\treadonly kind: 'missing-issuer';\n\t\t\treadonly path: readonly ParsedCertificate[];\n\t\t\treadonly missingIssuerAt: number;\n\t }\n\t| {\n\t\t\treadonly kind: 'specific-failure';\n\t\t\treadonly path: readonly ParsedCertificate[];\n\t\t\treadonly failure: VerifyChainFailure;\n\t };\n\nconst DIAGNOSTIC_TIER = {\n\t'specific-failure': 3,\n\t'untrusted-anchor': 2,\n\t'missing-issuer': 1,\n\tnone: 0,\n} as const satisfies Record<PathDiagnostic['kind'], number>;\n\nfunction isMoreSignificant(candidate: PathDiagnostic, incumbent: PathDiagnostic): boolean {\n\tconst candidateTier = DIAGNOSTIC_TIER[candidate.kind];\n\tconst incumbentTier = DIAGNOSTIC_TIER[incumbent.kind];\n\treturn candidateTier === incumbentTier\n\t\t? candidate.path.length > incumbent.path.length\n\t\t: candidateTier > incumbentTier;\n}\n\ninterface DeadEnd {\n\treadonly diagnostic: PathDiagnostic;\n\treadonly nodeIndex: number;\n}\n\n/**\n * Moves a diagnostic recorded below the certificate at `nodeIndex` onto a new\n * prefix ending at that same certificate. A suffix that repeats a certificate\n * of the new prefix cannot form a path, so only the prefix is reported.\n */\nexport function rebaseDiagnostic(\n\tdiagnostic: PathDiagnostic,\n\tnodeIndex: number,\n\tprefix: readonly ParsedCertificate[],\n): PathDiagnostic {\n\tconst suffix = diagnostic.path.slice(nodeIndex + 1);\n\tconst spent = new Set(prefix.map((certificate) => fingerprint(certificate)));\n\tif (suffix.some((certificate) => spent.has(fingerprint(certificate)))) {\n\t\treturn { kind: 'none', path: prefix };\n\t}\n\tconst path = [...prefix, ...suffix];\n\tconst shift = prefix.length - 1 - nodeIndex;\n\tswitch (diagnostic.kind) {\n\t\tcase 'none':\n\t\tcase 'untrusted-anchor':\n\t\t\treturn { kind: diagnostic.kind, path };\n\t\tcase 'missing-issuer':\n\t\t\treturn { kind: 'missing-issuer', path, missingIssuerAt: diagnostic.missingIssuerAt + shift };\n\t\tcase 'specific-failure':\n\t\t\treturn {\n\t\t\t\tkind: 'specific-failure',\n\t\t\t\tpath,\n\t\t\t\tfailure:\n\t\t\t\t\tdiagnostic.failure.index === undefined\n\t\t\t\t\t\t? diagnostic.failure\n\t\t\t\t\t\t: { ...diagnostic.failure, index: diagnostic.failure.index + shift },\n\t\t\t};\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = diagnostic;\n\t\t\tthrow new Error(`unreachable diagnostic ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Depth-first chain search from leaf to root. Tries all issuer candidates,\n * checking validity, CA constraints, AKI, pathLength, and signatures at each\n * step. Returns the first fully anchored path or the deepest partial path\n * with the best failure encountered.\n */\nexport async function buildChainInternal(\n\tleaf: ParsedCertificate,\n\tintermediates: readonly ParsedCertificate[],\n\troots: readonly ParsedCertificate[],\n\ttrustAnchors: readonly TrustAnchor[],\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n\tsignatureChecks: VerifyPathSignatureChecks = DEFAULT_SIGNATURE_CHECKS,\n\tmaxIssuerChecks: number = DEFAULT_MAX_PATH_BUILDING_CHECKS,\n): Promise<InternalBuildResult> {\n\tconst candidates = [...intermediates, ...roots];\n\tconst subjectIndex = new Map<string, ParsedCertificate[]>();\n\tconst order = new Map<string, number>();\n\tconst rootFingerprints = new Set(roots.map((candidate) => fingerprint(candidate)));\n\tconst anchorIndex = new Map<string, TrustAnchor[]>();\n\tfor (const anchor of trustAnchors) {\n\t\tconst key = canonicalDnKey(anchor.subject);\n\t\tconst existing = anchorIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tanchorIndex.set(key, [anchor]);\n\t\t} else {\n\t\t\texisting.push(anchor);\n\t\t}\n\t}\n\tconst best: { current: PathDiagnostic } = { current: { kind: 'none', path: [leaf] } };\n\tconst deadEnds = new Map<string, DeadEnd>();\n\tconst subtrees: { best: PathDiagnostic }[] = [];\n\tconst signatureResults = new Map<string, Promise<VerifyCertificateSignatureResult>>();\n\tconst budget = { remaining: maxIssuerChecks, exhausted: false };\n\tconst rankedBuckets = new Map<string, RankedBucket>();\n\n\tcandidates.forEach((candidate, index) => {\n\t\tconst key = canonicalDnKey(candidate.subject);\n\t\tconst existing = subjectIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tsubjectIndex.set(key, [candidate]);\n\t\t} else {\n\t\t\texisting.push(candidate);\n\t\t}\n\t\torder.set(fingerprint(candidate), index);\n\t});\n\n\tconst maxDepth = candidates.length + 1;\n\tconst startFingerprint = fingerprint(leaf);\n\tconst success = await search(leaf, [leaf], new Set([startFingerprint]), 0);\n\tif (success !== undefined) {\n\t\tconst terminal = success[success.length - 1];\n\t\treturn {\n\t\t\tchain: success,\n\t\t\tfoundTrustedRoot: true,\n\t\t\tanchorCertificateInChain:\n\t\t\t\tterminal !== undefined && rootFingerprints.has(fingerprint(terminal)),\n\t\t};\n\t}\n\tconst owner = best.current;\n\tif (budget.exhausted) {\n\t\treturn {\n\t\t\tchain: owner.path,\n\t\t\tfoundTrustedRoot: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'path_building_limit_exceeded',\n\t\t\t\t'path building stopped at its work limit',\n\t\t\t\tundefined,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\texpected: `at most ${maxIssuerChecks} issuer and trust-anchor checks`,\n\t\t\t\t\tactual: 'limit reached before a trusted path was found',\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tswitch (owner.kind) {\n\t\tcase 'specific-failure':\n\t\t\treturn { chain: owner.path, foundTrustedRoot: false, failure: owner.failure };\n\t\tcase 'missing-issuer':\n\t\t\treturn {\n\t\t\t\tchain: owner.path,\n\t\t\t\tfoundTrustedRoot: false,\n\t\t\t\tmissingIssuerAt: owner.missingIssuerAt,\n\t\t\t};\n\t\tcase 'untrusted-anchor':\n\t\tcase 'none':\n\t\t\treturn { chain: owner.path, foundTrustedRoot: false };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = owner;\n\t\t\tthrow new Error(`unreachable diagnostic ${String(_exhaustive)}`);\n\t\t}\n\t}\n\n\tasync function search(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tif (budget.exhausted) return undefined;\n\t\tif (rootFingerprints.has(fingerprint(current))) {\n\t\t\treturn path;\n\t\t}\n\t\tconst matchedAnchor = await matchTrustAnchor(\n\t\t\tcurrent,\n\t\t\tanchorIndex,\n\t\t\tcallbacks,\n\t\t\tpath.length - 1,\n\t\t\tverifyAnchorOnce,\n\t\t\tchargeBudget,\n\t\t);\n\t\tif (budget.exhausted) return undefined;\n\t\tif (matchedAnchor.failure !== undefined) {\n\t\t\trecordFailure(matchedAnchor.failure, path);\n\t\t}\n\t\tif (matchedAnchor.matched) {\n\t\t\treturn path;\n\t\t}\n\t\tif (path.length > maxDepth) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst memoKey = `${fingerprint(current)}:${caBelowCount}`;\n\t\tconst memoized = deadEnds.get(memoKey);\n\t\tif (memoized !== undefined) {\n\t\t\tconsider(rebaseDiagnostic(memoized.diagnostic, memoized.nodeIndex, path));\n\t\t\treturn undefined;\n\t\t}\n\t\tconst subtree: { best: PathDiagnostic } = { best: { kind: 'none', path } };\n\t\tsubtrees.push(subtree);\n\t\ttry {\n\t\t\tconst issuerPath = await searchBelow(current, path, visited, caBelowCount);\n\t\t\tif (issuerPath !== undefined) return issuerPath;\n\t\t} finally {\n\t\t\tsubtrees.pop();\n\t\t}\n\t\tdeadEnds.set(memoKey, { diagnostic: subtree.best, nodeIndex: path.length - 1 });\n\t\treturn undefined;\n\t}\n\n\tasync function searchBelow(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tlet sawIssuer = false;\n\t\tfor (const issuer of issuerCandidates(current)) {\n\t\t\tif (!chargeBudget()) return undefined;\n\t\t\tif (!isIssuerOf(issuer, current)) continue;\n\t\t\tsawIssuer = true;\n\t\t\tconst issuerFingerprint = fingerprint(issuer);\n\t\t\tif (visited.has(issuerFingerprint)) continue;\n\t\t\tconst result = await searchIssuerCandidate(\n\t\t\t\tcurrent,\n\t\t\t\tissuer,\n\t\t\t\tissuerFingerprint,\n\t\t\t\tpath,\n\t\t\t\tvisited,\n\t\t\t\tcaBelowCount,\n\t\t\t);\n\t\t\tif (result !== undefined) return result;\n\t\t\tif (budget.exhausted) return undefined;\n\t\t}\n\t\tif (!sawIssuer) {\n\t\t\trecordMissingIssuers(current, path);\n\t\t\treturn undefined;\n\t\t}\n\t\tconsider({ kind: 'none', path });\n\t\treturn undefined;\n\t}\n\n\t/** Yields the issuer bucket for `current`: AKI matches first, then roots, then input order. */\n\tfunction* issuerCandidates(current: ParsedCertificate): Generator<ParsedCertificate> {\n\t\tconst key = canonicalDnKey(current.issuer);\n\t\tlet bucket = rankedBuckets.get(key);\n\t\tif (bucket === undefined) {\n\t\t\tbucket = rankBucket(subjectIndex.get(key) ?? [], order, rootFingerprints);\n\t\t\trankedBuckets.set(key, bucket);\n\t\t}\n\t\tconst aki = current.authorityKeyIdentifier;\n\t\tif (aki === undefined) {\n\t\t\tyield* bucket.ordered;\n\t\t\treturn;\n\t\t}\n\t\tyield* bucket.bySubjectKeyIdentifier.get(aki) ?? [];\n\t\tfor (const candidate of bucket.ordered) {\n\t\t\tif (candidate.subjectKeyIdentifier !== aki) yield candidate;\n\t\t}\n\t}\n\n\tfunction recordMissingIssuers(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t): void {\n\t\tif (isSelfIssued(current)) {\n\t\t\tconsider({ kind: 'untrusted-anchor', path });\n\t\t\treturn;\n\t\t}\n\t\tif (path.length > 1) {\n\t\t\tconsider({ kind: 'missing-issuer', path, missingIssuerAt: path.length - 1 });\n\t\t}\n\t}\n\n\tasync function searchIssuerCandidate(\n\t\tcurrent: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t\tissuerFingerprint: string,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tconst candidate = await evaluateIssuerCandidate(\n\t\t\tcurrent,\n\t\t\tissuer,\n\t\t\tpath,\n\t\t\tcaBelowCount,\n\t\t\tat,\n\t\t\tcallbacks,\n\t\t\tverifySignatureOnce,\n\t\t);\n\t\tif (!candidate.ok) {\n\t\t\trecordFailure(candidate.failure, path);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst nextVisited = new Set(visited);\n\t\tnextVisited.add(issuerFingerprint);\n\t\treturn await search(issuer, [...path, issuer], nextVisited, candidate.nextCaBelowCount);\n\t}\n\n\tfunction chargeBudget(): boolean {\n\t\tif (budget.remaining === 0) {\n\t\t\tbudget.exhausted = true;\n\t\t\treturn false;\n\t\t}\n\t\tbudget.remaining -= 1;\n\t\treturn true;\n\t}\n\n\tfunction verifySignatureOnce(\n\t\tcertificate: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t): Promise<VerifyCertificateSignatureResult> {\n\t\treturn verifyOnce(\n\t\t\t`c:${fingerprint(certificate)}:${toHex(issuer.subjectPublicKeyInfoDer)}`,\n\t\t\t() => signatureChecks.certificate(certificate, issuer),\n\t\t);\n\t}\n\n\tfunction verifyAnchorOnce(\n\t\tcertificate: ParsedCertificate,\n\t\tanchor: TrustAnchor,\n\t): Promise<VerifyCertificateSignatureResult> {\n\t\tconst anchorKey = `${anchor.publicKeyAlgorithmOid}:${anchor.publicKeyParametersOid ?? ''}:${toHex(\n\t\t\tanchor.subjectPublicKeyInfoDer,\n\t\t)}`;\n\t\treturn verifyOnce(`a:${fingerprint(certificate)}:${anchorKey}`, () =>\n\t\t\tsignatureChecks.trustAnchor(certificate, anchor),\n\t\t);\n\t}\n\n\t/** One signature check per distinct certificate-and-key pair for the whole search. */\n\tfunction verifyOnce(\n\t\tkey: string,\n\t\trun: () => Promise<VerifyCertificateSignatureResult>,\n\t): Promise<VerifyCertificateSignatureResult> {\n\t\tlet pending = signatureResults.get(key);\n\t\tif (pending === undefined) {\n\t\t\tpending = run();\n\t\t\tsignatureResults.set(key, pending);\n\t\t}\n\t\treturn pending;\n\t}\n\n\tfunction consider(candidate: PathDiagnostic): void {\n\t\tif (isMoreSignificant(candidate, best.current)) {\n\t\t\tbest.current = candidate;\n\t\t}\n\t\tfor (const subtree of subtrees) {\n\t\t\tif (isMoreSignificant(candidate, subtree.best)) {\n\t\t\t\tsubtree.best = candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction recordFailure(\n\t\tcandidateFailure: VerifyChainFailure,\n\t\tpath: readonly ParsedCertificate[],\n\t): void {\n\t\tconsider({ kind: 'specific-failure', path, failure: candidateFailure });\n\t}\n}\n\n/** Applies issuer constraints and signature verification to one path candidate. */\nasync function evaluateIssuerCandidate(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n\tverifySignature: typeof verifyCertificateSignature,\n): Promise<IssuerCandidateEvaluation> {\n\tconst issuerConstraints = evaluateIssuerConstraints(\n\t\tcurrent,\n\t\tissuer,\n\t\tpath,\n\t\tcaBelowCount,\n\t\tat,\n\t\tcallbacks,\n\t);\n\tif (!issuerConstraints.ok) {\n\t\treturn issuerConstraints;\n\t}\n\tconst signatureResult = await verifySignature(current, issuer);\n\tif (!signatureResult.ok) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\tsignatureResult.code,\n\t\t\t\tsignatureResult.reason,\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\tactual: signatureResult.reason,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tif (!signatureResult.valid) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'certificate signature does not verify',\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\treturn issuerConstraints;\n}\n\nfunction evaluateIssuerConstraints(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n): IssuerCandidateEvaluation {\n\tif (!isWithinValidity(issuer, at)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'certificate_expired',\n\t\t\t\t'certificate not valid at requested time',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: describeDateTime(at),\n\t\t\t\t\tactual: `${describeDateTime(issuer.notBefore)}..${describeDateTime(issuer.notAfter)}`,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tif (issuer.basicConstraints?.ca !== true) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'ca_required',\n\t\t\t\t'issuer must be a CA certificate',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({ subjectCommonName: issuer.subject.values.commonName }),\n\t\t\t),\n\t\t};\n\t}\n\treturn evaluateIssuerKeyConstraints(current, issuer, path, caBelowCount, callbacks);\n}\n\nfunction evaluateIssuerKeyConstraints(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tcallbacks: VerifyPathCallbacks,\n): IssuerCandidateEvaluation {\n\tif (issuer.keyUsage !== undefined && !issuer.keyUsage.flags.includes('keyCertSign')) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'key_cert_sign_required',\n\t\t\t\t'issuer missing keyCertSign',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({ subjectCommonName: issuer.subject.values.commonName }),\n\t\t\t),\n\t\t};\n\t}\n\tif (authorityKeyIdentifierMismatch(current, issuer)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'authority_key_identifier_mismatch',\n\t\t\t\t'authorityKeyIdentifier does not match issuer subjectKeyIdentifier',\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: issuer.subjectKeyIdentifier,\n\t\t\t\t\tactual: current.authorityKeyIdentifier,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tconst nextCaBelowCount =\n\t\tcaBelowCount +\n\t\t(current.basicConstraints?.ca === true && !isSelfIssued(current) && path.length > 1 ? 1 : 0);\n\tconst pathLength = issuer.basicConstraints?.pathLength;\n\tif (isNonNegativeInteger(pathLength) && nextCaBelowCount > pathLength) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'path_length_exceeded',\n\t\t\t\t'path length constraint exceeded',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: String(pathLength),\n\t\t\t\t\tactual: String(nextCaBelowCount),\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\treturn { ok: true, nextCaBelowCount };\n}\n\nexport function authorityKeyIdentifierMismatch(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): boolean {\n\treturn (\n\t\tcurrent.authorityKeyIdentifier !== undefined &&\n\t\tissuer.subjectKeyIdentifier !== undefined &&\n\t\tcurrent.authorityKeyIdentifier !== issuer.subjectKeyIdentifier\n\t);\n}\n\n/** Expands a PEM (possibly multi-block) or DER source into parsed certificates. */\nfunction expandSource(source: CertificateSource): readonly ParsedCertificate[] {\n\treturn parseCertificatesFromSource(source);\n}\n\ninterface RankedBucket {\n\treadonly ordered: readonly ParsedCertificate[];\n\treadonly bySubjectKeyIdentifier: ReadonlyMap<string, readonly ParsedCertificate[]>;\n}\n\n/** Orders one subject bucket once, roots first and then input order, and indexes it by SKI. */\nfunction rankBucket(\n\tmembers: readonly ParsedCertificate[],\n\torder: ReadonlyMap<string, number>,\n\trootFingerprints: ReadonlySet<string>,\n): RankedBucket {\n\tconst ordered = [...members].sort((left, right) => {\n\t\tconst leftFp = fingerprint(left);\n\t\tconst rightFp = fingerprint(right);\n\t\tconst rootScore = compareBooleans(rootFingerprints.has(leftFp), rootFingerprints.has(rightFp));\n\t\tif (rootScore !== 0) {\n\t\t\treturn rootScore;\n\t\t}\n\t\treturn (\n\t\t\t(order.get(leftFp) ?? Number.MAX_SAFE_INTEGER) -\n\t\t\t(order.get(rightFp) ?? Number.MAX_SAFE_INTEGER)\n\t\t);\n\t});\n\tconst bySubjectKeyIdentifier = new Map<string, ParsedCertificate[]>();\n\tfor (const candidate of ordered) {\n\t\tconst ski = candidate.subjectKeyIdentifier;\n\t\tif (ski === undefined) continue;\n\t\tconst existing = bySubjectKeyIdentifier.get(ski);\n\t\tif (existing === undefined) {\n\t\t\tbySubjectKeyIdentifier.set(ski, [candidate]);\n\t\t} else {\n\t\t\texisting.push(candidate);\n\t\t}\n\t}\n\treturn { ordered, bySubjectKeyIdentifier };\n}\n\n/** Sort comparator: `true` sorts before `false`. Returns -1, 0, or 1. */\nfunction compareBooleans(left: boolean, right: boolean): number {\n\tif (left === right) {\n\t\treturn 0;\n\t}\n\treturn left ? -1 : 1;\n}\n\n/** Returns `true` if `issuer`'s subject DN semantically matches `child`'s issuer DN (RFC 5280 §7.1). */\nfunction isIssuerOf(issuer: ParsedCertificate, child: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(child.issuer, issuer.subject);\n}\n\n/** Attempts to verify `certificate` against each bare trust anchor whose subject DN matches. */\nasync function matchTrustAnchor(\n\tcertificate: ParsedCertificate,\n\tanchorIndex: ReadonlyMap<string, readonly TrustAnchor[]>,\n\tcallbacks: VerifyPathCallbacks,\n\tindex: number,\n\tverifyAnchor: typeof verifyTrustAnchorSignature,\n\tcharge: () => boolean,\n): Promise<TrustAnchorMatchResult> {\n\tconst anchors = anchorIndex.get(canonicalDnKey(certificate.issuer));\n\tif (anchors === undefined) {\n\t\treturn { matched: false };\n\t}\n\tlet firstFailure: VerifyChainFailure | undefined;\n\tfor (const anchor of anchors) {\n\t\tif (!charge()) return { matched: false };\n\t\tif (trustAnchorAkiMismatch(certificate, anchor)) continue;\n\t\t// The canonicalDnKey bucket is not proof of DN equality (prohibited values\n\t\t// are non-reflexive and prepared/tagged namespaces can collide), so confirm\n\t\t// the anchor's subject actually equals the certificate's issuer.\n\t\tif (!compareDistinguishedNames(certificate.issuer, anchor.subject)) continue;\n\t\tconst verified = await verifyAnchor(certificate, anchor);\n\t\tif (!verified.ok) {\n\t\t\t// Capture the first failure but continue trying other anchors\n\t\t\tif (firstFailure === undefined) {\n\t\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t\tverified.code,\n\t\t\t\t\tverified.reason,\n\t\t\t\t\tindex,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: verified.reason,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (!verified.valid) {\n\t\t\tif (firstFailure === undefined) {\n\t\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate signature does not verify',\n\t\t\t\t\tindex,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: 'certificate signature does not verify',\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\treturn { matched: true };\n\t}\n\treturn firstFailure !== undefined\n\t\t? { matched: false, failure: firstFailure }\n\t\t: { matched: false };\n}\n\nfunction trustAnchorAkiMismatch(certificate: ParsedCertificate, anchor: TrustAnchor): boolean {\n\treturn (\n\t\tanchor.subjectKeyIdentifier !== undefined &&\n\t\tcertificate.authorityKeyIdentifier !== undefined &&\n\t\tanchor.subjectKeyIdentifier !== certificate.authorityKeyIdentifier\n\t);\n}\n\n/** Verifies that `certificate` was signed by a bare trust anchor's key. */\nexport function verifyTrustAnchorSignature(\n\tcertificate: ParsedCertificate,\n\tanchor: TrustAnchor,\n): Promise<VerifyCertificateSignatureResult> {\n\treturn signatureCheck(() =>\n\t\tverifySignedDataDetailed(\n\t\t\tcertificate.signatureAlgorithmOid,\n\t\t\tcertificate.signatureAlgorithmParametersDer,\n\t\t\tanchor.publicKeyAlgorithmOid,\n\t\t\tanchor.publicKeyParametersOid,\n\t\t\tanchor.subjectPublicKeyInfoDer,\n\t\t\tcertificate.signatureValue,\n\t\t\tcertificate.tbsCertificateDer,\n\t\t),\n\t);\n}\n\nfunction describeDateTime(value: Date): string {\n\treturn Number.isNaN(value.getTime()) ? '<invalid date>' : value.toISOString();\n}\n\nfunction isNonNegativeInteger(value: number | undefined): value is number {\n\treturn value !== undefined && Number.isInteger(value) && value >= 0;\n}\n\n/** Cache for computed fingerprints to avoid repeated toHex() calls. */\nconst fingerprintCache = new WeakMap<ParsedCertificate, string>();\n\n/** Returns a hex fingerprint of the certificate's raw DER, used for cycle detection and dedup. */\nfunction fingerprint(certificate: ParsedCertificate): string {\n\tlet cached = fingerprintCache.get(certificate);\n\tif (cached === undefined) {\n\t\tcached = toHex(certificate.der);\n\t\tfingerprintCache.set(certificate, cached);\n\t}\n\treturn cached;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsFA,MAAaC,IAAmC;;AAGhD,SAAgB,yBAAyB,GAAiC;CACzE,IAAIC,MAAU,KAAA,MAAc,CAAC,OAAO,cAAcA,CAAK,KAAKA,IAAQ,IACnE,MAAU,WAAW,+DAA+DA,GAAO;AAE7F;;AA8BA,SAAgB,iBAAiB,GAAgC,GAAmB;CACnF,OACCC,EAAY,UAAU,QAAQ,KAAKC,EAAG,QAAQ,KAC9CA,EAAG,QAAQ,KAAKD,EAAY,SAAS,QAAQ;AAE/C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EAAY,GAAG,GAC9BmG,EAAiB,IAAInG,GAAaoG,CAAM,IAElCA;AACR"}
1
+ {"version":3,"file":"verify-path.js","names":["_exhaustive","DEFAULT_MAX_PATH_BUILDING_CHECKS","limit","certificate","at","compareDistinguishedNames","total","cursor","index","chain","loaded","source","sources","first","verifySignedDataDetailed","issuer","result","verify","error","refusal","decodeRefusalOf","DECODE_LIMIT_CODES","DEFAULT_SIGNATURE_CHECKS","DIAGNOSTIC_TIER","candidateTier","candidate","incumbentTier","incumbent","suffix","diagnostic","nodeIndex","spent","prefix","path","shift","selectedAnchor","candidates","intermediates","roots","subjectIndex","order","rootFingerprints","anchorIndex","anchor","trustAnchors","key","canonicalDnKey","existing","best","leaf","deadEnds","subtrees","signatureResults","budget","maxIssuerChecks","rankedBuckets","maxDepth","startFingerprint","success","terminal","owner","callbacks","blockedHash","distrust","current","matchedAnchor","memoKey","caBelowCount","memoized","subtree","issuerPath","visited","sawIssuer","issuerFingerprint","bucket","aki","nextVisited","toHex","signatureChecks","anchorKey","pending","run","candidateFailure","issuerConstraints","signatureResult","verifySignature","nextCaBelowCount","pathLength","parseCertificatesFromSource","ordered","members","leftFp","left","rightFp","right","rootScore","bySubjectKeyIdentifier","ski","child","anchors","firstFailure","charge","verified","verifyAnchor","value","fingerprintCache","cached"],"sources":["../../../src/internal/verify/verify-path.ts"],"sourcesContent":["/**\n * Internal certificate path-building and signature-check helpers.\n *\n * Loads and parses candidate certificates, ranks issuer candidates by AKI/root\n * affinity, matches against bare {@linkcode TrustAnchor}s, and performs the\n * depth-first chain search used by the public verify APIs in `verify.ts`.\n *\n * @module\n */\n\nimport { toHex } from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, decodeRefusalOf } from '#micro509/internal/asn1/decode-refusal';\nimport type { VerifySignedDataResult } from '#micro509/internal/crypto/sig-verify';\nimport { verifySignedDataDetailed } from '#micro509/internal/crypto/sig-verify';\nimport { canonicalDnKey, compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport type {\n\tCertificateSource,\n\tTrustAnchor,\n\tVerifyChainFailure,\n\tVerifyErrorCode,\n\tVerifyFailureDetails,\n} from '#micro509/verify/verify';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificatesFromSource } from '#micro509/x509/parse';\n\n/** Outcome of verifying one certificate's signature against its issuer's key. */\nexport type VerifyCertificateSignatureResult =\n\t| { readonly ok: true; readonly valid: boolean }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly code:\n\t\t\t\t| 'signature_invalid'\n\t\t\t\t| 'unsupported_signature_algorithm_parameters'\n\t\t\t\t| 'limit_exceeded';\n\t\t\treadonly reason: string;\n\t };\n\n/** Result of the internal chain-building search. */\nexport interface InternalBuildResult {\n\t/** Deepest chain found (leaf-to-root order), may be partial if no root was reached. */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** `true` when the chain terminates at a trusted root or anchor. */\n\treadonly foundTrustedRoot: boolean;\n\t/**\n\t * `true` when the terminal certificate in `chain` is a trusted root cert (and\n\t * so is excluded from policy/name processing); `false` when a bare trust\n\t * anchor verified the terminal certificate, which then stays a path cert.\n\t */\n\treadonly anchorCertificateInChain?: boolean;\n\t/** Bare trust anchor that completed the path. */\n\treadonly trustAnchor?: TrustAnchor;\n\t/** Chain index where no issuer candidate existed, when the search dead-ended. */\n\treadonly missingIssuerAt?: number;\n\t/** Best failure encountered during the search, for diagnostic reporting. */\n\treadonly failure?: VerifyChainFailure;\n}\n\n/** Result of attempting to match a certificate against bare trust anchors. */\ninterface TrustAnchorMatchResult {\n\t/** `true` if a trust anchor verified the certificate's signature. */\n\treadonly matched: boolean;\n\t/** Selected bare trust anchor on success. */\n\treadonly anchor?: TrustAnchor;\n\t/** Failure to report when matching was attempted but signature verification failed. */\n\treadonly failure?: VerifyChainFailure;\n}\n\ntype IssuerCandidateEvaluation =\n\t| { readonly ok: true; readonly nextCaBelowCount: number }\n\t| { readonly ok: false; readonly failure: VerifyChainFailure };\n\n/**\n * The signature checks {@linkcode buildChainInternal} performs, injected per\n * call. A caller can wrap them to observe how much cryptographic work path\n * building costs; replacing a global would leak across concurrent searches.\n */\nexport interface VerifyPathSignatureChecks {\n\t/** Verifies a certificate against a candidate issuer certificate. */\n\treadonly certificate: (\n\t\tcertificate: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t) => Promise<VerifyCertificateSignatureResult>;\n\t/** Verifies a certificate against a bare trust anchor. */\n\treadonly trustAnchor: (\n\t\tcertificate: ParsedCertificate,\n\t\tanchor: TrustAnchor,\n\t) => Promise<VerifyCertificateSignatureResult>;\n}\n\n/** Default upper bound on issuer candidates and trust anchors one path search may try. */\nexport const DEFAULT_MAX_PATH_BUILDING_CHECKS = 100_000;\n\n/** Throws when a caller-supplied path-building limit is not a positive safe integer. */\nexport function assertPathBuildingChecks(limit: number | undefined): void {\n\tif (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) {\n\t\tthrow new RangeError(`Invalid maxPathBuildingChecks: must be an integer >= 1, got ${limit}`);\n\t}\n}\n\n/** Loose input for constructing failure detail objects during path building. */\nexport interface VerifyPathFailureDetailsInput {\n\t/** Common name of the certificate under evaluation, if known. */\n\treadonly subjectCommonName?: string | undefined;\n\t/** Common name of the expected issuer, if known. */\n\treadonly issuerCommonName?: string | undefined;\n\t/** Description of what the check expected. */\n\treadonly expected?: string | undefined;\n\t/** Description of what the check actually observed. */\n\treadonly actual?: string | undefined;\n\t/** Common names of every certificate in the candidate chain. */\n\treadonly chainCommonNames?: readonly string[] | undefined;\n}\n\n/** Callbacks injected by the caller to construct failure objects during path building. */\nexport interface VerifyPathCallbacks {\n\t/** Constructs a {@linkcode VerifyChainFailure} from a code, message, chain index, and details. */\n\treadonly failure: (\n\t\tcode: VerifyErrorCode,\n\t\tmessage: string,\n\t\tindex?: number,\n\t\tdetails?: VerifyFailureDetails,\n\t) => VerifyChainFailure;\n\t/** Constructs a {@linkcode VerifyFailureDetails} from loose inputs. */\n\treadonly detail: (input: VerifyPathFailureDetailsInput) => VerifyFailureDetails;\n}\n\n/** Returns `true` if `at` falls within the certificate's notBefore/notAfter window (inclusive). */\nexport function isWithinValidity(certificate: ParsedCertificate, at: Date): boolean {\n\treturn (\n\t\tcertificate.notBefore.getTime() <= at.getTime() &&\n\t\tat.getTime() <= certificate.notAfter.getTime()\n\t);\n}\n\n/** Returns `true` if the certificate's subject and issuer DNs are semantically equal (RFC 5280 §7.1). */\nexport function isSelfIssued(certificate: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(certificate.subject, certificate.issuer);\n}\n\n/** Counts non-self-issued CA certificates in positions 0..(index-1) for pathLength checking. */\nexport function countCaCertificatesBelowParsed(\n\tchain: readonly ParsedCertificate[],\n\tindex: number,\n): number {\n\tlet total = 0;\n\tfor (let cursor = 1; cursor < index; cursor += 1) {\n\t\tconst certificate = chain[cursor];\n\t\tif (certificate?.basicConstraints?.ca === true && !isSelfIssued(certificate)) {\n\t\t\ttotal += 1;\n\t\t}\n\t}\n\treturn total;\n}\n\n/** Parses an array of PEM/DER sources into parsed certificates, expanding multi-block PEM. */\nexport function loadCertificates(\n\tsources: readonly CertificateSource[],\n): readonly ParsedCertificate[] {\n\tconst loaded: ParsedCertificate[] = [];\n\tfor (const source of sources) {\n\t\tloaded.push(...expandSource(source));\n\t}\n\treturn loaded;\n}\n\n/** Parses exactly one certificate from a PEM/DER source. Throws if the source contains zero or multiple certificates. */\nexport function loadSingleCertificate(source: CertificateSource): ParsedCertificate {\n\tconst loaded = expandSource(source);\n\tconst first = loaded[0];\n\tif (first === undefined) {\n\t\tthrow new Error('No certificate found');\n\t}\n\tif (loaded.length !== 1) {\n\t\tthrow new Error('Expected a single certificate source');\n\t}\n\treturn first;\n}\n\n/** Verifies that `certificate` was signed by `issuer`'s public key. */\nexport function verifyCertificateSignature(\n\tcertificate: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): Promise<VerifyCertificateSignatureResult> {\n\treturn signatureCheck(() =>\n\t\tverifySignedDataDetailed(\n\t\t\tcertificate.signatureAlgorithmOid,\n\t\t\tcertificate.signatureAlgorithmParametersDer,\n\t\t\tissuer.publicKeyAlgorithmOid,\n\t\t\tissuer.publicKeyParametersOid,\n\t\t\tissuer.subjectPublicKeyInfoDer,\n\t\t\tcertificate.signatureValue,\n\t\t\tcertificate.tbsCertificateDer,\n\t\t),\n\t);\n}\n\n/** Runs `verify` as a path check, reporting a runtime failure as `signature_invalid` and a decoding limit as `limit_exceeded`. */\nasync function signatureCheck(\n\tverify: () => Promise<VerifySignedDataResult>,\n): Promise<VerifyCertificateSignatureResult> {\n\tlet result: VerifySignedDataResult;\n\ttry {\n\t\tresult = await verify();\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\tif (refusal === undefined) {\n\t\t\tthrow error;\n\t\t}\n\t\treturn { ok: false, code: refusal.code, reason: refusal.message };\n\t}\n\treturn !result.ok && result.code === 'verification_error'\n\t\t? { ok: false, code: 'signature_invalid', reason: result.reason }\n\t\t: result;\n}\n\n/** The real signature checks, used unless a caller injects its own. */\nconst DEFAULT_SIGNATURE_CHECKS: VerifyPathSignatureChecks = {\n\tcertificate: verifyCertificateSignature,\n\ttrustAnchor: verifyTrustAnchorSignature,\n};\n\nexport type PathDiagnostic =\n\t| { readonly kind: 'none'; readonly path: readonly ParsedCertificate[] }\n\t| { readonly kind: 'untrusted-anchor'; readonly path: readonly ParsedCertificate[] }\n\t| {\n\t\t\treadonly kind: 'missing-issuer';\n\t\t\treadonly path: readonly ParsedCertificate[];\n\t\t\treadonly missingIssuerAt: number;\n\t }\n\t| {\n\t\t\treadonly kind: 'specific-failure';\n\t\t\treadonly path: readonly ParsedCertificate[];\n\t\t\treadonly failure: VerifyChainFailure;\n\t };\n\nconst DIAGNOSTIC_TIER = {\n\t'specific-failure': 3,\n\t'untrusted-anchor': 2,\n\t'missing-issuer': 1,\n\tnone: 0,\n} as const satisfies Record<PathDiagnostic['kind'], number>;\n\nfunction isMoreSignificant(candidate: PathDiagnostic, incumbent: PathDiagnostic): boolean {\n\tconst candidateTier = DIAGNOSTIC_TIER[candidate.kind];\n\tconst incumbentTier = DIAGNOSTIC_TIER[incumbent.kind];\n\treturn candidateTier === incumbentTier\n\t\t? candidate.path.length > incumbent.path.length\n\t\t: candidateTier > incumbentTier;\n}\n\ninterface DeadEnd {\n\treadonly diagnostic: PathDiagnostic;\n\treadonly nodeIndex: number;\n}\n\n/**\n * Moves a diagnostic recorded below the certificate at `nodeIndex` onto a new\n * prefix ending at that same certificate. A suffix that repeats a certificate\n * of the new prefix cannot form a path, so only the prefix is reported.\n */\nexport function rebaseDiagnostic(\n\tdiagnostic: PathDiagnostic,\n\tnodeIndex: number,\n\tprefix: readonly ParsedCertificate[],\n): PathDiagnostic {\n\tconst suffix = diagnostic.path.slice(nodeIndex + 1);\n\tconst spent = new Set(prefix.map((certificate) => fingerprint(certificate)));\n\tif (suffix.some((certificate) => spent.has(fingerprint(certificate)))) {\n\t\treturn { kind: 'none', path: prefix };\n\t}\n\tconst path = [...prefix, ...suffix];\n\tconst shift = prefix.length - 1 - nodeIndex;\n\tswitch (diagnostic.kind) {\n\t\tcase 'none':\n\t\tcase 'untrusted-anchor':\n\t\t\treturn { kind: diagnostic.kind, path };\n\t\tcase 'missing-issuer':\n\t\t\treturn { kind: 'missing-issuer', path, missingIssuerAt: diagnostic.missingIssuerAt + shift };\n\t\tcase 'specific-failure':\n\t\t\treturn {\n\t\t\t\tkind: 'specific-failure',\n\t\t\t\tpath,\n\t\t\t\tfailure:\n\t\t\t\t\tdiagnostic.failure.index === undefined\n\t\t\t\t\t\t? diagnostic.failure\n\t\t\t\t\t\t: { ...diagnostic.failure, index: diagnostic.failure.index + shift },\n\t\t\t};\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = diagnostic;\n\t\t\tthrow new Error(`unreachable diagnostic ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Depth-first chain search from leaf to root. Tries all issuer candidates,\n * checking validity, CA constraints, AKI, pathLength, and signatures at each\n * step. Returns the first fully anchored path or the deepest partial path\n * with the best failure encountered.\n */\nexport async function buildChainInternal(\n\tleaf: ParsedCertificate,\n\tintermediates: readonly ParsedCertificate[],\n\troots: readonly ParsedCertificate[],\n\ttrustAnchors: readonly TrustAnchor[],\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n\tsignatureChecks: VerifyPathSignatureChecks = DEFAULT_SIGNATURE_CHECKS,\n\tmaxIssuerChecks: number = DEFAULT_MAX_PATH_BUILDING_CHECKS,\n\tdistrust: (spki: Uint8Array) => Promise<string | undefined> = () => Promise.resolve(undefined),\n): Promise<InternalBuildResult> {\n\tlet selectedAnchor: TrustAnchor | undefined;\n\tconst candidates = [...intermediates, ...roots];\n\tconst subjectIndex = new Map<string, ParsedCertificate[]>();\n\tconst order = new Map<string, number>();\n\tconst rootFingerprints = new Set(roots.map((candidate) => fingerprint(candidate)));\n\tconst anchorIndex = new Map<string, TrustAnchor[]>();\n\tfor (const anchor of trustAnchors) {\n\t\tconst key = canonicalDnKey(anchor.subject);\n\t\tconst existing = anchorIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tanchorIndex.set(key, [anchor]);\n\t\t} else {\n\t\t\texisting.push(anchor);\n\t\t}\n\t}\n\tconst best: { current: PathDiagnostic } = { current: { kind: 'none', path: [leaf] } };\n\tconst deadEnds = new Map<string, DeadEnd>();\n\tconst subtrees: { best: PathDiagnostic }[] = [];\n\tconst signatureResults = new Map<string, Promise<VerifyCertificateSignatureResult>>();\n\tconst budget = { remaining: maxIssuerChecks, exhausted: false };\n\tconst rankedBuckets = new Map<string, RankedBucket>();\n\n\tcandidates.forEach((candidate, index) => {\n\t\tconst key = canonicalDnKey(candidate.subject);\n\t\tconst existing = subjectIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tsubjectIndex.set(key, [candidate]);\n\t\t} else {\n\t\t\texisting.push(candidate);\n\t\t}\n\t\torder.set(fingerprint(candidate), index);\n\t});\n\n\tconst maxDepth = candidates.length + 1;\n\tconst startFingerprint = fingerprint(leaf);\n\tconst success = await search(leaf, [leaf], new Set([startFingerprint]), 0);\n\tif (success !== undefined) {\n\t\tconst terminal = success[success.length - 1];\n\t\treturn {\n\t\t\tchain: success,\n\t\t\tfoundTrustedRoot: true,\n\t\t\t...(selectedAnchor !== undefined && { trustAnchor: selectedAnchor }),\n\t\t\tanchorCertificateInChain:\n\t\t\t\tterminal !== undefined && rootFingerprints.has(fingerprint(terminal)),\n\t\t};\n\t}\n\tconst owner = best.current;\n\tif (budget.exhausted) {\n\t\treturn {\n\t\t\tchain: owner.path,\n\t\t\tfoundTrustedRoot: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'path_building_limit_exceeded',\n\t\t\t\t'path building stopped at its work limit',\n\t\t\t\tundefined,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\texpected: `at most ${maxIssuerChecks} issuer and trust-anchor checks`,\n\t\t\t\t\tactual: 'limit reached before a trusted path was found',\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tswitch (owner.kind) {\n\t\tcase 'specific-failure':\n\t\t\treturn { chain: owner.path, foundTrustedRoot: false, failure: owner.failure };\n\t\tcase 'missing-issuer':\n\t\t\treturn {\n\t\t\t\tchain: owner.path,\n\t\t\t\tfoundTrustedRoot: false,\n\t\t\t\tmissingIssuerAt: owner.missingIssuerAt,\n\t\t\t};\n\t\tcase 'untrusted-anchor':\n\t\tcase 'none':\n\t\t\treturn { chain: owner.path, foundTrustedRoot: false };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = owner;\n\t\t\tthrow new Error(`unreachable diagnostic ${String(_exhaustive)}`);\n\t\t}\n\t}\n\n\tasync function search(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tif (budget.exhausted) return undefined;\n\t\tconst blockedHash = await distrust(current.subjectPublicKeyInfoDer);\n\t\tif (blockedHash !== undefined) {\n\t\t\trecordFailure(\n\t\t\t\tcallbacks.failure(\n\t\t\t\t\t'public_key_distrusted',\n\t\t\t\t\t'certificate public key is explicitly distrusted',\n\t\t\t\t\tpath.length - 1,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\t\tactual: blockedHash,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\tpath,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\tif (rootFingerprints.has(fingerprint(current))) {\n\t\t\treturn path;\n\t\t}\n\t\tconst matchedAnchor = await matchTrustAnchor(\n\t\t\tcurrent,\n\t\t\tanchorIndex,\n\t\t\tcallbacks,\n\t\t\tpath.length - 1,\n\t\t\tverifyAnchorOnce,\n\t\t\tchargeBudget,\n\t\t\tdistrust,\n\t\t);\n\t\tif (budget.exhausted) return undefined;\n\t\tif (matchedAnchor.failure !== undefined) {\n\t\t\trecordFailure(matchedAnchor.failure, path);\n\t\t}\n\t\tif (matchedAnchor.matched) {\n\t\t\tselectedAnchor = matchedAnchor.anchor;\n\t\t\treturn path;\n\t\t}\n\t\tif (path.length > maxDepth) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst memoKey = `${fingerprint(current)}:${caBelowCount}`;\n\t\tconst memoized = deadEnds.get(memoKey);\n\t\tif (memoized !== undefined) {\n\t\t\tconsider(rebaseDiagnostic(memoized.diagnostic, memoized.nodeIndex, path));\n\t\t\treturn undefined;\n\t\t}\n\t\tconst subtree: { best: PathDiagnostic } = { best: { kind: 'none', path } };\n\t\tsubtrees.push(subtree);\n\t\ttry {\n\t\t\tconst issuerPath = await searchBelow(current, path, visited, caBelowCount);\n\t\t\tif (issuerPath !== undefined) return issuerPath;\n\t\t} finally {\n\t\t\tsubtrees.pop();\n\t\t}\n\t\tdeadEnds.set(memoKey, { diagnostic: subtree.best, nodeIndex: path.length - 1 });\n\t\treturn undefined;\n\t}\n\n\tasync function searchBelow(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tlet sawIssuer = false;\n\t\tfor (const issuer of issuerCandidates(current)) {\n\t\t\tif (!chargeBudget()) return undefined;\n\t\t\tif (!isIssuerOf(issuer, current)) continue;\n\t\t\tsawIssuer = true;\n\t\t\tconst issuerFingerprint = fingerprint(issuer);\n\t\t\tif (visited.has(issuerFingerprint)) continue;\n\t\t\tconst result = await searchIssuerCandidate(\n\t\t\t\tcurrent,\n\t\t\t\tissuer,\n\t\t\t\tissuerFingerprint,\n\t\t\t\tpath,\n\t\t\t\tvisited,\n\t\t\t\tcaBelowCount,\n\t\t\t);\n\t\t\tif (result !== undefined) return result;\n\t\t\tif (budget.exhausted) return undefined;\n\t\t}\n\t\tif (!sawIssuer) {\n\t\t\trecordMissingIssuers(current, path);\n\t\t\treturn undefined;\n\t\t}\n\t\tconsider({ kind: 'none', path });\n\t\treturn undefined;\n\t}\n\n\t/** Yields the issuer bucket for `current`: AKI matches first, then roots, then input order. */\n\tfunction* issuerCandidates(current: ParsedCertificate): Generator<ParsedCertificate> {\n\t\tconst key = canonicalDnKey(current.issuer);\n\t\tlet bucket = rankedBuckets.get(key);\n\t\tif (bucket === undefined) {\n\t\t\tbucket = rankBucket(subjectIndex.get(key) ?? [], order, rootFingerprints);\n\t\t\trankedBuckets.set(key, bucket);\n\t\t}\n\t\tconst aki = current.authorityKeyIdentifier;\n\t\tif (aki === undefined) {\n\t\t\tyield* bucket.ordered;\n\t\t\treturn;\n\t\t}\n\t\tyield* bucket.bySubjectKeyIdentifier.get(aki) ?? [];\n\t\tfor (const candidate of bucket.ordered) {\n\t\t\tif (candidate.subjectKeyIdentifier !== aki) yield candidate;\n\t\t}\n\t}\n\n\tfunction recordMissingIssuers(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t): void {\n\t\tif (isSelfIssued(current)) {\n\t\t\tconsider({ kind: 'untrusted-anchor', path });\n\t\t\treturn;\n\t\t}\n\t\tif (path.length > 1) {\n\t\t\tconsider({ kind: 'missing-issuer', path, missingIssuerAt: path.length - 1 });\n\t\t}\n\t}\n\n\tasync function searchIssuerCandidate(\n\t\tcurrent: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t\tissuerFingerprint: string,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tconst candidate = await evaluateIssuerCandidate(\n\t\t\tcurrent,\n\t\t\tissuer,\n\t\t\tpath,\n\t\t\tcaBelowCount,\n\t\t\tat,\n\t\t\tcallbacks,\n\t\t\tverifySignatureOnce,\n\t\t);\n\t\tif (!candidate.ok) {\n\t\t\trecordFailure(candidate.failure, path);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst nextVisited = new Set(visited);\n\t\tnextVisited.add(issuerFingerprint);\n\t\treturn await search(issuer, [...path, issuer], nextVisited, candidate.nextCaBelowCount);\n\t}\n\n\tfunction chargeBudget(): boolean {\n\t\tif (budget.remaining === 0) {\n\t\t\tbudget.exhausted = true;\n\t\t\treturn false;\n\t\t}\n\t\tbudget.remaining -= 1;\n\t\treturn true;\n\t}\n\n\tfunction verifySignatureOnce(\n\t\tcertificate: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t): Promise<VerifyCertificateSignatureResult> {\n\t\treturn verifyOnce(\n\t\t\t`c:${fingerprint(certificate)}:${toHex(issuer.subjectPublicKeyInfoDer)}`,\n\t\t\t() => signatureChecks.certificate(certificate, issuer),\n\t\t);\n\t}\n\n\tfunction verifyAnchorOnce(\n\t\tcertificate: ParsedCertificate,\n\t\tanchor: TrustAnchor,\n\t): Promise<VerifyCertificateSignatureResult> {\n\t\tconst anchorKey = `${anchor.publicKeyAlgorithmOid}:${anchor.publicKeyParametersOid ?? ''}:${toHex(\n\t\t\tanchor.subjectPublicKeyInfoDer,\n\t\t)}`;\n\t\treturn verifyOnce(`a:${fingerprint(certificate)}:${anchorKey}`, () =>\n\t\t\tsignatureChecks.trustAnchor(certificate, anchor),\n\t\t);\n\t}\n\n\t/** One signature check per distinct certificate-and-key pair for the whole search. */\n\tfunction verifyOnce(\n\t\tkey: string,\n\t\trun: () => Promise<VerifyCertificateSignatureResult>,\n\t): Promise<VerifyCertificateSignatureResult> {\n\t\tlet pending = signatureResults.get(key);\n\t\tif (pending === undefined) {\n\t\t\tpending = run();\n\t\t\tsignatureResults.set(key, pending);\n\t\t}\n\t\treturn pending;\n\t}\n\n\tfunction consider(candidate: PathDiagnostic): void {\n\t\tif (isMoreSignificant(candidate, best.current)) {\n\t\t\tbest.current = candidate;\n\t\t}\n\t\tfor (const subtree of subtrees) {\n\t\t\tif (isMoreSignificant(candidate, subtree.best)) {\n\t\t\t\tsubtree.best = candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction recordFailure(\n\t\tcandidateFailure: VerifyChainFailure,\n\t\tpath: readonly ParsedCertificate[],\n\t): void {\n\t\tconsider({ kind: 'specific-failure', path, failure: candidateFailure });\n\t}\n}\n\n/** Applies issuer constraints and signature verification to one path candidate. */\nasync function evaluateIssuerCandidate(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n\tverifySignature: typeof verifyCertificateSignature,\n): Promise<IssuerCandidateEvaluation> {\n\tconst issuerConstraints = evaluateIssuerConstraints(\n\t\tcurrent,\n\t\tissuer,\n\t\tpath,\n\t\tcaBelowCount,\n\t\tat,\n\t\tcallbacks,\n\t);\n\tif (!issuerConstraints.ok) {\n\t\treturn issuerConstraints;\n\t}\n\tconst signatureResult = await verifySignature(current, issuer);\n\tif (!signatureResult.ok) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\tsignatureResult.code,\n\t\t\t\tsignatureResult.reason,\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\tactual: signatureResult.reason,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tif (!signatureResult.valid) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'certificate signature does not verify',\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\treturn issuerConstraints;\n}\n\nfunction evaluateIssuerConstraints(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n): IssuerCandidateEvaluation {\n\tif (!isWithinValidity(issuer, at)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'certificate_expired',\n\t\t\t\t'certificate not valid at requested time',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: describeDateTime(at),\n\t\t\t\t\tactual: `${describeDateTime(issuer.notBefore)}..${describeDateTime(issuer.notAfter)}`,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tif (issuer.basicConstraints?.ca !== true) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'ca_required',\n\t\t\t\t'issuer must be a CA certificate',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({ subjectCommonName: issuer.subject.values.commonName }),\n\t\t\t),\n\t\t};\n\t}\n\treturn evaluateIssuerKeyConstraints(current, issuer, path, caBelowCount, callbacks);\n}\n\nfunction evaluateIssuerKeyConstraints(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tcallbacks: VerifyPathCallbacks,\n): IssuerCandidateEvaluation {\n\tif (issuer.keyUsage !== undefined && !issuer.keyUsage.flags.includes('keyCertSign')) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'key_cert_sign_required',\n\t\t\t\t'issuer missing keyCertSign',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({ subjectCommonName: issuer.subject.values.commonName }),\n\t\t\t),\n\t\t};\n\t}\n\tif (authorityKeyIdentifierMismatch(current, issuer)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'authority_key_identifier_mismatch',\n\t\t\t\t'authorityKeyIdentifier does not match issuer subjectKeyIdentifier',\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: issuer.subjectKeyIdentifier,\n\t\t\t\t\tactual: current.authorityKeyIdentifier,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tconst nextCaBelowCount =\n\t\tcaBelowCount +\n\t\t(current.basicConstraints?.ca === true && !isSelfIssued(current) && path.length > 1 ? 1 : 0);\n\tconst pathLength = issuer.basicConstraints?.pathLength;\n\tif (isNonNegativeInteger(pathLength) && nextCaBelowCount > pathLength) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'path_length_exceeded',\n\t\t\t\t'path length constraint exceeded',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: String(pathLength),\n\t\t\t\t\tactual: String(nextCaBelowCount),\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\treturn { ok: true, nextCaBelowCount };\n}\n\nexport function authorityKeyIdentifierMismatch(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): boolean {\n\treturn (\n\t\tcurrent.authorityKeyIdentifier !== undefined &&\n\t\tissuer.subjectKeyIdentifier !== undefined &&\n\t\tcurrent.authorityKeyIdentifier !== issuer.subjectKeyIdentifier\n\t);\n}\n\n/** Expands a PEM (possibly multi-block) or DER source into parsed certificates. */\nfunction expandSource(source: CertificateSource): readonly ParsedCertificate[] {\n\treturn parseCertificatesFromSource(source);\n}\n\ninterface RankedBucket {\n\treadonly ordered: readonly ParsedCertificate[];\n\treadonly bySubjectKeyIdentifier: ReadonlyMap<string, readonly ParsedCertificate[]>;\n}\n\n/** Orders one subject bucket once, roots first and then input order, and indexes it by SKI. */\nfunction rankBucket(\n\tmembers: readonly ParsedCertificate[],\n\torder: ReadonlyMap<string, number>,\n\trootFingerprints: ReadonlySet<string>,\n): RankedBucket {\n\tconst ordered = [...members].sort((left, right) => {\n\t\tconst leftFp = fingerprint(left);\n\t\tconst rightFp = fingerprint(right);\n\t\tconst rootScore = compareBooleans(rootFingerprints.has(leftFp), rootFingerprints.has(rightFp));\n\t\tif (rootScore !== 0) {\n\t\t\treturn rootScore;\n\t\t}\n\t\treturn (\n\t\t\t(order.get(leftFp) ?? Number.MAX_SAFE_INTEGER) -\n\t\t\t(order.get(rightFp) ?? Number.MAX_SAFE_INTEGER)\n\t\t);\n\t});\n\tconst bySubjectKeyIdentifier = new Map<string, ParsedCertificate[]>();\n\tfor (const candidate of ordered) {\n\t\tconst ski = candidate.subjectKeyIdentifier;\n\t\tif (ski === undefined) continue;\n\t\tconst existing = bySubjectKeyIdentifier.get(ski);\n\t\tif (existing === undefined) {\n\t\t\tbySubjectKeyIdentifier.set(ski, [candidate]);\n\t\t} else {\n\t\t\texisting.push(candidate);\n\t\t}\n\t}\n\treturn { ordered, bySubjectKeyIdentifier };\n}\n\n/** Sort comparator: `true` sorts before `false`. Returns -1, 0, or 1. */\nfunction compareBooleans(left: boolean, right: boolean): number {\n\tif (left === right) {\n\t\treturn 0;\n\t}\n\treturn left ? -1 : 1;\n}\n\n/** Returns `true` if `issuer`'s subject DN semantically matches `child`'s issuer DN (RFC 5280 §7.1). */\nfunction isIssuerOf(issuer: ParsedCertificate, child: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(child.issuer, issuer.subject);\n}\n\n/** Attempts to verify `certificate` against each bare trust anchor whose subject DN matches. */\nasync function matchTrustAnchor(\n\tcertificate: ParsedCertificate,\n\tanchorIndex: ReadonlyMap<string, readonly TrustAnchor[]>,\n\tcallbacks: VerifyPathCallbacks,\n\tindex: number,\n\tverifyAnchor: typeof verifyTrustAnchorSignature,\n\tcharge: () => boolean,\n\tdistrust: (spki: Uint8Array) => Promise<string | undefined>,\n): Promise<TrustAnchorMatchResult> {\n\tconst anchors = anchorIndex.get(canonicalDnKey(certificate.issuer));\n\tif (anchors === undefined) {\n\t\treturn { matched: false };\n\t}\n\tlet firstFailure: VerifyChainFailure | undefined;\n\tfor (const anchor of anchors) {\n\t\tif (!charge()) return { matched: false };\n\t\tif (trustAnchorAkiMismatch(certificate, anchor)) continue;\n\t\t// The canonicalDnKey bucket is not proof of DN equality (prohibited values\n\t\t// are non-reflexive and prepared/tagged namespaces can collide), so confirm\n\t\t// the anchor's subject actually equals the certificate's issuer.\n\t\tif (!compareDistinguishedNames(certificate.issuer, anchor.subject)) continue;\n\t\tconst blockedHash = await distrust(anchor.subjectPublicKeyInfoDer);\n\t\tif (blockedHash !== undefined) {\n\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t'public_key_distrusted',\n\t\t\t\t'bare trust anchor public key is explicitly distrusted',\n\t\t\t\tundefined,\n\t\t\t\tcallbacks.detail({ actual: blockedHash }),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst verified = await verifyAnchor(certificate, anchor);\n\t\tif (!verified.ok) {\n\t\t\t// Capture the first failure but continue trying other anchors\n\t\t\tfirstFailure ??= callbacks.failure(\n\t\t\t\tverified.code,\n\t\t\t\tverified.reason,\n\t\t\t\tindex,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\tactual: verified.reason,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!verified.valid) {\n\t\t\tif (firstFailure === undefined) {\n\t\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate signature does not verify',\n\t\t\t\t\tindex,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: 'certificate signature does not verify',\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\treturn { matched: true, anchor };\n\t}\n\treturn firstFailure !== undefined\n\t\t? { matched: false, failure: firstFailure }\n\t\t: { matched: false };\n}\n\nfunction trustAnchorAkiMismatch(certificate: ParsedCertificate, anchor: TrustAnchor): boolean {\n\treturn (\n\t\tanchor.subjectKeyIdentifier !== undefined &&\n\t\tcertificate.authorityKeyIdentifier !== undefined &&\n\t\tanchor.subjectKeyIdentifier !== certificate.authorityKeyIdentifier\n\t);\n}\n\n/** Verifies that `certificate` was signed by a bare trust anchor's key. */\nexport function verifyTrustAnchorSignature(\n\tcertificate: ParsedCertificate,\n\tanchor: TrustAnchor,\n): Promise<VerifyCertificateSignatureResult> {\n\treturn signatureCheck(() =>\n\t\tverifySignedDataDetailed(\n\t\t\tcertificate.signatureAlgorithmOid,\n\t\t\tcertificate.signatureAlgorithmParametersDer,\n\t\t\tanchor.publicKeyAlgorithmOid,\n\t\t\tanchor.publicKeyParametersOid,\n\t\t\tanchor.subjectPublicKeyInfoDer,\n\t\t\tcertificate.signatureValue,\n\t\t\tcertificate.tbsCertificateDer,\n\t\t),\n\t);\n}\n\nfunction describeDateTime(value: Date): string {\n\treturn Number.isNaN(value.getTime()) ? '<invalid date>' : value.toISOString();\n}\n\nfunction isNonNegativeInteger(value: number | undefined): value is number {\n\treturn value !== undefined && Number.isInteger(value) && value >= 0;\n}\n\n/** Cache for computed fingerprints to avoid repeated toHex() calls. */\nconst fingerprintCache = new WeakMap<ParsedCertificate, string>();\n\n/** Returns a hex fingerprint of the certificate's raw DER, used for cycle detection and dedup. */\nfunction fingerprint(certificate: ParsedCertificate): string {\n\tlet cached = fingerprintCache.get(certificate);\n\tif (cached === undefined) {\n\t\tcached = toHex(certificate.der);\n\t\tfingerprintCache.set(certificate, cached);\n\t}\n\treturn cached;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA0FA,MAAaC,IAAmC;;AAGhD,SAAgB,yBAAyB,GAAiC;CACzE,IAAIC,MAAU,KAAA,MAAc,CAAC,OAAO,cAAcA,CAAK,KAAKA,IAAQ,IACnE,MAAU,WAAW,+DAA+DA,GAAO;AAE7F;;AA8BA,SAAgB,iBAAiB,GAAgC,GAAmB;CACnF,OACCC,EAAY,UAAU,QAAQ,KAAKC,EAAG,QAAQ,KAC9CA,EAAG,QAAQ,KAAKD,EAAY,SAAS,QAAQ;AAE/C;;AAGA,SAAgB,aAAa,GAAyC;CACrE,OAAOE,EAA0BF,EAAY,SAASA,EAAY,MAAM;AACzE;;AAGA,SAAgB,+BACf,GACA,GACS;CACT,IAAIG,IAAQ;CACZ,KAAK,IAAIC,IAAS,GAAGA,IAASC,GAAO,KAAU,GAAG;EACjD,IAAML,IAAcM,EAAMF;EAC1B,AAAIJ,GAAa,kBAAkB,OAAO,MAAQ,CAAC,aAAaA,CAAW,MAC1E,KAAS;CAEX;CACA,OAAOG;AACR;;AAGA,SAAgB,iBACf,GAC+B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,OAAO,UAAUA,CAAK,KAAKA,KAAS;AACnE;;AAGA,MAAMC,oBAAmB,IAAI,QAAmC;;AAGhE,SAAS,YAAY,GAAwC;CAC5D,IAAIC,IAASD,EAAiB,IAAItG,CAAW;CAK7C,OAJIuG,MAAW,KAAA,MACd,IAAS7B,EAAM1E,EAAY,GAAG,GAC9BsG,EAAiB,IAAItG,GAAauG,CAAM,IAElCA;AACR"}
@@ -0,0 +1,44 @@
1
+ import { ErrorResult, Micro509Error } from "../result/result.js";
2
+ /** Reasons a compact serialization is refused before any signature is checked. */
3
+ export type JwsParseErrorCode = "token_too_large" | "malformed_token" | "invalid_encoding" | "invalid_utf8" | "invalid_json" | "duplicate_member" | "limit_exceeded" | "invalid_header" | "unsupported_critical_header" | "unsupported_unencoded_payload" | "unsupported_nested_jwt" | "invalid_payload";
4
+ /** Reasons a signing key cannot be resolved for a token. */
5
+ export type KeyResolutionErrorCode = "key_not_found" | "ambiguous_key" | "key_unsuitable" | "key_resolution_failed" | "jwks_unavailable" | "jwks_malformed" | "aborted";
6
+ /** Reasons a well-formed token is refused by the verification policy or its signature. */
7
+ export type JwsPolicyErrorCode = "invalid_options" | "unsigned_token" | "algorithm_not_allowed" | "token_type_mismatch" | "invalid_signature";
8
+ /** Reasons a signature-verified token fails the claims policy. */
9
+ export type JwtClaimsErrorCode = "missing_claim" | "invalid_claim" | "issuer_mismatch" | "audience_mismatch" | "expired" | "not_yet_valid" | "issued_in_future" | "token_too_old";
10
+ /** Failure codes of {@linkcode verifyCompactJws}. */
11
+ export type VerifyJwsErrorCode = JwsParseErrorCode | KeyResolutionErrorCode | JwsPolicyErrorCode;
12
+ /** Failure codes of {@linkcode verifyJwt}. */
13
+ export type VerifyJwtErrorCode = VerifyJwsErrorCode | JwtClaimsErrorCode;
14
+ /** Every code a JOSE API reports. */
15
+ export type JoseErrorCode = VerifyJwtErrorCode;
16
+ /**
17
+ * Structured context for a failure. Holds names and short identifiers only, never token
18
+ * segments, claim values or key material.
19
+ */
20
+ export interface JoseErrorDetails {
21
+ /** The `alg` header value the token carried. */
22
+ readonly alg?: string;
23
+ /** The `kid` header value the token carried, truncated to 64 characters. */
24
+ readonly kid?: string;
25
+ /** The claim name a claims failure concerns. */
26
+ readonly claim?: string;
27
+ /** The critical header names that were refused. */
28
+ readonly crit?: readonly string[];
29
+ /** The HTTP status a JWKS endpoint answered with. */
30
+ readonly status?: number;
31
+ }
32
+ /** Failure payload of the JOSE APIs. */
33
+ export interface JoseFailure<TCode extends string = JoseErrorCode> extends Micro509Error<TCode, JoseErrorDetails> {
34
+ /** Always `false` for failures. */
35
+ readonly ok: false;
36
+ }
37
+ /** A flattened failed result carrying a {@linkcode JoseFailure}. */
38
+ export type JoseErrorResult<TCode extends string = JoseErrorCode> = ErrorResult<TCode, JoseErrorDetails, JoseFailure<TCode>>;
39
+ /** Success-or-failure result of a JOSE API. */
40
+ export type JoseResult<TValue, TCode extends string = JoseErrorCode> = {
41
+ readonly ok: true;
42
+ readonly value: TValue;
43
+ } | JoseErrorResult<TCode>;
44
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1,11 @@
1
+ import { failureResult as e } from "../result/result.js";
2
+ /** Builds a failed result, truncating any reported `kid`. */
3
+ function joseFailure(t, n, r) {
4
+ return e(t, n, r?.kid === void 0 ? r : {
5
+ ...r,
6
+ kid: r.kid.slice(0, 64)
7
+ });
8
+ }
9
+ export { joseFailure };
10
+
11
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":["failureResult","code","message","details"],"sources":["../../src/jose/errors.ts"],"sourcesContent":["/**\n * Typed failures shared by the JOSE parsing, verification and key-resolution APIs.\n *\n * @module\n */\n\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult } from '#micro509/result/result';\n\n/** Longest `kid` echoed into {@linkcode JoseErrorDetails}. */\nconst MAX_REPORTED_KID_LENGTH = 64;\n\n/** Reasons a compact serialization is refused before any signature is checked. */\nexport type JwsParseErrorCode =\n\t| 'token_too_large'\n\t| 'malformed_token'\n\t| 'invalid_encoding'\n\t| 'invalid_utf8'\n\t| 'invalid_json'\n\t| 'duplicate_member'\n\t| 'limit_exceeded'\n\t| 'invalid_header'\n\t| 'unsupported_critical_header'\n\t| 'unsupported_unencoded_payload'\n\t| 'unsupported_nested_jwt'\n\t| 'invalid_payload';\n\n/** Reasons a signing key cannot be resolved for a token. */\nexport type KeyResolutionErrorCode =\n\t| 'key_not_found'\n\t| 'ambiguous_key'\n\t| 'key_unsuitable'\n\t| 'key_resolution_failed'\n\t| 'jwks_unavailable'\n\t| 'jwks_malformed'\n\t| 'aborted';\n\n/** Reasons a well-formed token is refused by the verification policy or its signature. */\nexport type JwsPolicyErrorCode =\n\t| 'invalid_options'\n\t| 'unsigned_token'\n\t| 'algorithm_not_allowed'\n\t| 'token_type_mismatch'\n\t| 'invalid_signature';\n\n/** Reasons a signature-verified token fails the claims policy. */\nexport type JwtClaimsErrorCode =\n\t| 'missing_claim'\n\t| 'invalid_claim'\n\t| 'issuer_mismatch'\n\t| 'audience_mismatch'\n\t| 'expired'\n\t| 'not_yet_valid'\n\t| 'issued_in_future'\n\t| 'token_too_old';\n\n/** Failure codes of {@linkcode verifyCompactJws}. */\nexport type VerifyJwsErrorCode = JwsParseErrorCode | KeyResolutionErrorCode | JwsPolicyErrorCode;\n\n/** Failure codes of {@linkcode verifyJwt}. */\nexport type VerifyJwtErrorCode = VerifyJwsErrorCode | JwtClaimsErrorCode;\n\n/** Every code a JOSE API reports. */\nexport type JoseErrorCode = VerifyJwtErrorCode;\n\n/**\n * Structured context for a failure. Holds names and short identifiers only, never token\n * segments, claim values or key material.\n */\nexport interface JoseErrorDetails {\n\t/** The `alg` header value the token carried. */\n\treadonly alg?: string;\n\t/** The `kid` header value the token carried, truncated to 64 characters. */\n\treadonly kid?: string;\n\t/** The claim name a claims failure concerns. */\n\treadonly claim?: string;\n\t/** The critical header names that were refused. */\n\treadonly crit?: readonly string[];\n\t/** The HTTP status a JWKS endpoint answered with. */\n\treadonly status?: number;\n}\n\n/** Failure payload of the JOSE APIs. */\nexport interface JoseFailure<TCode extends string = JoseErrorCode>\n\textends Micro509Error<TCode, JoseErrorDetails> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** A flattened failed result carrying a {@linkcode JoseFailure}. */\nexport type JoseErrorResult<TCode extends string = JoseErrorCode> = ErrorResult<\n\tTCode,\n\tJoseErrorDetails,\n\tJoseFailure<TCode>\n>;\n\n/** Success-or-failure result of a JOSE API. */\nexport type JoseResult<TValue, TCode extends string = JoseErrorCode> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| JoseErrorResult<TCode>;\n\n/** Builds a failed result, truncating any reported `kid`. */\nexport function joseFailure<TCode extends JoseErrorCode>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: JoseErrorDetails,\n): JoseErrorResult<TCode> {\n\treturn failureResult(\n\t\tcode,\n\t\tmessage,\n\t\tdetails?.kid === undefined\n\t\t\t? details\n\t\t\t: { ...details, kid: details.kid.slice(0, MAX_REPORTED_KID_LENGTH) },\n\t);\n}\n"],"mappings":";;AAsGA,SAAgB,YACf,GACA,GACA,GACyB;CACzB,OAAOA,EACNC,GACAC,GACAC,GAAS,QAAQ,KAAA,IACdA,IACA;EAAE,GAAGA;EAAS,KAAKA,EAAQ,IAAI,MAAM,GAAG,EAAuB;CAAE,CACrE;AACD"}
@@ -0,0 +1,93 @@
1
+ import { JsonObject } from "../internal/jose/strict-json.js";
2
+ import { JoseResult, KeyResolutionErrorCode } from "./errors.js";
3
+ import { JwsAlgorithm, JwsKeyResolver } from "./jws.js";
4
+ /** Bounds applied while parsing a JWK Set. */
5
+ export interface JwksLimits {
6
+ /** Maximum JWK Set size in bytes. Default `65536`. */
7
+ readonly maxBytes: number;
8
+ /** Maximum number of keys in the set. Default `32`. */
9
+ readonly maxKeys: number;
10
+ }
11
+ /** The limits applied when a caller supplies none. */
12
+ export declare const DEFAULT_JWKS_LIMITS: JwksLimits;
13
+ /** Members every JWK entry carries beside its key material. */
14
+ export interface JwkMetadata {
15
+ /** Key identifier. */
16
+ readonly kid?: string;
17
+ /** Intended use: `sig` or `enc`, or another value kept verbatim. */
18
+ readonly use?: string;
19
+ /** Permitted operations, verbatim. */
20
+ readonly keyOps?: readonly string[];
21
+ /** The algorithm the key is restricted to. */
22
+ readonly alg?: string;
23
+ }
24
+ /** Members shared by every parsed entry. */
25
+ export interface JwkEntryBase extends JwkMetadata {
26
+ /** Every member the entry carried, as parsed, including key material this module does not read. */
27
+ readonly members: JsonObject;
28
+ }
29
+ /** An RSA public key entry. */
30
+ export interface RsaJwkEntry extends JwkEntryBase {
31
+ /** Discriminant. */
32
+ readonly kind: "rsa";
33
+ /** Base64url modulus. */
34
+ readonly n: string;
35
+ /** Base64url public exponent. */
36
+ readonly e: string;
37
+ }
38
+ /**
39
+ * An entry this module never selects: a `kty` other than `RSA`, or an entry with missing or
40
+ * wrongly typed members (RFC 7517 §5). Kept so callers can inspect the whole set.
41
+ */
42
+ export interface UnsupportedJwkEntry extends JwkEntryBase {
43
+ /** Discriminant. */
44
+ readonly kind: "unsupported";
45
+ /** The `kty` the entry carried, when it was a string. */
46
+ readonly kty?: string;
47
+ }
48
+ /** One key of a JWK Set. */
49
+ export type JwkEntry = RsaJwkEntry | UnsupportedJwkEntry;
50
+ /** A parsed JWK Set. */
51
+ export interface Jwks {
52
+ /** The keys, in document order. */
53
+ readonly keys: readonly JwkEntry[];
54
+ /** Every top-level member of the document, as parsed. */
55
+ readonly members: JsonObject;
56
+ }
57
+ /** Codes {@linkcode parseJwks} returns. */
58
+ export type ParseJwksErrorCode = "jwks_malformed" | "limit_exceeded" | "invalid_options";
59
+ /**
60
+ * Parses a JWK Set document.
61
+ *
62
+ * The document must be duplicate-free JSON with a `keys` array within `limits`. Keys with a `kty`
63
+ * other than `RSA`, and keys with missing or wrongly typed members, are kept as `unsupported`
64
+ * entries and never selected (RFC 7517 §5). A set that is not a duplicate-free object with a
65
+ * `keys` array of objects is `jwks_malformed`.
66
+ */
67
+ export declare function parseJwks(input: string | Uint8Array, limits?: Partial<JwksLimits>): JoseResult<Jwks, ParseJwksErrorCode>;
68
+ /** What {@linkcode selectJwk} matches against. */
69
+ export interface JwkSelector {
70
+ /** The algorithm the token uses. */
71
+ readonly algorithm: JwsAlgorithm;
72
+ /** The token's `kid`, when it carries one. */
73
+ readonly kid?: string;
74
+ }
75
+ /**
76
+ * Selects the one key of a set that can verify `selector`.
77
+ *
78
+ * Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA
79
+ * parameters. No match is `key_not_found`, or `key_unsuitable` when `kid` matched only keys that
80
+ * fail the other checks. More than one match is `ambiguous_key`: a token without `kid` therefore
81
+ * resolves only against a set with a single usable key.
82
+ */
83
+ export declare function selectJwk(jwks: Jwks, selector: JwkSelector): JoseResult<RsaJwkEntry, Exclude<KeyResolutionErrorCode, "jwks_unavailable" | "aborted">>;
84
+ /** Imports a selected entry as a verify-only RS256 `CryptoKey`. */
85
+ export declare function importJwkEntry(entry: RsaJwkEntry): Promise<JoseResult<CryptoKey, "key_unsuitable">>;
86
+ /**
87
+ * Creates a key resolver over a fixed JWK Set.
88
+ *
89
+ * The resolver selects with {@linkcode selectJwk} and imports each key once, so repeated
90
+ * verifications reuse the same `CryptoKey`.
91
+ */
92
+ export declare function createJwksKeyResolver(jwks: Jwks): JwsKeyResolver;
93
+ //# sourceMappingURL=jwks.d.ts.map