micro509 0.13.0 → 0.15.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 (165) hide show
  1. package/CHANGELOG.md +2064 -0
  2. package/README.md +111 -183
  3. package/dist/crypto/crypto.d.ts +104 -0
  4. package/dist/crypto/crypto.js +105 -0
  5. package/dist/crypto/crypto.js.map +1 -0
  6. package/dist/crypto.d.ts +4 -0
  7. package/dist/crypto.js +1 -0
  8. package/dist/der/der.d.ts +41 -33
  9. package/dist/der/der.js +26 -24
  10. package/dist/der/der.js.map +1 -1
  11. package/dist/index.d.ts +18 -14
  12. package/dist/index.js +19 -17
  13. package/dist/internal/asn1/asn1.d.ts +3 -6
  14. package/dist/internal/asn1/asn1.js +355 -44
  15. package/dist/internal/asn1/asn1.js.map +1 -1
  16. package/dist/internal/asn1/ber.js +146 -0
  17. package/dist/internal/asn1/ber.js.map +1 -0
  18. package/dist/internal/asn1/decode-refusal.js +29 -0
  19. package/dist/internal/asn1/decode-refusal.js.map +1 -0
  20. package/dist/internal/asn1/der.d.ts +42 -43
  21. package/dist/internal/asn1/der.js +148 -56
  22. package/dist/internal/asn1/der.js.map +1 -1
  23. package/dist/internal/asn1/oids.js +90 -54
  24. package/dist/internal/asn1/oids.js.map +1 -1
  25. package/dist/internal/asn1/oids2.js +1 -2
  26. package/dist/internal/asn1/oids2.js.map +1 -1
  27. package/dist/internal/crypto/algorithm-names.js +5 -2
  28. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  29. package/dist/internal/crypto/ecdsa.js +13 -8
  30. package/dist/internal/crypto/ecdsa.js.map +1 -1
  31. package/dist/internal/crypto/hash.js +1 -2
  32. package/dist/internal/crypto/hash.js.map +1 -1
  33. package/dist/internal/crypto/pbes2.d.ts +51 -0
  34. package/dist/internal/crypto/pbes2.js +86 -34
  35. package/dist/internal/crypto/pbes2.js.map +1 -1
  36. package/dist/internal/crypto/rsa-pss.js +48 -44
  37. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  38. package/dist/internal/crypto/sig-verify.d.ts +28 -0
  39. package/dist/internal/crypto/sig-verify.js +111 -62
  40. package/dist/internal/crypto/sig-verify.js.map +1 -1
  41. package/dist/internal/crypto/signing.d.ts +1 -4
  42. package/dist/internal/crypto/signing.js +28 -29
  43. package/dist/internal/crypto/signing.js.map +1 -1
  44. package/dist/internal/crypto/webcrypto.js +1 -2
  45. package/dist/internal/crypto/webcrypto.js.map +1 -1
  46. package/dist/internal/shared/base64.js +8 -3
  47. package/dist/internal/shared/base64.js.map +1 -1
  48. package/dist/internal/shared/dn.d.ts +13 -0
  49. package/dist/internal/shared/dn.js +101 -48
  50. package/dist/internal/shared/dn.js.map +1 -1
  51. package/dist/internal/shared/idna-tables.js +7217 -0
  52. package/dist/internal/shared/idna-tables.js.map +1 -0
  53. package/dist/internal/shared/idna.js +296 -0
  54. package/dist/internal/shared/idna.js.map +1 -0
  55. package/dist/internal/shared/ip.d.ts +66 -0
  56. package/dist/internal/shared/ip.js +19 -3
  57. package/dist/internal/shared/ip.js.map +1 -1
  58. package/dist/internal/shared/mailbox.js +26 -0
  59. package/dist/internal/shared/mailbox.js.map +1 -0
  60. package/dist/internal/shared/punycode.js +101 -0
  61. package/dist/internal/shared/punycode.js.map +1 -0
  62. package/dist/internal/shared/rfc3454-tables.js +1 -2
  63. package/dist/internal/shared/rfc3454-tables.js.map +1 -1
  64. package/dist/internal/shared/rfc4518-tables.js +119 -0
  65. package/dist/internal/shared/rfc4518-tables.js.map +1 -0
  66. package/dist/internal/shared/uri-host.js +102 -0
  67. package/dist/internal/shared/uri-host.js.map +1 -0
  68. package/dist/internal/verify/name-constraints-engine.js +246 -131
  69. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  70. package/dist/internal/verify/policy-engine.js +6 -21
  71. package/dist/internal/verify/policy-engine.js.map +1 -1
  72. package/dist/internal/verify/verify-path.d.ts +4 -0
  73. package/dist/internal/verify/verify-path.js +264 -128
  74. package/dist/internal/verify/verify-path.js.map +1 -1
  75. package/dist/internal/x509/directory-name.js +23 -0
  76. package/dist/internal/x509/directory-name.js.map +1 -0
  77. package/dist/internal/x509/extension-bits.js +15 -13
  78. package/dist/internal/x509/extension-bits.js.map +1 -1
  79. package/dist/internal/x509/extension-errors.d.ts +3 -0
  80. package/dist/internal/x509/extension-errors.js +19 -0
  81. package/dist/internal/x509/extension-errors.js.map +1 -0
  82. package/dist/internal/x509/extension-registry.js +157 -81
  83. package/dist/internal/x509/extension-registry.js.map +1 -1
  84. package/dist/internal/x509/general-name-profile.js +129 -0
  85. package/dist/internal/x509/general-name-profile.js.map +1 -0
  86. package/dist/internal/x509/general-name-tags.js +27 -0
  87. package/dist/internal/x509/general-name-tags.js.map +1 -0
  88. package/dist/internal/x509/general-name.js +183 -0
  89. package/dist/internal/x509/general-name.js.map +1 -0
  90. package/dist/internal/x509/name-fields.js +21 -12
  91. package/dist/internal/x509/name-fields.js.map +1 -1
  92. package/dist/internal/x509/or-address.js +217 -0
  93. package/dist/internal/x509/or-address.js.map +1 -0
  94. package/dist/keys/keys.d.ts +124 -95
  95. package/dist/keys/keys.js +362 -214
  96. package/dist/keys/keys.js.map +1 -1
  97. package/dist/keys.d.ts +3 -2
  98. package/dist/keys.js +3 -2
  99. package/dist/pem/pem.d.ts +17 -19
  100. package/dist/pem/pem.js +122 -41
  101. package/dist/pem/pem.js.map +1 -1
  102. package/dist/pem.js +1 -2
  103. package/dist/pkcs/pfx.d.ts +57 -32
  104. package/dist/pkcs/pfx.js +209 -173
  105. package/dist/pkcs/pfx.js.map +1 -1
  106. package/dist/pkcs/pkcs12-mac.d.ts +104 -27
  107. package/dist/pkcs/pkcs12-mac.js +266 -79
  108. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  109. package/dist/pkcs/pkcs7.d.ts +123 -53
  110. package/dist/pkcs/pkcs7.js +314 -238
  111. package/dist/pkcs/pkcs7.js.map +1 -1
  112. package/dist/pkcs.d.ts +5 -4
  113. package/dist/result/result.d.ts +43 -28
  114. package/dist/result/result.js +27 -14
  115. package/dist/result/result.js.map +1 -1
  116. package/dist/result.d.ts +2 -2
  117. package/dist/result.js +1 -2
  118. package/dist/revocation/chain.d.ts +101 -23
  119. package/dist/revocation/chain.js +456 -206
  120. package/dist/revocation/chain.js.map +1 -1
  121. package/dist/revocation/crl.d.ts +140 -65
  122. package/dist/revocation/crl.js +691 -391
  123. package/dist/revocation/crl.js.map +1 -1
  124. package/dist/revocation/ocsp.d.ts +145 -69
  125. package/dist/revocation/ocsp.js +347 -297
  126. package/dist/revocation/ocsp.js.map +1 -1
  127. package/dist/revocation/revocation.d.ts +48 -36
  128. package/dist/revocation/revocation.js +112 -63
  129. package/dist/revocation/revocation.js.map +1 -1
  130. package/dist/revocation.d.ts +5 -5
  131. package/dist/revocation.js +5 -5
  132. package/dist/verify/identity.d.ts +18 -20
  133. package/dist/verify/identity.js +120 -90
  134. package/dist/verify/identity.js.map +1 -1
  135. package/dist/verify/name-constraints.d.ts +1 -4
  136. package/dist/verify/policy.d.ts +15 -8
  137. package/dist/verify/verify.d.ts +86 -46
  138. package/dist/verify/verify.js +309 -143
  139. package/dist/verify/verify.js.map +1 -1
  140. package/dist/verify.d.ts +3 -2
  141. package/dist/verify.js +4 -3
  142. package/dist/x509/certificate.d.ts +50 -28
  143. package/dist/x509/certificate.js +69 -36
  144. package/dist/x509/certificate.js.map +1 -1
  145. package/dist/x509/csr.d.ts +9 -8
  146. package/dist/x509/csr.js +10 -11
  147. package/dist/x509/csr.js.map +1 -1
  148. package/dist/x509/extensions.d.ts +207 -82
  149. package/dist/x509/extensions.js +561 -128
  150. package/dist/x509/extensions.js.map +1 -1
  151. package/dist/x509/fingerprint.d.ts +4 -7
  152. package/dist/x509/fingerprint.js +1 -2
  153. package/dist/x509/fingerprint.js.map +1 -1
  154. package/dist/x509/name-text.d.ts +7 -9
  155. package/dist/x509/name-text.js +20 -4
  156. package/dist/x509/name-text.js.map +1 -1
  157. package/dist/x509/name.d.ts +15 -14
  158. package/dist/x509/name.js +23 -19
  159. package/dist/x509/name.js.map +1 -1
  160. package/dist/x509/parse.d.ts +165 -64
  161. package/dist/x509/parse.js +444 -459
  162. package/dist/x509/parse.js.map +1 -1
  163. package/dist/x509.d.ts +8 -5
  164. package/dist/x509.js +10 -8
  165. package/package.json +90 -65
@@ -1 +1 @@
1
- {"version":3,"file":"verify-path.js","names":[],"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 { 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: 'signature_invalid' | 'unsupported_signature_algorithm_parameters';\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/** 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 async function verifyCertificateSignature(\n\tcertificate: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): Promise<VerifyCertificateSignatureResult> {\n\tconst result = await verifySignedDataDetailed(\n\t\tcertificate.signatureAlgorithmOid,\n\t\tcertificate.signatureAlgorithmParametersDer,\n\t\tissuer.publicKeyAlgorithmOid,\n\t\tissuer.publicKeyParametersOid,\n\t\tissuer.subjectPublicKeyInfoDer,\n\t\tcertificate.signatureValue,\n\t\tcertificate.tbsCertificateDer,\n\t);\n\tif (!result.ok && result.code === 'verification_error') {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'signature_invalid',\n\t\t\treason: result.reason,\n\t\t};\n\t}\n\treturn result;\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): 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\tlet sawUntrustedAnchor = false;\n\tlet deepestPath: readonly ParsedCertificate[] = [leaf];\n\tlet deepestMissingIssuerAt: number | undefined;\n\tlet preferredFailure: VerifyChainFailure | undefined;\n\tconst deadEnds = new Set<string>();\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\tif (preferredFailure !== undefined) {\n\t\treturn {\n\t\t\tchain: deepestPath,\n\t\t\tfoundTrustedRoot: false,\n\t\t\tfailure: preferredFailure,\n\t\t};\n\t}\n\tif (sawUntrustedAnchor) {\n\t\treturn { chain: deepestPath, foundTrustedRoot: false };\n\t}\n\treturn deepestMissingIssuerAt === undefined\n\t\t? { chain: deepestPath, foundTrustedRoot: false }\n\t\t: {\n\t\t\t\tchain: deepestPath,\n\t\t\t\tfoundTrustedRoot: false,\n\t\t\t\tmissingIssuerAt: deepestMissingIssuerAt,\n\t\t\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 (rootFingerprints.has(fingerprint(current))) {\n\t\t\treturn path;\n\t\t}\n\t\tconst matchedAnchor = await matchTrustAnchor(current, anchorIndex, callbacks, path.length - 1);\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 visitedKey = [...visited].sort().join(',');\n\t\tconst memoKey = `${fingerprint(current)}:${caBelowCount}:${visitedKey}`;\n\t\tif (deadEnds.has(memoKey)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst issuers = rankIssuerCandidates(\n\t\t\tcurrent,\n\t\t\tsubjectIndex.get(canonicalDnKey(current.issuer)) ?? [],\n\t\t\torder,\n\t\t\trootFingerprints,\n\t\t);\n\t\tif (issuers.length === 0) {\n\t\t\trecordMissingIssuers(current, path);\n\t\t\tdeadEnds.add(memoKey);\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst issuerPath = await searchIssuerCandidates(current, issuers, path, visited, caBelowCount);\n\t\tif (issuerPath !== undefined) return issuerPath;\n\n\t\tdeadEnds.add(memoKey);\n\t\tupdateDeepest(path);\n\t\treturn undefined;\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\tupdateDeepest(path);\n\t\t\tsawUntrustedAnchor = true;\n\t\t} else if (updateDeepest(path)) {\n\t\t\tdeepestMissingIssuerAt = path.length - 1;\n\t\t}\n\t}\n\n\t/** Searches ranked issuer candidates until one produces a trusted path. */\n\tasync function searchIssuerCandidates(\n\t\tcurrent: ParsedCertificate,\n\t\tissuers: readonly ParsedCertificate[],\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tfor (const issuer of issuers) {\n\t\t\tconst result = await searchIssuerCandidate(current, issuer, path, visited, caBelowCount);\n\t\t\tif (result !== undefined) return result;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tasync function searchIssuerCandidate(\n\t\tcurrent: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tconst issuerFingerprint = fingerprint(issuer);\n\t\tif (visited.has(issuerFingerprint)) return 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);\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 updateDeepest(path: readonly ParsedCertificate[]): boolean {\n\t\tif (path.length > deepestPath.length) {\n\t\t\tdeepestPath = path;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tfunction recordFailure(\n\t\tcandidateFailure: VerifyChainFailure,\n\t\tpath: readonly ParsedCertificate[],\n\t): void {\n\t\tif (preferredFailure === undefined || path.length > deepestPath.length) {\n\t\t\tpreferredFailure = candidateFailure;\n\t\t\tdeepestPath = path;\n\t\t}\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): 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 verifyCertificateSignature(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\n/** Filters and sorts issuer candidates: AKI match first, then roots, then input order. */\nfunction rankIssuerCandidates(\n\tcurrent: ParsedCertificate,\n\tcandidates: readonly ParsedCertificate[],\n\torder: ReadonlyMap<string, number>,\n\trootFingerprints: ReadonlySet<string>,\n): readonly ParsedCertificate[] {\n\tconst aki = current.authorityKeyIdentifier;\n\tconst filtered = [...candidates].filter((candidate) => isIssuerOf(candidate, current));\n\tconst fps = new Map<ParsedCertificate, string>();\n\tfor (const candidate of filtered) {\n\t\tfps.set(candidate, fingerprint(candidate));\n\t}\n\treturn filtered.sort((left, right) => {\n\t\tconst akiScore = compareBooleans(matchesAki(left, aki), matchesAki(right, aki));\n\t\tif (akiScore !== 0) {\n\t\t\treturn akiScore;\n\t\t}\n\t\tconst leftFp = fps.get(left) ?? '';\n\t\tconst rightFp = fps.get(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}\n\n/** Returns `true` if the candidate's SKI matches the given authority key identifier. */\nfunction matchesAki(candidate: ParsedCertificate, aki: string | undefined): boolean {\n\treturn (\n\t\taki !== undefined &&\n\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\tcandidate.subjectKeyIdentifier === aki\n\t);\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): 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 (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 verifyTrustAnchorSignature(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\nasync function verifyTrustAnchorSignature(\n\tcertificate: ParsedCertificate,\n\tanchor: TrustAnchor,\n): Promise<VerifyCertificateSignatureResult> {\n\tconst verificationResult = await verifySignedDataDetailed(\n\t\tcertificate.signatureAlgorithmOid,\n\t\tcertificate.signatureAlgorithmParametersDer,\n\t\tanchor.publicKeyAlgorithmOid,\n\t\tanchor.publicKeyParametersOid,\n\t\tanchor.subjectPublicKeyInfoDer,\n\t\tcertificate.signatureValue,\n\t\tcertificate.tbsCertificateDer,\n\t);\n\treturn !verificationResult.ok && verificationResult.code === 'verification_error'\n\t\t? { ok: false, code: 'signature_invalid', reason: verificationResult.reason }\n\t\t: verificationResult;\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,SAAgB,iBAAiB,GAAgC,GA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QAAmC;;AAGhE,SAAS,YAAY,GAAwC;CAC5D,IAAI,IAAS,EAAiB,IAAI,CAAW;CAK7C,OAJI,MAAW,KAAA,MACd,IAAS,EAAM,EAAY,GAAG,GAC9B,EAAiB,IAAI,GAAa,CAAM,IAElC;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","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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AwC;CAC5D,IAAIC,IAASD,EAAiB,IAAInG,CAAW;CAK7C,OAJIoG,MAAW,KAAA,MACd,IAAS7B,EAAMvE,EAAY,GAAG,GAC9BmG,EAAiB,IAAInG,GAAaoG,CAAM,IAElCA;AACR"}
@@ -0,0 +1,23 @@
1
+ import { readRootElement as e } from "../asn1/der.js";
2
+ import { childrenOf as t, decodeObjectIdentifier as n, requireElement as r } from "../asn1/asn1.js";
3
+ // src/internal/x509/directory-name.ts
4
+ /** Read and validate the explicit X.501 Name carried by directoryName [4]. */
5
+ function readDirectoryNameTlv(i) {
6
+ let a = new Uint8Array(i.value), o = r(e(a, { maxDepth: 64 }), "directoryName Name");
7
+ if (o.tag !== 48) throw Error("directoryName must wrap a Name SEQUENCE");
8
+ for (let e of t(a, o)) {
9
+ if (e.tag !== 49) throw Error("directoryName RDN must use SET");
10
+ let r = t(a, e);
11
+ if (r.length === 0) throw Error("directoryName RDN must not be empty");
12
+ for (let e of r) {
13
+ if (e.tag !== 48) throw Error("directoryName attribute must use SEQUENCE");
14
+ let r = t(a, e), i = r[0];
15
+ if (r.length !== 2 || i === void 0 || i.tag !== 6) throw Error("directoryName attribute must contain an OID and value");
16
+ n(i.value);
17
+ }
18
+ }
19
+ return a;
20
+ }
21
+ export { readDirectoryNameTlv };
22
+
23
+ //# sourceMappingURL=directory-name.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"directory-name.js","names":["nameDer","element","name","requireElement","readRootElement","rdn","childrenOf","attributes","attribute","parts","type"],"sources":["../../../src/internal/x509/directory-name.ts"],"sourcesContent":["import { childrenOf, decodeObjectIdentifier, requireElement } from '#micro509/internal/asn1/asn1';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport { DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der';\n\n/** Read and validate the explicit X.501 Name carried by directoryName [4]. */\nexport function readDirectoryNameTlv(element: DerElement): Uint8Array {\n\tconst nameDer = new Uint8Array(element.value);\n\tconst name = requireElement(\n\t\treadRootElement(nameDer, { maxDepth: DEFAULT_MAX_DER_DEPTH }),\n\t\t'directoryName Name',\n\t);\n\tif (name.tag !== 0x30) {\n\t\tthrow new Error('directoryName must wrap a Name SEQUENCE');\n\t}\n\tfor (const rdn of childrenOf(nameDer, name)) {\n\t\tif (rdn.tag !== 0x31) {\n\t\t\tthrow new Error('directoryName RDN must use SET');\n\t\t}\n\t\tconst attributes = childrenOf(nameDer, rdn);\n\t\tif (attributes.length === 0) {\n\t\t\tthrow new Error('directoryName RDN must not be empty');\n\t\t}\n\t\tfor (const attribute of attributes) {\n\t\t\tif (attribute.tag !== 0x30) {\n\t\t\t\tthrow new Error('directoryName attribute must use SEQUENCE');\n\t\t\t}\n\t\t\tconst parts = childrenOf(nameDer, attribute);\n\t\t\tconst type = parts[0];\n\t\t\tif (parts.length !== 2 || type === undefined || type.tag !== 0x06) {\n\t\t\t\tthrow new Error('directoryName attribute must contain an OID and value');\n\t\t\t}\n\t\t\tdecodeObjectIdentifier(type.value);\n\t\t}\n\t}\n\treturn nameDer;\n}\n"],"mappings":";;;;AAKA,SAAgB,qBAAqB,GAAiC;CACrE,IAAMA,IAAU,IAAI,WAAWC,EAAQ,KAAK,GACtCC,IAAOC,EACZC,EAAgBJ,GAAS,EAAE,UAAA,GAAgC,CAAC,GAC5D,oBACD;CACA,IAAIE,EAAK,QAAQ,IAChB,MAAU,MAAM,yCAAyC;CAE1D,KAAK,IAAMG,KAAOC,EAAWN,GAASE,CAAI,GAAG;EAC5C,IAAIG,EAAI,QAAQ,IACf,MAAU,MAAM,gCAAgC;EAEjD,IAAME,IAAaD,EAAWN,GAASK,CAAG;EAC1C,IAAIE,EAAW,WAAW,GACzB,MAAU,MAAM,qCAAqC;EAEtD,KAAK,IAAMC,KAAaD,GAAY;GACnC,IAAIC,EAAU,QAAQ,IACrB,MAAU,MAAM,2CAA2C;GAE5D,IAAMC,IAAQH,EAAWN,GAASQ,CAAS,GACrCE,IAAOD,EAAM;GACnB,IAAIA,EAAM,WAAW,KAAKC,MAAS,KAAA,KAAaA,EAAK,QAAQ,GAC5D,MAAU,MAAM,uDAAuD;GAExE,EAAuBA,EAAK,KAAK;EAClC;CACD;CACA,OAAOV;AACR"}
@@ -1,5 +1,6 @@
1
1
  import { bitString as e, readRootElement as t } from "../asn1/der.js";
2
- //#region src/internal/x509/extension-bits.ts
2
+ import { throwExtensionEncoderError as n } from "./extension-errors.js";
3
+ // src/internal/x509/extension-bits.ts
3
4
  /**
4
5
  * BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.
5
6
  *
@@ -14,10 +15,11 @@ import { bitString as e, readRootElement as t } from "../asn1/der.js";
14
15
  * `flags` contains the recognized flag values with any non-zero padding bits
15
16
  * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding
16
17
  * had non-zero bits in positions that DER ({@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1}) requires to be zero.
17
- * Verification layers can use this signal to reject non-conformant encodings.
18
+ * `requireCanonicalBitFlags` rejects such encodings before they reach parsed
19
+ * extension values.
18
20
  */
19
21
  /** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */
20
- const n = [
22
+ const r = [
21
23
  "digitalSignature",
22
24
  "nonRepudiation",
23
25
  "keyEncipherment",
@@ -27,7 +29,7 @@ const n = [
27
29
  "cRLSign",
28
30
  "encipherOnly",
29
31
  "decipherOnly"
30
- ], r = [
32
+ ], i = [
31
33
  "keyCompromise",
32
34
  "cACompromise",
33
35
  "affiliationChanged",
@@ -43,8 +45,9 @@ const n = [
43
45
  * @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.
44
46
  */
45
47
  function encodeKeyUsageExtension(t) {
46
- let r = encodeBitFlags(t, (e) => indexInOrder(n, e, "key usage"));
47
- return e(r.bytes, r.unusedBits);
48
+ t.length === 0 && n("key_usage_empty", "keyUsage must set at least one bit");
49
+ let i = encodeBitFlags(t, (e) => indexInOrder(r, e, "key usage"));
50
+ return e(i.bytes, i.unusedBits);
48
51
  }
49
52
  /**
50
53
  * Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.
@@ -52,9 +55,9 @@ function encodeKeyUsageExtension(t) {
52
55
  * @param bytes DER of the keyUsage extension value (BIT STRING).
53
56
  */
54
57
  function parseKeyUsageExtension(e) {
55
- let r = t(e, { maxDepth: 64 });
56
- if (r.tag !== 3) throw Error("keyUsage must be a BIT STRING");
57
- return requireCanonicalBitFlags(decodeBitFlags(r.value, n, 0), "keyUsage");
58
+ let n = t(e, { maxDepth: 64 });
59
+ if (n.tag !== 3) throw Error("keyUsage must be a BIT STRING");
60
+ return requireCanonicalBitFlags(decodeBitFlags(n.value, r, 0), "keyUsage");
58
61
  }
59
62
  /**
60
63
  * Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes
@@ -63,7 +66,7 @@ function parseKeyUsageExtension(e) {
63
66
  * @param reasons Reason flags to encode.
64
67
  */
65
68
  function encodeDistributionPointReasonFlagsContent(e) {
66
- let t = encodeBitFlags(e, (e) => indexInOrder(r, e, "distribution point reason") + 1);
69
+ let t = encodeBitFlags(e, (e) => indexInOrder(i, e, "distribution point reason") + 1);
67
70
  return Uint8Array.of(t.unusedBits, ...t.bytes);
68
71
  }
69
72
  /**
@@ -73,7 +76,7 @@ function encodeDistributionPointReasonFlagsContent(e) {
73
76
  * @returns Decoded reason flags, preserving empty-but-present values and padding metadata.
74
77
  */
75
78
  function parseDistributionPointReasonFlagsContent(e) {
76
- return requireCanonicalBitFlags(decodeBitFlags(e, r, 1), "DistributionPoint reasons");
79
+ return requireCanonicalBitFlags(decodeBitFlags(e, i, 1), "DistributionPoint reasons");
77
80
  }
78
81
  /** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */
79
82
  function encodeBitFlags(e, t) {
@@ -104,7 +107,7 @@ function decodeBitFlags(e, t, n) {
104
107
  let i = e.slice(1);
105
108
  if (i.length === 0 && r !== 0) throw Error("Invalid BIT STRING");
106
109
  let a = !1;
107
- r > 0 && i.length > 0 && (a = ((i[i.length - 1] ?? 0) & (1 << r) - 1) != 0);
110
+ r > 0 && i.length > 0 && (a = !!((i[i.length - 1] ?? 0) & (1 << r) - 1));
108
111
  let o = [];
109
112
  for (let e = 0; e < t.length; e += 1) {
110
113
  let r = e + n, a = Math.floor(r / 8);
@@ -129,7 +132,6 @@ function indexInOrder(e, t, n) {
129
132
  if (r < 0) throw Error(`Unsupported ${n}: ${t}`);
130
133
  return r;
131
134
  }
132
- //#endregion
133
135
  export { encodeDistributionPointReasonFlagsContent, encodeKeyUsageExtension, parseDistributionPointReasonFlagsContent, parseKeyUsageExtension };
134
136
 
135
137
  //# sourceMappingURL=extension-bits.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"extension-bits.js","names":[],"sources":["../../../src/internal/x509/extension-bits.ts"],"sourcesContent":["/**\n * BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.\n *\n * Centralizes the bit-position ordering so certificate builders and parsers\n * produce identical wire encodings.\n *\n * @module\n */\n\n/**\n * Decoded BIT STRING flags with DER conformance metadata.\n *\n * `flags` contains the recognized flag values with any non-zero padding bits\n * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding\n * had non-zero bits in positions that DER ({@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1}) requires to be zero.\n * Verification layers can use this signal to reject non-conformant encodings.\n */\nimport { bitString, DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der';\nimport type { DistributionPointReason, KeyUsage, ParsedBitFlags } from '#micro509/x509/extensions';\n\nexport type { ParsedBitFlags };\n\n/** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */\nconst KEY_USAGE_ORDER = [\n\t'digitalSignature',\n\t'nonRepudiation',\n\t'keyEncipherment',\n\t'dataEncipherment',\n\t'keyAgreement',\n\t'keyCertSign',\n\t'cRLSign',\n\t'encipherOnly',\n\t'decipherOnly',\n] as const satisfies readonly KeyUsage[];\n\n/** Canonical bit-position order for DistributionPoint reason flags (RFC 5280 §4.2.1.13). */\nconst DISTRIBUTION_POINT_REASON_ORDER = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n] as const satisfies readonly DistributionPointReason[];\n\n/**\n * Encode an array of {@linkcode KeyUsage} flags into a DER BIT STRING.\n *\n * @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.\n */\nexport function encodeKeyUsageExtension(usages: readonly KeyUsage[]): Uint8Array {\n\tconst encoded = encodeBitFlags(usages, (usage) =>\n\t\tindexInOrder(KEY_USAGE_ORDER, usage, 'key usage'),\n\t);\n\treturn bitString(encoded.bytes, encoded.unusedBits);\n}\n\n/**\n * Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.\n *\n * @param bytes DER of the keyUsage extension value (BIT STRING).\n */\nexport function parseKeyUsageExtension(bytes: Uint8Array): ParsedBitFlags<KeyUsage> {\n\tconst bitStringElement = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (bitStringElement.tag !== 0x03) {\n\t\tthrow new Error('keyUsage must be a BIT STRING');\n\t}\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(bitStringElement.value, KEY_USAGE_ORDER, 0),\n\t\t'keyUsage',\n\t);\n}\n\n/**\n * Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes\n * (unusedBits prefix + flag bytes), suitable for wrapping in an implicit context tag.\n *\n * @param reasons Reason flags to encode.\n */\nexport function encodeDistributionPointReasonFlagsContent(\n\treasons: readonly DistributionPointReason[],\n): Uint8Array {\n\tconst encoded = encodeBitFlags(\n\t\treasons,\n\t\t(reason) =>\n\t\t\tindexInOrder(DISTRIBUTION_POINT_REASON_ORDER, reason, 'distribution point reason') + 1,\n\t);\n\treturn Uint8Array.of(encoded.unusedBits, ...encoded.bytes);\n}\n\n/**\n * Decode BIT STRING content bytes into {@linkcode DistributionPointReason} flags.\n *\n * @param value Raw content bytes (unusedBits prefix + flag bytes).\n * @returns Decoded reason flags, preserving empty-but-present values and padding metadata.\n */\nexport function parseDistributionPointReasonFlagsContent(\n\tvalue: Uint8Array,\n): ParsedBitFlags<DistributionPointReason> {\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(value, DISTRIBUTION_POINT_REASON_ORDER, 1),\n\t\t'DistributionPoint reasons',\n\t);\n}\n\n/** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */\nfunction encodeBitFlags<T extends string>(\n\tvalues: readonly T[],\n\tbitForValue: (value: T) => number,\n): {\n\treadonly bytes: Uint8Array;\n\treadonly unusedBits: number;\n} {\n\tif (values.length === 0) {\n\t\treturn { bytes: new Uint8Array(0), unusedBits: 0 };\n\t}\n\tlet highestBit = -1;\n\tconst bits: number[] = [];\n\tfor (const value of values) {\n\t\tconst bit = bitForValue(value);\n\t\tbits.push(bit);\n\t\tif (bit > highestBit) {\n\t\t\thighestBit = bit;\n\t\t}\n\t}\n\tconst byteLength = Math.floor(highestBit / 8) + 1;\n\tconst bytes = new Uint8Array(byteLength);\n\tfor (const bit of bits) {\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tconst bitIndex = bit % 8;\n\t\tconst current = bytes[byteIndex] ?? 0;\n\t\tbytes[byteIndex] = current | (1 << (7 - bitIndex));\n\t}\n\tconst totalBits = highestBit + 1;\n\tconst unusedBits = (8 - (totalBits % 8)) % 8;\n\treturn {\n\t\tbytes,\n\t\tunusedBits,\n\t};\n}\n\n/** Unpack set bits from a BIT STRING content into named flags from a candidate list. */\nfunction decodeBitFlags<T extends string>(\n\tvalue: Uint8Array,\n\tcandidates: readonly T[],\n\tbitOffset: number,\n): ParsedBitFlags<T> {\n\tif (value.length === 0) {\n\t\tthrow new Error('Empty BIT STRING');\n\t}\n\tconst unusedBits = value[0] ?? 0;\n\tif (unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst bytes = value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\t// Detect non-zero padding bits in the unused positions of the last byte.\n\t// DER X.690 §11.2.1 requires these to be zero. Rather than rejecting here\n\t// (which would break interop with real-world non-conformant certificates),\n\t// we record the violation so verification layers can decide.\n\tlet nonZeroPadding = false;\n\tif (unusedBits > 0 && bytes.length > 0) {\n\t\tconst lastByte = bytes[bytes.length - 1] ?? 0;\n\t\tconst paddingMask = (1 << unusedBits) - 1;\n\t\tnonZeroPadding = (lastByte & paddingMask) !== 0;\n\t}\n\tconst flags: T[] = [];\n\tfor (let index = 0; index < candidates.length; index += 1) {\n\t\tconst bit = index + bitOffset;\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tif (byteIndex >= bytes.length) {\n\t\t\tbreak;\n\t\t}\n\t\tconst byte = bytes[byteIndex] ?? 0;\n\t\tconst bitIndex = bit % 8;\n\t\tif ((byte & (1 << (7 - bitIndex))) !== 0) {\n\t\t\tconst candidate = candidates[index];\n\t\t\tif (candidate !== undefined) {\n\t\t\t\tflags.push(candidate);\n\t\t\t}\n\t\t}\n\t}\n\treturn { flags, nonZeroPadding };\n}\n\nfunction requireCanonicalBitFlags<T extends string>(\n\tparsed: ParsedBitFlags<T>,\n\tlabel: string,\n): ParsedBitFlags<T> {\n\tif (parsed.nonZeroPadding) {\n\t\tthrow new Error(`${label} BIT STRING must not set padding bits`);\n\t}\n\treturn parsed;\n}\n\n/** Look up the bit position of a flag in its canonical order array. Throws on unknown flags. */\nfunction indexInOrder<T extends string>(order: readonly T[], value: T, label: string): number {\n\tconst index = order.indexOf(value);\n\tif (index < 0) {\n\t\tthrow new Error(`Unsupported ${label}: ${value}`);\n\t}\n\treturn index;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,MAAM,IAAkB;CACvB;CACA;CACA;CACA;CACA;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Aa,KACM,KAAM;CAI3C;AACD;;AAGA,SAAS,eACR,GACA,GACA,GACoB;CACpB,IAAI,EAAM,WAAW,GACpB,MAAU,MAAM,kBAAkB;CAEnC,IAAM,IAAa,EAAM,MAAM;CAC/B,IAAI,IAAa,GAChB,MAAU,MAAM,oBAAoB;CAErC,IAAM,IAAQ,EAAM,MAAM,CAAC;CAC3B,IAAI,EAAM,WAAW,KAAK,MAAe,GACxC,MAAU,MAAM,oBAAoB;CAMrC,IAAI,IAAiB;CACrB,AAAI,IAAa,KAAK,EAAM,SAAS,MAGpC,MAFiB,EAAM,EAAM,SAAS,MAAM,MACvB,KAAK,KAAc,MACM;CAE/C,IAAM,IAAa,CAAC;CACpB,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAW,QAAQ,KAAS,GAAG;EAC1D,IAAM,IAAM,IAAQ,GACd,IAAY,KAAK,MAAM,IAAM,CAAC;EACpC,IAAI,KAAa,EAAM,QACtB;EAID,KAFa,EAAM,MAAc,KAEpB,KAAM,IADF,IAAM,GACmB;GACzC,IAAM,IAAY,EAAW;GAC7B,AAAI,MAAc,KAAA,KACjB,EAAM,KAAK,CAAS;EAEtB;CACD;CACA,OAAO;EAAE;EAAO;CAAe;AAChC;AAEA,SAAS,yBACR,GACA,GACoB;CACpB,IAAI,EAAO,gBACV,MAAU,MAAM,GAAG,EAAM,sCAAsC;CAEhE,OAAO;AACR;;AAGA,SAAS,aAA+B,GAAqB,GAAU,GAAuB;CAC7F,IAAM,IAAQ,EAAM,QAAQ,CAAK;CACjC,IAAI,IAAQ,GACX,MAAU,MAAM,eAAe,EAAM,IAAI,GAAO;CAEjD,OAAO;AACR"}
1
+ {"version":3,"file":"extension-bits.js","names":["KEY_USAGE_ORDER","DISTRIBUTION_POINT_REASON_ORDER","usages","throwExtensionEncoderError","encoded","usage","bitString","bitStringElement","readRootElement","bytes","reasons","reason","value","values","highestBit","bits","bit","bitForValue","byteLength","byteIndex","bitIndex","unusedBits","nonZeroPadding","flags","index","candidates","bitOffset","candidate","parsed","label","order"],"sources":["../../../src/internal/x509/extension-bits.ts"],"sourcesContent":["/**\n * BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.\n *\n * Centralizes the bit-position ordering so certificate builders and parsers\n * produce identical wire encodings.\n *\n * @module\n */\n\n/**\n * Decoded BIT STRING flags with DER conformance metadata.\n *\n * `flags` contains the recognized flag values with any non-zero padding bits\n * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding\n * had non-zero bits in positions that DER ({@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1}) requires to be zero.\n * `requireCanonicalBitFlags` rejects such encodings before they reach parsed\n * extension values.\n */\nimport { bitString, DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der';\nimport { throwExtensionEncoderError } from '#micro509/internal/x509/extension-errors';\nimport type { DistributionPointReason, KeyUsage, ParsedBitFlags } from '#micro509/x509/extensions';\n\nexport type { ParsedBitFlags };\n\n/** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */\nconst KEY_USAGE_ORDER = [\n\t'digitalSignature',\n\t'nonRepudiation',\n\t'keyEncipherment',\n\t'dataEncipherment',\n\t'keyAgreement',\n\t'keyCertSign',\n\t'cRLSign',\n\t'encipherOnly',\n\t'decipherOnly',\n] as const satisfies readonly KeyUsage[];\n\n/** Canonical bit-position order for DistributionPoint reason flags (RFC 5280 §4.2.1.13). */\nconst DISTRIBUTION_POINT_REASON_ORDER = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n] as const satisfies readonly DistributionPointReason[];\n\n/**\n * Encode an array of {@linkcode KeyUsage} flags into a DER BIT STRING.\n *\n * @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.\n */\nexport function encodeKeyUsageExtension(usages: readonly KeyUsage[]): Uint8Array {\n\tif (usages.length === 0) {\n\t\tthrowExtensionEncoderError('key_usage_empty', 'keyUsage must set at least one bit');\n\t}\n\tconst encoded = encodeBitFlags(usages, (usage) =>\n\t\tindexInOrder(KEY_USAGE_ORDER, usage, 'key usage'),\n\t);\n\treturn bitString(encoded.bytes, encoded.unusedBits);\n}\n\n/**\n * Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.\n *\n * @param bytes DER of the keyUsage extension value (BIT STRING).\n */\nexport function parseKeyUsageExtension(bytes: Uint8Array): ParsedBitFlags<KeyUsage> {\n\tconst bitStringElement = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (bitStringElement.tag !== 0x03) {\n\t\tthrow new Error('keyUsage must be a BIT STRING');\n\t}\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(bitStringElement.value, KEY_USAGE_ORDER, 0),\n\t\t'keyUsage',\n\t);\n}\n\n/**\n * Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes\n * (unusedBits prefix + flag bytes), suitable for wrapping in an implicit context tag.\n *\n * @param reasons Reason flags to encode.\n */\nexport function encodeDistributionPointReasonFlagsContent(\n\treasons: readonly DistributionPointReason[],\n): Uint8Array {\n\tconst encoded = encodeBitFlags(\n\t\treasons,\n\t\t(reason) =>\n\t\t\tindexInOrder(DISTRIBUTION_POINT_REASON_ORDER, reason, 'distribution point reason') + 1,\n\t);\n\treturn Uint8Array.of(encoded.unusedBits, ...encoded.bytes);\n}\n\n/**\n * Decode BIT STRING content bytes into {@linkcode DistributionPointReason} flags.\n *\n * @param value Raw content bytes (unusedBits prefix + flag bytes).\n * @returns Decoded reason flags, preserving empty-but-present values and padding metadata.\n */\nexport function parseDistributionPointReasonFlagsContent(\n\tvalue: Uint8Array,\n): ParsedBitFlags<DistributionPointReason> {\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(value, DISTRIBUTION_POINT_REASON_ORDER, 1),\n\t\t'DistributionPoint reasons',\n\t);\n}\n\n/** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */\nfunction encodeBitFlags<T extends string>(\n\tvalues: readonly T[],\n\tbitForValue: (value: T) => number,\n): {\n\treadonly bytes: Uint8Array;\n\treadonly unusedBits: number;\n} {\n\tif (values.length === 0) {\n\t\treturn { bytes: new Uint8Array(0), unusedBits: 0 };\n\t}\n\tlet highestBit = -1;\n\tconst bits: number[] = [];\n\tfor (const value of values) {\n\t\tconst bit = bitForValue(value);\n\t\tbits.push(bit);\n\t\tif (bit > highestBit) {\n\t\t\thighestBit = bit;\n\t\t}\n\t}\n\tconst byteLength = Math.floor(highestBit / 8) + 1;\n\tconst bytes = new Uint8Array(byteLength);\n\tfor (const bit of bits) {\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tconst bitIndex = bit % 8;\n\t\tconst current = bytes[byteIndex] ?? 0;\n\t\tbytes[byteIndex] = current | (1 << (7 - bitIndex));\n\t}\n\tconst totalBits = highestBit + 1;\n\tconst unusedBits = (8 - (totalBits % 8)) % 8;\n\treturn {\n\t\tbytes,\n\t\tunusedBits,\n\t};\n}\n\n/** Unpack set bits from a BIT STRING content into named flags from a candidate list. */\nfunction decodeBitFlags<T extends string>(\n\tvalue: Uint8Array,\n\tcandidates: readonly T[],\n\tbitOffset: number,\n): ParsedBitFlags<T> {\n\tif (value.length === 0) {\n\t\tthrow new Error('Empty BIT STRING');\n\t}\n\tconst unusedBits = value[0] ?? 0;\n\tif (unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst bytes = value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tlet nonZeroPadding = false;\n\tif (unusedBits > 0 && bytes.length > 0) {\n\t\tconst lastByte = bytes[bytes.length - 1] ?? 0;\n\t\tconst paddingMask = (1 << unusedBits) - 1;\n\t\tnonZeroPadding = (lastByte & paddingMask) !== 0;\n\t}\n\tconst flags: T[] = [];\n\tfor (let index = 0; index < candidates.length; index += 1) {\n\t\tconst bit = index + bitOffset;\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tif (byteIndex >= bytes.length) {\n\t\t\tbreak;\n\t\t}\n\t\tconst byte = bytes[byteIndex] ?? 0;\n\t\tconst bitIndex = bit % 8;\n\t\tif ((byte & (1 << (7 - bitIndex))) !== 0) {\n\t\t\tconst candidate = candidates[index];\n\t\t\tif (candidate !== undefined) {\n\t\t\t\tflags.push(candidate);\n\t\t\t}\n\t\t}\n\t}\n\treturn { flags, nonZeroPadding };\n}\n\nfunction requireCanonicalBitFlags<T extends string>(\n\tparsed: ParsedBitFlags<T>,\n\tlabel: string,\n): ParsedBitFlags<T> {\n\tif (parsed.nonZeroPadding) {\n\t\tthrow new Error(`${label} BIT STRING must not set padding bits`);\n\t}\n\treturn parsed;\n}\n\n/** Look up the bit position of a flag in its canonical order array. Throws on unknown flags. */\nfunction indexInOrder<T extends string>(order: readonly T[], value: T, label: string): number {\n\tconst index = order.indexOf(value);\n\tif (index < 0) {\n\t\tthrow new Error(`Unsupported ${label}: ${value}`);\n\t}\n\treturn index;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyBA,MAAMA,IAAkB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,GAGMC,IAAkC;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAOA,SAAgB,wBAAwB,GAAyC;CAChF,AAAIC,EAAO,WAAW,KACrBC,EAA2B,mBAAmB,oCAAoC;CAEnF,IAAMC,IAAU,eAAeF,IAAS,MACvC,aAAaF,GAAiBK,GAAO,WAAW,CACjD;CACA,OAAOC,EAAUF,EAAQ,OAAOA,EAAQ,UAAU;AACnD;;;;;;AAOA,SAAgB,uBAAuB,GAA6C;CACnF,IAAMG,IAAmBC,EAAgBC,GAAO,EAAE,UAAA,GAAgC,CAAC;CACnF,IAAIF,EAAiB,QAAQ,GAC5B,MAAU,MAAM,+BAA+B;CAEhD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AKZ,EAAM,SAAS,MAGpC,IAAA,IAFiBA,EAAMA,EAAM,SAAS,MAAM,MACvB,KAAKY,KAAc;CAGzC,IAAME,IAAa,CAAC;CACpB,KAAK,IAAIC,IAAQ,GAAGA,IAAQC,EAAW,QAAQ,KAAS,GAAG;EAC1D,IAAMT,IAAMQ,IAAQE,GACdP,IAAY,KAAK,MAAMH,IAAM,CAAC;EACpC,IAAIG,KAAaV,EAAM,QACtB;EAID,KAFaA,EAAMU,MAAc,KAEpB,KAAM,IADFH,IAAM,GACmB;GACzC,IAAMW,IAAYF,EAAWD;GAC7B,AAAIG,MAAc,KAAA,KACjBJ,EAAM,KAAKI,CAAS;EAEtB;CACD;CACA,OAAO;EAAE;EAAO;CAAe;AAChC;AAEA,SAAS,yBACR,GACA,GACoB;CACpB,IAAIC,EAAO,gBACV,MAAU,MAAM,GAAGC,EAAM,sCAAsC;CAEhE,OAAOD;AACR;;AAGA,SAAS,aAA+B,GAAqB,GAAU,GAAuB;CAC7F,IAAMJ,IAAQM,EAAM,QAAQlB,CAAK;CACjC,IAAIY,IAAQ,GACX,MAAU,MAAM,eAAeK,EAAM,IAAIjB,GAAO;CAEjD,OAAOY;AACR"}
@@ -0,0 +1,3 @@
1
+ /** Machine-readable reason an extension encoder rejected its construction input. */
2
+ export type ExtensionEncoderErrorCode = "authority_info_access_empty" | "authority_info_access_ocsp_not_uri" | "certificate_policies_empty" | "crl_distribution_points_empty" | "directory_name_not_sequence" | "display_text_control_character" | "display_text_ia5_string" | "display_text_lone_surrogate" | "display_text_not_nfc" | "display_text_out_of_range" | "distribution_point_crl_issuer_empty" | "distribution_point_crl_issuer_not_directory_name" | "distribution_point_empty" | "distribution_point_full_name_empty" | "distribution_point_relative_name_multiple_crl_issuers" | "domain_trailing_dot" | "duplicate_extension_oid" | "duplicate_policy_oid" | "edwards_key_usage_forbids_agreement_bit" | "edwards_key_usage_forbids_key_cert_sign" | "edwards_key_usage_requires_key_cert_sign" | "edwards_key_usage_requires_signing_bit" | "email_name_constraint_names_mailbox" | "empty_general_name_value" | "empty_subject_requires_subject_alt_name" | "extended_key_usage_empty" | "extension_must_be_critical" | "extension_must_be_non_critical" | "extension_not_supported_in_context" | "invalid_bmp_string" | "invalid_general_name_content" | "invalid_general_name_tag" | "invalid_ia5_string" | "invalid_idn" | "invalid_ip_name_constraint" | "invalid_krb5_principal_name" | "invalid_other_name_value" | "invalid_oid" | "invalid_smtp_utf8_mailbox" | "invalid_srv_name" | "invalid_srv_name_constraint" | "invalid_uri_name_constraint" | "invalid_visible_string" | "key_usage_empty" | "limit_exceeded" | "malformed_known_extension_value" | "montgomery_key_usage_forbids_both_cipher_bits" | "montgomery_key_usage_forbids_signature_bit" | "montgomery_key_usage_requires_key_agreement" | "name_constraints_empty" | "no_rev_avail_conflict" | "other_name_type_id_has_variant" | "path_length_requires_ca" | "path_length_requires_key_cert_sign" | "policy_constraints_empty" | "policy_mappings_any_policy" | "policy_mappings_empty" | "reserved_policy_qualifier_oid" | "smtp_utf8_mailbox_ascii_local_part";
3
+ //# sourceMappingURL=extension-errors.d.ts.map
@@ -0,0 +1,19 @@
1
+ import { throwMicro509Error as e } from "../../result/result.js";
2
+ // src/internal/x509/extension-errors.ts
3
+ /**
4
+ * Stable error codes for X.509 extension encoder input validation.
5
+ *
6
+ * The extension builders throw on invalid construction input (an empty
7
+ * collection, a duplicate OID, an out-of-range value). Each failure carries one
8
+ * of these codes on a {@link ResultError}, so callers branch on `error.code` via
9
+ * `isResultError` instead of matching message strings.
10
+ *
11
+ * @module
12
+ */
13
+ /** Throws a {@link ResultError} for an extension encoder input-validation failure. */
14
+ function throwExtensionEncoderError(t, n) {
15
+ e(t, n);
16
+ }
17
+ export { throwExtensionEncoderError };
18
+
19
+ //# sourceMappingURL=extension-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension-errors.js","names":["code","message"],"sources":["../../../src/internal/x509/extension-errors.ts"],"sourcesContent":["/**\n * Stable error codes for X.509 extension encoder input validation.\n *\n * The extension builders throw on invalid construction input (an empty\n * collection, a duplicate OID, an out-of-range value). Each failure carries one\n * of these codes on a {@link ResultError}, so callers branch on `error.code` via\n * `isResultError` instead of matching message strings.\n *\n * @module\n */\n\nimport { throwMicro509Error } from '#micro509/result/result';\n\n/** Machine-readable reason an extension encoder rejected its construction input. */\nexport type ExtensionEncoderErrorCode =\n\t| 'authority_info_access_empty'\n\t| 'authority_info_access_ocsp_not_uri'\n\t| 'certificate_policies_empty'\n\t| 'crl_distribution_points_empty'\n\t| 'directory_name_not_sequence'\n\t| 'display_text_control_character'\n\t| 'display_text_ia5_string'\n\t| 'display_text_lone_surrogate'\n\t| 'display_text_not_nfc'\n\t| 'display_text_out_of_range'\n\t| 'distribution_point_crl_issuer_empty'\n\t| 'distribution_point_crl_issuer_not_directory_name'\n\t| 'distribution_point_empty'\n\t| 'distribution_point_full_name_empty'\n\t| 'distribution_point_relative_name_multiple_crl_issuers'\n\t| 'domain_trailing_dot'\n\t| 'duplicate_extension_oid'\n\t| 'duplicate_policy_oid'\n\t| 'edwards_key_usage_forbids_agreement_bit'\n\t| 'edwards_key_usage_forbids_key_cert_sign'\n\t| 'edwards_key_usage_requires_key_cert_sign'\n\t| 'edwards_key_usage_requires_signing_bit'\n\t| 'email_name_constraint_names_mailbox'\n\t| 'empty_general_name_value'\n\t| 'empty_subject_requires_subject_alt_name'\n\t| 'extended_key_usage_empty'\n\t| 'extension_must_be_critical'\n\t| 'extension_must_be_non_critical'\n\t| 'extension_not_supported_in_context'\n\t| 'invalid_bmp_string'\n\t| 'invalid_general_name_content'\n\t| 'invalid_general_name_tag'\n\t| 'invalid_ia5_string'\n\t| 'invalid_idn'\n\t| 'invalid_ip_name_constraint'\n\t| 'invalid_krb5_principal_name'\n\t| 'invalid_other_name_value'\n\t| 'invalid_oid'\n\t| 'invalid_smtp_utf8_mailbox'\n\t| 'invalid_srv_name'\n\t| 'invalid_srv_name_constraint'\n\t| 'invalid_uri_name_constraint'\n\t| 'invalid_visible_string'\n\t| 'key_usage_empty'\n\t| 'limit_exceeded'\n\t| 'malformed_known_extension_value'\n\t| 'montgomery_key_usage_forbids_both_cipher_bits'\n\t| 'montgomery_key_usage_forbids_signature_bit'\n\t| 'montgomery_key_usage_requires_key_agreement'\n\t| 'name_constraints_empty'\n\t| 'no_rev_avail_conflict'\n\t| 'other_name_type_id_has_variant'\n\t| 'path_length_requires_ca'\n\t| 'path_length_requires_key_cert_sign'\n\t| 'policy_constraints_empty'\n\t| 'policy_mappings_any_policy'\n\t| 'policy_mappings_empty'\n\t| 'reserved_policy_qualifier_oid'\n\t| 'smtp_utf8_mailbox_ascii_local_part';\n\n/** Throws a {@link ResultError} for an extension encoder input-validation failure. */\nexport function throwExtensionEncoderError(\n\tcode: ExtensionEncoderErrorCode,\n\tmessage: string,\n): never {\n\tthrowMicro509Error(code, message);\n}\n"],"mappings":";;;;;;;;;;;;;AA4EA,SAAgB,2BACf,GACA,GACQ;CACR,EAAmBA,GAAMC,CAAO;AACjC"}