micro509 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/CHANGELOG.md +88 -1
  2. package/dist/crypto/crypto.d.ts +11 -2
  3. package/dist/crypto/crypto.js +30 -17
  4. package/dist/crypto/crypto.js.map +1 -1
  5. package/dist/crypto.d.ts +2 -2
  6. package/dist/der/der.js.map +1 -1
  7. package/dist/index.d.ts +6 -5
  8. package/dist/internal/asn1/asn1.js +10 -2
  9. package/dist/internal/asn1/asn1.js.map +1 -1
  10. package/dist/internal/asn1/ber.js.map +1 -1
  11. package/dist/internal/asn1/decode-refusal.js.map +1 -1
  12. package/dist/internal/asn1/der.js.map +1 -1
  13. package/dist/internal/asn1/oids.js.map +1 -1
  14. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  15. package/dist/internal/crypto/ecdsa.js.map +1 -1
  16. package/dist/internal/crypto/hash.js.map +1 -1
  17. package/dist/internal/crypto/pbes2.js.map +1 -1
  18. package/dist/internal/crypto/prime-ec.js.map +1 -1
  19. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  20. package/dist/internal/crypto/sig-verify.d.ts +40 -0
  21. package/dist/internal/crypto/sig-verify.js +152 -65
  22. package/dist/internal/crypto/sig-verify.js.map +1 -1
  23. package/dist/internal/crypto/signing.js.map +1 -1
  24. package/dist/internal/jose/base64url.js.map +1 -1
  25. package/dist/internal/jose/json-data.js.map +1 -1
  26. package/dist/internal/jose/strict-json.js.map +1 -1
  27. package/dist/internal/shared/base64.js.map +1 -1
  28. package/dist/internal/shared/dn.js.map +1 -1
  29. package/dist/internal/shared/idna.js.map +1 -1
  30. package/dist/internal/shared/ip.js.map +1 -1
  31. package/dist/internal/shared/mailbox.js.map +1 -1
  32. package/dist/internal/shared/punycode.js.map +1 -1
  33. package/dist/internal/shared/uri-host.js.map +1 -1
  34. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  35. package/dist/internal/verify/policy-engine.js.map +1 -1
  36. package/dist/internal/verify/spki-distrust.js.map +1 -1
  37. package/dist/internal/verify/verify-path.js +222 -116
  38. package/dist/internal/verify/verify-path.js.map +1 -1
  39. package/dist/internal/x509/directory-name.js.map +1 -1
  40. package/dist/internal/x509/extension-bits.js.map +1 -1
  41. package/dist/internal/x509/extension-errors.js.map +1 -1
  42. package/dist/internal/x509/extension-registry.js.map +1 -1
  43. package/dist/internal/x509/general-name-profile.js.map +1 -1
  44. package/dist/internal/x509/general-name.js.map +1 -1
  45. package/dist/internal/x509/name-fields.js.map +1 -1
  46. package/dist/internal/x509/or-address.js.map +1 -1
  47. package/dist/jose/base64url.js.map +1 -1
  48. package/dist/jose/errors.js.map +1 -1
  49. package/dist/jose/jwe.js.map +1 -1
  50. package/dist/jose/jwks.js.map +1 -1
  51. package/dist/jose/jws.js.map +1 -1
  52. package/dist/jose/jwt.js.map +1 -1
  53. package/dist/jose/remote-jwks.js.map +1 -1
  54. package/dist/kdf/argon2-arithmetic.js.map +1 -1
  55. package/dist/kdf/argon2-core.js.map +1 -1
  56. package/dist/kdf/argon2-memory.js.map +1 -1
  57. package/dist/kdf/argon2-portable.js.map +1 -1
  58. package/dist/kdf/argon2.js.map +1 -1
  59. package/dist/keys/keys.js.map +1 -1
  60. package/dist/pem/pem.js.map +1 -1
  61. package/dist/pkcs/pfx.js.map +1 -1
  62. package/dist/pkcs/pkcs12-mac.js +1 -1
  63. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  64. package/dist/pkcs/pkcs7.d.ts +10 -0
  65. package/dist/pkcs/pkcs7.js +106 -88
  66. package/dist/pkcs/pkcs7.js.map +1 -1
  67. package/dist/result/result.js.map +1 -1
  68. package/dist/revocation/chain.d.ts +67 -13
  69. package/dist/revocation/chain.js +429 -301
  70. package/dist/revocation/chain.js.map +1 -1
  71. package/dist/revocation/crl.d.ts +65 -11
  72. package/dist/revocation/crl.js +492 -202
  73. package/dist/revocation/crl.js.map +1 -1
  74. package/dist/revocation/ocsp.d.ts +79 -24
  75. package/dist/revocation/ocsp.js +417 -231
  76. package/dist/revocation/ocsp.js.map +1 -1
  77. package/dist/revocation/revocation.d.ts +68 -13
  78. package/dist/revocation/revocation.js +194 -73
  79. package/dist/revocation/revocation.js.map +1 -1
  80. package/dist/revocation.d.ts +4 -4
  81. package/dist/ssh/ssh.js.map +1 -1
  82. package/dist/ssh/wire.js.map +1 -1
  83. package/dist/verify/identity.d.ts +2 -2
  84. package/dist/verify/identity.js +2 -2
  85. package/dist/verify/identity.js.map +1 -1
  86. package/dist/verify/verify.d.ts +84 -32
  87. package/dist/verify/verify.js +221 -171
  88. package/dist/verify/verify.js.map +1 -1
  89. package/dist/verify.d.ts +3 -2
  90. package/dist/x509/certificate.js.map +1 -1
  91. package/dist/x509/csr.js.map +1 -1
  92. package/dist/x509/extensions.js.map +1 -1
  93. package/dist/x509/fingerprint.js.map +1 -1
  94. package/dist/x509/name-text.js.map +1 -1
  95. package/dist/x509/name.js.map +1 -1
  96. package/dist/x509/parse.d.ts +6 -2
  97. package/dist/x509/parse.js +121 -121
  98. package/dist/x509/parse.js.map +1 -1
  99. package/package.json +11 -11
@@ -1 +1 @@
1
- {"version":3,"file":"ocsp.js","names":["_exhaustive","code","message","date","field","hashAlgorithm","input","requestEntries","request","certificate","issuer","sequence","tbsRequestFields","explicitContext","objectIdentifier","OIDS","octetString","der","pemEncode","base64Encode","top","readSequenceChildren","tbsRequest","requireElement","optionalSignature","tbsChildren","childrenOf","cursor","requestList","requests","requestChildren","certId","extensions","nonce","versionWrapper","versionFields","versionElement","decodeNonNegativeIntegerNumber","requestorName","pemDecodeOrThrow","pem","successResult","error","rethrowIfInvariant","decodeFailureResult","DECODE_REFUSAL_CODES","statusElement","responseStatus","responseBytes","responseBytesWrapper","bytesSequence","responseBytesChildren","responseType","response","responseTypeOid","decodeObjectIdentifier","basicResponse","basicChildren","responseData","signatureAlgorithm","signatureValue","certificatesElement","signatureAlgorithmChildren","signatureAlgorithmOid","signatureAlgorithmParameters","signatureAlgorithmParametersDer","responseDataDer","signedResponseData","describeSignatureAlgorithm","extractBitStringValue","signerCertificate","getSignatureAlgorithm","getVerifySignatureConfigResult","producedAt","responses","responderKeyHash","responseDataFields","generalizedTime","signature","signBytes","includedCertificates","basicResponseFields","encodeAlgorithmIdentifier","bitString","tlv","parsed","refusal","decodeRefusalOf","signer","verifiedResult","verifySignedDataDetailed","parsedResponse","normalized","responderAuthorization","trustedResponders","at","skew","freshness","requestMatch","resolvedResponder","responderBinding","isLocallyTrustedResponder","trusted","allowChainedResponderCertificate","verifyCertificateChain","responderRevocation","context","responseFreshness","expected","profile","requestSource","entry","requestIds","requestId","responseIds","failureResult","extension","source","parseCertificateRevocationListPemOrThrow","parseCertificateRevocationListDerOrThrow","policy","crlCheck","coveredReasons","sawUnrecognizedReason","crl","result","checkCertificateRevocationAgainstCrl","reason","coversAllDistributionPointReasons","responseDataChildren","index","responderId","producedAtElement","responsesElement","responseExtensions","parsedResponses","singleResponse","parseTime","certificates","toHex","left","right","compareDistinguishedNames","byte","intermediates","hashAlgorithmOid","nullValue","hexToBytes","integer","describeHashAlgorithm","getCrypto","algorithm","toArrayBuffer","bytes","certStatus","revokedFields","enumeratedFromNumber","concatBytes","parseCertificateDerOrThrow","parseCertificateFromSource","value","root","readRootElement","children","algorithmChildren","algorithmOid","serialNumber","element","thisUpdate","nextUpdateElement","singleExtensions","revokedInfo","reasonChildren","enumerated","decodeNonNegativeIntegerBigInt","inner","keyHash","rdns","attributes","values","setElement","rdn","attribute","attributeSequence","parts","oid","valueElement","key","decodeString","leftRdn","rightRdn","matched","leftAttribute","found","rightAttribute","preparedLeft","preparedRight","tag","extensionsChildren","extensionsSequence","seenOids","extnValue","nonceElement","sequenceElement","offset","child","readElement","spkiDer","bitStringElement","seen","serial","wrapperChildren","signatureSequence","signatureChildren","certificateChildren","nextUpdate","label"],"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\tdecodeNonNegativeIntegerBigInt,\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 {\n\tDECODE_REFUSAL_CODES,\n\tdecodeFailureResult,\n\tdecodeRefusalOf,\n} from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\tbitString,\n\tconcatBytes,\n\tDEFAULT_MAX_DER_DEPTH,\n\tenumeratedFromNumber,\n\texplicitContext,\n\tgeneralizedTime,\n\tinteger,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\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 {\n\tgetVerifySignatureConfigResult,\n\tverifySignedDataDetailed,\n} 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 {\n\tDecodeFailureCode,\n\tDecodeRefusalCode,\n\tErrorResult,\n\tMicro509Error,\n} from '#micro509/result/result';\nimport {\n\tfailureResult,\n\trethrowIfInvariant,\n\tsuccessResult,\n\tthrowMicro509Error,\n} from '#micro509/result/result';\nimport type {\n\tCheckCertificateRevocationAgainstCrlInput,\n\tCrlSource,\n\tParsedCertificateRevocationList,\n\tUnrecognizedReasonCodePolicy,\n} from '#micro509/revocation/crl';\nimport {\n\tassertCrlMaxAge,\n\tcheckCertificateRevocationAgainstCrl,\n\tcoversAllDistributionPointReasons,\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. RFC 9919 §3.1.1 requires SHA-256 for conforming clients; RFC 6960 defines no 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-256'`. */\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 type ParsedOcspSingleResponse = {\n\t/** Which certificate this status applies to. */\n\treadonly certId: ParsedOcspCertId;\n\t/** Start of the validity window for this status assertion. */\n\treadonly thisUpdate: Date;\n\t/**\n\t * Time at or before which newer status information will be available.\n\t * Absent when the responder indicates that newer revocation information is\n\t * available all the time (RFC 6960 §4.2.2.1).\n\t */\n\treadonly nextUpdate?: Date;\n} & ParsedOcspCertStatus;\n\n/**\n * RFC 6960 §4.2.1 `CertStatus ::= CHOICE { good [0] NULL, revoked [1] RevokedInfo,\n * unknown [2] UnknownInfo }`.\n *\n * Only `revoked` carries data, so `RevokedInfo`'s fields exist only on that\n * alternative. `revocationReasonCode` stays optional because `revocationReason`\n * is OPTIONAL within `RevokedInfo`.\n */\nexport type ParsedOcspCertStatus =\n\t| {\n\t\t\t/** Responder asserts the certificate is not revoked. */\n\t\t\treadonly certStatus: 'good';\n\t }\n\t| {\n\t\t\t/** Responder asserts the certificate is revoked. */\n\t\t\treadonly certStatus: 'revoked';\n\t\t\t/** `RevokedInfo.revocationTime`. */\n\t\t\treadonly revokedAt: Date;\n\t\t\t/** `RevokedInfo.revocationReason` CRLReason value, when present. */\n\t\t\treadonly revocationReasonCode?: bigint;\n\t }\n\t| {\n\t\t\t/** Responder has no record of the certificate. */\n\t\t\treadonly certStatus: 'unknown';\n\t };\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/** DER-encoded `parameters` field of the signature AlgorithmIdentifier. */\n\treadonly signatureAlgorithmParametersDer?: Uint8Array;\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 type CreateOcspSingleResponseInput = CreateOcspRequestItemInput & {\n\t/** Start of the validity window for this status assertion. Defaults to `new Date()`. */\n\treadonly thisUpdate?: Date;\n\t/**\n\t * Time at or before which newer status information will be available.\n\t * When omitted, the response indicates that newer information is available\n\t * all the time (RFC 6960 §4.2.2.1), and RFC 9919 clients reject it.\n\t */\n\treadonly nextUpdate?: Date;\n} & CreateOcspCertStatusInput;\n\n/**\n * Status to assert for one certificate, mirroring RFC 6960 §4.2.1 `CertStatus`.\n *\n * `RevokedInfo`'s fields are reachable only under `'revoked'`.\n */\nexport type CreateOcspCertStatusInput =\n\t| {\n\t\t\t/** Assert the certificate is not revoked. */\n\t\t\treadonly certStatus: 'good';\n\t\t\t/** Unavailable unless `certStatus` is `'revoked'`. */\n\t\t\treadonly revokedAt?: never;\n\t\t\t/** Unavailable unless `certStatus` is `'revoked'`. */\n\t\t\treadonly revocationReasonCode?: never;\n\t }\n\t| {\n\t\t\t/** Assert the certificate is revoked. */\n\t\t\treadonly certStatus: 'revoked';\n\t\t\t/** `RevokedInfo.revocationTime`. Defaults to `thisUpdate`. */\n\t\t\treadonly revokedAt?: Date;\n\t\t\t/** `RevokedInfo.revocationReason` CRLReason integer code. */\n\t\t\treadonly revocationReasonCode?: number;\n\t }\n\t| {\n\t\t\t/** Assert no record of the certificate exists. */\n\t\t\treadonly certStatus: 'unknown';\n\t\t\t/** Unavailable unless `certStatus` is `'revoked'`. */\n\t\t\treadonly revokedAt?: never;\n\t\t\t/** Unavailable unless `certStatus` is `'revoked'`. */\n\t\t\treadonly revocationReasonCode?: never;\n\t };\n\n/** Machine-readable reason an OCSP encoder rejected its construction input. */\nexport type OcspEncoderErrorCode =\n\t| 'invalid_date'\n\t| 'invalid_revocation_reason_code'\n\t| 'signer_certificate_key_mismatch';\n\n/** Throws a {@link ResultError} for an OCSP encoder input-validation failure. */\nfunction throwOcspEncoderError(code: OcspEncoderErrorCode, message: string): never {\n\tthrowMicro509Error(code, message);\n}\n\nfunction assertOcspDate(date: Date | undefined, field: string): void {\n\tif (date !== undefined && Number.isNaN(date.getTime())) {\n\t\tthrowOcspEncoderError('invalid_date', `${field} must be a valid date`);\n\t}\n}\n\nfunction assertOcspRevocationReasonCode(code: number | undefined): void {\n\tif (code !== undefined && !(Number.isSafeInteger(code) && code >= 0)) {\n\t\tthrowOcspEncoderError(\n\t\t\t'invalid_revocation_reason_code',\n\t\t\t'revocationReasonCode must be a non-negative integer',\n\t\t);\n\t}\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-256'`. */\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/**\n * Failure detail when OCSP response signature verification fails. `unsupported`\n * and `limit_exceeded` report a response or signer certificate micro509 cannot\n * decode (see {@linkcode ParseOcspResponseErrorCode}).\n */\nexport interface VerifyOcspResponseSignatureFailure\n\textends Micro509Error<'signature_invalid' | DecodeRefusalCode> {\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<\n\t\t\t'signature_invalid' | DecodeRefusalCode,\n\t\t\tRecord<never, never>,\n\t\t\tVerifyOcspResponseSignatureFailure\n\t >;\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/**\n\t * Maximum age of each `responderRevocationCrls` entry's `thisUpdate` at\n\t * `at`, in milliseconds. An older CRL yields no evidence. Unbounded by\n\t * default, in which case a CRL without `nextUpdate` yields no evidence.\n\t * Throws `RangeError` when negative or not finite.\n\t */\n\treadonly responderRevocationCrlMaxAgeMs?: number;\n\t/**\n\t * Treatment of a `responderRevocationCrls` entry that revokes the responder\n\t * with an unrecognized CRLReason. See {@linkcode UnrecognizedReasonCodePolicy}.\n\t * `'reject'` blocks validation with `responder_revocation_unknown`, even when\n\t * another CRL provides good coverage. Defaults to `'revoked'`.\n\t */\n\treadonly responderRevocationUnrecognizedReasonCode?: UnrecognizedReasonCodePolicy;\n\t/** Evaluation time for freshness checks and delegated responder chain validation. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/**\n\t * Clock-skew tolerance in milliseconds for `thisUpdate`/`nextUpdate`/`producedAt`,\n\t * including those of `responderRevocationCrls`. It also widens\n\t * `responderRevocationCrlMaxAgeMs`.\n\t */\n\treadonly clockSkewMs?: number;\n\t/**\n\t * OCSP client profile to enforce. Defaults to `'rfc6960'`, which accepts a\n\t * response without `nextUpdate` (RFC 6960 §4.2.2.1). `'rfc9919'` applies the\n\t * RFC 9919 §5 client rule and fails with `next_update_missing` when any\n\t * single response omits `nextUpdate`.\n\t */\n\treadonly profile?: 'rfc6960' | 'rfc9919';\n}\n\n/** Failure codes produced by {@linkcode validateOcspResponse}. */\nexport type ValidateOcspResponseErrorCode =\n\t| 'next_update_missing'\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\t| DecodeRefusalCode;\n\n/**\n * Failure detail for {@linkcode validateOcspResponse}.\n *\n * Possible codes: `next_update_missing`, `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\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-256';\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 = DecodeFailureCode;\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 decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed OCSP request');\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 decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed OCSP request');\n\t}\n}\n\n/** Machine-readable failure reason for the OCSP response parsers, with the codes of {@linkcode ParseOcspRequestErrorCode}. */\nexport type ParseOcspResponseErrorCode = ParseOcspRequestErrorCode;\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 signatureAlgorithmParametersDer =\n\t\tsignatureAlgorithmParameters === undefined\n\t\t\t? undefined\n\t\t\t: basicResponse.slice(\n\t\t\t\t\tsignatureAlgorithmParameters.start - signatureAlgorithmParameters.headerLength,\n\t\t\t\t\tsignatureAlgorithmParameters.end,\n\t\t\t\t);\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\t...(signatureAlgorithmParametersDer === undefined ? {} : { signatureAlgorithmParametersDer }),\n\t\tsignatureAlgorithmName: describeSignatureAlgorithm(\n\t\t\tsignatureAlgorithmOid,\n\t\t\tsignatureAlgorithmParametersDer,\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 decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed OCSP response');\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 decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed OCSP response');\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\t// RFC 8410 §12: \"the same public key cannot be used for both ECDH and EdDSA\",\n\t// so a responder must not name a certificate whose subject public key cannot\n\t// verify the algorithm the signer key produces.\n\tif (\n\t\t!getVerifySignatureConfigResult(\n\t\t\tsignatureAlgorithm.algorithmOid,\n\t\t\tsignatureAlgorithm.parameters,\n\t\t\tsignerCertificate.publicKeyAlgorithmOid,\n\t\t\tsignerCertificate.publicKeyParametersOid,\n\t\t\t'signer',\n\t\t).ok\n\t) {\n\t\tthrowOcspEncoderError(\n\t\t\t'signer_certificate_key_mismatch',\n\t\t\t'signerCertificate must carry a public key that verifies the signer key algorithm',\n\t\t);\n\t}\n\tconst producedAt = input.producedAt ?? new Date();\n\tassertOcspDate(producedAt, 'producedAt');\n\tconst hashAlgorithm = input.hashAlgorithm ?? 'SHA-256';\n\tconst responses: Uint8Array[] = [];\n\tfor (const response of input.responses) {\n\t\tassertOcspDate(response.thisUpdate, 'thisUpdate');\n\t\tassertOcspDate(response.nextUpdate, 'nextUpdate');\n\t\tassertOcspDate(response.revokedAt, 'revokedAt');\n\t\tassertOcspRevocationReasonCode(response.revocationReasonCode);\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\texplicitContext(2, octetString(responderKeyHash)),\n\t\tgeneralizedTime(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\t// certs [0] EXPLICIT SEQUENCE OF Certificate (RFC 6960 §4.2.1).\n\t\tbasicResponseFields.push(\n\t\t\texplicitContext(0, sequence(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 (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? verifyOcspResponseFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'OCSP response signed content is malformed',\n\t\t\t\t)\n\t\t\t: verifyOcspResponseFailureResult(refusal.code, refusal.message);\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 (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? verifyOcspResponseFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'OCSP signer certificate input is malformed',\n\t\t\t\t)\n\t\t\t: verifyOcspResponseFailureResult(refusal.code, refusal.message);\n\t}\n\tlet verifiedResult: Awaited<ReturnType<typeof verifySignedDataDetailed>>;\n\ttry {\n\t\tverifiedResult = await verifySignedDataDetailed(\n\t\t\tparsed.signatureAlgorithmOid,\n\t\t\tparsed.signatureAlgorithmParametersDer,\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 (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? verifyOcspResponseFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'OCSP response signature verification failed',\n\t\t\t\t)\n\t\t\t: verifyOcspResponseFailureResult(refusal.code, refusal.message);\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\tassertCrlMaxAge(input.responderRevocationCrlMaxAgeMs);\n\tlet parsedResponse: ParsedOcspResponse;\n\ttry {\n\t\tparsedResponse = normalizeOcspResponse(input.response);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateOcspResponseFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'OCSP response signed content is malformed',\n\t\t\t\t)\n\t\t\t: validateOcspResponseFailureResult(refusal.code, refusal.message);\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, {\n\t\tat,\n\t\tskew,\n\t\tprofile: input.profile ?? 'rfc6960',\n\t});\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 (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateOcspResponseFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'issuer certificate input is malformed',\n\t\t\t\t)\n\t\t\t: validateOcspResponseFailureResult(refusal.code, refusal.message);\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 (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateOcspResponseFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'OCSP responder certificate input is malformed',\n\t\t\t\t)\n\t\t\t: validateOcspResponseFailureResult(refusal.code, refusal.message);\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 (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateOcspResponseFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'OCSP responder certificate input is malformed',\n\t\t\t\t)\n\t\t\t: validateOcspResponseFailureResult(refusal.code, refusal.message);\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\ninterface OcspFreshnessContext {\n\treadonly at: Date;\n\treadonly skew: number;\n\treadonly profile: NonNullable<ValidateOcspResponseInput['profile']>;\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\tcontext: OcspFreshnessContext,\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tif (\n\t\tparsedResponse.producedAt !== undefined &&\n\t\tparsedResponse.producedAt.getTime() - context.skew > context.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\tcontext,\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\tcontext: OcspFreshnessContext,\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, context);\n}\n\nfunction validateOcspSingleResponseTimes(\n\tresponse: ParsedOcspSingleResponse,\n\tproducedAt: Date | undefined,\n\t{ at, skew, profile }: OcspFreshnessContext,\n): ValidateOcspResponseFailureBranch | undefined {\n\tif (profile === 'rfc9919' && response.nextUpdate === undefined) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'next_update_missing',\n\t\t\t'OCSP response omits nextUpdate, which the RFC 9919 profile requires',\n\t\t);\n\t}\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 (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateOcspResponseFailureResult('request_mismatch', 'OCSP request input is malformed')\n\t\t\t: validateOcspResponseFailureResult(refusal.code, refusal.message);\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' | DecodeRefusalCode,\n\tmessage: string,\n): ErrorResult<\n\t'signature_invalid' | DecodeRefusalCode,\n\tRecord<never, never>,\n\tVerifyOcspResponseSignatureFailure\n> {\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 * An extension whose value is not the NULL that §4.2.2.2.1 requires does not count.\n */\nexport function hasOcspNoCheckExtension(certificate: OcspCertificateSource): boolean {\n\treturn carriesOcspNoCheck(normalizeCertificate(certificate));\n}\n\n/** Whether a parsed certificate carries `id-pkix-ocsp-nocheck` with its NULL value. */\nexport function carriesOcspNoCheck(certificate: ParsedCertificate): boolean {\n\treturn certificate.extensions.some(\n\t\t(extension) => extension.oid === OIDS.ocspNoCheck && extension.valueHex === '0500',\n\t);\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\nfunction responderCrlCheck(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: ValidateOcspResponseInput,\n): Omit<CheckCertificateRevocationAgainstCrlInput, 'crl'> {\n\treturn {\n\t\tcertificate: signer,\n\t\tissuerCertificate: issuer,\n\t\tat: input.at ?? new Date(),\n\t\t...(input.responderRevocationCrlMaxAgeMs === undefined\n\t\t\t? {}\n\t\t\t: { maxAgeMs: input.responderRevocationCrlMaxAgeMs }),\n\t\t...(input.clockSkewMs === undefined ? {} : { clockSkewMs: input.clockSkewMs }),\n\t\t...(input.responderRevocationUnrecognizedReasonCode === undefined\n\t\t\t? {}\n\t\t\t: { unrecognizedReasonCode: input.responderRevocationUnrecognizedReasonCode }),\n\t};\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 crlCheck = responderCrlCheck(signer, issuer, input);\n\tconst coveredReasons = new Set<string>();\n\tlet sawUnrecognizedReason = 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({ ...crlCheck, crl });\n\t\tif (!result.ok) {\n\t\t\tsawUnrecognizedReason ||= result.code === 'reason_code_unrecognized';\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\tfor (const reason of result.value.coveredReasons) {\n\t\t\tcoveredReasons.add(reason);\n\t\t}\n\t}\n\tif (sawUnrecognizedReason) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'responder_revocation_unknown',\n\t\t\t'Delegated OCSP responder carries an unrecognized CRL reason code',\n\t\t);\n\t}\n\t// A definitive good requires every revocation reason to be covered; a single\n\t// reason-scoped CRL does not prove the responder unrevoked.\n\tif (coversAllDistributionPointReasons(coveredReasons) || 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\tgeneralizedTime(input.thisUpdate ?? new Date()),\n\t\t...(input.nextUpdate === undefined\n\t\t\t? []\n\t\t\t: [explicitContext(0, generalizedTime(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[] = [\n\t\t\t\tgeneralizedTime(input.revokedAt ?? input.thisUpdate ?? new Date()),\n\t\t\t];\n\t\t\tif (input.revocationReasonCode !== undefined) {\n\t\t\t\trevokedFields.push(explicitContext(0, enumeratedFromNumber(input.revocationReasonCode)));\n\t\t\t}\n\t\t\treturn tlv(0xa1, concatBytes(revokedFields));\n\t\t}\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = input;\n\t\t\tthrow new Error(`Unhandled CertStatus type: ${String(_exhaustive)}`);\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\treturn {\n\t\tcertId: parseOcspCertId(source.slice(certId.start - certId.headerLength, certId.end)),\n\t\tthisUpdate: parseTime(thisUpdate),\n\t\t...parseOcspSingleResponseNextUpdate(source, nextUpdateElement),\n\t\t...parseOcspCertStatusFields(source, certStatus),\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): ParsedOcspCertStatus {\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?: bigint } {\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: decodeNonNegativeIntegerBigInt(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 0xa2: {\n\t\t\tconst inner = childrenOf(source, element);\n\t\t\tif (inner.length !== 1) {\n\t\t\t\tthrow new Error('ResponderID byKey must wrap exactly one OCTET STRING');\n\t\t\t}\n\t\t\tconst keyHash = requireElement(inner[0], 'ResponderID byKey');\n\t\t\tif (keyHash.tag !== 0x04) {\n\t\t\t\tthrow new Error('ResponderID byKey must wrap an OCTET STRING');\n\t\t\t}\n\t\t\t// KeyHash is the SHA-1 hash of the responder's public key (RFC 6960 §4.2.1).\n\t\t\tif (keyHash.value.length !== 20) {\n\t\t\t\tthrow new Error('ResponderID byKey must be a 20-byte SHA-1 KeyHash');\n\t\t\t}\n\t\t\treturn { type: 'byKeyHash', keyHashHex: toHex(keyHash.value) };\n\t\t}\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 a directory attribute type OID (X.520 `id-at` arc plus the legacy PKCS #9 emailAddress) 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\t// certs [0] EXPLICIT SEQUENCE OF Certificate (RFC 6960 §4.2.1): the single\n\t// child of [0] is the SEQUENCE whose elements are the certificates.\n\tconst sequenceElement = childrenOf(source, element)[0];\n\tif (sequenceElement === undefined || sequenceElement.tag !== 0x30) {\n\t\tthrow new Error('Malformed BasicOCSPResponse certs');\n\t}\n\tlet offset = sequenceElement.start;\n\twhile (offset < sequenceElement.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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAwUA,SAAS,s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AAGA,SAAS,gBAAgB,GAAkC;CAC1D,OAAO;EACN1J,EAAO;EACPA,EAAO;EACPA,EAAO;EACPA,EAAO;CACR,CAAC,CAAC,KAAK,GAAG;AACX"}
1
+ {"version":3,"file":"ocsp.js","names":["_exhaustive","childrenOf","decodeNonNegativeIntegerBigInt","decodeNonNegativeIntegerNumber","decodeObjectIdentifier","decodeString","extractBitStringValue","hexToBytes","parseTime","requireElement","signatureBits","toArrayBuffer","toHex","decodeFailureResult","decodeRefusalOf","bitString","concatBytes","enumeratedFromNumber","explicitContext","generalizedTime","integer","nullValue","objectIdentifier","octetString","readElement","readRootElement","readSequenceChildren","sequence","tlv","OIDS","describeHashAlgorithm","describeSignatureAlgorithm","callerVerification","getVerifySignatureConfigResult","resolveSignatureVerifiers","verifySignedDataDetailed","encodeAlgorithmIdentifier","getSignatureAlgorithm","signBytes","getCrypto","base64Encode","compareDistinguishedNames","anchorWorkingKey","carriesTrustAnchorKey","certificateWorkingKey","pathWorkingKey","withWorkingParameters","workingParametersAt","pemDecodeOrThrow","pemEncode","DECODE_REFUSAL_CODES","failureResult","rethrowIfInvariant","successResult","throwMicro509Error","assertClockSkew","assertCrlMaxAge","checkCertificateRevocationAgainstCrlsBy","coversAllDistributionPointReasons","distinctSignedCrls","normalizeCrl","trustAnchorFromCertificate","verifyCertificateChain","parseCertificateDerOrThrow","parseCertificateFromSource","code","message","date","field","resolved","issuer","input","hashAlgorithm","requestEntries","request","certificate","tbsRequestFields","der","top","tbsRequest","optionalSignature","tbsChildren","cursor","requestList","requests","requestChildren","certId","extensions","nonce","versionWrapper","versionFields","versionElement","requestorName","pem","error","statusElement","responseStatus","responseBytes","responseBytesWrapper","bytesSequence","responseBytesChildren","responseType","response","responseTypeOid","basicResponse","basicChildren","responseData","signatureAlgorithm","signatureValue","certificatesElement","signatureAlgorithmChildren","signatureAlgorithmOid","signatureAlgorithmParameters","signatureAlgorithmParametersDer","responseDataDer","signedResponseData","signerCertificate","producedAt","responses","responderKeyHash","responseDataFields","signature","includedCertificates","basicResponseFields","options","verification","parsed","refusal","signer","verifiedResult","context","callerInput","issuerInput","parsedResponse","normalized","trustedResponders","issuerWorkingKey","resolvedContext","responder","responderAuthorization","at","skew","freshness","requestMatch","resolvedResponder","matched","responderId","trusted","responderBinding","responderFailure","link","revocation","allowChainedResponderCertificate","chain","responderLink","caCertificates","path","index","next","own","working","left","right","byte","responderRevocation","responseFreshness","expected","profile","requestSource","entry","requestIds","responseIds","requestId","extension","sources","complete","delta","source","crl","policy","skipReason","settled","crlCheck","crls","coveredReasons","sawUnrecognizedReason","sawUnsettledDelta","outcome","result","reason","responseDataChildren","producedAtElement","responsesElement","responseExtensions","parsedResponses","singleResponse","certificates","intermediates","hashAlgorithmOid","serialNumberHex","algorithm","bytes","certStatus","revokedFields","value","root","children","algorithmChildren","algorithmOid","serialNumber","element","thisUpdate","nextUpdateElement","singleExtensions","revokedInfo","reasonChildren","enumerated","inner","keyHash","rdns","attributes","values","setElement","rdn","attribute","attributeSequence","parts","oid","valueElement","key","leftRdn","rightRdn","leftAttribute","found","rightAttribute","preparedLeft","preparedRight","tag","extensionsChildren","extensionsSequence","seenOids","extnValue","nonceElement","sequenceElement","offset","child","spkiDer","bitStringElement","seen","serial","wrapperChildren","signatureSequence","signatureChildren","certificateChildren","nextUpdate","label"],"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\tdecodeNonNegativeIntegerBigInt,\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\textractBitStringValue,\n\thexToBytes,\n\tparseTime,\n\trequireElement,\n\tsignatureBits,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tDECODE_REFUSAL_CODES,\n\tdecodeFailureResult,\n\tdecodeRefusalOf,\n} from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\tbitString,\n\tconcatBytes,\n\tDEFAULT_MAX_DER_DEPTH,\n\tenumeratedFromNumber,\n\texplicitContext,\n\tgeneralizedTime,\n\tinteger,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\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 type {\n\tCallerVerification,\n\tSignatureVerifier,\n\tSignatureVerifiers,\n} from '#micro509/internal/crypto/sig-verify';\nimport {\n\tcallerVerification,\n\tgetVerifySignatureConfigResult,\n\tresolveSignatureVerifiers,\n\tverifySignedDataDetailed,\n} 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 type { WorkingPublicKey } from '#micro509/internal/verify/verify-path';\nimport {\n\tanchorWorkingKey,\n\tcarriesTrustAnchorKey,\n\tcertificateWorkingKey,\n\tpathWorkingKey,\n\twithWorkingParameters,\n\tworkingParametersAt,\n} from '#micro509/internal/verify/verify-path';\nimport { pemDecodeOrThrow, pemEncode } from '#micro509/pem/pem';\nimport type { DecodeFailureCode, ErrorResult, Micro509Error } from '#micro509/result/result';\nimport {\n\tfailureResult,\n\trethrowIfInvariant,\n\tsuccessResult,\n\tthrowMicro509Error,\n} from '#micro509/result/result';\nimport type {\n\tCrlCheckOptions,\n\tCrlSource,\n\tDeltaCrlBudget,\n\tParsedCertificateRevocationList,\n\tSupersededDeltaCrlPolicy,\n\tUnrecognizedReasonCodePolicy,\n} from '#micro509/revocation/crl';\nimport {\n\tassertClockSkew,\n\tassertCrlMaxAge,\n\tcheckCertificateRevocationAgainstCrlsBy,\n\tcoversAllDistributionPointReasons,\n\tDELTA_CRL_ATTEMPTS_PER_CALL,\n\tdistinctSignedCrls,\n\tnormalizeCrl,\n} from '#micro509/revocation/crl';\nimport type { CandidatePath, TrustAnchor } from '#micro509/verify/verify';\nimport { trustAnchorFromCertificate, 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. RFC 9919 §3.1.1 requires SHA-256 for conforming clients; RFC 6960 defines no 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-256'`. */\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 type ParsedOcspSingleResponse = {\n\t/** Which certificate this status applies to. */\n\treadonly certId: ParsedOcspCertId;\n\t/** Start of the validity window for this status assertion. */\n\treadonly thisUpdate: Date;\n\t/**\n\t * Time at or before which newer status information will be available.\n\t * Absent when the responder indicates that newer revocation information is\n\t * available all the time (RFC 6960 §4.2.2.1).\n\t */\n\treadonly nextUpdate?: Date;\n} & ParsedOcspCertStatus;\n\n/**\n * RFC 6960 §4.2.1 `CertStatus ::= CHOICE { good [0] NULL, revoked [1] RevokedInfo,\n * unknown [2] UnknownInfo }`.\n *\n * Only `revoked` carries data, so `RevokedInfo`'s fields exist only on that\n * alternative. `revocationReasonCode` stays optional because `revocationReason`\n * is OPTIONAL within `RevokedInfo`.\n */\nexport type ParsedOcspCertStatus =\n\t| {\n\t\t\t/** Responder asserts the certificate is not revoked. */\n\t\t\treadonly certStatus: 'good';\n\t }\n\t| {\n\t\t\t/** Responder asserts the certificate is revoked. */\n\t\t\treadonly certStatus: 'revoked';\n\t\t\t/** `RevokedInfo.revocationTime`. */\n\t\t\treadonly revokedAt: Date;\n\t\t\t/** `RevokedInfo.revocationReason` CRLReason value, when present. */\n\t\t\treadonly revocationReasonCode?: bigint;\n\t }\n\t| {\n\t\t\t/** Responder has no record of the certificate. */\n\t\t\treadonly certStatus: 'unknown';\n\t };\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/** DER-encoded `parameters` field of the signature AlgorithmIdentifier. */\n\treadonly signatureAlgorithmParametersDer?: Uint8Array;\n\t/** Human-readable signature algorithm name. */\n\treadonly signatureAlgorithmName?: string;\n\t/** Signature bytes: the `signature` BIT STRING content after its unused-bit count. */\n\treadonly signatureValue?: Uint8Array;\n\t/** Unused bits in the final octet of {@linkcode signatureValue}, 0 through 7. */\n\treadonly signatureValueUnusedBits?: number;\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 type CreateOcspSingleResponseInput = CreateOcspRequestItemInput & {\n\t/** Start of the validity window for this status assertion. Defaults to `new Date()`. */\n\treadonly thisUpdate?: Date;\n\t/**\n\t * Time at or before which newer status information will be available.\n\t * When omitted, the response indicates that newer information is available\n\t * all the time (RFC 6960 §4.2.2.1), and RFC 9919 clients reject it.\n\t */\n\treadonly nextUpdate?: Date;\n} & CreateOcspCertStatusInput;\n\n/**\n * Status to assert for one certificate, mirroring RFC 6960 §4.2.1 `CertStatus`.\n *\n * `RevokedInfo`'s fields are reachable only under `'revoked'`.\n */\nexport type CreateOcspCertStatusInput =\n\t| {\n\t\t\t/** Assert the certificate is not revoked. */\n\t\t\treadonly certStatus: 'good';\n\t\t\t/** Unavailable unless `certStatus` is `'revoked'`. */\n\t\t\treadonly revokedAt?: never;\n\t\t\t/** Unavailable unless `certStatus` is `'revoked'`. */\n\t\t\treadonly revocationReasonCode?: never;\n\t }\n\t| {\n\t\t\t/** Assert the certificate is revoked. */\n\t\t\treadonly certStatus: 'revoked';\n\t\t\t/** `RevokedInfo.revocationTime`. Defaults to `thisUpdate`. */\n\t\t\treadonly revokedAt?: Date;\n\t\t\t/** `RevokedInfo.revocationReason` CRLReason integer code. */\n\t\t\treadonly revocationReasonCode?: number;\n\t }\n\t| {\n\t\t\t/** Assert no record of the certificate exists. */\n\t\t\treadonly certStatus: 'unknown';\n\t\t\t/** Unavailable unless `certStatus` is `'revoked'`. */\n\t\t\treadonly revokedAt?: never;\n\t\t\t/** Unavailable unless `certStatus` is `'revoked'`. */\n\t\t\treadonly revocationReasonCode?: never;\n\t };\n\n/** Machine-readable reason an OCSP encoder rejected its construction input. */\nexport type OcspEncoderErrorCode =\n\t| 'invalid_date'\n\t| 'invalid_revocation_reason_code'\n\t| 'signer_certificate_key_mismatch';\n\n/** Throws a {@link ResultError} for an OCSP encoder input-validation failure. */\nfunction throwOcspEncoderError(code: OcspEncoderErrorCode, message: string): never {\n\tthrowMicro509Error(code, message);\n}\n\nfunction assertOcspDate(date: Date | undefined, field: string): void {\n\tif (date !== undefined && Number.isNaN(date.getTime())) {\n\t\tthrowOcspEncoderError('invalid_date', `${field} must be a valid date`);\n\t}\n}\n\nfunction assertOcspRevocationReasonCode(code: number | undefined): void {\n\tif (code !== undefined && !(Number.isSafeInteger(code) && code >= 0)) {\n\t\tthrowOcspEncoderError(\n\t\t\t'invalid_revocation_reason_code',\n\t\t\t'revocationReasonCode must be a non-negative integer',\n\t\t);\n\t}\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-256'`. */\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/**\n * Failure detail when OCSP response signature verification fails. `unsupported`\n * and `limit_exceeded` report a response or signer certificate micro509 cannot\n * decode (see {@linkcode ParseOcspResponseErrorCode}).\n */\nexport interface VerifyOcspResponseSignatureFailure\n\textends Micro509Error<'signature_invalid' | DecodeFailureCode> {\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<\n\t\t\t'signature_invalid' | DecodeFailureCode,\n\t\t\tRecord<never, never>,\n\t\t\tVerifyOcspResponseSignatureFailure\n\t >;\n\n/**\n * Revocation policy for delegated OCSP responder certificates. RFC 6960\n * §4.2.2.2.1 leaves the check of a responder without `id-pkix-ocsp-nocheck` to\n * local policy. CRL evidence comes from\n * {@linkcode ValidateOcspResponseInput.responderRevocationCrls}.\n *\n * - `'nocheck-or-evidence'` (default): a responder carrying\n * `id-pkix-ocsp-nocheck` or noRevAvail is exempt (RFC 9608 §4). Otherwise\n * CRL evidence must show it is not revoked, as RFC 9608 §4 runs the RFC 5280\n * §6.1.3 (a)(3) check.\n * - `'honor-nocheck'`: as `'nocheck-or-evidence'`, but missing or unusable\n * evidence is tolerated. A revoked verdict rejects, and so do an entry\n * whose reason code `responderRevocationUnrecognizedReasonCode: 'reject'`\n * refuses and an applicable delta CRL that cannot settle the status. A\n * responder with a critical cRLDistributionPoints extension still needs\n * evidence (X.509 (2019) §9.6.2.1).\n * - `'require-evidence'`: `id-pkix-ocsp-nocheck` is ignored and CRL evidence\n * must show the responder is not revoked (RFC 5280 §6.1 lets an application\n * further limit the valid paths). A responder carrying noRevAvail is\n * rejected, as RFC 9608 §2 keeps it off every CRL.\n * - `'skip'`: no responder revocation checking.\n */\nexport type OcspResponderRevocationPolicy =\n\t| 'nocheck-or-evidence'\n\t| 'honor-nocheck'\n\t| 'require-evidence'\n\t| '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/**\n\t * When `true`, allows delegated responder chain validation beyond direct\n\t * issuance. `responderRevocationPolicy` then also applies to each CA\n\t * certificate between the issuer and the responder.\n\t */\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 `'nocheck-or-evidence'`. */\n\treadonly responderRevocationPolicy?: OcspResponderRevocationPolicy;\n\t/**\n\t * CRLs used as revocation evidence for delegated responder certificates. A\n\t * delta CRL in the list updates the complete CRL it applies to (RFC 5280\n\t * §5.2.4).\n\t */\n\treadonly responderRevocationCrls?: readonly CrlSource[];\n\t/**\n\t * Maximum age of each `responderRevocationCrls` entry's `thisUpdate` at\n\t * `at`, in milliseconds. An older CRL, or one without `nextUpdate` when\n\t * this is unset, settles only a revocation other than certificateHold of\n\t * the responder (RFC 5280 §5.3.1). Unbounded by default. Throws\n\t * `RangeError` when negative or not finite.\n\t */\n\treadonly responderRevocationCrlMaxAgeMs?: number;\n\t/**\n\t * Treatment of a `responderRevocationCrls` entry that revokes the responder\n\t * with an unrecognized CRLReason. See {@linkcode UnrecognizedReasonCodePolicy}.\n\t * `'reject'` blocks validation with `responder_revocation_unknown`, even when\n\t * another CRL provides good coverage. Defaults to `'revoked'`.\n\t */\n\treadonly responderRevocationUnrecognizedReasonCode?: UnrecognizedReasonCodePolicy;\n\t/**\n\t * Treatment of `responderRevocationCrls` delta CRLs that the attempt limits\n\t * leave unread although one already read supersedes them. See\n\t * {@linkcode SupersededDeltaCrlPolicy}. Defaults to `'indeterminate'`, which\n\t * leaves the responder `responder_revocation_unknown`.\n\t */\n\treadonly responderRevocationUnreadSupersededDeltaCrls?: SupersededDeltaCrlPolicy;\n\t/** Evaluation time for freshness checks and delegated responder chain validation. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/**\n\t * Clock-skew tolerance in milliseconds for `thisUpdate`/`nextUpdate`/`producedAt`,\n\t * including those of `responderRevocationCrls`. It also widens\n\t * `responderRevocationCrlMaxAgeMs`. Throws `RangeError` when negative or\n\t * not finite.\n\t */\n\treadonly clockSkewMs?: number;\n\t/**\n\t * OCSP client profile to enforce. Defaults to `'rfc6960'`, which accepts a\n\t * response without `nextUpdate` (RFC 6960 §4.2.2.1). `'rfc9919'` applies the\n\t * RFC 9919 §5 client rule and fails with `next_update_missing` when any\n\t * single response omits `nextUpdate`.\n\t */\n\treadonly profile?: 'rfc6960' | 'rfc9919';\n\t/**\n\t * Caller verifiers for signature algorithms micro509 does not verify through\n\t * WebCrypto, keyed by dotted-decimal signature algorithm OID. One runs only\n\t * where a signature would otherwise use unsupported algorithm parameters. A\n\t * key that micro509 verifies natively, a key that is no OID, or a value that\n\t * is no function throws `RangeError`.\n\t */\n\treadonly signatureVerifiers?: SignatureVerifiers;\n}\n\n/** {@linkcode ValidateOcspResponseInput} once its issuer is resolved separately. */\ntype OcspValidationOptions = Omit<ValidateOcspResponseInput, 'issuerCertificate'>;\n\n/** Options for {@linkcode verifyOcspResponseSignature}. */\nexport interface VerifyOcspResponseSignatureOptions {\n\t/**\n\t * Caller verifiers for signature algorithms micro509 does not verify through\n\t * WebCrypto, keyed by dotted-decimal signature algorithm OID. One runs only\n\t * where a signature would otherwise use unsupported algorithm parameters. A\n\t * key that micro509 verifies natively, a key that is no OID, or a value that\n\t * is no function throws `RangeError`.\n\t */\n\treadonly signatureVerifiers?: SignatureVerifiers;\n}\n\n/**\n * Caller verifiers for one OCSP validation, with the working key that the\n * issuer's certification path gives it (RFC 5280 §6.1.4 (e)).\n *\n * @internal\n */\nexport interface OcspCallerVerification {\n\t/** Resolved caller verifiers. */\n\treadonly verifiers: ReadonlyMap<string, SignatureVerifier>;\n\t/** The issuer's working key; defaults to its own key parameters. */\n\treadonly issuerWorkingKey?: WorkingPublicKey;\n\t/** SHA-256 SPKI hashes that a delegated responder's certification path must not carry. */\n\treadonly distrustedSpkiSha256?: readonly string[];\n\t/**\n\t * Delta CRL checks left for the revocation check this validation serves.\n\t * Defaults to {@linkcode DELTA_CRL_ATTEMPTS_PER_CALL} for this validation.\n\t */\n\treadonly deltaBudget?: DeltaCrlBudget;\n}\n\n/** {@linkcode OcspCallerVerification} with the issuer's working key resolved. */\ntype ResolvedOcspCallerVerification = OcspCallerVerification & {\n\treadonly issuerWorkingKey: WorkingPublicKey;\n\treadonly deltaBudget: DeltaCrlBudget;\n};\n\n/** Failure codes produced by {@linkcode validateOcspResponse}. */\nexport type ValidateOcspResponseErrorCode =\n\t| 'next_update_missing'\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\t| DecodeFailureCode;\n\n/**\n * Failure detail for {@linkcode validateOcspResponse}.\n *\n * Possible codes: `next_update_missing`, `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\n/**\n * The issuer of the certificate under check: a CA certificate, or a bare trust\n * anchor, which X.509 (2019) §7.5 lets sign OCSP responses and certify\n * delegated responders with its own key.\n *\n * @internal\n */\nexport type OcspIssuer =\n\t| { readonly kind: 'certificate'; readonly certificate: OcspCertificateSource }\n\t| {\n\t\t\treadonly kind: 'trust_anchor';\n\t\t\treadonly trustAnchor: TrustAnchor;\n\t\t\t/**\n\t\t\t * The issuer field of the certificate under check, which RFC 6960 §4.1.1\n\t\t\t * hashes into the CertID in place of an issuer certificate's subject.\n\t\t\t */\n\t\t\treadonly certificateIssuer: ParsedName;\n\t };\n\n/** A name and public key, as an issuer certificate or a trust anchor carries them. */\ntype OcspIssuerKey = Pick<\n\tTrustAnchor,\n\t| 'subject'\n\t| 'subjectKeyIdentifier'\n\t| 'subjectPublicKeyInfoDer'\n\t| 'publicKeyAlgorithmOid'\n\t| 'publicKeyParametersOid'\n>;\n\n/** An {@linkcode OcspIssuer} with its certificate parsed; also the shape of a response signer. */\ntype ResolvedOcspKey =\n\t| { readonly kind: 'certificate'; readonly certificate: ParsedCertificate }\n\t| Extract<OcspIssuer, { readonly kind: 'trust_anchor' }>;\n\nfunction ocspKeyOf(resolved: ResolvedOcspKey): OcspIssuerKey {\n\treturn resolved.kind === 'certificate' ? resolved.certificate : resolved.trustAnchor;\n}\n\n/** The name and key a CertID for `issuer` hashes (RFC 6960 §4.1.1). */\nfunction certIdIssuerKey(issuer: ResolvedOcspKey): OcspIssuerKey {\n\treturn issuer.kind === 'certificate'\n\t\t? issuer.certificate\n\t\t: { ...issuer.trustAnchor, subject: issuer.certificateIssuer };\n}\n\nfunction ocspCertificateOf(resolved: ResolvedOcspKey): ParsedCertificate | undefined {\n\treturn resolved.kind === 'certificate' ? resolved.certificate : undefined;\n}\n\ninterface NormalizedOcspValidationInput {\n\treadonly ok: true;\n\treadonly parsedResponse: ParsedOcspResponse;\n\treadonly issuer: ResolvedOcspKey;\n\treadonly trustedResponders: readonly ParsedCertificate[];\n\treadonly signer: ResolvedOcspKey;\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-256';\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 = DecodeFailureCode;\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 decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed OCSP request');\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 decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed OCSP request');\n\t}\n}\n\n/** Machine-readable failure reason for the OCSP response parsers, with the codes of {@linkcode ParseOcspRequestErrorCode}. */\nexport type ParseOcspResponseErrorCode = ParseOcspRequestErrorCode;\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 signatureAlgorithmParametersDer =\n\t\tsignatureAlgorithmParameters === undefined\n\t\t\t? undefined\n\t\t\t: basicResponse.slice(\n\t\t\t\t\tsignatureAlgorithmParameters.start - signatureAlgorithmParameters.headerLength,\n\t\t\t\t\tsignatureAlgorithmParameters.end,\n\t\t\t\t);\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\t...(signatureAlgorithmParametersDer === undefined ? {} : { signatureAlgorithmParametersDer }),\n\t\tsignatureAlgorithmName: describeSignatureAlgorithm(\n\t\t\tsignatureAlgorithmOid,\n\t\t\tsignatureAlgorithmParametersDer,\n\t\t),\n\t\t...signatureBits(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 decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed OCSP response');\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 decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed OCSP response');\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\t// RFC 8410 §12: \"the same public key cannot be used for both ECDH and EdDSA\",\n\t// so a responder must not name a certificate whose subject public key cannot\n\t// verify the algorithm the signer key produces.\n\tif (\n\t\t!getVerifySignatureConfigResult(\n\t\t\tsignatureAlgorithm.algorithmOid,\n\t\t\tsignatureAlgorithm.parameters,\n\t\t\tsignerCertificate.publicKeyAlgorithmOid,\n\t\t\tsignerCertificate.publicKeyParametersOid,\n\t\t\t'signer',\n\t\t).ok\n\t) {\n\t\tthrowOcspEncoderError(\n\t\t\t'signer_certificate_key_mismatch',\n\t\t\t'signerCertificate must carry a public key that verifies the signer key algorithm',\n\t\t);\n\t}\n\tconst producedAt = input.producedAt ?? new Date();\n\tassertOcspDate(producedAt, 'producedAt');\n\tconst hashAlgorithm = input.hashAlgorithm ?? 'SHA-256';\n\tconst responses: Uint8Array[] = [];\n\tfor (const response of input.responses) {\n\t\tassertOcspDate(response.thisUpdate, 'thisUpdate');\n\t\tassertOcspDate(response.nextUpdate, 'nextUpdate');\n\t\tassertOcspDate(response.revokedAt, 'revokedAt');\n\t\tassertOcspRevocationReasonCode(response.revocationReasonCode);\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\texplicitContext(2, octetString(responderKeyHash)),\n\t\tgeneralizedTime(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\t// certs [0] EXPLICIT SEQUENCE OF Certificate (RFC 6960 §4.2.1).\n\t\tbasicResponseFields.push(\n\t\t\texplicitContext(0, sequence(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\toptions: VerifyOcspResponseSignatureOptions = {},\n): Promise<VerifyOcspResponseSignatureResult> {\n\treturn await verifyOcspResponseSignatureWith(\n\t\tresponse,\n\t\tsignerCertificate,\n\t\tcallerVerification(options.signatureVerifiers),\n\t);\n}\n\nasync function verifyOcspResponseSignatureWith(\n\tresponse: string | Uint8Array | ParsedOcspResponse,\n\tsignerCertificate: OcspCertificateSource,\n\tverification: CallerVerification,\n): Promise<VerifyOcspResponseSignatureResult> {\n\tlet parsed: ParsedOcspResponse;\n\ttry {\n\t\tparsed = normalizeOcspResponse(response);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? verifyOcspResponseFailureResult('malformed', 'OCSP response signed content is malformed')\n\t\t\t: verifyOcspResponseFailureResult(refusal.code, refusal.message);\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 (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? verifyOcspResponseFailureResult('malformed', 'OCSP signer certificate input is malformed')\n\t\t\t: verifyOcspResponseFailureResult(refusal.code, refusal.message);\n\t}\n\treturn await verifyOcspResponseSignatureByKey(parsed, signer, verification);\n}\n\n/** Verifies the signature of a parsed OCSP response with `signer`'s public key. */\nasync function verifyOcspResponseSignatureByKey(\n\tparsed: ParsedOcspResponse,\n\tsigner: OcspIssuerKey,\n\tverification: CallerVerification,\n): Promise<VerifyOcspResponseSignatureResult> {\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 verifiedResult: Awaited<ReturnType<typeof verifySignedDataDetailed>>;\n\ttry {\n\t\tverifiedResult = await verifySignedDataDetailed(\n\t\t\tparsed.signatureAlgorithmOid,\n\t\t\tparsed.signatureAlgorithmParametersDer,\n\t\t\tsigner.publicKeyAlgorithmOid,\n\t\t\tsigner.publicKeyParametersOid,\n\t\t\tsigner.subjectPublicKeyInfoDer,\n\t\t\tparsed.signatureValue,\n\t\t\tparsed.signatureValueUnusedBits ?? 0,\n\t\t\tparsed.responseDataDer,\n\t\t\tverification,\n\t\t);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? verifyOcspResponseFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'OCSP response signature verification failed',\n\t\t\t\t)\n\t\t\t: verifyOcspResponseFailureResult(refusal.code, refusal.message);\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\treturn await validateOcspResponseWith(input, {\n\t\tverifiers: resolveSignatureVerifiers(input.signatureVerifiers),\n\t});\n}\n\n/**\n * {@linkcode validateOcspResponse} with resolved caller verifiers and the\n * issuer's working key.\n *\n * @internal\n */\nexport async function validateOcspResponseWith(\n\tinput: ValidateOcspResponseInput,\n\tcontext: OcspCallerVerification,\n): Promise<ValidateOcspResponseResult> {\n\treturn await validateOcspResponseBy(\n\t\tinput,\n\t\t{ kind: 'certificate', certificate: input.issuerCertificate },\n\t\tcontext,\n\t);\n}\n\n/**\n * {@linkcode validateOcspResponse} for a certificate that `issuer` issued,\n * which may be a bare trust anchor.\n *\n * @internal\n */\nexport async function validateOcspResponseBy(\n\tcallerInput: OcspValidationOptions,\n\tissuerInput: OcspIssuer,\n\tcontext: OcspCallerVerification,\n): Promise<ValidateOcspResponseResult> {\n\tconst input = { ...callerInput, at: callerInput.at ?? new Date() };\n\tassertCrlMaxAge(input.responderRevocationCrlMaxAgeMs);\n\tassertClockSkew(input.clockSkewMs);\n\tlet parsedResponse: ParsedOcspResponse;\n\ttry {\n\t\tparsedResponse = normalizeOcspResponse(input.response);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateOcspResponseFailureResult('malformed', 'OCSP response signed content is malformed')\n\t\t\t: validateOcspResponseFailureResult(refusal.code, refusal.message);\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, issuerInput, parsedResponse);\n\tif (!normalized.ok) {\n\t\treturn normalized;\n\t}\n\tconst { issuer, trustedResponders, signer } = normalized;\n\tconst issuerWorkingKey =\n\t\tcontext.issuerWorkingKey ??\n\t\t(issuer.kind === 'certificate'\n\t\t\t? certificateWorkingKey(issuer.certificate)\n\t\t\t: anchorWorkingKey(issuer.trustAnchor));\n\tconst resolvedContext = {\n\t\t...context,\n\t\tissuerWorkingKey,\n\t\tdeltaBudget: context.deltaBudget ?? { remaining: DELTA_CRL_ATTEMPTS_PER_CALL },\n\t};\n\tconst responder = await classifyOcspResponder(\n\t\tinput,\n\t\tparsedResponse,\n\t\tissuer,\n\t\tsigner,\n\t\ttrustedResponders,\n\t\tresolvedContext,\n\t);\n\tconst signature = await verifyOcspResponseSignatureByKey(parsedResponse, ocspKeyOf(signer), {\n\t\tverifiers: context.verifiers,\n\t\tworkingParameters: { parametersDer: responderWorkingParameters(responder, issuerWorkingKey) },\n\t});\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\tresponder,\n\t\tresolvedContext,\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, certIdIssuerKey(issuer), {\n\t\tat,\n\t\tskew,\n\t\tprofile: input.profile ?? 'rfc6960',\n\t});\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: OcspValidationOptions,\n\tissuerInput: OcspIssuer,\n\tparsedResponse: ParsedOcspResponse,\n): Promise<NormalizedOcspValidationInput | ValidateOcspResponseFailureBranch> {\n\tlet issuer: ResolvedOcspKey;\n\ttry {\n\t\tissuer =\n\t\t\tissuerInput.kind === 'certificate'\n\t\t\t\t? { kind: 'certificate', certificate: normalizeCertificate(issuerInput.certificate) }\n\t\t\t\t: issuerInput;\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateOcspResponseFailureResult('malformed', 'issuer certificate input is malformed')\n\t\t\t: validateOcspResponseFailureResult(refusal.code, refusal.message);\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\tissuerInput,\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:\n\t\t\t\tresolvedResponder === undefined\n\t\t\t\t\t? issuer\n\t\t\t\t\t: { kind: 'certificate', certificate: normalizeCertificate(resolvedResponder) },\n\t\t};\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateOcspResponseFailureResult(\n\t\t\t\t\t'malformed',\n\t\t\t\t\t'OCSP responder certificate input is malformed',\n\t\t\t\t)\n\t\t\t: validateOcspResponseFailureResult(refusal.code, refusal.message);\n\t}\n}\n\n/**\n * Selects the responder certificate from explicit, embedded, trusted, or issuer\n * inputs. `undefined` means the bare trust anchor issuer signed the response\n * with its own key.\n */\nasync function resolveOcspResponderCertificate(\n\tinput: OcspValidationOptions,\n\tissuer: OcspIssuer,\n\tparsedResponse: ParsedOcspResponse,\n\ttrustedResponders: readonly ParsedCertificate[],\n): Promise<OcspCertificateSource | undefined> {\n\tconst matched =\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\tif (matched !== undefined) return matched;\n\tif (issuer.kind === 'certificate') {\n\t\treturn parsedResponse.certificates?.[0] ?? issuer.certificate;\n\t}\n\tconst responderId = parsedResponse.responderId;\n\treturn responderId === undefined ||\n\t\t(await matchesOcspResponderId(responderId, issuer.trustAnchor))\n\t\t? undefined\n\t\t: parsedResponse.certificates?.[0];\n}\n\n/**\n * Who signed an OCSP response: the issuer itself, a locally trusted responder,\n * or a delegated responder with the outcome of validating its path.\n */\ntype OcspResponder =\n\t| { readonly kind: 'issuer'; readonly signer: ResolvedOcspKey }\n\t| { readonly kind: 'trusted'; readonly certificate: ParsedCertificate }\n\t| {\n\t\t\treadonly kind: 'delegated';\n\t\t\treadonly certificate: ParsedCertificate;\n\t\t\treadonly path: DelegatedResponderPath;\n\t };\n\n/** A certificate of a delegated responder's path with the issuer whose CRLs cover it. */\ninterface ResponderPathLink {\n\treadonly certificate: ParsedCertificate;\n\treadonly issuer: ResolvedOcspKey;\n\treadonly issuerWorkingKey: WorkingPublicKey;\n}\n\n/**\n * A delegated responder's validated path: the parameters it gives the\n * responder's key, the responder's immediate issuer with its working key,\n * whose CRLs cover the responder, and each CA certificate between that issuer\n * and the OCSP issuer. Otherwise why the path does not validate.\n */\ntype DelegatedResponderPath =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly parametersDer: Uint8Array | undefined;\n\t\t\treadonly issuer: ResolvedOcspKey;\n\t\t\treadonly issuerWorkingKey: WorkingPublicKey;\n\t\t\treadonly caCertificates: readonly ResponderPathLink[];\n\t }\n\t| ValidateOcspResponseFailureBranch;\n\nasync function classifyOcspResponder(\n\tinput: OcspValidationOptions,\n\tparsedResponse: ParsedOcspResponse,\n\tissuer: ResolvedOcspKey,\n\tsigner: ResolvedOcspKey,\n\ttrustedResponders: readonly ParsedCertificate[],\n\tcontext: ResolvedOcspCallerVerification,\n): Promise<OcspResponder> {\n\tif (signer.kind === 'trust_anchor' || isOcspIssuer(signer.certificate, issuer)) {\n\t\treturn { kind: 'issuer', signer };\n\t}\n\tconst certificate = signer.certificate;\n\tif (trustedResponders.some((trusted) => isSameOcspCertificate(certificate, trusted))) {\n\t\treturn { kind: 'trusted', certificate };\n\t}\n\treturn {\n\t\tkind: 'delegated',\n\t\tcertificate,\n\t\tpath: await validateDelegatedResponderPath(input, parsedResponse, issuer, certificate, context),\n\t};\n}\n\n/**\n * The key parameters a responder's signature verifies with: the issuer's\n * working key, a trusted responder's own or inherited parameters, or those its\n * delegated path gives it.\n */\nfunction responderWorkingParameters(\n\tresponder: OcspResponder,\n\tissuerWorkingKey: WorkingPublicKey,\n): Uint8Array | undefined {\n\tif (responder.kind === 'issuer') return issuerWorkingKey.parametersDer;\n\tif (responder.kind === 'delegated' && responder.path.ok) return responder.path.parametersDer;\n\treturn workingParametersAt([responder.certificate], 0, 0, issuerWorkingKey);\n}\n\nasync function validateOcspResponderAuthorization(\n\tinput: OcspValidationOptions,\n\tparsedResponse: ParsedOcspResponse,\n\tresponder: OcspResponder,\n\tcontext: ResolvedOcspCallerVerification,\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tconst responderBinding = await validateOcspResponderIdBinding(\n\t\tparsedResponse.responderId,\n\t\tresponder.kind === 'issuer' ? ocspKeyOf(responder.signer) : responder.certificate,\n\t);\n\tif (!responderBinding.ok) {\n\t\treturn responderBinding;\n\t}\n\tif (responder.kind !== 'delegated') {\n\t\treturn undefined;\n\t}\n\tif (!responder.path.ok) {\n\t\treturn responder.path;\n\t}\n\tconst responderFailure = await validateDelegatedOcspResponder(\n\t\tinput,\n\t\tresponder.path.issuer,\n\t\tresponder.certificate,\n\t\t{ ...context, issuerWorkingKey: responder.path.issuerWorkingKey },\n\t);\n\tif (responderFailure !== undefined) return responderFailure;\n\tfor (const link of responder.path.caCertificates) {\n\t\tconst revocation = await checkDelegatedResponderRevocation(\n\t\t\tlink.certificate,\n\t\t\tlink.issuer,\n\t\t\tinput,\n\t\t\t{\n\t\t\t\t...context,\n\t\t\t\tissuerWorkingKey: link.issuerWorkingKey,\n\t\t\t},\n\t\t);\n\t\tif (!revocation.ok) return revocation;\n\t}\n\treturn undefined;\n}\n\n/**\n * Whether `signer` is the issuer itself: the issuer certificate, or a\n * certificate carrying the bare trust anchor's name and key.\n */\nfunction isOcspIssuer(signer: ParsedCertificate, issuer: ResolvedOcspKey): boolean {\n\tif (issuer.kind === 'certificate') {\n\t\treturn isSameOcspCertificate(signer, issuer.certificate);\n\t}\n\treturn carriesTrustAnchorKey(signer, issuer.trustAnchor);\n}\n\n/**\n * Validates a delegated responder's certification path below `issuer`, which\n * starts from the issuer's working key (RFC 5280 §6.1.4 (e)), and returns the\n * parameters that path gives the responder's key.\n */\nasync function validateDelegatedResponderPath(\n\tinput: OcspValidationOptions,\n\tparsedResponse: ParsedOcspResponse,\n\tissuer: ResolvedOcspKey,\n\tsigner: ParsedCertificate,\n\tcontext: ResolvedOcspCallerVerification,\n): Promise<DelegatedResponderPath> {\n\tconst issuerWorkingKey = context.issuerWorkingKey;\n\tconst allowChainedResponderCertificate = input.allowChainedResponderCertificate === true;\n\tif (\n\t\t!allowChainedResponderCertificate &&\n\t\t!isDirectlyIssuedByOcspIssuer(signer, ocspKeyOf(issuer))\n\t) {\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(\n\t\t\t\t\tparsedResponse.certificates,\n\t\t\t\t\tsigner,\n\t\t\t\t\tocspCertificateOf(issuer),\n\t\t\t\t)\n\t\t\t: [],\n\t\t...delegatedPathStart(issuer, issuerWorkingKey),\n\t\t...(input.at !== undefined ? { at: input.at } : {}),\n\t\t...(input.signatureVerifiers !== undefined && {\n\t\t\tsignatureVerifiers: input.signatureVerifiers,\n\t\t}),\n\t\t...(context.distrustedSpkiSha256 !== undefined && {\n\t\t\tdistrustedSpkiSha256: context.distrustedSpkiSha256,\n\t\t}),\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\tconst [responderLink, ...caCertificates] = responderPathLinks(\n\t\tchain.value,\n\t\tissuer,\n\t\tissuerWorkingKey,\n\t);\n\treturn {\n\t\tok: true,\n\t\tparametersDer: pathWorkingKey(chain.value, 0).parametersDer,\n\t\tissuer: responderLink?.issuer ?? issuer,\n\t\tissuerWorkingKey: responderLink?.issuerWorkingKey ?? issuerWorkingKey,\n\t\tcaCertificates,\n\t};\n}\n\n/**\n * Each certificate of a delegated responder's validated path below the OCSP\n * issuer, with the next certificate as its issuer and the OCSP issuer above\n * the last.\n */\nfunction responderPathLinks(\n\tpath: CandidatePath,\n\tissuer: ResolvedOcspKey,\n\tissuerWorkingKey: WorkingPublicKey,\n): readonly ResponderPathLink[] {\n\tconst below = path.anchorCertificateInChain ? path.chain.slice(0, -1) : path.chain;\n\treturn below.map((certificate, index) => {\n\t\tconst next = path.chain[index + 1];\n\t\treturn next === undefined\n\t\t\t? { certificate, issuer, issuerWorkingKey }\n\t\t\t: {\n\t\t\t\t\tcertificate,\n\t\t\t\t\tissuer: { kind: 'certificate', certificate: next },\n\t\t\t\t\tissuerWorkingKey: pathWorkingKey(path, index + 1),\n\t\t\t\t};\n\t});\n}\n\n/**\n * Where a delegated responder's path starts: the issuer certificate as root,\n * or trust anchor information carrying the issuer's working key when the\n * issuer inherits its parameters or is a bare anchor.\n */\nfunction delegatedPathStart(\n\tissuer: ResolvedOcspKey,\n\tissuerWorkingKey: WorkingPublicKey,\n):\n\t| { readonly roots: readonly Uint8Array[] }\n\t| { readonly roots: readonly Uint8Array[]; readonly trustAnchors: readonly TrustAnchor[] } {\n\tif (issuer.kind === 'trust_anchor') {\n\t\treturn { roots: [], trustAnchors: [issuer.trustAnchor] };\n\t}\n\tconst own = certificateWorkingKey(issuer.certificate).parametersDer;\n\tconst working = issuerWorkingKey.parametersDer;\n\tif (working === undefined || (own !== undefined && sameDer(own, working))) {\n\t\treturn { roots: [issuer.certificate.der] };\n\t}\n\treturn {\n\t\troots: [],\n\t\ttrustAnchors: [withWorkingParameters(trustAnchorFromCertificate(issuer.certificate), working)],\n\t};\n}\n\nfunction sameDer(left: Uint8Array, right: Uint8Array): boolean {\n\treturn left.length === right.length && left.every((byte, index) => byte === right[index]);\n}\n\n/** The ocspSigning and revocation checks on a delegated responder whose path validated. */\nasync function validateDelegatedOcspResponder(\n\tinput: OcspValidationOptions,\n\tissuer: ResolvedOcspKey,\n\tsigner: ParsedCertificate,\n\tcontext: ResolvedOcspCallerVerification,\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\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(\n\t\tsigner,\n\t\tissuer,\n\t\tinput,\n\t\tcontext,\n\t);\n\treturn responderRevocation.ok ? undefined : responderRevocation;\n}\n\ninterface OcspFreshnessContext {\n\treadonly at: Date;\n\treadonly skew: number;\n\treadonly profile: NonNullable<ValidateOcspResponseInput['profile']>;\n}\n\n/** Checks response-level and per-certificate OCSP timestamps against the validation time. */\nasync function validateOcspResponseFreshness(\n\tparsedResponse: ParsedOcspResponse,\n\tissuer: OcspIssuerKey,\n\tcontext: OcspFreshnessContext,\n): Promise<ValidateOcspResponseFailureBranch | undefined> {\n\tif (\n\t\tparsedResponse.producedAt !== undefined &&\n\t\tparsedResponse.producedAt.getTime() - context.skew > context.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\tcontext,\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: OcspIssuerKey,\n\tcontext: OcspFreshnessContext,\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, context);\n}\n\nfunction validateOcspSingleResponseTimes(\n\tresponse: ParsedOcspSingleResponse,\n\tproducedAt: Date | undefined,\n\t{ at, skew, profile }: OcspFreshnessContext,\n): ValidateOcspResponseFailureBranch | undefined {\n\tif (profile === 'rfc9919' && response.nextUpdate === undefined) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'next_update_missing',\n\t\t\t'OCSP response omits nextUpdate, which the RFC 9919 profile requires',\n\t\t);\n\t}\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 (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateOcspResponseFailureResult('malformed', 'OCSP request input is malformed')\n\t\t\t: validateOcspResponseFailureResult(refusal.code, refusal.message);\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' | DecodeFailureCode,\n\tmessage: string,\n): ErrorResult<\n\t'signature_invalid' | DecodeFailureCode,\n\tRecord<never, never>,\n\tVerifyOcspResponseSignatureFailure\n> {\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 * An extension whose value is not the NULL that §4.2.2.2.1 requires does not count.\n */\nexport function hasOcspNoCheckExtension(certificate: OcspCertificateSource): boolean {\n\treturn carriesOcspNoCheck(normalizeCertificate(certificate));\n}\n\n/**\n * The extension that exempts a certificate from revocation checking (RFC 9608\n * §4): `'no_rev_avail'` for noRevAvail (RFC 9608 §2) or `'ocsp_nocheck'` for\n * id-pkix-ocsp-nocheck.\n */\nexport type RevocationSkipReason = 'no_rev_avail' | 'ocsp_nocheck';\n\n/** The RFC 9608 §4 exemption a certificate parsed from its signed DER carries. */\nexport function revocationSkipReasonOf(\n\tcertificate: ParsedCertificate,\n): RevocationSkipReason | undefined {\n\tif (certificate.noRevAvail === true) return 'no_rev_avail';\n\treturn carriesOcspNoCheck(certificate) ? 'ocsp_nocheck' : undefined;\n}\n\n/** Whether a parsed certificate carries `id-pkix-ocsp-nocheck` with its NULL value. */\nexport function carriesOcspNoCheck(certificate: ParsedCertificate): boolean {\n\treturn certificate.extensions.some(\n\t\t(extension) => extension.oid === OIDS.ocspNoCheck && extension.valueHex === '0500',\n\t);\n}\n\n/** The CRLs among `sources` that parse, split into complete and delta CRLs. */\nfunction partitionResponderCrls(sources: readonly CrlSource[]): {\n\treadonly complete: readonly ParsedCertificateRevocationList[];\n\treadonly delta: readonly ParsedCertificateRevocationList[];\n} {\n\tconst complete: ParsedCertificateRevocationList[] = [];\n\tconst delta: ParsedCertificateRevocationList[] = [];\n\tfor (const source of sources) {\n\t\tlet crl: ParsedCertificateRevocationList;\n\t\ttry {\n\t\t\tcrl = normalizeCrl(source);\n\t\t} catch {\n\t\t\tcontinue; // Unusable evidence — try remaining CRLs\n\t\t}\n\t\t(crl.baseCrlNumber === undefined ? complete : delta).push(crl);\n\t}\n\treturn { complete: distinctSignedCrls(complete), delta: distinctSignedCrls(delta) };\n}\n\nfunction responderCrlCheck(input: OcspValidationOptions): CrlCheckOptions {\n\treturn {\n\t\tat: input.at ?? new Date(),\n\t\t...(input.responderRevocationCrlMaxAgeMs === undefined\n\t\t\t? {}\n\t\t\t: { maxAgeMs: input.responderRevocationCrlMaxAgeMs }),\n\t\t...(input.clockSkewMs === undefined ? {} : { clockSkewMs: input.clockSkewMs }),\n\t\t...(input.responderRevocationUnrecognizedReasonCode === undefined\n\t\t\t? {}\n\t\t\t: { unrecognizedReasonCode: input.responderRevocationUnrecognizedReasonCode }),\n\t\t...(input.responderRevocationUnreadSupersededDeltaCrls === undefined\n\t\t\t? {}\n\t\t\t: { unreadSupersededDeltaCrls: input.responderRevocationUnreadSupersededDeltaCrls }),\n\t};\n}\n\n/** The responder revocation outcome that `policy` and the responder's own extensions settle before any CRL is read. */\nfunction responderRevocationSettledWithoutCrls(\n\tsigner: ParsedCertificate,\n\tpolicy: OcspResponderRevocationPolicy,\n): { readonly ok: true } | ReturnType<typeof validateOcspResponseFailureResult> | undefined {\n\tif (policy === 'skip') {\n\t\treturn { ok: true };\n\t}\n\tconst skipReason = revocationSkipReasonOf(signer);\n\tif (skipReason === 'no_rev_avail') {\n\t\treturn policy === 'require-evidence'\n\t\t\t? validateOcspResponseFailureResult(\n\t\t\t\t\t'responder_revocation_unknown',\n\t\t\t\t\t'Delegated OCSP responder carries noRevAvail, which no CRL lists',\n\t\t\t\t)\n\t\t\t: { ok: true };\n\t}\n\treturn skipReason === 'ocsp_nocheck' && policy !== 'require-evidence' ? { ok: true } : undefined;\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: ResolvedOcspKey,\n\tinput: OcspValidationOptions,\n\tcontext: ResolvedOcspCallerVerification,\n): Promise<{ readonly ok: true } | ReturnType<typeof validateOcspResponseFailureResult>> {\n\tconst policy = input.responderRevocationPolicy ?? 'nocheck-or-evidence';\n\tconst settled = responderRevocationSettledWithoutCrls(signer, policy);\n\tif (settled !== undefined) {\n\t\treturn settled;\n\t}\n\tconst crlCheck = responderCrlCheck(input);\n\tconst verification = {\n\t\tverifiers: context.verifiers,\n\t\tworkingParameters: { parametersDer: context.issuerWorkingKey.parametersDer },\n\t};\n\tconst crls = partitionResponderCrls(input.responderRevocationCrls ?? []);\n\tconst coveredReasons = new Set<string>();\n\tlet sawUnrecognizedReason = false;\n\tlet sawUnsettledDelta = false;\n\tfor (const crl of crls.complete) {\n\t\tconst outcome = await checkCertificateRevocationAgainstCrlsBy(\n\t\t\tsigner,\n\t\t\tcrl,\n\t\t\tcrls.delta,\n\t\t\tissuer,\n\t\t\tcrlCheck,\n\t\t\tverification,\n\t\t\t[context.deltaBudget],\n\t\t);\n\t\tif (outcome.kind === 'unsettled') {\n\t\t\tsawUnsettledDelta = true;\n\t\t\tcontinue;\n\t\t}\n\t\tconst result = outcome.result;\n\t\tif (!result.ok) {\n\t\t\tsawUnrecognizedReason ||= result.code === 'reason_code_unrecognized';\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\tfor (const reason of result.value.coveredReasons) {\n\t\t\tcoveredReasons.add(reason);\n\t\t}\n\t}\n\tif (sawUnrecognizedReason) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'responder_revocation_unknown',\n\t\t\t'Delegated OCSP responder carries an unrecognized CRL reason code',\n\t\t);\n\t}\n\tif (sawUnsettledDelta) {\n\t\treturn validateOcspResponseFailureResult(\n\t\t\t'responder_revocation_unknown',\n\t\t\t'A delta CRL for the delegated OCSP responder could not settle its status',\n\t\t);\n\t}\n\t// A definitive good requires every revocation reason to be covered; a single\n\t// reason-scoped CRL does not prove the responder unrevoked.\n\tif (\n\t\tcoversAllDistributionPointReasons(coveredReasons) ||\n\t\t(policy === 'honor-nocheck' && !hasCriticalCrlDistributionPoints(signer))\n\t) {\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\nfunction hasCriticalCrlDistributionPoints(certificate: ParsedCertificate): boolean {\n\treturn certificate.extensions.some(\n\t\t(extension) => extension.oid === OIDS.cRLDistributionPoints && extension.critical,\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: OcspIssuerKey,\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: OcspIssuerKey,\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(signer: ParsedCertificate, issuer: OcspIssuerKey): 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 | undefined,\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 (\n\t\t\tisSameOcspCertificate(certificate, signer) ||\n\t\t\t(issuer !== undefined && isSameOcspCertificate(certificate, issuer))\n\t\t) {\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: OcspIssuerKey,\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\tgeneralizedTime(input.thisUpdate ?? new Date()),\n\t\t...(input.nextUpdate === undefined\n\t\t\t? []\n\t\t\t: [explicitContext(0, generalizedTime(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[] = [\n\t\t\t\tgeneralizedTime(input.revokedAt ?? input.thisUpdate ?? new Date()),\n\t\t\t];\n\t\t\tif (input.revocationReasonCode !== undefined) {\n\t\t\t\trevokedFields.push(explicitContext(0, enumeratedFromNumber(input.revocationReasonCode)));\n\t\t\t}\n\t\t\treturn tlv(0xa1, concatBytes(revokedFields));\n\t\t}\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = input;\n\t\t\tthrow new Error(`Unhandled CertStatus type: ${String(_exhaustive)}`);\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\treturn {\n\t\tcertId: parseOcspCertId(source.slice(certId.start - certId.headerLength, certId.end)),\n\t\tthisUpdate: parseTime(thisUpdate),\n\t\t...parseOcspSingleResponseNextUpdate(source, nextUpdateElement),\n\t\t...parseOcspCertStatusFields(source, certStatus),\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): ParsedOcspCertStatus {\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?: bigint } {\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: decodeNonNegativeIntegerBigInt(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 0xa2: {\n\t\t\tconst inner = childrenOf(source, element);\n\t\t\tif (inner.length !== 1) {\n\t\t\t\tthrow new Error('ResponderID byKey must wrap exactly one OCTET STRING');\n\t\t\t}\n\t\t\tconst keyHash = requireElement(inner[0], 'ResponderID byKey');\n\t\t\tif (keyHash.tag !== 0x04) {\n\t\t\t\tthrow new Error('ResponderID byKey must wrap an OCTET STRING');\n\t\t\t}\n\t\t\t// KeyHash is the SHA-1 hash of the responder's public key (RFC 6960 §4.2.1).\n\t\t\tif (keyHash.value.length !== 20) {\n\t\t\t\tthrow new Error('ResponderID byKey must be a 20-byte SHA-1 KeyHash');\n\t\t\t}\n\t\t\treturn { type: 'byKeyHash', keyHashHex: toHex(keyHash.value) };\n\t\t}\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 a directory attribute type OID (X.520 `id-at` arc plus the legacy PKCS #9 emailAddress) 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\t// certs [0] EXPLICIT SEQUENCE OF Certificate (RFC 6960 §4.2.1): the single\n\t// child of [0] is the SEQUENCE whose elements are the certificates.\n\tconst sequenceElement = childrenOf(source, element)[0];\n\tif (sequenceElement === undefined || sequenceElement.tag !== 0x30) {\n\t\tthrow new Error('Malformed BasicOCSPResponse certs');\n\t}\n\tlet offset = sequenceElement.start;\n\twhile (offset < sequenceElement.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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2VA,SAAS,sBAAsBiE,GAA4BC,GAAwB;CAClFZ,EAAmBW,GAAMC,CAAO;AACjC;AAEA,SAAS,eAAeC,GAAwBC,GAAqB;CAChED,MAAS,KAAA,KAAa,OAAO,MAAMA,EAAK,QAAQ,CAAC,KACpD,sBAAsB,gBAAgB,GAAGC,EAAM,sBAAsB;AAEvE;AAEA,SAAS,+BAA+BH,GAAgC;CACnEA,MAAS,KAAA,KAAa,EAAE,OAAO,cAAcA,CAAI,KAAKA,KAAQ,MACjE,sBACC,kCACA,qDACD;AAEF;AA2SA,SAAS,UAAUI,GAA0C;CAC5D,OAAOA,EAAS,SAAS,gBAAgBA,EAAS,cAAcA,EAAS;AAC1E;;AAGA,SAAS,gBAAgBC,GAAwC;CAChE,OAAOA,EAAO,SAAS,gBACpBA,EAAO,cACP;EAAE,GAAGA,EAAO;EAAa,SAASA,EAAO;CAAkB;AAC/D;AAEA,SAAS,kBAAkBD,GAA0D;CACpF,OAAOA,EAAS,SAAS,gBAAgBA,EAAS,cAAc,KAAA;AACjE;;;;;;;;;;;;;;;;;AA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