micro509 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/index.d.ts +13 -14
  2. package/dist/index.js +1 -1
  3. package/dist/internal/crypto/pbes2.d.ts +6 -6
  4. package/dist/internal/crypto/pbes2.js +1 -1
  5. package/dist/internal/crypto/pbes2.js.map +1 -1
  6. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  7. package/dist/internal/x509/extension-bits.js.map +1 -1
  8. package/dist/keys/keys.d.ts +15 -15
  9. package/dist/keys/keys.js +1 -1
  10. package/dist/keys/keys.js.map +1 -1
  11. package/dist/keys.d.ts +2 -3
  12. package/dist/pem/pem.d.ts +57 -6
  13. package/dist/pem/pem.js +5 -5
  14. package/dist/pem/pem.js.map +1 -1
  15. package/dist/pem.d.ts +2 -2
  16. package/dist/pem.js +1 -1
  17. package/dist/pkcs/pfx.d.ts +4 -4
  18. package/dist/pkcs/pfx.js +1 -1
  19. package/dist/pkcs/pfx.js.map +1 -1
  20. package/dist/pkcs/pkcs12-mac.d.ts +29 -5
  21. package/dist/pkcs/pkcs12-mac.js +1 -1
  22. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  23. package/dist/pkcs/pkcs7.d.ts +36 -50
  24. package/dist/pkcs/pkcs7.js +1 -1
  25. package/dist/pkcs/pkcs7.js.map +1 -1
  26. package/dist/pkcs.d.ts +3 -4
  27. package/dist/pkcs.js +1 -1
  28. package/dist/result/result.d.ts +3 -12
  29. package/dist/result/result.js.map +1 -1
  30. package/dist/result.d.ts +2 -2
  31. package/dist/result.js +1 -1
  32. package/dist/revocation/chain.d.ts +35 -34
  33. package/dist/revocation/chain.js +1 -1
  34. package/dist/revocation/chain.js.map +1 -1
  35. package/dist/revocation/crl.d.ts +40 -15
  36. package/dist/revocation/crl.js +1 -1
  37. package/dist/revocation/crl.js.map +1 -1
  38. package/dist/revocation/ocsp.d.ts +63 -13
  39. package/dist/revocation/ocsp.js +1 -1
  40. package/dist/revocation/ocsp.js.map +1 -1
  41. package/dist/revocation/revocation.d.ts +21 -19
  42. package/dist/revocation/revocation.js +1 -1
  43. package/dist/revocation/revocation.js.map +1 -1
  44. package/dist/revocation.d.ts +7 -5
  45. package/dist/revocation.js +1 -1
  46. package/dist/verify/identity.d.ts +4 -10
  47. package/dist/verify/identity.js +1 -1
  48. package/dist/verify/identity.js.map +1 -1
  49. package/dist/verify/verify.d.ts +9 -9
  50. package/dist/verify/verify.js +1 -1
  51. package/dist/verify/verify.js.map +1 -1
  52. package/dist/verify.d.ts +2 -2
  53. package/dist/x509/certificate.d.ts +2 -2
  54. package/dist/x509/certificate.js.map +1 -1
  55. package/dist/x509/csr.d.ts +2 -2
  56. package/dist/x509/csr.js.map +1 -1
  57. package/dist/x509/extensions.d.ts +21 -6
  58. package/dist/x509/extensions.js.map +1 -1
  59. package/dist/x509/parse.d.ts +3 -4
  60. package/dist/x509/parse.js +1 -1
  61. package/dist/x509/parse.js.map +1 -1
  62. package/dist/x509.d.ts +3 -4
  63. package/package.json +3 -1
  64. package/dist/internal/x509/extension-bits.d.ts +0 -18
package/dist/index.d.ts CHANGED
@@ -1,21 +1,20 @@
1
- import { Pbes2EncryptionOptions, Pbes2EncryptionScheme, Pbes2Prf } from "./internal/crypto/pbes2.js";
2
1
  import { ErrorResult, IndexedErrorResult, IndexedMicro509Error, Micro509Error, Result, ResultError, isResultError, unwrap, unwrapOr } from "./result/result.js";
3
- import { EcKeyAlgorithmInput, EcNamedCurve, Ed25519KeyAlgorithmInput, EncryptedPkcs8Options, ImportEcPublicKeyInput, ImportEd25519PublicKeyInput, ImportEncryptedKeyErrorCode, ImportEncryptedKeyFailure, ImportEncryptedKeyResult, ImportKeyErrorCode, ImportKeyFailure, ImportKeyResult, ImportRsaPublicKeyInput, KeyAlgorithmInput, KeyPairMaterial, LegacyPemEncryptionOptions, PrivateKeyImportInput, PublicKeyImportInput, RsaHash, RsaKeyAlgorithmInput, RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem } from "./keys/keys.js";
4
- import { CategorizedPemBlocks, PemBlock, categorizePemBlocks, pemDecode, pemEncode, splitPemBlocks } from "./pem/pem.js";
2
+ import { EcKeyAlgorithmInput, EcNamedCurve, Ed25519KeyAlgorithmInput, EncryptedPkcs8Options, ImportEcKeyInput, ImportEd25519KeyInput, ImportEncryptedKeyErrorCode, ImportEncryptedKeyFailure, ImportEncryptedKeyResult, ImportKeyErrorCode, ImportKeyFailure, ImportKeyResult, ImportRsaKeyInput, KeyAlgorithmInput, KeyPairMaterial, LegacyPemEncryptionOptions, PrivateKeyImportInput, PublicKeyImportInput, RsaHash, RsaKeyAlgorithmInput, RsaScheme, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem } from "./keys/keys.js";
3
+ import { CategorizePemBlocksResult, CategorizedPemBlocks, PemBlock, PemDecodeResult, PemErrorCode, PemFailure, SplitPemBlocksResult, categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow } from "./pem/pem.js";
5
4
  import { NameAttribute, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput } from "./x509/name.js";
6
- import { AuthorityInformationAccess, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, DistributionPoint, DistributionPointName, ExtendedKeyUsage, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, KeyUsage, NameConstraintForm, NameConstraints, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyQualifierInfo, SubjectAltName } from "./x509/extensions.js";
7
- import { ParsedBitFlags } from "./internal/x509/extension-bits.js";
5
+ import { AuthorityInformationAccess, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, DistributionPoint, DistributionPointName, ExtendedKeyUsage, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, NameConstraintForm, NameConstraints, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyQualifierInfo, SubjectAltName } from "./x509/extensions.js";
8
6
  import { DecodedExtensionMap, DecodedExtensionValue, ExtensionDecoder, ExtensionDecoderMap, ParseCertificateErrorCode, ParseCertificateFailure, ParseCertificateResult, ParseCertificateSigningRequestErrorCode, ParseCertificateSigningRequestFailure, ParseCertificateSigningRequestResult, ParseOptions, ParsedCertificate, ParsedCertificateSigningRequest, ParsedDistributionPoint, ParsedDistributionPointName, ParsedExtension, ParsedIssuingDistributionPoint, ParsedName, ParsedNameAttribute, ParsedRelativeDistinguishedName, decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, findExtension, parseCertificateChainPem, parseCertificateDer, parseCertificatePem, parseCertificateSigningRequestDer, parseCertificateSigningRequestPem } from "./x509/parse.js";
7
+ import { ParsePkcs12MacDataErrorCode, ParsePkcs12MacDataFailure, ParsePkcs12MacDataResult, ParsedPkcs12MacData, Pkcs12MacOptions } from "./pkcs/pkcs12-mac.js";
9
8
  import { CreatePfxErrorCode, CreatePfxFailure, CreatePfxInput, CreatePfxResult, ParsePfxErrorCode, ParsePfxFailure, ParsePfxOptions, ParsePfxResult, ParsedPfx, ParsedPfxAttribute, ParsedPfxBag, ParsedPfxBagAttributes, PfxBagAttributesInput, PfxCertificateBagInput, PfxCertificateSource, PfxEncryptionOptions, PfxMaterial, PfxPrivateKeyBagInput, PfxPrivateKeySource, createPfx, parsePfxDer, parsePfxPem } from "./pkcs/pfx.js";
10
- import { CreatePkcs7CertBagDerResult, CreatePkcs7CertBagErrorCode, CreatePkcs7CertBagFailure, CreatePkcs7CertBagResult, CreatePkcs7SignedDataDerResult, CreatePkcs7SignedDataErrorCode, CreatePkcs7SignedDataFailure, CreatePkcs7SignedDataInput, CreatePkcs7SignedDataResult, ParsePkcs7CertBagResult, ParsePkcs7ErrorCode, ParsePkcs7Failure, ParsePkcs7SignedDataResult, ParsedPkcs7SignedData, ParsedPkcs7SignerInfo, Pkcs7CertBag, Pkcs7CertificateSource, Pkcs7SignedDataMaterial, Pkcs7Signer, VerifyPkcs7SignedDataFailure, VerifyPkcs7SignedDataResult, createPkcs7CertBagDer, createPkcs7CertBagPem, createPkcs7SignedDataDer, createPkcs7SignedDataPem, parsePkcs7CertBagDer, parsePkcs7CertBagPem, parsePkcs7SignedDataDer, parsePkcs7SignedDataPem, verifyPkcs7SignedData } from "./pkcs/pkcs7.js";
11
- import { CertificateRevocationListMaterial, CheckCertificateRevocationAgainstCrlInput, CheckCertificateRevocationAgainstCrlResult, CreateCertificateRevocationListInput, CrlCertificateSource, CrlSource, ParsedCertificateRevocationList, ParsedRevokedCertificate, RevocationReason, RevokedCertificateInput, ValidateCertificateRevocationListFailure, ValidateCertificateRevocationListInput, ValidateCertificateRevocationListResult, VerifyCertificateRevocationListFailure, VerifyCertificateRevocationListResult, checkCertificateRevocationAgainstCrl, createCertificateRevocationList, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListPem, validateCertificateRevocationList, verifyCertificateRevocationList } from "./revocation/crl.js";
12
- import { CreateOcspRequestInput, CreateOcspRequestItemInput, CreateOcspResponseInput, CreateOcspSingleResponseInput, OcspCertStatus, OcspCertificateSource, OcspRequestMaterial, OcspRequestSource, OcspResponseMaterial, ParsedOcspCertId, ParsedOcspRequest, ParsedOcspResponderId, ParsedOcspResponse, ParsedOcspSingleResponse, ValidateOcspResponseFailure, ValidateOcspResponseInput, ValidateOcspResponseResult, VerifyOcspResponseFailure, VerifyOcspResponseResult, createOcspRequest, createOcspResponse, hasOcspNoCheckExtension, parseOcspRequestDer, parseOcspRequestPem, parseOcspResponseDer, parseOcspResponsePem, validateOcspResponse, verifyOcspResponse } from "./revocation/ocsp.js";
13
- import { CheckCertificateRevocationInput, CheckCertificateRevocationResult, ConfiguredOcspResponder, OcspResponderCandidate, OcspResponderSource, ResolveOcspResponderCandidatesInput, RevocationCertificateSource, RevocationCrlEvidenceInput, RevocationEvidenceInput, RevocationEvidenceKind, RevocationOcspEvidenceInput, RevocationStatus, checkCertificateRevocation, getCertificateOcspResponderUris, resolveOcspResponderCandidates } from "./revocation/revocation.js";
14
- import { CertificateRevocationStatus, CheckChainRevocationInput, CheckChainRevocationResult, CheckChainRevocationValue, RevocationExecutionError, RevocationIndeterminateReason, RevocationPolicy, RevocationSource, checkChainRevocation } from "./revocation/chain.js";
15
- import { DnsServiceIdentityInput, IpServiceIdentityInput, MatchServiceIdentityErrorCode, MatchServiceIdentityFailure, MatchServiceIdentityInput, MatchServiceIdentityResult, MatchServiceIdentitySuccess, ServiceIdentityInput, ServiceIdentityType, SrvServiceIdentityInput, UriServiceIdentityInput, VerifyServiceIdentityInput, matchCertificateServiceIdentity, matchServiceIdentity } from "./verify/identity.js";
9
+ import { CertificateMaterial, CreateCertificateInput, CreateSelfSignedCertificateInput, SelfSignedCertificateResult, ValidityInput, createCertificate, createSelfSignedCertificate } from "./x509/certificate.js";
10
+ import { CreatePkcs7CertBagErrorCode, CreatePkcs7CertBagFailure, CreatePkcs7CertBagResult, CreatePkcs7SignedDataErrorCode, CreatePkcs7SignedDataFailure, CreatePkcs7SignedDataInput, CreatePkcs7SignedDataResult, ParsePkcs7CertBagResult, ParsePkcs7ErrorCode, ParsePkcs7Failure, ParsePkcs7SignedDataResult, ParsedPkcs7SignedData, ParsedPkcs7SignerInfo, Pkcs7CertBagMaterial, Pkcs7CertificateSource, Pkcs7SignedDataMaterial, Pkcs7Signer, VerifyPkcs7SignedDataFailure, VerifyPkcs7SignedDataResult, createPkcs7CertBag, createPkcs7SignedData, parsePkcs7CertBagDer, parsePkcs7CertBagPem, parsePkcs7SignedDataDer, parsePkcs7SignedDataPem, verifyPkcs7SignedData } from "./pkcs/pkcs7.js";
11
+ import { CertificateRevocationListMaterial, CheckCertificateRevocationAgainstCrlErrorCode, CheckCertificateRevocationAgainstCrlFailure, CheckCertificateRevocationAgainstCrlFailureDetails, CheckCertificateRevocationAgainstCrlGoodValue, CheckCertificateRevocationAgainstCrlInput, CheckCertificateRevocationAgainstCrlResult, CheckCertificateRevocationAgainstCrlRevokedValue, CheckCertificateRevocationAgainstCrlValue, CreateCertificateRevocationListInput, CrlApplicabilityFailureReason, CrlCertificateSource, CrlSource, ParseCertificateRevocationListErrorCode, ParseCertificateRevocationListFailure, ParseCertificateRevocationListResult, ParsedCertificateRevocationList, ParsedRevokedCertificate, RevocationReason, RevokedCertificateInput, ValidateCertificateRevocationListFailure, ValidateCertificateRevocationListInput, ValidateCertificateRevocationListResult, VerifyCertificateRevocationListSignatureFailure, VerifyCertificateRevocationListSignatureResult, checkCertificateRevocationAgainstCrl, createCertificateRevocationList, isCertificateRevoked, parseCertificateRevocationListDer, parseCertificateRevocationListDerOrThrow, parseCertificateRevocationListPem, parseCertificateRevocationListPemOrThrow, validateCertificateRevocationList, verifyCertificateRevocationListSignature } from "./revocation/crl.js";
12
+ import { CreateOcspRequestInput, CreateOcspRequestItemInput, CreateOcspResponseInput, CreateOcspSingleResponseInput, OcspCertStatus, OcspCertificateSource, OcspHashAlgorithm, OcspRequestMaterial, OcspRequestSource, OcspResponderRevocationPolicy, OcspResponseMaterial, OcspResponseStatus, ParseOcspRequestErrorCode, ParseOcspRequestFailure, ParseOcspRequestResult, ParseOcspResponseErrorCode, ParseOcspResponseFailure, ParseOcspResponseResult, ParsedOcspCertId, ParsedOcspRequest, ParsedOcspResponderId, ParsedOcspResponse, ParsedOcspSingleResponse, ValidateOcspResponseErrorCode, ValidateOcspResponseFailure, ValidateOcspResponseInput, ValidateOcspResponseResult, VerifyOcspResponseSignatureFailure, VerifyOcspResponseSignatureResult, createOcspRequest, createOcspResponse, hasOcspNoCheckExtension, parseOcspRequestDer, parseOcspRequestDerOrThrow, parseOcspRequestPem, parseOcspRequestPemOrThrow, parseOcspResponseDer, parseOcspResponseDerOrThrow, parseOcspResponsePem, parseOcspResponsePemOrThrow, validateOcspResponse, verifyOcspResponseSignature } from "./revocation/ocsp.js";
13
+ import { CheckCertificateRevocationErrorCode, CheckCertificateRevocationFailureDetails, CheckCertificateRevocationInput, CheckCertificateRevocationResult, CheckCertificateRevocationValue, ConfiguredOcspResponder, ConfiguredOcspResponderCertificate, OcspResponderCandidate, OcspResponderSource, REVOCATION_INDETERMINATE_REASON_CODES, ResolveOcspResponderCandidatesInput, RevocationCertificateSource, RevocationCheckGoodValue, RevocationCheckIndeterminateValue, RevocationCheckRevokedValue, RevocationCrlEvidenceInput, RevocationEvidenceInput, RevocationEvidenceKind, RevocationIndeterminateEvidence, RevocationIndeterminateReasonCode, RevocationOcspEvidenceInput, RevocationStatus, checkCertificateRevocation, getCertificateOcspResponderUris, resolveOcspResponderCandidates } from "./revocation/revocation.js";
14
+ import { CertificateRevocationStatus, CheckChainRevocationInput, CheckChainRevocationResult, CheckChainRevocationValue, OcspResponseSource, REVOCATION_INDETERMINATE_REASONS, RevocationExecutionError, RevocationIndeterminateReason, RevocationPolicy, RevocationSource, checkChainRevocation } from "./revocation/chain.js";
15
+ import { DnsServiceIdentityInput, IpServiceIdentityInput, MatchServiceIdentityErrorCode, MatchServiceIdentityFailure, MatchServiceIdentityFailureDetails, MatchServiceIdentityFailureResult, MatchServiceIdentityInput, MatchServiceIdentityResult, MatchServiceIdentitySuccess, ServiceIdentityInput, ServiceIdentityType, SrvServiceIdentityInput, UriServiceIdentityInput, matchCertificateServiceIdentity, matchServiceIdentity } from "./verify/identity.js";
16
16
  import { InitialNameConstraintsInput } from "./verify/name-constraints.js";
17
- import { PolicyValidationInput } from "./verify/policy.js";
17
+ import { ConstrainedPolicy, PolicyValidationInput, PolicyValidationOutcome } from "./verify/policy.js";
18
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
- import { CertificateMaterial, CreateCertificateInput, CreateSelfSignedCertificateInput, SelfSignedCertificateResult, ValidityInput, createCertificate, createSelfSignedCertificate } from "./x509/certificate.js";
20
19
  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, 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, hasOcspNoCheckExtension, 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 };
20
+ export { type AuthorityInformationAccess, type BasicConstraints, type BuildCandidatePathInput, type BuildCandidatePathResult, type CandidatePath, type CategorizePemBlocksResult, type CategorizedPemBlocks, type CertificateExtensionsInput, type CertificateMaterial, type CertificatePolicies, type CertificateRevocationListMaterial, type CertificateRevocationStatus, type CertificateSource, type ChainRevocationInput, type CheckCertificateRevocationAgainstCrlErrorCode, type CheckCertificateRevocationAgainstCrlFailure, type CheckCertificateRevocationAgainstCrlFailureDetails, type CheckCertificateRevocationAgainstCrlGoodValue, type CheckCertificateRevocationAgainstCrlInput, type CheckCertificateRevocationAgainstCrlResult, type CheckCertificateRevocationAgainstCrlRevokedValue, type CheckCertificateRevocationAgainstCrlValue, type CheckCertificateRevocationErrorCode, type CheckCertificateRevocationFailureDetails, type CheckCertificateRevocationInput, type CheckCertificateRevocationResult, type CheckCertificateRevocationValue, type CheckChainRevocationInput, type CheckChainRevocationResult, type CheckChainRevocationValue, type ConfiguredOcspResponder, type ConfiguredOcspResponderCertificate, type ConstrainedPolicy, type CreateCertificateInput, type CreateCertificateRevocationListInput, type CreateCsrInput, type CreateOcspRequestInput, type CreateOcspRequestItemInput, type CreateOcspResponseInput, type CreateOcspSingleResponseInput, type CreatePfxErrorCode, type CreatePfxFailure, type CreatePfxInput, type CreatePfxResult, type CreatePkcs7CertBagErrorCode, type CreatePkcs7CertBagFailure, type CreatePkcs7CertBagResult, type CreatePkcs7SignedDataErrorCode, type CreatePkcs7SignedDataFailure, type CreatePkcs7SignedDataInput, type CreatePkcs7SignedDataResult, type CreateSelfSignedCertificateInput, type CrlApplicabilityFailureReason, 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 ImportEcKeyInput, type ImportEd25519KeyInput, type ImportEncryptedKeyErrorCode, type ImportEncryptedKeyFailure, type ImportEncryptedKeyResult, type ImportKeyErrorCode, type ImportKeyFailure, type ImportKeyResult, type ImportRsaKeyInput, type IndexedErrorResult, type IndexedMicro509Error, type InhibitAnyPolicy, type InitialNameConstraintsInput, type IpServiceIdentityInput, type IssuingDistributionPoint, type IssuingDistributionPointForAttributeCerts, type IssuingDistributionPointForCaCerts, type IssuingDistributionPointForUserCerts, type KeyAlgorithmInput, type KeyPairMaterial, type KeyUsage, type LegacyPemEncryptionOptions, type MatchServiceIdentityErrorCode, type MatchServiceIdentityFailure, type MatchServiceIdentityFailureDetails, type MatchServiceIdentityFailureResult, 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 OcspHashAlgorithm, type OcspRequestMaterial, type OcspRequestSource, type OcspResponderCandidate, type OcspResponderRevocationPolicy, type OcspResponderSource, type OcspResponseMaterial, type OcspResponseSource, type OcspResponseStatus, type ParseCertificateErrorCode, type ParseCertificateFailure, type ParseCertificateResult, type ParseCertificateRevocationListErrorCode, type ParseCertificateRevocationListFailure, type ParseCertificateRevocationListResult, type ParseCertificateSigningRequestErrorCode, type ParseCertificateSigningRequestFailure, type ParseCertificateSigningRequestResult, type ParseOcspRequestErrorCode, type ParseOcspRequestFailure, type ParseOcspRequestResult, type ParseOcspResponseErrorCode, type ParseOcspResponseFailure, type ParseOcspResponseResult, type ParseOptions, type ParsePfxErrorCode, type ParsePfxFailure, type ParsePfxOptions, type ParsePfxResult, type ParsePkcs12MacDataErrorCode, type ParsePkcs12MacDataFailure, type ParsePkcs12MacDataResult, 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 ParsedPkcs12MacData, type ParsedPkcs7SignedData, type ParsedPkcs7SignerInfo, type ParsedRelativeDistinguishedName, type ParsedRevokedCertificate, type PemBlock, type PemDecodeResult, type PemErrorCode, type PemFailure, type PfxBagAttributesInput, type PfxCertificateBagInput, type PfxCertificateSource, type PfxEncryptionOptions, type PfxMaterial, type PfxPrivateKeyBagInput, type PfxPrivateKeySource, type Pkcs12MacOptions, type Pkcs7CertBagMaterial, type Pkcs7CertificateSource, type Pkcs7SignedDataMaterial, type Pkcs7Signer, type PolicyConstraints, type PolicyInformation, type PolicyMapping, type PolicyMappings, type PolicyQualifierInfo, type PolicyValidationInput, type PolicyValidationOutcome, type PrivateKeyImportInput, type PublicKeyImportInput, REVOCATION_INDETERMINATE_REASONS, REVOCATION_INDETERMINATE_REASON_CODES, type RelativeDistinguishedNameInput, type ResolveOcspResponderCandidatesInput, type Result, type ResultError, type RevocationCertificateSource, type RevocationCheckGoodValue, type RevocationCheckIndeterminateValue, type RevocationCheckRevokedValue, type RevocationCrlEvidenceInput, type RevocationEvidenceInput, type RevocationEvidenceKind, type RevocationExecutionError, type RevocationIndeterminateEvidence, type RevocationIndeterminateReason, type RevocationIndeterminateReasonCode, 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 SplitPemBlocksResult, 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 ValidateOcspResponseErrorCode, type ValidateOcspResponseFailure, type ValidateOcspResponseInput, type ValidateOcspResponseResult, type ValidityInput, type VerifiedCertificateChain, type VerifyCertificateChainInput, type VerifyCertificateRevocationListSignatureFailure, type VerifyCertificateRevocationListSignatureResult, type VerifyChainFailure, type VerifyChainResult, type VerifyErrorCode, type VerifyFailureDetails, type VerifyOcspResponseSignatureFailure, type VerifyOcspResponseSignatureResult, type VerifyPkcs7SignedDataFailure, type VerifyPkcs7SignedDataResult, type VerifyPurpose, type VerifyRequestFailure, type VerifyRequestResult, buildCandidatePath, categorizePemBlocks, categorizePemBlocksOrThrow, checkCertificateRevocation, checkCertificateRevocationAgainstCrl, checkChainRevocation, checkExtendedKeyUsage, createCertificate, createCertificateRevocationList, createCertificateSigningRequest, createOcspRequest, createOcspResponse, createPfx, createPkcs7CertBag, createPkcs7SignedData, createSelfSignedCertificate, decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, findExtension, generateKeyPair, getCertificateOcspResponderUris, hasOcspNoCheckExtension, importEncryptedPkcs1Pem, importEncryptedPkcs8Der, importEncryptedPkcs8Pem, importEncryptedSec1Pem, importPkcs1Der, importPkcs1Pem, importPkcs8Base64, importPkcs8Der, importPkcs8Pem, importPrivateJwk, importPublicJwk, importSec1Der, importSec1Pem, importSpkiBase64, importSpkiDer, importSpkiPem, isCertificateRevoked, isResultError, matchCertificateServiceIdentity, matchServiceIdentity, parseCertificateChainPem, parseCertificateDer, parseCertificatePem, parseCertificateRevocationListDer, parseCertificateRevocationListDerOrThrow, parseCertificateRevocationListPem, parseCertificateRevocationListPemOrThrow, parseCertificateSigningRequestDer, parseCertificateSigningRequestPem, parseOcspRequestDer, parseOcspRequestDerOrThrow, parseOcspRequestPem, parseOcspRequestPemOrThrow, parseOcspResponseDer, parseOcspResponseDerOrThrow, parseOcspResponsePem, parseOcspResponsePemOrThrow, parsePfxDer, parsePfxPem, parsePkcs7CertBagDer, parsePkcs7CertBagPem, parsePkcs7SignedDataDer, parsePkcs7SignedDataPem, pemDecode, pemDecodeOrThrow, pemEncode, resolveOcspResponderCandidates, splitPemBlocks, splitPemBlocksOrThrow, trustAnchorFromCertificate, unwrap, unwrapOr, validateCandidatePath, validateCertificateRevocationList, validateForCa, validateForCodeSigning, validateForTlsClient, validateForTlsServer, validateOcspResponse, verifyCertificateChain, verifyCertificateRevocationListSignature, verifyCertificateSigningRequest, verifyOcspResponseSignature, 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{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,hasOcspNoCheckExtension as je,parseOcspRequestDer as Me,parseOcspRequestPem as Ne,parseOcspResponseDer as Pe,parseOcspResponsePem as Fe,validateOcspResponse as Ie,verifyOcspResponse as Le}from"./revocation/ocsp.js";import{checkCertificateRevocation as Re,getCertificateOcspResponderUris as ze,resolveOcspResponderCandidates as Be}from"./revocation/revocation.js";import{createCertificate as Ve,createSelfSignedCertificate as He}from"./x509/certificate.js";import{createCertificateSigningRequest as Ue}from"./x509/csr.js";export{ve as VERIFY_ERROR_CODES,ye as buildCandidatePath,e as categorizePemBlocks,Re as checkCertificateRevocation,ce as checkCertificateRevocationAgainstCrl,he as checkChainRevocation,be as checkExtendedKeyUsage,Ve as createCertificate,le as createCertificateRevocationList,Ue as createCertificateSigningRequest,ke as createOcspRequest,Ae as createOcspResponse,X as createPfx,$ as createPkcs7CertBagDer,ee as createPkcs7CertBagPem,te as createPkcs7SignedDataDer,ne as createPkcs7SignedDataPem,He 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,ze as getCertificateOcspResponderUris,je as hasOcspNoCheckExtension,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,Me as parseOcspRequestDer,Ne as parseOcspRequestPem,Pe as parseOcspResponseDer,Fe 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,Be 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,Ie as validateOcspResponse,De as verifyCertificateChain,me as verifyCertificateRevocationList,Oe as verifyCertificateSigningRequest,Le as verifyOcspResponse,se as verifyPkcs7SignedData};
1
+ import{isResultError as e,unwrap as t,unwrapOr as n}from"./result/result.js";import{categorizePemBlocks as r,categorizePemBlocksOrThrow as i,pemDecode as a,pemDecodeOrThrow as o,pemEncode as s,splitPemBlocks as c,splitPemBlocksOrThrow as l}from"./pem/pem.js";import{exportBinaryBase64 as u,exportEncryptedPkcs1Pem as d,exportEncryptedPkcs8Der as f,exportEncryptedPkcs8Pem as p,exportEncryptedSec1Pem as m,exportPkcs1Der as h,exportPkcs1Pem as g,exportPkcs8Der as _,exportPkcs8Pem as v,exportPrivateJwk as y,exportPublicJwk as b,exportSec1Der as x,exportSec1Pem as S,exportSpkiDer as C,exportSpkiPem as w,generateKeyPair as T,importEncryptedPkcs1Pem as E,importEncryptedPkcs8Der as D,importEncryptedPkcs8Pem as O,importEncryptedSec1Pem as k,importPkcs1Der as A,importPkcs1Pem as j,importPkcs8Base64 as M,importPkcs8Der as N,importPkcs8Pem as P,importPrivateJwk as F,importPublicJwk as I,importSec1Der as L,importSec1Pem as R,importSpkiBase64 as z,importSpkiDer as B,importSpkiPem as V}from"./keys/keys.js";import{decodeExtension as H,decodeExtensionMap as U,decodeExtensions as W,defineExtensionDecoder as G,defineExtensionDecoderMap as K,findExtension as q,parseCertificateChainPem as J,parseCertificateDer as Y,parseCertificatePem as X,parseCertificateSigningRequestDer as Z,parseCertificateSigningRequestPem as Q}from"./x509/parse.js";import{createPfx as $,parsePfxDer as ee,parsePfxPem as te}from"./pkcs/pfx.js";import{createPkcs7CertBag as ne,createPkcs7SignedData as re,parsePkcs7CertBagDer as ie,parsePkcs7CertBagPem as ae,parsePkcs7SignedDataDer as oe,parsePkcs7SignedDataPem as se,verifyPkcs7SignedData as ce}from"./pkcs/pkcs7.js";import{checkCertificateRevocationAgainstCrl as le,createCertificateRevocationList as ue,isCertificateRevoked as de,parseCertificateRevocationListDer as fe,parseCertificateRevocationListDerOrThrow as pe,parseCertificateRevocationListPem as me,parseCertificateRevocationListPemOrThrow as he,validateCertificateRevocationList as ge,verifyCertificateRevocationListSignature as _e}from"./revocation/crl.js";import{REVOCATION_INDETERMINATE_REASONS as ve,checkChainRevocation as ye}from"./revocation/chain.js";import{matchCertificateServiceIdentity as be,matchServiceIdentity as xe}from"./verify/identity.js";import{VERIFY_ERROR_CODES as Se,buildCandidatePath as Ce,checkExtendedKeyUsage as we,trustAnchorFromCertificate as Te,validateCandidatePath as Ee,validateForCa as De,validateForCodeSigning as Oe,validateForTlsClient as ke,validateForTlsServer as Ae,verifyCertificateChain as je,verifyCertificateSigningRequest as Me}from"./verify/verify.js";import{createOcspRequest as Ne,createOcspResponse as Pe,hasOcspNoCheckExtension as Fe,parseOcspRequestDer as Ie,parseOcspRequestDerOrThrow as Le,parseOcspRequestPem as Re,parseOcspRequestPemOrThrow as ze,parseOcspResponseDer as Be,parseOcspResponseDerOrThrow as Ve,parseOcspResponsePem as He,parseOcspResponsePemOrThrow as Ue,validateOcspResponse as We,verifyOcspResponseSignature as Ge}from"./revocation/ocsp.js";import{REVOCATION_INDETERMINATE_REASON_CODES as Ke,checkCertificateRevocation as qe,getCertificateOcspResponderUris as Je,resolveOcspResponderCandidates as Ye}from"./revocation/revocation.js";import{createCertificate as Xe,createSelfSignedCertificate as Ze}from"./x509/certificate.js";import{createCertificateSigningRequest as Qe}from"./x509/csr.js";export{ve as REVOCATION_INDETERMINATE_REASONS,Ke as REVOCATION_INDETERMINATE_REASON_CODES,Se as VERIFY_ERROR_CODES,Ce as buildCandidatePath,r as categorizePemBlocks,i as categorizePemBlocksOrThrow,qe as checkCertificateRevocation,le as checkCertificateRevocationAgainstCrl,ye as checkChainRevocation,we as checkExtendedKeyUsage,Xe as createCertificate,ue as createCertificateRevocationList,Qe as createCertificateSigningRequest,Ne as createOcspRequest,Pe as createOcspResponse,$ as createPfx,ne as createPkcs7CertBag,re as createPkcs7SignedData,Ze as createSelfSignedCertificate,H as decodeExtension,U as decodeExtensionMap,W as decodeExtensions,G as defineExtensionDecoder,K as defineExtensionDecoderMap,u as exportBinaryBase64,d as exportEncryptedPkcs1Pem,f as exportEncryptedPkcs8Der,p as exportEncryptedPkcs8Pem,m as exportEncryptedSec1Pem,h as exportPkcs1Der,g as exportPkcs1Pem,_ as exportPkcs8Der,v as exportPkcs8Pem,y as exportPrivateJwk,b as exportPublicJwk,x as exportSec1Der,S as exportSec1Pem,C as exportSpkiDer,w as exportSpkiPem,q as findExtension,T as generateKeyPair,Je as getCertificateOcspResponderUris,Fe as hasOcspNoCheckExtension,E as importEncryptedPkcs1Pem,D as importEncryptedPkcs8Der,O as importEncryptedPkcs8Pem,k as importEncryptedSec1Pem,A as importPkcs1Der,j as importPkcs1Pem,M as importPkcs8Base64,N as importPkcs8Der,P as importPkcs8Pem,F as importPrivateJwk,I as importPublicJwk,L as importSec1Der,R as importSec1Pem,z as importSpkiBase64,B as importSpkiDer,V as importSpkiPem,de as isCertificateRevoked,e as isResultError,be as matchCertificateServiceIdentity,xe as matchServiceIdentity,J as parseCertificateChainPem,Y as parseCertificateDer,X as parseCertificatePem,fe as parseCertificateRevocationListDer,pe as parseCertificateRevocationListDerOrThrow,me as parseCertificateRevocationListPem,he as parseCertificateRevocationListPemOrThrow,Z as parseCertificateSigningRequestDer,Q as parseCertificateSigningRequestPem,Ie as parseOcspRequestDer,Le as parseOcspRequestDerOrThrow,Re as parseOcspRequestPem,ze as parseOcspRequestPemOrThrow,Be as parseOcspResponseDer,Ve as parseOcspResponseDerOrThrow,He as parseOcspResponsePem,Ue as parseOcspResponsePemOrThrow,ee as parsePfxDer,te as parsePfxPem,ie as parsePkcs7CertBagDer,ae as parsePkcs7CertBagPem,oe as parsePkcs7SignedDataDer,se as parsePkcs7SignedDataPem,a as pemDecode,o as pemDecodeOrThrow,s as pemEncode,Ye as resolveOcspResponderCandidates,c as splitPemBlocks,l as splitPemBlocksOrThrow,Te as trustAnchorFromCertificate,t as unwrap,n as unwrapOr,Ee as validateCandidatePath,ge as validateCertificateRevocationList,De as validateForCa,Oe as validateForCodeSigning,ke as validateForTlsClient,Ae as validateForTlsServer,We as validateOcspResponse,je as verifyCertificateChain,_e as verifyCertificateRevocationListSignature,Me as verifyCertificateSigningRequest,Ge as verifyOcspResponseSignature,ce as verifyPkcs7SignedData};
@@ -1,8 +1,8 @@
1
1
  //#region src/internal/crypto/pbes2.d.ts
2
2
  /** AES-CBC key sizes supported by this PBES2 implementation. */
3
- type Pbes2EncryptionScheme = "aes128-cbc" | "aes192-cbc" | "aes256-cbc";
4
- /** PBKDF2 pseudo-random function choices. `hmac-sha1` is the RFC default; `hmac-sha256` is preferred. */
5
- type Pbes2Prf = "hmac-sha1" | "hmac-sha256";
3
+ type Pbes2EncryptionScheme = "AES-128-CBC" | "AES-192-CBC" | "AES-256-CBC";
4
+ /** PBKDF2 pseudo-random function choices. `HMAC-SHA-1` is the RFC default; `HMAC-SHA-256` is preferred. */
5
+ type Pbes2Prf = "HMAC-SHA-1" | "HMAC-SHA-256";
6
6
  /** Input for `encryptPbes2`. */
7
7
  interface Pbes2EncryptionOptions {
8
8
  /** Password fed to PBKDF2 for key derivation. */
@@ -13,9 +13,9 @@ interface Pbes2EncryptionOptions {
13
13
  readonly salt?: Uint8Array;
14
14
  /** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */
15
15
  readonly iv?: Uint8Array;
16
- /** AES key size. Default: `'aes256-cbc'`. */
17
- readonly encryption?: Pbes2EncryptionScheme;
18
- /** PBKDF2 PRF. Default: `'hmac-sha256'`. */
16
+ /** AES-CBC cipher. Default: `'AES-256-CBC'`. */
17
+ readonly cipher?: Pbes2EncryptionScheme;
18
+ /** PBKDF2 PRF. Default: `'HMAC-SHA-256'`. */
19
19
  readonly prf?: Pbes2Prf;
20
20
  }
21
21
  //#endregion
@@ -1,2 +1,2 @@
1
- import{integerFromNumber as e,nullValue as t,objectIdentifier as n,octetString as r,readSequenceChildren as i,sequence as a}from"../asn1/der.js";import{decodeIntegerNumber as o,decodeObjectIdentifier as s,toArrayBuffer as c}from"../asn1/asn1.js";import{OIDS as l}from"../asn1/oids.js";import{getCrypto as u}from"./webcrypto.js";const d=Symbol(`micro509.WrongPasswordError`);function f(e){return Object.assign(Error(e),{name:`WrongPasswordError`,[d]:!0})}function p(e){return e instanceof Error&&d in e}async function m(e,t){let n=t.iterations??1e5,r=t.salt??u().getRandomValues(new Uint8Array(16)),i=t.iv??u().getRandomValues(new Uint8Array(16)),a=t.encryption??`aes256-cbc`,o=t.prf??`hmac-sha256`;if(!Number.isInteger(n)||n<1)throw RangeError(`Invalid iterations: must be an integer >= 1, got ${n}`);if(!(r instanceof Uint8Array)||r.length<8)throw TypeError(`Invalid salt: must be Uint8Array with length >= 8, got length ${r.length}`);if(!(i instanceof Uint8Array)||i.length!==16)throw TypeError(`Invalid IV: must be Uint8Array of exactly 16 bytes, got length ${i.length}`);let s=await v(t.password,r,n,a,o,[`encrypt`]),l=new Uint8Array(await u().subtle.encrypt({name:`AES-CBC`,iv:c(i)},s,c(e)));return{algorithmIdentifierDer:g({iterations:n,salt:r,iv:i,encryption:a,prf:o}),encryptedData:l,parameters:{iterations:n,salt:r,iv:i,encryption:a,prf:o}}}async function h(e,t,n){let r=_(e),i=await v(n,r.salt,r.iterations,r.encryption,r.prf,[`decrypt`]);try{return new Uint8Array(await u().subtle.decrypt({name:`AES-CBC`,iv:c(r.iv)},i,c(t)))}catch{throw f(`Invalid password or encrypted content`)}}function g(i){let o=S(i.encryption),s=C(i.prf);return a([n(l.pbes2),a([a([n(l.pbkdf2),a([r(i.salt),e(i.iterations),e(o.keyLengthBytes),a([n(s.oid),t()])])]),a([n(o.oid),r(i.iv)])])])}function _(e){let t=i(e),n=t[0],r=t[1];if(n===void 0||r===void 0)throw Error(`Malformed PBES2 algorithm identifier`);if(s(n.value)!==l.pbes2)throw Error(`Unsupported encryption algorithm`);let a=e.slice(r.start-r.headerLength,r.end),c=i(a),u=c[0],d=c[1];if(u===void 0||d===void 0)throw Error(`Malformed PBES2 params`);let f=a.slice(u.start-u.headerLength,u.end),p=i(f),m=p[0],h=p[1];if(m===void 0||h===void 0)throw Error(`Malformed KDF params`);if(s(m.value)!==l.pbkdf2)throw Error(`Unsupported KDF`);let g=f.slice(h.start-h.headerLength,h.end),_=i(g),v=_[0],x=_[1];if(v===void 0||x===void 0||v.tag!==4)throw Error(`Malformed PBKDF2 params`);let S=_[2],C=S?.tag===2,w=C?_[3]:S,T=i(a.slice(d.start-d.headerLength,d.end)),E=T[0],D=T[1];if(E===void 0||D===void 0||D.tag!==4)throw Error(`Malformed encryption scheme`);let O=b(s(E.value));if(O===void 0)throw Error(`Unsupported content encryption scheme`);if(S!==void 0&&!C&&S.tag!==48)throw Error(`Malformed PBKDF2 params`);if(C&&o(S.value)!==O.keyLengthBytes)throw Error(`Unsupported PBKDF2 key length`);let k=y(g,w),A=o(x.value),j=new Uint8Array(v.value),M=new Uint8Array(D.value);if(A<1)throw RangeError(`Invalid PBES2 iterations: must be >= 1, got ${A}`);if(j.length<8)throw RangeError(`Invalid PBES2 salt: must be >= 8 bytes, got ${j.length}`);if(M.length!==16)throw RangeError(`Invalid PBES2 IV: must be exactly 16 bytes, got ${M.length}`);return{salt:j,iterations:A,iv:M,encryption:O.name,prf:k}}async function v(e,t,n,r,i,a){let o=S(r),s=C(i),l=await u().subtle.importKey(`raw`,new TextEncoder().encode(e),`PBKDF2`,!1,[`deriveKey`]);return u().subtle.deriveKey({name:`PBKDF2`,salt:c(t),iterations:n,hash:s.hash},l,{name:`AES-CBC`,length:o.keyLengthBits},!1,a)}function y(e,t){if(t===void 0)return`hmac-sha1`;if(t.tag!==48)throw Error(`Malformed PBKDF2 PRF`);let n=i(e.slice(t.start-t.headerLength,t.end))[0];if(n===void 0)throw Error(`Malformed PBKDF2 PRF`);let r=x(s(n.value));if(r===void 0)throw Error(`Unsupported PBKDF2 PRF`);return r}function b(e){switch(e){case l.aes128Cbc:return{name:`aes128-cbc`,oid:e,keyLengthBits:128,keyLengthBytes:16};case l.aes192Cbc:return{name:`aes192-cbc`,oid:e,keyLengthBits:192,keyLengthBytes:24};case l.aes256Cbc:return{name:`aes256-cbc`,oid:e,keyLengthBits:256,keyLengthBytes:32}}}function x(e){switch(e){case l.hmacWithSHA1:return`hmac-sha1`;case l.hmacWithSHA256:return`hmac-sha256`}}function S(e){let t=b(e===`aes128-cbc`?l.aes128Cbc:e===`aes192-cbc`?l.aes192Cbc:l.aes256Cbc);if(t===void 0)throw Error(`Unsupported content encryption scheme`);return t}function C(e){switch(e){case`hmac-sha1`:return{oid:l.hmacWithSHA1,hash:`SHA-1`};case`hmac-sha256`:return{oid:l.hmacWithSHA256,hash:`SHA-256`}}}export{h as decryptPbes2,g as encodePbes2AlgorithmIdentifier,m as encryptPbes2,p as isWrongPasswordError,_ as parsePbes2AlgorithmIdentifier,f as wrongPasswordError};
1
+ import{integerFromNumber as e,nullValue as t,objectIdentifier as n,octetString as r,readSequenceChildren as i,sequence as a}from"../asn1/der.js";import{decodeIntegerNumber as o,decodeObjectIdentifier as s,toArrayBuffer as c}from"../asn1/asn1.js";import{OIDS as l}from"../asn1/oids.js";import{getCrypto as u}from"./webcrypto.js";const d=Symbol(`micro509.WrongPasswordError`);function f(e){return Object.assign(Error(e),{name:`WrongPasswordError`,[d]:!0})}function p(e){return e instanceof Error&&d in e}async function m(e,t){let n=t.iterations??1e5,r=t.salt??u().getRandomValues(new Uint8Array(16)),i=t.iv??u().getRandomValues(new Uint8Array(16)),a=t.cipher??`AES-256-CBC`,o=t.prf??`HMAC-SHA-256`;if(!Number.isInteger(n)||n<1)throw RangeError(`Invalid iterations: must be an integer >= 1, got ${n}`);if(!(r instanceof Uint8Array)||r.length<8)throw TypeError(`Invalid salt: must be Uint8Array with length >= 8, got length ${r.length}`);if(!(i instanceof Uint8Array)||i.length!==16)throw TypeError(`Invalid IV: must be Uint8Array of exactly 16 bytes, got length ${i.length}`);let s=await v(t.password,r,n,a,o,[`encrypt`]),l=new Uint8Array(await u().subtle.encrypt({name:`AES-CBC`,iv:c(i)},s,c(e)));return{algorithmIdentifierDer:g({iterations:n,salt:r,iv:i,cipher:a,prf:o}),encryptedData:l,parameters:{iterations:n,salt:r,iv:i,cipher:a,prf:o}}}async function h(e,t,n){let r=_(e),i=await v(n,r.salt,r.iterations,r.cipher,r.prf,[`decrypt`]);try{return new Uint8Array(await u().subtle.decrypt({name:`AES-CBC`,iv:c(r.iv)},i,c(t)))}catch{throw f(`Invalid password or encrypted content`)}}function g(i){let o=S(i.cipher),s=C(i.prf);return a([n(l.pbes2),a([a([n(l.pbkdf2),a([r(i.salt),e(i.iterations),e(o.keyLengthBytes),a([n(s.oid),t()])])]),a([n(o.oid),r(i.iv)])])])}function _(e){let t=i(e),n=t[0],r=t[1];if(n===void 0||r===void 0)throw Error(`Malformed PBES2 algorithm identifier`);if(s(n.value)!==l.pbes2)throw Error(`Unsupported encryption algorithm`);let a=e.slice(r.start-r.headerLength,r.end),c=i(a),u=c[0],d=c[1];if(u===void 0||d===void 0)throw Error(`Malformed PBES2 params`);let f=a.slice(u.start-u.headerLength,u.end),p=i(f),m=p[0],h=p[1];if(m===void 0||h===void 0)throw Error(`Malformed KDF params`);if(s(m.value)!==l.pbkdf2)throw Error(`Unsupported KDF`);let g=f.slice(h.start-h.headerLength,h.end),_=i(g),v=_[0],x=_[1];if(v===void 0||x===void 0||v.tag!==4)throw Error(`Malformed PBKDF2 params`);let S=_[2],C=S?.tag===2,w=C?_[3]:S,T=i(a.slice(d.start-d.headerLength,d.end)),E=T[0],D=T[1];if(E===void 0||D===void 0||D.tag!==4)throw Error(`Malformed encryption scheme`);let O=b(s(E.value));if(O===void 0)throw Error(`Unsupported content encryption scheme`);if(S!==void 0&&!C&&S.tag!==48)throw Error(`Malformed PBKDF2 params`);if(C&&o(S.value)!==O.keyLengthBytes)throw Error(`Unsupported PBKDF2 key length`);let k=y(g,w),A=o(x.value),j=new Uint8Array(v.value),M=new Uint8Array(D.value);if(A<1)throw RangeError(`Invalid PBES2 iterations: must be >= 1, got ${A}`);if(j.length<8)throw RangeError(`Invalid PBES2 salt: must be >= 8 bytes, got ${j.length}`);if(M.length!==16)throw RangeError(`Invalid PBES2 IV: must be exactly 16 bytes, got ${M.length}`);return{salt:j,iterations:A,iv:M,cipher:O.name,prf:k}}async function v(e,t,n,r,i,a){let o=S(r),s=C(i),l=await u().subtle.importKey(`raw`,new TextEncoder().encode(e),`PBKDF2`,!1,[`deriveKey`]);return u().subtle.deriveKey({name:`PBKDF2`,salt:c(t),iterations:n,hash:s.hash},l,{name:`AES-CBC`,length:o.keyLengthBits},!1,a)}function y(e,t){if(t===void 0)return`HMAC-SHA-1`;if(t.tag!==48)throw Error(`Malformed PBKDF2 PRF`);let n=i(e.slice(t.start-t.headerLength,t.end))[0];if(n===void 0)throw Error(`Malformed PBKDF2 PRF`);let r=x(s(n.value));if(r===void 0)throw Error(`Unsupported PBKDF2 PRF`);return r}function b(e){switch(e){case l.aes128Cbc:return{name:`AES-128-CBC`,oid:e,keyLengthBits:128,keyLengthBytes:16};case l.aes192Cbc:return{name:`AES-192-CBC`,oid:e,keyLengthBits:192,keyLengthBytes:24};case l.aes256Cbc:return{name:`AES-256-CBC`,oid:e,keyLengthBits:256,keyLengthBytes:32}}}function x(e){switch(e){case l.hmacWithSHA1:return`HMAC-SHA-1`;case l.hmacWithSHA256:return`HMAC-SHA-256`}}function S(e){let t=b(e===`AES-128-CBC`?l.aes128Cbc:e===`AES-192-CBC`?l.aes192Cbc:l.aes256Cbc);if(t===void 0)throw Error(`Unsupported content encryption scheme`);return t}function C(e){switch(e){case`HMAC-SHA-1`:return{oid:l.hmacWithSHA1,hash:`SHA-1`};case`HMAC-SHA-256`:return{oid:l.hmacWithSHA256,hash:`SHA-256`}}}export{h as decryptPbes2,g as encodePbes2AlgorithmIdentifier,m as encryptPbes2,p as isWrongPasswordError,_ as parsePbes2AlgorithmIdentifier,f as wrongPasswordError};
2
2
  //# sourceMappingURL=pbes2.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pbes2.js","names":[],"sources":["../../../src/internal/crypto/pbes2.ts"],"sourcesContent":["/**\n * PBES2 password-based encryption and decryption (RFC 8018).\n *\n * Supports AES-CBC-128/192/256 with PBKDF2 using HMAC-SHA-1 or HMAC-SHA-256.\n * Used internally by encrypted PKCS#8 and PFX flows.\n *\n * @module\n */\n\nimport {\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n} from '#micro509/internal/asn1/asn1.ts';\nimport {\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { getCrypto } from './webcrypto.ts';\n\n/**\n * Thrown when PBES2 / AES-CBC decryption fails its integrity check, which in\n * practice means the supplied password was wrong (or the ciphertext was\n * corrupted). Lets callers distinguish a bad password from malformed input.\n */\n/** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */\nconst wrongPasswordBrand = Symbol('micro509.WrongPasswordError');\n\n/** Builds the branded `Error` (no class) thrown when decryption fails — a wrong password or corrupt content. */\nexport function wrongPasswordError(message: string): Error {\n\treturn Object.assign(new Error(message), {\n\t\tname: 'WrongPasswordError',\n\t\t[wrongPasswordBrand]: true,\n\t});\n}\n\n/** Type guard: was decryption rejected for a wrong password / corrupt content? */\nexport function isWrongPasswordError(value: unknown): value is Error {\n\treturn value instanceof Error && wrongPasswordBrand in value;\n}\n\n/** AES-CBC key sizes supported by this PBES2 implementation. */\nexport type Pbes2EncryptionScheme = 'aes128-cbc' | 'aes192-cbc' | 'aes256-cbc';\n\n/** PBKDF2 pseudo-random function choices. `hmac-sha1` is the RFC default; `hmac-sha256` is preferred. */\nexport type Pbes2Prf = 'hmac-sha1' | 'hmac-sha256';\n\n/** Input for `encryptPbes2`. */\nexport interface Pbes2EncryptionOptions {\n\t/** Password fed to PBKDF2 for key derivation. */\n\treadonly password: string;\n\t/** PBKDF2 iteration count. Default: `100_000`. */\n\treadonly iterations?: number;\n\t/** PBKDF2 salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n\t/** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */\n\treadonly iv?: Uint8Array;\n\t/** AES key size. Default: `'aes256-cbc'`. */\n\treadonly encryption?: Pbes2EncryptionScheme;\n\t/** PBKDF2 PRF. Default: `'hmac-sha256'`. */\n\treadonly prf?: Pbes2Prf;\n}\n\n/** Resolved PBES2 algorithm parameters, either parsed from DER or built by `encryptPbes2`. */\nexport interface Pbes2Parameters {\n\t/** PBKDF2 iteration count. */\n\treadonly iterations: number;\n\t/** PBKDF2 salt bytes. */\n\treadonly salt: Uint8Array;\n\t/** AES-CBC initialization vector. */\n\treadonly iv: Uint8Array;\n\t/** AES-CBC key-size variant. */\n\treadonly encryption: Pbes2EncryptionScheme;\n\t/** PBKDF2 pseudo-random function. */\n\treadonly prf: Pbes2Prf;\n}\n\n/** Output of `encryptPbes2`: ciphertext plus the DER-encoded AlgorithmIdentifier. */\nexport interface Pbes2EncryptionResult {\n\t/** DER-encoded PBES2 AlgorithmIdentifier SEQUENCE (embeds KDF + cipher params). */\n\treadonly algorithmIdentifierDer: Uint8Array;\n\t/** AES-CBC ciphertext (includes PKCS#7 padding). */\n\treadonly encryptedData: Uint8Array;\n\t/** Resolved algorithm parameters used during encryption. */\n\treadonly parameters: Pbes2Parameters;\n}\n\n/** Encrypts `data` using PBES2 (PBKDF2 + AES-CBC) and returns ciphertext with algorithm params. */\nexport async function encryptPbes2(\n\tdata: Uint8Array,\n\toptions: Pbes2EncryptionOptions,\n): Promise<Pbes2EncryptionResult> {\n\tconst iterations = options.iterations ?? 100_000;\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst encryption = options.encryption ?? 'aes256-cbc';\n\tconst prf = options.prf ?? 'hmac-sha256';\n\n\t// Validate inputs before any WebCrypto calls\n\tif (!Number.isInteger(iterations) || iterations < 1) {\n\t\tthrow new RangeError(`Invalid iterations: must be an integer >= 1, got ${iterations}`);\n\t}\n\tif (!(salt instanceof Uint8Array) || salt.length < 8) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid salt: must be Uint8Array with length >= 8, got length ${salt.length}`,\n\t\t);\n\t}\n\tif (!(iv instanceof Uint8Array) || iv.length !== 16) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid IV: must be Uint8Array of exactly 16 bytes, got length ${iv.length}`,\n\t\t);\n\t}\n\n\tconst key = await deriveAesKey(options.password, salt, iterations, encryption, prf, ['encrypt']);\n\tconst encryptedData = new Uint8Array(\n\t\tawait getCrypto().subtle.encrypt(\n\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(data),\n\t\t),\n\t);\n\treturn {\n\t\talgorithmIdentifierDer: encodePbes2AlgorithmIdentifier({\n\t\t\titerations,\n\t\t\tsalt,\n\t\t\tiv,\n\t\t\tencryption,\n\t\t\tprf,\n\t\t}),\n\t\tencryptedData,\n\t\tparameters: { iterations, salt, iv, encryption, prf },\n\t};\n}\n\n/** Decrypts PBES2 ciphertext given the DER AlgorithmIdentifier and password. Throws on wrong password. */\nexport async function decryptPbes2(\n\talgorithmIdentifierDer: Uint8Array,\n\tencryptedData: Uint8Array,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst parameters = parsePbes2AlgorithmIdentifier(algorithmIdentifierDer);\n\tconst key = await deriveAesKey(\n\t\tpassword,\n\t\tparameters.salt,\n\t\tparameters.iterations,\n\t\tparameters.encryption,\n\t\tparameters.prf,\n\t\t['decrypt'],\n\t);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(parameters.iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(encryptedData),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted content');\n\t}\n}\n\n/** DER-encodes a PBES2 AlgorithmIdentifier SEQUENCE from resolved parameters. */\nexport function encodePbes2AlgorithmIdentifier(parameters: Pbes2Parameters): Uint8Array {\n\tconst encryption = resolveEncryptionProfile(parameters.encryption);\n\tconst prf = resolvePrfProfile(parameters.prf);\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pbes2),\n\t\tsequence([\n\t\t\tsequence([\n\t\t\t\tobjectIdentifier(OIDS.pbkdf2),\n\t\t\t\tsequence([\n\t\t\t\t\toctetString(parameters.salt),\n\t\t\t\t\tintegerFromNumber(parameters.iterations),\n\t\t\t\t\tintegerFromNumber(encryption.keyLengthBytes),\n\t\t\t\t\tsequence([objectIdentifier(prf.oid), nullValue()]),\n\t\t\t\t]),\n\t\t\t]),\n\t\t\tsequence([objectIdentifier(encryption.oid), octetString(parameters.iv)]),\n\t\t]),\n\t]);\n}\n\n/** Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}. */\nexport function parsePbes2AlgorithmIdentifier(algorithmIdentifierDer: Uint8Array): Pbes2Parameters {\n\tconst topLevel = readSequenceChildren(algorithmIdentifierDer);\n\tconst oid = topLevel[0];\n\tconst params = topLevel[1];\n\tif (oid === undefined || params === undefined) {\n\t\tthrow new Error('Malformed PBES2 algorithm identifier');\n\t}\n\tif (decodeObjectIdentifier(oid.value) !== OIDS.pbes2) {\n\t\tthrow new Error('Unsupported encryption algorithm');\n\t}\n\tconst paramsDer = algorithmIdentifierDer.slice(params.start - params.headerLength, params.end);\n\tconst pbes2Params = readSequenceChildren(paramsDer);\n\tconst kdf = pbes2Params[0];\n\tconst scheme = pbes2Params[1];\n\tif (kdf === undefined || scheme === undefined) {\n\t\tthrow new Error('Malformed PBES2 params');\n\t}\n\tconst kdfDer = paramsDer.slice(kdf.start - kdf.headerLength, kdf.end);\n\tconst kdfChildren = readSequenceChildren(kdfDer);\n\tconst kdfOid = kdfChildren[0];\n\tconst kdfParams = kdfChildren[1];\n\tif (kdfOid === undefined || kdfParams === undefined) {\n\t\tthrow new Error('Malformed KDF params');\n\t}\n\tif (decodeObjectIdentifier(kdfOid.value) !== OIDS.pbkdf2) {\n\t\tthrow new Error('Unsupported KDF');\n\t}\n\t// PBKDF2 params: SEQUENCE { salt OCTET STRING, iterationCount INTEGER, [keyLength INTEGER], [prf AlgorithmIdentifier] }\n\tconst pbkdf2Der = kdfDer.slice(kdfParams.start - kdfParams.headerLength, kdfParams.end);\n\tconst pbkdf2Params = readSequenceChildren(pbkdf2Der);\n\tconst salt = pbkdf2Params[0];\n\tconst iterations = pbkdf2Params[1];\n\tif (salt === undefined || iterations === undefined || salt.tag !== 0x04) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tconst keyLengthElement = pbkdf2Params[2];\n\tconst hasExplicitKeyLength = keyLengthElement?.tag === 0x02;\n\tconst prfElement = hasExplicitKeyLength ? pbkdf2Params[3] : keyLengthElement;\n\tconst schemeDer = paramsDer.slice(scheme.start - scheme.headerLength, scheme.end);\n\tconst schemeChildren = readSequenceChildren(schemeDer);\n\tconst schemeOid = schemeChildren[0];\n\tconst iv = schemeChildren[1];\n\tif (schemeOid === undefined || iv === undefined || iv.tag !== 0x04) {\n\t\tthrow new Error('Malformed encryption scheme');\n\t}\n\tconst encryption = encryptionSchemeFromOid(decodeObjectIdentifier(schemeOid.value));\n\tif (encryption === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\tif (keyLengthElement !== undefined && !hasExplicitKeyLength && keyLengthElement.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tif (\n\t\thasExplicitKeyLength &&\n\t\tdecodeIntegerNumber(keyLengthElement.value) !== encryption.keyLengthBytes\n\t) {\n\t\tthrow new Error('Unsupported PBKDF2 key length');\n\t}\n\tconst prf = parsePbkdf2Prf(pbkdf2Der, prfElement);\n\n\t// Validate parsed parameters before returning\n\tconst iterationsValue = decodeIntegerNumber(iterations.value);\n\tconst saltValue = new Uint8Array(salt.value);\n\tconst ivValue = new Uint8Array(iv.value);\n\n\tif (iterationsValue < 1) {\n\t\tthrow new RangeError(`Invalid PBES2 iterations: must be >= 1, got ${iterationsValue}`);\n\t}\n\tif (saltValue.length < 8) {\n\t\tthrow new RangeError(`Invalid PBES2 salt: must be >= 8 bytes, got ${saltValue.length}`);\n\t}\n\tif (ivValue.length !== 16) {\n\t\tthrow new RangeError(`Invalid PBES2 IV: must be exactly 16 bytes, got ${ivValue.length}`);\n\t}\n\n\treturn {\n\t\tsalt: saltValue,\n\t\titerations: iterationsValue,\n\t\tiv: ivValue,\n\t\tencryption: encryption.name,\n\t\tprf,\n\t};\n}\n\n/** Derives an AES-CBC `CryptoKey` from a password via PBKDF2. */\nasync function deriveAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tencryptionName: Pbes2EncryptionScheme,\n\tprfName: Pbes2Prf,\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst encryption = resolveEncryptionProfile(encryptionName);\n\tconst prf = resolvePrfProfile(prfName);\n\tconst passwordKey = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(password),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveKey'],\n\t);\n\treturn getCrypto().subtle.deriveKey(\n\t\t{\n\t\t\tname: 'PBKDF2',\n\t\t\tsalt: toArrayBuffer(salt),\n\t\t\titerations,\n\t\t\thash: prf.hash,\n\t\t},\n\t\tpasswordKey,\n\t\t{ name: 'AES-CBC', length: encryption.keyLengthBits },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/** Parses the optional PRF AlgorithmIdentifier from PBKDF2 params. Absent means HMAC-SHA-1. */\nfunction parsePbkdf2Prf(\n\tpbkdf2Der: Uint8Array,\n\telement: ReturnType<typeof readSequenceChildren>[number] | undefined,\n): Pbes2Prf {\n\tif (element === undefined) {\n\t\treturn 'hmac-sha1';\n\t}\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prfDer = readSequenceChildren(\n\t\tpbkdf2Der.slice(element.start - element.headerLength, element.end),\n\t);\n\tconst oid = prfDer[0];\n\tif (oid === undefined) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prf = prfFromOid(decodeObjectIdentifier(oid.value));\n\tif (prf === undefined) {\n\t\tthrow new Error('Unsupported PBKDF2 PRF');\n\t}\n\treturn prf;\n}\n\n/** Maps an AES-CBC OID to the encryption profile, or `undefined` if unsupported. */\nfunction encryptionSchemeFromOid(oid: string):\n\t| {\n\t\t\treadonly name: Pbes2EncryptionScheme;\n\t\t\treadonly oid: string;\n\t\t\treadonly keyLengthBits: 128 | 192 | 256;\n\t\t\treadonly keyLengthBytes: 16 | 24 | 32;\n\t }\n\t| undefined {\n\tswitch (oid) {\n\t\tcase OIDS.aes128Cbc:\n\t\t\treturn { name: 'aes128-cbc', oid, keyLengthBits: 128, keyLengthBytes: 16 };\n\t\tcase OIDS.aes192Cbc:\n\t\t\treturn { name: 'aes192-cbc', oid, keyLengthBits: 192, keyLengthBytes: 24 };\n\t\tcase OIDS.aes256Cbc:\n\t\t\treturn { name: 'aes256-cbc', oid, keyLengthBits: 256, keyLengthBytes: 32 };\n\t}\n\treturn undefined;\n}\n\n/** Maps an HMAC OID to the PRF name, or `undefined` if unsupported. */\nfunction prfFromOid(oid: string): Pbes2Prf | undefined {\n\tswitch (oid) {\n\t\tcase OIDS.hmacWithSHA1:\n\t\t\treturn 'hmac-sha1';\n\t\tcase OIDS.hmacWithSHA256:\n\t\t\treturn 'hmac-sha256';\n\t}\n\treturn undefined;\n}\n\n/** Looks up the full encryption profile for a scheme name. Throws if unsupported. */\nfunction resolveEncryptionProfile(name: Pbes2EncryptionScheme): {\n\treadonly name: Pbes2EncryptionScheme;\n\treadonly oid: string;\n\treadonly keyLengthBits: 128 | 192 | 256;\n\treadonly keyLengthBytes: 16 | 24 | 32;\n} {\n\tconst profile = encryptionSchemeFromOid(\n\t\tname === 'aes128-cbc'\n\t\t\t? OIDS.aes128Cbc\n\t\t\t: name === 'aes192-cbc'\n\t\t\t\t? OIDS.aes192Cbc\n\t\t\t\t: OIDS.aes256Cbc,\n\t);\n\tif (profile === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\treturn profile;\n}\n\n/** Looks up OID and WebCrypto hash name for a PRF. */\nfunction resolvePrfProfile(name: Pbes2Prf): {\n\treadonly oid: string;\n\treadonly hash: 'SHA-1' | 'SHA-256';\n} {\n\tswitch (name) {\n\t\tcase 'hmac-sha1':\n\t\t\treturn { oid: OIDS.hmacWithSHA1, hash: 'SHA-1' };\n\t\tcase 'hmac-sha256':\n\t\t\treturn { oid: OIDS.hmacWithSHA256, hash: 'SHA-256' };\n\t}\n}\n"],"mappings":"wUA+BA,MAAM,EAAqB,OAAO,6BAA6B,EAG/D,SAAgB,EAAmB,EAAwB,CAC1D,OAAO,OAAO,OAAW,MAAM,CAAO,EAAG,CACxC,KAAM,sBACL,GAAqB,EACvB,CAAC,CACF,CAGA,SAAgB,EAAqB,EAAgC,CACpE,OAAO,aAAiB,OAAS,KAAsB,CACxD,CAiDA,eAAsB,EACrB,EACA,EACiC,CACjC,IAAM,EAAa,EAAQ,YAAc,IACnC,EAAO,EAAQ,MAAQ,EAAU,CAAC,CAAC,gBAAgB,IAAI,WAAW,EAAE,CAAC,EACrE,EAAK,EAAQ,IAAM,EAAU,CAAC,CAAC,gBAAgB,IAAI,WAAW,EAAE,CAAC,EACjE,EAAa,EAAQ,YAAc,aACnC,EAAM,EAAQ,KAAO,cAG3B,GAAI,CAAC,OAAO,UAAU,CAAU,GAAK,EAAa,EACjD,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IAAA,GACf,MAAO,YAER,GAAI,EAAQ,MAAQ,GACnB,MAAU,MAAM,sBAAsB,EAKvC,IAAM,EAHS,EACd,EAAU,MAAM,EAAQ,MAAQ,EAAQ,aAAc,EAAQ,GAAG,CAEjD,CAAC,CAAC,GACnB,GAAI,IAAQ,IAAA,GACX,MAAU,MAAM,sBAAsB,EAEvC,IAAM,EAAM,EAAW,EAAuB,EAAI,KAAK,CAAC,EACxD,GAAI,IAAQ,IAAA,GACX,MAAU,MAAM,wBAAwB,EAEzC,OAAO,CACR,CAGA,SAAS,EAAwB,EAOpB,CACZ,OAAQ,EAAR,CACC,KAAK,EAAK,UACT,MAAO,CAAE,KAAM,aAAc,MAAK,cAAe,IAAK,eAAgB,EAAG,EAC1E,KAAK,EAAK,UACT,MAAO,CAAE,KAAM,aAAc,MAAK,cAAe,IAAK,eAAgB,EAAG,EAC1E,KAAK,EAAK,UACT,MAAO,CAAE,KAAM,aAAc,MAAK,cAAe,IAAK,eAAgB,EAAG,CAC3E,CAED,CAGA,SAAS,EAAW,EAAmC,CACtD,OAAQ,EAAR,CACC,KAAK,EAAK,aACT,MAAO,YACR,KAAK,EAAK,eACT,MAAO,aACT,CAED,CAGA,SAAS,EAAyB,EAKhC,CACD,IAAM,EAAU,EACf,IAAS,aACN,EAAK,UACL,IAAS,aACR,EAAK,UACL,EAAK,SACV,EACA,GAAI,IAAY,IAAA,GACf,MAAU,MAAM,uCAAuC,EAExD,OAAO,CACR,CAGA,SAAS,EAAkB,EAGzB,CACD,OAAQ,EAAR,CACC,IAAK,YACJ,MAAO,CAAE,IAAK,EAAK,aAAc,KAAM,OAAQ,EAChD,IAAK,cACJ,MAAO,CAAE,IAAK,EAAK,eAAgB,KAAM,SAAU,CACrD,CACD"}
1
+ {"version":3,"file":"pbes2.js","names":[],"sources":["../../../src/internal/crypto/pbes2.ts"],"sourcesContent":["/**\n * PBES2 password-based encryption and decryption (RFC 8018).\n *\n * Supports AES-CBC-128/192/256 with PBKDF2 using HMAC-SHA-1 or HMAC-SHA-256.\n * Used internally by encrypted PKCS#8 and PFX flows.\n *\n * @module\n */\n\nimport {\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n} from '#micro509/internal/asn1/asn1.ts';\nimport {\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport { getCrypto } from './webcrypto.ts';\n\n/**\n * Thrown when PBES2 / AES-CBC decryption fails its integrity check, which in\n * practice means the supplied password was wrong (or the ciphertext was\n * corrupted). Lets callers distinguish a bad password from malformed input.\n */\n/** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */\nconst wrongPasswordBrand = Symbol('micro509.WrongPasswordError');\n\n/** Builds the branded `Error` (no class) thrown when decryption fails — a wrong password or corrupt content. */\nexport function wrongPasswordError(message: string): Error {\n\treturn Object.assign(new Error(message), {\n\t\tname: 'WrongPasswordError',\n\t\t[wrongPasswordBrand]: true,\n\t});\n}\n\n/** Type guard: was decryption rejected for a wrong password / corrupt content? */\nexport function isWrongPasswordError(value: unknown): value is Error {\n\treturn value instanceof Error && wrongPasswordBrand in value;\n}\n\n/** AES-CBC key sizes supported by this PBES2 implementation. */\nexport type Pbes2EncryptionScheme = 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n\n/** PBKDF2 pseudo-random function choices. `HMAC-SHA-1` is the RFC default; `HMAC-SHA-256` is preferred. */\nexport type Pbes2Prf = 'HMAC-SHA-1' | 'HMAC-SHA-256';\n\n/** Input for `encryptPbes2`. */\nexport interface Pbes2EncryptionOptions {\n\t/** Password fed to PBKDF2 for key derivation. */\n\treadonly password: string;\n\t/** PBKDF2 iteration count. Default: `100_000`. */\n\treadonly iterations?: number;\n\t/** PBKDF2 salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n\t/** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Default: `'AES-256-CBC'`. */\n\treadonly cipher?: Pbes2EncryptionScheme;\n\t/** PBKDF2 PRF. Default: `'HMAC-SHA-256'`. */\n\treadonly prf?: Pbes2Prf;\n}\n\n/** Resolved PBES2 algorithm parameters, either parsed from DER or built by `encryptPbes2`. */\nexport interface Pbes2Parameters {\n\t/** PBKDF2 iteration count. */\n\treadonly iterations: number;\n\t/** PBKDF2 salt bytes. */\n\treadonly salt: Uint8Array;\n\t/** AES-CBC initialization vector. */\n\treadonly iv: Uint8Array;\n\t/** AES-CBC key-size variant. */\n\treadonly cipher: Pbes2EncryptionScheme;\n\t/** PBKDF2 pseudo-random function. */\n\treadonly prf: Pbes2Prf;\n}\n\n/** Output of `encryptPbes2`: ciphertext plus the DER-encoded AlgorithmIdentifier. */\nexport interface Pbes2EncryptionResult {\n\t/** DER-encoded PBES2 AlgorithmIdentifier SEQUENCE (embeds KDF + cipher params). */\n\treadonly algorithmIdentifierDer: Uint8Array;\n\t/** AES-CBC ciphertext (includes PKCS#7 padding). */\n\treadonly encryptedData: Uint8Array;\n\t/** Resolved algorithm parameters used during encryption. */\n\treadonly parameters: Pbes2Parameters;\n}\n\n/** Encrypts `data` using PBES2 (PBKDF2 + AES-CBC) and returns ciphertext with algorithm params. */\nexport async function encryptPbes2(\n\tdata: Uint8Array,\n\toptions: Pbes2EncryptionOptions,\n): Promise<Pbes2EncryptionResult> {\n\tconst iterations = options.iterations ?? 100_000;\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst encryption = options.cipher ?? 'AES-256-CBC';\n\tconst prf = options.prf ?? 'HMAC-SHA-256';\n\n\t// Validate inputs before any WebCrypto calls\n\tif (!Number.isInteger(iterations) || iterations < 1) {\n\t\tthrow new RangeError(`Invalid iterations: must be an integer >= 1, got ${iterations}`);\n\t}\n\tif (!(salt instanceof Uint8Array) || salt.length < 8) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid salt: must be Uint8Array with length >= 8, got length ${salt.length}`,\n\t\t);\n\t}\n\tif (!(iv instanceof Uint8Array) || iv.length !== 16) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid IV: must be Uint8Array of exactly 16 bytes, got length ${iv.length}`,\n\t\t);\n\t}\n\n\tconst key = await deriveAesKey(options.password, salt, iterations, encryption, prf, ['encrypt']);\n\tconst encryptedData = new Uint8Array(\n\t\tawait getCrypto().subtle.encrypt(\n\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(data),\n\t\t),\n\t);\n\treturn {\n\t\talgorithmIdentifierDer: encodePbes2AlgorithmIdentifier({\n\t\t\titerations,\n\t\t\tsalt,\n\t\t\tiv,\n\t\t\tcipher: encryption,\n\t\t\tprf,\n\t\t}),\n\t\tencryptedData,\n\t\tparameters: { iterations, salt, iv, cipher: encryption, prf },\n\t};\n}\n\n/** Decrypts PBES2 ciphertext given the DER AlgorithmIdentifier and password. Throws on wrong password. */\nexport async function decryptPbes2(\n\talgorithmIdentifierDer: Uint8Array,\n\tencryptedData: Uint8Array,\n\tpassword: string,\n): Promise<Uint8Array> {\n\tconst parameters = parsePbes2AlgorithmIdentifier(algorithmIdentifierDer);\n\tconst key = await deriveAesKey(\n\t\tpassword,\n\t\tparameters.salt,\n\t\tparameters.iterations,\n\t\tparameters.cipher,\n\t\tparameters.prf,\n\t\t['decrypt'],\n\t);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(parameters.iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(encryptedData),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted content');\n\t}\n}\n\n/** DER-encodes a PBES2 AlgorithmIdentifier SEQUENCE from resolved parameters. */\nexport function encodePbes2AlgorithmIdentifier(parameters: Pbes2Parameters): Uint8Array {\n\tconst encryption = resolveEncryptionProfile(parameters.cipher);\n\tconst prf = resolvePrfProfile(parameters.prf);\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pbes2),\n\t\tsequence([\n\t\t\tsequence([\n\t\t\t\tobjectIdentifier(OIDS.pbkdf2),\n\t\t\t\tsequence([\n\t\t\t\t\toctetString(parameters.salt),\n\t\t\t\t\tintegerFromNumber(parameters.iterations),\n\t\t\t\t\tintegerFromNumber(encryption.keyLengthBytes),\n\t\t\t\t\tsequence([objectIdentifier(prf.oid), nullValue()]),\n\t\t\t\t]),\n\t\t\t]),\n\t\t\tsequence([objectIdentifier(encryption.oid), octetString(parameters.iv)]),\n\t\t]),\n\t]);\n}\n\n/** Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}. */\nexport function parsePbes2AlgorithmIdentifier(algorithmIdentifierDer: Uint8Array): Pbes2Parameters {\n\tconst topLevel = readSequenceChildren(algorithmIdentifierDer);\n\tconst oid = topLevel[0];\n\tconst params = topLevel[1];\n\tif (oid === undefined || params === undefined) {\n\t\tthrow new Error('Malformed PBES2 algorithm identifier');\n\t}\n\tif (decodeObjectIdentifier(oid.value) !== OIDS.pbes2) {\n\t\tthrow new Error('Unsupported encryption algorithm');\n\t}\n\tconst paramsDer = algorithmIdentifierDer.slice(params.start - params.headerLength, params.end);\n\tconst pbes2Params = readSequenceChildren(paramsDer);\n\tconst kdf = pbes2Params[0];\n\tconst scheme = pbes2Params[1];\n\tif (kdf === undefined || scheme === undefined) {\n\t\tthrow new Error('Malformed PBES2 params');\n\t}\n\tconst kdfDer = paramsDer.slice(kdf.start - kdf.headerLength, kdf.end);\n\tconst kdfChildren = readSequenceChildren(kdfDer);\n\tconst kdfOid = kdfChildren[0];\n\tconst kdfParams = kdfChildren[1];\n\tif (kdfOid === undefined || kdfParams === undefined) {\n\t\tthrow new Error('Malformed KDF params');\n\t}\n\tif (decodeObjectIdentifier(kdfOid.value) !== OIDS.pbkdf2) {\n\t\tthrow new Error('Unsupported KDF');\n\t}\n\t// PBKDF2 params: SEQUENCE { salt OCTET STRING, iterationCount INTEGER, [keyLength INTEGER], [prf AlgorithmIdentifier] }\n\tconst pbkdf2Der = kdfDer.slice(kdfParams.start - kdfParams.headerLength, kdfParams.end);\n\tconst pbkdf2Params = readSequenceChildren(pbkdf2Der);\n\tconst salt = pbkdf2Params[0];\n\tconst iterations = pbkdf2Params[1];\n\tif (salt === undefined || iterations === undefined || salt.tag !== 0x04) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tconst keyLengthElement = pbkdf2Params[2];\n\tconst hasExplicitKeyLength = keyLengthElement?.tag === 0x02;\n\tconst prfElement = hasExplicitKeyLength ? pbkdf2Params[3] : keyLengthElement;\n\tconst schemeDer = paramsDer.slice(scheme.start - scheme.headerLength, scheme.end);\n\tconst schemeChildren = readSequenceChildren(schemeDer);\n\tconst schemeOid = schemeChildren[0];\n\tconst iv = schemeChildren[1];\n\tif (schemeOid === undefined || iv === undefined || iv.tag !== 0x04) {\n\t\tthrow new Error('Malformed encryption scheme');\n\t}\n\tconst encryption = encryptionSchemeFromOid(decodeObjectIdentifier(schemeOid.value));\n\tif (encryption === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\tif (keyLengthElement !== undefined && !hasExplicitKeyLength && keyLengthElement.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tif (\n\t\thasExplicitKeyLength &&\n\t\tdecodeIntegerNumber(keyLengthElement.value) !== encryption.keyLengthBytes\n\t) {\n\t\tthrow new Error('Unsupported PBKDF2 key length');\n\t}\n\tconst prf = parsePbkdf2Prf(pbkdf2Der, prfElement);\n\n\t// Validate parsed parameters before returning\n\tconst iterationsValue = decodeIntegerNumber(iterations.value);\n\tconst saltValue = new Uint8Array(salt.value);\n\tconst ivValue = new Uint8Array(iv.value);\n\n\tif (iterationsValue < 1) {\n\t\tthrow new RangeError(`Invalid PBES2 iterations: must be >= 1, got ${iterationsValue}`);\n\t}\n\tif (saltValue.length < 8) {\n\t\tthrow new RangeError(`Invalid PBES2 salt: must be >= 8 bytes, got ${saltValue.length}`);\n\t}\n\tif (ivValue.length !== 16) {\n\t\tthrow new RangeError(`Invalid PBES2 IV: must be exactly 16 bytes, got ${ivValue.length}`);\n\t}\n\n\treturn {\n\t\tsalt: saltValue,\n\t\titerations: iterationsValue,\n\t\tiv: ivValue,\n\t\tcipher: encryption.name,\n\t\tprf,\n\t};\n}\n\n/** Derives an AES-CBC `CryptoKey` from a password via PBKDF2. */\nasync function deriveAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tencryptionName: Pbes2EncryptionScheme,\n\tprfName: Pbes2Prf,\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst encryption = resolveEncryptionProfile(encryptionName);\n\tconst prf = resolvePrfProfile(prfName);\n\tconst passwordKey = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(password),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveKey'],\n\t);\n\treturn getCrypto().subtle.deriveKey(\n\t\t{\n\t\t\tname: 'PBKDF2',\n\t\t\tsalt: toArrayBuffer(salt),\n\t\t\titerations,\n\t\t\thash: prf.hash,\n\t\t},\n\t\tpasswordKey,\n\t\t{ name: 'AES-CBC', length: encryption.keyLengthBits },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/** Parses the optional PRF AlgorithmIdentifier from PBKDF2 params. Absent means HMAC-SHA-1. */\nfunction parsePbkdf2Prf(\n\tpbkdf2Der: Uint8Array,\n\telement: ReturnType<typeof readSequenceChildren>[number] | undefined,\n): Pbes2Prf {\n\tif (element === undefined) {\n\t\treturn 'HMAC-SHA-1';\n\t}\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prfDer = readSequenceChildren(\n\t\tpbkdf2Der.slice(element.start - element.headerLength, element.end),\n\t);\n\tconst oid = prfDer[0];\n\tif (oid === undefined) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prf = prfFromOid(decodeObjectIdentifier(oid.value));\n\tif (prf === undefined) {\n\t\tthrow new Error('Unsupported PBKDF2 PRF');\n\t}\n\treturn prf;\n}\n\n/** Maps an AES-CBC OID to the encryption profile, or `undefined` if unsupported. */\nfunction encryptionSchemeFromOid(oid: string):\n\t| {\n\t\t\treadonly name: Pbes2EncryptionScheme;\n\t\t\treadonly oid: string;\n\t\t\treadonly keyLengthBits: 128 | 192 | 256;\n\t\t\treadonly keyLengthBytes: 16 | 24 | 32;\n\t }\n\t| undefined {\n\tswitch (oid) {\n\t\tcase OIDS.aes128Cbc:\n\t\t\treturn { name: 'AES-128-CBC', oid, keyLengthBits: 128, keyLengthBytes: 16 };\n\t\tcase OIDS.aes192Cbc:\n\t\t\treturn { name: 'AES-192-CBC', oid, keyLengthBits: 192, keyLengthBytes: 24 };\n\t\tcase OIDS.aes256Cbc:\n\t\t\treturn { name: 'AES-256-CBC', oid, keyLengthBits: 256, keyLengthBytes: 32 };\n\t}\n\treturn undefined;\n}\n\n/** Maps an HMAC OID to the PRF name, or `undefined` if unsupported. */\nfunction prfFromOid(oid: string): Pbes2Prf | undefined {\n\tswitch (oid) {\n\t\tcase OIDS.hmacWithSHA1:\n\t\t\treturn 'HMAC-SHA-1';\n\t\tcase OIDS.hmacWithSHA256:\n\t\t\treturn 'HMAC-SHA-256';\n\t}\n\treturn undefined;\n}\n\n/** Looks up the full encryption profile for a scheme name. Throws if unsupported. */\nfunction resolveEncryptionProfile(name: Pbes2EncryptionScheme): {\n\treadonly name: Pbes2EncryptionScheme;\n\treadonly oid: string;\n\treadonly keyLengthBits: 128 | 192 | 256;\n\treadonly keyLengthBytes: 16 | 24 | 32;\n} {\n\tconst profile = encryptionSchemeFromOid(\n\t\tname === 'AES-128-CBC'\n\t\t\t? OIDS.aes128Cbc\n\t\t\t: name === 'AES-192-CBC'\n\t\t\t\t? OIDS.aes192Cbc\n\t\t\t\t: OIDS.aes256Cbc,\n\t);\n\tif (profile === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\treturn profile;\n}\n\n/** Looks up OID and WebCrypto hash name for a PRF. */\nfunction resolvePrfProfile(name: Pbes2Prf): {\n\treadonly oid: string;\n\treadonly hash: 'SHA-1' | 'SHA-256';\n} {\n\tswitch (name) {\n\t\tcase 'HMAC-SHA-1':\n\t\t\treturn { oid: OIDS.hmacWithSHA1, hash: 'SHA-1' };\n\t\tcase 'HMAC-SHA-256':\n\t\t\treturn { oid: OIDS.hmacWithSHA256, hash: 'SHA-256' };\n\t}\n}\n"],"mappings":"wUA+BA,MAAM,EAAqB,OAAO,6BAA6B,EAG/D,SAAgB,EAAmB,EAAwB,CAC1D,OAAO,OAAO,OAAW,MAAM,CAAO,EAAG,CACxC,KAAM,sBACL,GAAqB,EACvB,CAAC,CACF,CAGA,SAAgB,EAAqB,EAAgC,CACpE,OAAO,aAAiB,OAAS,KAAsB,CACxD,CAiDA,eAAsB,EACrB,EACA,EACiC,CACjC,IAAM,EAAa,EAAQ,YAAc,IACnC,EAAO,EAAQ,MAAQ,EAAU,CAAC,CAAC,gBAAgB,IAAI,WAAW,EAAE,CAAC,EACrE,EAAK,EAAQ,IAAM,EAAU,CAAC,CAAC,gBAAgB,IAAI,WAAW,EAAE,CAAC,EACjE,EAAa,EAAQ,QAAU,cAC/B,EAAM,EAAQ,KAAO,eAG3B,GAAI,CAAC,OAAO,UAAU,CAAU,GAAK,EAAa,EACjD,MAAU,WAAW,oDAAoD,GAAY,EAEtF,GAAI,EAAE,aAAgB,aAAe,EAAK,OAAS,EAClD,MAAU,UACT,iEAAiE,EAAK,QACvE,EAED,GAAI,EAAE,aAAc,aAAe,EAAG,SAAW,GAChD,MAAU,UACT,kEAAkE,EAAG,QACtE,EA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AI,IAAQ,IAAA,GACX,MAAU,MAAM,sBAAsB,EAEvC,IAAM,EAAM,EAAW,EAAuB,EAAI,KAAK,CAAC,EACxD,GAAI,IAAQ,IAAA,GACX,MAAU,MAAM,wBAAwB,EAEzC,OAAO,CACR,CAGA,SAAS,EAAwB,EAOpB,CACZ,OAAQ,EAAR,CACC,KAAK,EAAK,UACT,MAAO,CAAE,KAAM,cAAe,MAAK,cAAe,IAAK,eAAgB,EAAG,EAC3E,KAAK,EAAK,UACT,MAAO,CAAE,KAAM,cAAe,MAAK,cAAe,IAAK,eAAgB,EAAG,EAC3E,KAAK,EAAK,UACT,MAAO,CAAE,KAAM,cAAe,MAAK,cAAe,IAAK,eAAgB,EAAG,CAC5E,CAED,CAGA,SAAS,EAAW,EAAmC,CACtD,OAAQ,EAAR,CACC,KAAK,EAAK,aACT,MAAO,aACR,KAAK,EAAK,eACT,MAAO,cACT,CAED,CAGA,SAAS,EAAyB,EAKhC,CACD,IAAM,EAAU,EACf,IAAS,cACN,EAAK,UACL,IAAS,cACR,EAAK,UACL,EAAK,SACV,EACA,GAAI,IAAY,IAAA,GACf,MAAU,MAAM,uCAAuC,EAExD,OAAO,CACR,CAGA,SAAS,EAAkB,EAGzB,CACD,OAAQ,EAAR,CACC,IAAK,aACJ,MAAO,CAAE,IAAK,EAAK,aAAc,KAAM,OAAQ,EAChD,IAAK,eACJ,MAAO,CAAE,IAAK,EAAK,eAAgB,KAAM,SAAU,CACrD,CACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"name-constraints-engine.js","names":["exhaustive"],"sources":["../../../src/internal/verify/name-constraints-engine.ts"],"sourcesContent":["/**\n * Internal name-constraints evaluation engine.\n *\n * Accumulates and evaluates the shipped RFC 5280 §4.2.1.10 / §6.1\n * name-constraint subset during certificate path validation.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\thexToBytes,\n\trequireElement,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\ttype DerElement,\n\treadRootElement,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport {\n\tcompareDistinguishedNames,\n\tisWithinDirectoryNameSubtree,\n} from '#micro509/internal/shared/dn.ts';\nimport {\n\tallOnesMaskForIpAddress,\n\tdecodeIpAddress,\n\tparseIpAddressToBytes,\n} from '#micro509/internal/shared/ip.ts';\nimport type { Micro509Error } from '#micro509/result/result.ts';\nimport type { InitialNameConstraintsInput } from '#micro509/verify/name-constraints.ts';\nimport type {\n\tNameConstraintForm,\n\tNameConstraints,\n\tParsedNameConstraintForm,\n\tSubjectAltName,\n\tUnsupportedNameConstraintForm,\n} from '#micro509/x509/extensions.ts';\nimport { nameFieldKeyFromOid } from '#micro509/x509/name.ts';\nimport type {\n\tParsedCertificate,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse.ts';\n\n/**\n * Opaque state seeded from {@linkcode InitialNameConstraintsInput} and consumed\n * by {@linkcode evaluateNameConstraints}.\n */\nexport interface NameConstraintValidationState {\n\t/** Caller-supplied permitted subtree bases (pre-chain). */\n\treadonly initialPermittedSubtrees: readonly NameConstraintForm[];\n\t/** Caller-supplied excluded subtree bases (pre-chain). */\n\treadonly initialExcludedSubtrees: readonly NameConstraintForm[];\n}\n\n/** Discriminant codes for name-constraint validation failures. */\nexport type NameConstraintValidationFailureCode =\n\t| 'name_constraints_violated'\n\t| 'unsupported_name_constraints';\n\n/** Diagnostic context attached to a name-constraint validation failure. */\nexport interface NameConstraintValidationFailureDetails {\n\t/** CN of the certificate whose name violated constraints, if available. */\n\treadonly subjectCommonName?: string;\n\t/** The name or constraint-type string that caused the violation. */\n\treadonly actual?: string;\n}\n\n/** A name-constraint check that failed, with the offending certificate's chain index. */\nexport interface NameConstraintValidationFailure\n\textends Micro509Error<\n\t\tNameConstraintValidationFailureCode,\n\t\tNameConstraintValidationFailureDetails\n\t> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n\t/** Zero-based index into the chain of the certificate that violated constraints. */\n\treadonly index: number;\n}\n\n/** Success or failure outcome of name-constraint evaluation across a chain. */\nexport type NameConstraintValidationResult =\n\t| {\n\t\t\t/** All names in the chain satisfy accumulated constraints. */\n\t\t\treadonly ok: true;\n\t }\n\t| NameConstraintValidationFailure;\n\n/** Builder input for assembling optional failure detail fields. */\ninterface NameConstraintValidationFailureDetailsInput {\n\treadonly subjectCommonName?: string | undefined;\n\treadonly actual?: string | undefined;\n}\n\ntype SubjectAltNameCheckableResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly value: NameConstraintForm | undefined;\n\t }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly actual: string;\n\t };\n\n/** Constructs a {@linkcode NameConstraintValidationFailure} with optional details. */\nfunction nameConstraintFailure(\n\tcode: NameConstraintValidationFailureCode,\n\tmessage: string,\n\tindex: number,\n\tdetails?: NameConstraintValidationFailureDetails,\n): NameConstraintValidationFailure {\n\treturn {\n\t\tok: false,\n\t\tcode,\n\t\tmessage,\n\t\tindex,\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\n/** Strips undefined fields and returns `undefined` when all fields are empty. */\nfunction nameConstraintDetails(\n\tinput: NameConstraintValidationFailureDetailsInput,\n): NameConstraintValidationFailureDetails | undefined {\n\tconst details: NameConstraintValidationFailureDetails = {\n\t\t...(input.subjectCommonName === undefined\n\t\t\t? {}\n\t\t\t: { subjectCommonName: input.subjectCommonName }),\n\t\t...(input.actual === undefined ? {} : { actual: input.actual }),\n\t};\n\treturn Object.keys(details).length === 0 ? undefined : details;\n}\n\n/** A certificate is self-issued when subject and issuer DNs are semantically equal (RFC 5280 §7.1). */\nfunction isSelfIssued(certificate: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(certificate.subject, certificate.issuer);\n}\n\n/**\n * Initializes validation state from caller-supplied initial constraints.\n *\n * Call once before {@linkcode evaluateNameConstraints}.\n */\nexport function createNameConstraintValidationState(\n\tinput: InitialNameConstraintsInput,\n): NameConstraintValidationState {\n\treturn {\n\t\tinitialPermittedSubtrees: input.permittedSubtrees?.map((subtree) => subtree.base) ?? [],\n\t\tinitialExcludedSubtrees: input.excludedSubtrees?.map((subtree) => subtree.base) ?? [],\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Private: name constraint validation (RFC 5280 §4.2.1.10 / §6.1)\n// ---------------------------------------------------------------------------\n\n/** Empty SEQUENCE DER hex — represents an empty subject DN. */\nconst EMPTY_SEQUENCE_HEX = '3000';\n\n/**\n * Accumulated name constraint state during root-to-leaf traversal.\n * - `permittedLevels`: each entry is one CA's permittedSubtrees. A name\n * must match at least one entry in *every* level (intersection semantics).\n * - `excluded`: flat list; a name must NOT match *any* entry.\n */\ninterface AccumulatedNameConstraints {\n\t/** One entry per CA that asserted permittedSubtrees; intersection semantics. */\n\treadonly permittedLevels: readonly (readonly NameConstraintForm[])[];\n\t/** Flat union of all excludedSubtrees seen so far. */\n\treadonly excluded: readonly NameConstraintForm[];\n\t/**\n\t * Name forms this engine cannot evaluate that were imposed by a\n\t * **critical** nameConstraints extension above. RFC 5280 §4.2.1.10:\n\t * a subsequent certificate carrying a name of such a form MUST be\n\t * rejected; certificates without one stay acceptable.\n\t */\n\treadonly unsupportedCriticalForms: ReadonlySet<UnsupportedNameConstraintForm['type']>;\n}\n\n/**\n * Walks the chain root-to-leaf, accumulating nameConstraints from CA\n * certificates and checking each non-self-issued certificate's names\n * against the accumulated constraints.\n *\n * RFC 5280 §6.1.3(b)–(c) for intermediates, §6.1.5(g) for the leaf.\n */\n\nexport function evaluateNameConstraints(\n\tchain: readonly ParsedCertificate[],\n\tstate: NameConstraintValidationState,\n): NameConstraintValidationResult {\n\tlet accumulated = seedInitialNameConstraints(state);\n\n\t// Seed constraints from the root (trust anchor). The root's own\n\t// names are not checked, but its nameConstraints apply to all\n\t// certificates below it in the chain.\n\tconst root = chain[chain.length - 1];\n\tif (root?.nameConstraints !== undefined) {\n\t\taccumulated = accumulateConstraints(\n\t\t\taccumulated,\n\t\t\troot.nameConstraints,\n\t\t\thasCriticalNameConstraintsExtension(root),\n\t\t);\n\t}\n\n\t// Walk from just below root toward leaf.\n\tfor (let index = chain.length - 2; index >= 0; index -= 1) {\n\t\tconst current = chain[index];\n\t\tif (current === undefined) {\n\t\t\tthrow new Error(`Certificate chain contains undefined at index ${String(index)}`);\n\t\t}\n\n\t\t// (b) If not self-issued, check names against accumulated constraints.\n\t\t// RFC 5280 §4.2.1.10: self-issued certificates are exempt UNLESS\n\t\t// they are the final certificate (leaf) in the path.\n\t\tif (!isSelfIssued(current) || index === 0) {\n\t\t\tconst nameCheckResult = checkCertificateNames(current, accumulated, index);\n\t\t\tif (!nameCheckResult.ok) {\n\t\t\t\treturn nameCheckResult;\n\t\t\t}\n\t\t}\n\n\t\t// (c) If this cert has nameConstraints, accumulate them.\n\t\tif (current.nameConstraints !== undefined) {\n\t\t\taccumulated = accumulateConstraints(\n\t\t\t\taccumulated,\n\t\t\t\tcurrent.nameConstraints,\n\t\t\t\thasCriticalNameConstraintsExtension(current),\n\t\t\t);\n\t\t}\n\t}\n\n\treturn { ok: true };\n}\n\n/** True when the certificate carries a critical nameConstraints extension. */\nfunction hasCriticalNameConstraintsExtension(certificate: ParsedCertificate): boolean {\n\treturn certificate.extensions.some(\n\t\t(entry) => entry.oid === OIDS.nameConstraints && entry.critical,\n\t);\n}\n\n/** Converts initial state into the starting accumulated-constraints snapshot. */\nfunction seedInitialNameConstraints(\n\tstate: NameConstraintValidationState,\n): AccumulatedNameConstraints {\n\treturn {\n\t\tpermittedLevels:\n\t\t\tstate.initialPermittedSubtrees.length > 0 ? [state.initialPermittedSubtrees] : [],\n\t\texcluded: state.initialExcludedSubtrees,\n\t\tunsupportedCriticalForms: new Set(),\n\t};\n}\n\n/**\n * Merges one certificate's nameConstraints extension into the running totals.\n *\n * Unsupported constraint forms from a critical extension are recorded so\n * subsequent certificates carrying a name of that form fail closed\n * (RFC 5280 §4.2.1.10). Unsupported forms in a non-critical extension are\n * dropped — the RFC's rejection requirement is scoped to critical\n * extensions (conforming CAs MUST mark nameConstraints critical anyway).\n */\nfunction accumulateConstraints(\n\tcurrent: AccumulatedNameConstraints,\n\tconstraints: NameConstraints<ParsedNameConstraintForm>,\n\tcritical: boolean,\n): AccumulatedNameConstraints {\n\tconst permittedLevels =\n\t\tconstraints.permittedSubtrees !== undefined && constraints.permittedSubtrees.length > 0\n\t\t\t? [\n\t\t\t\t\t...current.permittedLevels,\n\t\t\t\t\tconstraints.permittedSubtrees.flatMap((subtree) =>\n\t\t\t\t\t\tisSupportedNameConstraintForm(subtree.base) ? [subtree.base] : [],\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t: current.permittedLevels;\n\tconst excluded =\n\t\tconstraints.excludedSubtrees !== undefined && constraints.excludedSubtrees.length > 0\n\t\t\t? [\n\t\t\t\t\t...current.excluded,\n\t\t\t\t\t...constraints.excludedSubtrees.flatMap((subtree) =>\n\t\t\t\t\t\tisSupportedNameConstraintForm(subtree.base) ? [subtree.base] : [],\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t: current.excluded;\n\tconst newUnsupported = critical ? listUnsupportedNameConstraintTypes(constraints) : [];\n\tconst unsupportedCriticalForms =\n\t\tnewUnsupported.length > 0\n\t\t\t? new Set([...current.unsupportedCriticalForms, ...newUnsupported])\n\t\t\t: current.unsupportedCriticalForms;\n\treturn { permittedLevels, excluded, unsupportedCriticalForms };\n}\n\n/** Collects the distinct unsupported GeneralName form types from a nameConstraints extension. */\nfunction listUnsupportedNameConstraintTypes(\n\tconstraints: NameConstraints<ParsedNameConstraintForm>,\n): readonly UnsupportedNameConstraintForm['type'][] {\n\tconst unsupportedTypes = new Set<UnsupportedNameConstraintForm['type']>();\n\tfor (const subtree of constraints.permittedSubtrees ?? []) {\n\t\tif (!isSupportedNameConstraintForm(subtree.base)) {\n\t\t\tunsupportedTypes.add(subtree.base.type);\n\t\t}\n\t}\n\tfor (const subtree of constraints.excludedSubtrees ?? []) {\n\t\tif (!isSupportedNameConstraintForm(subtree.base)) {\n\t\t\tunsupportedTypes.add(subtree.base.type);\n\t\t}\n\t}\n\treturn [...unsupportedTypes];\n}\n\n/** True for name forms this engine can evaluate: dns, email, uri, ip, directoryName. */\nfunction isSupportedNameConstraintForm(form: ParsedNameConstraintForm): form is NameConstraintForm {\n\tswitch (form.type) {\n\t\tcase 'dns':\n\t\tcase 'email':\n\t\tcase 'uri':\n\t\tcase 'ip':\n\t\tcase 'directoryName':\n\t\t\treturn true;\n\t\tcase 'otherName':\n\t\tcase 'x400Address':\n\t\tcase 'ediPartyName':\n\t\tcase 'registeredID':\n\t\t\treturn false;\n\t\tdefault: {\n\t\t\tconst exhaustive: never = form;\n\t\t\tthrow new Error(`Unhandled NameConstraintForm type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Checks a certificate's subject DN and SANs against accumulated\n * name constraints. Returns a failure if any name violates constraints.\n */\nfunction checkCertificateNames(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tindex: number,\n): NameConstraintValidationResult {\n\t// Check subject DN as directoryName (if non-empty).\n\tif (certificate.subject.derHex !== EMPTY_SEQUENCE_HEX) {\n\t\tconst dnResult = isNamePermitted(\n\t\t\t{ type: 'directoryName', derHex: certificate.subject.derHex },\n\t\t\taccumulated,\n\t\t);\n\t\tif (!dnResult) {\n\t\t\treturn nameConstraintFailure(\n\t\t\t\t'name_constraints_violated',\n\t\t\t\t'subject distinguished name violates name constraints',\n\t\t\t\tindex,\n\t\t\t\tnameConstraintDetails({\n\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\t// Check each SAN.\n\tif (certificate.subjectAltNames !== undefined) {\n\t\tfor (const san of certificate.subjectAltNames) {\n\t\t\t// RFC 5280 §4.2.1.10: a critical nameConstraints extension imposing\n\t\t\t// constraints on a name form this engine cannot process forces\n\t\t\t// rejection of any subsequent certificate carrying that form.\n\t\t\tconst unsupportedForm = sanUnsupportedFormType(san);\n\t\t\tif (\n\t\t\t\tunsupportedForm !== undefined &&\n\t\t\t\taccumulated.unsupportedCriticalForms.has(unsupportedForm)\n\t\t\t) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'unsupported_name_constraints',\n\t\t\t\t\t`critical name constraints impose ${unsupportedForm} constraints that cannot be processed, and the certificate contains a ${unsupportedForm} subject alternative name`,\n\t\t\t\t\tindex,\n\t\t\t\t\tnameConstraintDetails({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: unsupportedForm,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst checkableResult = sanToConstraintCheckable(san);\n\t\t\tif (!checkableResult.ok) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'name_constraints_violated',\n\t\t\t\t\t`SAN ${checkableResult.actual} is malformed and cannot be checked against name constraints`,\n\t\t\t\t\tindex,\n\t\t\t\t\tnameConstraintDetails({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: checkableResult.actual,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst checkable = checkableResult.value;\n\t\t\tif (checkable === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isNamePermitted(checkable, accumulated)) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'name_constraints_violated',\n\t\t\t\t\t`SAN ${formatConstraintForm(checkable)} violates name constraints`,\n\t\t\t\t\tindex,\n\t\t\t\t\tnameConstraintDetails({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: formatConstraintForm(checkable),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// RFC 5280 §4.2.1.10: When constraints are imposed on the rfc822Name\n\t// name form, but the certificate does not include a SAN email, the\n\t// constraint MUST be applied to the emailAddress attribute in the\n\t// subject DN.\n\tconst hasEmailConstraints = accumulatedHasEmailConstraints(accumulated);\n\tif (hasEmailConstraints) {\n\t\tconst hasSanEmail = certificate.subjectAltNames?.some((san) => san.type === 'email') ?? false;\n\t\tif (!hasSanEmail && certificate.subject.values.emailAddress !== undefined) {\n\t\t\tconst emailForm: NameConstraintForm = {\n\t\t\t\ttype: 'email',\n\t\t\t\tvalue: certificate.subject.values.emailAddress,\n\t\t\t};\n\t\t\tif (!isNamePermitted(emailForm, accumulated)) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'name_constraints_violated',\n\t\t\t\t\t`subject emailAddress ${certificate.subject.values.emailAddress} violates name constraints`,\n\t\t\t\t\tindex,\n\t\t\t\t\tnameConstraintDetails({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: certificate.subject.values.emailAddress,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { ok: true };\n}\n\n/** True when any level of accumulated constraints addresses the email name form. */\nfunction accumulatedHasEmailConstraints(accumulated: AccumulatedNameConstraints): boolean {\n\tfor (const level of accumulated.permittedLevels) {\n\t\tif (level.some((c) => c.type === 'email')) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn accumulated.excluded.some((c) => c.type === 'email');\n}\n\n/**\n * Maps a SAN to the unsupported constraint form it instantiates, if any.\n *\n * SRV-ID SANs are otherName [0] instances. Unknown SANs carry the full DER\n * tag byte: 0xa0 otherName [0], 0xa3 x400Address [3], 0xa5 ediPartyName [5],\n * 0x88 registeredID [8].\n */\nfunction sanUnsupportedFormType(\n\tsan: SubjectAltName,\n): UnsupportedNameConstraintForm['type'] | undefined {\n\tif (san.type === 'srv') {\n\t\treturn 'otherName';\n\t}\n\tif (san.type !== 'unknown') {\n\t\treturn undefined;\n\t}\n\tswitch (san.tag) {\n\t\tcase 0xa0:\n\t\t\treturn 'otherName';\n\t\tcase 0xa3:\n\t\t\treturn 'x400Address';\n\t\tcase 0xa5:\n\t\t\treturn 'ediPartyName';\n\t\tcase 0x88:\n\t\t\treturn 'registeredID';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Converts a SubjectAltName to a NameConstraintForm for checking.\n * Returns `undefined` for name forms that don't participate in\n * constraint checking (unknown tags).\n */\nfunction sanToConstraintCheckable(san: SubjectAltName): SubjectAltNameCheckableResult {\n\tswitch (san.type) {\n\t\tcase 'dns':\n\t\t\treturn { ok: true, value: { type: 'dns', value: san.value } };\n\t\tcase 'email':\n\t\t\treturn { ok: true, value: { type: 'email', value: san.value } };\n\t\tcase 'uri':\n\t\t\treturn { ok: true, value: { type: 'uri', value: san.value } };\n\t\tcase 'srv':\n\t\t\treturn { ok: true, value: undefined };\n\t\tcase 'ip':\n\t\t\ttry {\n\t\t\t\treturn {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\ttype: 'ip',\n\t\t\t\t\t\taddressBytes: parseIpAddressToBytes(san.value),\n\t\t\t\t\t\tmaskBytes: allOnesMaskForIpAddress(san.value),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tactual: `ip:${san.value}`,\n\t\t\t\t};\n\t\t\t}\n\t\tcase 'directoryName':\n\t\t\treturn { ok: true, value: { type: 'directoryName', derHex: san.derHex } };\n\t\tcase 'unknown':\n\t\t\treturn { ok: true, value: undefined };\n\t\tdefault: {\n\t\t\tconst exhaustive: never = san;\n\t\t\tthrow new Error(`Unhandled SubjectAltName type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Checks whether a name is permitted by the accumulated constraints.\n * A name is permitted if:\n * 1. It does NOT match any excluded constraint, AND\n * 2. For every permitted level that contains constraints of the same\n * name form, it matches at least one.\n */\nfunction isNamePermitted(\n\tname: NameConstraintForm,\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\t// Check excluded — if any match, reject.\n\tfor (const constraint of accumulated.excluded) {\n\t\tif (nameMatchesConstraint(name, constraint)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t// Check permitted — for each level with relevant constraints,\n\t// the name must match at least one.\n\tfor (const level of accumulated.permittedLevels) {\n\t\tconst relevant = level.filter((constraint) => constraint.type === name.type);\n\t\tif (relevant.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!relevant.some((constraint) => nameMatchesConstraint(name, constraint))) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Dispatches to the type-specific matching function for the name form. */\nfunction nameMatchesConstraint(name: NameConstraintForm, constraint: NameConstraintForm): boolean {\n\tif (name.type === 'dns' && constraint.type === 'dns') {\n\t\treturn matchesDnsConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'email' && constraint.type === 'email') {\n\t\treturn matchesEmailConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'uri' && constraint.type === 'uri') {\n\t\treturn matchesUriConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'ip' && constraint.type === 'ip') {\n\t\treturn matchesIpConstraint(name.addressBytes, constraint.addressBytes, constraint.maskBytes);\n\t}\n\tif (name.type === 'directoryName' && constraint.type === 'directoryName') {\n\t\treturn matchesDnConstraint(name.derHex, constraint.derHex);\n\t}\n\treturn false;\n}\n\n/**\n * RFC 5280 §4.2.1.10: DNS name constraint matching.\n * Constraint \"example.com\" matches \"example.com\" and any subdomain.\n * Constraint \".example.com\" matches only subdomains, not \"example.com\" itself.\n */\nfunction matchesDnsConstraint(name: string, constraint: string): boolean {\n\tconst lowerName = name.toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.length === 0) {\n\t\treturn true;\n\t}\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn lowerName.endsWith(lowerConstraint);\n\t}\n\treturn lowerName === lowerConstraint || lowerName.endsWith(`.${lowerConstraint}`);\n}\n\n/**\n * RFC 5280 §4.2.1.10: Email constraint matching.\n * - \"user@example.com\" matches only that exact address.\n * - \"example.com\" matches any address @example.com.\n * - \".example.com\" matches any address @subdomain.example.com.\n */\nfunction matchesEmailConstraint(name: string, constraint: string): boolean {\n\tconst lowerName = name.toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.includes('@')) {\n\t\treturn lowerName === lowerConstraint;\n\t}\n\tconst atIndex = lowerName.indexOf('@');\n\tif (atIndex < 0) {\n\t\treturn false;\n\t}\n\tconst host = lowerName.slice(atIndex + 1);\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn host.endsWith(lowerConstraint);\n\t}\n\treturn host === lowerConstraint;\n}\n\n/**\n * RFC 5280 §4.2.1.10: URI constraint matching.\n * Applied to the host part of the URI.\n * - Constraint \".example.com\" matches subdomains only.\n * - Constraint \"example.com\" matches ONLY that exact host (no subdomain\n * expansion, unlike DNS constraints).\n */\nfunction matchesUriConstraint(uri: string, constraint: string): boolean {\n\tconst host = extractUriHost(uri);\n\tif (host === undefined) {\n\t\treturn false;\n\t}\n\tconst lowerHost = host.toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.length === 0) {\n\t\treturn true;\n\t}\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn lowerHost.endsWith(lowerConstraint);\n\t}\n\t// Non-period constraint: exact host match only (RFC 5280 §4.2.1.10).\n\treturn lowerHost === lowerConstraint;\n}\n\n/** Extracts the host (reg-name) portion of a URI, stripping scheme, userinfo, port, and path. */\nfunction extractUriHost(uri: string): string | undefined {\n\ttry {\n\t\tconst url = new URL(uri);\n\t\treturn url.hostname;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * RFC 5280 §4.2.1.10: IP constraint matching.\n * (nameiP & mask) == (constraintiP & mask)\n */\nfunction matchesIpConstraint(\n\tnameBytes: Uint8Array,\n\tconstraintAddr: Uint8Array,\n\tconstraintMask: Uint8Array,\n): boolean {\n\tif (nameBytes.length !== constraintAddr.length) {\n\t\treturn false;\n\t}\n\tfor (let i = 0; i < nameBytes.length; i += 1) {\n\t\tconst nameByte = nameBytes[i] ?? 0;\n\t\tconst addrByte = constraintAddr[i] ?? 0;\n\t\tconst maskByte = constraintMask[i] ?? 0;\n\t\tif ((nameByte & maskByte) !== (addrByte & maskByte)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/**\n * RFC 5280 §4.2.1.10: DirectoryName constraint matching.\n * The subject DN must equal or be subordinate to the constraint DN,\n * using RFC 5280 section 7.1 name comparison semantics.\n */\nfunction matchesDnConstraint(subjectDerHex: string, constraintDerHex: string): boolean {\n\tconst subjectName = parseDirectoryNameDerHex(subjectDerHex);\n\tconst constraintName = parseDirectoryNameDerHex(constraintDerHex);\n\tif (subjectName === undefined || constraintName === undefined) {\n\t\treturn false;\n\t}\n\treturn isWithinDirectoryNameSubtree(subjectName, constraintName);\n}\n\n/** Re-parses a hex-encoded DER Name for RDN-by-RDN comparison. Returns `undefined` on malformed input. */\nfunction parseDirectoryNameDerHex(derHex: string): ParsedName | undefined {\n\tif (!/^(?:[0-9a-fA-F]{2})+$/.test(derHex)) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\tconst bytes = hexToBytes(derHex);\n\t\tconst root = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tconst element = unwrapDirectoryNameElement(bytes, root);\n\t\tif (element.tag !== 0x30) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst rdns: ParsedRelativeDistinguishedName[] = [];\n\t\tconst attributes: ParsedNameAttribute[] = [];\n\t\tconst values: ParsedName['values'] = {};\n\t\tfor (const setElement of childrenOf(bytes, element)) {\n\t\t\tconst rdn = parseDirectoryNameRdn(bytes, setElement);\n\t\t\tif (rdn === undefined) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\trdns.push(rdn);\n\t\t\tfor (const attribute of rdn.attributes) {\n\t\t\t\tattributes.push(attribute);\n\t\t\t\tif (attribute.key !== undefined && values[attribute.key] === undefined) {\n\t\t\t\t\tvalues[attribute.key] = attribute.value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tderHex: toHex(bytes),\n\t\t\trdns,\n\t\t\tattributes,\n\t\t\tvalues,\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Unwraps doubly-nested directoryName SEQUENCE encoding.\n *\n * Some encoders produce `[4] { SEQ { SEQ { SET... } } }` instead of `[4] { SEQ { SET... } }`.\n * A single SEQUENCE child indicates the extra wrapper (valid Names have SET children).\n */\nfunction unwrapDirectoryNameElement(source: Uint8Array, element: DerElement): DerElement {\n\tif (element.tag !== 0x30) {\n\t\treturn element;\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length === 1 && child?.tag === 0x30) {\n\t\treturn child;\n\t}\n\treturn element;\n}\n\n/** Parses one SET element (a single RDN) from the DER Name SEQUENCE. */\nfunction parseDirectoryNameRdn(\n\tsource: Uint8Array,\n\tsetElement: DerElement,\n): ParsedRelativeDistinguishedName | undefined {\n\tif (setElement.tag !== 0x31) {\n\t\treturn undefined;\n\t}\n\tconst children = childrenOf(source, setElement);\n\tif (children.length === 0) {\n\t\treturn undefined;\n\t}\n\tconst attributes: ParsedNameAttribute[] = [];\n\tconst values: ParsedName['values'] = {};\n\tfor (const attributeSequence of children) {\n\t\tif (attributeSequence.tag !== 0x30) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parts = childrenOf(source, attributeSequence);\n\t\tconst oidElement = parts[0];\n\t\tconst valueElement = parts[1];\n\t\tif (oidElement === undefined || valueElement === undefined || parts.length !== 2) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (oidElement.tag !== 0x06) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst oid = decodeObjectIdentifier(requireElement(oidElement, 'directoryName OID').value);\n\t\tlet fieldValue: string;\n\t\ttry {\n\t\t\tfieldValue = decodeString(\n\t\t\t\tvalueElement.tag,\n\t\t\t\trequireElement(valueElement, 'directoryName value').value,\n\t\t\t);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst fieldKey = nameFieldKeyFromOid(oid);\n\t\tconst attribute: ParsedNameAttribute =\n\t\t\tfieldKey !== undefined\n\t\t\t\t? { oid, key: fieldKey, valueTag: valueElement.tag, value: fieldValue }\n\t\t\t\t: { oid, valueTag: valueElement.tag, value: fieldValue };\n\t\tattributes.push(attribute);\n\t\tif (fieldKey !== undefined && values[fieldKey] === undefined) {\n\t\t\tvalues[fieldKey] = fieldValue;\n\t\t}\n\t}\n\tif (attributes.length === 0) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tderHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),\n\t\tattributes,\n\t\tvalues,\n\t};\n}\n\n/** Human-readable label for a constraint form, used in error messages. */\nfunction formatConstraintForm(form: NameConstraintForm): string {\n\tswitch (form.type) {\n\t\tcase 'dns':\n\t\t\treturn `dns:${form.value}`;\n\t\tcase 'email':\n\t\t\treturn `email:${form.value}`;\n\t\tcase 'uri':\n\t\t\treturn `uri:${form.value}`;\n\t\tcase 'ip':\n\t\t\treturn `ip:${decodeIpAddress(form.addressBytes)}`;\n\t\tcase 'directoryName':\n\t\t\treturn `dn:${form.derHex.slice(0, 20)}${form.derHex.length > 20 ? '...' : ''}`;\n\t\tdefault: {\n\t\t\tconst exhaustive = form;\n\t\t\tthrow new Error(`Unhandled NameConstraintForm type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":"ueA8GA,SAAS,EACR,EACA,EACA,EACA,EACkC,CAClC,MAAO,CACN,GAAI,GACJ,OACA,UACA,QACA,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,SAAQ,CAC5C,CACD,CAGA,SAAS,EACR,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EAAoB,CAAG,EAClC,EACL,IAAa,IAAA,GAEV,CAAE,MAAK,SAAU,EAAa,IAAK,MAAO,CAAW,EADrD,CAAE,MAAK,IAAK,EAAU,SAAU,EAAa,IAAK,MAAO,CAAW,EAExE,EAAW,KAAK,CAAS,EACrB,IAAa,IAAA,IAAa,EAAO,KAAc,IAAA,KAClD,EAAO,GAAY,EAErB,CACI,KAAW,SAAW,EAG1B,MAAO,CACN,OAAQ,EAAM,EAAO,MAAM,EAAW,MAAQ,EAAW,aAAc,EAAW,GAAG,CAAC,EACtF,aACA,QACD,CACD,CAGA,SAAS,EAAqB,EAAkC,CAC/D,OAAQ,EAAK,KAAb,CACC,IAAK,MACJ,MAAO,OAAO,EAAK,QACpB,IAAK,QACJ,MAAO,SAAS,EAAK,QACtB,IAAK,MACJ,MAAO,OAAO,EAAK,QACpB,IAAK,KACJ,MAAO,MAAM,EAAgB,EAAK,YAAY,IAC/C,IAAK,gBACJ,MAAO,MAAM,EAAK,OAAO,MAAM,EAAG,EAAE,IAAI,EAAK,OAAO,OAAS,GAAK,MAAQ,KAC3E,QAEC,MAAU,MAAM,sCAAsC,OAAOA,CAAU,GAAG,CAE5E,CACD"}
1
+ {"version":3,"file":"name-constraints-engine.js","names":["exhaustive"],"sources":["../../../src/internal/verify/name-constraints-engine.ts"],"sourcesContent":["/**\n * Internal name-constraints evaluation engine.\n *\n * Accumulates and evaluates the shipped RFC 5280 §4.2.1.10 / §6.1\n * name-constraint subset during certificate path validation.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\thexToBytes,\n\trequireElement,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1.ts';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\ttype DerElement,\n\treadRootElement,\n} from '#micro509/internal/asn1/der.ts';\nimport { OIDS } from '#micro509/internal/asn1/oids.ts';\nimport {\n\tcompareDistinguishedNames,\n\tisWithinDirectoryNameSubtree,\n} from '#micro509/internal/shared/dn.ts';\nimport {\n\tallOnesMaskForIpAddress,\n\tdecodeIpAddress,\n\tparseIpAddressToBytes,\n} from '#micro509/internal/shared/ip.ts';\nimport type { Micro509Error } from '#micro509/result/result.ts';\nimport type { InitialNameConstraintsInput } from '#micro509/verify/name-constraints.ts';\nimport type {\n\tNameConstraintForm,\n\tNameConstraints,\n\tParsedNameConstraintForm,\n\tSubjectAltName,\n\tUnsupportedNameConstraintForm,\n} from '#micro509/x509/extensions.ts';\nimport { nameFieldKeyFromOid } from '#micro509/x509/name.ts';\nimport type {\n\tNameFieldKey,\n\tParsedCertificate,\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse.ts';\n\n/**\n * Opaque state seeded from {@linkcode InitialNameConstraintsInput} and consumed\n * by {@linkcode evaluateNameConstraints}.\n */\nexport interface NameConstraintValidationState {\n\t/** Caller-supplied permitted subtree bases (pre-chain). */\n\treadonly initialPermittedSubtrees: readonly NameConstraintForm[];\n\t/** Caller-supplied excluded subtree bases (pre-chain). */\n\treadonly initialExcludedSubtrees: readonly NameConstraintForm[];\n}\n\n/** Discriminant codes for name-constraint validation failures. */\nexport type NameConstraintValidationFailureCode =\n\t| 'name_constraints_violated'\n\t| 'unsupported_name_constraints';\n\n/** Diagnostic context attached to a name-constraint validation failure. */\nexport interface NameConstraintValidationFailureDetails {\n\t/** CN of the certificate whose name violated constraints, if available. */\n\treadonly subjectCommonName?: string;\n\t/** The name or constraint-type string that caused the violation. */\n\treadonly actual?: string;\n}\n\n/** A name-constraint check that failed, with the offending certificate's chain index. */\nexport interface NameConstraintValidationFailure\n\textends Micro509Error<\n\t\tNameConstraintValidationFailureCode,\n\t\tNameConstraintValidationFailureDetails\n\t> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n\t/** Zero-based index into the chain of the certificate that violated constraints. */\n\treadonly index: number;\n}\n\n/** Success or failure outcome of name-constraint evaluation across a chain. */\nexport type NameConstraintValidationResult =\n\t| {\n\t\t\t/** All names in the chain satisfy accumulated constraints. */\n\t\t\treadonly ok: true;\n\t }\n\t| NameConstraintValidationFailure;\n\n/** Builder input for assembling optional failure detail fields. */\ninterface NameConstraintValidationFailureDetailsInput {\n\treadonly subjectCommonName?: string | undefined;\n\treadonly actual?: string | undefined;\n}\n\ntype SubjectAltNameCheckableResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\treadonly value: NameConstraintForm | undefined;\n\t }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly actual: string;\n\t };\n\n/** Constructs a {@linkcode NameConstraintValidationFailure} with optional details. */\nfunction nameConstraintFailure(\n\tcode: NameConstraintValidationFailureCode,\n\tmessage: string,\n\tindex: number,\n\tdetails?: NameConstraintValidationFailureDetails,\n): NameConstraintValidationFailure {\n\treturn {\n\t\tok: false,\n\t\tcode,\n\t\tmessage,\n\t\tindex,\n\t\t...(details === undefined ? {} : { details }),\n\t};\n}\n\n/** Strips undefined fields and returns `undefined` when all fields are empty. */\nfunction nameConstraintDetails(\n\tinput: NameConstraintValidationFailureDetailsInput,\n): NameConstraintValidationFailureDetails | undefined {\n\tconst details: NameConstraintValidationFailureDetails = {\n\t\t...(input.subjectCommonName === undefined\n\t\t\t? {}\n\t\t\t: { subjectCommonName: input.subjectCommonName }),\n\t\t...(input.actual === undefined ? {} : { actual: input.actual }),\n\t};\n\treturn Object.keys(details).length === 0 ? undefined : details;\n}\n\n/** A certificate is self-issued when subject and issuer DNs are semantically equal (RFC 5280 §7.1). */\nfunction isSelfIssued(certificate: ParsedCertificate): boolean {\n\treturn compareDistinguishedNames(certificate.subject, certificate.issuer);\n}\n\n/**\n * Initializes validation state from caller-supplied initial constraints.\n *\n * Call once before {@linkcode evaluateNameConstraints}.\n */\nexport function createNameConstraintValidationState(\n\tinput: InitialNameConstraintsInput,\n): NameConstraintValidationState {\n\treturn {\n\t\tinitialPermittedSubtrees: input.permittedSubtrees?.map((subtree) => subtree.base) ?? [],\n\t\tinitialExcludedSubtrees: input.excludedSubtrees?.map((subtree) => subtree.base) ?? [],\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Private: name constraint validation (RFC 5280 §4.2.1.10 / §6.1)\n// ---------------------------------------------------------------------------\n\n/** Empty SEQUENCE DER hex — represents an empty subject DN. */\nconst EMPTY_SEQUENCE_HEX = '3000';\n\n/**\n * Accumulated name constraint state during root-to-leaf traversal.\n * - `permittedLevels`: each entry is one CA's permittedSubtrees. A name\n * must match at least one entry in *every* level (intersection semantics).\n * - `excluded`: flat list; a name must NOT match *any* entry.\n */\ninterface AccumulatedNameConstraints {\n\t/** One entry per CA that asserted permittedSubtrees; intersection semantics. */\n\treadonly permittedLevels: readonly (readonly NameConstraintForm[])[];\n\t/** Flat union of all excludedSubtrees seen so far. */\n\treadonly excluded: readonly NameConstraintForm[];\n\t/**\n\t * Name forms this engine cannot evaluate that were imposed by a\n\t * **critical** nameConstraints extension above. RFC 5280 §4.2.1.10:\n\t * a subsequent certificate carrying a name of such a form MUST be\n\t * rejected; certificates without one stay acceptable.\n\t */\n\treadonly unsupportedCriticalForms: ReadonlySet<UnsupportedNameConstraintForm['type']>;\n}\n\n/**\n * Walks the chain root-to-leaf, accumulating nameConstraints from CA\n * certificates and checking each non-self-issued certificate's names\n * against the accumulated constraints.\n *\n * RFC 5280 §6.1.3(b)–(c) for intermediates, §6.1.5(g) for the leaf.\n */\n\nexport function evaluateNameConstraints(\n\tchain: readonly ParsedCertificate[],\n\tstate: NameConstraintValidationState,\n): NameConstraintValidationResult {\n\tlet accumulated = seedInitialNameConstraints(state);\n\n\t// Seed constraints from the root (trust anchor). The root's own\n\t// names are not checked, but its nameConstraints apply to all\n\t// certificates below it in the chain.\n\tconst root = chain[chain.length - 1];\n\tif (root?.nameConstraints !== undefined) {\n\t\taccumulated = accumulateConstraints(\n\t\t\taccumulated,\n\t\t\troot.nameConstraints,\n\t\t\thasCriticalNameConstraintsExtension(root),\n\t\t);\n\t}\n\n\t// Walk from just below root toward leaf.\n\tfor (let index = chain.length - 2; index >= 0; index -= 1) {\n\t\tconst current = chain[index];\n\t\tif (current === undefined) {\n\t\t\tthrow new Error(`Certificate chain contains undefined at index ${String(index)}`);\n\t\t}\n\n\t\t// (b) If not self-issued, check names against accumulated constraints.\n\t\t// RFC 5280 §4.2.1.10: self-issued certificates are exempt UNLESS\n\t\t// they are the final certificate (leaf) in the path.\n\t\tif (!isSelfIssued(current) || index === 0) {\n\t\t\tconst nameCheckResult = checkCertificateNames(current, accumulated, index);\n\t\t\tif (!nameCheckResult.ok) {\n\t\t\t\treturn nameCheckResult;\n\t\t\t}\n\t\t}\n\n\t\t// (c) If this cert has nameConstraints, accumulate them.\n\t\tif (current.nameConstraints !== undefined) {\n\t\t\taccumulated = accumulateConstraints(\n\t\t\t\taccumulated,\n\t\t\t\tcurrent.nameConstraints,\n\t\t\t\thasCriticalNameConstraintsExtension(current),\n\t\t\t);\n\t\t}\n\t}\n\n\treturn { ok: true };\n}\n\n/** True when the certificate carries a critical nameConstraints extension. */\nfunction hasCriticalNameConstraintsExtension(certificate: ParsedCertificate): boolean {\n\treturn certificate.extensions.some(\n\t\t(entry) => entry.oid === OIDS.nameConstraints && entry.critical,\n\t);\n}\n\n/** Converts initial state into the starting accumulated-constraints snapshot. */\nfunction seedInitialNameConstraints(\n\tstate: NameConstraintValidationState,\n): AccumulatedNameConstraints {\n\treturn {\n\t\tpermittedLevels:\n\t\t\tstate.initialPermittedSubtrees.length > 0 ? [state.initialPermittedSubtrees] : [],\n\t\texcluded: state.initialExcludedSubtrees,\n\t\tunsupportedCriticalForms: new Set(),\n\t};\n}\n\n/**\n * Merges one certificate's nameConstraints extension into the running totals.\n *\n * Unsupported constraint forms from a critical extension are recorded so\n * subsequent certificates carrying a name of that form fail closed\n * (RFC 5280 §4.2.1.10). Unsupported forms in a non-critical extension are\n * dropped — the RFC's rejection requirement is scoped to critical\n * extensions (conforming CAs MUST mark nameConstraints critical anyway).\n */\nfunction accumulateConstraints(\n\tcurrent: AccumulatedNameConstraints,\n\tconstraints: NameConstraints<ParsedNameConstraintForm>,\n\tcritical: boolean,\n): AccumulatedNameConstraints {\n\tconst permittedLevels =\n\t\tconstraints.permittedSubtrees !== undefined && constraints.permittedSubtrees.length > 0\n\t\t\t? [\n\t\t\t\t\t...current.permittedLevels,\n\t\t\t\t\tconstraints.permittedSubtrees.flatMap((subtree) =>\n\t\t\t\t\t\tisSupportedNameConstraintForm(subtree.base) ? [subtree.base] : [],\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t: current.permittedLevels;\n\tconst excluded =\n\t\tconstraints.excludedSubtrees !== undefined && constraints.excludedSubtrees.length > 0\n\t\t\t? [\n\t\t\t\t\t...current.excluded,\n\t\t\t\t\t...constraints.excludedSubtrees.flatMap((subtree) =>\n\t\t\t\t\t\tisSupportedNameConstraintForm(subtree.base) ? [subtree.base] : [],\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t: current.excluded;\n\tconst newUnsupported = critical ? listUnsupportedNameConstraintTypes(constraints) : [];\n\tconst unsupportedCriticalForms =\n\t\tnewUnsupported.length > 0\n\t\t\t? new Set([...current.unsupportedCriticalForms, ...newUnsupported])\n\t\t\t: current.unsupportedCriticalForms;\n\treturn { permittedLevels, excluded, unsupportedCriticalForms };\n}\n\n/** Collects the distinct unsupported GeneralName form types from a nameConstraints extension. */\nfunction listUnsupportedNameConstraintTypes(\n\tconstraints: NameConstraints<ParsedNameConstraintForm>,\n): readonly UnsupportedNameConstraintForm['type'][] {\n\tconst unsupportedTypes = new Set<UnsupportedNameConstraintForm['type']>();\n\tfor (const subtree of constraints.permittedSubtrees ?? []) {\n\t\tif (!isSupportedNameConstraintForm(subtree.base)) {\n\t\t\tunsupportedTypes.add(subtree.base.type);\n\t\t}\n\t}\n\tfor (const subtree of constraints.excludedSubtrees ?? []) {\n\t\tif (!isSupportedNameConstraintForm(subtree.base)) {\n\t\t\tunsupportedTypes.add(subtree.base.type);\n\t\t}\n\t}\n\treturn [...unsupportedTypes];\n}\n\n/** True for name forms this engine can evaluate: dns, email, uri, ip, directoryName. */\nfunction isSupportedNameConstraintForm(form: ParsedNameConstraintForm): form is NameConstraintForm {\n\tswitch (form.type) {\n\t\tcase 'dns':\n\t\tcase 'email':\n\t\tcase 'uri':\n\t\tcase 'ip':\n\t\tcase 'directoryName':\n\t\t\treturn true;\n\t\tcase 'otherName':\n\t\tcase 'x400Address':\n\t\tcase 'ediPartyName':\n\t\tcase 'registeredID':\n\t\t\treturn false;\n\t\tdefault: {\n\t\t\tconst exhaustive: never = form;\n\t\t\tthrow new Error(`Unhandled NameConstraintForm type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Checks a certificate's subject DN and SANs against accumulated\n * name constraints. Returns a failure if any name violates constraints.\n */\nfunction checkCertificateNames(\n\tcertificate: ParsedCertificate,\n\taccumulated: AccumulatedNameConstraints,\n\tindex: number,\n): NameConstraintValidationResult {\n\t// Check subject DN as directoryName (if non-empty).\n\tif (certificate.subject.derHex !== EMPTY_SEQUENCE_HEX) {\n\t\tconst dnResult = isNamePermitted(\n\t\t\t{ type: 'directoryName', derHex: certificate.subject.derHex },\n\t\t\taccumulated,\n\t\t);\n\t\tif (!dnResult) {\n\t\t\treturn nameConstraintFailure(\n\t\t\t\t'name_constraints_violated',\n\t\t\t\t'subject distinguished name violates name constraints',\n\t\t\t\tindex,\n\t\t\t\tnameConstraintDetails({\n\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\t// Check each SAN.\n\tif (certificate.subjectAltNames !== undefined) {\n\t\tfor (const san of certificate.subjectAltNames) {\n\t\t\t// RFC 5280 §4.2.1.10: a critical nameConstraints extension imposing\n\t\t\t// constraints on a name form this engine cannot process forces\n\t\t\t// rejection of any subsequent certificate carrying that form.\n\t\t\tconst unsupportedForm = sanUnsupportedFormType(san);\n\t\t\tif (\n\t\t\t\tunsupportedForm !== undefined &&\n\t\t\t\taccumulated.unsupportedCriticalForms.has(unsupportedForm)\n\t\t\t) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'unsupported_name_constraints',\n\t\t\t\t\t`critical name constraints impose ${unsupportedForm} constraints that cannot be processed, and the certificate contains a ${unsupportedForm} subject alternative name`,\n\t\t\t\t\tindex,\n\t\t\t\t\tnameConstraintDetails({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: unsupportedForm,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst checkableResult = sanToConstraintCheckable(san);\n\t\t\tif (!checkableResult.ok) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'name_constraints_violated',\n\t\t\t\t\t`SAN ${checkableResult.actual} is malformed and cannot be checked against name constraints`,\n\t\t\t\t\tindex,\n\t\t\t\t\tnameConstraintDetails({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: checkableResult.actual,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst checkable = checkableResult.value;\n\t\t\tif (checkable === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isNamePermitted(checkable, accumulated)) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'name_constraints_violated',\n\t\t\t\t\t`SAN ${formatConstraintForm(checkable)} violates name constraints`,\n\t\t\t\t\tindex,\n\t\t\t\t\tnameConstraintDetails({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: formatConstraintForm(checkable),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// RFC 5280 §4.2.1.10: When constraints are imposed on the rfc822Name\n\t// name form, but the certificate does not include a SAN email, the\n\t// constraint MUST be applied to the emailAddress attribute in the\n\t// subject DN.\n\tconst hasEmailConstraints = accumulatedHasEmailConstraints(accumulated);\n\tif (hasEmailConstraints) {\n\t\tconst hasSanEmail = certificate.subjectAltNames?.some((san) => san.type === 'email') ?? false;\n\t\tif (!hasSanEmail && certificate.subject.values.emailAddress !== undefined) {\n\t\t\tconst emailForm: NameConstraintForm = {\n\t\t\t\ttype: 'email',\n\t\t\t\tvalue: certificate.subject.values.emailAddress,\n\t\t\t};\n\t\t\tif (!isNamePermitted(emailForm, accumulated)) {\n\t\t\t\treturn nameConstraintFailure(\n\t\t\t\t\t'name_constraints_violated',\n\t\t\t\t\t`subject emailAddress ${certificate.subject.values.emailAddress} violates name constraints`,\n\t\t\t\t\tindex,\n\t\t\t\t\tnameConstraintDetails({\n\t\t\t\t\t\tsubjectCommonName: certificate.subject.values.commonName,\n\t\t\t\t\t\tactual: certificate.subject.values.emailAddress,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { ok: true };\n}\n\n/** True when any level of accumulated constraints addresses the email name form. */\nfunction accumulatedHasEmailConstraints(accumulated: AccumulatedNameConstraints): boolean {\n\tfor (const level of accumulated.permittedLevels) {\n\t\tif (level.some((c) => c.type === 'email')) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn accumulated.excluded.some((c) => c.type === 'email');\n}\n\n/**\n * Maps a SAN to the unsupported constraint form it instantiates, if any.\n *\n * SRV-ID SANs are otherName [0] instances. Unknown SANs carry the full DER\n * tag byte: 0xa0 otherName [0], 0xa3 x400Address [3], 0xa5 ediPartyName [5],\n * 0x88 registeredID [8].\n */\nfunction sanUnsupportedFormType(\n\tsan: SubjectAltName,\n): UnsupportedNameConstraintForm['type'] | undefined {\n\tif (san.type === 'srv') {\n\t\treturn 'otherName';\n\t}\n\tif (san.type !== 'unknown') {\n\t\treturn undefined;\n\t}\n\tswitch (san.tag) {\n\t\tcase 0xa0:\n\t\t\treturn 'otherName';\n\t\tcase 0xa3:\n\t\t\treturn 'x400Address';\n\t\tcase 0xa5:\n\t\t\treturn 'ediPartyName';\n\t\tcase 0x88:\n\t\t\treturn 'registeredID';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Converts a SubjectAltName to a NameConstraintForm for checking.\n * Returns `undefined` for name forms that don't participate in\n * constraint checking (unknown tags).\n */\nfunction sanToConstraintCheckable(san: SubjectAltName): SubjectAltNameCheckableResult {\n\tswitch (san.type) {\n\t\tcase 'dns':\n\t\t\treturn { ok: true, value: { type: 'dns', value: san.value } };\n\t\tcase 'email':\n\t\t\treturn { ok: true, value: { type: 'email', value: san.value } };\n\t\tcase 'uri':\n\t\t\treturn { ok: true, value: { type: 'uri', value: san.value } };\n\t\tcase 'srv':\n\t\t\treturn { ok: true, value: undefined };\n\t\tcase 'ip':\n\t\t\ttry {\n\t\t\t\treturn {\n\t\t\t\t\tok: true,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\ttype: 'ip',\n\t\t\t\t\t\taddressBytes: parseIpAddressToBytes(san.value),\n\t\t\t\t\t\tmaskBytes: allOnesMaskForIpAddress(san.value),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tactual: `ip:${san.value}`,\n\t\t\t\t};\n\t\t\t}\n\t\tcase 'directoryName':\n\t\t\treturn { ok: true, value: { type: 'directoryName', derHex: san.derHex } };\n\t\tcase 'unknown':\n\t\t\treturn { ok: true, value: undefined };\n\t\tdefault: {\n\t\t\tconst exhaustive: never = san;\n\t\t\tthrow new Error(`Unhandled SubjectAltName type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Checks whether a name is permitted by the accumulated constraints.\n * A name is permitted if:\n * 1. It does NOT match any excluded constraint, AND\n * 2. For every permitted level that contains constraints of the same\n * name form, it matches at least one.\n */\nfunction isNamePermitted(\n\tname: NameConstraintForm,\n\taccumulated: AccumulatedNameConstraints,\n): boolean {\n\t// Check excluded — if any match, reject.\n\tfor (const constraint of accumulated.excluded) {\n\t\tif (nameMatchesConstraint(name, constraint)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t// Check permitted — for each level with relevant constraints,\n\t// the name must match at least one.\n\tfor (const level of accumulated.permittedLevels) {\n\t\tconst relevant = level.filter((constraint) => constraint.type === name.type);\n\t\tif (relevant.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!relevant.some((constraint) => nameMatchesConstraint(name, constraint))) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Dispatches to the type-specific matching function for the name form. */\nfunction nameMatchesConstraint(name: NameConstraintForm, constraint: NameConstraintForm): boolean {\n\tif (name.type === 'dns' && constraint.type === 'dns') {\n\t\treturn matchesDnsConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'email' && constraint.type === 'email') {\n\t\treturn matchesEmailConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'uri' && constraint.type === 'uri') {\n\t\treturn matchesUriConstraint(name.value, constraint.value);\n\t}\n\tif (name.type === 'ip' && constraint.type === 'ip') {\n\t\treturn matchesIpConstraint(name.addressBytes, constraint.addressBytes, constraint.maskBytes);\n\t}\n\tif (name.type === 'directoryName' && constraint.type === 'directoryName') {\n\t\treturn matchesDnConstraint(name.derHex, constraint.derHex);\n\t}\n\treturn false;\n}\n\n/**\n * RFC 5280 §4.2.1.10: DNS name constraint matching.\n * Constraint \"example.com\" matches \"example.com\" and any subdomain.\n * Constraint \".example.com\" matches only subdomains, not \"example.com\" itself.\n */\nfunction matchesDnsConstraint(name: string, constraint: string): boolean {\n\tconst lowerName = name.toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.length === 0) {\n\t\treturn true;\n\t}\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn lowerName.endsWith(lowerConstraint);\n\t}\n\treturn lowerName === lowerConstraint || lowerName.endsWith(`.${lowerConstraint}`);\n}\n\n/**\n * RFC 5280 §4.2.1.10: Email constraint matching.\n * - \"user@example.com\" matches only that exact address.\n * - \"example.com\" matches any address @example.com.\n * - \".example.com\" matches any address @subdomain.example.com.\n */\nfunction matchesEmailConstraint(name: string, constraint: string): boolean {\n\tconst lowerName = name.toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.includes('@')) {\n\t\treturn lowerName === lowerConstraint;\n\t}\n\tconst atIndex = lowerName.indexOf('@');\n\tif (atIndex < 0) {\n\t\treturn false;\n\t}\n\tconst host = lowerName.slice(atIndex + 1);\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn host.endsWith(lowerConstraint);\n\t}\n\treturn host === lowerConstraint;\n}\n\n/**\n * RFC 5280 §4.2.1.10: URI constraint matching.\n * Applied to the host part of the URI.\n * - Constraint \".example.com\" matches subdomains only.\n * - Constraint \"example.com\" matches ONLY that exact host (no subdomain\n * expansion, unlike DNS constraints).\n */\nfunction matchesUriConstraint(uri: string, constraint: string): boolean {\n\tconst host = extractUriHost(uri);\n\tif (host === undefined) {\n\t\treturn false;\n\t}\n\tconst lowerHost = host.toLowerCase();\n\tconst lowerConstraint = constraint.toLowerCase();\n\tif (lowerConstraint.length === 0) {\n\t\treturn true;\n\t}\n\tif (lowerConstraint.startsWith('.')) {\n\t\treturn lowerHost.endsWith(lowerConstraint);\n\t}\n\t// Non-period constraint: exact host match only (RFC 5280 §4.2.1.10).\n\treturn lowerHost === lowerConstraint;\n}\n\n/** Extracts the host (reg-name) portion of a URI, stripping scheme, userinfo, port, and path. */\nfunction extractUriHost(uri: string): string | undefined {\n\ttry {\n\t\tconst url = new URL(uri);\n\t\treturn url.hostname;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * RFC 5280 §4.2.1.10: IP constraint matching.\n * (nameiP & mask) == (constraintiP & mask)\n */\nfunction matchesIpConstraint(\n\tnameBytes: Uint8Array,\n\tconstraintAddr: Uint8Array,\n\tconstraintMask: Uint8Array,\n): boolean {\n\tif (nameBytes.length !== constraintAddr.length) {\n\t\treturn false;\n\t}\n\tfor (let i = 0; i < nameBytes.length; i += 1) {\n\t\tconst nameByte = nameBytes[i] ?? 0;\n\t\tconst addrByte = constraintAddr[i] ?? 0;\n\t\tconst maskByte = constraintMask[i] ?? 0;\n\t\tif ((nameByte & maskByte) !== (addrByte & maskByte)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/**\n * RFC 5280 §4.2.1.10: DirectoryName constraint matching.\n * The subject DN must equal or be subordinate to the constraint DN,\n * using RFC 5280 section 7.1 name comparison semantics.\n */\nfunction matchesDnConstraint(subjectDerHex: string, constraintDerHex: string): boolean {\n\tconst subjectName = parseDirectoryNameDerHex(subjectDerHex);\n\tconst constraintName = parseDirectoryNameDerHex(constraintDerHex);\n\tif (subjectName === undefined || constraintName === undefined) {\n\t\treturn false;\n\t}\n\treturn isWithinDirectoryNameSubtree(subjectName, constraintName);\n}\n\n/** Re-parses a hex-encoded DER Name for RDN-by-RDN comparison. Returns `undefined` on malformed input. */\nfunction parseDirectoryNameDerHex(derHex: string): ParsedName | undefined {\n\tif (!/^(?:[0-9a-fA-F]{2})+$/.test(derHex)) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\tconst bytes = hexToBytes(derHex);\n\t\tconst root = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tconst element = unwrapDirectoryNameElement(bytes, root);\n\t\tif (element.tag !== 0x30) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst rdns: ParsedRelativeDistinguishedName[] = [];\n\t\tconst attributes: ParsedNameAttribute[] = [];\n\t\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\t\tfor (const setElement of childrenOf(bytes, element)) {\n\t\t\tconst rdn = parseDirectoryNameRdn(bytes, setElement);\n\t\t\tif (rdn === undefined) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\trdns.push(rdn);\n\t\t\tfor (const attribute of rdn.attributes) {\n\t\t\t\tattributes.push(attribute);\n\t\t\t\tif (attribute.key !== undefined && values[attribute.key] === undefined) {\n\t\t\t\t\tvalues[attribute.key] = attribute.value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tderHex: toHex(bytes),\n\t\t\trdns,\n\t\t\tattributes,\n\t\t\tvalues,\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Unwraps doubly-nested directoryName SEQUENCE encoding.\n *\n * Some encoders produce `[4] { SEQ { SEQ { SET... } } }` instead of `[4] { SEQ { SET... } }`.\n * A single SEQUENCE child indicates the extra wrapper (valid Names have SET children).\n */\nfunction unwrapDirectoryNameElement(source: Uint8Array, element: DerElement): DerElement {\n\tif (element.tag !== 0x30) {\n\t\treturn element;\n\t}\n\tconst children = childrenOf(source, element);\n\tconst child = children[0];\n\tif (children.length === 1 && child?.tag === 0x30) {\n\t\treturn child;\n\t}\n\treturn element;\n}\n\n/** Parses one SET element (a single RDN) from the DER Name SEQUENCE. */\nfunction parseDirectoryNameRdn(\n\tsource: Uint8Array,\n\tsetElement: DerElement,\n): ParsedRelativeDistinguishedName | undefined {\n\tif (setElement.tag !== 0x31) {\n\t\treturn undefined;\n\t}\n\tconst children = childrenOf(source, setElement);\n\tif (children.length === 0) {\n\t\treturn undefined;\n\t}\n\tconst attributes: ParsedNameAttribute[] = [];\n\tconst values: Partial<Record<NameFieldKey, string>> = {};\n\tfor (const attributeSequence of children) {\n\t\tif (attributeSequence.tag !== 0x30) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parts = childrenOf(source, attributeSequence);\n\t\tconst oidElement = parts[0];\n\t\tconst valueElement = parts[1];\n\t\tif (oidElement === undefined || valueElement === undefined || parts.length !== 2) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (oidElement.tag !== 0x06) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst oid = decodeObjectIdentifier(requireElement(oidElement, 'directoryName OID').value);\n\t\tlet fieldValue: string;\n\t\ttry {\n\t\t\tfieldValue = decodeString(\n\t\t\t\tvalueElement.tag,\n\t\t\t\trequireElement(valueElement, 'directoryName value').value,\n\t\t\t);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst fieldKey = nameFieldKeyFromOid(oid);\n\t\tconst attribute: ParsedNameAttribute =\n\t\t\tfieldKey !== undefined\n\t\t\t\t? { oid, key: fieldKey, valueTag: valueElement.tag, value: fieldValue }\n\t\t\t\t: { oid, valueTag: valueElement.tag, value: fieldValue };\n\t\tattributes.push(attribute);\n\t\tif (fieldKey !== undefined && values[fieldKey] === undefined) {\n\t\t\tvalues[fieldKey] = fieldValue;\n\t\t}\n\t}\n\tif (attributes.length === 0) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tderHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),\n\t\tattributes,\n\t\tvalues,\n\t};\n}\n\n/** Human-readable label for a constraint form, used in error messages. */\nfunction formatConstraintForm(form: NameConstraintForm): string {\n\tswitch (form.type) {\n\t\tcase 'dns':\n\t\t\treturn `dns:${form.value}`;\n\t\tcase 'email':\n\t\t\treturn `email:${form.value}`;\n\t\tcase 'uri':\n\t\t\treturn `uri:${form.value}`;\n\t\tcase 'ip':\n\t\t\treturn `ip:${decodeIpAddress(form.addressBytes)}`;\n\t\tcase 'directoryName':\n\t\t\treturn `dn:${form.derHex.slice(0, 20)}${form.derHex.length > 20 ? '...' : ''}`;\n\t\tdefault: {\n\t\t\tconst exhaustive = form;\n\t\t\tthrow new Error(`Unhandled NameConstraintForm type: ${String(exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":"ueA+GA,SAAS,EACR,EACA,EACA,EACA,EACkC,CAClC,MAAO,CACN,GAAI,GACJ,OACA,UACA,QACA,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,SAAQ,CAC5C,CACD,CAGA,SAAS,EACR,EACqD,CACrD,IAAM,EAAkD,CACvD,GAAI,EAAM,oBAAsB,IAAA,GAC7B,CAAC,EACD,CAAE,kBAAmB,EAAM,iBAAkB,EAChD,GAAI,EAAM,SAAW,IAAA,GAAY,CAAC,EAAI,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AW,KAAK,CAAS,EACrB,IAAa,IAAA,IAAa,EAAO,KAAc,IAAA,KAClD,EAAO,GAAY,EAErB,CACI,KAAW,SAAW,EAG1B,MAAO,CACN,OAAQ,EAAM,EAAO,MAAM,EAAW,MAAQ,EAAW,aAAc,EAAW,GAAG,CAAC,EACtF,aACA,QACD,CACD,CAGA,SAAS,EAAqB,EAAkC,CAC/D,OAAQ,EAAK,KAAb,CACC,IAAK,MACJ,MAAO,OAAO,EAAK,QACpB,IAAK,QACJ,MAAO,SAAS,EAAK,QACtB,IAAK,MACJ,MAAO,OAAO,EAAK,QACpB,IAAK,KACJ,MAAO,MAAM,EAAgB,EAAK,YAAY,IAC/C,IAAK,gBACJ,MAAO,MAAM,EAAK,OAAO,MAAM,EAAG,EAAE,IAAI,EAAK,OAAO,OAAS,GAAK,MAAQ,KAC3E,QAEC,MAAU,MAAM,sCAAsC,OAAOA,CAAU,GAAG,CAE5E,CACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"extension-bits.js","names":[],"sources":["../../../src/internal/x509/extension-bits.ts"],"sourcesContent":["/**\n * BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.\n *\n * Centralizes the bit-position ordering so certificate builders and parsers\n * produce identical wire encodings.\n *\n * @module\n */\n\nimport { bitString, DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der.ts';\nimport type { DistributionPointReason, KeyUsage } from '#micro509/x509/extensions.ts';\n\n/**\n * Decoded BIT STRING flags with DER conformance metadata.\n *\n * `flags` contains the recognized flag values with any non-zero padding bits\n * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding\n * had non-zero bits in positions that DER (X.690 §11.2.2) requires to be zero.\n * Verification layers can use this signal to reject non-conformant encodings.\n */\nexport interface ParsedBitFlags<T extends string> {\n\t/** Decoded flag values, padding bits masked. */\n\treadonly flags: readonly T[];\n\t/** `true` when the original encoding had non-zero padding bits (DER violation). */\n\treadonly nonZeroPadding: boolean;\n}\n\n/** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */\nconst KEY_USAGE_ORDER = [\n\t'digitalSignature',\n\t'nonRepudiation',\n\t'keyEncipherment',\n\t'dataEncipherment',\n\t'keyAgreement',\n\t'keyCertSign',\n\t'cRLSign',\n\t'encipherOnly',\n\t'decipherOnly',\n] as const satisfies readonly KeyUsage[];\n\n/** Canonical bit-position order for DistributionPoint reason flags (RFC 5280 §4.2.1.13). */\nconst DISTRIBUTION_POINT_REASON_ORDER = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n] as const satisfies readonly DistributionPointReason[];\n\n/**\n * Encode an array of {@linkcode KeyUsage} flags into a DER BIT STRING.\n *\n * @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.\n */\nexport function encodeKeyUsageExtension(usages: readonly KeyUsage[]): Uint8Array {\n\tconst encoded = encodeBitFlags(usages, (usage) =>\n\t\tindexInOrder(KEY_USAGE_ORDER, usage, 'key usage'),\n\t);\n\treturn bitString(encoded.bytes, encoded.unusedBits);\n}\n\n/**\n * Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.\n *\n * @param bytes DER of the keyUsage extension value (BIT STRING).\n */\nexport function parseKeyUsageExtension(bytes: Uint8Array): ParsedBitFlags<KeyUsage> {\n\tconst bitStringElement = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (bitStringElement.tag !== 0x03) {\n\t\tthrow new Error('keyUsage must be a BIT STRING');\n\t}\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(bitStringElement.value, KEY_USAGE_ORDER, 0),\n\t\t'keyUsage',\n\t);\n}\n\n/**\n * Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes\n * (unusedBits prefix + flag bytes), suitable for wrapping in an implicit context tag.\n *\n * @param reasons Reason flags to encode.\n */\nexport function encodeDistributionPointReasonFlagsContent(\n\treasons: readonly DistributionPointReason[],\n): Uint8Array {\n\tconst encoded = encodeBitFlags(\n\t\treasons,\n\t\t(reason) =>\n\t\t\tindexInOrder(DISTRIBUTION_POINT_REASON_ORDER, reason, 'distribution point reason') + 1,\n\t);\n\treturn Uint8Array.of(encoded.unusedBits, ...encoded.bytes);\n}\n\n/**\n * Decode BIT STRING content bytes into {@linkcode DistributionPointReason} flags.\n *\n * @param value Raw content bytes (unusedBits prefix + flag bytes).\n * @returns Decoded reason flags, preserving empty-but-present values and padding metadata.\n */\nexport function parseDistributionPointReasonFlagsContent(\n\tvalue: Uint8Array,\n): ParsedBitFlags<DistributionPointReason> {\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(value, DISTRIBUTION_POINT_REASON_ORDER, 1),\n\t\t'DistributionPoint reasons',\n\t);\n}\n\n/** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */\nfunction encodeBitFlags<T extends string>(\n\tvalues: readonly T[],\n\tbitForValue: (value: T) => number,\n): {\n\treadonly bytes: Uint8Array;\n\treadonly unusedBits: number;\n} {\n\tif (values.length === 0) {\n\t\treturn { bytes: new Uint8Array(0), unusedBits: 0 };\n\t}\n\tlet highestBit = -1;\n\tconst bits: number[] = [];\n\tfor (const value of values) {\n\t\tconst bit = bitForValue(value);\n\t\tbits.push(bit);\n\t\tif (bit > highestBit) {\n\t\t\thighestBit = bit;\n\t\t}\n\t}\n\tconst byteLength = Math.floor(highestBit / 8) + 1;\n\tconst bytes = new Uint8Array(byteLength);\n\tfor (const bit of bits) {\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tconst bitIndex = bit % 8;\n\t\tconst current = bytes[byteIndex] ?? 0;\n\t\tbytes[byteIndex] = current | (1 << (7 - bitIndex));\n\t}\n\tconst totalBits = highestBit + 1;\n\tconst unusedBits = (8 - (totalBits % 8)) % 8;\n\treturn {\n\t\tbytes,\n\t\tunusedBits,\n\t};\n}\n\n/** Unpack set bits from a BIT STRING content into named flags from a candidate list. */\nfunction decodeBitFlags<T extends string>(\n\tvalue: Uint8Array,\n\tcandidates: readonly T[],\n\tbitOffset: number,\n): ParsedBitFlags<T> {\n\tif (value.length === 0) {\n\t\tthrow new Error('Empty BIT STRING');\n\t}\n\tconst unusedBits = value[0] ?? 0;\n\tif (unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst bytes = value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\t// Detect non-zero padding bits in the unused positions of the last byte.\n\t// DER X.690 §11.2.2 requires these to be zero. Rather than rejecting here\n\t// (which would break interop with real-world non-conformant certificates),\n\t// we record the violation so verification layers can decide.\n\tlet nonZeroPadding = false;\n\tif (unusedBits > 0 && bytes.length > 0) {\n\t\tconst lastByte = bytes[bytes.length - 1] ?? 0;\n\t\tconst paddingMask = (1 << unusedBits) - 1;\n\t\tnonZeroPadding = (lastByte & paddingMask) !== 0;\n\t}\n\tconst flags: T[] = [];\n\tfor (let index = 0; index < candidates.length; index += 1) {\n\t\tconst bit = index + bitOffset;\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tif (byteIndex >= bytes.length) {\n\t\t\tbreak;\n\t\t}\n\t\tconst byte = bytes[byteIndex] ?? 0;\n\t\tconst bitIndex = bit % 8;\n\t\tif ((byte & (1 << (7 - bitIndex))) !== 0) {\n\t\t\tconst candidate = candidates[index];\n\t\t\tif (candidate !== undefined) {\n\t\t\t\tflags.push(candidate);\n\t\t\t}\n\t\t}\n\t}\n\treturn { flags, nonZeroPadding };\n}\n\nfunction requireCanonicalBitFlags<T extends string>(\n\tparsed: ParsedBitFlags<T>,\n\tlabel: string,\n): ParsedBitFlags<T> {\n\tif (parsed.nonZeroPadding) {\n\t\tthrow new Error(`${label} BIT STRING must not set padding bits`);\n\t}\n\treturn parsed;\n}\n\n/** Look up the bit position of a flag in its canonical order array. Throws on unknown flags. */\nfunction indexInOrder<T extends string>(order: readonly T[], value: T, label: string): number {\n\tconst index = order.indexOf(value);\n\tif (index < 0) {\n\t\tthrow new Error(`Unsupported ${label}: ${value}`);\n\t}\n\treturn index;\n}\n"],"mappings":"gEA4BA,MAAM,EAAkB,CACvB,mBACA,iBACA,kBACA,mBACA,eACA,cACA,UACA,eACA,cACD,EAGM,EAAkC,CACvC,gBACA,eACA,qBACA,aACA,uBACA,kBACA,qBACA,cACD,EAOA,SAAgB,EAAwB,EAAyC,CAChF,IAAM,EAAU,EAAe,EAAS,GACvC,EAAa,EAAiB,EAAO,WAAW,CACjD,EACA,OAAO,EAAU,EAAQ,MAAO,EAAQ,UAAU,CACnD,CAOA,SAAgB,EAAuB,EAA6C,CACnF,IAAM,EAAmB,EAAgB,EAAO,CAAE,SAAA,EAAgC,CAAC,EACnF,GAAI,EAAiB,MAAQ,EAC5B,MAAU,MAAM,+BAA+B,EAEhD,OAAO,EACN,EAAe,EAAiB,MAAO,EAAiB,CAAC,EACzD,UACD,CACD,CAQA,SAAgB,EACf,EACa,CACb,IAAM,EAAU,EACf,EACC,GACA,EAAa,EAAiC,EAAQ,2BAA2B,EAAI,CACvF,EACA,OAAO,WAAW,GAAG,EAAQ,WAAY,GAAG,EAAQ,KAAK,CAC1D,CAQA,SAAgB,EACf,EAC0C,CAC1C,OAAO,EACN,EAAe,EAAO,EAAiC,CAAC,EACxD,2BACD,CACD,CAGA,SAAS,EACR,EACA,EAIC,CACD,GAAI,EAAO,SAAW,EACrB,MAAO,CAAE,MAAO,IAAI,WAAe,WAAY,CAAE,EAElD,IAAI,EAAa,GACX,EAAiB,CAAC,EACxB,IAAK,IAAM,KAAS,EAAQ,CAC3B,IAAM,EAAM,EAAY,CAAK,EAC7B,EAAK,KAAK,CAAG,EACT,EAAM,IACT,EAAa,EAEf,CACA,IAAM,EAAa,KAAK,MAAM,EAAa,CAAC,EAAI,EAC1C,EAAQ,IAAI,WAAW,CAAU,EACvC,IAAK,IAAM,KAAO,EAAM,CACvB,IAAM,EAAY,KAAK,MAAM,EAAM,CAAC,EAC9B,EAAW,EAAM,EAEvB,EAAM,IADU,EAAM,IAAc,GACN,GAAM,EAAI,CACzC,CAGA,MAAO,CACN,QACA,YAHmB,GADF,EAAa,GACM,GAAM,CAI3C,CACD,CAGA,SAAS,EACR,EACA,EACA,EACoB,CACpB,GAAI,EAAM,SAAW,EACpB,MAAU,MAAM,kBAAkB,EAEnC,IAAM,EAAa,EAAM,IAAM,EAC/B,GAAI,EAAa,EAChB,MAAU,MAAM,oBAAoB,EAErC,IAAM,EAAQ,EAAM,MAAM,CAAC,EAC3B,GAAI,EAAM,SAAW,GAAK,IAAe,EACxC,MAAU,MAAM,oBAAoB,EAMrC,IAAI,EAAiB,GACjB,EAAa,GAAK,EAAM,OAAS,IAGpC,IAFiB,EAAM,EAAM,OAAS,IAAM,IACvB,GAAK,GAAc,IACM,GAE/C,IAAM,EAAa,CAAC,EACpB,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAW,OAAQ,GAAS,EAAG,CAC1D,IAAM,EAAM,EAAQ,EACd,EAAY,KAAK,MAAM,EAAM,CAAC,EACpC,GAAI,GAAa,EAAM,OACtB,MAID,IAFa,EAAM,IAAc,GAEpB,GAAM,EADF,EAAM,EACmB,CACzC,IAAM,EAAY,EAAW,GACzB,IAAc,IAAA,IACjB,EAAM,KAAK,CAAS,CAEtB,CACD,CACA,MAAO,CAAE,QAAO,gBAAe,CAChC,CAEA,SAAS,EACR,EACA,EACoB,CACpB,GAAI,EAAO,eACV,MAAU,MAAM,GAAG,EAAM,sCAAsC,EAEhE,OAAO,CACR,CAGA,SAAS,EAA+B,EAAqB,EAAU,EAAuB,CAC7F,IAAM,EAAQ,EAAM,QAAQ,CAAK,EACjC,GAAI,EAAQ,EACX,MAAU,MAAM,eAAe,EAAM,IAAI,GAAO,EAEjD,OAAO,CACR"}
1
+ {"version":3,"file":"extension-bits.js","names":[],"sources":["../../../src/internal/x509/extension-bits.ts"],"sourcesContent":["/**\n * BIT STRING helpers for {@linkcode KeyUsage} and {@linkcode DistributionPointReason} flags.\n *\n * Centralizes the bit-position ordering so certificate builders and parsers\n * produce identical wire encodings.\n *\n * @module\n */\n\nimport { bitString, DEFAULT_MAX_DER_DEPTH, readRootElement } from '#micro509/internal/asn1/der.ts';\nimport type { DistributionPointReason, KeyUsage } from '#micro509/x509/extensions.ts';\n\n/**\n * Decoded BIT STRING flags with DER conformance metadata.\n *\n * `flags` contains the recognized flag values with any non-zero padding bits\n * masked out. `nonZeroPadding` is `true` when the original BIT STRING encoding\n * had non-zero bits in positions that DER (X.690 §11.2.2) requires to be zero.\n * Verification layers can use this signal to reject non-conformant encodings.\n */\nimport type { ParsedBitFlags } from '#micro509/x509/extensions.ts';\n\nexport type { ParsedBitFlags };\n\n/** Canonical bit-position order for Key Usage flags (RFC 5280 §4.2.1.3). */\nconst KEY_USAGE_ORDER = [\n\t'digitalSignature',\n\t'nonRepudiation',\n\t'keyEncipherment',\n\t'dataEncipherment',\n\t'keyAgreement',\n\t'keyCertSign',\n\t'cRLSign',\n\t'encipherOnly',\n\t'decipherOnly',\n] as const satisfies readonly KeyUsage[];\n\n/** Canonical bit-position order for DistributionPoint reason flags (RFC 5280 §4.2.1.13). */\nconst DISTRIBUTION_POINT_REASON_ORDER = [\n\t'keyCompromise',\n\t'cACompromise',\n\t'affiliationChanged',\n\t'superseded',\n\t'cessationOfOperation',\n\t'certificateHold',\n\t'privilegeWithdrawn',\n\t'aACompromise',\n] as const satisfies readonly DistributionPointReason[];\n\n/**\n * Encode an array of {@linkcode KeyUsage} flags into a DER BIT STRING.\n *\n * @param usages Flags to set. Bit positions follow RFC 5280 §4.2.1.3 order.\n */\nexport function encodeKeyUsageExtension(usages: readonly KeyUsage[]): Uint8Array {\n\tconst encoded = encodeBitFlags(usages, (usage) =>\n\t\tindexInOrder(KEY_USAGE_ORDER, usage, 'key usage'),\n\t);\n\treturn bitString(encoded.bytes, encoded.unusedBits);\n}\n\n/**\n * Decode a DER-encoded Key Usage BIT STRING into an array of {@linkcode KeyUsage} flags.\n *\n * @param bytes DER of the keyUsage extension value (BIT STRING).\n */\nexport function parseKeyUsageExtension(bytes: Uint8Array): ParsedBitFlags<KeyUsage> {\n\tconst bitStringElement = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (bitStringElement.tag !== 0x03) {\n\t\tthrow new Error('keyUsage must be a BIT STRING');\n\t}\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(bitStringElement.value, KEY_USAGE_ORDER, 0),\n\t\t'keyUsage',\n\t);\n}\n\n/**\n * Encode {@linkcode DistributionPointReason} flags as BIT STRING content bytes\n * (unusedBits prefix + flag bytes), suitable for wrapping in an implicit context tag.\n *\n * @param reasons Reason flags to encode.\n */\nexport function encodeDistributionPointReasonFlagsContent(\n\treasons: readonly DistributionPointReason[],\n): Uint8Array {\n\tconst encoded = encodeBitFlags(\n\t\treasons,\n\t\t(reason) =>\n\t\t\tindexInOrder(DISTRIBUTION_POINT_REASON_ORDER, reason, 'distribution point reason') + 1,\n\t);\n\treturn Uint8Array.of(encoded.unusedBits, ...encoded.bytes);\n}\n\n/**\n * Decode BIT STRING content bytes into {@linkcode DistributionPointReason} flags.\n *\n * @param value Raw content bytes (unusedBits prefix + flag bytes).\n * @returns Decoded reason flags, preserving empty-but-present values and padding metadata.\n */\nexport function parseDistributionPointReasonFlagsContent(\n\tvalue: Uint8Array,\n): ParsedBitFlags<DistributionPointReason> {\n\treturn requireCanonicalBitFlags(\n\t\tdecodeBitFlags(value, DISTRIBUTION_POINT_REASON_ORDER, 1),\n\t\t'DistributionPoint reasons',\n\t);\n}\n\n/** Pack named flags into a minimal byte array with DER BIT STRING unused-bits count. */\nfunction encodeBitFlags<T extends string>(\n\tvalues: readonly T[],\n\tbitForValue: (value: T) => number,\n): {\n\treadonly bytes: Uint8Array;\n\treadonly unusedBits: number;\n} {\n\tif (values.length === 0) {\n\t\treturn { bytes: new Uint8Array(0), unusedBits: 0 };\n\t}\n\tlet highestBit = -1;\n\tconst bits: number[] = [];\n\tfor (const value of values) {\n\t\tconst bit = bitForValue(value);\n\t\tbits.push(bit);\n\t\tif (bit > highestBit) {\n\t\t\thighestBit = bit;\n\t\t}\n\t}\n\tconst byteLength = Math.floor(highestBit / 8) + 1;\n\tconst bytes = new Uint8Array(byteLength);\n\tfor (const bit of bits) {\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tconst bitIndex = bit % 8;\n\t\tconst current = bytes[byteIndex] ?? 0;\n\t\tbytes[byteIndex] = current | (1 << (7 - bitIndex));\n\t}\n\tconst totalBits = highestBit + 1;\n\tconst unusedBits = (8 - (totalBits % 8)) % 8;\n\treturn {\n\t\tbytes,\n\t\tunusedBits,\n\t};\n}\n\n/** Unpack set bits from a BIT STRING content into named flags from a candidate list. */\nfunction decodeBitFlags<T extends string>(\n\tvalue: Uint8Array,\n\tcandidates: readonly T[],\n\tbitOffset: number,\n): ParsedBitFlags<T> {\n\tif (value.length === 0) {\n\t\tthrow new Error('Empty BIT STRING');\n\t}\n\tconst unusedBits = value[0] ?? 0;\n\tif (unusedBits > 7) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\tconst bytes = value.slice(1);\n\tif (bytes.length === 0 && unusedBits !== 0) {\n\t\tthrow new Error('Invalid BIT STRING');\n\t}\n\t// Detect non-zero padding bits in the unused positions of the last byte.\n\t// DER X.690 §11.2.2 requires these to be zero. Rather than rejecting here\n\t// (which would break interop with real-world non-conformant certificates),\n\t// we record the violation so verification layers can decide.\n\tlet nonZeroPadding = false;\n\tif (unusedBits > 0 && bytes.length > 0) {\n\t\tconst lastByte = bytes[bytes.length - 1] ?? 0;\n\t\tconst paddingMask = (1 << unusedBits) - 1;\n\t\tnonZeroPadding = (lastByte & paddingMask) !== 0;\n\t}\n\tconst flags: T[] = [];\n\tfor (let index = 0; index < candidates.length; index += 1) {\n\t\tconst bit = index + bitOffset;\n\t\tconst byteIndex = Math.floor(bit / 8);\n\t\tif (byteIndex >= bytes.length) {\n\t\t\tbreak;\n\t\t}\n\t\tconst byte = bytes[byteIndex] ?? 0;\n\t\tconst bitIndex = bit % 8;\n\t\tif ((byte & (1 << (7 - bitIndex))) !== 0) {\n\t\t\tconst candidate = candidates[index];\n\t\t\tif (candidate !== undefined) {\n\t\t\t\tflags.push(candidate);\n\t\t\t}\n\t\t}\n\t}\n\treturn { flags, nonZeroPadding };\n}\n\nfunction requireCanonicalBitFlags<T extends string>(\n\tparsed: ParsedBitFlags<T>,\n\tlabel: string,\n): ParsedBitFlags<T> {\n\tif (parsed.nonZeroPadding) {\n\t\tthrow new Error(`${label} BIT STRING must not set padding bits`);\n\t}\n\treturn parsed;\n}\n\n/** Look up the bit position of a flag in its canonical order array. Throws on unknown flags. */\nfunction indexInOrder<T extends string>(order: readonly T[], value: T, label: string): number {\n\tconst index = order.indexOf(value);\n\tif (index < 0) {\n\t\tthrow new Error(`Unsupported ${label}: ${value}`);\n\t}\n\treturn index;\n}\n"],"mappings":"gEAyBA,MAAM,EAAkB,CACvB,mBACA,iBACA,kBACA,mBACA,eACA,cACA,UACA,eACA,cACD,EAGM,EAAkC,CACvC,gBACA,eACA,qBACA,aACA,uBACA,kBACA,qBACA,cACD,EAOA,SAAgB,EAAwB,EAAyC,CAChF,IAAM,EAAU,EAAe,EAAS,GACvC,EAAa,EAAiB,EAAO,WAAW,CACjD,EACA,OAAO,EAAU,EAAQ,MAAO,EAAQ,UAAU,CACnD,CAOA,SAAgB,EAAuB,EAA6C,CACnF,IAAM,EAAmB,EAAgB,EAAO,CAAE,SAAA,EAAgC,CAAC,EACnF,GAAI,EAAiB,MAAQ,EAC5B,MAAU,MAAM,+BAA+B,EAEhD,OAAO,EACN,EAAe,EAAiB,MAAO,EAAiB,CAAC,EACzD,UACD,CACD,CAQA,SAAgB,EACf,EACa,CACb,IAAM,EAAU,EACf,EACC,GACA,EAAa,EAAiC,EAAQ,2BAA2B,EAAI,CACvF,EACA,OAAO,WAAW,GAAG,EA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