micro509 0.4.0 → 0.6.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/README.md +6 -6
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/internal/asn1/oids.js +1 -1
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/verify/name-constraints-engine.js +1 -1
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/revocation/chain.d.ts +22 -1
- package/dist/revocation/chain.js +1 -1
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +44 -6
- package/dist/revocation/ocsp.js +1 -1
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +3 -3
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +2 -2
- package/dist/revocation.js +1 -1
- package/dist/verify/identity.d.ts +2 -2
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/verify.d.ts +2 -0
- package/dist/verify/verify.js +1 -1
- package/dist/verify/verify.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chain.js","names":[],"sources":["../../src/revocation/chain.ts"],"sourcesContent":["/**\n * Chain-level revocation orchestration.\n *\n * Evaluates CRL and OCSP evidence for an entire validated certificate chain,\n * implementing the revocation checking portion of RFC 5280 §6.3.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#section-6.3 | RFC 5280 §6.3 CRL Validation}\n * @module\n */\n\nimport type { ParsedCertificate } from '#micro509/x509/parse.ts';\nimport { parseCertificateFromSource } from '#micro509/x509/parse.ts';\nimport {\n\tcheckCertificateRevocationAgainstCrl,\n\tparseCertificateRevocationListDer,\n\tparseCertificateRevocationListPem,\n\ttype ParsedCertificateRevocationList,\n\ttype RevocationReason,\n\trevocationReasonFromCode,\n} from './crl.ts';\nimport type { CrlSource } from './crl.ts';\nimport {\n\ttype ParsedOcspResponse,\n\tparseOcspResponseDer,\n\tparseOcspResponsePem,\n\ttype ValidateOcspResponseFailure,\n\ttype ValidateOcspResponseResult,\n\tvalidateOcspResponse,\n} from './ocsp.ts';\n\nexport type { CrlSource };\n\n// ---------------------------------------------------------------------------\n// Input Types\n// ---------------------------------------------------------------------------\n\n/**\n * Certificate in any supported format.\n *\n * Accepts PEM string, DER bytes, or an already-parsed {@linkcode ParsedCertificate}.\n * Used for {@linkcode CheckChainRevocationInput.extraCertificates}.\n */\nexport type CertificateSource = string | Uint8Array | ParsedCertificate;\n\n/**\n * OCSP response in any supported format.\n *\n * Accepts PEM string or DER bytes. Used for\n * {@linkcode CheckChainRevocationInput.ocspResponses}.\n */\nexport type OcspResponseSource = string | Uint8Array;\n\n/**\n * Revocation checking policy for {@linkcode checkChainRevocation}.\n *\n * Controls how indeterminate results (missing evidence, expired CRLs) affect\n * the final {@linkcode CheckChainRevocationValue.decision | decision}.\n */\nexport interface RevocationPolicy {\n\t/**\n\t * How to handle indeterminate status.\n\t *\n\t * - `'soft-fail'`: indeterminate certificates are allowed (default)\n\t * - `'hard-fail'`: indeterminate certificates cause denial\n\t */\n\treadonly mode?: 'soft-fail' | 'hard-fail';\n\t/**\n\t * Evidence preference when multiple sources are available.\n\t *\n\t * Both evidence kinds are always evaluated, and a validated `revoked`\n\t * verdict from either source wins regardless of preference (fail-closed).\n\t * Preference only decides which source's `good` verdict is reported when\n\t * both yield one.\n\t *\n\t * - `'best-available'`: OCSP consulted first, CRL as fallback (default)\n\t * - `'ocsp'`: prefer OCSP over CRL\n\t * - `'crl'`: prefer CRL over OCSP\n\t */\n\treadonly prefer?: 'ocsp' | 'crl' | 'best-available';\n}\n\n/** Input for {@linkcode checkChainRevocation}. */\nexport interface CheckChainRevocationInput {\n\t/** Validated certificate chain (leaf first, root last). */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** CRLs to evaluate. */\n\treadonly crls?: readonly CrlSource[];\n\t/** OCSP responses to evaluate. */\n\treadonly ocspResponses?: readonly OcspResponseSource[];\n\t/** Extra certs for indirect CRL issuers / delegated OCSP responders. */\n\treadonly extraCertificates?: readonly CertificateSource[];\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/** Revocation policy. */\n\treadonly policy?: RevocationPolicy;\n}\n\n// ---------------------------------------------------------------------------\n// Output Types\n// ---------------------------------------------------------------------------\n\n/**\n * Granular reasons why revocation status could not be determined.\n *\n * Returned in {@linkcode CertificateRevocationStatus.indeterminateReasons} when\n * `status` is `'indeterminate'`. Grouped by category:\n *\n * - **Evidence not found**: `no_applicable_crl`, `no_applicable_ocsp`\n * - **Scope mismatch**: `distribution_point_mismatch`, `issuer_name_mismatch`,\n * `reason_scope_mismatch`, `indirect_crl_scope_mismatch`, `reason_coverage_incomplete`\n * - **Signer trust**: `crl_signer_not_found`, `crl_signer_not_authorized`,\n * `crl_signer_revoked`, `crl_signer_indeterminate`, and OCSP equivalents\n * - **Freshness**: `crl_expired`, `ocsp_response_expired`\n */\nexport type RevocationIndeterminateReason =\n\t// Evidence not found\n\t| 'no_applicable_crl'\n\t| 'no_applicable_ocsp'\n\t// Scope issues\n\t| 'distribution_point_mismatch'\n\t| 'issuer_name_mismatch'\n\t| 'reason_scope_mismatch'\n\t| 'indirect_crl_scope_mismatch'\n\t| 'reason_coverage_incomplete'\n\t// Signer trust issues\n\t| 'crl_signer_not_found'\n\t| 'crl_signer_not_authorized'\n\t| 'crl_signer_revoked'\n\t| 'crl_signer_indeterminate'\n\t| 'ocsp_responder_not_found'\n\t| 'ocsp_responder_not_authorized'\n\t| 'ocsp_responder_revoked'\n\t| 'ocsp_responder_indeterminate'\n\t// Freshness\n\t| 'crl_expired'\n\t| 'ocsp_response_expired'\n\t// OCSP specific\n\t| 'ocsp_status_unknown';\n\n/**\n * Identifies the source of revocation evidence.\n *\n * Included in {@linkcode CertificateRevocationStatus.source} when status is\n * `'good'` or `'revoked'` to indicate which CRL or OCSP response provided the answer.\n */\nexport interface RevocationSource {\n\t/** Whether evidence came from a CRL or OCSP response. */\n\treadonly type: 'crl' | 'ocsp';\n\t/** Certificate that signed the evidence (CRL issuer or OCSP responder). */\n\treadonly signerCertificate?: ParsedCertificate;\n\t/** Identifier for debugging (e.g., CRL issuer DN or OCSP responder URL). */\n\treadonly evidenceIdentifier?: string;\n}\n\n/**\n * Revocation evaluation result for a single certificate.\n *\n * One entry per certificate in {@linkcode CheckChainRevocationValue.certificates}.\n * The trust anchor is excluded (never checked for revocation).\n */\nexport interface CertificateRevocationStatus {\n\t/** The certificate that was evaluated. */\n\treadonly certificate: ParsedCertificate;\n\t/**\n\t * Revocation status determination.\n\t *\n\t * - `'good'`: evidence confirms certificate is not revoked\n\t * - `'revoked'`: evidence confirms certificate is revoked\n\t * - `'indeterminate'`: could not determine status (see {@linkcode indeterminateReasons})\n\t */\n\treadonly status: 'good' | 'revoked' | 'indeterminate';\n\t/** Evidence source when status is `'good'` or `'revoked'`. */\n\treadonly source?: RevocationSource;\n\t/** Why status could not be determined. Present when `status` is `'indeterminate'`. */\n\treadonly indeterminateReasons?: readonly RevocationIndeterminateReason[];\n\t/** Revocation details. Present when `status` is `'revoked'`. */\n\treadonly revocationInfo?: {\n\t\t/** When the certificate was revoked. */\n\t\treadonly date: Date;\n\t\t/** RFC 5280 CRLReason code, if provided by the CRL/OCSP response. */\n\t\treadonly reason?: RevocationReason;\n\t};\n}\n\n/**\n * Errors encountered while processing revocation evidence.\n *\n * Distinct from {@linkcode RevocationIndeterminateReason}: execution errors are\n * code failures (malformed CRL, unsupported extension) rather than evaluation\n * outcomes (CRL doesn't cover this certificate).\n *\n * Collected in {@linkcode CheckChainRevocationValue.executionErrors}.\n */\nexport interface RevocationExecutionError {\n\t/** Error category. */\n\treadonly kind: 'parse_error' | 'unsupported_extension' | 'internal_error';\n\t/** Human-readable error description. */\n\treadonly message: string;\n\t/** Which evidence caused the error (e.g., CRL issuer DN). */\n\treadonly evidenceIdentifier?: string;\n}\n\n/**\n * Detailed revocation check results.\n *\n * Returned as {@linkcode CheckChainRevocationResult.value} from\n * {@linkcode checkChainRevocation}. Contains both the policy decision and\n * detailed per-certificate findings for debugging.\n */\nexport interface CheckChainRevocationValue {\n\t/**\n\t * Final policy decision based on {@linkcode RevocationPolicy}.\n\t *\n\t * - `'allow'`: chain passes revocation check\n\t * - `'deny'`: chain fails (revoked certificate or hard-fail on indeterminate)\n\t */\n\treadonly decision: 'allow' | 'deny';\n\t/** Quick-access summary of problematic certificates. */\n\treadonly summary: {\n\t\t/** Certificates confirmed as revoked. */\n\t\treadonly revokedCertificates: readonly ParsedCertificate[];\n\t\t/** Certificates whose status could not be determined. */\n\t\treadonly indeterminateCertificates: readonly ParsedCertificate[];\n\t};\n\t/** Per-certificate evaluation results. See {@linkcode CertificateRevocationStatus}. */\n\treadonly certificates: readonly CertificateRevocationStatus[];\n\t/** Evidence that could not be processed. See {@linkcode RevocationExecutionError}. */\n\treadonly executionErrors?: readonly RevocationExecutionError[];\n}\n\n/** Result type for {@linkcode checkChainRevocation}. */\nexport type CheckChainRevocationResult = {\n\treadonly ok: true;\n\treadonly value: CheckChainRevocationValue;\n};\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parses a CRL from various source formats.\n */\nfunction parseCrlFromSource(source: CrlSource): ParsedCertificateRevocationList {\n\tif (typeof source === 'object' && 'issuer' in source) {\n\t\treturn source;\n\t}\n\tif (typeof source === 'string') {\n\t\treturn parseCertificateRevocationListPem(source);\n\t}\n\treturn parseCertificateRevocationListDer(source);\n}\n\n/**\n * Parses a certificate from various source formats, returning undefined on failure.\n */\nfunction parseCertificateSafe(source: CertificateSource): ParsedCertificate | undefined {\n\ttry {\n\t\treturn parseCertificateFromSource(source);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Compares two certificates by DER bytes for identity.\n * Reference equality fails when same cert is parsed from different sources.\n */\nfunction sameCertificate(a: ParsedCertificate, b: ParsedCertificate): boolean {\n\tif (a.der.length !== b.der.length) return false;\n\tfor (let i = 0; i < a.der.length; i++) {\n\t\tif (a.der[i] !== b.der[i]) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Searches for a certificate that could have signed the given CRL.\n * Matches by AKI/SKI or issuer/subject DN.\n */\nfunction findIndirectCrlIssuer(\n\tcrl: ParsedCertificateRevocationList,\n\textraCertificates: readonly CertificateSource[],\n\tchain: readonly ParsedCertificate[],\n): ParsedCertificate | undefined {\n\t// Combine extra certs with chain certs for searching\n\t// Chain certs are already parsed; extra certs may need parsing\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...parsedExtras, ...chain];\n\n\t// First pass: prefer AKI/SKI match (more specific)\n\tif (crl.authorityKeyIdentifier !== undefined) {\n\t\tfor (const candidate of candidates) {\n\t\t\tif (\n\t\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\t\tnormalizeHex(crl.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t\t) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: fall back to DN match\n\tfor (const candidate of candidates) {\n\t\tif (crl.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/** Lowercases a hex string for bytewise comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n// ---------------------------------------------------------------------------\n// CRL Signer Validation (RFC 5280 §6.3.3)\n// ---------------------------------------------------------------------------\n\n/**\n * State machine for CRL signer validation with memoization.\n * - `visiting`: Currently being checked (cycle detection)\n * - `resolved-valid`: Signer is not revoked\n * - `resolved-revoked`: Signer is revoked\n * - `resolved-indeterminate`: Can't determine signer status\n */\ntype SignerValidationState =\n\t| 'visiting'\n\t| 'resolved-valid'\n\t| 'resolved-revoked'\n\t| 'resolved-indeterminate';\n\n/** Context for CRL signer validation with memoization cache. */\ninterface SignerValidationContext {\n\treadonly cache: Map<string, SignerValidationState>;\n\treadonly chain: readonly ParsedCertificate[];\n\treadonly crls: readonly CrlSource[];\n\treadonly extraCertificates: readonly CertificateSource[];\n\treadonly at: Date;\n}\n\n/**\n * Builds a unique cache key for a certificate.\n * Uses issuer DN + serial number which uniquely identifies a cert.\n */\nfunction certCacheKey(cert: ParsedCertificate): string {\n\treturn `${cert.issuer.derHex}:${cert.serialNumberHex}`;\n}\n\n/**\n * Validates that a CRL signer certificate is not revoked.\n * Uses memoization to avoid redundant checks and detect cycles.\n */\nasync function validateCrlSigner(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// Use issuer+serial as cache key (unique per certificate)\n\tconst key = certCacheKey(signer);\n\tconst cached = ctx.cache.get(key);\n\n\t// Cycle detection: if we're already visiting this signer, it's indeterminate\n\tif (cached === 'visiting') {\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Return cached result if already resolved\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\t// Mark as visiting before recursive checks\n\tctx.cache.set(key, 'visiting');\n\n\t// Trust anchor (last in chain) is trusted by definition\n\tconst trustAnchor = ctx.chain[ctx.chain.length - 1];\n\tif (trustAnchor !== undefined && sameCertificate(signer, trustAnchor)) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// If signer is in the validated chain, it's trusted\n\t// (Chain was already validated before revocation checking)\n\tconst isInChain = ctx.chain.some((c) => sameCertificate(c, signer));\n\tif (isInChain) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// Signer is not in chain — need to check its revocation status\n\t// Find signer's issuer to perform revocation check\n\tconst signerIssuer = findSignerIssuer(signer, ctx);\n\tif (signerIssuer === undefined) {\n\t\tctx.cache.set(key, 'resolved-indeterminate');\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Check signer's revocation status (recursive)\n\tconst signerRevocation = await checkSignerRevocation(signer, signerIssuer, ctx);\n\tctx.cache.set(key, signerRevocation);\n\treturn signerRevocation;\n}\n\n/**\n * Finds the issuer certificate for a CRL signer.\n * Searches the chain and extraCertificates by AKI/SKI or DN matching.\n */\nfunction findSignerIssuer(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): ParsedCertificate | undefined {\n\t// Parse extra certificates\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of ctx.extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...ctx.chain, ...parsedExtras];\n\n\tfor (const candidate of candidates) {\n\t\t// Match by AKI → SKI (preferred, more specific)\n\t\tif (\n\t\t\tsigner.authorityKeyIdentifier !== undefined &&\n\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\tnormalizeHex(signer.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t) {\n\t\t\treturn candidate;\n\t\t}\n\n\t\t// Match by issuer DN → subject DN\n\t\tif (signer.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Checks if a CRL signer certificate is revoked by examining available CRLs.\n * Recursively validates the CRL signer of any CRL used to check revocation.\n */\nasync function checkSignerRevocation(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// If the signer's issuer is in the validated chain, the signer is trusted\n\t// by virtue of being issued by a trusted CA. We only need to check if\n\t// it's explicitly revoked, not prove \"good\" status.\n\tconst issuerInChain = ctx.chain.some((c) => sameCertificate(c, issuer));\n\n\t// Try each CRL to check signer's revocation\n\tfor (const crlSource of ctx.crls) {\n\t\tlet crl: ParsedCertificateRevocationList;\n\t\ttry {\n\t\t\tcrl = parseCrlFromSource(crlSource);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if this CRL can provide revocation info for the signer\n\t\tconst result = await checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: signer,\n\t\t\tissuerCertificate: issuer,\n\t\t\tcrl,\n\t\t\tat: ctx.at,\n\t\t});\n\n\t\tif (result.ok) {\n\t\t\tif (result.value.status === 'revoked') {\n\t\t\t\treturn 'resolved-revoked';\n\t\t\t}\n\t\t\tif (result.value.status === 'good') {\n\t\t\t\t// Before accepting this result, validate the CRL's signer\n\t\t\t\t// The CRL's signer is the issuer we just used\n\t\t\t\tconst crlSignerStatus = await validateCrlSigner(issuer, ctx);\n\t\t\t\tif (crlSignerStatus === 'resolved-valid') {\n\t\t\t\t\treturn 'resolved-valid';\n\t\t\t\t}\n\t\t\t\t// If CRL signer is revoked or indeterminate, can't trust this result\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the signer's issuer is in the chain and we found no revocation,\n\t// trust the signer (issued by trusted CA, no evidence of revocation)\n\tif (issuerInChain) {\n\t\treturn 'resolved-valid';\n\t}\n\n\treturn 'resolved-indeterminate';\n}\n\n/** Builds a CertificateRevocationStatus for a CRL check result. */\nfunction buildCrlStatus(\n\tcert: ParsedCertificate,\n\tsigner: ParsedCertificate,\n\tstatus: 'good' | 'revoked',\n\trevocationDate?: Date,\n\treasonCode?: RevocationReason,\n): CertificateRevocationStatus {\n\tif (status === 'revoked' && revocationDate !== undefined) {\n\t\treturn {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'revoked',\n\t\t\tsource: { type: 'crl', signerCertificate: signer },\n\t\t\trevocationInfo: {\n\t\t\t\tdate: revocationDate,\n\t\t\t\t...(reasonCode !== undefined ? { reason: reasonCode } : {}),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tcertificate: cert,\n\t\tstatus: 'good',\n\t\tsource: { type: 'crl', signerCertificate: signer },\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// OCSP Evidence Evaluation (RFC 6960)\n// ---------------------------------------------------------------------------\n\n/** Per-certificate evidence evaluation outcome shared by the CRL and OCSP evaluators. */\ninterface EvidenceEvaluation {\n\treadonly status: CertificateRevocationStatus;\n\treadonly executionErrors: readonly RevocationExecutionError[];\n}\n\n/** Parses an OCSP response from PEM string or DER bytes. */\nfunction parseOcspResponseFromSource(source: OcspResponseSource): ParsedOcspResponse {\n\tif (typeof source === 'string') {\n\t\treturn parseOcspResponsePem(source);\n\t}\n\treturn parseOcspResponseDer(source);\n}\n\n/** Maps a {@linkcode validateOcspResponse} failure code to an indeterminate reason. */\nfunction ocspIndeterminateReasonFromFailure(\n\tcode: ValidateOcspResponseFailure['code'],\n): RevocationIndeterminateReason {\n\tswitch (code) {\n\t\tcase 'stale_response':\n\t\t\treturn 'ocsp_response_expired';\n\t\tcase 'responder_id_mismatch':\n\t\tcase 'responder_chain_invalid':\n\t\tcase 'ocsp_signing_missing':\n\t\t\treturn 'ocsp_responder_not_authorized';\n\t\tcase 'signature_invalid':\n\t\t\treturn 'ocsp_responder_indeterminate';\n\t\tcase 'response_status_invalid':\n\t\tcase 'issuer_mismatch':\n\t\tcase 'nonce_mismatch':\n\t\tcase 'request_mismatch':\n\t\t\treturn 'no_applicable_ocsp';\n\t}\n}\n\n/** Validation failures worth retrying with an explicit responder certificate. */\nconst OCSP_RESPONDER_FAILURE_CODES: ReadonlySet<ValidateOcspResponseFailure['code']> = new Set([\n\t'signature_invalid',\n\t'responder_id_mismatch',\n\t'responder_chain_invalid',\n\t'ocsp_signing_missing',\n]);\n\n/**\n * Validates an OCSP response, retrying with caller-provided extra certificates\n * as explicit responder certificates when embedded discovery fails.\n */\nasync function validateOcspResponseWithResponderFallback(\n\tresponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\textraCertificates: readonly CertificateSource[],\n\tat: Date,\n): Promise<ValidateOcspResponseResult> {\n\tconst primary = await validateOcspResponse({ response, issuerCertificate: issuer, at });\n\tif (primary.ok || !OCSP_RESPONDER_FAILURE_CODES.has(primary.code)) {\n\t\treturn primary;\n\t}\n\tfor (const source of extraCertificates) {\n\t\tconst responder = parseCertificateSafe(source);\n\t\tif (responder === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst retry = await validateOcspResponse({\n\t\t\tresponse,\n\t\t\tissuerCertificate: issuer,\n\t\t\tresponderCertificate: responder,\n\t\t\tat,\n\t\t});\n\t\tif (retry.ok) {\n\t\t\treturn retry;\n\t\t}\n\t}\n\treturn primary;\n}\n\n/**\n * Evaluates OCSP evidence for a single certificate (RFC 6960).\n *\n * Every response is fully validated — signature, responder binding and\n * authorization, and freshness — via {@linkcode validateOcspResponse} before\n * its status entry is trusted. Issuer binding of each CertID is enforced by\n * the validator, so a serial-number match on a validated response is\n * sufficient to attribute the entry to `cert`.\n */\nasync function evaluateOcspEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n): Promise<EvidenceEvaluation> {\n\tconst { ocspResponses = [], extraCertificates = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\n\tfor (const source of ocspResponses) {\n\t\tlet parsed: ParsedOcspResponse;\n\t\ttry {\n\t\t\tparsed = parseOcspResponseFromSource(source);\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'OCSP response parse failed',\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst entry = (parsed.responses ?? []).find(\n\t\t\t(single) =>\n\t\t\t\tnormalizeHex(single.certId.serialNumberHex) === normalizeHex(cert.serialNumberHex),\n\t\t);\n\t\tif (entry === undefined) {\n\t\t\tcontinue; // Response does not cover this certificate\n\t\t}\n\n\t\tconst validation = await validateOcspResponseWithResponderFallback(\n\t\t\tparsed,\n\t\t\tissuer,\n\t\t\textraCertificates,\n\t\t\tat,\n\t\t);\n\t\tif (!validation.ok) {\n\t\t\treasons.add(ocspIndeterminateReasonFromFailure(validation.code));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.certStatus === 'revoked') {\n\t\t\tconst reason = revocationReasonFromCode(entry.revocationReasonCode);\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'revoked',\n\t\t\t\t\tsource: { type: 'ocsp' },\n\t\t\t\t\trevocationInfo: {\n\t\t\t\t\t\tdate: entry.revokedAt ?? entry.thisUpdate,\n\t\t\t\t\t\t...(reason !== undefined ? { reason } : {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\tif (entry.certStatus === 'good') {\n\t\t\treturn {\n\t\t\t\tstatus: { certificate: cert, status: 'good', source: { type: 'ocsp' } },\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\treasons.add('ocsp_status_unknown');\n\t}\n\n\tif (reasons.size === 0) {\n\t\treasons.add('no_applicable_ocsp');\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate using available CRLs.\n * Returns both status and any execution errors encountered.\n *\n * Tries the chain issuer first; if that fails, searches extraCertificates\n * and chain for an indirect CRL issuer that matches the CRL's AKI or issuer DN.\n *\n * Also validates that CRL signers are not revoked (RFC 5280 §6.3.3).\n */\n// RFC 5280 ReasonFlags — all possible revocation reasons that CRLs can cover.\nconst ALL_REASON_FLAGS: readonly string[] = [\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];\n\nasync function evaluateCrlEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst { crls = [], extraCertificates = [], chain = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tlet sawCrlSignerRevoked = false;\n\tlet sawCrlSignerIndeterminate = false;\n\tlet sawGood = false;\n\tlet lastGoodSigner: ParsedCertificate | undefined;\n\tconst coveredReasons = new Set<string>();\n\n\t// Parse all CRLs and separate base CRLs from delta CRLs\n\tconst parsedCrls: ParsedCertificateRevocationList[] = [];\n\tfor (const crlSource of crls) {\n\t\ttry {\n\t\t\tparsedCrls.push(parseCrlFromSource(crlSource));\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'CRL parse failed',\n\t\t\t});\n\t\t}\n\t}\n\n\tconst baseCrls = parsedCrls.filter((crl) => crl.baseCrlNumber === undefined);\n\tconst deltaCrls = parsedCrls.filter((crl) => crl.baseCrlNumber !== undefined);\n\n\t// Helper to check CRL with given issuer and optional delta\n\tconst checkWithIssuer = async (\n\t\tcrl: ParsedCertificateRevocationList,\n\t\tdeltaCrl: ParsedCertificateRevocationList | undefined,\n\t\tcrlIssuer: ParsedCertificate,\n\t) => {\n\t\treturn checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: cert,\n\t\t\tissuerCertificate: crlIssuer,\n\t\t\tcrl,\n\t\t\t...(deltaCrl !== undefined ? { deltaCrl } : {}),\n\t\t\tat,\n\t\t});\n\t};\n\n\t// Process base CRLs (optionally paired with delta CRLs)\n\tfor (const baseCrl of baseCrls) {\n\t\t// Find applicable delta CRL for this base CRL (if any)\n\t\t// Delta CRL applies if it has the same issuer and crlNumber matches baseCrlNumber\n\t\tconst applicableDelta = deltaCrls.find(\n\t\t\t(d) =>\n\t\t\t\td.issuer.derHex === baseCrl.issuer.derHex &&\n\t\t\t\td.baseCrlNumber !== undefined &&\n\t\t\t\tbaseCrl.crlNumber !== undefined &&\n\t\t\t\tBigInt(d.baseCrlNumber) <= BigInt(baseCrl.crlNumber),\n\t\t);\n\n\t\t// Try chain issuer first\n\t\tlet result = await checkWithIssuer(baseCrl, applicableDelta, issuer);\n\t\tlet effectiveSigner = issuer;\n\n\t\t// Chain issuer failed — try to find indirect CRL issuer\n\t\tif (!result.ok) {\n\t\t\tconst indirectIssuer = findIndirectCrlIssuer(baseCrl, extraCertificates, chain);\n\t\t\tif (indirectIssuer !== undefined && !sameCertificate(indirectIssuer, issuer)) {\n\t\t\t\tresult = await checkWithIssuer(baseCrl, applicableDelta, indirectIssuer);\n\t\t\t\teffectiveSigner = indirectIssuer;\n\t\t\t}\n\t\t}\n\n\t\tif (!result.ok) {\n\t\t\tcontinue; // CRL doesn't apply to this certificate\n\t\t}\n\n\t\t// Validate CRL signer is not revoked before accepting result\n\t\tconst signerStatus = await validateCrlSigner(effectiveSigner, signerCtx);\n\t\tif (signerStatus === 'resolved-revoked') {\n\t\t\tsawCrlSignerRevoked = true;\n\t\t\tcontinue; // CRL signer revoked — can't trust this CRL\n\t\t}\n\t\tif (signerStatus === 'resolved-indeterminate') {\n\t\t\tsawCrlSignerIndeterminate = true;\n\t\t\tcontinue; // CRL signer status unknown — try other CRLs\n\t\t}\n\n\t\t// CRL is valid — check result\n\t\tif (result.value.status === 'revoked') {\n\t\t\t// Immediately return revoked status\n\t\t\treturn {\n\t\t\t\tstatus: buildCrlStatus(\n\t\t\t\t\tcert,\n\t\t\t\t\teffectiveSigner,\n\t\t\t\t\t'revoked',\n\t\t\t\t\tresult.value.revocationDate,\n\t\t\t\t\tresult.value.reasonCode,\n\t\t\t\t),\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\n\t\t// Status is 'good' — track which reasons this CRL covers\n\t\tsawGood = true;\n\t\tlastGoodSigner = effectiveSigner;\n\t\tconst crlReasons = baseCrl.issuingDistributionPoint?.onlySomeReasons?.flags;\n\t\tif (crlReasons === undefined) {\n\t\t\t// CRL covers all reasons\n\t\t\tfor (const reason of ALL_REASON_FLAGS) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t} else {\n\t\t\t// CRL only covers specific reasons\n\t\t\tfor (const reason of crlReasons) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return 'good' only if we saw at least one good result AND all reasons are covered\n\tif (sawGood) {\n\t\tconst allReasonsCovered = ALL_REASON_FLAGS.every((r) => coveredReasons.has(r));\n\t\tif (allReasonsCovered) {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\t...(lastGoodSigner !== undefined\n\t\t\t\t\t\t? { source: { type: 'crl', signerCertificate: lastGoodSigner } }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\t// Not all reasons covered — indeterminate\n\t\treturn {\n\t\t\tstatus: {\n\t\t\t\tcertificate: cert,\n\t\t\t\tstatus: 'indeterminate',\n\t\t\t\tindeterminateReasons: ['reason_coverage_incomplete'],\n\t\t\t},\n\t\t\texecutionErrors,\n\t\t};\n\t}\n\n\t// No applicable CRL found — determine most appropriate indeterminate reason\n\tconst reasons: RevocationIndeterminateReason[] = [];\n\tif (sawCrlSignerRevoked) {\n\t\treasons.push('crl_signer_revoked');\n\t} else if (sawCrlSignerIndeterminate) {\n\t\treasons.push('crl_signer_indeterminate');\n\t} else {\n\t\treasons.push('no_applicable_crl');\n\t}\n\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: reasons,\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate by combining OCSP and\n * CRL evidence.\n *\n * Both evidence kinds are always evaluated: a validated `revoked` verdict from\n * either source wins regardless of {@linkcode RevocationPolicy.prefer}\n * (fail-closed). Otherwise the preferred source's `good` verdict is reported;\n * if neither source is definitive, indeterminate reasons from both are merged.\n */\nasync function evaluateCertificateRevocation(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst prefer = input.policy?.prefer ?? 'best-available';\n\tconst ocsp = await evaluateOcspEvidence(cert, issuer, input);\n\tconst crl = await evaluateCrlEvidence(cert, issuer, input, signerCtx);\n\tconst executionErrors = [...ocsp.executionErrors, ...crl.executionErrors];\n\n\tconst ordered = prefer === 'crl' ? [crl, ocsp] : [ocsp, crl];\n\tconst revoked = ordered.find((evaluation) => evaluation.status.status === 'revoked');\n\tif (revoked !== undefined) {\n\t\treturn { status: revoked.status, executionErrors };\n\t}\n\tconst good = ordered.find((evaluation) => evaluation.status.status === 'good');\n\tif (good !== undefined) {\n\t\treturn { status: good.status, executionErrors };\n\t}\n\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\tfor (const evaluation of ordered) {\n\t\tfor (const reason of evaluation.status.indeterminateReasons ?? []) {\n\t\t\treasons.add(reason);\n\t\t}\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Function\n// ---------------------------------------------------------------------------\n\n/**\n * Checks revocation status for all certificates in a validated chain.\n *\n * Evaluates CRL and OCSP evidence against each certificate (except the trust\n * anchor), applies the revocation policy, and returns a unified decision.\n *\n * @example\n * ```ts\n * const result = await checkChainRevocation({\n * chain: validatedChain,\n * crls: [crl1, crl2],\n * ocspResponses: [ocspResponseDer],\n * policy: { mode: 'hard-fail' },\n * });\n * if (result.value.decision === 'deny') {\n * console.log('Revocation check failed');\n * }\n * ```\n */\nexport async function checkChainRevocation(\n\tinput: CheckChainRevocationInput,\n): Promise<CheckChainRevocationResult> {\n\tconst { chain, policy, crls = [], extraCertificates = [], at = new Date() } = input;\n\tconst mode = policy?.mode ?? 'soft-fail';\n\n\t// Empty chain → allow\n\tif (chain.length === 0) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tdecision: 'allow',\n\t\t\t\tsummary: { revokedCertificates: [], indeterminateCertificates: [] },\n\t\t\t\tcertificates: [],\n\t\t\t},\n\t\t};\n\t}\n\n\t// Create signer validation context with memoization cache\n\t// This cache is shared across all certificate checks in this chain evaluation\n\tconst signerCtx: SignerValidationContext = {\n\t\tcache: new Map(),\n\t\tchain,\n\t\tcrls,\n\t\textraCertificates,\n\t\tat,\n\t};\n\n\t// Skip trust anchor (last cert) — it's the trust base\n\tconst certsToCheck = chain.slice(0, -1);\n\tconst certificates: CertificateRevocationStatus[] = [];\n\tconst revokedCertificates: ParsedCertificate[] = [];\n\tconst indeterminateCertificates: ParsedCertificate[] = [];\n\tconst allExecutionErrors: RevocationExecutionError[] = [];\n\n\tfor (let i = 0; i < certsToCheck.length; i++) {\n\t\tconst cert = certsToCheck[i];\n\t\tconst issuer = chain[i + 1]; // Next cert in chain is the issuer\n\t\tif (cert === undefined || issuer === undefined) {\n\t\t\tcontinue; // Should never happen given loop bounds\n\t\t}\n\n\t\tconst { status, executionErrors } = await evaluateCertificateRevocation(\n\t\t\tcert,\n\t\t\tissuer,\n\t\t\tinput,\n\t\t\tsignerCtx,\n\t\t);\n\t\tcertificates.push(status);\n\t\tallExecutionErrors.push(...executionErrors);\n\n\t\tif (status.status === 'revoked') {\n\t\t\trevokedCertificates.push(cert);\n\t\t} else if (status.status === 'indeterminate') {\n\t\t\tindeterminateCertificates.push(cert);\n\t\t}\n\t}\n\n\t// Apply policy\n\tconst hasRevoked = revokedCertificates.length > 0;\n\tconst hasIndeterminate = indeterminateCertificates.length > 0;\n\tconst decision: 'allow' | 'deny' = hasRevoked\n\t\t? 'deny'\n\t\t: hasIndeterminate && mode === 'hard-fail'\n\t\t\t? 'deny'\n\t\t\t: 'allow';\n\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tdecision,\n\t\t\tsummary: { revokedCertificates, indeterminateCertificates },\n\t\t\tcertificates,\n\t\t\t...(allExecutionErrors.length > 0 ? { executionErrors: allExecutionErrors } : {}),\n\t\t},\n\t};\n}\n"],"mappings":"+UAmPA,SAAS,EAAmB,EAAoD,CAO/E,OANI,OAAO,GAAW,UAAY,WAAY,EACtC,EAEJ,OAAO,GAAW,SACd,EAAkC,CAAM,EAEzC,EAAkC,CAAM,CAChD,CAKA,SAAS,EAAqB,EAA0D,CACvF,GAAI,CACH,OAAO,EAA2B,CAAM,CACzC,MAAQ,CACP,MACD,CACD,CAMA,SAAS,EAAgB,EAAsB,EAA+B,CAC7E,GAAI,EAAE,IAAI,SAAW,EAAE,IAAI,OAAQ,MAAO,GAC1C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAE,IAAI,OAAQ,IACjC,GAAI,EAAE,IAAI,KAAO,EAAE,IAAI,GAAI,MAAO,GAEnC,MAAO,EACR,CAMA,SAAS,EACR,EACA,EACA,EACgC,CAGhC,IAAM,EAAoC,CAAC,EAC3C,IAAK,IAAM,KAAU,EAAmB,CACvC,IAAM,EAAS,EAAqB,CAAM,EACtC,IAAW,IAAA,IACd,EAAa,KAAK,CAAM,CAE1B,CAEA,IAAM,EAAa,CAAC,GAAG,EAAc,GAAG,CAAK,EAG7C,GAAI,EAAI,yBAA2B,IAAA,QAC7B,IAAM,KAAa,EACvB,GACC,EAAU,uBAAyB,IAAA,IACnC,EAAa,EAAI,sBAAsB,IAAM,EAAa,EAAU,oBAAoB,EAExF,OAAO,CAAA,CAMV,IAAK,IAAM,KAAa,EACvB,GAAI,EAAI,OAAO,SAAW,EAAU,QAAQ,OAC3C,OAAO,CAKV,CAGA,SAAS,EAAa,EAAuB,CAC5C,OAAO,EAAM,YAAY,CA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CAAC,EAClD,EAAiD,CAAC,EAExD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAa,OAAQ,IAAK,CAC7C,IAAM,EAAO,EAAa,GACpB,EAAS,EAAM,EAAI,GACzB,GAAI,IAAS,IAAA,IAAa,IAAW,IAAA,GACpC,SAGD,GAAM,CAAE,SAAQ,mBAAoB,MAAM,EACzC,EACA,EACA,EACA,CACD,EACA,EAAa,KAAK,CAAM,EACxB,EAAmB,KAAK,GAAG,CAAe,EAEtC,EAAO,SAAW,UACrB,EAAoB,KAAK,CAAI,EACnB,EAAO,SAAW,iBAC5B,EAA0B,KAAK,CAAI,CAErC,CAGA,IAAM,EAAa,EAAoB,OAAS,EAC1C,EAAmB,EAA0B,OAAS,EAO5D,MAAO,CACN,GAAI,GACJ,MAAO,CACN,SATiC,GAEhC,GAAoB,IAAS,YAD7B,OAGC,QAMF,QAAS,CAAE,sBAAqB,2BAA0B,EAC1D,eACA,GAAI,EAAmB,OAAS,EAAI,CAAE,gBAAiB,CAAmB,EAAI,CAAC,CAChF,CACD,CACD"}
|
|
1
|
+
{"version":3,"file":"chain.js","names":[],"sources":["../../src/revocation/chain.ts"],"sourcesContent":["/**\n * Chain-level revocation orchestration.\n *\n * Evaluates CRL and OCSP evidence for an entire validated certificate chain,\n * implementing the revocation checking portion of RFC 5280 §6.3.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#section-6.3 | RFC 5280 §6.3 CRL Validation}\n * @module\n */\n\nimport type { ParsedCertificate } from '#micro509/x509/parse.ts';\nimport { parseCertificateFromSource } from '#micro509/x509/parse.ts';\nimport {\n\tcheckCertificateRevocationAgainstCrl,\n\tparseCertificateRevocationListDer,\n\tparseCertificateRevocationListPem,\n\ttype ParsedCertificateRevocationList,\n\ttype RevocationReason,\n\trevocationReasonFromCode,\n} from './crl.ts';\nimport type { CrlSource } from './crl.ts';\nimport {\n\ttype OcspResponderRevocationPolicy,\n\ttype ParsedOcspResponse,\n\tparseOcspResponseDer,\n\tparseOcspResponsePem,\n\ttype ValidateOcspResponseFailure,\n\ttype ValidateOcspResponseResult,\n\tvalidateOcspResponse,\n} from './ocsp.ts';\n\nexport type { CrlSource };\n\n// ---------------------------------------------------------------------------\n// Input Types\n// ---------------------------------------------------------------------------\n\n/**\n * Certificate in any supported format.\n *\n * Accepts PEM string, DER bytes, or an already-parsed {@linkcode ParsedCertificate}.\n * Used for {@linkcode CheckChainRevocationInput.extraCertificates}.\n */\nexport type CertificateSource = string | Uint8Array | ParsedCertificate;\n\n/**\n * OCSP response in any supported format.\n *\n * Accepts PEM string or DER bytes. Used for\n * {@linkcode CheckChainRevocationInput.ocspResponses}.\n */\nexport type OcspResponseSource = string | Uint8Array;\n\n/**\n * Revocation checking policy for {@linkcode checkChainRevocation}.\n *\n * Controls how indeterminate results (missing evidence, expired CRLs) affect\n * the final {@linkcode CheckChainRevocationValue.decision | decision}.\n */\nexport interface RevocationPolicy {\n\t/**\n\t * How to handle indeterminate status.\n\t *\n\t * - `'soft-fail'`: indeterminate certificates are allowed (default)\n\t * - `'hard-fail'`: indeterminate certificates cause denial\n\t */\n\treadonly mode?: 'soft-fail' | 'hard-fail';\n\t/**\n\t * Evidence preference when multiple sources are available.\n\t *\n\t * Both evidence kinds are always evaluated, and a validated `revoked`\n\t * verdict from either source wins regardless of preference (fail-closed).\n\t * Preference only decides which source's `good` verdict is reported when\n\t * both yield one.\n\t *\n\t * - `'best-available'`: the source with the fresher evidence — the later\n\t * `thisUpdate` on the validated OCSP entry or CRL — is reported; ties\n\t * favor OCSP (default)\n\t * - `'ocsp'`: prefer OCSP over CRL\n\t * - `'crl'`: prefer CRL over OCSP\n\t */\n\treadonly prefer?: 'ocsp' | 'crl' | 'best-available';\n\t/**\n\t * Revocation policy for delegated OCSP responder certificates\n\t * (RFC 6960 §4.2.2.2.1). Supplied CRLs double as responder revocation\n\t * evidence. Defaults to `'honor-nocheck'`.\n\t */\n\treadonly ocspResponderRevocation?: OcspResponderRevocationPolicy;\n}\n\n/** Input for {@linkcode checkChainRevocation}. */\nexport interface CheckChainRevocationInput {\n\t/** Validated certificate chain (leaf first, root last). */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** CRLs to evaluate. */\n\treadonly crls?: readonly CrlSource[];\n\t/** OCSP responses to evaluate. */\n\treadonly ocspResponses?: readonly OcspResponseSource[];\n\t/** Extra certs for indirect CRL issuers / delegated OCSP responders. */\n\treadonly extraCertificates?: readonly CertificateSource[];\n\t/**\n\t * Explicitly trusted OCSP responder certificates (RFC 6960 §4.2.2.2\n\t * criterion 1). A response signed by one of these is accepted without\n\t * delegated-responder issuance, EKU, and revocation checks.\n\t */\n\treadonly trustedOcspResponders?: readonly CertificateSource[];\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/** Revocation policy. */\n\treadonly policy?: RevocationPolicy;\n}\n\n// ---------------------------------------------------------------------------\n// Output Types\n// ---------------------------------------------------------------------------\n\n/**\n * Granular reasons why revocation status could not be determined.\n *\n * Returned in {@linkcode CertificateRevocationStatus.indeterminateReasons} when\n * `status` is `'indeterminate'`. Grouped by category:\n *\n * - **Evidence not found**: `no_applicable_crl`, `no_applicable_ocsp`\n * - **Scope mismatch**: `distribution_point_mismatch`, `issuer_name_mismatch`,\n * `reason_scope_mismatch`, `indirect_crl_scope_mismatch`, `reason_coverage_incomplete`\n * - **Signer trust**: `crl_signer_not_found`, `crl_signer_not_authorized`,\n * `crl_signer_revoked`, `crl_signer_indeterminate`, and OCSP equivalents\n * - **Freshness**: `crl_expired`, `ocsp_response_expired`\n */\nexport type RevocationIndeterminateReason =\n\t// Evidence not found\n\t| 'no_applicable_crl'\n\t| 'no_applicable_ocsp'\n\t// Scope issues\n\t| 'distribution_point_mismatch'\n\t| 'issuer_name_mismatch'\n\t| 'reason_scope_mismatch'\n\t| 'indirect_crl_scope_mismatch'\n\t| 'reason_coverage_incomplete'\n\t// Signer trust issues\n\t| 'crl_signer_not_found'\n\t| 'crl_signer_not_authorized'\n\t| 'crl_signer_revoked'\n\t| 'crl_signer_indeterminate'\n\t| 'ocsp_responder_not_found'\n\t| 'ocsp_responder_not_authorized'\n\t| 'ocsp_responder_revoked'\n\t| 'ocsp_responder_indeterminate'\n\t// Freshness\n\t| 'crl_expired'\n\t| 'ocsp_response_expired'\n\t// OCSP specific\n\t| 'ocsp_status_unknown';\n\n/**\n * Identifies the source of revocation evidence.\n *\n * Included in {@linkcode CertificateRevocationStatus.source} when status is\n * `'good'` or `'revoked'` to indicate which CRL or OCSP response provided the answer.\n */\nexport interface RevocationSource {\n\t/** Whether evidence came from a CRL or OCSP response. */\n\treadonly type: 'crl' | 'ocsp';\n\t/** Certificate that signed the evidence (CRL issuer or OCSP responder). */\n\treadonly signerCertificate?: ParsedCertificate;\n\t/** Identifier for debugging (e.g., CRL issuer DN or OCSP responder URL). */\n\treadonly evidenceIdentifier?: string;\n\t/**\n\t * `thisUpdate` of the evidence backing the verdict — the OCSP single\n\t * response entry or the freshest contributing CRL (an applied delta CRL\n\t * supersedes its base). This is the timestamp `'best-available'` compares.\n\t */\n\treadonly thisUpdate?: Date;\n}\n\n/**\n * Revocation evaluation result for a single certificate.\n *\n * One entry per certificate in {@linkcode CheckChainRevocationValue.certificates}.\n * The trust anchor is excluded (never checked for revocation).\n */\nexport interface CertificateRevocationStatus {\n\t/** The certificate that was evaluated. */\n\treadonly certificate: ParsedCertificate;\n\t/**\n\t * Revocation status determination.\n\t *\n\t * - `'good'`: evidence confirms certificate is not revoked\n\t * - `'revoked'`: evidence confirms certificate is revoked\n\t * - `'indeterminate'`: could not determine status (see {@linkcode indeterminateReasons})\n\t */\n\treadonly status: 'good' | 'revoked' | 'indeterminate';\n\t/** Evidence source when status is `'good'` or `'revoked'`. */\n\treadonly source?: RevocationSource;\n\t/** Why status could not be determined. Present when `status` is `'indeterminate'`. */\n\treadonly indeterminateReasons?: readonly RevocationIndeterminateReason[];\n\t/** Revocation details. Present when `status` is `'revoked'`. */\n\treadonly revocationInfo?: {\n\t\t/** When the certificate was revoked. */\n\t\treadonly date: Date;\n\t\t/** RFC 5280 CRLReason code, if provided by the CRL/OCSP response. */\n\t\treadonly reason?: RevocationReason;\n\t};\n}\n\n/**\n * Errors encountered while processing revocation evidence.\n *\n * Distinct from {@linkcode RevocationIndeterminateReason}: execution errors are\n * code failures (malformed CRL, unsupported extension) rather than evaluation\n * outcomes (CRL doesn't cover this certificate).\n *\n * Collected in {@linkcode CheckChainRevocationValue.executionErrors}.\n */\nexport interface RevocationExecutionError {\n\t/** Error category. */\n\treadonly kind: 'parse_error' | 'unsupported_extension' | 'internal_error';\n\t/** Human-readable error description. */\n\treadonly message: string;\n\t/** Which evidence caused the error (e.g., CRL issuer DN). */\n\treadonly evidenceIdentifier?: string;\n}\n\n/**\n * Detailed revocation check results.\n *\n * Returned as {@linkcode CheckChainRevocationResult.value} from\n * {@linkcode checkChainRevocation}. Contains both the policy decision and\n * detailed per-certificate findings for debugging.\n */\nexport interface CheckChainRevocationValue {\n\t/**\n\t * Final policy decision based on {@linkcode RevocationPolicy}.\n\t *\n\t * - `'allow'`: chain passes revocation check\n\t * - `'deny'`: chain fails (revoked certificate or hard-fail on indeterminate)\n\t */\n\treadonly decision: 'allow' | 'deny';\n\t/** Quick-access summary of problematic certificates. */\n\treadonly summary: {\n\t\t/** Certificates confirmed as revoked. */\n\t\treadonly revokedCertificates: readonly ParsedCertificate[];\n\t\t/** Certificates whose status could not be determined. */\n\t\treadonly indeterminateCertificates: readonly ParsedCertificate[];\n\t};\n\t/** Per-certificate evaluation results. See {@linkcode CertificateRevocationStatus}. */\n\treadonly certificates: readonly CertificateRevocationStatus[];\n\t/** Evidence that could not be processed. See {@linkcode RevocationExecutionError}. */\n\treadonly executionErrors?: readonly RevocationExecutionError[];\n}\n\n/** Result type for {@linkcode checkChainRevocation}. */\nexport type CheckChainRevocationResult = {\n\treadonly ok: true;\n\treadonly value: CheckChainRevocationValue;\n};\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parses a CRL from various source formats.\n */\nfunction parseCrlFromSource(source: CrlSource): ParsedCertificateRevocationList {\n\tif (typeof source === 'object' && 'issuer' in source) {\n\t\treturn source;\n\t}\n\tif (typeof source === 'string') {\n\t\treturn parseCertificateRevocationListPem(source);\n\t}\n\treturn parseCertificateRevocationListDer(source);\n}\n\n/**\n * Parses a certificate from various source formats, returning undefined on failure.\n */\nfunction parseCertificateSafe(source: CertificateSource): ParsedCertificate | undefined {\n\ttry {\n\t\treturn parseCertificateFromSource(source);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Compares two certificates by DER bytes for identity.\n * Reference equality fails when same cert is parsed from different sources.\n */\nfunction sameCertificate(a: ParsedCertificate, b: ParsedCertificate): boolean {\n\tif (a.der.length !== b.der.length) return false;\n\tfor (let i = 0; i < a.der.length; i++) {\n\t\tif (a.der[i] !== b.der[i]) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Searches for a certificate that could have signed the given CRL.\n * Matches by AKI/SKI or issuer/subject DN.\n */\nfunction findIndirectCrlIssuer(\n\tcrl: ParsedCertificateRevocationList,\n\textraCertificates: readonly CertificateSource[],\n\tchain: readonly ParsedCertificate[],\n): ParsedCertificate | undefined {\n\t// Combine extra certs with chain certs for searching\n\t// Chain certs are already parsed; extra certs may need parsing\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...parsedExtras, ...chain];\n\n\t// First pass: prefer AKI/SKI match (more specific)\n\tif (crl.authorityKeyIdentifier !== undefined) {\n\t\tfor (const candidate of candidates) {\n\t\t\tif (\n\t\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\t\tnormalizeHex(crl.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t\t) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: fall back to DN match\n\tfor (const candidate of candidates) {\n\t\tif (crl.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/** Lowercases a hex string for bytewise comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n// ---------------------------------------------------------------------------\n// CRL Signer Validation (RFC 5280 §6.3.3)\n// ---------------------------------------------------------------------------\n\n/**\n * State machine for CRL signer validation with memoization.\n * - `visiting`: Currently being checked (cycle detection)\n * - `resolved-valid`: Signer is not revoked\n * - `resolved-revoked`: Signer is revoked\n * - `resolved-indeterminate`: Can't determine signer status\n */\ntype SignerValidationState =\n\t| 'visiting'\n\t| 'resolved-valid'\n\t| 'resolved-revoked'\n\t| 'resolved-indeterminate';\n\n/** Context for CRL signer validation with memoization cache. */\ninterface SignerValidationContext {\n\treadonly cache: Map<string, SignerValidationState>;\n\treadonly chain: readonly ParsedCertificate[];\n\treadonly crls: readonly CrlSource[];\n\treadonly extraCertificates: readonly CertificateSource[];\n\treadonly at: Date;\n}\n\n/**\n * Builds a unique cache key for a certificate.\n * Uses issuer DN + serial number which uniquely identifies a cert.\n */\nfunction certCacheKey(cert: ParsedCertificate): string {\n\treturn `${cert.issuer.derHex}:${cert.serialNumberHex}`;\n}\n\n/**\n * Validates that a CRL signer certificate is not revoked.\n * Uses memoization to avoid redundant checks and detect cycles.\n */\nasync function validateCrlSigner(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// Use issuer+serial as cache key (unique per certificate)\n\tconst key = certCacheKey(signer);\n\tconst cached = ctx.cache.get(key);\n\n\t// Cycle detection: if we're already visiting this signer, it's indeterminate\n\tif (cached === 'visiting') {\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Return cached result if already resolved\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\t// Mark as visiting before recursive checks\n\tctx.cache.set(key, 'visiting');\n\n\t// Trust anchor (last in chain) is trusted by definition\n\tconst trustAnchor = ctx.chain[ctx.chain.length - 1];\n\tif (trustAnchor !== undefined && sameCertificate(signer, trustAnchor)) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// If signer is in the validated chain, it's trusted\n\t// (Chain was already validated before revocation checking)\n\tconst isInChain = ctx.chain.some((c) => sameCertificate(c, signer));\n\tif (isInChain) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// Signer is not in chain — need to check its revocation status\n\t// Find signer's issuer to perform revocation check\n\tconst signerIssuer = findSignerIssuer(signer, ctx);\n\tif (signerIssuer === undefined) {\n\t\tctx.cache.set(key, 'resolved-indeterminate');\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Check signer's revocation status (recursive)\n\tconst signerRevocation = await checkSignerRevocation(signer, signerIssuer, ctx);\n\tctx.cache.set(key, signerRevocation);\n\treturn signerRevocation;\n}\n\n/**\n * Finds the issuer certificate for a CRL signer.\n * Searches the chain and extraCertificates by AKI/SKI or DN matching.\n */\nfunction findSignerIssuer(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): ParsedCertificate | undefined {\n\t// Parse extra certificates\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of ctx.extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...ctx.chain, ...parsedExtras];\n\n\tfor (const candidate of candidates) {\n\t\t// Match by AKI → SKI (preferred, more specific)\n\t\tif (\n\t\t\tsigner.authorityKeyIdentifier !== undefined &&\n\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\tnormalizeHex(signer.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t) {\n\t\t\treturn candidate;\n\t\t}\n\n\t\t// Match by issuer DN → subject DN\n\t\tif (signer.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Checks if a CRL signer certificate is revoked by examining available CRLs.\n * Recursively validates the CRL signer of any CRL used to check revocation.\n */\nasync function checkSignerRevocation(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// If the signer's issuer is in the validated chain, the signer is trusted\n\t// by virtue of being issued by a trusted CA. We only need to check if\n\t// it's explicitly revoked, not prove \"good\" status.\n\tconst issuerInChain = ctx.chain.some((c) => sameCertificate(c, issuer));\n\n\t// Try each CRL to check signer's revocation\n\tfor (const crlSource of ctx.crls) {\n\t\tlet crl: ParsedCertificateRevocationList;\n\t\ttry {\n\t\t\tcrl = parseCrlFromSource(crlSource);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if this CRL can provide revocation info for the signer\n\t\tconst result = await checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: signer,\n\t\t\tissuerCertificate: issuer,\n\t\t\tcrl,\n\t\t\tat: ctx.at,\n\t\t});\n\n\t\tif (result.ok) {\n\t\t\tif (result.value.status === 'revoked') {\n\t\t\t\treturn 'resolved-revoked';\n\t\t\t}\n\t\t\tif (result.value.status === 'good') {\n\t\t\t\t// Before accepting this result, validate the CRL's signer\n\t\t\t\t// The CRL's signer is the issuer we just used\n\t\t\t\tconst crlSignerStatus = await validateCrlSigner(issuer, ctx);\n\t\t\t\tif (crlSignerStatus === 'resolved-valid') {\n\t\t\t\t\treturn 'resolved-valid';\n\t\t\t\t}\n\t\t\t\t// If CRL signer is revoked or indeterminate, can't trust this result\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the signer's issuer is in the chain and we found no revocation,\n\t// trust the signer (issued by trusted CA, no evidence of revocation)\n\tif (issuerInChain) {\n\t\treturn 'resolved-valid';\n\t}\n\n\treturn 'resolved-indeterminate';\n}\n\n/** Builds a CertificateRevocationStatus for a CRL check result. */\nfunction buildCrlStatus(\n\tcert: ParsedCertificate,\n\tsigner: ParsedCertificate,\n\tstatus: 'good' | 'revoked',\n\tthisUpdate: Date,\n\trevocationDate?: Date,\n\treasonCode?: RevocationReason,\n): CertificateRevocationStatus {\n\tif (status === 'revoked' && revocationDate !== undefined) {\n\t\treturn {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'revoked',\n\t\t\tsource: { type: 'crl', signerCertificate: signer, thisUpdate },\n\t\t\trevocationInfo: {\n\t\t\t\tdate: revocationDate,\n\t\t\t\t...(reasonCode !== undefined ? { reason: reasonCode } : {}),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tcertificate: cert,\n\t\tstatus: 'good',\n\t\tsource: { type: 'crl', signerCertificate: signer, thisUpdate },\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// OCSP Evidence Evaluation (RFC 6960)\n// ---------------------------------------------------------------------------\n\n/** Per-certificate evidence evaluation outcome shared by the CRL and OCSP evaluators. */\ninterface EvidenceEvaluation {\n\treadonly status: CertificateRevocationStatus;\n\treadonly executionErrors: readonly RevocationExecutionError[];\n}\n\n/** Parses an OCSP response from PEM string or DER bytes. */\nfunction parseOcspResponseFromSource(source: OcspResponseSource): ParsedOcspResponse {\n\tif (typeof source === 'string') {\n\t\treturn parseOcspResponsePem(source);\n\t}\n\treturn parseOcspResponseDer(source);\n}\n\n/** Maps a {@linkcode validateOcspResponse} failure code to an indeterminate reason. */\nfunction ocspIndeterminateReasonFromFailure(\n\tcode: ValidateOcspResponseFailure['code'],\n): RevocationIndeterminateReason {\n\tswitch (code) {\n\t\tcase 'stale_response':\n\t\t\treturn 'ocsp_response_expired';\n\t\tcase 'responder_id_mismatch':\n\t\tcase 'responder_chain_invalid':\n\t\tcase 'ocsp_signing_missing':\n\t\t\treturn 'ocsp_responder_not_authorized';\n\t\tcase 'responder_revoked':\n\t\t\treturn 'ocsp_responder_revoked';\n\t\tcase 'signature_invalid':\n\t\tcase 'responder_revocation_unknown':\n\t\t\treturn 'ocsp_responder_indeterminate';\n\t\tcase 'response_status_invalid':\n\t\tcase 'issuer_mismatch':\n\t\tcase 'nonce_mismatch':\n\t\tcase 'request_mismatch':\n\t\t\treturn 'no_applicable_ocsp';\n\t}\n}\n\n/** Validation failures worth retrying with an explicit responder certificate. */\nconst OCSP_RESPONDER_FAILURE_CODES: ReadonlySet<ValidateOcspResponseFailure['code']> = new Set([\n\t'signature_invalid',\n\t'responder_id_mismatch',\n\t'responder_chain_invalid',\n\t'ocsp_signing_missing',\n]);\n\n/**\n * Validates an OCSP response, retrying with caller-provided extra certificates\n * as explicit responder certificates when embedded discovery fails.\n */\nasync function validateOcspResponseWithResponderFallback(\n\tresponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tat: Date,\n): Promise<ValidateOcspResponseResult> {\n\tconst shared = {\n\t\tissuerCertificate: issuer,\n\t\tat,\n\t\t...(input.trustedOcspResponders !== undefined\n\t\t\t? { trustedResponderCertificates: input.trustedOcspResponders }\n\t\t\t: {}),\n\t\t...(input.policy?.ocspResponderRevocation !== undefined\n\t\t\t? { responderRevocationPolicy: input.policy.ocspResponderRevocation }\n\t\t\t: {}),\n\t\t// Chain-level CRLs double as responder revocation evidence\n\t\t...(input.crls !== undefined ? { responderRevocationCrls: input.crls } : {}),\n\t};\n\tconst primary = await validateOcspResponse({ response, ...shared });\n\tif (primary.ok || !OCSP_RESPONDER_FAILURE_CODES.has(primary.code)) {\n\t\treturn primary;\n\t}\n\tfor (const source of input.extraCertificates ?? []) {\n\t\tconst responder = parseCertificateSafe(source);\n\t\tif (responder === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst retry = await validateOcspResponse({\n\t\t\tresponse,\n\t\t\t...shared,\n\t\t\tresponderCertificate: responder,\n\t\t});\n\t\tif (retry.ok) {\n\t\t\treturn retry;\n\t\t}\n\t}\n\treturn primary;\n}\n\n/**\n * Evaluates OCSP evidence for a single certificate (RFC 6960).\n *\n * Every response is fully validated — signature, responder binding and\n * authorization, and freshness — via {@linkcode validateOcspResponse} before\n * its status entry is trusted. Issuer binding of each CertID is enforced by\n * the validator, so a serial-number match on a validated response is\n * sufficient to attribute the entry to `cert`.\n */\nasync function evaluateOcspEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n): Promise<EvidenceEvaluation> {\n\tconst { ocspResponses = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\n\tfor (const source of ocspResponses) {\n\t\tlet parsed: ParsedOcspResponse;\n\t\ttry {\n\t\t\tparsed = parseOcspResponseFromSource(source);\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'OCSP response parse failed',\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst entry = (parsed.responses ?? []).find(\n\t\t\t(single) =>\n\t\t\t\tnormalizeHex(single.certId.serialNumberHex) === normalizeHex(cert.serialNumberHex),\n\t\t);\n\t\tif (entry === undefined) {\n\t\t\tcontinue; // Response does not cover this certificate\n\t\t}\n\n\t\tconst validation = await validateOcspResponseWithResponderFallback(parsed, issuer, input, at);\n\t\tif (!validation.ok) {\n\t\t\treasons.add(ocspIndeterminateReasonFromFailure(validation.code));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.certStatus === 'revoked') {\n\t\t\tconst reason = revocationReasonFromCode(entry.revocationReasonCode);\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'revoked',\n\t\t\t\t\tsource: { type: 'ocsp', thisUpdate: entry.thisUpdate },\n\t\t\t\t\trevocationInfo: {\n\t\t\t\t\t\tdate: entry.revokedAt ?? entry.thisUpdate,\n\t\t\t\t\t\t...(reason !== undefined ? { reason } : {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\tif (entry.certStatus === 'good') {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\tsource: { type: 'ocsp', thisUpdate: entry.thisUpdate },\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\treasons.add('ocsp_status_unknown');\n\t}\n\n\tif (reasons.size === 0) {\n\t\treasons.add('no_applicable_ocsp');\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate using available CRLs.\n * Returns both status and any execution errors encountered.\n *\n * Tries the chain issuer first; if that fails, searches extraCertificates\n * and chain for an indirect CRL issuer that matches the CRL's AKI or issuer DN.\n *\n * Also validates that CRL signers are not revoked (RFC 5280 §6.3.3).\n */\n// RFC 5280 ReasonFlags — all possible revocation reasons that CRLs can cover.\nconst ALL_REASON_FLAGS: readonly string[] = [\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];\n\nasync function evaluateCrlEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst { crls = [], extraCertificates = [], chain = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tlet sawCrlSignerRevoked = false;\n\tlet sawCrlSignerIndeterminate = false;\n\tlet sawGood = false;\n\t// Signer and thisUpdate are tracked together so the reported\n\t// signerCertificate always belongs to the CRL whose freshness is reported.\n\tlet freshestGood: { readonly signer: ParsedCertificate; readonly thisUpdate: Date } | undefined;\n\tconst coveredReasons = new Set<string>();\n\n\t// Parse all CRLs and separate base CRLs from delta CRLs\n\tconst parsedCrls: ParsedCertificateRevocationList[] = [];\n\tfor (const crlSource of crls) {\n\t\ttry {\n\t\t\tparsedCrls.push(parseCrlFromSource(crlSource));\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'CRL parse failed',\n\t\t\t});\n\t\t}\n\t}\n\n\tconst baseCrls = parsedCrls.filter((crl) => crl.baseCrlNumber === undefined);\n\tconst deltaCrls = parsedCrls.filter((crl) => crl.baseCrlNumber !== undefined);\n\n\t// Helper to check CRL with given issuer and optional delta\n\tconst checkWithIssuer = async (\n\t\tcrl: ParsedCertificateRevocationList,\n\t\tdeltaCrl: ParsedCertificateRevocationList | undefined,\n\t\tcrlIssuer: ParsedCertificate,\n\t) => {\n\t\treturn checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: cert,\n\t\t\tissuerCertificate: crlIssuer,\n\t\t\tcrl,\n\t\t\t...(deltaCrl !== undefined ? { deltaCrl } : {}),\n\t\t\tat,\n\t\t});\n\t};\n\n\t// Process base CRLs (optionally paired with delta CRLs)\n\tfor (const baseCrl of baseCrls) {\n\t\t// Find applicable delta CRL for this base CRL (if any)\n\t\t// Delta CRL applies if it has the same issuer and crlNumber matches baseCrlNumber\n\t\tconst applicableDelta = deltaCrls.find(\n\t\t\t(d) =>\n\t\t\t\td.issuer.derHex === baseCrl.issuer.derHex &&\n\t\t\t\td.baseCrlNumber !== undefined &&\n\t\t\t\tbaseCrl.crlNumber !== undefined &&\n\t\t\t\tBigInt(d.baseCrlNumber) <= BigInt(baseCrl.crlNumber),\n\t\t);\n\n\t\t// Try chain issuer first\n\t\tlet result = await checkWithIssuer(baseCrl, applicableDelta, issuer);\n\t\tlet effectiveSigner = issuer;\n\n\t\t// Chain issuer failed — try to find indirect CRL issuer\n\t\tif (!result.ok) {\n\t\t\tconst indirectIssuer = findIndirectCrlIssuer(baseCrl, extraCertificates, chain);\n\t\t\tif (indirectIssuer !== undefined && !sameCertificate(indirectIssuer, issuer)) {\n\t\t\t\tresult = await checkWithIssuer(baseCrl, applicableDelta, indirectIssuer);\n\t\t\t\teffectiveSigner = indirectIssuer;\n\t\t\t}\n\t\t}\n\n\t\tif (!result.ok) {\n\t\t\tcontinue; // CRL doesn't apply to this certificate\n\t\t}\n\n\t\t// Validate CRL signer is not revoked before accepting result\n\t\tconst signerStatus = await validateCrlSigner(effectiveSigner, signerCtx);\n\t\tif (signerStatus === 'resolved-revoked') {\n\t\t\tsawCrlSignerRevoked = true;\n\t\t\tcontinue; // CRL signer revoked — can't trust this CRL\n\t\t}\n\t\tif (signerStatus === 'resolved-indeterminate') {\n\t\t\tsawCrlSignerIndeterminate = true;\n\t\t\tcontinue; // CRL signer status unknown — try other CRLs\n\t\t}\n\n\t\t// Evidence freshness: an applied delta CRL supersedes its base\n\t\tconst crlThisUpdate =\n\t\t\tapplicableDelta !== undefined &&\n\t\t\tapplicableDelta.thisUpdate.getTime() > baseCrl.thisUpdate.getTime()\n\t\t\t\t? applicableDelta.thisUpdate\n\t\t\t\t: baseCrl.thisUpdate;\n\n\t\t// CRL is valid — check result\n\t\tif (result.value.status === 'revoked') {\n\t\t\t// Immediately return revoked status\n\t\t\treturn {\n\t\t\t\tstatus: buildCrlStatus(\n\t\t\t\t\tcert,\n\t\t\t\t\teffectiveSigner,\n\t\t\t\t\t'revoked',\n\t\t\t\t\tcrlThisUpdate,\n\t\t\t\t\tresult.value.revocationDate,\n\t\t\t\t\tresult.value.reasonCode,\n\t\t\t\t),\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\n\t\t// Status is 'good' — track which reasons this CRL covers\n\t\tsawGood = true;\n\t\tif (freshestGood === undefined || crlThisUpdate.getTime() > freshestGood.thisUpdate.getTime()) {\n\t\t\tfreshestGood = { signer: effectiveSigner, thisUpdate: crlThisUpdate };\n\t\t}\n\t\tconst crlReasons = baseCrl.issuingDistributionPoint?.onlySomeReasons?.flags;\n\t\tif (crlReasons === undefined) {\n\t\t\t// CRL covers all reasons\n\t\t\tfor (const reason of ALL_REASON_FLAGS) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t} else {\n\t\t\t// CRL only covers specific reasons\n\t\t\tfor (const reason of crlReasons) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return 'good' only if we saw at least one good result AND all reasons are covered\n\tif (sawGood) {\n\t\tconst allReasonsCovered = ALL_REASON_FLAGS.every((r) => coveredReasons.has(r));\n\t\tif (allReasonsCovered) {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\t...(freshestGood !== undefined\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tsource: {\n\t\t\t\t\t\t\t\t\ttype: 'crl',\n\t\t\t\t\t\t\t\t\tsignerCertificate: freshestGood.signer,\n\t\t\t\t\t\t\t\t\tthisUpdate: freshestGood.thisUpdate,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\t// Not all reasons covered — indeterminate\n\t\treturn {\n\t\t\tstatus: {\n\t\t\t\tcertificate: cert,\n\t\t\t\tstatus: 'indeterminate',\n\t\t\t\tindeterminateReasons: ['reason_coverage_incomplete'],\n\t\t\t},\n\t\t\texecutionErrors,\n\t\t};\n\t}\n\n\t// No applicable CRL found — determine most appropriate indeterminate reason\n\tconst reasons: RevocationIndeterminateReason[] = [];\n\tif (sawCrlSignerRevoked) {\n\t\treasons.push('crl_signer_revoked');\n\t} else if (sawCrlSignerIndeterminate) {\n\t\treasons.push('crl_signer_indeterminate');\n\t} else {\n\t\treasons.push('no_applicable_crl');\n\t}\n\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: reasons,\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate by combining OCSP and\n * CRL evidence.\n *\n * Both evidence kinds are always evaluated: a validated `revoked` verdict from\n * either source wins regardless of {@linkcode RevocationPolicy.prefer}\n * (fail-closed). Otherwise the preferred source's `good` verdict is reported —\n * for `'best-available'` the source with the later evidence `thisUpdate` wins,\n * ties favoring OCSP. If neither source is definitive, indeterminate reasons\n * from both are merged.\n */\nasync function evaluateCertificateRevocation(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst prefer = input.policy?.prefer ?? 'best-available';\n\tconst ocsp = await evaluateOcspEvidence(cert, issuer, input);\n\tconst crl = await evaluateCrlEvidence(cert, issuer, input, signerCtx);\n\tconst executionErrors = [...ocsp.executionErrors, ...crl.executionErrors];\n\n\t// 'best-available' ranks by evidence freshness; the sort is stable, so\n\t// equal (or absent) thisUpdate keeps OCSP first.\n\tconst ordered =\n\t\tprefer === 'crl'\n\t\t\t? [crl, ocsp]\n\t\t\t: prefer === 'ocsp'\n\t\t\t\t? [ocsp, crl]\n\t\t\t\t: [ocsp, crl].sort(\n\t\t\t\t\t\t(a, b) =>\n\t\t\t\t\t\t\t(b.status.source?.thisUpdate?.getTime() ?? 0) -\n\t\t\t\t\t\t\t(a.status.source?.thisUpdate?.getTime() ?? 0),\n\t\t\t\t\t);\n\tconst revoked = ordered.find((evaluation) => evaluation.status.status === 'revoked');\n\tif (revoked !== undefined) {\n\t\treturn { status: revoked.status, executionErrors };\n\t}\n\tconst good = ordered.find((evaluation) => evaluation.status.status === 'good');\n\tif (good !== undefined) {\n\t\treturn { status: good.status, executionErrors };\n\t}\n\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\tfor (const evaluation of ordered) {\n\t\tfor (const reason of evaluation.status.indeterminateReasons ?? []) {\n\t\t\treasons.add(reason);\n\t\t}\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Function\n// ---------------------------------------------------------------------------\n\n/**\n * Checks revocation status for all certificates in a validated chain.\n *\n * Evaluates CRL and OCSP evidence against each certificate (except the trust\n * anchor), applies the revocation policy, and returns a unified decision.\n *\n * @example\n * ```ts\n * const result = await checkChainRevocation({\n * chain: validatedChain,\n * crls: [crl1, crl2],\n * ocspResponses: [ocspResponseDer],\n * policy: { mode: 'hard-fail' },\n * });\n * if (result.value.decision === 'deny') {\n * console.log('Revocation check failed');\n * }\n * ```\n */\nexport async function checkChainRevocation(\n\tinput: CheckChainRevocationInput,\n): Promise<CheckChainRevocationResult> {\n\tconst { chain, policy, crls = [], extraCertificates = [], at = new Date() } = input;\n\tconst mode = policy?.mode ?? 'soft-fail';\n\n\t// Empty chain → allow\n\tif (chain.length === 0) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tdecision: 'allow',\n\t\t\t\tsummary: { revokedCertificates: [], indeterminateCertificates: [] },\n\t\t\t\tcertificates: [],\n\t\t\t},\n\t\t};\n\t}\n\n\t// Create signer validation context with memoization cache\n\t// This cache is shared across all certificate checks in this chain evaluation\n\tconst signerCtx: SignerValidationContext = {\n\t\tcache: new Map(),\n\t\tchain,\n\t\tcrls,\n\t\textraCertificates,\n\t\tat,\n\t};\n\n\t// Skip trust anchor (last cert) — it's the trust base\n\tconst certsToCheck = chain.slice(0, -1);\n\tconst certificates: CertificateRevocationStatus[] = [];\n\tconst revokedCertificates: ParsedCertificate[] = [];\n\tconst indeterminateCertificates: ParsedCertificate[] = [];\n\tconst allExecutionErrors: RevocationExecutionError[] = [];\n\n\tfor (let i = 0; i < certsToCheck.length; i++) {\n\t\tconst cert = certsToCheck[i];\n\t\tconst issuer = chain[i + 1]; // Next cert in chain is the issuer\n\t\tif (cert === undefined || issuer === undefined) {\n\t\t\tcontinue; // Should never happen given loop bounds\n\t\t}\n\n\t\tconst { status, executionErrors } = await evaluateCertificateRevocation(\n\t\t\tcert,\n\t\t\tissuer,\n\t\t\tinput,\n\t\t\tsignerCtx,\n\t\t);\n\t\tcertificates.push(status);\n\t\tallExecutionErrors.push(...executionErrors);\n\n\t\tif (status.status === 'revoked') {\n\t\t\trevokedCertificates.push(cert);\n\t\t} else if (status.status === 'indeterminate') {\n\t\t\tindeterminateCertificates.push(cert);\n\t\t}\n\t}\n\n\t// Apply policy\n\tconst hasRevoked = revokedCertificates.length > 0;\n\tconst hasIndeterminate = indeterminateCertificates.length > 0;\n\tconst decision: 'allow' | 'deny' = hasRevoked\n\t\t? 'deny'\n\t\t: hasIndeterminate && mode === 'hard-fail'\n\t\t\t? 'deny'\n\t\t\t: 'allow';\n\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tdecision,\n\t\t\tsummary: { revokedCertificates, indeterminateCertificates },\n\t\t\tcertificates,\n\t\t\t...(allExecutionErrors.length > 0 ? { executionErrors: allExecutionErrors } : {}),\n\t\t},\n\t};\n}\n"],"mappings":"+UAwQA,SAAS,EAAmB,EAAoD,CAO/E,OANI,OAAO,GAAW,UAAY,WAAY,EACtC,EAEJ,OAAO,GAAW,SACd,EAAkC,CAAM,EAEzC,EAAkC,CAAM,CAChD,CAKA,SAAS,EAAqB,EAA0D,CACvF,GAAI,CACH,OAAO,EAA2B,CAAM,CACzC,MAAQ,CACP,MACD,CACD,CAMA,SAAS,EAAgB,EAAsB,EAA+B,CAC7E,GAAI,EAAE,IAAI,SAAW,EAAE,IAAI,OAAQ,MAAO,GAC1C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAE,IAAI,OAAQ,IACjC,GAAI,EA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ACD,EAGM,EAAe,EAAM,MAAM,EAAG,EAAE,EAChC,EAA8C,CAAC,EAC/C,EAA2C,CAAC,EAC5C,EAAiD,CAAC,EAClD,EAAiD,CAAC,EAExD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAa,OAAQ,IAAK,CAC7C,IAAM,EAAO,EAAa,GACpB,EAAS,EAAM,EAAI,GACzB,GAAI,IAAS,IAAA,IAAa,IAAW,IAAA,GACpC,SAGD,GAAM,CAAE,SAAQ,mBAAoB,MAAM,EACzC,EACA,EACA,EACA,CACD,EACA,EAAa,KAAK,CAAM,EACxB,EAAmB,KAAK,GAAG,CAAe,EAEtC,EAAO,SAAW,UACrB,EAAoB,KAAK,CAAI,EACnB,EAAO,SAAW,iBAC5B,EAA0B,KAAK,CAAI,CAErC,CAGA,IAAM,EAAa,EAAoB,OAAS,EAC1C,EAAmB,EAA0B,OAAS,EAO5D,MAAO,CACN,GAAI,GACJ,MAAO,CACN,SATiC,GAEhC,GAAoB,IAAS,YAD7B,OAGC,QAMF,QAAS,CAAE,sBAAqB,2BAA0B,EAC1D,eACA,GAAI,EAAmB,OAAS,EAAI,CAAE,gBAAiB,CAAmB,EAAI,CAAC,CAChF,CACD,CACD"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ErrorResult, Micro509Error } from "../result/result.js";
|
|
2
2
|
import { ParsedCertificate, ParsedName } from "../x509/parse.js";
|
|
3
|
+
import { CrlSource } from "./crl.js";
|
|
3
4
|
|
|
4
5
|
//#region src/revocation/ocsp.d.ts
|
|
5
6
|
/** Hash algorithm used to compute OCSP CertID fields. SHA-1 is the RFC 6960 default. */
|
|
@@ -191,6 +192,19 @@ type VerifyOcspResponseResult = {
|
|
|
191
192
|
readonly value: ParsedOcspResponse;
|
|
192
193
|
} | ErrorResult<"signature_invalid", Record<never, never>, VerifyOcspResponseFailure>;
|
|
193
194
|
/**
|
|
195
|
+
* Revocation policy for delegated OCSP responder certificates (RFC 6960 §4.2.2.2.1).
|
|
196
|
+
*
|
|
197
|
+
* - `'honor-nocheck'` (default): a responder carrying `id-pkix-ocsp-nocheck`
|
|
198
|
+
* is exempt from revocation checking. Otherwise, CRL evidence from
|
|
199
|
+
* {@linkcode ValidateOcspResponseInput.responderRevocationCrls} is consulted
|
|
200
|
+
* when provided — a revoked responder rejects the response; missing or
|
|
201
|
+
* unusable evidence is tolerated (soft).
|
|
202
|
+
* - `'require-evidence'`: `nocheck` is ignored; CRL evidence must positively
|
|
203
|
+
* show the responder is not revoked, otherwise the response is rejected.
|
|
204
|
+
* - `'skip'`: no responder revocation checking.
|
|
205
|
+
*/
|
|
206
|
+
type OcspResponderRevocationPolicy = "honor-nocheck" | "require-evidence" | "skip";
|
|
207
|
+
/**
|
|
194
208
|
* Input for {@linkcode validateOcspResponse}.
|
|
195
209
|
*/
|
|
196
210
|
interface ValidateOcspResponseInput {
|
|
@@ -204,20 +218,37 @@ interface ValidateOcspResponseInput {
|
|
|
204
218
|
readonly responderCertificate?: OcspCertificateSource;
|
|
205
219
|
/** When `true`, allows delegated responder chain validation beyond direct issuance. */
|
|
206
220
|
readonly allowChainedResponderCertificate?: boolean;
|
|
207
|
-
/**
|
|
221
|
+
/**
|
|
222
|
+
* Explicitly trusted responder certificates for this issuer's scope
|
|
223
|
+
* (RFC 6960 §4.2.2.2 criterion 1 — local responder configuration).
|
|
224
|
+
*
|
|
225
|
+
* A response signer matching one of these certificates is accepted without
|
|
226
|
+
* the delegated-responder issuance, chain, EKU, and revocation checks.
|
|
227
|
+
* Signature verification and responder-ID binding are still enforced.
|
|
228
|
+
* Also consulted during responder discovery when the response embeds no
|
|
229
|
+
* matching certificate.
|
|
230
|
+
*/
|
|
231
|
+
readonly trustedResponderCertificates?: readonly OcspCertificateSource[];
|
|
232
|
+
/** Revocation policy for delegated responder certificates. Defaults to `'honor-nocheck'`. */
|
|
233
|
+
readonly responderRevocationPolicy?: OcspResponderRevocationPolicy;
|
|
234
|
+
/** CRLs used as revocation evidence for delegated responder certificates. */
|
|
235
|
+
readonly responderRevocationCrls?: readonly CrlSource[];
|
|
236
|
+
/** Evaluation time for freshness checks and delegated responder chain validation. Defaults to `new Date()`. */
|
|
208
237
|
readonly at?: Date;
|
|
209
238
|
/** Clock-skew tolerance in milliseconds for `thisUpdate`/`nextUpdate`/`producedAt`. */
|
|
210
239
|
readonly clockSkewMs?: number;
|
|
211
240
|
}
|
|
241
|
+
/** Failure codes produced by {@linkcode validateOcspResponse}. */
|
|
242
|
+
type ValidateOcspResponseErrorCode = "response_status_invalid" | "signature_invalid" | "responder_id_mismatch" | "nonce_mismatch" | "request_mismatch" | "issuer_mismatch" | "responder_chain_invalid" | "ocsp_signing_missing" | "responder_revoked" | "responder_revocation_unknown" | "stale_response";
|
|
212
243
|
/**
|
|
213
244
|
* Failure detail for {@linkcode validateOcspResponse}.
|
|
214
245
|
*
|
|
215
246
|
* Possible codes: `response_status_invalid`, `signature_invalid`,
|
|
216
247
|
* `responder_id_mismatch`, `nonce_mismatch`, `request_mismatch`,
|
|
217
248
|
* `issuer_mismatch`, `responder_chain_invalid`, `ocsp_signing_missing`,
|
|
218
|
-
* `stale_response`.
|
|
249
|
+
* `responder_revoked`, `responder_revocation_unknown`, `stale_response`.
|
|
219
250
|
*/
|
|
220
|
-
interface ValidateOcspResponseFailure extends Micro509Error<
|
|
251
|
+
interface ValidateOcspResponseFailure extends Micro509Error<ValidateOcspResponseErrorCode> {
|
|
221
252
|
/** Always `false` for failures. */
|
|
222
253
|
readonly ok: false;
|
|
223
254
|
}
|
|
@@ -225,12 +256,13 @@ interface ValidateOcspResponseFailure extends Micro509Error<"response_status_inv
|
|
|
225
256
|
* Result of {@linkcode validateOcspResponse}.
|
|
226
257
|
*
|
|
227
258
|
* On success, the response has passed status, signature, responder binding,
|
|
228
|
-
* freshness, nonce,
|
|
259
|
+
* authorization (including responder revocation policy), freshness, nonce,
|
|
260
|
+
* and request-coverage checks.
|
|
229
261
|
*/
|
|
230
262
|
type ValidateOcspResponseResult = {
|
|
231
263
|
readonly ok: true; /** Fully validated OCSP response. */
|
|
232
264
|
readonly value: ParsedOcspResponse;
|
|
233
|
-
} | ErrorResult<
|
|
265
|
+
} | ErrorResult<ValidateOcspResponseErrorCode, Record<never, never>, ValidateOcspResponseFailure>;
|
|
234
266
|
/**
|
|
235
267
|
* Builds a DER-encoded OCSP request containing one or more CertID entries
|
|
236
268
|
* and an optional nonce extension.
|
|
@@ -327,6 +359,12 @@ declare function verifyOcspResponse(response: string | Uint8Array | ParsedOcspRe
|
|
|
327
359
|
* ```
|
|
328
360
|
*/
|
|
329
361
|
declare function validateOcspResponse(input: ValidateOcspResponseInput): Promise<ValidateOcspResponseResult>;
|
|
362
|
+
/**
|
|
363
|
+
* Reports whether a certificate carries the `id-pkix-ocsp-nocheck` extension
|
|
364
|
+
* (RFC 6960 §4.2.2.2.1) — the CA's assertion that relying parties may trust
|
|
365
|
+
* this OCSP responder certificate for its lifetime without revocation checks.
|
|
366
|
+
*/
|
|
367
|
+
declare function hasOcspNoCheckExtension(certificate: OcspCertificateSource): boolean;
|
|
330
368
|
//#endregion
|
|
331
|
-
export { CreateOcspRequestInput, CreateOcspRequestItemInput, CreateOcspResponseInput, CreateOcspSingleResponseInput, OcspCertStatus, OcspCertificateSource, OcspHashAlgorithm, OcspRequestMaterial, OcspRequestSource, OcspResponseMaterial, OcspResponseStatus, ParsedOcspCertId, ParsedOcspRequest, ParsedOcspResponderId, ParsedOcspResponse, ParsedOcspSingleResponse, ValidateOcspResponseFailure, ValidateOcspResponseInput, ValidateOcspResponseResult, VerifyOcspResponseFailure, VerifyOcspResponseResult, createOcspRequest, createOcspResponse, parseOcspRequestDer, parseOcspRequestPem, parseOcspResponseDer, parseOcspResponsePem, validateOcspResponse, verifyOcspResponse };
|
|
369
|
+
export { CreateOcspRequestInput, CreateOcspRequestItemInput, CreateOcspResponseInput, CreateOcspSingleResponseInput, OcspCertStatus, OcspCertificateSource, OcspHashAlgorithm, OcspRequestMaterial, OcspRequestSource, OcspResponderRevocationPolicy, OcspResponseMaterial, OcspResponseStatus, ParsedOcspCertId, ParsedOcspRequest, ParsedOcspResponderId, ParsedOcspResponse, ParsedOcspSingleResponse, ValidateOcspResponseErrorCode, ValidateOcspResponseFailure, ValidateOcspResponseInput, ValidateOcspResponseResult, VerifyOcspResponseFailure, VerifyOcspResponseResult, createOcspRequest, createOcspResponse, hasOcspNoCheckExtension, parseOcspRequestDer, parseOcspRequestPem, parseOcspResponseDer, parseOcspResponsePem, validateOcspResponse, verifyOcspResponse };
|
|
332
370
|
//# sourceMappingURL=ocsp.d.ts.map
|
package/dist/revocation/ocsp.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{bitString as e,concatBytes as t,explicitContext as n,implicitPrimitiveContext as r,integer as i,nullValue as a,objectIdentifier as o,octetString as s,readElement as c,readRootElement as l,readSequenceChildren as u,sequence as d,time as f,tlv as p}from"../internal/asn1/der.js";import{childrenOf as m,decodeNonNegativeIntegerNumber as h,decodeObjectIdentifier as g,decodeString as _,extractBitStringValue as v,hexToBytes as y,parseTime as b,requireElement as x,toArrayBuffer as S,toHex as C}from"../internal/asn1/asn1.js";import{OIDS as w}from"../internal/asn1/oids.js";import{getCrypto as T}from"../internal/crypto/webcrypto.js";import{base64Encode as E}from"../internal/shared/base64.js";import{pemDecode as D,pemEncode as O}from"../pem/pem.js";import{failureResult as k}from"../result/result.js";import{describeHashAlgorithm as A,describeSignatureAlgorithm as ee}from"../internal/crypto/algorithm-names.js";import{parseCertificateDerOrThrow as j,parseCertificateFromSource as te}from"../x509/parse.js";import{verifySignedDataDetailed as ne}from"../internal/crypto/sig-verify.js";import{encodeAlgorithmIdentifier as re,getSignatureAlgorithm as ie,signBytes as ae}from"../internal/crypto/signing.js";import{compareDistinguishedNames as M}from"../internal/shared/dn.js";import{verifyCertificateChain as oe}from"../verify/verify.js";async function se(e){let t=e.hashAlgorithm??`SHA-1`,r=[];for(let n of e.requests){let e=await K(n.certificate),i=await K(n.issuerCertificate);r.push(d([await U(e,i,t)]))}let i=[d(r)];e.nonce!==void 0&&i.push(n(2,d([d([o(w.ocspNonce),s(s(e.nonce))])])));let a=d([d(i)]);return{der:a,pem:O(`OCSP REQUEST`,a),base64:E(a)}}function N(e){let t=u(e,{maxDepth:64});if(t.length<1||t.length>2)throw Error(`Malformed OCSP request`);let n=x(t[0],`tbsRequest`),r=t[1];if(r!==void 0&&r.tag!==160)throw Error(`Malformed OCSP request`);r!==void 0&&Ne(e,r);let i=m(e,n),a=0;if(i[a]?.tag===160){let t=m(e,x(i[a],`version`)),n=x(t[0],`version`);if(t.length!==1||n.tag!==2)throw Error(`version must use INTEGER`);if(h(n.value,`OCSP request version`)!==0)throw Error(`Unsupported OCSP request version`);a+=1}let o=i[a];o?.tag===161&&(Me(e,o),a+=1);let s=x(i[a],`requestList`);if(s.tag!==48)throw Error(`requestList must use SEQUENCE`);if(m(e,s).length===0)throw Error(`requestList must not be empty`);let c=m(e,s).map(t=>{let n=m(e,t);if(n.length<1||n.length>2||n[1]!==void 0&&n[1].tag!==160)throw Error(`Malformed OCSP request entry`);let r=x(n[0],`reqCert`);return q(e.slice(r.start-r.headerLength,r.end))});a+=1;let l=i[a];if(l!==void 0&&l.tag!==162||i.length!==a+(l===void 0?0:1))throw Error(`Malformed OCSP request`);let d=l===void 0?void 0:X(e,l);return{der:new Uint8Array(e),requests:c,...d===void 0?{}:{nonce:d}}}function P(e){return N(D(`OCSP REQUEST`,e))}function F(e){let t=u(e,{maxDepth:64});if(t.length<1||t.length>2)throw Error(`Malformed OCSP response`);let n=x(t[0],`responseStatus`);if(n.tag!==10)throw Error(`responseStatus must use ENUMERATED`);let r=Oe(h(n.value,`OCSP responseStatus`)),i=t[1];if(i===void 0)return{der:new Uint8Array(e),responseStatus:r};if(i.tag!==160)throw Error(`Malformed OCSP response`);let a=m(e,i),o=x(a[0],`responseBytes`);if(a.length!==1||o.tag!==48)throw Error(`Malformed OCSP response`);let s=m(e,o);if(s.length!==2)throw Error(`responseBytes must contain responseType and response`);let c=x(s[0],`responseType`),l=x(s[1],`response`);if(l.tag!==4)throw Error(`response must use OCTET STRING`);let d=g(c.value);if(d!==w.ocspBasicResponse)return{der:new Uint8Array(e),responseStatus:r,responseTypeOid:d};let f=l.value,p=u(f);if(p.length<3||p.length>4)throw Error(`Malformed BasicOCSPResponse`);let _=x(p[0],`responseData`),y=x(p[1],`signatureAlgorithm`),b=x(p[2],`signatureValue`),S=p[3];if(S!==void 0&&S.tag!==160)throw Error(`Malformed BasicOCSPResponse`);let C=m(f,y),T=g(x(C[0],`signatureAlgorithm OID`).value),E=C[1],D=f.slice(_.start-_.headerLength,_.end),O=de(D);return{der:new Uint8Array(e),responseStatus:r,responseTypeOid:d,responseDataDer:D,responderId:O.responderId,signatureAlgorithmOid:T,signatureAlgorithmName:ee(T,E===void 0?void 0:f.slice(E.start-E.headerLength,E.end)),signatureValue:v(b),producedAt:O.producedAt,responses:O.responses,...O.nonce===void 0?{}:{nonce:O.nonce},...S?.tag===160?{certificates:De(f,S)}:{}}}function I(e){return F(D(`OCSP RESPONSE`,e))}async function ce(i){let a=await K(i.signerCertificate),c=ie(i.signerPrivateKey),l=i.producedAt??new Date,u=i.hashAlgorithm??`SHA-1`,m=[];for(let e of i.responses){let t=await K(e.certificate),n=await K(e.issuerCertificate);m.push(await ge(t,n,e,u))}let h=[r(2,await G(`SHA-1`,Z(a.subjectPublicKeyInfoDer))),f(l),d(m)];i.nonce!==void 0&&h.push(n(1,d([d([o(w.ocspNonce),s(s(i.nonce))])])));let g=d(h),_=await ae(i.signerPrivateKey,c,g),v=i.includedCertificates===void 0?[]:await Promise.all(i.includedCertificates.map(K)),y=[g,re(c),e(_)];v.length>0&&y.push(n(0,t(v.map(e=>e.der))));let b=d(y),x=d([p(10,Uint8Array.of(0)),n(0,d([o(w.ocspBasicResponse),s(b)]))]);return{der:x,pem:O(`OCSP RESPONSE`,x),base64:E(x)}}async function L(e,t){let n;try{n=B(e)}catch{return R(`signature_invalid`,`OCSP response signed content is malformed`)}if(n.responseDataDer===void 0||n.signatureAlgorithmOid===void 0||n.signatureValue===void 0)return R(`signature_invalid`,`OCSP response is not signed`);let r;try{r=await K(t)}catch{return R(`signature_invalid`,`OCSP signer certificate input is malformed`)}let i;try{i=await ne(n.signatureAlgorithmOid,void 0,r.publicKeyAlgorithmOid,r.publicKeyParametersOid,r.subjectPublicKeyInfoDer,n.signatureValue,n.responseDataDer)}catch{return R(`signature_invalid`,`OCSP response signature verification failed`)}return i.ok?i.valid?{ok:!0,value:n}:R(`signature_invalid`,`OCSP response signature does not verify`):i.code===`verification_error`?R(`signature_invalid`,`OCSP response signature verification failed`):R(`signature_invalid`,`OCSP response signature uses unsupported algorithm parameters`)}async function le(e){let t;try{t=B(e.response)}catch{return z(`signature_invalid`,`OCSP response signed content is malformed`)}if(t.responseStatus!==`successful`)return z(`response_status_invalid`,`OCSP response status is ${t.responseStatus}`);let n;try{n=await K(e.issuerCertificate)}catch{return z(`signature_invalid`,`issuer certificate input is malformed`)}let r;try{r=e.responderCertificate??await fe(t.certificates,t.responderId)??t.certificates?.[0]??e.issuerCertificate}catch{return z(`signature_invalid`,`OCSP responder certificate input is malformed`)}let i;try{i=await K(r)}catch{return z(`signature_invalid`,`OCSP responder certificate input is malformed`)}let a=await L(t,i);if(!a.ok)return z(a.code,a.message);let o;try{o=await pe(t.responderId,i)}catch{return z(`signature_invalid`,`OCSP responder certificate input is malformed`)}if(!o.ok)return o;if(!H(i,n)){let r=e.allowChainedResponderCertificate===!0;if(!r&&!me(i,n))return z(`responder_chain_invalid`,`Delegated OCSP responder must be directly issued by issuer certificate`);if(!(await oe({leaf:i.der,intermediates:r?he(t.certificates,i,n):[],roots:[n.der]})).ok)return z(`responder_chain_invalid`,`OCSP responder certificate chain does not validate`);if(i.extendedKeyUsage===void 0||!i.extendedKeyUsage.includes(`ocspSigning`))return z(`ocsp_signing_missing`,`Delegated OCSP responder lacks ocspSigning EKU`)}let s=e.at??new Date,c=e.clockSkewMs??0;if(t.producedAt!==void 0&&t.producedAt.getTime()-c>s.getTime())return z(`stale_response`,`OCSP response producedAt is later than requested time`);for(let e of t.responses??[]){let r;try{r=await W(e.certId.hashAlgorithmOid,n,e.certId.serialNumberHex)}catch{return z(`signature_invalid`,`OCSP response CertID hash algorithm is unsupported`)}if(e.certId.issuerNameHashHex!==r.issuerNameHashHex||e.certId.issuerKeyHashHex!==r.issuerKeyHashHex)return z(`issuer_mismatch`,`OCSP response certId does not match issuer certificate`);if(e.thisUpdate.getTime()-c>s.getTime()||e.nextUpdate!==void 0&&e.nextUpdate.getTime()+c<s.getTime())return z(`stale_response`,`OCSP response is not valid at requested time`);if(t.producedAt!==void 0&&e.nextUpdate!==void 0&&t.producedAt.getTime()-c>e.nextUpdate.getTime())return z(`stale_response`,`OCSP response producedAt is later than nextUpdate`)}if(je(t.responses??[]))return z(`signature_invalid`,`OCSP response contains multiple status entries for the same certificate`);if(e.request!==void 0){let n;try{n=ue(e.request)}catch{return z(`request_mismatch`,`OCSP request input is malformed`)}if(n.nonce!==void 0&&n.nonce!==t.nonce)return z(`nonce_mismatch`,`OCSP response nonce does not match request nonce`);let r=new Set(n.requests.map(e=>$(e))),i=new Set((t.responses??[]).map(e=>$(e.certId)));for(let e of t.responses??[])if(!r.has($(e.certId)))return z(`request_mismatch`,`OCSP response includes a certId not present in request`);for(let e of r)if(!i.has(e))return z(`request_mismatch`,`OCSP response does not cover every requested certId`)}return{ok:!0,value:t}}function R(e,t){return k(e,t)}function z(e,t){return k(e,t)}function B(e){if(typeof e==`string`)return I(e);if(e instanceof Uint8Array)return F(e);if(Ae(e))return F(new Uint8Array(e.der));throw Error(`OCSP response input is malformed`)}function ue(e){if(typeof e==`string`)return P(e);if(e instanceof Uint8Array)return N(e);if(ke(e))return N(new Uint8Array(e.der));throw Error(`OCSP request input is malformed`)}function de(e){let t=u(e);if(t.length<3||t.length>5)throw Error(`Malformed OCSP responseData`);let n=0;if(t[n]?.tag===160){let r=m(e,x(t[n],`version`)),i=x(r[0],`version`);if(r.length!==1||i.tag!==2)throw Error(`version must use INTEGER`);if(h(i.value,`OCSP response version`)!==0)throw Error(`Unsupported OCSP response version`);n+=1}let r=be(e,x(t[n],`responderID`));n+=1;let i=x(t[n],`producedAt`),a=x(t[n+1],`responses`);if(a.tag!==48)throw Error(`responses must use SEQUENCE`);if(m(e,a).length===0)throw Error(`responses must not be empty`);let o=t[n+2];if(o!==void 0&&o.tag!==161||t.length!==n+2+(o===void 0?0:1))throw Error(`Malformed OCSP responseData`);let s=o===void 0?void 0:X(e,o),c=m(e,a).map(t=>ye(e,t));return Q(c),{responderId:r,producedAt:b(i),responses:c,...s===void 0?{}:{nonce:s}}}async function fe(e,t){if(!(e===void 0||t===void 0)){for(let n of e)if(await V(t,n))return n}}async function pe(e,t){return e===void 0||await V(e,t)?{ok:!0}:e.type===`byName`?z(`responder_id_mismatch`,`OCSP responder certificate subject does not match responderID byName`):z(`responder_id_mismatch`,`OCSP responder certificate public key does not match responderID byKeyHash`)}async function V(e,t){return e.type===`byName`?Ce(e.name,t.subject):C(await G(`SHA-1`,Z(t.subjectPublicKeyInfoDer)))===e.keyHashHex}function H(e,t){return e.serialNumberHex===t.serialNumberHex&&M(e.issuer,t.issuer)&&M(e.subject,t.subject)&&e.subjectPublicKeyInfoDer.length===t.subjectPublicKeyInfoDer.length&&e.subjectPublicKeyInfoDer.every((e,n)=>e===t.subjectPublicKeyInfoDer[n])}function me(e,t){return!(!M(e.issuer,t.subject)||e.authorityKeyIdentifier!==void 0&&t.subjectKeyIdentifier!==void 0&&e.authorityKeyIdentifier!==t.subjectKeyIdentifier)}function he(e,t,n){if(e===void 0)return[];let r=[];for(let i of e)H(i,t)||H(i,n)||r.push(i.der);return r}async function U(e,t,n){let r=n===`SHA-1`?w.sha1:w.sha256,c=await W(r,t,e.serialNumberHex);return d([d([o(r),a()]),s(y(c.issuerNameHashHex)),s(y(c.issuerKeyHashHex)),i(y(c.serialNumberHex))])}async function W(e,t,n){let r=Le(e);return{hashAlgorithmOid:e,hashAlgorithmName:A(e),issuerNameHashHex:C(await G(r,y(t.subject.derHex))),issuerKeyHashHex:C(await G(r,Z(t.subjectPublicKeyInfoDer))),serialNumberHex:n}}async function G(e,t){return new Uint8Array(await T().subtle.digest(e,S(t)))}async function ge(e,t,r,i){return d([await U(e,t,i),_e(r),f(r.thisUpdate??new Date),...r.nextUpdate===void 0?[]:[n(0,f(r.nextUpdate))]])}function _e(e){switch(e.certStatus){case`good`:return p(128,new Uint8Array);case`unknown`:return p(130,new Uint8Array);case`revoked`:{let r=[f(e.revokedAt??e.thisUpdate??new Date)];return e.revocationReasonCode!==void 0&&r.push(n(0,p(10,Uint8Array.of(e.revocationReasonCode)))),p(161,t(r))}}}function K(e){return ve(e)?j(new Uint8Array(e.der)):te(e)}function ve(e){return typeof e!=`string`&&`subjectPublicKeyInfoDer`in e}function q(e){let t=l(e,{maxDepth:64});if(t.tag!==48)throw Error(`CertID must use SEQUENCE`);let n=m(e,t);if(n.length!==4)throw Error(`CertID must contain hashAlgorithm, issuerNameHash, issuerKeyHash, and serialNumber`);let r=x(n[0],`hashAlgorithm`);if(r.tag!==48)throw Error(`hashAlgorithm must use SEQUENCE`);let i=m(e,r);if(i.length<1||i.length>2)throw Error(`Malformed hashAlgorithm`);let a=g(x(i[0],`hashAlgorithm OID`).value);if(x(n[1],`issuerNameHash`).tag!==4)throw Error(`issuerNameHash must use OCTET STRING`);if(x(n[2],`issuerKeyHash`).tag!==4)throw Error(`issuerKeyHash must use OCTET STRING`);let o=x(n[3],`serialNumber`);if(o.tag!==2)throw Error(`serialNumber must use INTEGER`);return{hashAlgorithmOid:a,hashAlgorithmName:A(a),issuerNameHashHex:C(x(n[1],`issuerNameHash`).value),issuerKeyHashHex:C(x(n[2],`issuerKeyHash`).value),serialNumberHex:C(o.value)}}function ye(e,t){let n=m(e,t);if(n.length<3||n.length>5)throw Error(`Malformed OCSP SingleResponse`);let r=x(n[0],`certId`),i=x(n[1],`certStatus`),a=x(n[2],`thisUpdate`),o=3,s=n[o]?.tag===160?n[o]:void 0;s!==void 0&&(Pe(e,s),o+=1);let c=n[o];if(c!==void 0&&c.tag!==161||n.length!==o+(c===void 0?0:1))throw Error(`Malformed OCSP SingleResponse`);let l,u;if(i.tag===128){if(i.value.length!==0)throw Error(`OCSP good certStatus must be empty`);return{certId:q(e.slice(r.start-r.headerLength,r.end)),certStatus:`good`,thisUpdate:b(a),...s===void 0?{}:{nextUpdate:b(x(m(e,s)[0],`nextUpdate`))}}}if(i.tag===161){let t=m(e,i);if(t.length<1||t.length>2)throw Error(`Malformed OCSP revoked certStatus`);l=b(x(t[0],`revocationTime`));let n=t[1];if(n?.tag===160){let t=m(e,n),r=x(t[0],`revocationReason`);if(t.length!==1||r.tag!==10)throw Error(`revocationReason must use ENUMERATED`);u=h(r.value,`OCSP revocationReason`)}else if(n!==void 0)throw Error(`Malformed OCSP revoked certStatus`)}else if(i.tag!==130)throw Error(`Unsupported OCSP certStatus tag: ${String(i.tag)}`);else if(i.value.length!==0)throw Error(`OCSP unknown certStatus must be empty`);return{certId:q(e.slice(r.start-r.headerLength,r.end)),certStatus:i.tag===130?`unknown`:`revoked`,thisUpdate:b(a),...s===void 0?{}:{nextUpdate:b(x(m(e,s)[0],`nextUpdate`))},...l===void 0?{}:{revokedAt:l},...u===void 0?{}:{revocationReasonCode:u}}}function be(e,t){switch(t.tag){case 130:if(t.value.length===0)throw Error(`ResponderID byKeyHash must not be empty`);return{type:`byKeyHash`,keyHashHex:C(t.value)};case 161:if(m(e,t).length!==1)throw Error(`ResponderID byName must wrap exactly one Name`);return{type:`byName`,name:xe(e,x(m(e,t)[0],`ResponderID byName`))};default:throw Error(`Unsupported OCSP responderID tag: ${String(t.tag)}`)}}function xe(e,t){if(t.tag!==48)throw Error(`ResponderID byName must use Name SEQUENCE`);let n=[],r=[],i={};for(let a of m(e,t)){let t=Se(e,a);n.push(t);for(let e of t.attributes)r.push(e),e.key!==void 0&&i[e.key]===void 0&&(i[e.key]=e.value)}return{derHex:C(e.slice(t.start-t.headerLength,t.end)),rdns:n,attributes:r,values:i}}function Se(e,t){let n=[],r={};for(let i of m(e,t)){let t=m(e,i),a=g(x(t[0],`name OID`).value),o=x(t[1],`name value`),s=Ee(a),c=_(o.tag,o.value),l=s===void 0?{oid:a,valueTag:o.tag,value:c}:{oid:a,key:s,valueTag:o.tag,value:c};n.push(l),s!==void 0&&r[s]===void 0&&(r[s]=c)}return{derHex:C(e.slice(t.start-t.headerLength,t.end)),attributes:n,values:r}}function Ce(e,t){if(e.rdns.length!==t.rdns.length)return!1;for(let n=0;n<e.rdns.length;n+=1){let r=e.rdns[n],i=t.rdns[n];if(r===void 0||i===void 0||!we(r,i))return!1}return!0}function we(e,t){if(e.attributes.length!==t.attributes.length)return!1;let n=Array(t.attributes.length).fill(!1);for(let r of e.attributes){let e=!1;for(let i=0;i<t.attributes.length;i+=1){let a=t.attributes[i];if(!(a===void 0||n[i])&&Te(r,a)){n[i]=!0,e=!0;break}}if(!e)return!1}return!0}function Te(e,t){if(e.oid!==t.oid)return!1;if(J(e.valueTag)&&J(t.valueTag)){let n=Y(e.value),r=Y(t.value);return n===void 0||r===void 0?!1:n===r}return e.valueTag===t.valueTag&&e.value===t.value}function J(e){return e===12||e===19}function Y(e){let t=e.normalize(`NFKC`);if(!/[^\P{Cc}\t\n\r]/u.test(t))return t.toLowerCase().trim().replace(/\s+/gu,` `)}function Ee(e){switch(e){case w.commonName:return`commonName`;case w.surname:return`surname`;case w.serialNumber:return`serialNumber`;case w.countryName:return`country`;case w.localityName:return`locality`;case w.stateOrProvinceName:return`state`;case w.streetAddress:return`street`;case w.organizationName:return`organization`;case w.organizationalUnitName:return`organizationalUnit`;case w.title:return`title`;case w.givenName:return`givenName`;case w.emailAddress:return`emailAddress`;default:return}}function X(e,t){let n=m(e,t),r=x(n[0],`extensions`);if(n.length!==1||r.tag!==48)throw Error(`Malformed OCSP extensions`);let i=new Set,a;for(let t of m(e,r)){let n=m(e,t);if(n.length<2||n.length>3||n.length===3&&n[1]?.tag!==1)throw Error(`Malformed OCSP extension`);let r=g(x(n[0],`extension OID`).value);if(i.has(r))throw Error(`Duplicate OCSP extension OID: ${r}`);i.add(r);let o=x(n[n.length-1],`extnValue`);if(o.tag!==4)throw Error(`OCSP extension value must use OCTET STRING`);if(r!==w.ocspNonce)continue;let s=l(o.value,{maxDepth:64});if(s.tag!==4)throw Error(`OCSP nonce extension value must use OCTET STRING`);a=C(s.value)}return a}function De(e,t){let n=[],r=t.start;for(;r<t.end;){let t=c(e,r);n.push(j(e.slice(r,t.end))),r=t.end}return n}function Z(e){let t=x(m(e,c(e))[1],`subjectPublicKey BIT STRING`);if(t.tag!==3)throw Error(`SPKI missing subjectPublicKey BIT STRING`);return t.value.slice(1)}function Oe(e){switch(e){case 0:return`successful`;case 1:return`malformedRequest`;case 2:return`internalError`;case 3:return`tryLater`;case 5:return`sigRequired`;case 6:return`unauthorized`;default:throw Error(`Unsupported OCSP responseStatus value: ${String(e)}`)}}function ke(e){return`der`in e&&e.der instanceof Uint8Array}function Ae(e){return`der`in e&&e.der instanceof Uint8Array}function Q(e){let t=new Set;for(let n of e){let e=$(n.certId);if(t.has(e))throw Error(`Duplicate OCSP response CertID`);t.add(e)}}function je(e){let t=new Set;for(let n of e){let e=Ie(n.certId.serialNumberHex);if(t.has(e))return!0;t.add(e)}return!1}function Me(e,t){let n=m(e,t),r=x(n[0],`requestorName`);if(n.length!==1||(r.tag&192)!=128)throw Error(`requestorName must wrap exactly one GeneralName`)}function Ne(e,t){let n=m(e,t),r=x(n[0],`optionalSignature`);if(n.length!==1||r.tag!==48)throw Error(`optionalSignature must wrap exactly one Signature`);let i=m(e,r);if(i.length<2||i.length>3||i[0]?.tag!==48||i[2]!==void 0&&i[2]?.tag!==160)throw Error(`Malformed optionalSignature`);let a=x(i[0],`signatureAlgorithm`),o=x(i[1],`signature`),s=i[2];if(Fe(e,a,`optionalSignature algorithm`),v(o),s!==void 0){let t=m(e,s);if(t.length!==1||t[0]?.tag!==48)throw Error(`optionalSignature certs must use SEQUENCE OF Certificate`)}}function Pe(e,t){let n=m(e,t),r=x(n[0],`nextUpdate`);if(n.length!==1||r.tag!==23&&r.tag!==24)throw Error(`nextUpdate must wrap exactly one time value`)}function Fe(e,t,n){let r=m(e,t);if(t.tag!==48||r.length<1||r.length>2||r[0]?.tag!==6)throw Error(`${n} must use AlgorithmIdentifier SEQUENCE`);g(x(r[0],`${n} OID`).value)}function Ie(e){return e.toLowerCase()}function Le(e){switch(e){case w.sha1:return`SHA-1`;case w.sha256:return`SHA-256`;default:throw Error(`Unsupported OCSP hash algorithm OID: ${e}`)}}function $(e){return[e.hashAlgorithmOid,e.issuerNameHashHex,e.issuerKeyHashHex,e.serialNumberHex].join(`:`)}export{se as createOcspRequest,ce as createOcspResponse,N as parseOcspRequestDer,P as parseOcspRequestPem,F as parseOcspResponseDer,I as parseOcspResponsePem,le as validateOcspResponse,L as verifyOcspResponse};
|
|
1
|
+
import{bitString as e,concatBytes as t,explicitContext as n,implicitPrimitiveContext as r,integer as i,nullValue as a,objectIdentifier as o,octetString as s,readElement as c,readRootElement as l,readSequenceChildren as u,sequence as d,time as f,tlv as p}from"../internal/asn1/der.js";import{childrenOf as m,decodeNonNegativeIntegerNumber as h,decodeObjectIdentifier as g,decodeString as _,extractBitStringValue as v,hexToBytes as y,parseTime as b,requireElement as x,toArrayBuffer as S,toHex as C}from"../internal/asn1/asn1.js";import{OIDS as w}from"../internal/asn1/oids.js";import{getCrypto as T}from"../internal/crypto/webcrypto.js";import{base64Encode as E}from"../internal/shared/base64.js";import{pemDecode as D,pemEncode as O}from"../pem/pem.js";import{failureResult as k}from"../result/result.js";import{describeHashAlgorithm as A,describeSignatureAlgorithm as ee}from"../internal/crypto/algorithm-names.js";import{parseCertificateDerOrThrow as j,parseCertificateFromSource as te}from"../x509/parse.js";import{verifySignedDataDetailed as ne}from"../internal/crypto/sig-verify.js";import{encodeAlgorithmIdentifier as re,getSignatureAlgorithm as ie,signBytes as ae}from"../internal/crypto/signing.js";import{compareDistinguishedNames as M}from"../internal/shared/dn.js";import{checkCertificateRevocationAgainstCrl as oe,parseCertificateRevocationListDer as se,parseCertificateRevocationListPem as ce}from"./crl.js";import{verifyCertificateChain as le}from"../verify/verify.js";async function ue(e){let t=e.hashAlgorithm??`SHA-1`,r=[];for(let n of e.requests){let e=await q(n.certificate),i=await q(n.issuerCertificate);r.push(d([await W(e,i,t)]))}let i=[d(r)];e.nonce!==void 0&&i.push(n(2,d([d([o(w.ocspNonce),s(s(e.nonce))])])));let a=d([d(i)]);return{der:a,pem:O(`OCSP REQUEST`,a),base64:E(a)}}function N(e){let t=u(e,{maxDepth:64});if(t.length<1||t.length>2)throw Error(`Malformed OCSP request`);let n=x(t[0],`tbsRequest`),r=t[1];if(r!==void 0&&r.tag!==160)throw Error(`Malformed OCSP request`);r!==void 0&&ze(e,r);let i=m(e,n),a=0;if(i[a]?.tag===160){let t=m(e,x(i[a],`version`)),n=x(t[0],`version`);if(t.length!==1||n.tag!==2)throw Error(`version must use INTEGER`);if(h(n.value,`OCSP request version`)!==0)throw Error(`Unsupported OCSP request version`);a+=1}let o=i[a];o?.tag===161&&(Re(e,o),a+=1);let s=x(i[a],`requestList`);if(s.tag!==48)throw Error(`requestList must use SEQUENCE`);if(m(e,s).length===0)throw Error(`requestList must not be empty`);let c=m(e,s).map(t=>{let n=m(e,t);if(n.length<1||n.length>2||n[1]!==void 0&&n[1].tag!==160)throw Error(`Malformed OCSP request entry`);let r=x(n[0],`reqCert`);return J(e.slice(r.start-r.headerLength,r.end))});a+=1;let l=i[a];if(l!==void 0&&l.tag!==162||i.length!==a+(l===void 0?0:1))throw Error(`Malformed OCSP request`);let d=l===void 0?void 0:Z(e,l);return{der:new Uint8Array(e),requests:c,...d===void 0?{}:{nonce:d}}}function P(e){return N(D(`OCSP REQUEST`,e))}function F(e){let t=u(e,{maxDepth:64});if(t.length<1||t.length>2)throw Error(`Malformed OCSP response`);let n=x(t[0],`responseStatus`);if(n.tag!==10)throw Error(`responseStatus must use ENUMERATED`);let r=Ne(h(n.value,`OCSP responseStatus`)),i=t[1];if(i===void 0)return{der:new Uint8Array(e),responseStatus:r};if(i.tag!==160)throw Error(`Malformed OCSP response`);let a=m(e,i),o=x(a[0],`responseBytes`);if(a.length!==1||o.tag!==48)throw Error(`Malformed OCSP response`);let s=m(e,o);if(s.length!==2)throw Error(`responseBytes must contain responseType and response`);let c=x(s[0],`responseType`),l=x(s[1],`response`);if(l.tag!==4)throw Error(`response must use OCTET STRING`);let d=g(c.value);if(d!==w.ocspBasicResponse)return{der:new Uint8Array(e),responseStatus:r,responseTypeOid:d};let f=l.value,p=u(f);if(p.length<3||p.length>4)throw Error(`Malformed BasicOCSPResponse`);let _=x(p[0],`responseData`),y=x(p[1],`signatureAlgorithm`),b=x(p[2],`signatureValue`),S=p[3];if(S!==void 0&&S.tag!==160)throw Error(`Malformed BasicOCSPResponse`);let C=m(f,y),T=g(x(C[0],`signatureAlgorithm OID`).value),E=C[1],D=f.slice(_.start-_.headerLength,_.end),O=_e(D);return{der:new Uint8Array(e),responseStatus:r,responseTypeOid:d,responseDataDer:D,responderId:O.responderId,signatureAlgorithmOid:T,signatureAlgorithmName:ee(T,E===void 0?void 0:f.slice(E.start-E.headerLength,E.end)),signatureValue:v(b),producedAt:O.producedAt,responses:O.responses,...O.nonce===void 0?{}:{nonce:O.nonce},...S?.tag===160?{certificates:Me(f,S)}:{}}}function I(e){return F(D(`OCSP RESPONSE`,e))}async function de(i){let a=await q(i.signerCertificate),c=ie(i.signerPrivateKey),l=i.producedAt??new Date,u=i.hashAlgorithm??`SHA-1`,m=[];for(let e of i.responses){let t=await q(e.certificate),n=await q(e.issuerCertificate);m.push(await xe(t,n,e,u))}let h=[r(2,await K(`SHA-1`,Q(a.subjectPublicKeyInfoDer))),f(l),d(m)];i.nonce!==void 0&&h.push(n(1,d([d([o(w.ocspNonce),s(s(i.nonce))])])));let g=d(h),_=await ae(i.signerPrivateKey,c,g),v=i.includedCertificates===void 0?[]:await Promise.all(i.includedCertificates.map(q)),y=[g,re(c),e(_)];v.length>0&&y.push(n(0,t(v.map(e=>e.der))));let b=d(y),x=d([p(10,Uint8Array.of(0)),n(0,d([o(w.ocspBasicResponse),s(b)]))]);return{der:x,pem:O(`OCSP RESPONSE`,x),base64:E(x)}}async function fe(e,t){let n;try{n=B(e)}catch{return L(`signature_invalid`,`OCSP response signed content is malformed`)}if(n.responseDataDer===void 0||n.signatureAlgorithmOid===void 0||n.signatureValue===void 0)return L(`signature_invalid`,`OCSP response is not signed`);let r;try{r=await q(t)}catch{return L(`signature_invalid`,`OCSP signer certificate input is malformed`)}let i;try{i=await ne(n.signatureAlgorithmOid,void 0,r.publicKeyAlgorithmOid,r.publicKeyParametersOid,r.subjectPublicKeyInfoDer,n.signatureValue,n.responseDataDer)}catch{return L(`signature_invalid`,`OCSP response signature verification failed`)}return i.ok?i.valid?{ok:!0,value:n}:L(`signature_invalid`,`OCSP response signature does not verify`):i.code===`verification_error`?L(`signature_invalid`,`OCSP response signature verification failed`):L(`signature_invalid`,`OCSP response signature uses unsupported algorithm parameters`)}async function pe(e){let t;try{t=B(e.response)}catch{return R(`signature_invalid`,`OCSP response signed content is malformed`)}if(t.responseStatus!==`successful`)return R(`response_status_invalid`,`OCSP response status is ${t.responseStatus}`);let n;try{n=await q(e.issuerCertificate)}catch{return R(`signature_invalid`,`issuer certificate input is malformed`)}let r,i;try{i=(e.trustedResponderCertificates??[]).map(q),r=e.responderCertificate??await V(t.certificates,t.responderId)??await V(i,t.responderId)??t.certificates?.[0]??e.issuerCertificate}catch{return R(`signature_invalid`,`OCSP responder certificate input is malformed`)}let a;try{a=await q(r)}catch{return R(`signature_invalid`,`OCSP responder certificate input is malformed`)}let o=await fe(t,a);if(!o.ok)return R(o.code,o.message);let s;try{s=await ve(t.responderId,a)}catch{return R(`signature_invalid`,`OCSP responder certificate input is malformed`)}if(!s.ok)return s;let c=i.some(e=>U(a,e));if(!U(a,n)&&!c){let r=e.allowChainedResponderCertificate===!0;if(!r&&!ye(a,n))return R(`responder_chain_invalid`,`Delegated OCSP responder must be directly issued by issuer certificate`);if(!(await le({leaf:a.der,intermediates:r?be(t.certificates,a,n):[],roots:[n.der],...e.at===void 0?{}:{at:e.at}})).ok)return R(`responder_chain_invalid`,`OCSP responder certificate chain does not validate`);if(a.extendedKeyUsage===void 0||!a.extendedKeyUsage.includes(`ocspSigning`))return R(`ocsp_signing_missing`,`Delegated OCSP responder lacks ocspSigning EKU`);let i=await he(a,n,e);if(!i.ok)return i}let l=e.at??new Date,u=e.clockSkewMs??0;if(t.producedAt!==void 0&&t.producedAt.getTime()-u>l.getTime())return R(`stale_response`,`OCSP response producedAt is later than requested time`);for(let e of t.responses??[]){let r;try{r=await G(e.certId.hashAlgorithmOid,n,e.certId.serialNumberHex)}catch{return R(`signature_invalid`,`OCSP response CertID hash algorithm is unsupported`)}if(e.certId.issuerNameHashHex!==r.issuerNameHashHex||e.certId.issuerKeyHashHex!==r.issuerKeyHashHex)return R(`issuer_mismatch`,`OCSP response certId does not match issuer certificate`);if(e.thisUpdate.getTime()-u>l.getTime()||e.nextUpdate!==void 0&&e.nextUpdate.getTime()+u<l.getTime())return R(`stale_response`,`OCSP response is not valid at requested time`);if(t.producedAt!==void 0&&e.nextUpdate!==void 0&&t.producedAt.getTime()-u>e.nextUpdate.getTime())return R(`stale_response`,`OCSP response producedAt is later than nextUpdate`)}if(Le(t.responses??[]))return R(`signature_invalid`,`OCSP response contains multiple status entries for the same certificate`);if(e.request!==void 0){let n;try{n=ge(e.request)}catch{return R(`request_mismatch`,`OCSP request input is malformed`)}if(n.nonce!==void 0&&n.nonce!==t.nonce)return R(`nonce_mismatch`,`OCSP response nonce does not match request nonce`);let r=new Set(n.requests.map(e=>$(e))),i=new Set((t.responses??[]).map(e=>$(e.certId)));for(let e of t.responses??[])if(!r.has($(e.certId)))return R(`request_mismatch`,`OCSP response includes a certId not present in request`);for(let e of r)if(!i.has(e))return R(`request_mismatch`,`OCSP response does not cover every requested certId`)}return{ok:!0,value:t}}function L(e,t){return k(e,t)}function R(e,t){return k(e,t)}function z(e){return q(e).extensions.some(e=>e.oid===w.ocspNoCheck)}function me(e){return typeof e==`object`&&`issuer`in e?e:typeof e==`string`?ce(e):se(e)}async function he(e,t,n){let r=n.responderRevocationPolicy??`honor-nocheck`;if(r===`skip`||r===`honor-nocheck`&&z(e))return{ok:!0};let i=n.at??new Date,a=!1;for(let r of n.responderRevocationCrls??[]){let n;try{n=me(r)}catch{continue}let o=await oe({certificate:e,issuerCertificate:t,crl:n,at:i});if(o.ok){if(o.value.status===`revoked`)return R(`responder_revoked`,`Delegated OCSP responder certificate is revoked`);o.value.status===`good`&&(a=!0)}}return a||r===`honor-nocheck`?{ok:!0}:R(`responder_revocation_unknown`,`Delegated OCSP responder revocation status could not be established`)}function B(e){if(typeof e==`string`)return I(e);if(e instanceof Uint8Array)return F(e);if(Fe(e))return F(new Uint8Array(e.der));throw Error(`OCSP response input is malformed`)}function ge(e){if(typeof e==`string`)return P(e);if(e instanceof Uint8Array)return N(e);if(Pe(e))return N(new Uint8Array(e.der));throw Error(`OCSP request input is malformed`)}function _e(e){let t=u(e);if(t.length<3||t.length>5)throw Error(`Malformed OCSP responseData`);let n=0;if(t[n]?.tag===160){let r=m(e,x(t[n],`version`)),i=x(r[0],`version`);if(r.length!==1||i.tag!==2)throw Error(`version must use INTEGER`);if(h(i.value,`OCSP response version`)!==0)throw Error(`Unsupported OCSP response version`);n+=1}let r=Te(e,x(t[n],`responderID`));n+=1;let i=x(t[n],`producedAt`),a=x(t[n+1],`responses`);if(a.tag!==48)throw Error(`responses must use SEQUENCE`);if(m(e,a).length===0)throw Error(`responses must not be empty`);let o=t[n+2];if(o!==void 0&&o.tag!==161||t.length!==n+2+(o===void 0?0:1))throw Error(`Malformed OCSP responseData`);let s=o===void 0?void 0:Z(e,o),c=m(e,a).map(t=>we(e,t));return Ie(c),{responderId:r,producedAt:b(i),responses:c,...s===void 0?{}:{nonce:s}}}async function V(e,t){if(!(e===void 0||t===void 0)){for(let n of e)if(await H(t,n))return n}}async function ve(e,t){return e===void 0||await H(e,t)?{ok:!0}:e.type===`byName`?R(`responder_id_mismatch`,`OCSP responder certificate subject does not match responderID byName`):R(`responder_id_mismatch`,`OCSP responder certificate public key does not match responderID byKeyHash`)}async function H(e,t){return e.type===`byName`?Oe(e.name,t.subject):C(await K(`SHA-1`,Q(t.subjectPublicKeyInfoDer)))===e.keyHashHex}function U(e,t){return e.serialNumberHex===t.serialNumberHex&&M(e.issuer,t.issuer)&&M(e.subject,t.subject)&&e.subjectPublicKeyInfoDer.length===t.subjectPublicKeyInfoDer.length&&e.subjectPublicKeyInfoDer.every((e,n)=>e===t.subjectPublicKeyInfoDer[n])}function ye(e,t){return!(!M(e.issuer,t.subject)||e.authorityKeyIdentifier!==void 0&&t.subjectKeyIdentifier!==void 0&&e.authorityKeyIdentifier!==t.subjectKeyIdentifier)}function be(e,t,n){if(e===void 0)return[];let r=[];for(let i of e)U(i,t)||U(i,n)||r.push(i.der);return r}async function W(e,t,n){let r=n===`SHA-1`?w.sha1:w.sha256,c=await G(r,t,e.serialNumberHex);return d([d([o(r),a()]),s(y(c.issuerNameHashHex)),s(y(c.issuerKeyHashHex)),i(y(c.serialNumberHex))])}async function G(e,t,n){let r=Ue(e);return{hashAlgorithmOid:e,hashAlgorithmName:A(e),issuerNameHashHex:C(await K(r,y(t.subject.derHex))),issuerKeyHashHex:C(await K(r,Q(t.subjectPublicKeyInfoDer))),serialNumberHex:n}}async function K(e,t){return new Uint8Array(await T().subtle.digest(e,S(t)))}async function xe(e,t,r,i){return d([await W(e,t,i),Se(r),f(r.thisUpdate??new Date),...r.nextUpdate===void 0?[]:[n(0,f(r.nextUpdate))]])}function Se(e){switch(e.certStatus){case`good`:return p(128,new Uint8Array);case`unknown`:return p(130,new Uint8Array);case`revoked`:{let r=[f(e.revokedAt??e.thisUpdate??new Date)];return e.revocationReasonCode!==void 0&&r.push(n(0,p(10,Uint8Array.of(e.revocationReasonCode)))),p(161,t(r))}}}function q(e){return Ce(e)?j(new Uint8Array(e.der)):te(e)}function Ce(e){return typeof e!=`string`&&`subjectPublicKeyInfoDer`in e}function J(e){let t=l(e,{maxDepth:64});if(t.tag!==48)throw Error(`CertID must use SEQUENCE`);let n=m(e,t);if(n.length!==4)throw Error(`CertID must contain hashAlgorithm, issuerNameHash, issuerKeyHash, and serialNumber`);let r=x(n[0],`hashAlgorithm`);if(r.tag!==48)throw Error(`hashAlgorithm must use SEQUENCE`);let i=m(e,r);if(i.length<1||i.length>2)throw Error(`Malformed hashAlgorithm`);let a=g(x(i[0],`hashAlgorithm OID`).value);if(x(n[1],`issuerNameHash`).tag!==4)throw Error(`issuerNameHash must use OCTET STRING`);if(x(n[2],`issuerKeyHash`).tag!==4)throw Error(`issuerKeyHash must use OCTET STRING`);let o=x(n[3],`serialNumber`);if(o.tag!==2)throw Error(`serialNumber must use INTEGER`);return{hashAlgorithmOid:a,hashAlgorithmName:A(a),issuerNameHashHex:C(x(n[1],`issuerNameHash`).value),issuerKeyHashHex:C(x(n[2],`issuerKeyHash`).value),serialNumberHex:C(o.value)}}function we(e,t){let n=m(e,t);if(n.length<3||n.length>5)throw Error(`Malformed OCSP SingleResponse`);let r=x(n[0],`certId`),i=x(n[1],`certStatus`),a=x(n[2],`thisUpdate`),o=3,s=n[o]?.tag===160?n[o]:void 0;s!==void 0&&(Be(e,s),o+=1);let c=n[o];if(c!==void 0&&c.tag!==161||n.length!==o+(c===void 0?0:1))throw Error(`Malformed OCSP SingleResponse`);let l,u;if(i.tag===128){if(i.value.length!==0)throw Error(`OCSP good certStatus must be empty`);return{certId:J(e.slice(r.start-r.headerLength,r.end)),certStatus:`good`,thisUpdate:b(a),...s===void 0?{}:{nextUpdate:b(x(m(e,s)[0],`nextUpdate`))}}}if(i.tag===161){let t=m(e,i);if(t.length<1||t.length>2)throw Error(`Malformed OCSP revoked certStatus`);l=b(x(t[0],`revocationTime`));let n=t[1];if(n?.tag===160){let t=m(e,n),r=x(t[0],`revocationReason`);if(t.length!==1||r.tag!==10)throw Error(`revocationReason must use ENUMERATED`);u=h(r.value,`OCSP revocationReason`)}else if(n!==void 0)throw Error(`Malformed OCSP revoked certStatus`)}else if(i.tag!==130)throw Error(`Unsupported OCSP certStatus tag: ${String(i.tag)}`);else if(i.value.length!==0)throw Error(`OCSP unknown certStatus must be empty`);return{certId:J(e.slice(r.start-r.headerLength,r.end)),certStatus:i.tag===130?`unknown`:`revoked`,thisUpdate:b(a),...s===void 0?{}:{nextUpdate:b(x(m(e,s)[0],`nextUpdate`))},...l===void 0?{}:{revokedAt:l},...u===void 0?{}:{revocationReasonCode:u}}}function Te(e,t){switch(t.tag){case 130:if(t.value.length===0)throw Error(`ResponderID byKeyHash must not be empty`);return{type:`byKeyHash`,keyHashHex:C(t.value)};case 161:if(m(e,t).length!==1)throw Error(`ResponderID byName must wrap exactly one Name`);return{type:`byName`,name:Ee(e,x(m(e,t)[0],`ResponderID byName`))};default:throw Error(`Unsupported OCSP responderID tag: ${String(t.tag)}`)}}function Ee(e,t){if(t.tag!==48)throw Error(`ResponderID byName must use Name SEQUENCE`);let n=[],r=[],i={};for(let a of m(e,t)){let t=De(e,a);n.push(t);for(let e of t.attributes)r.push(e),e.key!==void 0&&i[e.key]===void 0&&(i[e.key]=e.value)}return{derHex:C(e.slice(t.start-t.headerLength,t.end)),rdns:n,attributes:r,values:i}}function De(e,t){let n=[],r={};for(let i of m(e,t)){let t=m(e,i),a=g(x(t[0],`name OID`).value),o=x(t[1],`name value`),s=je(a),c=_(o.tag,o.value),l=s===void 0?{oid:a,valueTag:o.tag,value:c}:{oid:a,key:s,valueTag:o.tag,value:c};n.push(l),s!==void 0&&r[s]===void 0&&(r[s]=c)}return{derHex:C(e.slice(t.start-t.headerLength,t.end)),attributes:n,values:r}}function Oe(e,t){if(e.rdns.length!==t.rdns.length)return!1;for(let n=0;n<e.rdns.length;n+=1){let r=e.rdns[n],i=t.rdns[n];if(r===void 0||i===void 0||!ke(r,i))return!1}return!0}function ke(e,t){if(e.attributes.length!==t.attributes.length)return!1;let n=Array(t.attributes.length).fill(!1);for(let r of e.attributes){let e=!1;for(let i=0;i<t.attributes.length;i+=1){let a=t.attributes[i];if(!(a===void 0||n[i])&&Ae(r,a)){n[i]=!0,e=!0;break}}if(!e)return!1}return!0}function Ae(e,t){if(e.oid!==t.oid)return!1;if(Y(e.valueTag)&&Y(t.valueTag)){let n=X(e.value),r=X(t.value);return n===void 0||r===void 0?!1:n===r}return e.valueTag===t.valueTag&&e.value===t.value}function Y(e){return e===12||e===19}function X(e){let t=e.normalize(`NFKC`);if(!/[^\P{Cc}\t\n\r]/u.test(t))return t.toLowerCase().trim().replace(/\s+/gu,` `)}function je(e){switch(e){case w.commonName:return`commonName`;case w.surname:return`surname`;case w.serialNumber:return`serialNumber`;case w.countryName:return`country`;case w.localityName:return`locality`;case w.stateOrProvinceName:return`state`;case w.streetAddress:return`street`;case w.organizationName:return`organization`;case w.organizationalUnitName:return`organizationalUnit`;case w.title:return`title`;case w.givenName:return`givenName`;case w.emailAddress:return`emailAddress`;default:return}}function Z(e,t){let n=m(e,t),r=x(n[0],`extensions`);if(n.length!==1||r.tag!==48)throw Error(`Malformed OCSP extensions`);let i=new Set,a;for(let t of m(e,r)){let n=m(e,t);if(n.length<2||n.length>3||n.length===3&&n[1]?.tag!==1)throw Error(`Malformed OCSP extension`);let r=g(x(n[0],`extension OID`).value);if(i.has(r))throw Error(`Duplicate OCSP extension OID: ${r}`);i.add(r);let o=x(n[n.length-1],`extnValue`);if(o.tag!==4)throw Error(`OCSP extension value must use OCTET STRING`);if(r!==w.ocspNonce)continue;let s=l(o.value,{maxDepth:64});if(s.tag!==4)throw Error(`OCSP nonce extension value must use OCTET STRING`);a=C(s.value)}return a}function Me(e,t){let n=[],r=t.start;for(;r<t.end;){let t=c(e,r);n.push(j(e.slice(r,t.end))),r=t.end}return n}function Q(e){let t=x(m(e,c(e))[1],`subjectPublicKey BIT STRING`);if(t.tag!==3)throw Error(`SPKI missing subjectPublicKey BIT STRING`);return t.value.slice(1)}function Ne(e){switch(e){case 0:return`successful`;case 1:return`malformedRequest`;case 2:return`internalError`;case 3:return`tryLater`;case 5:return`sigRequired`;case 6:return`unauthorized`;default:throw Error(`Unsupported OCSP responseStatus value: ${String(e)}`)}}function Pe(e){return`der`in e&&e.der instanceof Uint8Array}function Fe(e){return`der`in e&&e.der instanceof Uint8Array}function Ie(e){let t=new Set;for(let n of e){let e=$(n.certId);if(t.has(e))throw Error(`Duplicate OCSP response CertID`);t.add(e)}}function Le(e){let t=new Set;for(let n of e){let e=He(n.certId.serialNumberHex);if(t.has(e))return!0;t.add(e)}return!1}function Re(e,t){let n=m(e,t),r=x(n[0],`requestorName`);if(n.length!==1||(r.tag&192)!=128)throw Error(`requestorName must wrap exactly one GeneralName`)}function ze(e,t){let n=m(e,t),r=x(n[0],`optionalSignature`);if(n.length!==1||r.tag!==48)throw Error(`optionalSignature must wrap exactly one Signature`);let i=m(e,r);if(i.length<2||i.length>3||i[0]?.tag!==48||i[2]!==void 0&&i[2]?.tag!==160)throw Error(`Malformed optionalSignature`);let a=x(i[0],`signatureAlgorithm`),o=x(i[1],`signature`),s=i[2];if(Ve(e,a,`optionalSignature algorithm`),v(o),s!==void 0){let t=m(e,s);if(t.length!==1||t[0]?.tag!==48)throw Error(`optionalSignature certs must use SEQUENCE OF Certificate`)}}function Be(e,t){let n=m(e,t),r=x(n[0],`nextUpdate`);if(n.length!==1||r.tag!==23&&r.tag!==24)throw Error(`nextUpdate must wrap exactly one time value`)}function Ve(e,t,n){let r=m(e,t);if(t.tag!==48||r.length<1||r.length>2||r[0]?.tag!==6)throw Error(`${n} must use AlgorithmIdentifier SEQUENCE`);g(x(r[0],`${n} OID`).value)}function He(e){return e.toLowerCase()}function Ue(e){switch(e){case w.sha1:return`SHA-1`;case w.sha256:return`SHA-256`;default:throw Error(`Unsupported OCSP hash algorithm OID: ${e}`)}}function $(e){return[e.hashAlgorithmOid,e.issuerNameHashHex,e.issuerKeyHashHex,e.serialNumberHex].join(`:`)}export{ue as createOcspRequest,de as createOcspResponse,z as hasOcspNoCheckExtension,N as parseOcspRequestDer,P as parseOcspRequestPem,F as parseOcspResponseDer,I as parseOcspResponsePem,pe as validateOcspResponse,fe as verifyOcspResponse};
|
|
2
2
|
//# sourceMappingURL=ocsp.js.map
|