micro509 0.18.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +88 -1
- package/dist/crypto/crypto.d.ts +11 -2
- package/dist/crypto/crypto.js +30 -17
- package/dist/crypto/crypto.js.map +1 -1
- package/dist/crypto.d.ts +2 -2
- package/dist/der/der.js.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/internal/asn1/asn1.js +10 -2
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/ber.js.map +1 -1
- package/dist/internal/asn1/decode-refusal.js.map +1 -1
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/ecdsa.js.map +1 -1
- package/dist/internal/crypto/hash.js.map +1 -1
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/prime-ec.js.map +1 -1
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +40 -0
- package/dist/internal/crypto/sig-verify.js +152 -65
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/crypto/signing.js.map +1 -1
- package/dist/internal/jose/base64url.js.map +1 -1
- package/dist/internal/jose/json-data.js.map +1 -1
- package/dist/internal/jose/strict-json.js.map +1 -1
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/idna.js.map +1 -1
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/shared/mailbox.js.map +1 -1
- package/dist/internal/shared/punycode.js.map +1 -1
- package/dist/internal/shared/uri-host.js.map +1 -1
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/verify/spki-distrust.js.map +1 -1
- package/dist/internal/verify/verify-path.js +222 -116
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/internal/x509/directory-name.js.map +1 -1
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.js.map +1 -1
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-profile.js.map +1 -1
- package/dist/internal/x509/general-name.js.map +1 -1
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/internal/x509/or-address.js.map +1 -1
- package/dist/jose/base64url.js.map +1 -1
- package/dist/jose/errors.js.map +1 -1
- package/dist/jose/jwe.js.map +1 -1
- package/dist/jose/jwks.js.map +1 -1
- package/dist/jose/jws.js.map +1 -1
- package/dist/jose/jwt.js.map +1 -1
- package/dist/jose/remote-jwks.js.map +1 -1
- package/dist/kdf/argon2-arithmetic.js.map +1 -1
- package/dist/kdf/argon2-core.js.map +1 -1
- package/dist/kdf/argon2-memory.js.map +1 -1
- package/dist/kdf/argon2-portable.js.map +1 -1
- package/dist/kdf/argon2.js.map +1 -1
- package/dist/keys/keys.js.map +1 -1
- package/dist/pem/pem.js.map +1 -1
- package/dist/pkcs/pfx.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.js +1 -1
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +10 -0
- package/dist/pkcs/pkcs7.js +106 -88
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/result/result.js.map +1 -1
- package/dist/revocation/chain.d.ts +67 -13
- package/dist/revocation/chain.js +429 -301
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +65 -11
- package/dist/revocation/crl.js +492 -202
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +79 -24
- package/dist/revocation/ocsp.js +417 -231
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +68 -13
- package/dist/revocation/revocation.js +194 -73
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +4 -4
- package/dist/ssh/ssh.js.map +1 -1
- package/dist/ssh/wire.js.map +1 -1
- package/dist/verify/identity.d.ts +2 -2
- package/dist/verify/identity.js +2 -2
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/verify.d.ts +84 -32
- package/dist/verify/verify.js +221 -171
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +3 -2
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.js.map +1 -1
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +6 -2
- package/dist/x509/parse.js +121 -121
- package/dist/x509/parse.js.map +1 -1
- package/package.json +11 -11
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verify-path.js","names":["_exhaustive","DEFAULT_MAX_PATH_BUILDING_CHECKS","limit","certificate","at","compareDistinguishedNames","total","cursor","index","chain","loaded","source","sources","first","verifySignedDataDetailed","issuer","result","verify","error","refusal","decodeRefusalOf","DECODE_LIMIT_CODES","DEFAULT_SIGNATURE_CHECKS","DIAGNOSTIC_TIER","candidateTier","candidate","incumbentTier","incumbent","suffix","diagnostic","nodeIndex","spent","prefix","path","shift","selectedAnchor","candidates","intermediates","roots","subjectIndex","order","rootFingerprints","anchorIndex","anchor","trustAnchors","key","canonicalDnKey","existing","best","leaf","deadEnds","subtrees","signatureResults","budget","maxIssuerChecks","rankedBuckets","maxDepth","startFingerprint","success","terminal","owner","callbacks","blockedHash","distrust","current","matchedAnchor","memoKey","caBelowCount","memoized","subtree","issuerPath","visited","sawIssuer","issuerFingerprint","bucket","aki","nextVisited","toHex","signatureChecks","anchorKey","pending","run","candidateFailure","issuerConstraints","signatureResult","verifySignature","nextCaBelowCount","pathLength","parseCertificatesFromSource","ordered","members","leftFp","left","rightFp","right","rootScore","bySubjectKeyIdentifier","ski","child","anchors","firstFailure","charge","verified","verifyAnchor","value","fingerprintCache","cached"],"sources":["../../../src/internal/verify/verify-path.ts"],"sourcesContent":["/**\n * Internal certificate path-building and signature-check helpers.\n *\n * Loads and parses candidate certificates, ranks issuer candidates by AKI/root\n * affinity, matches against bare {@linkcode TrustAnchor}s, and performs the\n * depth-first chain search used by the public verify APIs in `verify.ts`.\n *\n * @module\n */\n\nimport { toHex } from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, decodeRefusalOf } from '#micro509/internal/asn1/decode-refusal';\nimport type { VerifySignedDataResult } from '#micro509/internal/crypto/sig-verify';\nimport { verifySignedDataDetailed } from '#micro509/internal/crypto/sig-verify';\nimport { canonicalDnKey, compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport type {\n\tCertificateSource,\n\tTrustAnchor,\n\tVerifyChainFailure,\n\tVerifyErrorCode,\n\tVerifyFailureDetails,\n} from '#micro509/verify/verify';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificatesFromSource } from '#micro509/x509/parse';\n\n/** Outcome of verifying one certificate's signature against its issuer's key. */\nexport type VerifyCertificateSignatureResult =\n\t| { readonly ok: true; readonly valid: boolean }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly code:\n\t\t\t\t| 'signature_invalid'\n\t\t\t\t| 'unsupported_signature_algorithm_parameters'\n\t\t\t\t| 'limit_exceeded';\n\t\t\treadonly reason: string;\n\t };\n\n/** Result of the internal chain-building search. */\nexport interface InternalBuildResult {\n\t/** Deepest chain found (leaf-to-root order), may be partial if no root was reached. */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** `true` when the chain terminates at a trusted root or anchor. */\n\treadonly foundTrustedRoot: boolean;\n\t/**\n\t * `true` when the terminal certificate in `chain` is a trusted root cert (and\n\t * so is excluded from policy/name processing); `false` when a bare trust\n\t * anchor verified the terminal certificate, which then stays a path cert.\n\t */\n\treadonly anchorCertificateInChain?: boolean;\n\t/** Bare trust anchor that completed the path. */\n\treadonly trustAnchor?: TrustAnchor;\n\t/** Chain index where no issuer candidate existed, when the search dead-ended. */\n\treadonly missingIssuerAt?: number;\n\t/** Best failure encountered during the search, for diagnostic reporting. */\n\treadonly failure?: VerifyChainFailure;\n}\n\n/** Result of attempting to match a certificate against bare trust anchors. */\ninterface TrustAnchorMatchResult {\n\t/** `true` if a trust anchor verified the certificate's signature. */\n\treadonly matched: boolean;\n\t/** Selected bare trust anchor on success. */\n\treadonly anchor?: TrustAnchor;\n\t/** Failure to report when matching was attempted but signature verification failed. */\n\treadonly failure?: VerifyChainFailure;\n}\n\ntype IssuerCandidateEvaluation =\n\t| { readonly ok: true; readonly nextCaBelowCount: number }\n\t| { readonly ok: false; readonly failure: VerifyChainFailure };\n\n/**\n * The signature checks {@linkcode buildChainInternal} performs, injected per\n * call. A caller can wrap them to observe how much cryptographic work path\n * building costs; replacing a global would leak across concurrent searches.\n */\nexport interface VerifyPathSignatureChecks {\n\t/** Verifies a certificate against a candidate issuer certificate. */\n\treadonly certificate: (\n\t\tcertificate: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t) => Promise<VerifyCertificateSignatureResult>;\n\t/** Verifies a certificate against a bare trust anchor. */\n\treadonly trustAnchor: (\n\t\tcertificate: ParsedCertificate,\n\t\tanchor: TrustAnchor,\n\t) => Promise<VerifyCertificateSignatureResult>;\n}\n\n/** Default upper bound on issuer candidates and trust anchors one path search may try. */\nexport const DEFAULT_MAX_PATH_BUILDING_CHECKS = 100_000;\n\n/** Throws when a caller-supplied path-building limit is not a positive safe integer. */\nexport function assertPathBuildingChecks(limit: number | undefined): void {\n\tif (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) {\n\t\tthrow new RangeError(`Invalid maxPathBuildingChecks: must be an integer >= 1, got ${limit}`);\n\t}\n}\n\n/** Loose input for constructing failure detail objects during path building. */\nexport interface VerifyPathFailureDetailsInput {\n\t/** Common name of the certificate under evaluation, if known. */\n\treadonly subjectCommonName?: string | undefined;\n\t/** Common name of the expected issuer, if known. */\n\treadonly issuerCommonName?: string | undefined;\n\t/** Description of what the check expected. */\n\treadonly expected?: string | undefined;\n\t/** Description of what the check actually observed. */\n\treadonly actual?: string | undefined;\n\t/** Common names of every certificate in the candidate chain. */\n\treadonly chainCommonNames?: readonly string[] | undefined;\n}\n\n/** Callbacks injected by the caller to construct failure objects during path building. */\nexport interface VerifyPathCallbacks {\n\t/** Constructs a {@linkcode VerifyChainFailure} from a code, message, chain index, and details. */\n\treadonly failure: (\n\t\tcode: VerifyErrorCode,\n\t\tmessage: string,\n\t\tindex?: number,\n\t\tdetails?: VerifyFailureDetails,\n\t) => VerifyChainFailure;\n\t/** Constructs a {@linkcode VerifyFailureDetails} from loose inputs. */\n\treadonly detail: (input: VerifyPathFailureDetailsInput) => VerifyFailureDetails;\n}\n\n/** Returns `true` if `at` falls within the certificate's notBefore/notAfter window (inclusive). */\nexport function isWithinValidity(certificate: ParsedCertificate, at: Date): boolean {\n\treturn (\n\t\tcertificate.notBefore.getTime() <= at.getTime() &&\n\t\tat.getTime() <= certificate.notAfter.getTime()\n\t);\n}\n\n/** Returns `true` if the certificate's subject and issuer DNs are semantically equal (RFC 5280 §7.1). */\nexport function isSelfIssued(certificate: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(certificate.subject, certificate.issuer);\n}\n\n/** Counts non-self-issued CA certificates in positions 0..(index-1) for pathLength checking. */\nexport function countCaCertificatesBelowParsed(\n\tchain: readonly ParsedCertificate[],\n\tindex: number,\n): number {\n\tlet total = 0;\n\tfor (let cursor = 1; cursor < index; cursor += 1) {\n\t\tconst certificate = chain[cursor];\n\t\tif (certificate?.basicConstraints?.ca === true && !isSelfIssued(certificate)) {\n\t\t\ttotal += 1;\n\t\t}\n\t}\n\treturn total;\n}\n\n/** Parses an array of PEM/DER sources into parsed certificates, expanding multi-block PEM. */\nexport function loadCertificates(\n\tsources: readonly CertificateSource[],\n): readonly ParsedCertificate[] {\n\tconst loaded: ParsedCertificate[] = [];\n\tfor (const source of sources) {\n\t\tloaded.push(...expandSource(source));\n\t}\n\treturn loaded;\n}\n\n/** Parses exactly one certificate from a PEM/DER source. Throws if the source contains zero or multiple certificates. */\nexport function loadSingleCertificate(source: CertificateSource): ParsedCertificate {\n\tconst loaded = expandSource(source);\n\tconst first = loaded[0];\n\tif (first === undefined) {\n\t\tthrow new Error('No certificate found');\n\t}\n\tif (loaded.length !== 1) {\n\t\tthrow new Error('Expected a single certificate source');\n\t}\n\treturn first;\n}\n\n/** Verifies that `certificate` was signed by `issuer`'s public key. */\nexport function verifyCertificateSignature(\n\tcertificate: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): Promise<VerifyCertificateSignatureResult> {\n\treturn signatureCheck(() =>\n\t\tverifySignedDataDetailed(\n\t\t\tcertificate.signatureAlgorithmOid,\n\t\t\tcertificate.signatureAlgorithmParametersDer,\n\t\t\tissuer.publicKeyAlgorithmOid,\n\t\t\tissuer.publicKeyParametersOid,\n\t\t\tissuer.subjectPublicKeyInfoDer,\n\t\t\tcertificate.signatureValue,\n\t\t\tcertificate.tbsCertificateDer,\n\t\t),\n\t);\n}\n\n/** Runs `verify` as a path check, reporting a runtime failure as `signature_invalid` and a decoding limit as `limit_exceeded`. */\nasync function signatureCheck(\n\tverify: () => Promise<VerifySignedDataResult>,\n): Promise<VerifyCertificateSignatureResult> {\n\tlet result: VerifySignedDataResult;\n\ttry {\n\t\tresult = await verify();\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\tif (refusal === undefined) {\n\t\t\tthrow error;\n\t\t}\n\t\treturn { ok: false, code: refusal.code, reason: refusal.message };\n\t}\n\treturn !result.ok && result.code === 'verification_error'\n\t\t? { ok: false, code: 'signature_invalid', reason: result.reason }\n\t\t: result;\n}\n\n/** The real signature checks, used unless a caller injects its own. */\nconst DEFAULT_SIGNATURE_CHECKS: VerifyPathSignatureChecks = {\n\tcertificate: verifyCertificateSignature,\n\ttrustAnchor: verifyTrustAnchorSignature,\n};\n\nexport type PathDiagnostic =\n\t| { readonly kind: 'none'; readonly path: readonly ParsedCertificate[] }\n\t| { readonly kind: 'untrusted-anchor'; readonly path: readonly ParsedCertificate[] }\n\t| {\n\t\t\treadonly kind: 'missing-issuer';\n\t\t\treadonly path: readonly ParsedCertificate[];\n\t\t\treadonly missingIssuerAt: number;\n\t }\n\t| {\n\t\t\treadonly kind: 'specific-failure';\n\t\t\treadonly path: readonly ParsedCertificate[];\n\t\t\treadonly failure: VerifyChainFailure;\n\t };\n\nconst DIAGNOSTIC_TIER = {\n\t'specific-failure': 3,\n\t'untrusted-anchor': 2,\n\t'missing-issuer': 1,\n\tnone: 0,\n} as const satisfies Record<PathDiagnostic['kind'], number>;\n\nfunction isMoreSignificant(candidate: PathDiagnostic, incumbent: PathDiagnostic): boolean {\n\tconst candidateTier = DIAGNOSTIC_TIER[candidate.kind];\n\tconst incumbentTier = DIAGNOSTIC_TIER[incumbent.kind];\n\treturn candidateTier === incumbentTier\n\t\t? candidate.path.length > incumbent.path.length\n\t\t: candidateTier > incumbentTier;\n}\n\ninterface DeadEnd {\n\treadonly diagnostic: PathDiagnostic;\n\treadonly nodeIndex: number;\n}\n\n/**\n * Moves a diagnostic recorded below the certificate at `nodeIndex` onto a new\n * prefix ending at that same certificate. A suffix that repeats a certificate\n * of the new prefix cannot form a path, so only the prefix is reported.\n */\nexport function rebaseDiagnostic(\n\tdiagnostic: PathDiagnostic,\n\tnodeIndex: number,\n\tprefix: readonly ParsedCertificate[],\n): PathDiagnostic {\n\tconst suffix = diagnostic.path.slice(nodeIndex + 1);\n\tconst spent = new Set(prefix.map((certificate) => fingerprint(certificate)));\n\tif (suffix.some((certificate) => spent.has(fingerprint(certificate)))) {\n\t\treturn { kind: 'none', path: prefix };\n\t}\n\tconst path = [...prefix, ...suffix];\n\tconst shift = prefix.length - 1 - nodeIndex;\n\tswitch (diagnostic.kind) {\n\t\tcase 'none':\n\t\tcase 'untrusted-anchor':\n\t\t\treturn { kind: diagnostic.kind, path };\n\t\tcase 'missing-issuer':\n\t\t\treturn { kind: 'missing-issuer', path, missingIssuerAt: diagnostic.missingIssuerAt + shift };\n\t\tcase 'specific-failure':\n\t\t\treturn {\n\t\t\t\tkind: 'specific-failure',\n\t\t\t\tpath,\n\t\t\t\tfailure:\n\t\t\t\t\tdiagnostic.failure.index === undefined\n\t\t\t\t\t\t? diagnostic.failure\n\t\t\t\t\t\t: { ...diagnostic.failure, index: diagnostic.failure.index + shift },\n\t\t\t};\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = diagnostic;\n\t\t\tthrow new Error(`unreachable diagnostic ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Depth-first chain search from leaf to root. Tries all issuer candidates,\n * checking validity, CA constraints, AKI, pathLength, and signatures at each\n * step. Returns the first fully anchored path or the deepest partial path\n * with the best failure encountered.\n */\nexport async function buildChainInternal(\n\tleaf: ParsedCertificate,\n\tintermediates: readonly ParsedCertificate[],\n\troots: readonly ParsedCertificate[],\n\ttrustAnchors: readonly TrustAnchor[],\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n\tsignatureChecks: VerifyPathSignatureChecks = DEFAULT_SIGNATURE_CHECKS,\n\tmaxIssuerChecks: number = DEFAULT_MAX_PATH_BUILDING_CHECKS,\n\tdistrust: (spki: Uint8Array) => Promise<string | undefined> = () => Promise.resolve(undefined),\n): Promise<InternalBuildResult> {\n\tlet selectedAnchor: TrustAnchor | undefined;\n\tconst candidates = [...intermediates, ...roots];\n\tconst subjectIndex = new Map<string, ParsedCertificate[]>();\n\tconst order = new Map<string, number>();\n\tconst rootFingerprints = new Set(roots.map((candidate) => fingerprint(candidate)));\n\tconst anchorIndex = new Map<string, TrustAnchor[]>();\n\tfor (const anchor of trustAnchors) {\n\t\tconst key = canonicalDnKey(anchor.subject);\n\t\tconst existing = anchorIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tanchorIndex.set(key, [anchor]);\n\t\t} else {\n\t\t\texisting.push(anchor);\n\t\t}\n\t}\n\tconst best: { current: PathDiagnostic } = { current: { kind: 'none', path: [leaf] } };\n\tconst deadEnds = new Map<string, DeadEnd>();\n\tconst subtrees: { best: PathDiagnostic }[] = [];\n\tconst signatureResults = new Map<string, Promise<VerifyCertificateSignatureResult>>();\n\tconst budget = { remaining: maxIssuerChecks, exhausted: false };\n\tconst rankedBuckets = new Map<string, RankedBucket>();\n\n\tcandidates.forEach((candidate, index) => {\n\t\tconst key = canonicalDnKey(candidate.subject);\n\t\tconst existing = subjectIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tsubjectIndex.set(key, [candidate]);\n\t\t} else {\n\t\t\texisting.push(candidate);\n\t\t}\n\t\torder.set(fingerprint(candidate), index);\n\t});\n\n\tconst maxDepth = candidates.length + 1;\n\tconst startFingerprint = fingerprint(leaf);\n\tconst success = await search(leaf, [leaf], new Set([startFingerprint]), 0);\n\tif (success !== undefined) {\n\t\tconst terminal = success[success.length - 1];\n\t\treturn {\n\t\t\tchain: success,\n\t\t\tfoundTrustedRoot: true,\n\t\t\t...(selectedAnchor !== undefined && { trustAnchor: selectedAnchor }),\n\t\t\tanchorCertificateInChain:\n\t\t\t\tterminal !== undefined && rootFingerprints.has(fingerprint(terminal)),\n\t\t};\n\t}\n\tconst owner = best.current;\n\tif (budget.exhausted) {\n\t\treturn {\n\t\t\tchain: owner.path,\n\t\t\tfoundTrustedRoot: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'path_building_limit_exceeded',\n\t\t\t\t'path building stopped at its work limit',\n\t\t\t\tundefined,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\texpected: `at most ${maxIssuerChecks} issuer and trust-anchor checks`,\n\t\t\t\t\tactual: 'limit reached before a trusted path was found',\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tswitch (owner.kind) {\n\t\tcase 'specific-failure':\n\t\t\treturn { chain: owner.path, foundTrustedRoot: false, failure: owner.failure };\n\t\tcase 'missing-issuer':\n\t\t\treturn {\n\t\t\t\tchain: owner.path,\n\t\t\t\tfoundTrustedRoot: false,\n\t\t\t\tmissingIssuerAt: owner.missingIssuerAt,\n\t\t\t};\n\t\tcase 'untrusted-anchor':\n\t\tcase 'none':\n\t\t\treturn { chain: owner.path, foundTrustedRoot: false };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = owner;\n\t\t\tthrow new Error(`unreachable diagnostic ${String(_exhaustive)}`);\n\t\t}\n\t}\n\n\tasync function search(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tif (budget.exhausted) return undefined;\n\t\tconst blockedHash = await distrust(current.subjectPublicKeyInfoDer);\n\t\tif (blockedHash !== undefined) {\n\t\t\trecordFailure(\n\t\t\t\tcallbacks.failure(\n\t\t\t\t\t'public_key_distrusted',\n\t\t\t\t\t'certificate public key is explicitly distrusted',\n\t\t\t\t\tpath.length - 1,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\t\tactual: blockedHash,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\tpath,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\tif (rootFingerprints.has(fingerprint(current))) {\n\t\t\treturn path;\n\t\t}\n\t\tconst matchedAnchor = await matchTrustAnchor(\n\t\t\tcurrent,\n\t\t\tanchorIndex,\n\t\t\tcallbacks,\n\t\t\tpath.length - 1,\n\t\t\tverifyAnchorOnce,\n\t\t\tchargeBudget,\n\t\t\tdistrust,\n\t\t);\n\t\tif (budget.exhausted) return undefined;\n\t\tif (matchedAnchor.failure !== undefined) {\n\t\t\trecordFailure(matchedAnchor.failure, path);\n\t\t}\n\t\tif (matchedAnchor.matched) {\n\t\t\tselectedAnchor = matchedAnchor.anchor;\n\t\t\treturn path;\n\t\t}\n\t\tif (path.length > maxDepth) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst memoKey = `${fingerprint(current)}:${caBelowCount}`;\n\t\tconst memoized = deadEnds.get(memoKey);\n\t\tif (memoized !== undefined) {\n\t\t\tconsider(rebaseDiagnostic(memoized.diagnostic, memoized.nodeIndex, path));\n\t\t\treturn undefined;\n\t\t}\n\t\tconst subtree: { best: PathDiagnostic } = { best: { kind: 'none', path } };\n\t\tsubtrees.push(subtree);\n\t\ttry {\n\t\t\tconst issuerPath = await searchBelow(current, path, visited, caBelowCount);\n\t\t\tif (issuerPath !== undefined) return issuerPath;\n\t\t} finally {\n\t\t\tsubtrees.pop();\n\t\t}\n\t\tdeadEnds.set(memoKey, { diagnostic: subtree.best, nodeIndex: path.length - 1 });\n\t\treturn undefined;\n\t}\n\n\tasync function searchBelow(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tlet sawIssuer = false;\n\t\tfor (const issuer of issuerCandidates(current)) {\n\t\t\tif (!chargeBudget()) return undefined;\n\t\t\tif (!isIssuerOf(issuer, current)) continue;\n\t\t\tsawIssuer = true;\n\t\t\tconst issuerFingerprint = fingerprint(issuer);\n\t\t\tif (visited.has(issuerFingerprint)) continue;\n\t\t\tconst result = await searchIssuerCandidate(\n\t\t\t\tcurrent,\n\t\t\t\tissuer,\n\t\t\t\tissuerFingerprint,\n\t\t\t\tpath,\n\t\t\t\tvisited,\n\t\t\t\tcaBelowCount,\n\t\t\t);\n\t\t\tif (result !== undefined) return result;\n\t\t\tif (budget.exhausted) return undefined;\n\t\t}\n\t\tif (!sawIssuer) {\n\t\t\trecordMissingIssuers(current, path);\n\t\t\treturn undefined;\n\t\t}\n\t\tconsider({ kind: 'none', path });\n\t\treturn undefined;\n\t}\n\n\t/** Yields the issuer bucket for `current`: AKI matches first, then roots, then input order. */\n\tfunction* issuerCandidates(current: ParsedCertificate): Generator<ParsedCertificate> {\n\t\tconst key = canonicalDnKey(current.issuer);\n\t\tlet bucket = rankedBuckets.get(key);\n\t\tif (bucket === undefined) {\n\t\t\tbucket = rankBucket(subjectIndex.get(key) ?? [], order, rootFingerprints);\n\t\t\trankedBuckets.set(key, bucket);\n\t\t}\n\t\tconst aki = current.authorityKeyIdentifier;\n\t\tif (aki === undefined) {\n\t\t\tyield* bucket.ordered;\n\t\t\treturn;\n\t\t}\n\t\tyield* bucket.bySubjectKeyIdentifier.get(aki) ?? [];\n\t\tfor (const candidate of bucket.ordered) {\n\t\t\tif (candidate.subjectKeyIdentifier !== aki) yield candidate;\n\t\t}\n\t}\n\n\tfunction recordMissingIssuers(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t): void {\n\t\tif (isSelfIssued(current)) {\n\t\t\tconsider({ kind: 'untrusted-anchor', path });\n\t\t\treturn;\n\t\t}\n\t\tif (path.length > 1) {\n\t\t\tconsider({ kind: 'missing-issuer', path, missingIssuerAt: path.length - 1 });\n\t\t}\n\t}\n\n\tasync function searchIssuerCandidate(\n\t\tcurrent: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t\tissuerFingerprint: string,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tconst candidate = await evaluateIssuerCandidate(\n\t\t\tcurrent,\n\t\t\tissuer,\n\t\t\tpath,\n\t\t\tcaBelowCount,\n\t\t\tat,\n\t\t\tcallbacks,\n\t\t\tverifySignatureOnce,\n\t\t);\n\t\tif (!candidate.ok) {\n\t\t\trecordFailure(candidate.failure, path);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst nextVisited = new Set(visited);\n\t\tnextVisited.add(issuerFingerprint);\n\t\treturn await search(issuer, [...path, issuer], nextVisited, candidate.nextCaBelowCount);\n\t}\n\n\tfunction chargeBudget(): boolean {\n\t\tif (budget.remaining === 0) {\n\t\t\tbudget.exhausted = true;\n\t\t\treturn false;\n\t\t}\n\t\tbudget.remaining -= 1;\n\t\treturn true;\n\t}\n\n\tfunction verifySignatureOnce(\n\t\tcertificate: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t): Promise<VerifyCertificateSignatureResult> {\n\t\treturn verifyOnce(\n\t\t\t`c:${fingerprint(certificate)}:${toHex(issuer.subjectPublicKeyInfoDer)}`,\n\t\t\t() => signatureChecks.certificate(certificate, issuer),\n\t\t);\n\t}\n\n\tfunction verifyAnchorOnce(\n\t\tcertificate: ParsedCertificate,\n\t\tanchor: TrustAnchor,\n\t): Promise<VerifyCertificateSignatureResult> {\n\t\tconst anchorKey = `${anchor.publicKeyAlgorithmOid}:${anchor.publicKeyParametersOid ?? ''}:${toHex(\n\t\t\tanchor.subjectPublicKeyInfoDer,\n\t\t)}`;\n\t\treturn verifyOnce(`a:${fingerprint(certificate)}:${anchorKey}`, () =>\n\t\t\tsignatureChecks.trustAnchor(certificate, anchor),\n\t\t);\n\t}\n\n\t/** One signature check per distinct certificate-and-key pair for the whole search. */\n\tfunction verifyOnce(\n\t\tkey: string,\n\t\trun: () => Promise<VerifyCertificateSignatureResult>,\n\t): Promise<VerifyCertificateSignatureResult> {\n\t\tlet pending = signatureResults.get(key);\n\t\tif (pending === undefined) {\n\t\t\tpending = run();\n\t\t\tsignatureResults.set(key, pending);\n\t\t}\n\t\treturn pending;\n\t}\n\n\tfunction consider(candidate: PathDiagnostic): void {\n\t\tif (isMoreSignificant(candidate, best.current)) {\n\t\t\tbest.current = candidate;\n\t\t}\n\t\tfor (const subtree of subtrees) {\n\t\t\tif (isMoreSignificant(candidate, subtree.best)) {\n\t\t\t\tsubtree.best = candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction recordFailure(\n\t\tcandidateFailure: VerifyChainFailure,\n\t\tpath: readonly ParsedCertificate[],\n\t): void {\n\t\tconsider({ kind: 'specific-failure', path, failure: candidateFailure });\n\t}\n}\n\n/** Applies issuer constraints and signature verification to one path candidate. */\nasync function evaluateIssuerCandidate(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n\tverifySignature: typeof verifyCertificateSignature,\n): Promise<IssuerCandidateEvaluation> {\n\tconst issuerConstraints = evaluateIssuerConstraints(\n\t\tcurrent,\n\t\tissuer,\n\t\tpath,\n\t\tcaBelowCount,\n\t\tat,\n\t\tcallbacks,\n\t);\n\tif (!issuerConstraints.ok) {\n\t\treturn issuerConstraints;\n\t}\n\tconst signatureResult = await verifySignature(current, issuer);\n\tif (!signatureResult.ok) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\tsignatureResult.code,\n\t\t\t\tsignatureResult.reason,\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\tactual: signatureResult.reason,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tif (!signatureResult.valid) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'certificate signature does not verify',\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\treturn issuerConstraints;\n}\n\nfunction evaluateIssuerConstraints(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n): IssuerCandidateEvaluation {\n\tif (!isWithinValidity(issuer, at)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'certificate_expired',\n\t\t\t\t'certificate not valid at requested time',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: describeDateTime(at),\n\t\t\t\t\tactual: `${describeDateTime(issuer.notBefore)}..${describeDateTime(issuer.notAfter)}`,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tif (issuer.basicConstraints?.ca !== true) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'ca_required',\n\t\t\t\t'issuer must be a CA certificate',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({ subjectCommonName: issuer.subject.values.commonName }),\n\t\t\t),\n\t\t};\n\t}\n\treturn evaluateIssuerKeyConstraints(current, issuer, path, caBelowCount, callbacks);\n}\n\nfunction evaluateIssuerKeyConstraints(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tpath: readonly ParsedCertificate[],\n\tcaBelowCount: number,\n\tcallbacks: VerifyPathCallbacks,\n): IssuerCandidateEvaluation {\n\tif (issuer.keyUsage !== undefined && !issuer.keyUsage.flags.includes('keyCertSign')) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'key_cert_sign_required',\n\t\t\t\t'issuer missing keyCertSign',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({ subjectCommonName: issuer.subject.values.commonName }),\n\t\t\t),\n\t\t};\n\t}\n\tif (authorityKeyIdentifierMismatch(current, issuer)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'authority_key_identifier_mismatch',\n\t\t\t\t'authorityKeyIdentifier does not match issuer subjectKeyIdentifier',\n\t\t\t\tpath.length - 1,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: issuer.subjectKeyIdentifier,\n\t\t\t\t\tactual: current.authorityKeyIdentifier,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\tconst nextCaBelowCount =\n\t\tcaBelowCount +\n\t\t(current.basicConstraints?.ca === true && !isSelfIssued(current) && path.length > 1 ? 1 : 0);\n\tconst pathLength = issuer.basicConstraints?.pathLength;\n\tif (isNonNegativeInteger(pathLength) && nextCaBelowCount > pathLength) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfailure: callbacks.failure(\n\t\t\t\t'path_length_exceeded',\n\t\t\t\t'path length constraint exceeded',\n\t\t\t\tpath.length,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: issuer.subject.values.commonName,\n\t\t\t\t\texpected: String(pathLength),\n\t\t\t\t\tactual: String(nextCaBelowCount),\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\treturn { ok: true, nextCaBelowCount };\n}\n\nexport function authorityKeyIdentifierMismatch(\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): boolean {\n\treturn (\n\t\tcurrent.authorityKeyIdentifier !== undefined &&\n\t\tissuer.subjectKeyIdentifier !== undefined &&\n\t\tcurrent.authorityKeyIdentifier !== issuer.subjectKeyIdentifier\n\t);\n}\n\n/** Expands a PEM (possibly multi-block) or DER source into parsed certificates. */\nfunction expandSource(source: CertificateSource): readonly ParsedCertificate[] {\n\treturn parseCertificatesFromSource(source);\n}\n\ninterface RankedBucket {\n\treadonly ordered: readonly ParsedCertificate[];\n\treadonly bySubjectKeyIdentifier: ReadonlyMap<string, readonly ParsedCertificate[]>;\n}\n\n/** Orders one subject bucket once, roots first and then input order, and indexes it by SKI. */\nfunction rankBucket(\n\tmembers: readonly ParsedCertificate[],\n\torder: ReadonlyMap<string, number>,\n\trootFingerprints: ReadonlySet<string>,\n): RankedBucket {\n\tconst ordered = [...members].sort((left, right) => {\n\t\tconst leftFp = fingerprint(left);\n\t\tconst rightFp = fingerprint(right);\n\t\tconst rootScore = compareBooleans(rootFingerprints.has(leftFp), rootFingerprints.has(rightFp));\n\t\tif (rootScore !== 0) {\n\t\t\treturn rootScore;\n\t\t}\n\t\treturn (\n\t\t\t(order.get(leftFp) ?? Number.MAX_SAFE_INTEGER) -\n\t\t\t(order.get(rightFp) ?? Number.MAX_SAFE_INTEGER)\n\t\t);\n\t});\n\tconst bySubjectKeyIdentifier = new Map<string, ParsedCertificate[]>();\n\tfor (const candidate of ordered) {\n\t\tconst ski = candidate.subjectKeyIdentifier;\n\t\tif (ski === undefined) continue;\n\t\tconst existing = bySubjectKeyIdentifier.get(ski);\n\t\tif (existing === undefined) {\n\t\t\tbySubjectKeyIdentifier.set(ski, [candidate]);\n\t\t} else {\n\t\t\texisting.push(candidate);\n\t\t}\n\t}\n\treturn { ordered, bySubjectKeyIdentifier };\n}\n\n/** Sort comparator: `true` sorts before `false`. Returns -1, 0, or 1. */\nfunction compareBooleans(left: boolean, right: boolean): number {\n\tif (left === right) {\n\t\treturn 0;\n\t}\n\treturn left ? -1 : 1;\n}\n\n/** Returns `true` if `issuer`'s subject DN semantically matches `child`'s issuer DN (RFC 5280 §7.1). */\nfunction isIssuerOf(issuer: ParsedCertificate, child: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(child.issuer, issuer.subject);\n}\n\n/** Attempts to verify `certificate` against each bare trust anchor whose subject DN matches. */\nasync function matchTrustAnchor(\n\tcertificate: ParsedCertificate,\n\tanchorIndex: ReadonlyMap<string, readonly TrustAnchor[]>,\n\tcallbacks: VerifyPathCallbacks,\n\tindex: number,\n\tverifyAnchor: typeof verifyTrustAnchorSignature,\n\tcharge: () => boolean,\n\tdistrust: (spki: Uint8Array) => Promise<string | undefined>,\n): Promise<TrustAnchorMatchResult> {\n\tconst anchors = anchorIndex.get(canonicalDnKey(certificate.issuer));\n\tif (anchors === undefined) {\n\t\treturn { matched: false };\n\t}\n\tlet firstFailure: VerifyChainFailure | undefined;\n\tfor (const anchor of anchors) {\n\t\tif (!charge()) return { matched: false };\n\t\tif (trustAnchorAkiMismatch(certificate, anchor)) continue;\n\t\t// The canonicalDnKey bucket is not proof of DN equality (prohibited values\n\t\t// are non-reflexive and prepared/tagged namespaces can collide), so confirm\n\t\t// the anchor's subject actually equals the certificate's issuer.\n\t\tif (!compareDistinguishedNames(certificate.issuer, anchor.subject)) continue;\n\t\tconst blockedHash = await distrust(anchor.subjectPublicKeyInfoDer);\n\t\tif (blockedHash !== undefined) {\n\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t'public_key_distrusted',\n\t\t\t\t'bare trust anchor public key is explicitly distrusted',\n\t\t\t\tundefined,\n\t\t\t\tcallbacks.detail({ actual: blockedHash }),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst verified = await verifyAnchor(certificate, anchor);\n\t\tif (!verified.ok) {\n\t\t\t// Capture the first failure but continue trying other anchors\n\t\t\tfirstFailure ??= callbacks.failure(\n\t\t\t\tverified.code,\n\t\t\t\tverified.reason,\n\t\t\t\tindex,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\tactual: verified.reason,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!verified.valid) {\n\t\t\tif (firstFailure === undefined) {\n\t\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate signature does not verify',\n\t\t\t\t\tindex,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: 'certificate signature does not verify',\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\treturn { matched: true, anchor };\n\t}\n\treturn firstFailure !== undefined\n\t\t? { matched: false, failure: firstFailure }\n\t\t: { matched: false };\n}\n\nfunction trustAnchorAkiMismatch(certificate: ParsedCertificate, anchor: TrustAnchor): boolean {\n\treturn (\n\t\tanchor.subjectKeyIdentifier !== undefined &&\n\t\tcertificate.authorityKeyIdentifier !== undefined &&\n\t\tanchor.subjectKeyIdentifier !== certificate.authorityKeyIdentifier\n\t);\n}\n\n/** Verifies that `certificate` was signed by a bare trust anchor's key. */\nexport function verifyTrustAnchorSignature(\n\tcertificate: ParsedCertificate,\n\tanchor: TrustAnchor,\n): Promise<VerifyCertificateSignatureResult> {\n\treturn signatureCheck(() =>\n\t\tverifySignedDataDetailed(\n\t\t\tcertificate.signatureAlgorithmOid,\n\t\t\tcertificate.signatureAlgorithmParametersDer,\n\t\t\tanchor.publicKeyAlgorithmOid,\n\t\t\tanchor.publicKeyParametersOid,\n\t\t\tanchor.subjectPublicKeyInfoDer,\n\t\t\tcertificate.signatureValue,\n\t\t\tcertificate.tbsCertificateDer,\n\t\t),\n\t);\n}\n\nfunction describeDateTime(value: Date): string {\n\treturn Number.isNaN(value.getTime()) ? '<invalid date>' : value.toISOString();\n}\n\nfunction isNonNegativeInteger(value: number | undefined): value is number {\n\treturn value !== undefined && Number.isInteger(value) && value >= 0;\n}\n\n/** Cache for computed fingerprints to avoid repeated toHex() calls. */\nconst fingerprintCache = new WeakMap<ParsedCertificate, string>();\n\n/** Returns a hex fingerprint of the certificate's raw DER, used for cycle detection and dedup. */\nfunction fingerprint(certificate: ParsedCertificate): string {\n\tlet cached = fingerprintCache.get(certificate);\n\tif (cached === undefined) {\n\t\tcached = toHex(certificate.der);\n\t\tfingerprintCache.set(certificate, cached);\n\t}\n\treturn cached;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA0FA,MAAaC,IAAmC;;AAGhD,SAAgB,yBAAyB,GAAiC;CACzE,IAAIC,MAAU,KAAA,MAAc,CAAC,OAAO,cAAcA,CAAK,KAAKA,IAAQ,IACnE,MAAU,WAAW,+DAA+DA,GAAO;AAE7F;;AA8BA,SAAgB,iBAAiB,GAAgC,GAAmB;CACnF,OACCC,EAA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7F,OACCzD,EAAO,yBAAyB,KAAA,KAChCxC,EAAY,2BAA2B,KAAA,KACvCwC,EAAO,yBAAyBxC,EAAY;AAE9C;;AAGA,SAAgB,2BACf,GACA,GAC4C;CAC5C,OAAO,qBACNW,EACCX,EAAY,uBACZA,EAAY,iCACZwC,EAAO,uBACPA,EAAO,wBACPA,EAAO,yBACPxC,EAAY,gBACZA,EAAY,iBACb,CACD;AACD;AAEA,SAAS,iBAAiB,GAAqB;CAC9C,OAAO,OAAO,MAAMqG,EAAM,QAAQ,CAAC,IAAI,mBAAmBA,EAAM,YAAY;AAC7E;AAEA,SAAS,qBAAqB,GAA4C;CACzE,OAAOA,MAAU,KAAA,KAAa,OAAO,UAAUA,CAAK,KAAKA,KAAS;AACnE;;AAGA,MAAMC,oBAAmB,IAAI,QAAmC;;AAGhE,SAAS,YAAY,GAAwC;CAC5D,IAAIC,IAASD,EAAiB,IAAItG,CAAW;CAK7C,OAJIuG,MAAW,KAAA,MACd,IAAS7B,EAAM1E,EAAY,GAAG,GAC9BsG,EAAiB,IAAItG,GAAauG,CAAM,IAElCA;AACR"}
|
|
1
|
+
{"version":3,"file":"verify-path.js","names":["_exhaustive","toHex","DECODE_LIMIT_CODES","decodeRefusalOf","readSequenceChildren","sequence","NO_CALLER_VERIFICATION","explicitParameters","spkiAlgorithmParametersDer","verifySignedDataDetailed","canonicalDnKey","compareDistinguishedNames","parseCertificatesFromSource","DEFAULT_MAX_PATH_BUILDING_CHECKS","limit","certificate","at","chain","index","total","cursor","sources","loaded","source","first","issuer","verification","verify","result","error","refusal","DEFAULT_SIGNATURE_CHECKS","verifiers","workingParameters","anchor","key","byte","parametersDer","spki","algorithm","subjectPublicKey","algorithmDer","oid","path","top","issuerIndex","firstProcessed","start","algorithmOid","own","DIAGNOSTIC_TIER","candidate","incumbent","candidateTier","incumbentTier","diagnostic","nodeIndex","prefix","suffix","spent","shift","leaf","intermediates","roots","trustAnchors","callbacks","signatureChecks","maxIssuerChecks","distrust","selectedAnchor","candidates","subjectIndex","order","rootFingerprints","anchorIndex","existing","best","deadEnds","subtrees","signatureResults","budget","rankedBuckets","startFingerprint","success","owner","current","visited","caBelowCount","pending","blockedHash","terminal","matchedAnchor","memoKey","memoized","subtree","issuerPath","signatureFailure","sawIssuer","issuerFingerprint","bucket","aki","inherits","nextVisited","anchorKey","run","candidateFailure","verifySignature","issuerConstraints","signatureResult","nextCaBelowCount","pathLength","members","ordered","left","right","leftFp","rightFp","rootScore","bySubjectKeyIdentifier","ski","child","verifyAnchor","charge","completesPath","anchors","firstFailure","verified","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 { readSequenceChildren, sequence } from '#micro509/internal/asn1/der';\nimport type {\n\tCallerVerification,\n\tSignatureVerifier,\n\tVerifySignedDataResult,\n} from '#micro509/internal/crypto/sig-verify';\nimport {\n\texplicitParameters,\n\tNO_CALLER_VERIFICATION,\n\tspkiAlgorithmParametersDer,\n\tverifySignedDataDetailed,\n} from '#micro509/internal/crypto/sig-verify';\nimport { canonicalDnKey, compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport type {\n\tCandidatePath,\n\tCertificateSource,\n\tTrustAnchor,\n\tVerifyChainFailure,\n\tVerifyErrorCode,\n\tVerifyFailureDetails,\n} from '#micro509/verify/verify';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificatesFromSource } from '#micro509/x509/parse';\n\n/** Outcome of verifying one certificate's signature against its issuer's key. */\nexport type VerifyCertificateSignatureResult =\n\t| { readonly ok: true; readonly valid: boolean }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly code:\n\t\t\t\t| 'signature_invalid'\n\t\t\t\t| 'unsupported_signature_algorithm_parameters'\n\t\t\t\t| 'limit_exceeded';\n\t\t\treadonly reason: string;\n\t };\n\n/** Result of the internal chain-building search. */\nexport interface InternalBuildResult {\n\t/** Deepest chain found (leaf-to-root order), may be partial if no root was reached. */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** `true` when the chain terminates at a trusted root or anchor. */\n\treadonly foundTrustedRoot: boolean;\n\t/**\n\t * `true` when the terminal certificate in `chain` is a trusted root cert (and\n\t * so is excluded from policy/name processing); `false` when a bare trust\n\t * anchor verified the terminal certificate, which then stays a path cert.\n\t */\n\treadonly anchorCertificateInChain?: boolean;\n\t/** Bare trust anchor that completed the path. */\n\treadonly trustAnchor?: TrustAnchor;\n\t/** Chain index where no issuer candidate existed, when the search dead-ended. */\n\treadonly missingIssuerAt?: number;\n\t/** Best failure encountered during the search, for diagnostic reporting. */\n\treadonly failure?: VerifyChainFailure;\n}\n\n/**\n * Result of attempting to match a certificate against bare trust anchors: the\n * anchor that verified its signature, or the failure to report when matching\n * was attempted and no anchor verified it.\n */\ntype TrustAnchorMatchResult =\n\t| { readonly matched: true; readonly anchor: TrustAnchor }\n\t| { readonly matched: false; readonly failure?: VerifyChainFailure };\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/**\n\t * Verifies a certificate against a candidate issuer certificate.\n\t * `workingParameters` replaces the issuer's own key parameters for a\n\t * caller verifier.\n\t */\n\treadonly certificate: (\n\t\tcertificate: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t\tworkingParameters?: WorkingParameters,\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\t/**\n\t * Whether a caller verifier checks `certificate` under an `issuer` key whose\n\t * parameters are absent or NULL, so they come from the path above `issuer`.\n\t */\n\treadonly inheritsParameters: (\n\t\tcertificate: ParsedCertificate,\n\t\tissuer: ParsedCertificate,\n\t) => boolean;\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\tverification: CallerVerification = NO_CALLER_VERIFICATION,\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.signatureValueUnusedBits,\n\t\t\tcertificate.tbsCertificateDer,\n\t\t\tverification,\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 = signatureChecksWith(new Map());\n\n/** The real signature checks, falling back to caller verifiers for algorithms WebCrypto cannot run. */\nexport function signatureChecksWith(\n\tverifiers: ReadonlyMap<string, SignatureVerifier>,\n): VerifyPathSignatureChecks {\n\treturn {\n\t\tcertificate: (certificate, issuer, workingParameters) =>\n\t\t\tverifyCertificateSignature(certificate, issuer, {\n\t\t\t\tverifiers,\n\t\t\t\t...(workingParameters !== undefined && { workingParameters }),\n\t\t\t}),\n\t\ttrustAnchor: (certificate, anchor) =>\n\t\t\tverifyTrustAnchorSignature(certificate, anchor, { verifiers }),\n\t\tinheritsParameters: (certificate, issuer) =>\n\t\t\tverifiers.has(certificate.signatureAlgorithmOid) &&\n\t\t\texplicitParameters(issuer.publicKeyAlgorithmParametersDer) === undefined,\n\t};\n}\n\n/** RFC 5280 §6.1 `working_public_key_parameters`, absent once the path leaves none. */\nexport type WorkingParameters = NonNullable<CallerVerification['workingParameters']>;\n\n/** RFC 5280 §6.1 `working_public_key_algorithm` and `working_public_key_parameters`. */\nexport interface WorkingPublicKey {\n\t/** Dotted-decimal public key algorithm OID. */\n\treadonly algorithmOid: string;\n\t/** DER key parameters, absent once the path leaves none. */\n\treadonly parametersDer: Uint8Array | undefined;\n}\n\n/** The working key a trust anchor initializes (RFC 5280 §6.1.2 (g)-(i)). */\nexport function anchorWorkingKey(anchor: {\n\treadonly publicKeyAlgorithmOid: string;\n\treadonly subjectPublicKeyInfoDer: Uint8Array;\n}): WorkingPublicKey {\n\treturn {\n\t\talgorithmOid: anchor.publicKeyAlgorithmOid,\n\t\tparametersDer: explicitParameters(spkiAlgorithmParametersDer(anchor.subjectPublicKeyInfoDer)),\n\t};\n}\n\n/** Whether `certificate` carries `anchor`'s name and public key: the anchor's own certificate. */\nexport function carriesTrustAnchorKey(\n\tcertificate: ParsedCertificate,\n\tanchor: TrustAnchor,\n): boolean {\n\tconst key = anchor.subjectPublicKeyInfoDer;\n\treturn (\n\t\tcompareDistinguishedNames(certificate.subject, anchor.subject) &&\n\t\tcertificate.subjectPublicKeyInfoDer.length === key.length &&\n\t\tcertificate.subjectPublicKeyInfoDer.every((byte, index) => byte === key[index])\n\t);\n}\n\n/**\n * `anchor` with `parametersDer` in its SubjectPublicKeyInfo: the trust anchor\n * information of RFC 5280 §6.1.1 (d) for a key whose path supplies its\n * parameters (§6.1.4 (e)).\n */\nexport function withWorkingParameters(anchor: TrustAnchor, parametersDer: Uint8Array): TrustAnchor {\n\tconst spki = anchor.subjectPublicKeyInfoDer;\n\tconst [algorithm, subjectPublicKey] = readSequenceChildren(spki);\n\tif (algorithm === undefined || subjectPublicKey === undefined) {\n\t\tthrow new Error('SubjectPublicKeyInfo lacks its algorithm or key');\n\t}\n\tconst algorithmDer = spki.subarray(algorithm.start - algorithm.headerLength, algorithm.end);\n\tconst [oid] = readSequenceChildren(algorithmDer);\n\tif (oid === undefined) throw new Error('AlgorithmIdentifier lacks its OID');\n\treturn {\n\t\t...anchor,\n\t\tsubjectPublicKeyInfoDer: sequence([\n\t\t\tsequence([algorithmDer.subarray(oid.start - oid.headerLength, oid.end), parametersDer]),\n\t\t\tspki.subarray(subjectPublicKey.start - subjectPublicKey.headerLength, subjectPublicKey.end),\n\t\t]),\n\t};\n}\n\n/**\n * The working key of `path.chain[index]` along a validated path: its own key\n * parameters, or those it inherits from the root or bare anchor above it.\n */\nexport function pathWorkingKey(path: CandidatePath, index: number): WorkingPublicKey {\n\tconst certificate = path.chain[index];\n\tconst top = path.chain[path.chain.length - 1];\n\tif (certificate === undefined || top === undefined) {\n\t\tthrow new Error(`no certificate at path index ${index}`);\n\t}\n\treturn {\n\t\talgorithmOid: certificate.publicKeyAlgorithmOid,\n\t\tparametersDer: path.anchorCertificateInChain\n\t\t\t? workingParametersAt(path.chain, index, path.chain.length - 2, certificateWorkingKey(top))\n\t\t\t: workingParametersAt(\n\t\t\t\t\tpath.chain,\n\t\t\t\t\tindex,\n\t\t\t\t\tpath.chain.length - 1,\n\t\t\t\t\tanchorWorkingKey(path.trustAnchor),\n\t\t\t\t),\n\t};\n}\n\n/** The working key a certificate used as trust anchor initializes. */\nexport function certificateWorkingKey(certificate: ParsedCertificate): WorkingPublicKey {\n\treturn {\n\t\talgorithmOid: certificate.publicKeyAlgorithmOid,\n\t\tparametersDer: explicitParameters(certificate.publicKeyAlgorithmParametersDer),\n\t};\n}\n\n/**\n * RFC 5280 §6.1.4 (e)-(f): the working parameters after processing `path` from\n * index `firstProcessed` down to `issuerIndex`, starting from `start`. A\n * certificate with its own parameters sets them. One without keeps the working\n * parameters when its algorithm matches and clears them when it differs.\n */\nexport function workingParametersAt(\n\tpath: readonly ParsedCertificate[],\n\tissuerIndex: number,\n\tfirstProcessed: number,\n\tstart: WorkingPublicKey,\n): Uint8Array | undefined {\n\tlet { algorithmOid, parametersDer } = start;\n\tfor (let index = firstProcessed; index >= issuerIndex; index -= 1) {\n\t\tconst certificate = path[index];\n\t\tif (certificate === undefined) return undefined;\n\t\tconst own = explicitParameters(certificate.publicKeyAlgorithmParametersDer);\n\t\tif (own !== undefined) {\n\t\t\tparametersDer = own;\n\t\t} else if (certificate.publicKeyAlgorithmOid !== algorithmOid) {\n\t\t\tparametersDer = undefined;\n\t\t}\n\t\talgorithmOid = certificate.publicKeyAlgorithmOid;\n\t}\n\treturn parametersDer;\n}\n\nexport type PathDiagnostic =\n\t| { readonly kind: 'none'; readonly path: readonly ParsedCertificate[] }\n\t| { readonly kind: 'untrusted-anchor'; readonly path: readonly ParsedCertificate[] }\n\t| {\n\t\t\treadonly kind: 'missing-issuer';\n\t\t\treadonly path: readonly ParsedCertificate[];\n\t\t\treadonly missingIssuerAt: number;\n\t }\n\t| {\n\t\t\treadonly kind: 'specific-failure';\n\t\t\treadonly path: readonly ParsedCertificate[];\n\t\t\treadonly failure: VerifyChainFailure;\n\t };\n\nconst DIAGNOSTIC_TIER = {\n\t'specific-failure': 3,\n\t'untrusted-anchor': 2,\n\t'missing-issuer': 1,\n\tnone: 0,\n} as const satisfies Record<PathDiagnostic['kind'], number>;\n\nfunction isMoreSignificant(candidate: PathDiagnostic, incumbent: PathDiagnostic): boolean {\n\tconst candidateTier = DIAGNOSTIC_TIER[candidate.kind];\n\tconst incumbentTier = DIAGNOSTIC_TIER[incumbent.kind];\n\treturn candidateTier === incumbentTier\n\t\t? candidate.path.length > incumbent.path.length\n\t\t: candidateTier > incumbentTier;\n}\n\ninterface DeadEnd {\n\treadonly diagnostic: PathDiagnostic;\n\treadonly nodeIndex: number;\n}\n\n/**\n * Moves a diagnostic recorded below the certificate at `nodeIndex` onto a new\n * prefix ending at that same certificate. A suffix that repeats a certificate\n * of the new prefix cannot form a path, so only the prefix is reported.\n */\nexport function rebaseDiagnostic(\n\tdiagnostic: PathDiagnostic,\n\tnodeIndex: number,\n\tprefix: readonly ParsedCertificate[],\n): PathDiagnostic {\n\tconst suffix = diagnostic.path.slice(nodeIndex + 1);\n\tconst spent = new Set(prefix.map((certificate) => fingerprint(certificate)));\n\tif (suffix.some((certificate) => spent.has(fingerprint(certificate)))) {\n\t\treturn { kind: 'none', path: prefix };\n\t}\n\tconst path = [...prefix, ...suffix];\n\tconst shift = prefix.length - 1 - nodeIndex;\n\tswitch (diagnostic.kind) {\n\t\tcase 'none':\n\t\tcase 'untrusted-anchor':\n\t\t\treturn { kind: diagnostic.kind, path };\n\t\tcase 'missing-issuer':\n\t\t\treturn { kind: 'missing-issuer', path, missingIssuerAt: diagnostic.missingIssuerAt + shift };\n\t\tcase 'specific-failure':\n\t\t\treturn {\n\t\t\t\tkind: 'specific-failure',\n\t\t\t\tpath,\n\t\t\t\tfailure:\n\t\t\t\t\tdiagnostic.failure.index === undefined\n\t\t\t\t\t\t? diagnostic.failure\n\t\t\t\t\t\t: { ...diagnostic.failure, index: diagnostic.failure.index + shift },\n\t\t\t};\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = diagnostic;\n\t\t\tthrow new Error(`unreachable diagnostic ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Depth-first chain search from leaf to root. Tries all issuer candidates,\n * checking validity, CA constraints, AKI, pathLength, and signatures at each\n * step. Returns the first fully anchored path or the deepest partial path\n * with the best failure encountered.\n */\nexport async function buildChainInternal(\n\tleaf: ParsedCertificate,\n\tintermediates: readonly ParsedCertificate[],\n\troots: readonly ParsedCertificate[],\n\ttrustAnchors: readonly TrustAnchor[],\n\tat: Date,\n\tcallbacks: VerifyPathCallbacks,\n\tsignatureChecks: VerifyPathSignatureChecks = DEFAULT_SIGNATURE_CHECKS,\n\tmaxIssuerChecks: number = DEFAULT_MAX_PATH_BUILDING_CHECKS,\n\tdistrust: (spki: Uint8Array) => Promise<string | undefined> = () => Promise.resolve(undefined),\n): Promise<InternalBuildResult> {\n\tlet selectedAnchor: TrustAnchor | undefined;\n\tconst candidates = [...intermediates, ...roots];\n\tconst subjectIndex = new Map<string, ParsedCertificate[]>();\n\tconst order = new Map<string, number>();\n\tconst rootFingerprints = new Set(roots.map((candidate) => fingerprint(candidate)));\n\tconst anchorIndex = new Map<string, TrustAnchor[]>();\n\tfor (const anchor of trustAnchors) {\n\t\tconst key = canonicalDnKey(anchor.subject);\n\t\tconst existing = anchorIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tanchorIndex.set(key, [anchor]);\n\t\t} else {\n\t\t\texisting.push(anchor);\n\t\t}\n\t}\n\tconst best: { current: PathDiagnostic } = { current: { kind: 'none', path: [leaf] } };\n\tconst deadEnds = new Map<string, DeadEnd>();\n\tconst subtrees: { best: PathDiagnostic }[] = [];\n\tconst signatureResults = new Map<string, Promise<VerifyCertificateSignatureResult>>();\n\tconst budget = { remaining: maxIssuerChecks, exhausted: false };\n\tconst rankedBuckets = new Map<string, RankedBucket>();\n\n\tcandidates.forEach((candidate, index) => {\n\t\tconst key = canonicalDnKey(candidate.subject);\n\t\tconst existing = subjectIndex.get(key);\n\t\tif (existing === undefined) {\n\t\t\tsubjectIndex.set(key, [candidate]);\n\t\t} else {\n\t\t\texisting.push(candidate);\n\t\t}\n\t\torder.set(fingerprint(candidate), index);\n\t});\n\n\tconst startFingerprint = fingerprint(leaf);\n\tconst success = await search(leaf, [leaf], new Set([startFingerprint]), 0, []);\n\tif (success !== undefined) {\n\t\treturn {\n\t\t\tchain: success,\n\t\t\tfoundTrustedRoot: true,\n\t\t\t...(selectedAnchor === undefined\n\t\t\t\t? { anchorCertificateInChain: true }\n\t\t\t\t: { anchorCertificateInChain: false, trustAnchor: selectedAnchor }),\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\tpending: readonly number[],\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tif (budget.exhausted) return undefined;\n\t\tconst blockedHash = await distrust(current.subjectPublicKeyInfoDer);\n\t\tif (blockedHash !== undefined) {\n\t\t\trecordFailure(\n\t\t\t\tcallbacks.failure(\n\t\t\t\t\t'public_key_distrusted',\n\t\t\t\t\t'certificate public key is explicitly distrusted',\n\t\t\t\t\tpath.length - 1,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\t\t\tactual: blockedHash,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\tpath,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst terminal = await terminateAtAnchor(current, path, pending);\n\t\tif (terminal !== 'open') return terminal;\n\t\treturn await searchIssuers(current, path, visited, caBelowCount, pending);\n\t}\n\n\t/** Ends the path at a root or a bare trust anchor, or reports `'open'` to keep searching. */\n\tasync function terminateAtAnchor(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tpending: readonly number[],\n\t): Promise<readonly ParsedCertificate[] | undefined | 'open'> {\n\t\tif (\n\t\t\trootFingerprints.has(fingerprint(current)) &&\n\t\t\t(await verifyInheritedLinks(path, pending, certificateWorkingKey(current), path.length - 2))\n\t\t) {\n\t\t\treturn path;\n\t\t}\n\t\tconst matchedAnchor = await matchTrustAnchor(current, anchorIndex, callbacks, path.length - 1, {\n\t\t\tverifyAnchor: verifyAnchorOnce,\n\t\t\tcharge: chargeBudget,\n\t\t\tdistrust,\n\t\t\tcompletesPath: (anchor) =>\n\t\t\t\tverifyInheritedLinks(path, pending, anchorWorkingKey(anchor), path.length - 1),\n\t\t});\n\t\tif (budget.exhausted) return undefined;\n\t\tif (!matchedAnchor.matched) {\n\t\t\tif (matchedAnchor.failure !== undefined) recordFailure(matchedAnchor.failure, path);\n\t\t\treturn 'open';\n\t\t}\n\t\tselectedAnchor = matchedAnchor.anchor;\n\t\treturn path;\n\t}\n\n\t/**\n\t * Searches the issuers of `current`. A subtree that carries deferred links\n\t * depends on the path below it, so it skips the dead-end memo.\n\t */\n\tasync function searchIssuers(\n\t\tcurrent: ParsedCertificate,\n\t\tpath: readonly ParsedCertificate[],\n\t\tvisited: ReadonlySet<string>,\n\t\tcaBelowCount: number,\n\t\tpending: readonly number[],\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tconst memoKey = pending.length === 0 ? `${fingerprint(current)}:${caBelowCount}` : undefined;\n\t\tconst memoized = memoKey === undefined ? undefined : 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, pending);\n\t\t\tif (issuerPath !== undefined) return issuerPath;\n\t\t} finally {\n\t\t\tsubtrees.pop();\n\t\t}\n\t\tif (memoKey !== undefined) {\n\t\t\tdeadEnds.set(memoKey, { diagnostic: subtree.best, nodeIndex: path.length - 1 });\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Verifies the deferred links of a completed path once its trust anchor fixes\n\t * the working key. `pending` holds the index of each certificate whose issuer\n\t * key inherits its parameters.\n\t */\n\tasync function verifyInheritedLinks(\n\t\tpath: readonly ParsedCertificate[],\n\t\tpending: readonly number[],\n\t\tstart: WorkingPublicKey,\n\t\tfirstProcessed: number,\n\t): Promise<boolean> {\n\t\tfor (const index of pending) {\n\t\t\tconst certificate = path[index];\n\t\t\tconst issuer = path[index + 1];\n\t\t\tif (certificate === undefined || issuer === undefined) return false;\n\t\t\tconst parametersDer = workingParametersAt(path, index + 1, firstProcessed, start);\n\t\t\tconst result = await verifyOnce(\n\t\t\t\t`c:${fingerprint(certificate)}:${toHex(issuer.subjectPublicKeyInfoDer)}:${\n\t\t\t\t\tparametersDer === undefined ? '-' : toHex(parametersDer)\n\t\t\t\t}`,\n\t\t\t\t() => signatureChecks.certificate(certificate, issuer, { parametersDer }),\n\t\t\t);\n\t\t\tconst signatureFailure = signatureResultFailure(\n\t\t\t\tresult,\n\t\t\t\tcertificate,\n\t\t\t\tissuer,\n\t\t\t\tindex,\n\t\t\t\tcallbacks,\n\t\t\t);\n\t\t\tif (signatureFailure !== undefined) {\n\t\t\t\trecordFailure(signatureFailure, path);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\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\tpending: readonly 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\tpending,\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\tpending: readonly number[],\n\t): Promise<readonly ParsedCertificate[] | undefined> {\n\t\tconst inherits = signatureChecks.inheritsParameters(current, issuer);\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\tinherits ? deferSignature : verifySignatureOnce,\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(\n\t\t\tissuer,\n\t\t\t[...path, issuer],\n\t\t\tnextVisited,\n\t\t\tcandidate.nextCaBelowCount,\n\t\t\tinherits ? [...pending, path.length - 1] : pending,\n\t\t);\n\t}\n\n\tfunction deferSignature(): Promise<VerifyCertificateSignatureResult> {\n\t\treturn Promise.resolve({ ok: true, valid: true });\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\tconst signatureFailure = signatureResultFailure(\n\t\tsignatureResult,\n\t\tcurrent,\n\t\tissuer,\n\t\tpath.length - 1,\n\t\tcallbacks,\n\t);\n\treturn signatureFailure === undefined\n\t\t? issuerConstraints\n\t\t: { ok: false, failure: signatureFailure };\n}\n\n/** The path failure for a signature check of `current` under `issuer`, if it did not pass. */\nfunction signatureResultFailure(\n\tsignatureResult: VerifyCertificateSignatureResult,\n\tcurrent: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tindex: number,\n\tcallbacks: VerifyPathCallbacks,\n): VerifyChainFailure | undefined {\n\tif (!signatureResult.ok) {\n\t\treturn callbacks.failure(\n\t\t\tsignatureResult.code,\n\t\t\tsignatureResult.reason,\n\t\t\tindex,\n\t\t\tcallbacks.detail({\n\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t\tactual: signatureResult.reason,\n\t\t\t}),\n\t\t);\n\t}\n\tif (!signatureResult.valid) {\n\t\treturn callbacks.failure(\n\t\t\t'signature_invalid',\n\t\t\t'certificate signature does not verify',\n\t\t\tindex,\n\t\t\tcallbacks.detail({\n\t\t\t\tsubjectCommonName: current.subject.values.commonName,\n\t\t\t\tissuerCommonName: issuer.subject.values.commonName,\n\t\t\t}),\n\t\t);\n\t}\n\treturn undefined;\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. */\n/**\n * What {@linkcode matchTrustAnchor} runs for each candidate anchor:\n * `completesPath` verifies the links below that wait on the parameters the\n * anchor passes down (RFC 5280 §6.1.4 (e)).\n */\ninterface TrustAnchorChecks {\n\treadonly verifyAnchor: typeof verifyTrustAnchorSignature;\n\treadonly charge: () => boolean;\n\treadonly distrust: (spki: Uint8Array) => Promise<string | undefined>;\n\treadonly completesPath: (anchor: TrustAnchor) => Promise<boolean>;\n}\n\nasync function matchTrustAnchor(\n\tcertificate: ParsedCertificate,\n\tanchorIndex: ReadonlyMap<string, readonly TrustAnchor[]>,\n\tcallbacks: VerifyPathCallbacks,\n\tindex: number,\n\t{ verifyAnchor, charge, distrust, completesPath }: TrustAnchorChecks,\n): Promise<TrustAnchorMatchResult> {\n\tconst anchors = anchorIndex.get(canonicalDnKey(certificate.issuer));\n\tif (anchors === undefined) {\n\t\treturn { matched: false };\n\t}\n\tlet firstFailure: VerifyChainFailure | undefined;\n\tfor (const anchor of anchors) {\n\t\tif (!charge()) return { matched: false };\n\t\tif (trustAnchorAkiMismatch(certificate, anchor)) continue;\n\t\t// The canonicalDnKey bucket is not proof of DN equality (prohibited values\n\t\t// are non-reflexive and prepared/tagged namespaces can collide), so confirm\n\t\t// the anchor's subject actually equals the certificate's issuer.\n\t\tif (!compareDistinguishedNames(certificate.issuer, anchor.subject)) continue;\n\t\tconst blockedHash = await distrust(anchor.subjectPublicKeyInfoDer);\n\t\tif (blockedHash !== undefined) {\n\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t'public_key_distrusted',\n\t\t\t\t'bare trust anchor public key is explicitly distrusted',\n\t\t\t\tundefined,\n\t\t\t\tcallbacks.detail({ actual: blockedHash }),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst verified = await verifyAnchor(certificate, anchor);\n\t\tif (!verified.ok) {\n\t\t\t// Capture the first failure but continue trying other anchors\n\t\t\tfirstFailure ??= callbacks.failure(\n\t\t\t\tverified.code,\n\t\t\t\tverified.reason,\n\t\t\t\tindex,\n\t\t\t\tcallbacks.detail({\n\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\tactual: verified.reason,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!verified.valid) {\n\t\t\tif (firstFailure === undefined) {\n\t\t\t\tfirstFailure = callbacks.failure(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate signature does not verify',\n\t\t\t\t\tindex,\n\t\t\t\t\tcallbacks.detail({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: 'certificate signature does not verify',\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (!(await completesPath(anchor))) continue;\n\t\treturn { matched: true, anchor };\n\t}\n\treturn firstFailure !== undefined\n\t\t? { matched: false, failure: firstFailure }\n\t\t: { matched: false };\n}\n\nfunction trustAnchorAkiMismatch(certificate: ParsedCertificate, anchor: TrustAnchor): boolean {\n\treturn (\n\t\tanchor.subjectKeyIdentifier !== undefined &&\n\t\tcertificate.authorityKeyIdentifier !== undefined &&\n\t\tanchor.subjectKeyIdentifier !== certificate.authorityKeyIdentifier\n\t);\n}\n\n/** Verifies that `certificate` was signed by a bare trust anchor's key. */\nexport function verifyTrustAnchorSignature(\n\tcertificate: ParsedCertificate,\n\tanchor: TrustAnchor,\n\tverification: CallerVerification = NO_CALLER_VERIFICATION,\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.signatureValueUnusedBits,\n\t\t\tcertificate.tbsCertificateDer,\n\t\t\tverification,\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":";;;;;;;;;;;;;;;;;AAiHA,MAAaa,IAAmC;;AAGhD,SAAgB,yBAAyBC,GAAiC;CACzE,IAAIA,MAAU,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ACTD,MAAiB,KAAA,MACpBA,IAAe5D,EAAU,QACxB,qBACA,yCACA/C,GACA+C,EAAU,OAAO;GAChB,mBAAmBlD,EAAY,QAAQ,OAAO;GAC9C,QAAQ;EACT,CAAC,CACF;OAIF,IAAM,MAAM4G,EAAczF,CAAM,GAChC,OAAO;GAAE,SAAS;GAAMA;EAAO;CAChC;CACA,OAAO2F,MAAiB,KAAA,IAErB,EAAE,SAAS,GAAM,IADjB;EAAE,SAAS;EAAO,SAASA;CAAa;AAE5C;AAEA,SAAS,uBAAuB9G,GAAgCmB,GAA8B;CAC7F,OACCA,EAAO,yBAAyB,KAAA,KAChCnB,EAAY,2BAA2B,KAAA,KACvCmB,EAAO,yBAAyBnB,EAAY;AAE9C;;AAGA,SAAgB,2BACfA,GACAmB,GACAR,IAAmCpB,GACS;CAC5C,OAAO,qBACNG,EACCM,EAAY,uBACZA,EAAY,iCACZmB,EAAO,uBACPA,EAAO,wBACPA,EAAO,yBACPnB,EAAY,gBACZA,EAAY,0BACZA,EAAY,mBACZW,CACD,CACD;AACD;AAEA,SAAS,iBAAiBqG,GAAqB;CAC9C,OAAO,OAAO,MAAMA,EAAM,QAAQ,CAAC,IAAI,mBAAmBA,EAAM,YAAY;AAC7E;AAEA,SAAS,qBAAqBA,GAA4C;CACzE,OAAOA,MAAU,KAAA,KAAa,OAAO,UAAUA,CAAK,KAAKA,KAAS;AACnE;;AAGA,MAAMC,oBAAmB,IAAI,QAAmC;;AAGhE,SAAS,YAAYjH,GAAwC;CAC5D,IAAIkH,IAASD,EAAiB,IAAIjH,CAAW;CAK7C,OAJIkH,MAAW,KAAA,MACdA,IAAShI,EAAMc,EAAY,GAAG,GAC9BiH,EAAiB,IAAIjH,GAAakH,CAAM,IAElCA;AACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"directory-name.js","names":["
|
|
1
|
+
{"version":3,"file":"directory-name.js","names":["childrenOf","decodeObjectIdentifier","requireElement","readRootElement","element","nameDer","name","rdn","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,qBAAqBI,GAAiC;CACrE,IAAMC,IAAU,IAAI,WAAWD,EAAQ,KAAK,GACtCE,IAAOJ,EACZC,EAAgBE,GAAS,EAAE,UAAA,GAAgC,CAAC,GAC5D,oBACD;CACA,IAAIC,EAAK,QAAQ,IAChB,MAAU,MAAM,yCAAyC;CAE1D,KAAK,IAAMC,KAAOP,EAAWK,GAASC,CAAI,GAAG;EAC5C,IAAIC,EAAI,QAAQ,IACf,MAAU,MAAM,gCAAgC;EAEjD,IAAMC,IAAaR,EAAWK,GAASE,CAAG;EAC1C,IAAIC,EAAW,WAAW,GACzB,MAAU,MAAM,qCAAqC;EAEtD,KAAK,IAAMC,KAAaD,GAAY;GACnC,IAAIC,EAAU,QAAQ,IACrB,MAAU,MAAM,2CAA2C;GAE5D,IAAMC,IAAQV,EAAWK,GAASI,CAAS,GACrCE,IAAOD,EAAM;GACnB,IAAIA,EAAM,WAAW,KAAKC,MAAS,KAAA,KAAaA,EAAK,QAAQ,GAC5D,MAAU,MAAM,uDAAuD;GAExEV,EAAuBU,EAAK,KAAK;EAClC;CACD;CACA,OAAON;AACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension-bits.js","names":["
|
|
1
|
+
{"version":3,"file":"extension-bits.js","names":["bitString","readRootElement","throwExtensionEncoderError","KEY_USAGE_ORDER","DISTRIBUTION_POINT_REASON_ORDER","usages","encoded","usage","bytes","bitStringElement","reasons","reason","value","values","bitForValue","highestBit","bits","bit","byteLength","byteIndex","bitIndex","candidates","bitOffset","unusedBits","nonZeroPadding","flags","index","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,MAAMG,IAAkB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,GAGMC,IAAkC;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAOA,SAAgB,wBAAwBC,GAAyC;CAC5EA,EAAO,WAAW,KACrBH,EAA2B,mBAAmB,oCAAoC;CAEnF,IAAMI,IAAU,eAAeD,IAASE,MACvC,aAAaJ,GAAiBI,GAAO,WAAW,CACjD;CACA,OAAOP,EAAUM,EAAQ,OAAOA,EAAQ,UAAU;AACnD;;;;;;AAOA,SAAgB,uBAAuBE,GAA6C;CACnF,IAAMC,IAAmBR,EAAgBO,GAAO,EAAE,UAAA,GAAgC,CAAC;CACnF,IAAIC,EAAiB,QAAQ,GAC5B,MAAU,MAAM,+BAA+B;CAEhD,OAAO,yBACN,eAAeA,EAAiB,OAAON,GAAiB,CAAC,GACzD,UACD;AACD;;;;;;;AAQA,SAAgB,0CACfO,GACa;CACb,IAAMJ,IAAU,eACfI,IACCC,MACA,aAAaP,GAAiCO,GAAQ,2BAA2B,IAAI,CACvF;CACA,OAAO,WAAW,GAAGL,EAAQ,YAAY,GAAGA,EAAQ,KAAK;AAC1D;;;;;;;AAQA,SAAgB,yCACfM,GAC0C;CAC1C,OAAO,yBACN,eAAeA,GAAOR,GAAiC,CAAC,GACxD,2BACD;AACD;;AAGA,SAAS,eACRS,GACAC,GAIC;CACD,IAAID,EAAO,WAAW,GACrB,OAAO;EAAE,uBAAO,IAAI,WAAY;EAAG,YAAY;CAAE;CAElD,IAAIE,IAAa,IACXC,IAAiB,CAAC;CACxB,KAAK,IAA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,EAAO,gBACV,MAAU,MAAM,GAAGC,EAAM,sCAAsC;CAEhE,OAAOD;AACR;;AAGA,SAAS,aAA+BE,GAAqBlB,GAAUiB,GAAuB;CAC7F,IAAMH,IAAQI,EAAM,QAAQlB,CAAK;CACjC,IAAIc,IAAQ,GACX,MAAU,MAAM,eAAeG,EAAM,IAAIjB,GAAO;CAEjD,OAAOc;AACR"}
|
|
@@ -1 +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,
|
|
1
|
+
{"version":3,"file":"extension-errors.js","names":["throwMicro509Error","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,2BACfC,GACAC,GACQ;CACRF,EAAmBC,GAAMC,CAAO;AACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension-registry.js","names":["extensionAppliers","BASIC_CONSTRAINTS_EXTENSION_DEFINITION","OIDS","parseBasicConstraints","valueDer","encodeBasicConstraints","value","KEY_USAGE_EXTENSION_DEFINITION","parseKeyUsage","encodeKeyUsage","EXTENDED_KEY_USAGE_EXTENSION_DEFINITION","parseExtendedKeyUsage","encodeExtendedKeyUsage","SUBJECT_ALT_NAME_EXTENSION_DEFINITION","parseSubjectAltNames","sequence","encodeSubjectAltName","name","ISSUER_ALT_NAME_EXTENSION_DEFINITION","NAME_CONSTRAINTS_EXTENSION_DEFINITION","parseNameConstraints","encodeNameConstraints","assertNameConstraintsProfile","assertExtensionCriticality","critical","CERTIFICATE_POLICIES_EXTENSION_DEFINITION","parseCertificatePolicies","encodeCertificatePolicies","POLICY_MAPPINGS_EXTENSION_DEFINITION","parsePolicyMappings","encodePolicyMappings","POLICY_CONSTRAINTS_EXTENSION_DEFINITION","parsePolicyConstraints","encodePolicyConstraints","INHIBIT_ANY_POLICY_EXTENSION_DEFINITION","parseInhibitAnyPolicy","encodeInhibitAnyPolicy","AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION","parseAuthorityInfoAccess","encodeAuthorityInfoAccess","assertAuthorityInfoAccessProfile","CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION","parseCrlDistributionPoints","encodeCrlDistributionPoints","NO_REV_AVAIL_EXTENSION_DEFINITION","nullValue","SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION","octetString","hexToBytes","AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION","parseAuthorityKeyIdentifier","implicitPrimitiveContext","CERT_CSR_EXTENSION_DEFINITIONS","EXTENSION_DEFINITION_MAP","definition","oid","context","applier","accumulator","element","readRootElement","toHex"],"sources":["../../../src/internal/x509/extension-registry.ts"],"sourcesContent":["/**\n * Internal extension registry for certificate and CSR parsing.\n *\n * Maps each supported extension OID to a definition that can decode DER,\n * encode input, and apply parsed values to the accumulator used during\n * certificate/CSR parsing.\n *\n * @module\n */\n\nimport { hexToBytes, toHex } from '#micro509/internal/asn1/asn1';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\timplicitPrimitiveContext,\n\tnullValue,\n\toctetString,\n\treadRootElement,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport type { ParsedBitFlags } from '#micro509/internal/x509/extension-bits';\nimport type {\n\tAuthorityInformationAccess,\n\tAuthorityInformationAccessInput,\n\tBasicConstraints,\n\tCertificatePolicies,\n\tDistributionPoint,\n\tExtendedKeyUsage,\n\tInhibitAnyPolicy,\n\tKeyUsage,\n\tNameConstraints,\n\tParsedNameConstraintForm,\n\tPolicyConstraints,\n\tPolicyMappings,\n\tSubjectAltName,\n} from '#micro509/x509/extensions';\nimport {\n\tassertAuthorityInfoAccessProfile,\n\tassertCrlDistributionPointsProfile,\n\tassertExtensionCriticality,\n\tassertNameConstraintsProfile,\n\tassertStoredSubjectAltName,\n\tbuildSubjectKeyIdentifier,\n\tencodeAuthorityInfoAccess,\n\tencodeBasicConstraints,\n\tencodeCertificatePolicies,\n\tencodeCrlDistributionPoints,\n\tencodeExtendedKeyUsage,\n\tencodeInhibitAnyPolicy,\n\tencodeKeyUsage,\n\tencodeNameConstraints,\n\tencodePolicyConstraints,\n\tencodePolicyMappings,\n\tencodeSubjectAltName,\n} from '#micro509/x509/extensions';\nimport type { ParsedDistributionPoint } from '#micro509/x509/parse';\nimport {\n\tparseAuthorityInfoAccess,\n\tparseAuthorityKeyIdentifier,\n\tparseBasicConstraints,\n\tparseCertificatePolicies,\n\tparseCrlDistributionPoints,\n\tparseExtendedKeyUsage,\n\tparseInhibitAnyPolicy,\n\tparseKeyUsage,\n\tparseNameConstraints,\n\tparsePolicyConstraints,\n\tparsePolicyMappings,\n\tparseSubjectAltNames,\n} from '#micro509/x509/parse';\n\n/** Whether an extension applies to certificate parsing, CSR parsing, or both. */\nexport type ExtensionRegistryContext = 'certificate' | 'csr';\n\n/**\n * Readonly snapshot of decoded known extensions collected during parsing.\n *\n * Fields mirror the extension slots on {@linkcode ParsedCertificate}.\n */\nexport interface KnownParsedExtensionAccumulator {\n\t/** Basic Constraints (CA flag + optional pathLength). */\n\treadonly basicConstraints?: BasicConstraints;\n\t/** Key Usage flags (digitalSignature, keyCertSign, etc.). */\n\treadonly keyUsage?: ParsedBitFlags<KeyUsage>;\n\t/** Extended Key Usage purposes (serverAuth, clientAuth, etc.). */\n\treadonly extendedKeyUsage?: readonly ExtendedKeyUsage[];\n\t/** Subject Alternative Names (dns, ip, email, uri, srv, directoryName). */\n\treadonly subjectAltNames?: readonly SubjectAltName[];\n\t/** Issuer Alternative Names (RFC 5280 §4.2.1.7, same GeneralNames syntax). */\n\treadonly issuerAltNames?: readonly SubjectAltName[];\n\t/** Name Constraints (permitted/excluded subtrees). */\n\treadonly nameConstraints?: NameConstraints<ParsedNameConstraintForm>;\n\t/** Certificate Policies extension values. */\n\treadonly certificatePolicies?: CertificatePolicies;\n\t/** Policy Mappings from issuer to subject policy domains. */\n\treadonly policyMappings?: PolicyMappings;\n\t/** Policy Constraints (requireExplicitPolicy / inhibitPolicyMapping). */\n\treadonly policyConstraints?: PolicyConstraints;\n\t/** Inhibit Any-Policy skip-certs value. */\n\treadonly inhibitAnyPolicy?: InhibitAnyPolicy;\n\t/** Authority Information Access (OCSP, CA issuers). */\n\treadonly authorityInfoAccess?: readonly AuthorityInformationAccess[];\n\t/** CRL Distribution Points. */\n\treadonly crlDistributionPoints?: readonly ParsedDistributionPoint[];\n\t/** No Revocation Available (RFC 9608 §2). */\n\treadonly noRevAvail?: true;\n\t/** Hex-encoded Subject Key Identifier. */\n\treadonly subjectKeyIdentifier?: string;\n\t/** Hex-encoded Authority Key Identifier. */\n\treadonly authorityKeyIdentifier?: string;\n}\n\n/**\n * Mutable version of {@linkcode KnownParsedExtensionAccumulator} used during\n * extension parsing to progressively fill in decoded values.\n */\nexport type MutableKnownParsedExtensionAccumulator = {\n\t-readonly [Key in keyof KnownParsedExtensionAccumulator]: KnownParsedExtensionAccumulator[Key];\n};\n\n/**\n * Full lifecycle definition for a known X.509 extension: decode, encode,\n * and apply-to-accumulator during parsing.\n *\n * `TParsed` is the type produced when decoding DER; `TInput` is the type\n * accepted when encoding (they may differ, e.g. for NameConstraints).\n */\nexport interface ExtensionDefinition<TParsed, TInput = TParsed> {\n\t/** Dotted-decimal OID of the extension. */\n\treadonly oid: string;\n\t/** Contexts where this extension is valid (`'certificate'`, `'csr'`, or both). */\n\treadonly contexts: readonly ExtensionRegistryContext[];\n\t/** Whether the extension is marked critical by default when encoding. */\n\treadonly defaultCritical: boolean;\n\t/** When true, the extension is computed by the builder (e.g. SKI, AKI) rather than user-supplied. */\n\treadonly autoGenerated?: boolean;\n\t/** Decode the extension's DER extnValue into a typed value. */\n\tdecode(valueDer: Uint8Array): TParsed;\n\t/** Encode a typed input into the extension's DER extnValue. */\n\tencode(value: TInput): Uint8Array;\n\t/**\n\t * Apply the RFC 5280 profile rules this extension's encoder enforces to an\n\t * already-decoded value, throwing a coded encoder error on violation.\n\t *\n\t * Decoding proves a payload's structure; it does not prove the payload obeys\n\t * the profile, because the parser is deliberately tolerant. Builders route a\n\t * `customExtensions` payload carrying a known OID through here so a raw value\n\t * meets the same bar as the typed input for that extension. Implementations\n\t * delegate to the encoder that owns the rule so the two cannot drift.\n\t *\n\t * Parsing never calls this.\n\t */\n\tassertProfile(value: TParsed, critical: boolean): void;\n\t/** Store a decoded value into the parse-time accumulator. */\n\tapplyParsed(accumulator: MutableKnownParsedExtensionAccumulator, value: TParsed): void;\n}\n\n/**\n * An {@linkcode ExtensionDefinition} after registration, carrying the\n * decode-then-validate closure captured when `TParsed` was concrete.\n */\nexport type RegisteredExtensionDefinition<TParsed, TInput = TParsed> = ExtensionDefinition<\n\tTParsed,\n\tTInput\n> & {\n\t/** Decode a DER extnValue and apply this extension's profile rules to it. */\n\tassertDerProfile(valueDer: Uint8Array, critical: boolean): void;\n};\n\n/**\n * Module-internal decode-and-apply closures, captured at definition time.\n *\n * Each entry is keyed by OID and populated by {@linkcode defineExtensionDefinition}\n * when the concrete generic type is known, avoiding the correlated-union problem\n * that would arise from calling `decode` and `applyParsed` through a union type.\n */\nconst extensionAppliers = new Map<\n\tstring,\n\t(accumulator: MutableKnownParsedExtensionAccumulator, valueDer: Uint8Array) => void\n>();\n\n/** Registry entry for Basic Constraints (OID 2.5.29.19). Critical by default. */\nexport const BASIC_CONSTRAINTS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<BasicConstraints> =\n\tdefineExtensionDefinition<BasicConstraints>({\n\t\toid: OIDS.basicConstraints,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parseBasicConstraints(valueDer),\n\t\tencode: (value) => encodeBasicConstraints(value),\n\t\tassertProfile: (value) => {\n\t\t\tencodeBasicConstraints(value);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.basicConstraints = value;\n\t\t},\n\t});\n\n/** Registry entry for Key Usage (OID 2.5.29.15). Critical by default. */\nexport const KEY_USAGE_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\tParsedBitFlags<KeyUsage>,\n\treadonly KeyUsage[]\n> = defineExtensionDefinition<ParsedBitFlags<KeyUsage>, readonly KeyUsage[]>({\n\toid: OIDS.keyUsage,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: true,\n\tdecode: (valueDer) => parseKeyUsage(valueDer),\n\tencode: (value) => encodeKeyUsage(value),\n\tassertProfile: (value) => {\n\t\tencodeKeyUsage(value.flags);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.keyUsage = value;\n\t},\n});\n\n/** Registry entry for Extended Key Usage (OID 2.5.29.37). Non-critical by default. */\nexport const EXTENDED_KEY_USAGE_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\treadonly ExtendedKeyUsage[]\n> = defineExtensionDefinition<readonly ExtendedKeyUsage[]>({\n\toid: OIDS.extendedKeyUsage,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseExtendedKeyUsage(valueDer),\n\tencode: (value) => encodeExtendedKeyUsage(value),\n\tassertProfile: (value) => {\n\t\tencodeExtendedKeyUsage(value);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.extendedKeyUsage = value;\n\t},\n});\n\n/** Registry entry for Subject Alternative Name (OID 2.5.29.17). Non-critical by default. */\nexport const SUBJECT_ALT_NAME_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\treadonly SubjectAltName[]\n> = defineExtensionDefinition<readonly SubjectAltName[]>({\n\toid: OIDS.subjectAltName,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseSubjectAltNames(valueDer),\n\tencode: (value) => sequence(value.map(encodeSubjectAltName)),\n\tassertProfile: (value) => {\n\t\tfor (const name of value) {\n\t\t\tassertStoredSubjectAltName(name);\n\t\t}\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.subjectAltNames = value;\n\t},\n});\n\n/** Registry entry for Issuer Alternative Name (OID 2.5.29.18). Non-critical by default. */\nexport const ISSUER_ALT_NAME_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\treadonly SubjectAltName[]\n> = defineExtensionDefinition<readonly SubjectAltName[]>({\n\toid: OIDS.issuerAltName,\n\tcontexts: ['certificate'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseSubjectAltNames(valueDer, 'issuerAltName'),\n\tencode: (value) => sequence(value.map(encodeSubjectAltName)),\n\tassertProfile: (value) => {\n\t\tfor (const name of value) {\n\t\t\tassertStoredSubjectAltName(name);\n\t\t}\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.issuerAltNames = value;\n\t},\n});\n\n/** Registry entry for Name Constraints (OID 2.5.29.30). Critical by default. */\nexport const NAME_CONSTRAINTS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\tNameConstraints<ParsedNameConstraintForm>,\n\tNameConstraints\n> = defineExtensionDefinition<NameConstraints<ParsedNameConstraintForm>, NameConstraints>({\n\toid: OIDS.nameConstraints,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: true,\n\tdecode: (valueDer) => parseNameConstraints(valueDer),\n\tencode: (value) => encodeNameConstraints(value),\n\tassertProfile: (value, critical) => {\n\t\tassertNameConstraintsProfile(value);\n\t\tassertExtensionCriticality('nameConstraints', true, critical);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.nameConstraints = value;\n\t},\n});\n\n/** Registry entry for Certificate Policies (OID 2.5.29.32). Non-critical by default. */\nexport const CERTIFICATE_POLICIES_EXTENSION_DEFINITION: RegisteredExtensionDefinition<CertificatePolicies> =\n\tdefineExtensionDefinition<CertificatePolicies>({\n\t\toid: OIDS.certificatePolicies,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: false,\n\t\tdecode: (valueDer) => parseCertificatePolicies(valueDer),\n\t\tencode: (value) => encodeCertificatePolicies(value),\n\t\tassertProfile: (value) => {\n\t\t\tencodeCertificatePolicies(value);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.certificatePolicies = value;\n\t\t},\n\t});\n\n/** Registry entry for Policy Mappings (OID 2.5.29.33). Critical by default. */\nexport const POLICY_MAPPINGS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<PolicyMappings> =\n\tdefineExtensionDefinition<PolicyMappings>({\n\t\toid: OIDS.policyMappings,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parsePolicyMappings(valueDer),\n\t\tencode: (value) => encodePolicyMappings(value),\n\t\tassertProfile: (value) => {\n\t\t\tencodePolicyMappings(value);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.policyMappings = value;\n\t\t},\n\t});\n\n/** Registry entry for Policy Constraints (OID 2.5.29.36). Critical by default. */\nexport const POLICY_CONSTRAINTS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<PolicyConstraints> =\n\tdefineExtensionDefinition<PolicyConstraints>({\n\t\toid: OIDS.policyConstraints,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parsePolicyConstraints(valueDer),\n\t\tencode: (value) => encodePolicyConstraints(value),\n\t\tassertProfile: (value, critical) => {\n\t\t\tencodePolicyConstraints(value);\n\t\t\tassertExtensionCriticality('policyConstraints', true, critical);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.policyConstraints = value;\n\t\t},\n\t});\n\n/** Registry entry for Inhibit anyPolicy (OID 2.5.29.54). Critical by default. */\nexport const INHIBIT_ANY_POLICY_EXTENSION_DEFINITION: RegisteredExtensionDefinition<InhibitAnyPolicy> =\n\tdefineExtensionDefinition<InhibitAnyPolicy>({\n\t\toid: OIDS.inhibitAnyPolicy,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parseInhibitAnyPolicy(valueDer),\n\t\tencode: (value) => encodeInhibitAnyPolicy(value),\n\t\tassertProfile: (value, critical) => {\n\t\t\tencodeInhibitAnyPolicy(value);\n\t\t\tassertExtensionCriticality('inhibitAnyPolicy', true, critical);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.inhibitAnyPolicy = value;\n\t\t},\n\t});\n\n/** Registry entry for Authority Information Access (OID 1.3.6.1.5.5.7.1.1). Non-critical. */\nexport const AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\treadonly AuthorityInformationAccess[],\n\treadonly AuthorityInformationAccessInput[]\n> = defineExtensionDefinition<\n\treadonly AuthorityInformationAccess[],\n\treadonly AuthorityInformationAccessInput[]\n>({\n\toid: OIDS.authorityInfoAccess,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseAuthorityInfoAccess(valueDer),\n\tencode: (value) => encodeAuthorityInfoAccess(value),\n\tassertProfile: (value, critical) => {\n\t\tassertAuthorityInfoAccessProfile(value);\n\t\tassertExtensionCriticality('authorityInfoAccess', false, critical);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.authorityInfoAccess = value;\n\t},\n});\n\n/** Registry entry for CRL Distribution Points (OID 2.5.29.31). Non-critical by default. */\nexport const CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\treadonly ParsedDistributionPoint[],\n\treadonly DistributionPoint[]\n> = defineExtensionDefinition<readonly ParsedDistributionPoint[], readonly DistributionPoint[]>({\n\toid: OIDS.cRLDistributionPoints,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseCrlDistributionPoints(valueDer),\n\tencode: (value) => encodeCrlDistributionPoints(value),\n\tassertProfile: (value) => {\n\t\tassertCrlDistributionPointsProfile(value);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.crlDistributionPoints = value;\n\t},\n});\n\n/** Registry entry for No Revocation Available (OID 2.5.29.56, RFC 9608 §2). Non-critical. */\nexport const NO_REV_AVAIL_EXTENSION_DEFINITION: RegisteredExtensionDefinition<true> =\n\tdefineExtensionDefinition<true>({\n\t\toid: OIDS.noRevAvail,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: false,\n\t\tdecode: (valueDer) => decodeNoRevAvail(valueDer),\n\t\tencode: () => nullValue(),\n\t\tassertProfile: (_value, critical) => {\n\t\t\tassertExtensionCriticality('noRevAvail', false, critical);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.noRevAvail = value;\n\t\t},\n\t});\n\n/** Registry entry for Subject Key Identifier (OID 2.5.29.14). Auto-generated; non-critical. */\nexport const SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\tstring,\n\tstring | Uint8Array\n> = defineExtensionDefinition<string, string | Uint8Array>({\n\toid: OIDS.subjectKeyIdentifier,\n\tcontexts: ['certificate'],\n\tdefaultCritical: false,\n\tautoGenerated: true,\n\tdecode: (valueDer) => decodeSubjectKeyIdentifier(valueDer),\n\tencode: (value) => octetString(normalizeKeyIdentifier(value)),\n\tassertProfile: (value, critical) => {\n\t\thexToBytes(value);\n\t\tassertExtensionCriticality('subjectKeyIdentifier', false, critical);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.subjectKeyIdentifier = value;\n\t},\n});\n\n/** Registry entry for Authority Key Identifier (OID 2.5.29.35). Auto-generated; non-critical. */\nexport const AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\tstring | undefined,\n\tstring | Uint8Array\n> = defineExtensionDefinition<string | undefined, string | Uint8Array>({\n\toid: OIDS.authorityKeyIdentifier,\n\tcontexts: ['certificate'],\n\tdefaultCritical: false,\n\tautoGenerated: true,\n\tdecode: (valueDer) => parseAuthorityKeyIdentifier(valueDer),\n\tencode: (value) => sequence([implicitPrimitiveContext(0, normalizeKeyIdentifier(value))]),\n\tassertProfile: (value, critical) => {\n\t\tif (value !== undefined) {\n\t\t\thexToBytes(value);\n\t\t}\n\t\tassertExtensionCriticality('authorityKeyIdentifier', false, critical);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\tif (value !== undefined) {\n\t\t\taccumulator.authorityKeyIdentifier = value;\n\t\t}\n\t},\n});\n\n/** Union of all built-in extension definition constants. */\nexport type KnownExtensionDefinition =\n\t| typeof BASIC_CONSTRAINTS_EXTENSION_DEFINITION\n\t| typeof KEY_USAGE_EXTENSION_DEFINITION\n\t| typeof EXTENDED_KEY_USAGE_EXTENSION_DEFINITION\n\t| typeof SUBJECT_ALT_NAME_EXTENSION_DEFINITION\n\t| typeof ISSUER_ALT_NAME_EXTENSION_DEFINITION\n\t| typeof NAME_CONSTRAINTS_EXTENSION_DEFINITION\n\t| typeof CERTIFICATE_POLICIES_EXTENSION_DEFINITION\n\t| typeof POLICY_MAPPINGS_EXTENSION_DEFINITION\n\t| typeof POLICY_CONSTRAINTS_EXTENSION_DEFINITION\n\t| typeof INHIBIT_ANY_POLICY_EXTENSION_DEFINITION\n\t| typeof AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION\n\t| typeof CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION\n\t| typeof NO_REV_AVAIL_EXTENSION_DEFINITION\n\t| typeof SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION\n\t| typeof AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION;\n\n/** All built-in extension definitions, in registration order. */\nexport const CERT_CSR_EXTENSION_DEFINITIONS: readonly KnownExtensionDefinition[] = [\n\tBASIC_CONSTRAINTS_EXTENSION_DEFINITION,\n\tKEY_USAGE_EXTENSION_DEFINITION,\n\tEXTENDED_KEY_USAGE_EXTENSION_DEFINITION,\n\tSUBJECT_ALT_NAME_EXTENSION_DEFINITION,\n\tISSUER_ALT_NAME_EXTENSION_DEFINITION,\n\tNAME_CONSTRAINTS_EXTENSION_DEFINITION,\n\tCERTIFICATE_POLICIES_EXTENSION_DEFINITION,\n\tPOLICY_MAPPINGS_EXTENSION_DEFINITION,\n\tPOLICY_CONSTRAINTS_EXTENSION_DEFINITION,\n\tINHIBIT_ANY_POLICY_EXTENSION_DEFINITION,\n\tAUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION,\n\tCRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION,\n\tNO_REV_AVAIL_EXTENSION_DEFINITION,\n\tSUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n\tAUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n];\n\n/** OID-keyed lookup for known extension definitions. */\nconst EXTENSION_DEFINITION_MAP = new Map<string, KnownExtensionDefinition>(\n\tCERT_CSR_EXTENSION_DEFINITIONS.map((definition) => [definition.oid, definition]),\n);\n\n/**\n * Return all known extension definitions, optionally filtered by context.\n *\n * @param context If provided, only definitions valid in that context are returned.\n */\nexport function listExtensionDefinitions(\n\tcontext?: ExtensionRegistryContext,\n): readonly KnownExtensionDefinition[] {\n\tif (context === undefined) {\n\t\treturn CERT_CSR_EXTENSION_DEFINITIONS;\n\t}\n\treturn CERT_CSR_EXTENSION_DEFINITIONS.filter((definition) =>\n\t\tdefinition.contexts.includes(context),\n\t);\n}\n\n/**\n * Look up a known extension definition by OID.\n *\n * Overloaded for each built-in OID constant to return the exact definition type;\n * the generic `string` form returns the union or `undefined`.\n *\n * @param oid Dotted-decimal extension OID.\n * @returns The matching definition, or `undefined` for unrecognized OIDs.\n */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.basicConstraints,\n): typeof BASIC_CONSTRAINTS_EXTENSION_DEFINITION;\n/** Exact definition for the Key Usage extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.keyUsage,\n): typeof KEY_USAGE_EXTENSION_DEFINITION;\n/** Exact definition for the Extended Key Usage extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.extendedKeyUsage,\n): typeof EXTENDED_KEY_USAGE_EXTENSION_DEFINITION;\n/** Exact definition for the Subject Alternative Name extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.subjectAltName,\n): typeof SUBJECT_ALT_NAME_EXTENSION_DEFINITION;\n/** Exact definition for the Issuer Alternative Name extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.issuerAltName,\n): typeof ISSUER_ALT_NAME_EXTENSION_DEFINITION;\n/** Exact definition for the Name Constraints extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.nameConstraints,\n): typeof NAME_CONSTRAINTS_EXTENSION_DEFINITION;\n/** Exact definition for the Certificate Policies extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.certificatePolicies,\n): typeof CERTIFICATE_POLICIES_EXTENSION_DEFINITION;\n/** Exact definition for the Policy Mappings extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.policyMappings,\n): typeof POLICY_MAPPINGS_EXTENSION_DEFINITION;\n/** Exact definition for the Policy Constraints extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.policyConstraints,\n): typeof POLICY_CONSTRAINTS_EXTENSION_DEFINITION;\n/** Exact definition for the Inhibit Any-Policy extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.inhibitAnyPolicy,\n): typeof INHIBIT_ANY_POLICY_EXTENSION_DEFINITION;\n/** Exact definition for the Authority Information Access extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.authorityInfoAccess,\n): typeof AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION;\n/** Exact definition for the CRL Distribution Points extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.cRLDistributionPoints,\n): typeof CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION;\n/** Exact definition for the No Revocation Available extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.noRevAvail,\n): typeof NO_REV_AVAIL_EXTENSION_DEFINITION;\n/** Exact definition for the Subject Key Identifier extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.subjectKeyIdentifier,\n): typeof SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION;\n/** Exact definition for the Authority Key Identifier extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.authorityKeyIdentifier,\n): typeof AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION;\n/** Generic lookup: returns the matching definition, or `undefined` for unrecognized OIDs. */\nexport function getExtensionDefinition(oid: string): KnownExtensionDefinition | undefined;\nexport function getExtensionDefinition(oid: string): KnownExtensionDefinition | undefined {\n\treturn EXTENSION_DEFINITION_MAP.get(oid);\n}\n\n/**\n * If `oid` matches a known extension valid in `context`, decode its DER\n * value and store the result in the accumulator.\n *\n * @returns `true` if the extension was recognized and applied.\n */\nexport function decodeAndApplyKnownExtension(\n\tcontext: ExtensionRegistryContext,\n\toid: string,\n\taccumulator: MutableKnownParsedExtensionAccumulator,\n\tvalueDer: Uint8Array,\n): boolean {\n\tconst definition = getExtensionDefinition(oid);\n\tif (definition === undefined || !definition.contexts.includes(context)) {\n\t\treturn false;\n\t}\n\tconst applier = extensionAppliers.get(oid);\n\tif (applier === undefined) {\n\t\treturn false;\n\t}\n\tapplier(accumulator, valueDer);\n\treturn true;\n}\n\n/**\n * Compute a Subject Key Identifier (SHA-1 of the public key bits) from\n * a DER-encoded SubjectPublicKeyInfo.\n */\nexport function buildSubjectKeyIdentifierFromSubjectPublicKeyInfo(\n\tsubjectPublicKeyInfo: Uint8Array,\n): Uint8Array {\n\treturn buildSubjectKeyIdentifier(subjectPublicKeyInfo);\n}\n\n/**\n * Register an {@linkcode ExtensionDefinition} literal, capturing its\n * decode-and-apply and decode-and-validate closures.\n *\n * Both closures are built here, where `TParsed` is concrete, so that\n * `decodeAndApplyKnownExtension` and `assertDerProfile` can be called through the\n * union-typed `KnownExtensionDefinition` without hitting TypeScript's\n * correlated-union limitation.\n */\nfunction defineExtensionDefinition<TParsed, TInput = TParsed>(\n\tdefinition: ExtensionDefinition<TParsed, TInput>,\n): RegisteredExtensionDefinition<TParsed, TInput> {\n\textensionAppliers.set(definition.oid, (accumulator, valueDer) => {\n\t\tdefinition.applyParsed(accumulator, definition.decode(valueDer));\n\t});\n\treturn {\n\t\t...definition,\n\t\tassertDerProfile: (valueDer, critical) => {\n\t\t\tdefinition.assertProfile(definition.decode(valueDer), critical);\n\t\t},\n\t};\n}\n\n/** Accept hex string or Uint8Array and return raw bytes. */\nfunction normalizeKeyIdentifier(value: string | Uint8Array): Uint8Array {\n\treturn typeof value === 'string' ? hexToBytes(value) : value;\n}\n\n/** Decode a noRevAvail extension value, which RFC 9608 §2 defines as NULL. */\nfunction decodeNoRevAvail(valueDer: Uint8Array): true {\n\tconst element = readRootElement(valueDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (element.tag !== 0x05 || element.value.length !== 0) {\n\t\tthrow new Error('noRevAvail must be NULL');\n\t}\n\treturn true;\n}\n\n/** Decode an SKI extension value DER to a hex string. */\nfunction decodeSubjectKeyIdentifier(valueDer: Uint8Array): string {\n\tconst element = readRootElement(valueDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (element.tag !== 0x04) {\n\t\tthrow new Error('SubjectKeyIdentifier must be an OCTET STRING');\n\t}\n\treturn toHex(element.value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgLA,MAAMA,oBAAoB,IAAI,IAG5B,GAGWC,IACZ,0BAA4C;CAC3C,KAAKC,EAAK;CACV,UAAU,CAAC,eAAe,KAAK;CAC/B,iBAAiB;CACjB,SAAS,MAAaC,EAAsBC,CAAQ;CACpD,SAAS,MAAUC,EAAuBC,CAAK;CAC/C,gBAAgB,MAAU;EACzB,EAAuBA,CAAK;CAC7B;CACA,cAAc,GAAa,MAAU;EACpC,EAAY,mBAAmBA;CAChC;AACD,CAAC,GAGWC,IAGT,0BAAyE;CAC5E,KAAKL,EAAK;CACV,UAAU,CAAC,eAAe,KAAK;CAC/B,iBAAiB;CACjB,SAAS,MAAaM,EAAcJ,CAAQ;CAC5C,SAAS,MAAUK,EA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AAGoB,CAAQ;EAC/D;CACD;AACD;;AAGA,SAAS,uBAAuB,GAAwC;CACvE,OAAO,OAAOlB,KAAU,WAAW0C,EAAW1C,CAAK,IAAIA;AACxD;;AAGA,SAAS,iBAAiB,GAA4B;CACrD,IAAMqD,IAAUC,EAAgBxD,GAAU,EAAE,UAAA,GAAgC,CAAC;CAC7E,IAAIuD,EAAQ,QAAQ,KAAQA,EAAQ,MAAM,WAAW,GACpD,MAAU,MAAM,yBAAyB;CAE1C,OAAO;AACR;;AAGA,SAAS,2BAA2B,GAA8B;CACjE,IAAMA,IAAUC,EAAgBxD,GAAU,EAAE,UAAA,GAAgC,CAAC;CAC7E,IAAIuD,EAAQ,QAAQ,GACnB,MAAU,MAAM,8CAA8C;CAE/D,OAAOE,EAAMF,EAAQ,KAAK;AAC3B"}
|
|
1
|
+
{"version":3,"file":"extension-registry.js","names":["hexToBytes","toHex","implicitPrimitiveContext","nullValue","octetString","readRootElement","sequence","OIDS","assertAuthorityInfoAccessProfile","assertCrlDistributionPointsProfile","assertExtensionCriticality","assertNameConstraintsProfile","assertStoredSubjectAltName","encodeAuthorityInfoAccess","encodeBasicConstraints","encodeCertificatePolicies","encodeCrlDistributionPoints","encodeExtendedKeyUsage","encodeInhibitAnyPolicy","encodeKeyUsage","encodeNameConstraints","encodePolicyConstraints","encodePolicyMappings","encodeSubjectAltName","parseAuthorityInfoAccess","parseAuthorityKeyIdentifier","parseBasicConstraints","parseCertificatePolicies","parseCrlDistributionPoints","parseExtendedKeyUsage","parseInhibitAnyPolicy","parseKeyUsage","parseNameConstraints","parsePolicyConstraints","parsePolicyMappings","parseSubjectAltNames","extensionAppliers","BASIC_CONSTRAINTS_EXTENSION_DEFINITION","valueDer","value","accumulator","KEY_USAGE_EXTENSION_DEFINITION","EXTENDED_KEY_USAGE_EXTENSION_DEFINITION","SUBJECT_ALT_NAME_EXTENSION_DEFINITION","name","ISSUER_ALT_NAME_EXTENSION_DEFINITION","NAME_CONSTRAINTS_EXTENSION_DEFINITION","critical","CERTIFICATE_POLICIES_EXTENSION_DEFINITION","POLICY_MAPPINGS_EXTENSION_DEFINITION","POLICY_CONSTRAINTS_EXTENSION_DEFINITION","INHIBIT_ANY_POLICY_EXTENSION_DEFINITION","AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION","CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION","NO_REV_AVAIL_EXTENSION_DEFINITION","_value","SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION","AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION","CERT_CSR_EXTENSION_DEFINITIONS","EXTENSION_DEFINITION_MAP","definition","oid","context","applier","element"],"sources":["../../../src/internal/x509/extension-registry.ts"],"sourcesContent":["/**\n * Internal extension registry for certificate and CSR parsing.\n *\n * Maps each supported extension OID to a definition that can decode DER,\n * encode input, and apply parsed values to the accumulator used during\n * certificate/CSR parsing.\n *\n * @module\n */\n\nimport { hexToBytes, toHex } from '#micro509/internal/asn1/asn1';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\timplicitPrimitiveContext,\n\tnullValue,\n\toctetString,\n\treadRootElement,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport type { ParsedBitFlags } from '#micro509/internal/x509/extension-bits';\nimport type {\n\tAuthorityInformationAccess,\n\tAuthorityInformationAccessInput,\n\tBasicConstraints,\n\tCertificatePolicies,\n\tDistributionPoint,\n\tExtendedKeyUsage,\n\tInhibitAnyPolicy,\n\tKeyUsage,\n\tNameConstraints,\n\tParsedNameConstraintForm,\n\tPolicyConstraints,\n\tPolicyMappings,\n\tSubjectAltName,\n} from '#micro509/x509/extensions';\nimport {\n\tassertAuthorityInfoAccessProfile,\n\tassertCrlDistributionPointsProfile,\n\tassertExtensionCriticality,\n\tassertNameConstraintsProfile,\n\tassertStoredSubjectAltName,\n\tbuildSubjectKeyIdentifier,\n\tencodeAuthorityInfoAccess,\n\tencodeBasicConstraints,\n\tencodeCertificatePolicies,\n\tencodeCrlDistributionPoints,\n\tencodeExtendedKeyUsage,\n\tencodeInhibitAnyPolicy,\n\tencodeKeyUsage,\n\tencodeNameConstraints,\n\tencodePolicyConstraints,\n\tencodePolicyMappings,\n\tencodeSubjectAltName,\n} from '#micro509/x509/extensions';\nimport type { ParsedDistributionPoint } from '#micro509/x509/parse';\nimport {\n\tparseAuthorityInfoAccess,\n\tparseAuthorityKeyIdentifier,\n\tparseBasicConstraints,\n\tparseCertificatePolicies,\n\tparseCrlDistributionPoints,\n\tparseExtendedKeyUsage,\n\tparseInhibitAnyPolicy,\n\tparseKeyUsage,\n\tparseNameConstraints,\n\tparsePolicyConstraints,\n\tparsePolicyMappings,\n\tparseSubjectAltNames,\n} from '#micro509/x509/parse';\n\n/** Whether an extension applies to certificate parsing, CSR parsing, or both. */\nexport type ExtensionRegistryContext = 'certificate' | 'csr';\n\n/**\n * Readonly snapshot of decoded known extensions collected during parsing.\n *\n * Fields mirror the extension slots on {@linkcode ParsedCertificate}.\n */\nexport interface KnownParsedExtensionAccumulator {\n\t/** Basic Constraints (CA flag + optional pathLength). */\n\treadonly basicConstraints?: BasicConstraints;\n\t/** Key Usage flags (digitalSignature, keyCertSign, etc.). */\n\treadonly keyUsage?: ParsedBitFlags<KeyUsage>;\n\t/** Extended Key Usage purposes (serverAuth, clientAuth, etc.). */\n\treadonly extendedKeyUsage?: readonly ExtendedKeyUsage[];\n\t/** Subject Alternative Names (dns, ip, email, uri, srv, directoryName). */\n\treadonly subjectAltNames?: readonly SubjectAltName[];\n\t/** Issuer Alternative Names (RFC 5280 §4.2.1.7, same GeneralNames syntax). */\n\treadonly issuerAltNames?: readonly SubjectAltName[];\n\t/** Name Constraints (permitted/excluded subtrees). */\n\treadonly nameConstraints?: NameConstraints<ParsedNameConstraintForm>;\n\t/** Certificate Policies extension values. */\n\treadonly certificatePolicies?: CertificatePolicies;\n\t/** Policy Mappings from issuer to subject policy domains. */\n\treadonly policyMappings?: PolicyMappings;\n\t/** Policy Constraints (requireExplicitPolicy / inhibitPolicyMapping). */\n\treadonly policyConstraints?: PolicyConstraints;\n\t/** Inhibit Any-Policy skip-certs value. */\n\treadonly inhibitAnyPolicy?: InhibitAnyPolicy;\n\t/** Authority Information Access (OCSP, CA issuers). */\n\treadonly authorityInfoAccess?: readonly AuthorityInformationAccess[];\n\t/** CRL Distribution Points. */\n\treadonly crlDistributionPoints?: readonly ParsedDistributionPoint[];\n\t/** No Revocation Available (RFC 9608 §2). */\n\treadonly noRevAvail?: true;\n\t/** Hex-encoded Subject Key Identifier. */\n\treadonly subjectKeyIdentifier?: string;\n\t/** Hex-encoded Authority Key Identifier. */\n\treadonly authorityKeyIdentifier?: string;\n}\n\n/**\n * Mutable version of {@linkcode KnownParsedExtensionAccumulator} used during\n * extension parsing to progressively fill in decoded values.\n */\nexport type MutableKnownParsedExtensionAccumulator = {\n\t-readonly [Key in keyof KnownParsedExtensionAccumulator]: KnownParsedExtensionAccumulator[Key];\n};\n\n/**\n * Full lifecycle definition for a known X.509 extension: decode, encode,\n * and apply-to-accumulator during parsing.\n *\n * `TParsed` is the type produced when decoding DER; `TInput` is the type\n * accepted when encoding (they may differ, e.g. for NameConstraints).\n */\nexport interface ExtensionDefinition<TParsed, TInput = TParsed> {\n\t/** Dotted-decimal OID of the extension. */\n\treadonly oid: string;\n\t/** Contexts where this extension is valid (`'certificate'`, `'csr'`, or both). */\n\treadonly contexts: readonly ExtensionRegistryContext[];\n\t/** Whether the extension is marked critical by default when encoding. */\n\treadonly defaultCritical: boolean;\n\t/** When true, the extension is computed by the builder (e.g. SKI, AKI) rather than user-supplied. */\n\treadonly autoGenerated?: boolean;\n\t/** Decode the extension's DER extnValue into a typed value. */\n\tdecode(valueDer: Uint8Array): TParsed;\n\t/** Encode a typed input into the extension's DER extnValue. */\n\tencode(value: TInput): Uint8Array;\n\t/**\n\t * Apply the RFC 5280 profile rules this extension's encoder enforces to an\n\t * already-decoded value, throwing a coded encoder error on violation.\n\t *\n\t * Decoding proves a payload's structure; it does not prove the payload obeys\n\t * the profile, because the parser is deliberately tolerant. Builders route a\n\t * `customExtensions` payload carrying a known OID through here so a raw value\n\t * meets the same bar as the typed input for that extension. Implementations\n\t * delegate to the encoder that owns the rule so the two cannot drift.\n\t *\n\t * Parsing never calls this.\n\t */\n\tassertProfile(value: TParsed, critical: boolean): void;\n\t/** Store a decoded value into the parse-time accumulator. */\n\tapplyParsed(accumulator: MutableKnownParsedExtensionAccumulator, value: TParsed): void;\n}\n\n/**\n * An {@linkcode ExtensionDefinition} after registration, carrying the\n * decode-then-validate closure captured when `TParsed` was concrete.\n */\nexport type RegisteredExtensionDefinition<TParsed, TInput = TParsed> = ExtensionDefinition<\n\tTParsed,\n\tTInput\n> & {\n\t/** Decode a DER extnValue and apply this extension's profile rules to it. */\n\tassertDerProfile(valueDer: Uint8Array, critical: boolean): void;\n};\n\n/**\n * Module-internal decode-and-apply closures, captured at definition time.\n *\n * Each entry is keyed by OID and populated by {@linkcode defineExtensionDefinition}\n * when the concrete generic type is known, avoiding the correlated-union problem\n * that would arise from calling `decode` and `applyParsed` through a union type.\n */\nconst extensionAppliers = new Map<\n\tstring,\n\t(accumulator: MutableKnownParsedExtensionAccumulator, valueDer: Uint8Array) => void\n>();\n\n/** Registry entry for Basic Constraints (OID 2.5.29.19). Critical by default. */\nexport const BASIC_CONSTRAINTS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<BasicConstraints> =\n\tdefineExtensionDefinition<BasicConstraints>({\n\t\toid: OIDS.basicConstraints,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parseBasicConstraints(valueDer),\n\t\tencode: (value) => encodeBasicConstraints(value),\n\t\tassertProfile: (value) => {\n\t\t\tencodeBasicConstraints(value);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.basicConstraints = value;\n\t\t},\n\t});\n\n/** Registry entry for Key Usage (OID 2.5.29.15). Critical by default. */\nexport const KEY_USAGE_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\tParsedBitFlags<KeyUsage>,\n\treadonly KeyUsage[]\n> = defineExtensionDefinition<ParsedBitFlags<KeyUsage>, readonly KeyUsage[]>({\n\toid: OIDS.keyUsage,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: true,\n\tdecode: (valueDer) => parseKeyUsage(valueDer),\n\tencode: (value) => encodeKeyUsage(value),\n\tassertProfile: (value) => {\n\t\tencodeKeyUsage(value.flags);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.keyUsage = value;\n\t},\n});\n\n/** Registry entry for Extended Key Usage (OID 2.5.29.37). Non-critical by default. */\nexport const EXTENDED_KEY_USAGE_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\treadonly ExtendedKeyUsage[]\n> = defineExtensionDefinition<readonly ExtendedKeyUsage[]>({\n\toid: OIDS.extendedKeyUsage,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseExtendedKeyUsage(valueDer),\n\tencode: (value) => encodeExtendedKeyUsage(value),\n\tassertProfile: (value) => {\n\t\tencodeExtendedKeyUsage(value);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.extendedKeyUsage = value;\n\t},\n});\n\n/** Registry entry for Subject Alternative Name (OID 2.5.29.17). Non-critical by default. */\nexport const SUBJECT_ALT_NAME_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\treadonly SubjectAltName[]\n> = defineExtensionDefinition<readonly SubjectAltName[]>({\n\toid: OIDS.subjectAltName,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseSubjectAltNames(valueDer),\n\tencode: (value) => sequence(value.map(encodeSubjectAltName)),\n\tassertProfile: (value) => {\n\t\tfor (const name of value) {\n\t\t\tassertStoredSubjectAltName(name);\n\t\t}\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.subjectAltNames = value;\n\t},\n});\n\n/** Registry entry for Issuer Alternative Name (OID 2.5.29.18). Non-critical by default. */\nexport const ISSUER_ALT_NAME_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\treadonly SubjectAltName[]\n> = defineExtensionDefinition<readonly SubjectAltName[]>({\n\toid: OIDS.issuerAltName,\n\tcontexts: ['certificate'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseSubjectAltNames(valueDer, 'issuerAltName'),\n\tencode: (value) => sequence(value.map(encodeSubjectAltName)),\n\tassertProfile: (value) => {\n\t\tfor (const name of value) {\n\t\t\tassertStoredSubjectAltName(name);\n\t\t}\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.issuerAltNames = value;\n\t},\n});\n\n/** Registry entry for Name Constraints (OID 2.5.29.30). Critical by default. */\nexport const NAME_CONSTRAINTS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\tNameConstraints<ParsedNameConstraintForm>,\n\tNameConstraints\n> = defineExtensionDefinition<NameConstraints<ParsedNameConstraintForm>, NameConstraints>({\n\toid: OIDS.nameConstraints,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: true,\n\tdecode: (valueDer) => parseNameConstraints(valueDer),\n\tencode: (value) => encodeNameConstraints(value),\n\tassertProfile: (value, critical) => {\n\t\tassertNameConstraintsProfile(value);\n\t\tassertExtensionCriticality('nameConstraints', true, critical);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.nameConstraints = value;\n\t},\n});\n\n/** Registry entry for Certificate Policies (OID 2.5.29.32). Non-critical by default. */\nexport const CERTIFICATE_POLICIES_EXTENSION_DEFINITION: RegisteredExtensionDefinition<CertificatePolicies> =\n\tdefineExtensionDefinition<CertificatePolicies>({\n\t\toid: OIDS.certificatePolicies,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: false,\n\t\tdecode: (valueDer) => parseCertificatePolicies(valueDer),\n\t\tencode: (value) => encodeCertificatePolicies(value),\n\t\tassertProfile: (value) => {\n\t\t\tencodeCertificatePolicies(value);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.certificatePolicies = value;\n\t\t},\n\t});\n\n/** Registry entry for Policy Mappings (OID 2.5.29.33). Critical by default. */\nexport const POLICY_MAPPINGS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<PolicyMappings> =\n\tdefineExtensionDefinition<PolicyMappings>({\n\t\toid: OIDS.policyMappings,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parsePolicyMappings(valueDer),\n\t\tencode: (value) => encodePolicyMappings(value),\n\t\tassertProfile: (value) => {\n\t\t\tencodePolicyMappings(value);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.policyMappings = value;\n\t\t},\n\t});\n\n/** Registry entry for Policy Constraints (OID 2.5.29.36). Critical by default. */\nexport const POLICY_CONSTRAINTS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<PolicyConstraints> =\n\tdefineExtensionDefinition<PolicyConstraints>({\n\t\toid: OIDS.policyConstraints,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parsePolicyConstraints(valueDer),\n\t\tencode: (value) => encodePolicyConstraints(value),\n\t\tassertProfile: (value, critical) => {\n\t\t\tencodePolicyConstraints(value);\n\t\t\tassertExtensionCriticality('policyConstraints', true, critical);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.policyConstraints = value;\n\t\t},\n\t});\n\n/** Registry entry for Inhibit anyPolicy (OID 2.5.29.54). Critical by default. */\nexport const INHIBIT_ANY_POLICY_EXTENSION_DEFINITION: RegisteredExtensionDefinition<InhibitAnyPolicy> =\n\tdefineExtensionDefinition<InhibitAnyPolicy>({\n\t\toid: OIDS.inhibitAnyPolicy,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: true,\n\t\tdecode: (valueDer) => parseInhibitAnyPolicy(valueDer),\n\t\tencode: (value) => encodeInhibitAnyPolicy(value),\n\t\tassertProfile: (value, critical) => {\n\t\t\tencodeInhibitAnyPolicy(value);\n\t\t\tassertExtensionCriticality('inhibitAnyPolicy', true, critical);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.inhibitAnyPolicy = value;\n\t\t},\n\t});\n\n/** Registry entry for Authority Information Access (OID 1.3.6.1.5.5.7.1.1). Non-critical. */\nexport const AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\treadonly AuthorityInformationAccess[],\n\treadonly AuthorityInformationAccessInput[]\n> = defineExtensionDefinition<\n\treadonly AuthorityInformationAccess[],\n\treadonly AuthorityInformationAccessInput[]\n>({\n\toid: OIDS.authorityInfoAccess,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseAuthorityInfoAccess(valueDer),\n\tencode: (value) => encodeAuthorityInfoAccess(value),\n\tassertProfile: (value, critical) => {\n\t\tassertAuthorityInfoAccessProfile(value);\n\t\tassertExtensionCriticality('authorityInfoAccess', false, critical);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.authorityInfoAccess = value;\n\t},\n});\n\n/** Registry entry for CRL Distribution Points (OID 2.5.29.31). Non-critical by default. */\nexport const CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\treadonly ParsedDistributionPoint[],\n\treadonly DistributionPoint[]\n> = defineExtensionDefinition<readonly ParsedDistributionPoint[], readonly DistributionPoint[]>({\n\toid: OIDS.cRLDistributionPoints,\n\tcontexts: ['certificate', 'csr'],\n\tdefaultCritical: false,\n\tdecode: (valueDer) => parseCrlDistributionPoints(valueDer),\n\tencode: (value) => encodeCrlDistributionPoints(value),\n\tassertProfile: (value) => {\n\t\tassertCrlDistributionPointsProfile(value);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.crlDistributionPoints = value;\n\t},\n});\n\n/** Registry entry for No Revocation Available (OID 2.5.29.56, RFC 9608 §2). Non-critical. */\nexport const NO_REV_AVAIL_EXTENSION_DEFINITION: RegisteredExtensionDefinition<true> =\n\tdefineExtensionDefinition<true>({\n\t\toid: OIDS.noRevAvail,\n\t\tcontexts: ['certificate', 'csr'],\n\t\tdefaultCritical: false,\n\t\tdecode: (valueDer) => decodeNoRevAvail(valueDer),\n\t\tencode: () => nullValue(),\n\t\tassertProfile: (_value, critical) => {\n\t\t\tassertExtensionCriticality('noRevAvail', false, critical);\n\t\t},\n\t\tapplyParsed: (accumulator, value) => {\n\t\t\taccumulator.noRevAvail = value;\n\t\t},\n\t});\n\n/** Registry entry for Subject Key Identifier (OID 2.5.29.14). Auto-generated; non-critical. */\nexport const SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\tstring,\n\tstring | Uint8Array\n> = defineExtensionDefinition<string, string | Uint8Array>({\n\toid: OIDS.subjectKeyIdentifier,\n\tcontexts: ['certificate'],\n\tdefaultCritical: false,\n\tautoGenerated: true,\n\tdecode: (valueDer) => decodeSubjectKeyIdentifier(valueDer),\n\tencode: (value) => octetString(normalizeKeyIdentifier(value)),\n\tassertProfile: (value, critical) => {\n\t\thexToBytes(value);\n\t\tassertExtensionCriticality('subjectKeyIdentifier', false, critical);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\taccumulator.subjectKeyIdentifier = value;\n\t},\n});\n\n/** Registry entry for Authority Key Identifier (OID 2.5.29.35). Auto-generated; non-critical. */\nexport const AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION: RegisteredExtensionDefinition<\n\tstring | undefined,\n\tstring | Uint8Array\n> = defineExtensionDefinition<string | undefined, string | Uint8Array>({\n\toid: OIDS.authorityKeyIdentifier,\n\tcontexts: ['certificate'],\n\tdefaultCritical: false,\n\tautoGenerated: true,\n\tdecode: (valueDer) => parseAuthorityKeyIdentifier(valueDer),\n\tencode: (value) => sequence([implicitPrimitiveContext(0, normalizeKeyIdentifier(value))]),\n\tassertProfile: (value, critical) => {\n\t\tif (value !== undefined) {\n\t\t\thexToBytes(value);\n\t\t}\n\t\tassertExtensionCriticality('authorityKeyIdentifier', false, critical);\n\t},\n\tapplyParsed: (accumulator, value) => {\n\t\tif (value !== undefined) {\n\t\t\taccumulator.authorityKeyIdentifier = value;\n\t\t}\n\t},\n});\n\n/** Union of all built-in extension definition constants. */\nexport type KnownExtensionDefinition =\n\t| typeof BASIC_CONSTRAINTS_EXTENSION_DEFINITION\n\t| typeof KEY_USAGE_EXTENSION_DEFINITION\n\t| typeof EXTENDED_KEY_USAGE_EXTENSION_DEFINITION\n\t| typeof SUBJECT_ALT_NAME_EXTENSION_DEFINITION\n\t| typeof ISSUER_ALT_NAME_EXTENSION_DEFINITION\n\t| typeof NAME_CONSTRAINTS_EXTENSION_DEFINITION\n\t| typeof CERTIFICATE_POLICIES_EXTENSION_DEFINITION\n\t| typeof POLICY_MAPPINGS_EXTENSION_DEFINITION\n\t| typeof POLICY_CONSTRAINTS_EXTENSION_DEFINITION\n\t| typeof INHIBIT_ANY_POLICY_EXTENSION_DEFINITION\n\t| typeof AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION\n\t| typeof CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION\n\t| typeof NO_REV_AVAIL_EXTENSION_DEFINITION\n\t| typeof SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION\n\t| typeof AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION;\n\n/** All built-in extension definitions, in registration order. */\nexport const CERT_CSR_EXTENSION_DEFINITIONS: readonly KnownExtensionDefinition[] = [\n\tBASIC_CONSTRAINTS_EXTENSION_DEFINITION,\n\tKEY_USAGE_EXTENSION_DEFINITION,\n\tEXTENDED_KEY_USAGE_EXTENSION_DEFINITION,\n\tSUBJECT_ALT_NAME_EXTENSION_DEFINITION,\n\tISSUER_ALT_NAME_EXTENSION_DEFINITION,\n\tNAME_CONSTRAINTS_EXTENSION_DEFINITION,\n\tCERTIFICATE_POLICIES_EXTENSION_DEFINITION,\n\tPOLICY_MAPPINGS_EXTENSION_DEFINITION,\n\tPOLICY_CONSTRAINTS_EXTENSION_DEFINITION,\n\tINHIBIT_ANY_POLICY_EXTENSION_DEFINITION,\n\tAUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION,\n\tCRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION,\n\tNO_REV_AVAIL_EXTENSION_DEFINITION,\n\tSUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n\tAUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n];\n\n/** OID-keyed lookup for known extension definitions. */\nconst EXTENSION_DEFINITION_MAP = new Map<string, KnownExtensionDefinition>(\n\tCERT_CSR_EXTENSION_DEFINITIONS.map((definition) => [definition.oid, definition]),\n);\n\n/**\n * Return all known extension definitions, optionally filtered by context.\n *\n * @param context If provided, only definitions valid in that context are returned.\n */\nexport function listExtensionDefinitions(\n\tcontext?: ExtensionRegistryContext,\n): readonly KnownExtensionDefinition[] {\n\tif (context === undefined) {\n\t\treturn CERT_CSR_EXTENSION_DEFINITIONS;\n\t}\n\treturn CERT_CSR_EXTENSION_DEFINITIONS.filter((definition) =>\n\t\tdefinition.contexts.includes(context),\n\t);\n}\n\n/**\n * Look up a known extension definition by OID.\n *\n * Overloaded for each built-in OID constant to return the exact definition type;\n * the generic `string` form returns the union or `undefined`.\n *\n * @param oid Dotted-decimal extension OID.\n * @returns The matching definition, or `undefined` for unrecognized OIDs.\n */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.basicConstraints,\n): typeof BASIC_CONSTRAINTS_EXTENSION_DEFINITION;\n/** Exact definition for the Key Usage extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.keyUsage,\n): typeof KEY_USAGE_EXTENSION_DEFINITION;\n/** Exact definition for the Extended Key Usage extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.extendedKeyUsage,\n): typeof EXTENDED_KEY_USAGE_EXTENSION_DEFINITION;\n/** Exact definition for the Subject Alternative Name extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.subjectAltName,\n): typeof SUBJECT_ALT_NAME_EXTENSION_DEFINITION;\n/** Exact definition for the Issuer Alternative Name extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.issuerAltName,\n): typeof ISSUER_ALT_NAME_EXTENSION_DEFINITION;\n/** Exact definition for the Name Constraints extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.nameConstraints,\n): typeof NAME_CONSTRAINTS_EXTENSION_DEFINITION;\n/** Exact definition for the Certificate Policies extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.certificatePolicies,\n): typeof CERTIFICATE_POLICIES_EXTENSION_DEFINITION;\n/** Exact definition for the Policy Mappings extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.policyMappings,\n): typeof POLICY_MAPPINGS_EXTENSION_DEFINITION;\n/** Exact definition for the Policy Constraints extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.policyConstraints,\n): typeof POLICY_CONSTRAINTS_EXTENSION_DEFINITION;\n/** Exact definition for the Inhibit Any-Policy extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.inhibitAnyPolicy,\n): typeof INHIBIT_ANY_POLICY_EXTENSION_DEFINITION;\n/** Exact definition for the Authority Information Access extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.authorityInfoAccess,\n): typeof AUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION;\n/** Exact definition for the CRL Distribution Points extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.cRLDistributionPoints,\n): typeof CRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION;\n/** Exact definition for the No Revocation Available extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.noRevAvail,\n): typeof NO_REV_AVAIL_EXTENSION_DEFINITION;\n/** Exact definition for the Subject Key Identifier extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.subjectKeyIdentifier,\n): typeof SUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION;\n/** Exact definition for the Authority Key Identifier extension. */\nexport function getExtensionDefinition(\n\toid: typeof OIDS.authorityKeyIdentifier,\n): typeof AUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION;\n/** Generic lookup: returns the matching definition, or `undefined` for unrecognized OIDs. */\nexport function getExtensionDefinition(oid: string): KnownExtensionDefinition | undefined;\nexport function getExtensionDefinition(oid: string): KnownExtensionDefinition | undefined {\n\treturn EXTENSION_DEFINITION_MAP.get(oid);\n}\n\n/**\n * If `oid` matches a known extension valid in `context`, decode its DER\n * value and store the result in the accumulator.\n *\n * @returns `true` if the extension was recognized and applied.\n */\nexport function decodeAndApplyKnownExtension(\n\tcontext: ExtensionRegistryContext,\n\toid: string,\n\taccumulator: MutableKnownParsedExtensionAccumulator,\n\tvalueDer: Uint8Array,\n): boolean {\n\tconst definition = getExtensionDefinition(oid);\n\tif (definition === undefined || !definition.contexts.includes(context)) {\n\t\treturn false;\n\t}\n\tconst applier = extensionAppliers.get(oid);\n\tif (applier === undefined) {\n\t\treturn false;\n\t}\n\tapplier(accumulator, valueDer);\n\treturn true;\n}\n\n/**\n * Compute a Subject Key Identifier (SHA-1 of the public key bits) from\n * a DER-encoded SubjectPublicKeyInfo.\n */\nexport function buildSubjectKeyIdentifierFromSubjectPublicKeyInfo(\n\tsubjectPublicKeyInfo: Uint8Array,\n): Uint8Array {\n\treturn buildSubjectKeyIdentifier(subjectPublicKeyInfo);\n}\n\n/**\n * Register an {@linkcode ExtensionDefinition} literal, capturing its\n * decode-and-apply and decode-and-validate closures.\n *\n * Both closures are built here, where `TParsed` is concrete, so that\n * `decodeAndApplyKnownExtension` and `assertDerProfile` can be called through the\n * union-typed `KnownExtensionDefinition` without hitting TypeScript's\n * correlated-union limitation.\n */\nfunction defineExtensionDefinition<TParsed, TInput = TParsed>(\n\tdefinition: ExtensionDefinition<TParsed, TInput>,\n): RegisteredExtensionDefinition<TParsed, TInput> {\n\textensionAppliers.set(definition.oid, (accumulator, valueDer) => {\n\t\tdefinition.applyParsed(accumulator, definition.decode(valueDer));\n\t});\n\treturn {\n\t\t...definition,\n\t\tassertDerProfile: (valueDer, critical) => {\n\t\t\tdefinition.assertProfile(definition.decode(valueDer), critical);\n\t\t},\n\t};\n}\n\n/** Accept hex string or Uint8Array and return raw bytes. */\nfunction normalizeKeyIdentifier(value: string | Uint8Array): Uint8Array {\n\treturn typeof value === 'string' ? hexToBytes(value) : value;\n}\n\n/** Decode a noRevAvail extension value, which RFC 9608 §2 defines as NULL. */\nfunction decodeNoRevAvail(valueDer: Uint8Array): true {\n\tconst element = readRootElement(valueDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (element.tag !== 0x05 || element.value.length !== 0) {\n\t\tthrow new Error('noRevAvail must be NULL');\n\t}\n\treturn true;\n}\n\n/** Decode an SKI extension value DER to a hex string. */\nfunction decodeSubjectKeyIdentifier(valueDer: Uint8Array): string {\n\tconst element = readRootElement(valueDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (element.tag !== 0x04) {\n\t\tthrow new Error('SubjectKeyIdentifier must be an OCTET STRING');\n\t}\n\treturn toHex(element.value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgLA,MAAMoC,oBAAoB,IAAI,IAG5B,GAGWC,IACZ,0BAA4C;CAC3C,KAAK9B,EAAK;CACV,UAAU,CAAC,eAAe,KAAK;CAC/B,iBAAiB;CACjB,SAAS+B,MAAaZ,EAAsBY,CAAQ;CACpD,SAASC,MAAUzB,EAAuByB,CAAK;CAC/C,gBAAgBA,MAAU;EACzBzB,EAAuByB,CAAK;CAC7B;CACA,cAAcC,GAAaD,MAAU;EACpCC,EAAY,mBAAmBD;CAChC;AACD,CAAC,GAGWE,IAGT,0BAAyE;CAC5E,KAAKlC,EAAK;CACV,UAAU,CAAC,eAAe,KAAK;CAC/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IwB,EAAW,MAAMpB,GAAaF,MAAa;EAChEsB,EAAW,YAAYpB,GAAaoB,EAAW,OAAOtB,CAAQ,CAAC;CAChE,CAAC,GACM;EACN,GAAGsB;EACH,mBAAmBtB,GAAUS,MAAa;GACzCa,EAAW,cAAcA,EAAW,OAAOtB,CAAQ,GAAGS,CAAQ;EAC/D;CACD;AACD;;AAGA,SAAS,uBAAuBR,GAAwC;CACvE,OAAO,OAAOA,KAAU,WAAWvC,EAAWuC,CAAK,IAAIA;AACxD;;AAGA,SAAS,iBAAiBD,GAA4B;CACrD,IAAM0B,IAAU3D,EAAgBiC,GAAU,EAAE,UAAA,GAAgC,CAAC;CAC7E,IAAI0B,EAAQ,QAAQ,KAAQA,EAAQ,MAAM,WAAW,GACpD,MAAU,MAAM,yBAAyB;CAE1C,OAAO;AACR;;AAGA,SAAS,2BAA2B1B,GAA8B;CACjE,IAAM0B,IAAU3D,EAAgBiC,GAAU,EAAE,UAAA,GAAgC,CAAC;CAC7E,IAAI0B,EAAQ,QAAQ,GACnB,MAAU,MAAM,8CAA8C;CAE/D,OAAO/D,EAAM+D,EAAQ,KAAK;AAC3B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"general-name-profile.js","names":["IDEOGRAPHIC_LABEL_SEPARATORS","value","name","label","domainToAscii","dot","parts","serviceOk","nameOk","subdomains","presentedDomainToAscii","isIpv4Address","VALID","MALFORMED","UNSUPPORTED","DECODABLE_DIRECTORY_STRING_TAGS","element","decodeString","children","inner","childrenOf","source","child","directoryString","checkOrAddressFields","encoding","checkStrictDer","profile","check","readRootElement","checks"],"sources":["../../../src/internal/x509/general-name-profile.ts"],"sourcesContent":["/**\n * Profile validation for GeneralName alternatives whose content micro509\n * checks beyond DER framing: SRVName (RFC 4985, RFC 6335), the URI name\n * constraint, DirectoryString, EDIPartyName, and ORAddress (RFC 5280).\n *\n * @module\n */\n\nimport { checkStrictDer, childrenOf, decodeString } from '#micro509/internal/asn1/asn1';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport { readRootElement } from '#micro509/internal/asn1/der';\nimport { domainToAscii, presentedDomainToAscii } from '#micro509/internal/shared/idna';\nimport { isIpv4Address } from '#micro509/internal/shared/uri-host';\nimport { checkOrAddressFields } from '#micro509/internal/x509/or-address';\n\n/** A SRVName's `_Service` label and Name without its root label, either possibly empty in a restriction. */\nexport interface SrvNameParts {\n\treadonly service: string;\n\treadonly name: string;\n}\n\n/** U+3002, U+FF0E and U+FF61, the label separators RFC 4985 §3 stores as U+002E. */\nconst IDEOGRAPHIC_LABEL_SEPARATORS = /[。.。]/g;\n\n/** Replaces each RFC 4985 §3 label separator with U+002E. */\nexport function normalizeLabelSeparators(value: string): string {\n\treturn value.replace(IDEOGRAPHIC_LABEL_SEPARATORS, '.');\n}\n\n/**\n * RFC 6335 §5.1 service name behind the underscore of a `_Service` label: 1 to\n * 15 letters, digits, and hyphens, at least one letter, and no hyphen at either\n * end or beside another hyphen.\n */\nfunction isServiceLabel(label: string): boolean {\n\tconst name = label.slice(1);\n\treturn (\n\t\tlabel.startsWith('_') &&\n\t\t/^[A-Za-z0-9-]{1,15}$/.test(name) &&\n\t\t/[A-Za-z]/.test(name) &&\n\t\t!name.startsWith('-') &&\n\t\t!name.endsWith('-') &&\n\t\t!name.includes('--')\n\t);\n}\n\n/** RFC 1034 §3.1: an absolute domain name with the dot of its terminal root label removed. */\nfunction withoutRootLabel(name: string): string {\n\treturn name.endsWith('.') ? name.slice(0, -1) : name;\n}\n\n/**\n * RFC 4985 §3 Name under `UseSTD3ASCIIRules`: at most 253 octets of LDH labels\n * of 1 to 63 octets that start and end with a letter or digit, with every\n * `xn--` label an IDNA2008 A-label.\n */\nfunction isSrvDomainName(name: string): boolean {\n\treturn (\n\t\tname.length <= 253 &&\n\t\tname\n\t\t\t.split('.')\n\t\t\t.every((label) => /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(label)) &&\n\t\tdomainToAscii(name, 'lookup').ok\n\t);\n}\n\nfunction splitSrvName(value: string): SrvNameParts {\n\tif (!value.startsWith('_')) {\n\t\treturn { service: '', name: withoutRootLabel(value) };\n\t}\n\tconst dot = value.indexOf('.');\n\treturn dot < 0\n\t\t? { service: value, name: '' }\n\t\t: { service: value.slice(0, dot), name: withoutRootLabel(value.slice(dot + 1)) };\n}\n\n/** RFC 4985 §4: a restriction is `_Service.Name`, `_Service`, or `Name`. */\nexport function parseSrvNameRestriction(value: string): SrvNameParts | undefined {\n\tconst parts = splitSrvName(value);\n\tconst serviceOk = parts.service.length === 0 || isServiceLabel(parts.service);\n\tconst nameOk = (parts.service.length > 0 && !value.includes('.')) || isSrvDomainName(parts.name);\n\treturn serviceOk && nameOk ? parts : undefined;\n}\n\n/** RFC 4985 §2: a presented SRVName is `_Service.Name`. */\nexport function parsePresentedSrvName(value: string): SrvNameParts | undefined {\n\tconst parts = splitSrvName(value);\n\treturn isServiceLabel(parts.service) && isSrvDomainName(parts.name) ? parts : undefined;\n}\n\n/** RFC 5280 §4.2.1.10 URI constraint: every host, one host, or the subdomains of a domain. */\nexport type UriNameConstraint =\n\t| { readonly type: 'any' }\n\t| { readonly type: 'host'; readonly name: string }\n\t| { readonly type: 'subdomains'; readonly name: string };\n\n/** RFC 5280 §4.2.1.10 and Appendix B: a URI constraint holds a DNS name, not a URI. */\nexport function parseUriNameConstraint(value: string): UriNameConstraint | undefined {\n\tif (value.length === 0) return { type: 'any' };\n\tconst subdomains = value.startsWith('.');\n\tconst name = /^[\\x21-\\x7e]+$/.test(value)\n\t\t? presentedDomainToAscii(subdomains ? value.slice(1) : value)\n\t\t: undefined;\n\tif (name === undefined || isIpv4Address(name)) return undefined;\n\treturn subdomains ? { type: 'subdomains', name } : { type: 'host', name };\n}\n\n/** Why a structured GeneralName value failed its profile. */\nexport type GeneralNameContentFailure = 'malformed' | 'unsupported';\n\nexport type GeneralNameContentCheck =\n\t| { readonly ok: true }\n\t| { readonly ok: false; readonly reason: GeneralNameContentFailure };\n\nconst VALID: GeneralNameContentCheck = { ok: true };\nconst MALFORMED: GeneralNameContentCheck = { ok: false, reason: 'malformed' };\nconst UNSUPPORTED: GeneralNameContentCheck = { ok: false, reason: 'unsupported' };\n\nconst TELETEX_STRING = 0x14;\n\n/** DirectoryString alternatives other than TeletexString: PrintableString, UniversalString, UTF8String, BMPString. */\nconst DECODABLE_DIRECTORY_STRING_TAGS: ReadonlySet<number> = new Set([0x13, 0x1c, 0x0c, 0x1e]);\n\n/** RFC 5280 DirectoryString, each alternative `SIZE (1..MAX)`, with TeletexString unsupported. */\nexport function checkDirectoryString(element: DerElement): GeneralNameContentCheck {\n\tif (element.tag === TELETEX_STRING) {\n\t\treturn UNSUPPORTED;\n\t}\n\tif (!DECODABLE_DIRECTORY_STRING_TAGS.has(element.tag) || element.value.length === 0) {\n\t\treturn MALFORMED;\n\t}\n\ttry {\n\t\tdecodeString(element.tag, element.value);\n\t\treturn VALID;\n\t} catch {\n\t\treturn MALFORMED;\n\t}\n}\n\n/**\n * RFC 5280 §4.2.1.6: `EDIPartyName ::= SEQUENCE { nameAssigner [0]\n * DirectoryString OPTIONAL, partyName [1] DirectoryString }`, each tag\n * explicit around its CHOICE.\n */\nexport function checkEdiPartyName(element: Uint8Array): GeneralNameContentCheck {\n\treturn checkStructuredGeneralName(element, (children, source) => {\n\t\tconst partyName = children.at(-1);\n\t\tif (\n\t\t\tpartyName?.tag !== 0xa1 ||\n\t\t\t!(children.length === 1 || (children.length === 2 && children[0]?.tag === 0xa0))\n\t\t) {\n\t\t\treturn MALFORMED;\n\t\t}\n\t\treturn firstFailure(\n\t\t\tchildren.map((child) => {\n\t\t\t\tconst inner = childrenOf(source, child);\n\t\t\t\tconst directoryString = inner[0];\n\t\t\t\treturn inner.length === 1 && directoryString !== undefined\n\t\t\t\t\t? checkDirectoryString(directoryString)\n\t\t\t\t\t: MALFORMED;\n\t\t\t}),\n\t\t);\n\t});\n}\n\n/** RFC 5280 Appendix A.1 ORAddress, with its fields checked against their schema. */\nexport function checkOrAddress(element: Uint8Array): GeneralNameContentCheck {\n\treturn checkStructuredGeneralName(element, checkOrAddressFields);\n}\n\nfunction checkStructuredGeneralName(\n\telement: Uint8Array,\n\tcheck: (children: readonly DerElement[], source: Uint8Array) => GeneralNameContentCheck,\n): GeneralNameContentCheck {\n\tconst encoding = checkStrictDer(element);\n\tif (encoding === 'malformed') {\n\t\treturn MALFORMED;\n\t}\n\ttry {\n\t\tconst profile = check(childrenOf(element, readRootElement(element)), element);\n\t\treturn profile.ok && encoding === 'unsupported' ? UNSUPPORTED : profile;\n\t} catch {\n\t\treturn MALFORMED;\n\t}\n}\n\nfunction firstFailure(checks: readonly GeneralNameContentCheck[]): GeneralNameContentCheck {\n\treturn checks.find((check) => !check.ok) ?? VALID;\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAMA,IAA+B;;AAGrC,SAAgB,yBAAyB,GAAuB;CAC/D,OAAOC,EAAM,QAAQD,GAA8B,GAAG;AACvD;;;;;;AAOA,SAAS,eAAe,GAAwB;CAC/C,IAAME,IAAOC,EAAM,MAAM,CAAC;CAC1B,OACCA,EAAM,WAAW,GAAG,KACpB,uBAAuB,KAAKD,CAAI,KAChC,WAAW,KAAKA,CAAI,KACpB,CAACA,EAAK,WAAW,GAAG,KACpB,CAACA,EAAK,SAAS,GAAG,KAClB,CAACA,EAAK,SAAS,IAAI;AAErB;;AAGA,SAAS,iBAAiB,GAAsB;CAC/C,OAAOA,EAAK,SAAS,GAAG,IAAIA,EAAK,MAAM,GAAG,EAAE,IAAIA;AACjD;;;;;;AAOA,SAAS,gBAAgB,GAAuB;CAC/C,OACCA,EAAK,UAAU,OACfA,EACE,MAAM,GAAG,CAAC,CACV,OAAO,MAAU,kDAAkD,KAAKC,CAAK,CAAC,KAChFC,EAAcF,GAAM,QAAQ,CAAC,CAAC;AAEhC;AAEA,SAAS,aAAa,GAA6B;CAClD,IAAI,CAACD,EAAM,WAAW,GAAG,GACxB,OAAO;EAAE,SAAS;E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;CAClF,IAAIC,EAAQ,QAAQ,IACnB,OAAOF;CAER,IAAI,CAACC,EAAgC,IAAIC,EAAQ,GAAG,KAAKA,EAAQ,MAAM,WAAW,GACjF,OAAOH;CAER,IAAI;EAEH,OADAI,EAAaD,EAAQ,KAAKA,EAAQ,KAAK,GAChCJ;CACR,QAAQ;EACP,OAAOC;CACR;AACD;;;;;;AAOA,SAAgB,kBAAkB,GAA8C;CAC/E,OAAO,2BAA2BG,IAAU,GAAU,MACnCE,EAAS,GAAG,EAErB,CAAC,EAAE,QAAQ,OACnB,EAAEA,EAAS,WAAW,KAAMA,EAAS,WAAW,KAAKA,EAAS,EAAE,EAAE,QAAQ,OAEnEL,IAED,aACNK,EAAS,KAAK,MAAU;EACvB,IAAMC,IAAQC,EAAWC,GAAQC,CAAK,GAChCC,IAAkBJ,EAAM;EAC9B,OAAOA,EAAM,WAAW,KAAKI,MAAoB,KAAA,IAC9C,qBAAqBA,CAAe,IACpCV;CACJ,CAAC,CACF,CACA;AACF;;AAGA,SAAgB,eAAe,GAA8C;CAC5E,OAAO,2BAA2BG,GAASQ,CAAoB;AAChE;AAEA,SAAS,2BACR,GACA,GAC0B;CAC1B,IAAMC,IAAWC,EAAeV,CAAO;CACvC,IAAIS,MAAa,aAChB,OAAOZ;CAER,IAAI;EACH,IAAMc,IAAUC,EAAMR,EAAWJ,GAASa,EAAgBb,CAAO,CAAC,GAAGA,CAAO;EAC5E,OAAOW,EAAQ,MAAMF,MAAa,gBAAgBX,IAAca;CACjE,QAAQ;EACP,OAAOd;CACR;AACD;AAEA,SAAS,aAAa,GAAqE;CAC1F,OAAOiB,EAAO,MAAM,MAAU,CAACF,EAAM,EAAE,KAAKhB;AAC7C"}
|
|
1
|
+
{"version":3,"file":"general-name-profile.js","names":["checkStrictDer","childrenOf","decodeString","readRootElement","domainToAscii","presentedDomainToAscii","isIpv4Address","checkOrAddressFields","IDEOGRAPHIC_LABEL_SEPARATORS","value","label","name","dot","parts","serviceOk","nameOk","subdomains","VALID","MALFORMED","UNSUPPORTED","DECODABLE_DIRECTORY_STRING_TAGS","element","children","source","child","inner","directoryString","check","encoding","profile","checks"],"sources":["../../../src/internal/x509/general-name-profile.ts"],"sourcesContent":["/**\n * Profile validation for GeneralName alternatives whose content micro509\n * checks beyond DER framing: SRVName (RFC 4985, RFC 6335), the URI name\n * constraint, DirectoryString, EDIPartyName, and ORAddress (RFC 5280).\n *\n * @module\n */\n\nimport { checkStrictDer, childrenOf, decodeString } from '#micro509/internal/asn1/asn1';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport { readRootElement } from '#micro509/internal/asn1/der';\nimport { domainToAscii, presentedDomainToAscii } from '#micro509/internal/shared/idna';\nimport { isIpv4Address } from '#micro509/internal/shared/uri-host';\nimport { checkOrAddressFields } from '#micro509/internal/x509/or-address';\n\n/** A SRVName's `_Service` label and Name without its root label, either possibly empty in a restriction. */\nexport interface SrvNameParts {\n\treadonly service: string;\n\treadonly name: string;\n}\n\n/** U+3002, U+FF0E and U+FF61, the label separators RFC 4985 §3 stores as U+002E. */\nconst IDEOGRAPHIC_LABEL_SEPARATORS = /[。.。]/g;\n\n/** Replaces each RFC 4985 §3 label separator with U+002E. */\nexport function normalizeLabelSeparators(value: string): string {\n\treturn value.replace(IDEOGRAPHIC_LABEL_SEPARATORS, '.');\n}\n\n/**\n * RFC 6335 §5.1 service name behind the underscore of a `_Service` label: 1 to\n * 15 letters, digits, and hyphens, at least one letter, and no hyphen at either\n * end or beside another hyphen.\n */\nfunction isServiceLabel(label: string): boolean {\n\tconst name = label.slice(1);\n\treturn (\n\t\tlabel.startsWith('_') &&\n\t\t/^[A-Za-z0-9-]{1,15}$/.test(name) &&\n\t\t/[A-Za-z]/.test(name) &&\n\t\t!name.startsWith('-') &&\n\t\t!name.endsWith('-') &&\n\t\t!name.includes('--')\n\t);\n}\n\n/** RFC 1034 §3.1: an absolute domain name with the dot of its terminal root label removed. */\nfunction withoutRootLabel(name: string): string {\n\treturn name.endsWith('.') ? name.slice(0, -1) : name;\n}\n\n/**\n * RFC 4985 §3 Name under `UseSTD3ASCIIRules`: at most 253 octets of LDH labels\n * of 1 to 63 octets that start and end with a letter or digit, with every\n * `xn--` label an IDNA2008 A-label.\n */\nfunction isSrvDomainName(name: string): boolean {\n\treturn (\n\t\tname.length <= 253 &&\n\t\tname\n\t\t\t.split('.')\n\t\t\t.every((label) => /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(label)) &&\n\t\tdomainToAscii(name, 'lookup').ok\n\t);\n}\n\nfunction splitSrvName(value: string): SrvNameParts {\n\tif (!value.startsWith('_')) {\n\t\treturn { service: '', name: withoutRootLabel(value) };\n\t}\n\tconst dot = value.indexOf('.');\n\treturn dot < 0\n\t\t? { service: value, name: '' }\n\t\t: { service: value.slice(0, dot), name: withoutRootLabel(value.slice(dot + 1)) };\n}\n\n/** RFC 4985 §4: a restriction is `_Service.Name`, `_Service`, or `Name`. */\nexport function parseSrvNameRestriction(value: string): SrvNameParts | undefined {\n\tconst parts = splitSrvName(value);\n\tconst serviceOk = parts.service.length === 0 || isServiceLabel(parts.service);\n\tconst nameOk = (parts.service.length > 0 && !value.includes('.')) || isSrvDomainName(parts.name);\n\treturn serviceOk && nameOk ? parts : undefined;\n}\n\n/** RFC 4985 §2: a presented SRVName is `_Service.Name`. */\nexport function parsePresentedSrvName(value: string): SrvNameParts | undefined {\n\tconst parts = splitSrvName(value);\n\treturn isServiceLabel(parts.service) && isSrvDomainName(parts.name) ? parts : undefined;\n}\n\n/** RFC 5280 §4.2.1.10 URI constraint: every host, one host, or the subdomains of a domain. */\nexport type UriNameConstraint =\n\t| { readonly type: 'any' }\n\t| { readonly type: 'host'; readonly name: string }\n\t| { readonly type: 'subdomains'; readonly name: string };\n\n/** RFC 5280 §4.2.1.10 and Appendix B: a URI constraint holds a DNS name, not a URI. */\nexport function parseUriNameConstraint(value: string): UriNameConstraint | undefined {\n\tif (value.length === 0) return { type: 'any' };\n\tconst subdomains = value.startsWith('.');\n\tconst name = /^[\\x21-\\x7e]+$/.test(value)\n\t\t? presentedDomainToAscii(subdomains ? value.slice(1) : value)\n\t\t: undefined;\n\tif (name === undefined || isIpv4Address(name)) return undefined;\n\treturn subdomains ? { type: 'subdomains', name } : { type: 'host', name };\n}\n\n/** Why a structured GeneralName value failed its profile. */\nexport type GeneralNameContentFailure = 'malformed' | 'unsupported';\n\nexport type GeneralNameContentCheck =\n\t| { readonly ok: true }\n\t| { readonly ok: false; readonly reason: GeneralNameContentFailure };\n\nconst VALID: GeneralNameContentCheck = { ok: true };\nconst MALFORMED: GeneralNameContentCheck = { ok: false, reason: 'malformed' };\nconst UNSUPPORTED: GeneralNameContentCheck = { ok: false, reason: 'unsupported' };\n\nconst TELETEX_STRING = 0x14;\n\n/** DirectoryString alternatives other than TeletexString: PrintableString, UniversalString, UTF8String, BMPString. */\nconst DECODABLE_DIRECTORY_STRING_TAGS: ReadonlySet<number> = new Set([0x13, 0x1c, 0x0c, 0x1e]);\n\n/** RFC 5280 DirectoryString, each alternative `SIZE (1..MAX)`, with TeletexString unsupported. */\nexport function checkDirectoryString(element: DerElement): GeneralNameContentCheck {\n\tif (element.tag === TELETEX_STRING) {\n\t\treturn UNSUPPORTED;\n\t}\n\tif (!DECODABLE_DIRECTORY_STRING_TAGS.has(element.tag) || element.value.length === 0) {\n\t\treturn MALFORMED;\n\t}\n\ttry {\n\t\tdecodeString(element.tag, element.value);\n\t\treturn VALID;\n\t} catch {\n\t\treturn MALFORMED;\n\t}\n}\n\n/**\n * RFC 5280 §4.2.1.6: `EDIPartyName ::= SEQUENCE { nameAssigner [0]\n * DirectoryString OPTIONAL, partyName [1] DirectoryString }`, each tag\n * explicit around its CHOICE.\n */\nexport function checkEdiPartyName(element: Uint8Array): GeneralNameContentCheck {\n\treturn checkStructuredGeneralName(element, (children, source) => {\n\t\tconst partyName = children.at(-1);\n\t\tif (\n\t\t\tpartyName?.tag !== 0xa1 ||\n\t\t\t!(children.length === 1 || (children.length === 2 && children[0]?.tag === 0xa0))\n\t\t) {\n\t\t\treturn MALFORMED;\n\t\t}\n\t\treturn firstFailure(\n\t\t\tchildren.map((child) => {\n\t\t\t\tconst inner = childrenOf(source, child);\n\t\t\t\tconst directoryString = inner[0];\n\t\t\t\treturn inner.length === 1 && directoryString !== undefined\n\t\t\t\t\t? checkDirectoryString(directoryString)\n\t\t\t\t\t: MALFORMED;\n\t\t\t}),\n\t\t);\n\t});\n}\n\n/** RFC 5280 Appendix A.1 ORAddress, with its fields checked against their schema. */\nexport function checkOrAddress(element: Uint8Array): GeneralNameContentCheck {\n\treturn checkStructuredGeneralName(element, checkOrAddressFields);\n}\n\nfunction checkStructuredGeneralName(\n\telement: Uint8Array,\n\tcheck: (children: readonly DerElement[], source: Uint8Array) => GeneralNameContentCheck,\n): GeneralNameContentCheck {\n\tconst encoding = checkStrictDer(element);\n\tif (encoding === 'malformed') {\n\t\treturn MALFORMED;\n\t}\n\ttry {\n\t\tconst profile = check(childrenOf(element, readRootElement(element)), element);\n\t\treturn profile.ok && encoding === 'unsupported' ? UNSUPPORTED : profile;\n\t} catch {\n\t\treturn MALFORMED;\n\t}\n}\n\nfunction firstFailure(checks: readonly GeneralNameContentCheck[]): GeneralNameContentCheck {\n\treturn checks.find((check) => !check.ok) ?? VALID;\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAMQ,IAA+B;;AAGrC,SAAgB,yBAAyBC,GAAuB;CAC/D,OAAOA,EAAM,QAAQD,GAA8B,GAAG;AACvD;;;;;;AAOA,SAAS,eAAeE,GAAwB;CAC/C,IAAMC,IAAOD,EAAM,MAAM,CAAC;CAC1B,OACCA,EAAM,WAAW,GAAG,KACpB,uBAAuB,KAAKC,CAAI,KAChC,WAAW,KAAKA,CAAI,KACpB,CAACA,EAAK,WAAW,GAAG,KACpB,CAACA,EAAK,SAAS,GAAG,KAClB,CAACA,EAAK,SAAS,IAAI;AAErB;;AAGA,SAAS,iBAAiBA,GAAsB;CAC/C,OA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