micro509 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -5
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/revocation/chain.d.ts +8 -2
- package/dist/revocation/chain.js +1 -1
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +3 -1
- package/dist/revocation/crl.js +1 -1
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/revocation.d.ts +2 -2
- package/dist/revocation.d.ts +2 -2
- package/dist/verify/verify.d.ts +8 -5
- package/dist/verify/verify.js +1 -1
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +2 -2
- package/dist/verify.js +1 -1
- package/package.json +12 -47
package/README.md
CHANGED
|
@@ -40,10 +40,10 @@ PKCS#7 SignedData, PFX/PKCS#12, PEM handling, and key
|
|
|
40
40
|
import/export.
|
|
41
41
|
|
|
42
42
|
And when verification fails, you get typed results your code
|
|
43
|
-
can act on: [
|
|
44
|
-
and structured failure details instead of `false`.
|
|
43
|
+
can act on: [a typed error code for every failure mode], the failing
|
|
44
|
+
certificate index, and structured failure details instead of `false`.
|
|
45
45
|
|
|
46
|
-
[
|
|
46
|
+
[a typed error code for every failure mode]: https://micro509.kjanat.dev/guide/verification#error-codes
|
|
47
47
|
|
|
48
48
|
```ts
|
|
49
49
|
if (!result.ok) {
|
|
@@ -117,15 +117,18 @@ console.log(csr.pem);
|
|
|
117
117
|
Parse a certificate:
|
|
118
118
|
|
|
119
119
|
```ts
|
|
120
|
-
import { parseCertificatePem } from 'micro509';
|
|
120
|
+
import { parseCertificatePem, unwrap } from 'micro509';
|
|
121
121
|
|
|
122
122
|
// Using certificate from previous example
|
|
123
|
-
const parsed = parseCertificatePem(certificate.pem);
|
|
123
|
+
const parsed = unwrap(parseCertificatePem(certificate.pem));
|
|
124
124
|
console.log(parsed.subject.values.commonName);
|
|
125
125
|
console.log(parsed.extendedKeyUsage);
|
|
126
126
|
console.log(parsed.authorityInfoAccess);
|
|
127
127
|
```
|
|
128
128
|
|
|
129
|
+
`parseCertificatePem` returns a typed `Result` — check `result.ok`, or
|
|
130
|
+
`unwrap()` to throw on malformed input.
|
|
131
|
+
|
|
129
132
|
Verify a chain:
|
|
130
133
|
|
|
131
134
|
```ts
|
package/dist/index.d.ts
CHANGED
|
@@ -15,7 +15,7 @@ import { CertificateRevocationStatus, CheckChainRevocationInput, CheckChainRevoc
|
|
|
15
15
|
import { DnsServiceIdentityInput, IpServiceIdentityInput, MatchServiceIdentityErrorCode, MatchServiceIdentityFailure, MatchServiceIdentityInput, MatchServiceIdentityResult, MatchServiceIdentitySuccess, ServiceIdentityInput, ServiceIdentityType, SrvServiceIdentityInput, UriServiceIdentityInput, VerifyServiceIdentityInput, matchCertificateServiceIdentity, matchServiceIdentity } from "./verify/identity.js";
|
|
16
16
|
import { InitialNameConstraintsInput } from "./verify/name-constraints.js";
|
|
17
17
|
import { PolicyValidationInput } from "./verify/policy.js";
|
|
18
|
-
import { BuildCandidatePathInput, BuildCandidatePathResult, CandidatePath, CertificateSource, ChainRevocationInput, CsrSource, EkuCheckFailure, EkuCheckPurpose, EkuCheckResult, TrustAnchor, ValidateCandidatePathInput, ValidateCandidatePathResult, ValidateCandidatePathSuccess, ValidateForCaInput, ValidateForCodeSigningInput, ValidateForTlsClientInput, ValidateForTlsServerInput, VerifiedCertificateChain, VerifyCertificateChainInput, VerifyChainFailure, VerifyChainResult, VerifyErrorCode, VerifyFailureDetails, VerifyPurpose, VerifyRequestFailure, VerifyRequestResult, buildCandidatePath, checkExtendedKeyUsage, trustAnchorFromCertificate, validateCandidatePath, validateForCa, validateForCodeSigning, validateForTlsClient, validateForTlsServer, verifyCertificateChain, verifyCertificateSigningRequest } from "./verify/verify.js";
|
|
18
|
+
import { BuildCandidatePathInput, BuildCandidatePathResult, CandidatePath, CertificateSource, ChainRevocationInput, CsrSource, EkuCheckFailure, EkuCheckPurpose, EkuCheckResult, TrustAnchor, VERIFY_ERROR_CODES, ValidateCandidatePathInput, ValidateCandidatePathResult, ValidateCandidatePathSuccess, ValidateForCaInput, ValidateForCodeSigningInput, ValidateForTlsClientInput, ValidateForTlsServerInput, VerifiedCertificateChain, VerifyCertificateChainInput, VerifyChainFailure, VerifyChainResult, VerifyErrorCode, VerifyFailureDetails, VerifyPurpose, VerifyRequestFailure, VerifyRequestResult, buildCandidatePath, checkExtendedKeyUsage, trustAnchorFromCertificate, validateCandidatePath, validateForCa, validateForCodeSigning, validateForTlsClient, validateForTlsServer, verifyCertificateChain, verifyCertificateSigningRequest } from "./verify/verify.js";
|
|
19
19
|
import { CertificateMaterial, CreateCertificateInput, CreateSelfSignedCertificateInput, SelfSignedCertificateResult, ValidityInput, createCertificate, createSelfSignedCertificate } from "./x509/certificate.js";
|
|
20
20
|
import { CreateCsrInput, CsrMaterial, createCertificateSigningRequest } from "./x509/csr.js";
|
|
21
|
-
export { type AuthorityInformationAccess, type BasicConstraints, type BuildCandidatePathInput, type BuildCandidatePathResult, type CandidatePath, type CategorizedPemBlocks, type CertificateExtensionsInput, type CertificateMaterial, type CertificatePolicies, type CertificateRevocationListMaterial, type CertificateRevocationStatus, type CertificateSource, type ChainRevocationInput, type CheckCertificateRevocationAgainstCrlInput, type CheckCertificateRevocationAgainstCrlResult, type CheckCertificateRevocationInput, type CheckCertificateRevocationResult, type CheckChainRevocationInput, type CheckChainRevocationResult, type CheckChainRevocationValue, type ConfiguredOcspResponder, type CreateCertificateInput, type CreateCertificateRevocationListInput, type CreateCsrInput, type CreateOcspRequestInput, type CreateOcspRequestItemInput, type CreateOcspResponseInput, type CreateOcspSingleResponseInput, type CreatePfxErrorCode, type CreatePfxFailure, type CreatePfxInput, type CreatePfxResult, type CreatePkcs7CertBagDerResult, type CreatePkcs7CertBagErrorCode, type CreatePkcs7CertBagFailure, type CreatePkcs7CertBagResult, type CreatePkcs7SignedDataDerResult, type CreatePkcs7SignedDataErrorCode, type CreatePkcs7SignedDataFailure, type CreatePkcs7SignedDataInput, type CreatePkcs7SignedDataResult, type CreateSelfSignedCertificateInput, type CrlCertificateSource, type CrlSource, type CsrMaterial, type CsrSource, type DecodedExtensionMap, type DecodedExtensionValue, type DistributionPoint, type DistributionPointName, type DnsServiceIdentityInput, type EcKeyAlgorithmInput, type EcNamedCurve, type Ed25519KeyAlgorithmInput, type EkuCheckFailure, type EkuCheckPurpose, type EkuCheckResult, type EncryptedPkcs8Options, type ErrorResult, type ExtendedKeyUsage, type ExtensionDecoder, type ExtensionDecoderMap, type GeneralName, type GeneralSubtree, type ImportEcPublicKeyInput, type ImportEd25519PublicKeyInput, type ImportEncryptedKeyErrorCode, type ImportEncryptedKeyFailure, type ImportEncryptedKeyResult, type ImportKeyErrorCode, type ImportKeyFailure, type ImportKeyResult, type ImportRsaPublicKeyInput, type IndexedErrorResult, type IndexedMicro509Error, type InhibitAnyPolicy, type InitialNameConstraintsInput, type IpServiceIdentityInput, type IssuingDistributionPoint, type KeyAlgorithmInput, type KeyPairMaterial, type KeyUsage, type LegacyPemEncryptionOptions, type MatchServiceIdentityErrorCode, type MatchServiceIdentityFailure, type MatchServiceIdentityInput, type MatchServiceIdentityResult, type MatchServiceIdentitySuccess, type Micro509Error, type NameAttribute, type NameConstraintForm, type NameConstraints, type NameFieldKey, type NameInput, type NameObject, type OcspCertStatus, type OcspCertificateSource, type OcspRequestMaterial, type OcspRequestSource, type OcspResponderCandidate, type OcspResponderSource, type OcspResponseMaterial, type ParseCertificateErrorCode, type ParseCertificateFailure, type ParseCertificateResult, type ParseCertificateSigningRequestErrorCode, type ParseCertificateSigningRequestFailure, type ParseCertificateSigningRequestResult, type ParseOptions, type ParsePfxErrorCode, type ParsePfxFailure, type ParsePfxOptions, type ParsePfxResult, type ParsePkcs7CertBagResult, type ParsePkcs7ErrorCode, type ParsePkcs7Failure, type ParsePkcs7SignedDataResult, type ParsedBitFlags, type ParsedCertificate, type ParsedCertificateRevocationList, type ParsedCertificateSigningRequest, type ParsedDistributionPoint, type ParsedDistributionPointName, type ParsedExtension, type ParsedIssuingDistributionPoint, type ParsedName, type ParsedNameAttribute, type ParsedNameConstraintForm, type ParsedOcspCertId, type ParsedOcspRequest, type ParsedOcspResponderId, type ParsedOcspResponse, type ParsedOcspSingleResponse, type ParsedPfx, type ParsedPfxAttribute, type ParsedPfxBag, type ParsedPfxBagAttributes, type ParsedPkcs7SignedData, type ParsedPkcs7SignerInfo, type ParsedRelativeDistinguishedName, type ParsedRevokedCertificate, type Pbes2EncryptionOptions, type Pbes2EncryptionScheme, type Pbes2Prf, type PemBlock, type PfxBagAttributesInput, type PfxCertificateBagInput, type PfxCertificateSource, type PfxEncryptionOptions, type PfxMaterial, type PfxPrivateKeyBagInput, type PfxPrivateKeySource, type Pkcs7CertBag, type Pkcs7CertificateSource, type Pkcs7SignedDataMaterial, type Pkcs7Signer, type PolicyConstraints, type PolicyInformation, type PolicyMapping, type PolicyMappings, type PolicyQualifierInfo, type PolicyValidationInput, type PrivateKeyImportInput, type PublicKeyImportInput, type RelativeDistinguishedNameInput, type ResolveOcspResponderCandidatesInput, type Result, type ResultError, type RevocationCertificateSource, type RevocationCrlEvidenceInput, type RevocationEvidenceInput, type RevocationEvidenceKind, type RevocationExecutionError, type RevocationIndeterminateReason, type RevocationOcspEvidenceInput, type RevocationPolicy, type RevocationReason, type RevocationSource, type RevocationStatus, type RevokedCertificateInput, type RsaHash, type RsaKeyAlgorithmInput, type RsaScheme, type SelfSignedCertificateResult, type ServiceIdentityInput, type ServiceIdentityType, type SrvServiceIdentityInput, type SubjectAltName, type TrustAnchor, type UriServiceIdentityInput, type ValidateCandidatePathInput, type ValidateCandidatePathResult, type ValidateCandidatePathSuccess, type ValidateCertificateRevocationListFailure, type ValidateCertificateRevocationListInput, type ValidateCertificateRevocationListResult, type ValidateForCaInput, type ValidateForCodeSigningInput, type ValidateForTlsClientInput, type ValidateForTlsServerInput, type ValidateOcspResponseFailure, type ValidateOcspResponseInput, type ValidateOcspResponseResult, type ValidityInput, type VerifiedCertificateChain, type VerifyCertificateChainInput, type VerifyCertificateRevocationListFailure, type VerifyCertificateRevocationListResult, type VerifyChainFailure, type VerifyChainResult, type VerifyErrorCode, type VerifyFailureDetails, type VerifyOcspResponseFailure, type VerifyOcspResponseResult, type VerifyPkcs7SignedDataFailure, type VerifyPkcs7SignedDataResult, type VerifyPurpose, type VerifyRequestFailure, type VerifyRequestResult, type VerifyServiceIdentityInput, buildCandidatePath, categorizePemBlocks, checkCertificateRevocation, checkCertificateRevocationAgainstCrl, checkChainRevocation, checkExtendedKeyUsage, createCertificate, createCertificateRevocationList, createCertificateSigningRequest, createOcspRequest, createOcspResponse, createPfx, createPkcs7CertBagDer, createPkcs7CertBagPem, createPkcs7SignedDataDer, createPkcs7SignedDataPem, createSelfSignedCertificate, decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, findExtension, generateKeyPair, getCertificateOcspResponderUris, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem, isCertificateRevoked, isResultError, matchCertificateServiceIdentity, matchServiceIdentity, parseCertificateChainPem, parseCertificateDer, parseCertificatePem, parseCertificateRevocationListDer, parseCertificateRevocationListPem, parseCertificateSigningRequestDer, parseCertificateSigningRequestPem, parseOcspRequestDer, parseOcspRequestPem, parseOcspResponseDer, parseOcspResponsePem, parsePfxDer, parsePfxPem, parsePkcs7CertBagDer, parsePkcs7CertBagPem, parsePkcs7SignedDataDer, parsePkcs7SignedDataPem, pemDecode, pemEncode, resolveOcspResponderCandidates, splitPemBlocks, trustAnchorFromCertificate, unwrap, unwrapOr, validateCandidatePath, validateCertificateRevocationList, validateForCa, validateForCodeSigning, validateForTlsClient, validateForTlsServer, validateOcspResponse, verifyCertificateChain, verifyCertificateRevocationList, verifyCertificateSigningRequest, verifyOcspResponse, verifyPkcs7SignedData };
|
|
21
|
+
export { type AuthorityInformationAccess, type BasicConstraints, type BuildCandidatePathInput, type BuildCandidatePathResult, type CandidatePath, type CategorizedPemBlocks, type CertificateExtensionsInput, type CertificateMaterial, type CertificatePolicies, type CertificateRevocationListMaterial, type CertificateRevocationStatus, type CertificateSource, type ChainRevocationInput, type CheckCertificateRevocationAgainstCrlInput, type CheckCertificateRevocationAgainstCrlResult, type CheckCertificateRevocationInput, type CheckCertificateRevocationResult, type CheckChainRevocationInput, type CheckChainRevocationResult, type CheckChainRevocationValue, type ConfiguredOcspResponder, type CreateCertificateInput, type CreateCertificateRevocationListInput, type CreateCsrInput, type CreateOcspRequestInput, type CreateOcspRequestItemInput, type CreateOcspResponseInput, type CreateOcspSingleResponseInput, type CreatePfxErrorCode, type CreatePfxFailure, type CreatePfxInput, type CreatePfxResult, type CreatePkcs7CertBagDerResult, type CreatePkcs7CertBagErrorCode, type CreatePkcs7CertBagFailure, type CreatePkcs7CertBagResult, type CreatePkcs7SignedDataDerResult, type CreatePkcs7SignedDataErrorCode, type CreatePkcs7SignedDataFailure, type CreatePkcs7SignedDataInput, type CreatePkcs7SignedDataResult, type CreateSelfSignedCertificateInput, type CrlCertificateSource, type CrlSource, type CsrMaterial, type CsrSource, type DecodedExtensionMap, type DecodedExtensionValue, type DistributionPoint, type DistributionPointName, type DnsServiceIdentityInput, type EcKeyAlgorithmInput, type EcNamedCurve, type Ed25519KeyAlgorithmInput, type EkuCheckFailure, type EkuCheckPurpose, type EkuCheckResult, type EncryptedPkcs8Options, type ErrorResult, type ExtendedKeyUsage, type ExtensionDecoder, type ExtensionDecoderMap, type GeneralName, type GeneralSubtree, type ImportEcPublicKeyInput, type ImportEd25519PublicKeyInput, type ImportEncryptedKeyErrorCode, type ImportEncryptedKeyFailure, type ImportEncryptedKeyResult, type ImportKeyErrorCode, type ImportKeyFailure, type ImportKeyResult, type ImportRsaPublicKeyInput, type IndexedErrorResult, type IndexedMicro509Error, type InhibitAnyPolicy, type InitialNameConstraintsInput, type IpServiceIdentityInput, type IssuingDistributionPoint, type KeyAlgorithmInput, type KeyPairMaterial, type KeyUsage, type LegacyPemEncryptionOptions, type MatchServiceIdentityErrorCode, type MatchServiceIdentityFailure, type MatchServiceIdentityInput, type MatchServiceIdentityResult, type MatchServiceIdentitySuccess, type Micro509Error, type NameAttribute, type NameConstraintForm, type NameConstraints, type NameFieldKey, type NameInput, type NameObject, type OcspCertStatus, type OcspCertificateSource, type OcspRequestMaterial, type OcspRequestSource, type OcspResponderCandidate, type OcspResponderSource, type OcspResponseMaterial, type ParseCertificateErrorCode, type ParseCertificateFailure, type ParseCertificateResult, type ParseCertificateSigningRequestErrorCode, type ParseCertificateSigningRequestFailure, type ParseCertificateSigningRequestResult, type ParseOptions, type ParsePfxErrorCode, type ParsePfxFailure, type ParsePfxOptions, type ParsePfxResult, type ParsePkcs7CertBagResult, type ParsePkcs7ErrorCode, type ParsePkcs7Failure, type ParsePkcs7SignedDataResult, type ParsedBitFlags, type ParsedCertificate, type ParsedCertificateRevocationList, type ParsedCertificateSigningRequest, type ParsedDistributionPoint, type ParsedDistributionPointName, type ParsedExtension, type ParsedIssuingDistributionPoint, type ParsedName, type ParsedNameAttribute, type ParsedNameConstraintForm, type ParsedOcspCertId, type ParsedOcspRequest, type ParsedOcspResponderId, type ParsedOcspResponse, type ParsedOcspSingleResponse, type ParsedPfx, type ParsedPfxAttribute, type ParsedPfxBag, type ParsedPfxBagAttributes, type ParsedPkcs7SignedData, type ParsedPkcs7SignerInfo, type ParsedRelativeDistinguishedName, type ParsedRevokedCertificate, type Pbes2EncryptionOptions, type Pbes2EncryptionScheme, type Pbes2Prf, type PemBlock, type PfxBagAttributesInput, type PfxCertificateBagInput, type PfxCertificateSource, type PfxEncryptionOptions, type PfxMaterial, type PfxPrivateKeyBagInput, type PfxPrivateKeySource, type Pkcs7CertBag, type Pkcs7CertificateSource, type Pkcs7SignedDataMaterial, type Pkcs7Signer, type PolicyConstraints, type PolicyInformation, type PolicyMapping, type PolicyMappings, type PolicyQualifierInfo, type PolicyValidationInput, type PrivateKeyImportInput, type PublicKeyImportInput, type RelativeDistinguishedNameInput, type ResolveOcspResponderCandidatesInput, type Result, type ResultError, type RevocationCertificateSource, type RevocationCrlEvidenceInput, type RevocationEvidenceInput, type RevocationEvidenceKind, type RevocationExecutionError, type RevocationIndeterminateReason, type RevocationOcspEvidenceInput, type RevocationPolicy, type RevocationReason, type RevocationSource, type RevocationStatus, type RevokedCertificateInput, type RsaHash, type RsaKeyAlgorithmInput, type RsaScheme, type SelfSignedCertificateResult, type ServiceIdentityInput, type ServiceIdentityType, type SrvServiceIdentityInput, type SubjectAltName, type TrustAnchor, type UriServiceIdentityInput, VERIFY_ERROR_CODES, type ValidateCandidatePathInput, type ValidateCandidatePathResult, type ValidateCandidatePathSuccess, type ValidateCertificateRevocationListFailure, type ValidateCertificateRevocationListInput, type ValidateCertificateRevocationListResult, type ValidateForCaInput, type ValidateForCodeSigningInput, type ValidateForTlsClientInput, type ValidateForTlsServerInput, type ValidateOcspResponseFailure, type ValidateOcspResponseInput, type ValidateOcspResponseResult, type ValidityInput, type VerifiedCertificateChain, type VerifyCertificateChainInput, type VerifyCertificateRevocationListFailure, type VerifyCertificateRevocationListResult, type VerifyChainFailure, type VerifyChainResult, type VerifyErrorCode, type VerifyFailureDetails, type VerifyOcspResponseFailure, type VerifyOcspResponseResult, type VerifyPkcs7SignedDataFailure, type VerifyPkcs7SignedDataResult, type VerifyPurpose, type VerifyRequestFailure, type VerifyRequestResult, type VerifyServiceIdentityInput, buildCandidatePath, categorizePemBlocks, checkCertificateRevocation, checkCertificateRevocationAgainstCrl, checkChainRevocation, checkExtendedKeyUsage, createCertificate, createCertificateRevocationList, createCertificateSigningRequest, createOcspRequest, createOcspResponse, createPfx, createPkcs7CertBagDer, createPkcs7CertBagPem, createPkcs7SignedDataDer, createPkcs7SignedDataPem, createSelfSignedCertificate, decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, findExtension, generateKeyPair, getCertificateOcspResponderUris, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem, isCertificateRevoked, isResultError, matchCertificateServiceIdentity, matchServiceIdentity, parseCertificateChainPem, parseCertificateDer, parseCertificatePem, parseCertificateRevocationListDer, parseCertificateRevocationListPem, parseCertificateSigningRequestDer, parseCertificateSigningRequestPem, parseOcspRequestDer, parseOcspRequestPem, parseOcspResponseDer, parseOcspResponsePem, parsePfxDer, parsePfxPem, parsePkcs7CertBagDer, parsePkcs7CertBagPem, parsePkcs7SignedDataDer, parsePkcs7SignedDataPem, pemDecode, pemEncode, resolveOcspResponderCandidates, splitPemBlocks, trustAnchorFromCertificate, unwrap, unwrapOr, validateCandidatePath, validateCertificateRevocationList, validateForCa, validateForCodeSigning, validateForTlsClient, validateForTlsServer, validateOcspResponse, verifyCertificateChain, verifyCertificateRevocationList, verifyCertificateSigningRequest, verifyOcspResponse, verifyPkcs7SignedData };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{categorizePemBlocks as e,pemDecode as t,pemEncode as n,splitPemBlocks as r}from"./pem/pem.js";import{isResultError as i,unwrap as a,unwrapOr as o}from"./result/result.js";import{exportBinaryBase64 as s,exportEncryptedPkcs1Pem as c,exportEncryptedPkcs8Der as l,exportEncryptedPkcs8Pem as u,exportEncryptedSec1Pem as d,exportPkcs1Der as f,exportPkcs1Pem as p,exportPkcs8Der as m,exportPkcs8Pem as h,exportPrivateJwk as g,exportPublicJwk as _,exportSec1Der as v,exportSec1Pem as y,exportSpkiDer as b,exportSpkiPem as x,generateKeyPair as S,importEncryptedPkcs1Pem as C,importEncryptedPkcs8Der as w,importEncryptedPkcs8Pem as T,importEncryptedSec1Pem as E,importPkcs1Der as D,importPkcs1Pem as O,importPkcs8Base64 as k,importPkcs8Der as A,importPkcs8Pem as j,importPrivateJwk as M,importPublicJwk as N,importSec1Der as P,importSec1Pem as F,importSpkiBase64 as I,importSpkiDer as L,importSpkiPem as R}from"./keys/keys.js";import{decodeExtension as z,decodeExtensionMap as B,decodeExtensions as V,defineExtensionDecoder as H,defineExtensionDecoderMap as U,findExtension as W,parseCertificateChainPem as G,parseCertificateDer as K,parseCertificatePem as q,parseCertificateSigningRequestDer as J,parseCertificateSigningRequestPem as Y}from"./x509/parse.js";import{createPfx as X,parsePfxDer as Z,parsePfxPem as Q}from"./pkcs/pfx.js";import{createPkcs7CertBagDer as $,createPkcs7CertBagPem as ee,createPkcs7SignedDataDer as te,createPkcs7SignedDataPem as ne,parsePkcs7CertBagDer as re,parsePkcs7CertBagPem as ie,parsePkcs7SignedDataDer as ae,parsePkcs7SignedDataPem as oe,verifyPkcs7SignedData as se}from"./pkcs/pkcs7.js";import{checkCertificateRevocationAgainstCrl as ce,createCertificateRevocationList as le,isCertificateRevoked as ue,parseCertificateRevocationListDer as de,parseCertificateRevocationListPem as fe,validateCertificateRevocationList as pe,verifyCertificateRevocationList as me}from"./revocation/crl.js";import{checkChainRevocation as he}from"./revocation/chain.js";import{matchCertificateServiceIdentity as ge,matchServiceIdentity as _e}from"./verify/identity.js";import{
|
|
1
|
+
import{categorizePemBlocks as e,pemDecode as t,pemEncode as n,splitPemBlocks as r}from"./pem/pem.js";import{isResultError as i,unwrap as a,unwrapOr as o}from"./result/result.js";import{exportBinaryBase64 as s,exportEncryptedPkcs1Pem as c,exportEncryptedPkcs8Der as l,exportEncryptedPkcs8Pem as u,exportEncryptedSec1Pem as d,exportPkcs1Der as f,exportPkcs1Pem as p,exportPkcs8Der as m,exportPkcs8Pem as h,exportPrivateJwk as g,exportPublicJwk as _,exportSec1Der as v,exportSec1Pem as y,exportSpkiDer as b,exportSpkiPem as x,generateKeyPair as S,importEncryptedPkcs1Pem as C,importEncryptedPkcs8Der as w,importEncryptedPkcs8Pem as T,importEncryptedSec1Pem as E,importPkcs1Der as D,importPkcs1Pem as O,importPkcs8Base64 as k,importPkcs8Der as A,importPkcs8Pem as j,importPrivateJwk as M,importPublicJwk as N,importSec1Der as P,importSec1Pem as F,importSpkiBase64 as I,importSpkiDer as L,importSpkiPem as R}from"./keys/keys.js";import{decodeExtension as z,decodeExtensionMap as B,decodeExtensions as V,defineExtensionDecoder as H,defineExtensionDecoderMap as U,findExtension as W,parseCertificateChainPem as G,parseCertificateDer as K,parseCertificatePem as q,parseCertificateSigningRequestDer as J,parseCertificateSigningRequestPem as Y}from"./x509/parse.js";import{createPfx as X,parsePfxDer as Z,parsePfxPem as Q}from"./pkcs/pfx.js";import{createPkcs7CertBagDer as $,createPkcs7CertBagPem as ee,createPkcs7SignedDataDer as te,createPkcs7SignedDataPem as ne,parsePkcs7CertBagDer as re,parsePkcs7CertBagPem as ie,parsePkcs7SignedDataDer as ae,parsePkcs7SignedDataPem as oe,verifyPkcs7SignedData as se}from"./pkcs/pkcs7.js";import{checkCertificateRevocationAgainstCrl as ce,createCertificateRevocationList as le,isCertificateRevoked as ue,parseCertificateRevocationListDer as de,parseCertificateRevocationListPem as fe,validateCertificateRevocationList as pe,verifyCertificateRevocationList as me}from"./revocation/crl.js";import{checkChainRevocation as he}from"./revocation/chain.js";import{matchCertificateServiceIdentity as ge,matchServiceIdentity as _e}from"./verify/identity.js";import{VERIFY_ERROR_CODES as ve,buildCandidatePath as ye,checkExtendedKeyUsage as be,trustAnchorFromCertificate as xe,validateCandidatePath as Se,validateForCa as Ce,validateForCodeSigning as we,validateForTlsClient as Te,validateForTlsServer as Ee,verifyCertificateChain as De,verifyCertificateSigningRequest as Oe}from"./verify/verify.js";import{createOcspRequest as ke,createOcspResponse as Ae,parseOcspRequestDer as je,parseOcspRequestPem as Me,parseOcspResponseDer as Ne,parseOcspResponsePem as Pe,validateOcspResponse as Fe,verifyOcspResponse as Ie}from"./revocation/ocsp.js";import{checkCertificateRevocation as Le,getCertificateOcspResponderUris as Re,resolveOcspResponderCandidates as ze}from"./revocation/revocation.js";import{createCertificate as Be,createSelfSignedCertificate as Ve}from"./x509/certificate.js";import{createCertificateSigningRequest as He}from"./x509/csr.js";export{ve as VERIFY_ERROR_CODES,ye as buildCandidatePath,e as categorizePemBlocks,Le as checkCertificateRevocation,ce as checkCertificateRevocationAgainstCrl,he as checkChainRevocation,be as checkExtendedKeyUsage,Be as createCertificate,le as createCertificateRevocationList,He as createCertificateSigningRequest,ke as createOcspRequest,Ae as createOcspResponse,X as createPfx,$ as createPkcs7CertBagDer,ee as createPkcs7CertBagPem,te as createPkcs7SignedDataDer,ne as createPkcs7SignedDataPem,Ve as createSelfSignedCertificate,z as decodeExtension,B as decodeExtensionMap,V as decodeExtensions,H as defineExtensionDecoder,U as defineExtensionDecoderMap,s as exportBinaryBase64,c as exportEncryptedPkcs1Pem,l as exportEncryptedPkcs8Der,u as exportEncryptedPkcs8Pem,d as exportEncryptedSec1Pem,f as exportPkcs1Der,p as exportPkcs1Pem,m as exportPkcs8Der,h as exportPkcs8Pem,g as exportPrivateJwk,_ as exportPublicJwk,v as exportSec1Der,y as exportSec1Pem,b as exportSpkiDer,x as exportSpkiPem,W as findExtension,S as generateKeyPair,Re as getCertificateOcspResponderUris,C as importEncryptedPkcs1Pem,w as importEncryptedPkcs8Der,T as importEncryptedPkcs8Pem,E as importEncryptedSec1Pem,D as importPkcs1Der,O as importPkcs1Pem,k as importPkcs8Base64,A as importPkcs8Der,j as importPkcs8Pem,M as importPrivateJwk,N as importPublicJwk,P as importSec1Der,F as importSec1Pem,I as importSpkiBase64,L as importSpkiDer,R as importSpkiPem,ue as isCertificateRevoked,i as isResultError,ge as matchCertificateServiceIdentity,_e as matchServiceIdentity,G as parseCertificateChainPem,K as parseCertificateDer,q as parseCertificatePem,de as parseCertificateRevocationListDer,fe as parseCertificateRevocationListPem,J as parseCertificateSigningRequestDer,Y as parseCertificateSigningRequestPem,je as parseOcspRequestDer,Me as parseOcspRequestPem,Ne as parseOcspResponseDer,Pe as parseOcspResponsePem,Z as parsePfxDer,Q as parsePfxPem,re as parsePkcs7CertBagDer,ie as parsePkcs7CertBagPem,ae as parsePkcs7SignedDataDer,oe as parsePkcs7SignedDataPem,t as pemDecode,n as pemEncode,ze as resolveOcspResponderCandidates,r as splitPemBlocks,xe as trustAnchorFromCertificate,a as unwrap,o as unwrapOr,Se as validateCandidatePath,pe as validateCertificateRevocationList,Ce as validateForCa,we as validateForCodeSigning,Te as validateForTlsClient,Ee as validateForTlsServer,Fe as validateOcspResponse,De as verifyCertificateChain,me as verifyCertificateRevocationList,Oe as verifyCertificateSigningRequest,Ie as verifyOcspResponse,se as verifyPkcs7SignedData};
|
|
@@ -12,7 +12,7 @@ type CertificateSource = string | Uint8Array | ParsedCertificate;
|
|
|
12
12
|
/**
|
|
13
13
|
* OCSP response in any supported format.
|
|
14
14
|
*
|
|
15
|
-
* Accepts PEM string or DER bytes.
|
|
15
|
+
* Accepts PEM string or DER bytes. Used for
|
|
16
16
|
* {@linkcode CheckChainRevocationInput.ocspResponses}.
|
|
17
17
|
*/
|
|
18
18
|
type OcspResponseSource = string | Uint8Array;
|
|
@@ -33,7 +33,12 @@ interface RevocationPolicy {
|
|
|
33
33
|
/**
|
|
34
34
|
* Evidence preference when multiple sources are available.
|
|
35
35
|
*
|
|
36
|
-
*
|
|
36
|
+
* Both evidence kinds are always evaluated, and a validated `revoked`
|
|
37
|
+
* verdict from either source wins regardless of preference (fail-closed).
|
|
38
|
+
* Preference only decides which source's `good` verdict is reported when
|
|
39
|
+
* both yield one.
|
|
40
|
+
*
|
|
41
|
+
* - `'best-available'`: OCSP consulted first, CRL as fallback (default)
|
|
37
42
|
* - `'ocsp'`: prefer OCSP over CRL
|
|
38
43
|
* - `'crl'`: prefer CRL over OCSP
|
|
39
44
|
*/
|
|
@@ -167,6 +172,7 @@ type CheckChainRevocationResult = {
|
|
|
167
172
|
* const result = await checkChainRevocation({
|
|
168
173
|
* chain: validatedChain,
|
|
169
174
|
* crls: [crl1, crl2],
|
|
175
|
+
* ocspResponses: [ocspResponseDer],
|
|
170
176
|
* policy: { mode: 'hard-fail' },
|
|
171
177
|
* });
|
|
172
178
|
* if (result.value.decision === 'deny') {
|
package/dist/revocation/chain.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{parseCertificateFromSource as e}from"../x509/parse.js";import{checkCertificateRevocationAgainstCrl as t,parseCertificateRevocationListDer as n,parseCertificateRevocationListPem as r}from"./crl.js";function
|
|
1
|
+
import{parseCertificateFromSource as e}from"../x509/parse.js";import{checkCertificateRevocationAgainstCrl as t,parseCertificateRevocationListDer as n,parseCertificateRevocationListPem as r,revocationReasonFromCode as i}from"./crl.js";import{parseOcspResponseDer as a,parseOcspResponsePem as o,validateOcspResponse as s}from"./ocsp.js";function c(e){return typeof e==`object`&&`issuer`in e?e:typeof e==`string`?r(e):n(e)}function l(t){try{return e(t)}catch{return}}function u(e,t){if(e.der.length!==t.der.length)return!1;for(let n=0;n<e.der.length;n++)if(e.der[n]!==t.der[n])return!1;return!0}function d(e,t,n){let r=[];for(let e of t){let t=l(e);t!==void 0&&r.push(t)}let i=[...r,...n];if(e.authorityKeyIdentifier!==void 0){for(let t of i)if(t.subjectKeyIdentifier!==void 0&&f(e.authorityKeyIdentifier)===f(t.subjectKeyIdentifier))return t}for(let t of i)if(e.issuer.derHex===t.subject.derHex)return t}function f(e){return e.toLowerCase()}function p(e){return`${e.issuer.derHex}:${e.serialNumberHex}`}async function m(e,t){let n=p(e),r=t.cache.get(n);if(r===`visiting`)return`resolved-indeterminate`;if(r!==void 0)return r;t.cache.set(n,`visiting`);let i=t.chain[t.chain.length-1];if(i!==void 0&&u(e,i)||t.chain.some(t=>u(t,e)))return t.cache.set(n,`resolved-valid`),`resolved-valid`;let a=h(e,t);if(a===void 0)return t.cache.set(n,`resolved-indeterminate`),`resolved-indeterminate`;let o=await g(e,a,t);return t.cache.set(n,o),o}function h(e,t){let n=[];for(let e of t.extraCertificates){let t=l(e);t!==void 0&&n.push(t)}let r=[...t.chain,...n];for(let t of r)if(e.authorityKeyIdentifier!==void 0&&t.subjectKeyIdentifier!==void 0&&f(e.authorityKeyIdentifier)===f(t.subjectKeyIdentifier)||e.issuer.derHex===t.subject.derHex)return t}async function g(e,n,r){let i=r.chain.some(e=>u(e,n));for(let i of r.crls){let a;try{a=c(i)}catch{continue}let o=await t({certificate:e,issuerCertificate:n,crl:a,at:r.at});if(o.ok){if(o.value.status===`revoked`)return`resolved-revoked`;if(o.value.status===`good`&&await m(n,r)===`resolved-valid`)return`resolved-valid`}}return i?`resolved-valid`:`resolved-indeterminate`}function _(e,t,n,r,i){return n===`revoked`&&r!==void 0?{certificate:e,status:`revoked`,source:{type:`crl`,signerCertificate:t},revocationInfo:{date:r,...i===void 0?{}:{reason:i}}}:{certificate:e,status:`good`,source:{type:`crl`,signerCertificate:t}}}function v(e){return typeof e==`string`?o(e):a(e)}function y(e){switch(e){case`stale_response`:return`ocsp_response_expired`;case`responder_id_mismatch`:case`responder_chain_invalid`:case`ocsp_signing_missing`:return`ocsp_responder_not_authorized`;case`signature_invalid`:return`ocsp_responder_indeterminate`;case`response_status_invalid`:case`issuer_mismatch`:case`nonce_mismatch`:case`request_mismatch`:return`no_applicable_ocsp`}}const b=new Set([`signature_invalid`,`responder_id_mismatch`,`responder_chain_invalid`,`ocsp_signing_missing`]);async function x(e,t,n,r){let i=await s({response:e,issuerCertificate:t,at:r});if(i.ok||!b.has(i.code))return i;for(let i of n){let n=l(i);if(n===void 0)continue;let a=await s({response:e,issuerCertificate:t,responderCertificate:n,at:r});if(a.ok)return a}return i}async function S(e,t,n){let{ocspResponses:r=[],extraCertificates:a=[],at:o=new Date}=n,s=[],c=new Set;for(let n of r){let r;try{r=v(n)}catch(e){s.push({kind:`parse_error`,message:e instanceof Error?e.message:`OCSP response parse failed`});continue}let l=(r.responses??[]).find(t=>f(t.certId.serialNumberHex)===f(e.serialNumberHex));if(l===void 0)continue;let u=await x(r,t,a,o);if(!u.ok){c.add(y(u.code));continue}if(l.certStatus===`revoked`){let t=i(l.revocationReasonCode);return{status:{certificate:e,status:`revoked`,source:{type:`ocsp`},revocationInfo:{date:l.revokedAt??l.thisUpdate,...t===void 0?{}:{reason:t}}},executionErrors:s}}if(l.certStatus===`good`)return{status:{certificate:e,status:`good`,source:{type:`ocsp`}},executionErrors:s};c.add(`ocsp_status_unknown`)}return c.size===0&&c.add(`no_applicable_ocsp`),{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[...c]},executionErrors:s}}const C=[`keyCompromise`,`cACompromise`,`affiliationChanged`,`superseded`,`cessationOfOperation`,`certificateHold`,`privilegeWithdrawn`,`aACompromise`];async function w(e,n,r,i){let{crls:a=[],extraCertificates:o=[],chain:s=[],at:l=new Date}=r,f=[],p=!1,h=!1,g=!1,v,y=new Set,b=[];for(let e of a)try{b.push(c(e))}catch(e){f.push({kind:`parse_error`,message:e instanceof Error?e.message:`CRL parse failed`})}let x=b.filter(e=>e.baseCrlNumber===void 0),S=b.filter(e=>e.baseCrlNumber!==void 0),w=async(n,r,i)=>t({certificate:e,issuerCertificate:i,crl:n,...r===void 0?{}:{deltaCrl:r},at:l});for(let t of x){let r=S.find(e=>e.issuer.derHex===t.issuer.derHex&&e.baseCrlNumber!==void 0&&t.crlNumber!==void 0&&BigInt(e.baseCrlNumber)<=BigInt(t.crlNumber)),a=await w(t,r,n),c=n;if(!a.ok){let e=d(t,o,s);e!==void 0&&!u(e,n)&&(a=await w(t,r,e),c=e)}if(!a.ok)continue;let l=await m(c,i);if(l===`resolved-revoked`){p=!0;continue}if(l===`resolved-indeterminate`){h=!0;continue}if(a.value.status===`revoked`)return{status:_(e,c,`revoked`,a.value.revocationDate,a.value.reasonCode),executionErrors:f};g=!0,v=c;let b=t.issuingDistributionPoint?.onlySomeReasons?.flags;if(b===void 0)for(let e of C)y.add(e);else for(let e of b)y.add(e)}if(g)return C.every(e=>y.has(e))?{status:{certificate:e,status:`good`,...v===void 0?{}:{source:{type:`crl`,signerCertificate:v}}},executionErrors:f}:{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[`reason_coverage_incomplete`]},executionErrors:f};let T=[];return p?T.push(`crl_signer_revoked`):h?T.push(`crl_signer_indeterminate`):T.push(`no_applicable_crl`),{status:{certificate:e,status:`indeterminate`,indeterminateReasons:T},executionErrors:f}}async function T(e,t,n,r){let i=n.policy?.prefer??`best-available`,a=await S(e,t,n),o=await w(e,t,n,r),s=[...a.executionErrors,...o.executionErrors],c=i===`crl`?[o,a]:[a,o],l=c.find(e=>e.status.status===`revoked`);if(l!==void 0)return{status:l.status,executionErrors:s};let u=c.find(e=>e.status.status===`good`);if(u!==void 0)return{status:u.status,executionErrors:s};let d=new Set;for(let e of c)for(let t of e.status.indeterminateReasons??[])d.add(t);return{status:{certificate:e,status:`indeterminate`,indeterminateReasons:[...d]},executionErrors:s}}async function E(e){let{chain:t,policy:n,crls:r=[],extraCertificates:i=[],at:a=new Date}=e,o=n?.mode??`soft-fail`;if(t.length===0)return{ok:!0,value:{decision:`allow`,summary:{revokedCertificates:[],indeterminateCertificates:[]},certificates:[]}};let s={cache:new Map,chain:t,crls:r,extraCertificates:i,at:a},c=t.slice(0,-1),l=[],u=[],d=[],f=[];for(let n=0;n<c.length;n++){let r=c[n],i=t[n+1];if(r===void 0||i===void 0)continue;let{status:a,executionErrors:o}=await T(r,i,e,s);l.push(a),f.push(...o),a.status===`revoked`?u.push(r):a.status===`indeterminate`&&d.push(r)}let p=u.length>0,m=d.length>0;return{ok:!0,value:{decision:p||m&&o===`hard-fail`?`deny`:`allow`,summary:{revokedCertificates:u,indeterminateCertificates:d},certificates:l,...f.length>0?{executionErrors:f}:{}}}}export{E as checkChainRevocation};
|
|
2
2
|
//# sourceMappingURL=chain.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chain.js","names":[],"sources":["../../src/revocation/chain.ts"],"sourcesContent":["/**\n * Chain-level revocation orchestration.\n *\n * Evaluates CRL and OCSP evidence for an entire validated certificate chain,\n * implementing the revocation checking portion of RFC 5280 §6.3.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#section-6.3 | RFC 5280 §6.3 CRL Validation}\n * @module\n */\n\nimport type { ParsedCertificate } from '#micro509/x509/parse.ts';\nimport { parseCertificateFromSource } from '#micro509/x509/parse.ts';\nimport {\n\tcheckCertificateRevocationAgainstCrl,\n\tparseCertificateRevocationListDer,\n\tparseCertificateRevocationListPem,\n\ttype ParsedCertificateRevocationList,\n\ttype RevocationReason,\n} from './crl.ts';\nimport type { CrlSource } from './crl.ts';\n\nexport type { CrlSource };\n\n// ---------------------------------------------------------------------------\n// Input Types\n// ---------------------------------------------------------------------------\n\n/**\n * Certificate in any supported format.\n *\n * Accepts PEM string, DER bytes, or an already-parsed {@linkcode ParsedCertificate}.\n * Used for {@linkcode CheckChainRevocationInput.extraCertificates}.\n */\nexport type CertificateSource = string | Uint8Array | ParsedCertificate;\n\n/**\n * OCSP response in any supported format.\n *\n * Accepts PEM string or DER bytes. Reserved for future OCSP support in\n * {@linkcode CheckChainRevocationInput.ocspResponses}.\n */\nexport type OcspResponseSource = string | Uint8Array;\n\n/**\n * Revocation checking policy for {@linkcode checkChainRevocation}.\n *\n * Controls how indeterminate results (missing evidence, expired CRLs) affect\n * the final {@linkcode CheckChainRevocationValue.decision | decision}.\n */\nexport interface RevocationPolicy {\n\t/**\n\t * How to handle indeterminate status.\n\t *\n\t * - `'soft-fail'`: indeterminate certificates are allowed (default)\n\t * - `'hard-fail'`: indeterminate certificates cause denial\n\t */\n\treadonly mode?: 'soft-fail' | 'hard-fail';\n\t/**\n\t * Evidence preference when multiple sources are available.\n\t *\n\t * - `'best-available'`: use whichever evidence is freshest (default)\n\t * - `'ocsp'`: prefer OCSP over CRL\n\t * - `'crl'`: prefer CRL over OCSP\n\t */\n\treadonly prefer?: 'ocsp' | 'crl' | 'best-available';\n}\n\n/** Input for {@linkcode checkChainRevocation}. */\nexport interface CheckChainRevocationInput {\n\t/** Validated certificate chain (leaf first, root last). */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** CRLs to evaluate. */\n\treadonly crls?: readonly CrlSource[];\n\t/** OCSP responses to evaluate. */\n\treadonly ocspResponses?: readonly OcspResponseSource[];\n\t/** Extra certs for indirect CRL issuers / delegated OCSP responders. */\n\treadonly extraCertificates?: readonly CertificateSource[];\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/** Revocation policy. */\n\treadonly policy?: RevocationPolicy;\n}\n\n// ---------------------------------------------------------------------------\n// Output Types\n// ---------------------------------------------------------------------------\n\n/**\n * Granular reasons why revocation status could not be determined.\n *\n * Returned in {@linkcode CertificateRevocationStatus.indeterminateReasons} when\n * `status` is `'indeterminate'`. Grouped by category:\n *\n * - **Evidence not found**: `no_applicable_crl`, `no_applicable_ocsp`\n * - **Scope mismatch**: `distribution_point_mismatch`, `issuer_name_mismatch`,\n * `reason_scope_mismatch`, `indirect_crl_scope_mismatch`, `reason_coverage_incomplete`\n * - **Signer trust**: `crl_signer_not_found`, `crl_signer_not_authorized`,\n * `crl_signer_revoked`, `crl_signer_indeterminate`, and OCSP equivalents\n * - **Freshness**: `crl_expired`, `ocsp_response_expired`\n */\nexport type RevocationIndeterminateReason =\n\t// Evidence not found\n\t| 'no_applicable_crl'\n\t| 'no_applicable_ocsp'\n\t// Scope issues\n\t| 'distribution_point_mismatch'\n\t| 'issuer_name_mismatch'\n\t| 'reason_scope_mismatch'\n\t| 'indirect_crl_scope_mismatch'\n\t| 'reason_coverage_incomplete'\n\t// Signer trust issues\n\t| 'crl_signer_not_found'\n\t| 'crl_signer_not_authorized'\n\t| 'crl_signer_revoked'\n\t| 'crl_signer_indeterminate'\n\t| 'ocsp_responder_not_found'\n\t| 'ocsp_responder_not_authorized'\n\t| 'ocsp_responder_revoked'\n\t| 'ocsp_responder_indeterminate'\n\t// Freshness\n\t| 'crl_expired'\n\t| 'ocsp_response_expired'\n\t// OCSP specific\n\t| 'ocsp_status_unknown';\n\n/**\n * Identifies the source of revocation evidence.\n *\n * Included in {@linkcode CertificateRevocationStatus.source} when status is\n * `'good'` or `'revoked'` to indicate which CRL or OCSP response provided the answer.\n */\nexport interface RevocationSource {\n\t/** Whether evidence came from a CRL or OCSP response. */\n\treadonly type: 'crl' | 'ocsp';\n\t/** Certificate that signed the evidence (CRL issuer or OCSP responder). */\n\treadonly signerCertificate?: ParsedCertificate;\n\t/** Identifier for debugging (e.g., CRL issuer DN or OCSP responder URL). */\n\treadonly evidenceIdentifier?: string;\n}\n\n/**\n * Revocation evaluation result for a single certificate.\n *\n * One entry per certificate in {@linkcode CheckChainRevocationValue.certificates}.\n * The trust anchor is excluded (never checked for revocation).\n */\nexport interface CertificateRevocationStatus {\n\t/** The certificate that was evaluated. */\n\treadonly certificate: ParsedCertificate;\n\t/**\n\t * Revocation status determination.\n\t *\n\t * - `'good'`: evidence confirms certificate is not revoked\n\t * - `'revoked'`: evidence confirms certificate is revoked\n\t * - `'indeterminate'`: could not determine status (see {@linkcode indeterminateReasons})\n\t */\n\treadonly status: 'good' | 'revoked' | 'indeterminate';\n\t/** Evidence source when status is `'good'` or `'revoked'`. */\n\treadonly source?: RevocationSource;\n\t/** Why status could not be determined. Present when `status` is `'indeterminate'`. */\n\treadonly indeterminateReasons?: readonly RevocationIndeterminateReason[];\n\t/** Revocation details. Present when `status` is `'revoked'`. */\n\treadonly revocationInfo?: {\n\t\t/** When the certificate was revoked. */\n\t\treadonly date: Date;\n\t\t/** RFC 5280 CRLReason code, if provided by the CRL/OCSP response. */\n\t\treadonly reason?: RevocationReason;\n\t};\n}\n\n/**\n * Errors encountered while processing revocation evidence.\n *\n * Distinct from {@linkcode RevocationIndeterminateReason}: execution errors are\n * code failures (malformed CRL, unsupported extension) rather than evaluation\n * outcomes (CRL doesn't cover this certificate).\n *\n * Collected in {@linkcode CheckChainRevocationValue.executionErrors}.\n */\nexport interface RevocationExecutionError {\n\t/** Error category. */\n\treadonly kind: 'parse_error' | 'unsupported_extension' | 'internal_error';\n\t/** Human-readable error description. */\n\treadonly message: string;\n\t/** Which evidence caused the error (e.g., CRL issuer DN). */\n\treadonly evidenceIdentifier?: string;\n}\n\n/**\n * Detailed revocation check results.\n *\n * Returned as {@linkcode CheckChainRevocationResult.value} from\n * {@linkcode checkChainRevocation}. Contains both the policy decision and\n * detailed per-certificate findings for debugging.\n */\nexport interface CheckChainRevocationValue {\n\t/**\n\t * Final policy decision based on {@linkcode RevocationPolicy}.\n\t *\n\t * - `'allow'`: chain passes revocation check\n\t * - `'deny'`: chain fails (revoked certificate or hard-fail on indeterminate)\n\t */\n\treadonly decision: 'allow' | 'deny';\n\t/** Quick-access summary of problematic certificates. */\n\treadonly summary: {\n\t\t/** Certificates confirmed as revoked. */\n\t\treadonly revokedCertificates: readonly ParsedCertificate[];\n\t\t/** Certificates whose status could not be determined. */\n\t\treadonly indeterminateCertificates: readonly ParsedCertificate[];\n\t};\n\t/** Per-certificate evaluation results. See {@linkcode CertificateRevocationStatus}. */\n\treadonly certificates: readonly CertificateRevocationStatus[];\n\t/** Evidence that could not be processed. See {@linkcode RevocationExecutionError}. */\n\treadonly executionErrors?: readonly RevocationExecutionError[];\n}\n\n/** Result type for {@linkcode checkChainRevocation}. */\nexport type CheckChainRevocationResult = {\n\treadonly ok: true;\n\treadonly value: CheckChainRevocationValue;\n};\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parses a CRL from various source formats.\n */\nfunction parseCrlFromSource(source: CrlSource): ParsedCertificateRevocationList {\n\tif (typeof source === 'object' && 'issuer' in source) {\n\t\treturn source;\n\t}\n\tif (typeof source === 'string') {\n\t\treturn parseCertificateRevocationListPem(source);\n\t}\n\treturn parseCertificateRevocationListDer(source);\n}\n\n/**\n * Parses a certificate from various source formats, returning undefined on failure.\n */\nfunction parseCertificateSafe(source: CertificateSource): ParsedCertificate | undefined {\n\ttry {\n\t\treturn parseCertificateFromSource(source);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Compares two certificates by DER bytes for identity.\n * Reference equality fails when same cert is parsed from different sources.\n */\nfunction sameCertificate(a: ParsedCertificate, b: ParsedCertificate): boolean {\n\tif (a.der.length !== b.der.length) return false;\n\tfor (let i = 0; i < a.der.length; i++) {\n\t\tif (a.der[i] !== b.der[i]) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Searches for a certificate that could have signed the given CRL.\n * Matches by AKI/SKI or issuer/subject DN.\n */\nfunction findIndirectCrlIssuer(\n\tcrl: ParsedCertificateRevocationList,\n\textraCertificates: readonly CertificateSource[],\n\tchain: readonly ParsedCertificate[],\n): ParsedCertificate | undefined {\n\t// Combine extra certs with chain certs for searching\n\t// Chain certs are already parsed; extra certs may need parsing\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...parsedExtras, ...chain];\n\n\t// First pass: prefer AKI/SKI match (more specific)\n\tif (crl.authorityKeyIdentifier !== undefined) {\n\t\tfor (const candidate of candidates) {\n\t\t\tif (\n\t\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\t\tnormalizeHex(crl.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t\t) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: fall back to DN match\n\tfor (const candidate of candidates) {\n\t\tif (crl.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/** Lowercases a hex string for bytewise comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n// ---------------------------------------------------------------------------\n// CRL Signer Validation (RFC 5280 §6.3.3)\n// ---------------------------------------------------------------------------\n\n/**\n * State machine for CRL signer validation with memoization.\n * - `visiting`: Currently being checked (cycle detection)\n * - `resolved-valid`: Signer is not revoked\n * - `resolved-revoked`: Signer is revoked\n * - `resolved-indeterminate`: Can't determine signer status\n */\ntype SignerValidationState =\n\t| 'visiting'\n\t| 'resolved-valid'\n\t| 'resolved-revoked'\n\t| 'resolved-indeterminate';\n\n/** Context for CRL signer validation with memoization cache. */\ninterface SignerValidationContext {\n\treadonly cache: Map<string, SignerValidationState>;\n\treadonly chain: readonly ParsedCertificate[];\n\treadonly crls: readonly CrlSource[];\n\treadonly extraCertificates: readonly CertificateSource[];\n\treadonly at: Date;\n}\n\n/**\n * Builds a unique cache key for a certificate.\n * Uses issuer DN + serial number which uniquely identifies a cert.\n */\nfunction certCacheKey(cert: ParsedCertificate): string {\n\treturn `${cert.issuer.derHex}:${cert.serialNumberHex}`;\n}\n\n/**\n * Validates that a CRL signer certificate is not revoked.\n * Uses memoization to avoid redundant checks and detect cycles.\n */\nasync function validateCrlSigner(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// Use issuer+serial as cache key (unique per certificate)\n\tconst key = certCacheKey(signer);\n\tconst cached = ctx.cache.get(key);\n\n\t// Cycle detection: if we're already visiting this signer, it's indeterminate\n\tif (cached === 'visiting') {\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Return cached result if already resolved\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\t// Mark as visiting before recursive checks\n\tctx.cache.set(key, 'visiting');\n\n\t// Trust anchor (last in chain) is trusted by definition\n\tconst trustAnchor = ctx.chain[ctx.chain.length - 1];\n\tif (trustAnchor !== undefined && sameCertificate(signer, trustAnchor)) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// If signer is in the validated chain, it's trusted\n\t// (Chain was already validated before revocation checking)\n\tconst isInChain = ctx.chain.some((c) => sameCertificate(c, signer));\n\tif (isInChain) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// Signer is not in chain — need to check its revocation status\n\t// Find signer's issuer to perform revocation check\n\tconst signerIssuer = findSignerIssuer(signer, ctx);\n\tif (signerIssuer === undefined) {\n\t\tctx.cache.set(key, 'resolved-indeterminate');\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Check signer's revocation status (recursive)\n\tconst signerRevocation = await checkSignerRevocation(signer, signerIssuer, ctx);\n\tctx.cache.set(key, signerRevocation);\n\treturn signerRevocation;\n}\n\n/**\n * Finds the issuer certificate for a CRL signer.\n * Searches the chain and extraCertificates by AKI/SKI or DN matching.\n */\nfunction findSignerIssuer(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): ParsedCertificate | undefined {\n\t// Parse extra certificates\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of ctx.extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...ctx.chain, ...parsedExtras];\n\n\tfor (const candidate of candidates) {\n\t\t// Match by AKI → SKI (preferred, more specific)\n\t\tif (\n\t\t\tsigner.authorityKeyIdentifier !== undefined &&\n\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\tnormalizeHex(signer.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t) {\n\t\t\treturn candidate;\n\t\t}\n\n\t\t// Match by issuer DN → subject DN\n\t\tif (signer.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Checks if a CRL signer certificate is revoked by examining available CRLs.\n * Recursively validates the CRL signer of any CRL used to check revocation.\n */\nasync function checkSignerRevocation(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// If the signer's issuer is in the validated chain, the signer is trusted\n\t// by virtue of being issued by a trusted CA. We only need to check if\n\t// it's explicitly revoked, not prove \"good\" status.\n\tconst issuerInChain = ctx.chain.some((c) => sameCertificate(c, issuer));\n\n\t// Try each CRL to check signer's revocation\n\tfor (const crlSource of ctx.crls) {\n\t\tlet crl: ParsedCertificateRevocationList;\n\t\ttry {\n\t\t\tcrl = parseCrlFromSource(crlSource);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if this CRL can provide revocation info for the signer\n\t\tconst result = await checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: signer,\n\t\t\tissuerCertificate: issuer,\n\t\t\tcrl,\n\t\t\tat: ctx.at,\n\t\t});\n\n\t\tif (result.ok) {\n\t\t\tif (result.value.status === 'revoked') {\n\t\t\t\treturn 'resolved-revoked';\n\t\t\t}\n\t\t\tif (result.value.status === 'good') {\n\t\t\t\t// Before accepting this result, validate the CRL's signer\n\t\t\t\t// The CRL's signer is the issuer we just used\n\t\t\t\tconst crlSignerStatus = await validateCrlSigner(issuer, ctx);\n\t\t\t\tif (crlSignerStatus === 'resolved-valid') {\n\t\t\t\t\treturn 'resolved-valid';\n\t\t\t\t}\n\t\t\t\t// If CRL signer is revoked or indeterminate, can't trust this result\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the signer's issuer is in the chain and we found no revocation,\n\t// trust the signer (issued by trusted CA, no evidence of revocation)\n\tif (issuerInChain) {\n\t\treturn 'resolved-valid';\n\t}\n\n\treturn 'resolved-indeterminate';\n}\n\n/** Builds a CertificateRevocationStatus for a CRL check result. */\nfunction buildCrlStatus(\n\tcert: ParsedCertificate,\n\tsigner: ParsedCertificate,\n\tstatus: 'good' | 'revoked',\n\trevocationDate?: Date,\n\treasonCode?: RevocationReason,\n): CertificateRevocationStatus {\n\tif (status === 'revoked' && revocationDate !== undefined) {\n\t\treturn {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'revoked',\n\t\t\tsource: { type: 'crl', signerCertificate: signer },\n\t\t\trevocationInfo: {\n\t\t\t\tdate: revocationDate,\n\t\t\t\t...(reasonCode !== undefined ? { reason: reasonCode } : {}),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tcertificate: cert,\n\t\tstatus: 'good',\n\t\tsource: { type: 'crl', signerCertificate: signer },\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate using available CRLs.\n * Returns both status and any execution errors encountered.\n *\n * Tries the chain issuer first; if that fails, searches extraCertificates\n * and chain for an indirect CRL issuer that matches the CRL's AKI or issuer DN.\n *\n * Also validates that CRL signers are not revoked (RFC 5280 §6.3.3).\n */\n// RFC 5280 ReasonFlags — all possible revocation reasons that CRLs can cover.\nconst ALL_REASON_FLAGS: readonly string[] = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n];\n\nasync function evaluateCertificateRevocation(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<{\n\tstatus: CertificateRevocationStatus;\n\texecutionErrors: readonly RevocationExecutionError[];\n}> {\n\tconst { crls = [], extraCertificates = [], chain = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tlet sawCrlSignerRevoked = false;\n\tlet sawCrlSignerIndeterminate = false;\n\tlet sawGood = false;\n\tlet lastGoodSigner: ParsedCertificate | undefined;\n\tconst coveredReasons = new Set<string>();\n\n\t// Parse all CRLs and separate base CRLs from delta CRLs\n\tconst parsedCrls: ParsedCertificateRevocationList[] = [];\n\tfor (const crlSource of crls) {\n\t\ttry {\n\t\t\tparsedCrls.push(parseCrlFromSource(crlSource));\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'CRL parse failed',\n\t\t\t});\n\t\t}\n\t}\n\n\tconst baseCrls = parsedCrls.filter((crl) => crl.baseCrlNumber === undefined);\n\tconst deltaCrls = parsedCrls.filter((crl) => crl.baseCrlNumber !== undefined);\n\n\t// Helper to check CRL with given issuer and optional delta\n\tconst checkWithIssuer = async (\n\t\tcrl: ParsedCertificateRevocationList,\n\t\tdeltaCrl: ParsedCertificateRevocationList | undefined,\n\t\tcrlIssuer: ParsedCertificate,\n\t) => {\n\t\treturn checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: cert,\n\t\t\tissuerCertificate: crlIssuer,\n\t\t\tcrl,\n\t\t\t...(deltaCrl !== undefined ? { deltaCrl } : {}),\n\t\t\tat,\n\t\t});\n\t};\n\n\t// Process base CRLs (optionally paired with delta CRLs)\n\tfor (const baseCrl of baseCrls) {\n\t\t// Find applicable delta CRL for this base CRL (if any)\n\t\t// Delta CRL applies if it has the same issuer and crlNumber matches baseCrlNumber\n\t\tconst applicableDelta = deltaCrls.find(\n\t\t\t(d) =>\n\t\t\t\td.issuer.derHex === baseCrl.issuer.derHex &&\n\t\t\t\td.baseCrlNumber !== undefined &&\n\t\t\t\tbaseCrl.crlNumber !== undefined &&\n\t\t\t\tBigInt(d.baseCrlNumber) <= BigInt(baseCrl.crlNumber),\n\t\t);\n\n\t\t// Try chain issuer first\n\t\tlet result = await checkWithIssuer(baseCrl, applicableDelta, issuer);\n\t\tlet effectiveSigner = issuer;\n\n\t\t// Chain issuer failed — try to find indirect CRL issuer\n\t\tif (!result.ok) {\n\t\t\tconst indirectIssuer = findIndirectCrlIssuer(baseCrl, extraCertificates, chain);\n\t\t\tif (indirectIssuer !== undefined && !sameCertificate(indirectIssuer, issuer)) {\n\t\t\t\tresult = await checkWithIssuer(baseCrl, applicableDelta, indirectIssuer);\n\t\t\t\teffectiveSigner = indirectIssuer;\n\t\t\t}\n\t\t}\n\n\t\tif (!result.ok) {\n\t\t\tcontinue; // CRL doesn't apply to this certificate\n\t\t}\n\n\t\t// Validate CRL signer is not revoked before accepting result\n\t\tconst signerStatus = await validateCrlSigner(effectiveSigner, signerCtx);\n\t\tif (signerStatus === 'resolved-revoked') {\n\t\t\tsawCrlSignerRevoked = true;\n\t\t\tcontinue; // CRL signer revoked — can't trust this CRL\n\t\t}\n\t\tif (signerStatus === 'resolved-indeterminate') {\n\t\t\tsawCrlSignerIndeterminate = true;\n\t\t\tcontinue; // CRL signer status unknown — try other CRLs\n\t\t}\n\n\t\t// CRL is valid — check result\n\t\tif (result.value.status === 'revoked') {\n\t\t\t// Immediately return revoked status\n\t\t\treturn {\n\t\t\t\tstatus: buildCrlStatus(\n\t\t\t\t\tcert,\n\t\t\t\t\teffectiveSigner,\n\t\t\t\t\t'revoked',\n\t\t\t\t\tresult.value.revocationDate,\n\t\t\t\t\tresult.value.reasonCode,\n\t\t\t\t),\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\n\t\t// Status is 'good' — track which reasons this CRL covers\n\t\tsawGood = true;\n\t\tlastGoodSigner = effectiveSigner;\n\t\tconst crlReasons = baseCrl.issuingDistributionPoint?.onlySomeReasons?.flags;\n\t\tif (crlReasons === undefined) {\n\t\t\t// CRL covers all reasons\n\t\t\tfor (const reason of ALL_REASON_FLAGS) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t} else {\n\t\t\t// CRL only covers specific reasons\n\t\t\tfor (const reason of crlReasons) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return 'good' only if we saw at least one good result AND all reasons are covered\n\tif (sawGood) {\n\t\tconst allReasonsCovered = ALL_REASON_FLAGS.every((r) => coveredReasons.has(r));\n\t\tif (allReasonsCovered) {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\t...(lastGoodSigner !== undefined\n\t\t\t\t\t\t? { source: { type: 'crl', signerCertificate: lastGoodSigner } }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\t// Not all reasons covered — indeterminate\n\t\treturn {\n\t\t\tstatus: {\n\t\t\t\tcertificate: cert,\n\t\t\t\tstatus: 'indeterminate',\n\t\t\t\tindeterminateReasons: ['reason_coverage_incomplete'],\n\t\t\t},\n\t\t\texecutionErrors,\n\t\t};\n\t}\n\n\t// No applicable CRL found — determine most appropriate indeterminate reason\n\tconst reasons: RevocationIndeterminateReason[] = [];\n\tif (sawCrlSignerRevoked) {\n\t\treasons.push('crl_signer_revoked');\n\t} else if (sawCrlSignerIndeterminate) {\n\t\treasons.push('crl_signer_indeterminate');\n\t} else if (crls.length === 0) {\n\t\treasons.push('no_applicable_crl', 'no_applicable_ocsp');\n\t} else {\n\t\treasons.push('no_applicable_crl');\n\t}\n\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: reasons,\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Function\n// ---------------------------------------------------------------------------\n\n/**\n * Checks revocation status for all certificates in a validated chain.\n *\n * Evaluates CRL and OCSP evidence against each certificate (except the trust\n * anchor), applies the revocation policy, and returns a unified decision.\n *\n * @example\n * ```ts\n * const result = await checkChainRevocation({\n * chain: validatedChain,\n * crls: [crl1, crl2],\n * policy: { mode: 'hard-fail' },\n * });\n * if (result.value.decision === 'deny') {\n * console.log('Revocation check failed');\n * }\n * ```\n */\nexport async function checkChainRevocation(\n\tinput: CheckChainRevocationInput,\n): Promise<CheckChainRevocationResult> {\n\tconst { chain, policy, crls = [], extraCertificates = [], at = new Date() } = input;\n\tconst mode = policy?.mode ?? 'soft-fail';\n\n\t// Empty chain → allow\n\tif (chain.length === 0) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tdecision: 'allow',\n\t\t\t\tsummary: { revokedCertificates: [], indeterminateCertificates: [] },\n\t\t\t\tcertificates: [],\n\t\t\t},\n\t\t};\n\t}\n\n\t// Create signer validation context with memoization cache\n\t// This cache is shared across all certificate checks in this chain evaluation\n\tconst signerCtx: SignerValidationContext = {\n\t\tcache: new Map(),\n\t\tchain,\n\t\tcrls,\n\t\textraCertificates,\n\t\tat,\n\t};\n\n\t// Skip trust anchor (last cert) — it's the trust base\n\tconst certsToCheck = chain.slice(0, -1);\n\tconst certificates: CertificateRevocationStatus[] = [];\n\tconst revokedCertificates: ParsedCertificate[] = [];\n\tconst indeterminateCertificates: ParsedCertificate[] = [];\n\tconst allExecutionErrors: RevocationExecutionError[] = [];\n\n\tfor (let i = 0; i < certsToCheck.length; i++) {\n\t\tconst cert = certsToCheck[i];\n\t\tconst issuer = chain[i + 1]; // Next cert in chain is the issuer\n\t\tif (cert === undefined || issuer === undefined) {\n\t\t\tcontinue; // Should never happen given loop bounds\n\t\t}\n\n\t\tconst { status, executionErrors } = await evaluateCertificateRevocation(\n\t\t\tcert,\n\t\t\tissuer,\n\t\t\tinput,\n\t\t\tsignerCtx,\n\t\t);\n\t\tcertificates.push(status);\n\t\tallExecutionErrors.push(...executionErrors);\n\n\t\tif (status.status === 'revoked') {\n\t\t\trevokedCertificates.push(cert);\n\t\t} else if (status.status === 'indeterminate') {\n\t\t\tindeterminateCertificates.push(cert);\n\t\t}\n\t}\n\n\t// Apply policy\n\tconst hasRevoked = revokedCertificates.length > 0;\n\tconst hasIndeterminate = indeterminateCertificates.length > 0;\n\tconst decision: 'allow' | 'deny' = hasRevoked\n\t\t? 'deny'\n\t\t: hasIndeterminate && mode === 'hard-fail'\n\t\t\t? 'deny'\n\t\t\t: 'allow';\n\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tdecision,\n\t\t\tsummary: { revokedCertificates, indeterminateCertificates },\n\t\t\tcertificates,\n\t\t\t...(allExecutionErrors.length > 0 ? { executionErrors: allExecutionErrors } : {}),\n\t\t},\n\t};\n}\n"],"mappings":"4MAqOA,SAAS,EAAmB,EAAoD,CAO/E,OANI,OAAO,GAAW,UAAY,WAAY,EACtC,EAEJ,OAAO,GAAW,SACd,EAAkC,CAAM,EAEzC,EAAkC,CAAM,CAChD,CAKA,SAAS,EAAqB,EAA0D,CACvF,GAAI,CACH,OAAO,EAA2B,CAAM,CACzC,MAAQ,CACP,MACD,CACD,CAMA,SAAS,EAAgB,EAAsB,EAA+B,CAC7E,GAAI,EAAE,IAAI,SAAW,EAAE,IAAI,OAAQ,MAAO,GAC1C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAE,IAAI,OAAQ,IACjC,GAAI,EAAE,IAAI,KAAO,EAAE,IAAI,GAAI,MAAO,GAEnC,MAAO,EACR,CAMA,SAAS,EACR,EACA,EACA,EACgC,CAGhC,IAAM,EAAoC,CAAC,EAC3C,IAAK,IAAM,KAAU,EAAmB,CACvC,IAAM,EAAS,EAAqB,CAAM,EACtC,IAAW,IAAA,IACd,EAAa,KAAK,CAAM,CAE1B,CAEA,IAAM,EAAa,CAAC,GAAG,EAAc,GAAG,CAAK,EAG7C,GAAI,EAAI,yBAA2B,IAAA,QAC7B,IAAM,KAAa,EACvB,GACC,EAAU,uBAAyB,IAAA,IACnC,EAAa,EAAI,sBAAsB,IAAM,EAAa,EAAU,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,IAAK,CAC7C,IAAM,EAAO,EAAa,GACpB,EAAS,EAAM,EAAI,GACzB,GAAI,IAAS,IAAA,IAAa,IAAW,IAAA,GACpC,SAGD,GAAM,CAAE,SAAQ,mBAAoB,MAAM,EACzC,EACA,EACA,EACA,CACD,EACA,EAAa,KAAK,CAAM,EACxB,EAAmB,KAAK,GAAG,CAAe,EAEtC,EAAO,SAAW,UACrB,EAAoB,KAAK,CAAI,EACnB,EAAO,SAAW,iBAC5B,EAA0B,KAAK,CAAI,CAErC,CAGA,IAAM,EAAa,EAAoB,OAAS,EAC1C,EAAmB,EAA0B,OAAS,EAO5D,MAAO,CACN,GAAI,GACJ,MAAO,CACN,SATiC,GAEhC,GAAoB,IAAS,YAD7B,OAGC,QAMF,QAAS,CAAE,sBAAqB,2BAA0B,EAC1D,eACA,GAAI,EAAmB,OAAS,EAAI,CAAE,gBAAiB,CAAmB,EAAI,CAAC,CAChF,CACD,CACD"}
|
|
1
|
+
{"version":3,"file":"chain.js","names":[],"sources":["../../src/revocation/chain.ts"],"sourcesContent":["/**\n * Chain-level revocation orchestration.\n *\n * Evaluates CRL and OCSP evidence for an entire validated certificate chain,\n * implementing the revocation checking portion of RFC 5280 §6.3.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#section-6.3 | RFC 5280 §6.3 CRL Validation}\n * @module\n */\n\nimport type { ParsedCertificate } from '#micro509/x509/parse.ts';\nimport { parseCertificateFromSource } from '#micro509/x509/parse.ts';\nimport {\n\tcheckCertificateRevocationAgainstCrl,\n\tparseCertificateRevocationListDer,\n\tparseCertificateRevocationListPem,\n\ttype ParsedCertificateRevocationList,\n\ttype RevocationReason,\n\trevocationReasonFromCode,\n} from './crl.ts';\nimport type { CrlSource } from './crl.ts';\nimport {\n\ttype ParsedOcspResponse,\n\tparseOcspResponseDer,\n\tparseOcspResponsePem,\n\ttype ValidateOcspResponseFailure,\n\ttype ValidateOcspResponseResult,\n\tvalidateOcspResponse,\n} from './ocsp.ts';\n\nexport type { CrlSource };\n\n// ---------------------------------------------------------------------------\n// Input Types\n// ---------------------------------------------------------------------------\n\n/**\n * Certificate in any supported format.\n *\n * Accepts PEM string, DER bytes, or an already-parsed {@linkcode ParsedCertificate}.\n * Used for {@linkcode CheckChainRevocationInput.extraCertificates}.\n */\nexport type CertificateSource = string | Uint8Array | ParsedCertificate;\n\n/**\n * OCSP response in any supported format.\n *\n * Accepts PEM string or DER bytes. Used for\n * {@linkcode CheckChainRevocationInput.ocspResponses}.\n */\nexport type OcspResponseSource = string | Uint8Array;\n\n/**\n * Revocation checking policy for {@linkcode checkChainRevocation}.\n *\n * Controls how indeterminate results (missing evidence, expired CRLs) affect\n * the final {@linkcode CheckChainRevocationValue.decision | decision}.\n */\nexport interface RevocationPolicy {\n\t/**\n\t * How to handle indeterminate status.\n\t *\n\t * - `'soft-fail'`: indeterminate certificates are allowed (default)\n\t * - `'hard-fail'`: indeterminate certificates cause denial\n\t */\n\treadonly mode?: 'soft-fail' | 'hard-fail';\n\t/**\n\t * Evidence preference when multiple sources are available.\n\t *\n\t * Both evidence kinds are always evaluated, and a validated `revoked`\n\t * verdict from either source wins regardless of preference (fail-closed).\n\t * Preference only decides which source's `good` verdict is reported when\n\t * both yield one.\n\t *\n\t * - `'best-available'`: OCSP consulted first, CRL as fallback (default)\n\t * - `'ocsp'`: prefer OCSP over CRL\n\t * - `'crl'`: prefer CRL over OCSP\n\t */\n\treadonly prefer?: 'ocsp' | 'crl' | 'best-available';\n}\n\n/** Input for {@linkcode checkChainRevocation}. */\nexport interface CheckChainRevocationInput {\n\t/** Validated certificate chain (leaf first, root last). */\n\treadonly chain: readonly ParsedCertificate[];\n\t/** CRLs to evaluate. */\n\treadonly crls?: readonly CrlSource[];\n\t/** OCSP responses to evaluate. */\n\treadonly ocspResponses?: readonly OcspResponseSource[];\n\t/** Extra certs for indirect CRL issuers / delegated OCSP responders. */\n\treadonly extraCertificates?: readonly CertificateSource[];\n\t/** Evaluation time. Defaults to `new Date()`. */\n\treadonly at?: Date;\n\t/** Revocation policy. */\n\treadonly policy?: RevocationPolicy;\n}\n\n// ---------------------------------------------------------------------------\n// Output Types\n// ---------------------------------------------------------------------------\n\n/**\n * Granular reasons why revocation status could not be determined.\n *\n * Returned in {@linkcode CertificateRevocationStatus.indeterminateReasons} when\n * `status` is `'indeterminate'`. Grouped by category:\n *\n * - **Evidence not found**: `no_applicable_crl`, `no_applicable_ocsp`\n * - **Scope mismatch**: `distribution_point_mismatch`, `issuer_name_mismatch`,\n * `reason_scope_mismatch`, `indirect_crl_scope_mismatch`, `reason_coverage_incomplete`\n * - **Signer trust**: `crl_signer_not_found`, `crl_signer_not_authorized`,\n * `crl_signer_revoked`, `crl_signer_indeterminate`, and OCSP equivalents\n * - **Freshness**: `crl_expired`, `ocsp_response_expired`\n */\nexport type RevocationIndeterminateReason =\n\t// Evidence not found\n\t| 'no_applicable_crl'\n\t| 'no_applicable_ocsp'\n\t// Scope issues\n\t| 'distribution_point_mismatch'\n\t| 'issuer_name_mismatch'\n\t| 'reason_scope_mismatch'\n\t| 'indirect_crl_scope_mismatch'\n\t| 'reason_coverage_incomplete'\n\t// Signer trust issues\n\t| 'crl_signer_not_found'\n\t| 'crl_signer_not_authorized'\n\t| 'crl_signer_revoked'\n\t| 'crl_signer_indeterminate'\n\t| 'ocsp_responder_not_found'\n\t| 'ocsp_responder_not_authorized'\n\t| 'ocsp_responder_revoked'\n\t| 'ocsp_responder_indeterminate'\n\t// Freshness\n\t| 'crl_expired'\n\t| 'ocsp_response_expired'\n\t// OCSP specific\n\t| 'ocsp_status_unknown';\n\n/**\n * Identifies the source of revocation evidence.\n *\n * Included in {@linkcode CertificateRevocationStatus.source} when status is\n * `'good'` or `'revoked'` to indicate which CRL or OCSP response provided the answer.\n */\nexport interface RevocationSource {\n\t/** Whether evidence came from a CRL or OCSP response. */\n\treadonly type: 'crl' | 'ocsp';\n\t/** Certificate that signed the evidence (CRL issuer or OCSP responder). */\n\treadonly signerCertificate?: ParsedCertificate;\n\t/** Identifier for debugging (e.g., CRL issuer DN or OCSP responder URL). */\n\treadonly evidenceIdentifier?: string;\n}\n\n/**\n * Revocation evaluation result for a single certificate.\n *\n * One entry per certificate in {@linkcode CheckChainRevocationValue.certificates}.\n * The trust anchor is excluded (never checked for revocation).\n */\nexport interface CertificateRevocationStatus {\n\t/** The certificate that was evaluated. */\n\treadonly certificate: ParsedCertificate;\n\t/**\n\t * Revocation status determination.\n\t *\n\t * - `'good'`: evidence confirms certificate is not revoked\n\t * - `'revoked'`: evidence confirms certificate is revoked\n\t * - `'indeterminate'`: could not determine status (see {@linkcode indeterminateReasons})\n\t */\n\treadonly status: 'good' | 'revoked' | 'indeterminate';\n\t/** Evidence source when status is `'good'` or `'revoked'`. */\n\treadonly source?: RevocationSource;\n\t/** Why status could not be determined. Present when `status` is `'indeterminate'`. */\n\treadonly indeterminateReasons?: readonly RevocationIndeterminateReason[];\n\t/** Revocation details. Present when `status` is `'revoked'`. */\n\treadonly revocationInfo?: {\n\t\t/** When the certificate was revoked. */\n\t\treadonly date: Date;\n\t\t/** RFC 5280 CRLReason code, if provided by the CRL/OCSP response. */\n\t\treadonly reason?: RevocationReason;\n\t};\n}\n\n/**\n * Errors encountered while processing revocation evidence.\n *\n * Distinct from {@linkcode RevocationIndeterminateReason}: execution errors are\n * code failures (malformed CRL, unsupported extension) rather than evaluation\n * outcomes (CRL doesn't cover this certificate).\n *\n * Collected in {@linkcode CheckChainRevocationValue.executionErrors}.\n */\nexport interface RevocationExecutionError {\n\t/** Error category. */\n\treadonly kind: 'parse_error' | 'unsupported_extension' | 'internal_error';\n\t/** Human-readable error description. */\n\treadonly message: string;\n\t/** Which evidence caused the error (e.g., CRL issuer DN). */\n\treadonly evidenceIdentifier?: string;\n}\n\n/**\n * Detailed revocation check results.\n *\n * Returned as {@linkcode CheckChainRevocationResult.value} from\n * {@linkcode checkChainRevocation}. Contains both the policy decision and\n * detailed per-certificate findings for debugging.\n */\nexport interface CheckChainRevocationValue {\n\t/**\n\t * Final policy decision based on {@linkcode RevocationPolicy}.\n\t *\n\t * - `'allow'`: chain passes revocation check\n\t * - `'deny'`: chain fails (revoked certificate or hard-fail on indeterminate)\n\t */\n\treadonly decision: 'allow' | 'deny';\n\t/** Quick-access summary of problematic certificates. */\n\treadonly summary: {\n\t\t/** Certificates confirmed as revoked. */\n\t\treadonly revokedCertificates: readonly ParsedCertificate[];\n\t\t/** Certificates whose status could not be determined. */\n\t\treadonly indeterminateCertificates: readonly ParsedCertificate[];\n\t};\n\t/** Per-certificate evaluation results. See {@linkcode CertificateRevocationStatus}. */\n\treadonly certificates: readonly CertificateRevocationStatus[];\n\t/** Evidence that could not be processed. See {@linkcode RevocationExecutionError}. */\n\treadonly executionErrors?: readonly RevocationExecutionError[];\n}\n\n/** Result type for {@linkcode checkChainRevocation}. */\nexport type CheckChainRevocationResult = {\n\treadonly ok: true;\n\treadonly value: CheckChainRevocationValue;\n};\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parses a CRL from various source formats.\n */\nfunction parseCrlFromSource(source: CrlSource): ParsedCertificateRevocationList {\n\tif (typeof source === 'object' && 'issuer' in source) {\n\t\treturn source;\n\t}\n\tif (typeof source === 'string') {\n\t\treturn parseCertificateRevocationListPem(source);\n\t}\n\treturn parseCertificateRevocationListDer(source);\n}\n\n/**\n * Parses a certificate from various source formats, returning undefined on failure.\n */\nfunction parseCertificateSafe(source: CertificateSource): ParsedCertificate | undefined {\n\ttry {\n\t\treturn parseCertificateFromSource(source);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Compares two certificates by DER bytes for identity.\n * Reference equality fails when same cert is parsed from different sources.\n */\nfunction sameCertificate(a: ParsedCertificate, b: ParsedCertificate): boolean {\n\tif (a.der.length !== b.der.length) return false;\n\tfor (let i = 0; i < a.der.length; i++) {\n\t\tif (a.der[i] !== b.der[i]) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Searches for a certificate that could have signed the given CRL.\n * Matches by AKI/SKI or issuer/subject DN.\n */\nfunction findIndirectCrlIssuer(\n\tcrl: ParsedCertificateRevocationList,\n\textraCertificates: readonly CertificateSource[],\n\tchain: readonly ParsedCertificate[],\n): ParsedCertificate | undefined {\n\t// Combine extra certs with chain certs for searching\n\t// Chain certs are already parsed; extra certs may need parsing\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...parsedExtras, ...chain];\n\n\t// First pass: prefer AKI/SKI match (more specific)\n\tif (crl.authorityKeyIdentifier !== undefined) {\n\t\tfor (const candidate of candidates) {\n\t\t\tif (\n\t\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\t\tnormalizeHex(crl.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t\t) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: fall back to DN match\n\tfor (const candidate of candidates) {\n\t\tif (crl.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/** Lowercases a hex string for bytewise comparison. */\nfunction normalizeHex(value: string): string {\n\treturn value.toLowerCase();\n}\n\n// ---------------------------------------------------------------------------\n// CRL Signer Validation (RFC 5280 §6.3.3)\n// ---------------------------------------------------------------------------\n\n/**\n * State machine for CRL signer validation with memoization.\n * - `visiting`: Currently being checked (cycle detection)\n * - `resolved-valid`: Signer is not revoked\n * - `resolved-revoked`: Signer is revoked\n * - `resolved-indeterminate`: Can't determine signer status\n */\ntype SignerValidationState =\n\t| 'visiting'\n\t| 'resolved-valid'\n\t| 'resolved-revoked'\n\t| 'resolved-indeterminate';\n\n/** Context for CRL signer validation with memoization cache. */\ninterface SignerValidationContext {\n\treadonly cache: Map<string, SignerValidationState>;\n\treadonly chain: readonly ParsedCertificate[];\n\treadonly crls: readonly CrlSource[];\n\treadonly extraCertificates: readonly CertificateSource[];\n\treadonly at: Date;\n}\n\n/**\n * Builds a unique cache key for a certificate.\n * Uses issuer DN + serial number which uniquely identifies a cert.\n */\nfunction certCacheKey(cert: ParsedCertificate): string {\n\treturn `${cert.issuer.derHex}:${cert.serialNumberHex}`;\n}\n\n/**\n * Validates that a CRL signer certificate is not revoked.\n * Uses memoization to avoid redundant checks and detect cycles.\n */\nasync function validateCrlSigner(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// Use issuer+serial as cache key (unique per certificate)\n\tconst key = certCacheKey(signer);\n\tconst cached = ctx.cache.get(key);\n\n\t// Cycle detection: if we're already visiting this signer, it's indeterminate\n\tif (cached === 'visiting') {\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Return cached result if already resolved\n\tif (cached !== undefined) {\n\t\treturn cached;\n\t}\n\n\t// Mark as visiting before recursive checks\n\tctx.cache.set(key, 'visiting');\n\n\t// Trust anchor (last in chain) is trusted by definition\n\tconst trustAnchor = ctx.chain[ctx.chain.length - 1];\n\tif (trustAnchor !== undefined && sameCertificate(signer, trustAnchor)) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// If signer is in the validated chain, it's trusted\n\t// (Chain was already validated before revocation checking)\n\tconst isInChain = ctx.chain.some((c) => sameCertificate(c, signer));\n\tif (isInChain) {\n\t\tctx.cache.set(key, 'resolved-valid');\n\t\treturn 'resolved-valid';\n\t}\n\n\t// Signer is not in chain — need to check its revocation status\n\t// Find signer's issuer to perform revocation check\n\tconst signerIssuer = findSignerIssuer(signer, ctx);\n\tif (signerIssuer === undefined) {\n\t\tctx.cache.set(key, 'resolved-indeterminate');\n\t\treturn 'resolved-indeterminate';\n\t}\n\n\t// Check signer's revocation status (recursive)\n\tconst signerRevocation = await checkSignerRevocation(signer, signerIssuer, ctx);\n\tctx.cache.set(key, signerRevocation);\n\treturn signerRevocation;\n}\n\n/**\n * Finds the issuer certificate for a CRL signer.\n * Searches the chain and extraCertificates by AKI/SKI or DN matching.\n */\nfunction findSignerIssuer(\n\tsigner: ParsedCertificate,\n\tctx: SignerValidationContext,\n): ParsedCertificate | undefined {\n\t// Parse extra certificates\n\tconst parsedExtras: ParsedCertificate[] = [];\n\tfor (const source of ctx.extraCertificates) {\n\t\tconst parsed = parseCertificateSafe(source);\n\t\tif (parsed !== undefined) {\n\t\t\tparsedExtras.push(parsed);\n\t\t}\n\t}\n\n\tconst candidates = [...ctx.chain, ...parsedExtras];\n\n\tfor (const candidate of candidates) {\n\t\t// Match by AKI → SKI (preferred, more specific)\n\t\tif (\n\t\t\tsigner.authorityKeyIdentifier !== undefined &&\n\t\t\tcandidate.subjectKeyIdentifier !== undefined &&\n\t\t\tnormalizeHex(signer.authorityKeyIdentifier) === normalizeHex(candidate.subjectKeyIdentifier)\n\t\t) {\n\t\t\treturn candidate;\n\t\t}\n\n\t\t// Match by issuer DN → subject DN\n\t\tif (signer.issuer.derHex === candidate.subject.derHex) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Checks if a CRL signer certificate is revoked by examining available CRLs.\n * Recursively validates the CRL signer of any CRL used to check revocation.\n */\nasync function checkSignerRevocation(\n\tsigner: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tctx: SignerValidationContext,\n): Promise<SignerValidationState> {\n\t// If the signer's issuer is in the validated chain, the signer is trusted\n\t// by virtue of being issued by a trusted CA. We only need to check if\n\t// it's explicitly revoked, not prove \"good\" status.\n\tconst issuerInChain = ctx.chain.some((c) => sameCertificate(c, issuer));\n\n\t// Try each CRL to check signer's revocation\n\tfor (const crlSource of ctx.crls) {\n\t\tlet crl: ParsedCertificateRevocationList;\n\t\ttry {\n\t\t\tcrl = parseCrlFromSource(crlSource);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if this CRL can provide revocation info for the signer\n\t\tconst result = await checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: signer,\n\t\t\tissuerCertificate: issuer,\n\t\t\tcrl,\n\t\t\tat: ctx.at,\n\t\t});\n\n\t\tif (result.ok) {\n\t\t\tif (result.value.status === 'revoked') {\n\t\t\t\treturn 'resolved-revoked';\n\t\t\t}\n\t\t\tif (result.value.status === 'good') {\n\t\t\t\t// Before accepting this result, validate the CRL's signer\n\t\t\t\t// The CRL's signer is the issuer we just used\n\t\t\t\tconst crlSignerStatus = await validateCrlSigner(issuer, ctx);\n\t\t\t\tif (crlSignerStatus === 'resolved-valid') {\n\t\t\t\t\treturn 'resolved-valid';\n\t\t\t\t}\n\t\t\t\t// If CRL signer is revoked or indeterminate, can't trust this result\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the signer's issuer is in the chain and we found no revocation,\n\t// trust the signer (issued by trusted CA, no evidence of revocation)\n\tif (issuerInChain) {\n\t\treturn 'resolved-valid';\n\t}\n\n\treturn 'resolved-indeterminate';\n}\n\n/** Builds a CertificateRevocationStatus for a CRL check result. */\nfunction buildCrlStatus(\n\tcert: ParsedCertificate,\n\tsigner: ParsedCertificate,\n\tstatus: 'good' | 'revoked',\n\trevocationDate?: Date,\n\treasonCode?: RevocationReason,\n): CertificateRevocationStatus {\n\tif (status === 'revoked' && revocationDate !== undefined) {\n\t\treturn {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'revoked',\n\t\t\tsource: { type: 'crl', signerCertificate: signer },\n\t\t\trevocationInfo: {\n\t\t\t\tdate: revocationDate,\n\t\t\t\t...(reasonCode !== undefined ? { reason: reasonCode } : {}),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tcertificate: cert,\n\t\tstatus: 'good',\n\t\tsource: { type: 'crl', signerCertificate: signer },\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// OCSP Evidence Evaluation (RFC 6960)\n// ---------------------------------------------------------------------------\n\n/** Per-certificate evidence evaluation outcome shared by the CRL and OCSP evaluators. */\ninterface EvidenceEvaluation {\n\treadonly status: CertificateRevocationStatus;\n\treadonly executionErrors: readonly RevocationExecutionError[];\n}\n\n/** Parses an OCSP response from PEM string or DER bytes. */\nfunction parseOcspResponseFromSource(source: OcspResponseSource): ParsedOcspResponse {\n\tif (typeof source === 'string') {\n\t\treturn parseOcspResponsePem(source);\n\t}\n\treturn parseOcspResponseDer(source);\n}\n\n/** Maps a {@linkcode validateOcspResponse} failure code to an indeterminate reason. */\nfunction ocspIndeterminateReasonFromFailure(\n\tcode: ValidateOcspResponseFailure['code'],\n): RevocationIndeterminateReason {\n\tswitch (code) {\n\t\tcase 'stale_response':\n\t\t\treturn 'ocsp_response_expired';\n\t\tcase 'responder_id_mismatch':\n\t\tcase 'responder_chain_invalid':\n\t\tcase 'ocsp_signing_missing':\n\t\t\treturn 'ocsp_responder_not_authorized';\n\t\tcase 'signature_invalid':\n\t\t\treturn 'ocsp_responder_indeterminate';\n\t\tcase 'response_status_invalid':\n\t\tcase 'issuer_mismatch':\n\t\tcase 'nonce_mismatch':\n\t\tcase 'request_mismatch':\n\t\t\treturn 'no_applicable_ocsp';\n\t}\n}\n\n/** Validation failures worth retrying with an explicit responder certificate. */\nconst OCSP_RESPONDER_FAILURE_CODES: ReadonlySet<ValidateOcspResponseFailure['code']> = new Set([\n\t'signature_invalid',\n\t'responder_id_mismatch',\n\t'responder_chain_invalid',\n\t'ocsp_signing_missing',\n]);\n\n/**\n * Validates an OCSP response, retrying with caller-provided extra certificates\n * as explicit responder certificates when embedded discovery fails.\n */\nasync function validateOcspResponseWithResponderFallback(\n\tresponse: ParsedOcspResponse,\n\tissuer: ParsedCertificate,\n\textraCertificates: readonly CertificateSource[],\n\tat: Date,\n): Promise<ValidateOcspResponseResult> {\n\tconst primary = await validateOcspResponse({ response, issuerCertificate: issuer, at });\n\tif (primary.ok || !OCSP_RESPONDER_FAILURE_CODES.has(primary.code)) {\n\t\treturn primary;\n\t}\n\tfor (const source of extraCertificates) {\n\t\tconst responder = parseCertificateSafe(source);\n\t\tif (responder === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst retry = await validateOcspResponse({\n\t\t\tresponse,\n\t\t\tissuerCertificate: issuer,\n\t\t\tresponderCertificate: responder,\n\t\t\tat,\n\t\t});\n\t\tif (retry.ok) {\n\t\t\treturn retry;\n\t\t}\n\t}\n\treturn primary;\n}\n\n/**\n * Evaluates OCSP evidence for a single certificate (RFC 6960).\n *\n * Every response is fully validated — signature, responder binding and\n * authorization, and freshness — via {@linkcode validateOcspResponse} before\n * its status entry is trusted. Issuer binding of each CertID is enforced by\n * the validator, so a serial-number match on a validated response is\n * sufficient to attribute the entry to `cert`.\n */\nasync function evaluateOcspEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n): Promise<EvidenceEvaluation> {\n\tconst { ocspResponses = [], extraCertificates = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\n\tfor (const source of ocspResponses) {\n\t\tlet parsed: ParsedOcspResponse;\n\t\ttry {\n\t\t\tparsed = parseOcspResponseFromSource(source);\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'OCSP response parse failed',\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst entry = (parsed.responses ?? []).find(\n\t\t\t(single) =>\n\t\t\t\tnormalizeHex(single.certId.serialNumberHex) === normalizeHex(cert.serialNumberHex),\n\t\t);\n\t\tif (entry === undefined) {\n\t\t\tcontinue; // Response does not cover this certificate\n\t\t}\n\n\t\tconst validation = await validateOcspResponseWithResponderFallback(\n\t\t\tparsed,\n\t\t\tissuer,\n\t\t\textraCertificates,\n\t\t\tat,\n\t\t);\n\t\tif (!validation.ok) {\n\t\t\treasons.add(ocspIndeterminateReasonFromFailure(validation.code));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.certStatus === 'revoked') {\n\t\t\tconst reason = revocationReasonFromCode(entry.revocationReasonCode);\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'revoked',\n\t\t\t\t\tsource: { type: 'ocsp' },\n\t\t\t\t\trevocationInfo: {\n\t\t\t\t\t\tdate: entry.revokedAt ?? entry.thisUpdate,\n\t\t\t\t\t\t...(reason !== undefined ? { reason } : {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\tif (entry.certStatus === 'good') {\n\t\t\treturn {\n\t\t\t\tstatus: { certificate: cert, status: 'good', source: { type: 'ocsp' } },\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\treasons.add('ocsp_status_unknown');\n\t}\n\n\tif (reasons.size === 0) {\n\t\treasons.add('no_applicable_ocsp');\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate using available CRLs.\n * Returns both status and any execution errors encountered.\n *\n * Tries the chain issuer first; if that fails, searches extraCertificates\n * and chain for an indirect CRL issuer that matches the CRL's AKI or issuer DN.\n *\n * Also validates that CRL signers are not revoked (RFC 5280 §6.3.3).\n */\n// RFC 5280 ReasonFlags — all possible revocation reasons that CRLs can cover.\nconst ALL_REASON_FLAGS: readonly string[] = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n];\n\nasync function evaluateCrlEvidence(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst { crls = [], extraCertificates = [], chain = [], at = new Date() } = input;\n\tconst executionErrors: RevocationExecutionError[] = [];\n\tlet sawCrlSignerRevoked = false;\n\tlet sawCrlSignerIndeterminate = false;\n\tlet sawGood = false;\n\tlet lastGoodSigner: ParsedCertificate | undefined;\n\tconst coveredReasons = new Set<string>();\n\n\t// Parse all CRLs and separate base CRLs from delta CRLs\n\tconst parsedCrls: ParsedCertificateRevocationList[] = [];\n\tfor (const crlSource of crls) {\n\t\ttry {\n\t\t\tparsedCrls.push(parseCrlFromSource(crlSource));\n\t\t} catch (e) {\n\t\t\texecutionErrors.push({\n\t\t\t\tkind: 'parse_error',\n\t\t\t\tmessage: e instanceof Error ? e.message : 'CRL parse failed',\n\t\t\t});\n\t\t}\n\t}\n\n\tconst baseCrls = parsedCrls.filter((crl) => crl.baseCrlNumber === undefined);\n\tconst deltaCrls = parsedCrls.filter((crl) => crl.baseCrlNumber !== undefined);\n\n\t// Helper to check CRL with given issuer and optional delta\n\tconst checkWithIssuer = async (\n\t\tcrl: ParsedCertificateRevocationList,\n\t\tdeltaCrl: ParsedCertificateRevocationList | undefined,\n\t\tcrlIssuer: ParsedCertificate,\n\t) => {\n\t\treturn checkCertificateRevocationAgainstCrl({\n\t\t\tcertificate: cert,\n\t\t\tissuerCertificate: crlIssuer,\n\t\t\tcrl,\n\t\t\t...(deltaCrl !== undefined ? { deltaCrl } : {}),\n\t\t\tat,\n\t\t});\n\t};\n\n\t// Process base CRLs (optionally paired with delta CRLs)\n\tfor (const baseCrl of baseCrls) {\n\t\t// Find applicable delta CRL for this base CRL (if any)\n\t\t// Delta CRL applies if it has the same issuer and crlNumber matches baseCrlNumber\n\t\tconst applicableDelta = deltaCrls.find(\n\t\t\t(d) =>\n\t\t\t\td.issuer.derHex === baseCrl.issuer.derHex &&\n\t\t\t\td.baseCrlNumber !== undefined &&\n\t\t\t\tbaseCrl.crlNumber !== undefined &&\n\t\t\t\tBigInt(d.baseCrlNumber) <= BigInt(baseCrl.crlNumber),\n\t\t);\n\n\t\t// Try chain issuer first\n\t\tlet result = await checkWithIssuer(baseCrl, applicableDelta, issuer);\n\t\tlet effectiveSigner = issuer;\n\n\t\t// Chain issuer failed — try to find indirect CRL issuer\n\t\tif (!result.ok) {\n\t\t\tconst indirectIssuer = findIndirectCrlIssuer(baseCrl, extraCertificates, chain);\n\t\t\tif (indirectIssuer !== undefined && !sameCertificate(indirectIssuer, issuer)) {\n\t\t\t\tresult = await checkWithIssuer(baseCrl, applicableDelta, indirectIssuer);\n\t\t\t\teffectiveSigner = indirectIssuer;\n\t\t\t}\n\t\t}\n\n\t\tif (!result.ok) {\n\t\t\tcontinue; // CRL doesn't apply to this certificate\n\t\t}\n\n\t\t// Validate CRL signer is not revoked before accepting result\n\t\tconst signerStatus = await validateCrlSigner(effectiveSigner, signerCtx);\n\t\tif (signerStatus === 'resolved-revoked') {\n\t\t\tsawCrlSignerRevoked = true;\n\t\t\tcontinue; // CRL signer revoked — can't trust this CRL\n\t\t}\n\t\tif (signerStatus === 'resolved-indeterminate') {\n\t\t\tsawCrlSignerIndeterminate = true;\n\t\t\tcontinue; // CRL signer status unknown — try other CRLs\n\t\t}\n\n\t\t// CRL is valid — check result\n\t\tif (result.value.status === 'revoked') {\n\t\t\t// Immediately return revoked status\n\t\t\treturn {\n\t\t\t\tstatus: buildCrlStatus(\n\t\t\t\t\tcert,\n\t\t\t\t\teffectiveSigner,\n\t\t\t\t\t'revoked',\n\t\t\t\t\tresult.value.revocationDate,\n\t\t\t\t\tresult.value.reasonCode,\n\t\t\t\t),\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\n\t\t// Status is 'good' — track which reasons this CRL covers\n\t\tsawGood = true;\n\t\tlastGoodSigner = effectiveSigner;\n\t\tconst crlReasons = baseCrl.issuingDistributionPoint?.onlySomeReasons?.flags;\n\t\tif (crlReasons === undefined) {\n\t\t\t// CRL covers all reasons\n\t\t\tfor (const reason of ALL_REASON_FLAGS) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t} else {\n\t\t\t// CRL only covers specific reasons\n\t\t\tfor (const reason of crlReasons) {\n\t\t\t\tcoveredReasons.add(reason);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return 'good' only if we saw at least one good result AND all reasons are covered\n\tif (sawGood) {\n\t\tconst allReasonsCovered = ALL_REASON_FLAGS.every((r) => coveredReasons.has(r));\n\t\tif (allReasonsCovered) {\n\t\t\treturn {\n\t\t\t\tstatus: {\n\t\t\t\t\tcertificate: cert,\n\t\t\t\t\tstatus: 'good',\n\t\t\t\t\t...(lastGoodSigner !== undefined\n\t\t\t\t\t\t? { source: { type: 'crl', signerCertificate: lastGoodSigner } }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\texecutionErrors,\n\t\t\t};\n\t\t}\n\t\t// Not all reasons covered — indeterminate\n\t\treturn {\n\t\t\tstatus: {\n\t\t\t\tcertificate: cert,\n\t\t\t\tstatus: 'indeterminate',\n\t\t\t\tindeterminateReasons: ['reason_coverage_incomplete'],\n\t\t\t},\n\t\t\texecutionErrors,\n\t\t};\n\t}\n\n\t// No applicable CRL found — determine most appropriate indeterminate reason\n\tconst reasons: RevocationIndeterminateReason[] = [];\n\tif (sawCrlSignerRevoked) {\n\t\treasons.push('crl_signer_revoked');\n\t} else if (sawCrlSignerIndeterminate) {\n\t\treasons.push('crl_signer_indeterminate');\n\t} else {\n\t\treasons.push('no_applicable_crl');\n\t}\n\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: reasons,\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n/**\n * Evaluates revocation status for a single certificate by combining OCSP and\n * CRL evidence.\n *\n * Both evidence kinds are always evaluated: a validated `revoked` verdict from\n * either source wins regardless of {@linkcode RevocationPolicy.prefer}\n * (fail-closed). Otherwise the preferred source's `good` verdict is reported;\n * if neither source is definitive, indeterminate reasons from both are merged.\n */\nasync function evaluateCertificateRevocation(\n\tcert: ParsedCertificate,\n\tissuer: ParsedCertificate,\n\tinput: CheckChainRevocationInput,\n\tsignerCtx: SignerValidationContext,\n): Promise<EvidenceEvaluation> {\n\tconst prefer = input.policy?.prefer ?? 'best-available';\n\tconst ocsp = await evaluateOcspEvidence(cert, issuer, input);\n\tconst crl = await evaluateCrlEvidence(cert, issuer, input, signerCtx);\n\tconst executionErrors = [...ocsp.executionErrors, ...crl.executionErrors];\n\n\tconst ordered = prefer === 'crl' ? [crl, ocsp] : [ocsp, crl];\n\tconst revoked = ordered.find((evaluation) => evaluation.status.status === 'revoked');\n\tif (revoked !== undefined) {\n\t\treturn { status: revoked.status, executionErrors };\n\t}\n\tconst good = ordered.find((evaluation) => evaluation.status.status === 'good');\n\tif (good !== undefined) {\n\t\treturn { status: good.status, executionErrors };\n\t}\n\n\tconst reasons = new Set<RevocationIndeterminateReason>();\n\tfor (const evaluation of ordered) {\n\t\tfor (const reason of evaluation.status.indeterminateReasons ?? []) {\n\t\t\treasons.add(reason);\n\t\t}\n\t}\n\treturn {\n\t\tstatus: {\n\t\t\tcertificate: cert,\n\t\t\tstatus: 'indeterminate',\n\t\t\tindeterminateReasons: [...reasons],\n\t\t},\n\t\texecutionErrors,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Function\n// ---------------------------------------------------------------------------\n\n/**\n * Checks revocation status for all certificates in a validated chain.\n *\n * Evaluates CRL and OCSP evidence against each certificate (except the trust\n * anchor), applies the revocation policy, and returns a unified decision.\n *\n * @example\n * ```ts\n * const result = await checkChainRevocation({\n * chain: validatedChain,\n * crls: [crl1, crl2],\n * ocspResponses: [ocspResponseDer],\n * policy: { mode: 'hard-fail' },\n * });\n * if (result.value.decision === 'deny') {\n * console.log('Revocation check failed');\n * }\n * ```\n */\nexport async function checkChainRevocation(\n\tinput: CheckChainRevocationInput,\n): Promise<CheckChainRevocationResult> {\n\tconst { chain, policy, crls = [], extraCertificates = [], at = new Date() } = input;\n\tconst mode = policy?.mode ?? 'soft-fail';\n\n\t// Empty chain → allow\n\tif (chain.length === 0) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tdecision: 'allow',\n\t\t\t\tsummary: { revokedCertificates: [], indeterminateCertificates: [] },\n\t\t\t\tcertificates: [],\n\t\t\t},\n\t\t};\n\t}\n\n\t// Create signer validation context with memoization cache\n\t// This cache is shared across all certificate checks in this chain evaluation\n\tconst signerCtx: SignerValidationContext = {\n\t\tcache: new Map(),\n\t\tchain,\n\t\tcrls,\n\t\textraCertificates,\n\t\tat,\n\t};\n\n\t// Skip trust anchor (last cert) — it's the trust base\n\tconst certsToCheck = chain.slice(0, -1);\n\tconst certificates: CertificateRevocationStatus[] = [];\n\tconst revokedCertificates: ParsedCertificate[] = [];\n\tconst indeterminateCertificates: ParsedCertificate[] = [];\n\tconst allExecutionErrors: RevocationExecutionError[] = [];\n\n\tfor (let i = 0; i < certsToCheck.length; i++) {\n\t\tconst cert = certsToCheck[i];\n\t\tconst issuer = chain[i + 1]; // Next cert in chain is the issuer\n\t\tif (cert === undefined || issuer === undefined) {\n\t\t\tcontinue; // Should never happen given loop bounds\n\t\t}\n\n\t\tconst { status, executionErrors } = await evaluateCertificateRevocation(\n\t\t\tcert,\n\t\t\tissuer,\n\t\t\tinput,\n\t\t\tsignerCtx,\n\t\t);\n\t\tcertificates.push(status);\n\t\tallExecutionErrors.push(...executionErrors);\n\n\t\tif (status.status === 'revoked') {\n\t\t\trevokedCertificates.push(cert);\n\t\t} else if (status.status === 'indeterminate') {\n\t\t\tindeterminateCertificates.push(cert);\n\t\t}\n\t}\n\n\t// Apply policy\n\tconst hasRevoked = revokedCertificates.length > 0;\n\tconst hasIndeterminate = indeterminateCertificates.length > 0;\n\tconst decision: 'allow' | 'deny' = hasRevoked\n\t\t? 'deny'\n\t\t: hasIndeterminate && mode === 'hard-fail'\n\t\t\t? 'deny'\n\t\t\t: 'allow';\n\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tdecision,\n\t\t\tsummary: { revokedCertificates, indeterminateCertificates },\n\t\t\tcertificates,\n\t\t\t...(allExecutionErrors.length > 0 ? { executionErrors: allExecutionErrors } : {}),\n\t\t},\n\t};\n}\n"],"mappings":"+UAmPA,SAAS,EAAmB,EAAoD,CAO/E,OANI,OAAO,GAAW,UAAY,WAAY,EACtC,EAEJ,OAAO,GAAW,SACd,EAAkC,CAAM,EAEzC,EAAkC,CAAM,CAChD,CAKA,SAAS,EAAqB,EAA0D,CACvF,GAAI,CACH,OAAO,EAA2B,CAAM,CACzC,MAAQ,CACP,MACD,CACD,CAMA,SAAS,EAAgB,EAAsB,EAA+B,CAC7E,GAAI,EAAE,IAAI,SAAW,EAAE,IAAI,OAAQ,MAAO,GAC1C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAE,IAAI,OAAQ,IACjC,GAAI,EAAE,IAAI,KAAO,EAAE,IAAI,GAAI,MAAO,GAEnC,MAAO,EACR,CAMA,SAAS,EACR,EACA,EACA,EACgC,CAGhC,IAAM,EAAoC,CAAC,EAC3C,IAAK,IAAM,KAAU,EAAmB,CACvC,IAAM,EAAS,EAAqB,CAAM,EACtC,IAAW,IAAA,IACd,EAAa,KAAK,CAAM,CAE1B,CAEA,IAAM,EAAa,CAAC,GAAG,EAAc,GAAG,CAAK,EAG7C,GAAI,EAAI,yBAA2B,IAAA,QAC7B,IAAM,KAAa,EACvB,GACC,EAAU,uBAAyB,IAAA,IACnC,EAAa,EAAI,sBAAsB,IAAM,EAAa,EAAU,oBAAoB,EAExF,OAAO,CAAA,CAMV,IAAK,IAAM,KAAa,EACvB,GAAI,EAAI,OAAO,SAAW,EAAU,QAAQ,OAC3C,OAAO,CAKV,CAGA,SAAS,EAAa,EAAuB,CAC5C,OAAO,EAAM,YAAY,CAC1B,CAgCA,SAAS,EAAa,EAAiC,CACtD,MAAO,GAAG,EAAK,OAAO,OAAO,GAAG,EAAK,iBACtC,CAMA,eAAe,EACd,EACA,EACiC,CAEjC,IAAM,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I,GACzB,GAAI,IAAS,IAAA,IAAa,IAAW,IAAA,GACpC,SAGD,GAAM,CAAE,SAAQ,mBAAoB,MAAM,EACzC,EACA,EACA,EACA,CACD,EACA,EAAa,KAAK,CAAM,EACxB,EAAmB,KAAK,GAAG,CAAe,EAEtC,EAAO,SAAW,UACrB,EAAoB,KAAK,CAAI,EACnB,EAAO,SAAW,iBAC5B,EAA0B,KAAK,CAAI,CAErC,CAGA,IAAM,EAAa,EAAoB,OAAS,EAC1C,EAAmB,EAA0B,OAAS,EAO5D,MAAO,CACN,GAAI,GACJ,MAAO,CACN,SATiC,GAEhC,GAAoB,IAAS,YAD7B,OAGC,QAMF,QAAS,CAAE,sBAAqB,2BAA0B,EAC1D,eACA,GAAI,EAAmB,OAAS,EAAI,CAAE,gBAAiB,CAAmB,EAAI,CAAC,CAChF,CACD,CACD"}
|
package/dist/revocation/crl.d.ts
CHANGED
|
@@ -311,6 +311,8 @@ declare function checkCertificateRevocationAgainstCrl(input: CheckCertificateRev
|
|
|
311
311
|
* CRL's revoked entries. Does **not** validate the CRL or check applicability.
|
|
312
312
|
*/
|
|
313
313
|
declare function isCertificateRevoked(certificateSerialNumber: Uint8Array | string, crl: ParsedCertificateRevocationList): boolean;
|
|
314
|
+
/** Maps an integer CRLReason code back to its {@linkcode RevocationReason} string, or `undefined` for unknown codes. */
|
|
315
|
+
declare function revocationReasonFromCode(code: number | undefined): RevocationReason | undefined;
|
|
314
316
|
//#endregion
|
|
315
|
-
export { CertificateRevocationListMaterial, CheckCertificateRevocationAgainstCrlErrorCode, CheckCertificateRevocationAgainstCrlFailure, CheckCertificateRevocationAgainstCrlFailureDetails, CheckCertificateRevocationAgainstCrlGoodValue, CheckCertificateRevocationAgainstCrlInput, CheckCertificateRevocationAgainstCrlResult, CheckCertificateRevocationAgainstCrlRevokedValue, CheckCertificateRevocationAgainstCrlValue, CreateCertificateRevocationListInput, CrlApplicabilityFailureReason, CrlCertificateSource, CrlSource, ParsedCertificateRevocationList, ParsedRevokedCertificate, RevocationReason, RevokedCertificateInput, ValidateCertificateRevocationListFailure, ValidateCertificateRevocationListInput, ValidateCertificateRevocationListResult, VerifyCertificateRevocationListFailure, VerifyCertificateRevocationListResult, checkCertificateRevocationAgainstCrl, createCertificateRevocationList, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListPem, validateCertificateRevocationList, verifyCertificateRevocationList };
|
|
317
|
+
export { CertificateRevocationListMaterial, CheckCertificateRevocationAgainstCrlErrorCode, CheckCertificateRevocationAgainstCrlFailure, CheckCertificateRevocationAgainstCrlFailureDetails, CheckCertificateRevocationAgainstCrlGoodValue, CheckCertificateRevocationAgainstCrlInput, CheckCertificateRevocationAgainstCrlResult, CheckCertificateRevocationAgainstCrlRevokedValue, CheckCertificateRevocationAgainstCrlValue, CreateCertificateRevocationListInput, CrlApplicabilityFailureReason, CrlCertificateSource, CrlSource, ParsedCertificateRevocationList, ParsedRevokedCertificate, RevocationReason, RevokedCertificateInput, ValidateCertificateRevocationListFailure, ValidateCertificateRevocationListInput, ValidateCertificateRevocationListResult, VerifyCertificateRevocationListFailure, VerifyCertificateRevocationListResult, checkCertificateRevocationAgainstCrl, createCertificateRevocationList, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListPem, revocationReasonFromCode, validateCertificateRevocationList, verifyCertificateRevocationList };
|
|
316
318
|
//# sourceMappingURL=crl.d.ts.map
|
package/dist/revocation/crl.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{bitString as e,concatBytes as t,explicitContext as n,generalizedTime as r,implicitConstructedContext as i,implicitPrimitiveContext as a,integer as o,integerFromNumber as s,readElement as c,readRootElement as l,readSequenceChildren as u,sequence as d,time as f,tlv as p}from"../internal/asn1/der.js";import{childrenOf as m,decodeBoolean as ee,decodeIntegerNumber as h,decodeObjectIdentifier as g,decodeString as _,extractBitStringValue as v,hexToBytes as y,parseTime as b,requireElement as x,toHex as S}from"../internal/asn1/asn1.js";import{OIDS as C}from"../internal/asn1/oids.js";import{base64Encode as w}from"../internal/shared/base64.js";import{pemDecode as T,pemEncode as E}from"../pem/pem.js";import{failureResult as D}from"../result/result.js";import{exportSpkiDer as te}from"../keys/keys.js";import{describeSignatureAlgorithm as ne}from"../internal/crypto/algorithm-names.js";import{decodeIpAddress as re}from"../internal/shared/ip.js";import{encodeDistributionPointReasonFlagsContent as ie,parseDistributionPointReasonFlagsContent as O}from"../internal/x509/extension-bits.js";import{nameFieldKeyFromOid as ae}from"../internal/x509/name-fields.js";import{encodeName as oe,encodeRelativeDistinguishedName as se}from"../x509/name.js";import{buildSubjectKeyIdentifier as ce,encodeCrlDistributionPoints as le,encodeExtension as k,encodeSubjectAltName as ue}from"../x509/extensions.js";import{parseCertificateDerOrThrow as de,parseCertificateFromSource as A}from"../x509/parse.js";import{verifySignedDataDetailed as j}from"../internal/crypto/sig-verify.js";import{encodeAlgorithmIdentifier as M,getSignatureAlgorithm as fe,signBytes as pe}from"../internal/crypto/signing.js";import{compareDistinguishedNames as N,compareNameAttributeValue as me}from"../internal/shared/dn.js";const he={unspecified:0,keyCompromise:1,cACompromise:2,affiliationChanged:3,superseded:4,cessationOfOperation:5,certificateHold:6,removeFromCRL:8,privilegeWithdrawn:9,aACompromise:10};async function ge(t){let r=fe(t.signerPrivateKey),i=t.thisUpdate??new Date,a=t.nextUpdate,o=await Me(t.issuerPublicKey,t.crlNumber,t.baseCrlNumber,t.issuingDistributionPoint,t.freshestCrlDistributionPoints),c=t.revokedCertificates??[],l=c.length===0?[]:[d(c.map(e=>Ne(e,i)))],u=d([s(1),M(r),oe(t.issuer),f(i),...a===void 0?[]:[f(a)],...l,...o.length===0?[]:[n(0,d(o))]]),p=await pe(t.signerPrivateKey,r,u),m=d([u,M(r),e(p)]);return{der:m,pem:E(`X509 CRL`,m),base64:w(m)}}function P(e){let t=u(e,{maxDepth:64});if(t.length!==3)throw Error(`Malformed CRL`);let n=x(t[0],`TBSCertList`),r=x(t[1],`signatureAlgorithm`),i=x(t[2],`signatureValue`),a=tt(e.slice(n.start-n.headerLength,n.end)),o=Xe(e,r);return{der:new Uint8Array(e),version:a.version,tbsCertListDer:e.slice(n.start-n.headerLength,n.end),signatureValue:v(i),issuer:a.issuer,thisUpdate:a.thisUpdate,...a.nextUpdate===void 0?{}:{nextUpdate:a.nextUpdate},signatureAlgorithmOid:o.oid,signatureAlgorithmName:ne(o.oid,o.parametersDer),...o.parametersDer===void 0?{}:{signatureAlgorithmParametersDer:o.parametersDer},...a.authorityKeyIdentifier===void 0?{}:{authorityKeyIdentifier:a.authorityKeyIdentifier},...a.crlNumber===void 0?{}:{crlNumber:a.crlNumber},...a.baseCrlNumber===void 0?{}:{baseCrlNumber:a.baseCrlNumber},...a.issuingDistributionPoint===void 0?{}:{issuingDistributionPoint:a.issuingDistributionPoint},...a.freshestCrlDistributionPoints===void 0?{}:{freshestCrlDistributionPoints:a.freshestCrlDistributionPoints},revokedCertificates:a.revokedCertificates}}function F(e){return P(T(`X509 CRL`,e))}async function _e(e,t){let n,r;try{n=typeof e==`string`?F(e):P(new Uint8Array(e)),r=typeof t==`string`?$e(t):Qe(new Uint8Array(t))}catch{return L(`signature_invalid`,`certificate revocation list or issuer certificate input is malformed`)}let i;try{i=await j(n.signatureAlgorithmOid,n.signatureAlgorithmParametersDer,r.publicKeyAlgorithmOid,r.publicKeyParametersOid,r.subjectPublicKeyInfoDer,n.signatureValue,n.tbsCertListDer)}catch{return L(`signature_invalid`,`certificate revocation list signature verification failed`)}return i.ok?i.valid?{ok:!0,value:n}:L(`signature_invalid`,`certificate revocation list signature does not verify`):i.code===`verification_error`?L(`signature_invalid`,`certificate revocation list signature verification failed`):L(`signature_invalid`,`certificate revocation list signature uses unsupported algorithm parameters`)}async function I(e){let t;try{t=et(e.crl)}catch{return R(`signature_invalid`,`certificate revocation list signed content is malformed`)}let n;try{n=nt(e.issuerCertificate)}catch{return R(`signature_invalid`,`issuer certificate input is malformed`)}if(!N(t.issuer,n.subject))return R(`issuer_mismatch`,`CRL issuer name does not match certificate subject`);if(t.authorityKeyIdentifier!==void 0&&n.subjectKeyIdentifier!==void 0&&t.authorityKeyIdentifier!==n.subjectKeyIdentifier)return R(`issuer_mismatch`,`CRL authority key identifier does not match issuer subject key identifier`);if(n.keyUsage!==void 0&&!n.keyUsage.flags.includes(`cRLSign`))return R(`crl_sign_not_permitted`,`issuer certificate key usage does not permit CRL signing`);let r;try{r=await j(t.signatureAlgorithmOid,t.signatureAlgorithmParametersDer,n.publicKeyAlgorithmOid,n.publicKeyParametersOid,n.subjectPublicKeyInfoDer,t.signatureValue,t.tbsCertListDer)}catch{return R(`signature_invalid`,`certificate revocation list signature verification failed`)}if(!r.ok)return r.code===`verification_error`?R(`signature_invalid`,`certificate revocation list signature verification failed`):R(`signature_invalid`,`certificate revocation list signature uses unsupported algorithm parameters`);if(!r.valid)return R(`signature_invalid`,`certificate revocation list signature does not verify`);let i=e.at??new Date,a=e.clockSkewMs??0;return t.thisUpdate.getTime()-a>i.getTime()||t.nextUpdate!==void 0&&t.nextUpdate.getTime()+a<i.getTime()?R(`stale_crl`,`CRL is not valid at requested time`):{ok:!0,value:t}}async function ve(e){let t;try{t=nt(e.certificate)}catch{return z(`non_applicable`,`certificate input is malformed`)}let n=await I({crl:e.crl,issuerCertificate:e.issuerCertificate,...e.at===void 0?{}:{at:e.at},...e.clockSkewMs===void 0?{}:{clockSkewMs:e.clockSkewMs}});if(!n.ok)return z(n.code,n.message);let r;if(e.deltaCrl!==void 0){let t=await I({crl:e.deltaCrl,issuerCertificate:e.issuerCertificate,...e.at===void 0?{}:{at:e.at},...e.clockSkewMs===void 0?{}:{clockSkewMs:e.clockSkewMs}});if(!t.ok)return z(t.code,t.message);let i=be(n.value,t.value);if(i!==void 0)return i;r=t.value}let i=H(t,n.value);if(i!==void 0)return i;if(r!==void 0){let e=H(t,r,!0);if(e!==void 0)return e}let a=V(t,n.value);if(!a.ok)return a;let o;if(r!==void 0){let e=V(t,r);if(!e.ok)return e;o=e.entry}return Ce(t,e.at??new Date,n.value,a.entry,o)}function L(e,t){return D(e,t)}function R(e,t){return D(e,t)}function z(e,t,n){return D(e,t,n)}function B(e){return{ok:!0,value:e}}function ye(e,t){let n=typeof e==`string`?Q(e):S(e);return t.revokedCertificates.some(e=>Q(e.serialNumberHex)===n)}function V(e,t){let n=Q(e.serialNumberHex),r,i=!1,a;for(let o of t.revokedCertificates){if(o.certificateIssuer!==void 0&&(r=o.certificateIssuer),Q(o.serialNumberHex)!==n)continue;let s=Se(e,t,r);if(s===`match`){if(a!==void 0)return z(`signature_invalid`,`CRL contains multiple revoked entries for certificate`);a=o;continue}s===`unsupported`&&(i=!0)}return a===void 0?i?U(`indirect_crl_unsupported`,`indirect CRL entry certificateIssuer must include a directoryName`):{ok:!0}:{ok:!0,entry:a}}function H(e,t,n=!1){if(!n&&t.baseCrlNumber!==void 0)return U(`delta_crl_unsupported`,`a delta CRL cannot be used as the primary complete CRL input`);let r=t.issuingDistributionPoint,i=r?.indirectCrl===!0;if(!i&&!N(e.issuer,t.issuer))return U(`issuer_mismatch`,`CRL issuer does not match certificate issuer for direct CRL processing`);if(r?.onlyContainsAttributeCerts===!0)return U(`certificate_scope_mismatch`,`attribute-certificate-only CRLs are not applicable to public-key certificates`);let a=e.basicConstraints?.ca===!0;if(r?.onlyContainsUserCerts===!0&&a)return U(`certificate_scope_mismatch`,`CRL only applies to end-entity certificates`);if(r?.onlyContainsCACerts===!0&&!a)return U(`certificate_scope_mismatch`,`CRL only applies to CA certificates`);let o=e.crlDistributionPoints??[];if(o.length===0)return r?.distributionPoint===void 0?i&&!N(e.issuer,t.issuer)?U(`issuer_mismatch`,`indirect CRLs for alternate certificate issuers require matching CRLIssuer distribution points`):void 0:U(`distribution_point_mismatch`,`certificates without CRL distribution points only accept full-scope CRLs`);let s=!1,c=!1,l=!1,u=!1,d=!1;for(let n of o){if(!i&&n.crlIssuer!==void 0){s=!0;continue}if(i&&(!N(e.issuer,t.issuer)||n.crlIssuer!==void 0)){let e=xe(n.crlIssuer,t);if(e===`unsupported`){u=!0;continue}if(!e){l=!0;continue}}if(!we(n.distributionPoint,r?.distributionPoint,t.issuer)){c=!0;continue}if(!Ae(n.reasons,r?.onlySomeReasons)){d=!0;continue}return}return d?U(`reasons_mismatch`,`certificate distribution point reasons do not overlap the CRL reason scope`):u?U(`indirect_crl_unsupported`,`indirect CRL distribution points must identify the CRL issuer with directoryName`):l?U(`issuer_mismatch`,`certificate distribution points do not authorize this indirect CRL issuer`):c?U(`distribution_point_mismatch`,`certificate distribution points do not match the CRL issuing distribution point`):s?U(`indirect_crl_unsupported`,`certificate distribution points that name alternate CRL issuers are not supported yet`):U(`distribution_point_mismatch`,`certificate distribution points do not match the CRL scope`)}function be(e,t){if(e.baseCrlNumber!==void 0)return U(`delta_crl_incompatible`,`complete CRL input must not itself be a delta CRL`);if(t.baseCrlNumber===void 0)return U(`delta_crl_incompatible`,`delta CRL input must include a delta CRL indicator`);if(!N(e.issuer,t.issuer))return U(`delta_crl_incompatible`,`complete and delta CRLs must share the same issuer`);if(e.authorityKeyIdentifier!==t.authorityKeyIdentifier)return U(`delta_crl_incompatible`,`complete and delta CRLs must share the same authority key identifier`);if(!Ee(e.issuingDistributionPoint,t.issuingDistributionPoint))return U(`delta_crl_incompatible`,`complete and delta CRLs must share the same issuing distribution point scope`);if(e.crlNumber===void 0||t.crlNumber===void 0)return U(`delta_crl_incompatible`,`complete and delta CRLs must both carry CRL numbers for delta processing`);if(e.crlNumber<t.baseCrlNumber)return U(`delta_crl_incompatible`,`delta CRL base number must not exceed the complete CRL number`);if(e.crlNumber>=t.crlNumber)return U(`delta_crl_incompatible`,`delta CRL number must be newer than the complete CRL number`)}function xe(e,t){if(e===void 0)return!1;let n=!1;for(let r of e){if(r.type===`directoryName`){if(qe(r.derHex,t.issuer))return!0;continue}n=!0}return n?`unsupported`:!1}function Se(e,t,n){if(n===void 0)return N(e.issuer,t.issuer)?`match`:`mismatch`;let r=!1;for(let t of n){if(t.type===`directoryName`){if(qe(t.derHex,e.issuer))return`match`;continue}r=!0}return r?`unsupported`:`mismatch`}function U(e,t){return z(`non_applicable`,t,{reason:e})}function Ce(e,t,n,r,i){if(i!==void 0)if(i.reasonCode===`removeFromCRL`){if(r?.reasonCode===`certificateHold`||e.notAfter.getTime()<t.getTime())return B({status:`good`,crl:n})}else return B({status:`revoked`,crl:n,revocationDate:i.revocationDate,...i.reasonCode===void 0?{}:{reasonCode:i.reasonCode}});return B(r===void 0?{status:`good`,crl:n}:{status:`revoked`,crl:n,revocationDate:r.revocationDate,...r.reasonCode===void 0?{}:{reasonCode:r.reasonCode}})}function we(e,t,n){if(t===void 0)return!0;if(e===void 0)return!1;if(e.fullName!==void 0&&t.fullName!==void 0)return e.fullName.some(e=>t.fullName?.some(t=>G(e,t))===!0);if(e.relativeName!==void 0&&t.fullName!==void 0){let r=W(n,e.relativeName);return t.fullName.some(e=>e.type===`directoryName`&&e.derHex===r)}if(e.relativeName!==void 0&&t.relativeName!==void 0)return K(e.relativeName,t.relativeName);if(e.fullName!==void 0&&t.relativeName!==void 0){let r=W(n,t.relativeName);return e.fullName.some(e=>e.type===`directoryName`&&e.derHex===r)}return!1}function W(e,t){let n=e.rdns.map(e=>y(e.derHex)),r=Te(y(t.derHex));return n.push(r),S(d(n))}function Te(e){return p(49,l(e,{maxDepth:64}).value)}function Ee(e,t){return e===void 0||t===void 0?e===t:De(e.distributionPoint,t.distributionPoint)&&e.onlyContainsUserCerts===!0==(t.onlyContainsUserCerts===!0)&&e.onlyContainsCACerts===!0==(t.onlyContainsCACerts===!0)&&e.indirectCrl===!0==(t.indirectCrl===!0)&&e.onlyContainsAttributeCerts===!0==(t.onlyContainsAttributeCerts===!0)&&ke(e.onlySomeReasons,t.onlySomeReasons)}function De(e,t){return e===void 0||t===void 0?e===t:e.fullName!==void 0||t.fullName!==void 0?e.fullName===void 0||t.fullName===void 0?!1:Oe(e.fullName,t.fullName):e.relativeName===void 0||t.relativeName===void 0?!1:K(e.relativeName,t.relativeName)}function Oe(e,t){if(e.length!==t.length)return!1;let n=Array(t.length).fill(!1);for(let r of e){let e=!1;for(let i=0;i<t.length;i+=1){let a=t[i];if(!(a===void 0||n[i])&&G(r,a)){n[i]=!0,e=!0;break}}if(!e)return!1}return!0}function ke(e,t){return e===void 0||t===void 0?e===t:e.flags.length===t.flags.length?e.flags.every(e=>t.flags.includes(e)):!1}function Ae(e,t){return e===void 0||t===void 0?!0:e.flags.some(e=>t.flags.includes(e))}function G(e,t){if(e.type===`dns`&&t.type===`dns`||e.type===`email`&&t.type===`email`||e.type===`ip`&&t.type===`ip`||e.type===`uri`&&t.type===`uri`)return e.value===t.value;if(e.type===`directoryName`&&t.type===`directoryName`){let n=Z(e.derHex),r=Z(t.derHex);return n===void 0||r===void 0?!1:N(n,r)}return e.type===`unknown`&&t.type===`unknown`?e.tag===t.tag&&je(e.value,t.value):!1}function je(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function K(e,t){if(e.attributes.length!==t.attributes.length)return!1;let n=Array(t.attributes.length).fill(!1);for(let r of e.attributes){let e=!1;for(let i=0;i<t.attributes.length;i+=1){let a=t.attributes[i];if(!(a===void 0||n[i])&&me(r,a)){n[i]=!0,e=!0;break}}if(!e)return!1}return!0}async function Me(e,t,n,r,i){let o=[];if(e!==void 0){let t=await te(e);o.push(k(C.authorityKeyIdentifier,d([a(0,ce(t))])))}return t!==void 0&&o.push(k(C.cRLNumber,s(t))),n!==void 0&&o.push(k(C.deltaCRLIndicator,s(n),!0)),r!==void 0&&o.push(k(C.issuingDistributionPoint,Ve(r),!0)),i!==void 0&&i.length>0&&o.push(k(C.freshestCRL,le(i))),o}function Ne(e,t){let n=Pe(e);return d([o(e.serialNumber),f(e.revocationDate??t),...n.length===0?[]:[d(n)]])}function Pe(e){let t=[];return e.reasonCode!==void 0&&t.push(k(C.cRLReason,p(10,Uint8Array.of(he[e.reasonCode])))),e.invalidityDate!==void 0&&t.push(k(C.invalidityDate,r(e.invalidityDate))),t}function Fe(e,t){if(e===void 0||t===void 0)return{};let n,r,i,a=new Set;for(let o of m(e,t)){let t=m(e,o);if(t.length<2||t.length>3||t.length===3&&t[1]?.tag!==1)throw Error(`Malformed revoked certificate extension`);let s=g(x(t[0],`revoked certificate extension OID`).value);if(a.has(s))throw Error(`Duplicate revoked certificate extension OID: ${s}`);a.add(s);let u=x(t[t.length-1],`revoked certificate extension value`);if(u.tag!==4)throw Error(`Revoked certificate extension value must use OCTET STRING`);if(s===C.cRLReason&&(n=Ze(c(u.value).value[0])),s===C.invalidityDate&&(r=b(c(u.value))),s===C.certificateIssuer){let e=l(u.value,{maxDepth:64});if(e.tag!==48)throw Error(`certificateIssuer must use SEQUENCE`);i=Y(u.value,e)}}return{...n===void 0?{}:{reasonCode:n},...r===void 0?{}:{invalidityDate:r},...i===void 0?{}:{certificateIssuer:i}}}function Ie(e){let t=l(e,{maxDepth:64}),n,r,i,a,o,s;for(let c of m(e,t))if(c.tag===160){if(n!==void 0)throw Error(`IssuingDistributionPoint distributionPoint must not repeat`);let t=q(e,c);t!==void 0&&(n=t)}else if(c.tag===129){if(r!==void 0)throw Error(`IssuingDistributionPoint onlyContainsUserCerts must not repeat`);r=X(c)}else if(c.tag===130){if(i!==void 0)throw Error(`IssuingDistributionPoint onlyContainsCACerts must not repeat`);i=X(c)}else if(c.tag===131){if(a!==void 0)throw Error(`IssuingDistributionPoint onlySomeReasons must not repeat`);a=O(c.value)}else if(c.tag===132){if(o!==void 0)throw Error(`IssuingDistributionPoint indirectCrl must not repeat`);o=X(c)}else if(c.tag===133){if(s!==void 0)throw Error(`IssuingDistributionPoint onlyContainsAttributeCerts must not repeat`);s=X(c)}else throw Error(`Unsupported IssuingDistributionPoint field tag: ${String(c.tag)}`);if([r,i,s].filter(e=>e===!0).length>1)throw Error(`IssuingDistributionPoint scope booleans are mutually exclusive`);return{...n===void 0?{}:{distributionPoint:n},...r===void 0?{}:{onlyContainsUserCerts:r},...i===void 0?{}:{onlyContainsCACerts:i},...a===void 0?{}:{onlySomeReasons:a},...o===void 0?{}:{indirectCrl:o},...s===void 0?{}:{onlyContainsAttributeCerts:s}}}function Le(e){let t=l(e,{maxDepth:64});if(t.tag!==48)throw Error(`DistributionPoints must use SEQUENCE`);let n=m(e,t);if(n.length===0)throw Error(`DistributionPoints must not be empty`);return n.map(t=>Re(e,t))}function q(e,t){let n=m(e,t);if(n.length!==1)throw Error(`distributionPointName must contain exactly one choice`);let r=x(n[0],`distributionPointName`);if(r.tag===160){let t=m(e,r);if(t.length===0)throw Error(`distributionPointName fullName must not be empty`);for(let e of t)if((e.tag&192)!=128)throw Error(`distributionPointName fullName must contain GeneralName entries`);return{fullName:t.map(e=>J(e))}}if(r.tag===161)return{relativeName:ze(e,r)};throw Error(`Unsupported distributionPointName tag: ${String(r.tag)}`)}function Re(e,t){if(t.tag!==48)throw Error(`DistributionPoint must use SEQUENCE`);let n,r,i;for(let a of m(e,t))if(a.tag===160){if(n!==void 0)throw Error(`DistributionPoint distributionPoint must not repeat`);let t=q(e,a);t!==void 0&&(n=t)}else if(a.tag===129){if(r!==void 0)throw Error(`DistributionPoint reasons must not repeat`);r=O(a.value)}else if(a.tag===162){if(i!==void 0)throw Error(`DistributionPoint crlIssuer must not repeat`);i=Y(e,a)}else throw Error(`Unsupported DistributionPoint field tag: ${String(a.tag)}`);if(n===void 0&&i===void 0)throw Error(`DistributionPoint must include distributionPoint or crlIssuer`);return{...n===void 0?{}:{distributionPoint:n},...r===void 0?{}:{reasons:r},...i===void 0?{}:{crlIssuer:i}}}function J(e){switch(e.tag){case 129:return{type:`email`,value:$.decode(e.value)};case 130:return{type:`dns`,value:$.decode(e.value)};case 134:return{type:`uri`,value:$.decode(e.value)};case 135:return{type:`ip`,value:re(e.value)};case 164:return{type:`directoryName`,derHex:S(We(e))};default:return{type:`unknown`,tag:e.tag,value:new Uint8Array(e.value)}}}function Y(e,t){let n=m(e,t);if(n.length===0)throw Error(`GeneralNames must not be empty`);for(let e of n)if((e.tag&192)!=128)throw Error(`GeneralNames must contain GeneralName entries`);return n.map(e=>J(e))}function ze(e,t){let n=[],r={};for(let i of m(e,t)){let t=m(e,i),a=g(x(t[0],`name OID`).value),o=x(t[1],`name value`),s=ae(a),c=Be(o),l=s===void 0?{oid:a,valueTag:o.tag,value:c}:{oid:a,key:s,valueTag:o.tag,value:c};n.push(l),s!==void 0&&r[s]===void 0&&(r[s]=c)}return{derHex:S(e.slice(t.start-t.headerLength,t.end)),attributes:n,values:r}}function Be(e){return _(e.tag,e.value)}function X(e){return(e.value[0]??0)!==0}function Ve(e){if([e.onlyContainsUserCerts===!0,e.onlyContainsCACerts===!0,e.onlyContainsAttributeCerts===!0].filter(Boolean).length>1)throw Error(`IssuingDistributionPoint can assert at most one of user, CA, or attribute cert scope`);let t=[];return e.distributionPoint!==void 0&&t.push(i(0,He(e.distributionPoint))),e.onlyContainsUserCerts&&t.push(a(1,Uint8Array.of(255))),e.onlyContainsCACerts&&t.push(a(2,Uint8Array.of(255))),e.onlySomeReasons!==void 0&&e.onlySomeReasons.length>0&&t.push(a(3,ie(e.onlySomeReasons))),e.indirectCrl&&t.push(a(4,Uint8Array.of(255))),e.onlyContainsAttributeCerts&&t.push(a(5,Uint8Array.of(255))),d(t)}function He(e){if(e===void 0)throw Error(`IssuingDistributionPoint distributionPoint is required`);if(e.fullName!==void 0&&e.relativeName!==void 0)throw Error(`DistributionPointName cannot contain both fullName and relativeName`);if(e.fullName!==void 0){if(e.fullName.length===0)throw Error(`DistributionPointName fullName must not be empty`);return i(0,Ue(e.fullName))}if(e.relativeName!==void 0){let t=se(e.relativeName),n=c(t);return i(1,t.slice(n.start,n.end))}throw Error(`DistributionPointName must contain fullName or relativeName`)}function Ue(e){return t(e.map(e=>ue(e)))}function We(e){return e.value.length>0&&e.value[0]===48?new Uint8Array(e.value):p(48,e.value)}function Ge(e,t){let n=S(e.slice(t.start-t.headerLength,t.end)),r=[],i=[],a={};for(let n of m(e,t)){let t=[],o={};for(let r of m(e,n)){let n=m(e,r),s=x(n[0],`issuer attribute OID`),c=x(n[1],`issuer attribute value`),l=g(s.value),u;try{u=_(c.tag,c.value)}catch{u=$.decode(c.value)}let d=ae(l),f=d===void 0?{oid:l,valueTag:c.tag,value:u}:{oid:l,key:d,valueTag:c.tag,value:u};t.push(f),i.push(f),d!==void 0&&(o[d]===void 0&&(o[d]=u),a[d]===void 0&&(a[d]=u))}r.push({derHex:S(e.slice(n.start-n.headerLength,n.end)),attributes:t,values:o})}return{derHex:n,rdns:r,attributes:i,values:a}}function Z(e){try{let t=y(e),n=Ke(t,l(t,{maxDepth:64}));return n.tag===48?Ge(t,n):void 0}catch{return}}function Ke(e,t){if(t.tag!==48)return t;let n=m(e,t),r=n[0];return n.length===1&&r?.tag===48?r:t}function qe(e,t){let n=Z(e);return n===void 0?!1:N(n,t)}function Je(e){let t=l(e,{maxDepth:64,allowOpaqueConstructedTags:[161,162]});if(t.tag!==48)throw Error(`authorityKeyIdentifier must use SEQUENCE`);let n,r=!1,i=!1,a=-1;for(let o of m(e,t)){if(o.tag===128){if(n!==void 0)throw Error(`authorityKeyIdentifier keyIdentifier must not repeat`);if(a>=0)throw Error(`authorityKeyIdentifier fields must preserve DER order`);n=S(o.value),a=0;continue}if(o.tag===161){if(r)throw Error(`authorityKeyIdentifier authorityCertIssuer must not repeat`);if(a>=1)throw Error(`authorityKeyIdentifier fields must preserve DER order`);Y(e,o),r=!0,a=1;continue}if(o.tag===130){if(i)throw Error(`authorityKeyIdentifier authorityCertSerialNumber must not repeat`);if(a>=2||!r)throw Error(`authorityKeyIdentifier fields must preserve DER order`);Ye(o.value,`authorityKeyIdentifier authorityCertSerialNumber`),i=!0,a=2;continue}throw Error(`Unsupported authorityKeyIdentifier field tag: ${String(o.tag)}`)}return n}function Ye(e,t){let n=e[0];if(n===void 0)throw Error(`${t} must not be empty`);if(n&128)throw Error(`${t} must be non-negative`);if(e.length>1&&n===0&&!((e[1]??0)&128))throw Error(`${t} must use minimal encoding`)}function Xe(e,t){let n=m(e,t),r=x(n[0],`algorithm OID`),i=n[1];return i===void 0?{oid:g(r.value)}:{oid:g(r.value),parametersDer:e.slice(i.start-i.headerLength,i.end)}}function Q(e){return e.toLowerCase()}function Ze(e){switch(e){case 0:return`unspecified`;case 1:return`keyCompromise`;case 2:return`cACompromise`;case 3:return`affiliationChanged`;case 4:return`superseded`;case 5:return`cessationOfOperation`;case 6:return`certificateHold`;case 8:return`removeFromCRL`;case 9:return`privilegeWithdrawn`;case 10:return`aACompromise`}}function Qe(e){return A(e)}function $e(e){return A(e)}function et(e){if(typeof e==`string`)return F(e);if(e instanceof Uint8Array)return P(new Uint8Array(e));if(it(e))return P(new Uint8Array(e.der));throw Error(`certificate revocation list input is malformed`)}function tt(e){let t=m(e,l(e,{maxDepth:64})),n=0,r=1,i=t[n];if(i!==void 0&&i.tag!==2&&i.tag!==48)throw Error(`version must use INTEGER`);if(i?.tag===2){let e=x(t[n],`version`);if(e.tag!==2)throw Error(`version must use INTEGER`);if(r=h(e.value)+1,r!==2)throw Error(`Unsupported CRL version: ${String(r)}`);n+=1}n+=1;let a=x(t[n],`issuer`),o=x(t[n+1],`thisUpdate`),s=n+2,d=t[s],f=d!==void 0&&(d.tag===23||d.tag===24)?b(d):void 0;f!==void 0&&(s+=1);let p=[],_=t[s];_?.tag===48&&(p=m(e,_).map(t=>{let n=e.slice(t.start-t.headerLength,t.end),i=u(n),a=x(i[0],`revoked serialNumber`);if(a.tag!==2)throw Error(`revoked serialNumber must use INTEGER`);let o=i[2];if(o!==void 0&&r!==2)throw Error(`revoked certificate extensions require CRL version 2`);let s=Fe(n,o);return{serialNumberHex:S(a.value),revocationDate:b(x(i[1],`revocationDate`)),...s.reasonCode===void 0?{}:{reasonCode:s.reasonCode},...s.invalidityDate===void 0?{}:{invalidityDate:s.invalidityDate},...s.certificateIssuer===void 0?{}:{certificateIssuer:s.certificateIssuer}}}),s+=1);let v,y,w,T,E,D=t[s];if(D?.tag===160){if(r!==2)throw Error(`CRL extensions require version 2`);let t=new Set,n=x(m(e,D)[0],`crl extensions`);for(let r of m(e,n)){let n=m(e,r);if(n.length<2||n.length>3||n.length===3&&n[1]?.tag!==1)throw Error(`Malformed CRL extension`);let i=g(x(n[0],`extension OID`).value);if(t.has(i))throw Error(`Duplicate CRL extension OID: ${i}`);t.add(i);let a=n.length===3?ee(x(n[1],`extension critical`).value):!1,o=x(n[n.length-1],`extension value`);if(o.tag!==4)throw Error(`CRL extension value must use OCTET STRING`);if(i!==C.authorityKeyIdentifier&&i!==C.cRLNumber&&i!==C.deltaCRLIndicator&&i!==C.issuingDistributionPoint&&i!==C.freshestCRL&&a)throw Error(`Unsupported critical CRL extension OID: ${i}`);i===C.authorityKeyIdentifier&&(v=Je(o.value)),i===C.cRLNumber&&(y=h(c(o.value).value)),i===C.deltaCRLIndicator&&(w=h(c(o.value).value)),i===C.issuingDistributionPoint&&(T=Ie(o.value)),i===C.freshestCRL&&(E=Le(o.value))}}return{version:r,issuer:Ge(e,a),thisUpdate:b(o),...f===void 0?{}:{nextUpdate:f},...v===void 0?{}:{authorityKeyIdentifier:v},...y===void 0?{}:{crlNumber:y},...w===void 0?{}:{baseCrlNumber:w},...T===void 0?{}:{issuingDistributionPoint:T},...E===void 0?{}:{freshestCrlDistributionPoints:E},revokedCertificates:p}}function nt(e){return rt(e)?de(new Uint8Array(e.der)):A(e)}function rt(e){return typeof e!=`string`&&`subjectPublicKeyInfoDer`in e}function it(e){return`der`in e&&e.der instanceof Uint8Array}const $=new TextDecoder;export{ve as checkCertificateRevocationAgainstCrl,ge as createCertificateRevocationList,ye as isCertificateRevoked,P as parseCertificateRevocationListDer,F as parseCertificateRevocationListPem,I as validateCertificateRevocationList,_e as verifyCertificateRevocationList};
|
|
1
|
+
import{bitString as e,concatBytes as t,explicitContext as n,generalizedTime as r,implicitConstructedContext as i,implicitPrimitiveContext as a,integer as o,integerFromNumber as s,readElement as c,readRootElement as l,readSequenceChildren as u,sequence as d,time as f,tlv as p}from"../internal/asn1/der.js";import{childrenOf as m,decodeBoolean as ee,decodeIntegerNumber as h,decodeObjectIdentifier as g,decodeString as _,extractBitStringValue as v,hexToBytes as y,parseTime as b,requireElement as x,toHex as S}from"../internal/asn1/asn1.js";import{OIDS as C}from"../internal/asn1/oids.js";import{base64Encode as w}from"../internal/shared/base64.js";import{pemDecode as T,pemEncode as E}from"../pem/pem.js";import{failureResult as D}from"../result/result.js";import{exportSpkiDer as te}from"../keys/keys.js";import{describeSignatureAlgorithm as ne}from"../internal/crypto/algorithm-names.js";import{decodeIpAddress as re}from"../internal/shared/ip.js";import{encodeDistributionPointReasonFlagsContent as ie,parseDistributionPointReasonFlagsContent as O}from"../internal/x509/extension-bits.js";import{nameFieldKeyFromOid as ae}from"../internal/x509/name-fields.js";import{encodeName as oe,encodeRelativeDistinguishedName as se}from"../x509/name.js";import{buildSubjectKeyIdentifier as ce,encodeCrlDistributionPoints as le,encodeExtension as k,encodeSubjectAltName as ue}from"../x509/extensions.js";import{parseCertificateDerOrThrow as de,parseCertificateFromSource as A}from"../x509/parse.js";import{verifySignedDataDetailed as j}from"../internal/crypto/sig-verify.js";import{encodeAlgorithmIdentifier as M,getSignatureAlgorithm as fe,signBytes as pe}from"../internal/crypto/signing.js";import{compareDistinguishedNames as N,compareNameAttributeValue as me}from"../internal/shared/dn.js";const he={unspecified:0,keyCompromise:1,cACompromise:2,affiliationChanged:3,superseded:4,cessationOfOperation:5,certificateHold:6,removeFromCRL:8,privilegeWithdrawn:9,aACompromise:10};async function ge(t){let r=fe(t.signerPrivateKey),i=t.thisUpdate??new Date,a=t.nextUpdate,o=await Me(t.issuerPublicKey,t.crlNumber,t.baseCrlNumber,t.issuingDistributionPoint,t.freshestCrlDistributionPoints),c=t.revokedCertificates??[],l=c.length===0?[]:[d(c.map(e=>Ne(e,i)))],u=d([s(1),M(r),oe(t.issuer),f(i),...a===void 0?[]:[f(a)],...l,...o.length===0?[]:[n(0,d(o))]]),p=await pe(t.signerPrivateKey,r,u),m=d([u,M(r),e(p)]);return{der:m,pem:E(`X509 CRL`,m),base64:w(m)}}function P(e){let t=u(e,{maxDepth:64});if(t.length!==3)throw Error(`Malformed CRL`);let n=x(t[0],`TBSCertList`),r=x(t[1],`signatureAlgorithm`),i=x(t[2],`signatureValue`),a=tt(e.slice(n.start-n.headerLength,n.end)),o=Xe(e,r);return{der:new Uint8Array(e),version:a.version,tbsCertListDer:e.slice(n.start-n.headerLength,n.end),signatureValue:v(i),issuer:a.issuer,thisUpdate:a.thisUpdate,...a.nextUpdate===void 0?{}:{nextUpdate:a.nextUpdate},signatureAlgorithmOid:o.oid,signatureAlgorithmName:ne(o.oid,o.parametersDer),...o.parametersDer===void 0?{}:{signatureAlgorithmParametersDer:o.parametersDer},...a.authorityKeyIdentifier===void 0?{}:{authorityKeyIdentifier:a.authorityKeyIdentifier},...a.crlNumber===void 0?{}:{crlNumber:a.crlNumber},...a.baseCrlNumber===void 0?{}:{baseCrlNumber:a.baseCrlNumber},...a.issuingDistributionPoint===void 0?{}:{issuingDistributionPoint:a.issuingDistributionPoint},...a.freshestCrlDistributionPoints===void 0?{}:{freshestCrlDistributionPoints:a.freshestCrlDistributionPoints},revokedCertificates:a.revokedCertificates}}function F(e){return P(T(`X509 CRL`,e))}async function _e(e,t){let n,r;try{n=typeof e==`string`?F(e):P(new Uint8Array(e)),r=typeof t==`string`?$e(t):Qe(new Uint8Array(t))}catch{return L(`signature_invalid`,`certificate revocation list or issuer certificate input is malformed`)}let i;try{i=await j(n.signatureAlgorithmOid,n.signatureAlgorithmParametersDer,r.publicKeyAlgorithmOid,r.publicKeyParametersOid,r.subjectPublicKeyInfoDer,n.signatureValue,n.tbsCertListDer)}catch{return L(`signature_invalid`,`certificate revocation list signature verification failed`)}return i.ok?i.valid?{ok:!0,value:n}:L(`signature_invalid`,`certificate revocation list signature does not verify`):i.code===`verification_error`?L(`signature_invalid`,`certificate revocation list signature verification failed`):L(`signature_invalid`,`certificate revocation list signature uses unsupported algorithm parameters`)}async function I(e){let t;try{t=et(e.crl)}catch{return R(`signature_invalid`,`certificate revocation list signed content is malformed`)}let n;try{n=nt(e.issuerCertificate)}catch{return R(`signature_invalid`,`issuer certificate input is malformed`)}if(!N(t.issuer,n.subject))return R(`issuer_mismatch`,`CRL issuer name does not match certificate subject`);if(t.authorityKeyIdentifier!==void 0&&n.subjectKeyIdentifier!==void 0&&t.authorityKeyIdentifier!==n.subjectKeyIdentifier)return R(`issuer_mismatch`,`CRL authority key identifier does not match issuer subject key identifier`);if(n.keyUsage!==void 0&&!n.keyUsage.flags.includes(`cRLSign`))return R(`crl_sign_not_permitted`,`issuer certificate key usage does not permit CRL signing`);let r;try{r=await j(t.signatureAlgorithmOid,t.signatureAlgorithmParametersDer,n.publicKeyAlgorithmOid,n.publicKeyParametersOid,n.subjectPublicKeyInfoDer,t.signatureValue,t.tbsCertListDer)}catch{return R(`signature_invalid`,`certificate revocation list signature verification failed`)}if(!r.ok)return r.code===`verification_error`?R(`signature_invalid`,`certificate revocation list signature verification failed`):R(`signature_invalid`,`certificate revocation list signature uses unsupported algorithm parameters`);if(!r.valid)return R(`signature_invalid`,`certificate revocation list signature does not verify`);let i=e.at??new Date,a=e.clockSkewMs??0;return t.thisUpdate.getTime()-a>i.getTime()||t.nextUpdate!==void 0&&t.nextUpdate.getTime()+a<i.getTime()?R(`stale_crl`,`CRL is not valid at requested time`):{ok:!0,value:t}}async function ve(e){let t;try{t=nt(e.certificate)}catch{return z(`non_applicable`,`certificate input is malformed`)}let n=await I({crl:e.crl,issuerCertificate:e.issuerCertificate,...e.at===void 0?{}:{at:e.at},...e.clockSkewMs===void 0?{}:{clockSkewMs:e.clockSkewMs}});if(!n.ok)return z(n.code,n.message);let r;if(e.deltaCrl!==void 0){let t=await I({crl:e.deltaCrl,issuerCertificate:e.issuerCertificate,...e.at===void 0?{}:{at:e.at},...e.clockSkewMs===void 0?{}:{clockSkewMs:e.clockSkewMs}});if(!t.ok)return z(t.code,t.message);let i=be(n.value,t.value);if(i!==void 0)return i;r=t.value}let i=H(t,n.value);if(i!==void 0)return i;if(r!==void 0){let e=H(t,r,!0);if(e!==void 0)return e}let a=V(t,n.value);if(!a.ok)return a;let o;if(r!==void 0){let e=V(t,r);if(!e.ok)return e;o=e.entry}return Ce(t,e.at??new Date,n.value,a.entry,o)}function L(e,t){return D(e,t)}function R(e,t){return D(e,t)}function z(e,t,n){return D(e,t,n)}function B(e){return{ok:!0,value:e}}function ye(e,t){let n=typeof e==`string`?Q(e):S(e);return t.revokedCertificates.some(e=>Q(e.serialNumberHex)===n)}function V(e,t){let n=Q(e.serialNumberHex),r,i=!1,a;for(let o of t.revokedCertificates){if(o.certificateIssuer!==void 0&&(r=o.certificateIssuer),Q(o.serialNumberHex)!==n)continue;let s=Se(e,t,r);if(s===`match`){if(a!==void 0)return z(`signature_invalid`,`CRL contains multiple revoked entries for certificate`);a=o;continue}s===`unsupported`&&(i=!0)}return a===void 0?i?U(`indirect_crl_unsupported`,`indirect CRL entry certificateIssuer must include a directoryName`):{ok:!0}:{ok:!0,entry:a}}function H(e,t,n=!1){if(!n&&t.baseCrlNumber!==void 0)return U(`delta_crl_unsupported`,`a delta CRL cannot be used as the primary complete CRL input`);let r=t.issuingDistributionPoint,i=r?.indirectCrl===!0;if(!i&&!N(e.issuer,t.issuer))return U(`issuer_mismatch`,`CRL issuer does not match certificate issuer for direct CRL processing`);if(r?.onlyContainsAttributeCerts===!0)return U(`certificate_scope_mismatch`,`attribute-certificate-only CRLs are not applicable to public-key certificates`);let a=e.basicConstraints?.ca===!0;if(r?.onlyContainsUserCerts===!0&&a)return U(`certificate_scope_mismatch`,`CRL only applies to end-entity certificates`);if(r?.onlyContainsCACerts===!0&&!a)return U(`certificate_scope_mismatch`,`CRL only applies to CA certificates`);let o=e.crlDistributionPoints??[];if(o.length===0)return r?.distributionPoint===void 0?i&&!N(e.issuer,t.issuer)?U(`issuer_mismatch`,`indirect CRLs for alternate certificate issuers require matching CRLIssuer distribution points`):void 0:U(`distribution_point_mismatch`,`certificates without CRL distribution points only accept full-scope CRLs`);let s=!1,c=!1,l=!1,u=!1,d=!1;for(let n of o){if(!i&&n.crlIssuer!==void 0){s=!0;continue}if(i&&(!N(e.issuer,t.issuer)||n.crlIssuer!==void 0)){let e=xe(n.crlIssuer,t);if(e===`unsupported`){u=!0;continue}if(!e){l=!0;continue}}if(!we(n.distributionPoint,r?.distributionPoint,t.issuer)){c=!0;continue}if(!Ae(n.reasons,r?.onlySomeReasons)){d=!0;continue}return}return d?U(`reasons_mismatch`,`certificate distribution point reasons do not overlap the CRL reason scope`):u?U(`indirect_crl_unsupported`,`indirect CRL distribution points must identify the CRL issuer with directoryName`):l?U(`issuer_mismatch`,`certificate distribution points do not authorize this indirect CRL issuer`):c?U(`distribution_point_mismatch`,`certificate distribution points do not match the CRL issuing distribution point`):s?U(`indirect_crl_unsupported`,`certificate distribution points that name alternate CRL issuers are not supported yet`):U(`distribution_point_mismatch`,`certificate distribution points do not match the CRL scope`)}function be(e,t){if(e.baseCrlNumber!==void 0)return U(`delta_crl_incompatible`,`complete CRL input must not itself be a delta CRL`);if(t.baseCrlNumber===void 0)return U(`delta_crl_incompatible`,`delta CRL input must include a delta CRL indicator`);if(!N(e.issuer,t.issuer))return U(`delta_crl_incompatible`,`complete and delta CRLs must share the same issuer`);if(e.authorityKeyIdentifier!==t.authorityKeyIdentifier)return U(`delta_crl_incompatible`,`complete and delta CRLs must share the same authority key identifier`);if(!Ee(e.issuingDistributionPoint,t.issuingDistributionPoint))return U(`delta_crl_incompatible`,`complete and delta CRLs must share the same issuing distribution point scope`);if(e.crlNumber===void 0||t.crlNumber===void 0)return U(`delta_crl_incompatible`,`complete and delta CRLs must both carry CRL numbers for delta processing`);if(e.crlNumber<t.baseCrlNumber)return U(`delta_crl_incompatible`,`delta CRL base number must not exceed the complete CRL number`);if(e.crlNumber>=t.crlNumber)return U(`delta_crl_incompatible`,`delta CRL number must be newer than the complete CRL number`)}function xe(e,t){if(e===void 0)return!1;let n=!1;for(let r of e){if(r.type===`directoryName`){if(qe(r.derHex,t.issuer))return!0;continue}n=!0}return n?`unsupported`:!1}function Se(e,t,n){if(n===void 0)return N(e.issuer,t.issuer)?`match`:`mismatch`;let r=!1;for(let t of n){if(t.type===`directoryName`){if(qe(t.derHex,e.issuer))return`match`;continue}r=!0}return r?`unsupported`:`mismatch`}function U(e,t){return z(`non_applicable`,t,{reason:e})}function Ce(e,t,n,r,i){if(i!==void 0)if(i.reasonCode===`removeFromCRL`){if(r?.reasonCode===`certificateHold`||e.notAfter.getTime()<t.getTime())return B({status:`good`,crl:n})}else return B({status:`revoked`,crl:n,revocationDate:i.revocationDate,...i.reasonCode===void 0?{}:{reasonCode:i.reasonCode}});return B(r===void 0?{status:`good`,crl:n}:{status:`revoked`,crl:n,revocationDate:r.revocationDate,...r.reasonCode===void 0?{}:{reasonCode:r.reasonCode}})}function we(e,t,n){if(t===void 0)return!0;if(e===void 0)return!1;if(e.fullName!==void 0&&t.fullName!==void 0)return e.fullName.some(e=>t.fullName?.some(t=>G(e,t))===!0);if(e.relativeName!==void 0&&t.fullName!==void 0){let r=W(n,e.relativeName);return t.fullName.some(e=>e.type===`directoryName`&&e.derHex===r)}if(e.relativeName!==void 0&&t.relativeName!==void 0)return K(e.relativeName,t.relativeName);if(e.fullName!==void 0&&t.relativeName!==void 0){let r=W(n,t.relativeName);return e.fullName.some(e=>e.type===`directoryName`&&e.derHex===r)}return!1}function W(e,t){let n=e.rdns.map(e=>y(e.derHex)),r=Te(y(t.derHex));return n.push(r),S(d(n))}function Te(e){return p(49,l(e,{maxDepth:64}).value)}function Ee(e,t){return e===void 0||t===void 0?e===t:De(e.distributionPoint,t.distributionPoint)&&e.onlyContainsUserCerts===!0==(t.onlyContainsUserCerts===!0)&&e.onlyContainsCACerts===!0==(t.onlyContainsCACerts===!0)&&e.indirectCrl===!0==(t.indirectCrl===!0)&&e.onlyContainsAttributeCerts===!0==(t.onlyContainsAttributeCerts===!0)&&ke(e.onlySomeReasons,t.onlySomeReasons)}function De(e,t){return e===void 0||t===void 0?e===t:e.fullName!==void 0||t.fullName!==void 0?e.fullName===void 0||t.fullName===void 0?!1:Oe(e.fullName,t.fullName):e.relativeName===void 0||t.relativeName===void 0?!1:K(e.relativeName,t.relativeName)}function Oe(e,t){if(e.length!==t.length)return!1;let n=Array(t.length).fill(!1);for(let r of e){let e=!1;for(let i=0;i<t.length;i+=1){let a=t[i];if(!(a===void 0||n[i])&&G(r,a)){n[i]=!0,e=!0;break}}if(!e)return!1}return!0}function ke(e,t){return e===void 0||t===void 0?e===t:e.flags.length===t.flags.length?e.flags.every(e=>t.flags.includes(e)):!1}function Ae(e,t){return e===void 0||t===void 0?!0:e.flags.some(e=>t.flags.includes(e))}function G(e,t){if(e.type===`dns`&&t.type===`dns`||e.type===`email`&&t.type===`email`||e.type===`ip`&&t.type===`ip`||e.type===`uri`&&t.type===`uri`)return e.value===t.value;if(e.type===`directoryName`&&t.type===`directoryName`){let n=Z(e.derHex),r=Z(t.derHex);return n===void 0||r===void 0?!1:N(n,r)}return e.type===`unknown`&&t.type===`unknown`?e.tag===t.tag&&je(e.value,t.value):!1}function je(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function K(e,t){if(e.attributes.length!==t.attributes.length)return!1;let n=Array(t.attributes.length).fill(!1);for(let r of e.attributes){let e=!1;for(let i=0;i<t.attributes.length;i+=1){let a=t.attributes[i];if(!(a===void 0||n[i])&&me(r,a)){n[i]=!0,e=!0;break}}if(!e)return!1}return!0}async function Me(e,t,n,r,i){let o=[];if(e!==void 0){let t=await te(e);o.push(k(C.authorityKeyIdentifier,d([a(0,ce(t))])))}return t!==void 0&&o.push(k(C.cRLNumber,s(t))),n!==void 0&&o.push(k(C.deltaCRLIndicator,s(n),!0)),r!==void 0&&o.push(k(C.issuingDistributionPoint,Ve(r),!0)),i!==void 0&&i.length>0&&o.push(k(C.freshestCRL,le(i))),o}function Ne(e,t){let n=Pe(e);return d([o(e.serialNumber),f(e.revocationDate??t),...n.length===0?[]:[d(n)]])}function Pe(e){let t=[];return e.reasonCode!==void 0&&t.push(k(C.cRLReason,p(10,Uint8Array.of(he[e.reasonCode])))),e.invalidityDate!==void 0&&t.push(k(C.invalidityDate,r(e.invalidityDate))),t}function Fe(e,t){if(e===void 0||t===void 0)return{};let n,r,i,a=new Set;for(let o of m(e,t)){let t=m(e,o);if(t.length<2||t.length>3||t.length===3&&t[1]?.tag!==1)throw Error(`Malformed revoked certificate extension`);let s=g(x(t[0],`revoked certificate extension OID`).value);if(a.has(s))throw Error(`Duplicate revoked certificate extension OID: ${s}`);a.add(s);let u=x(t[t.length-1],`revoked certificate extension value`);if(u.tag!==4)throw Error(`Revoked certificate extension value must use OCTET STRING`);if(s===C.cRLReason&&(n=Ze(c(u.value).value[0])),s===C.invalidityDate&&(r=b(c(u.value))),s===C.certificateIssuer){let e=l(u.value,{maxDepth:64});if(e.tag!==48)throw Error(`certificateIssuer must use SEQUENCE`);i=Y(u.value,e)}}return{...n===void 0?{}:{reasonCode:n},...r===void 0?{}:{invalidityDate:r},...i===void 0?{}:{certificateIssuer:i}}}function Ie(e){let t=l(e,{maxDepth:64}),n,r,i,a,o,s;for(let c of m(e,t))if(c.tag===160){if(n!==void 0)throw Error(`IssuingDistributionPoint distributionPoint must not repeat`);let t=q(e,c);t!==void 0&&(n=t)}else if(c.tag===129){if(r!==void 0)throw Error(`IssuingDistributionPoint onlyContainsUserCerts must not repeat`);r=X(c)}else if(c.tag===130){if(i!==void 0)throw Error(`IssuingDistributionPoint onlyContainsCACerts must not repeat`);i=X(c)}else if(c.tag===131){if(a!==void 0)throw Error(`IssuingDistributionPoint onlySomeReasons must not repeat`);a=O(c.value)}else if(c.tag===132){if(o!==void 0)throw Error(`IssuingDistributionPoint indirectCrl must not repeat`);o=X(c)}else if(c.tag===133){if(s!==void 0)throw Error(`IssuingDistributionPoint onlyContainsAttributeCerts must not repeat`);s=X(c)}else throw Error(`Unsupported IssuingDistributionPoint field tag: ${String(c.tag)}`);if([r,i,s].filter(e=>e===!0).length>1)throw Error(`IssuingDistributionPoint scope booleans are mutually exclusive`);return{...n===void 0?{}:{distributionPoint:n},...r===void 0?{}:{onlyContainsUserCerts:r},...i===void 0?{}:{onlyContainsCACerts:i},...a===void 0?{}:{onlySomeReasons:a},...o===void 0?{}:{indirectCrl:o},...s===void 0?{}:{onlyContainsAttributeCerts:s}}}function Le(e){let t=l(e,{maxDepth:64});if(t.tag!==48)throw Error(`DistributionPoints must use SEQUENCE`);let n=m(e,t);if(n.length===0)throw Error(`DistributionPoints must not be empty`);return n.map(t=>Re(e,t))}function q(e,t){let n=m(e,t);if(n.length!==1)throw Error(`distributionPointName must contain exactly one choice`);let r=x(n[0],`distributionPointName`);if(r.tag===160){let t=m(e,r);if(t.length===0)throw Error(`distributionPointName fullName must not be empty`);for(let e of t)if((e.tag&192)!=128)throw Error(`distributionPointName fullName must contain GeneralName entries`);return{fullName:t.map(e=>J(e))}}if(r.tag===161)return{relativeName:ze(e,r)};throw Error(`Unsupported distributionPointName tag: ${String(r.tag)}`)}function Re(e,t){if(t.tag!==48)throw Error(`DistributionPoint must use SEQUENCE`);let n,r,i;for(let a of m(e,t))if(a.tag===160){if(n!==void 0)throw Error(`DistributionPoint distributionPoint must not repeat`);let t=q(e,a);t!==void 0&&(n=t)}else if(a.tag===129){if(r!==void 0)throw Error(`DistributionPoint reasons must not repeat`);r=O(a.value)}else if(a.tag===162){if(i!==void 0)throw Error(`DistributionPoint crlIssuer must not repeat`);i=Y(e,a)}else throw Error(`Unsupported DistributionPoint field tag: ${String(a.tag)}`);if(n===void 0&&i===void 0)throw Error(`DistributionPoint must include distributionPoint or crlIssuer`);return{...n===void 0?{}:{distributionPoint:n},...r===void 0?{}:{reasons:r},...i===void 0?{}:{crlIssuer:i}}}function J(e){switch(e.tag){case 129:return{type:`email`,value:$.decode(e.value)};case 130:return{type:`dns`,value:$.decode(e.value)};case 134:return{type:`uri`,value:$.decode(e.value)};case 135:return{type:`ip`,value:re(e.value)};case 164:return{type:`directoryName`,derHex:S(We(e))};default:return{type:`unknown`,tag:e.tag,value:new Uint8Array(e.value)}}}function Y(e,t){let n=m(e,t);if(n.length===0)throw Error(`GeneralNames must not be empty`);for(let e of n)if((e.tag&192)!=128)throw Error(`GeneralNames must contain GeneralName entries`);return n.map(e=>J(e))}function ze(e,t){let n=[],r={};for(let i of m(e,t)){let t=m(e,i),a=g(x(t[0],`name OID`).value),o=x(t[1],`name value`),s=ae(a),c=Be(o),l=s===void 0?{oid:a,valueTag:o.tag,value:c}:{oid:a,key:s,valueTag:o.tag,value:c};n.push(l),s!==void 0&&r[s]===void 0&&(r[s]=c)}return{derHex:S(e.slice(t.start-t.headerLength,t.end)),attributes:n,values:r}}function Be(e){return _(e.tag,e.value)}function X(e){return(e.value[0]??0)!==0}function Ve(e){if([e.onlyContainsUserCerts===!0,e.onlyContainsCACerts===!0,e.onlyContainsAttributeCerts===!0].filter(Boolean).length>1)throw Error(`IssuingDistributionPoint can assert at most one of user, CA, or attribute cert scope`);let t=[];return e.distributionPoint!==void 0&&t.push(i(0,He(e.distributionPoint))),e.onlyContainsUserCerts&&t.push(a(1,Uint8Array.of(255))),e.onlyContainsCACerts&&t.push(a(2,Uint8Array.of(255))),e.onlySomeReasons!==void 0&&e.onlySomeReasons.length>0&&t.push(a(3,ie(e.onlySomeReasons))),e.indirectCrl&&t.push(a(4,Uint8Array.of(255))),e.onlyContainsAttributeCerts&&t.push(a(5,Uint8Array.of(255))),d(t)}function He(e){if(e===void 0)throw Error(`IssuingDistributionPoint distributionPoint is required`);if(e.fullName!==void 0&&e.relativeName!==void 0)throw Error(`DistributionPointName cannot contain both fullName and relativeName`);if(e.fullName!==void 0){if(e.fullName.length===0)throw Error(`DistributionPointName fullName must not be empty`);return i(0,Ue(e.fullName))}if(e.relativeName!==void 0){let t=se(e.relativeName),n=c(t);return i(1,t.slice(n.start,n.end))}throw Error(`DistributionPointName must contain fullName or relativeName`)}function Ue(e){return t(e.map(e=>ue(e)))}function We(e){return e.value.length>0&&e.value[0]===48?new Uint8Array(e.value):p(48,e.value)}function Ge(e,t){let n=S(e.slice(t.start-t.headerLength,t.end)),r=[],i=[],a={};for(let n of m(e,t)){let t=[],o={};for(let r of m(e,n)){let n=m(e,r),s=x(n[0],`issuer attribute OID`),c=x(n[1],`issuer attribute value`),l=g(s.value),u;try{u=_(c.tag,c.value)}catch{u=$.decode(c.value)}let d=ae(l),f=d===void 0?{oid:l,valueTag:c.tag,value:u}:{oid:l,key:d,valueTag:c.tag,value:u};t.push(f),i.push(f),d!==void 0&&(o[d]===void 0&&(o[d]=u),a[d]===void 0&&(a[d]=u))}r.push({derHex:S(e.slice(n.start-n.headerLength,n.end)),attributes:t,values:o})}return{derHex:n,rdns:r,attributes:i,values:a}}function Z(e){try{let t=y(e),n=Ke(t,l(t,{maxDepth:64}));return n.tag===48?Ge(t,n):void 0}catch{return}}function Ke(e,t){if(t.tag!==48)return t;let n=m(e,t),r=n[0];return n.length===1&&r?.tag===48?r:t}function qe(e,t){let n=Z(e);return n===void 0?!1:N(n,t)}function Je(e){let t=l(e,{maxDepth:64,allowOpaqueConstructedTags:[161,162]});if(t.tag!==48)throw Error(`authorityKeyIdentifier must use SEQUENCE`);let n,r=!1,i=!1,a=-1;for(let o of m(e,t)){if(o.tag===128){if(n!==void 0)throw Error(`authorityKeyIdentifier keyIdentifier must not repeat`);if(a>=0)throw Error(`authorityKeyIdentifier fields must preserve DER order`);n=S(o.value),a=0;continue}if(o.tag===161){if(r)throw Error(`authorityKeyIdentifier authorityCertIssuer must not repeat`);if(a>=1)throw Error(`authorityKeyIdentifier fields must preserve DER order`);Y(e,o),r=!0,a=1;continue}if(o.tag===130){if(i)throw Error(`authorityKeyIdentifier authorityCertSerialNumber must not repeat`);if(a>=2||!r)throw Error(`authorityKeyIdentifier fields must preserve DER order`);Ye(o.value,`authorityKeyIdentifier authorityCertSerialNumber`),i=!0,a=2;continue}throw Error(`Unsupported authorityKeyIdentifier field tag: ${String(o.tag)}`)}return n}function Ye(e,t){let n=e[0];if(n===void 0)throw Error(`${t} must not be empty`);if(n&128)throw Error(`${t} must be non-negative`);if(e.length>1&&n===0&&!((e[1]??0)&128))throw Error(`${t} must use minimal encoding`)}function Xe(e,t){let n=m(e,t),r=x(n[0],`algorithm OID`),i=n[1];return i===void 0?{oid:g(r.value)}:{oid:g(r.value),parametersDer:e.slice(i.start-i.headerLength,i.end)}}function Q(e){return e.toLowerCase()}function Ze(e){switch(e){case 0:return`unspecified`;case 1:return`keyCompromise`;case 2:return`cACompromise`;case 3:return`affiliationChanged`;case 4:return`superseded`;case 5:return`cessationOfOperation`;case 6:return`certificateHold`;case 8:return`removeFromCRL`;case 9:return`privilegeWithdrawn`;case 10:return`aACompromise`}}function Qe(e){return A(e)}function $e(e){return A(e)}function et(e){if(typeof e==`string`)return F(e);if(e instanceof Uint8Array)return P(new Uint8Array(e));if(it(e))return P(new Uint8Array(e.der));throw Error(`certificate revocation list input is malformed`)}function tt(e){let t=m(e,l(e,{maxDepth:64})),n=0,r=1,i=t[n];if(i!==void 0&&i.tag!==2&&i.tag!==48)throw Error(`version must use INTEGER`);if(i?.tag===2){let e=x(t[n],`version`);if(e.tag!==2)throw Error(`version must use INTEGER`);if(r=h(e.value)+1,r!==2)throw Error(`Unsupported CRL version: ${String(r)}`);n+=1}n+=1;let a=x(t[n],`issuer`),o=x(t[n+1],`thisUpdate`),s=n+2,d=t[s],f=d!==void 0&&(d.tag===23||d.tag===24)?b(d):void 0;f!==void 0&&(s+=1);let p=[],_=t[s];_?.tag===48&&(p=m(e,_).map(t=>{let n=e.slice(t.start-t.headerLength,t.end),i=u(n),a=x(i[0],`revoked serialNumber`);if(a.tag!==2)throw Error(`revoked serialNumber must use INTEGER`);let o=i[2];if(o!==void 0&&r!==2)throw Error(`revoked certificate extensions require CRL version 2`);let s=Fe(n,o);return{serialNumberHex:S(a.value),revocationDate:b(x(i[1],`revocationDate`)),...s.reasonCode===void 0?{}:{reasonCode:s.reasonCode},...s.invalidityDate===void 0?{}:{invalidityDate:s.invalidityDate},...s.certificateIssuer===void 0?{}:{certificateIssuer:s.certificateIssuer}}}),s+=1);let v,y,w,T,E,D=t[s];if(D?.tag===160){if(r!==2)throw Error(`CRL extensions require version 2`);let t=new Set,n=x(m(e,D)[0],`crl extensions`);for(let r of m(e,n)){let n=m(e,r);if(n.length<2||n.length>3||n.length===3&&n[1]?.tag!==1)throw Error(`Malformed CRL extension`);let i=g(x(n[0],`extension OID`).value);if(t.has(i))throw Error(`Duplicate CRL extension OID: ${i}`);t.add(i);let a=n.length===3?ee(x(n[1],`extension critical`).value):!1,o=x(n[n.length-1],`extension value`);if(o.tag!==4)throw Error(`CRL extension value must use OCTET STRING`);if(i!==C.authorityKeyIdentifier&&i!==C.cRLNumber&&i!==C.deltaCRLIndicator&&i!==C.issuingDistributionPoint&&i!==C.freshestCRL&&a)throw Error(`Unsupported critical CRL extension OID: ${i}`);i===C.authorityKeyIdentifier&&(v=Je(o.value)),i===C.cRLNumber&&(y=h(c(o.value).value)),i===C.deltaCRLIndicator&&(w=h(c(o.value).value)),i===C.issuingDistributionPoint&&(T=Ie(o.value)),i===C.freshestCRL&&(E=Le(o.value))}}return{version:r,issuer:Ge(e,a),thisUpdate:b(o),...f===void 0?{}:{nextUpdate:f},...v===void 0?{}:{authorityKeyIdentifier:v},...y===void 0?{}:{crlNumber:y},...w===void 0?{}:{baseCrlNumber:w},...T===void 0?{}:{issuingDistributionPoint:T},...E===void 0?{}:{freshestCrlDistributionPoints:E},revokedCertificates:p}}function nt(e){return rt(e)?de(new Uint8Array(e.der)):A(e)}function rt(e){return typeof e!=`string`&&`subjectPublicKeyInfoDer`in e}function it(e){return`der`in e&&e.der instanceof Uint8Array}const $=new TextDecoder;export{ve as checkCertificateRevocationAgainstCrl,ge as createCertificateRevocationList,ye as isCertificateRevoked,P as parseCertificateRevocationListDer,F as parseCertificateRevocationListPem,Ze as revocationReasonFromCode,I as validateCertificateRevocationList,_e as verifyCertificateRevocationList};
|
|
2
2
|
//# sourceMappingURL=crl.js.map
|