micro509 0.15.0 → 0.16.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.
- package/CHANGELOG.md +56 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -3
- package/dist/internal/verify/spki-distrust.js +23 -0
- package/dist/internal/verify/spki-distrust.js.map +1 -0
- package/dist/internal/verify/verify-path.js +77 -60
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/keys/keys.d.ts +11 -8
- package/dist/keys/keys.js.map +1 -1
- package/dist/revocation/crl.js +2 -7
- package/dist/revocation/crl.js.map +1 -1
- package/dist/verify/verify.d.ts +32 -1
- package/dist/verify/verify.js +100 -58
- package/dist/verify/verify.js.map +1 -1
- package/dist/x509/fingerprint.d.ts +11 -0
- package/dist/x509/fingerprint.js +19 -1
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509.d.ts +2 -2
- package/dist/x509.js +3 -3
- package/package.json +3 -3
|
@@ -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;;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;CAC/B,IAAMI,IAA8B,CAAC;CACrC,KAAK,IAAMC,KAAUC,GACpB,EAAO,KAAK,GAAG,aAAaD,CAAM,CAAC;CAEpC,OAAOD;AACR;;AAGA,SAAgB,sBAAsB,GAA8C;CACnF,IAAMA,IAAS,aAAaC,CAAM,GAC5BE,IAAQH,EAAO;CACrB,IAAIG,MAAU,KAAA,GACb,MAAU,MAAM,sBAAsB;CAEvC,IAAIH,EAAO,WAAW,GACrB,MAAU,MAAM,sCAAsC;CAEvD,OAAOG;AACR;;AAGA,SAA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CuC,EAAO,yBAAyBvC,EAAY;AAE9C;;AAGA,SAAgB,2BACf,GACA,GAC4C;CAC5C,OAAO,qBACNW,EACCX,EAAY,uBACZA,EAAY,iCACZuC,EAAO,uBACPA,EAAO,wBACPA,EAAO,yBACPvC,EAAY,gBACZA,EAAY,iBACb,CACD;AACD;AAEA,SAAS,iBAAiB,GAAqB;CAC9C,OAAO,OAAO,MAAMkG,EAAM,QAAQ,CAAC,IAAI,mBAAmBA,EAAM,YAAY;AAC7E;AAEA,SAAS,qBAAqB,GAA4C;CACzE,OAAOA,MAAU,KAAA,KAAa,OAAO,UAAUA,CAAK,KAAKA,KAAS;AACnE;;AAGA,MAAMC,oBAAmB,IAAI,QAAmC;;AAGhE,SAAS,YAAY,GAAwC;CAC5D,IAAIC,IAASD,EAAiB,IAAInG,CAAW;CAK7C,OAJIoG,MAAW,KAAA,MACd,IAAS7B,EAAMvE,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,MAA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AChC;CACA,OAAOiG,MAAiB,KAAA,IAErB,EAAE,SAAS,GAAM,IADjB;EAAE,SAAS;EAAO,SAASA;CAAa;AAE5C;AAEA,SAAS,uBAAuB,GAAgC,GAA8B;CAC7F,OACCzD,EAAO,yBAAyB,KAAA,KAChCxC,EAAY,2BAA2B,KAAA,KACvCwC,EAAO,yBAAyBxC,EAAY;AAE9C;;AAGA,SAAgB,2BACf,GACA,GAC4C;CAC5C,OAAO,qBACNW,EACCX,EAAY,uBACZA,EAAY,iCACZwC,EAAO,uBACPA,EAAO,wBACPA,EAAO,yBACPxC,EAAY,gBACZA,EAAY,iBACb,CACD;AACD;AAEA,SAAS,iBAAiB,GAAqB;CAC9C,OAAO,OAAO,MAAMqG,EAAM,QAAQ,CAAC,IAAI,mBAAmBA,EAAM,YAAY;AAC7E;AAEA,SAAS,qBAAqB,GAA4C;CACzE,OAAOA,MAAU,KAAA,KAAa,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"}
|
package/dist/keys/keys.d.ts
CHANGED
|
@@ -59,17 +59,20 @@ export interface KeyPairMaterial {
|
|
|
59
59
|
exportPrivateJwk(): Promise<JsonWebKey>;
|
|
60
60
|
}
|
|
61
61
|
/** RSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */
|
|
62
|
-
export
|
|
62
|
+
export type ImportRsaKeyInput = {
|
|
63
63
|
/** Discriminant selecting RSA import. */
|
|
64
64
|
readonly kind: "rsa";
|
|
65
|
-
|
|
65
|
+
} & ({
|
|
66
|
+
/** Signature padding scheme. Defaults to `'pkcs1-v1_5'`. */
|
|
67
|
+
readonly scheme?: RsaSignatureScheme;
|
|
68
|
+
/** Signature hash. Defaults to `'SHA-256'`. */
|
|
66
69
|
readonly hash?: RsaHash;
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
readonly
|
|
72
|
-
}
|
|
70
|
+
} | {
|
|
71
|
+
/** Import an encryption key with `encrypt`/`decrypt` usages. */
|
|
72
|
+
readonly scheme: "oaep";
|
|
73
|
+
/** Hash. Defaults to `'SHA-256'`. Explicit `'SHA-1'` supports legacy OAEP envelopes. */
|
|
74
|
+
readonly hash?: RsaHash | "SHA-1";
|
|
75
|
+
});
|
|
73
76
|
/** ECDSA variant of {@linkcode PublicKeyImportInput} / {@linkcode PrivateKeyImportInput}. */
|
|
74
77
|
export interface ImportEcKeyInput {
|
|
75
78
|
/** Discriminant selecting ECDSA import. */
|