micro509 0.11.0 → 0.12.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.
@@ -731,7 +731,7 @@ function compareOcspResponderNames(e, t) {
731
731
  /** Set-equality comparison for RDN attribute sets (order-independent). */
732
732
  function compareOcspRelativeDistinguishedNames(e, t) {
733
733
  if (e.attributes.length !== t.attributes.length) return !1;
734
- let n = Array(t.attributes.length).fill(!1);
734
+ let n = Array.from({ length: t.attributes.length }, () => !1);
735
735
  for (let r of e.attributes) {
736
736
  let e = !1;
737
737
  for (let i = 0; i < t.attributes.length; i += 1) {
@@ -1 +1 @@
1
- {"version":3,"file":"ocsp.js","names":[],"sources":["../../src/revocation/ocsp.ts"],"sourcesContent":["/**\n * Full OCSP lifecycle: build requests, create/parse/verify/validate responses.\n *\n * Supports SHA-1 and SHA-256 cert-ID hashing, nonce replay protection,\n * delegated responder certificate validation (direct and chain-based),\n * and embedded responder certificate discovery.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\textractBitStringValue,\n\thexToBytes,\n\tparseTime,\n\trequireElement,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\tbitString,\n\tconcatBytes,\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\timplicitPrimitiveContext,\n\tinteger,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\ttime,\n\ttlv,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport {\n\tdescribeHashAlgorithm,\n\tdescribeSignatureAlgorithm,\n} from '#micro509/internal/crypto/algorithm-names';\nimport { verifySignedDataDetailed } from '#micro509/internal/crypto/sig-verify';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport { compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport { pemDecodeOrThrow, pemEncode } from '#micro509/pem/pem';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, successResult } from '#micro509/result/result';\nimport type { CrlSource, ParsedCertificateRevocationList } from '#micro509/revocation/crl';\nimport {\n\tcheckCertificateRevocationAgainstCrl,\n\tparseCertificateRevocationListDerOrThrow,\n\tparseCertificateRevocationListPemOrThrow,\n} from '#micro509/revocation/crl';\nimport { verifyCertificateChain } from '#micro509/verify/verify';\nimport type {\n\tNameFieldKey,\n\tParsedCertificate,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow, parseCertificateFromSource } from '#micro509/x509/parse';\n\n/** Hash algorithm used to compute OCSP CertID fields. SHA-1 is the RFC 6960 default. */\nexport type OcspHashAlgorithm = 'SHA-1' | 'SHA-256';\n/** PEM string, DER bytes, or already-parsed certificate. */\nexport type OcspCertificateSource = string | Uint8Array | ParsedCertificate;\n/** PEM string, DER bytes, or already-parsed OCSP request. */\nexport type OcspRequestSource = string | Uint8Array | ParsedOcspRequest;\n\n/**\n * One certificate whose status to query in an OCSP request.\n * Used as an element of {@linkcode CreateOcspRequestInput.requests}.\n */\nexport interface CreateOcspRequestItemInput {\n\t/** Certificate whose revocation status is being queried. */\n\treadonly certificate: OcspCertificateSource;\n\t/** Issuer of `certificate` — needed to compute the CertID hash. */\n\treadonly issuerCertificate: OcspCertificateSource;\n}\n\n/**\n * Input for {@linkcode createOcspRequest}.\n */\nexport interface CreateOcspRequestInput {\n\t/** One or more certificates to query (batched into a single OCSP request). */\n\treadonly requests: readonly CreateOcspRequestItemInput[];\n\t/** Hash algorithm for CertID computation. Defaults to `'SHA-1'`. */\n\treadonly hashAlgorithm?: OcspHashAlgorithm;\n\t/** Random nonce for replay protection. Omit to skip the nonce extension. */\n\treadonly nonce?: Uint8Array;\n}\n\n/**\n * Encoded OCSP request in multiple serialisation formats, returned by {@linkcode createOcspRequest}.\n */\nexport interface OcspRequestMaterial {\n\t/** Raw DER bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-encoded request (`-----BEGIN OCSP REQUEST-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armour). */\n\treadonly base64: string;\n}\n\n/**\n * Decoded OCSP CertID — identifies a certificate by hashed issuer name,\n * hashed issuer key, and serial number.\n */\nexport interface ParsedOcspCertId {\n\t/** OID of the hash algorithm used for the name and key hashes. */\n\treadonly hashAlgorithmOid: string;\n\t/** Human-readable hash algorithm name (e.g. `\"SHA-256\"`). */\n\treadonly hashAlgorithmName: string;\n\t/** Hex-encoded hash of the issuer's distinguished name DER. */\n\treadonly issuerNameHashHex: string;\n\t/** Hex-encoded hash of the issuer's SubjectPublicKey BIT STRING content. */\n\treadonly issuerKeyHashHex: string;\n\t/** Hex-encoded serial number of the certificate. */\n\treadonly serialNumberHex: string;\n}\n\n/**\n * Decoded OCSP request, returned by {@linkcode parseOcspRequestDer} / {@linkcode parseOcspRequestPem}.\n */\nexport interface ParsedOcspRequest {\n\t/** Original DER bytes when this object came from {@linkcode parseOcspRequestDer} or PEM parsing. */\n\treadonly der?: Uint8Array;\n\t/** CertIDs of the certificates being queried. */\n\treadonly requests: readonly ParsedOcspCertId[];\n\t/** Hex-encoded nonce extension value, if present. */\n\treadonly nonce?: string;\n}\n\n/** RFC 6960 certificate status reported by the responder for a single CertID. */\nexport type OcspCertStatus = 'good' | 'revoked' | 'unknown';\n/** RFC 6960 overall response status — anything other than `'successful'` means the response body is absent or unusable. */\nexport type OcspResponseStatus =\n\t| 'successful'\n\t| 'malformedRequest'\n\t| 'internalError'\n\t| 'tryLater'\n\t| 'sigRequired'\n\t| 'unauthorized';\n\n/**\n * Status of one certificate inside an OCSP BasicResponse.\n */\nexport interface ParsedOcspSingleResponse {\n\t/** Which certificate this status applies to. */\n\treadonly certId: ParsedOcspCertId;\n\t/** Responder's verdict: `good`, `revoked`, or `unknown`. */\n\treadonly certStatus: OcspCertStatus;\n\t/** Start of the validity window for this status assertion. */\n\treadonly thisUpdate: Date;\n\t/** End of the validity window. Absent if the responder does not commit to a schedule. */\n\treadonly nextUpdate?: Date;\n\t/** When the certificate was revoked (only for `certStatus === 'revoked'`). */\n\treadonly revokedAt?: Date;\n\t/** CRLReason integer (only for `certStatus === 'revoked'`). */\n\treadonly revocationReasonCode?: number;\n}\n\n/**\n * How the OCSP responder identifies itself — either by distinguished name or\n * by SHA-1 hash of its public key.\n */\nexport type ParsedOcspResponderId =\n\t| {\n\t\t\t/** Responder identified by its certificate subject name. */\n\t\t\treadonly type: 'byName';\n\t\t\t/** Parsed distinguished name of the responder. */\n\t\t\treadonly name: ParsedName;\n\t }\n\t| {\n\t\t\t/** Responder identified by public-key hash. */\n\t\t\treadonly type: 'byKeyHash';\n\t\t\t/** Hex-encoded SHA-1 hash of the responder's SubjectPublicKey content. */\n\t\t\treadonly keyHashHex: string;\n\t };\n\n/**\n * Decoded OCSP response, returned by {@linkcode parseOcspResponseDer} / {@linkcode parseOcspResponsePem}.\n *\n * When `responseStatus` is not `'successful'`, most fields are absent.\n */\nexport interface ParsedOcspResponse {\n\t/** Original DER bytes when this object came from {@linkcode parseOcspResponseDer} or PEM parsing. */\n\treadonly der?: Uint8Array;\n\t/** Overall response status. Only `'successful'` carries a BasicOCSPResponse body. */\n\treadonly responseStatus: OcspResponseStatus;\n\t/** OID of the response type (normally `id-pkix-ocsp-basic`). */\n\treadonly responseTypeOid?: string;\n\t/** DER-encoded ResponseData — the signed payload for signature verification. */\n\treadonly responseDataDer?: Uint8Array;\n\t/** How the responder identifies itself. */\n\treadonly responderId?: ParsedOcspResponderId;\n\t/** OID of the algorithm used to sign this response. */\n\treadonly signatureAlgorithmOid?: string;\n\t/** Human-readable signature algorithm name. */\n\treadonly signatureAlgorithmName?: string;\n\t/** Raw signature bytes. */\n\treadonly signatureValue?: Uint8Array;\n\t/** Timestamp when the responder produced this response. */\n\treadonly producedAt?: Date;\n\t/** Per-certificate status entries. */\n\treadonly responses?: readonly ParsedOcspSingleResponse[];\n\t/** Hex-encoded nonce, if the response echoed one. */\n\treadonly nonce?: string;\n\t/** Certificates embedded in the response (typically the responder's chain). */\n\treadonly certificates?: readonly ParsedCertificate[];\n}\n\n/**\n * One certificate's status entry for {@linkcode CreateOcspResponseInput.responses}.\n * Extends {@linkcode CreateOcspRequestItemInput} with status and timing fields.\n */\nexport interface CreateOcspSingleResponseInput extends CreateOcspRequestItemInput {\n\t/** Status to assert for this certificate. */\n\treadonly certStatus: OcspCertStatus;\n\t/** Start of the validity window for this status assertion. Defaults to `new Date()`. */\n\treadonly thisUpdate?: Date;\n\t/** End of the validity window. Omit for open-ended assertions. */\n\treadonly nextUpdate?: Date;\n\t/** Revocation time (required when `certStatus` is `'revoked'`). Defaults to `thisUpdate`. */\n\treadonly revokedAt?: Date;\n\t/** CRLReason integer code (only meaningful when `certStatus` is `'revoked'`). */\n\treadonly revocationReasonCode?: number;\n}\n\n/**\n * Input for {@linkcode createOcspResponse}.\n */\nexport interface CreateOcspResponseInput {\n\t/** Private key used to sign the response. Algorithm is inferred from the key. */\n\treadonly signerPrivateKey: CryptoKey;\n\t/** Certificate of the OCSP responder — used to build the responder ID (by key hash). */\n\treadonly signerCertificate: OcspCertificateSource;\n\t/** Per-certificate status entries to include in the BasicOCSPResponse. */\n\treadonly responses: readonly CreateOcspSingleResponseInput[];\n\t/** Timestamp for the `producedAt` field. Defaults to `new Date()`. */\n\treadonly producedAt?: Date;\n\t/** Nonce to echo back for replay protection. */\n\treadonly nonce?: Uint8Array;\n\t/** Hash algorithm for CertID computation. Defaults to `'SHA-1'`. */\n\treadonly hashAlgorithm?: OcspHashAlgorithm;\n\t/** Extra certificates to embed in the response (e.g. the responder's issuer chain). */\n\treadonly includedCertificates?: readonly OcspCertificateSource[];\n}\n\n/**\n * Encoded OCSP response in multiple serialisation formats, returned by {@linkcode createOcspResponse}.\n */\nexport interface OcspResponseMaterial {\n\t/** Raw DER bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-encoded response (`-----BEGIN OCSP RESPONSE-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armour). */\n\treadonly base64: string;\n}\n\n/** Failure detail when OCSP response signature verification fails. */\nexport interface VerifyOcspResponseSignatureFailure extends Micro509Error<'signature_invalid'> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Result of {@linkcode verifyOcspResponseSignature}.\n *\n * On success, `value` is the parsed response whose signature has been verified.\n */\nexport type VerifyOcspResponseSignatureResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** Parsed response with a verified signature. */\n\t\t\treadonly value: ParsedOcspResponse;\n\t }\n\t| ErrorResult<'signature_invalid', Record<never, never>, VerifyOcspResponseSignatureFailure>;\n\n/**\n * Revocation policy for delegated OCSP responder certificates (RFC 6960 §4.2.2.2.1).\n *\n * - `'honor-nocheck'` (default): a responder carrying `id-pkix-ocsp-nocheck`\n * is exempt from revocation checking. Otherwise, CRL evidence from\n * {@linkcode ValidateOcspResponseInput.responderRevocationCrls} is consulted\n * when provided — a revoked responder rejects the response; missing or\n * unusable evidence is tolerated (soft).\n * - `'require-evidence'`: `nocheck` is ignored; CRL evidence must positively\n * show the responder is not revoked, otherwise the response is rejected.\n * - `'skip'`: no responder revocation checking.\n */\nexport type OcspResponderRevocationPolicy = 'honor-nocheck' | 'require-evidence' | 'skip';\n\n/**\n * Input for {@linkcode validateOcspResponse}.\n */\nexport interface ValidateOcspResponseInput {\n\t/** The OCSP response to validate. */\n\treadonly response: string | Uint8Array | ParsedOcspResponse;\n\t/** Certificate of the CA that issued the target certificate. */\n\treadonly issuerCertificate: OcspCertificateSource;\n\t/** Original request — enables nonce and request-coverage checks. */\n\treadonly request?: OcspRequestSource;\n\t/** Explicit responder certificate — overrides embedded certificate discovery. */\n\treadonly responderCertificate?: OcspCertificateSource;\n\t/** When `true`, allows delegated responder chain validation beyond direct issuance. */\n\treadonly allowChainedResponderCertificate?: boolean;\n\t/**\n\t * Explicitly trusted responder certificates for this issuer's scope\n\t * (RFC 6960 §4.2.2.2 criterion 1 — local responder configuration).\n\t *\n\t * A response signer matching one of these certificates is accepted without\n\t * the delegated-responder issuance, chain, EKU, and revocation checks.\n\t * Signature verification and responder-ID binding are still enforced.\n\t * Also consulted during responder discovery when the response embeds no\n\t * matching certificate.\n\t */\n\treadonly trustedOcspResponders?: readonly OcspCertificateSource[];\n\t/** Revocation policy for delegated responder certificates. Defaults to `'honor-nocheck'`. */\n\treadonly responderRevocationPolicy?: OcspResponderRevocationPolicy;\n\t/** CRLs used as revocation evidence for delegated responder certificates. */\n\treadonly responderRevocationCrls?: readonly CrlSource[];\n\t/** Evaluation time for freshness checks and delegated responder chain validation. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/** Clock-skew tolerance in milliseconds for `thisUpdate`/`nextUpdate`/`producedAt`. */\n\treadonly clockSkewMs?: number;\n}\n\n/** Failure codes produced by {@linkcode validateOcspResponse}. */\nexport type ValidateOcspResponseErrorCode =\n\t| 'response_status_invalid'\n\t| 'signature_invalid'\n\t| 'responder_id_mismatch'\n\t| 'nonce_mismatch'\n\t| 'request_mismatch'\n\t| 'issuer_mismatch'\n\t| 'responder_chain_invalid'\n\t| 'ocsp_signing_missing'\n\t| 'responder_revoked'\n\t| 'responder_revocation_unknown'\n\t| 'stale_response';\n\n/**\n * Failure detail for {@linkcode validateOcspResponse}.\n *\n * Possible codes: `response_status_invalid`, `signature_invalid`,\n * `responder_id_mismatch`, `nonce_mismatch`, `request_mismatch`,\n * `issuer_mismatch`, `responder_chain_invalid`, `ocsp_signing_missing`,\n * `responder_revoked`, `responder_revocation_unknown`, `stale_response`.\n */\nexport interface ValidateOcspResponseFailure extends Micro509Error<ValidateOcspResponseErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Result of {@linkcode validateOcspResponse}.\n *\n * On success, the response has passed status, signature, responder binding,\n * authorization (including responder revocation policy), freshness, nonce,\n * and request-coverage checks.\n */\nexport type ValidateOcspResponseResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** Fully validated OCSP response. */\n\t\t\treadonly value: ParsedOcspResponse;\n\t }\n\t| ErrorResult<ValidateOcspResponseErrorCode, Record<never, never>, ValidateOcspResponseFailure>;\n\ntype ValidateOcspResponseFailureBranch = Extract<\n\tValidateOcspResponseResult,\n\t{ readonly ok: false }\n>;\n\ninterface NormalizedOcspValidationInput {\n\treadonly ok: true;\n\treadonly parsedResponse: ParsedOcspResponse;\n\treadonly issuer: ParsedCertificate;\n\treadonly trustedResponders: readonly ParsedCertificate[];\n\treadonly signer: ParsedCertificate;\n}\n\ninterface ParsedOcspCertStatusFields {\n\treadonly certStatus: ParsedOcspSingleResponse['certStatus'];\n\treadonly revokedAt?: Date;\n\treadonly revocationReasonCode?: number;\n}\n\n/**\n * Builds a DER-encoded OCSP request containing one or more CertID entries\n * and an optional nonce extension.\n *\n * @example\n * ```ts\n * import { createOcspRequest } from 'micro509';\n *\n * const req = await createOcspRequest({\n * requests: [{ certificate: leafPem, issuerCertificate: caPem }],\n * hashAlgorithm: 'SHA-256',\n * nonce: crypto.getRandomValues(new Uint8Array(16)),\n * });\n * // POST req.der to the OCSP responder URI\n * ```\n */\nexport async function createOcspRequest(\n\tinput: CreateOcspRequestInput,\n): Promise<OcspRequestMaterial> {\n\tconst hashAlgorithm = input.hashAlgorithm ?? 'SHA-1';\n\tconst requestEntries: Uint8Array[] = [];\n\tfor (const request of input.requests) {\n\t\tconst certificate = normalizeCertificate(request.certificate);\n\t\tconst issuer = normalizeCertificate(request.issuerCertificate);\n\t\trequestEntries.push(sequence([await encodeOcspCertId(certificate, issuer, hashAlgorithm)]));\n\t}\n\tconst tbsRequestFields: Uint8Array[] = [sequence(requestEntries)];\n\tif (input.nonce !== undefined) {\n\t\ttbsRequestFields.push(\n\t\t\texplicitContext(\n\t\t\t\t2,\n\t\t\t\tsequence([\n\t\t\t\t\tsequence([objectIdentifier(OIDS.ocspNonce), octetString(octetString(input.nonce))]),\n\t\t\t\t]),\n\t\t\t),\n\t\t);\n\t}\n\tconst der = sequence([sequence(tbsRequestFields)]);\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('OCSP REQUEST', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/** Machine-readable failure reason for the OCSP request parsers. */\nexport type ParseOcspRequestErrorCode = 'malformed';\n\n/** Structured failure payload for OCSP request parsing. */\nexport interface ParseOcspRequestFailure extends Micro509Error<ParseOcspRequestErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parseOcspRequestDer} / {@linkcode parseOcspRequestPem}. */\nexport type ParseOcspRequestResult =\n\t| { readonly ok: true; readonly value: ParsedOcspRequest }\n\t| ErrorResult<ParseOcspRequestErrorCode, Record<never, never>, ParseOcspRequestFailure>;\n\n/** Throwing core for {@linkcode parseOcspRequestDer}. */\nexport function parseOcspRequestDerOrThrow(der: Uint8Array): ParsedOcspRequest {\n\tconst top = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (top.length < 1 || top.length > 2) {\n\t\tthrow new Error('Malformed OCSP request');\n\t}\n\tconst tbsRequest = requireElement(top[0], 'tbsRequest');\n\tconst optionalSignature = top[1];\n\tif (optionalSignature !== undefined && optionalSignature.tag !== 0xa0) {\n\t\tthrow new Error('Malformed OCSP request');\n\t}\n\tif (optionalSignature !== undefined) {\n\t\tvalidateOcspOptionalSignature(der, optionalSignature);\n\t}\n\tconst tbsChildren = childrenOf(der, tbsRequest);\n\tlet cursor = skipOcspRequestVersion(der, tbsChildren, 0);\n\tcursor = skipOcspRequestorName(der, tbsChildren, cursor);\n\tconst requestList = requireElement(tbsChildren[cursor], 'requestList');\n\tif (requestList.tag !== 0x30) {\n\t\tthrow new Error('requestList must use SEQUENCE');\n\t}\n\tif (childrenOf(der, requestList).length === 0) {\n\t\tthrow new Error('requestList must not be empty');\n\t}\n\tconst requests = childrenOf(der, requestList).map((request) => {\n\t\tconst requestChildren = childrenOf(der, request);\n\t\tif (requestChildren.length < 1 || requestChildren.length > 2) {\n\t\t\tthrow new Error('Malformed OCSP request entry');\n\t\t}\n\t\tif (requestChildren[1] !== undefined && requestChildren[1].tag !== 0xa0) {\n\t\t\tthrow new Error('Malformed OCSP request entry');\n\t\t}\n\t\tconst certId = requireElement(requestChildren[0], 'reqCert');\n\t\treturn parseOcspCertId(der.slice(certId.start - certId.headerLength, certId.end));\n\t});\n\tcursor += 1;\n\tconst extensions = tbsChildren[cursor];\n\tif (extensions !== undefined && extensions.tag !== 0xa2) {\n\t\tthrow new Error('Malformed OCSP request');\n\t}\n\tif (tbsChildren.length !== cursor + (extensions === undefined ? 0 : 1)) {\n\t\tthrow new Error('Malformed OCSP request');\n\t}\n\tconst nonce =\n\t\textensions === undefined ? undefined : parseOcspNonceFromExtensions(der, extensions);\n\treturn {\n\t\tder: new Uint8Array(der),\n\t\trequests,\n\t\t...(nonce === undefined ? {} : { nonce }),\n\t};\n}\n\nfunction skipOcspRequestVersion(\n\tder: Uint8Array,\n\ttbsChildren: readonly DerElement[],\n\tcursor: number,\n): number {\n\tif (tbsChildren[cursor]?.tag !== 0xa0) return cursor;\n\tconst versionWrapper = requireElement(tbsChildren[cursor], 'version');\n\tconst versionFields = childrenOf(der, versionWrapper);\n\tconst versionElement = requireElement(versionFields[0], 'version');\n\tif (versionFields.length !== 1 || versionElement.tag !== 0x02) {\n\t\tthrow new Error('version must use INTEGER');\n\t}\n\tif (decodeNonNegativeIntegerNumber(versionElement.value, 'OCSP request version') !== 0) {\n\t\tthrow new Error('Unsupported OCSP request version');\n\t}\n\treturn cursor + 1;\n}\n\nfunction skipOcspRequestorName(\n\tder: Uint8Array,\n\ttbsChildren: readonly DerElement[],\n\tcursor: number,\n): number {\n\tconst requestorName = tbsChildren[cursor];\n\tif (requestorName?.tag !== 0xa1) return cursor;\n\tvalidateOcspRequestorName(der, requestorName);\n\treturn cursor + 1;\n}\n\n/** Decodes a PEM-encoded OCSP request (`-----BEGIN OCSP REQUEST-----`). */\nexport function parseOcspRequestPemOrThrow(pem: string): ParsedOcspRequest {\n\treturn parseOcspRequestDerOrThrow(pemDecodeOrThrow('OCSP REQUEST', pem));\n}\n\n/**\n * Decodes a DER-encoded OCSP request into a structured {@linkcode ParsedOcspRequest}.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseOcspRequestDerOrThrow}.\n */\nexport function parseOcspRequestDer(der: Uint8Array): ParseOcspRequestResult {\n\ttry {\n\t\treturn successResult(parseOcspRequestDerOrThrow(der));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed OCSP request',\n\t\t);\n\t}\n}\n\n/**\n * Decodes a PEM-encoded OCSP request (`-----BEGIN OCSP REQUEST-----`).\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseOcspRequestPemOrThrow}.\n */\nexport function parseOcspRequestPem(pem: string): ParseOcspRequestResult {\n\ttry {\n\t\treturn successResult(parseOcspRequestPemOrThrow(pem));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed OCSP request',\n\t\t);\n\t}\n}\n\n/** Machine-readable failure reason for the OCSP response parsers. */\nexport type ParseOcspResponseErrorCode = 'malformed';\n\n/** Structured failure payload for OCSP response parsing. */\nexport interface ParseOcspResponseFailure extends Micro509Error<ParseOcspResponseErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parseOcspResponseDer} / {@linkcode parseOcspResponsePem}. */\nexport type ParseOcspResponseResult =\n\t| { readonly ok: true; readonly value: ParsedOcspResponse }\n\t| ErrorResult<ParseOcspResponseErrorCode, Record<never, never>, ParseOcspResponseFailure>;\n\n/** Throwing core for {@linkcode parseOcspResponseDer}. */\nexport function parseOcspResponseDerOrThrow(der: Uint8Array): ParsedOcspResponse {\n\tconst top = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (top.length < 1 || top.length > 2) {\n\t\tthrow new Error('Malformed OCSP response');\n\t}\n\tconst statusElement = requireElement(top[0], 'responseStatus');\n\tif (statusElement.tag !== 0x0a) {\n\t\tthrow new Error('responseStatus must use ENUMERATED');\n\t}\n\tconst responseStatus = ocspResponseStatusFromCode(\n\t\tdecodeNonNegativeIntegerNumber(statusElement.value, 'OCSP responseStatus'),\n\t);\n\tconst responseBytes = top[1];\n\tif (responseBytes === undefined) {\n\t\treturn { der: new Uint8Array(der), responseStatus };\n\t}\n\tif (responseBytes.tag !== 0xa0) {\n\t\tthrow new Error('Malformed OCSP response');\n\t}\n\tconst responseBytesWrapper = childrenOf(der, responseBytes);\n\tconst bytesSequence = requireElement(responseBytesWrapper[0], 'responseBytes');\n\tif (responseBytesWrapper.length !== 1 || bytesSequence.tag !== 0x30) {\n\t\tthrow new Error('Malformed OCSP response');\n\t}\n\tconst responseBytesChildren = childrenOf(der, bytesSequence);\n\tif (responseBytesChildren.length !== 2) {\n\t\tthrow new Error('responseBytes must contain responseType and response');\n\t}\n\tconst responseType = requireElement(responseBytesChildren[0], 'responseType');\n\tconst response = requireElement(responseBytesChildren[1], 'response');\n\tif (response.tag !== 0x04) {\n\t\tthrow new Error('response must use OCTET STRING');\n\t}\n\tconst responseTypeOid = decodeObjectIdentifier(responseType.value);\n\tif (responseTypeOid !== OIDS.ocspBasicResponse) {\n\t\treturn { der: new Uint8Array(der), responseStatus, responseTypeOid };\n\t}\n\tconst basicResponse = response.value;\n\tconst basicChildren = readSequenceChildren(basicResponse);\n\tif (basicChildren.length < 3 || basicChildren.length > 4) {\n\t\tthrow new Error('Malformed BasicOCSPResponse');\n\t}\n\tconst responseData = requireElement(basicChildren[0], 'responseData');\n\tconst signatureAlgorithm = requireElement(basicChildren[1], 'signatureAlgorithm');\n\tconst signatureValue = requireElement(basicChildren[2], 'signatureValue');\n\tconst certificatesElement = basicChildren[3];\n\tif (certificatesElement !== undefined && certificatesElement.tag !== 0xa0) {\n\t\tthrow new Error('Malformed BasicOCSPResponse');\n\t}\n\tconst signatureAlgorithmChildren = childrenOf(basicResponse, signatureAlgorithm);\n\tconst signatureAlgorithmOid = decodeObjectIdentifier(\n\t\trequireElement(signatureAlgorithmChildren[0], 'signatureAlgorithm OID').value,\n\t);\n\tconst signatureAlgorithmParameters = signatureAlgorithmChildren[1];\n\tconst responseDataDer = basicResponse.slice(\n\t\tresponseData.start - responseData.headerLength,\n\t\tresponseData.end,\n\t);\n\tconst signedResponseData = parseSignedOcspResponseData(responseDataDer);\n\treturn {\n\t\tder: new Uint8Array(der),\n\t\tresponseStatus,\n\t\tresponseTypeOid,\n\t\tresponseDataDer,\n\t\tresponderId: signedResponseData.responderId,\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmName: describeSignatureAlgorithm(\n\t\t\tsignatureAlgorithmOid,\n\t\t\tsignatureAlgorithmParameters === undefined\n\t\t\t\t? undefined\n\t\t\t\t: basicResponse.slice(\n\t\t\t\t\t\tsignatureAlgorithmParameters.start - signatureAlgorithmParameters.headerLength,\n\t\t\t\t\t\tsignatureAlgorithmParameters.end,\n\t\t\t\t\t),\n\t\t),\n\t\tsignatureValue: extractBitStringValue(signatureValue),\n\t\tproducedAt: signedResponseData.producedAt,\n\t\tresponses: signedResponseData.responses,\n\t\t...(signedResponseData.nonce === undefined ? {} : { nonce: signedResponseData.nonce }),\n\t\t...(certificatesElement?.tag === 0xa0\n\t\t\t? {\n\t\t\t\t\tcertificates: parseEmbeddedCertificates(basicResponse, certificatesElement),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Decodes a PEM-encoded OCSP response (`-----BEGIN OCSP RESPONSE-----`).\n *\n * @example\n * ```ts\n * import { parseOcspResponsePemOrThrow } from 'micro509';\n *\n * const resp = parseOcspResponsePemOrThrow(pemString);\n * if (resp.responseStatus === 'successful') {\n * for (const entry of resp.responses ?? []) {\n * console.log(entry.certId.serialNumberHex, entry.certStatus);\n * }\n * }\n * ```\n */\nexport function parseOcspResponsePemOrThrow(pem: string): ParsedOcspResponse {\n\treturn parseOcspResponseDerOrThrow(pemDecodeOrThrow('OCSP RESPONSE', pem));\n}\n\n/**\n * Decodes a DER-encoded OCSP response into a structured {@linkcode ParsedOcspResponse}.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseOcspResponseDerOrThrow}.\n */\nexport function parseOcspResponseDer(der: Uint8Array): ParseOcspResponseResult {\n\ttry {\n\t\treturn successResult(parseOcspResponseDerOrThrow(der));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed OCSP response',\n\t\t);\n\t}\n}\n\n/**\n * Decodes a PEM-encoded OCSP response (`-----BEGIN OCSP RESPONSE-----`).\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseOcspResponsePemOrThrow}.\n */\nexport function parseOcspResponsePem(pem: string): ParseOcspResponseResult {\n\ttry {\n\t\treturn successResult(parseOcspResponsePemOrThrow(pem));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed OCSP response',\n\t\t);\n\t}\n}\n\n/**\n * Signs and encodes an OCSP BasicResponse with a `successful` status.\n *\n * The responder is identified by key hash (SHA-1 of the signer's SubjectPublicKey).\n * Use `includedCertificates` to embed the responder's chain for relying parties.\n *\n * @example\n * ```ts\n * import { createOcspResponse } from 'micro509';\n *\n * const resp = await createOcspResponse({\n * signerPrivateKey: responderPrivateKey,\n * signerCertificate: responderCertPem,\n * responses: [\n * {\n * certificate: leafPem,\n * issuerCertificate: caPem,\n * certStatus: 'good',\n * thisUpdate: new Date('2025-01-01'),\n * nextUpdate: new Date('2025-01-08'),\n * },\n * ],\n * nonce: requestNonce,\n * });\n * // resp.der, resp.pem, resp.base64\n * ```\n */\nexport async function createOcspResponse(\n\tinput: CreateOcspResponseInput,\n): Promise<OcspResponseMaterial> {\n\tconst signerCertificate = normalizeCertificate(input.signerCertificate);\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey);\n\tconst producedAt = input.producedAt ?? new Date();\n\tconst hashAlgorithm = input.hashAlgorithm ?? 'SHA-1';\n\tconst responses: Uint8Array[] = [];\n\tfor (const response of input.responses) {\n\t\tconst certificate = normalizeCertificate(response.certificate);\n\t\tconst issuer = normalizeCertificate(response.issuerCertificate);\n\t\tresponses.push(await encodeSingleResponse(certificate, issuer, response, hashAlgorithm));\n\t}\n\tconst responderKeyHash = await digestBytes(\n\t\t'SHA-1',\n\t\textractSubjectPublicKeyBytes(signerCertificate.subjectPublicKeyInfoDer),\n\t);\n\tconst responseDataFields: Uint8Array[] = [\n\t\timplicitPrimitiveContext(2, responderKeyHash),\n\t\ttime(producedAt),\n\t\tsequence(responses),\n\t];\n\tif (input.nonce !== undefined) {\n\t\tresponseDataFields.push(\n\t\t\texplicitContext(\n\t\t\t\t1,\n\t\t\t\tsequence([\n\t\t\t\t\tsequence([objectIdentifier(OIDS.ocspNonce), octetString(octetString(input.nonce))]),\n\t\t\t\t]),\n\t\t\t),\n\t\t);\n\t}\n\tconst responseData = sequence(responseDataFields);\n\tconst signature = await signBytes(input.signerPrivateKey, signatureAlgorithm, responseData);\n\tconst includedCertificates =\n\t\tinput.includedCertificates === undefined\n\t\t\t? []\n\t\t\t: await Promise.all(input.includedCertificates.map(normalizeCertificate));\n\tconst basicResponseFields: Uint8Array[] = [\n\t\tresponseData,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(signature),\n\t];\n\tif (includedCertificates.length > 0) {\n\t\tbasicResponseFields.push(\n\t\t\texplicitContext(0, concatBytes(includedCertificates.map((certificate) => certificate.der))),\n\t\t);\n\t}\n\tconst basicResponse = sequence(basicResponseFields);\n\tconst der = sequence([\n\t\ttlv(0x0a, Uint8Array.of(0x00)),\n\t\texplicitContext(\n\t\t\t0,\n\t\t\tsequence([objectIdentifier(OIDS.ocspBasicResponse), octetString(basicResponse)]),\n\t\t),\n\t]);\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('OCSP RESPONSE', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/**\n * Verifies the OCSP response signature against the given signer certificate.\n *\n * Does **not** check responder binding, freshness, or nonce — use\n * {@linkcode validateOcspResponse} for full validation.\n */\nexport async function verifyOcspResponseSignature(\n\tresponse: string | Uint8Array | ParsedOcspResponse,\n\tsignerCertificate: OcspCertificateSource,\n): Promise<VerifyOcspResponseSignatureResult> {\n\tlet parsed: ParsedOcspResponse;\n\ttry {\n\t\tparsed = normalizeOcspResponse(response);\n\t} catch {\n\t\treturn verifyOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response signed content is malformed',\n\t\t);\n\t}\n\tif (\n\t\tparsed.responseDataDer === undefined ||\n\t\tparsed.signatureAlgorithmOid === undefined ||\n\t\tparsed.signatureValue === undefined\n\t) {\n\t\treturn verifyOcspResponseFailureResult('signature_invalid', 'OCSP response is not signed');\n\t}\n\tlet signer: ParsedCertificate;\n\ttry {\n\t\tsigner = normalizeCertificate(signerCertificate);\n\t} catch {\n\t\treturn verifyOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP signer certificate input is malformed',\n\t\t);\n\t}\n\tlet verifiedResult: Awaited<ReturnType<typeof verifySignedDataDetailed>>;\n\ttry {\n\t\tverifiedResult = await verifySignedDataDetailed(\n\t\t\tparsed.signatureAlgorithmOid,\n\t\t\tundefined,\n\t\t\tsigner.publicKeyAlgorithmOid,\n\t\t\tsigner.publicKeyParametersOid,\n\t\t\tsigner.subjectPublicKeyInfoDer,\n\t\t\tparsed.signatureValue,\n\t\t\tparsed.responseDataDer,\n\t\t);\n\t} catch {\n\t\treturn verifyOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response signature verification failed',\n\t\t);\n\t}\n\tif (!verifiedResult.ok) {\n\t\tif (verifiedResult.code === 'verification_error') {\n\t\t\treturn verifyOcspResponseFailureResult(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'OCSP response signature verification failed',\n\t\t\t);\n\t\t}\n\t\treturn verifyOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response signature uses unsupported algorithm parameters',\n\t\t);\n\t}\n\treturn verifiedResult.valid\n\t\t? { ok: true, value: parsed }\n\t\t: verifyOcspResponseFailureResult(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'OCSP response signature does not verify',\n\t\t\t);\n}\n\n/**\n * Full OCSP response validation: response status check, signature verification,\n * responder ID binding (byName or byKeyHash), delegated-responder chain and\n * ocspSigning EKU checks, `producedAt`/`thisUpdate`/`nextUpdate` freshness,\n * nonce match, and request-coverage completeness.\n *\n * @example\n * ```ts\n * import { validateOcspResponse } from 'micro509';\n *\n * const result = await validateOcspResponse({\n * response: ocspResponseDer,\n * issuerCertificate: caPem,\n * request: ocspRequestDer,\n * });\n * if (result.ok) {\n * const entry = result.value.responses?.[0];\n * console.log(entry?.certStatus); // 'good' | 'revoked' | 'unknown'\n * }\n * ```\n */\nexport async function validateOcspResponse(\n\tinput: ValidateOcspResponseInput,\n): Promise<ValidateOcspResponseResult> {\n\tlet parsedResponse: ParsedOcspResponse;\n\ttry {\n\t\tparsedResponse = normalizeOcspResponse(input.response);\n\t} catch {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response signed content is malformed',\n\t\t);\n\t}\n\tif (parsedResponse.responseStatus !== 'successful') {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'response_status_invalid',\n\t\t\t`OCSP response status is ${parsedResponse.responseStatus}`,\n\t\t);\n\t}\n\tconst normalized = await normalizeOcspValidationInput(input, parsedResponse);\n\tif (!normalized.ok) {\n\t\treturn normalized;\n\t}\n\tconst { issuer, trustedResponders, signer } = normalized;\n\tconst signature = await verifyOcspResponseSignature(parsedResponse, signer);\n\tif (!signature.ok) {\n\t\treturn validateOcspResponseFailureResult(signature.code, signature.message);\n\t}\n\tconst responderAuthorization = await validateOcspResponderAuthorization(\n\t\tinput,\n\t\tparsedResponse,\n\t\tissuer,\n\t\tsigner,\n\t\ttrustedResponders,\n\t);\n\tif (responderAuthorization !== undefined) return responderAuthorization;\n\tconst at = input.at ?? new Date();\n\tconst skew = input.clockSkewMs ?? 0;\n\tconst freshness = await validateOcspResponseFreshness(parsedResponse, issuer, at, skew);\n\tif (freshness !== undefined) return freshness;\n\tif (hasDuplicateOcspResponseCertificateSerial(parsedResponse.responses ?? [])) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response contains multiple status entries for the same certificate',\n\t\t);\n\t}\n\tif (input.request !== undefined) {\n\t\tconst requestMatch = validateOcspRequestCoverage(input.request, parsedResponse);\n\t\tif (requestMatch !== undefined) return requestMatch;\n\t}\n\treturn { ok: true, value: parsedResponse };\n}\n\n/** Re-parses OCSP validation certificates and resolves the response signer. */\nasync function normalizeOcspValidationInput(\n\tinput: ValidateOcspResponseInput,\n\tparsedResponse: ParsedOcspResponse,\n): Promise<NormalizedOcspValidationInput | ValidateOcspResponseFailureBranch> {\n\tlet issuer: ParsedCertificate;\n\ttry {\n\t\tissuer = normalizeCertificate(input.issuerCertificate);\n\t} catch {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'issuer certificate input is malformed',\n\t\t);\n\t}\n\ttry {\n\t\tconst trustedResponders = (input.trustedOcspResponders ?? []).map(normalizeCertificate);\n\t\tconst resolvedResponder = await resolveOcspResponderCertificate(\n\t\t\tinput,\n\t\t\tparsedResponse,\n\t\t\ttrustedResponders,\n\t\t);\n\t\treturn {\n\t\t\tok: true,\n\t\t\tparsedResponse,\n\t\t\tissuer,\n\t\t\ttrustedResponders,\n\t\t\tsigner: normalizeCertificate(resolvedResponder),\n\t\t};\n\t} catch {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP responder certificate input is malformed',\n\t\t);\n\t}\n}\n\n/** Selects the responder certificate from explicit, embedded, trusted, or issuer inputs. */\nasync function resolveOcspResponderCertificate(\n\tinput: ValidateOcspResponseInput,\n\tparsedResponse: ParsedOcspResponse,\n\ttrustedResponders: readonly ParsedCertificate[],\n): Promise<OcspCertificateSource> {\n\treturn (\n\t\tinput.responderCertificate ??\n\t\t(await findMatchingOcspResponderCertificate(\n\t\t\tparsedResponse.certificates,\n\t\t\tparsedResponse.responderId,\n\t\t)) ??\n\t\t(await findMatchingOcspResponderCertificate(trustedResponders, parsedResponse.responderId)) ??\n\t\tparsedResponse.certificates?.[0] ??\n\t\tinput.issuerCertificate\n\t);\n}\n\nasync function validateOcspResponderAuthorization(\n\tinput: ValidateOcspResponseInput,\n\tparsedResponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\tsigner: ParsedCertificate,\n\ttrustedResponders: readonly ParsedCertificate[],\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tconst responderBinding = await safeValidateOcspResponderIdBinding(parsedResponse, signer);\n\tif (!responderBinding.ok) {\n\t\treturn responderBinding;\n\t}\n\tconst isLocallyTrustedResponder = trustedResponders.some((trusted) =>\n\t\tisSameOcspCertificate(signer, trusted),\n\t);\n\tif (isSameOcspCertificate(signer, issuer) || isLocallyTrustedResponder) {\n\t\treturn undefined;\n\t}\n\treturn await validateDelegatedOcspResponder(input, parsedResponse, issuer, signer);\n}\n\nasync function safeValidateOcspResponderIdBinding(\n\tparsedResponse: ParsedOcspResponse,\n\tsigner: ParsedCertificate,\n): Promise<ValidateOcspResponseFailureBranch | { readonly ok: true }> {\n\ttry {\n\t\treturn await validateOcspResponderIdBinding(parsedResponse.responderId, signer);\n\t} catch {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP responder certificate input is malformed',\n\t\t);\n\t}\n}\n\nasync function validateDelegatedOcspResponder(\n\tinput: ValidateOcspResponseInput,\n\tparsedResponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\tsigner: ParsedCertificate,\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tconst allowChainedResponderCertificate = input.allowChainedResponderCertificate === true;\n\tif (!allowChainedResponderCertificate && !isDirectlyIssuedByOcspIssuer(signer, issuer)) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'responder_chain_invalid',\n\t\t\t'Delegated OCSP responder must be directly issued by issuer certificate',\n\t\t);\n\t}\n\tconst chain = await verifyCertificateChain({\n\t\tleaf: signer.der,\n\t\tintermediates: allowChainedResponderCertificate\n\t\t\t? buildOcspResponderIntermediates(parsedResponse.certificates, signer, issuer)\n\t\t\t: [],\n\t\troots: [issuer.der],\n\t\t...(input.at !== undefined ? { at: input.at } : {}),\n\t});\n\tif (!chain.ok) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'responder_chain_invalid',\n\t\t\t'OCSP responder certificate chain does not validate',\n\t\t);\n\t}\n\tif (signer.extendedKeyUsage === undefined || !signer.extendedKeyUsage.includes('ocspSigning')) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'ocsp_signing_missing',\n\t\t\t'Delegated OCSP responder lacks ocspSigning EKU',\n\t\t);\n\t}\n\tconst responderRevocation = await checkDelegatedResponderRevocation(signer, issuer, input);\n\treturn responderRevocation.ok ? undefined : responderRevocation;\n}\n\n/** Checks response-level and per-certificate OCSP timestamps against the validation time. */\nasync function validateOcspResponseFreshness(\n\tparsedResponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\tat: Date,\n\tskew: number,\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tif (\n\t\tparsedResponse.producedAt !== undefined &&\n\t\tparsedResponse.producedAt.getTime() - skew > at.getTime()\n\t) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'stale_response',\n\t\t\t'OCSP response producedAt is later than requested time',\n\t\t);\n\t}\n\tfor (const response of parsedResponse.responses ?? []) {\n\t\tconst responseFreshness = await validateOcspSingleResponseFreshness(\n\t\t\tresponse,\n\t\t\tparsedResponse.producedAt,\n\t\t\tissuer,\n\t\t\tat,\n\t\t\tskew,\n\t\t);\n\t\tif (responseFreshness !== undefined) return responseFreshness;\n\t}\n\treturn undefined;\n}\n\nasync function validateOcspSingleResponseFreshness(\n\tresponse: ParsedOcspSingleResponse,\n\tproducedAt: Date | undefined,\n\tissuer: ParsedCertificate,\n\tat: Date,\n\tskew: number,\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tlet expected: ParsedOcspCertId;\n\ttry {\n\t\texpected = await buildParsedOcspCertId(\n\t\t\tresponse.certId.hashAlgorithmOid,\n\t\t\tissuer,\n\t\t\tresponse.certId.serialNumberHex,\n\t\t);\n\t} catch {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response CertID hash algorithm is unsupported',\n\t\t);\n\t}\n\tif (\n\t\tresponse.certId.issuerNameHashHex !== expected.issuerNameHashHex ||\n\t\tresponse.certId.issuerKeyHashHex !== expected.issuerKeyHashHex\n\t) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'issuer_mismatch',\n\t\t\t'OCSP response certId does not match issuer certificate',\n\t\t);\n\t}\n\treturn validateOcspSingleResponseTimes(response, producedAt, at, skew);\n}\n\nfunction validateOcspSingleResponseTimes(\n\tresponse: ParsedOcspSingleResponse,\n\tproducedAt: Date | undefined,\n\tat: Date,\n\tskew: number,\n): ValidateOcspResponseFailureBranch | undefined {\n\tif (\n\t\tresponse.thisUpdate.getTime() - skew > at.getTime() ||\n\t\t(response.nextUpdate !== undefined && response.nextUpdate.getTime() + skew < at.getTime())\n\t) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'stale_response',\n\t\t\t'OCSP response is not valid at requested time',\n\t\t);\n\t}\n\tif (\n\t\tproducedAt !== undefined &&\n\t\tresponse.nextUpdate !== undefined &&\n\t\tproducedAt.getTime() - skew > response.nextUpdate.getTime()\n\t) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'stale_response',\n\t\t\t'OCSP response producedAt is later than nextUpdate',\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction validateOcspRequestCoverage(\n\trequestSource: OcspRequestSource,\n\tparsedResponse: ParsedOcspResponse,\n): ValidateOcspResponseFailureBranch | undefined {\n\tlet request: ParsedOcspRequest;\n\ttry {\n\t\trequest = normalizeOcspRequest(requestSource);\n\t} catch {\n\t\treturn validateOcspResponseFailureResult('request_mismatch', 'OCSP request input is malformed');\n\t}\n\tif (request.nonce !== undefined && request.nonce !== parsedResponse.nonce) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'nonce_mismatch',\n\t\t\t'OCSP response nonce does not match request nonce',\n\t\t);\n\t}\n\tconst requestIds = new Set(request.requests.map((entry) => serializeCertId(entry)));\n\tconst responseIds = new Set(\n\t\t(parsedResponse.responses ?? []).map((response) => serializeCertId(response.certId)),\n\t);\n\treturn validateOcspRequestIdCoverage(requestIds, responseIds, parsedResponse.responses ?? []);\n}\n\nfunction validateOcspRequestIdCoverage(\n\trequestIds: ReadonlySet<string>,\n\tresponseIds: ReadonlySet<string>,\n\tresponses: readonly ParsedOcspSingleResponse[],\n): ValidateOcspResponseFailureBranch | undefined {\n\tfor (const response of responses) {\n\t\tif (!requestIds.has(serializeCertId(response.certId))) {\n\t\t\treturn validateOcspResponseFailureResult(\n\t\t\t\t'request_mismatch',\n\t\t\t\t'OCSP response includes a certId not present in request',\n\t\t\t);\n\t\t}\n\t}\n\tfor (const requestId of requestIds) {\n\t\tif (!responseIds.has(requestId)) {\n\t\t\treturn validateOcspResponseFailureResult(\n\t\t\t\t'request_mismatch',\n\t\t\t\t'OCSP response does not cover every requested certId',\n\t\t\t);\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Builds a `VerifyOcspResponseSignatureFailureResult`. */\nfunction verifyOcspResponseFailureResult(\n\tcode: 'signature_invalid',\n\tmessage: string,\n): ErrorResult<'signature_invalid', Record<never, never>, VerifyOcspResponseSignatureFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Builds a `ValidateOcspResponseFailureResult`. */\nfunction validateOcspResponseFailureResult(\n\tcode: ValidateOcspResponseErrorCode,\n\tmessage: string,\n): ErrorResult<ValidateOcspResponseErrorCode, Record<never, never>, ValidateOcspResponseFailure> {\n\treturn failureResult(code, message);\n}\n\n/**\n * Reports whether a certificate carries the `id-pkix-ocsp-nocheck` extension\n * (RFC 6960 §4.2.2.2.1) — the CA's assertion that relying parties may trust\n * this OCSP responder certificate for its lifetime without revocation checks.\n */\nexport function hasOcspNoCheckExtension(certificate: OcspCertificateSource): boolean {\n\tconst parsed = normalizeCertificate(certificate);\n\treturn parsed.extensions.some((extension) => extension.oid === OIDS.ocspNoCheck);\n}\n\n/** Parses a CRL from PEM string, DER bytes, or an already-parsed CRL. */\nfunction parseResponderCrlFromSource(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 parseCertificateRevocationListPemOrThrow(source);\n\t}\n\treturn parseCertificateRevocationListDerOrThrow(source);\n}\n\n/**\n * Applies the delegated-responder revocation policy (RFC 6960 §4.2.2.2.1).\n * See {@linkcode OcspResponderRevocationPolicy} for the policy semantics.\n */\nasync function checkDelegatedResponderRevocation(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: ValidateOcspResponseInput,\n): Promise<{ readonly ok: true } | ReturnType<typeof validateOcspResponseFailureResult>> {\n\tconst policy = input.responderRevocationPolicy ?? 'honor-nocheck';\n\tif (policy === 'skip') {\n\t\treturn { ok: true };\n\t}\n\tif (policy === 'honor-nocheck' && hasOcspNoCheckExtension(signer)) {\n\t\treturn { ok: true };\n\t}\n\tconst at = input.at ?? new Date();\n\tlet sawGood = false;\n\tfor (const source of input.responderRevocationCrls ?? []) {\n\t\tlet crl: ParsedCertificateRevocationList;\n\t\ttry {\n\t\t\tcrl = parseResponderCrlFromSource(source);\n\t\t} catch {\n\t\t\tcontinue; // Unusable evidence — try remaining CRLs\n\t\t}\n\t\tconst result = await checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: signer,\n\t\t\tissuerCertificate: issuer,\n\t\t\tcrl,\n\t\t\tat,\n\t\t});\n\t\tif (!result.ok) {\n\t\t\tcontinue; // CRL does not apply to the responder certificate\n\t\t}\n\t\tif (result.value.status === 'revoked') {\n\t\t\treturn validateOcspResponseFailureResult(\n\t\t\t\t'responder_revoked',\n\t\t\t\t'Delegated OCSP responder certificate is revoked',\n\t\t\t);\n\t\t}\n\t\tif (result.value.status === 'good') {\n\t\t\tsawGood = true;\n\t\t}\n\t}\n\tif (sawGood || policy === 'honor-nocheck') {\n\t\t// honor-nocheck tolerates missing evidence (soft) — only a positive\n\t\t// revoked verdict rejects when no usable evidence proves 'good'.\n\t\treturn { ok: true };\n\t}\n\treturn validateOcspResponseFailureResult(\n\t\t'responder_revocation_unknown',\n\t\t'Delegated OCSP responder revocation status could not be established',\n\t);\n}\n\n/** Accepts PEM, DER, or already-parsed OCSP response and returns a parsed response. */\nfunction normalizeOcspResponse(\n\tresponse: string | Uint8Array | ParsedOcspResponse,\n): ParsedOcspResponse {\n\tif (typeof response === 'string') {\n\t\treturn parseOcspResponsePemOrThrow(response);\n\t}\n\tif (response instanceof Uint8Array) {\n\t\treturn parseOcspResponseDerOrThrow(response);\n\t}\n\tif (hasReparseableOcspResponseShape(response)) {\n\t\treturn parseOcspResponseDerOrThrow(new Uint8Array(response.der));\n\t}\n\tthrow new Error('OCSP response input is malformed');\n}\n\n/** Accepts PEM, DER, or already-parsed OCSP request and returns a parsed request. */\nfunction normalizeOcspRequest(request: OcspRequestSource): ParsedOcspRequest {\n\tif (typeof request === 'string') {\n\t\treturn parseOcspRequestPemOrThrow(request);\n\t}\n\tif (request instanceof Uint8Array) {\n\t\treturn parseOcspRequestDerOrThrow(request);\n\t}\n\tif (hasReparseableOcspRequestShape(request)) {\n\t\treturn parseOcspRequestDerOrThrow(new Uint8Array(request.der));\n\t}\n\tthrow new Error('OCSP request input is malformed');\n}\n\nfunction parseSignedOcspResponseData(responseDataDer: Uint8Array): {\n\treadonly responderId: ParsedOcspResponderId;\n\treadonly producedAt: Date;\n\treadonly responses: readonly ParsedOcspSingleResponse[];\n\treadonly nonce?: string;\n} {\n\tconst responseDataChildren = readSequenceChildren(responseDataDer);\n\tif (responseDataChildren.length < 3 || responseDataChildren.length > 5) {\n\t\tthrow new Error('Malformed OCSP responseData');\n\t}\n\tlet index = 0;\n\tif (responseDataChildren[index]?.tag === 0xa0) {\n\t\tconst versionWrapper = requireElement(responseDataChildren[index], 'version');\n\t\tconst versionFields = childrenOf(responseDataDer, versionWrapper);\n\t\tconst versionElement = requireElement(versionFields[0], 'version');\n\t\tif (versionFields.length !== 1 || versionElement.tag !== 0x02) {\n\t\t\tthrow new Error('version must use INTEGER');\n\t\t}\n\t\tif (decodeNonNegativeIntegerNumber(versionElement.value, 'OCSP response version') !== 0) {\n\t\t\tthrow new Error('Unsupported OCSP response version');\n\t\t}\n\t\tindex += 1;\n\t}\n\tconst responderIdElement = requireElement(responseDataChildren[index], 'responderID');\n\tconst responderId = parseOcspResponderId(responseDataDer, responderIdElement);\n\tindex += 1;\n\tconst producedAtElement = requireElement(responseDataChildren[index], 'producedAt');\n\tconst responsesElement = requireElement(responseDataChildren[index + 1], 'responses');\n\tif (responsesElement.tag !== 0x30) {\n\t\tthrow new Error('responses must use SEQUENCE');\n\t}\n\tif (childrenOf(responseDataDer, responsesElement).length === 0) {\n\t\tthrow new Error('responses must not be empty');\n\t}\n\tconst responseExtensions = responseDataChildren[index + 2];\n\tif (responseExtensions !== undefined && responseExtensions.tag !== 0xa1) {\n\t\tthrow new Error('Malformed OCSP responseData');\n\t}\n\tif (responseDataChildren.length !== index + 2 + (responseExtensions === undefined ? 0 : 1)) {\n\t\tthrow new Error('Malformed OCSP responseData');\n\t}\n\tconst nonce =\n\t\tresponseExtensions === undefined\n\t\t\t? undefined\n\t\t\t: parseOcspNonceFromExtensions(responseDataDer, responseExtensions);\n\tconst parsedResponses = childrenOf(responseDataDer, responsesElement).map((singleResponse) =>\n\t\tparseSingleResponse(responseDataDer, singleResponse),\n\t);\n\tassertUniqueOcspResponseCertIds(parsedResponses);\n\treturn {\n\t\tresponderId,\n\t\tproducedAt: parseTime(producedAtElement),\n\t\tresponses: parsedResponses,\n\t\t...(nonce === undefined ? {} : { nonce }),\n\t};\n}\n\n/** Searches embedded certificates for one whose subject or key hash matches the responder ID. */\nasync function findMatchingOcspResponderCertificate(\n\tcertificates: readonly ParsedCertificate[] | undefined,\n\tresponderId: ParsedOcspResponderId | undefined,\n): Promise<ParsedCertificate | undefined> {\n\tif (certificates === undefined || responderId === undefined) {\n\t\treturn undefined;\n\t}\n\tfor (const certificate of certificates) {\n\t\tif (await matchesOcspResponderId(responderId, certificate)) {\n\t\t\treturn certificate;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Verifies that the signer certificate matches the response's responder ID (byName or byKeyHash). */\nasync function validateOcspResponderIdBinding(\n\tresponderId: ParsedOcspResponderId | undefined,\n\tsigner: ParsedCertificate,\n): Promise<Extract<ValidateOcspResponseResult, { readonly ok: false }> | { readonly ok: true }> {\n\tif (responderId === undefined) {\n\t\treturn { ok: true };\n\t}\n\tif (await matchesOcspResponderId(responderId, signer)) {\n\t\treturn { ok: true };\n\t}\n\treturn responderId.type === 'byName'\n\t\t? validateOcspResponseFailureResult(\n\t\t\t\t'responder_id_mismatch',\n\t\t\t\t'OCSP responder certificate subject does not match responderID byName',\n\t\t\t)\n\t\t: validateOcspResponseFailureResult(\n\t\t\t\t'responder_id_mismatch',\n\t\t\t\t'OCSP responder certificate public key does not match responderID byKeyHash',\n\t\t\t);\n}\n\n/** Returns `true` if the certificate matches the responder ID (subject name or key hash). */\nasync function matchesOcspResponderId(\n\tresponderId: ParsedOcspResponderId,\n\tcertificate: ParsedCertificate,\n): Promise<boolean> {\n\tif (responderId.type === 'byName') {\n\t\treturn compareOcspResponderNames(responderId.name, certificate.subject);\n\t}\n\tconst certificateKeyHashHex = toHex(\n\t\tawait digestBytes('SHA-1', extractSubjectPublicKeyBytes(certificate.subjectPublicKeyInfoDer)),\n\t);\n\treturn certificateKeyHashHex === responderId.keyHashHex;\n}\n\n/** Identity check — same serial, issuer, subject, and SPKI. */\nfunction isSameOcspCertificate(left: ParsedCertificate, right: ParsedCertificate): boolean {\n\treturn (\n\t\tleft.serialNumberHex === right.serialNumberHex &&\n\t\tcompareDistinguishedNames(left.issuer, right.issuer) &&\n\t\tcompareDistinguishedNames(left.subject, right.subject) &&\n\t\tleft.subjectPublicKeyInfoDer.length === right.subjectPublicKeyInfoDer.length &&\n\t\tleft.subjectPublicKeyInfoDer.every(\n\t\t\t(byte, index) => byte === right.subjectPublicKeyInfoDer[index],\n\t\t)\n\t);\n}\n\n/** Returns `true` if `signer` was directly issued by `issuer` (name + AKI match). */\nfunction isDirectlyIssuedByOcspIssuer(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): boolean {\n\tif (!compareDistinguishedNames(signer.issuer, issuer.subject)) {\n\t\treturn false;\n\t}\n\tif (\n\t\tsigner.authorityKeyIdentifier !== undefined &&\n\t\tissuer.subjectKeyIdentifier !== undefined &&\n\t\tsigner.authorityKeyIdentifier !== issuer.subjectKeyIdentifier\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/** Filters embedded certificates to produce an intermediate chain (excluding signer and issuer). */\nfunction buildOcspResponderIntermediates(\n\tcertificates: readonly ParsedCertificate[] | undefined,\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): readonly Uint8Array[] {\n\tif (certificates === undefined) {\n\t\treturn [];\n\t}\n\tconst intermediates: Uint8Array[] = [];\n\tfor (const certificate of certificates) {\n\t\tif (isSameOcspCertificate(certificate, signer) || isSameOcspCertificate(certificate, issuer)) {\n\t\t\tcontinue;\n\t\t}\n\t\tintermediates.push(certificate.der);\n\t}\n\treturn intermediates;\n}\n\n/** DER-encodes a CertID SEQUENCE (hashAlgorithm, issuerNameHash, issuerKeyHash, serialNumber). */\nasync function encodeOcspCertId(\n\tcertificate: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\thashAlgorithm: OcspHashAlgorithm,\n): Promise<Uint8Array> {\n\tconst hashAlgorithmOid = hashAlgorithm === 'SHA-1' ? OIDS.sha1 : OIDS.sha256;\n\tconst parsed = await buildParsedOcspCertId(hashAlgorithmOid, issuer, certificate.serialNumberHex);\n\treturn sequence([\n\t\tsequence([objectIdentifier(hashAlgorithmOid), nullValue()]),\n\t\toctetString(hexToBytes(parsed.issuerNameHashHex)),\n\t\toctetString(hexToBytes(parsed.issuerKeyHashHex)),\n\t\tinteger(hexToBytes(parsed.serialNumberHex)),\n\t]);\n}\n\n/** Computes issuer name/key hashes for a CertID given the hash algorithm OID and issuer certificate. */\nasync function buildParsedOcspCertId(\n\thashAlgorithmOid: string,\n\tissuer: ParsedCertificate,\n\tserialNumberHex: string,\n): Promise<ParsedOcspCertId> {\n\tconst hashAlgorithm = ocspHashAlgorithmFromOid(hashAlgorithmOid);\n\treturn {\n\t\thashAlgorithmOid,\n\t\thashAlgorithmName: describeHashAlgorithm(hashAlgorithmOid),\n\t\tissuerNameHashHex: toHex(await digestBytes(hashAlgorithm, hexToBytes(issuer.subject.derHex))),\n\t\tissuerKeyHashHex: toHex(\n\t\t\tawait digestBytes(\n\t\t\t\thashAlgorithm,\n\t\t\t\textractSubjectPublicKeyBytes(issuer.subjectPublicKeyInfoDer),\n\t\t\t),\n\t\t),\n\t\tserialNumberHex,\n\t};\n}\n\n/** Hashes `bytes` with the given WebCrypto algorithm name. */\nasync function digestBytes(algorithm: OcspHashAlgorithm, bytes: Uint8Array): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.digest(algorithm, toArrayBuffer(bytes)));\n}\n\n/** DER-encodes a SingleResponse (certId, certStatus, thisUpdate, optional nextUpdate). */\nasync function encodeSingleResponse(\n\tcertificate: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CreateOcspSingleResponseInput,\n\thashAlgorithm: OcspHashAlgorithm,\n): Promise<Uint8Array> {\n\tconst certId = await encodeOcspCertId(certificate, issuer, hashAlgorithm);\n\tconst certStatus = encodeOcspCertStatus(input);\n\treturn sequence([\n\t\tcertId,\n\t\tcertStatus,\n\t\ttime(input.thisUpdate ?? new Date()),\n\t\t...(input.nextUpdate === undefined ? [] : [explicitContext(0, time(input.nextUpdate))]),\n\t]);\n}\n\n/** DER-encodes the CertStatus CHOICE (good [0], revoked [1], unknown [2]). */\nfunction encodeOcspCertStatus(input: CreateOcspSingleResponseInput): Uint8Array {\n\tswitch (input.certStatus) {\n\t\tcase 'good':\n\t\t\treturn tlv(0x80, new Uint8Array());\n\t\tcase 'unknown':\n\t\t\treturn tlv(0x82, new Uint8Array());\n\t\tcase 'revoked': {\n\t\t\tconst revokedFields: Uint8Array[] = [time(input.revokedAt ?? input.thisUpdate ?? new Date())];\n\t\t\tif (input.revocationReasonCode !== undefined) {\n\t\t\t\trevokedFields.push(\n\t\t\t\t\texplicitContext(0, tlv(0x0a, Uint8Array.of(input.revocationReasonCode))),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn tlv(0xa1, concatBytes(revokedFields));\n\t\t}\n\t}\n}\n\n/** Accepts PEM, DER, or already-parsed certificate and returns a parsed certificate. */\nfunction normalizeCertificate(source: OcspCertificateSource): ParsedCertificate {\n\tif (hasParsedCertificateShape(source)) {\n\t\treturn parseCertificateDerOrThrow(new Uint8Array(source.der));\n\t}\n\treturn parseCertificateFromSource(source);\n}\n\n/** Type guard: distinguishes a `ParsedCertificate` from raw `Uint8Array`. */\nfunction hasParsedCertificateShape(value: OcspCertificateSource): value is ParsedCertificate {\n\treturn typeof value !== 'string' && 'subjectPublicKeyInfoDer' in value;\n}\n\n/** Decodes a DER-encoded CertID SEQUENCE into a {@linkcode ParsedOcspCertId}. */\nfunction parseOcspCertId(der: Uint8Array): ParsedOcspCertId {\n\tconst root = readRootElement(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (root.tag !== 0x30) {\n\t\tthrow new Error('CertID must use SEQUENCE');\n\t}\n\tconst children = childrenOf(der, root);\n\tif (children.length !== 4) {\n\t\tthrow new Error(\n\t\t\t'CertID must contain hashAlgorithm, issuerNameHash, issuerKeyHash, and serialNumber',\n\t\t);\n\t}\n\tconst hashAlgorithm = requireElement(children[0], 'hashAlgorithm');\n\tif (hashAlgorithm.tag !== 0x30) {\n\t\tthrow new Error('hashAlgorithm must use SEQUENCE');\n\t}\n\tconst algorithmChildren = childrenOf(der, hashAlgorithm);\n\tif (algorithmChildren.length < 1 || algorithmChildren.length > 2) {\n\t\tthrow new Error('Malformed hashAlgorithm');\n\t}\n\tconst algorithmOid = requireElement(algorithmChildren[0], 'hashAlgorithm OID');\n\tconst hashAlgorithmOid = decodeObjectIdentifier(algorithmOid.value);\n\tif (requireElement(children[1], 'issuerNameHash').tag !== 0x04) {\n\t\tthrow new Error('issuerNameHash must use OCTET STRING');\n\t}\n\tif (requireElement(children[2], 'issuerKeyHash').tag !== 0x04) {\n\t\tthrow new Error('issuerKeyHash must use OCTET STRING');\n\t}\n\tconst serialNumber = requireElement(children[3], 'serialNumber');\n\tif (serialNumber.tag !== 0x02) {\n\t\tthrow new Error('serialNumber must use INTEGER');\n\t}\n\treturn {\n\t\thashAlgorithmOid,\n\t\thashAlgorithmName: describeHashAlgorithm(hashAlgorithmOid),\n\t\tissuerNameHashHex: toHex(requireElement(children[1], 'issuerNameHash').value),\n\t\tissuerKeyHashHex: toHex(requireElement(children[2], 'issuerKeyHash').value),\n\t\tserialNumberHex: toHex(serialNumber.value),\n\t};\n}\n\n/** Decodes a SingleResponse from its ASN.1 element within the ResponseData. */\nfunction parseSingleResponse(source: Uint8Array, element: DerElement): ParsedOcspSingleResponse {\n\tconst children = childrenOf(source, element);\n\tif (children.length < 3 || children.length > 5) {\n\t\tthrow new Error('Malformed OCSP SingleResponse');\n\t}\n\tconst certId = requireElement(children[0], 'certId');\n\tconst certStatus = requireElement(children[1], 'certStatus');\n\tconst thisUpdate = requireElement(children[2], 'thisUpdate');\n\tlet cursor = 3;\n\tconst nextUpdateElement = children[cursor]?.tag === 0xa0 ? children[cursor] : undefined;\n\tif (nextUpdateElement !== undefined) {\n\t\tvalidateOcspSingleResponseNextUpdate(source, nextUpdateElement);\n\t\tcursor += 1;\n\t}\n\tconst singleExtensions = children[cursor];\n\tif (singleExtensions !== undefined && singleExtensions.tag !== 0xa1) {\n\t\tthrow new Error('Malformed OCSP SingleResponse');\n\t}\n\tif (children.length !== cursor + (singleExtensions === undefined ? 0 : 1)) {\n\t\tthrow new Error('Malformed OCSP SingleResponse');\n\t}\n\tconst statusFields = parseOcspCertStatusFields(source, certStatus);\n\treturn {\n\t\tcertId: parseOcspCertId(source.slice(certId.start - certId.headerLength, certId.end)),\n\t\tcertStatus: statusFields.certStatus,\n\t\tthisUpdate: parseTime(thisUpdate),\n\t\t...parseOcspSingleResponseNextUpdate(source, nextUpdateElement),\n\t\t...(statusFields.revokedAt === undefined ? {} : { revokedAt: statusFields.revokedAt }),\n\t\t...(statusFields.revocationReasonCode === undefined\n\t\t\t? {}\n\t\t\t: { revocationReasonCode: statusFields.revocationReasonCode }),\n\t};\n}\n\nfunction parseOcspSingleResponseNextUpdate(\n\tsource: Uint8Array,\n\tnextUpdateElement: DerElement | undefined,\n): { readonly nextUpdate?: Date } {\n\treturn nextUpdateElement === undefined\n\t\t? {}\n\t\t: {\n\t\t\t\tnextUpdate: parseTime(\n\t\t\t\t\trequireElement(childrenOf(source, nextUpdateElement)[0], 'nextUpdate'),\n\t\t\t\t),\n\t\t\t};\n}\n\nfunction parseOcspCertStatusFields(\n\tsource: Uint8Array,\n\tcertStatus: DerElement,\n): ParsedOcspCertStatusFields {\n\tif (certStatus.tag === 0x80) {\n\t\tif (certStatus.value.length !== 0) {\n\t\t\tthrow new Error('OCSP good certStatus must be empty');\n\t\t}\n\t\treturn { certStatus: 'good' };\n\t}\n\tif (certStatus.tag === 0x82) {\n\t\tif (certStatus.value.length !== 0) {\n\t\t\tthrow new Error('OCSP unknown certStatus must be empty');\n\t\t}\n\t\treturn { certStatus: 'unknown' };\n\t}\n\tif (certStatus.tag !== 0xa1) {\n\t\tthrow new Error(`Unsupported OCSP certStatus tag: ${String(certStatus.tag)}`);\n\t}\n\tconst revokedInfo = childrenOf(source, certStatus);\n\tif (revokedInfo.length < 1 || revokedInfo.length > 2) {\n\t\tthrow new Error('Malformed OCSP revoked certStatus');\n\t}\n\treturn {\n\t\tcertStatus: 'revoked',\n\t\trevokedAt: parseTime(requireElement(revokedInfo[0], 'revocationTime')),\n\t\t...parseOcspRevocationReason(source, revokedInfo[1]),\n\t};\n}\n\nfunction parseOcspRevocationReason(\n\tsource: Uint8Array,\n\treason: DerElement | undefined,\n): { readonly revocationReasonCode?: number } {\n\tif (reason === undefined) {\n\t\treturn {};\n\t}\n\tif (reason.tag !== 0xa0) {\n\t\tthrow new Error('Malformed OCSP revoked certStatus');\n\t}\n\tconst reasonChildren = childrenOf(source, reason);\n\tconst enumerated = requireElement(reasonChildren[0], 'revocationReason');\n\tif (reasonChildren.length !== 1 || enumerated.tag !== 0x0a) {\n\t\tthrow new Error('revocationReason must use ENUMERATED');\n\t}\n\treturn {\n\t\trevocationReasonCode: decodeNonNegativeIntegerNumber(enumerated.value, 'OCSP revocationReason'),\n\t};\n}\n\n/** Decodes a ResponderID from its context-tagged ASN.1 element (byName [1] or byKeyHash [2]). */\nfunction parseOcspResponderId(source: Uint8Array, element: DerElement): ParsedOcspResponderId {\n\tswitch (element.tag) {\n\t\tcase 0x82:\n\t\t\tif (element.value.length === 0) {\n\t\t\t\tthrow new Error('ResponderID byKeyHash must not be empty');\n\t\t\t}\n\t\t\treturn { type: 'byKeyHash', keyHashHex: toHex(element.value) };\n\t\tcase 0xa1:\n\t\t\tif (childrenOf(source, element).length !== 1) {\n\t\t\t\tthrow new Error('ResponderID byName must wrap exactly one Name');\n\t\t\t}\n\t\t\treturn {\n\t\t\t\ttype: 'byName',\n\t\t\t\tname: parseResponderName(\n\t\t\t\t\tsource,\n\t\t\t\t\trequireElement(childrenOf(source, element)[0], 'ResponderID byName'),\n\t\t\t\t),\n\t\t\t};\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported OCSP responderID tag: ${String(element.tag)}`);\n\t}\n}\n\n/** Decodes a Name SEQUENCE from the ResponderID byName form. */\nfunction parseResponderName(source: Uint8Array, element: DerElement): ParsedName {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('ResponderID byName must use Name SEQUENCE');\n\t}\n\tconst rdns: ParsedRelativeDistinguishedName[] = [];\n\tconst attributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const setElement of childrenOf(source, element)) {\n\t\tconst rdn = parseResponderNameAttributeSet(source, setElement);\n\t\trdns.push(rdn);\n\t\tfor (const attribute of rdn.attributes) {\n\t\t\tattributes.push(attribute);\n\t\t\tif (attribute.key !== undefined && values[attribute.key] === undefined) {\n\t\t\t\tvalues[attribute.key] = attribute.value;\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tderHex: toHex(source.slice(element.start - element.headerLength, element.end)),\n\t\trdns,\n\t\tattributes,\n\t\tvalues,\n\t};\n}\n\n/** Decodes one RDN SET from a responder name. */\nfunction parseResponderNameAttributeSet(\n\tsource: Uint8Array,\n\tsetElement: DerElement,\n): ParsedRelativeDistinguishedName {\n\tconst attributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const attributeSequence of childrenOf(source, setElement)) {\n\t\tconst parts = childrenOf(source, attributeSequence);\n\t\tconst oid = decodeObjectIdentifier(requireElement(parts[0], 'name OID').value);\n\t\tconst valueElement = requireElement(parts[1], 'name value');\n\t\tconst key = responderNameKeyFromOid(oid);\n\t\tconst value = decodeString(valueElement.tag, valueElement.value);\n\t\tconst attribute: ParsedNameAttribute =\n\t\t\tkey === undefined\n\t\t\t\t? { oid, valueTag: valueElement.tag, value }\n\t\t\t\t: { oid, key, valueTag: valueElement.tag, value };\n\t\tattributes.push(attribute);\n\t\tif (key !== undefined && values[key] === undefined) {\n\t\t\tvalues[key] = value;\n\t\t}\n\t}\n\treturn {\n\t\tderHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),\n\t\tattributes,\n\t\tvalues,\n\t};\n}\n\n/** RDN-by-RDN responder name comparison with RFC 4518 string prep. */\nfunction compareOcspResponderNames(left: ParsedName, right: ParsedName): boolean {\n\tif (left.rdns.length !== right.rdns.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < left.rdns.length; index += 1) {\n\t\tconst leftRdn = left.rdns[index];\n\t\tconst rightRdn = right.rdns[index];\n\t\tif (leftRdn === undefined || rightRdn === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!compareOcspRelativeDistinguishedNames(leftRdn, rightRdn)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Set-equality comparison for RDN attribute sets (order-independent). */\nfunction compareOcspRelativeDistinguishedNames(\n\tleft: ParsedRelativeDistinguishedName,\n\tright: ParsedRelativeDistinguishedName,\n): boolean {\n\tif (left.attributes.length !== right.attributes.length) {\n\t\treturn false;\n\t}\n\tconst matched = new Array(right.attributes.length).fill(false);\n\tfor (const leftAttribute of left.attributes) {\n\t\tlet found = false;\n\t\tfor (let index = 0; index < right.attributes.length; index += 1) {\n\t\t\tconst rightAttribute = right.attributes[index];\n\t\t\tif (rightAttribute === undefined || matched[index]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!compareOcspNameAttributeValue(leftAttribute, rightAttribute)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmatched[index] = true;\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (!found) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Compares two name attributes with RFC 4518 string prep for directory-string types. */\nfunction compareOcspNameAttributeValue(\n\tleft: ParsedNameAttribute,\n\tright: ParsedNameAttribute,\n): boolean {\n\tif (left.oid !== right.oid) {\n\t\treturn false;\n\t}\n\tif (isOcspDirectoryStringTag(left.valueTag) && isOcspDirectoryStringTag(right.valueTag)) {\n\t\tconst preparedLeft = prepareOcspNameCompareString(left.value);\n\t\tconst preparedRight = prepareOcspNameCompareString(right.value);\n\t\tif (preparedLeft === undefined || preparedRight === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn preparedLeft === preparedRight;\n\t}\n\treturn left.valueTag === right.valueTag && left.value === right.value;\n}\n\n/** Returns `true` for UTF8String (0x0c) and PrintableString (0x13). */\nfunction isOcspDirectoryStringTag(tag: number): boolean {\n\treturn tag === 0x0c || tag === 0x13;\n}\n\n/** NFKC-normalises, lowercases, trims, and collapses whitespace for RFC 4518 name comparison. */\nfunction prepareOcspNameCompareString(value: string): string | undefined {\n\tconst normalized = value.normalize('NFKC');\n\tif (/[^\\P{Cc}\\t\\n\\r]/u.test(normalized)) {\n\t\treturn undefined;\n\t}\n\treturn normalized.toLowerCase().trim().replace(/\\s+/gu, ' ');\n}\n\n/** Maps an X.500 attribute type OID to its friendly key name for responder name parsing. */\nfunction responderNameKeyFromOid(oid: string): ParsedNameAttribute['key'] {\n\tswitch (oid) {\n\t\tcase OIDS.commonName:\n\t\t\treturn 'commonName';\n\t\tcase OIDS.surname:\n\t\t\treturn 'surname';\n\t\tcase OIDS.serialNumber:\n\t\t\treturn 'serialNumber';\n\t\tcase OIDS.countryName:\n\t\t\treturn 'country';\n\t\tcase OIDS.localityName:\n\t\t\treturn 'locality';\n\t\tcase OIDS.stateOrProvinceName:\n\t\t\treturn 'state';\n\t\tcase OIDS.streetAddress:\n\t\t\treturn 'street';\n\t\tcase OIDS.organizationName:\n\t\t\treturn 'organization';\n\t\tcase OIDS.organizationalUnitName:\n\t\t\treturn 'organizationalUnit';\n\t\tcase OIDS.title:\n\t\t\treturn 'title';\n\t\tcase OIDS.givenName:\n\t\t\treturn 'givenName';\n\t\tcase OIDS.emailAddress:\n\t\t\treturn 'emailAddress';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/** Extracts the nonce value (as hex) from an OCSP extensions wrapper, if present. */\nfunction parseOcspNonceFromExtensions(source: Uint8Array, element: DerElement): string | undefined {\n\tconst extensionsChildren = childrenOf(source, element);\n\tconst extensionsSequence = requireElement(extensionsChildren[0], 'extensions');\n\tif (extensionsChildren.length !== 1 || extensionsSequence.tag !== 0x30) {\n\t\tthrow new Error('Malformed OCSP extensions');\n\t}\n\tconst seenOids = new Set<string>();\n\tlet nonce: string | undefined;\n\tfor (const extension of childrenOf(source, extensionsSequence)) {\n\t\tconst parts = childrenOf(source, extension);\n\t\tif (parts.length < 2 || parts.length > 3) {\n\t\t\tthrow new Error('Malformed OCSP extension');\n\t\t}\n\t\tif (parts.length === 3 && parts[1]?.tag !== 0x01) {\n\t\t\tthrow new Error('Malformed OCSP extension');\n\t\t}\n\t\tconst oid = decodeObjectIdentifier(requireElement(parts[0], 'extension OID').value);\n\t\tif (seenOids.has(oid)) {\n\t\t\tthrow new Error(`Duplicate OCSP extension OID: ${oid}`);\n\t\t}\n\t\tseenOids.add(oid);\n\t\tconst extnValue = requireElement(parts[parts.length - 1], 'extnValue');\n\t\tif (extnValue.tag !== 0x04) {\n\t\t\tthrow new Error('OCSP extension value must use OCTET STRING');\n\t\t}\n\t\tif (oid !== OIDS.ocspNonce) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst nonceElement = readRootElement(extnValue.value, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (nonceElement.tag !== 0x04) {\n\t\t\tthrow new Error('OCSP nonce extension value must use OCTET STRING');\n\t\t}\n\t\tnonce = toHex(nonceElement.value);\n\t}\n\treturn nonce;\n}\n\n/** Decodes the optional `certs [0]` field from a BasicOCSPResponse. */\nfunction parseEmbeddedCertificates(\n\tsource: Uint8Array,\n\telement: DerElement,\n): readonly ParsedCertificate[] {\n\tconst certificates: ParsedCertificate[] = [];\n\tlet offset = element.start;\n\twhile (offset < element.end) {\n\t\tconst child = readElement(source, offset);\n\t\tcertificates.push(parseCertificateDerOrThrow(source.slice(offset, child.end)));\n\t\toffset = child.end;\n\t}\n\treturn certificates;\n}\n\n/** Extracts the raw public key bytes (without BIT STRING padding byte) from SPKI DER. */\nfunction extractSubjectPublicKeyBytes(spkiDer: Uint8Array): Uint8Array {\n\tconst top = childrenOf(spkiDer, readElement(spkiDer));\n\tconst bitStringElement = requireElement(top[1], 'subjectPublicKey BIT STRING');\n\tif (bitStringElement.tag !== 0x03) {\n\t\tthrow new Error('SPKI missing subjectPublicKey BIT STRING');\n\t}\n\treturn bitStringElement.value.slice(1);\n}\n\n/** Maps an integer response-status code to its {@linkcode OcspResponseStatus} string. */\nfunction ocspResponseStatusFromCode(code: number | undefined): OcspResponseStatus {\n\tswitch (code) {\n\t\tcase 0:\n\t\t\treturn 'successful';\n\t\tcase 1:\n\t\t\treturn 'malformedRequest';\n\t\tcase 2:\n\t\t\treturn 'internalError';\n\t\tcase 3:\n\t\t\treturn 'tryLater';\n\t\tcase 5:\n\t\t\treturn 'sigRequired';\n\t\tcase 6:\n\t\t\treturn 'unauthorized';\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported OCSP responseStatus value: ${String(code)}`);\n\t}\n}\n\nfunction hasReparseableOcspRequestShape(\n\trequest: ParsedOcspRequest,\n): request is ParsedOcspRequest & { readonly der: Uint8Array } {\n\treturn 'der' in request && request.der instanceof Uint8Array;\n}\n\nfunction hasReparseableOcspResponseShape(\n\tresponse: ParsedOcspResponse,\n): response is ParsedOcspResponse & { readonly der: Uint8Array } {\n\treturn 'der' in response && response.der instanceof Uint8Array;\n}\n\nfunction assertUniqueOcspResponseCertIds(responses: readonly ParsedOcspSingleResponse[]): void {\n\tconst seen = new Set<string>();\n\tfor (const response of responses) {\n\t\tconst key = serializeCertId(response.certId);\n\t\tif (seen.has(key)) {\n\t\t\tthrow new Error('Duplicate OCSP response CertID');\n\t\t}\n\t\tseen.add(key);\n\t}\n}\n\nfunction hasDuplicateOcspResponseCertificateSerial(\n\tresponses: readonly ParsedOcspSingleResponse[],\n): boolean {\n\tconst seen = new Set<string>();\n\tfor (const response of responses) {\n\t\tconst serial = normalizeHex(response.certId.serialNumberHex);\n\t\tif (seen.has(serial)) {\n\t\t\treturn true;\n\t\t}\n\t\tseen.add(serial);\n\t}\n\treturn false;\n}\n\nfunction validateOcspRequestorName(source: Uint8Array, element: DerElement): void {\n\tconst children = childrenOf(source, element);\n\tconst requestorName = requireElement(children[0], 'requestorName');\n\tif (children.length !== 1 || (requestorName.tag & 0xc0) !== 0x80) {\n\t\tthrow new Error('requestorName must wrap exactly one GeneralName');\n\t}\n}\n\nfunction validateOcspOptionalSignature(source: Uint8Array, element: DerElement): void {\n\tconst wrapperChildren = childrenOf(source, element);\n\tconst signatureSequence = requireElement(wrapperChildren[0], 'optionalSignature');\n\tif (wrapperChildren.length !== 1 || signatureSequence.tag !== 0x30) {\n\t\tthrow new Error('optionalSignature must wrap exactly one Signature');\n\t}\n\tconst signatureChildren = childrenOf(source, signatureSequence);\n\tif (\n\t\tsignatureChildren.length < 2 ||\n\t\tsignatureChildren.length > 3 ||\n\t\tsignatureChildren[0]?.tag !== 0x30 ||\n\t\t(signatureChildren[2] !== undefined && signatureChildren[2]?.tag !== 0xa0)\n\t) {\n\t\tthrow new Error('Malformed optionalSignature');\n\t}\n\tconst signatureAlgorithm = requireElement(signatureChildren[0], 'signatureAlgorithm');\n\tconst signatureValue = requireElement(signatureChildren[1], 'signature');\n\tconst certificates = signatureChildren[2];\n\tvalidateAlgorithmIdentifierShape(source, signatureAlgorithm, 'optionalSignature algorithm');\n\textractBitStringValue(signatureValue);\n\tif (certificates !== undefined) {\n\t\tconst certificateChildren = childrenOf(source, certificates);\n\t\tif (certificateChildren.length !== 1 || certificateChildren[0]?.tag !== 0x30) {\n\t\t\tthrow new Error('optionalSignature certs must use SEQUENCE OF Certificate');\n\t\t}\n\t}\n}\n\nfunction validateOcspSingleResponseNextUpdate(source: Uint8Array, element: DerElement): void {\n\tconst children = childrenOf(source, element);\n\tconst nextUpdate = requireElement(children[0], 'nextUpdate');\n\tif (children.length !== 1 || (nextUpdate.tag !== 0x17 && nextUpdate.tag !== 0x18)) {\n\t\tthrow new Error('nextUpdate must wrap exactly one time value');\n\t}\n}\n\nfunction validateAlgorithmIdentifierShape(\n\tsource: Uint8Array,\n\telement: DerElement,\n\tlabel: string,\n): void {\n\tconst children = childrenOf(source, element);\n\tif (\n\t\telement.tag !== 0x30 ||\n\t\tchildren.length < 1 ||\n\t\tchildren.length > 2 ||\n\t\tchildren[0]?.tag !== 0x06\n\t) {\n\t\tthrow new Error(`${label} must use AlgorithmIdentifier SEQUENCE`);\n\t}\n\tdecodeObjectIdentifier(requireElement(children[0], `${label} OID`).value);\n}\n\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n/** Maps a hash algorithm OID to the WebCrypto algorithm name. Throws on unsupported OIDs. */\nfunction ocspHashAlgorithmFromOid(oid: string): OcspHashAlgorithm {\n\tswitch (oid) {\n\t\tcase OIDS.sha1:\n\t\t\treturn 'SHA-1';\n\t\tcase OIDS.sha256:\n\t\t\treturn 'SHA-256';\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported OCSP hash algorithm OID: ${oid}`);\n\t}\n}\n\n/** Produces a colon-delimited canonical string for CertID set comparison. */\nfunction serializeCertId(certId: ParsedOcspCertId): string {\n\treturn [\n\t\tcertId.hashAlgorithmOid,\n\t\tcertId.issuerNameHashHex,\n\t\tcertId.issuerKeyHashHex,\n\t\tcertId.serialNumberHex,\n\t].join(':');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiaA,eAAsB,kBACrB,GAC+B;CAC/B,IAAM,IAAgB,EAAM,iBAAiB,SACvC,IAA+B,CAAC;CACtC,KAAK,IAAM,KAAW,EAAM,UAAU;EACrC,IAAM,IAAc,qBAAqB,EAAQ,WAAW,GACtD,IAAS,qBAAqB,EAAQ,iBAAiB;EAC7D,EAAe,KAAK,EAAS,CAAC,MAAM,iBAAiB,GAAa,GAAQ,CAAa,CAAC,CAAC,CAAC;CAC3F;CACA,IAAM,IAAiC,CAAC,EAAS,CAAc,CAAC;CAChE,AAAI,EAAM,UAAU,KAAA,KACnB,EAAiB,KAChB,EACC,GACA,EAAS,CACR,EAAS,CAAC,EAAiB,EAAK,SAAS,GAAG,EAAY,EAAY,EAAM,KAAK,CAAC,CAAC,CAAC,CACnF,CAAC,CACF,CACD;CAED,IAAM,IAAM,EAAS,CAAC,EAAS,CAAgB,CAAC,CAAC;CACjD,OAAO;EACN;EACA,KAAK,EAAU,gBAAgB,CAAG;EAClC,QAAQ,EAAa,CAAG;CACzB;AACD;;AAiBA,SAAgB,2BAA2B,GAAoC;CAC9E,IAAM,IAAM,EAAqB,GAAK,EAAE,UAAA,GAAgC,CAAC;CACzE,IAAI,EAAI,SAAS,KAAK,EAAI,SAAS,GAClC,MAAU,MAAM,wBAAwB;CAEzC,IAAM,IAAa,EAAe,EAAI,IAAI,YAAY,GAChD,IAAoB,EAAI;CAC9B,IAAI,MAAsB,KAAA,KAAa,EAAkB,QAAQ,KAChE,MAAU,MAAM,wBAAwB;CAEzC,AAAI,MAAsB,KAAA,KACzB,8BAA8B,GA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,IAC3E,MAAU,MAAM,6CAA6C;AAE/D;AAEA,SAAS,iCACR,GACA,GACA,GACO;CACP,IAAM,IAAW,EAAW,GAAQ,CAAO;CAC3C,IACC,EAAQ,QAAQ,MAChB,EAAS,SAAS,KAClB,EAAS,SAAS,KAClB,EAAS,EAAE,EAAE,QAAQ,GAErB,MAAU,MAAM,GAAG,EAAM,uCAAuC;CAEjE,EAAuB,EAAe,EAAS,IAAI,GAAG,EAAM,KAAK,CAAC,CAAC,KAAK;AACzE;AAEA,SAAS,aAAa,GAAuB;CAC5C,OAAO,EAAM,YAAY;AAC1B;;AAGA,SAAS,yBAAyB,GAAgC;CACjE,QAAQ,GAAR;EACC,KAAK,EAAK,MACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,SACC,MAAU,MAAM,wCAAwC,GAAK;CAC/D;AACD;;AAGA,SAAS,gBAAgB,GAAkC;CAC1D,OAAO;EACN,EAAO;EACP,EAAO;EACP,EAAO;EACP,EAAO;CACR,CAAC,CAAC,KAAK,GAAG;AACX"}
1
+ {"version":3,"file":"ocsp.js","names":[],"sources":["../../src/revocation/ocsp.ts"],"sourcesContent":["/**\n * Full OCSP lifecycle: build requests, create/parse/verify/validate responses.\n *\n * Supports SHA-1 and SHA-256 cert-ID hashing, nonce replay protection,\n * delegated responder certificate validation (direct and chain-based),\n * and embedded responder certificate discovery.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\textractBitStringValue,\n\thexToBytes,\n\tparseTime,\n\trequireElement,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\tbitString,\n\tconcatBytes,\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\timplicitPrimitiveContext,\n\tinteger,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\ttime,\n\ttlv,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport {\n\tdescribeHashAlgorithm,\n\tdescribeSignatureAlgorithm,\n} from '#micro509/internal/crypto/algorithm-names';\nimport { verifySignedDataDetailed } from '#micro509/internal/crypto/sig-verify';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport { compareDistinguishedNames } from '#micro509/internal/shared/dn';\nimport { pemDecodeOrThrow, pemEncode } from '#micro509/pem/pem';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, successResult } from '#micro509/result/result';\nimport type { CrlSource, ParsedCertificateRevocationList } from '#micro509/revocation/crl';\nimport {\n\tcheckCertificateRevocationAgainstCrl,\n\tparseCertificateRevocationListDerOrThrow,\n\tparseCertificateRevocationListPemOrThrow,\n} from '#micro509/revocation/crl';\nimport { verifyCertificateChain } from '#micro509/verify/verify';\nimport type {\n\tNameFieldKey,\n\tParsedCertificate,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow, parseCertificateFromSource } from '#micro509/x509/parse';\n\n/** Hash algorithm used to compute OCSP CertID fields. SHA-1 is the RFC 6960 default. */\nexport type OcspHashAlgorithm = 'SHA-1' | 'SHA-256';\n/** PEM string, DER bytes, or already-parsed certificate. */\nexport type OcspCertificateSource = string | Uint8Array | ParsedCertificate;\n/** PEM string, DER bytes, or already-parsed OCSP request. */\nexport type OcspRequestSource = string | Uint8Array | ParsedOcspRequest;\n\n/**\n * One certificate whose status to query in an OCSP request.\n * Used as an element of {@linkcode CreateOcspRequestInput.requests}.\n */\nexport interface CreateOcspRequestItemInput {\n\t/** Certificate whose revocation status is being queried. */\n\treadonly certificate: OcspCertificateSource;\n\t/** Issuer of `certificate` — needed to compute the CertID hash. */\n\treadonly issuerCertificate: OcspCertificateSource;\n}\n\n/**\n * Input for {@linkcode createOcspRequest}.\n */\nexport interface CreateOcspRequestInput {\n\t/** One or more certificates to query (batched into a single OCSP request). */\n\treadonly requests: readonly CreateOcspRequestItemInput[];\n\t/** Hash algorithm for CertID computation. Defaults to `'SHA-1'`. */\n\treadonly hashAlgorithm?: OcspHashAlgorithm;\n\t/** Random nonce for replay protection. Omit to skip the nonce extension. */\n\treadonly nonce?: Uint8Array;\n}\n\n/**\n * Encoded OCSP request in multiple serialisation formats, returned by {@linkcode createOcspRequest}.\n */\nexport interface OcspRequestMaterial {\n\t/** Raw DER bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-encoded request (`-----BEGIN OCSP REQUEST-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armour). */\n\treadonly base64: string;\n}\n\n/**\n * Decoded OCSP CertID — identifies a certificate by hashed issuer name,\n * hashed issuer key, and serial number.\n */\nexport interface ParsedOcspCertId {\n\t/** OID of the hash algorithm used for the name and key hashes. */\n\treadonly hashAlgorithmOid: string;\n\t/** Human-readable hash algorithm name (e.g. `\"SHA-256\"`). */\n\treadonly hashAlgorithmName: string;\n\t/** Hex-encoded hash of the issuer's distinguished name DER. */\n\treadonly issuerNameHashHex: string;\n\t/** Hex-encoded hash of the issuer's SubjectPublicKey BIT STRING content. */\n\treadonly issuerKeyHashHex: string;\n\t/** Hex-encoded serial number of the certificate. */\n\treadonly serialNumberHex: string;\n}\n\n/**\n * Decoded OCSP request, returned by {@linkcode parseOcspRequestDer} / {@linkcode parseOcspRequestPem}.\n */\nexport interface ParsedOcspRequest {\n\t/** Original DER bytes when this object came from {@linkcode parseOcspRequestDer} or PEM parsing. */\n\treadonly der?: Uint8Array;\n\t/** CertIDs of the certificates being queried. */\n\treadonly requests: readonly ParsedOcspCertId[];\n\t/** Hex-encoded nonce extension value, if present. */\n\treadonly nonce?: string;\n}\n\n/** RFC 6960 certificate status reported by the responder for a single CertID. */\nexport type OcspCertStatus = 'good' | 'revoked' | 'unknown';\n/** RFC 6960 overall response status — anything other than `'successful'` means the response body is absent or unusable. */\nexport type OcspResponseStatus =\n\t| 'successful'\n\t| 'malformedRequest'\n\t| 'internalError'\n\t| 'tryLater'\n\t| 'sigRequired'\n\t| 'unauthorized';\n\n/**\n * Status of one certificate inside an OCSP BasicResponse.\n */\nexport interface ParsedOcspSingleResponse {\n\t/** Which certificate this status applies to. */\n\treadonly certId: ParsedOcspCertId;\n\t/** Responder's verdict: `good`, `revoked`, or `unknown`. */\n\treadonly certStatus: OcspCertStatus;\n\t/** Start of the validity window for this status assertion. */\n\treadonly thisUpdate: Date;\n\t/** End of the validity window. Absent if the responder does not commit to a schedule. */\n\treadonly nextUpdate?: Date;\n\t/** When the certificate was revoked (only for `certStatus === 'revoked'`). */\n\treadonly revokedAt?: Date;\n\t/** CRLReason integer (only for `certStatus === 'revoked'`). */\n\treadonly revocationReasonCode?: number;\n}\n\n/**\n * How the OCSP responder identifies itself — either by distinguished name or\n * by SHA-1 hash of its public key.\n */\nexport type ParsedOcspResponderId =\n\t| {\n\t\t\t/** Responder identified by its certificate subject name. */\n\t\t\treadonly type: 'byName';\n\t\t\t/** Parsed distinguished name of the responder. */\n\t\t\treadonly name: ParsedName;\n\t }\n\t| {\n\t\t\t/** Responder identified by public-key hash. */\n\t\t\treadonly type: 'byKeyHash';\n\t\t\t/** Hex-encoded SHA-1 hash of the responder's SubjectPublicKey content. */\n\t\t\treadonly keyHashHex: string;\n\t };\n\n/**\n * Decoded OCSP response, returned by {@linkcode parseOcspResponseDer} / {@linkcode parseOcspResponsePem}.\n *\n * When `responseStatus` is not `'successful'`, most fields are absent.\n */\nexport interface ParsedOcspResponse {\n\t/** Original DER bytes when this object came from {@linkcode parseOcspResponseDer} or PEM parsing. */\n\treadonly der?: Uint8Array;\n\t/** Overall response status. Only `'successful'` carries a BasicOCSPResponse body. */\n\treadonly responseStatus: OcspResponseStatus;\n\t/** OID of the response type (normally `id-pkix-ocsp-basic`). */\n\treadonly responseTypeOid?: string;\n\t/** DER-encoded ResponseData — the signed payload for signature verification. */\n\treadonly responseDataDer?: Uint8Array;\n\t/** How the responder identifies itself. */\n\treadonly responderId?: ParsedOcspResponderId;\n\t/** OID of the algorithm used to sign this response. */\n\treadonly signatureAlgorithmOid?: string;\n\t/** Human-readable signature algorithm name. */\n\treadonly signatureAlgorithmName?: string;\n\t/** Raw signature bytes. */\n\treadonly signatureValue?: Uint8Array;\n\t/** Timestamp when the responder produced this response. */\n\treadonly producedAt?: Date;\n\t/** Per-certificate status entries. */\n\treadonly responses?: readonly ParsedOcspSingleResponse[];\n\t/** Hex-encoded nonce, if the response echoed one. */\n\treadonly nonce?: string;\n\t/** Certificates embedded in the response (typically the responder's chain). */\n\treadonly certificates?: readonly ParsedCertificate[];\n}\n\n/**\n * One certificate's status entry for {@linkcode CreateOcspResponseInput.responses}.\n * Extends {@linkcode CreateOcspRequestItemInput} with status and timing fields.\n */\nexport interface CreateOcspSingleResponseInput extends CreateOcspRequestItemInput {\n\t/** Status to assert for this certificate. */\n\treadonly certStatus: OcspCertStatus;\n\t/** Start of the validity window for this status assertion. Defaults to `new Date()`. */\n\treadonly thisUpdate?: Date;\n\t/** End of the validity window. Omit for open-ended assertions. */\n\treadonly nextUpdate?: Date;\n\t/** Revocation time (required when `certStatus` is `'revoked'`). Defaults to `thisUpdate`. */\n\treadonly revokedAt?: Date;\n\t/** CRLReason integer code (only meaningful when `certStatus` is `'revoked'`). */\n\treadonly revocationReasonCode?: number;\n}\n\n/**\n * Input for {@linkcode createOcspResponse}.\n */\nexport interface CreateOcspResponseInput {\n\t/** Private key used to sign the response. Algorithm is inferred from the key. */\n\treadonly signerPrivateKey: CryptoKey;\n\t/** Certificate of the OCSP responder — used to build the responder ID (by key hash). */\n\treadonly signerCertificate: OcspCertificateSource;\n\t/** Per-certificate status entries to include in the BasicOCSPResponse. */\n\treadonly responses: readonly CreateOcspSingleResponseInput[];\n\t/** Timestamp for the `producedAt` field. Defaults to `new Date()`. */\n\treadonly producedAt?: Date;\n\t/** Nonce to echo back for replay protection. */\n\treadonly nonce?: Uint8Array;\n\t/** Hash algorithm for CertID computation. Defaults to `'SHA-1'`. */\n\treadonly hashAlgorithm?: OcspHashAlgorithm;\n\t/** Extra certificates to embed in the response (e.g. the responder's issuer chain). */\n\treadonly includedCertificates?: readonly OcspCertificateSource[];\n}\n\n/**\n * Encoded OCSP response in multiple serialisation formats, returned by {@linkcode createOcspResponse}.\n */\nexport interface OcspResponseMaterial {\n\t/** Raw DER bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-encoded response (`-----BEGIN OCSP RESPONSE-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armour). */\n\treadonly base64: string;\n}\n\n/** Failure detail when OCSP response signature verification fails. */\nexport interface VerifyOcspResponseSignatureFailure extends Micro509Error<'signature_invalid'> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Result of {@linkcode verifyOcspResponseSignature}.\n *\n * On success, `value` is the parsed response whose signature has been verified.\n */\nexport type VerifyOcspResponseSignatureResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** Parsed response with a verified signature. */\n\t\t\treadonly value: ParsedOcspResponse;\n\t }\n\t| ErrorResult<'signature_invalid', Record<never, never>, VerifyOcspResponseSignatureFailure>;\n\n/**\n * Revocation policy for delegated OCSP responder certificates (RFC 6960 §4.2.2.2.1).\n *\n * - `'honor-nocheck'` (default): a responder carrying `id-pkix-ocsp-nocheck`\n * is exempt from revocation checking. Otherwise, CRL evidence from\n * {@linkcode ValidateOcspResponseInput.responderRevocationCrls} is consulted\n * when provided — a revoked responder rejects the response; missing or\n * unusable evidence is tolerated (soft).\n * - `'require-evidence'`: `nocheck` is ignored; CRL evidence must positively\n * show the responder is not revoked, otherwise the response is rejected.\n * - `'skip'`: no responder revocation checking.\n */\nexport type OcspResponderRevocationPolicy = 'honor-nocheck' | 'require-evidence' | 'skip';\n\n/**\n * Input for {@linkcode validateOcspResponse}.\n */\nexport interface ValidateOcspResponseInput {\n\t/** The OCSP response to validate. */\n\treadonly response: string | Uint8Array | ParsedOcspResponse;\n\t/** Certificate of the CA that issued the target certificate. */\n\treadonly issuerCertificate: OcspCertificateSource;\n\t/** Original request — enables nonce and request-coverage checks. */\n\treadonly request?: OcspRequestSource;\n\t/** Explicit responder certificate — overrides embedded certificate discovery. */\n\treadonly responderCertificate?: OcspCertificateSource;\n\t/** When `true`, allows delegated responder chain validation beyond direct issuance. */\n\treadonly allowChainedResponderCertificate?: boolean;\n\t/**\n\t * Explicitly trusted responder certificates for this issuer's scope\n\t * (RFC 6960 §4.2.2.2 criterion 1 — local responder configuration).\n\t *\n\t * A response signer matching one of these certificates is accepted without\n\t * the delegated-responder issuance, chain, EKU, and revocation checks.\n\t * Signature verification and responder-ID binding are still enforced.\n\t * Also consulted during responder discovery when the response embeds no\n\t * matching certificate.\n\t */\n\treadonly trustedOcspResponders?: readonly OcspCertificateSource[];\n\t/** Revocation policy for delegated responder certificates. Defaults to `'honor-nocheck'`. */\n\treadonly responderRevocationPolicy?: OcspResponderRevocationPolicy;\n\t/** CRLs used as revocation evidence for delegated responder certificates. */\n\treadonly responderRevocationCrls?: readonly CrlSource[];\n\t/** Evaluation time for freshness checks and delegated responder chain validation. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/** Clock-skew tolerance in milliseconds for `thisUpdate`/`nextUpdate`/`producedAt`. */\n\treadonly clockSkewMs?: number;\n}\n\n/** Failure codes produced by {@linkcode validateOcspResponse}. */\nexport type ValidateOcspResponseErrorCode =\n\t| 'response_status_invalid'\n\t| 'signature_invalid'\n\t| 'responder_id_mismatch'\n\t| 'nonce_mismatch'\n\t| 'request_mismatch'\n\t| 'issuer_mismatch'\n\t| 'responder_chain_invalid'\n\t| 'ocsp_signing_missing'\n\t| 'responder_revoked'\n\t| 'responder_revocation_unknown'\n\t| 'stale_response';\n\n/**\n * Failure detail for {@linkcode validateOcspResponse}.\n *\n * Possible codes: `response_status_invalid`, `signature_invalid`,\n * `responder_id_mismatch`, `nonce_mismatch`, `request_mismatch`,\n * `issuer_mismatch`, `responder_chain_invalid`, `ocsp_signing_missing`,\n * `responder_revoked`, `responder_revocation_unknown`, `stale_response`.\n */\nexport interface ValidateOcspResponseFailure extends Micro509Error<ValidateOcspResponseErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Result of {@linkcode validateOcspResponse}.\n *\n * On success, the response has passed status, signature, responder binding,\n * authorization (including responder revocation policy), freshness, nonce,\n * and request-coverage checks.\n */\nexport type ValidateOcspResponseResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** Fully validated OCSP response. */\n\t\t\treadonly value: ParsedOcspResponse;\n\t }\n\t| ErrorResult<ValidateOcspResponseErrorCode, Record<never, never>, ValidateOcspResponseFailure>;\n\ntype ValidateOcspResponseFailureBranch = Extract<\n\tValidateOcspResponseResult,\n\t{ readonly ok: false }\n>;\n\ninterface NormalizedOcspValidationInput {\n\treadonly ok: true;\n\treadonly parsedResponse: ParsedOcspResponse;\n\treadonly issuer: ParsedCertificate;\n\treadonly trustedResponders: readonly ParsedCertificate[];\n\treadonly signer: ParsedCertificate;\n}\n\ninterface ParsedOcspCertStatusFields {\n\treadonly certStatus: ParsedOcspSingleResponse['certStatus'];\n\treadonly revokedAt?: Date;\n\treadonly revocationReasonCode?: number;\n}\n\n/**\n * Builds a DER-encoded OCSP request containing one or more CertID entries\n * and an optional nonce extension.\n *\n * @example\n * ```ts\n * import { createOcspRequest } from 'micro509';\n *\n * const req = await createOcspRequest({\n * requests: [{ certificate: leafPem, issuerCertificate: caPem }],\n * hashAlgorithm: 'SHA-256',\n * nonce: crypto.getRandomValues(new Uint8Array(16)),\n * });\n * // POST req.der to the OCSP responder URI\n * ```\n */\nexport async function createOcspRequest(\n\tinput: CreateOcspRequestInput,\n): Promise<OcspRequestMaterial> {\n\tconst hashAlgorithm = input.hashAlgorithm ?? 'SHA-1';\n\tconst requestEntries: Uint8Array[] = [];\n\tfor (const request of input.requests) {\n\t\tconst certificate = normalizeCertificate(request.certificate);\n\t\tconst issuer = normalizeCertificate(request.issuerCertificate);\n\t\trequestEntries.push(sequence([await encodeOcspCertId(certificate, issuer, hashAlgorithm)]));\n\t}\n\tconst tbsRequestFields: Uint8Array[] = [sequence(requestEntries)];\n\tif (input.nonce !== undefined) {\n\t\ttbsRequestFields.push(\n\t\t\texplicitContext(\n\t\t\t\t2,\n\t\t\t\tsequence([\n\t\t\t\t\tsequence([objectIdentifier(OIDS.ocspNonce), octetString(octetString(input.nonce))]),\n\t\t\t\t]),\n\t\t\t),\n\t\t);\n\t}\n\tconst der = sequence([sequence(tbsRequestFields)]);\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('OCSP REQUEST', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/** Machine-readable failure reason for the OCSP request parsers. */\nexport type ParseOcspRequestErrorCode = 'malformed';\n\n/** Structured failure payload for OCSP request parsing. */\nexport interface ParseOcspRequestFailure extends Micro509Error<ParseOcspRequestErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parseOcspRequestDer} / {@linkcode parseOcspRequestPem}. */\nexport type ParseOcspRequestResult =\n\t| { readonly ok: true; readonly value: ParsedOcspRequest }\n\t| ErrorResult<ParseOcspRequestErrorCode, Record<never, never>, ParseOcspRequestFailure>;\n\n/** Throwing core for {@linkcode parseOcspRequestDer}. */\nexport function parseOcspRequestDerOrThrow(der: Uint8Array): ParsedOcspRequest {\n\tconst top = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (top.length < 1 || top.length > 2) {\n\t\tthrow new Error('Malformed OCSP request');\n\t}\n\tconst tbsRequest = requireElement(top[0], 'tbsRequest');\n\tconst optionalSignature = top[1];\n\tif (optionalSignature !== undefined && optionalSignature.tag !== 0xa0) {\n\t\tthrow new Error('Malformed OCSP request');\n\t}\n\tif (optionalSignature !== undefined) {\n\t\tvalidateOcspOptionalSignature(der, optionalSignature);\n\t}\n\tconst tbsChildren = childrenOf(der, tbsRequest);\n\tlet cursor = skipOcspRequestVersion(der, tbsChildren, 0);\n\tcursor = skipOcspRequestorName(der, tbsChildren, cursor);\n\tconst requestList = requireElement(tbsChildren[cursor], 'requestList');\n\tif (requestList.tag !== 0x30) {\n\t\tthrow new Error('requestList must use SEQUENCE');\n\t}\n\tif (childrenOf(der, requestList).length === 0) {\n\t\tthrow new Error('requestList must not be empty');\n\t}\n\tconst requests = childrenOf(der, requestList).map((request) => {\n\t\tconst requestChildren = childrenOf(der, request);\n\t\tif (requestChildren.length < 1 || requestChildren.length > 2) {\n\t\t\tthrow new Error('Malformed OCSP request entry');\n\t\t}\n\t\tif (requestChildren[1] !== undefined && requestChildren[1].tag !== 0xa0) {\n\t\t\tthrow new Error('Malformed OCSP request entry');\n\t\t}\n\t\tconst certId = requireElement(requestChildren[0], 'reqCert');\n\t\treturn parseOcspCertId(der.slice(certId.start - certId.headerLength, certId.end));\n\t});\n\tcursor += 1;\n\tconst extensions = tbsChildren[cursor];\n\tif (extensions !== undefined && extensions.tag !== 0xa2) {\n\t\tthrow new Error('Malformed OCSP request');\n\t}\n\tif (tbsChildren.length !== cursor + (extensions === undefined ? 0 : 1)) {\n\t\tthrow new Error('Malformed OCSP request');\n\t}\n\tconst nonce =\n\t\textensions === undefined ? undefined : parseOcspNonceFromExtensions(der, extensions);\n\treturn {\n\t\tder: new Uint8Array(der),\n\t\trequests,\n\t\t...(nonce === undefined ? {} : { nonce }),\n\t};\n}\n\nfunction skipOcspRequestVersion(\n\tder: Uint8Array,\n\ttbsChildren: readonly DerElement[],\n\tcursor: number,\n): number {\n\tif (tbsChildren[cursor]?.tag !== 0xa0) return cursor;\n\tconst versionWrapper = requireElement(tbsChildren[cursor], 'version');\n\tconst versionFields = childrenOf(der, versionWrapper);\n\tconst versionElement = requireElement(versionFields[0], 'version');\n\tif (versionFields.length !== 1 || versionElement.tag !== 0x02) {\n\t\tthrow new Error('version must use INTEGER');\n\t}\n\tif (decodeNonNegativeIntegerNumber(versionElement.value, 'OCSP request version') !== 0) {\n\t\tthrow new Error('Unsupported OCSP request version');\n\t}\n\treturn cursor + 1;\n}\n\nfunction skipOcspRequestorName(\n\tder: Uint8Array,\n\ttbsChildren: readonly DerElement[],\n\tcursor: number,\n): number {\n\tconst requestorName = tbsChildren[cursor];\n\tif (requestorName?.tag !== 0xa1) return cursor;\n\tvalidateOcspRequestorName(der, requestorName);\n\treturn cursor + 1;\n}\n\n/** Decodes a PEM-encoded OCSP request (`-----BEGIN OCSP REQUEST-----`). */\nexport function parseOcspRequestPemOrThrow(pem: string): ParsedOcspRequest {\n\treturn parseOcspRequestDerOrThrow(pemDecodeOrThrow('OCSP REQUEST', pem));\n}\n\n/**\n * Decodes a DER-encoded OCSP request into a structured {@linkcode ParsedOcspRequest}.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseOcspRequestDerOrThrow}.\n */\nexport function parseOcspRequestDer(der: Uint8Array): ParseOcspRequestResult {\n\ttry {\n\t\treturn successResult(parseOcspRequestDerOrThrow(der));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed OCSP request',\n\t\t);\n\t}\n}\n\n/**\n * Decodes a PEM-encoded OCSP request (`-----BEGIN OCSP REQUEST-----`).\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseOcspRequestPemOrThrow}.\n */\nexport function parseOcspRequestPem(pem: string): ParseOcspRequestResult {\n\ttry {\n\t\treturn successResult(parseOcspRequestPemOrThrow(pem));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed OCSP request',\n\t\t);\n\t}\n}\n\n/** Machine-readable failure reason for the OCSP response parsers. */\nexport type ParseOcspResponseErrorCode = 'malformed';\n\n/** Structured failure payload for OCSP response parsing. */\nexport interface ParseOcspResponseFailure extends Micro509Error<ParseOcspResponseErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parseOcspResponseDer} / {@linkcode parseOcspResponsePem}. */\nexport type ParseOcspResponseResult =\n\t| { readonly ok: true; readonly value: ParsedOcspResponse }\n\t| ErrorResult<ParseOcspResponseErrorCode, Record<never, never>, ParseOcspResponseFailure>;\n\n/** Throwing core for {@linkcode parseOcspResponseDer}. */\nexport function parseOcspResponseDerOrThrow(der: Uint8Array): ParsedOcspResponse {\n\tconst top = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (top.length < 1 || top.length > 2) {\n\t\tthrow new Error('Malformed OCSP response');\n\t}\n\tconst statusElement = requireElement(top[0], 'responseStatus');\n\tif (statusElement.tag !== 0x0a) {\n\t\tthrow new Error('responseStatus must use ENUMERATED');\n\t}\n\tconst responseStatus = ocspResponseStatusFromCode(\n\t\tdecodeNonNegativeIntegerNumber(statusElement.value, 'OCSP responseStatus'),\n\t);\n\tconst responseBytes = top[1];\n\tif (responseBytes === undefined) {\n\t\treturn { der: new Uint8Array(der), responseStatus };\n\t}\n\tif (responseBytes.tag !== 0xa0) {\n\t\tthrow new Error('Malformed OCSP response');\n\t}\n\tconst responseBytesWrapper = childrenOf(der, responseBytes);\n\tconst bytesSequence = requireElement(responseBytesWrapper[0], 'responseBytes');\n\tif (responseBytesWrapper.length !== 1 || bytesSequence.tag !== 0x30) {\n\t\tthrow new Error('Malformed OCSP response');\n\t}\n\tconst responseBytesChildren = childrenOf(der, bytesSequence);\n\tif (responseBytesChildren.length !== 2) {\n\t\tthrow new Error('responseBytes must contain responseType and response');\n\t}\n\tconst responseType = requireElement(responseBytesChildren[0], 'responseType');\n\tconst response = requireElement(responseBytesChildren[1], 'response');\n\tif (response.tag !== 0x04) {\n\t\tthrow new Error('response must use OCTET STRING');\n\t}\n\tconst responseTypeOid = decodeObjectIdentifier(responseType.value);\n\tif (responseTypeOid !== OIDS.ocspBasicResponse) {\n\t\treturn { der: new Uint8Array(der), responseStatus, responseTypeOid };\n\t}\n\tconst basicResponse = response.value;\n\tconst basicChildren = readSequenceChildren(basicResponse);\n\tif (basicChildren.length < 3 || basicChildren.length > 4) {\n\t\tthrow new Error('Malformed BasicOCSPResponse');\n\t}\n\tconst responseData = requireElement(basicChildren[0], 'responseData');\n\tconst signatureAlgorithm = requireElement(basicChildren[1], 'signatureAlgorithm');\n\tconst signatureValue = requireElement(basicChildren[2], 'signatureValue');\n\tconst certificatesElement = basicChildren[3];\n\tif (certificatesElement !== undefined && certificatesElement.tag !== 0xa0) {\n\t\tthrow new Error('Malformed BasicOCSPResponse');\n\t}\n\tconst signatureAlgorithmChildren = childrenOf(basicResponse, signatureAlgorithm);\n\tconst signatureAlgorithmOid = decodeObjectIdentifier(\n\t\trequireElement(signatureAlgorithmChildren[0], 'signatureAlgorithm OID').value,\n\t);\n\tconst signatureAlgorithmParameters = signatureAlgorithmChildren[1];\n\tconst responseDataDer = basicResponse.slice(\n\t\tresponseData.start - responseData.headerLength,\n\t\tresponseData.end,\n\t);\n\tconst signedResponseData = parseSignedOcspResponseData(responseDataDer);\n\treturn {\n\t\tder: new Uint8Array(der),\n\t\tresponseStatus,\n\t\tresponseTypeOid,\n\t\tresponseDataDer,\n\t\tresponderId: signedResponseData.responderId,\n\t\tsignatureAlgorithmOid,\n\t\tsignatureAlgorithmName: describeSignatureAlgorithm(\n\t\t\tsignatureAlgorithmOid,\n\t\t\tsignatureAlgorithmParameters === undefined\n\t\t\t\t? undefined\n\t\t\t\t: basicResponse.slice(\n\t\t\t\t\t\tsignatureAlgorithmParameters.start - signatureAlgorithmParameters.headerLength,\n\t\t\t\t\t\tsignatureAlgorithmParameters.end,\n\t\t\t\t\t),\n\t\t),\n\t\tsignatureValue: extractBitStringValue(signatureValue),\n\t\tproducedAt: signedResponseData.producedAt,\n\t\tresponses: signedResponseData.responses,\n\t\t...(signedResponseData.nonce === undefined ? {} : { nonce: signedResponseData.nonce }),\n\t\t...(certificatesElement?.tag === 0xa0\n\t\t\t? {\n\t\t\t\t\tcertificates: parseEmbeddedCertificates(basicResponse, certificatesElement),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Decodes a PEM-encoded OCSP response (`-----BEGIN OCSP RESPONSE-----`).\n *\n * @example\n * ```ts\n * import { parseOcspResponsePemOrThrow } from 'micro509';\n *\n * const resp = parseOcspResponsePemOrThrow(pemString);\n * if (resp.responseStatus === 'successful') {\n * for (const entry of resp.responses ?? []) {\n * console.log(entry.certId.serialNumberHex, entry.certStatus);\n * }\n * }\n * ```\n */\nexport function parseOcspResponsePemOrThrow(pem: string): ParsedOcspResponse {\n\treturn parseOcspResponseDerOrThrow(pemDecodeOrThrow('OCSP RESPONSE', pem));\n}\n\n/**\n * Decodes a DER-encoded OCSP response into a structured {@linkcode ParsedOcspResponse}.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseOcspResponseDerOrThrow}.\n */\nexport function parseOcspResponseDer(der: Uint8Array): ParseOcspResponseResult {\n\ttry {\n\t\treturn successResult(parseOcspResponseDerOrThrow(der));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed OCSP response',\n\t\t);\n\t}\n}\n\n/**\n * Decodes a PEM-encoded OCSP response (`-----BEGIN OCSP RESPONSE-----`).\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseOcspResponsePemOrThrow}.\n */\nexport function parseOcspResponsePem(pem: string): ParseOcspResponseResult {\n\ttry {\n\t\treturn successResult(parseOcspResponsePemOrThrow(pem));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult(\n\t\t\t'malformed',\n\t\t\terror instanceof Error ? error.message : 'Malformed OCSP response',\n\t\t);\n\t}\n}\n\n/**\n * Signs and encodes an OCSP BasicResponse with a `successful` status.\n *\n * The responder is identified by key hash (SHA-1 of the signer's SubjectPublicKey).\n * Use `includedCertificates` to embed the responder's chain for relying parties.\n *\n * @example\n * ```ts\n * import { createOcspResponse } from 'micro509';\n *\n * const resp = await createOcspResponse({\n * signerPrivateKey: responderPrivateKey,\n * signerCertificate: responderCertPem,\n * responses: [\n * {\n * certificate: leafPem,\n * issuerCertificate: caPem,\n * certStatus: 'good',\n * thisUpdate: new Date('2025-01-01'),\n * nextUpdate: new Date('2025-01-08'),\n * },\n * ],\n * nonce: requestNonce,\n * });\n * // resp.der, resp.pem, resp.base64\n * ```\n */\nexport async function createOcspResponse(\n\tinput: CreateOcspResponseInput,\n): Promise<OcspResponseMaterial> {\n\tconst signerCertificate = normalizeCertificate(input.signerCertificate);\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey);\n\tconst producedAt = input.producedAt ?? new Date();\n\tconst hashAlgorithm = input.hashAlgorithm ?? 'SHA-1';\n\tconst responses: Uint8Array[] = [];\n\tfor (const response of input.responses) {\n\t\tconst certificate = normalizeCertificate(response.certificate);\n\t\tconst issuer = normalizeCertificate(response.issuerCertificate);\n\t\tresponses.push(await encodeSingleResponse(certificate, issuer, response, hashAlgorithm));\n\t}\n\tconst responderKeyHash = await digestBytes(\n\t\t'SHA-1',\n\t\textractSubjectPublicKeyBytes(signerCertificate.subjectPublicKeyInfoDer),\n\t);\n\tconst responseDataFields: Uint8Array[] = [\n\t\timplicitPrimitiveContext(2, responderKeyHash),\n\t\ttime(producedAt),\n\t\tsequence(responses),\n\t];\n\tif (input.nonce !== undefined) {\n\t\tresponseDataFields.push(\n\t\t\texplicitContext(\n\t\t\t\t1,\n\t\t\t\tsequence([\n\t\t\t\t\tsequence([objectIdentifier(OIDS.ocspNonce), octetString(octetString(input.nonce))]),\n\t\t\t\t]),\n\t\t\t),\n\t\t);\n\t}\n\tconst responseData = sequence(responseDataFields);\n\tconst signature = await signBytes(input.signerPrivateKey, signatureAlgorithm, responseData);\n\tconst includedCertificates =\n\t\tinput.includedCertificates === undefined\n\t\t\t? []\n\t\t\t: await Promise.all(input.includedCertificates.map(normalizeCertificate));\n\tconst basicResponseFields: Uint8Array[] = [\n\t\tresponseData,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(signature),\n\t];\n\tif (includedCertificates.length > 0) {\n\t\tbasicResponseFields.push(\n\t\t\texplicitContext(0, concatBytes(includedCertificates.map((certificate) => certificate.der))),\n\t\t);\n\t}\n\tconst basicResponse = sequence(basicResponseFields);\n\tconst der = sequence([\n\t\ttlv(0x0a, Uint8Array.of(0x00)),\n\t\texplicitContext(\n\t\t\t0,\n\t\t\tsequence([objectIdentifier(OIDS.ocspBasicResponse), octetString(basicResponse)]),\n\t\t),\n\t]);\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('OCSP RESPONSE', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/**\n * Verifies the OCSP response signature against the given signer certificate.\n *\n * Does **not** check responder binding, freshness, or nonce — use\n * {@linkcode validateOcspResponse} for full validation.\n */\nexport async function verifyOcspResponseSignature(\n\tresponse: string | Uint8Array | ParsedOcspResponse,\n\tsignerCertificate: OcspCertificateSource,\n): Promise<VerifyOcspResponseSignatureResult> {\n\tlet parsed: ParsedOcspResponse;\n\ttry {\n\t\tparsed = normalizeOcspResponse(response);\n\t} catch {\n\t\treturn verifyOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response signed content is malformed',\n\t\t);\n\t}\n\tif (\n\t\tparsed.responseDataDer === undefined ||\n\t\tparsed.signatureAlgorithmOid === undefined ||\n\t\tparsed.signatureValue === undefined\n\t) {\n\t\treturn verifyOcspResponseFailureResult('signature_invalid', 'OCSP response is not signed');\n\t}\n\tlet signer: ParsedCertificate;\n\ttry {\n\t\tsigner = normalizeCertificate(signerCertificate);\n\t} catch {\n\t\treturn verifyOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP signer certificate input is malformed',\n\t\t);\n\t}\n\tlet verifiedResult: Awaited<ReturnType<typeof verifySignedDataDetailed>>;\n\ttry {\n\t\tverifiedResult = await verifySignedDataDetailed(\n\t\t\tparsed.signatureAlgorithmOid,\n\t\t\tundefined,\n\t\t\tsigner.publicKeyAlgorithmOid,\n\t\t\tsigner.publicKeyParametersOid,\n\t\t\tsigner.subjectPublicKeyInfoDer,\n\t\t\tparsed.signatureValue,\n\t\t\tparsed.responseDataDer,\n\t\t);\n\t} catch {\n\t\treturn verifyOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response signature verification failed',\n\t\t);\n\t}\n\tif (!verifiedResult.ok) {\n\t\tif (verifiedResult.code === 'verification_error') {\n\t\t\treturn verifyOcspResponseFailureResult(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'OCSP response signature verification failed',\n\t\t\t);\n\t\t}\n\t\treturn verifyOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response signature uses unsupported algorithm parameters',\n\t\t);\n\t}\n\treturn verifiedResult.valid\n\t\t? { ok: true, value: parsed }\n\t\t: verifyOcspResponseFailureResult(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'OCSP response signature does not verify',\n\t\t\t);\n}\n\n/**\n * Full OCSP response validation: response status check, signature verification,\n * responder ID binding (byName or byKeyHash), delegated-responder chain and\n * ocspSigning EKU checks, `producedAt`/`thisUpdate`/`nextUpdate` freshness,\n * nonce match, and request-coverage completeness.\n *\n * @example\n * ```ts\n * import { validateOcspResponse } from 'micro509';\n *\n * const result = await validateOcspResponse({\n * response: ocspResponseDer,\n * issuerCertificate: caPem,\n * request: ocspRequestDer,\n * });\n * if (result.ok) {\n * const entry = result.value.responses?.[0];\n * console.log(entry?.certStatus); // 'good' | 'revoked' | 'unknown'\n * }\n * ```\n */\nexport async function validateOcspResponse(\n\tinput: ValidateOcspResponseInput,\n): Promise<ValidateOcspResponseResult> {\n\tlet parsedResponse: ParsedOcspResponse;\n\ttry {\n\t\tparsedResponse = normalizeOcspResponse(input.response);\n\t} catch {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response signed content is malformed',\n\t\t);\n\t}\n\tif (parsedResponse.responseStatus !== 'successful') {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'response_status_invalid',\n\t\t\t`OCSP response status is ${parsedResponse.responseStatus}`,\n\t\t);\n\t}\n\tconst normalized = await normalizeOcspValidationInput(input, parsedResponse);\n\tif (!normalized.ok) {\n\t\treturn normalized;\n\t}\n\tconst { issuer, trustedResponders, signer } = normalized;\n\tconst signature = await verifyOcspResponseSignature(parsedResponse, signer);\n\tif (!signature.ok) {\n\t\treturn validateOcspResponseFailureResult(signature.code, signature.message);\n\t}\n\tconst responderAuthorization = await validateOcspResponderAuthorization(\n\t\tinput,\n\t\tparsedResponse,\n\t\tissuer,\n\t\tsigner,\n\t\ttrustedResponders,\n\t);\n\tif (responderAuthorization !== undefined) return responderAuthorization;\n\tconst at = input.at ?? new Date();\n\tconst skew = input.clockSkewMs ?? 0;\n\tconst freshness = await validateOcspResponseFreshness(parsedResponse, issuer, at, skew);\n\tif (freshness !== undefined) return freshness;\n\tif (hasDuplicateOcspResponseCertificateSerial(parsedResponse.responses ?? [])) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response contains multiple status entries for the same certificate',\n\t\t);\n\t}\n\tif (input.request !== undefined) {\n\t\tconst requestMatch = validateOcspRequestCoverage(input.request, parsedResponse);\n\t\tif (requestMatch !== undefined) return requestMatch;\n\t}\n\treturn { ok: true, value: parsedResponse };\n}\n\n/** Re-parses OCSP validation certificates and resolves the response signer. */\nasync function normalizeOcspValidationInput(\n\tinput: ValidateOcspResponseInput,\n\tparsedResponse: ParsedOcspResponse,\n): Promise<NormalizedOcspValidationInput | ValidateOcspResponseFailureBranch> {\n\tlet issuer: ParsedCertificate;\n\ttry {\n\t\tissuer = normalizeCertificate(input.issuerCertificate);\n\t} catch {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'issuer certificate input is malformed',\n\t\t);\n\t}\n\ttry {\n\t\tconst trustedResponders = (input.trustedOcspResponders ?? []).map(normalizeCertificate);\n\t\tconst resolvedResponder = await resolveOcspResponderCertificate(\n\t\t\tinput,\n\t\t\tparsedResponse,\n\t\t\ttrustedResponders,\n\t\t);\n\t\treturn {\n\t\t\tok: true,\n\t\t\tparsedResponse,\n\t\t\tissuer,\n\t\t\ttrustedResponders,\n\t\t\tsigner: normalizeCertificate(resolvedResponder),\n\t\t};\n\t} catch {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP responder certificate input is malformed',\n\t\t);\n\t}\n}\n\n/** Selects the responder certificate from explicit, embedded, trusted, or issuer inputs. */\nasync function resolveOcspResponderCertificate(\n\tinput: ValidateOcspResponseInput,\n\tparsedResponse: ParsedOcspResponse,\n\ttrustedResponders: readonly ParsedCertificate[],\n): Promise<OcspCertificateSource> {\n\treturn (\n\t\tinput.responderCertificate ??\n\t\t(await findMatchingOcspResponderCertificate(\n\t\t\tparsedResponse.certificates,\n\t\t\tparsedResponse.responderId,\n\t\t)) ??\n\t\t(await findMatchingOcspResponderCertificate(trustedResponders, parsedResponse.responderId)) ??\n\t\tparsedResponse.certificates?.[0] ??\n\t\tinput.issuerCertificate\n\t);\n}\n\nasync function validateOcspResponderAuthorization(\n\tinput: ValidateOcspResponseInput,\n\tparsedResponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\tsigner: ParsedCertificate,\n\ttrustedResponders: readonly ParsedCertificate[],\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tconst responderBinding = await safeValidateOcspResponderIdBinding(parsedResponse, signer);\n\tif (!responderBinding.ok) {\n\t\treturn responderBinding;\n\t}\n\tconst isLocallyTrustedResponder = trustedResponders.some((trusted) =>\n\t\tisSameOcspCertificate(signer, trusted),\n\t);\n\tif (isSameOcspCertificate(signer, issuer) || isLocallyTrustedResponder) {\n\t\treturn undefined;\n\t}\n\treturn await validateDelegatedOcspResponder(input, parsedResponse, issuer, signer);\n}\n\nasync function safeValidateOcspResponderIdBinding(\n\tparsedResponse: ParsedOcspResponse,\n\tsigner: ParsedCertificate,\n): Promise<ValidateOcspResponseFailureBranch | { readonly ok: true }> {\n\ttry {\n\t\treturn await validateOcspResponderIdBinding(parsedResponse.responderId, signer);\n\t} catch {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP responder certificate input is malformed',\n\t\t);\n\t}\n}\n\nasync function validateDelegatedOcspResponder(\n\tinput: ValidateOcspResponseInput,\n\tparsedResponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\tsigner: ParsedCertificate,\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tconst allowChainedResponderCertificate = input.allowChainedResponderCertificate === true;\n\tif (!allowChainedResponderCertificate && !isDirectlyIssuedByOcspIssuer(signer, issuer)) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'responder_chain_invalid',\n\t\t\t'Delegated OCSP responder must be directly issued by issuer certificate',\n\t\t);\n\t}\n\tconst chain = await verifyCertificateChain({\n\t\tleaf: signer.der,\n\t\tintermediates: allowChainedResponderCertificate\n\t\t\t? buildOcspResponderIntermediates(parsedResponse.certificates, signer, issuer)\n\t\t\t: [],\n\t\troots: [issuer.der],\n\t\t...(input.at !== undefined ? { at: input.at } : {}),\n\t});\n\tif (!chain.ok) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'responder_chain_invalid',\n\t\t\t'OCSP responder certificate chain does not validate',\n\t\t);\n\t}\n\tif (signer.extendedKeyUsage === undefined || !signer.extendedKeyUsage.includes('ocspSigning')) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'ocsp_signing_missing',\n\t\t\t'Delegated OCSP responder lacks ocspSigning EKU',\n\t\t);\n\t}\n\tconst responderRevocation = await checkDelegatedResponderRevocation(signer, issuer, input);\n\treturn responderRevocation.ok ? undefined : responderRevocation;\n}\n\n/** Checks response-level and per-certificate OCSP timestamps against the validation time. */\nasync function validateOcspResponseFreshness(\n\tparsedResponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\tat: Date,\n\tskew: number,\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tif (\n\t\tparsedResponse.producedAt !== undefined &&\n\t\tparsedResponse.producedAt.getTime() - skew > at.getTime()\n\t) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'stale_response',\n\t\t\t'OCSP response producedAt is later than requested time',\n\t\t);\n\t}\n\tfor (const response of parsedResponse.responses ?? []) {\n\t\tconst responseFreshness = await validateOcspSingleResponseFreshness(\n\t\t\tresponse,\n\t\t\tparsedResponse.producedAt,\n\t\t\tissuer,\n\t\t\tat,\n\t\t\tskew,\n\t\t);\n\t\tif (responseFreshness !== undefined) return responseFreshness;\n\t}\n\treturn undefined;\n}\n\nasync function validateOcspSingleResponseFreshness(\n\tresponse: ParsedOcspSingleResponse,\n\tproducedAt: Date | undefined,\n\tissuer: ParsedCertificate,\n\tat: Date,\n\tskew: number,\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tlet expected: ParsedOcspCertId;\n\ttry {\n\t\texpected = await buildParsedOcspCertId(\n\t\t\tresponse.certId.hashAlgorithmOid,\n\t\t\tissuer,\n\t\t\tresponse.certId.serialNumberHex,\n\t\t);\n\t} catch {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'OCSP response CertID hash algorithm is unsupported',\n\t\t);\n\t}\n\tif (\n\t\tresponse.certId.issuerNameHashHex !== expected.issuerNameHashHex ||\n\t\tresponse.certId.issuerKeyHashHex !== expected.issuerKeyHashHex\n\t) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'issuer_mismatch',\n\t\t\t'OCSP response certId does not match issuer certificate',\n\t\t);\n\t}\n\treturn validateOcspSingleResponseTimes(response, producedAt, at, skew);\n}\n\nfunction validateOcspSingleResponseTimes(\n\tresponse: ParsedOcspSingleResponse,\n\tproducedAt: Date | undefined,\n\tat: Date,\n\tskew: number,\n): ValidateOcspResponseFailureBranch | undefined {\n\tif (\n\t\tresponse.thisUpdate.getTime() - skew > at.getTime() ||\n\t\t(response.nextUpdate !== undefined && response.nextUpdate.getTime() + skew < at.getTime())\n\t) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'stale_response',\n\t\t\t'OCSP response is not valid at requested time',\n\t\t);\n\t}\n\tif (\n\t\tproducedAt !== undefined &&\n\t\tresponse.nextUpdate !== undefined &&\n\t\tproducedAt.getTime() - skew > response.nextUpdate.getTime()\n\t) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'stale_response',\n\t\t\t'OCSP response producedAt is later than nextUpdate',\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction validateOcspRequestCoverage(\n\trequestSource: OcspRequestSource,\n\tparsedResponse: ParsedOcspResponse,\n): ValidateOcspResponseFailureBranch | undefined {\n\tlet request: ParsedOcspRequest;\n\ttry {\n\t\trequest = normalizeOcspRequest(requestSource);\n\t} catch {\n\t\treturn validateOcspResponseFailureResult('request_mismatch', 'OCSP request input is malformed');\n\t}\n\tif (request.nonce !== undefined && request.nonce !== parsedResponse.nonce) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'nonce_mismatch',\n\t\t\t'OCSP response nonce does not match request nonce',\n\t\t);\n\t}\n\tconst requestIds = new Set(request.requests.map((entry) => serializeCertId(entry)));\n\tconst responseIds = new Set(\n\t\t(parsedResponse.responses ?? []).map((response) => serializeCertId(response.certId)),\n\t);\n\treturn validateOcspRequestIdCoverage(requestIds, responseIds, parsedResponse.responses ?? []);\n}\n\nfunction validateOcspRequestIdCoverage(\n\trequestIds: ReadonlySet<string>,\n\tresponseIds: ReadonlySet<string>,\n\tresponses: readonly ParsedOcspSingleResponse[],\n): ValidateOcspResponseFailureBranch | undefined {\n\tfor (const response of responses) {\n\t\tif (!requestIds.has(serializeCertId(response.certId))) {\n\t\t\treturn validateOcspResponseFailureResult(\n\t\t\t\t'request_mismatch',\n\t\t\t\t'OCSP response includes a certId not present in request',\n\t\t\t);\n\t\t}\n\t}\n\tfor (const requestId of requestIds) {\n\t\tif (!responseIds.has(requestId)) {\n\t\t\treturn validateOcspResponseFailureResult(\n\t\t\t\t'request_mismatch',\n\t\t\t\t'OCSP response does not cover every requested certId',\n\t\t\t);\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Builds a `VerifyOcspResponseSignatureFailureResult`. */\nfunction verifyOcspResponseFailureResult(\n\tcode: 'signature_invalid',\n\tmessage: string,\n): ErrorResult<'signature_invalid', Record<never, never>, VerifyOcspResponseSignatureFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Builds a `ValidateOcspResponseFailureResult`. */\nfunction validateOcspResponseFailureResult(\n\tcode: ValidateOcspResponseErrorCode,\n\tmessage: string,\n): ErrorResult<ValidateOcspResponseErrorCode, Record<never, never>, ValidateOcspResponseFailure> {\n\treturn failureResult(code, message);\n}\n\n/**\n * Reports whether a certificate carries the `id-pkix-ocsp-nocheck` extension\n * (RFC 6960 §4.2.2.2.1) — the CA's assertion that relying parties may trust\n * this OCSP responder certificate for its lifetime without revocation checks.\n */\nexport function hasOcspNoCheckExtension(certificate: OcspCertificateSource): boolean {\n\tconst parsed = normalizeCertificate(certificate);\n\treturn parsed.extensions.some((extension) => extension.oid === OIDS.ocspNoCheck);\n}\n\n/** Parses a CRL from PEM string, DER bytes, or an already-parsed CRL. */\nfunction parseResponderCrlFromSource(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 parseCertificateRevocationListPemOrThrow(source);\n\t}\n\treturn parseCertificateRevocationListDerOrThrow(source);\n}\n\n/**\n * Applies the delegated-responder revocation policy (RFC 6960 §4.2.2.2.1).\n * See {@linkcode OcspResponderRevocationPolicy} for the policy semantics.\n */\nasync function checkDelegatedResponderRevocation(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: ValidateOcspResponseInput,\n): Promise<{ readonly ok: true } | ReturnType<typeof validateOcspResponseFailureResult>> {\n\tconst policy = input.responderRevocationPolicy ?? 'honor-nocheck';\n\tif (policy === 'skip') {\n\t\treturn { ok: true };\n\t}\n\tif (policy === 'honor-nocheck' && hasOcspNoCheckExtension(signer)) {\n\t\treturn { ok: true };\n\t}\n\tconst at = input.at ?? new Date();\n\tlet sawGood = false;\n\tfor (const source of input.responderRevocationCrls ?? []) {\n\t\tlet crl: ParsedCertificateRevocationList;\n\t\ttry {\n\t\t\tcrl = parseResponderCrlFromSource(source);\n\t\t} catch {\n\t\t\tcontinue; // Unusable evidence — try remaining CRLs\n\t\t}\n\t\tconst result = await checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: signer,\n\t\t\tissuerCertificate: issuer,\n\t\t\tcrl,\n\t\t\tat,\n\t\t});\n\t\tif (!result.ok) {\n\t\t\tcontinue; // CRL does not apply to the responder certificate\n\t\t}\n\t\tif (result.value.status === 'revoked') {\n\t\t\treturn validateOcspResponseFailureResult(\n\t\t\t\t'responder_revoked',\n\t\t\t\t'Delegated OCSP responder certificate is revoked',\n\t\t\t);\n\t\t}\n\t\tif (result.value.status === 'good') {\n\t\t\tsawGood = true;\n\t\t}\n\t}\n\tif (sawGood || policy === 'honor-nocheck') {\n\t\t// honor-nocheck tolerates missing evidence (soft) — only a positive\n\t\t// revoked verdict rejects when no usable evidence proves 'good'.\n\t\treturn { ok: true };\n\t}\n\treturn validateOcspResponseFailureResult(\n\t\t'responder_revocation_unknown',\n\t\t'Delegated OCSP responder revocation status could not be established',\n\t);\n}\n\n/** Accepts PEM, DER, or already-parsed OCSP response and returns a parsed response. */\nfunction normalizeOcspResponse(\n\tresponse: string | Uint8Array | ParsedOcspResponse,\n): ParsedOcspResponse {\n\tif (typeof response === 'string') {\n\t\treturn parseOcspResponsePemOrThrow(response);\n\t}\n\tif (response instanceof Uint8Array) {\n\t\treturn parseOcspResponseDerOrThrow(response);\n\t}\n\tif (hasReparseableOcspResponseShape(response)) {\n\t\treturn parseOcspResponseDerOrThrow(new Uint8Array(response.der));\n\t}\n\tthrow new Error('OCSP response input is malformed');\n}\n\n/** Accepts PEM, DER, or already-parsed OCSP request and returns a parsed request. */\nfunction normalizeOcspRequest(request: OcspRequestSource): ParsedOcspRequest {\n\tif (typeof request === 'string') {\n\t\treturn parseOcspRequestPemOrThrow(request);\n\t}\n\tif (request instanceof Uint8Array) {\n\t\treturn parseOcspRequestDerOrThrow(request);\n\t}\n\tif (hasReparseableOcspRequestShape(request)) {\n\t\treturn parseOcspRequestDerOrThrow(new Uint8Array(request.der));\n\t}\n\tthrow new Error('OCSP request input is malformed');\n}\n\nfunction parseSignedOcspResponseData(responseDataDer: Uint8Array): {\n\treadonly responderId: ParsedOcspResponderId;\n\treadonly producedAt: Date;\n\treadonly responses: readonly ParsedOcspSingleResponse[];\n\treadonly nonce?: string;\n} {\n\tconst responseDataChildren = readSequenceChildren(responseDataDer);\n\tif (responseDataChildren.length < 3 || responseDataChildren.length > 5) {\n\t\tthrow new Error('Malformed OCSP responseData');\n\t}\n\tlet index = 0;\n\tif (responseDataChildren[index]?.tag === 0xa0) {\n\t\tconst versionWrapper = requireElement(responseDataChildren[index], 'version');\n\t\tconst versionFields = childrenOf(responseDataDer, versionWrapper);\n\t\tconst versionElement = requireElement(versionFields[0], 'version');\n\t\tif (versionFields.length !== 1 || versionElement.tag !== 0x02) {\n\t\t\tthrow new Error('version must use INTEGER');\n\t\t}\n\t\tif (decodeNonNegativeIntegerNumber(versionElement.value, 'OCSP response version') !== 0) {\n\t\t\tthrow new Error('Unsupported OCSP response version');\n\t\t}\n\t\tindex += 1;\n\t}\n\tconst responderIdElement = requireElement(responseDataChildren[index], 'responderID');\n\tconst responderId = parseOcspResponderId(responseDataDer, responderIdElement);\n\tindex += 1;\n\tconst producedAtElement = requireElement(responseDataChildren[index], 'producedAt');\n\tconst responsesElement = requireElement(responseDataChildren[index + 1], 'responses');\n\tif (responsesElement.tag !== 0x30) {\n\t\tthrow new Error('responses must use SEQUENCE');\n\t}\n\tif (childrenOf(responseDataDer, responsesElement).length === 0) {\n\t\tthrow new Error('responses must not be empty');\n\t}\n\tconst responseExtensions = responseDataChildren[index + 2];\n\tif (responseExtensions !== undefined && responseExtensions.tag !== 0xa1) {\n\t\tthrow new Error('Malformed OCSP responseData');\n\t}\n\tif (responseDataChildren.length !== index + 2 + (responseExtensions === undefined ? 0 : 1)) {\n\t\tthrow new Error('Malformed OCSP responseData');\n\t}\n\tconst nonce =\n\t\tresponseExtensions === undefined\n\t\t\t? undefined\n\t\t\t: parseOcspNonceFromExtensions(responseDataDer, responseExtensions);\n\tconst parsedResponses = childrenOf(responseDataDer, responsesElement).map((singleResponse) =>\n\t\tparseSingleResponse(responseDataDer, singleResponse),\n\t);\n\tassertUniqueOcspResponseCertIds(parsedResponses);\n\treturn {\n\t\tresponderId,\n\t\tproducedAt: parseTime(producedAtElement),\n\t\tresponses: parsedResponses,\n\t\t...(nonce === undefined ? {} : { nonce }),\n\t};\n}\n\n/** Searches embedded certificates for one whose subject or key hash matches the responder ID. */\nasync function findMatchingOcspResponderCertificate(\n\tcertificates: readonly ParsedCertificate[] | undefined,\n\tresponderId: ParsedOcspResponderId | undefined,\n): Promise<ParsedCertificate | undefined> {\n\tif (certificates === undefined || responderId === undefined) {\n\t\treturn undefined;\n\t}\n\tfor (const certificate of certificates) {\n\t\tif (await matchesOcspResponderId(responderId, certificate)) {\n\t\t\treturn certificate;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Verifies that the signer certificate matches the response's responder ID (byName or byKeyHash). */\nasync function validateOcspResponderIdBinding(\n\tresponderId: ParsedOcspResponderId | undefined,\n\tsigner: ParsedCertificate,\n): Promise<Extract<ValidateOcspResponseResult, { readonly ok: false }> | { readonly ok: true }> {\n\tif (responderId === undefined) {\n\t\treturn { ok: true };\n\t}\n\tif (await matchesOcspResponderId(responderId, signer)) {\n\t\treturn { ok: true };\n\t}\n\treturn responderId.type === 'byName'\n\t\t? validateOcspResponseFailureResult(\n\t\t\t\t'responder_id_mismatch',\n\t\t\t\t'OCSP responder certificate subject does not match responderID byName',\n\t\t\t)\n\t\t: validateOcspResponseFailureResult(\n\t\t\t\t'responder_id_mismatch',\n\t\t\t\t'OCSP responder certificate public key does not match responderID byKeyHash',\n\t\t\t);\n}\n\n/** Returns `true` if the certificate matches the responder ID (subject name or key hash). */\nasync function matchesOcspResponderId(\n\tresponderId: ParsedOcspResponderId,\n\tcertificate: ParsedCertificate,\n): Promise<boolean> {\n\tif (responderId.type === 'byName') {\n\t\treturn compareOcspResponderNames(responderId.name, certificate.subject);\n\t}\n\tconst certificateKeyHashHex = toHex(\n\t\tawait digestBytes('SHA-1', extractSubjectPublicKeyBytes(certificate.subjectPublicKeyInfoDer)),\n\t);\n\treturn certificateKeyHashHex === responderId.keyHashHex;\n}\n\n/** Identity check — same serial, issuer, subject, and SPKI. */\nfunction isSameOcspCertificate(left: ParsedCertificate, right: ParsedCertificate): boolean {\n\treturn (\n\t\tleft.serialNumberHex === right.serialNumberHex &&\n\t\tcompareDistinguishedNames(left.issuer, right.issuer) &&\n\t\tcompareDistinguishedNames(left.subject, right.subject) &&\n\t\tleft.subjectPublicKeyInfoDer.length === right.subjectPublicKeyInfoDer.length &&\n\t\tleft.subjectPublicKeyInfoDer.every(\n\t\t\t(byte, index) => byte === right.subjectPublicKeyInfoDer[index],\n\t\t)\n\t);\n}\n\n/** Returns `true` if `signer` was directly issued by `issuer` (name + AKI match). */\nfunction isDirectlyIssuedByOcspIssuer(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): boolean {\n\tif (!compareDistinguishedNames(signer.issuer, issuer.subject)) {\n\t\treturn false;\n\t}\n\tif (\n\t\tsigner.authorityKeyIdentifier !== undefined &&\n\t\tissuer.subjectKeyIdentifier !== undefined &&\n\t\tsigner.authorityKeyIdentifier !== issuer.subjectKeyIdentifier\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/** Filters embedded certificates to produce an intermediate chain (excluding signer and issuer). */\nfunction buildOcspResponderIntermediates(\n\tcertificates: readonly ParsedCertificate[] | undefined,\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n): readonly Uint8Array[] {\n\tif (certificates === undefined) {\n\t\treturn [];\n\t}\n\tconst intermediates: Uint8Array[] = [];\n\tfor (const certificate of certificates) {\n\t\tif (isSameOcspCertificate(certificate, signer) || isSameOcspCertificate(certificate, issuer)) {\n\t\t\tcontinue;\n\t\t}\n\t\tintermediates.push(certificate.der);\n\t}\n\treturn intermediates;\n}\n\n/** DER-encodes a CertID SEQUENCE (hashAlgorithm, issuerNameHash, issuerKeyHash, serialNumber). */\nasync function encodeOcspCertId(\n\tcertificate: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\thashAlgorithm: OcspHashAlgorithm,\n): Promise<Uint8Array> {\n\tconst hashAlgorithmOid = hashAlgorithm === 'SHA-1' ? OIDS.sha1 : OIDS.sha256;\n\tconst parsed = await buildParsedOcspCertId(hashAlgorithmOid, issuer, certificate.serialNumberHex);\n\treturn sequence([\n\t\tsequence([objectIdentifier(hashAlgorithmOid), nullValue()]),\n\t\toctetString(hexToBytes(parsed.issuerNameHashHex)),\n\t\toctetString(hexToBytes(parsed.issuerKeyHashHex)),\n\t\tinteger(hexToBytes(parsed.serialNumberHex)),\n\t]);\n}\n\n/** Computes issuer name/key hashes for a CertID given the hash algorithm OID and issuer certificate. */\nasync function buildParsedOcspCertId(\n\thashAlgorithmOid: string,\n\tissuer: ParsedCertificate,\n\tserialNumberHex: string,\n): Promise<ParsedOcspCertId> {\n\tconst hashAlgorithm = ocspHashAlgorithmFromOid(hashAlgorithmOid);\n\treturn {\n\t\thashAlgorithmOid,\n\t\thashAlgorithmName: describeHashAlgorithm(hashAlgorithmOid),\n\t\tissuerNameHashHex: toHex(await digestBytes(hashAlgorithm, hexToBytes(issuer.subject.derHex))),\n\t\tissuerKeyHashHex: toHex(\n\t\t\tawait digestBytes(\n\t\t\t\thashAlgorithm,\n\t\t\t\textractSubjectPublicKeyBytes(issuer.subjectPublicKeyInfoDer),\n\t\t\t),\n\t\t),\n\t\tserialNumberHex,\n\t};\n}\n\n/** Hashes `bytes` with the given WebCrypto algorithm name. */\nasync function digestBytes(algorithm: OcspHashAlgorithm, bytes: Uint8Array): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.digest(algorithm, toArrayBuffer(bytes)));\n}\n\n/** DER-encodes a SingleResponse (certId, certStatus, thisUpdate, optional nextUpdate). */\nasync function encodeSingleResponse(\n\tcertificate: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CreateOcspSingleResponseInput,\n\thashAlgorithm: OcspHashAlgorithm,\n): Promise<Uint8Array> {\n\tconst certId = await encodeOcspCertId(certificate, issuer, hashAlgorithm);\n\tconst certStatus = encodeOcspCertStatus(input);\n\treturn sequence([\n\t\tcertId,\n\t\tcertStatus,\n\t\ttime(input.thisUpdate ?? new Date()),\n\t\t...(input.nextUpdate === undefined ? [] : [explicitContext(0, time(input.nextUpdate))]),\n\t]);\n}\n\n/** DER-encodes the CertStatus CHOICE (good [0], revoked [1], unknown [2]). */\nfunction encodeOcspCertStatus(input: CreateOcspSingleResponseInput): Uint8Array {\n\tswitch (input.certStatus) {\n\t\tcase 'good':\n\t\t\treturn tlv(0x80, new Uint8Array());\n\t\tcase 'unknown':\n\t\t\treturn tlv(0x82, new Uint8Array());\n\t\tcase 'revoked': {\n\t\t\tconst revokedFields: Uint8Array[] = [time(input.revokedAt ?? input.thisUpdate ?? new Date())];\n\t\t\tif (input.revocationReasonCode !== undefined) {\n\t\t\t\trevokedFields.push(\n\t\t\t\t\texplicitContext(0, tlv(0x0a, Uint8Array.of(input.revocationReasonCode))),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn tlv(0xa1, concatBytes(revokedFields));\n\t\t}\n\t}\n}\n\n/** Accepts PEM, DER, or already-parsed certificate and returns a parsed certificate. */\nfunction normalizeCertificate(source: OcspCertificateSource): ParsedCertificate {\n\tif (hasParsedCertificateShape(source)) {\n\t\treturn parseCertificateDerOrThrow(new Uint8Array(source.der));\n\t}\n\treturn parseCertificateFromSource(source);\n}\n\n/** Type guard: distinguishes a `ParsedCertificate` from raw `Uint8Array`. */\nfunction hasParsedCertificateShape(value: OcspCertificateSource): value is ParsedCertificate {\n\treturn typeof value !== 'string' && 'subjectPublicKeyInfoDer' in value;\n}\n\n/** Decodes a DER-encoded CertID SEQUENCE into a {@linkcode ParsedOcspCertId}. */\nfunction parseOcspCertId(der: Uint8Array): ParsedOcspCertId {\n\tconst root = readRootElement(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (root.tag !== 0x30) {\n\t\tthrow new Error('CertID must use SEQUENCE');\n\t}\n\tconst children = childrenOf(der, root);\n\tif (children.length !== 4) {\n\t\tthrow new Error(\n\t\t\t'CertID must contain hashAlgorithm, issuerNameHash, issuerKeyHash, and serialNumber',\n\t\t);\n\t}\n\tconst hashAlgorithm = requireElement(children[0], 'hashAlgorithm');\n\tif (hashAlgorithm.tag !== 0x30) {\n\t\tthrow new Error('hashAlgorithm must use SEQUENCE');\n\t}\n\tconst algorithmChildren = childrenOf(der, hashAlgorithm);\n\tif (algorithmChildren.length < 1 || algorithmChildren.length > 2) {\n\t\tthrow new Error('Malformed hashAlgorithm');\n\t}\n\tconst algorithmOid = requireElement(algorithmChildren[0], 'hashAlgorithm OID');\n\tconst hashAlgorithmOid = decodeObjectIdentifier(algorithmOid.value);\n\tif (requireElement(children[1], 'issuerNameHash').tag !== 0x04) {\n\t\tthrow new Error('issuerNameHash must use OCTET STRING');\n\t}\n\tif (requireElement(children[2], 'issuerKeyHash').tag !== 0x04) {\n\t\tthrow new Error('issuerKeyHash must use OCTET STRING');\n\t}\n\tconst serialNumber = requireElement(children[3], 'serialNumber');\n\tif (serialNumber.tag !== 0x02) {\n\t\tthrow new Error('serialNumber must use INTEGER');\n\t}\n\treturn {\n\t\thashAlgorithmOid,\n\t\thashAlgorithmName: describeHashAlgorithm(hashAlgorithmOid),\n\t\tissuerNameHashHex: toHex(requireElement(children[1], 'issuerNameHash').value),\n\t\tissuerKeyHashHex: toHex(requireElement(children[2], 'issuerKeyHash').value),\n\t\tserialNumberHex: toHex(serialNumber.value),\n\t};\n}\n\n/** Decodes a SingleResponse from its ASN.1 element within the ResponseData. */\nfunction parseSingleResponse(source: Uint8Array, element: DerElement): ParsedOcspSingleResponse {\n\tconst children = childrenOf(source, element);\n\tif (children.length < 3 || children.length > 5) {\n\t\tthrow new Error('Malformed OCSP SingleResponse');\n\t}\n\tconst certId = requireElement(children[0], 'certId');\n\tconst certStatus = requireElement(children[1], 'certStatus');\n\tconst thisUpdate = requireElement(children[2], 'thisUpdate');\n\tlet cursor = 3;\n\tconst nextUpdateElement = children[cursor]?.tag === 0xa0 ? children[cursor] : undefined;\n\tif (nextUpdateElement !== undefined) {\n\t\tvalidateOcspSingleResponseNextUpdate(source, nextUpdateElement);\n\t\tcursor += 1;\n\t}\n\tconst singleExtensions = children[cursor];\n\tif (singleExtensions !== undefined && singleExtensions.tag !== 0xa1) {\n\t\tthrow new Error('Malformed OCSP SingleResponse');\n\t}\n\tif (children.length !== cursor + (singleExtensions === undefined ? 0 : 1)) {\n\t\tthrow new Error('Malformed OCSP SingleResponse');\n\t}\n\tconst statusFields = parseOcspCertStatusFields(source, certStatus);\n\treturn {\n\t\tcertId: parseOcspCertId(source.slice(certId.start - certId.headerLength, certId.end)),\n\t\tcertStatus: statusFields.certStatus,\n\t\tthisUpdate: parseTime(thisUpdate),\n\t\t...parseOcspSingleResponseNextUpdate(source, nextUpdateElement),\n\t\t...(statusFields.revokedAt === undefined ? {} : { revokedAt: statusFields.revokedAt }),\n\t\t...(statusFields.revocationReasonCode === undefined\n\t\t\t? {}\n\t\t\t: { revocationReasonCode: statusFields.revocationReasonCode }),\n\t};\n}\n\nfunction parseOcspSingleResponseNextUpdate(\n\tsource: Uint8Array,\n\tnextUpdateElement: DerElement | undefined,\n): { readonly nextUpdate?: Date } {\n\treturn nextUpdateElement === undefined\n\t\t? {}\n\t\t: {\n\t\t\t\tnextUpdate: parseTime(\n\t\t\t\t\trequireElement(childrenOf(source, nextUpdateElement)[0], 'nextUpdate'),\n\t\t\t\t),\n\t\t\t};\n}\n\nfunction parseOcspCertStatusFields(\n\tsource: Uint8Array,\n\tcertStatus: DerElement,\n): ParsedOcspCertStatusFields {\n\tif (certStatus.tag === 0x80) {\n\t\tif (certStatus.value.length !== 0) {\n\t\t\tthrow new Error('OCSP good certStatus must be empty');\n\t\t}\n\t\treturn { certStatus: 'good' };\n\t}\n\tif (certStatus.tag === 0x82) {\n\t\tif (certStatus.value.length !== 0) {\n\t\t\tthrow new Error('OCSP unknown certStatus must be empty');\n\t\t}\n\t\treturn { certStatus: 'unknown' };\n\t}\n\tif (certStatus.tag !== 0xa1) {\n\t\tthrow new Error(`Unsupported OCSP certStatus tag: ${String(certStatus.tag)}`);\n\t}\n\tconst revokedInfo = childrenOf(source, certStatus);\n\tif (revokedInfo.length < 1 || revokedInfo.length > 2) {\n\t\tthrow new Error('Malformed OCSP revoked certStatus');\n\t}\n\treturn {\n\t\tcertStatus: 'revoked',\n\t\trevokedAt: parseTime(requireElement(revokedInfo[0], 'revocationTime')),\n\t\t...parseOcspRevocationReason(source, revokedInfo[1]),\n\t};\n}\n\nfunction parseOcspRevocationReason(\n\tsource: Uint8Array,\n\treason: DerElement | undefined,\n): { readonly revocationReasonCode?: number } {\n\tif (reason === undefined) {\n\t\treturn {};\n\t}\n\tif (reason.tag !== 0xa0) {\n\t\tthrow new Error('Malformed OCSP revoked certStatus');\n\t}\n\tconst reasonChildren = childrenOf(source, reason);\n\tconst enumerated = requireElement(reasonChildren[0], 'revocationReason');\n\tif (reasonChildren.length !== 1 || enumerated.tag !== 0x0a) {\n\t\tthrow new Error('revocationReason must use ENUMERATED');\n\t}\n\treturn {\n\t\trevocationReasonCode: decodeNonNegativeIntegerNumber(enumerated.value, 'OCSP revocationReason'),\n\t};\n}\n\n/** Decodes a ResponderID from its context-tagged ASN.1 element (byName [1] or byKeyHash [2]). */\nfunction parseOcspResponderId(source: Uint8Array, element: DerElement): ParsedOcspResponderId {\n\tswitch (element.tag) {\n\t\tcase 0x82:\n\t\t\tif (element.value.length === 0) {\n\t\t\t\tthrow new Error('ResponderID byKeyHash must not be empty');\n\t\t\t}\n\t\t\treturn { type: 'byKeyHash', keyHashHex: toHex(element.value) };\n\t\tcase 0xa1:\n\t\t\tif (childrenOf(source, element).length !== 1) {\n\t\t\t\tthrow new Error('ResponderID byName must wrap exactly one Name');\n\t\t\t}\n\t\t\treturn {\n\t\t\t\ttype: 'byName',\n\t\t\t\tname: parseResponderName(\n\t\t\t\t\tsource,\n\t\t\t\t\trequireElement(childrenOf(source, element)[0], 'ResponderID byName'),\n\t\t\t\t),\n\t\t\t};\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported OCSP responderID tag: ${String(element.tag)}`);\n\t}\n}\n\n/** Decodes a Name SEQUENCE from the ResponderID byName form. */\nfunction parseResponderName(source: Uint8Array, element: DerElement): ParsedName {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('ResponderID byName must use Name SEQUENCE');\n\t}\n\tconst rdns: ParsedRelativeDistinguishedName[] = [];\n\tconst attributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const setElement of childrenOf(source, element)) {\n\t\tconst rdn = parseResponderNameAttributeSet(source, setElement);\n\t\trdns.push(rdn);\n\t\tfor (const attribute of rdn.attributes) {\n\t\t\tattributes.push(attribute);\n\t\t\tif (attribute.key !== undefined && values[attribute.key] === undefined) {\n\t\t\t\tvalues[attribute.key] = attribute.value;\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tderHex: toHex(source.slice(element.start - element.headerLength, element.end)),\n\t\trdns,\n\t\tattributes,\n\t\tvalues,\n\t};\n}\n\n/** Decodes one RDN SET from a responder name. */\nfunction parseResponderNameAttributeSet(\n\tsource: Uint8Array,\n\tsetElement: DerElement,\n): ParsedRelativeDistinguishedName {\n\tconst attributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const attributeSequence of childrenOf(source, setElement)) {\n\t\tconst parts = childrenOf(source, attributeSequence);\n\t\tconst oid = decodeObjectIdentifier(requireElement(parts[0], 'name OID').value);\n\t\tconst valueElement = requireElement(parts[1], 'name value');\n\t\tconst key = responderNameKeyFromOid(oid);\n\t\tconst value = decodeString(valueElement.tag, valueElement.value);\n\t\tconst attribute: ParsedNameAttribute =\n\t\t\tkey === undefined\n\t\t\t\t? { oid, valueTag: valueElement.tag, value }\n\t\t\t\t: { oid, key, valueTag: valueElement.tag, value };\n\t\tattributes.push(attribute);\n\t\tif (key !== undefined && values[key] === undefined) {\n\t\t\tvalues[key] = value;\n\t\t}\n\t}\n\treturn {\n\t\tderHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),\n\t\tattributes,\n\t\tvalues,\n\t};\n}\n\n/** RDN-by-RDN responder name comparison with RFC 4518 string prep. */\nfunction compareOcspResponderNames(left: ParsedName, right: ParsedName): boolean {\n\tif (left.rdns.length !== right.rdns.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < left.rdns.length; index += 1) {\n\t\tconst leftRdn = left.rdns[index];\n\t\tconst rightRdn = right.rdns[index];\n\t\tif (leftRdn === undefined || rightRdn === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!compareOcspRelativeDistinguishedNames(leftRdn, rightRdn)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Set-equality comparison for RDN attribute sets (order-independent). */\nfunction compareOcspRelativeDistinguishedNames(\n\tleft: ParsedRelativeDistinguishedName,\n\tright: ParsedRelativeDistinguishedName,\n): boolean {\n\tif (left.attributes.length !== right.attributes.length) {\n\t\treturn false;\n\t}\n\tconst matched = Array.from({ length: right.attributes.length }, () => false);\n\tfor (const leftAttribute of left.attributes) {\n\t\tlet found = false;\n\t\tfor (let index = 0; index < right.attributes.length; index += 1) {\n\t\t\tconst rightAttribute = right.attributes[index];\n\t\t\tif (rightAttribute === undefined || matched[index]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!compareOcspNameAttributeValue(leftAttribute, rightAttribute)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmatched[index] = true;\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (!found) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Compares two name attributes with RFC 4518 string prep for directory-string types. */\nfunction compareOcspNameAttributeValue(\n\tleft: ParsedNameAttribute,\n\tright: ParsedNameAttribute,\n): boolean {\n\tif (left.oid !== right.oid) {\n\t\treturn false;\n\t}\n\tif (isOcspDirectoryStringTag(left.valueTag) && isOcspDirectoryStringTag(right.valueTag)) {\n\t\tconst preparedLeft = prepareOcspNameCompareString(left.value);\n\t\tconst preparedRight = prepareOcspNameCompareString(right.value);\n\t\tif (preparedLeft === undefined || preparedRight === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn preparedLeft === preparedRight;\n\t}\n\treturn left.valueTag === right.valueTag && left.value === right.value;\n}\n\n/** Returns `true` for UTF8String (0x0c) and PrintableString (0x13). */\nfunction isOcspDirectoryStringTag(tag: number): boolean {\n\treturn tag === 0x0c || tag === 0x13;\n}\n\n/** NFKC-normalises, lowercases, trims, and collapses whitespace for RFC 4518 name comparison. */\nfunction prepareOcspNameCompareString(value: string): string | undefined {\n\tconst normalized = value.normalize('NFKC');\n\tif (/[^\\P{Cc}\\t\\n\\r]/u.test(normalized)) {\n\t\treturn undefined;\n\t}\n\treturn normalized.toLowerCase().trim().replace(/\\s+/gu, ' ');\n}\n\n/** Maps an X.500 attribute type OID to its friendly key name for responder name parsing. */\nfunction responderNameKeyFromOid(oid: string): ParsedNameAttribute['key'] {\n\tswitch (oid) {\n\t\tcase OIDS.commonName:\n\t\t\treturn 'commonName';\n\t\tcase OIDS.surname:\n\t\t\treturn 'surname';\n\t\tcase OIDS.serialNumber:\n\t\t\treturn 'serialNumber';\n\t\tcase OIDS.countryName:\n\t\t\treturn 'country';\n\t\tcase OIDS.localityName:\n\t\t\treturn 'locality';\n\t\tcase OIDS.stateOrProvinceName:\n\t\t\treturn 'state';\n\t\tcase OIDS.streetAddress:\n\t\t\treturn 'street';\n\t\tcase OIDS.organizationName:\n\t\t\treturn 'organization';\n\t\tcase OIDS.organizationalUnitName:\n\t\t\treturn 'organizationalUnit';\n\t\tcase OIDS.title:\n\t\t\treturn 'title';\n\t\tcase OIDS.givenName:\n\t\t\treturn 'givenName';\n\t\tcase OIDS.emailAddress:\n\t\t\treturn 'emailAddress';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/** Extracts the nonce value (as hex) from an OCSP extensions wrapper, if present. */\nfunction parseOcspNonceFromExtensions(source: Uint8Array, element: DerElement): string | undefined {\n\tconst extensionsChildren = childrenOf(source, element);\n\tconst extensionsSequence = requireElement(extensionsChildren[0], 'extensions');\n\tif (extensionsChildren.length !== 1 || extensionsSequence.tag !== 0x30) {\n\t\tthrow new Error('Malformed OCSP extensions');\n\t}\n\tconst seenOids = new Set<string>();\n\tlet nonce: string | undefined;\n\tfor (const extension of childrenOf(source, extensionsSequence)) {\n\t\tconst parts = childrenOf(source, extension);\n\t\tif (parts.length < 2 || parts.length > 3) {\n\t\t\tthrow new Error('Malformed OCSP extension');\n\t\t}\n\t\tif (parts.length === 3 && parts[1]?.tag !== 0x01) {\n\t\t\tthrow new Error('Malformed OCSP extension');\n\t\t}\n\t\tconst oid = decodeObjectIdentifier(requireElement(parts[0], 'extension OID').value);\n\t\tif (seenOids.has(oid)) {\n\t\t\tthrow new Error(`Duplicate OCSP extension OID: ${oid}`);\n\t\t}\n\t\tseenOids.add(oid);\n\t\tconst extnValue = requireElement(parts[parts.length - 1], 'extnValue');\n\t\tif (extnValue.tag !== 0x04) {\n\t\t\tthrow new Error('OCSP extension value must use OCTET STRING');\n\t\t}\n\t\tif (oid !== OIDS.ocspNonce) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst nonceElement = readRootElement(extnValue.value, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (nonceElement.tag !== 0x04) {\n\t\t\tthrow new Error('OCSP nonce extension value must use OCTET STRING');\n\t\t}\n\t\tnonce = toHex(nonceElement.value);\n\t}\n\treturn nonce;\n}\n\n/** Decodes the optional `certs [0]` field from a BasicOCSPResponse. */\nfunction parseEmbeddedCertificates(\n\tsource: Uint8Array,\n\telement: DerElement,\n): readonly ParsedCertificate[] {\n\tconst certificates: ParsedCertificate[] = [];\n\tlet offset = element.start;\n\twhile (offset < element.end) {\n\t\tconst child = readElement(source, offset);\n\t\tcertificates.push(parseCertificateDerOrThrow(source.slice(offset, child.end)));\n\t\toffset = child.end;\n\t}\n\treturn certificates;\n}\n\n/** Extracts the raw public key bytes (without BIT STRING padding byte) from SPKI DER. */\nfunction extractSubjectPublicKeyBytes(spkiDer: Uint8Array): Uint8Array {\n\tconst top = childrenOf(spkiDer, readElement(spkiDer));\n\tconst bitStringElement = requireElement(top[1], 'subjectPublicKey BIT STRING');\n\tif (bitStringElement.tag !== 0x03) {\n\t\tthrow new Error('SPKI missing subjectPublicKey BIT STRING');\n\t}\n\treturn bitStringElement.value.slice(1);\n}\n\n/** Maps an integer response-status code to its {@linkcode OcspResponseStatus} string. */\nfunction ocspResponseStatusFromCode(code: number | undefined): OcspResponseStatus {\n\tswitch (code) {\n\t\tcase 0:\n\t\t\treturn 'successful';\n\t\tcase 1:\n\t\t\treturn 'malformedRequest';\n\t\tcase 2:\n\t\t\treturn 'internalError';\n\t\tcase 3:\n\t\t\treturn 'tryLater';\n\t\tcase 5:\n\t\t\treturn 'sigRequired';\n\t\tcase 6:\n\t\t\treturn 'unauthorized';\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported OCSP responseStatus value: ${String(code)}`);\n\t}\n}\n\nfunction hasReparseableOcspRequestShape(\n\trequest: ParsedOcspRequest,\n): request is ParsedOcspRequest & { readonly der: Uint8Array } {\n\treturn 'der' in request && request.der instanceof Uint8Array;\n}\n\nfunction hasReparseableOcspResponseShape(\n\tresponse: ParsedOcspResponse,\n): response is ParsedOcspResponse & { readonly der: Uint8Array } {\n\treturn 'der' in response && response.der instanceof Uint8Array;\n}\n\nfunction assertUniqueOcspResponseCertIds(responses: readonly ParsedOcspSingleResponse[]): void {\n\tconst seen = new Set<string>();\n\tfor (const response of responses) {\n\t\tconst key = serializeCertId(response.certId);\n\t\tif (seen.has(key)) {\n\t\t\tthrow new Error('Duplicate OCSP response CertID');\n\t\t}\n\t\tseen.add(key);\n\t}\n}\n\nfunction hasDuplicateOcspResponseCertificateSerial(\n\tresponses: readonly ParsedOcspSingleResponse[],\n): boolean {\n\tconst seen = new Set<string>();\n\tfor (const response of responses) {\n\t\tconst serial = normalizeHex(response.certId.serialNumberHex);\n\t\tif (seen.has(serial)) {\n\t\t\treturn true;\n\t\t}\n\t\tseen.add(serial);\n\t}\n\treturn false;\n}\n\nfunction validateOcspRequestorName(source: Uint8Array, element: DerElement): void {\n\tconst children = childrenOf(source, element);\n\tconst requestorName = requireElement(children[0], 'requestorName');\n\tif (children.length !== 1 || (requestorName.tag & 0xc0) !== 0x80) {\n\t\tthrow new Error('requestorName must wrap exactly one GeneralName');\n\t}\n}\n\nfunction validateOcspOptionalSignature(source: Uint8Array, element: DerElement): void {\n\tconst wrapperChildren = childrenOf(source, element);\n\tconst signatureSequence = requireElement(wrapperChildren[0], 'optionalSignature');\n\tif (wrapperChildren.length !== 1 || signatureSequence.tag !== 0x30) {\n\t\tthrow new Error('optionalSignature must wrap exactly one Signature');\n\t}\n\tconst signatureChildren = childrenOf(source, signatureSequence);\n\tif (\n\t\tsignatureChildren.length < 2 ||\n\t\tsignatureChildren.length > 3 ||\n\t\tsignatureChildren[0]?.tag !== 0x30 ||\n\t\t(signatureChildren[2] !== undefined && signatureChildren[2]?.tag !== 0xa0)\n\t) {\n\t\tthrow new Error('Malformed optionalSignature');\n\t}\n\tconst signatureAlgorithm = requireElement(signatureChildren[0], 'signatureAlgorithm');\n\tconst signatureValue = requireElement(signatureChildren[1], 'signature');\n\tconst certificates = signatureChildren[2];\n\tvalidateAlgorithmIdentifierShape(source, signatureAlgorithm, 'optionalSignature algorithm');\n\textractBitStringValue(signatureValue);\n\tif (certificates !== undefined) {\n\t\tconst certificateChildren = childrenOf(source, certificates);\n\t\tif (certificateChildren.length !== 1 || certificateChildren[0]?.tag !== 0x30) {\n\t\t\tthrow new Error('optionalSignature certs must use SEQUENCE OF Certificate');\n\t\t}\n\t}\n}\n\nfunction validateOcspSingleResponseNextUpdate(source: Uint8Array, element: DerElement): void {\n\tconst children = childrenOf(source, element);\n\tconst nextUpdate = requireElement(children[0], 'nextUpdate');\n\tif (children.length !== 1 || (nextUpdate.tag !== 0x17 && nextUpdate.tag !== 0x18)) {\n\t\tthrow new Error('nextUpdate must wrap exactly one time value');\n\t}\n}\n\nfunction validateAlgorithmIdentifierShape(\n\tsource: Uint8Array,\n\telement: DerElement,\n\tlabel: string,\n): void {\n\tconst children = childrenOf(source, element);\n\tif (\n\t\telement.tag !== 0x30 ||\n\t\tchildren.length < 1 ||\n\t\tchildren.length > 2 ||\n\t\tchildren[0]?.tag !== 0x06\n\t) {\n\t\tthrow new Error(`${label} must use AlgorithmIdentifier SEQUENCE`);\n\t}\n\tdecodeObjectIdentifier(requireElement(children[0], `${label} OID`).value);\n}\n\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n/** Maps a hash algorithm OID to the WebCrypto algorithm name. Throws on unsupported OIDs. */\nfunction ocspHashAlgorithmFromOid(oid: string): OcspHashAlgorithm {\n\tswitch (oid) {\n\t\tcase OIDS.sha1:\n\t\t\treturn 'SHA-1';\n\t\tcase OIDS.sha256:\n\t\t\treturn 'SHA-256';\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported OCSP hash algorithm OID: ${oid}`);\n\t}\n}\n\n/** Produces a colon-delimited canonical string for CertID set comparison. */\nfunction serializeCertId(certId: ParsedOcspCertId): string {\n\treturn [\n\t\tcertId.hashAlgorithmOid,\n\t\tcertId.issuerNameHashHex,\n\t\tcertId.issuerKeyHashHex,\n\t\tcertId.serialNumberHex,\n\t].join(':');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiaA,eAAsB,kBACrB,GAC+B;CAC/B,IAAM,IAAgB,EAAM,iBAAiB,SACvC,IAA+B,CAAC;CACtC,KAAK,IAAM,KAAW,EAAM,UAAU;EACrC,IAAM,IAAc,qBAAqB,EAAQ,WAAW,GACtD,IAAS,qBAAqB,EAAQ,iBAAiB;EAC7D,EAAe,KAAK,EAAS,CAAC,MAAM,iBAAiB,GAAa,GAAQ,CAAa,CAAC,CAAC,CAAC;CAC3F;CACA,IAAM,IAAiC,CAAC,EAAS,CAAc,CAAC;CAChE,AAAI,EAAM,UAAU,KAAA,KACnB,EAAiB,KAChB,EACC,GACA,EAAS,CACR,EAAS,CAAC,EAAiB,EAAK,SAAS,GAAG,EAAY,EAAY,EAAM,KAAK,CAAC,CAAC,CAAC,CACnF,CAAC,CACF,CACD;CAED,IAAM,IAAM,EAAS,CAAC,EAAS,CAAgB,CAAC,CAAC;CACjD,OAAO;EACN;EACA,KAAK,EAAU,gBAAgB,CAAG;EAClC,QAAQ,EAAa,CAAG;CACzB;AACD;;AAiBA,SAAgB,2BAA2B,GAAoC;CAC9E,IAAM,IAAM,EAAqB,GAAK,EAAE,UAAA,GAAgC,CAAC;CACzE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,WAAW,KAAK,EAAoB,EAAE,EAAE,QAAQ,IACvE,MAAU,MAAM,0DAA0D;CAE5E;AACD;AAEA,SAAS,qCAAqC,GAAoB,GAA2B;CAC5F,IAAM,IAAW,EAAW,GAAQ,CAAO,GACrC,IAAa,EAAe,EAAS,IAAI,YAAY;CAC3D,IAAI,EAAS,WAAW,KAAM,EAAW,QAAQ,MAAQ,EAAW,QAAQ,IAC3E,MAAU,MAAM,6CAA6C;AAE/D;AAEA,SAAS,iCACR,GACA,GACA,GACO;CACP,IAAM,IAAW,EAAW,GAAQ,CAAO;CAC3C,IACC,EAAQ,QAAQ,MAChB,EAAS,SAAS,KAClB,EAAS,SAAS,KAClB,EAAS,EAAE,EAAE,QAAQ,GAErB,MAAU,MAAM,GAAG,EAAM,uCAAuC;CAEjE,EAAuB,EAAe,EAAS,IAAI,GAAG,EAAM,KAAK,CAAC,CAAC,KAAK;AACzE;AAEA,SAAS,aAAa,GAAuB;CAC5C,OAAO,EAAM,YAAY;AAC1B;;AAGA,SAAS,yBAAyB,GAAgC;CACjE,QAAQ,GAAR;EACC,KAAK,EAAK,MACT,OAAO;EACR,KAAK,EAAK,QACT,OAAO;EACR,SACC,MAAU,MAAM,wCAAwC,GAAK;CAC/D;AACD;;AAGA,SAAS,gBAAgB,GAAkC;CAC1D,OAAO;EACN,EAAO;EACP,EAAO;EACP,EAAO;EACP,EAAO;CACR,CAAC,CAAC,KAAK,GAAG;AACX"}
@@ -32,6 +32,9 @@ interface CertificateFingerprint {
32
32
  * a well-formed certificate. Malformed input throws, matching the other DER/PEM
33
33
  * boundaries in the library.
34
34
  *
35
+ * **Asynchronous:** hashing uses WebCrypto's `crypto.subtle.digest`. Await the
36
+ * returned promise before reading `bytes`, `hex`, or `colonHex`.
37
+ *
35
38
  * @example
36
39
  * ```ts
37
40
  * const fingerprint = await certificateFingerprint(pemString);
@@ -20,6 +20,9 @@ import { parseCertificateFromSource as r } from "./parse.js";
20
20
  * a well-formed certificate. Malformed input throws, matching the other DER/PEM
21
21
  * boundaries in the library.
22
22
  *
23
+ * **Asynchronous:** hashing uses WebCrypto's `crypto.subtle.digest`. Await the
24
+ * returned promise before reading `bytes`, `hex`, or `colonHex`.
25
+ *
23
26
  * @example
24
27
  * ```ts
25
28
  * const fingerprint = await certificateFingerprint(pemString);
@@ -1 +1 @@
1
- {"version":3,"file":"fingerprint.js","names":[],"sources":["../../src/x509/fingerprint.ts"],"sourcesContent":["/**\n * Certificate fingerprints: a cryptographic hash over the DER encoding.\n *\n * This is the identifier that `openssl x509 -fingerprint` and every TLS UI show.\n * The helper accepts the same PEM / DER / parsed-certificate source union as\n * the verification APIs and returns the digest in the forms callers actually\n * paste around: raw bytes, lowercase hex, and uppercase colon-separated hex.\n *\n * @module\n */\n\nimport { toArrayBuffer, toHex } from '#micro509/internal/asn1/asn1';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateFromSource } from '#micro509/x509/parse';\n\n/**\n * A PEM string, raw DER bytes, or an already-parsed certificate.\n *\n * Mirrors the source union accepted by the verification, revocation, and\n * PKCS APIs so a fingerprint can be taken from whatever a caller already holds.\n */\nexport type CertificateFingerprintSource = string | Uint8Array | ParsedCertificate;\n\n/**\n * Digest algorithms supported by {@linkcode certificateFingerprint}.\n *\n * SHA-1 is intentionally included: legacy ecosystems (PGP-adjacent tooling,\n * older certificate pinning) still identify certificates by their SHA-1\n * fingerprint. Prefer SHA-256 for anything new.\n */\nexport type CertificateFingerprintAlgorithm = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/** The three rendered forms of a certificate fingerprint. */\nexport interface CertificateFingerprint {\n\t/** Raw digest bytes. */\n\treadonly bytes: Uint8Array;\n\t/** Lowercase hex, no separators (e.g. `\"a1b2c3…\"`). */\n\treadonly hex: string;\n\t/** Uppercase hex, colon-separated (e.g. `\"A1:B2:C3:…\"`, `openssl x509 -fingerprint` style). */\n\treadonly colonHex: string;\n}\n\n/**\n * Compute a certificate fingerprint — a hash over the DER encoding.\n *\n * The certificate is parsed (validating the input and, for PEM, decoding it to\n * DER) before hashing, so the digest is always taken over the canonical DER of\n * a well-formed certificate. Malformed input throws, matching the other DER/PEM\n * boundaries in the library.\n *\n * @example\n * ```ts\n * const fingerprint = await certificateFingerprint(pemString);\n * console.log(fingerprint.colonHex); // \"AB:CD:…\" — matches `openssl x509 -fingerprint -sha256`\n * ```\n *\n * @example\n * ```ts\n * // Reuse an already-parsed certificate and request SHA-1.\n * const parsed = parseCertificatePemOrThrow(pemString);\n * const legacy = await certificateFingerprint(parsed, 'SHA-1');\n * console.log(legacy.hex);\n * ```\n *\n * @param certificate PEM string, DER bytes, or a {@linkcode ParsedCertificate}.\n * @param algorithm Digest algorithm to use. Defaults to `'SHA-256'`.\n */\nexport async function certificateFingerprint(\n\tcertificate: CertificateFingerprintSource,\n\talgorithm: CertificateFingerprintAlgorithm = 'SHA-256',\n): Promise<CertificateFingerprint> {\n\tconst { der } = parseCertificateFromSource(certificate);\n\tconst digest = await getCrypto().subtle.digest(algorithm, toArrayBuffer(der));\n\tconst bytes = new Uint8Array(digest);\n\treturn {\n\t\tbytes,\n\t\thex: toHex(bytes),\n\t\tcolonHex: toColonHex(bytes),\n\t};\n}\n\n/** Renders bytes as uppercase, colon-separated hex (openssl fingerprint style). */\nfunction toColonHex(bytes: Uint8Array): string {\n\treturn Array.from(bytes, (value) => value.toString(16).padStart(2, '0').toUpperCase()).join(':');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,eAAsB,uBACrB,GACA,IAA6C,WACX;CAClC,IAAM,EAAE,WAAQ,EAA2B,CAAW,GAChD,IAAS,MAAM,EAAU,CAAC,CAAC,OAAO,OAAO,GAAW,EAAc,CAAG,CAAC,GACtE,IAAQ,IAAI,WAAW,CAAM;CACnC,OAAO;EACN;EACA,KAAK,EAAM,CAAK;EAChB,UAAU,WAAW,CAAK;CAC3B;AACD;;AAGA,SAAS,WAAW,GAA2B;CAC9C,OAAO,MAAM,KAAK,IAAQ,MAAU,EAAM,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,GAAG;AAChG"}
1
+ {"version":3,"file":"fingerprint.js","names":[],"sources":["../../src/x509/fingerprint.ts"],"sourcesContent":["/**\n * Certificate fingerprints: a cryptographic hash over the DER encoding.\n *\n * This is the identifier that `openssl x509 -fingerprint` and every TLS UI show.\n * The helper accepts the same PEM / DER / parsed-certificate source union as\n * the verification APIs and returns the digest in the forms callers actually\n * paste around: raw bytes, lowercase hex, and uppercase colon-separated hex.\n *\n * @module\n */\n\nimport { toArrayBuffer, toHex } from '#micro509/internal/asn1/asn1';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateFromSource } from '#micro509/x509/parse';\n\n/**\n * A PEM string, raw DER bytes, or an already-parsed certificate.\n *\n * Mirrors the source union accepted by the verification, revocation, and\n * PKCS APIs so a fingerprint can be taken from whatever a caller already holds.\n */\nexport type CertificateFingerprintSource = string | Uint8Array | ParsedCertificate;\n\n/**\n * Digest algorithms supported by {@linkcode certificateFingerprint}.\n *\n * SHA-1 is intentionally included: legacy ecosystems (PGP-adjacent tooling,\n * older certificate pinning) still identify certificates by their SHA-1\n * fingerprint. Prefer SHA-256 for anything new.\n */\nexport type CertificateFingerprintAlgorithm = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/** The three rendered forms of a certificate fingerprint. */\nexport interface CertificateFingerprint {\n\t/** Raw digest bytes. */\n\treadonly bytes: Uint8Array;\n\t/** Lowercase hex, no separators (e.g. `\"a1b2c3…\"`). */\n\treadonly hex: string;\n\t/** Uppercase hex, colon-separated (e.g. `\"A1:B2:C3:…\"`, `openssl x509 -fingerprint` style). */\n\treadonly colonHex: string;\n}\n\n/**\n * Compute a certificate fingerprint — a hash over the DER encoding.\n *\n * The certificate is parsed (validating the input and, for PEM, decoding it to\n * DER) before hashing, so the digest is always taken over the canonical DER of\n * a well-formed certificate. Malformed input throws, matching the other DER/PEM\n * boundaries in the library.\n *\n * **Asynchronous:** hashing uses WebCrypto's `crypto.subtle.digest`. Await the\n * returned promise before reading `bytes`, `hex`, or `colonHex`.\n *\n * @example\n * ```ts\n * const fingerprint = await certificateFingerprint(pemString);\n * console.log(fingerprint.colonHex); // \"AB:CD:…\" — matches `openssl x509 -fingerprint -sha256`\n * ```\n *\n * @example\n * ```ts\n * // Reuse an already-parsed certificate and request SHA-1.\n * const parsed = parseCertificatePemOrThrow(pemString);\n * const legacy = await certificateFingerprint(parsed, 'SHA-1');\n * console.log(legacy.hex);\n * ```\n *\n * @param certificate PEM string, DER bytes, or a {@linkcode ParsedCertificate}.\n * @param algorithm Digest algorithm to use. Defaults to `'SHA-256'`.\n */\nexport async function certificateFingerprint(\n\tcertificate: CertificateFingerprintSource,\n\talgorithm: CertificateFingerprintAlgorithm = 'SHA-256',\n): Promise<CertificateFingerprint> {\n\tconst { der } = parseCertificateFromSource(certificate);\n\tconst digest = await getCrypto().subtle.digest(algorithm, toArrayBuffer(der));\n\tconst bytes = new Uint8Array(digest);\n\treturn {\n\t\tbytes,\n\t\thex: toHex(bytes),\n\t\tcolonHex: toColonHex(bytes),\n\t};\n}\n\n/** Renders bytes as uppercase, colon-separated hex (openssl fingerprint style). */\nfunction toColonHex(bytes: Uint8Array): string {\n\treturn Array.from(bytes, (value) => value.toString(16).padStart(2, '0').toUpperCase()).join(':');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,eAAsB,uBACrB,GACA,IAA6C,WACX;CAClC,IAAM,EAAE,WAAQ,EAA2B,CAAW,GAChD,IAAS,MAAM,EAAU,CAAC,CAAC,OAAO,OAAO,GAAW,EAAc,CAAG,CAAC,GACtE,IAAQ,IAAI,WAAW,CAAM;CACnC,OAAO;EACN;EACA,KAAK,EAAM,CAAK;EAChB,UAAU,WAAW,CAAK;CAC3B;AACD;;AAGA,SAAS,WAAW,GAA2B;CAC9C,OAAO,MAAM,KAAK,IAAQ,MAAU,EAAM,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,GAAG;AAChG"}