micro509 0.11.0 → 0.13.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 (54) hide show
  1. package/README.md +17 -3
  2. package/dist/der/der.d.ts +127 -0
  3. package/dist/der/der.js +171 -0
  4. package/dist/der/der.js.map +1 -0
  5. package/dist/der.d.ts +4 -0
  6. package/dist/der.js +4 -0
  7. package/dist/index.d.ts +2 -1
  8. package/dist/index.js +2 -1
  9. package/dist/internal/asn1/asn1.d.ts +20 -0
  10. package/dist/internal/asn1/asn1.js +60 -28
  11. package/dist/internal/asn1/asn1.js.map +1 -1
  12. package/dist/internal/asn1/der.d.ts +171 -0
  13. package/dist/internal/asn1/der.js +101 -36
  14. package/dist/internal/asn1/der.js.map +1 -1
  15. package/dist/internal/asn1/oids.js +22 -0
  16. package/dist/internal/asn1/oids2.js +9 -2
  17. package/dist/internal/asn1/oids2.js.map +1 -1
  18. package/dist/internal/shared/dn.js +143 -13
  19. package/dist/internal/shared/dn.js.map +1 -1
  20. package/dist/internal/shared/rfc3454-tables.js +1782 -0
  21. package/dist/internal/shared/rfc3454-tables.js.map +1 -0
  22. package/dist/internal/verify/name-constraints-engine.js +47 -15
  23. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  24. package/dist/internal/verify/policy-engine.js +86 -95
  25. package/dist/internal/verify/policy-engine.js.map +1 -1
  26. package/dist/internal/verify/verify-path.js +18 -14
  27. package/dist/internal/verify/verify-path.js.map +1 -1
  28. package/dist/internal/x509/extension-bits.js +1 -1
  29. package/dist/internal/x509/extension-bits.js.map +1 -1
  30. package/dist/internal/x509/name-fields.js +19 -4
  31. package/dist/internal/x509/name-fields.js.map +1 -1
  32. package/dist/revocation/chain.js +110 -55
  33. package/dist/revocation/chain.js.map +1 -1
  34. package/dist/revocation/crl.js +2 -2
  35. package/dist/revocation/crl.js.map +1 -1
  36. package/dist/revocation/ocsp.js +2 -2
  37. package/dist/revocation/ocsp.js.map +1 -1
  38. package/dist/verify/verify.d.ts +14 -1
  39. package/dist/verify/verify.js +39 -32
  40. package/dist/verify/verify.js.map +1 -1
  41. package/dist/x509/extensions.d.ts +1 -1
  42. package/dist/x509/extensions.js.map +1 -1
  43. package/dist/x509/fingerprint.d.ts +3 -0
  44. package/dist/x509/fingerprint.js +3 -0
  45. package/dist/x509/fingerprint.js.map +1 -1
  46. package/dist/x509/name-text.d.ts +50 -0
  47. package/dist/x509/name-text.js +111 -0
  48. package/dist/x509/name-text.js.map +1 -0
  49. package/dist/x509/parse.d.ts +3 -0
  50. package/dist/x509/parse.js +10 -1
  51. package/dist/x509/parse.js.map +1 -1
  52. package/dist/x509.d.ts +2 -1
  53. package/dist/x509.js +2 -1
  54. package/package.json +46 -25
@@ -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/** 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\treturn { chain: success, foundTrustedRoot: true };\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\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":";;;;;;;;;;;;;;;AAoFA,SAAgB,iBAAiB,GAAgC,GAAmB;CACnF,OACC,EAAY,UAAU,QAAQ,KAAK,EAAG,QAAQ,KAC9C,EAAG,QAAQ,KAAK,EAAY,SAAS,QAAQ;AAE/C;;AAGA,SAAgB,aAAa,GAAyC;CACrE,OAAO,EAA0B,EAAY,SAA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EAAS,OAAO;GACpB,AAAI,MAAiB,KAAA,MACpB,IAAe,EAAU,QACxB,qBACA,yCACA,GACA,EAAU,OAAO;IAChB,mBAAmB,EAAY,QAAQ,OAAO;IAC9C,QAAQ;GACT,CAAC,CACF;GAED;EACD;EACA,OAAO,EAAE,SAAS,GAAK;CACxB;CACA,OAAO,MAAiB,KAAA,IAErB,EAAE,SAAS,GAAM,IADjB;EAAE,SAAS;EAAO,SAAS;CAAa;AAE5C;AAEA,SAAS,uBAAuB,GAAgC,GAA8B;CAC7F,OACC,EAAO,yBAAyB,KAAA,KAChC,EAAY,2BAA2B,KAAA,KACvC,EAAO,yBAAyB,EAAY;AAE9C;AAEA,eAAe,2BACd,GACA,GAC4C;CAC5C,IAAM,IAAqB,MAAM,EAChC,EAAY,uBACZ,EAAY,iCACZ,EAAO,uBACP,EAAO,wBACP,EAAO,yBACP,EAAY,gBACZ,EAAY,iBACb;CACA,OAAO,CAAC,EAAmB,MAAM,EAAmB,SAAS,uBAC1D;EAAE,IAAI;EAAO,MAAM;EAAqB,QAAQ,EAAmB;CAAO,IAC1E;AACJ;AAEA,SAAS,iBAAiB,GAAqB;CAC9C,OAAO,OAAO,MAAM,EAAM,QAAQ,CAAC,IAAI,mBAAmB,EAAM,YAAY;AAC7E;AAEA,SAAS,qBAAqB,GAA4C;CACzE,OAAO,MAAU,KAAA,KAAa,OAAO,UAAU,CAAK,KAAK,KAAS;AACnE;;AAGA,MAAM,oBAAmB,IAAI,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":[],"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,GAAmB;CACnF,OACC,EAAY,UAAU,QAAQ,KAAK,EAAG,QAAQ,KAC9C,EAAG,QAAQ,KAAK,EAAY,SAAS,QAAQ;AAE/C;;AAGA,SAAgB,aAAa,GAAyC;CACrE,OAAO,EAA0B,EAAY,SAAS,EAAY,MAAM;AACzE;;AAGA,SAAgB,+BACf,GACA,GACS;CACT,IAAI,IAAQ;CACZ,KAAK,IAAI,IAAS,GAAG,IAAS,GAAO,KAAU,GAAG;EACjD,IAAM,IAAc,EAAM;EAC1B,AAAI,GAAa,kBAAkB,OAAO,MAAQ,CAAC,a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ACpB,IAAe,EAAU,QACxB,qBACA,yCACA,GACA,EAAU,OAAO;IAChB,mBAAmB,EAAY,QAAQ,OAAO;IAC9C,QAAQ;GACT,CAAC,CACF;GAED;EACD;EACA,OAAO,EAAE,SAAS,GAAK;CACxB;CACA,OAAO,MAAiB,KAAA,IAErB,EAAE,SAAS,GAAM,IADjB;EAAE,SAAS;EAAO,SAAS;CAAa;AAE5C;AAEA,SAAS,uBAAuB,GAAgC,GAA8B;CAC7F,OACC,EAAO,yBAAyB,KAAA,KAChC,EAAY,2BAA2B,KAAA,KACvC,EAAO,yBAAyB,EAAY;AAE9C;AAEA,eAAe,2BACd,GACA,GAC4C;CAC5C,IAAM,IAAqB,MAAM,EAChC,EAAY,uBACZ,EAAY,iCACZ,EAAO,uBACP,EAAO,wBACP,EAAO,yBACP,EAAY,gBACZ,EAAY,iBACb;CACA,OAAO,CAAC,EAAmB,MAAM,EAAmB,SAAS,uBAC1D;EAAE,IAAI;EAAO,MAAM;EAAqB,QAAQ,EAAmB;CAAO,IAC1E;AACJ;AAEA,SAAS,iBAAiB,GAAqB;CAC9C,OAAO,OAAO,MAAM,EAAM,QAAQ,CAAC,IAAI,mBAAmB,EAAM,YAAY;AAC7E;AAEA,SAAS,qBAAqB,GAA4C;CACzE,OAAO,MAAU,KAAA,KAAa,OAAO,UAAU,CAAK,KAAK,KAAS;AACnE;;AAGA,MAAM,oBAAmB,IAAI,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"}
@@ -13,7 +13,7 @@ import { bitString as e, readRootElement as t } from "../asn1/der.js";
13
13
  *
14
14
  * `flags` contains the recognized flag values with any non-zero padding bits
15
15
  * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding
16
- * had non-zero bits in positions that DER (X.690 §11.2.2) requires to be zero.
16
+ * 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
17
  * Verification layers can use this signal to reject non-conformant encodings.
18
18
  */
19
19
  /** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */
@@ -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 (X.690 §11.2.2) 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.2 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;CACA;CACA;CACA;CACA;AACD,GAGM,IAAkC;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAOA,SAAgB,wBAAwB,GAAyC;CAChF,IAAM,IAAU,eAAe,IAAS,MACvC,aAAa,GAAiB,GAAO,WAAW,CACjD;CACA,OAAO,EAAU,EAAQ,OAAO,EAAQ,UAAU;AACnD;;;;;;AAOA,SAAgB,uBAAuB,GAA6C;CACnF,IAAM,IAAmB,EAAgB,GAAO,EAAE,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B;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":[],"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;CACA;CACA;CACA;CACA;AACD,GAGM,IAAkC;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAOA,SAAgB,wBAAwB,GAAyC;CAChF,IAAM,IAAU,eAAe,IAAS,MACvC,aAAa,GAAiB,GAAO,WAAW,CACjD;CACA,OAAO,EAAU,EAAQ,OAAO,EAAQ,UAAU;AACnD;;;;;;AAOA,SAAgB,uBAAuB,GAA6C;CACnF,IAAM,IAAmB,EAAgB,GAAO,EAAE,UAAA,GAAgC,CAAC;CACnF,IAAI,EAAiB,QAAQ,GAC5B,MAAU,MAAM,+BAA+B;CAEhD,OAAO,yBACN,eAAe,EAAiB,OAAO,GAAiB,CAAC,GACzD,UACD;AACD;;;;;;;AAQA,SAAgB,0CACf,GACa;CACb,IAAM,IAAU,eACf,IACC,MACA,aAAa,GAAiC,GAAQ,2BAA2B,IAAI,CACvF;CACA,OAAO,WAAW,GAAG,EAAQ,YAAY,GAAG,EAAQ,KAAK;AAC1D;;;;;;;AAQA,SAAgB,yCACf,GAC0C;CAC1C,OAAO,yBACN,eAAe,GAAO,GAAiC,CAAC,GACxD,2BACD;AACD;;AAGA,SAAS,eACR,GACA,GAIC;CACD,IAAI,EAAO,WAAW,GACrB,OAAO;EAAE,uBAAO,IAAI,WAAY;EAAG,YAAY;CAAE;CAElD,IAAI,IAAa,IACX,IAAiB,CAAC;CACxB,KAAK,IAAM,KAAS,GAAQ;EAC3B,IAAM,IAAM,EAAY,CAAK;EAE7B,AADA,EAAK,KAAK,CAAG,GACT,IAAM,MACT,IAAa;CAEf;CACA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AAM,eAAe,EAAM,IAAI,GAAO;CAEjD,OAAO;AACR"}
@@ -75,13 +75,28 @@ const i = {
75
75
  "title",
76
76
  "serialNumber",
77
77
  "emailAddress"
78
- ], o = /* @__PURE__ */ new Map();
79
- for (let e of a) o.set(i[e].oid, e);
78
+ ], o = {
79
+ [r.commonName]: "CN",
80
+ [r.surname]: "SN",
81
+ [r.serialNumber]: "serialNumber",
82
+ [r.countryName]: "C",
83
+ [r.localityName]: "L",
84
+ [r.stateOrProvinceName]: "ST",
85
+ [r.streetAddress]: "STREET",
86
+ [r.organizationName]: "O",
87
+ [r.organizationalUnitName]: "OU",
88
+ [r.title]: "title",
89
+ [r.givenName]: "GN",
90
+ [r.emailAddress]: "emailAddress",
91
+ [r.userId]: "UID",
92
+ [r.domainComponent]: "DC"
93
+ }, s = /* @__PURE__ */ new Map();
94
+ for (let e of a) s.set(i[e].oid, e);
80
95
  /** Resolves a dotted-decimal OID to its {@linkcode NameFieldKey}, or `undefined` if unknown. */
81
96
  function nameFieldKeyFromOid(e) {
82
- return o.get(e);
97
+ return s.get(e);
83
98
  }
84
99
  //#endregion
85
- export { i as NAME_FIELD_DEFINITIONS, a as NAME_OBJECT_ORDER, nameFieldKeyFromOid };
100
+ export { o as DN_ATTRIBUTE_KEYWORDS, i as NAME_FIELD_DEFINITIONS, a as NAME_OBJECT_ORDER, nameFieldKeyFromOid };
86
101
 
87
102
  //# sourceMappingURL=name-fields.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"name-fields.js","names":[],"sources":["../../../src/internal/x509/name-fields.ts"],"sourcesContent":["/**\n * Distinguished-name field metadata.\n *\n * Maps friendly {@linkcode NameFieldKey} names to their ASN.1 OIDs and string-encoding functions.\n * @module\n */\n\nimport { ia5String, printableString, utf8String } from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport type { NameFieldKey } from '#micro509/x509/name';\n\n/**\n * OID and ASN.1 string encoder for one distinguished-name attribute type.\n */\nexport interface NameFieldDefinition {\n\t/** Dotted-decimal OID (e.g. `\"2.5.4.3\"` for commonName). */\n\treadonly oid: string;\n\t/** Encodes the attribute value to the correct ASN.1 string type (UTF8, PrintableString, IA5). */\n\treadonly encode: (value: string) => Uint8Array;\n}\n\n/**\n * Registry mapping every {@linkcode NameFieldKey} to its OID and ASN.1 encoder.\n *\n * Country and serialNumber use PrintableString; emailAddress uses IA5String;\n * all others use UTF8String.\n */\nexport const NAME_FIELD_DEFINITIONS: Record<NameFieldKey, NameFieldDefinition> = {\n\tcommonName: { oid: OIDS.commonName, encode: utf8String },\n\tsurname: { oid: OIDS.surname, encode: utf8String },\n\tserialNumber: { oid: OIDS.serialNumber, encode: printableString },\n\tcountry: { oid: OIDS.countryName, encode: printableString },\n\tlocality: { oid: OIDS.localityName, encode: utf8String },\n\tstate: { oid: OIDS.stateOrProvinceName, encode: utf8String },\n\tstreet: { oid: OIDS.streetAddress, encode: utf8String },\n\torganization: { oid: OIDS.organizationName, encode: utf8String },\n\torganizationalUnit: { oid: OIDS.organizationalUnitName, encode: utf8String },\n\ttitle: { oid: OIDS.title, encode: utf8String },\n\tgivenName: { oid: OIDS.givenName, encode: utf8String },\n\temailAddress: { oid: OIDS.emailAddress, encode: ia5String },\n};\n\n/**\n * Canonical emission order when converting a {@linkcode NameObject} to RDN attributes.\n *\n * Follows the conventional `C/ST/L/STREET/O/OU/CN/…` ordering.\n */\nexport const NAME_OBJECT_ORDER: readonly NameFieldKey[] = [\n\t'country',\n\t'state',\n\t'locality',\n\t'street',\n\t'organization',\n\t'organizationalUnit',\n\t'commonName',\n\t'givenName',\n\t'surname',\n\t'title',\n\t'serialNumber',\n\t'emailAddress',\n];\n\n/** Reverse lookup table: OID string → friendly {@linkcode NameFieldKey}. */\nconst NAME_FIELD_KEYS_BY_OID = new Map<string, NameFieldKey>();\nfor (const key of NAME_OBJECT_ORDER) {\n\tNAME_FIELD_KEYS_BY_OID.set(NAME_FIELD_DEFINITIONS[key].oid, key);\n}\n\n/** Resolves a dotted-decimal OID to its {@linkcode NameFieldKey}, or `undefined` if unknown. */\nexport function nameFieldKeyFromOid(oid: string): NameFieldKey | undefined {\n\treturn NAME_FIELD_KEYS_BY_OID.get(oid);\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,MAAa,IAAoE;CAChF,YAAY;EAAE,KAAK,EAAK;EAAY,QAAQ;CAAW;CACvD,SAAS;EAAE,KAAK,EAAK;EAAS,QAAQ;CAAW;CACjD,cAAc;EAAE,KAAK,EAAK;EAAc,QAAQ;CAAgB;CAChE,SAAS;EAAE,KAAK,EAAK;EAAa,QAAQ;CAAgB;CAC1D,UAAU;EAAE,KAAK,EAAK;EAAc,QAAQ;CAAW;CACvD,OAAO;EAAE,KAAK,EAAK;EAAqB,QAAQ;CAAW;CAC3D,QAAQ;EAAE,KAAK,EAAK;EAAe,QAAQ;CAAW;CACtD,cAAc;EAAE,KAAK,EAAK;EAAkB,QAAQ;CAAW;CAC/D,oBAAoB;EAAE,KAAK,EAAK;EAAwB,QAAQ;CAAW;CAC3E,OAAO;EAAE,KAAK,EAAK;EAAO,QAAQ;CAAW;CAC7C,WAAW;EAAE,KAAK,EAAK;EAAW,QAAQ;CAAW;CACrD,cAAc;EAAE,KAAK,EAAK;EAAc,QAAQ;CAAU;AAC3D,GAOa,IAA6C;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,GAGM,oBAAyB,IAAI,IAA0B;AAC7D,KAAK,IAAM,KAAO,GACjB,EAAuB,IAAI,EAAuB,EAAI,CAAC,KAAK,CAAG;;AAIhE,SAAgB,oBAAoB,GAAuC;CAC1E,OAAO,EAAuB,IAAI,CAAG;AACtC"}
1
+ {"version":3,"file":"name-fields.js","names":[],"sources":["../../../src/internal/x509/name-fields.ts"],"sourcesContent":["/**\n * Distinguished-name field metadata.\n *\n * Maps friendly {@linkcode NameFieldKey} names to their ASN.1 OIDs and string-encoding functions.\n * @module\n */\n\nimport { ia5String, printableString, utf8String } from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport type { NameFieldKey } from '#micro509/x509/name';\n\n/**\n * OID and ASN.1 string encoder for one distinguished-name attribute type.\n */\nexport interface NameFieldDefinition {\n\t/** Dotted-decimal OID (e.g. `\"2.5.4.3\"` for commonName). */\n\treadonly oid: string;\n\t/** Encodes the attribute value to the correct ASN.1 string type (UTF8, PrintableString, IA5). */\n\treadonly encode: (value: string) => Uint8Array;\n}\n\n/**\n * Registry mapping every {@linkcode NameFieldKey} to its OID and ASN.1 encoder.\n *\n * Country and serialNumber use PrintableString; emailAddress uses IA5String;\n * all others use UTF8String.\n */\nexport const NAME_FIELD_DEFINITIONS: Record<NameFieldKey, NameFieldDefinition> = {\n\tcommonName: { oid: OIDS.commonName, encode: utf8String },\n\tsurname: { oid: OIDS.surname, encode: utf8String },\n\tserialNumber: { oid: OIDS.serialNumber, encode: printableString },\n\tcountry: { oid: OIDS.countryName, encode: printableString },\n\tlocality: { oid: OIDS.localityName, encode: utf8String },\n\tstate: { oid: OIDS.stateOrProvinceName, encode: utf8String },\n\tstreet: { oid: OIDS.streetAddress, encode: utf8String },\n\torganization: { oid: OIDS.organizationName, encode: utf8String },\n\torganizationalUnit: { oid: OIDS.organizationalUnitName, encode: utf8String },\n\ttitle: { oid: OIDS.title, encode: utf8String },\n\tgivenName: { oid: OIDS.givenName, encode: utf8String },\n\temailAddress: { oid: OIDS.emailAddress, encode: ia5String },\n};\n\n/**\n * Canonical emission order when converting a {@linkcode NameObject} to RDN attributes.\n *\n * Follows the conventional `C/ST/L/STREET/O/OU/CN/…` ordering.\n */\nexport const NAME_OBJECT_ORDER: readonly NameFieldKey[] = [\n\t'country',\n\t'state',\n\t'locality',\n\t'street',\n\t'organization',\n\t'organizationalUnit',\n\t'commonName',\n\t'givenName',\n\t'surname',\n\t'title',\n\t'serialNumber',\n\t'emailAddress',\n];\n\n/**\n * Display keyword for a DN attribute type, keyed by OID.\n *\n * RFC 4514 [§3](https://datatracker.ietf.org/doc/html/rfc4514#section-3) defines\n * `CN`, `L`, `ST`, `O`, `OU`, `C`, `STREET`, `DC`, and `UID`; the rest are the short\n * names `openssl` prints for attribute types the RFC leaves to the dotted OID.\n */\nexport const DN_ATTRIBUTE_KEYWORDS: Readonly<Record<string, string>> = {\n\t[OIDS.commonName]: 'CN',\n\t[OIDS.surname]: 'SN',\n\t[OIDS.serialNumber]: 'serialNumber',\n\t[OIDS.countryName]: 'C',\n\t[OIDS.localityName]: 'L',\n\t[OIDS.stateOrProvinceName]: 'ST',\n\t[OIDS.streetAddress]: 'STREET',\n\t[OIDS.organizationName]: 'O',\n\t[OIDS.organizationalUnitName]: 'OU',\n\t[OIDS.title]: 'title',\n\t[OIDS.givenName]: 'GN',\n\t[OIDS.emailAddress]: 'emailAddress',\n\t[OIDS.userId]: 'UID',\n\t[OIDS.domainComponent]: 'DC',\n};\n\n/** Reverse lookup table: OID string → friendly {@linkcode NameFieldKey}. */\nconst NAME_FIELD_KEYS_BY_OID = new Map<string, NameFieldKey>();\nfor (const key of NAME_OBJECT_ORDER) {\n\tNAME_FIELD_KEYS_BY_OID.set(NAME_FIELD_DEFINITIONS[key].oid, key);\n}\n\n/** Resolves a dotted-decimal OID to its {@linkcode NameFieldKey}, or `undefined` if unknown. */\nexport function nameFieldKeyFromOid(oid: string): NameFieldKey | undefined {\n\treturn NAME_FIELD_KEYS_BY_OID.get(oid);\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,MAAa,IAAoE;CAChF,YAAY;EAAE,KAAK,EAAK;EAAY,QAAQ;CAAW;CACvD,SAAS;EAAE,KAAK,EAAK;EAAS,QAAQ;CAAW;CACjD,cAAc;EAAE,KAAK,EAAK;EAAc,QAAQ;CAAgB;CAChE,SAAS;EAAE,KAAK,EAAK;EAAa,QAAQ;CAAgB;CAC1D,UAAU;EAAE,KAAK,EAAK;EAAc,QAAQ;CAAW;CACvD,OAAO;EAAE,KAAK,EAAK;EAAqB,QAAQ;CAAW;CAC3D,QAAQ;EAAE,KAAK,EAAK;EAAe,QAAQ;CAAW;CACtD,cAAc;EAAE,KAAK,EAAK;EAAkB,QAAQ;CAAW;CAC/D,oBAAoB;EAAE,KAAK,EAAK;EAAwB,QAAQ;CAAW;CAC3E,OAAO;EAAE,KAAK,EAAK;EAAO,QAAQ;CAAW;CAC7C,WAAW;EAAE,KAAK,EAAK;EAAW,QAAQ;CAAW;CACrD,cAAc;EAAE,KAAK,EAAK;EAAc,QAAQ;CAAU;AAC3D,GAOa,IAA6C;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,GASa,IAA0D;EACrE,EAAK,aAAa;EAClB,EAAK,UAAU;EACf,EAAK,eAAe;EACpB,EAAK,cAAc;EACnB,EAAK,eAAe;EACpB,EAAK,sBAAsB;EAC3B,EAAK,gBAAgB;EACrB,EAAK,mBAAmB;EACxB,EAAK,yBAAyB;EAC9B,EAAK,QAAQ;EACb,EAAK,YAAY;EACjB,EAAK,eAAe;EACpB,EAAK,SAAS;EACd,EAAK,kBAAkB;AACzB,GAGM,oBAAyB,IAAI,IAA0B;AAC7D,KAAK,IAAM,KAAO,GACjB,EAAuB,IAAI,EAAuB,EAAI,CAAC,KAAK,CAAG;;AAIhE,SAAgB,oBAAoB,GAAuC;CAC1E,OAAO,EAAuB,IAAI,CAAG;AACtC"}
@@ -1,6 +1,7 @@
1
1
  import { parseCertificateFromSource as e } from "../x509/parse.js";
2
2
  import { checkCertificateRevocationAgainstCrl as t, parseCertificateRevocationListDerOrThrow as n, parseCertificateRevocationListPemOrThrow as r, revocationReasonFromCode as i } from "./crl.js";
3
- import { parseOcspResponseDerOrThrow as a, parseOcspResponsePemOrThrow as o, validateOcspResponse as s } from "./ocsp.js";
3
+ import { verifyCertificateChain as a } from "../verify/verify.js";
4
+ import { parseOcspResponseDerOrThrow as o, parseOcspResponsePemOrThrow as s, validateOcspResponse as c } from "./ocsp.js";
4
5
  //#region src/revocation/chain.ts
5
6
  /**
6
7
  * Granular reasons why revocation status could not be determined.
@@ -15,7 +16,7 @@ import { parseOcspResponseDerOrThrow as a, parseOcspResponsePemOrThrow as o, val
15
16
  * `crl_signer_revoked`, `crl_signer_indeterminate`, and OCSP equivalents
16
17
  * - **Freshness**: `crl_expired`, `ocsp_response_expired`
17
18
  */
18
- const c = [
19
+ const l = [
19
20
  "no_applicable_crl",
20
21
  "no_applicable_ocsp",
21
22
  "distribution_point_mismatch",
@@ -61,26 +62,57 @@ function sameCertificate(e, t) {
61
62
  return !0;
62
63
  }
63
64
  /**
64
- * Searches for a certificate that could have signed the given CRL.
65
- * Matches by AKI/SKI or issuer/subject DN.
65
+ * Yields every certificate that could have signed the given CRL, AKI/SKI
66
+ * matches before DN matches. All candidates are returned so a certificate whose
67
+ * subject DN collides with the genuine CRL issuer cannot shadow it: each is
68
+ * tried against the CRL signature and its own path to the trust anchor.
66
69
  */
67
- function findIndirectCrlIssuer(e, t, n) {
70
+ function findIndirectCrlIssuers(e, t, n) {
68
71
  let r = [];
69
72
  for (let e of t) {
70
73
  let t = parseCertificateSafe(e);
71
74
  t !== void 0 && r.push(t);
72
75
  }
73
- let i = [...r, ...n];
74
- if (e.authorityKeyIdentifier !== void 0) {
75
- for (let t of i) if (t.subjectKeyIdentifier !== void 0 && normalizeHex(e.authorityKeyIdentifier) === normalizeHex(t.subjectKeyIdentifier)) return t;
76
- }
77
- for (let t of i) if (e.issuer.derHex === t.subject.derHex) return t;
76
+ let i = [...r, ...n], a = [], push = (e) => {
77
+ a.some((t) => sameCertificate(t, e)) || a.push(e);
78
+ };
79
+ if (e.authorityKeyIdentifier !== void 0) for (let t of i) t.subjectKeyIdentifier !== void 0 && normalizeHex(e.authorityKeyIdentifier) === normalizeHex(t.subjectKeyIdentifier) && push(t);
80
+ for (let t of i) e.issuer.derHex === t.subject.derHex && push(t);
81
+ return a;
78
82
  }
79
83
  /** Lowercases a hex string for bytewise comparison. */
80
84
  function normalizeHex(e) {
81
85
  return e.toLowerCase();
82
86
  }
83
87
  /**
88
+ * RFC 5280 §6.3.3(f): confirms the CRL issuer certificate has a valid
89
+ * certification path to the same trust anchor as the certificate under test. A
90
+ * signer already inside the validated chain is authorized by construction. The
91
+ * path check runs without revocation to avoid unbounded recursion.
92
+ */
93
+ async function crlSignerChainsToAnchor(e, t, n, r) {
94
+ if (t.some((t) => sameCertificate(t, e))) return !0;
95
+ let i = t[t.length - 1];
96
+ if (i === void 0) return !1;
97
+ let o = [], addCandidate = (t) => {
98
+ sameCertificate(t, e) || sameCertificate(t, i) || o.some((e) => sameCertificate(e, t)) || o.push(t);
99
+ };
100
+ for (let e = 0; e < t.length - 1; e += 1) {
101
+ let n = t[e];
102
+ n !== void 0 && addCandidate(n);
103
+ }
104
+ for (let e of n) {
105
+ let t = parseCertificateSafe(e);
106
+ t !== void 0 && addCandidate(t);
107
+ }
108
+ return (await a({
109
+ leaf: e.der,
110
+ intermediates: o.map((e) => e.der),
111
+ roots: [i.der],
112
+ at: r
113
+ })).ok;
114
+ }
115
+ /**
84
116
  * Builds a unique cache key for a certificate.
85
117
  * Uses issuer DN + serial number which uniquely identifies a cert.
86
118
  */
@@ -160,7 +192,7 @@ function buildCrlRevokedStatus(e, t, n, r, i) {
160
192
  }
161
193
  /** Parses an OCSP response from PEM string or DER bytes. */
162
194
  function parseOcspResponseFromSource(e) {
163
- return typeof e == "string" ? o(e) : a(e);
195
+ return typeof e == "string" ? s(e) : o(e);
164
196
  }
165
197
  /** Maps a {@linkcode validateOcspResponse} failure code to an indeterminate reason. */
166
198
  function ocspIndeterminateReasonFromFailure(e) {
@@ -179,7 +211,7 @@ function ocspIndeterminateReasonFromFailure(e) {
179
211
  }
180
212
  }
181
213
  /** Validation failures worth retrying with an explicit responder certificate. */
182
- const l = /* @__PURE__ */ new Set([
214
+ const u = /* @__PURE__ */ new Set([
183
215
  "signature_invalid",
184
216
  "responder_id_mismatch",
185
217
  "responder_chain_invalid",
@@ -196,15 +228,15 @@ async function validateOcspResponseWithResponderFallback(e, t, n, r) {
196
228
  ...n.trustedOcspResponders === void 0 ? {} : { trustedOcspResponders: n.trustedOcspResponders },
197
229
  ...n.policy?.ocspResponderRevocation === void 0 ? {} : { responderRevocationPolicy: n.policy.ocspResponderRevocation },
198
230
  ...n.crls === void 0 ? {} : { responderRevocationCrls: n.crls }
199
- }, a = await s({
231
+ }, a = await c({
200
232
  response: e,
201
233
  ...i
202
234
  });
203
- if (a.ok || !l.has(a.code)) return a;
235
+ if (a.ok || !u.has(a.code)) return a;
204
236
  for (let t of n.extraCertificates ?? []) {
205
237
  let n = parseCertificateSafe(t);
206
238
  if (n === void 0) continue;
207
- let r = await s({
239
+ let r = await c({
208
240
  response: e,
209
241
  ...i,
210
242
  responderCertificate: n
@@ -291,7 +323,7 @@ async function evaluateOcspEvidence(e, t, n) {
291
323
  *
292
324
  * Also validates that CRL signers are not revoked (RFC 5280 §6.3.3).
293
325
  */
294
- const u = [
326
+ const d = [
295
327
  "keyCompromise",
296
328
  "cACompromise",
297
329
  "affiliationChanged",
@@ -301,34 +333,65 @@ const u = [
301
333
  "privilegeWithdrawn",
302
334
  "aACompromise"
303
335
  ];
336
+ /**
337
+ * Runs each candidate signer through the full pipeline for one base CRL:
338
+ * signature/applicability, RFC 5280 §6.3.3(f) path to the anchor, then signer
339
+ * revocation. A candidate that verifies the signature but fails a later step
340
+ * does not shadow a subsequent usable signer, so the search continues. Returns
341
+ * a revoked status when one is found; otherwise records good or diagnostic
342
+ * evidence into `state`.
343
+ */
344
+ async function resolveBaseCrlAgainstSigners(e) {
345
+ let { cert: t, baseCrl: n, applicableDelta: r, crlThisUpdate: i, issuer: a, extraCertificates: o, chain: s, at: c, signerCtx: l, state: u } = e;
346
+ for (let e of collectCrlSignerCandidates(n, a, o, s)) {
347
+ let a = await checkCrlWithIssuer(t, n, r, e, c);
348
+ if (!a.ok) continue;
349
+ if (!await crlSignerChainsToAnchor(e, s, o, c)) {
350
+ u.sawCrlSignerNotAuthorized = !0;
351
+ continue;
352
+ }
353
+ let d = await validateCrlSigner(e, l);
354
+ if (d === "resolved-revoked") {
355
+ u.sawCrlSignerRevoked = !0;
356
+ continue;
357
+ }
358
+ if (d === "resolved-indeterminate") {
359
+ u.sawCrlSignerIndeterminate = !0;
360
+ continue;
361
+ }
362
+ if (a.value.status === "revoked") return buildCrlRevokedStatus(t, e, i, a.value.revocationDate, a.value.reasonCode);
363
+ recordGoodCrlEvidence(u, e, i, n);
364
+ return;
365
+ }
366
+ }
304
367
  async function evaluateCrlEvidence(e, t, n, r) {
305
368
  let { crls: i = [], extraCertificates: a = [], chain: o = [], at: s = /* @__PURE__ */ new Date() } = n, c = {
306
369
  executionErrors: [],
307
370
  coveredReasons: /* @__PURE__ */ new Set(),
308
371
  sawCrlSignerRevoked: !1,
309
372
  sawCrlSignerIndeterminate: !1,
373
+ sawCrlSignerNotAuthorized: !1,
310
374
  sawGood: !1
311
- }, l = parseCrlEvidenceSources(i, c.executionErrors), d = l.filter((e) => e.baseCrlNumber === void 0), f = l.filter((e) => e.baseCrlNumber !== void 0);
312
- for (let n of d) {
313
- let i = findApplicableDeltaCrl(n, f), l = await checkCrlWithAvailableIssuers(e, n, i, t, a, o, s);
314
- if (!l.result.ok) continue;
315
- let u = await validateCrlSigner(l.signer, r);
316
- if (u === "resolved-revoked") {
317
- c.sawCrlSignerRevoked = !0;
318
- continue;
319
- }
320
- if (u === "resolved-indeterminate") {
321
- c.sawCrlSignerIndeterminate = !0;
322
- continue;
323
- }
324
- let d = i !== void 0 && i.thisUpdate.getTime() > n.thisUpdate.getTime() ? i.thisUpdate : n.thisUpdate;
325
- if (l.result.value.status === "revoked") return {
326
- status: buildCrlRevokedStatus(e, l.signer, d, l.result.value.revocationDate, l.result.value.reasonCode),
375
+ }, l = parseCrlEvidenceSources(i, c.executionErrors), u = l.filter((e) => e.baseCrlNumber === void 0), f = l.filter((e) => e.baseCrlNumber !== void 0);
376
+ for (let n of u) {
377
+ let i = findApplicableDeltaCrl(n, f), l = await resolveBaseCrlAgainstSigners({
378
+ cert: e,
379
+ baseCrl: n,
380
+ applicableDelta: i,
381
+ crlThisUpdate: i !== void 0 && i.thisUpdate.getTime() > n.thisUpdate.getTime() ? i.thisUpdate : n.thisUpdate,
382
+ issuer: t,
383
+ extraCertificates: a,
384
+ chain: o,
385
+ at: s,
386
+ signerCtx: r,
387
+ state: c
388
+ });
389
+ if (l !== void 0) return {
390
+ status: l,
327
391
  executionErrors: c.executionErrors
328
392
  };
329
- recordGoodCrlEvidence(c, l.signer, d, n);
330
393
  }
331
- if (c.sawGood && c.freshestGood !== void 0) return u.every((e) => c.coveredReasons.has(e)) ? {
394
+ return c.sawGood && c.freshestGood !== void 0 ? d.every((e) => c.coveredReasons.has(e)) ? {
332
395
  status: {
333
396
  certificate: e,
334
397
  status: "good",
@@ -346,17 +409,19 @@ async function evaluateCrlEvidence(e, t, n, r) {
346
409
  indeterminateReasons: ["reason_coverage_incomplete"]
347
410
  },
348
411
  executionErrors: c.executionErrors
349
- };
350
- let p = [];
351
- return c.sawCrlSignerRevoked ? p.push("crl_signer_revoked") : c.sawCrlSignerIndeterminate ? p.push("crl_signer_indeterminate") : p.push("no_applicable_crl"), {
412
+ } : {
352
413
  status: {
353
414
  certificate: e,
354
415
  status: "indeterminate",
355
- indeterminateReasons: p
416
+ indeterminateReasons: [crlUnavailableReason(c)]
356
417
  },
357
418
  executionErrors: c.executionErrors
358
419
  };
359
420
  }
421
+ /** Most specific indeterminate reason when no CRL yielded a usable verdict. */
422
+ function crlUnavailableReason(e) {
423
+ return e.sawCrlSignerRevoked ? "crl_signer_revoked" : e.sawCrlSignerNotAuthorized ? "crl_signer_not_authorized" : e.sawCrlSignerIndeterminate ? "crl_signer_indeterminate" : "no_applicable_crl";
424
+ }
360
425
  /** Parses complete and delta CRL evidence while retaining source provenance. */
361
426
  function parseCrlEvidenceSources(e, t) {
362
427
  let n = [];
@@ -373,21 +438,11 @@ function parseCrlEvidenceSources(e, t) {
373
438
  function findApplicableDeltaCrl(e, t) {
374
439
  return t.find((t) => t.issuer.derHex === e.issuer.derHex && t.baseCrlNumber !== void 0 && e.crlNumber !== void 0 && BigInt(t.baseCrlNumber) <= BigInt(e.crlNumber));
375
440
  }
376
- /** Evaluates a CRL against each available issuer until applicable evidence is found. */
377
- async function checkCrlWithAvailableIssuers(e, t, n, r, i, a, o) {
378
- let s = await checkCrlWithIssuer(e, t, n, r, o);
379
- if (s.ok) return {
380
- result: s,
381
- signer: r
382
- };
383
- let c = findIndirectCrlIssuer(t, i, a);
384
- return c === void 0 || sameCertificate(c, r) ? {
385
- result: s,
386
- signer: r
387
- } : {
388
- result: await checkCrlWithIssuer(e, t, n, c, o),
389
- signer: c
390
- };
441
+ /** The direct issuer first, then deduplicated indirect CRL-issuer candidates. */
442
+ function collectCrlSignerCandidates(e, t, n, r) {
443
+ let i = [t];
444
+ for (let t of findIndirectCrlIssuers(e, n, r)) i.some((e) => sameCertificate(e, t)) || i.push(t);
445
+ return i;
391
446
  }
392
447
  function checkCrlWithIssuer(e, n, r, i, a) {
393
448
  return t({
@@ -403,7 +458,7 @@ function recordGoodCrlEvidence(e, t, n, r) {
403
458
  signer: t,
404
459
  thisUpdate: n
405
460
  });
406
- for (let t of r.issuingDistributionPoint?.onlySomeReasons?.flags ?? u) e.coveredReasons.add(t);
461
+ for (let t of r.issuingDistributionPoint?.onlySomeReasons?.flags ?? d) e.coveredReasons.add(t);
407
462
  }
408
463
  /**
409
464
  * Evaluates revocation status for a single certificate by combining OCSP and
@@ -498,6 +553,6 @@ async function checkChainRevocation(e) {
498
553
  };
499
554
  }
500
555
  //#endregion
501
- export { c as REVOCATION_INDETERMINATE_REASONS, checkChainRevocation };
556
+ export { l as REVOCATION_INDETERMINATE_REASONS, checkChainRevocation };
502
557
 
503
558
  //# sourceMappingURL=chain.js.map