micro509 0.19.0 → 0.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -1
- package/dist/index.d.ts +2 -2
- package/dist/internal/crypto/hash.js +64 -64
- package/dist/internal/crypto/pbes2.js +3 -3
- package/dist/internal/shared/dn.js +1 -1
- package/dist/internal/shared/idna-tables.js +3 -3
- package/dist/internal/shared/punycode.js +1 -1
- package/dist/kdf/argon2-portable.js +1 -1
- package/dist/kdf/argon2.js +2 -2
- package/dist/keys/keys.d.ts +7 -2
- package/dist/keys/keys.js +10 -6
- package/dist/keys/keys.js.map +1 -1
- package/dist/pem/pem.d.ts +20 -7
- package/dist/pem/pem.js +24 -20
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.d.ts +2 -2
- package/dist/pkcs/pkcs12-mac.js +2 -2
- package/dist/revocation/crl.js +46 -46
- package/dist/revocation/crl.js.map +1 -1
- package/dist/verify/verify.js +0 -4
- package/dist/verify/verify.js.map +1 -1
- package/dist/x509/extensions.js +1 -1
- package/dist/x509/name-text.js +1 -1
- package/dist/x509/name-text.js.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crl.js","names":["_exhaustive","childrenOf","decodeBoolean","decodeIntegerMagnitude","decodeIntegerNumber","decodeNonNegativeIntegerBigInt","decodeObjectIdentifier","decodeString","hexToBytes","parseTime","requireElement","signatureBits","toHex","decodeFailureResult","decodeRefusalOf","rethrowDecodeRefusal","bitString","concatBytes","explicitContext","generalizedTime","implicitConstructedContext","implicitPrimitiveContext","integer","integerFromNumber","optionalBytesEqual","readElement","readRootElement","readSequenceChildren","sequence","time","tlv","OIDS","describeSignatureAlgorithm","NO_CALLER_VERIFICATION","callerVerification","verifySignedDataDetailed","encodeAlgorithmIdentifier","getSignatureAlgorithm","signBytes","base64Encode","compareDistinguishedNames","compareRelativeDistinguishedNames","encodeDistributionPointReasonFlagsContent","parseDistributionPointReasonFlagsContent","parseGeneralName","parseGeneralNames","parsePresentedSrvName","pemDecodeOrThrow","pemEncode","nameFieldKeyFromOid","DECODE_REFUSAL_CODES","failureResult","rethrowIfInvariant","successResult","throwMicro509Error","encodeCrlDistributionPoints","encodeExtension","encodeSubjectAltName","issuerKeyIdentifier","encodeName","encodeRelativeDistinguishedName","isNameInputEmpty","parseCertificateDerOrThrow","parseCertificateFromSource","REVOCATION_REASON_CODES","ALL_DISTRIBUTION_POINT_REASONS","reasons","set","reason","input","issuerCertificate","crlNumber","baseCrlNumber","signatureAlgorithm","thisUpdate","nextUpdate","entry","extensions","revoked","revokedSequence","tbsCertList","signatureValue","der","top","signedFields","parsedSignatureAlgorithm","pem","error","crl","options","verification","parsedCrl","issuer","refusal","verifiedResult","authority","authenticated","freshnessFailure","resolved","keyUsageFailure","maxAgeMs","clockSkewMs","at","skew","deltaCrl","certificate","outcome","complete","completeCrl","_deltaCrl","completeOnly","alone","deltaResult","applicability","deltaApplicability","completeRevoked","deltaRevoked","deltaLookup","crls","seen","key","baseCrl","deltaCrls","left","right","byTime","leftNumber","rightNumber","newer","older","budgets","candidates","search","index","unreadMaySettle","aloneResult","budget","result","distributionPoint","issuingDistributionPoint","distributionPointReasons","crlReasons","compatibilityFailure","stale","lookup","rejected","settled","code","message","details","value","certificateSerialNumber","serialNumberHex","effectiveIssuer","sawUnsupportedIssuer","matchedEntry","issuerMatch","allowDeltaCrl","isIndirectCrl","isCaCertificate","distributionPoints","scanResult","coveredReasons","failures","sawMatch","failure","issuerResult","crlIssuerNames","name","sawUnsupportedName","generalName","deltaThisUpdate","completeEntry","deltaEntry","unrecognizedReasonCode","certificatePoint","crlPoint","crlIssuer","certificateCrlIssuer","leftName","rightName","resolvedDnHex","issuerName","relativeName","rdnDerParts","rdn","relativeNameRdnDer","implicitTaggedDer","element","matched","found","certificateReasons","leftParts","rightParts","component","leftAt","rightAt","normalizedLeft","URI_DEFAULT_PORT_BY_SCHEME","url","host","hostname","probe","PERCENT_TRIPLET","triplet","freshestCrlDistributionPoints","entryDer","fields","seenOids","extension","parts","oid","critical","valueElement","enumerated","reasonCode","generalNames","valueDer","sequenceElement","child","userCerts","caCerts","attributeCerts","IDP_SCOPE_CONFLICT","flags","existing","fieldName","elements","children","distributionPointName","fullName","attributes","values","attributeSequence","fieldKey","fieldValue","attribute","source","field","hex","magnitude","first","date","relativeNameElement","names","derHex","rdns","allAttributes","setElement","rdnAttributes","rdnValues","attrSequence","oidElement","bytes","parsed","state","label","signature","parameters","tbsCertListDer","tbsChildren","versionField","version","signatureElement","issuerElement","thisUpdateElement","cursor","maybeNextUpdate","maybeRevoked","revokedCertificates","maybeExtensions","parsedExtensions","firstChild","serialNumber","entryExtensions","parsedEntryExtensions","extensionSequence","authorityKeyIdentifier"],"sources":["../../src/revocation/crl.ts"],"sourcesContent":["/**\n * Full CRL lifecycle: create, parse, verify, validate, and revocation check.\n *\n * Supports complete and delta CRLs, issuing distribution point scoping,\n * indirect CRL processing, per-entry reason codes, and invalidity dates.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeBoolean,\n\tdecodeIntegerMagnitude,\n\tdecodeIntegerNumber,\n\tdecodeNonNegativeIntegerBigInt,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\thexToBytes,\n\tparseTime,\n\trequireElement,\n\tsignatureBits,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tDECODE_REFUSAL_CODES,\n\tdecodeFailureResult,\n\tdecodeRefusalOf,\n\trethrowDecodeRefusal,\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\texplicitContext,\n\tgeneralizedTime,\n\timplicitConstructedContext,\n\timplicitPrimitiveContext,\n\tinteger,\n\tintegerFromNumber,\n\toptionalBytesEqual,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\ttime,\n\ttlv,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { describeSignatureAlgorithm } from '#micro509/internal/crypto/algorithm-names';\nimport type { CallerVerification, SignatureVerifiers } from '#micro509/internal/crypto/sig-verify';\nimport {\n\tcallerVerification,\n\tNO_CALLER_VERIFICATION,\n\tverifySignedDataDetailed,\n} from '#micro509/internal/crypto/sig-verify';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport {\n\tcompareDistinguishedNames,\n\tcompareRelativeDistinguishedNames,\n} from '#micro509/internal/shared/dn';\nimport type { ParsedBitFlags } from '#micro509/internal/x509/extension-bits';\nimport {\n\tencodeDistributionPointReasonFlagsContent,\n\tparseDistributionPointReasonFlagsContent,\n} from '#micro509/internal/x509/extension-bits';\nimport { parseGeneralName, parseGeneralNames } from '#micro509/internal/x509/general-name';\nimport { parsePresentedSrvName } from '#micro509/internal/x509/general-name-profile';\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 { TrustAnchor } from '#micro509/verify/verify';\nimport type {\n\tDistributionPoint,\n\tDistributionPointReason,\n\tGeneralName,\n\tIssuingDistributionPoint,\n} from '#micro509/x509/extensions';\nimport {\n\tencodeCrlDistributionPoints,\n\tencodeExtension,\n\tencodeSubjectAltName,\n\tissuerKeyIdentifier,\n} from '#micro509/x509/extensions';\nimport type { NameFieldKey, NameInput } from '#micro509/x509/name';\nimport {\n\tencodeName,\n\tencodeRelativeDistinguishedName,\n\tisNameInputEmpty,\n\tnameFieldKeyFromOid,\n} from '#micro509/x509/name';\nimport type {\n\tParsedCertificate,\n\tParsedDistributionPoint,\n\tParsedDistributionPointName,\n\tParsedIssuingDistributionPoint,\n\tParsedIssuingDistributionPointScope,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow, parseCertificateFromSource } from '#micro509/x509/parse';\n\n/**\n * Single revoked certificate entry for {@linkcode createCertificateRevocationList}.\n */\nexport interface RevokedCertificateInput {\n\t/** DER-encoded certificate serial number to revoke. */\n\treadonly serialNumber: Uint8Array;\n\t/** When the certificate was revoked. Defaults to `thisUpdate` of the CRL. */\n\treadonly revocationDate?: Date;\n\t/** RFC 5280 CRLReason code. Omit for `unspecified`. */\n\treadonly reasonCode?: RevocationReason;\n\t/** When the key or certificate became suspect — may predate `revocationDate`. */\n\treadonly invalidityDate?: Date;\n}\n\n/**\n * RFC 5280 [§5.3.1](https://datatracker.ietf.org/doc/html/rfc5280#section-5.3.1) CRLReason code values.\n *\n * `removeFromCRL` is used in delta CRLs to un-hold a certificate.\n */\nexport type RevocationReason =\n\t| 'unspecified'\n\t| 'keyCompromise'\n\t| 'cACompromise'\n\t| 'affiliationChanged'\n\t| 'superseded'\n\t| 'cessationOfOperation'\n\t| 'certificateHold'\n\t| 'removeFromCRL'\n\t| 'privilegeWithdrawn'\n\t| 'aACompromise';\n\n/**\n * A CRLReason code outside the RFC 5280 §5.3.1 enumeration, such as the unused\n * value 7 or X.509 (10/2019) `weakAlgorithmOrKey (11)`.\n */\nexport interface UnrecognizedRevocationReason {\n\t/** Discriminator for a code with no {@linkcode RevocationReason} name. */\n\treadonly type: 'unrecognized';\n\t/** The decoded ENUMERATED value. */\n\treadonly code: bigint;\n}\n\n/** A decoded CRLReason: a named {@linkcode RevocationReason} or an {@linkcode UnrecognizedRevocationReason}. */\nexport type ParsedRevocationReason = RevocationReason | UnrecognizedRevocationReason;\n\n/**\n * Treatment of revocation evidence whose CRLReason is an\n * {@linkcode UnrecognizedRevocationReason}. RFC 5280 §5.3.1 and Appendix B do\n * not say what a relying party does with such a code.\n *\n * - `'revoked'`: the certificate is revoked, with the code reported (default).\n * A certificate that a CRL or OCSP response revokes is never reported `good`.\n * - `'reject'`: the evidence cannot settle the certificate's status.\n */\nexport type UnrecognizedReasonCodePolicy = 'revoked' | 'reject';\n\n/**\n * Treatment of delta CRLs that the attempt limits leave unread when a delta\n * CRL already read supersedes them by both `thisUpdate` and CRL number. RFC\n * 5280 §5.2.4 has a relying party use the most recent delta CRL, and §3.3 and\n * §5.3.1 keep a lasting revocation listed in every later CRL, so reading the\n * older ones is a check on the issuer's consistency.\n *\n * - `'indeterminate'`: any unread candidate leaves the status\n * `delta_crl_retry_limit_exceeded`, unless a revocation no delta CRL can\n * remove already settled it (default).\n * - `'ignore'`: an unread candidate does not count when the delta CRL that\n * settled the status as good supersedes it, or, without a good status, when\n * it is not current and a delta CRL read supersedes it.\n */\nexport type SupersededDeltaCrlPolicy = 'indeterminate' | 'ignore';\n\n/**\n * Input for {@linkcode createCertificateRevocationList}.\n */\nexport interface CreateCertificateRevocationListInput {\n\t/** Distinguished name of the CRL issuer (typically the signing CA). */\n\treadonly issuer: NameInput;\n\t/** Private key used to sign the CRL. Algorithm is inferred from the key. */\n\treadonly signerPrivateKey: CryptoKey;\n\t/**\n\t * Certificate of the CRL issuer. Its subject key identifier becomes the\n\t * Authority Key Identifier extension (RFC 5280 §5.2.1). An issuer\n\t * certificate without one yields a key identifier derived from its public key.\n\t */\n\treadonly issuerCertificate: CrlCertificateSource;\n\t/** Issuance timestamp. Defaults to `new Date()`. */\n\treadonly thisUpdate?: Date;\n\t/** Date by which the next CRL will be issued. Must be at least one second later than `thisUpdate`. */\n\treadonly nextUpdate: Date;\n\t/** Certificates to list as revoked in this CRL. */\n\treadonly revokedCertificates?: readonly RevokedCertificateInput[];\n\t/**\n\t * Monotonically-increasing CRL sequence number (CRLNumber extension, RFC 5280\n\t * §5.2.3): non-negative and at most 20 octets encoded. Pass a `bigint` above\n\t * `Number.MAX_SAFE_INTEGER`.\n\t */\n\treadonly crlNumber: number | bigint;\n\t/** If set, marks this CRL as a delta CRL referencing the given base CRL number, bounded like {@linkcode crlNumber}. */\n\treadonly baseCrlNumber?: number | bigint;\n\t/** Issuing distribution point extension — scopes this CRL to a subset of certificates. */\n\treadonly issuingDistributionPoint?: IssuingDistributionPoint;\n\t/** Freshest CRL distribution points — tells relying parties where to find delta CRLs. */\n\treadonly freshestCrlDistributionPoints?: readonly DistributionPoint[];\n}\n\n/**\n * Encoded CRL in multiple serialisation formats, returned by {@linkcode createCertificateRevocationList}.\n */\nexport interface CertificateRevocationListMaterial {\n\t/** Raw DER bytes of the signed CRL. */\n\treadonly der: Uint8Array;\n\t/** PEM-encoded CRL (`-----BEGIN X509 CRL-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armour). */\n\treadonly base64: string;\n}\n\n/**\n * A single revoked-certificate entry decoded from a CRL.\n */\nexport interface ParsedRevokedCertificate {\n\t/** Hex-encoded serial number of the revoked certificate. */\n\treadonly serialNumberHex: string;\n\t/** When the CA declared this certificate revoked. */\n\treadonly revocationDate: Date;\n\t/** RFC 5280 CRLReason, if the entry carries one. */\n\treadonly reasonCode?: ParsedRevocationReason;\n\t/** When the key or certificate actually became suspect, if present. */\n\treadonly invalidityDate?: Date;\n\t/** Indirect-CRL certificate issuer override (RFC 5280 §5.3.3). */\n\treadonly certificateIssuer?: readonly GeneralName[];\n}\n\n/**\n * Decoded X.509 CRL, returned by {@linkcode parseCertificateRevocationListDer}\n * and {@linkcode parseCertificateRevocationListPem}.\n */\nexport interface ParsedCertificateRevocationList {\n\t/** Original DER bytes when this object came from {@linkcode parseCertificateRevocationListDer} or PEM parsing. */\n\treadonly der?: Uint8Array;\n\t/** CRL version (1 = v1, 2 = v2 with extensions). */\n\treadonly version: number;\n\t/** DER-encoded TBSCertList — the signed payload for signature verification. */\n\treadonly tbsCertListDer: Uint8Array;\n\t/** Signature bytes: the `signatureValue` 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/** CRL issuer distinguished name. */\n\treadonly issuer: ParsedName;\n\t/** Issue date of this CRL. */\n\treadonly thisUpdate: Date;\n\t/** Date by which the next CRL will be issued. Absent when the encoded CRL omits it. */\n\treadonly nextUpdate?: Date;\n\t/** OID of the algorithm used to sign this CRL. */\n\treadonly signatureAlgorithmOid: string;\n\t/** Human-readable signature algorithm name (e.g. `\"ECDSA with SHA-256\"`). */\n\treadonly signatureAlgorithmName: string;\n\t/** DER-encoded signature algorithm parameters (e.g. DER NULL for RSA PKCS#1 v1.5). */\n\treadonly signatureAlgorithmParametersDer?: Uint8Array;\n\t/** OID of the issuer's public key algorithm, when available. */\n\treadonly issuerPublicKeyAlgorithmOid?: string;\n\t/** OID of the issuer's public key parameters (e.g. named curve), when available. */\n\treadonly issuerPublicKeyParametersOid?: string;\n\t/** Hex-encoded Authority Key Identifier, if the extension is present. */\n\treadonly authorityKeyIdentifier?: string;\n\t/** CRLNumber extension value — monotonically increasing sequence number. */\n\treadonly crlNumber?: bigint;\n\t/** Delta CRL indicator — present only on delta CRLs, referencing the base CRL number. */\n\treadonly baseCrlNumber?: bigint;\n\t/** Issuing distribution point extension — scopes this CRL to a certificate subset. */\n\treadonly issuingDistributionPoint?: ParsedIssuingDistributionPoint;\n\t/** Freshest CRL extension — points to delta CRL locations. */\n\treadonly freshestCrlDistributionPoints?: readonly ParsedDistributionPoint[];\n\t/** All revoked certificate entries (empty array if none). */\n\treadonly revokedCertificates: readonly ParsedRevokedCertificate[];\n}\n\n/** RFC 5280 §5.3.1 CRLReason integer codes, keyed by reason name. */\nconst REVOCATION_REASON_CODES: Record<RevocationReason, number> = {\n\tunspecified: 0,\n\tkeyCompromise: 1,\n\tcACompromise: 2,\n\taffiliationChanged: 3,\n\tsuperseded: 4,\n\tcessationOfOperation: 5,\n\tcertificateHold: 6,\n\tremoveFromCRL: 8,\n\tprivilegeWithdrawn: 9,\n\taACompromise: 10,\n};\n\n/** PEM string, DER bytes, or already-parsed CRL. */\nexport type CrlSource = string | Uint8Array | ParsedCertificateRevocationList;\n/** PEM string, DER bytes, or already-parsed certificate. */\nexport type CrlCertificateSource = string | Uint8Array | ParsedCertificate;\n\n/**\n * Failure detail when CRL signature verification fails. `unsupported` and\n * `limit_exceeded` report a CRL or issuer certificate micro509 cannot decode\n * (see {@linkcode ParseCertificateRevocationListErrorCode}).\n */\nexport interface VerifyCertificateRevocationListSignatureFailure\n\textends Micro509Error<'signature_invalid' | DecodeFailureCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Result of {@linkcode verifyCertificateRevocationListSignature}.\n *\n * On success, `value` is the parsed CRL whose signature has been verified.\n */\nexport type VerifyCertificateRevocationListSignatureResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** Parsed CRL with a verified signature. */\n\t\t\treadonly value: ParsedCertificateRevocationList;\n\t }\n\t| ErrorResult<\n\t\t\t'signature_invalid' | DecodeFailureCode,\n\t\t\tRecord<never, never>,\n\t\t\tVerifyCertificateRevocationListSignatureFailure\n\t >;\n\n/** Options for {@linkcode verifyCertificateRevocationListSignature}. */\nexport interface VerifyCertificateRevocationListSignatureOptions {\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 the CRL signature would otherwise use unsupported algorithm\n\t * parameters, with the parameters in the issuer certificate. A key that\n\t * micro509 verifies natively, a key that is no OID, or a value that is no\n\t * function throws `RangeError`.\n\t */\n\treadonly signatureVerifiers?: SignatureVerifiers;\n}\n\n/**\n * Input for {@linkcode validateCertificateRevocationList}.\n */\nexport interface ValidateCertificateRevocationListInput {\n\t/** The CRL to validate. */\n\treadonly crl: CrlSource;\n\t/** Certificate of the CA that should have signed the CRL. */\n\treadonly issuerCertificate: CrlCertificateSource;\n\t/** Evaluation time for freshness checks. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/**\n\t * Tolerance in milliseconds for clock skew when checking `thisUpdate` and\n\t * `nextUpdate`. It also widens `maxAgeMs` by the same amount. Throws\n\t * `RangeError` when negative or not finite.\n\t */\n\treadonly clockSkewMs?: number;\n\t/**\n\t * Maximum age of `thisUpdate` at `at`, in milliseconds. A CRL older than\n\t * this fails with `stale_crl` even when `nextUpdate` is absent or later.\n\t * Unbounded by default, in which case a CRL without `nextUpdate` fails with\n\t * `stale_crl`. RFC 5280 §3.3 leaves the required recency of revocation data\n\t * to local policy. {@linkcode checkCertificateRevocationAgainstCrl} still\n\t * reports a revocation such a CRL lists with a reason other than\n\t * certificateHold, for a certificate that has not expired (RFC 5280 §5.3.1).\n\t */\n\treadonly maxAgeMs?: number;\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 the CRL signature would otherwise use unsupported algorithm\n\t * parameters, with the parameters in the issuer certificate. A key that\n\t * micro509 verifies natively, a key that is no OID, or a value that is no\n\t * function throws `RangeError`.\n\t */\n\treadonly signatureVerifiers?: SignatureVerifiers;\n}\n\n/**\n * Failure detail for {@linkcode validateCertificateRevocationList}.\n *\n * Possible codes: `signature_invalid`, `issuer_mismatch`, `stale_crl`, `crl_sign_not_permitted`,\n * and `unsupported` or `limit_exceeded` for a CRL or issuer certificate micro509 cannot decode.\n */\nexport interface ValidateCertificateRevocationListFailure\n\textends Micro509Error<\n\t\t| 'signature_invalid'\n\t\t| 'issuer_mismatch'\n\t\t| 'stale_crl'\n\t\t| 'crl_sign_not_permitted'\n\t\t| DecodeFailureCode\n\t> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Result of {@linkcode validateCertificateRevocationList}.\n *\n * On success, the CRL has passed signature, issuer, key-usage, and freshness checks.\n */\nexport type ValidateCertificateRevocationListResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** Validated and parsed CRL. */\n\t\t\treadonly value: ParsedCertificateRevocationList;\n\t }\n\t| ErrorResult<\n\t\t\t| 'signature_invalid'\n\t\t\t| 'issuer_mismatch'\n\t\t\t| 'stale_crl'\n\t\t\t| 'crl_sign_not_permitted'\n\t\t\t| DecodeFailureCode,\n\t\t\tRecord<never, never>,\n\t\t\tValidateCertificateRevocationListFailure\n\t >;\n\n/**\n * Input for {@linkcode checkCertificateRevocationAgainstCrl}.\n */\nexport interface CheckCertificateRevocationAgainstCrlInput {\n\t/** Certificate whose revocation status to check. */\n\treadonly certificate: CrlCertificateSource;\n\t/** Issuer of `certificate` — also expected signer of the CRL. */\n\treadonly issuerCertificate: CrlCertificateSource;\n\t/** Complete (base) CRL to check against. */\n\treadonly crl: CrlSource;\n\t/**\n\t * Optional delta CRL for more recent revocation information. With a delta\n\t * CRL, the freshness checks and `maxAgeMs` apply to the delta CRL alone,\n\t * whose `thisUpdate` and `nextUpdate` the constructed CRL takes\n\t * (RFC 5280 §5.2.4, §6.3.3(a)(1)(i)). A delta CRL without `nextUpdate` is\n\t * never current and fails with `stale_crl`.\n\t */\n\treadonly deltaCrl?: CrlSource;\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/**\n\t * Clock-skew tolerance in milliseconds for freshness checks. It also widens\n\t * `maxAgeMs`. Throws `RangeError` when negative or not finite.\n\t */\n\treadonly clockSkewMs?: number;\n\t/** Maximum age of each CRL's `thisUpdate` in milliseconds. See {@linkcode ValidateCertificateRevocationListInput.maxAgeMs}. */\n\treadonly maxAgeMs?: number;\n\t/**\n\t * Treatment of a revoked entry whose CRLReason is unrecognized. `'reject'`\n\t * fails the check with `reason_code_unrecognized`. Defaults to `'revoked'`.\n\t */\n\treadonly unrecognizedReasonCode?: UnrecognizedReasonCodePolicy;\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 the CRL signature would otherwise use unsupported algorithm\n\t * parameters, with the parameters in the issuer certificate. A key that\n\t * micro509 verifies natively, a key that is no OID, or a value that is no\n\t * function throws `RangeError`.\n\t */\n\treadonly signatureVerifiers?: SignatureVerifiers;\n}\n\n/** Error codes that {@linkcode checkCertificateRevocationAgainstCrl} may return. */\nexport type CheckCertificateRevocationAgainstCrlErrorCode =\n\t| 'signature_invalid'\n\t| 'issuer_mismatch'\n\t| 'stale_crl'\n\t| 'crl_sign_not_permitted'\n\t| 'non_applicable'\n\t| 'reason_code_unrecognized'\n\t| DecodeFailureCode;\n\n/** Structured reason why a CRL was deemed non-applicable to a given certificate. */\nexport type CrlApplicabilityFailureReason =\n\t| 'certificate_scope_mismatch'\n\t| 'delta_crl_incompatible'\n\t| 'unsupported_delta_crl'\n\t| 'distribution_point_mismatch'\n\t| 'unsupported_indirect_crl'\n\t| 'issuer_mismatch'\n\t| 'reasons_mismatch';\n\n/** Internal result of looking up a serial number in a CRL's revoked entries. */\ntype RevokedCertificateLookupResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** Matching revoked entry, if found. */\n\t\t\treadonly entry?: ParsedRevokedCertificate;\n\t }\n\t| ErrorResult<\n\t\t\tCheckCertificateRevocationAgainstCrlErrorCode,\n\t\t\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\t\t\tCheckCertificateRevocationAgainstCrlFailure\n\t >;\n\n/** Structured details attached to a {@linkcode CheckCertificateRevocationAgainstCrlFailure}. */\nexport interface CheckCertificateRevocationAgainstCrlFailureDetails {\n\t/** Why the CRL was non-applicable, when the error code is `non_applicable`. */\n\treadonly reason?: CrlApplicabilityFailureReason;\n}\n\n/** Failure detail for {@linkcode checkCertificateRevocationAgainstCrl}. */\nexport interface CheckCertificateRevocationAgainstCrlFailure\n\textends Micro509Error<\n\t\tCheckCertificateRevocationAgainstCrlErrorCode,\n\t\tCheckCertificateRevocationAgainstCrlFailureDetails\n\t> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success value when the certificate is not found in the CRL. */\nexport interface CheckCertificateRevocationAgainstCrlGoodValue {\n\t/** Certificate is not revoked. */\n\treadonly status: 'good';\n\t/** The validated CRL that was checked. */\n\treadonly crl: ParsedCertificateRevocationList;\n\t/**\n\t * Revocation reasons this check covered, the RFC 5280 §6.3.3 (d)\n\t * interim_reasons_mask: the matched distribution point's reasons intersected\n\t * with the CRL's `onlySomeReasons`, either alone when the other is absent,\n\t * or every reason when both are.\n\t */\n\treadonly coveredReasons: readonly DistributionPointReason[];\n}\n\n/** Success value when the certificate is found as revoked in the CRL. */\nexport interface CheckCertificateRevocationAgainstCrlRevokedValue {\n\t/** Certificate is revoked. */\n\treadonly status: 'revoked';\n\t/** The validated CRL that contained the revocation entry. */\n\treadonly crl: ParsedCertificateRevocationList;\n\t/** When the CA declared this certificate revoked. */\n\treadonly revocationDate: Date;\n\t/** CRLReason from the entry, if present. */\n\treadonly reasonCode?: ParsedRevocationReason;\n}\n\n/** Discriminated union of `good` and `revoked` outcomes. */\nexport type CheckCertificateRevocationAgainstCrlValue =\n\t| CheckCertificateRevocationAgainstCrlGoodValue\n\t| CheckCertificateRevocationAgainstCrlRevokedValue;\n\n/**\n * Result of {@linkcode checkCertificateRevocationAgainstCrl}.\n *\n * On success `value.status` is `'good'` or `'revoked'`.\n * On failure the CRL could not be validated or was non-applicable.\n */\nexport type CheckCertificateRevocationAgainstCrlResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly value: CheckCertificateRevocationAgainstCrlValue;\n\t }\n\t| ErrorResult<\n\t\t\tCheckCertificateRevocationAgainstCrlErrorCode,\n\t\t\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\t\t\tCheckCertificateRevocationAgainstCrlFailure\n\t >;\n\ntype CrlApplicabilityFailure = ErrorResult<\n\tCheckCertificateRevocationAgainstCrlErrorCode,\n\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\tCheckCertificateRevocationAgainstCrlFailure\n>;\n\ntype CrlDistributionPointScanResult =\n\t| 'matched'\n\t| 'reasons_mismatch'\n\t| 'unsupported_indirect_crl_issuer'\n\t| 'indirect_issuer_mismatch'\n\t| 'distribution_point_mismatch'\n\t| 'indirect_distribution_point'\n\t| 'scope_mismatch';\n\ntype CrlDistributionPointScanFailure = Exclude<CrlDistributionPointScanResult, 'matched'>;\n\ntype CrlApplicabilityOutcome =\n\t| { readonly ok: true; readonly coveredReasons: readonly DistributionPointReason[] }\n\t| { readonly ok: false; readonly failure: CrlApplicabilityFailure };\n\n/**\n * RFC 5280 §4.2.1.13 ReasonFlags, excluding the reserved `unused` bit.\n *\n * Frozen so a `coveredReasons` result that aliases it cannot corrupt later completeness checks.\n */\nexport const ALL_DISTRIBUTION_POINT_REASONS: readonly DistributionPointReason[] = Object.freeze([\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n] as const);\n\n/** True when `reasons` covers every RFC 5280 §4.2.1.13 reason — a complete-scope CRL verdict. */\nexport function coversAllDistributionPointReasons(reasons: Iterable<string>): boolean {\n\tconst set = reasons instanceof Set ? reasons : new Set(reasons);\n\treturn ALL_DISTRIBUTION_POINT_REASONS.every((reason) => set.has(reason));\n}\n\ninterface MutableIssuingDistributionPointFields {\n\tdistributionPoint?: ParsedDistributionPointName;\n\tonlyContainsUserCerts?: boolean;\n\tonlyContainsCACerts?: boolean;\n\tonlySomeReasons?: ParsedBitFlags<DistributionPointReason>;\n\tindirectCrl?: boolean;\n\tonlyContainsAttributeCerts?: boolean;\n}\n\ninterface ParsedCrlVersionField {\n\treadonly version: number;\n\treadonly nextIndex: number;\n}\n\ninterface ParsedCrlExtensionFields {\n\treadonly authorityKeyIdentifier?: string;\n\treadonly crlNumber?: bigint;\n\treadonly baseCrlNumber?: bigint;\n\treadonly issuingDistributionPoint?: ParsedIssuingDistributionPoint;\n\treadonly freshestCrlDistributionPoints?: readonly ParsedDistributionPoint[];\n}\n\ninterface MutableParsedCrlExtensionFields {\n\tauthorityKeyIdentifier?: string;\n\tcrlNumber?: bigint;\n\tbaseCrlNumber?: bigint;\n\tissuingDistributionPoint?: ParsedIssuingDistributionPoint;\n\tfreshestCrlDistributionPoints?: readonly ParsedDistributionPoint[];\n}\n\ninterface MutableRevokedCertificateExtensionFields {\n\treasonCode?: ParsedRevocationReason;\n\tinvalidityDate?: Date;\n\tcertificateIssuer?: readonly GeneralName[];\n}\n\ninterface MutableDistributionPointFields {\n\tdistributionPoint?: ParsedDistributionPointName;\n\treasons?: ParsedBitFlags<DistributionPointReason>;\n\tcrlIssuer?: readonly GeneralName[];\n}\n\ninterface MutableAuthorityKeyIdentifierState {\n\tkeyIdentifier?: string;\n\tsawAuthorityCertIssuer: boolean;\n\tsawAuthorityCertSerialNumber: boolean;\n\tlastFieldOrder: number;\n}\n\n/**\n * Signs and encodes an X.509 v2 CRL.\n *\n * Always embeds the Authority Key Identifier and CRLNumber extensions\n * (RFC 5280 §5.2), plus delta CRL indicator, issuing distribution point and\n * freshest-CRL extensions as configured.\n *\n * @example\n * ```ts\n * import { createCertificateRevocationList } from 'micro509';\n *\n * const crl = await createCertificateRevocationList({\n * issuer: { commonName: 'Example CA' },\n * signerPrivateKey: caPrivateKey,\n * issuerCertificate: caCertificatePem,\n * thisUpdate: new Date('2025-01-01'),\n * nextUpdate: new Date('2025-02-01'),\n * crlNumber: 42,\n * revokedCertificates: [\n * { serialNumber: revokedSerial, reasonCode: 'keyCompromise' },\n * ],\n * });\n * // crl.pem, crl.der, crl.base64\n * ```\n */\nexport async function createCertificateRevocationList(\n\tinput: CreateCertificateRevocationListInput,\n): Promise<CertificateRevocationListMaterial> {\n\tif (isNameInputEmpty(input.issuer)) {\n\t\tthrowCrlEncoderError(\n\t\t\t'issuer_distinguished_name_empty',\n\t\t\t'issuer must be a non-empty distinguished name',\n\t\t);\n\t}\n\tconst issuerCertificate = issuerCertificateOf(input.issuerCertificate);\n\tconst crlNumber = encodeCrlNumber(input.crlNumber, 'crlNumber');\n\tconst baseCrlNumber =\n\t\tinput.baseCrlNumber === undefined\n\t\t\t? undefined\n\t\t\t: encodeCrlNumber(input.baseCrlNumber, 'baseCrlNumber');\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey);\n\tconst thisUpdate = input.thisUpdate ?? new Date();\n\tconst nextUpdate = input.nextUpdate;\n\tassertCrlDate(thisUpdate, 'thisUpdate');\n\tassertCrlDate(nextUpdate, 'nextUpdate');\n\tfor (const entry of input.revokedCertificates ?? []) {\n\t\tassertCrlDate(entry.revocationDate, 'revocationDate');\n\t\tassertCrlDate(entry.invalidityDate, 'invalidityDate');\n\t}\n\tif (Math.floor(nextUpdate.getTime() / 1000) <= Math.floor(thisUpdate.getTime() / 1000)) {\n\t\tthrowCrlEncoderError(\n\t\t\t'next_update_not_after_this_update',\n\t\t\t'nextUpdate must be at least one second later than thisUpdate',\n\t\t);\n\t}\n\tconst extensions = buildCrlExtensions(\n\t\tissuerCertificate,\n\t\tcrlNumber,\n\t\tbaseCrlNumber,\n\t\tinput.issuingDistributionPoint,\n\t\tinput.freshestCrlDistributionPoints,\n\t);\n\tconst revoked = input.revokedCertificates ?? [];\n\tconst revokedSequence =\n\t\trevoked.length === 0\n\t\t\t? []\n\t\t\t: [sequence(revoked.map((entry) => createRevokedCertificate(entry, thisUpdate)))];\n\tconst tbsCertList = sequence([\n\t\tintegerFromNumber(1),\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tencodeName(input.issuer),\n\t\ttime(thisUpdate),\n\t\ttime(nextUpdate),\n\t\t...revokedSequence,\n\t\texplicitContext(0, sequence(extensions)),\n\t]);\n\tconst signatureValue = await signBytes(input.signerPrivateKey, signatureAlgorithm, tbsCertList);\n\tconst der = sequence([\n\t\ttbsCertList,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(signatureValue),\n\t]);\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('X509 CRL', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/** Machine-readable failure reason for the CRL parsers. */\nexport type ParseCertificateRevocationListErrorCode = DecodeFailureCode;\n\n/** Structured failure payload for CRL parsing. */\nexport interface ParseCertificateRevocationListFailure\n\textends Micro509Error<ParseCertificateRevocationListErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parseCertificateRevocationListDer} / {@linkcode parseCertificateRevocationListPem}. */\nexport type ParseCertificateRevocationListResult =\n\t| { readonly ok: true; readonly value: ParsedCertificateRevocationList }\n\t| ErrorResult<\n\t\t\tParseCertificateRevocationListErrorCode,\n\t\t\tRecord<never, never>,\n\t\t\tParseCertificateRevocationListFailure\n\t >;\n\n/**\n * Throwing core for {@linkcode parseCertificateRevocationListDer}.\n *\n * Does not verify the signature — call {@linkcode verifyCertificateRevocationListSignature} or\n * {@linkcode validateCertificateRevocationList} for that.\n */\nexport function parseCertificateRevocationListDerOrThrow(\n\tder: Uint8Array,\n): ParsedCertificateRevocationList {\n\tconst top = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (top.length !== 3) {\n\t\tthrow new Error('Malformed CRL');\n\t}\n\tconst tbsCertList = requireElement(top[0], 'TBSCertList');\n\tconst signatureAlgorithm = requireElement(top[1], 'signatureAlgorithm');\n\tconst signatureValue = requireElement(top[2], 'signatureValue');\n\tconst signedFields = parseSignedCrlFields(\n\t\tder.slice(tbsCertList.start - tbsCertList.headerLength, tbsCertList.end),\n\t);\n\tconst parsedSignatureAlgorithm = parseAlgorithmIdentifier(der, signatureAlgorithm);\n\tassertMatchingCrlSignatureAlgorithms(signedFields.signature, parsedSignatureAlgorithm);\n\treturn {\n\t\tder: new Uint8Array(der),\n\t\tversion: signedFields.version,\n\t\ttbsCertListDer: der.slice(tbsCertList.start - tbsCertList.headerLength, tbsCertList.end),\n\t\t...signatureBits(signatureValue),\n\t\tissuer: signedFields.issuer,\n\t\tthisUpdate: signedFields.thisUpdate,\n\t\t...(signedFields.nextUpdate === undefined ? {} : { nextUpdate: signedFields.nextUpdate }),\n\t\tsignatureAlgorithmOid: parsedSignatureAlgorithm.oid,\n\t\tsignatureAlgorithmName: describeSignatureAlgorithm(\n\t\t\tparsedSignatureAlgorithm.oid,\n\t\t\tparsedSignatureAlgorithm.parametersDer,\n\t\t),\n\t\t...(parsedSignatureAlgorithm.parametersDer === undefined\n\t\t\t? {}\n\t\t\t: { signatureAlgorithmParametersDer: parsedSignatureAlgorithm.parametersDer }),\n\t\t...(signedFields.authorityKeyIdentifier === undefined\n\t\t\t? {}\n\t\t\t: { authorityKeyIdentifier: signedFields.authorityKeyIdentifier }),\n\t\t...(signedFields.crlNumber === undefined ? {} : { crlNumber: signedFields.crlNumber }),\n\t\t...(signedFields.baseCrlNumber === undefined\n\t\t\t? {}\n\t\t\t: { baseCrlNumber: signedFields.baseCrlNumber }),\n\t\t...(signedFields.issuingDistributionPoint === undefined\n\t\t\t? {}\n\t\t\t: { issuingDistributionPoint: signedFields.issuingDistributionPoint }),\n\t\t...(signedFields.freshestCrlDistributionPoints === undefined\n\t\t\t? {}\n\t\t\t: { freshestCrlDistributionPoints: signedFields.freshestCrlDistributionPoints }),\n\t\trevokedCertificates: signedFields.revokedCertificates,\n\t};\n}\n\n/**\n * Decodes a PEM-encoded X.509 CRL (`-----BEGIN X509 CRL-----`).\n *\n * @example\n * ```ts\n * import { parseCertificateRevocationListPemOrThrow } from 'micro509';\n *\n * const crl = parseCertificateRevocationListPemOrThrow(pemString); // throws if malformed\n * console.log(crl.issuer.values.commonName, crl.revokedCertificates.length);\n * ```\n */\nexport function parseCertificateRevocationListPemOrThrow(\n\tpem: string,\n): ParsedCertificateRevocationList {\n\treturn parseCertificateRevocationListDerOrThrow(pemDecodeOrThrow('X509 CRL', pem));\n}\n\n/**\n * Decodes a DER-encoded X.509 CRL into a structured {@linkcode ParsedCertificateRevocationList}.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseCertificateRevocationListDerOrThrow}.\n * Does not verify the signature — call {@linkcode verifyCertificateRevocationListSignature} or\n * {@linkcode validateCertificateRevocationList} for that.\n */\nexport function parseCertificateRevocationListDer(\n\tder: Uint8Array,\n): ParseCertificateRevocationListResult {\n\ttry {\n\t\treturn successResult(parseCertificateRevocationListDerOrThrow(der));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed CRL');\n\t}\n}\n\n/**\n * Decodes a PEM-encoded X.509 CRL (`-----BEGIN X509 CRL-----`).\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseCertificateRevocationListPemOrThrow}.\n */\nexport function parseCertificateRevocationListPem(\n\tpem: string,\n): ParseCertificateRevocationListResult {\n\ttry {\n\t\treturn successResult(parseCertificateRevocationListPemOrThrow(pem));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed CRL');\n\t}\n}\n\n/**\n * Verifies the CRL signature against the issuer certificate's public key.\n *\n * Does **not** check issuer name match, key-usage, or freshness — use\n * {@linkcode validateCertificateRevocationList} for full validation.\n */\nexport async function verifyCertificateRevocationListSignature(\n\tcrl: string | Uint8Array,\n\tissuerCertificate: string | Uint8Array,\n\toptions: VerifyCertificateRevocationListSignatureOptions = {},\n): Promise<VerifyCertificateRevocationListSignatureResult> {\n\tconst verification = callerVerification(options.signatureVerifiers);\n\tlet parsedCrl: ParsedCertificateRevocationList;\n\tlet issuer: ParsedCertificate;\n\ttry {\n\t\tparsedCrl =\n\t\t\ttypeof crl === 'string'\n\t\t\t\t? parseCertificateRevocationListPemOrThrow(crl)\n\t\t\t\t: parseCertificateRevocationListDerOrThrow(new Uint8Array(crl));\n\t\tissuer =\n\t\t\ttypeof issuerCertificate === 'string'\n\t\t\t\t? parseIssuerCertificatePem(issuerCertificate)\n\t\t\t\t: parseIssuerCertificateDer(new Uint8Array(issuerCertificate));\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? verifyCertificateRevocationListFailureResult(\n\t\t\t\t\t'malformed',\n\t\t\t\t\t'certificate revocation list or issuer certificate input is malformed',\n\t\t\t\t)\n\t\t\t: verifyCertificateRevocationListFailureResult(refusal.code, refusal.message);\n\t}\n\tlet verifiedResult: Awaited<ReturnType<typeof verifySignedDataDetailed>>;\n\ttry {\n\t\tverifiedResult = await verifySignedDataDetailed(\n\t\t\tparsedCrl.signatureAlgorithmOid,\n\t\t\tparsedCrl.signatureAlgorithmParametersDer,\n\t\t\tissuer.publicKeyAlgorithmOid,\n\t\t\tissuer.publicKeyParametersOid,\n\t\t\tissuer.subjectPublicKeyInfoDer,\n\t\t\tparsedCrl.signatureValue,\n\t\t\tparsedCrl.signatureValueUnusedBits,\n\t\t\tparsedCrl.tbsCertListDer,\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? verifyCertificateRevocationListFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate revocation list signature verification failed',\n\t\t\t\t)\n\t\t\t: verifyCertificateRevocationListFailureResult(refusal.code, refusal.message);\n\t}\n\tif (!verifiedResult.ok) {\n\t\tif (verifiedResult.code === 'verification_error') {\n\t\t\treturn verifyCertificateRevocationListFailureResult(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'certificate revocation list signature verification failed',\n\t\t\t);\n\t\t}\n\t\treturn verifyCertificateRevocationListFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'certificate revocation list signature uses unsupported algorithm parameters',\n\t\t);\n\t}\n\treturn verifiedResult.valid\n\t\t? { ok: true, value: parsedCrl }\n\t\t: verifyCertificateRevocationListFailureResult(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'certificate revocation list signature does not verify',\n\t\t\t);\n}\n\n/**\n * Full CRL validation: issuer name match, authority key identifier match,\n * a v3 issuer certificate's key usage must be present and assert cRLSign\n * (RFC 10007 §4), signature verification, `thisUpdate`/`nextUpdate`\n * freshness check (with optional clock-skew tolerance), and the optional\n * `maxAgeMs` bound on `thisUpdate`. A CRL that omits `nextUpdate` fails with\n * `stale_crl` unless `maxAgeMs` is set.\n */\nexport async function validateCertificateRevocationList(\n\tinput: ValidateCertificateRevocationListInput,\n): Promise<ValidateCertificateRevocationListResult> {\n\treturn await validateCrlWith(input, callerVerification(input.signatureVerifiers));\n}\n\n/** {@linkcode validateCertificateRevocationList} with resolved caller verification. */\nasync function validateCrlWith(\n\tinput: ValidateCertificateRevocationListInput,\n\tverification: CallerVerification,\n): Promise<ValidateCertificateRevocationListResult> {\n\treturn await validateCrlBy(\n\t\tinput,\n\t\t{ kind: 'certificate', certificate: input.issuerCertificate },\n\t\tverification,\n\t);\n}\n\n/** {@linkcode validateCertificateRevocationList} for a CRL that `authority` signs. */\nasync function validateCrlBy(\n\tinput: Omit<ValidateCertificateRevocationListInput, 'issuerCertificate'>,\n\tauthority: CrlAuthority,\n\tverification: CallerVerification,\n): Promise<ValidateCertificateRevocationListResult> {\n\tassertCrlMaxAge(input.maxAgeMs);\n\tassertClockSkew(input.clockSkewMs);\n\tconst authenticated = await authenticateCrl(input.crl, authority, verification);\n\tif (!authenticated.ok) {\n\t\treturn authenticated;\n\t}\n\tconst freshnessFailure = crlFreshnessFailure(\n\t\tauthenticated.value,\n\t\tinput.at ?? new Date(),\n\t\tinput.clockSkewMs ?? 0,\n\t\tinput.maxAgeMs,\n\t);\n\treturn freshnessFailure === undefined\n\t\t? authenticated\n\t\t: validateCertificateRevocationListFailureResult('stale_crl', freshnessFailure);\n}\n\n/**\n * The key that signs a CRL: a CA certificate, or a bare trust anchor, which\n * X.509 (2019) §7.5 lets issue CRLs that its own key verifies.\n *\n * @internal\n */\nexport type CrlAuthority =\n\t| { readonly kind: 'certificate'; readonly certificate: CrlCertificateSource }\n\t| { readonly kind: 'trust_anchor'; readonly trustAnchor: TrustAnchor };\n\n/** The signing key of a resolved {@linkcode CrlAuthority}. */\ntype CrlSigningKey = Pick<\n\tTrustAnchor,\n\t| 'subject'\n\t| 'subjectKeyIdentifier'\n\t| 'subjectPublicKeyInfoDer'\n\t| 'publicKeyAlgorithmOid'\n\t| 'publicKeyParametersOid'\n>;\n\n/**\n * Verifies the issuer binding, cRLSign permission and signature of `crl`\n * against `authority`, without freshness checks. A trust anchor carries no\n * certificate, so the RFC 10007 §4 key usage check applies to certificates only.\n *\n * @internal\n */\nexport async function authenticateCrl(\n\tcrl: CrlSource,\n\tauthority: CrlAuthority,\n\tverification: CallerVerification = NO_CALLER_VERIFICATION,\n): Promise<ValidateCertificateRevocationListResult> {\n\tlet parsedCrl: ParsedCertificateRevocationList;\n\ttry {\n\t\tparsedCrl = normalizeCrl(crl);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateCertificateRevocationListFailureResult(\n\t\t\t\t\t'malformed',\n\t\t\t\t\t'certificate revocation list signed content is malformed',\n\t\t\t\t)\n\t\t\t: validateCertificateRevocationListFailureResult(refusal.code, refusal.message);\n\t}\n\tconst resolved = resolveCrlSigningKey(authority);\n\tif (!resolved.ok) return resolved;\n\tconst { issuer, issuerCertificate } = resolved;\n\tif (!compareDistinguishedNames(parsedCrl.issuer, issuer.subject)) {\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'issuer_mismatch',\n\t\t\t'CRL issuer name does not match certificate subject',\n\t\t);\n\t}\n\tif (\n\t\tparsedCrl.authorityKeyIdentifier !== undefined &&\n\t\tissuer.subjectKeyIdentifier !== undefined &&\n\t\tparsedCrl.authorityKeyIdentifier !== issuer.subjectKeyIdentifier\n\t) {\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'issuer_mismatch',\n\t\t\t'CRL authority key identifier does not match issuer subject key identifier',\n\t\t);\n\t}\n\tconst keyUsageFailure =\n\t\tissuerCertificate === undefined ? undefined : crlSignFailure(issuerCertificate);\n\tif (keyUsageFailure !== undefined) return keyUsageFailure;\n\tlet verifiedResult: Awaited<ReturnType<typeof verifySignedDataDetailed>>;\n\ttry {\n\t\tverifiedResult = await verifySignedDataDetailed(\n\t\t\tparsedCrl.signatureAlgorithmOid,\n\t\t\tparsedCrl.signatureAlgorithmParametersDer,\n\t\t\tissuer.publicKeyAlgorithmOid,\n\t\t\tissuer.publicKeyParametersOid,\n\t\t\tissuer.subjectPublicKeyInfoDer,\n\t\t\tparsedCrl.signatureValue,\n\t\t\tparsedCrl.signatureValueUnusedBits,\n\t\t\tparsedCrl.tbsCertListDer,\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? validateCertificateRevocationListFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate revocation list signature verification failed',\n\t\t\t\t)\n\t\t\t: validateCertificateRevocationListFailureResult(refusal.code, refusal.message);\n\t}\n\tif (!verifiedResult.ok) {\n\t\tif (verifiedResult.code === 'verification_error') {\n\t\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'certificate revocation list signature verification failed',\n\t\t\t);\n\t\t}\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'certificate revocation list signature uses unsupported algorithm parameters',\n\t\t);\n\t}\n\tif (!verifiedResult.valid) {\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'certificate revocation list signature does not verify',\n\t\t);\n\t}\n\treturn { ok: true, value: parsedCrl };\n}\n\n/** The signing key `authority` names, with its certificate when it has one. */\nfunction resolveCrlSigningKey(authority: CrlAuthority):\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly issuer: CrlSigningKey;\n\t\t\treadonly issuerCertificate: ParsedCertificate | undefined;\n\t }\n\t| Extract<ValidateCertificateRevocationListResult, { readonly ok: false }> {\n\tif (authority.kind === 'trust_anchor') {\n\t\treturn { ok: true, issuer: authority.trustAnchor, issuerCertificate: undefined };\n\t}\n\ttry {\n\t\tconst issuerCertificate = normalizeCrlCertificate(authority.certificate);\n\t\treturn { ok: true, issuer: issuerCertificate, issuerCertificate };\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateCertificateRevocationListFailureResult(\n\t\t\t\t\t'malformed',\n\t\t\t\t\t'issuer certificate input is malformed',\n\t\t\t\t)\n\t\t\t: validateCertificateRevocationListFailureResult(refusal.code, refusal.message);\n\t}\n}\n\n/** RFC 10007 §4: a v3 CRL issuer certificate must carry key usage asserting cRLSign. */\nfunction crlSignFailure(\n\tissuer: ParsedCertificate,\n): Extract<ValidateCertificateRevocationListResult, { readonly ok: false }> | undefined {\n\tif (issuer.keyUsage === undefined && issuer.version === 3) {\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'crl_sign_not_permitted',\n\t\t\t'v3 issuer certificate has no key usage extension',\n\t\t);\n\t}\n\tif (issuer.keyUsage !== undefined && !issuer.keyUsage.flags.includes('cRLSign')) {\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'crl_sign_not_permitted',\n\t\t\t'issuer certificate key usage does not permit CRL signing',\n\t\t);\n\t}\n\treturn undefined;\n}\n\nexport function assertCrlMaxAge(maxAgeMs: number | undefined): void {\n\tif (maxAgeMs !== undefined && (!Number.isFinite(maxAgeMs) || maxAgeMs < 0)) {\n\t\tthrow new RangeError(`Invalid maxAgeMs: must be a non-negative number, got ${maxAgeMs}`);\n\t}\n}\n\nexport function assertClockSkew(clockSkewMs: number | undefined): void {\n\tif (clockSkewMs !== undefined && (!Number.isFinite(clockSkewMs) || clockSkewMs < 0)) {\n\t\tthrow new RangeError(`Invalid clockSkewMs: must be a non-negative number, got ${clockSkewMs}`);\n\t}\n}\n\nfunction crlFreshnessFailure(\n\tcrl: ParsedCertificateRevocationList,\n\tat: Date,\n\tskew: number,\n\tmaxAgeMs: number | undefined,\n): string | undefined {\n\tif (\n\t\tcrl.thisUpdate.getTime() - skew > at.getTime() ||\n\t\t(crl.nextUpdate !== undefined && crl.nextUpdate.getTime() + skew < at.getTime())\n\t) {\n\t\treturn 'CRL is not valid at requested time';\n\t}\n\tif (crl.nextUpdate === undefined && maxAgeMs === undefined) {\n\t\treturn 'CRL has no nextUpdate and no maximum age is set';\n\t}\n\tif (maxAgeMs !== undefined && at.getTime() - crl.thisUpdate.getTime() > maxAgeMs + skew) {\n\t\treturn 'CRL thisUpdate is older than the maximum age';\n\t}\n\treturn undefined;\n}\n\nfunction deltaCrlFreshnessFailure(\n\tdeltaCrl: ParsedCertificateRevocationList,\n\tat: Date,\n\tskew: number,\n\tmaxAgeMs: number | undefined,\n): string | undefined {\n\treturn deltaCrl.nextUpdate === undefined\n\t\t? 'delta CRL has no nextUpdate'\n\t\t: crlFreshnessFailure(deltaCrl, at, skew, maxAgeMs);\n}\n\n/** Whether `crl` was issued by `at`, so its entries record revocations known then. */\nfunction isIssuedCrl(crl: ParsedCertificateRevocationList, at: Date, skew: number): boolean {\n\treturn crl.thisUpdate.getTime() - skew <= at.getTime();\n}\n\n/**\n * End-to-end revocation check: validates the CRL (and optional delta CRL),\n * verifies applicability via distribution-point and scope matching, then\n * resolves the certificate's revocation status.\n *\n * Returns `good` if the serial is absent, `revoked` with date/reason if present,\n * or an error if the CRL cannot be validated or is non-applicable.\n *\n * @example\n * ```ts\n * import { checkCertificateRevocationAgainstCrl } from 'micro509';\n *\n * const result = await checkCertificateRevocationAgainstCrl({\n * certificate: leafPem,\n * issuerCertificate: caPem,\n * crl: crlPem,\n * });\n * if (result.ok && result.value.status === 'revoked') {\n * console.log('revoked on', result.value.revocationDate);\n * }\n * ```\n */\nexport async function checkCertificateRevocationAgainstCrl(\n\tinput: CheckCertificateRevocationAgainstCrlInput,\n): Promise<CheckCertificateRevocationAgainstCrlResult> {\n\treturn await checkCertificateRevocationAgainstCrlWith(\n\t\tinput,\n\t\tcallerVerification(input.signatureVerifiers),\n\t);\n}\n\n/**\n * {@linkcode checkCertificateRevocationAgainstCrl} with resolved caller\n * verification, which can carry the issuer's inherited key parameters.\n *\n * @internal\n */\nexport async function checkCertificateRevocationAgainstCrlWith(\n\tinput: CheckCertificateRevocationAgainstCrlInput,\n\tverification: CallerVerification,\n): Promise<CheckCertificateRevocationAgainstCrlResult> {\n\tassertCrlMaxAge(input.maxAgeMs);\n\tassertClockSkew(input.clockSkewMs);\n\tlet certificate: ParsedCertificate;\n\ttry {\n\t\tcertificate = normalizeCrlCertificate(input.certificate);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\t\t\t'malformed',\n\t\t\t\t\t'certificate input is malformed',\n\t\t\t\t)\n\t\t\t: checkCertificateRevocationAgainstCrlFailureResult(refusal.code, refusal.message);\n\t}\n\treturn await checkCertificateRevocationAgainstCrlBy(\n\t\tcertificate,\n\t\tinput.crl,\n\t\t{ kind: 'certificate', certificate: input.issuerCertificate },\n\t\tinput,\n\t\tverification,\n\t);\n}\n\n/**\n * {@linkcode checkCertificateRevocationAgainstCrl} for a CRL that `authority`\n * signs, which may be a bare trust anchor.\n *\n * @internal\n */\nexport async function checkCertificateRevocationAgainstCrlBy(\n\tcertificate: ParsedCertificate,\n\tcrl: CrlSource,\n\tauthority: CrlAuthority,\n\toptions: CrlCheckOptions,\n\tverification: CallerVerification,\n): Promise<CheckCertificateRevocationAgainstCrlResult> {\n\tconst authenticated = await authenticateCrl(crl, authority, verification);\n\tif (!authenticated.ok) {\n\t\treturn checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\tauthenticated.code,\n\t\t\tauthenticated.message,\n\t\t);\n\t}\n\tconst outcome = await checkRevocationAgainstAuthenticatedCrl(\n\t\tcertificate,\n\t\tauthenticated.value,\n\t\tauthority,\n\t\toptions,\n\t\tverification,\n\t);\n\tif (outcome.kind === 'checked') return outcome.result;\n\tconst complete =\n\t\toutcome.kind === 'delta_unresolved'\n\t\t\t? outcome.complete\n\t\t\t: await checkCompleteCrlAlone(\n\t\t\t\t\tcertificate,\n\t\t\t\t\tauthenticated.value,\n\t\t\t\t\tauthority,\n\t\t\t\t\toptions,\n\t\t\t\t\tverification,\n\t\t\t\t);\n\tif (outcome.kind === 'delta_stale') return complete;\n\treturn (\n\t\tirremovableCrlRevocation(certificate, complete, options.at ?? new Date()) ?? outcome.failure\n\t);\n}\n\n/** {@linkcode checkRevocationAgainstAuthenticatedCrl} on `completeCrl` without its delta CRL. */\nasync function checkCompleteCrlAlone(\n\tcertificate: ParsedCertificate,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tauthority: CrlAuthority,\n\toptions: CrlCheckOptions,\n\tverification: CallerVerification,\n): Promise<CheckCertificateRevocationAgainstCrlResult> {\n\tconst { deltaCrl: _deltaCrl, ...completeOnly } = options;\n\tconst alone = await checkRevocationAgainstAuthenticatedCrl(\n\t\tcertificate,\n\t\tcompleteCrl,\n\t\tauthority,\n\t\tcompleteOnly,\n\t\tverification,\n\t);\n\treturn alone.kind === 'checked' ? alone.result : alone.failure;\n}\n\n/**\n * Result of {@linkcode checkRevocationAgainstAuthenticatedCrl}, keyed by the\n * stage that settled it. `delta_rejected` means the delta CRL failed\n * authentication, freshness, compatibility or applicability;\n * `delta_stale` means it passed them except freshness and records no\n * revocation that stands, so it settles nothing;\n * `delta_unresolved` means it passed them and its revoked entries could not\n * settle the certificate's status; `complete` is then the complete CRL's own\n * result, without its freshness check.\n */\ntype AuthenticatedCrlCheckOutcome =\n\t| { readonly kind: 'checked'; readonly result: CheckCertificateRevocationAgainstCrlResult }\n\t| { readonly kind: 'delta_rejected'; readonly failure: CrlApplicabilityFailure }\n\t| { readonly kind: 'delta_stale'; readonly failure: CrlApplicabilityFailure }\n\t| {\n\t\t\treadonly kind: 'delta_unresolved';\n\t\t\treadonly failure: CrlApplicabilityFailure;\n\t\t\treadonly complete: CheckCertificateRevocationAgainstCrlResult;\n\t };\n\n/**\n * The options of a CRL check once its certificate, CRL and authority are\n * resolved. `unreadSupersededDeltaCrls` applies when\n * {@linkcode checkCertificateRevocationAgainstCrlsBy} runs out of attempts.\n */\nexport type CrlCheckOptions = Omit<\n\tCheckCertificateRevocationAgainstCrlInput,\n\t'certificate' | 'issuerCertificate' | 'crl'\n> & { readonly unreadSupersededDeltaCrls?: SupersededDeltaCrlPolicy };\n\n/**\n * Checks `certificate` against a complete CRL that {@linkcode authenticateCrl}\n * accepted for `authority`, updated by `input.deltaCrl` when given.\n */\nasync function checkRevocationAgainstAuthenticatedCrl(\n\tcertificate: ParsedCertificate,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tauthority: CrlAuthority,\n\tinput: CrlCheckOptions,\n\tverification: CallerVerification = callerVerification(input.signatureVerifiers),\n): Promise<AuthenticatedCrlCheckOutcome> {\n\tif (input.deltaCrl === undefined) {\n\t\tconst freshnessFailure = crlFreshnessFailure(\n\t\t\tcompleteCrl,\n\t\t\tinput.at ?? new Date(),\n\t\t\tinput.clockSkewMs ?? 0,\n\t\t\tinput.maxAgeMs,\n\t\t);\n\t\tif (freshnessFailure !== undefined) {\n\t\t\treturn {\n\t\t\t\tkind: 'checked',\n\t\t\t\tresult: staleCompleteCrlResult(\n\t\t\t\t\tcertificate,\n\t\t\t\t\tcompleteCrl,\n\t\t\t\t\tcheckCertificateRevocationAgainstCrlFailureResult('stale_crl', freshnessFailure),\n\t\t\t\t\tinput,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t}\n\tconst deltaResult = await validateOptionalDeltaCrl(input, completeCrl, authority, verification);\n\tif (!deltaResult.ok) return { kind: 'delta_rejected', failure: deltaResult };\n\tif (deltaResult.value !== undefined && deltaResult.stale !== undefined) {\n\t\treturn staleDeltaCrlOutcome(\n\t\t\tcertificate,\n\t\t\tcompleteCrl,\n\t\t\tdeltaResult.value,\n\t\t\tdeltaResult.stale,\n\t\t\tinput,\n\t\t);\n\t}\n\tconst deltaCrl = deltaResult.value;\n\tconst applicability = checkCrlApplicability(certificate, completeCrl);\n\tif (!applicability.ok) return { kind: 'checked', result: applicability.failure };\n\tif (deltaCrl !== undefined) {\n\t\tconst deltaApplicability = checkCrlApplicability(certificate, deltaCrl, true);\n\t\tif (!deltaApplicability.ok) {\n\t\t\treturn { kind: 'delta_rejected', failure: deltaApplicability.failure };\n\t\t}\n\t}\n\tconst completeRevoked = findRevokedCertificateEntry(certificate, completeCrl);\n\tif (!completeRevoked.ok) return { kind: 'checked', result: completeRevoked };\n\tlet deltaRevoked: ParsedRevokedCertificate | undefined;\n\tif (deltaCrl !== undefined) {\n\t\tconst deltaLookup = findRevokedCertificateEntry(certificate, deltaCrl);\n\t\tif (!deltaLookup.ok) {\n\t\t\treturn {\n\t\t\t\tkind: 'delta_unresolved',\n\t\t\t\tfailure: deltaLookup,\n\t\t\t\tcomplete: resolveCertificateRevocationStatus(\n\t\t\t\t\tcertificate,\n\t\t\t\t\tundefined,\n\t\t\t\t\tcompleteCrl,\n\t\t\t\t\tcompleteRevoked.entry,\n\t\t\t\t\tundefined,\n\t\t\t\t\tapplicability.coveredReasons,\n\t\t\t\t\tinput.unrecognizedReasonCode ?? 'revoked',\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\tdeltaRevoked = deltaLookup.entry;\n\t}\n\treturn {\n\t\tkind: 'checked',\n\t\tresult: resolveCertificateRevocationStatus(\n\t\t\tcertificate,\n\t\t\tdeltaCrl?.thisUpdate,\n\t\t\tcompleteCrl,\n\t\t\tcompleteRevoked.entry,\n\t\t\tdeltaRevoked,\n\t\t\tapplicability.coveredReasons,\n\t\t\tinput.unrecognizedReasonCode ?? 'revoked',\n\t\t),\n\t};\n}\n\n/**\n * A key equal for two CRLs exactly when their signed content and signature\n * are equal.\n *\n * @internal\n */\nexport function signedCrlKey(crl: ParsedCertificateRevocationList): string {\n\treturn [\n\t\tcrl.signatureAlgorithmOid,\n\t\ttoHex(crl.signatureAlgorithmParametersDer ?? new Uint8Array()),\n\t\ttoHex(crl.signatureValue),\n\t\tcrl.signatureValueUnusedBits,\n\t\ttoHex(crl.tbsCertListDer),\n\t].join(':');\n}\n\n/**\n * `crls` with each signed content and signature kept once.\n *\n * @internal\n */\nexport function distinctSignedCrls(\n\tcrls: readonly ParsedCertificateRevocationList[],\n): readonly ParsedCertificateRevocationList[] {\n\tconst seen = new Set<string>();\n\treturn crls.filter((crl) => {\n\t\tconst key = signedCrlKey(crl);\n\t\tif (seen.has(key)) {\n\t\t\treturn false;\n\t\t}\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n}\n\n/** Delta CRLs micro509 tries per complete CRL, an implementation limit. */\nexport const DELTA_CRL_ATTEMPTS_PER_BASE = 4;\n\n/** Delta CRLs micro509 tries in one revocation check, an implementation limit. */\nexport const DELTA_CRL_ATTEMPTS_PER_CALL = 32;\n\n/**\n * Delta CRL checks left to spend across one revocation check, an\n * implementation limit shared by every complete CRL it reads.\n *\n * @internal\n */\nexport interface DeltaCrlBudget {\n\tremaining: number;\n}\n\n/**\n * Every delta CRL that can update `baseCrl` and was issued by `at`, newest\n * first. A delta CRL that is no longer current still settles a revocation no\n * later CRL could remove (RFC 5280 §5.3.1), so currency does not move it\n * behind older ones.\n */\nfunction rankApplicableDeltaCrls(\n\tbaseCrl: ParsedCertificateRevocationList,\n\tdeltaCrls: readonly ParsedCertificateRevocationList[],\n\tat: Date,\n\tclockSkewMs: number,\n): readonly ParsedCertificateRevocationList[] {\n\treturn deltaCrls\n\t\t.filter(\n\t\t\t(deltaCrl) =>\n\t\t\t\tisCompatibleDeltaCrl(baseCrl, deltaCrl) && isIssuedCrl(deltaCrl, at, clockSkewMs),\n\t\t)\n\t\t.sort(compareDeltaCrlRecency);\n}\n\n/** Whether {@linkcode checkDeltaCrlCompatibility} accepts `deltaCrl` for `completeCrl`. */\nfunction isCompatibleDeltaCrl(\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tdeltaCrl: ParsedCertificateRevocationList,\n): boolean {\n\ttry {\n\t\treturn checkDeltaCrlCompatibility(completeCrl, deltaCrl) === undefined;\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn false;\n\t}\n}\n\n/**\n * Orders delta CRLs newest first by `thisUpdate`, the key RFC 5280 §5.2.4\n * names for the most current one, then by CRL number.\n */\nfunction compareDeltaCrlRecency(\n\tleft: ParsedCertificateRevocationList,\n\tright: ParsedCertificateRevocationList,\n): number {\n\tconst byTime = right.thisUpdate.getTime() - left.thisUpdate.getTime();\n\tif (byTime !== 0) return byTime;\n\tconst leftNumber = left.crlNumber ?? 0n;\n\tconst rightNumber = right.crlNumber ?? 0n;\n\treturn leftNumber === rightNumber ? 0 : leftNumber < rightNumber ? 1 : -1;\n}\n\n/**\n * Whether `newer` supersedes `older` by both its `thisUpdate` and its CRL\n * number (RFC 5280 §5.2.3, §5.1.2.4). RFC 5280 leaves a pair whose keys\n * disagree unspecified, and micro509 ranks such a pair alike.\n */\nfunction supersedesDeltaCrl(\n\tnewer: ParsedCertificateRevocationList,\n\tolder: ParsedCertificateRevocationList,\n): boolean {\n\treturn (\n\t\tnewer.thisUpdate.getTime() > older.thisUpdate.getTime() &&\n\t\tnewer.crlNumber !== undefined &&\n\t\tolder.crlNumber !== undefined &&\n\t\tnewer.crlNumber > older.crlNumber\n\t);\n}\n\n/**\n * Result of {@linkcode checkCertificateRevocationAgainstCrlsBy}. `checked`\n * names the delta CRL its result came from, if any. `unsettled` means an\n * applicable delta CRL could not settle the status (`delta_unusable`), or the\n * {@linkcode DELTA_CRL_ATTEMPTS_PER_BASE} limit or a shared\n * {@linkcode DeltaCrlBudget} left a delta CRL unread that counts under\n * `unreadSupersededDeltaCrls` (`retry_limit`). An unread delta CRL may then\n * revoke the certificate, so the complete CRL's good is no evidence.\n *\n * @internal\n */\nexport type CrlsCheckOutcome =\n\t| {\n\t\t\treadonly kind: 'checked';\n\t\t\treadonly result: CheckCertificateRevocationAgainstCrlResult;\n\t\t\treadonly deltaCrl?: ParsedCertificateRevocationList;\n\t }\n\t| { readonly kind: 'unsettled'; readonly reason: 'delta_unusable' | 'retry_limit' };\n\n/**\n * Checks `certificate` against `completeCrl`, which `authority` signs, and\n * the delta CRLs in `deltaCrls` that update it, newest first. A rejected\n * delta CRL, or one past its `nextUpdate` that records no lasting revocation,\n * passes the search to the next. The first current delta CRL settles the\n * status, and one past its `nextUpdate` settles a revocation no later CRL\n * could remove (RFC 5280 §5.3.1, §3.3). After a good status, older delta CRLs\n * are still read for such a revocation the newer one omits. Each delta CRL\n * check spends one from {@linkcode DELTA_CRL_ATTEMPTS_PER_BASE} and from every\n * budget in `budgets`. When they leave a delta CRL unread, the outcome is\n * `retry_limit` unless the complete CRL holds such a revocation. Under\n * `unreadSupersededDeltaCrls: 'ignore'`, only an unread delta CRL that\n * {@linkcode mayChangeSettledStatus} finds could change the status counts. A\n * complete CRL that does not cover `certificate` spends none.\n *\n * @internal\n */\nexport async function checkCertificateRevocationAgainstCrlsBy(\n\tcertificate: ParsedCertificate,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tdeltaCrls: readonly ParsedCertificateRevocationList[],\n\tauthority: CrlAuthority,\n\toptions: CrlCheckOptions,\n\tverification: CallerVerification,\n\tbudgets: readonly DeltaCrlBudget[] = [],\n): Promise<CrlsCheckOutcome> {\n\tconst authenticated = await authenticateCrl(completeCrl, authority, verification);\n\tif (!authenticated.ok) {\n\t\treturn {\n\t\t\tkind: 'checked',\n\t\t\tresult: checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\t\tauthenticated.code,\n\t\t\t\tauthenticated.message,\n\t\t\t),\n\t\t};\n\t}\n\tconst at = options.at ?? new Date();\n\tconst candidates = checkCrlApplicability(certificate, authenticated.value).ok\n\t\t? rankApplicableDeltaCrls(authenticated.value, deltaCrls, at, options.clockSkewMs ?? 0)\n\t\t: [];\n\tconst search: DeltaCrlSearch = { attempts: 0, unread: [] };\n\tfor (const [index, deltaCrl] of candidates.entries()) {\n\t\tif (!spendDeltaCrlAttempt(search, budgets)) {\n\t\t\tsearch.unread = candidates.slice(index);\n\t\t\tbreak;\n\t\t}\n\t\trecordDeltaCrlOutcome(\n\t\t\tsearch,\n\t\t\tcertificate,\n\t\t\tdeltaCrl,\n\t\t\tawait checkRevocationAgainstAuthenticatedCrl(\n\t\t\t\tcertificate,\n\t\t\t\tauthenticated.value,\n\t\t\t\tauthority,\n\t\t\t\t{ ...options, deltaCrl },\n\t\t\t\tverification,\n\t\t\t),\n\t\t\tat,\n\t\t);\n\t\tif (search.result !== undefined) return search.result;\n\t}\n\tconst unreadMaySettle =\n\t\toptions.unreadSupersededDeltaCrls === 'ignore'\n\t\t\t? search.unread.some((deltaCrl) => mayChangeSettledStatus(search, deltaCrl, at, options))\n\t\t\t: search.unread.length > 0;\n\tif (!unreadMaySettle && search.good !== undefined) return search.good;\n\tconst alone = await checkRevocationAgainstAuthenticatedCrl(\n\t\tcertificate,\n\t\tauthenticated.value,\n\t\tauthority,\n\t\toptions,\n\t\tverification,\n\t);\n\tconst aloneResult = alone.kind === 'checked' ? alone.result : alone.failure;\n\treturn unreadMaySettle\n\t\t? settledOrUnsettled(irremovableCrlRevocation(certificate, aloneResult, at), 'retry_limit')\n\t\t: { kind: 'checked', result: aloneResult };\n}\n\n/**\n * Where {@linkcode checkCertificateRevocationAgainstCrlsBy} stands in its\n * delta CRL candidates: `newest` is the first one examined that was not\n * rejected, and `unread` the ones the limits left unread.\n */\ninterface DeltaCrlSearch {\n\tattempts: number;\n\tnewest?: ParsedCertificateRevocationList;\n\tunread: readonly ParsedCertificateRevocationList[];\n\tgood?: {\n\t\treadonly kind: 'checked';\n\t\treadonly result: CheckCertificateRevocationAgainstCrlResult;\n\t\treadonly deltaCrl: ParsedCertificateRevocationList;\n\t};\n\tresult?: CrlsCheckOutcome;\n}\n\n/**\n * Whether reading the unread `deltaCrl` could change the status `search`\n * reached by more than an older entry its newer delta CRLs omit. After a good\n * status, only a delta CRL that the one settling it supersedes cannot.\n * Otherwise only one that is not current and that a delta CRL examined\n * supersedes cannot, since a current one settles the status.\n */\nfunction mayChangeSettledStatus(\n\tsearch: DeltaCrlSearch,\n\tdeltaCrl: ParsedCertificateRevocationList,\n\tat: Date,\n\toptions: CrlCheckOptions,\n): boolean {\n\tif (search.good !== undefined) return !supersedesDeltaCrl(search.good.deltaCrl, deltaCrl);\n\tconst current =\n\t\tdeltaCrlFreshnessFailure(deltaCrl, at, options.clockSkewMs ?? 0, options.maxAgeMs) ===\n\t\tundefined;\n\treturn current || search.newest === undefined || !supersedesDeltaCrl(search.newest, deltaCrl);\n}\n\n/** Spends one delta CRL check from the per-base limit and every budget, or none when any is spent. */\nfunction spendDeltaCrlAttempt(search: DeltaCrlSearch, budgets: readonly DeltaCrlBudget[]): boolean {\n\tif (\n\t\tsearch.attempts >= DELTA_CRL_ATTEMPTS_PER_BASE ||\n\t\tbudgets.some((budget) => budget.remaining <= 0)\n\t) {\n\t\treturn false;\n\t}\n\tsearch.attempts += 1;\n\tfor (const budget of budgets) budget.remaining -= 1;\n\treturn true;\n}\n\n/**\n * Folds the outcome of `deltaCrl` into `search`. A delta CRL that the one\n * settling the status as good supersedes only adds what\n * {@linkcode olderDeltaRevocation} finds. Any other settles like the first,\n * so two delta CRLs ranked alike that disagree yield the stricter result.\n */\nfunction recordDeltaCrlOutcome(\n\tsearch: DeltaCrlSearch,\n\tcertificate: ParsedCertificate,\n\tdeltaCrl: ParsedCertificateRevocationList,\n\toutcome: AuthenticatedCrlCheckOutcome,\n\tat: Date,\n): void {\n\tif (outcome.kind === 'delta_rejected') return;\n\tsearch.newest ??= deltaCrl;\n\tif (search.good !== undefined && supersedesDeltaCrl(search.good.deltaCrl, deltaCrl)) {\n\t\tsearch.result = olderDeltaRevocation(certificate, deltaCrl, outcome, at);\n\t\treturn;\n\t}\n\tif (outcome.kind === 'checked') {\n\t\tif (!isGoodResult(outcome.result)) {\n\t\t\tsearch.result = { kind: 'checked', result: outcome.result, deltaCrl };\n\t\t} else {\n\t\t\tsearch.good ??= { kind: 'checked', result: outcome.result, deltaCrl };\n\t\t}\n\t} else if (outcome.kind === 'delta_unresolved') {\n\t\tsearch.result = settledOrUnsettled(\n\t\t\tirremovableCrlRevocation(certificate, outcome.complete, at),\n\t\t\t'delta_unusable',\n\t\t);\n\t}\n}\n\nfunction isGoodResult(result: CheckCertificateRevocationAgainstCrlResult): boolean {\n\treturn result.ok && result.value.status === 'good';\n}\n\n/**\n * What an older delta CRL changes after a newer one settled the status as\n * good: a revocation no later CRL may drop (RFC 5280 §5.3.1, §3.3), a\n * failure such as an entry `unrecognizedReasonCode: 'reject'` refuses, or\n * entries that cannot settle the status. A newer delta CRL that omits such an\n * entry contradicts its issuer.\n */\nfunction olderDeltaRevocation(\n\tcertificate: ParsedCertificate,\n\tdeltaCrl: ParsedCertificateRevocationList,\n\toutcome: AuthenticatedCrlCheckOutcome,\n\tat: Date,\n): CrlsCheckOutcome | undefined {\n\tif (outcome.kind === 'delta_unresolved') {\n\t\treturn settledOrUnsettled(\n\t\t\tirremovableCrlRevocation(certificate, outcome.complete, at),\n\t\t\t'delta_unusable',\n\t\t);\n\t}\n\tif (outcome.kind !== 'checked') return undefined;\n\tif (!outcome.result.ok) return { kind: 'checked', result: outcome.result, deltaCrl };\n\tconst revoked = irremovableCrlRevocation(certificate, outcome.result, at);\n\treturn revoked === undefined ? undefined : { kind: 'checked', result: revoked, deltaCrl };\n}\n\nfunction settledOrUnsettled(\n\tresult: CheckCertificateRevocationAgainstCrlResult | undefined,\n\treason: Extract<CrlsCheckOutcome, { readonly kind: 'unsettled' }>['reason'],\n): CrlsCheckOutcome {\n\treturn result === undefined ? { kind: 'unsettled', reason } : { kind: 'checked', result };\n}\n\n/**\n * `result` when it revokes `certificate` in a way no delta CRL could undo at\n * `at`. RFC 5280 §5.3.1 lets removeFromCRL clear only a certificateHold entry\n * or a certificate that has expired.\n */\nfunction irremovableCrlRevocation(\n\tcertificate: ParsedCertificate,\n\tresult: CheckCertificateRevocationAgainstCrlResult,\n\tat: Date,\n): Extract<CheckCertificateRevocationAgainstCrlResult, { readonly ok: true }> | undefined {\n\treturn certificate.notAfter.getTime() >= at.getTime() &&\n\t\tresult.ok &&\n\t\tresult.value.status === 'revoked' &&\n\t\tresult.value.reasonCode !== 'certificateHold'\n\t\t? result\n\t\t: undefined;\n}\n\n/** RFC 5280 §6.3.3 (d): interim_reasons_mask from the matched DP and the CRL's IDP. */\nfunction interimReasonsMask(\n\tdistributionPoint: ParsedDistributionPoint | undefined,\n\tissuingDistributionPoint: ParsedIssuingDistributionPoint | undefined,\n): readonly DistributionPointReason[] {\n\tconst distributionPointReasons = distributionPoint?.reasons?.flags;\n\tconst crlReasons = issuingDistributionPoint?.onlySomeReasons?.flags;\n\tif (distributionPointReasons !== undefined && crlReasons !== undefined) {\n\t\treturn distributionPointReasons.filter((reason) => crlReasons.includes(reason));\n\t}\n\tif (distributionPointReasons !== undefined) {\n\t\treturn [...distributionPointReasons];\n\t}\n\tif (crlReasons !== undefined) {\n\t\treturn [...crlReasons];\n\t}\n\treturn ALL_DISTRIBUTION_POINT_REASONS;\n}\n\n/**\n * Authenticates an optional delta CRL and checks compatibility with its\n * complete CRL. A delta CRL issued by `input.at` but not current there comes\n * back with the freshness failure as `stale`.\n */\nasync function validateOptionalDeltaCrl(\n\tinput: CrlCheckOptions,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tauthority: CrlAuthority,\n\tverification: CallerVerification,\n): Promise<\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly value?: ParsedCertificateRevocationList;\n\t\t\treadonly stale?: CrlApplicabilityFailure;\n\t }\n\t| CrlApplicabilityFailure\n> {\n\tif (input.deltaCrl === undefined) return { ok: true };\n\tassertCrlMaxAge(input.maxAgeMs);\n\tassertClockSkew(input.clockSkewMs);\n\tconst authenticated = await authenticateCrl(input.deltaCrl, authority, verification);\n\tif (!authenticated.ok) {\n\t\treturn checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\tauthenticated.code,\n\t\t\tauthenticated.message,\n\t\t);\n\t}\n\tconst at = input.at ?? new Date();\n\tconst skew = input.clockSkewMs ?? 0;\n\tconst freshnessFailure = deltaCrlFreshnessFailure(authenticated.value, at, skew, input.maxAgeMs);\n\tif (freshnessFailure !== undefined && !isIssuedCrl(authenticated.value, at, skew)) {\n\t\treturn checkCertificateRevocationAgainstCrlFailureResult('stale_crl', freshnessFailure);\n\t}\n\tlet compatibilityFailure: CrlApplicabilityFailure | undefined;\n\ttry {\n\t\tcompatibilityFailure = checkDeltaCrlCompatibility(completeCrl, authenticated.value);\n\t} catch (error) {\n\t\treturn crlNameRefusalFailure(error);\n\t}\n\tif (compatibilityFailure !== undefined) {\n\t\treturn freshnessFailure === undefined\n\t\t\t? compatibilityFailure\n\t\t\t: checkCertificateRevocationAgainstCrlFailureResult('stale_crl', freshnessFailure);\n\t}\n\treturn {\n\t\tok: true,\n\t\tvalue: authenticated.value,\n\t\t...(freshnessFailure === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tstale: checkCertificateRevocationAgainstCrlFailureResult('stale_crl', freshnessFailure),\n\t\t\t\t}),\n\t};\n}\n\n/**\n * The result of `completeCrl`, which is not current at `input.at`: its\n * revocation of `certificate` when no later CRL could remove it (RFC 5280\n * §5.3.1, §3.3), otherwise `stale`. A CRL issued after `input.at` yields\n * `stale`.\n */\nfunction staleCompleteCrlResult(\n\tcertificate: ParsedCertificate,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tstale: CheckCertificateRevocationAgainstCrlResult,\n\tinput: CrlCheckOptions,\n): CheckCertificateRevocationAgainstCrlResult {\n\tconst at = input.at ?? new Date();\n\tif (\n\t\t!isIssuedCrl(completeCrl, at, input.clockSkewMs ?? 0) ||\n\t\t!checkCrlApplicability(certificate, completeCrl).ok\n\t) {\n\t\treturn stale;\n\t}\n\tconst lookup = findRevokedCertificateEntry(certificate, completeCrl);\n\tif (!lookup.ok || lookup.entry === undefined) return stale;\n\tconst result = revokedEntryResult(\n\t\tcompleteCrl,\n\t\tlookup.entry,\n\t\tinput.unrecognizedReasonCode ?? 'revoked',\n\t);\n\tif (!result.ok) return result;\n\treturn irremovableCrlRevocation(certificate, result, at) ?? stale;\n}\n\n/**\n * The outcome of `deltaCrl`, which updates `completeCrl` but is not current at\n * `input.at`. Its revocation of `certificate` settles the status when no later\n * CRL could remove it (RFC 5280 §5.3.1). Otherwise it is `delta_stale` when it\n * applies to `certificate`, and settles nothing. A delta CRL that does not\n * apply is rejected with `stale`.\n */\nfunction staleDeltaCrlOutcome(\n\tcertificate: ParsedCertificate,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tdeltaCrl: ParsedCertificateRevocationList,\n\tstale: CrlApplicabilityFailure,\n\tinput: CrlCheckOptions,\n): AuthenticatedCrlCheckOutcome {\n\tconst rejected = { kind: 'delta_rejected', failure: stale } as const;\n\tif (\n\t\t!checkCrlApplicability(certificate, completeCrl).ok ||\n\t\t!checkCrlApplicability(certificate, deltaCrl, true).ok\n\t) {\n\t\treturn rejected;\n\t}\n\tconst lookup = findRevokedCertificateEntry(certificate, deltaCrl);\n\tif (!lookup.ok) return rejected;\n\tconst settled = { kind: 'delta_stale', failure: stale } as const;\n\tif (lookup.entry === undefined || lookup.entry.reasonCode === 'removeFromCRL') return settled;\n\tconst result = revokedEntryResult(\n\t\tcompleteCrl,\n\t\tlookup.entry,\n\t\tinput.unrecognizedReasonCode ?? 'revoked',\n\t);\n\tif (!result.ok) return { kind: 'checked', result };\n\treturn irremovableCrlRevocation(certificate, result, input.at ?? new Date()) === undefined\n\t\t? settled\n\t\t: { kind: 'checked', result };\n}\n\n/** Builds a `VerifyCertificateRevocationListSignatureFailureResult`. */\nfunction verifyCertificateRevocationListFailureResult(\n\tcode: 'signature_invalid' | DecodeFailureCode,\n\tmessage: string,\n): ErrorResult<\n\t'signature_invalid' | DecodeFailureCode,\n\tRecord<never, never>,\n\tVerifyCertificateRevocationListSignatureFailure\n> {\n\treturn failureResult(code, message);\n}\n\n/** Builds a `ValidateCertificateRevocationListFailureResult`. */\nfunction validateCertificateRevocationListFailureResult(\n\tcode:\n\t\t| 'signature_invalid'\n\t\t| 'issuer_mismatch'\n\t\t| 'stale_crl'\n\t\t| 'crl_sign_not_permitted'\n\t\t| DecodeFailureCode,\n\tmessage: string,\n): ErrorResult<\n\t| 'signature_invalid'\n\t| 'issuer_mismatch'\n\t| 'stale_crl'\n\t| 'crl_sign_not_permitted'\n\t| DecodeFailureCode,\n\tRecord<never, never>,\n\tValidateCertificateRevocationListFailure\n> {\n\treturn failureResult(code, message);\n}\n\n/** Builds a `CheckCertificateRevocationAgainstCrlFailureResult`. */\nfunction checkCertificateRevocationAgainstCrlFailureResult(\n\tcode: CheckCertificateRevocationAgainstCrlErrorCode,\n\tmessage: string,\n\tdetails?: CheckCertificateRevocationAgainstCrlFailureDetails,\n): ErrorResult<\n\tCheckCertificateRevocationAgainstCrlErrorCode,\n\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\tCheckCertificateRevocationAgainstCrlFailure\n> {\n\treturn failureResult(code, message, details);\n}\n\n/** Wraps a success value into a `CheckCertificateRevocationAgainstCrlResult`. */\nfunction checkCertificateRevocationAgainstCrlSuccess(\n\tvalue: CheckCertificateRevocationAgainstCrlValue,\n): CheckCertificateRevocationAgainstCrlResult {\n\treturn { ok: true, value };\n}\n\n/**\n * Quick serial-number lookup — returns `true` if the serial appears in the\n * CRL's revoked entries. Does **not** validate the CRL or check applicability.\n */\nexport function isCertificateRevoked(\n\tcertificateSerialNumber: Uint8Array | string,\n\tcrl: ParsedCertificateRevocationList,\n): boolean {\n\tconst serialNumberHex =\n\t\ttypeof certificateSerialNumber === 'string'\n\t\t\t? normalizeHex(certificateSerialNumber)\n\t\t\t: toHex(certificateSerialNumber);\n\treturn crl.revokedCertificates.some(\n\t\t(entry) => normalizeHex(entry.serialNumberHex) === serialNumberHex,\n\t);\n}\n\n/** Searches CRL entries for the certificate's serial, respecting indirect-CRL issuer overrides. */\nfunction findRevokedCertificateEntry(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n): RevokedCertificateLookupResult {\n\ttry {\n\t\treturn lookupRevokedCertificateEntry(certificate, crl);\n\t} catch (error) {\n\t\treturn crlNameRefusalFailure(error);\n\t}\n}\n\nfunction lookupRevokedCertificateEntry(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n): RevokedCertificateLookupResult {\n\tconst serialNumberHex = normalizeHex(certificate.serialNumberHex);\n\tlet effectiveIssuer: readonly GeneralName[] | undefined;\n\tlet sawUnsupportedIssuer = false;\n\tlet matchedEntry: ParsedRevokedCertificate | undefined;\n\tfor (const entry of crl.revokedCertificates) {\n\t\tif (entry.certificateIssuer !== undefined) {\n\t\t\teffectiveIssuer = entry.certificateIssuer;\n\t\t}\n\t\tif (normalizeHex(entry.serialNumberHex) !== serialNumberHex) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst issuerMatch = matchesRevokedEntryIssuer(certificate, crl, effectiveIssuer);\n\t\tif (issuerMatch === 'match') {\n\t\t\tif (matchedEntry !== undefined) {\n\t\t\t\treturn checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'CRL contains multiple revoked entries for certificate',\n\t\t\t\t);\n\t\t\t}\n\t\t\tmatchedEntry = entry;\n\t\t\tcontinue;\n\t\t}\n\t\tif (issuerMatch === 'unsupported') {\n\t\t\tsawUnsupportedIssuer = true;\n\t\t}\n\t}\n\tif (matchedEntry !== undefined) {\n\t\treturn { ok: true, entry: matchedEntry };\n\t}\n\tif (sawUnsupportedIssuer) {\n\t\treturn nonApplicable(\n\t\t\t'unsupported_indirect_crl',\n\t\t\t'indirect CRL entry certificateIssuer must include a directoryName',\n\t\t);\n\t}\n\treturn { ok: true };\n}\n\n/**\n * Whether `crl` covers `certificate` under {@linkcode checkCrlApplicability}.\n *\n * @internal\n */\nexport function isCrlApplicableTo(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n): boolean {\n\treturn checkCrlApplicability(certificate, crl).ok;\n}\n\n/** RFC 5280 §6.3 CRL applicability: scope, distribution-point, reason, and indirect-CRL checks. */\nfunction checkCrlApplicability(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\tallowDeltaCrl = false,\n): CrlApplicabilityOutcome {\n\ttry {\n\t\treturn evaluateCrlApplicability(certificate, crl, allowDeltaCrl);\n\t} catch (error) {\n\t\treturn { ok: false, failure: crlNameRefusalFailure(error) };\n\t}\n}\n\nfunction evaluateCrlApplicability(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\tallowDeltaCrl: boolean,\n): CrlApplicabilityOutcome {\n\tif (!allowDeltaCrl && crl.baseCrlNumber !== undefined) {\n\t\treturn notApplicableOutcome(\n\t\t\t'unsupported_delta_crl',\n\t\t\t'a delta CRL cannot be used as the primary complete CRL input',\n\t\t);\n\t}\n\tconst issuingDistributionPoint = crl.issuingDistributionPoint;\n\tconst isIndirectCrl = issuingDistributionPoint?.indirectCrl === true;\n\tif (!isIndirectCrl && !compareDistinguishedNames(certificate.issuer, crl.issuer)) {\n\t\treturn notApplicableOutcome(\n\t\t\t'issuer_mismatch',\n\t\t\t'CRL issuer does not match certificate issuer for direct CRL processing',\n\t\t);\n\t}\n\tif (issuingDistributionPoint?.onlyContainsAttributeCerts === true) {\n\t\treturn notApplicableOutcome(\n\t\t\t'certificate_scope_mismatch',\n\t\t\t'attribute-certificate-only CRLs are not applicable to public-key certificates',\n\t\t);\n\t}\n\tconst isCaCertificate = certificate.basicConstraints?.ca === true;\n\tif (issuingDistributionPoint?.onlyContainsUserCerts === true && isCaCertificate) {\n\t\treturn notApplicableOutcome(\n\t\t\t'certificate_scope_mismatch',\n\t\t\t'CRL only applies to end-entity certificates',\n\t\t);\n\t}\n\tif (issuingDistributionPoint?.onlyContainsCACerts === true && !isCaCertificate) {\n\t\treturn notApplicableOutcome(\n\t\t\t'certificate_scope_mismatch',\n\t\t\t'CRL only applies to CA certificates',\n\t\t);\n\t}\n\tconst distributionPoints = certificate.crlDistributionPoints ?? [];\n\tif (distributionPoints.length === 0) {\n\t\tif (\n\t\t\tissuingDistributionPoint?.distributionPoint !== undefined &&\n\t\t\t!matchesDistributionPointName(\n\t\t\t\tissuerFallbackDistributionPointName(certificate),\n\t\t\t\tissuingDistributionPoint.distributionPoint,\n\t\t\t\tcrl.issuer,\n\t\t\t\tundefined,\n\t\t\t)\n\t\t) {\n\t\t\treturn notApplicableOutcome(\n\t\t\t\t'distribution_point_mismatch',\n\t\t\t\t'CRL issuing distribution point does not name the certificate issuer',\n\t\t\t);\n\t\t}\n\t\tif (isIndirectCrl && !compareDistinguishedNames(certificate.issuer, crl.issuer)) {\n\t\t\treturn notApplicableOutcome(\n\t\t\t\t'issuer_mismatch',\n\t\t\t\t'indirect CRLs for alternate certificate issuers require matching CRLIssuer distribution points',\n\t\t\t);\n\t\t}\n\t\treturn { ok: true, coveredReasons: interimReasonsMask(undefined, issuingDistributionPoint) };\n\t}\n\tconst scanResult = scanCrlDistributionPoints(\n\t\tdistributionPoints,\n\t\tcertificate,\n\t\tcrl,\n\t\tissuingDistributionPoint,\n\t\tisIndirectCrl,\n\t);\n\tif (typeof scanResult === 'string') {\n\t\treturn { ok: false, failure: crlDistributionPointScanFailure(scanResult) };\n\t}\n\treturn { ok: true, coveredReasons: scanResult.coveredReasons };\n}\n\n/** Wraps a non-applicability failure into a {@linkcode CrlApplicabilityOutcome}. */\nfunction notApplicableOutcome(\n\treason: CrlApplicabilityFailureReason,\n\tmessage: string,\n): CrlApplicabilityOutcome {\n\treturn { ok: false, failure: nonApplicable(reason, message) };\n}\n\n/**\n * RFC 5280 §6.3.3 final paragraph: for a certificate without a CRLDP extension,\n * assume a distribution point named by the certificate issuer and its\n * issuerAltName entries, with reasons and cRLIssuer omitted.\n */\nfunction issuerFallbackDistributionPointName(\n\tcertificate: ParsedCertificate,\n): ParsedDistributionPointName {\n\treturn {\n\t\ttype: 'fullName',\n\t\tfullName: [\n\t\t\t{ type: 'directoryName', derHex: certificate.issuer.derHex },\n\t\t\t...(certificate.issuerAltNames ?? []),\n\t\t],\n\t};\n}\n\n/**\n * Aggregates distribution-point matching across a certificate.\n *\n * RFC 5280 §6.3.3 processes every corresponding DP, so when several match the same CRL their\n * interim reason masks (d) are unioned rather than stopping at the first.\n */\nfunction scanCrlDistributionPoints(\n\tdistributionPoints: readonly ParsedDistributionPoint[],\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\tissuingDistributionPoint: ParsedIssuingDistributionPoint | undefined,\n\tisIndirectCrl: boolean,\n):\n\t| { readonly coveredReasons: readonly DistributionPointReason[] }\n\t| CrlDistributionPointScanFailure {\n\tconst coveredReasons = new Set<DistributionPointReason>();\n\tconst failures = new Set<CrlDistributionPointScanFailure>();\n\tlet sawMatch = false;\n\tfor (const distributionPoint of distributionPoints) {\n\t\tconst result = scanCrlDistributionPoint(\n\t\t\tdistributionPoint,\n\t\t\tcertificate,\n\t\t\tcrl,\n\t\t\tissuingDistributionPoint,\n\t\t\tisIndirectCrl,\n\t\t);\n\t\tif (result === 'matched') {\n\t\t\tsawMatch = true;\n\t\t\tfor (const reason of interimReasonsMask(distributionPoint, issuingDistributionPoint)) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfailures.add(result);\n\t}\n\treturn sawMatch ? { coveredReasons: [...coveredReasons] } : resolveScanFailure(failures);\n}\n\n/** Reports the highest-precedence distribution-point scan failure. */\nfunction resolveScanFailure(\n\tfailures: ReadonlySet<CrlDistributionPointScanFailure>,\n): CrlDistributionPointScanFailure {\n\tconst precedence: readonly CrlDistributionPointScanFailure[] = [\n\t\t'reasons_mismatch',\n\t\t'unsupported_indirect_crl_issuer',\n\t\t'indirect_issuer_mismatch',\n\t\t'distribution_point_mismatch',\n\t\t'indirect_distribution_point',\n\t];\n\treturn precedence.find((failure) => failures.has(failure)) ?? 'scope_mismatch';\n}\n\nfunction scanCrlDistributionPoint(\n\tdistributionPoint: ParsedDistributionPoint,\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\tissuingDistributionPoint: ParsedIssuingDistributionPoint | undefined,\n\tisIndirectCrl: boolean,\n): CrlDistributionPointScanResult {\n\tconst issuerResult = scanCrlDistributionPointIssuer(\n\t\tdistributionPoint,\n\t\tcertificate,\n\t\tcrl,\n\t\tisIndirectCrl,\n\t);\n\tif (issuerResult !== undefined) return issuerResult;\n\tif (\n\t\t!matchesDistributionPointName(\n\t\t\tdistributionPoint.distributionPoint,\n\t\t\tissuingDistributionPoint?.distributionPoint,\n\t\t\tcrl.issuer,\n\t\t\tdistributionPoint.crlIssuer,\n\t\t)\n\t) {\n\t\treturn 'distribution_point_mismatch';\n\t}\n\treturn hasOverlappingReasons(distributionPoint.reasons, issuingDistributionPoint?.onlySomeReasons)\n\t\t? 'matched'\n\t\t: 'reasons_mismatch';\n}\n\nfunction scanCrlDistributionPointIssuer(\n\tdistributionPoint: ParsedDistributionPoint,\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\tisIndirectCrl: boolean,\n): CrlDistributionPointScanResult | undefined {\n\tif (!isIndirectCrl) {\n\t\treturn distributionPoint.crlIssuer === undefined ? undefined : 'indirect_distribution_point';\n\t}\n\tif (\n\t\tcompareDistinguishedNames(certificate.issuer, crl.issuer) &&\n\t\tdistributionPoint.crlIssuer === undefined\n\t) {\n\t\treturn undefined;\n\t}\n\tconst issuerMatch = matchesIndirectCrlIssuer(distributionPoint.crlIssuer, crl);\n\tif (issuerMatch === 'unsupported') return 'unsupported_indirect_crl_issuer';\n\treturn issuerMatch ? undefined : 'indirect_issuer_mismatch';\n}\n\nfunction crlDistributionPointScanFailure(\n\tresult: CrlDistributionPointScanFailure,\n): CrlApplicabilityFailure {\n\tif (result === 'reasons_mismatch') {\n\t\treturn nonApplicable(\n\t\t\t'reasons_mismatch',\n\t\t\t'certificate distribution point reasons do not overlap the CRL reason scope',\n\t\t);\n\t}\n\tif (result === 'unsupported_indirect_crl_issuer') {\n\t\treturn nonApplicable(\n\t\t\t'unsupported_indirect_crl',\n\t\t\t'indirect CRL distribution points must identify the CRL issuer with directoryName',\n\t\t);\n\t}\n\tif (result === 'indirect_issuer_mismatch') {\n\t\treturn nonApplicable(\n\t\t\t'issuer_mismatch',\n\t\t\t'certificate distribution points do not authorize this indirect CRL issuer',\n\t\t);\n\t}\n\tif (result === 'distribution_point_mismatch') {\n\t\treturn nonApplicable(\n\t\t\t'distribution_point_mismatch',\n\t\t\t'certificate distribution points do not match the CRL issuing distribution point',\n\t\t);\n\t}\n\tif (result === 'indirect_distribution_point') {\n\t\treturn nonApplicable(\n\t\t\t'unsupported_indirect_crl',\n\t\t\t'certificate distribution points that name alternate CRL issuers are not supported yet',\n\t\t);\n\t}\n\treturn nonApplicable(\n\t\t'distribution_point_mismatch',\n\t\t'certificate distribution points do not match the CRL scope',\n\t);\n}\n\n/** Verifies that a delta CRL is compatible with the given complete CRL (same issuer, AKI, IDP, and valid numbering). */\nfunction checkDeltaCrlCompatibility(\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tdeltaCrl: ParsedCertificateRevocationList,\n):\n\t| ErrorResult<\n\t\t\tCheckCertificateRevocationAgainstCrlErrorCode,\n\t\t\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\t\t\tCheckCertificateRevocationAgainstCrlFailure\n\t >\n\t| undefined {\n\tif (completeCrl.baseCrlNumber !== undefined) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'complete CRL input must not itself be a delta CRL',\n\t\t);\n\t}\n\tif (deltaCrl.baseCrlNumber === undefined) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'delta CRL input must include a delta CRL indicator',\n\t\t);\n\t}\n\tif (!compareDistinguishedNames(completeCrl.issuer, deltaCrl.issuer)) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'complete and delta CRLs must share the same issuer',\n\t\t);\n\t}\n\tif (completeCrl.authorityKeyIdentifier !== deltaCrl.authorityKeyIdentifier) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'complete and delta CRLs must share the same authority key identifier',\n\t\t);\n\t}\n\tif (\n\t\t!sameIssuingDistributionPoint(\n\t\t\tcompleteCrl.issuingDistributionPoint,\n\t\t\tdeltaCrl.issuingDistributionPoint,\n\t\t)\n\t) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'complete and delta CRLs must share the same issuing distribution point scope',\n\t\t);\n\t}\n\tif (completeCrl.crlNumber === undefined || deltaCrl.crlNumber === undefined) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'complete and delta CRLs must both carry CRL numbers for delta processing',\n\t\t);\n\t}\n\tif (completeCrl.crlNumber < deltaCrl.baseCrlNumber) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'delta CRL base number must not exceed the complete CRL number',\n\t\t);\n\t}\n\tif (completeCrl.crlNumber >= deltaCrl.crlNumber) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'delta CRL number must be newer than the complete CRL number',\n\t\t);\n\t}\n\tif (completeCrl.thisUpdate.getTime() > deltaCrl.thisUpdate.getTime()) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'delta CRL thisUpdate must not precede the complete CRL thisUpdate',\n\t\t);\n\t}\n\treturn undefined;\n}\n\n/** RFC 5280 §4.2.1.13 requires only the CRL issuer DN, with identical DER encoding. */\nfunction matchesIndirectCrlIssuer(\n\tcrlIssuerNames: readonly GeneralName[] | undefined,\n\tcrl: ParsedCertificateRevocationList,\n): boolean | 'unsupported' {\n\tif (crlIssuerNames === undefined || crlIssuerNames.length === 0) return false;\n\tif (crlIssuerNames.some((name) => name.type !== 'directoryName')) return 'unsupported';\n\treturn crlIssuerNames.every(\n\t\t(name) =>\n\t\t\tname.type === 'directoryName' &&\n\t\t\tname.derHex.toLowerCase() === crl.issuer.derHex.toLowerCase(),\n\t);\n}\n\n/** Determines whether a revoked entry's effective issuer matches the certificate's issuer. */\nfunction matchesRevokedEntryIssuer(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\teffectiveIssuer: readonly GeneralName[] | undefined,\n): 'match' | 'mismatch' | 'unsupported' {\n\tif (effectiveIssuer === undefined) {\n\t\treturn compareDistinguishedNames(certificate.issuer, crl.issuer) ? 'match' : 'mismatch';\n\t}\n\tlet sawUnsupportedName = false;\n\tfor (const generalName of effectiveIssuer) {\n\t\tif (generalName.type === 'directoryName') {\n\t\t\tif (directoryNameDerHexMatchesParsedName(generalName.derHex, certificate.issuer)) {\n\t\t\t\treturn 'match';\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tsawUnsupportedName = true;\n\t}\n\treturn sawUnsupportedName ? 'unsupported' : 'mismatch';\n}\n\n/** Shorthand for building a `non_applicable` failure result with the given reason. */\nfunction nonApplicable(\n\treason: CrlApplicabilityFailureReason,\n\tmessage: string,\n): ErrorResult<\n\tCheckCertificateRevocationAgainstCrlErrorCode,\n\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\tCheckCertificateRevocationAgainstCrlFailure\n> {\n\treturn checkCertificateRevocationAgainstCrlFailureResult('non_applicable', message, { reason });\n}\n\n/**\n * Merges complete and delta CRL entries into a final `good`/`revoked` status\n * per the RFC 5280 §6.3.3 (i)-(k) relying-party algorithm.\n *\n * Deliberately harder than (i)-(k) on `removeFromCRL`: the entry clears a\n * revocation only in the two situations §5.2.4(b)/§5.3.1 permit an issuer to\n * emit it, a complete-CRL `certificateHold` entry or a certificate that\n * expired before the delta CRL's thisUpdate.\n */\nfunction resolveCertificateRevocationStatus(\n\tcertificate: ParsedCertificate,\n\tdeltaThisUpdate: Date | undefined,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tcompleteEntry: ParsedRevokedCertificate | undefined,\n\tdeltaEntry: ParsedRevokedCertificate | undefined,\n\tcoveredReasons: readonly DistributionPointReason[],\n\tunrecognizedReasonCode: UnrecognizedReasonCodePolicy,\n): CheckCertificateRevocationAgainstCrlResult {\n\tif (deltaEntry !== undefined) {\n\t\tif (deltaEntry.reasonCode === 'removeFromCRL') {\n\t\t\tif (\n\t\t\t\tcompleteEntry?.reasonCode === 'certificateHold' ||\n\t\t\t\t(deltaThisUpdate !== undefined &&\n\t\t\t\t\tcertificate.notAfter.getTime() < deltaThisUpdate.getTime())\n\t\t\t) {\n\t\t\t\treturn checkCertificateRevocationAgainstCrlSuccess({\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\tcrl: completeCrl,\n\t\t\t\t\tcoveredReasons,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\treturn revokedEntryResult(completeCrl, deltaEntry, unrecognizedReasonCode);\n\t\t}\n\t}\n\tif (completeEntry === undefined) {\n\t\treturn checkCertificateRevocationAgainstCrlSuccess({\n\t\t\tstatus: 'good',\n\t\t\tcrl: completeCrl,\n\t\t\tcoveredReasons,\n\t\t});\n\t}\n\treturn revokedEntryResult(completeCrl, completeEntry, unrecognizedReasonCode);\n}\n\nfunction revokedEntryResult(\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tentry: ParsedRevokedCertificate,\n\tunrecognizedReasonCode: UnrecognizedReasonCodePolicy,\n): CheckCertificateRevocationAgainstCrlResult {\n\tif (unrecognizedReasonCode === 'reject' && typeof entry.reasonCode === 'object') {\n\t\treturn checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\t'reason_code_unrecognized',\n\t\t\t`CRL entry carries unrecognized reason code ${String(entry.reasonCode.code)}`,\n\t\t);\n\t}\n\treturn checkCertificateRevocationAgainstCrlSuccess({\n\t\tstatus: 'revoked',\n\t\tcrl: completeCrl,\n\t\trevocationDate: entry.revocationDate,\n\t\t...(entry.reasonCode === undefined ? {} : { reasonCode: entry.reasonCode }),\n\t});\n}\n\n/**\n * Returns `true` if the certificate's distribution-point name matches the CRL's IDP name.\n *\n * Per RFC 5280 §4.2.1.13, when the certificate uses `nameRelativeToCRLIssuer` (relativeName),\n * the full distribution point name is formed by appending that RDN to the CRL issuer's DN.\n * This resolved name is then compared against the CRL's IDP fullName directoryName entries.\n */\nfunction matchesDistributionPointName(\n\tcertificatePoint: ParsedDistributionPointName | undefined,\n\tcrlPoint: ParsedDistributionPointName | undefined,\n\tcrlIssuer: ParsedName,\n\tcertificateCrlIssuer: readonly GeneralName[] | undefined,\n): boolean {\n\tif (crlPoint === undefined) {\n\t\treturn true;\n\t}\n\tif (certificatePoint === undefined) {\n\t\treturn matchesIdpNameAgainstCrlIssuer(crlPoint, certificateCrlIssuer, crlIssuer);\n\t}\n\tif (certificatePoint.type === 'fullName' && crlPoint.type === 'fullName') {\n\t\treturn certificatePoint.fullName.some((leftName) =>\n\t\t\tcrlPoint.fullName.some((rightName) => compareGeneralNames(leftName, rightName)),\n\t\t);\n\t}\n\tif (certificatePoint.type === 'relativeName' && crlPoint.type === 'fullName') {\n\t\tconst resolvedDnHex = resolveRelativeNameToDnHex(crlIssuer, certificatePoint.relativeName);\n\t\treturn crlPoint.fullName.some(\n\t\t\t(name) => name.type === 'directoryName' && name.derHex === resolvedDnHex,\n\t\t);\n\t}\n\tif (certificatePoint.type === 'relativeName' && crlPoint.type === 'relativeName') {\n\t\treturn compareRelativeDistinguishedNames(certificatePoint.relativeName, crlPoint.relativeName);\n\t}\n\tif (certificatePoint.type === 'fullName' && crlPoint.type === 'relativeName') {\n\t\tconst resolvedDnHex = resolveRelativeNameToDnHex(crlIssuer, crlPoint.relativeName);\n\t\treturn certificatePoint.fullName.some(\n\t\t\t(name) => name.type === 'directoryName' && name.derHex === resolvedDnHex,\n\t\t);\n\t}\n\treturn false;\n}\n\n/**\n * RFC 5280 §6.3.3 (b)(2)(i): when the certificate's distribution point omits the\n * distributionPoint field, match the CRL IDP's distributionPoint names against\n * the distribution point's `cRLIssuer` names.\n */\nfunction matchesIdpNameAgainstCrlIssuer(\n\tcrlPoint: ParsedDistributionPointName,\n\tcertificateCrlIssuer: readonly GeneralName[] | undefined,\n\tcrlIssuer: ParsedName,\n): boolean {\n\tif (certificateCrlIssuer === undefined) {\n\t\treturn false;\n\t}\n\tif (crlPoint.type === 'fullName') {\n\t\treturn certificateCrlIssuer.some((issuerName) =>\n\t\t\tcrlPoint.fullName.some((name) => compareGeneralNames(issuerName, name)),\n\t\t);\n\t}\n\tconst resolvedDnHex = resolveRelativeNameToDnHex(crlIssuer, crlPoint.relativeName);\n\treturn certificateCrlIssuer.some(\n\t\t(issuerName) => issuerName.type === 'directoryName' && issuerName.derHex === resolvedDnHex,\n\t);\n}\n\n/** Constructs a full DN by appending an RDN to an existing Name, returning hex-encoded DER. */\nfunction resolveRelativeNameToDnHex(\n\tissuer: ParsedName,\n\trelativeName: ParsedRelativeDistinguishedName,\n): string {\n\t// Collect existing RDN DER bytes from issuer\n\tconst rdnDerParts = issuer.rdns.map((rdn) => hexToBytes(rdn.derHex));\n\t// The relativeName.derHex has implicit tag [1] (0xa1) from the CHOICE encoding.\n\t// Extract the content and re-wrap as a proper RDN SET (tag 0x31).\n\tconst relativeNameDer = hexToBytes(relativeName.derHex);\n\tconst relativeNameRdnDer = rebuildRelativeNameAsSet(relativeNameDer);\n\trdnDerParts.push(relativeNameRdnDer);\n\t// Wrap in a Name SEQUENCE\n\treturn toHex(sequence(rdnDerParts));\n}\n\n/** Converts an implicit-tagged [1] relativeName to a proper SET-tagged RDN. */\nfunction rebuildRelativeNameAsSet(implicitTaggedDer: Uint8Array): Uint8Array {\n\t// The implicit tag [1] is 0xa1 (context-specific constructed).\n\t// Parse the element to get content, then re-wrap with SET tag 0x31.\n\tconst element = readRootElement(implicitTaggedDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\treturn tlv(0x31, element.value);\n}\n\n/** Deep-compares two issuing distribution point extensions for delta-CRL compatibility. */\nfunction sameIssuingDistributionPoint(\n\tleft: ParsedIssuingDistributionPoint | undefined,\n\tright: ParsedIssuingDistributionPoint | undefined,\n): boolean {\n\tif (left === undefined || right === undefined) {\n\t\treturn left === right;\n\t}\n\treturn (\n\t\tsameDistributionPointName(left.distributionPoint, right.distributionPoint) &&\n\t\t(left.onlyContainsUserCerts === true) === (right.onlyContainsUserCerts === true) &&\n\t\t(left.onlyContainsCACerts === true) === (right.onlyContainsCACerts === true) &&\n\t\t(left.indirectCrl === true) === (right.indirectCrl === true) &&\n\t\t(left.onlyContainsAttributeCerts === true) === (right.onlyContainsAttributeCerts === true) &&\n\t\tsameReasonSet(left.onlySomeReasons, right.onlySomeReasons)\n\t);\n}\n\n/** Compares two DistributionPointName values (fullName set or relativeName). */\nfunction sameDistributionPointName(\n\tleft: ParsedDistributionPointName | undefined,\n\tright: ParsedDistributionPointName | undefined,\n): boolean {\n\tif (left === undefined || right === undefined) {\n\t\treturn left === right;\n\t}\n\tif (left.type === 'fullName' && right.type === 'fullName') {\n\t\treturn sameGeneralNameSet(left.fullName, right.fullName);\n\t}\n\tif (left.type === 'relativeName' && right.type === 'relativeName') {\n\t\treturn compareRelativeDistinguishedNames(left.relativeName, right.relativeName);\n\t}\n\treturn false;\n}\n\n/** Set-equality comparison for GeneralName arrays (order-independent). */\nfunction sameGeneralNameSet(left: readonly GeneralName[], right: readonly GeneralName[]): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tconst matched = Array.from({ length: right.length }, () => false);\n\tfor (const leftName of left) {\n\t\tlet found = false;\n\t\tfor (let index = 0; index < right.length; index += 1) {\n\t\t\tconst rightName = right[index];\n\t\t\tif (rightName === undefined || matched[index]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!compareGeneralNames(leftName, rightName)) {\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/** Set-equality comparison for DistributionPointReason arrays. */\nfunction sameReasonSet(\n\tleft: ParsedBitFlags<DistributionPointReason> | undefined,\n\tright: ParsedBitFlags<DistributionPointReason> | undefined,\n): boolean {\n\tif (left === undefined || right === undefined) {\n\t\treturn left === right;\n\t}\n\tif (left.flags.length !== right.flags.length) {\n\t\treturn false;\n\t}\n\treturn left.flags.every((reason) => right.flags.includes(reason));\n}\n\n/** Returns `true` if the certificate's DP reasons overlap the CRL's `onlySomeReasons`, or if either is absent (= all reasons). */\nfunction hasOverlappingReasons(\n\tcertificateReasons: ParsedBitFlags<DistributionPointReason> | undefined,\n\tcrlReasons: ParsedBitFlags<DistributionPointReason> | undefined,\n): boolean {\n\tif (certificateReasons === undefined || crlReasons === undefined) {\n\t\treturn true;\n\t}\n\treturn certificateReasons.flags.some((reason) => crlReasons.flags.includes(reason));\n}\n\n/** Value-equality for two GeneralName entries, using DER comparison for directoryName. */\nfunction compareGeneralNames(left: GeneralName, right: GeneralName): boolean {\n\tif (left.type === 'dns' && right.type === 'dns') {\n\t\t// RFC 5280 §7.2: dNSName comparison is case-insensitive.\n\t\treturn left.value.toLowerCase() === right.value.toLowerCase();\n\t}\n\tif (left.type === 'srv' && right.type === 'srv') {\n\t\t// RFC 4985 §2: the SRVName Service and the DNS Name both compare case-insensitively.\n\t\treturn compareSrvNames(left.value.toLowerCase(), right.value.toLowerCase());\n\t}\n\tif (left.type === 'email' && right.type === 'email') {\n\t\treturn compareRfc822Names(left.value, right.value);\n\t}\n\tif (left.type === 'smtpUtf8Mailbox' && right.type === 'smtpUtf8Mailbox') {\n\t\t// RFC 9598 §5: two SmtpUTF8Mailboxes are equivalent on an exact octet-for-octet match.\n\t\treturn left.value === right.value;\n\t}\n\tif (left.type === 'ip' && right.type === 'ip') {\n\t\treturn left.value === right.value;\n\t}\n\tif (left.type === 'uri' && right.type === 'uri') {\n\t\treturn compareUniformResourceIdentifiers(left.value, right.value);\n\t}\n\tif (left.type === 'directoryName' && right.type === 'directoryName') {\n\t\tconst leftName = parseDerHexName(left.derHex);\n\t\tconst rightName = parseDerHexName(right.derHex);\n\t\tif (leftName === undefined || rightName === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn compareDistinguishedNames(leftName, rightName);\n\t}\n\treturn compareOpaqueGeneralNames(left, right);\n}\n\nfunction compareSrvNames(left: string, right: string): boolean {\n\tconst leftParts = parsePresentedSrvName(left);\n\tconst rightParts = parsePresentedSrvName(right);\n\tif (leftParts === undefined || rightParts === undefined) {\n\t\treturn left === right;\n\t}\n\treturn leftParts.service === rightParts.service && leftParts.name === rightParts.name;\n}\n\n/** Encoding equality for the GeneralName alternatives carried as DER or an OID. */\nfunction compareOpaqueGeneralNames(left: GeneralName, right: GeneralName): boolean {\n\tif (left.type === 'otherName' && right.type === 'otherName') {\n\t\treturn left.typeId === right.typeId && bytesEqual(left.value, right.value);\n\t}\n\tif (left.type === 'upn' && right.type === 'upn') {\n\t\treturn left.value === right.value;\n\t}\n\tif (left.type === 'krb5PrincipalName' && right.type === 'krb5PrincipalName') {\n\t\treturn (\n\t\t\tleft.realm === right.realm &&\n\t\t\tleft.nameType === right.nameType &&\n\t\t\tleft.nameString.length === right.nameString.length &&\n\t\t\tleft.nameString.every((component, index) => component === right.nameString[index])\n\t\t);\n\t}\n\tif (\n\t\t(left.type === 'x400Address' && right.type === 'x400Address') ||\n\t\t(left.type === 'ediPartyName' && right.type === 'ediPartyName')\n\t) {\n\t\treturn bytesEqual(left.value, right.value);\n\t}\n\tif (left.type === 'registeredID' && right.type === 'registeredID') {\n\t\treturn left.value === right.value;\n\t}\n\tif (left.type === 'unknown' && right.type === 'unknown') {\n\t\treturn left.tag === right.tag && bytesEqual(left.value, right.value);\n\t}\n\treturn false;\n}\n\n/** RFC 5280 §7.5: rfc822Name local-part is case-sensitive, the host-part case-insensitive. */\nfunction compareRfc822Names(left: string, right: string): boolean {\n\tconst leftAt = left.lastIndexOf('@');\n\tconst rightAt = right.lastIndexOf('@');\n\tif (leftAt < 0 || rightAt < 0) {\n\t\treturn left.toLowerCase() === right.toLowerCase();\n\t}\n\treturn (\n\t\tleft.slice(0, leftAt) === right.slice(0, rightAt) &&\n\t\tleft.slice(leftAt + 1).toLowerCase() === right.slice(rightAt + 1).toLowerCase()\n\t);\n}\n\n/** RFC 5280 §7.4: URIs compare only after syntax-based and scheme-based normalization. */\nfunction compareUniformResourceIdentifiers(left: string, right: string): boolean {\n\tif (left === right) {\n\t\treturn true;\n\t}\n\tconst normalizedLeft = normalizeUriForComparison(left);\n\tif (normalizedLeft === undefined) {\n\t\treturn false;\n\t}\n\treturn normalizedLeft === normalizeUriForComparison(right);\n}\n\n/**\n * The schemes RFC 5280 §7.4 step 5 requires implementations to recognise, with\n * the default port that scheme-based normalization elides. `ldaps` is included\n * as the TLS form of the mandatory `ldap` scheme.\n */\nconst URI_DEFAULT_PORT_BY_SCHEME: ReadonlyMap<string, string> = new Map([\n\t['ftp', '21'],\n\t['http', '80'],\n\t['https', '443'],\n\t['ldap', '389'],\n\t['ldaps', '636'],\n]);\n\n/**\n * Applies the RFC 5280 §7.4 comparison preparation: IDN labels to ASCII\n * Compatible Encoding, lowercased scheme and host, percent-encoding and path\n * segment normalization, and scheme-based normalization. The URL parser covers\n * path segments for every scheme and the scheme case; the remaining steps are\n * applied here because it leaves the host of a non-special scheme such as\n * `ldap` untouched and never normalizes percent-encoding.\n *\n * @returns `undefined` when the value does not parse as an absolute URI.\n */\nfunction normalizeUriForComparison(value: string): string | undefined {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (url.hostname !== '') {\n\t\tconst host = normalizeUriHost(url.hostname);\n\t\tif (host === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\turl.hostname = host;\n\t}\n\tif (url.port === URI_DEFAULT_PORT_BY_SCHEME.get(url.protocol.slice(0, -1))) {\n\t\turl.port = '';\n\t}\n\treturn normalizePercentEncoding(url.href);\n}\n\n/**\n * Reparses a host under a special scheme so the URL parser applies IDNA and\n * lowercasing to it, which it skips for opaque hosts.\n *\n * @returns `undefined` when the host does not survive the round trip intact.\n */\nfunction normalizeUriHost(hostname: string): string | undefined {\n\ttry {\n\t\tconst probe = new URL(`https://${decodeHostPercentEncoding(hostname)}`);\n\t\treturn probe.href === `https://${probe.hostname}/` ? probe.hostname : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Recovers the Unicode host an opaque-host URI carries as percent-encoded UTF-8. */\nfunction decodeHostPercentEncoding(hostname: string): string {\n\ttry {\n\t\treturn decodeURIComponent(hostname);\n\t} catch {\n\t\treturn hostname;\n\t}\n}\n\nconst PERCENT_TRIPLET = /%[0-9A-Fa-f]{2}/g;\n\n/** RFC 3986 §6.2.2.2: unreserved triplets decode, every other triplet uppercases. */\nfunction normalizePercentEncoding(value: string): string {\n\treturn value.replace(PERCENT_TRIPLET, (triplet) => {\n\t\tconst code = Number.parseInt(triplet.slice(1), 16);\n\t\treturn isUnreservedUriCharacter(code) ? String.fromCharCode(code) : triplet.toUpperCase();\n\t});\n}\n\n/** RFC 3986 §2.3 unreserved set: `ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"`. */\nfunction isUnreservedUriCharacter(code: number): boolean {\n\treturn (\n\t\t(code >= 0x41 && code <= 0x5a) ||\n\t\t(code >= 0x61 && code <= 0x7a) ||\n\t\t(code >= 0x30 && code <= 0x39) ||\n\t\tcode === 0x2d ||\n\t\tcode === 0x2e ||\n\t\tcode === 0x5f ||\n\t\tcode === 0x7e\n\t);\n}\n\n/** Constant-length byte-array equality check. */\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < left.length; index += 1) {\n\t\tif (left[index] !== right[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Assembles the CRL-level v2 extensions (AKI, CRLNumber, deltaCRLIndicator, IDP, freshestCRL). */\nfunction buildCrlExtensions(\n\tissuerCertificate: ParsedCertificate,\n\tcrlNumber: Uint8Array,\n\tbaseCrlNumber?: Uint8Array,\n\tissuingDistributionPoint?: IssuingDistributionPoint,\n\tfreshestCrlDistributionPoints?: readonly DistributionPoint[],\n): Uint8Array[] {\n\tconst extensions: Uint8Array[] = [\n\t\tencodeExtension(\n\t\t\tOIDS.authorityKeyIdentifier,\n\t\t\tsequence([implicitPrimitiveContext(0, issuerKeyIdentifier(issuerCertificate))]),\n\t\t),\n\t\tencodeExtension(OIDS.cRLNumber, crlNumber),\n\t];\n\tif (baseCrlNumber !== undefined) {\n\t\textensions.push(encodeExtension(OIDS.deltaCRLIndicator, baseCrlNumber, true));\n\t}\n\tif (issuingDistributionPoint !== undefined) {\n\t\textensions.push(\n\t\t\tencodeExtension(\n\t\t\t\tOIDS.issuingDistributionPoint,\n\t\t\t\tencodeIssuingDistributionPoint(issuingDistributionPoint),\n\t\t\t\ttrue,\n\t\t\t),\n\t\t);\n\t}\n\tif (freshestCrlDistributionPoints !== undefined && freshestCrlDistributionPoints.length > 0) {\n\t\textensions.push(\n\t\t\tencodeExtension(OIDS.freshestCRL, encodeCrlDistributionPoints(freshestCrlDistributionPoints)),\n\t\t);\n\t}\n\treturn extensions;\n}\n\n/** DER-encodes a single revokedCertificate SEQUENCE (serial, date, optional extensions). */\nfunction createRevokedCertificate(entry: RevokedCertificateInput, thisUpdate: Date): Uint8Array {\n\tconst extensions = buildRevokedCertificateExtensions(entry);\n\treturn sequence([\n\t\tinteger(entry.serialNumber),\n\t\ttime(entry.revocationDate ?? thisUpdate),\n\t\t...(extensions.length === 0 ? [] : [sequence(extensions)]),\n\t]);\n}\n\n/** Encodes CRL entry extensions (reasonCode, invalidityDate). */\nfunction buildRevokedCertificateExtensions(entry: RevokedCertificateInput): Uint8Array[] {\n\tconst extensions: Uint8Array[] = [];\n\tif (entry.reasonCode !== undefined) {\n\t\textensions.push(\n\t\t\tencodeExtension(\n\t\t\t\tOIDS.cRLReason,\n\t\t\t\ttlv(0x0a, Uint8Array.of(REVOCATION_REASON_CODES[entry.reasonCode])),\n\t\t\t),\n\t\t);\n\t}\n\tif (entry.invalidityDate !== undefined) {\n\t\textensions.push(encodeExtension(OIDS.invalidityDate, generalizedTime(entry.invalidityDate)));\n\t}\n\treturn extensions;\n}\n\n/** Decodes per-entry CRL extensions (reasonCode, invalidityDate, certificateIssuer). */\nfunction parseRevokedCertificateExtensions(\n\tentryDer: Uint8Array | undefined,\n\telement: DerElement | undefined,\n): {\n\treadonly reasonCode?: ParsedRevocationReason;\n\treadonly invalidityDate?: Date;\n\treadonly certificateIssuer?: readonly GeneralName[];\n} {\n\tif (entryDer === undefined || element === undefined) {\n\t\treturn {};\n\t}\n\tconst fields: MutableRevokedCertificateExtensionFields = {};\n\tconst seenOids = new Set<string>();\n\tfor (const extension of childrenOf(entryDer, element)) {\n\t\tparseRevokedCertificateExtension(entryDer, extension, seenOids, fields);\n\t}\n\treturn {\n\t\t...(fields.reasonCode === undefined ? {} : { reasonCode: fields.reasonCode }),\n\t\t...(fields.invalidityDate === undefined ? {} : { invalidityDate: fields.invalidityDate }),\n\t\t...(fields.certificateIssuer === undefined\n\t\t\t? {}\n\t\t\t: { certificateIssuer: fields.certificateIssuer }),\n\t};\n}\n\nfunction parseRevokedCertificateExtension(\n\tentryDer: Uint8Array,\n\textension: DerElement,\n\tseenOids: Set<string>,\n\tfields: MutableRevokedCertificateExtensionFields,\n): void {\n\tconst parts = childrenOf(entryDer, extension);\n\tif (parts.length < 2 || parts.length > 3) {\n\t\tthrow new Error('Malformed revoked certificate extension');\n\t}\n\tif (parts.length === 3 && parts[1]?.tag !== 0x01) {\n\t\tthrow new Error('Malformed revoked certificate extension');\n\t}\n\tconst oid = decodeObjectIdentifier(\n\t\trequireElement(parts[0], 'revoked certificate extension OID').value,\n\t);\n\tif (seenOids.has(oid)) {\n\t\tthrow new Error(`Duplicate revoked certificate extension OID: ${oid}`);\n\t}\n\tseenOids.add(oid);\n\tconst critical =\n\t\tparts.length === 3\n\t\t\t? decodeBoolean(requireElement(parts[1], 'revoked certificate extension critical').value)\n\t\t\t: false;\n\tconst valueElement = requireElement(\n\t\tparts[parts.length - 1],\n\t\t'revoked certificate extension value',\n\t);\n\tif (valueElement.tag !== 0x04) {\n\t\tthrow new Error('Revoked certificate extension value must use OCTET STRING');\n\t}\n\tif (critical && !isSupportedRevokedCertificateExtensionOid(oid)) {\n\t\tthrow new Error(`Unsupported critical revoked certificate extension OID: ${oid}`);\n\t}\n\tapplyRevokedCertificateExtensionValue(oid, valueElement.value, critical, fields);\n}\n\nfunction isSupportedRevokedCertificateExtensionOid(oid: string): boolean {\n\treturn oid === OIDS.cRLReason || oid === OIDS.invalidityDate || oid === OIDS.certificateIssuer;\n}\n\nfunction applyRevokedCertificateExtensionValue(\n\toid: string,\n\tvalue: Uint8Array,\n\tcritical: boolean,\n\tfields: MutableRevokedCertificateExtensionFields,\n): void {\n\tif (oid === OIDS.cRLReason) {\n\t\tconst enumerated = readRootElement(value, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (enumerated.tag !== 0x0a) {\n\t\t\tthrow new Error('cRLReason must use ENUMERATED');\n\t\t}\n\t\tconst reasonCode = parsedRevocationReason(\n\t\t\tdecodeNonNegativeIntegerBigInt(enumerated.value, 'cRLReason'),\n\t\t);\n\t\tif (critical && typeof reasonCode !== 'string') {\n\t\t\tthrow new Error(\n\t\t\t\t`Critical cRLReason holds unrecognized reason code ${String(reasonCode.code)}`,\n\t\t\t);\n\t\t}\n\t\tfields.reasonCode = reasonCode;\n\t}\n\tif (oid === OIDS.invalidityDate) {\n\t\tfields.invalidityDate = parseTime(readRootElement(value, { maxDepth: DEFAULT_MAX_DER_DEPTH }));\n\t}\n\tif (oid === OIDS.certificateIssuer) {\n\t\tconst generalNames = readRootElement(value, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (generalNames.tag !== 0x30) {\n\t\t\tthrow new Error('certificateIssuer must use SEQUENCE');\n\t\t}\n\t\tfields.certificateIssuer = parseGeneralNames(value, generalNames);\n\t}\n}\n\n/** Decodes the IssuingDistributionPoint extension from its OCTET STRING content. */\nfunction parseIssuingDistributionPoint(valueDer: Uint8Array): ParsedIssuingDistributionPoint {\n\tconst sequenceElement = readRootElement(valueDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tconst fields: MutableIssuingDistributionPointFields = {};\n\tfor (const child of childrenOf(valueDer, sequenceElement)) {\n\t\tparseIssuingDistributionPointField(valueDer, child, fields);\n\t}\n\treturn {\n\t\t...(fields.distributionPoint === undefined\n\t\t\t? {}\n\t\t\t: { distributionPoint: fields.distributionPoint }),\n\t\t...(fields.onlySomeReasons === undefined ? {} : { onlySomeReasons: fields.onlySomeReasons }),\n\t\t...(fields.indirectCrl === undefined ? {} : { indirectCrl: fields.indirectCrl }),\n\t\t...parseIssuingDistributionPointScope(fields),\n\t};\n}\n\n/** RFC 5280 §5.2.5: at most one `onlyContains*` flag may be TRUE. */\nfunction parseIssuingDistributionPointScope(\n\tfields: MutableIssuingDistributionPointFields,\n): ParsedIssuingDistributionPointScope {\n\tconst userCerts = fields.onlyContainsUserCerts;\n\tconst caCerts = fields.onlyContainsCACerts;\n\tconst attributeCerts = fields.onlyContainsAttributeCerts;\n\tif (userCerts === true) {\n\t\tif (caCerts === true || attributeCerts === true) {\n\t\t\tthrow new Error(IDP_SCOPE_CONFLICT);\n\t\t}\n\t\treturn { onlyContainsUserCerts: true, ...unselectedScopeFlags({ caCerts, attributeCerts }) };\n\t}\n\tif (caCerts === true) {\n\t\tif (attributeCerts === true) {\n\t\t\tthrow new Error(IDP_SCOPE_CONFLICT);\n\t\t}\n\t\treturn { onlyContainsCACerts: true, ...unselectedScopeFlags({ userCerts, attributeCerts }) };\n\t}\n\tif (attributeCerts === true) {\n\t\treturn { onlyContainsAttributeCerts: true, ...unselectedScopeFlags({ userCerts, caCerts }) };\n\t}\n\treturn unselectedScopeFlags({ userCerts, caCerts, attributeCerts });\n}\n\n/** Keeps the explicit-FALSE flags the encoding carried, omitting the ones it left out. */\nfunction unselectedScopeFlags(flags: {\n\treadonly userCerts?: false;\n\treadonly caCerts?: false;\n\treadonly attributeCerts?: false;\n}): {\n\treadonly onlyContainsUserCerts?: false;\n\treadonly onlyContainsCACerts?: false;\n\treadonly onlyContainsAttributeCerts?: false;\n} {\n\treturn {\n\t\t...(flags.userCerts === undefined ? {} : { onlyContainsUserCerts: flags.userCerts }),\n\t\t...(flags.caCerts === undefined ? {} : { onlyContainsCACerts: flags.caCerts }),\n\t\t...(flags.attributeCerts === undefined\n\t\t\t? {}\n\t\t\t: { onlyContainsAttributeCerts: flags.attributeCerts }),\n\t};\n}\n\nconst IDP_SCOPE_CONFLICT = 'IssuingDistributionPoint scope booleans are mutually exclusive';\n\nfunction parseIssuingDistributionPointField(\n\tvalueDer: Uint8Array,\n\tchild: DerElement,\n\tfields: MutableIssuingDistributionPointFields,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0xa0: {\n\t\t\tif (fields.distributionPoint !== undefined) {\n\t\t\t\tthrow new Error('IssuingDistributionPoint distributionPoint must not repeat');\n\t\t\t}\n\t\t\tconst distributionPoint = parseDistributionPointName(valueDer, child);\n\t\t\tif (distributionPoint !== undefined) {\n\t\t\t\tfields.distributionPoint = distributionPoint;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tcase 0x81:\n\t\t\tfields.onlyContainsUserCerts = parseUniqueIssuingDistributionPointBoolean(\n\t\t\t\tfields.onlyContainsUserCerts,\n\t\t\t\tchild,\n\t\t\t\t'onlyContainsUserCerts',\n\t\t\t);\n\t\t\treturn;\n\t\tcase 0x82:\n\t\t\tfields.onlyContainsCACerts = parseUniqueIssuingDistributionPointBoolean(\n\t\t\t\tfields.onlyContainsCACerts,\n\t\t\t\tchild,\n\t\t\t\t'onlyContainsCACerts',\n\t\t\t);\n\t\t\treturn;\n\t\tcase 0x83:\n\t\t\tif (fields.onlySomeReasons !== undefined) {\n\t\t\t\tthrow new Error('IssuingDistributionPoint onlySomeReasons must not repeat');\n\t\t\t}\n\t\t\tfields.onlySomeReasons = parseDistributionPointReasonFlagsContent(child.value);\n\t\t\treturn;\n\t\tcase 0x84:\n\t\t\tfields.indirectCrl = parseUniqueIssuingDistributionPointBoolean(\n\t\t\t\tfields.indirectCrl,\n\t\t\t\tchild,\n\t\t\t\t'indirectCrl',\n\t\t\t);\n\t\t\treturn;\n\t\tcase 0x85:\n\t\t\tfields.onlyContainsAttributeCerts = parseUniqueIssuingDistributionPointBoolean(\n\t\t\t\tfields.onlyContainsAttributeCerts,\n\t\t\t\tchild,\n\t\t\t\t'onlyContainsAttributeCerts',\n\t\t\t);\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported IssuingDistributionPoint field tag: ${String(child.tag)}`);\n\t}\n}\n\nfunction parseUniqueIssuingDistributionPointBoolean(\n\texisting: boolean | undefined,\n\tchild: DerElement,\n\tfieldName: string,\n): boolean {\n\tif (existing !== undefined) {\n\t\tthrow new Error(`IssuingDistributionPoint ${fieldName} must not repeat`);\n\t}\n\treturn decodeBoolean(child.value);\n}\n\n/** Decodes a SEQUENCE OF DistributionPoint from DER. */\nfunction parseDistributionPoints(valueDer: Uint8Array): readonly ParsedDistributionPoint[] {\n\tconst sequenceElement = readRootElement(valueDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (sequenceElement.tag !== 0x30) {\n\t\tthrow new Error('DistributionPoints must use SEQUENCE');\n\t}\n\tconst elements = childrenOf(valueDer, sequenceElement);\n\tif (elements.length === 0) {\n\t\tthrow new Error('DistributionPoints must not be empty');\n\t}\n\treturn elements.map((distributionPoint) => parseDistributionPoint(valueDer, distributionPoint));\n}\n\n/** Decodes a DistributionPointName (fullName or relativeName). */\nfunction parseDistributionPointName(\n\tvalueDer: Uint8Array,\n\telement: DerElement,\n): ParsedDistributionPointName | undefined {\n\tconst children = childrenOf(valueDer, element);\n\tif (children.length !== 1) {\n\t\tthrow new Error('distributionPointName must contain exactly one choice');\n\t}\n\tconst distributionPointName = requireElement(children[0], 'distributionPointName');\n\tif (distributionPointName.tag === 0xa0) {\n\t\tconst fullName = childrenOf(valueDer, distributionPointName);\n\t\tif (fullName.length === 0) {\n\t\t\tthrow new Error('distributionPointName fullName must not be empty');\n\t\t}\n\t\tfor (const name of fullName) {\n\t\t\tif ((name.tag & 0xc0) !== 0x80) {\n\t\t\t\tthrow new Error('distributionPointName fullName must contain GeneralName entries');\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\ttype: 'fullName',\n\t\t\tfullName: fullName.map((name) => parseGeneralName(valueDer, name)),\n\t\t};\n\t}\n\tif (distributionPointName.tag === 0xa1) {\n\t\treturn {\n\t\t\ttype: 'relativeName',\n\t\t\trelativeName: parseRelativeName(valueDer, distributionPointName),\n\t\t};\n\t}\n\tthrow new Error(`Unsupported distributionPointName tag: ${String(distributionPointName.tag)}`);\n}\n\n/** Decodes a single DistributionPoint SEQUENCE. */\nfunction parseDistributionPoint(\n\tvalueDer: Uint8Array,\n\telement: DerElement,\n): ParsedDistributionPoint {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('DistributionPoint must use SEQUENCE');\n\t}\n\tconst fields: MutableDistributionPointFields = {};\n\tfor (const child of childrenOf(valueDer, element)) {\n\t\tparseDistributionPointField(valueDer, child, fields);\n\t}\n\tif (fields.distributionPoint === undefined && fields.crlIssuer === undefined) {\n\t\tthrow new Error('DistributionPoint must include distributionPoint or crlIssuer');\n\t}\n\treturn {\n\t\t...(fields.distributionPoint === undefined\n\t\t\t? {}\n\t\t\t: { distributionPoint: fields.distributionPoint }),\n\t\t...(fields.reasons === undefined ? {} : { reasons: fields.reasons }),\n\t\t...(fields.crlIssuer === undefined ? {} : { crlIssuer: fields.crlIssuer }),\n\t};\n}\n\nfunction parseDistributionPointField(\n\tvalueDer: Uint8Array,\n\tchild: DerElement,\n\tfields: MutableDistributionPointFields,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0xa0: {\n\t\t\tif (fields.distributionPoint !== undefined) {\n\t\t\t\tthrow new Error('DistributionPoint distributionPoint must not repeat');\n\t\t\t}\n\t\t\tconst distributionPoint = parseDistributionPointName(valueDer, child);\n\t\t\tif (distributionPoint !== undefined) fields.distributionPoint = distributionPoint;\n\t\t\treturn;\n\t\t}\n\t\tcase 0x81:\n\t\t\tif (fields.reasons !== undefined)\n\t\t\t\tthrow new Error('DistributionPoint reasons must not repeat');\n\t\t\tfields.reasons = parseDistributionPointReasonFlagsContent(child.value);\n\t\t\treturn;\n\t\tcase 0xa2:\n\t\t\tif (fields.crlIssuer !== undefined)\n\t\t\t\tthrow new Error('DistributionPoint crlIssuer must not repeat');\n\t\t\tfields.crlIssuer = parseGeneralNames(valueDer, child);\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported DistributionPoint field tag: ${String(child.tag)}`);\n\t}\n}\n\n/** Decodes a RelativeDistinguishedName SET from an implicitly-tagged context element. */\nfunction parseRelativeName(\n\tvalueDer: Uint8Array,\n\telement: DerElement,\n): ParsedRelativeDistinguishedName {\n\tconst attributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const attributeSequence of childrenOf(valueDer, element)) {\n\t\tconst parts = childrenOf(valueDer, attributeSequence);\n\t\tconst oid = decodeObjectIdentifier(requireElement(parts[0], 'name OID').value);\n\t\tconst valueElement = requireElement(parts[1], 'name value');\n\t\tconst fieldKey = nameFieldKeyFromOid(oid);\n\t\tconst fieldValue = decodeNameValue(valueElement);\n\t\tconst attribute: ParsedNameAttribute =\n\t\t\tfieldKey === undefined\n\t\t\t\t? { oid, valueTag: valueElement.tag, value: fieldValue }\n\t\t\t\t: { oid, key: fieldKey, valueTag: valueElement.tag, value: fieldValue };\n\t\tattributes.push(attribute);\n\t\tif (fieldKey !== undefined && values[fieldKey] === undefined) {\n\t\t\tvalues[fieldKey] = fieldValue;\n\t\t}\n\t}\n\treturn {\n\t\tderHex: toHex(valueDer.slice(element.start - element.headerLength, element.end)),\n\t\tattributes,\n\t\tvalues,\n\t};\n}\n\n/** Decodes an ASN.1 string element (UTF8String, PrintableString, etc.) to a JS string. */\nfunction decodeNameValue(element: DerElement): string {\n\treturn decodeString(element.tag, element.value);\n}\n\n/** Machine-readable reason a CRL encoder rejected its construction input. */\nexport type CrlEncoderErrorCode =\n\t| 'crl_number_invalid'\n\t| 'distribution_point_full_name_empty'\n\t| 'issuer_certificate_invalid'\n\t| 'issuer_distinguished_name_empty'\n\t| 'invalid_date'\n\t| 'next_update_not_after_this_update';\n\n/** Throws a {@link ResultError} for a CRL encoder input-validation failure. */\nfunction throwCrlEncoderError(code: CrlEncoderErrorCode, message: string): never {\n\tthrowMicro509Error(code, message);\n}\n\n/** The parsed issuer certificate of a CRL being built. */\nfunction issuerCertificateOf(source: CrlCertificateSource): ParsedCertificate {\n\ttry {\n\t\treturn normalizeCrlCertificate(source);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\treturn throwCrlEncoderError(\n\t\t\t'issuer_certificate_invalid',\n\t\t\t'issuerCertificate must be a PEM, DER or parsed certificate',\n\t\t);\n\t}\n}\n\n/** RFC 5280 §5.2.3: \"Conforming CRL issuers MUST NOT use CRLNumber values longer than 20 octets.\" */\nconst CRL_NUMBER_MAX_OCTETS = 20;\n\n/** RFC 5280 §5.2.3 `CRLNumber ::= INTEGER (0..MAX)` as a DER INTEGER of at most 20 content octets. */\nfunction encodeCrlNumber(value: number | bigint, field: 'crlNumber' | 'baseCrlNumber'): Uint8Array {\n\tconst crlNumber =\n\t\ttypeof value === 'bigint' ? value : Number.isSafeInteger(value) ? BigInt(value) : -1n;\n\tconst hex = crlNumber.toString(16);\n\tconst magnitude = crlNumber < 0n ? undefined : hexToBytes(hex.length % 2 === 0 ? hex : `0${hex}`);\n\tconst first = magnitude?.[0];\n\tif (\n\t\tmagnitude === undefined ||\n\t\tfirst === undefined ||\n\t\tmagnitude.length + (first >= 0x80 ? 1 : 0) > CRL_NUMBER_MAX_OCTETS\n\t) {\n\t\tthrowCrlEncoderError(\n\t\t\t'crl_number_invalid',\n\t\t\t`${field} must be a non-negative integer of at most ${String(CRL_NUMBER_MAX_OCTETS)} octets (RFC 5280 §5.2.3)`,\n\t\t);\n\t}\n\treturn integer(magnitude);\n}\n\n/** RFC 5280 §5.2.3: a received CRLNumber of any length, since verifiers MUST handle up to 20 octets. */\nfunction decodeCrlNumber(value: Uint8Array): bigint {\n\tconst element = readRootElement(value, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (element.tag !== 0x02) {\n\t\tthrow new Error('CRLNumber must be an INTEGER');\n\t}\n\tdecodeIntegerMagnitude(element.value, 'CRLNumber');\n\treturn BigInt(`0x${toHex(element.value)}`);\n}\n\nfunction assertCrlDate(date: Date | undefined, field: string): void {\n\tif (date !== undefined && Number.isNaN(date.getTime())) {\n\t\tthrowCrlEncoderError('invalid_date', `${field} must be a valid date`);\n\t}\n}\n\n/** DER-encodes an IssuingDistributionPoint extension value. Throws on mutually-exclusive scope flags. */\nfunction encodeIssuingDistributionPoint(value: IssuingDistributionPoint): Uint8Array {\n\tconst certificateScopeFlags = [\n\t\tvalue.onlyContainsUserCerts === true,\n\t\tvalue.onlyContainsCACerts === true,\n\t\tvalue.onlyContainsAttributeCerts === true,\n\t].filter(Boolean).length;\n\tif (certificateScopeFlags > 1) {\n\t\tthrow new Error(\n\t\t\t'IssuingDistributionPoint can assert at most one of user, CA, or attribute cert scope',\n\t\t);\n\t}\n\tconst fields: Uint8Array[] = [];\n\tif (value.distributionPoint !== undefined) {\n\t\tfields.push(\n\t\t\timplicitConstructedContext(0, encodeDistributionPointName(value.distributionPoint)),\n\t\t);\n\t}\n\tif (value.onlyContainsUserCerts) {\n\t\tfields.push(implicitPrimitiveContext(1, Uint8Array.of(0xff)));\n\t}\n\tif (value.onlyContainsCACerts) {\n\t\tfields.push(implicitPrimitiveContext(2, Uint8Array.of(0xff)));\n\t}\n\tif (value.onlySomeReasons !== undefined && value.onlySomeReasons.length > 0) {\n\t\tfields.push(\n\t\t\timplicitPrimitiveContext(3, encodeDistributionPointReasonFlagsContent(value.onlySomeReasons)),\n\t\t);\n\t}\n\tif (value.indirectCrl) {\n\t\tfields.push(implicitPrimitiveContext(4, Uint8Array.of(0xff)));\n\t}\n\tif (value.onlyContainsAttributeCerts) {\n\t\tfields.push(implicitPrimitiveContext(5, Uint8Array.of(0xff)));\n\t}\n\treturn sequence(fields);\n}\n\n/** DER-encodes a DistributionPointName (fullName or relativeName). */\nfunction encodeDistributionPointName(\n\tvalue: IssuingDistributionPoint['distributionPoint'],\n): Uint8Array {\n\tif (value === undefined) {\n\t\tthrow new Error('IssuingDistributionPoint distributionPoint is required');\n\t}\n\tswitch (value.type) {\n\t\tcase 'fullName': {\n\t\t\tif (value.fullName.length === 0) {\n\t\t\t\tthrowCrlEncoderError(\n\t\t\t\t\t'distribution_point_full_name_empty',\n\t\t\t\t\t'DistributionPointName fullName must not be empty',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn implicitConstructedContext(0, concatGeneralNames(value.fullName));\n\t\t}\n\t\tcase 'relativeName': {\n\t\t\tconst relativeName = encodeRelativeDistinguishedName(value.relativeName);\n\t\t\tconst relativeNameElement = readElement(relativeName);\n\t\t\treturn implicitConstructedContext(\n\t\t\t\t1,\n\t\t\t\trelativeName.slice(relativeNameElement.start, relativeNameElement.end),\n\t\t\t);\n\t\t}\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = value;\n\t\t\tthrow new Error(`Unhandled DistributionPointName type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** DER-encodes and concatenates a list of GeneralName values. */\nfunction concatGeneralNames(names: readonly GeneralName[]): Uint8Array {\n\treturn concatBytes(names.map((name) => encodeSubjectAltName(name)));\n}\n\n/** Parses a Name SEQUENCE element into a full {@linkcode ParsedName}. */\nfunction parseIssuer(source: Uint8Array, element: DerElement): ParsedName {\n\tconst derHex = toHex(source.slice(element.start - element.headerLength, element.end));\n\tconst rdns: ParsedRelativeDistinguishedName[] = [];\n\tconst allAttributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const setElement of childrenOf(source, element)) {\n\t\tconst rdnAttributes: ParsedNameAttribute[] = [];\n\t\tconst rdnValues: Partial<Record<NameFieldKey, string>> = {};\n\t\tfor (const attrSequence of childrenOf(source, setElement)) {\n\t\t\tconst parts = childrenOf(source, attrSequence);\n\t\t\tconst oidElement = requireElement(parts[0], 'issuer attribute OID');\n\t\t\tconst valueElement = requireElement(parts[1], 'issuer attribute value');\n\t\t\tconst oid = decodeObjectIdentifier(oidElement.value);\n\t\t\tconst fieldValue = decodeNameValue(valueElement);\n\t\t\tconst fieldKey = nameFieldKeyFromOid(oid);\n\t\t\tconst attribute: ParsedNameAttribute =\n\t\t\t\tfieldKey !== undefined\n\t\t\t\t\t? { oid, key: fieldKey, valueTag: valueElement.tag, value: fieldValue }\n\t\t\t\t\t: { oid, valueTag: valueElement.tag, value: fieldValue };\n\t\t\trdnAttributes.push(attribute);\n\t\t\tallAttributes.push(attribute);\n\t\t\tif (fieldKey !== undefined) {\n\t\t\t\tif (rdnValues[fieldKey] === undefined) {\n\t\t\t\t\trdnValues[fieldKey] = fieldValue;\n\t\t\t\t}\n\t\t\t\tif (values[fieldKey] === undefined) {\n\t\t\t\t\tvalues[fieldKey] = fieldValue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trdns.push({\n\t\t\tderHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),\n\t\t\tattributes: rdnAttributes,\n\t\t\tvalues: rdnValues,\n\t\t});\n\t}\n\treturn { derHex, rdns, attributes: allAttributes, values };\n}\n\n/**\n * Re-parses a hex-encoded DER Name into a {@linkcode ParsedName}. Returns\n * `undefined` on malformed input and throws a decode refusal.\n */\nfunction parseDerHexName(hex: string): ParsedName | undefined {\n\ttry {\n\t\tconst bytes = hexToBytes(hex);\n\t\tconst root = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tconst element = unwrapNameElement(bytes, root);\n\t\tif (element.tag !== 0x30) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn parseIssuer(bytes, element);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\treturn undefined;\n\t}\n}\n\n/** The failure for a decode refusal a directoryName comparison threw. */\nfunction crlNameRefusalFailure(error: unknown): CrlApplicabilityFailure {\n\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\tif (refusal === undefined) {\n\t\tthrow error;\n\t}\n\treturn checkCertificateRevocationAgainstCrlFailureResult(refusal.code, refusal.message);\n}\n\nfunction unwrapNameElement(source: Uint8Array, element: DerElement): DerElement {\n\tif (element.tag !== 0x30) {\n\t\treturn element;\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length === 1 && child?.tag === 0x30) {\n\t\treturn child;\n\t}\n\treturn element;\n}\n\n/** Semantic comparison of a GeneralName directoryName `derHex` against a {@linkcode ParsedName}. */\nfunction directoryNameDerHexMatchesParsedName(derHex: string, name: ParsedName): boolean {\n\tconst parsed = parseDerHexName(derHex);\n\tif (parsed === undefined) {\n\t\treturn false;\n\t}\n\treturn compareDistinguishedNames(parsed, name);\n}\n\n/** Extracts the keyIdentifier field from an AuthorityKeyIdentifier extension value. */\nfunction parseAuthorityKeyIdentifier(bytes: Uint8Array): string | undefined {\n\tconst sequenceElement = readRootElement(bytes, {\n\t\tmaxDepth: DEFAULT_MAX_DER_DEPTH,\n\t\tallowOpaqueConstructedTags: [0xa1, 0xa2],\n\t});\n\tif (sequenceElement.tag !== 0x30) {\n\t\tthrow new Error('authorityKeyIdentifier must use SEQUENCE');\n\t}\n\tconst state: MutableAuthorityKeyIdentifierState = {\n\t\tsawAuthorityCertIssuer: false,\n\t\tsawAuthorityCertSerialNumber: false,\n\t\tlastFieldOrder: -1,\n\t};\n\tfor (const child of childrenOf(bytes, sequenceElement)) {\n\t\tparseAuthorityKeyIdentifierField(bytes, child, state);\n\t}\n\treturn state.keyIdentifier;\n}\n\nfunction parseAuthorityKeyIdentifierField(\n\tbytes: Uint8Array,\n\tchild: DerElement,\n\tstate: MutableAuthorityKeyIdentifierState,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0x80:\n\t\t\tparseAuthorityKeyIdentifierKeyId(child, state);\n\t\t\treturn;\n\t\tcase 0xa1:\n\t\t\tparseAuthorityKeyIdentifierIssuer(bytes, child, state);\n\t\t\treturn;\n\t\tcase 0x82:\n\t\t\tparseAuthorityKeyIdentifierSerial(child, state);\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported authorityKeyIdentifier field tag: ${String(child.tag)}`);\n\t}\n}\n\nfunction parseAuthorityKeyIdentifierKeyId(\n\tchild: DerElement,\n\tstate: MutableAuthorityKeyIdentifierState,\n): void {\n\tif (state.keyIdentifier !== undefined)\n\t\tthrow new Error('authorityKeyIdentifier keyIdentifier must not repeat');\n\tif (state.lastFieldOrder >= 0)\n\t\tthrow new Error('authorityKeyIdentifier fields must preserve DER order');\n\tstate.keyIdentifier = toHex(child.value);\n\tstate.lastFieldOrder = 0;\n}\n\nfunction parseAuthorityKeyIdentifierIssuer(\n\tbytes: Uint8Array,\n\tchild: DerElement,\n\tstate: MutableAuthorityKeyIdentifierState,\n): void {\n\tif (state.sawAuthorityCertIssuer) {\n\t\tthrow new Error('authorityKeyIdentifier authorityCertIssuer must not repeat');\n\t}\n\tif (state.lastFieldOrder >= 1)\n\t\tthrow new Error('authorityKeyIdentifier fields must preserve DER order');\n\tparseGeneralNames(bytes, child);\n\tstate.sawAuthorityCertIssuer = true;\n\tstate.lastFieldOrder = 1;\n}\n\nfunction parseAuthorityKeyIdentifierSerial(\n\tchild: DerElement,\n\tstate: MutableAuthorityKeyIdentifierState,\n): void {\n\tif (state.sawAuthorityCertSerialNumber) {\n\t\tthrow new Error('authorityKeyIdentifier authorityCertSerialNumber must not repeat');\n\t}\n\tif (state.lastFieldOrder >= 2 || !state.sawAuthorityCertIssuer) {\n\t\tthrow new Error('authorityKeyIdentifier fields must preserve DER order');\n\t}\n\tvalidateImplicitSerialNumberEncoding(\n\t\tchild.value,\n\t\t'authorityKeyIdentifier authorityCertSerialNumber',\n\t);\n\tstate.sawAuthorityCertSerialNumber = true;\n\tstate.lastFieldOrder = 2;\n}\n\nfunction validateImplicitSerialNumberEncoding(bytes: Uint8Array, label: string): void {\n\tconst first = bytes[0];\n\tif (first === undefined) {\n\t\tthrow new Error(`${label} must not be empty`);\n\t}\n\tif ((first & 0x80) !== 0) {\n\t\tthrow new Error(`${label} must be non-negative`);\n\t}\n\tif (bytes.length > 1 && first === 0 && ((bytes[1] ?? 0) & 0x80) === 0) {\n\t\tthrow new Error(`${label} must use minimal encoding`);\n\t}\n}\n\n/** An AlgorithmIdentifier decoded to its OID and the DER of its parameters. */\ninterface ParsedCrlAlgorithmIdentifier {\n\treadonly oid: string;\n\treadonly parametersDer?: Uint8Array;\n}\n\n/** RFC 5280 §5.1.1.2: signatureAlgorithm MUST equal the tbsCertList signature field. */\nfunction assertMatchingCrlSignatureAlgorithms(\n\tsignature: ParsedCrlAlgorithmIdentifier,\n\tsignatureAlgorithm: ParsedCrlAlgorithmIdentifier,\n): void {\n\tif (\n\t\tsignature.oid !== signatureAlgorithm.oid ||\n\t\t!optionalBytesEqual(signature.parametersDer, signatureAlgorithm.parametersDer)\n\t) {\n\t\tthrow new Error('CRL signatureAlgorithm must match TBSCertList signature');\n\t}\n}\n\n/** Extracts the algorithm OID from an AlgorithmIdentifier SEQUENCE. */\nfunction parseAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: DerElement,\n): ParsedCrlAlgorithmIdentifier {\n\tconst children = childrenOf(source, element);\n\tconst oid = requireElement(children[0], 'algorithm OID');\n\tconst parameters = children[1];\n\treturn parameters === undefined\n\t\t? { oid: decodeObjectIdentifier(oid.value) }\n\t\t: {\n\t\t\t\toid: decodeObjectIdentifier(oid.value),\n\t\t\t\tparametersDer: source.slice(parameters.start - parameters.headerLength, parameters.end),\n\t\t\t};\n}\n\n/** Lowercases a hex string for bytewise serial-number comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n/**\n * Maps an integer CRLReason code to its {@linkcode RevocationReason} name, or to\n * an {@linkcode UnrecognizedRevocationReason} carrying a code outside RFC 5280\n * §5.3.1. Returns `undefined` only when `code` is `undefined`.\n */\nexport function revocationReasonFromCode(\n\tcode: bigint | undefined,\n): ParsedRevocationReason | undefined {\n\treturn code === undefined ? undefined : parsedRevocationReason(code);\n}\n\nfunction parsedRevocationReason(code: bigint): ParsedRevocationReason {\n\tswitch (code) {\n\t\tcase 0n:\n\t\t\treturn 'unspecified';\n\t\tcase 1n:\n\t\t\treturn 'keyCompromise';\n\t\tcase 2n:\n\t\t\treturn 'cACompromise';\n\t\tcase 3n:\n\t\t\treturn 'affiliationChanged';\n\t\tcase 4n:\n\t\t\treturn 'superseded';\n\t\tcase 5n:\n\t\t\treturn 'cessationOfOperation';\n\t\tcase 6n:\n\t\t\treturn 'certificateHold';\n\t\tcase 8n:\n\t\t\treturn 'removeFromCRL';\n\t\tcase 9n:\n\t\t\treturn 'privilegeWithdrawn';\n\t\tcase 10n:\n\t\t\treturn 'aACompromise';\n\t\tdefault:\n\t\t\treturn { type: 'unrecognized', code };\n\t}\n}\n\n/** Thin wrapper — parses a DER-encoded certificate for use as a CRL issuer. */\nfunction parseIssuerCertificateDer(der: Uint8Array): ParsedCertificate {\n\treturn parseCertificateFromSource(der);\n}\n\n/** Thin wrapper — parses a PEM-encoded certificate for use as a CRL issuer. */\nfunction parseIssuerCertificatePem(pem: string): ParsedCertificate {\n\treturn parseCertificateFromSource(pem);\n}\n\n/**\n * Parses PEM, DER, or an already-parsed CRL's `der`, so every decoded field\n * comes from the signed bytes.\n *\n * @internal\n */\nexport function normalizeCrl(source: CrlSource): ParsedCertificateRevocationList {\n\tif (typeof source === 'string') {\n\t\treturn parseCertificateRevocationListPemOrThrow(source);\n\t}\n\tif (source instanceof Uint8Array) {\n\t\treturn parseCertificateRevocationListDerOrThrow(new Uint8Array(source));\n\t}\n\tif (hasReparseableCrlShape(source)) {\n\t\treturn parseCertificateRevocationListDerOrThrow(new Uint8Array(source.der));\n\t}\n\tthrow new Error('certificate revocation list input is malformed');\n}\n\nfunction parseSignedCrlFields(tbsCertListDer: Uint8Array): {\n\treadonly version: number;\n\treadonly signature: ParsedCrlAlgorithmIdentifier;\n\treadonly issuer: ParsedName;\n\treadonly thisUpdate: Date;\n\treadonly nextUpdate?: Date;\n\treadonly authorityKeyIdentifier?: string;\n\treadonly crlNumber?: bigint;\n\treadonly baseCrlNumber?: bigint;\n\treadonly issuingDistributionPoint?: ParsedIssuingDistributionPoint;\n\treadonly freshestCrlDistributionPoints?: readonly ParsedDistributionPoint[];\n\treadonly revokedCertificates: readonly ParsedRevokedCertificate[];\n} {\n\tconst tbsCertList = readRootElement(tbsCertListDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tconst tbsChildren = childrenOf(tbsCertListDer, tbsCertList);\n\tconst versionField = parseCrlVersionField(tbsChildren);\n\tconst version = versionField.version;\n\tconst signatureElement = requireElement(tbsChildren[versionField.nextIndex], 'signature');\n\tconst index = versionField.nextIndex + 1;\n\tconst issuerElement = requireElement(tbsChildren[index], 'issuer');\n\tconst thisUpdateElement = requireElement(tbsChildren[index + 1], 'thisUpdate');\n\tlet cursor = index + 2;\n\tconst maybeNextUpdate = tbsChildren[cursor];\n\tconst nextUpdate =\n\t\tmaybeNextUpdate !== undefined && (maybeNextUpdate.tag === 0x17 || maybeNextUpdate.tag === 0x18)\n\t\t\t? parseTime(maybeNextUpdate)\n\t\t\t: undefined;\n\tif (nextUpdate !== undefined) {\n\t\tcursor += 1;\n\t}\n\tconst maybeRevoked = tbsChildren[cursor];\n\tconst revokedCertificates =\n\t\tmaybeRevoked?.tag === 0x30\n\t\t\t? parseRevokedCertificates(tbsCertListDer, maybeRevoked, version)\n\t\t\t: [];\n\tif (maybeRevoked?.tag === 0x30) {\n\t\tcursor += 1;\n\t}\n\tconst maybeExtensions = tbsChildren[cursor];\n\tconst parsedExtensions = parseCrlExtensionFields(tbsCertListDer, maybeExtensions, version);\n\treturn {\n\t\tversion,\n\t\tsignature: parseAlgorithmIdentifier(tbsCertListDer, signatureElement),\n\t\tissuer: parseIssuer(tbsCertListDer, issuerElement),\n\t\tthisUpdate: parseTime(thisUpdateElement),\n\t\t...(nextUpdate === undefined ? {} : { nextUpdate }),\n\t\t...(parsedExtensions.authorityKeyIdentifier === undefined\n\t\t\t? {}\n\t\t\t: { authorityKeyIdentifier: parsedExtensions.authorityKeyIdentifier }),\n\t\t...(parsedExtensions.crlNumber === undefined ? {} : { crlNumber: parsedExtensions.crlNumber }),\n\t\t...(parsedExtensions.baseCrlNumber === undefined\n\t\t\t? {}\n\t\t\t: { baseCrlNumber: parsedExtensions.baseCrlNumber }),\n\t\t...(parsedExtensions.issuingDistributionPoint === undefined\n\t\t\t? {}\n\t\t\t: { issuingDistributionPoint: parsedExtensions.issuingDistributionPoint }),\n\t\t...(parsedExtensions.freshestCrlDistributionPoints === undefined\n\t\t\t? {}\n\t\t\t: { freshestCrlDistributionPoints: parsedExtensions.freshestCrlDistributionPoints }),\n\t\trevokedCertificates,\n\t};\n}\n\nfunction parseCrlVersionField(tbsChildren: readonly DerElement[]): ParsedCrlVersionField {\n\tconst firstChild = tbsChildren[0];\n\tif (firstChild !== undefined && firstChild.tag !== 0x02 && firstChild.tag !== 0x30) {\n\t\tthrow new Error('version must use INTEGER');\n\t}\n\tif (firstChild?.tag !== 0x02) {\n\t\treturn { version: 1, nextIndex: 0 };\n\t}\n\tconst version = decodeIntegerNumber(firstChild.value) + 1;\n\tif (version !== 2) {\n\t\tthrow new Error(`Unsupported CRL version: ${String(version)}`);\n\t}\n\treturn { version, nextIndex: 1 };\n}\n\nfunction parseRevokedCertificates(\n\ttbsCertListDer: Uint8Array,\n\trevokedSequence: DerElement,\n\tversion: number,\n): readonly ParsedRevokedCertificate[] {\n\treturn childrenOf(tbsCertListDer, revokedSequence).map((entry) =>\n\t\tparseRevokedCertificateEntry(tbsCertListDer, entry, version),\n\t);\n}\n\nfunction parseRevokedCertificateEntry(\n\ttbsCertListDer: Uint8Array,\n\tentry: DerElement,\n\tversion: number,\n): ParsedRevokedCertificate {\n\tconst entryDer = tbsCertListDer.slice(entry.start - entry.headerLength, entry.end);\n\tconst parts = readSequenceChildren(entryDer);\n\tconst serialNumber = requireElement(parts[0], 'revoked serialNumber');\n\tif (serialNumber.tag !== 0x02) {\n\t\tthrow new Error('revoked serialNumber must use INTEGER');\n\t}\n\tconst entryExtensions = parts[2];\n\tif (entryExtensions !== undefined && version !== 2) {\n\t\tthrow new Error('revoked certificate extensions require CRL version 2');\n\t}\n\tconst parsedEntryExtensions = parseRevokedCertificateExtensions(entryDer, entryExtensions);\n\treturn {\n\t\tserialNumberHex: toHex(serialNumber.value),\n\t\trevocationDate: parseTime(requireElement(parts[1], 'revocationDate')),\n\t\t...(parsedEntryExtensions.reasonCode === undefined\n\t\t\t? {}\n\t\t\t: { reasonCode: parsedEntryExtensions.reasonCode }),\n\t\t...(parsedEntryExtensions.invalidityDate === undefined\n\t\t\t? {}\n\t\t\t: { invalidityDate: parsedEntryExtensions.invalidityDate }),\n\t\t...(parsedEntryExtensions.certificateIssuer === undefined\n\t\t\t? {}\n\t\t\t: { certificateIssuer: parsedEntryExtensions.certificateIssuer }),\n\t};\n}\n\nfunction parseCrlExtensionFields(\n\ttbsCertListDer: Uint8Array,\n\tmaybeExtensions: DerElement | undefined,\n\tversion: number,\n): ParsedCrlExtensionFields {\n\tif (maybeExtensions?.tag !== 0xa0) {\n\t\treturn {};\n\t}\n\tif (version !== 2) {\n\t\tthrow new Error('CRL extensions require version 2');\n\t}\n\tconst fields: MutableParsedCrlExtensionFields = {};\n\tconst seenOids = new Set<string>();\n\tconst extensionSequence = requireElement(\n\t\tchildrenOf(tbsCertListDer, maybeExtensions)[0],\n\t\t'crl extensions',\n\t);\n\tfor (const extension of childrenOf(tbsCertListDer, extensionSequence)) {\n\t\tparseCrlExtensionField(tbsCertListDer, extension, seenOids, fields);\n\t}\n\treturn fields;\n}\n\nfunction parseCrlExtensionField(\n\ttbsCertListDer: Uint8Array,\n\textension: DerElement,\n\tseenOids: Set<string>,\n\tfields: MutableParsedCrlExtensionFields,\n): void {\n\tconst parts = childrenOf(tbsCertListDer, extension);\n\tif (parts.length < 2 || parts.length > 3) {\n\t\tthrow new Error('Malformed CRL extension');\n\t}\n\tif (parts.length === 3 && parts[1]?.tag !== 0x01) {\n\t\tthrow new Error('Malformed CRL extension');\n\t}\n\tconst oid = decodeObjectIdentifier(requireElement(parts[0], 'extension OID').value);\n\tif (seenOids.has(oid)) {\n\t\tthrow new Error(`Duplicate CRL extension OID: ${oid}`);\n\t}\n\tseenOids.add(oid);\n\tconst critical =\n\t\tparts.length === 3\n\t\t\t? decodeBoolean(requireElement(parts[1], 'extension critical').value)\n\t\t\t: false;\n\tconst valueElement = requireElement(parts[parts.length - 1], 'extension value');\n\tif (valueElement.tag !== 0x04) {\n\t\tthrow new Error('CRL extension value must use OCTET STRING');\n\t}\n\tif (!isSupportedCrlExtensionOid(oid) && critical) {\n\t\tthrow new Error(`Unsupported critical CRL extension OID: ${oid}`);\n\t}\n\tapplyParsedCrlExtensionField(oid, valueElement.value, fields);\n}\n\nfunction isSupportedCrlExtensionOid(oid: string): boolean {\n\treturn (\n\t\toid === OIDS.authorityKeyIdentifier ||\n\t\toid === OIDS.cRLNumber ||\n\t\toid === OIDS.deltaCRLIndicator ||\n\t\toid === OIDS.issuingDistributionPoint ||\n\t\toid === OIDS.freshestCRL\n\t);\n}\n\nfunction applyParsedCrlExtensionField(\n\toid: string,\n\tvalue: Uint8Array,\n\tfields: MutableParsedCrlExtensionFields,\n): void {\n\tif (oid === OIDS.authorityKeyIdentifier) {\n\t\tconst authorityKeyIdentifier = parseAuthorityKeyIdentifier(value);\n\t\tif (authorityKeyIdentifier !== undefined) {\n\t\t\tfields.authorityKeyIdentifier = authorityKeyIdentifier;\n\t\t}\n\t}\n\tif (oid === OIDS.cRLNumber) {\n\t\tfields.crlNumber = decodeCrlNumber(value);\n\t}\n\tif (oid === OIDS.deltaCRLIndicator) {\n\t\tfields.baseCrlNumber = decodeCrlNumber(value);\n\t}\n\tif (oid === OIDS.issuingDistributionPoint) {\n\t\tfields.issuingDistributionPoint = parseIssuingDistributionPoint(value);\n\t}\n\tif (oid === OIDS.freshestCRL) {\n\t\tfields.freshestCrlDistributionPoints = parseDistributionPoints(value);\n\t}\n}\n\n/** Accepts PEM, DER, or already-parsed certificate and returns a parsed certificate. */\nfunction normalizeCrlCertificate(source: CrlCertificateSource): ParsedCertificate {\n\treturn hasParsedCertificateShape(source)\n\t\t? parseCertificateDerOrThrow(new Uint8Array(source.der))\n\t\t: parseCertificateFromSource(source);\n}\n\nfunction hasParsedCertificateShape(value: CrlCertificateSource): value is ParsedCertificate {\n\treturn typeof value !== 'string' && 'subjectPublicKeyInfoDer' in value;\n}\n\nfunction hasReparseableCrlShape(\n\tcrl: ParsedCertificateRevocationList,\n): crl is ParsedCertificateRevocationList & { readonly der: Uint8Array } {\n\treturn 'der' in crl && crl.der instanceof Uint8Array;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqSA,MAAMgE,KAA4D;CACjE,aAAa;CACb,eAAe;CACf,cAAc;CACd,oBAAoB;CACpB,YAAY;CACZ,sBAAsB;CACtB,iBAAiB;CACjB,eAAe;CACf,oBAAoB;CACpB,cAAc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9K,EAA2B8K,CAAM;AACrC;AAEA,SAAS,0BAA0BvF,GAAyD;CAC3F,OAAO,OAAOA,KAAU,YAAY,6BAA6BA;AAClE;AAEA,SAAS,uBACR9D,GACwE;CACxE,OAAO,SAASA,KAAOA,EAAI,eAAe;AAC3C"}
|
|
1
|
+
{"version":3,"file":"crl.js","names":["_exhaustive","childrenOf","decodeBoolean","decodeIntegerMagnitude","decodeIntegerNumber","decodeNonNegativeIntegerBigInt","decodeObjectIdentifier","decodeString","hexToBytes","parseTime","requireElement","signatureBits","toHex","decodeFailureResult","decodeRefusalOf","rethrowDecodeRefusal","bitString","concatBytes","explicitContext","generalizedTime","implicitConstructedContext","implicitPrimitiveContext","integer","integerFromNumber","optionalBytesEqual","readElement","readRootElement","readSequenceChildren","sequence","time","tlv","OIDS","describeSignatureAlgorithm","NO_CALLER_VERIFICATION","callerVerification","verifySignedDataDetailed","encodeAlgorithmIdentifier","getSignatureAlgorithm","signBytes","base64Encode","compareDistinguishedNames","compareRelativeDistinguishedNames","encodeDistributionPointReasonFlagsContent","parseDistributionPointReasonFlagsContent","parseGeneralName","parseGeneralNames","parsePresentedSrvName","pemDecodeOrThrow","pemEncode","nameFieldKeyFromOid","DECODE_REFUSAL_CODES","failureResult","rethrowIfInvariant","successResult","throwMicro509Error","encodeCrlDistributionPoints","encodeExtension","encodeSubjectAltName","issuerKeyIdentifier","encodeName","encodeRelativeDistinguishedName","isNameInputEmpty","parseCertificateDerOrThrow","parseCertificateFromSource","REVOCATION_REASON_CODES","ALL_DISTRIBUTION_POINT_REASONS","reasons","set","reason","input","issuerCertificate","crlNumber","baseCrlNumber","signatureAlgorithm","thisUpdate","nextUpdate","entry","extensions","revoked","revokedSequence","tbsCertList","signatureValue","der","top","signedFields","parsedSignatureAlgorithm","pem","error","crl","options","verification","parsedCrl","issuer","refusal","verifiedResult","authority","authenticated","freshnessFailure","resolved","keyUsageFailure","maxAgeMs","clockSkewMs","at","skew","deltaCrl","certificate","outcome","complete","completeCrl","_deltaCrl","completeOnly","alone","deltaResult","applicability","deltaApplicability","completeRevoked","deltaRevoked","deltaLookup","crls","seen","key","baseCrl","deltaCrls","left","right","byTime","leftNumber","rightNumber","newer","older","budgets","candidates","search","index","unreadMaySettle","aloneResult","budget","result","distributionPoint","issuingDistributionPoint","distributionPointReasons","crlReasons","compatibilityFailure","stale","lookup","rejected","settled","code","message","details","value","certificateSerialNumber","serialNumberHex","effectiveIssuer","sawUnsupportedIssuer","matchedEntry","issuerMatch","allowDeltaCrl","isIndirectCrl","isCaCertificate","distributionPoints","scanResult","coveredReasons","failures","sawMatch","failure","issuerResult","crlIssuerNames","name","sawUnsupportedName","generalName","deltaThisUpdate","completeEntry","deltaEntry","unrecognizedReasonCode","certificatePoint","crlPoint","crlIssuer","certificateCrlIssuer","leftName","rightName","resolvedDnHex","issuerName","relativeName","rdnDerParts","rdn","relativeNameRdnDer","implicitTaggedDer","element","matched","found","certificateReasons","leftParts","rightParts","component","leftAt","rightAt","normalizedLeft","URI_DEFAULT_PORT_BY_SCHEME","url","host","hostname","probe","PERCENT_TRIPLET","triplet","freshestCrlDistributionPoints","entryDer","fields","seenOids","extension","parts","oid","critical","valueElement","enumerated","reasonCode","generalNames","valueDer","sequenceElement","child","userCerts","caCerts","attributeCerts","IDP_SCOPE_CONFLICT","flags","existing","fieldName","elements","children","distributionPointName","fullName","attributes","values","attributeSequence","fieldKey","fieldValue","attribute","source","field","hex","magnitude","first","date","relativeNameElement","names","derHex","rdns","allAttributes","setElement","rdnAttributes","rdnValues","attrSequence","oidElement","bytes","parsed","state","label","signature","parameters","tbsCertListDer","tbsChildren","versionField","version","signatureElement","issuerElement","thisUpdateElement","cursor","maybeNextUpdate","maybeRevoked","revokedCertificates","parsedExtensions","firstChild","serialNumber","entryExtensions","parsedEntryExtensions","maybeExtensions","extensionSequence","authorityKeyIdentifier"],"sources":["../../src/revocation/crl.ts"],"sourcesContent":["/**\n * Full CRL lifecycle: create, parse, verify, validate, and revocation check.\n *\n * Supports complete and delta CRLs, issuing distribution point scoping,\n * indirect CRL processing, per-entry reason codes, and invalidity dates.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeBoolean,\n\tdecodeIntegerMagnitude,\n\tdecodeIntegerNumber,\n\tdecodeNonNegativeIntegerBigInt,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\thexToBytes,\n\tparseTime,\n\trequireElement,\n\tsignatureBits,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tDECODE_REFUSAL_CODES,\n\tdecodeFailureResult,\n\tdecodeRefusalOf,\n\trethrowDecodeRefusal,\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\texplicitContext,\n\tgeneralizedTime,\n\timplicitConstructedContext,\n\timplicitPrimitiveContext,\n\tinteger,\n\tintegerFromNumber,\n\toptionalBytesEqual,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\ttime,\n\ttlv,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { describeSignatureAlgorithm } from '#micro509/internal/crypto/algorithm-names';\nimport type { CallerVerification, SignatureVerifiers } from '#micro509/internal/crypto/sig-verify';\nimport {\n\tcallerVerification,\n\tNO_CALLER_VERIFICATION,\n\tverifySignedDataDetailed,\n} from '#micro509/internal/crypto/sig-verify';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport {\n\tcompareDistinguishedNames,\n\tcompareRelativeDistinguishedNames,\n} from '#micro509/internal/shared/dn';\nimport type { ParsedBitFlags } from '#micro509/internal/x509/extension-bits';\nimport {\n\tencodeDistributionPointReasonFlagsContent,\n\tparseDistributionPointReasonFlagsContent,\n} from '#micro509/internal/x509/extension-bits';\nimport { parseGeneralName, parseGeneralNames } from '#micro509/internal/x509/general-name';\nimport { parsePresentedSrvName } from '#micro509/internal/x509/general-name-profile';\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 { TrustAnchor } from '#micro509/verify/verify';\nimport type {\n\tDistributionPoint,\n\tDistributionPointReason,\n\tGeneralName,\n\tIssuingDistributionPoint,\n} from '#micro509/x509/extensions';\nimport {\n\tencodeCrlDistributionPoints,\n\tencodeExtension,\n\tencodeSubjectAltName,\n\tissuerKeyIdentifier,\n} from '#micro509/x509/extensions';\nimport type { NameFieldKey, NameInput } from '#micro509/x509/name';\nimport {\n\tencodeName,\n\tencodeRelativeDistinguishedName,\n\tisNameInputEmpty,\n\tnameFieldKeyFromOid,\n} from '#micro509/x509/name';\nimport type {\n\tParsedCertificate,\n\tParsedDistributionPoint,\n\tParsedDistributionPointName,\n\tParsedIssuingDistributionPoint,\n\tParsedIssuingDistributionPointScope,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow, parseCertificateFromSource } from '#micro509/x509/parse';\n\n/**\n * Single revoked certificate entry for {@linkcode createCertificateRevocationList}.\n */\nexport interface RevokedCertificateInput {\n\t/** DER-encoded certificate serial number to revoke. */\n\treadonly serialNumber: Uint8Array;\n\t/** When the certificate was revoked. Defaults to `thisUpdate` of the CRL. */\n\treadonly revocationDate?: Date;\n\t/** RFC 5280 CRLReason code. Omit for `unspecified`. */\n\treadonly reasonCode?: RevocationReason;\n\t/** When the key or certificate became suspect — may predate `revocationDate`. */\n\treadonly invalidityDate?: Date;\n}\n\n/**\n * RFC 5280 [§5.3.1](https://datatracker.ietf.org/doc/html/rfc5280#section-5.3.1) CRLReason code values.\n *\n * `removeFromCRL` is used in delta CRLs to un-hold a certificate.\n */\nexport type RevocationReason =\n\t| 'unspecified'\n\t| 'keyCompromise'\n\t| 'cACompromise'\n\t| 'affiliationChanged'\n\t| 'superseded'\n\t| 'cessationOfOperation'\n\t| 'certificateHold'\n\t| 'removeFromCRL'\n\t| 'privilegeWithdrawn'\n\t| 'aACompromise';\n\n/**\n * A CRLReason code outside the RFC 5280 §5.3.1 enumeration, such as the unused\n * value 7 or X.509 (10/2019) `weakAlgorithmOrKey (11)`.\n */\nexport interface UnrecognizedRevocationReason {\n\t/** Discriminator for a code with no {@linkcode RevocationReason} name. */\n\treadonly type: 'unrecognized';\n\t/** The decoded ENUMERATED value. */\n\treadonly code: bigint;\n}\n\n/** A decoded CRLReason: a named {@linkcode RevocationReason} or an {@linkcode UnrecognizedRevocationReason}. */\nexport type ParsedRevocationReason = RevocationReason | UnrecognizedRevocationReason;\n\n/**\n * Treatment of revocation evidence whose CRLReason is an\n * {@linkcode UnrecognizedRevocationReason}. RFC 5280 §5.3.1 and Appendix B do\n * not say what a relying party does with such a code.\n *\n * - `'revoked'`: the certificate is revoked, with the code reported (default).\n * A certificate that a CRL or OCSP response revokes is never reported `good`.\n * - `'reject'`: the evidence cannot settle the certificate's status.\n */\nexport type UnrecognizedReasonCodePolicy = 'revoked' | 'reject';\n\n/**\n * Treatment of delta CRLs that the attempt limits leave unread when a delta\n * CRL already read supersedes them by both `thisUpdate` and CRL number. RFC\n * 5280 §5.2.4 has a relying party use the most recent delta CRL, and §3.3 and\n * §5.3.1 keep a lasting revocation listed in every later CRL, so reading the\n * older ones is a check on the issuer's consistency.\n *\n * - `'indeterminate'`: any unread candidate leaves the status\n * `delta_crl_retry_limit_exceeded`, unless a revocation no delta CRL can\n * remove already settled it (default).\n * - `'ignore'`: an unread candidate does not count when the delta CRL that\n * settled the status as good supersedes it, or, without a good status, when\n * it is not current and a delta CRL read supersedes it.\n */\nexport type SupersededDeltaCrlPolicy = 'indeterminate' | 'ignore';\n\n/**\n * Input for {@linkcode createCertificateRevocationList}.\n */\nexport interface CreateCertificateRevocationListInput {\n\t/** Distinguished name of the CRL issuer (typically the signing CA). */\n\treadonly issuer: NameInput;\n\t/** Private key used to sign the CRL. Algorithm is inferred from the key. */\n\treadonly signerPrivateKey: CryptoKey;\n\t/**\n\t * Certificate of the CRL issuer. Its subject key identifier becomes the\n\t * Authority Key Identifier extension (RFC 5280 §5.2.1). An issuer\n\t * certificate without one yields a key identifier derived from its public key.\n\t */\n\treadonly issuerCertificate: CrlCertificateSource;\n\t/** Issuance timestamp. Defaults to `new Date()`. */\n\treadonly thisUpdate?: Date;\n\t/** Date by which the next CRL will be issued. Must be at least one second later than `thisUpdate`. */\n\treadonly nextUpdate: Date;\n\t/** Certificates to list as revoked in this CRL. */\n\treadonly revokedCertificates?: readonly RevokedCertificateInput[];\n\t/**\n\t * Monotonically-increasing CRL sequence number (CRLNumber extension, RFC 5280\n\t * §5.2.3): non-negative and at most 20 octets encoded. Pass a `bigint` above\n\t * `Number.MAX_SAFE_INTEGER`.\n\t */\n\treadonly crlNumber: number | bigint;\n\t/** If set, marks this CRL as a delta CRL referencing the given base CRL number, bounded like {@linkcode crlNumber}. */\n\treadonly baseCrlNumber?: number | bigint;\n\t/** Issuing distribution point extension — scopes this CRL to a subset of certificates. */\n\treadonly issuingDistributionPoint?: IssuingDistributionPoint;\n\t/** Freshest CRL distribution points — tells relying parties where to find delta CRLs. */\n\treadonly freshestCrlDistributionPoints?: readonly DistributionPoint[];\n}\n\n/**\n * Encoded CRL in multiple serialisation formats, returned by {@linkcode createCertificateRevocationList}.\n */\nexport interface CertificateRevocationListMaterial {\n\t/** Raw DER bytes of the signed CRL. */\n\treadonly der: Uint8Array;\n\t/** PEM-encoded CRL (`-----BEGIN X509 CRL-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armour). */\n\treadonly base64: string;\n}\n\n/**\n * A single revoked-certificate entry decoded from a CRL.\n */\nexport interface ParsedRevokedCertificate {\n\t/** Hex-encoded serial number of the revoked certificate. */\n\treadonly serialNumberHex: string;\n\t/** When the CA declared this certificate revoked. */\n\treadonly revocationDate: Date;\n\t/** RFC 5280 CRLReason, if the entry carries one. */\n\treadonly reasonCode?: ParsedRevocationReason;\n\t/** When the key or certificate actually became suspect, if present. */\n\treadonly invalidityDate?: Date;\n\t/** Indirect-CRL certificate issuer override (RFC 5280 §5.3.3). */\n\treadonly certificateIssuer?: readonly GeneralName[];\n}\n\n/**\n * Decoded X.509 CRL, returned by {@linkcode parseCertificateRevocationListDer}\n * and {@linkcode parseCertificateRevocationListPem}.\n */\nexport interface ParsedCertificateRevocationList {\n\t/** Original DER bytes when this object came from {@linkcode parseCertificateRevocationListDer} or PEM parsing. */\n\treadonly der?: Uint8Array;\n\t/** CRL version (1 = v1, 2 = v2 with extensions). */\n\treadonly version: number;\n\t/** DER-encoded TBSCertList — the signed payload for signature verification. */\n\treadonly tbsCertListDer: Uint8Array;\n\t/** Signature bytes: the `signatureValue` 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/** CRL issuer distinguished name. */\n\treadonly issuer: ParsedName;\n\t/** Issue date of this CRL. */\n\treadonly thisUpdate: Date;\n\t/** Date by which the next CRL will be issued. Absent when the encoded CRL omits it. */\n\treadonly nextUpdate?: Date;\n\t/** OID of the algorithm used to sign this CRL. */\n\treadonly signatureAlgorithmOid: string;\n\t/** Human-readable signature algorithm name (e.g. `\"ECDSA with SHA-256\"`). */\n\treadonly signatureAlgorithmName: string;\n\t/** DER-encoded signature algorithm parameters (e.g. DER NULL for RSA PKCS#1 v1.5). */\n\treadonly signatureAlgorithmParametersDer?: Uint8Array;\n\t/** OID of the issuer's public key algorithm, when available. */\n\treadonly issuerPublicKeyAlgorithmOid?: string;\n\t/** OID of the issuer's public key parameters (e.g. named curve), when available. */\n\treadonly issuerPublicKeyParametersOid?: string;\n\t/** Hex-encoded Authority Key Identifier, if the extension is present. */\n\treadonly authorityKeyIdentifier?: string;\n\t/** CRLNumber extension value — monotonically increasing sequence number. */\n\treadonly crlNumber?: bigint;\n\t/** Delta CRL indicator — present only on delta CRLs, referencing the base CRL number. */\n\treadonly baseCrlNumber?: bigint;\n\t/** Issuing distribution point extension — scopes this CRL to a certificate subset. */\n\treadonly issuingDistributionPoint?: ParsedIssuingDistributionPoint;\n\t/** Freshest CRL extension — points to delta CRL locations. */\n\treadonly freshestCrlDistributionPoints?: readonly ParsedDistributionPoint[];\n\t/** All revoked certificate entries (empty array if none). */\n\treadonly revokedCertificates: readonly ParsedRevokedCertificate[];\n}\n\n/** RFC 5280 §5.3.1 CRLReason integer codes, keyed by reason name. */\nconst REVOCATION_REASON_CODES: Record<RevocationReason, number> = {\n\tunspecified: 0,\n\tkeyCompromise: 1,\n\tcACompromise: 2,\n\taffiliationChanged: 3,\n\tsuperseded: 4,\n\tcessationOfOperation: 5,\n\tcertificateHold: 6,\n\tremoveFromCRL: 8,\n\tprivilegeWithdrawn: 9,\n\taACompromise: 10,\n};\n\n/** PEM string, DER bytes, or already-parsed CRL. */\nexport type CrlSource = string | Uint8Array | ParsedCertificateRevocationList;\n/** PEM string, DER bytes, or already-parsed certificate. */\nexport type CrlCertificateSource = string | Uint8Array | ParsedCertificate;\n\n/**\n * Failure detail when CRL signature verification fails. `unsupported` and\n * `limit_exceeded` report a CRL or issuer certificate micro509 cannot decode\n * (see {@linkcode ParseCertificateRevocationListErrorCode}).\n */\nexport interface VerifyCertificateRevocationListSignatureFailure\n\textends Micro509Error<'signature_invalid' | DecodeFailureCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Result of {@linkcode verifyCertificateRevocationListSignature}.\n *\n * On success, `value` is the parsed CRL whose signature has been verified.\n */\nexport type VerifyCertificateRevocationListSignatureResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** Parsed CRL with a verified signature. */\n\t\t\treadonly value: ParsedCertificateRevocationList;\n\t }\n\t| ErrorResult<\n\t\t\t'signature_invalid' | DecodeFailureCode,\n\t\t\tRecord<never, never>,\n\t\t\tVerifyCertificateRevocationListSignatureFailure\n\t >;\n\n/** Options for {@linkcode verifyCertificateRevocationListSignature}. */\nexport interface VerifyCertificateRevocationListSignatureOptions {\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 the CRL signature would otherwise use unsupported algorithm\n\t * parameters, with the parameters in the issuer certificate. A key that\n\t * micro509 verifies natively, a key that is no OID, or a value that is no\n\t * function throws `RangeError`.\n\t */\n\treadonly signatureVerifiers?: SignatureVerifiers;\n}\n\n/**\n * Input for {@linkcode validateCertificateRevocationList}.\n */\nexport interface ValidateCertificateRevocationListInput {\n\t/** The CRL to validate. */\n\treadonly crl: CrlSource;\n\t/** Certificate of the CA that should have signed the CRL. */\n\treadonly issuerCertificate: CrlCertificateSource;\n\t/** Evaluation time for freshness checks. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/**\n\t * Tolerance in milliseconds for clock skew when checking `thisUpdate` and\n\t * `nextUpdate`. It also widens `maxAgeMs` by the same amount. Throws\n\t * `RangeError` when negative or not finite.\n\t */\n\treadonly clockSkewMs?: number;\n\t/**\n\t * Maximum age of `thisUpdate` at `at`, in milliseconds. A CRL older than\n\t * this fails with `stale_crl` even when `nextUpdate` is absent or later.\n\t * Unbounded by default, in which case a CRL without `nextUpdate` fails with\n\t * `stale_crl`. RFC 5280 §3.3 leaves the required recency of revocation data\n\t * to local policy. {@linkcode checkCertificateRevocationAgainstCrl} still\n\t * reports a revocation such a CRL lists with a reason other than\n\t * certificateHold, for a certificate that has not expired (RFC 5280 §5.3.1).\n\t */\n\treadonly maxAgeMs?: number;\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 the CRL signature would otherwise use unsupported algorithm\n\t * parameters, with the parameters in the issuer certificate. A key that\n\t * micro509 verifies natively, a key that is no OID, or a value that is no\n\t * function throws `RangeError`.\n\t */\n\treadonly signatureVerifiers?: SignatureVerifiers;\n}\n\n/**\n * Failure detail for {@linkcode validateCertificateRevocationList}.\n *\n * Possible codes: `signature_invalid`, `issuer_mismatch`, `stale_crl`, `crl_sign_not_permitted`,\n * and `unsupported` or `limit_exceeded` for a CRL or issuer certificate micro509 cannot decode.\n */\nexport interface ValidateCertificateRevocationListFailure\n\textends Micro509Error<\n\t\t| 'signature_invalid'\n\t\t| 'issuer_mismatch'\n\t\t| 'stale_crl'\n\t\t| 'crl_sign_not_permitted'\n\t\t| DecodeFailureCode\n\t> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/**\n * Result of {@linkcode validateCertificateRevocationList}.\n *\n * On success, the CRL has passed signature, issuer, key-usage, and freshness checks.\n */\nexport type ValidateCertificateRevocationListResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** Validated and parsed CRL. */\n\t\t\treadonly value: ParsedCertificateRevocationList;\n\t }\n\t| ErrorResult<\n\t\t\t| 'signature_invalid'\n\t\t\t| 'issuer_mismatch'\n\t\t\t| 'stale_crl'\n\t\t\t| 'crl_sign_not_permitted'\n\t\t\t| DecodeFailureCode,\n\t\t\tRecord<never, never>,\n\t\t\tValidateCertificateRevocationListFailure\n\t >;\n\n/**\n * Input for {@linkcode checkCertificateRevocationAgainstCrl}.\n */\nexport interface CheckCertificateRevocationAgainstCrlInput {\n\t/** Certificate whose revocation status to check. */\n\treadonly certificate: CrlCertificateSource;\n\t/** Issuer of `certificate` — also expected signer of the CRL. */\n\treadonly issuerCertificate: CrlCertificateSource;\n\t/** Complete (base) CRL to check against. */\n\treadonly crl: CrlSource;\n\t/**\n\t * Optional delta CRL for more recent revocation information. With a delta\n\t * CRL, the freshness checks and `maxAgeMs` apply to the delta CRL alone,\n\t * whose `thisUpdate` and `nextUpdate` the constructed CRL takes\n\t * (RFC 5280 §5.2.4, §6.3.3(a)(1)(i)). A delta CRL without `nextUpdate` is\n\t * never current and fails with `stale_crl`.\n\t */\n\treadonly deltaCrl?: CrlSource;\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/**\n\t * Clock-skew tolerance in milliseconds for freshness checks. It also widens\n\t * `maxAgeMs`. Throws `RangeError` when negative or not finite.\n\t */\n\treadonly clockSkewMs?: number;\n\t/** Maximum age of each CRL's `thisUpdate` in milliseconds. See {@linkcode ValidateCertificateRevocationListInput.maxAgeMs}. */\n\treadonly maxAgeMs?: number;\n\t/**\n\t * Treatment of a revoked entry whose CRLReason is unrecognized. `'reject'`\n\t * fails the check with `reason_code_unrecognized`. Defaults to `'revoked'`.\n\t */\n\treadonly unrecognizedReasonCode?: UnrecognizedReasonCodePolicy;\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 the CRL signature would otherwise use unsupported algorithm\n\t * parameters, with the parameters in the issuer certificate. A key that\n\t * micro509 verifies natively, a key that is no OID, or a value that is no\n\t * function throws `RangeError`.\n\t */\n\treadonly signatureVerifiers?: SignatureVerifiers;\n}\n\n/** Error codes that {@linkcode checkCertificateRevocationAgainstCrl} may return. */\nexport type CheckCertificateRevocationAgainstCrlErrorCode =\n\t| 'signature_invalid'\n\t| 'issuer_mismatch'\n\t| 'stale_crl'\n\t| 'crl_sign_not_permitted'\n\t| 'non_applicable'\n\t| 'reason_code_unrecognized'\n\t| DecodeFailureCode;\n\n/** Structured reason why a CRL was deemed non-applicable to a given certificate. */\nexport type CrlApplicabilityFailureReason =\n\t| 'certificate_scope_mismatch'\n\t| 'delta_crl_incompatible'\n\t| 'unsupported_delta_crl'\n\t| 'distribution_point_mismatch'\n\t| 'unsupported_indirect_crl'\n\t| 'issuer_mismatch'\n\t| 'reasons_mismatch';\n\n/** Internal result of looking up a serial number in a CRL's revoked entries. */\ntype RevokedCertificateLookupResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** Matching revoked entry, if found. */\n\t\t\treadonly entry?: ParsedRevokedCertificate;\n\t }\n\t| ErrorResult<\n\t\t\tCheckCertificateRevocationAgainstCrlErrorCode,\n\t\t\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\t\t\tCheckCertificateRevocationAgainstCrlFailure\n\t >;\n\n/** Structured details attached to a {@linkcode CheckCertificateRevocationAgainstCrlFailure}. */\nexport interface CheckCertificateRevocationAgainstCrlFailureDetails {\n\t/** Why the CRL was non-applicable, when the error code is `non_applicable`. */\n\treadonly reason?: CrlApplicabilityFailureReason;\n}\n\n/** Failure detail for {@linkcode checkCertificateRevocationAgainstCrl}. */\nexport interface CheckCertificateRevocationAgainstCrlFailure\n\textends Micro509Error<\n\t\tCheckCertificateRevocationAgainstCrlErrorCode,\n\t\tCheckCertificateRevocationAgainstCrlFailureDetails\n\t> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success value when the certificate is not found in the CRL. */\nexport interface CheckCertificateRevocationAgainstCrlGoodValue {\n\t/** Certificate is not revoked. */\n\treadonly status: 'good';\n\t/** The validated CRL that was checked. */\n\treadonly crl: ParsedCertificateRevocationList;\n\t/**\n\t * Revocation reasons this check covered, the RFC 5280 §6.3.3 (d)\n\t * interim_reasons_mask: the matched distribution point's reasons intersected\n\t * with the CRL's `onlySomeReasons`, either alone when the other is absent,\n\t * or every reason when both are.\n\t */\n\treadonly coveredReasons: readonly DistributionPointReason[];\n}\n\n/** Success value when the certificate is found as revoked in the CRL. */\nexport interface CheckCertificateRevocationAgainstCrlRevokedValue {\n\t/** Certificate is revoked. */\n\treadonly status: 'revoked';\n\t/** The validated CRL that contained the revocation entry. */\n\treadonly crl: ParsedCertificateRevocationList;\n\t/** When the CA declared this certificate revoked. */\n\treadonly revocationDate: Date;\n\t/** CRLReason from the entry, if present. */\n\treadonly reasonCode?: ParsedRevocationReason;\n}\n\n/** Discriminated union of `good` and `revoked` outcomes. */\nexport type CheckCertificateRevocationAgainstCrlValue =\n\t| CheckCertificateRevocationAgainstCrlGoodValue\n\t| CheckCertificateRevocationAgainstCrlRevokedValue;\n\n/**\n * Result of {@linkcode checkCertificateRevocationAgainstCrl}.\n *\n * On success `value.status` is `'good'` or `'revoked'`.\n * On failure the CRL could not be validated or was non-applicable.\n */\nexport type CheckCertificateRevocationAgainstCrlResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly value: CheckCertificateRevocationAgainstCrlValue;\n\t }\n\t| ErrorResult<\n\t\t\tCheckCertificateRevocationAgainstCrlErrorCode,\n\t\t\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\t\t\tCheckCertificateRevocationAgainstCrlFailure\n\t >;\n\ntype CrlApplicabilityFailure = ErrorResult<\n\tCheckCertificateRevocationAgainstCrlErrorCode,\n\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\tCheckCertificateRevocationAgainstCrlFailure\n>;\n\ntype CrlDistributionPointScanResult =\n\t| 'matched'\n\t| 'reasons_mismatch'\n\t| 'unsupported_indirect_crl_issuer'\n\t| 'indirect_issuer_mismatch'\n\t| 'distribution_point_mismatch'\n\t| 'indirect_distribution_point'\n\t| 'scope_mismatch';\n\ntype CrlDistributionPointScanFailure = Exclude<CrlDistributionPointScanResult, 'matched'>;\n\ntype CrlApplicabilityOutcome =\n\t| { readonly ok: true; readonly coveredReasons: readonly DistributionPointReason[] }\n\t| { readonly ok: false; readonly failure: CrlApplicabilityFailure };\n\n/**\n * RFC 5280 §4.2.1.13 ReasonFlags, excluding the reserved `unused` bit.\n *\n * Frozen so a `coveredReasons` result that aliases it cannot corrupt later completeness checks.\n */\nexport const ALL_DISTRIBUTION_POINT_REASONS: readonly DistributionPointReason[] = Object.freeze([\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n] as const);\n\n/** True when `reasons` covers every RFC 5280 §4.2.1.13 reason — a complete-scope CRL verdict. */\nexport function coversAllDistributionPointReasons(reasons: Iterable<string>): boolean {\n\tconst set = reasons instanceof Set ? reasons : new Set(reasons);\n\treturn ALL_DISTRIBUTION_POINT_REASONS.every((reason) => set.has(reason));\n}\n\ninterface MutableIssuingDistributionPointFields {\n\tdistributionPoint?: ParsedDistributionPointName;\n\tonlyContainsUserCerts?: boolean;\n\tonlyContainsCACerts?: boolean;\n\tonlySomeReasons?: ParsedBitFlags<DistributionPointReason>;\n\tindirectCrl?: boolean;\n\tonlyContainsAttributeCerts?: boolean;\n}\n\ninterface ParsedCrlVersionField {\n\treadonly version: number;\n\treadonly nextIndex: number;\n}\n\ninterface ParsedCrlExtensionFields {\n\treadonly authorityKeyIdentifier?: string;\n\treadonly crlNumber?: bigint;\n\treadonly baseCrlNumber?: bigint;\n\treadonly issuingDistributionPoint?: ParsedIssuingDistributionPoint;\n\treadonly freshestCrlDistributionPoints?: readonly ParsedDistributionPoint[];\n}\n\ninterface MutableParsedCrlExtensionFields {\n\tauthorityKeyIdentifier?: string;\n\tcrlNumber?: bigint;\n\tbaseCrlNumber?: bigint;\n\tissuingDistributionPoint?: ParsedIssuingDistributionPoint;\n\tfreshestCrlDistributionPoints?: readonly ParsedDistributionPoint[];\n}\n\ninterface MutableRevokedCertificateExtensionFields {\n\treasonCode?: ParsedRevocationReason;\n\tinvalidityDate?: Date;\n\tcertificateIssuer?: readonly GeneralName[];\n}\n\ninterface MutableDistributionPointFields {\n\tdistributionPoint?: ParsedDistributionPointName;\n\treasons?: ParsedBitFlags<DistributionPointReason>;\n\tcrlIssuer?: readonly GeneralName[];\n}\n\ninterface MutableAuthorityKeyIdentifierState {\n\tkeyIdentifier?: string;\n\tsawAuthorityCertIssuer: boolean;\n\tsawAuthorityCertSerialNumber: boolean;\n\tlastFieldOrder: number;\n}\n\n/**\n * Signs and encodes an X.509 v2 CRL.\n *\n * Always embeds the Authority Key Identifier and CRLNumber extensions\n * (RFC 5280 §5.2), plus delta CRL indicator, issuing distribution point and\n * freshest-CRL extensions as configured.\n *\n * @example\n * ```ts\n * import { createCertificateRevocationList } from 'micro509';\n *\n * const crl = await createCertificateRevocationList({\n * issuer: { commonName: 'Example CA' },\n * signerPrivateKey: caPrivateKey,\n * issuerCertificate: caCertificatePem,\n * thisUpdate: new Date('2025-01-01'),\n * nextUpdate: new Date('2025-02-01'),\n * crlNumber: 42,\n * revokedCertificates: [\n * { serialNumber: revokedSerial, reasonCode: 'keyCompromise' },\n * ],\n * });\n * // crl.pem, crl.der, crl.base64\n * ```\n */\nexport async function createCertificateRevocationList(\n\tinput: CreateCertificateRevocationListInput,\n): Promise<CertificateRevocationListMaterial> {\n\tif (isNameInputEmpty(input.issuer)) {\n\t\tthrowCrlEncoderError(\n\t\t\t'issuer_distinguished_name_empty',\n\t\t\t'issuer must be a non-empty distinguished name',\n\t\t);\n\t}\n\tconst issuerCertificate = issuerCertificateOf(input.issuerCertificate);\n\tconst crlNumber = encodeCrlNumber(input.crlNumber, 'crlNumber');\n\tconst baseCrlNumber =\n\t\tinput.baseCrlNumber === undefined\n\t\t\t? undefined\n\t\t\t: encodeCrlNumber(input.baseCrlNumber, 'baseCrlNumber');\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey);\n\tconst thisUpdate = input.thisUpdate ?? new Date();\n\tconst nextUpdate = input.nextUpdate;\n\tassertCrlDate(thisUpdate, 'thisUpdate');\n\tassertCrlDate(nextUpdate, 'nextUpdate');\n\tfor (const entry of input.revokedCertificates ?? []) {\n\t\tassertCrlDate(entry.revocationDate, 'revocationDate');\n\t\tassertCrlDate(entry.invalidityDate, 'invalidityDate');\n\t}\n\tif (Math.floor(nextUpdate.getTime() / 1000) <= Math.floor(thisUpdate.getTime() / 1000)) {\n\t\tthrowCrlEncoderError(\n\t\t\t'next_update_not_after_this_update',\n\t\t\t'nextUpdate must be at least one second later than thisUpdate',\n\t\t);\n\t}\n\tconst extensions = buildCrlExtensions(\n\t\tissuerCertificate,\n\t\tcrlNumber,\n\t\tbaseCrlNumber,\n\t\tinput.issuingDistributionPoint,\n\t\tinput.freshestCrlDistributionPoints,\n\t);\n\tconst revoked = input.revokedCertificates ?? [];\n\tconst revokedSequence =\n\t\trevoked.length === 0\n\t\t\t? []\n\t\t\t: [sequence(revoked.map((entry) => createRevokedCertificate(entry, thisUpdate)))];\n\tconst tbsCertList = sequence([\n\t\tintegerFromNumber(1),\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tencodeName(input.issuer),\n\t\ttime(thisUpdate),\n\t\ttime(nextUpdate),\n\t\t...revokedSequence,\n\t\texplicitContext(0, sequence(extensions)),\n\t]);\n\tconst signatureValue = await signBytes(input.signerPrivateKey, signatureAlgorithm, tbsCertList);\n\tconst der = sequence([\n\t\ttbsCertList,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(signatureValue),\n\t]);\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('X509 CRL', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/** Machine-readable failure reason for the CRL parsers. */\nexport type ParseCertificateRevocationListErrorCode = DecodeFailureCode;\n\n/** Structured failure payload for CRL parsing. */\nexport interface ParseCertificateRevocationListFailure\n\textends Micro509Error<ParseCertificateRevocationListErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parseCertificateRevocationListDer} / {@linkcode parseCertificateRevocationListPem}. */\nexport type ParseCertificateRevocationListResult =\n\t| { readonly ok: true; readonly value: ParsedCertificateRevocationList }\n\t| ErrorResult<\n\t\t\tParseCertificateRevocationListErrorCode,\n\t\t\tRecord<never, never>,\n\t\t\tParseCertificateRevocationListFailure\n\t >;\n\n/**\n * Throwing core for {@linkcode parseCertificateRevocationListDer}.\n *\n * Does not verify the signature — call {@linkcode verifyCertificateRevocationListSignature} or\n * {@linkcode validateCertificateRevocationList} for that.\n */\nexport function parseCertificateRevocationListDerOrThrow(\n\tder: Uint8Array,\n): ParsedCertificateRevocationList {\n\tconst top = readSequenceChildren(der, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (top.length !== 3) {\n\t\tthrow new Error('Malformed CRL');\n\t}\n\tconst tbsCertList = requireElement(top[0], 'TBSCertList');\n\tconst signatureAlgorithm = requireElement(top[1], 'signatureAlgorithm');\n\tconst signatureValue = requireElement(top[2], 'signatureValue');\n\tconst signedFields = parseSignedCrlFields(\n\t\tder.slice(tbsCertList.start - tbsCertList.headerLength, tbsCertList.end),\n\t);\n\tconst parsedSignatureAlgorithm = parseAlgorithmIdentifier(der, signatureAlgorithm);\n\tassertMatchingCrlSignatureAlgorithms(signedFields.signature, parsedSignatureAlgorithm);\n\treturn {\n\t\tder: new Uint8Array(der),\n\t\tversion: signedFields.version,\n\t\ttbsCertListDer: der.slice(tbsCertList.start - tbsCertList.headerLength, tbsCertList.end),\n\t\t...signatureBits(signatureValue),\n\t\tissuer: signedFields.issuer,\n\t\tthisUpdate: signedFields.thisUpdate,\n\t\t...(signedFields.nextUpdate === undefined ? {} : { nextUpdate: signedFields.nextUpdate }),\n\t\tsignatureAlgorithmOid: parsedSignatureAlgorithm.oid,\n\t\tsignatureAlgorithmName: describeSignatureAlgorithm(\n\t\t\tparsedSignatureAlgorithm.oid,\n\t\t\tparsedSignatureAlgorithm.parametersDer,\n\t\t),\n\t\t...(parsedSignatureAlgorithm.parametersDer === undefined\n\t\t\t? {}\n\t\t\t: { signatureAlgorithmParametersDer: parsedSignatureAlgorithm.parametersDer }),\n\t\t...(signedFields.authorityKeyIdentifier === undefined\n\t\t\t? {}\n\t\t\t: { authorityKeyIdentifier: signedFields.authorityKeyIdentifier }),\n\t\t...(signedFields.crlNumber === undefined ? {} : { crlNumber: signedFields.crlNumber }),\n\t\t...(signedFields.baseCrlNumber === undefined\n\t\t\t? {}\n\t\t\t: { baseCrlNumber: signedFields.baseCrlNumber }),\n\t\t...(signedFields.issuingDistributionPoint === undefined\n\t\t\t? {}\n\t\t\t: { issuingDistributionPoint: signedFields.issuingDistributionPoint }),\n\t\t...(signedFields.freshestCrlDistributionPoints === undefined\n\t\t\t? {}\n\t\t\t: { freshestCrlDistributionPoints: signedFields.freshestCrlDistributionPoints }),\n\t\trevokedCertificates: signedFields.revokedCertificates,\n\t};\n}\n\n/**\n * Decodes a PEM-encoded X.509 CRL (`-----BEGIN X509 CRL-----`).\n *\n * @example\n * ```ts\n * import { parseCertificateRevocationListPemOrThrow } from 'micro509';\n *\n * const crl = parseCertificateRevocationListPemOrThrow(pemString); // throws if malformed\n * console.log(crl.issuer.values.commonName, crl.revokedCertificates.length);\n * ```\n */\nexport function parseCertificateRevocationListPemOrThrow(\n\tpem: string,\n): ParsedCertificateRevocationList {\n\treturn parseCertificateRevocationListDerOrThrow(pemDecodeOrThrow('X509 CRL', pem));\n}\n\n/**\n * Decodes a DER-encoded X.509 CRL into a structured {@linkcode ParsedCertificateRevocationList}.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseCertificateRevocationListDerOrThrow}.\n * Does not verify the signature — call {@linkcode verifyCertificateRevocationListSignature} or\n * {@linkcode validateCertificateRevocationList} for that.\n */\nexport function parseCertificateRevocationListDer(\n\tder: Uint8Array,\n): ParseCertificateRevocationListResult {\n\ttry {\n\t\treturn successResult(parseCertificateRevocationListDerOrThrow(der));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed CRL');\n\t}\n}\n\n/**\n * Decodes a PEM-encoded X.509 CRL (`-----BEGIN X509 CRL-----`).\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input. For the\n * throwing form use {@linkcode parseCertificateRevocationListPemOrThrow}.\n */\nexport function parseCertificateRevocationListPem(\n\tpem: string,\n): ParseCertificateRevocationListResult {\n\ttry {\n\t\treturn successResult(parseCertificateRevocationListPemOrThrow(pem));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn decodeFailureResult(error, DECODE_REFUSAL_CODES, 'Malformed CRL');\n\t}\n}\n\n/**\n * Verifies the CRL signature against the issuer certificate's public key.\n *\n * Does **not** check issuer name match, key-usage, or freshness — use\n * {@linkcode validateCertificateRevocationList} for full validation.\n */\nexport async function verifyCertificateRevocationListSignature(\n\tcrl: string | Uint8Array,\n\tissuerCertificate: string | Uint8Array,\n\toptions: VerifyCertificateRevocationListSignatureOptions = {},\n): Promise<VerifyCertificateRevocationListSignatureResult> {\n\tconst verification = callerVerification(options.signatureVerifiers);\n\tlet parsedCrl: ParsedCertificateRevocationList;\n\tlet issuer: ParsedCertificate;\n\ttry {\n\t\tparsedCrl =\n\t\t\ttypeof crl === 'string'\n\t\t\t\t? parseCertificateRevocationListPemOrThrow(crl)\n\t\t\t\t: parseCertificateRevocationListDerOrThrow(new Uint8Array(crl));\n\t\tissuer =\n\t\t\ttypeof issuerCertificate === 'string'\n\t\t\t\t? parseIssuerCertificatePem(issuerCertificate)\n\t\t\t\t: parseIssuerCertificateDer(new Uint8Array(issuerCertificate));\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? verifyCertificateRevocationListFailureResult(\n\t\t\t\t\t'malformed',\n\t\t\t\t\t'certificate revocation list or issuer certificate input is malformed',\n\t\t\t\t)\n\t\t\t: verifyCertificateRevocationListFailureResult(refusal.code, refusal.message);\n\t}\n\tlet verifiedResult: Awaited<ReturnType<typeof verifySignedDataDetailed>>;\n\ttry {\n\t\tverifiedResult = await verifySignedDataDetailed(\n\t\t\tparsedCrl.signatureAlgorithmOid,\n\t\t\tparsedCrl.signatureAlgorithmParametersDer,\n\t\t\tissuer.publicKeyAlgorithmOid,\n\t\t\tissuer.publicKeyParametersOid,\n\t\t\tissuer.subjectPublicKeyInfoDer,\n\t\t\tparsedCrl.signatureValue,\n\t\t\tparsedCrl.signatureValueUnusedBits,\n\t\t\tparsedCrl.tbsCertListDer,\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? verifyCertificateRevocationListFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate revocation list signature verification failed',\n\t\t\t\t)\n\t\t\t: verifyCertificateRevocationListFailureResult(refusal.code, refusal.message);\n\t}\n\tif (!verifiedResult.ok) {\n\t\tif (verifiedResult.code === 'verification_error') {\n\t\t\treturn verifyCertificateRevocationListFailureResult(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'certificate revocation list signature verification failed',\n\t\t\t);\n\t\t}\n\t\treturn verifyCertificateRevocationListFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'certificate revocation list signature uses unsupported algorithm parameters',\n\t\t);\n\t}\n\treturn verifiedResult.valid\n\t\t? { ok: true, value: parsedCrl }\n\t\t: verifyCertificateRevocationListFailureResult(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'certificate revocation list signature does not verify',\n\t\t\t);\n}\n\n/**\n * Full CRL validation: issuer name match, authority key identifier match,\n * a v3 issuer certificate's key usage must be present and assert cRLSign\n * (RFC 10007 §4), signature verification, `thisUpdate`/`nextUpdate`\n * freshness check (with optional clock-skew tolerance), and the optional\n * `maxAgeMs` bound on `thisUpdate`. A CRL that omits `nextUpdate` fails with\n * `stale_crl` unless `maxAgeMs` is set.\n */\nexport async function validateCertificateRevocationList(\n\tinput: ValidateCertificateRevocationListInput,\n): Promise<ValidateCertificateRevocationListResult> {\n\treturn await validateCrlWith(input, callerVerification(input.signatureVerifiers));\n}\n\n/** {@linkcode validateCertificateRevocationList} with resolved caller verification. */\nasync function validateCrlWith(\n\tinput: ValidateCertificateRevocationListInput,\n\tverification: CallerVerification,\n): Promise<ValidateCertificateRevocationListResult> {\n\treturn await validateCrlBy(\n\t\tinput,\n\t\t{ kind: 'certificate', certificate: input.issuerCertificate },\n\t\tverification,\n\t);\n}\n\n/** {@linkcode validateCertificateRevocationList} for a CRL that `authority` signs. */\nasync function validateCrlBy(\n\tinput: Omit<ValidateCertificateRevocationListInput, 'issuerCertificate'>,\n\tauthority: CrlAuthority,\n\tverification: CallerVerification,\n): Promise<ValidateCertificateRevocationListResult> {\n\tassertCrlMaxAge(input.maxAgeMs);\n\tassertClockSkew(input.clockSkewMs);\n\tconst authenticated = await authenticateCrl(input.crl, authority, verification);\n\tif (!authenticated.ok) {\n\t\treturn authenticated;\n\t}\n\tconst freshnessFailure = crlFreshnessFailure(\n\t\tauthenticated.value,\n\t\tinput.at ?? new Date(),\n\t\tinput.clockSkewMs ?? 0,\n\t\tinput.maxAgeMs,\n\t);\n\treturn freshnessFailure === undefined\n\t\t? authenticated\n\t\t: validateCertificateRevocationListFailureResult('stale_crl', freshnessFailure);\n}\n\n/**\n * The key that signs a CRL: a CA certificate, or a bare trust anchor, which\n * X.509 (2019) §7.5 lets issue CRLs that its own key verifies.\n *\n * @internal\n */\nexport type CrlAuthority =\n\t| { readonly kind: 'certificate'; readonly certificate: CrlCertificateSource }\n\t| { readonly kind: 'trust_anchor'; readonly trustAnchor: TrustAnchor };\n\n/** The signing key of a resolved {@linkcode CrlAuthority}. */\ntype CrlSigningKey = Pick<\n\tTrustAnchor,\n\t| 'subject'\n\t| 'subjectKeyIdentifier'\n\t| 'subjectPublicKeyInfoDer'\n\t| 'publicKeyAlgorithmOid'\n\t| 'publicKeyParametersOid'\n>;\n\n/**\n * Verifies the issuer binding, cRLSign permission and signature of `crl`\n * against `authority`, without freshness checks. A trust anchor carries no\n * certificate, so the RFC 10007 §4 key usage check applies to certificates only.\n *\n * @internal\n */\nexport async function authenticateCrl(\n\tcrl: CrlSource,\n\tauthority: CrlAuthority,\n\tverification: CallerVerification = NO_CALLER_VERIFICATION,\n): Promise<ValidateCertificateRevocationListResult> {\n\tlet parsedCrl: ParsedCertificateRevocationList;\n\ttry {\n\t\tparsedCrl = normalizeCrl(crl);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateCertificateRevocationListFailureResult(\n\t\t\t\t\t'malformed',\n\t\t\t\t\t'certificate revocation list signed content is malformed',\n\t\t\t\t)\n\t\t\t: validateCertificateRevocationListFailureResult(refusal.code, refusal.message);\n\t}\n\tconst resolved = resolveCrlSigningKey(authority);\n\tif (!resolved.ok) return resolved;\n\tconst { issuer, issuerCertificate } = resolved;\n\tif (!compareDistinguishedNames(parsedCrl.issuer, issuer.subject)) {\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'issuer_mismatch',\n\t\t\t'CRL issuer name does not match certificate subject',\n\t\t);\n\t}\n\tif (\n\t\tparsedCrl.authorityKeyIdentifier !== undefined &&\n\t\tissuer.subjectKeyIdentifier !== undefined &&\n\t\tparsedCrl.authorityKeyIdentifier !== issuer.subjectKeyIdentifier\n\t) {\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'issuer_mismatch',\n\t\t\t'CRL authority key identifier does not match issuer subject key identifier',\n\t\t);\n\t}\n\tconst keyUsageFailure =\n\t\tissuerCertificate === undefined ? undefined : crlSignFailure(issuerCertificate);\n\tif (keyUsageFailure !== undefined) return keyUsageFailure;\n\tlet verifiedResult: Awaited<ReturnType<typeof verifySignedDataDetailed>>;\n\ttry {\n\t\tverifiedResult = await verifySignedDataDetailed(\n\t\t\tparsedCrl.signatureAlgorithmOid,\n\t\t\tparsedCrl.signatureAlgorithmParametersDer,\n\t\t\tissuer.publicKeyAlgorithmOid,\n\t\t\tissuer.publicKeyParametersOid,\n\t\t\tissuer.subjectPublicKeyInfoDer,\n\t\t\tparsedCrl.signatureValue,\n\t\t\tparsedCrl.signatureValueUnusedBits,\n\t\t\tparsedCrl.tbsCertListDer,\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? validateCertificateRevocationListFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'certificate revocation list signature verification failed',\n\t\t\t\t)\n\t\t\t: validateCertificateRevocationListFailureResult(refusal.code, refusal.message);\n\t}\n\tif (!verifiedResult.ok) {\n\t\tif (verifiedResult.code === 'verification_error') {\n\t\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t\t'signature_invalid',\n\t\t\t\t'certificate revocation list signature verification failed',\n\t\t\t);\n\t\t}\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'certificate revocation list signature uses unsupported algorithm parameters',\n\t\t);\n\t}\n\tif (!verifiedResult.valid) {\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'signature_invalid',\n\t\t\t'certificate revocation list signature does not verify',\n\t\t);\n\t}\n\treturn { ok: true, value: parsedCrl };\n}\n\n/** The signing key `authority` names, with its certificate when it has one. */\nfunction resolveCrlSigningKey(authority: CrlAuthority):\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly issuer: CrlSigningKey;\n\t\t\treadonly issuerCertificate: ParsedCertificate | undefined;\n\t }\n\t| Extract<ValidateCertificateRevocationListResult, { readonly ok: false }> {\n\tif (authority.kind === 'trust_anchor') {\n\t\treturn { ok: true, issuer: authority.trustAnchor, issuerCertificate: undefined };\n\t}\n\ttry {\n\t\tconst issuerCertificate = normalizeCrlCertificate(authority.certificate);\n\t\treturn { ok: true, issuer: issuerCertificate, issuerCertificate };\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? validateCertificateRevocationListFailureResult(\n\t\t\t\t\t'malformed',\n\t\t\t\t\t'issuer certificate input is malformed',\n\t\t\t\t)\n\t\t\t: validateCertificateRevocationListFailureResult(refusal.code, refusal.message);\n\t}\n}\n\n/** RFC 10007 §4: a v3 CRL issuer certificate must carry key usage asserting cRLSign. */\nfunction crlSignFailure(\n\tissuer: ParsedCertificate,\n): Extract<ValidateCertificateRevocationListResult, { readonly ok: false }> | undefined {\n\tif (issuer.keyUsage === undefined && issuer.version === 3) {\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'crl_sign_not_permitted',\n\t\t\t'v3 issuer certificate has no key usage extension',\n\t\t);\n\t}\n\tif (issuer.keyUsage !== undefined && !issuer.keyUsage.flags.includes('cRLSign')) {\n\t\treturn validateCertificateRevocationListFailureResult(\n\t\t\t'crl_sign_not_permitted',\n\t\t\t'issuer certificate key usage does not permit CRL signing',\n\t\t);\n\t}\n\treturn undefined;\n}\n\nexport function assertCrlMaxAge(maxAgeMs: number | undefined): void {\n\tif (maxAgeMs !== undefined && (!Number.isFinite(maxAgeMs) || maxAgeMs < 0)) {\n\t\tthrow new RangeError(`Invalid maxAgeMs: must be a non-negative number, got ${maxAgeMs}`);\n\t}\n}\n\nexport function assertClockSkew(clockSkewMs: number | undefined): void {\n\tif (clockSkewMs !== undefined && (!Number.isFinite(clockSkewMs) || clockSkewMs < 0)) {\n\t\tthrow new RangeError(`Invalid clockSkewMs: must be a non-negative number, got ${clockSkewMs}`);\n\t}\n}\n\nfunction crlFreshnessFailure(\n\tcrl: ParsedCertificateRevocationList,\n\tat: Date,\n\tskew: number,\n\tmaxAgeMs: number | undefined,\n): string | undefined {\n\tif (\n\t\tcrl.thisUpdate.getTime() - skew > at.getTime() ||\n\t\t(crl.nextUpdate !== undefined && crl.nextUpdate.getTime() + skew < at.getTime())\n\t) {\n\t\treturn 'CRL is not valid at requested time';\n\t}\n\tif (crl.nextUpdate === undefined && maxAgeMs === undefined) {\n\t\treturn 'CRL has no nextUpdate and no maximum age is set';\n\t}\n\tif (maxAgeMs !== undefined && at.getTime() - crl.thisUpdate.getTime() > maxAgeMs + skew) {\n\t\treturn 'CRL thisUpdate is older than the maximum age';\n\t}\n\treturn undefined;\n}\n\nfunction deltaCrlFreshnessFailure(\n\tdeltaCrl: ParsedCertificateRevocationList,\n\tat: Date,\n\tskew: number,\n\tmaxAgeMs: number | undefined,\n): string | undefined {\n\treturn deltaCrl.nextUpdate === undefined\n\t\t? 'delta CRL has no nextUpdate'\n\t\t: crlFreshnessFailure(deltaCrl, at, skew, maxAgeMs);\n}\n\n/** Whether `crl` was issued by `at`, so its entries record revocations known then. */\nfunction isIssuedCrl(crl: ParsedCertificateRevocationList, at: Date, skew: number): boolean {\n\treturn crl.thisUpdate.getTime() - skew <= at.getTime();\n}\n\n/**\n * End-to-end revocation check: validates the CRL (and optional delta CRL),\n * verifies applicability via distribution-point and scope matching, then\n * resolves the certificate's revocation status.\n *\n * Returns `good` if the serial is absent, `revoked` with date/reason if present,\n * or an error if the CRL cannot be validated or is non-applicable.\n *\n * @example\n * ```ts\n * import { checkCertificateRevocationAgainstCrl } from 'micro509';\n *\n * const result = await checkCertificateRevocationAgainstCrl({\n * certificate: leafPem,\n * issuerCertificate: caPem,\n * crl: crlPem,\n * });\n * if (result.ok && result.value.status === 'revoked') {\n * console.log('revoked on', result.value.revocationDate);\n * }\n * ```\n */\nexport async function checkCertificateRevocationAgainstCrl(\n\tinput: CheckCertificateRevocationAgainstCrlInput,\n): Promise<CheckCertificateRevocationAgainstCrlResult> {\n\treturn await checkCertificateRevocationAgainstCrlWith(\n\t\tinput,\n\t\tcallerVerification(input.signatureVerifiers),\n\t);\n}\n\n/**\n * {@linkcode checkCertificateRevocationAgainstCrl} with resolved caller\n * verification, which can carry the issuer's inherited key parameters.\n *\n * @internal\n */\nexport async function checkCertificateRevocationAgainstCrlWith(\n\tinput: CheckCertificateRevocationAgainstCrlInput,\n\tverification: CallerVerification,\n): Promise<CheckCertificateRevocationAgainstCrlResult> {\n\tassertCrlMaxAge(input.maxAgeMs);\n\tassertClockSkew(input.clockSkewMs);\n\tlet certificate: ParsedCertificate;\n\ttry {\n\t\tcertificate = normalizeCrlCertificate(input.certificate);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\t\t\t'malformed',\n\t\t\t\t\t'certificate input is malformed',\n\t\t\t\t)\n\t\t\t: checkCertificateRevocationAgainstCrlFailureResult(refusal.code, refusal.message);\n\t}\n\treturn await checkCertificateRevocationAgainstCrlBy(\n\t\tcertificate,\n\t\tinput.crl,\n\t\t{ kind: 'certificate', certificate: input.issuerCertificate },\n\t\tinput,\n\t\tverification,\n\t);\n}\n\n/**\n * {@linkcode checkCertificateRevocationAgainstCrl} for a CRL that `authority`\n * signs, which may be a bare trust anchor.\n *\n * @internal\n */\nexport async function checkCertificateRevocationAgainstCrlBy(\n\tcertificate: ParsedCertificate,\n\tcrl: CrlSource,\n\tauthority: CrlAuthority,\n\toptions: CrlCheckOptions,\n\tverification: CallerVerification,\n): Promise<CheckCertificateRevocationAgainstCrlResult> {\n\tconst authenticated = await authenticateCrl(crl, authority, verification);\n\tif (!authenticated.ok) {\n\t\treturn checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\tauthenticated.code,\n\t\t\tauthenticated.message,\n\t\t);\n\t}\n\tconst outcome = await checkRevocationAgainstAuthenticatedCrl(\n\t\tcertificate,\n\t\tauthenticated.value,\n\t\tauthority,\n\t\toptions,\n\t\tverification,\n\t);\n\tif (outcome.kind === 'checked') return outcome.result;\n\tconst complete =\n\t\toutcome.kind === 'delta_unresolved'\n\t\t\t? outcome.complete\n\t\t\t: await checkCompleteCrlAlone(\n\t\t\t\t\tcertificate,\n\t\t\t\t\tauthenticated.value,\n\t\t\t\t\tauthority,\n\t\t\t\t\toptions,\n\t\t\t\t\tverification,\n\t\t\t\t);\n\tif (outcome.kind === 'delta_stale') return complete;\n\treturn (\n\t\tirremovableCrlRevocation(certificate, complete, options.at ?? new Date()) ?? outcome.failure\n\t);\n}\n\n/** {@linkcode checkRevocationAgainstAuthenticatedCrl} on `completeCrl` without its delta CRL. */\nasync function checkCompleteCrlAlone(\n\tcertificate: ParsedCertificate,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tauthority: CrlAuthority,\n\toptions: CrlCheckOptions,\n\tverification: CallerVerification,\n): Promise<CheckCertificateRevocationAgainstCrlResult> {\n\tconst { deltaCrl: _deltaCrl, ...completeOnly } = options;\n\tconst alone = await checkRevocationAgainstAuthenticatedCrl(\n\t\tcertificate,\n\t\tcompleteCrl,\n\t\tauthority,\n\t\tcompleteOnly,\n\t\tverification,\n\t);\n\treturn alone.kind === 'checked' ? alone.result : alone.failure;\n}\n\n/**\n * Result of {@linkcode checkRevocationAgainstAuthenticatedCrl}, keyed by the\n * stage that settled it. `delta_rejected` means the delta CRL failed\n * authentication, freshness, compatibility or applicability;\n * `delta_stale` means it passed them except freshness and records no\n * revocation that stands, so it settles nothing;\n * `delta_unresolved` means it passed them and its revoked entries could not\n * settle the certificate's status; `complete` is then the complete CRL's own\n * result, without its freshness check.\n */\ntype AuthenticatedCrlCheckOutcome =\n\t| { readonly kind: 'checked'; readonly result: CheckCertificateRevocationAgainstCrlResult }\n\t| { readonly kind: 'delta_rejected'; readonly failure: CrlApplicabilityFailure }\n\t| { readonly kind: 'delta_stale'; readonly failure: CrlApplicabilityFailure }\n\t| {\n\t\t\treadonly kind: 'delta_unresolved';\n\t\t\treadonly failure: CrlApplicabilityFailure;\n\t\t\treadonly complete: CheckCertificateRevocationAgainstCrlResult;\n\t };\n\n/**\n * The options of a CRL check once its certificate, CRL and authority are\n * resolved. `unreadSupersededDeltaCrls` applies when\n * {@linkcode checkCertificateRevocationAgainstCrlsBy} runs out of attempts.\n */\nexport type CrlCheckOptions = Omit<\n\tCheckCertificateRevocationAgainstCrlInput,\n\t'certificate' | 'issuerCertificate' | 'crl'\n> & { readonly unreadSupersededDeltaCrls?: SupersededDeltaCrlPolicy };\n\n/**\n * Checks `certificate` against a complete CRL that {@linkcode authenticateCrl}\n * accepted for `authority`, updated by `input.deltaCrl` when given.\n */\nasync function checkRevocationAgainstAuthenticatedCrl(\n\tcertificate: ParsedCertificate,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tauthority: CrlAuthority,\n\tinput: CrlCheckOptions,\n\tverification: CallerVerification = callerVerification(input.signatureVerifiers),\n): Promise<AuthenticatedCrlCheckOutcome> {\n\tif (input.deltaCrl === undefined) {\n\t\tconst freshnessFailure = crlFreshnessFailure(\n\t\t\tcompleteCrl,\n\t\t\tinput.at ?? new Date(),\n\t\t\tinput.clockSkewMs ?? 0,\n\t\t\tinput.maxAgeMs,\n\t\t);\n\t\tif (freshnessFailure !== undefined) {\n\t\t\treturn {\n\t\t\t\tkind: 'checked',\n\t\t\t\tresult: staleCompleteCrlResult(\n\t\t\t\t\tcertificate,\n\t\t\t\t\tcompleteCrl,\n\t\t\t\t\tcheckCertificateRevocationAgainstCrlFailureResult('stale_crl', freshnessFailure),\n\t\t\t\t\tinput,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t}\n\tconst deltaResult = await validateOptionalDeltaCrl(input, completeCrl, authority, verification);\n\tif (!deltaResult.ok) return { kind: 'delta_rejected', failure: deltaResult };\n\tif (deltaResult.value !== undefined && deltaResult.stale !== undefined) {\n\t\treturn staleDeltaCrlOutcome(\n\t\t\tcertificate,\n\t\t\tcompleteCrl,\n\t\t\tdeltaResult.value,\n\t\t\tdeltaResult.stale,\n\t\t\tinput,\n\t\t);\n\t}\n\tconst deltaCrl = deltaResult.value;\n\tconst applicability = checkCrlApplicability(certificate, completeCrl);\n\tif (!applicability.ok) return { kind: 'checked', result: applicability.failure };\n\tif (deltaCrl !== undefined) {\n\t\tconst deltaApplicability = checkCrlApplicability(certificate, deltaCrl, true);\n\t\tif (!deltaApplicability.ok) {\n\t\t\treturn { kind: 'delta_rejected', failure: deltaApplicability.failure };\n\t\t}\n\t}\n\tconst completeRevoked = findRevokedCertificateEntry(certificate, completeCrl);\n\tif (!completeRevoked.ok) return { kind: 'checked', result: completeRevoked };\n\tlet deltaRevoked: ParsedRevokedCertificate | undefined;\n\tif (deltaCrl !== undefined) {\n\t\tconst deltaLookup = findRevokedCertificateEntry(certificate, deltaCrl);\n\t\tif (!deltaLookup.ok) {\n\t\t\treturn {\n\t\t\t\tkind: 'delta_unresolved',\n\t\t\t\tfailure: deltaLookup,\n\t\t\t\tcomplete: resolveCertificateRevocationStatus(\n\t\t\t\t\tcertificate,\n\t\t\t\t\tundefined,\n\t\t\t\t\tcompleteCrl,\n\t\t\t\t\tcompleteRevoked.entry,\n\t\t\t\t\tundefined,\n\t\t\t\t\tapplicability.coveredReasons,\n\t\t\t\t\tinput.unrecognizedReasonCode ?? 'revoked',\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\tdeltaRevoked = deltaLookup.entry;\n\t}\n\treturn {\n\t\tkind: 'checked',\n\t\tresult: resolveCertificateRevocationStatus(\n\t\t\tcertificate,\n\t\t\tdeltaCrl?.thisUpdate,\n\t\t\tcompleteCrl,\n\t\t\tcompleteRevoked.entry,\n\t\t\tdeltaRevoked,\n\t\t\tapplicability.coveredReasons,\n\t\t\tinput.unrecognizedReasonCode ?? 'revoked',\n\t\t),\n\t};\n}\n\n/**\n * A key equal for two CRLs exactly when their signed content and signature\n * are equal.\n *\n * @internal\n */\nexport function signedCrlKey(crl: ParsedCertificateRevocationList): string {\n\treturn [\n\t\tcrl.signatureAlgorithmOid,\n\t\ttoHex(crl.signatureAlgorithmParametersDer ?? new Uint8Array()),\n\t\ttoHex(crl.signatureValue),\n\t\tcrl.signatureValueUnusedBits,\n\t\ttoHex(crl.tbsCertListDer),\n\t].join(':');\n}\n\n/**\n * `crls` with each signed content and signature kept once.\n *\n * @internal\n */\nexport function distinctSignedCrls(\n\tcrls: readonly ParsedCertificateRevocationList[],\n): readonly ParsedCertificateRevocationList[] {\n\tconst seen = new Set<string>();\n\treturn crls.filter((crl) => {\n\t\tconst key = signedCrlKey(crl);\n\t\tif (seen.has(key)) {\n\t\t\treturn false;\n\t\t}\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n}\n\n/** Delta CRLs micro509 tries per complete CRL, an implementation limit. */\nexport const DELTA_CRL_ATTEMPTS_PER_BASE = 4;\n\n/** Delta CRLs micro509 tries in one revocation check, an implementation limit. */\nexport const DELTA_CRL_ATTEMPTS_PER_CALL = 32;\n\n/**\n * Delta CRL checks left to spend across one revocation check, an\n * implementation limit shared by every complete CRL it reads.\n *\n * @internal\n */\nexport interface DeltaCrlBudget {\n\tremaining: number;\n}\n\n/**\n * Every delta CRL that can update `baseCrl` and was issued by `at`, newest\n * first. A delta CRL that is no longer current still settles a revocation no\n * later CRL could remove (RFC 5280 §5.3.1), so currency does not move it\n * behind older ones.\n */\nfunction rankApplicableDeltaCrls(\n\tbaseCrl: ParsedCertificateRevocationList,\n\tdeltaCrls: readonly ParsedCertificateRevocationList[],\n\tat: Date,\n\tclockSkewMs: number,\n): readonly ParsedCertificateRevocationList[] {\n\treturn deltaCrls\n\t\t.filter(\n\t\t\t(deltaCrl) =>\n\t\t\t\tisCompatibleDeltaCrl(baseCrl, deltaCrl) && isIssuedCrl(deltaCrl, at, clockSkewMs),\n\t\t)\n\t\t.sort(compareDeltaCrlRecency);\n}\n\n/** Whether {@linkcode checkDeltaCrlCompatibility} accepts `deltaCrl` for `completeCrl`. */\nfunction isCompatibleDeltaCrl(\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tdeltaCrl: ParsedCertificateRevocationList,\n): boolean {\n\ttry {\n\t\treturn checkDeltaCrlCompatibility(completeCrl, deltaCrl) === undefined;\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn false;\n\t}\n}\n\n/**\n * Orders delta CRLs newest first by `thisUpdate`, the key RFC 5280 §5.2.4\n * names for the most current one, then by CRL number.\n */\nfunction compareDeltaCrlRecency(\n\tleft: ParsedCertificateRevocationList,\n\tright: ParsedCertificateRevocationList,\n): number {\n\tconst byTime = right.thisUpdate.getTime() - left.thisUpdate.getTime();\n\tif (byTime !== 0) return byTime;\n\tconst leftNumber = left.crlNumber ?? 0n;\n\tconst rightNumber = right.crlNumber ?? 0n;\n\treturn leftNumber === rightNumber ? 0 : leftNumber < rightNumber ? 1 : -1;\n}\n\n/**\n * Whether `newer` supersedes `older` by both its `thisUpdate` and its CRL\n * number (RFC 5280 §5.2.3, §5.1.2.4). RFC 5280 leaves a pair whose keys\n * disagree unspecified, and micro509 ranks such a pair alike.\n */\nfunction supersedesDeltaCrl(\n\tnewer: ParsedCertificateRevocationList,\n\tolder: ParsedCertificateRevocationList,\n): boolean {\n\treturn (\n\t\tnewer.thisUpdate.getTime() > older.thisUpdate.getTime() &&\n\t\tnewer.crlNumber !== undefined &&\n\t\tolder.crlNumber !== undefined &&\n\t\tnewer.crlNumber > older.crlNumber\n\t);\n}\n\n/**\n * Result of {@linkcode checkCertificateRevocationAgainstCrlsBy}. `checked`\n * names the delta CRL its result came from, if any. `unsettled` means an\n * applicable delta CRL could not settle the status (`delta_unusable`), or the\n * {@linkcode DELTA_CRL_ATTEMPTS_PER_BASE} limit or a shared\n * {@linkcode DeltaCrlBudget} left a delta CRL unread that counts under\n * `unreadSupersededDeltaCrls` (`retry_limit`). An unread delta CRL may then\n * revoke the certificate, so the complete CRL's good is no evidence.\n *\n * @internal\n */\nexport type CrlsCheckOutcome =\n\t| {\n\t\t\treadonly kind: 'checked';\n\t\t\treadonly result: CheckCertificateRevocationAgainstCrlResult;\n\t\t\treadonly deltaCrl?: ParsedCertificateRevocationList;\n\t }\n\t| { readonly kind: 'unsettled'; readonly reason: 'delta_unusable' | 'retry_limit' };\n\n/**\n * Checks `certificate` against `completeCrl`, which `authority` signs, and\n * the delta CRLs in `deltaCrls` that update it, newest first. A rejected\n * delta CRL, or one past its `nextUpdate` that records no lasting revocation,\n * passes the search to the next. The first current delta CRL settles the\n * status, and one past its `nextUpdate` settles a revocation no later CRL\n * could remove (RFC 5280 §5.3.1, §3.3). After a good status, older delta CRLs\n * are still read for such a revocation the newer one omits. Each delta CRL\n * check spends one from {@linkcode DELTA_CRL_ATTEMPTS_PER_BASE} and from every\n * budget in `budgets`. When they leave a delta CRL unread, the outcome is\n * `retry_limit` unless the complete CRL holds such a revocation. Under\n * `unreadSupersededDeltaCrls: 'ignore'`, only an unread delta CRL that\n * {@linkcode mayChangeSettledStatus} finds could change the status counts. A\n * complete CRL that does not cover `certificate` spends none.\n *\n * @internal\n */\nexport async function checkCertificateRevocationAgainstCrlsBy(\n\tcertificate: ParsedCertificate,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tdeltaCrls: readonly ParsedCertificateRevocationList[],\n\tauthority: CrlAuthority,\n\toptions: CrlCheckOptions,\n\tverification: CallerVerification,\n\tbudgets: readonly DeltaCrlBudget[] = [],\n): Promise<CrlsCheckOutcome> {\n\tconst authenticated = await authenticateCrl(completeCrl, authority, verification);\n\tif (!authenticated.ok) {\n\t\treturn {\n\t\t\tkind: 'checked',\n\t\t\tresult: checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\t\tauthenticated.code,\n\t\t\t\tauthenticated.message,\n\t\t\t),\n\t\t};\n\t}\n\tconst at = options.at ?? new Date();\n\tconst candidates = checkCrlApplicability(certificate, authenticated.value).ok\n\t\t? rankApplicableDeltaCrls(authenticated.value, deltaCrls, at, options.clockSkewMs ?? 0)\n\t\t: [];\n\tconst search: DeltaCrlSearch = { attempts: 0, unread: [] };\n\tfor (const [index, deltaCrl] of candidates.entries()) {\n\t\tif (!spendDeltaCrlAttempt(search, budgets)) {\n\t\t\tsearch.unread = candidates.slice(index);\n\t\t\tbreak;\n\t\t}\n\t\trecordDeltaCrlOutcome(\n\t\t\tsearch,\n\t\t\tcertificate,\n\t\t\tdeltaCrl,\n\t\t\tawait checkRevocationAgainstAuthenticatedCrl(\n\t\t\t\tcertificate,\n\t\t\t\tauthenticated.value,\n\t\t\t\tauthority,\n\t\t\t\t{ ...options, deltaCrl },\n\t\t\t\tverification,\n\t\t\t),\n\t\t\tat,\n\t\t);\n\t\tif (search.result !== undefined) return search.result;\n\t}\n\tconst unreadMaySettle =\n\t\toptions.unreadSupersededDeltaCrls === 'ignore'\n\t\t\t? search.unread.some((deltaCrl) => mayChangeSettledStatus(search, deltaCrl, at, options))\n\t\t\t: search.unread.length > 0;\n\tif (!unreadMaySettle && search.good !== undefined) return search.good;\n\tconst alone = await checkRevocationAgainstAuthenticatedCrl(\n\t\tcertificate,\n\t\tauthenticated.value,\n\t\tauthority,\n\t\toptions,\n\t\tverification,\n\t);\n\tconst aloneResult = alone.kind === 'checked' ? alone.result : alone.failure;\n\treturn unreadMaySettle\n\t\t? settledOrUnsettled(irremovableCrlRevocation(certificate, aloneResult, at), 'retry_limit')\n\t\t: { kind: 'checked', result: aloneResult };\n}\n\n/**\n * Where {@linkcode checkCertificateRevocationAgainstCrlsBy} stands in its\n * delta CRL candidates: `newest` is the first one examined that was not\n * rejected, and `unread` the ones the limits left unread.\n */\ninterface DeltaCrlSearch {\n\tattempts: number;\n\tnewest?: ParsedCertificateRevocationList;\n\tunread: readonly ParsedCertificateRevocationList[];\n\tgood?: {\n\t\treadonly kind: 'checked';\n\t\treadonly result: CheckCertificateRevocationAgainstCrlResult;\n\t\treadonly deltaCrl: ParsedCertificateRevocationList;\n\t};\n\tresult?: CrlsCheckOutcome;\n}\n\n/**\n * Whether reading the unread `deltaCrl` could change the status `search`\n * reached by more than an older entry its newer delta CRLs omit. After a good\n * status, only a delta CRL that the one settling it supersedes cannot.\n * Otherwise only one that is not current and that a delta CRL examined\n * supersedes cannot, since a current one settles the status.\n */\nfunction mayChangeSettledStatus(\n\tsearch: DeltaCrlSearch,\n\tdeltaCrl: ParsedCertificateRevocationList,\n\tat: Date,\n\toptions: CrlCheckOptions,\n): boolean {\n\tif (search.good !== undefined) return !supersedesDeltaCrl(search.good.deltaCrl, deltaCrl);\n\tconst current =\n\t\tdeltaCrlFreshnessFailure(deltaCrl, at, options.clockSkewMs ?? 0, options.maxAgeMs) ===\n\t\tundefined;\n\treturn current || search.newest === undefined || !supersedesDeltaCrl(search.newest, deltaCrl);\n}\n\n/** Spends one delta CRL check from the per-base limit and every budget, or none when any is spent. */\nfunction spendDeltaCrlAttempt(search: DeltaCrlSearch, budgets: readonly DeltaCrlBudget[]): boolean {\n\tif (\n\t\tsearch.attempts >= DELTA_CRL_ATTEMPTS_PER_BASE ||\n\t\tbudgets.some((budget) => budget.remaining <= 0)\n\t) {\n\t\treturn false;\n\t}\n\tsearch.attempts += 1;\n\tfor (const budget of budgets) budget.remaining -= 1;\n\treturn true;\n}\n\n/**\n * Folds the outcome of `deltaCrl` into `search`. A delta CRL that the one\n * settling the status as good supersedes only adds what\n * {@linkcode olderDeltaRevocation} finds. Any other settles like the first,\n * so two delta CRLs ranked alike that disagree yield the stricter result.\n */\nfunction recordDeltaCrlOutcome(\n\tsearch: DeltaCrlSearch,\n\tcertificate: ParsedCertificate,\n\tdeltaCrl: ParsedCertificateRevocationList,\n\toutcome: AuthenticatedCrlCheckOutcome,\n\tat: Date,\n): void {\n\tif (outcome.kind === 'delta_rejected') return;\n\tsearch.newest ??= deltaCrl;\n\tif (search.good !== undefined && supersedesDeltaCrl(search.good.deltaCrl, deltaCrl)) {\n\t\tsearch.result = olderDeltaRevocation(certificate, deltaCrl, outcome, at);\n\t\treturn;\n\t}\n\tif (outcome.kind === 'checked') {\n\t\tif (!isGoodResult(outcome.result)) {\n\t\t\tsearch.result = { kind: 'checked', result: outcome.result, deltaCrl };\n\t\t} else {\n\t\t\tsearch.good ??= { kind: 'checked', result: outcome.result, deltaCrl };\n\t\t}\n\t} else if (outcome.kind === 'delta_unresolved') {\n\t\tsearch.result = settledOrUnsettled(\n\t\t\tirremovableCrlRevocation(certificate, outcome.complete, at),\n\t\t\t'delta_unusable',\n\t\t);\n\t}\n}\n\nfunction isGoodResult(result: CheckCertificateRevocationAgainstCrlResult): boolean {\n\treturn result.ok && result.value.status === 'good';\n}\n\n/**\n * What an older delta CRL changes after a newer one settled the status as\n * good: a revocation no later CRL may drop (RFC 5280 §5.3.1, §3.3), a\n * failure such as an entry `unrecognizedReasonCode: 'reject'` refuses, or\n * entries that cannot settle the status. A newer delta CRL that omits such an\n * entry contradicts its issuer.\n */\nfunction olderDeltaRevocation(\n\tcertificate: ParsedCertificate,\n\tdeltaCrl: ParsedCertificateRevocationList,\n\toutcome: AuthenticatedCrlCheckOutcome,\n\tat: Date,\n): CrlsCheckOutcome | undefined {\n\tif (outcome.kind === 'delta_unresolved') {\n\t\treturn settledOrUnsettled(\n\t\t\tirremovableCrlRevocation(certificate, outcome.complete, at),\n\t\t\t'delta_unusable',\n\t\t);\n\t}\n\tif (outcome.kind !== 'checked') return undefined;\n\tif (!outcome.result.ok) return { kind: 'checked', result: outcome.result, deltaCrl };\n\tconst revoked = irremovableCrlRevocation(certificate, outcome.result, at);\n\treturn revoked === undefined ? undefined : { kind: 'checked', result: revoked, deltaCrl };\n}\n\nfunction settledOrUnsettled(\n\tresult: CheckCertificateRevocationAgainstCrlResult | undefined,\n\treason: Extract<CrlsCheckOutcome, { readonly kind: 'unsettled' }>['reason'],\n): CrlsCheckOutcome {\n\treturn result === undefined ? { kind: 'unsettled', reason } : { kind: 'checked', result };\n}\n\n/**\n * `result` when it revokes `certificate` in a way no delta CRL could undo at\n * `at`. RFC 5280 §5.3.1 lets removeFromCRL clear only a certificateHold entry\n * or a certificate that has expired.\n */\nfunction irremovableCrlRevocation(\n\tcertificate: ParsedCertificate,\n\tresult: CheckCertificateRevocationAgainstCrlResult,\n\tat: Date,\n): Extract<CheckCertificateRevocationAgainstCrlResult, { readonly ok: true }> | undefined {\n\treturn certificate.notAfter.getTime() >= at.getTime() &&\n\t\tresult.ok &&\n\t\tresult.value.status === 'revoked' &&\n\t\tresult.value.reasonCode !== 'certificateHold'\n\t\t? result\n\t\t: undefined;\n}\n\n/** RFC 5280 §6.3.3 (d): interim_reasons_mask from the matched DP and the CRL's IDP. */\nfunction interimReasonsMask(\n\tdistributionPoint: ParsedDistributionPoint | undefined,\n\tissuingDistributionPoint: ParsedIssuingDistributionPoint | undefined,\n): readonly DistributionPointReason[] {\n\tconst distributionPointReasons = distributionPoint?.reasons?.flags;\n\tconst crlReasons = issuingDistributionPoint?.onlySomeReasons?.flags;\n\tif (distributionPointReasons !== undefined && crlReasons !== undefined) {\n\t\treturn distributionPointReasons.filter((reason) => crlReasons.includes(reason));\n\t}\n\tif (distributionPointReasons !== undefined) {\n\t\treturn [...distributionPointReasons];\n\t}\n\tif (crlReasons !== undefined) {\n\t\treturn [...crlReasons];\n\t}\n\treturn ALL_DISTRIBUTION_POINT_REASONS;\n}\n\n/**\n * Authenticates an optional delta CRL and checks compatibility with its\n * complete CRL. A delta CRL issued by `input.at` but not current there comes\n * back with the freshness failure as `stale`.\n */\nasync function validateOptionalDeltaCrl(\n\tinput: CrlCheckOptions,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tauthority: CrlAuthority,\n\tverification: CallerVerification,\n): Promise<\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly value?: ParsedCertificateRevocationList;\n\t\t\treadonly stale?: CrlApplicabilityFailure;\n\t }\n\t| CrlApplicabilityFailure\n> {\n\tif (input.deltaCrl === undefined) return { ok: true };\n\tassertCrlMaxAge(input.maxAgeMs);\n\tassertClockSkew(input.clockSkewMs);\n\tconst authenticated = await authenticateCrl(input.deltaCrl, authority, verification);\n\tif (!authenticated.ok) {\n\t\treturn checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\tauthenticated.code,\n\t\t\tauthenticated.message,\n\t\t);\n\t}\n\tconst at = input.at ?? new Date();\n\tconst skew = input.clockSkewMs ?? 0;\n\tconst freshnessFailure = deltaCrlFreshnessFailure(authenticated.value, at, skew, input.maxAgeMs);\n\tif (freshnessFailure !== undefined && !isIssuedCrl(authenticated.value, at, skew)) {\n\t\treturn checkCertificateRevocationAgainstCrlFailureResult('stale_crl', freshnessFailure);\n\t}\n\tlet compatibilityFailure: CrlApplicabilityFailure | undefined;\n\ttry {\n\t\tcompatibilityFailure = checkDeltaCrlCompatibility(completeCrl, authenticated.value);\n\t} catch (error) {\n\t\treturn crlNameRefusalFailure(error);\n\t}\n\tif (compatibilityFailure !== undefined) {\n\t\treturn freshnessFailure === undefined\n\t\t\t? compatibilityFailure\n\t\t\t: checkCertificateRevocationAgainstCrlFailureResult('stale_crl', freshnessFailure);\n\t}\n\treturn {\n\t\tok: true,\n\t\tvalue: authenticated.value,\n\t\t...(freshnessFailure === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tstale: checkCertificateRevocationAgainstCrlFailureResult('stale_crl', freshnessFailure),\n\t\t\t\t}),\n\t};\n}\n\n/**\n * The result of `completeCrl`, which is not current at `input.at`: its\n * revocation of `certificate` when no later CRL could remove it (RFC 5280\n * §5.3.1, §3.3), otherwise `stale`. A CRL issued after `input.at` yields\n * `stale`.\n */\nfunction staleCompleteCrlResult(\n\tcertificate: ParsedCertificate,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tstale: CheckCertificateRevocationAgainstCrlResult,\n\tinput: CrlCheckOptions,\n): CheckCertificateRevocationAgainstCrlResult {\n\tconst at = input.at ?? new Date();\n\tif (\n\t\t!isIssuedCrl(completeCrl, at, input.clockSkewMs ?? 0) ||\n\t\t!checkCrlApplicability(certificate, completeCrl).ok\n\t) {\n\t\treturn stale;\n\t}\n\tconst lookup = findRevokedCertificateEntry(certificate, completeCrl);\n\tif (!lookup.ok || lookup.entry === undefined) return stale;\n\tconst result = revokedEntryResult(\n\t\tcompleteCrl,\n\t\tlookup.entry,\n\t\tinput.unrecognizedReasonCode ?? 'revoked',\n\t);\n\tif (!result.ok) return result;\n\treturn irremovableCrlRevocation(certificate, result, at) ?? stale;\n}\n\n/**\n * The outcome of `deltaCrl`, which updates `completeCrl` but is not current at\n * `input.at`. Its revocation of `certificate` settles the status when no later\n * CRL could remove it (RFC 5280 §5.3.1). Otherwise it is `delta_stale` when it\n * applies to `certificate`, and settles nothing. A delta CRL that does not\n * apply is rejected with `stale`.\n */\nfunction staleDeltaCrlOutcome(\n\tcertificate: ParsedCertificate,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tdeltaCrl: ParsedCertificateRevocationList,\n\tstale: CrlApplicabilityFailure,\n\tinput: CrlCheckOptions,\n): AuthenticatedCrlCheckOutcome {\n\tconst rejected = { kind: 'delta_rejected', failure: stale } as const;\n\tif (\n\t\t!checkCrlApplicability(certificate, completeCrl).ok ||\n\t\t!checkCrlApplicability(certificate, deltaCrl, true).ok\n\t) {\n\t\treturn rejected;\n\t}\n\tconst lookup = findRevokedCertificateEntry(certificate, deltaCrl);\n\tif (!lookup.ok) return rejected;\n\tconst settled = { kind: 'delta_stale', failure: stale } as const;\n\tif (lookup.entry === undefined || lookup.entry.reasonCode === 'removeFromCRL') return settled;\n\tconst result = revokedEntryResult(\n\t\tcompleteCrl,\n\t\tlookup.entry,\n\t\tinput.unrecognizedReasonCode ?? 'revoked',\n\t);\n\tif (!result.ok) return { kind: 'checked', result };\n\treturn irremovableCrlRevocation(certificate, result, input.at ?? new Date()) === undefined\n\t\t? settled\n\t\t: { kind: 'checked', result };\n}\n\n/** Builds a `VerifyCertificateRevocationListSignatureFailureResult`. */\nfunction verifyCertificateRevocationListFailureResult(\n\tcode: 'signature_invalid' | DecodeFailureCode,\n\tmessage: string,\n): ErrorResult<\n\t'signature_invalid' | DecodeFailureCode,\n\tRecord<never, never>,\n\tVerifyCertificateRevocationListSignatureFailure\n> {\n\treturn failureResult(code, message);\n}\n\n/** Builds a `ValidateCertificateRevocationListFailureResult`. */\nfunction validateCertificateRevocationListFailureResult(\n\tcode:\n\t\t| 'signature_invalid'\n\t\t| 'issuer_mismatch'\n\t\t| 'stale_crl'\n\t\t| 'crl_sign_not_permitted'\n\t\t| DecodeFailureCode,\n\tmessage: string,\n): ErrorResult<\n\t| 'signature_invalid'\n\t| 'issuer_mismatch'\n\t| 'stale_crl'\n\t| 'crl_sign_not_permitted'\n\t| DecodeFailureCode,\n\tRecord<never, never>,\n\tValidateCertificateRevocationListFailure\n> {\n\treturn failureResult(code, message);\n}\n\n/** Builds a `CheckCertificateRevocationAgainstCrlFailureResult`. */\nfunction checkCertificateRevocationAgainstCrlFailureResult(\n\tcode: CheckCertificateRevocationAgainstCrlErrorCode,\n\tmessage: string,\n\tdetails?: CheckCertificateRevocationAgainstCrlFailureDetails,\n): ErrorResult<\n\tCheckCertificateRevocationAgainstCrlErrorCode,\n\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\tCheckCertificateRevocationAgainstCrlFailure\n> {\n\treturn failureResult(code, message, details);\n}\n\n/** Wraps a success value into a `CheckCertificateRevocationAgainstCrlResult`. */\nfunction checkCertificateRevocationAgainstCrlSuccess(\n\tvalue: CheckCertificateRevocationAgainstCrlValue,\n): CheckCertificateRevocationAgainstCrlResult {\n\treturn { ok: true, value };\n}\n\n/**\n * Quick serial-number lookup — returns `true` if the serial appears in the\n * CRL's revoked entries. Does **not** validate the CRL or check applicability.\n */\nexport function isCertificateRevoked(\n\tcertificateSerialNumber: Uint8Array | string,\n\tcrl: ParsedCertificateRevocationList,\n): boolean {\n\tconst serialNumberHex =\n\t\ttypeof certificateSerialNumber === 'string'\n\t\t\t? normalizeHex(certificateSerialNumber)\n\t\t\t: toHex(certificateSerialNumber);\n\treturn crl.revokedCertificates.some(\n\t\t(entry) => normalizeHex(entry.serialNumberHex) === serialNumberHex,\n\t);\n}\n\n/** Searches CRL entries for the certificate's serial, respecting indirect-CRL issuer overrides. */\nfunction findRevokedCertificateEntry(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n): RevokedCertificateLookupResult {\n\ttry {\n\t\treturn lookupRevokedCertificateEntry(certificate, crl);\n\t} catch (error) {\n\t\treturn crlNameRefusalFailure(error);\n\t}\n}\n\nfunction lookupRevokedCertificateEntry(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n): RevokedCertificateLookupResult {\n\tconst serialNumberHex = normalizeHex(certificate.serialNumberHex);\n\tlet effectiveIssuer: readonly GeneralName[] | undefined;\n\tlet sawUnsupportedIssuer = false;\n\tlet matchedEntry: ParsedRevokedCertificate | undefined;\n\tfor (const entry of crl.revokedCertificates) {\n\t\tif (entry.certificateIssuer !== undefined) {\n\t\t\teffectiveIssuer = entry.certificateIssuer;\n\t\t}\n\t\tif (normalizeHex(entry.serialNumberHex) !== serialNumberHex) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst issuerMatch = matchesRevokedEntryIssuer(certificate, crl, effectiveIssuer);\n\t\tif (issuerMatch === 'match') {\n\t\t\tif (matchedEntry !== undefined) {\n\t\t\t\treturn checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\t\t\t'signature_invalid',\n\t\t\t\t\t'CRL contains multiple revoked entries for certificate',\n\t\t\t\t);\n\t\t\t}\n\t\t\tmatchedEntry = entry;\n\t\t\tcontinue;\n\t\t}\n\t\tif (issuerMatch === 'unsupported') {\n\t\t\tsawUnsupportedIssuer = true;\n\t\t}\n\t}\n\tif (matchedEntry !== undefined) {\n\t\treturn { ok: true, entry: matchedEntry };\n\t}\n\tif (sawUnsupportedIssuer) {\n\t\treturn nonApplicable(\n\t\t\t'unsupported_indirect_crl',\n\t\t\t'indirect CRL entry certificateIssuer must include a directoryName',\n\t\t);\n\t}\n\treturn { ok: true };\n}\n\n/**\n * Whether `crl` covers `certificate` under {@linkcode checkCrlApplicability}.\n *\n * @internal\n */\nexport function isCrlApplicableTo(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n): boolean {\n\treturn checkCrlApplicability(certificate, crl).ok;\n}\n\n/** RFC 5280 §6.3 CRL applicability: scope, distribution-point, reason, and indirect-CRL checks. */\nfunction checkCrlApplicability(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\tallowDeltaCrl = false,\n): CrlApplicabilityOutcome {\n\ttry {\n\t\treturn evaluateCrlApplicability(certificate, crl, allowDeltaCrl);\n\t} catch (error) {\n\t\treturn { ok: false, failure: crlNameRefusalFailure(error) };\n\t}\n}\n\nfunction evaluateCrlApplicability(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\tallowDeltaCrl: boolean,\n): CrlApplicabilityOutcome {\n\tif (!allowDeltaCrl && crl.baseCrlNumber !== undefined) {\n\t\treturn notApplicableOutcome(\n\t\t\t'unsupported_delta_crl',\n\t\t\t'a delta CRL cannot be used as the primary complete CRL input',\n\t\t);\n\t}\n\tconst issuingDistributionPoint = crl.issuingDistributionPoint;\n\tconst isIndirectCrl = issuingDistributionPoint?.indirectCrl === true;\n\tif (!isIndirectCrl && !compareDistinguishedNames(certificate.issuer, crl.issuer)) {\n\t\treturn notApplicableOutcome(\n\t\t\t'issuer_mismatch',\n\t\t\t'CRL issuer does not match certificate issuer for direct CRL processing',\n\t\t);\n\t}\n\tif (issuingDistributionPoint?.onlyContainsAttributeCerts === true) {\n\t\treturn notApplicableOutcome(\n\t\t\t'certificate_scope_mismatch',\n\t\t\t'attribute-certificate-only CRLs are not applicable to public-key certificates',\n\t\t);\n\t}\n\tconst isCaCertificate = certificate.basicConstraints?.ca === true;\n\tif (issuingDistributionPoint?.onlyContainsUserCerts === true && isCaCertificate) {\n\t\treturn notApplicableOutcome(\n\t\t\t'certificate_scope_mismatch',\n\t\t\t'CRL only applies to end-entity certificates',\n\t\t);\n\t}\n\tif (issuingDistributionPoint?.onlyContainsCACerts === true && !isCaCertificate) {\n\t\treturn notApplicableOutcome(\n\t\t\t'certificate_scope_mismatch',\n\t\t\t'CRL only applies to CA certificates',\n\t\t);\n\t}\n\tconst distributionPoints = certificate.crlDistributionPoints ?? [];\n\tif (distributionPoints.length === 0) {\n\t\tif (\n\t\t\tissuingDistributionPoint?.distributionPoint !== undefined &&\n\t\t\t!matchesDistributionPointName(\n\t\t\t\tissuerFallbackDistributionPointName(certificate),\n\t\t\t\tissuingDistributionPoint.distributionPoint,\n\t\t\t\tcrl.issuer,\n\t\t\t\tundefined,\n\t\t\t)\n\t\t) {\n\t\t\treturn notApplicableOutcome(\n\t\t\t\t'distribution_point_mismatch',\n\t\t\t\t'CRL issuing distribution point does not name the certificate issuer',\n\t\t\t);\n\t\t}\n\t\tif (isIndirectCrl && !compareDistinguishedNames(certificate.issuer, crl.issuer)) {\n\t\t\treturn notApplicableOutcome(\n\t\t\t\t'issuer_mismatch',\n\t\t\t\t'indirect CRLs for alternate certificate issuers require matching CRLIssuer distribution points',\n\t\t\t);\n\t\t}\n\t\treturn { ok: true, coveredReasons: interimReasonsMask(undefined, issuingDistributionPoint) };\n\t}\n\tconst scanResult = scanCrlDistributionPoints(\n\t\tdistributionPoints,\n\t\tcertificate,\n\t\tcrl,\n\t\tissuingDistributionPoint,\n\t\tisIndirectCrl,\n\t);\n\tif (typeof scanResult === 'string') {\n\t\treturn { ok: false, failure: crlDistributionPointScanFailure(scanResult) };\n\t}\n\treturn { ok: true, coveredReasons: scanResult.coveredReasons };\n}\n\n/** Wraps a non-applicability failure into a {@linkcode CrlApplicabilityOutcome}. */\nfunction notApplicableOutcome(\n\treason: CrlApplicabilityFailureReason,\n\tmessage: string,\n): CrlApplicabilityOutcome {\n\treturn { ok: false, failure: nonApplicable(reason, message) };\n}\n\n/**\n * RFC 5280 §6.3.3 final paragraph: for a certificate without a CRLDP extension,\n * assume a distribution point named by the certificate issuer and its\n * issuerAltName entries, with reasons and cRLIssuer omitted.\n */\nfunction issuerFallbackDistributionPointName(\n\tcertificate: ParsedCertificate,\n): ParsedDistributionPointName {\n\treturn {\n\t\ttype: 'fullName',\n\t\tfullName: [\n\t\t\t{ type: 'directoryName', derHex: certificate.issuer.derHex },\n\t\t\t...(certificate.issuerAltNames ?? []),\n\t\t],\n\t};\n}\n\n/**\n * Aggregates distribution-point matching across a certificate.\n *\n * RFC 5280 §6.3.3 processes every corresponding DP, so when several match the same CRL their\n * interim reason masks (d) are unioned rather than stopping at the first.\n */\nfunction scanCrlDistributionPoints(\n\tdistributionPoints: readonly ParsedDistributionPoint[],\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\tissuingDistributionPoint: ParsedIssuingDistributionPoint | undefined,\n\tisIndirectCrl: boolean,\n):\n\t| { readonly coveredReasons: readonly DistributionPointReason[] }\n\t| CrlDistributionPointScanFailure {\n\tconst coveredReasons = new Set<DistributionPointReason>();\n\tconst failures = new Set<CrlDistributionPointScanFailure>();\n\tlet sawMatch = false;\n\tfor (const distributionPoint of distributionPoints) {\n\t\tconst result = scanCrlDistributionPoint(\n\t\t\tdistributionPoint,\n\t\t\tcertificate,\n\t\t\tcrl,\n\t\t\tissuingDistributionPoint,\n\t\t\tisIndirectCrl,\n\t\t);\n\t\tif (result === 'matched') {\n\t\t\tsawMatch = true;\n\t\t\tfor (const reason of interimReasonsMask(distributionPoint, issuingDistributionPoint)) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfailures.add(result);\n\t}\n\treturn sawMatch ? { coveredReasons: [...coveredReasons] } : resolveScanFailure(failures);\n}\n\n/** Reports the highest-precedence distribution-point scan failure. */\nfunction resolveScanFailure(\n\tfailures: ReadonlySet<CrlDistributionPointScanFailure>,\n): CrlDistributionPointScanFailure {\n\tconst precedence: readonly CrlDistributionPointScanFailure[] = [\n\t\t'reasons_mismatch',\n\t\t'unsupported_indirect_crl_issuer',\n\t\t'indirect_issuer_mismatch',\n\t\t'distribution_point_mismatch',\n\t\t'indirect_distribution_point',\n\t];\n\treturn precedence.find((failure) => failures.has(failure)) ?? 'scope_mismatch';\n}\n\nfunction scanCrlDistributionPoint(\n\tdistributionPoint: ParsedDistributionPoint,\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\tissuingDistributionPoint: ParsedIssuingDistributionPoint | undefined,\n\tisIndirectCrl: boolean,\n): CrlDistributionPointScanResult {\n\tconst issuerResult = scanCrlDistributionPointIssuer(\n\t\tdistributionPoint,\n\t\tcertificate,\n\t\tcrl,\n\t\tisIndirectCrl,\n\t);\n\tif (issuerResult !== undefined) return issuerResult;\n\tif (\n\t\t!matchesDistributionPointName(\n\t\t\tdistributionPoint.distributionPoint,\n\t\t\tissuingDistributionPoint?.distributionPoint,\n\t\t\tcrl.issuer,\n\t\t\tdistributionPoint.crlIssuer,\n\t\t)\n\t) {\n\t\treturn 'distribution_point_mismatch';\n\t}\n\treturn hasOverlappingReasons(distributionPoint.reasons, issuingDistributionPoint?.onlySomeReasons)\n\t\t? 'matched'\n\t\t: 'reasons_mismatch';\n}\n\nfunction scanCrlDistributionPointIssuer(\n\tdistributionPoint: ParsedDistributionPoint,\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\tisIndirectCrl: boolean,\n): CrlDistributionPointScanResult | undefined {\n\tif (!isIndirectCrl) {\n\t\treturn distributionPoint.crlIssuer === undefined ? undefined : 'indirect_distribution_point';\n\t}\n\tif (\n\t\tcompareDistinguishedNames(certificate.issuer, crl.issuer) &&\n\t\tdistributionPoint.crlIssuer === undefined\n\t) {\n\t\treturn undefined;\n\t}\n\tconst issuerMatch = matchesIndirectCrlIssuer(distributionPoint.crlIssuer, crl);\n\tif (issuerMatch === 'unsupported') return 'unsupported_indirect_crl_issuer';\n\treturn issuerMatch ? undefined : 'indirect_issuer_mismatch';\n}\n\nfunction crlDistributionPointScanFailure(\n\tresult: CrlDistributionPointScanFailure,\n): CrlApplicabilityFailure {\n\tif (result === 'reasons_mismatch') {\n\t\treturn nonApplicable(\n\t\t\t'reasons_mismatch',\n\t\t\t'certificate distribution point reasons do not overlap the CRL reason scope',\n\t\t);\n\t}\n\tif (result === 'unsupported_indirect_crl_issuer') {\n\t\treturn nonApplicable(\n\t\t\t'unsupported_indirect_crl',\n\t\t\t'indirect CRL distribution points must identify the CRL issuer with directoryName',\n\t\t);\n\t}\n\tif (result === 'indirect_issuer_mismatch') {\n\t\treturn nonApplicable(\n\t\t\t'issuer_mismatch',\n\t\t\t'certificate distribution points do not authorize this indirect CRL issuer',\n\t\t);\n\t}\n\tif (result === 'distribution_point_mismatch') {\n\t\treturn nonApplicable(\n\t\t\t'distribution_point_mismatch',\n\t\t\t'certificate distribution points do not match the CRL issuing distribution point',\n\t\t);\n\t}\n\tif (result === 'indirect_distribution_point') {\n\t\treturn nonApplicable(\n\t\t\t'unsupported_indirect_crl',\n\t\t\t'certificate distribution points that name alternate CRL issuers are not supported yet',\n\t\t);\n\t}\n\treturn nonApplicable(\n\t\t'distribution_point_mismatch',\n\t\t'certificate distribution points do not match the CRL scope',\n\t);\n}\n\n/** Verifies that a delta CRL is compatible with the given complete CRL (same issuer, AKI, IDP, and valid numbering). */\nfunction checkDeltaCrlCompatibility(\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tdeltaCrl: ParsedCertificateRevocationList,\n):\n\t| ErrorResult<\n\t\t\tCheckCertificateRevocationAgainstCrlErrorCode,\n\t\t\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\t\t\tCheckCertificateRevocationAgainstCrlFailure\n\t >\n\t| undefined {\n\tif (completeCrl.baseCrlNumber !== undefined) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'complete CRL input must not itself be a delta CRL',\n\t\t);\n\t}\n\tif (deltaCrl.baseCrlNumber === undefined) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'delta CRL input must include a delta CRL indicator',\n\t\t);\n\t}\n\tif (!compareDistinguishedNames(completeCrl.issuer, deltaCrl.issuer)) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'complete and delta CRLs must share the same issuer',\n\t\t);\n\t}\n\tif (completeCrl.authorityKeyIdentifier !== deltaCrl.authorityKeyIdentifier) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'complete and delta CRLs must share the same authority key identifier',\n\t\t);\n\t}\n\tif (\n\t\t!sameIssuingDistributionPoint(\n\t\t\tcompleteCrl.issuingDistributionPoint,\n\t\t\tdeltaCrl.issuingDistributionPoint,\n\t\t)\n\t) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'complete and delta CRLs must share the same issuing distribution point scope',\n\t\t);\n\t}\n\tif (completeCrl.crlNumber === undefined || deltaCrl.crlNumber === undefined) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'complete and delta CRLs must both carry CRL numbers for delta processing',\n\t\t);\n\t}\n\tif (completeCrl.crlNumber < deltaCrl.baseCrlNumber) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'delta CRL base number must not exceed the complete CRL number',\n\t\t);\n\t}\n\tif (completeCrl.crlNumber >= deltaCrl.crlNumber) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'delta CRL number must be newer than the complete CRL number',\n\t\t);\n\t}\n\tif (completeCrl.thisUpdate.getTime() > deltaCrl.thisUpdate.getTime()) {\n\t\treturn nonApplicable(\n\t\t\t'delta_crl_incompatible',\n\t\t\t'delta CRL thisUpdate must not precede the complete CRL thisUpdate',\n\t\t);\n\t}\n\treturn undefined;\n}\n\n/** RFC 5280 §4.2.1.13 requires only the CRL issuer DN, with identical DER encoding. */\nfunction matchesIndirectCrlIssuer(\n\tcrlIssuerNames: readonly GeneralName[] | undefined,\n\tcrl: ParsedCertificateRevocationList,\n): boolean | 'unsupported' {\n\tif (crlIssuerNames === undefined || crlIssuerNames.length === 0) return false;\n\tif (crlIssuerNames.some((name) => name.type !== 'directoryName')) return 'unsupported';\n\treturn crlIssuerNames.every(\n\t\t(name) =>\n\t\t\tname.type === 'directoryName' &&\n\t\t\tname.derHex.toLowerCase() === crl.issuer.derHex.toLowerCase(),\n\t);\n}\n\n/** Determines whether a revoked entry's effective issuer matches the certificate's issuer. */\nfunction matchesRevokedEntryIssuer(\n\tcertificate: ParsedCertificate,\n\tcrl: ParsedCertificateRevocationList,\n\teffectiveIssuer: readonly GeneralName[] | undefined,\n): 'match' | 'mismatch' | 'unsupported' {\n\tif (effectiveIssuer === undefined) {\n\t\treturn compareDistinguishedNames(certificate.issuer, crl.issuer) ? 'match' : 'mismatch';\n\t}\n\tlet sawUnsupportedName = false;\n\tfor (const generalName of effectiveIssuer) {\n\t\tif (generalName.type === 'directoryName') {\n\t\t\tif (directoryNameDerHexMatchesParsedName(generalName.derHex, certificate.issuer)) {\n\t\t\t\treturn 'match';\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tsawUnsupportedName = true;\n\t}\n\treturn sawUnsupportedName ? 'unsupported' : 'mismatch';\n}\n\n/** Shorthand for building a `non_applicable` failure result with the given reason. */\nfunction nonApplicable(\n\treason: CrlApplicabilityFailureReason,\n\tmessage: string,\n): ErrorResult<\n\tCheckCertificateRevocationAgainstCrlErrorCode,\n\tCheckCertificateRevocationAgainstCrlFailureDetails,\n\tCheckCertificateRevocationAgainstCrlFailure\n> {\n\treturn checkCertificateRevocationAgainstCrlFailureResult('non_applicable', message, { reason });\n}\n\n/**\n * Merges complete and delta CRL entries into a final `good`/`revoked` status\n * per the RFC 5280 §6.3.3 (i)-(k) relying-party algorithm.\n *\n * Deliberately harder than (i)-(k) on `removeFromCRL`: the entry clears a\n * revocation only in the two situations §5.2.4(b)/§5.3.1 permit an issuer to\n * emit it, a complete-CRL `certificateHold` entry or a certificate that\n * expired before the delta CRL's thisUpdate.\n */\nfunction resolveCertificateRevocationStatus(\n\tcertificate: ParsedCertificate,\n\tdeltaThisUpdate: Date | undefined,\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tcompleteEntry: ParsedRevokedCertificate | undefined,\n\tdeltaEntry: ParsedRevokedCertificate | undefined,\n\tcoveredReasons: readonly DistributionPointReason[],\n\tunrecognizedReasonCode: UnrecognizedReasonCodePolicy,\n): CheckCertificateRevocationAgainstCrlResult {\n\tif (deltaEntry !== undefined) {\n\t\tif (deltaEntry.reasonCode === 'removeFromCRL') {\n\t\t\tif (\n\t\t\t\tcompleteEntry?.reasonCode === 'certificateHold' ||\n\t\t\t\t(deltaThisUpdate !== undefined &&\n\t\t\t\t\tcertificate.notAfter.getTime() < deltaThisUpdate.getTime())\n\t\t\t) {\n\t\t\t\treturn checkCertificateRevocationAgainstCrlSuccess({\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\tcrl: completeCrl,\n\t\t\t\t\tcoveredReasons,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\treturn revokedEntryResult(completeCrl, deltaEntry, unrecognizedReasonCode);\n\t\t}\n\t}\n\tif (completeEntry === undefined) {\n\t\treturn checkCertificateRevocationAgainstCrlSuccess({\n\t\t\tstatus: 'good',\n\t\t\tcrl: completeCrl,\n\t\t\tcoveredReasons,\n\t\t});\n\t}\n\treturn revokedEntryResult(completeCrl, completeEntry, unrecognizedReasonCode);\n}\n\nfunction revokedEntryResult(\n\tcompleteCrl: ParsedCertificateRevocationList,\n\tentry: ParsedRevokedCertificate,\n\tunrecognizedReasonCode: UnrecognizedReasonCodePolicy,\n): CheckCertificateRevocationAgainstCrlResult {\n\tif (unrecognizedReasonCode === 'reject' && typeof entry.reasonCode === 'object') {\n\t\treturn checkCertificateRevocationAgainstCrlFailureResult(\n\t\t\t'reason_code_unrecognized',\n\t\t\t`CRL entry carries unrecognized reason code ${String(entry.reasonCode.code)}`,\n\t\t);\n\t}\n\treturn checkCertificateRevocationAgainstCrlSuccess({\n\t\tstatus: 'revoked',\n\t\tcrl: completeCrl,\n\t\trevocationDate: entry.revocationDate,\n\t\t...(entry.reasonCode === undefined ? {} : { reasonCode: entry.reasonCode }),\n\t});\n}\n\n/**\n * Returns `true` if the certificate's distribution-point name matches the CRL's IDP name.\n *\n * Per RFC 5280 §4.2.1.13, when the certificate uses `nameRelativeToCRLIssuer` (relativeName),\n * the full distribution point name is formed by appending that RDN to the CRL issuer's DN.\n * This resolved name is then compared against the CRL's IDP fullName directoryName entries.\n */\nfunction matchesDistributionPointName(\n\tcertificatePoint: ParsedDistributionPointName | undefined,\n\tcrlPoint: ParsedDistributionPointName | undefined,\n\tcrlIssuer: ParsedName,\n\tcertificateCrlIssuer: readonly GeneralName[] | undefined,\n): boolean {\n\tif (crlPoint === undefined) {\n\t\treturn true;\n\t}\n\tif (certificatePoint === undefined) {\n\t\treturn matchesIdpNameAgainstCrlIssuer(crlPoint, certificateCrlIssuer, crlIssuer);\n\t}\n\tif (certificatePoint.type === 'fullName' && crlPoint.type === 'fullName') {\n\t\treturn certificatePoint.fullName.some((leftName) =>\n\t\t\tcrlPoint.fullName.some((rightName) => compareGeneralNames(leftName, rightName)),\n\t\t);\n\t}\n\tif (certificatePoint.type === 'relativeName' && crlPoint.type === 'fullName') {\n\t\tconst resolvedDnHex = resolveRelativeNameToDnHex(crlIssuer, certificatePoint.relativeName);\n\t\treturn crlPoint.fullName.some(\n\t\t\t(name) => name.type === 'directoryName' && name.derHex === resolvedDnHex,\n\t\t);\n\t}\n\tif (certificatePoint.type === 'relativeName' && crlPoint.type === 'relativeName') {\n\t\treturn compareRelativeDistinguishedNames(certificatePoint.relativeName, crlPoint.relativeName);\n\t}\n\tif (certificatePoint.type === 'fullName' && crlPoint.type === 'relativeName') {\n\t\tconst resolvedDnHex = resolveRelativeNameToDnHex(crlIssuer, crlPoint.relativeName);\n\t\treturn certificatePoint.fullName.some(\n\t\t\t(name) => name.type === 'directoryName' && name.derHex === resolvedDnHex,\n\t\t);\n\t}\n\treturn false;\n}\n\n/**\n * RFC 5280 §6.3.3 (b)(2)(i): when the certificate's distribution point omits the\n * distributionPoint field, match the CRL IDP's distributionPoint names against\n * the distribution point's `cRLIssuer` names.\n */\nfunction matchesIdpNameAgainstCrlIssuer(\n\tcrlPoint: ParsedDistributionPointName,\n\tcertificateCrlIssuer: readonly GeneralName[] | undefined,\n\tcrlIssuer: ParsedName,\n): boolean {\n\tif (certificateCrlIssuer === undefined) {\n\t\treturn false;\n\t}\n\tif (crlPoint.type === 'fullName') {\n\t\treturn certificateCrlIssuer.some((issuerName) =>\n\t\t\tcrlPoint.fullName.some((name) => compareGeneralNames(issuerName, name)),\n\t\t);\n\t}\n\tconst resolvedDnHex = resolveRelativeNameToDnHex(crlIssuer, crlPoint.relativeName);\n\treturn certificateCrlIssuer.some(\n\t\t(issuerName) => issuerName.type === 'directoryName' && issuerName.derHex === resolvedDnHex,\n\t);\n}\n\n/** Constructs a full DN by appending an RDN to an existing Name, returning hex-encoded DER. */\nfunction resolveRelativeNameToDnHex(\n\tissuer: ParsedName,\n\trelativeName: ParsedRelativeDistinguishedName,\n): string {\n\t// Collect existing RDN DER bytes from issuer\n\tconst rdnDerParts = issuer.rdns.map((rdn) => hexToBytes(rdn.derHex));\n\t// The relativeName.derHex has implicit tag [1] (0xa1) from the CHOICE encoding.\n\t// Extract the content and re-wrap as a proper RDN SET (tag 0x31).\n\tconst relativeNameDer = hexToBytes(relativeName.derHex);\n\tconst relativeNameRdnDer = rebuildRelativeNameAsSet(relativeNameDer);\n\trdnDerParts.push(relativeNameRdnDer);\n\t// Wrap in a Name SEQUENCE\n\treturn toHex(sequence(rdnDerParts));\n}\n\n/** Converts an implicit-tagged [1] relativeName to a proper SET-tagged RDN. */\nfunction rebuildRelativeNameAsSet(implicitTaggedDer: Uint8Array): Uint8Array {\n\t// The implicit tag [1] is 0xa1 (context-specific constructed).\n\t// Parse the element to get content, then re-wrap with SET tag 0x31.\n\tconst element = readRootElement(implicitTaggedDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\treturn tlv(0x31, element.value);\n}\n\n/** Deep-compares two issuing distribution point extensions for delta-CRL compatibility. */\nfunction sameIssuingDistributionPoint(\n\tleft: ParsedIssuingDistributionPoint | undefined,\n\tright: ParsedIssuingDistributionPoint | undefined,\n): boolean {\n\tif (left === undefined || right === undefined) {\n\t\treturn left === right;\n\t}\n\treturn (\n\t\tsameDistributionPointName(left.distributionPoint, right.distributionPoint) &&\n\t\t(left.onlyContainsUserCerts === true) === (right.onlyContainsUserCerts === true) &&\n\t\t(left.onlyContainsCACerts === true) === (right.onlyContainsCACerts === true) &&\n\t\t(left.indirectCrl === true) === (right.indirectCrl === true) &&\n\t\t(left.onlyContainsAttributeCerts === true) === (right.onlyContainsAttributeCerts === true) &&\n\t\tsameReasonSet(left.onlySomeReasons, right.onlySomeReasons)\n\t);\n}\n\n/** Compares two DistributionPointName values (fullName set or relativeName). */\nfunction sameDistributionPointName(\n\tleft: ParsedDistributionPointName | undefined,\n\tright: ParsedDistributionPointName | undefined,\n): boolean {\n\tif (left === undefined || right === undefined) {\n\t\treturn left === right;\n\t}\n\tif (left.type === 'fullName' && right.type === 'fullName') {\n\t\treturn sameGeneralNameSet(left.fullName, right.fullName);\n\t}\n\tif (left.type === 'relativeName' && right.type === 'relativeName') {\n\t\treturn compareRelativeDistinguishedNames(left.relativeName, right.relativeName);\n\t}\n\treturn false;\n}\n\n/** Set-equality comparison for GeneralName arrays (order-independent). */\nfunction sameGeneralNameSet(left: readonly GeneralName[], right: readonly GeneralName[]): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tconst matched = Array.from({ length: right.length }, () => false);\n\tfor (const leftName of left) {\n\t\tlet found = false;\n\t\tfor (let index = 0; index < right.length; index += 1) {\n\t\t\tconst rightName = right[index];\n\t\t\tif (rightName === undefined || matched[index]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!compareGeneralNames(leftName, rightName)) {\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/** Set-equality comparison for DistributionPointReason arrays. */\nfunction sameReasonSet(\n\tleft: ParsedBitFlags<DistributionPointReason> | undefined,\n\tright: ParsedBitFlags<DistributionPointReason> | undefined,\n): boolean {\n\tif (left === undefined || right === undefined) {\n\t\treturn left === right;\n\t}\n\tif (left.flags.length !== right.flags.length) {\n\t\treturn false;\n\t}\n\treturn left.flags.every((reason) => right.flags.includes(reason));\n}\n\n/** Returns `true` if the certificate's DP reasons overlap the CRL's `onlySomeReasons`, or if either is absent (= all reasons). */\nfunction hasOverlappingReasons(\n\tcertificateReasons: ParsedBitFlags<DistributionPointReason> | undefined,\n\tcrlReasons: ParsedBitFlags<DistributionPointReason> | undefined,\n): boolean {\n\tif (certificateReasons === undefined || crlReasons === undefined) {\n\t\treturn true;\n\t}\n\treturn certificateReasons.flags.some((reason) => crlReasons.flags.includes(reason));\n}\n\n/** Value-equality for two GeneralName entries, using DER comparison for directoryName. */\nfunction compareGeneralNames(left: GeneralName, right: GeneralName): boolean {\n\tif (left.type === 'dns' && right.type === 'dns') {\n\t\t// RFC 5280 §7.2: dNSName comparison is case-insensitive.\n\t\treturn left.value.toLowerCase() === right.value.toLowerCase();\n\t}\n\tif (left.type === 'srv' && right.type === 'srv') {\n\t\t// RFC 4985 §2: the SRVName Service and the DNS Name both compare case-insensitively.\n\t\treturn compareSrvNames(left.value.toLowerCase(), right.value.toLowerCase());\n\t}\n\tif (left.type === 'email' && right.type === 'email') {\n\t\treturn compareRfc822Names(left.value, right.value);\n\t}\n\tif (left.type === 'smtpUtf8Mailbox' && right.type === 'smtpUtf8Mailbox') {\n\t\t// RFC 9598 §5: two SmtpUTF8Mailboxes are equivalent on an exact octet-for-octet match.\n\t\treturn left.value === right.value;\n\t}\n\tif (left.type === 'ip' && right.type === 'ip') {\n\t\treturn left.value === right.value;\n\t}\n\tif (left.type === 'uri' && right.type === 'uri') {\n\t\treturn compareUniformResourceIdentifiers(left.value, right.value);\n\t}\n\tif (left.type === 'directoryName' && right.type === 'directoryName') {\n\t\tconst leftName = parseDerHexName(left.derHex);\n\t\tconst rightName = parseDerHexName(right.derHex);\n\t\tif (leftName === undefined || rightName === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn compareDistinguishedNames(leftName, rightName);\n\t}\n\treturn compareOpaqueGeneralNames(left, right);\n}\n\nfunction compareSrvNames(left: string, right: string): boolean {\n\tconst leftParts = parsePresentedSrvName(left);\n\tconst rightParts = parsePresentedSrvName(right);\n\tif (leftParts === undefined || rightParts === undefined) {\n\t\treturn left === right;\n\t}\n\treturn leftParts.service === rightParts.service && leftParts.name === rightParts.name;\n}\n\n/** Encoding equality for the GeneralName alternatives carried as DER or an OID. */\nfunction compareOpaqueGeneralNames(left: GeneralName, right: GeneralName): boolean {\n\tif (left.type === 'otherName' && right.type === 'otherName') {\n\t\treturn left.typeId === right.typeId && bytesEqual(left.value, right.value);\n\t}\n\tif (left.type === 'upn' && right.type === 'upn') {\n\t\treturn left.value === right.value;\n\t}\n\tif (left.type === 'krb5PrincipalName' && right.type === 'krb5PrincipalName') {\n\t\treturn (\n\t\t\tleft.realm === right.realm &&\n\t\t\tleft.nameType === right.nameType &&\n\t\t\tleft.nameString.length === right.nameString.length &&\n\t\t\tleft.nameString.every((component, index) => component === right.nameString[index])\n\t\t);\n\t}\n\tif (\n\t\t(left.type === 'x400Address' && right.type === 'x400Address') ||\n\t\t(left.type === 'ediPartyName' && right.type === 'ediPartyName')\n\t) {\n\t\treturn bytesEqual(left.value, right.value);\n\t}\n\tif (left.type === 'registeredID' && right.type === 'registeredID') {\n\t\treturn left.value === right.value;\n\t}\n\tif (left.type === 'unknown' && right.type === 'unknown') {\n\t\treturn left.tag === right.tag && bytesEqual(left.value, right.value);\n\t}\n\treturn false;\n}\n\n/** RFC 5280 §7.5: rfc822Name local-part is case-sensitive, the host-part case-insensitive. */\nfunction compareRfc822Names(left: string, right: string): boolean {\n\tconst leftAt = left.lastIndexOf('@');\n\tconst rightAt = right.lastIndexOf('@');\n\tif (leftAt < 0 || rightAt < 0) {\n\t\treturn left.toLowerCase() === right.toLowerCase();\n\t}\n\treturn (\n\t\tleft.slice(0, leftAt) === right.slice(0, rightAt) &&\n\t\tleft.slice(leftAt + 1).toLowerCase() === right.slice(rightAt + 1).toLowerCase()\n\t);\n}\n\n/** RFC 5280 §7.4: URIs compare only after syntax-based and scheme-based normalization. */\nfunction compareUniformResourceIdentifiers(left: string, right: string): boolean {\n\tif (left === right) {\n\t\treturn true;\n\t}\n\tconst normalizedLeft = normalizeUriForComparison(left);\n\tif (normalizedLeft === undefined) {\n\t\treturn false;\n\t}\n\treturn normalizedLeft === normalizeUriForComparison(right);\n}\n\n/**\n * The schemes RFC 5280 §7.4 step 5 requires implementations to recognise, with\n * the default port that scheme-based normalization elides. `ldaps` is included\n * as the TLS form of the mandatory `ldap` scheme.\n */\nconst URI_DEFAULT_PORT_BY_SCHEME: ReadonlyMap<string, string> = new Map([\n\t['ftp', '21'],\n\t['http', '80'],\n\t['https', '443'],\n\t['ldap', '389'],\n\t['ldaps', '636'],\n]);\n\n/**\n * Applies the RFC 5280 §7.4 comparison preparation: IDN labels to ASCII\n * Compatible Encoding, lowercased scheme and host, percent-encoding and path\n * segment normalization, and scheme-based normalization. The URL parser covers\n * path segments for every scheme and the scheme case; the remaining steps are\n * applied here because it leaves the host of a non-special scheme such as\n * `ldap` untouched and never normalizes percent-encoding.\n *\n * @returns `undefined` when the value does not parse as an absolute URI.\n */\nfunction normalizeUriForComparison(value: string): string | undefined {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (url.hostname !== '') {\n\t\tconst host = normalizeUriHost(url.hostname);\n\t\tif (host === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\turl.hostname = host;\n\t}\n\tif (url.port === URI_DEFAULT_PORT_BY_SCHEME.get(url.protocol.slice(0, -1))) {\n\t\turl.port = '';\n\t}\n\treturn normalizePercentEncoding(url.href);\n}\n\n/**\n * Reparses a host under a special scheme so the URL parser applies IDNA and\n * lowercasing to it, which it skips for opaque hosts.\n *\n * @returns `undefined` when the host does not survive the round trip intact.\n */\nfunction normalizeUriHost(hostname: string): string | undefined {\n\ttry {\n\t\tconst probe = new URL(`https://${decodeHostPercentEncoding(hostname)}`);\n\t\treturn probe.href === `https://${probe.hostname}/` ? probe.hostname : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Recovers the Unicode host an opaque-host URI carries as percent-encoded UTF-8. */\nfunction decodeHostPercentEncoding(hostname: string): string {\n\ttry {\n\t\treturn decodeURIComponent(hostname);\n\t} catch {\n\t\treturn hostname;\n\t}\n}\n\nconst PERCENT_TRIPLET = /%[0-9A-Fa-f]{2}/g;\n\n/** RFC 3986 §6.2.2.2: unreserved triplets decode, every other triplet uppercases. */\nfunction normalizePercentEncoding(value: string): string {\n\treturn value.replace(PERCENT_TRIPLET, (triplet) => {\n\t\tconst code = Number.parseInt(triplet.slice(1), 16);\n\t\treturn isUnreservedUriCharacter(code) ? String.fromCharCode(code) : triplet.toUpperCase();\n\t});\n}\n\n/** RFC 3986 §2.3 unreserved set: `ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"`. */\nfunction isUnreservedUriCharacter(code: number): boolean {\n\treturn (\n\t\t(code >= 0x41 && code <= 0x5a) ||\n\t\t(code >= 0x61 && code <= 0x7a) ||\n\t\t(code >= 0x30 && code <= 0x39) ||\n\t\tcode === 0x2d ||\n\t\tcode === 0x2e ||\n\t\tcode === 0x5f ||\n\t\tcode === 0x7e\n\t);\n}\n\n/** Constant-length byte-array equality check. */\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tfor (let index = 0; index < left.length; index += 1) {\n\t\tif (left[index] !== right[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Assembles the CRL-level v2 extensions (AKI, CRLNumber, deltaCRLIndicator, IDP, freshestCRL). */\nfunction buildCrlExtensions(\n\tissuerCertificate: ParsedCertificate,\n\tcrlNumber: Uint8Array,\n\tbaseCrlNumber?: Uint8Array,\n\tissuingDistributionPoint?: IssuingDistributionPoint,\n\tfreshestCrlDistributionPoints?: readonly DistributionPoint[],\n): Uint8Array[] {\n\tconst extensions: Uint8Array[] = [\n\t\tencodeExtension(\n\t\t\tOIDS.authorityKeyIdentifier,\n\t\t\tsequence([implicitPrimitiveContext(0, issuerKeyIdentifier(issuerCertificate))]),\n\t\t),\n\t\tencodeExtension(OIDS.cRLNumber, crlNumber),\n\t];\n\tif (baseCrlNumber !== undefined) {\n\t\textensions.push(encodeExtension(OIDS.deltaCRLIndicator, baseCrlNumber, true));\n\t}\n\tif (issuingDistributionPoint !== undefined) {\n\t\textensions.push(\n\t\t\tencodeExtension(\n\t\t\t\tOIDS.issuingDistributionPoint,\n\t\t\t\tencodeIssuingDistributionPoint(issuingDistributionPoint),\n\t\t\t\ttrue,\n\t\t\t),\n\t\t);\n\t}\n\tif (freshestCrlDistributionPoints !== undefined && freshestCrlDistributionPoints.length > 0) {\n\t\textensions.push(\n\t\t\tencodeExtension(OIDS.freshestCRL, encodeCrlDistributionPoints(freshestCrlDistributionPoints)),\n\t\t);\n\t}\n\treturn extensions;\n}\n\n/** DER-encodes a single revokedCertificate SEQUENCE (serial, date, optional extensions). */\nfunction createRevokedCertificate(entry: RevokedCertificateInput, thisUpdate: Date): Uint8Array {\n\tconst extensions = buildRevokedCertificateExtensions(entry);\n\treturn sequence([\n\t\tinteger(entry.serialNumber),\n\t\ttime(entry.revocationDate ?? thisUpdate),\n\t\t...(extensions.length === 0 ? [] : [sequence(extensions)]),\n\t]);\n}\n\n/** Encodes CRL entry extensions (reasonCode, invalidityDate). */\nfunction buildRevokedCertificateExtensions(entry: RevokedCertificateInput): Uint8Array[] {\n\tconst extensions: Uint8Array[] = [];\n\tif (entry.reasonCode !== undefined) {\n\t\textensions.push(\n\t\t\tencodeExtension(\n\t\t\t\tOIDS.cRLReason,\n\t\t\t\ttlv(0x0a, Uint8Array.of(REVOCATION_REASON_CODES[entry.reasonCode])),\n\t\t\t),\n\t\t);\n\t}\n\tif (entry.invalidityDate !== undefined) {\n\t\textensions.push(encodeExtension(OIDS.invalidityDate, generalizedTime(entry.invalidityDate)));\n\t}\n\treturn extensions;\n}\n\n/** Decodes per-entry CRL extensions (reasonCode, invalidityDate, certificateIssuer). */\nfunction parseRevokedCertificateExtensions(\n\tentryDer: Uint8Array | undefined,\n\telement: DerElement | undefined,\n): {\n\treadonly reasonCode?: ParsedRevocationReason;\n\treadonly invalidityDate?: Date;\n\treadonly certificateIssuer?: readonly GeneralName[];\n} {\n\tif (entryDer === undefined || element === undefined) {\n\t\treturn {};\n\t}\n\tconst fields: MutableRevokedCertificateExtensionFields = {};\n\tconst seenOids = new Set<string>();\n\tfor (const extension of childrenOf(entryDer, element)) {\n\t\tparseRevokedCertificateExtension(entryDer, extension, seenOids, fields);\n\t}\n\treturn {\n\t\t...(fields.reasonCode === undefined ? {} : { reasonCode: fields.reasonCode }),\n\t\t...(fields.invalidityDate === undefined ? {} : { invalidityDate: fields.invalidityDate }),\n\t\t...(fields.certificateIssuer === undefined\n\t\t\t? {}\n\t\t\t: { certificateIssuer: fields.certificateIssuer }),\n\t};\n}\n\nfunction parseRevokedCertificateExtension(\n\tentryDer: Uint8Array,\n\textension: DerElement,\n\tseenOids: Set<string>,\n\tfields: MutableRevokedCertificateExtensionFields,\n): void {\n\tconst parts = childrenOf(entryDer, extension);\n\tif (parts.length < 2 || parts.length > 3) {\n\t\tthrow new Error('Malformed revoked certificate extension');\n\t}\n\tif (parts.length === 3 && parts[1]?.tag !== 0x01) {\n\t\tthrow new Error('Malformed revoked certificate extension');\n\t}\n\tconst oid = decodeObjectIdentifier(\n\t\trequireElement(parts[0], 'revoked certificate extension OID').value,\n\t);\n\tif (seenOids.has(oid)) {\n\t\tthrow new Error(`Duplicate revoked certificate extension OID: ${oid}`);\n\t}\n\tseenOids.add(oid);\n\tconst critical =\n\t\tparts.length === 3\n\t\t\t? decodeBoolean(requireElement(parts[1], 'revoked certificate extension critical').value)\n\t\t\t: false;\n\tconst valueElement = requireElement(\n\t\tparts[parts.length - 1],\n\t\t'revoked certificate extension value',\n\t);\n\tif (valueElement.tag !== 0x04) {\n\t\tthrow new Error('Revoked certificate extension value must use OCTET STRING');\n\t}\n\tif (critical && !isSupportedRevokedCertificateExtensionOid(oid)) {\n\t\tthrow new Error(`Unsupported critical revoked certificate extension OID: ${oid}`);\n\t}\n\tapplyRevokedCertificateExtensionValue(oid, valueElement.value, critical, fields);\n}\n\nfunction isSupportedRevokedCertificateExtensionOid(oid: string): boolean {\n\treturn oid === OIDS.cRLReason || oid === OIDS.invalidityDate || oid === OIDS.certificateIssuer;\n}\n\nfunction applyRevokedCertificateExtensionValue(\n\toid: string,\n\tvalue: Uint8Array,\n\tcritical: boolean,\n\tfields: MutableRevokedCertificateExtensionFields,\n): void {\n\tif (oid === OIDS.cRLReason) {\n\t\tconst enumerated = readRootElement(value, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (enumerated.tag !== 0x0a) {\n\t\t\tthrow new Error('cRLReason must use ENUMERATED');\n\t\t}\n\t\tconst reasonCode = parsedRevocationReason(\n\t\t\tdecodeNonNegativeIntegerBigInt(enumerated.value, 'cRLReason'),\n\t\t);\n\t\tif (critical && typeof reasonCode !== 'string') {\n\t\t\tthrow new Error(\n\t\t\t\t`Critical cRLReason holds unrecognized reason code ${String(reasonCode.code)}`,\n\t\t\t);\n\t\t}\n\t\tfields.reasonCode = reasonCode;\n\t}\n\tif (oid === OIDS.invalidityDate) {\n\t\tfields.invalidityDate = parseTime(readRootElement(value, { maxDepth: DEFAULT_MAX_DER_DEPTH }));\n\t}\n\tif (oid === OIDS.certificateIssuer) {\n\t\tconst generalNames = readRootElement(value, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (generalNames.tag !== 0x30) {\n\t\t\tthrow new Error('certificateIssuer must use SEQUENCE');\n\t\t}\n\t\tfields.certificateIssuer = parseGeneralNames(value, generalNames);\n\t}\n}\n\n/** Decodes the IssuingDistributionPoint extension from its OCTET STRING content. */\nfunction parseIssuingDistributionPoint(valueDer: Uint8Array): ParsedIssuingDistributionPoint {\n\tconst sequenceElement = readRootElement(valueDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tconst fields: MutableIssuingDistributionPointFields = {};\n\tfor (const child of childrenOf(valueDer, sequenceElement)) {\n\t\tparseIssuingDistributionPointField(valueDer, child, fields);\n\t}\n\treturn {\n\t\t...(fields.distributionPoint === undefined\n\t\t\t? {}\n\t\t\t: { distributionPoint: fields.distributionPoint }),\n\t\t...(fields.onlySomeReasons === undefined ? {} : { onlySomeReasons: fields.onlySomeReasons }),\n\t\t...(fields.indirectCrl === undefined ? {} : { indirectCrl: fields.indirectCrl }),\n\t\t...parseIssuingDistributionPointScope(fields),\n\t};\n}\n\n/** RFC 5280 §5.2.5: at most one `onlyContains*` flag may be TRUE. */\nfunction parseIssuingDistributionPointScope(\n\tfields: MutableIssuingDistributionPointFields,\n): ParsedIssuingDistributionPointScope {\n\tconst userCerts = fields.onlyContainsUserCerts;\n\tconst caCerts = fields.onlyContainsCACerts;\n\tconst attributeCerts = fields.onlyContainsAttributeCerts;\n\tif (userCerts === true) {\n\t\tif (caCerts === true || attributeCerts === true) {\n\t\t\tthrow new Error(IDP_SCOPE_CONFLICT);\n\t\t}\n\t\treturn { onlyContainsUserCerts: true, ...unselectedScopeFlags({ caCerts, attributeCerts }) };\n\t}\n\tif (caCerts === true) {\n\t\tif (attributeCerts === true) {\n\t\t\tthrow new Error(IDP_SCOPE_CONFLICT);\n\t\t}\n\t\treturn { onlyContainsCACerts: true, ...unselectedScopeFlags({ userCerts, attributeCerts }) };\n\t}\n\tif (attributeCerts === true) {\n\t\treturn { onlyContainsAttributeCerts: true, ...unselectedScopeFlags({ userCerts, caCerts }) };\n\t}\n\treturn unselectedScopeFlags({ userCerts, caCerts, attributeCerts });\n}\n\n/** Keeps the explicit-FALSE flags the encoding carried, omitting the ones it left out. */\nfunction unselectedScopeFlags(flags: {\n\treadonly userCerts?: false;\n\treadonly caCerts?: false;\n\treadonly attributeCerts?: false;\n}): {\n\treadonly onlyContainsUserCerts?: false;\n\treadonly onlyContainsCACerts?: false;\n\treadonly onlyContainsAttributeCerts?: false;\n} {\n\treturn {\n\t\t...(flags.userCerts === undefined ? {} : { onlyContainsUserCerts: flags.userCerts }),\n\t\t...(flags.caCerts === undefined ? {} : { onlyContainsCACerts: flags.caCerts }),\n\t\t...(flags.attributeCerts === undefined\n\t\t\t? {}\n\t\t\t: { onlyContainsAttributeCerts: flags.attributeCerts }),\n\t};\n}\n\nconst IDP_SCOPE_CONFLICT = 'IssuingDistributionPoint scope booleans are mutually exclusive';\n\nfunction parseIssuingDistributionPointField(\n\tvalueDer: Uint8Array,\n\tchild: DerElement,\n\tfields: MutableIssuingDistributionPointFields,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0xa0: {\n\t\t\tif (fields.distributionPoint !== undefined) {\n\t\t\t\tthrow new Error('IssuingDistributionPoint distributionPoint must not repeat');\n\t\t\t}\n\t\t\tconst distributionPoint = parseDistributionPointName(valueDer, child);\n\t\t\tif (distributionPoint !== undefined) {\n\t\t\t\tfields.distributionPoint = distributionPoint;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tcase 0x81:\n\t\t\tfields.onlyContainsUserCerts = parseUniqueIssuingDistributionPointBoolean(\n\t\t\t\tfields.onlyContainsUserCerts,\n\t\t\t\tchild,\n\t\t\t\t'onlyContainsUserCerts',\n\t\t\t);\n\t\t\treturn;\n\t\tcase 0x82:\n\t\t\tfields.onlyContainsCACerts = parseUniqueIssuingDistributionPointBoolean(\n\t\t\t\tfields.onlyContainsCACerts,\n\t\t\t\tchild,\n\t\t\t\t'onlyContainsCACerts',\n\t\t\t);\n\t\t\treturn;\n\t\tcase 0x83:\n\t\t\tif (fields.onlySomeReasons !== undefined) {\n\t\t\t\tthrow new Error('IssuingDistributionPoint onlySomeReasons must not repeat');\n\t\t\t}\n\t\t\tfields.onlySomeReasons = parseDistributionPointReasonFlagsContent(child.value);\n\t\t\treturn;\n\t\tcase 0x84:\n\t\t\tfields.indirectCrl = parseUniqueIssuingDistributionPointBoolean(\n\t\t\t\tfields.indirectCrl,\n\t\t\t\tchild,\n\t\t\t\t'indirectCrl',\n\t\t\t);\n\t\t\treturn;\n\t\tcase 0x85:\n\t\t\tfields.onlyContainsAttributeCerts = parseUniqueIssuingDistributionPointBoolean(\n\t\t\t\tfields.onlyContainsAttributeCerts,\n\t\t\t\tchild,\n\t\t\t\t'onlyContainsAttributeCerts',\n\t\t\t);\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported IssuingDistributionPoint field tag: ${String(child.tag)}`);\n\t}\n}\n\nfunction parseUniqueIssuingDistributionPointBoolean(\n\texisting: boolean | undefined,\n\tchild: DerElement,\n\tfieldName: string,\n): boolean {\n\tif (existing !== undefined) {\n\t\tthrow new Error(`IssuingDistributionPoint ${fieldName} must not repeat`);\n\t}\n\treturn decodeBoolean(child.value);\n}\n\n/** Decodes a SEQUENCE OF DistributionPoint from DER. */\nfunction parseDistributionPoints(valueDer: Uint8Array): readonly ParsedDistributionPoint[] {\n\tconst sequenceElement = readRootElement(valueDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (sequenceElement.tag !== 0x30) {\n\t\tthrow new Error('DistributionPoints must use SEQUENCE');\n\t}\n\tconst elements = childrenOf(valueDer, sequenceElement);\n\tif (elements.length === 0) {\n\t\tthrow new Error('DistributionPoints must not be empty');\n\t}\n\treturn elements.map((distributionPoint) => parseDistributionPoint(valueDer, distributionPoint));\n}\n\n/** Decodes a DistributionPointName (fullName or relativeName). */\nfunction parseDistributionPointName(\n\tvalueDer: Uint8Array,\n\telement: DerElement,\n): ParsedDistributionPointName | undefined {\n\tconst children = childrenOf(valueDer, element);\n\tif (children.length !== 1) {\n\t\tthrow new Error('distributionPointName must contain exactly one choice');\n\t}\n\tconst distributionPointName = requireElement(children[0], 'distributionPointName');\n\tif (distributionPointName.tag === 0xa0) {\n\t\tconst fullName = childrenOf(valueDer, distributionPointName);\n\t\tif (fullName.length === 0) {\n\t\t\tthrow new Error('distributionPointName fullName must not be empty');\n\t\t}\n\t\tfor (const name of fullName) {\n\t\t\tif ((name.tag & 0xc0) !== 0x80) {\n\t\t\t\tthrow new Error('distributionPointName fullName must contain GeneralName entries');\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\ttype: 'fullName',\n\t\t\tfullName: fullName.map((name) => parseGeneralName(valueDer, name)),\n\t\t};\n\t}\n\tif (distributionPointName.tag === 0xa1) {\n\t\treturn {\n\t\t\ttype: 'relativeName',\n\t\t\trelativeName: parseRelativeName(valueDer, distributionPointName),\n\t\t};\n\t}\n\tthrow new Error(`Unsupported distributionPointName tag: ${String(distributionPointName.tag)}`);\n}\n\n/** Decodes a single DistributionPoint SEQUENCE. */\nfunction parseDistributionPoint(\n\tvalueDer: Uint8Array,\n\telement: DerElement,\n): ParsedDistributionPoint {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('DistributionPoint must use SEQUENCE');\n\t}\n\tconst fields: MutableDistributionPointFields = {};\n\tfor (const child of childrenOf(valueDer, element)) {\n\t\tparseDistributionPointField(valueDer, child, fields);\n\t}\n\tif (fields.distributionPoint === undefined && fields.crlIssuer === undefined) {\n\t\tthrow new Error('DistributionPoint must include distributionPoint or crlIssuer');\n\t}\n\treturn {\n\t\t...(fields.distributionPoint === undefined\n\t\t\t? {}\n\t\t\t: { distributionPoint: fields.distributionPoint }),\n\t\t...(fields.reasons === undefined ? {} : { reasons: fields.reasons }),\n\t\t...(fields.crlIssuer === undefined ? {} : { crlIssuer: fields.crlIssuer }),\n\t};\n}\n\nfunction parseDistributionPointField(\n\tvalueDer: Uint8Array,\n\tchild: DerElement,\n\tfields: MutableDistributionPointFields,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0xa0: {\n\t\t\tif (fields.distributionPoint !== undefined) {\n\t\t\t\tthrow new Error('DistributionPoint distributionPoint must not repeat');\n\t\t\t}\n\t\t\tconst distributionPoint = parseDistributionPointName(valueDer, child);\n\t\t\tif (distributionPoint !== undefined) fields.distributionPoint = distributionPoint;\n\t\t\treturn;\n\t\t}\n\t\tcase 0x81:\n\t\t\tif (fields.reasons !== undefined)\n\t\t\t\tthrow new Error('DistributionPoint reasons must not repeat');\n\t\t\tfields.reasons = parseDistributionPointReasonFlagsContent(child.value);\n\t\t\treturn;\n\t\tcase 0xa2:\n\t\t\tif (fields.crlIssuer !== undefined)\n\t\t\t\tthrow new Error('DistributionPoint crlIssuer must not repeat');\n\t\t\tfields.crlIssuer = parseGeneralNames(valueDer, child);\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported DistributionPoint field tag: ${String(child.tag)}`);\n\t}\n}\n\n/** Decodes a RelativeDistinguishedName SET from an implicitly-tagged context element. */\nfunction parseRelativeName(\n\tvalueDer: Uint8Array,\n\telement: DerElement,\n): ParsedRelativeDistinguishedName {\n\tconst attributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const attributeSequence of childrenOf(valueDer, element)) {\n\t\tconst parts = childrenOf(valueDer, attributeSequence);\n\t\tconst oid = decodeObjectIdentifier(requireElement(parts[0], 'name OID').value);\n\t\tconst valueElement = requireElement(parts[1], 'name value');\n\t\tconst fieldKey = nameFieldKeyFromOid(oid);\n\t\tconst fieldValue = decodeNameValue(valueElement);\n\t\tconst attribute: ParsedNameAttribute =\n\t\t\tfieldKey === undefined\n\t\t\t\t? { oid, valueTag: valueElement.tag, value: fieldValue }\n\t\t\t\t: { oid, key: fieldKey, valueTag: valueElement.tag, value: fieldValue };\n\t\tattributes.push(attribute);\n\t\tif (fieldKey !== undefined && values[fieldKey] === undefined) {\n\t\t\tvalues[fieldKey] = fieldValue;\n\t\t}\n\t}\n\treturn {\n\t\tderHex: toHex(valueDer.slice(element.start - element.headerLength, element.end)),\n\t\tattributes,\n\t\tvalues,\n\t};\n}\n\n/** Decodes an ASN.1 string element (UTF8String, PrintableString, etc.) to a JS string. */\nfunction decodeNameValue(element: DerElement): string {\n\treturn decodeString(element.tag, element.value);\n}\n\n/** Machine-readable reason a CRL encoder rejected its construction input. */\nexport type CrlEncoderErrorCode =\n\t| 'crl_number_invalid'\n\t| 'distribution_point_full_name_empty'\n\t| 'issuer_certificate_invalid'\n\t| 'issuer_distinguished_name_empty'\n\t| 'invalid_date'\n\t| 'next_update_not_after_this_update';\n\n/** Throws a {@link ResultError} for a CRL encoder input-validation failure. */\nfunction throwCrlEncoderError(code: CrlEncoderErrorCode, message: string): never {\n\tthrowMicro509Error(code, message);\n}\n\n/** The parsed issuer certificate of a CRL being built. */\nfunction issuerCertificateOf(source: CrlCertificateSource): ParsedCertificate {\n\ttry {\n\t\treturn normalizeCrlCertificate(source);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\treturn throwCrlEncoderError(\n\t\t\t'issuer_certificate_invalid',\n\t\t\t'issuerCertificate must be a PEM, DER or parsed certificate',\n\t\t);\n\t}\n}\n\n/** RFC 5280 §5.2.3: \"Conforming CRL issuers MUST NOT use CRLNumber values longer than 20 octets.\" */\nconst CRL_NUMBER_MAX_OCTETS = 20;\n\n/** RFC 5280 §5.2.3 `CRLNumber ::= INTEGER (0..MAX)` as a DER INTEGER of at most 20 content octets. */\nfunction encodeCrlNumber(value: number | bigint, field: 'crlNumber' | 'baseCrlNumber'): Uint8Array {\n\tconst crlNumber =\n\t\ttypeof value === 'bigint' ? value : Number.isSafeInteger(value) ? BigInt(value) : -1n;\n\tconst hex = crlNumber.toString(16);\n\tconst magnitude = crlNumber < 0n ? undefined : hexToBytes(hex.length % 2 === 0 ? hex : `0${hex}`);\n\tconst first = magnitude?.[0];\n\tif (\n\t\tmagnitude === undefined ||\n\t\tfirst === undefined ||\n\t\tmagnitude.length + (first >= 0x80 ? 1 : 0) > CRL_NUMBER_MAX_OCTETS\n\t) {\n\t\tthrowCrlEncoderError(\n\t\t\t'crl_number_invalid',\n\t\t\t`${field} must be a non-negative integer of at most ${String(CRL_NUMBER_MAX_OCTETS)} octets (RFC 5280 §5.2.3)`,\n\t\t);\n\t}\n\treturn integer(magnitude);\n}\n\n/** RFC 5280 §5.2.3: a received CRLNumber of any length, since verifiers MUST handle up to 20 octets. */\nfunction decodeCrlNumber(value: Uint8Array): bigint {\n\tconst element = readRootElement(value, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (element.tag !== 0x02) {\n\t\tthrow new Error('CRLNumber must be an INTEGER');\n\t}\n\tdecodeIntegerMagnitude(element.value, 'CRLNumber');\n\treturn BigInt(`0x${toHex(element.value)}`);\n}\n\nfunction assertCrlDate(date: Date | undefined, field: string): void {\n\tif (date !== undefined && Number.isNaN(date.getTime())) {\n\t\tthrowCrlEncoderError('invalid_date', `${field} must be a valid date`);\n\t}\n}\n\n/** DER-encodes an IssuingDistributionPoint extension value. Throws on mutually-exclusive scope flags. */\nfunction encodeIssuingDistributionPoint(value: IssuingDistributionPoint): Uint8Array {\n\tconst certificateScopeFlags = [\n\t\tvalue.onlyContainsUserCerts === true,\n\t\tvalue.onlyContainsCACerts === true,\n\t\tvalue.onlyContainsAttributeCerts === true,\n\t].filter(Boolean).length;\n\tif (certificateScopeFlags > 1) {\n\t\tthrow new Error(\n\t\t\t'IssuingDistributionPoint can assert at most one of user, CA, or attribute cert scope',\n\t\t);\n\t}\n\tconst fields: Uint8Array[] = [];\n\tif (value.distributionPoint !== undefined) {\n\t\tfields.push(\n\t\t\timplicitConstructedContext(0, encodeDistributionPointName(value.distributionPoint)),\n\t\t);\n\t}\n\tif (value.onlyContainsUserCerts) {\n\t\tfields.push(implicitPrimitiveContext(1, Uint8Array.of(0xff)));\n\t}\n\tif (value.onlyContainsCACerts) {\n\t\tfields.push(implicitPrimitiveContext(2, Uint8Array.of(0xff)));\n\t}\n\tif (value.onlySomeReasons !== undefined && value.onlySomeReasons.length > 0) {\n\t\tfields.push(\n\t\t\timplicitPrimitiveContext(3, encodeDistributionPointReasonFlagsContent(value.onlySomeReasons)),\n\t\t);\n\t}\n\tif (value.indirectCrl) {\n\t\tfields.push(implicitPrimitiveContext(4, Uint8Array.of(0xff)));\n\t}\n\tif (value.onlyContainsAttributeCerts) {\n\t\tfields.push(implicitPrimitiveContext(5, Uint8Array.of(0xff)));\n\t}\n\treturn sequence(fields);\n}\n\n/** DER-encodes a DistributionPointName (fullName or relativeName). */\nfunction encodeDistributionPointName(\n\tvalue: IssuingDistributionPoint['distributionPoint'],\n): Uint8Array {\n\tif (value === undefined) {\n\t\tthrow new Error('IssuingDistributionPoint distributionPoint is required');\n\t}\n\tswitch (value.type) {\n\t\tcase 'fullName': {\n\t\t\tif (value.fullName.length === 0) {\n\t\t\t\tthrowCrlEncoderError(\n\t\t\t\t\t'distribution_point_full_name_empty',\n\t\t\t\t\t'DistributionPointName fullName must not be empty',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn implicitConstructedContext(0, concatGeneralNames(value.fullName));\n\t\t}\n\t\tcase 'relativeName': {\n\t\t\tconst relativeName = encodeRelativeDistinguishedName(value.relativeName);\n\t\t\tconst relativeNameElement = readElement(relativeName);\n\t\t\treturn implicitConstructedContext(\n\t\t\t\t1,\n\t\t\t\trelativeName.slice(relativeNameElement.start, relativeNameElement.end),\n\t\t\t);\n\t\t}\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = value;\n\t\t\tthrow new Error(`Unhandled DistributionPointName type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** DER-encodes and concatenates a list of GeneralName values. */\nfunction concatGeneralNames(names: readonly GeneralName[]): Uint8Array {\n\treturn concatBytes(names.map((name) => encodeSubjectAltName(name)));\n}\n\n/** Parses a Name SEQUENCE element into a full {@linkcode ParsedName}. */\nfunction parseIssuer(source: Uint8Array, element: DerElement): ParsedName {\n\tconst derHex = toHex(source.slice(element.start - element.headerLength, element.end));\n\tconst rdns: ParsedRelativeDistinguishedName[] = [];\n\tconst allAttributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const setElement of childrenOf(source, element)) {\n\t\tconst rdnAttributes: ParsedNameAttribute[] = [];\n\t\tconst rdnValues: Partial<Record<NameFieldKey, string>> = {};\n\t\tfor (const attrSequence of childrenOf(source, setElement)) {\n\t\t\tconst parts = childrenOf(source, attrSequence);\n\t\t\tconst oidElement = requireElement(parts[0], 'issuer attribute OID');\n\t\t\tconst valueElement = requireElement(parts[1], 'issuer attribute value');\n\t\t\tconst oid = decodeObjectIdentifier(oidElement.value);\n\t\t\tconst fieldValue = decodeNameValue(valueElement);\n\t\t\tconst fieldKey = nameFieldKeyFromOid(oid);\n\t\t\tconst attribute: ParsedNameAttribute =\n\t\t\t\tfieldKey !== undefined\n\t\t\t\t\t? { oid, key: fieldKey, valueTag: valueElement.tag, value: fieldValue }\n\t\t\t\t\t: { oid, valueTag: valueElement.tag, value: fieldValue };\n\t\t\trdnAttributes.push(attribute);\n\t\t\tallAttributes.push(attribute);\n\t\t\tif (fieldKey !== undefined) {\n\t\t\t\tif (rdnValues[fieldKey] === undefined) {\n\t\t\t\t\trdnValues[fieldKey] = fieldValue;\n\t\t\t\t}\n\t\t\t\tif (values[fieldKey] === undefined) {\n\t\t\t\t\tvalues[fieldKey] = fieldValue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trdns.push({\n\t\t\tderHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),\n\t\t\tattributes: rdnAttributes,\n\t\t\tvalues: rdnValues,\n\t\t});\n\t}\n\treturn { derHex, rdns, attributes: allAttributes, values };\n}\n\n/**\n * Re-parses a hex-encoded DER Name into a {@linkcode ParsedName}. Returns\n * `undefined` on malformed input and throws a decode refusal.\n */\nfunction parseDerHexName(hex: string): ParsedName | undefined {\n\ttry {\n\t\tconst bytes = hexToBytes(hex);\n\t\tconst root = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tconst element = unwrapNameElement(bytes, root);\n\t\tif (element.tag !== 0x30) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn parseIssuer(bytes, element);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\treturn undefined;\n\t}\n}\n\n/** The failure for a decode refusal a directoryName comparison threw. */\nfunction crlNameRefusalFailure(error: unknown): CrlApplicabilityFailure {\n\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\tif (refusal === undefined) {\n\t\tthrow error;\n\t}\n\treturn checkCertificateRevocationAgainstCrlFailureResult(refusal.code, refusal.message);\n}\n\nfunction unwrapNameElement(source: Uint8Array, element: DerElement): DerElement {\n\tif (element.tag !== 0x30) {\n\t\treturn element;\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length === 1 && child?.tag === 0x30) {\n\t\treturn child;\n\t}\n\treturn element;\n}\n\n/** Semantic comparison of a GeneralName directoryName `derHex` against a {@linkcode ParsedName}. */\nfunction directoryNameDerHexMatchesParsedName(derHex: string, name: ParsedName): boolean {\n\tconst parsed = parseDerHexName(derHex);\n\tif (parsed === undefined) {\n\t\treturn false;\n\t}\n\treturn compareDistinguishedNames(parsed, name);\n}\n\n/** Extracts the keyIdentifier field from an AuthorityKeyIdentifier extension value. */\nfunction parseAuthorityKeyIdentifier(bytes: Uint8Array): string | undefined {\n\tconst sequenceElement = readRootElement(bytes, {\n\t\tmaxDepth: DEFAULT_MAX_DER_DEPTH,\n\t\tallowOpaqueConstructedTags: [0xa1, 0xa2],\n\t});\n\tif (sequenceElement.tag !== 0x30) {\n\t\tthrow new Error('authorityKeyIdentifier must use SEQUENCE');\n\t}\n\tconst state: MutableAuthorityKeyIdentifierState = {\n\t\tsawAuthorityCertIssuer: false,\n\t\tsawAuthorityCertSerialNumber: false,\n\t\tlastFieldOrder: -1,\n\t};\n\tfor (const child of childrenOf(bytes, sequenceElement)) {\n\t\tparseAuthorityKeyIdentifierField(bytes, child, state);\n\t}\n\treturn state.keyIdentifier;\n}\n\nfunction parseAuthorityKeyIdentifierField(\n\tbytes: Uint8Array,\n\tchild: DerElement,\n\tstate: MutableAuthorityKeyIdentifierState,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0x80:\n\t\t\tparseAuthorityKeyIdentifierKeyId(child, state);\n\t\t\treturn;\n\t\tcase 0xa1:\n\t\t\tparseAuthorityKeyIdentifierIssuer(bytes, child, state);\n\t\t\treturn;\n\t\tcase 0x82:\n\t\t\tparseAuthorityKeyIdentifierSerial(child, state);\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported authorityKeyIdentifier field tag: ${String(child.tag)}`);\n\t}\n}\n\nfunction parseAuthorityKeyIdentifierKeyId(\n\tchild: DerElement,\n\tstate: MutableAuthorityKeyIdentifierState,\n): void {\n\tif (state.keyIdentifier !== undefined)\n\t\tthrow new Error('authorityKeyIdentifier keyIdentifier must not repeat');\n\tif (state.lastFieldOrder >= 0)\n\t\tthrow new Error('authorityKeyIdentifier fields must preserve DER order');\n\tstate.keyIdentifier = toHex(child.value);\n\tstate.lastFieldOrder = 0;\n}\n\nfunction parseAuthorityKeyIdentifierIssuer(\n\tbytes: Uint8Array,\n\tchild: DerElement,\n\tstate: MutableAuthorityKeyIdentifierState,\n): void {\n\tif (state.sawAuthorityCertIssuer) {\n\t\tthrow new Error('authorityKeyIdentifier authorityCertIssuer must not repeat');\n\t}\n\tif (state.lastFieldOrder >= 1)\n\t\tthrow new Error('authorityKeyIdentifier fields must preserve DER order');\n\tparseGeneralNames(bytes, child);\n\tstate.sawAuthorityCertIssuer = true;\n\tstate.lastFieldOrder = 1;\n}\n\nfunction parseAuthorityKeyIdentifierSerial(\n\tchild: DerElement,\n\tstate: MutableAuthorityKeyIdentifierState,\n): void {\n\tif (state.sawAuthorityCertSerialNumber) {\n\t\tthrow new Error('authorityKeyIdentifier authorityCertSerialNumber must not repeat');\n\t}\n\tif (state.lastFieldOrder >= 2 || !state.sawAuthorityCertIssuer) {\n\t\tthrow new Error('authorityKeyIdentifier fields must preserve DER order');\n\t}\n\tvalidateImplicitSerialNumberEncoding(\n\t\tchild.value,\n\t\t'authorityKeyIdentifier authorityCertSerialNumber',\n\t);\n\tstate.sawAuthorityCertSerialNumber = true;\n\tstate.lastFieldOrder = 2;\n}\n\nfunction validateImplicitSerialNumberEncoding(bytes: Uint8Array, label: string): void {\n\tconst first = bytes[0];\n\tif (first === undefined) {\n\t\tthrow new Error(`${label} must not be empty`);\n\t}\n\tif ((first & 0x80) !== 0) {\n\t\tthrow new Error(`${label} must be non-negative`);\n\t}\n\tif (bytes.length > 1 && first === 0 && ((bytes[1] ?? 0) & 0x80) === 0) {\n\t\tthrow new Error(`${label} must use minimal encoding`);\n\t}\n}\n\n/** An AlgorithmIdentifier decoded to its OID and the DER of its parameters. */\ninterface ParsedCrlAlgorithmIdentifier {\n\treadonly oid: string;\n\treadonly parametersDer?: Uint8Array;\n}\n\n/** RFC 5280 §5.1.1.2: signatureAlgorithm MUST equal the tbsCertList signature field. */\nfunction assertMatchingCrlSignatureAlgorithms(\n\tsignature: ParsedCrlAlgorithmIdentifier,\n\tsignatureAlgorithm: ParsedCrlAlgorithmIdentifier,\n): void {\n\tif (\n\t\tsignature.oid !== signatureAlgorithm.oid ||\n\t\t!optionalBytesEqual(signature.parametersDer, signatureAlgorithm.parametersDer)\n\t) {\n\t\tthrow new Error('CRL signatureAlgorithm must match TBSCertList signature');\n\t}\n}\n\n/** Extracts the algorithm OID from an AlgorithmIdentifier SEQUENCE. */\nfunction parseAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: DerElement,\n): ParsedCrlAlgorithmIdentifier {\n\tconst children = childrenOf(source, element);\n\tconst oid = requireElement(children[0], 'algorithm OID');\n\tconst parameters = children[1];\n\treturn parameters === undefined\n\t\t? { oid: decodeObjectIdentifier(oid.value) }\n\t\t: {\n\t\t\t\toid: decodeObjectIdentifier(oid.value),\n\t\t\t\tparametersDer: source.slice(parameters.start - parameters.headerLength, parameters.end),\n\t\t\t};\n}\n\n/** Lowercases a hex string for bytewise serial-number comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n/**\n * Maps an integer CRLReason code to its {@linkcode RevocationReason} name, or to\n * an {@linkcode UnrecognizedRevocationReason} carrying a code outside RFC 5280\n * §5.3.1. Returns `undefined` only when `code` is `undefined`.\n */\nexport function revocationReasonFromCode(\n\tcode: bigint | undefined,\n): ParsedRevocationReason | undefined {\n\treturn code === undefined ? undefined : parsedRevocationReason(code);\n}\n\nfunction parsedRevocationReason(code: bigint): ParsedRevocationReason {\n\tswitch (code) {\n\t\tcase 0n:\n\t\t\treturn 'unspecified';\n\t\tcase 1n:\n\t\t\treturn 'keyCompromise';\n\t\tcase 2n:\n\t\t\treturn 'cACompromise';\n\t\tcase 3n:\n\t\t\treturn 'affiliationChanged';\n\t\tcase 4n:\n\t\t\treturn 'superseded';\n\t\tcase 5n:\n\t\t\treturn 'cessationOfOperation';\n\t\tcase 6n:\n\t\t\treturn 'certificateHold';\n\t\tcase 8n:\n\t\t\treturn 'removeFromCRL';\n\t\tcase 9n:\n\t\t\treturn 'privilegeWithdrawn';\n\t\tcase 10n:\n\t\t\treturn 'aACompromise';\n\t\tdefault:\n\t\t\treturn { type: 'unrecognized', code };\n\t}\n}\n\n/** Thin wrapper — parses a DER-encoded certificate for use as a CRL issuer. */\nfunction parseIssuerCertificateDer(der: Uint8Array): ParsedCertificate {\n\treturn parseCertificateFromSource(der);\n}\n\n/** Thin wrapper — parses a PEM-encoded certificate for use as a CRL issuer. */\nfunction parseIssuerCertificatePem(pem: string): ParsedCertificate {\n\treturn parseCertificateFromSource(pem);\n}\n\n/**\n * Parses PEM, DER, or an already-parsed CRL's `der`, so every decoded field\n * comes from the signed bytes.\n *\n * @internal\n */\nexport function normalizeCrl(source: CrlSource): ParsedCertificateRevocationList {\n\tif (typeof source === 'string') {\n\t\treturn parseCertificateRevocationListPemOrThrow(source);\n\t}\n\tif (source instanceof Uint8Array) {\n\t\treturn parseCertificateRevocationListDerOrThrow(new Uint8Array(source));\n\t}\n\tif (hasReparseableCrlShape(source)) {\n\t\treturn parseCertificateRevocationListDerOrThrow(new Uint8Array(source.der));\n\t}\n\tthrow new Error('certificate revocation list input is malformed');\n}\n\nfunction parseSignedCrlFields(tbsCertListDer: Uint8Array): {\n\treadonly version: number;\n\treadonly signature: ParsedCrlAlgorithmIdentifier;\n\treadonly issuer: ParsedName;\n\treadonly thisUpdate: Date;\n\treadonly nextUpdate?: Date;\n\treadonly authorityKeyIdentifier?: string;\n\treadonly crlNumber?: bigint;\n\treadonly baseCrlNumber?: bigint;\n\treadonly issuingDistributionPoint?: ParsedIssuingDistributionPoint;\n\treadonly freshestCrlDistributionPoints?: readonly ParsedDistributionPoint[];\n\treadonly revokedCertificates: readonly ParsedRevokedCertificate[];\n} {\n\tconst tbsCertList = readRootElement(tbsCertListDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tconst tbsChildren = childrenOf(tbsCertListDer, tbsCertList);\n\tconst versionField = parseCrlVersionField(tbsChildren);\n\tconst version = versionField.version;\n\tconst signatureElement = requireElement(tbsChildren[versionField.nextIndex], 'signature');\n\tconst index = versionField.nextIndex + 1;\n\tconst issuerElement = requireElement(tbsChildren[index], 'issuer');\n\tconst thisUpdateElement = requireElement(tbsChildren[index + 1], 'thisUpdate');\n\tlet cursor = index + 2;\n\tconst maybeNextUpdate = tbsChildren[cursor];\n\tconst nextUpdate =\n\t\tmaybeNextUpdate !== undefined && (maybeNextUpdate.tag === 0x17 || maybeNextUpdate.tag === 0x18)\n\t\t\t? parseTime(maybeNextUpdate)\n\t\t\t: undefined;\n\tif (nextUpdate !== undefined) {\n\t\tcursor += 1;\n\t}\n\tconst maybeRevoked = tbsChildren[cursor];\n\tconst revokedCertificates =\n\t\tmaybeRevoked?.tag === 0x30\n\t\t\t? parseRevokedCertificates(tbsCertListDer, maybeRevoked, version)\n\t\t\t: [];\n\tif (maybeRevoked?.tag === 0x30) {\n\t\tcursor += 1;\n\t}\n\tconst maybeExtensions = tbsChildren[cursor];\n\tconst parsedExtensions = parseCrlExtensionFields(tbsCertListDer, maybeExtensions, version);\n\treturn {\n\t\tversion,\n\t\tsignature: parseAlgorithmIdentifier(tbsCertListDer, signatureElement),\n\t\tissuer: parseIssuer(tbsCertListDer, issuerElement),\n\t\tthisUpdate: parseTime(thisUpdateElement),\n\t\t...(nextUpdate === undefined ? {} : { nextUpdate }),\n\t\t...(parsedExtensions.authorityKeyIdentifier === undefined\n\t\t\t? {}\n\t\t\t: { authorityKeyIdentifier: parsedExtensions.authorityKeyIdentifier }),\n\t\t...(parsedExtensions.crlNumber === undefined ? {} : { crlNumber: parsedExtensions.crlNumber }),\n\t\t...(parsedExtensions.baseCrlNumber === undefined\n\t\t\t? {}\n\t\t\t: { baseCrlNumber: parsedExtensions.baseCrlNumber }),\n\t\t...(parsedExtensions.issuingDistributionPoint === undefined\n\t\t\t? {}\n\t\t\t: { issuingDistributionPoint: parsedExtensions.issuingDistributionPoint }),\n\t\t...(parsedExtensions.freshestCrlDistributionPoints === undefined\n\t\t\t? {}\n\t\t\t: { freshestCrlDistributionPoints: parsedExtensions.freshestCrlDistributionPoints }),\n\t\trevokedCertificates,\n\t};\n}\n\nfunction parseCrlVersionField(tbsChildren: readonly DerElement[]): ParsedCrlVersionField {\n\tconst firstChild = tbsChildren[0];\n\tif (firstChild !== undefined && firstChild.tag !== 0x02 && firstChild.tag !== 0x30) {\n\t\tthrow new Error('version must use INTEGER');\n\t}\n\tif (firstChild?.tag !== 0x02) {\n\t\treturn { version: 1, nextIndex: 0 };\n\t}\n\tconst version = decodeIntegerNumber(firstChild.value) + 1;\n\tif (version !== 2) {\n\t\tthrow new Error(`Unsupported CRL version: ${String(version)}`);\n\t}\n\treturn { version, nextIndex: 1 };\n}\n\nfunction parseRevokedCertificates(\n\ttbsCertListDer: Uint8Array,\n\trevokedSequence: DerElement,\n\tversion: number,\n): readonly ParsedRevokedCertificate[] {\n\treturn childrenOf(tbsCertListDer, revokedSequence).map((entry) =>\n\t\tparseRevokedCertificateEntry(tbsCertListDer, entry, version),\n\t);\n}\n\nfunction parseRevokedCertificateEntry(\n\ttbsCertListDer: Uint8Array,\n\tentry: DerElement,\n\tversion: number,\n): ParsedRevokedCertificate {\n\tconst entryDer = tbsCertListDer.slice(entry.start - entry.headerLength, entry.end);\n\tconst parts = readSequenceChildren(entryDer);\n\tconst serialNumber = requireElement(parts[0], 'revoked serialNumber');\n\tif (serialNumber.tag !== 0x02) {\n\t\tthrow new Error('revoked serialNumber must use INTEGER');\n\t}\n\tconst entryExtensions = parts[2];\n\tif (entryExtensions !== undefined && version !== 2) {\n\t\tthrow new Error('revoked certificate extensions require CRL version 2');\n\t}\n\tconst parsedEntryExtensions = parseRevokedCertificateExtensions(entryDer, entryExtensions);\n\treturn {\n\t\tserialNumberHex: toHex(serialNumber.value),\n\t\trevocationDate: parseTime(requireElement(parts[1], 'revocationDate')),\n\t\t...(parsedEntryExtensions.reasonCode === undefined\n\t\t\t? {}\n\t\t\t: { reasonCode: parsedEntryExtensions.reasonCode }),\n\t\t...(parsedEntryExtensions.invalidityDate === undefined\n\t\t\t? {}\n\t\t\t: { invalidityDate: parsedEntryExtensions.invalidityDate }),\n\t\t...(parsedEntryExtensions.certificateIssuer === undefined\n\t\t\t? {}\n\t\t\t: { certificateIssuer: parsedEntryExtensions.certificateIssuer }),\n\t};\n}\n\nfunction parseCrlExtensionFields(\n\ttbsCertListDer: Uint8Array,\n\tmaybeExtensions: DerElement | undefined,\n\tversion: number,\n): ParsedCrlExtensionFields {\n\tif (maybeExtensions?.tag !== 0xa0) {\n\t\treturn {};\n\t}\n\tif (version !== 2) {\n\t\tthrow new Error('CRL extensions require version 2');\n\t}\n\tconst fields: MutableParsedCrlExtensionFields = {};\n\tconst seenOids = new Set<string>();\n\tconst extensionSequence = requireElement(\n\t\tchildrenOf(tbsCertListDer, maybeExtensions)[0],\n\t\t'crl extensions',\n\t);\n\tfor (const extension of childrenOf(tbsCertListDer, extensionSequence)) {\n\t\tparseCrlExtensionField(tbsCertListDer, extension, seenOids, fields);\n\t}\n\treturn fields;\n}\n\nfunction parseCrlExtensionField(\n\ttbsCertListDer: Uint8Array,\n\textension: DerElement,\n\tseenOids: Set<string>,\n\tfields: MutableParsedCrlExtensionFields,\n): void {\n\tconst parts = childrenOf(tbsCertListDer, extension);\n\tif (parts.length < 2 || parts.length > 3) {\n\t\tthrow new Error('Malformed CRL extension');\n\t}\n\tif (parts.length === 3 && parts[1]?.tag !== 0x01) {\n\t\tthrow new Error('Malformed CRL extension');\n\t}\n\tconst oid = decodeObjectIdentifier(requireElement(parts[0], 'extension OID').value);\n\tif (seenOids.has(oid)) {\n\t\tthrow new Error(`Duplicate CRL extension OID: ${oid}`);\n\t}\n\tseenOids.add(oid);\n\tconst critical =\n\t\tparts.length === 3\n\t\t\t? decodeBoolean(requireElement(parts[1], 'extension critical').value)\n\t\t\t: false;\n\tconst valueElement = requireElement(parts[parts.length - 1], 'extension value');\n\tif (valueElement.tag !== 0x04) {\n\t\tthrow new Error('CRL extension value must use OCTET STRING');\n\t}\n\tif (!isSupportedCrlExtensionOid(oid) && critical) {\n\t\tthrow new Error(`Unsupported critical CRL extension OID: ${oid}`);\n\t}\n\tapplyParsedCrlExtensionField(oid, valueElement.value, fields);\n}\n\nfunction isSupportedCrlExtensionOid(oid: string): boolean {\n\treturn (\n\t\toid === OIDS.authorityKeyIdentifier ||\n\t\toid === OIDS.cRLNumber ||\n\t\toid === OIDS.deltaCRLIndicator ||\n\t\toid === OIDS.issuingDistributionPoint ||\n\t\toid === OIDS.freshestCRL\n\t);\n}\n\nfunction applyParsedCrlExtensionField(\n\toid: string,\n\tvalue: Uint8Array,\n\tfields: MutableParsedCrlExtensionFields,\n): void {\n\tif (oid === OIDS.authorityKeyIdentifier) {\n\t\tconst authorityKeyIdentifier = parseAuthorityKeyIdentifier(value);\n\t\tif (authorityKeyIdentifier !== undefined) {\n\t\t\tfields.authorityKeyIdentifier = authorityKeyIdentifier;\n\t\t}\n\t}\n\tif (oid === OIDS.cRLNumber) {\n\t\tfields.crlNumber = decodeCrlNumber(value);\n\t}\n\tif (oid === OIDS.deltaCRLIndicator) {\n\t\tfields.baseCrlNumber = decodeCrlNumber(value);\n\t}\n\tif (oid === OIDS.issuingDistributionPoint) {\n\t\tfields.issuingDistributionPoint = parseIssuingDistributionPoint(value);\n\t}\n\tif (oid === OIDS.freshestCRL) {\n\t\tfields.freshestCrlDistributionPoints = parseDistributionPoints(value);\n\t}\n}\n\n/** Accepts PEM, DER, or already-parsed certificate and returns a parsed certificate. */\nfunction normalizeCrlCertificate(source: CrlCertificateSource): ParsedCertificate {\n\treturn hasParsedCertificateShape(source)\n\t\t? parseCertificateDerOrThrow(new Uint8Array(source.der))\n\t\t: parseCertificateFromSource(source);\n}\n\nfunction hasParsedCertificateShape(value: CrlCertificateSource): value is ParsedCertificate {\n\treturn typeof value !== 'string' && 'subjectPublicKeyInfoDer' in value;\n}\n\nfunction hasReparseableCrlShape(\n\tcrl: ParsedCertificateRevocationList,\n): crl is ParsedCertificateRevocationList & { readonly der: Uint8Array } {\n\treturn 'der' in crl && crl.der instanceof Uint8Array;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqSA,MAAMgE,KAA4D;CACjE,aAAa;CACb,eAAe;CACf,cAAc;CACd,oBAAoB;CACpB,YAAY;CACZ,sBAAsB;CACtB,iBAAiB;CACjB,eAAe;CACf,oBAAoB;CACpB,cAAc;AACf,GAmSaC,IAAqE,OAAO,OAAO;CAC/F;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;AAGV,SAAgB,kCAAkCC,GAAoC;CACrF,IAAMC,IAAMD,aAAmB,MAAMA,IAAU,IAAI,IAAIA,CAAO;CAC9D,OAAOD,EAA+B,OAAOG,MAAWD,EAAI,IAAIC,CAAM,CAAC;AACxE;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,eAAsB,gCACrBC,GAC6C;CACzCR,EAAiBQ,EAAM,MAAM,KAChC,qBACC,mCACA,+CACD;CAED,IAAMC,IAAoB,oBAAoBD,EAAM,iBAAiB,GAC/DE,IAAY,gBAAgBF,EAAM,WAAW,WAAW,GACxDG,IACLH,EAAM,kBAAkB,KAAA,IACrB,KAAA,IACA,gBAAgBA,EAAM,eAAe,eAAe,GAClDI,IAAqBpC,EAAsBgC,EAAM,gBAAgB,GACjEK,IAAaL,EA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