micro509 0.12.0 → 0.14.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 (123) hide show
  1. package/README.md +78 -30
  2. package/dist/crypto/crypto.d.ts +73 -0
  3. package/dist/crypto/crypto.js +74 -0
  4. package/dist/crypto/crypto.js.map +1 -0
  5. package/dist/crypto.d.ts +4 -0
  6. package/dist/crypto.js +2 -0
  7. package/dist/der/der.d.ts +127 -0
  8. package/dist/der/der.js +171 -0
  9. package/dist/der/der.js.map +1 -0
  10. package/dist/der.d.ts +4 -0
  11. package/dist/der.js +4 -0
  12. package/dist/index.d.ts +13 -9
  13. package/dist/index.js +17 -15
  14. package/dist/internal/asn1/asn1.d.ts +20 -0
  15. package/dist/internal/asn1/asn1.js +80 -37
  16. package/dist/internal/asn1/asn1.js.map +1 -1
  17. package/dist/internal/asn1/der.d.ts +173 -0
  18. package/dist/internal/asn1/der.js +116 -38
  19. package/dist/internal/asn1/der.js.map +1 -1
  20. package/dist/internal/asn1/oids.js +7 -1
  21. package/dist/internal/asn1/oids2.js +9 -2
  22. package/dist/internal/asn1/oids2.js.map +1 -1
  23. package/dist/internal/crypto/algorithm-names.js +4 -0
  24. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  25. package/dist/internal/crypto/pbes2.d.ts +38 -0
  26. package/dist/internal/crypto/pbes2.js +9 -10
  27. package/dist/internal/crypto/pbes2.js.map +1 -1
  28. package/dist/internal/crypto/rsa-pss.js +2 -0
  29. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  30. package/dist/internal/crypto/sig-verify.d.ts +31 -0
  31. package/dist/internal/crypto/sig-verify.js +10 -8
  32. package/dist/internal/crypto/sig-verify.js.map +1 -1
  33. package/dist/internal/shared/base64.js +7 -1
  34. package/dist/internal/shared/base64.js.map +1 -1
  35. package/dist/internal/shared/dn.d.ts +16 -0
  36. package/dist/internal/shared/dn.js +149 -12
  37. package/dist/internal/shared/dn.js.map +1 -1
  38. package/dist/internal/shared/ip.d.ts +69 -0
  39. package/dist/internal/shared/ip.js +18 -1
  40. package/dist/internal/shared/ip.js.map +1 -1
  41. package/dist/internal/shared/rfc3454-tables.js +1782 -0
  42. package/dist/internal/shared/rfc3454-tables.js.map +1 -0
  43. package/dist/internal/verify/name-constraints-engine.js +47 -15
  44. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  45. package/dist/internal/verify/policy-engine.js +85 -94
  46. package/dist/internal/verify/policy-engine.js.map +1 -1
  47. package/dist/internal/verify/verify-path.d.ts +7 -0
  48. package/dist/internal/verify/verify-path.js +49 -45
  49. package/dist/internal/verify/verify-path.js.map +1 -1
  50. package/dist/internal/x509/directory-name.js +24 -0
  51. package/dist/internal/x509/directory-name.js.map +1 -0
  52. package/dist/internal/x509/extension-bits.js +14 -11
  53. package/dist/internal/x509/extension-bits.js.map +1 -1
  54. package/dist/internal/x509/extension-errors.d.ts +6 -0
  55. package/dist/internal/x509/extension-errors.js +20 -0
  56. package/dist/internal/x509/extension-errors.js.map +1 -0
  57. package/dist/internal/x509/extension-registry.js +113 -55
  58. package/dist/internal/x509/extension-registry.js.map +1 -1
  59. package/dist/internal/x509/general-name-tags.js +28 -0
  60. package/dist/internal/x509/general-name-tags.js.map +1 -0
  61. package/dist/internal/x509/general-name.js +97 -0
  62. package/dist/internal/x509/general-name.js.map +1 -0
  63. package/dist/internal/x509/name-fields.js +20 -10
  64. package/dist/internal/x509/name-fields.js.map +1 -1
  65. package/dist/keys/keys.d.ts +16 -2
  66. package/dist/keys/keys.js +311 -170
  67. package/dist/keys/keys.js.map +1 -1
  68. package/dist/keys.d.ts +3 -2
  69. package/dist/keys.js +3 -2
  70. package/dist/pem/pem.d.ts +3 -2
  71. package/dist/pem/pem.js +112 -30
  72. package/dist/pem/pem.js.map +1 -1
  73. package/dist/pkcs/pkcs12-mac.js +3 -3
  74. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  75. package/dist/pkcs/pkcs7.d.ts +85 -21
  76. package/dist/pkcs/pkcs7.js +261 -186
  77. package/dist/pkcs/pkcs7.js.map +1 -1
  78. package/dist/pkcs.d.ts +2 -2
  79. package/dist/result/result.d.ts +18 -10
  80. package/dist/result/result.js +20 -12
  81. package/dist/result/result.js.map +1 -1
  82. package/dist/result.d.ts +2 -2
  83. package/dist/result.js +2 -2
  84. package/dist/revocation/chain.js +154 -103
  85. package/dist/revocation/chain.js.map +1 -1
  86. package/dist/revocation/crl.d.ts +13 -2
  87. package/dist/revocation/crl.js +415 -236
  88. package/dist/revocation/crl.js.map +1 -1
  89. package/dist/revocation/ocsp.d.ts +58 -17
  90. package/dist/revocation/ocsp.js +186 -174
  91. package/dist/revocation/ocsp.js.map +1 -1
  92. package/dist/revocation/revocation.d.ts +4 -4
  93. package/dist/revocation/revocation.js +48 -30
  94. package/dist/revocation/revocation.js.map +1 -1
  95. package/dist/revocation.d.ts +4 -4
  96. package/dist/revocation.js +5 -5
  97. package/dist/verify/identity.d.ts +2 -1
  98. package/dist/verify/identity.js +2 -1
  99. package/dist/verify/identity.js.map +1 -1
  100. package/dist/verify/policy.d.ts +6 -1
  101. package/dist/verify/verify.d.ts +18 -3
  102. package/dist/verify/verify.js +66 -41
  103. package/dist/verify/verify.js.map +1 -1
  104. package/dist/verify.d.ts +2 -1
  105. package/dist/verify.js +4 -3
  106. package/dist/x509/certificate.d.ts +36 -13
  107. package/dist/x509/certificate.js +36 -19
  108. package/dist/x509/certificate.js.map +1 -1
  109. package/dist/x509/csr.d.ts +6 -3
  110. package/dist/x509/extensions.d.ts +59 -22
  111. package/dist/x509/extensions.js +384 -117
  112. package/dist/x509/extensions.js.map +1 -1
  113. package/dist/x509/name-text.js +2 -0
  114. package/dist/x509/name-text.js.map +1 -1
  115. package/dist/x509/name.d.ts +8 -5
  116. package/dist/x509/name.js +17 -12
  117. package/dist/x509/name.js.map +1 -1
  118. package/dist/x509/parse.d.ts +104 -18
  119. package/dist/x509/parse.js +127 -163
  120. package/dist/x509/parse.js.map +1 -1
  121. package/dist/x509.d.ts +8 -5
  122. package/dist/x509.js +10 -8
  123. package/package.json +52 -34
@@ -1 +1 @@
1
- {"version":3,"file":"extensions.js","names":["_exhaustive"],"sources":["../../src/x509/extensions.ts"],"sourcesContent":["/**\n * Typed certificate and CSR extension model plus ASN.1 encoder helpers.\n *\n * Defines input types for every supported X.509v3 extension (RFC 5280) and\n * the DER encoders consumed by certificate and CSR builder flows.\n *\n * @module\n */\n\nimport { hexToBytes } from '#micro509/internal/asn1/asn1';\nimport {\n\tbool,\n\tconcatBytes,\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tia5String,\n\timplicitConstructedContext,\n\timplicitPrimitiveContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\ttlv,\n\tutf8String,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { sha1 } from '#micro509/internal/crypto/hash';\nimport { parseIpAddressToBytes } from '#micro509/internal/shared/ip';\nimport {\n\tencodeDistributionPointReasonFlagsContent,\n\tencodeKeyUsageExtension,\n} from '#micro509/internal/x509/extension-bits';\nimport type {\n\tExtensionDefinition,\n\tExtensionRegistryContext,\n} from '#micro509/internal/x509/extension-registry';\nimport {\n\tAUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION,\n\tAUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n\tBASIC_CONSTRAINTS_EXTENSION_DEFINITION,\n\tCERTIFICATE_POLICIES_EXTENSION_DEFINITION,\n\tCRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION,\n\tEXTENDED_KEY_USAGE_EXTENSION_DEFINITION,\n\tgetExtensionDefinition,\n\tINHIBIT_ANY_POLICY_EXTENSION_DEFINITION,\n\tKEY_USAGE_EXTENSION_DEFINITION,\n\tNAME_CONSTRAINTS_EXTENSION_DEFINITION,\n\tPOLICY_CONSTRAINTS_EXTENSION_DEFINITION,\n\tPOLICY_MAPPINGS_EXTENSION_DEFINITION,\n\tSUBJECT_ALT_NAME_EXTENSION_DEFINITION,\n\tSUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n} from '#micro509/internal/x509/extension-registry';\nimport type { RelativeDistinguishedNameInput } from '#micro509/x509/name';\nimport { encodeRelativeDistinguishedName } from '#micro509/x509/name';\n\nexport type {\n\tNameAttribute,\n\tNameFieldKey,\n\tRelativeDistinguishedNameInput,\n} from '#micro509/x509/name';\n\n/**\n * A decoded BIT STRING flag set.\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/**\n * RFC 5280 §4.2.1.3 Key Usage bit flag.\n *\n * Each value corresponds to one bit in the KeyUsage BIT STRING.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.3 RFC 5280 §4.2.1.3}\n */\nexport type KeyUsage =\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\n/**\n * RFC 5280 §4.2.1.6 Subject Alternative Name / GeneralName.\n *\n * Discriminated union keyed on `type`.\n *\n * The `'unknown'` variant preserves unrecognized {@linkcode GeneralName} tags for round-trip fidelity.\n */\nexport type SubjectAltName =\n\t| {\n\t\t\t/** DNS hostname (dNSName [2]). */\n\t\t\treadonly type: 'dns';\n\t\t\t/** Fully-qualified domain name, e.g. `\"example.com\"`. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** IP address (iPAddress [7]). */\n\t\t\treadonly type: 'ip';\n\t\t\t/** Dotted-decimal IPv4 or colon-hex IPv6 string. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** Email address (rfc822Name [1]). */\n\t\t\treadonly type: 'email';\n\t\t\t/** RFC 822 mailbox, e.g. `\"admin@example.com\"`. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** URI (uniformResourceIdentifier [6]). */\n\t\t\treadonly type: 'uri';\n\t\t\t/** Absolute URI string. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** SRV-ID otherName (id-on-dnsSRV). */\n\t\t\treadonly type: 'srv';\n\t\t\t/** SRV service name, e.g. `\"_imaps.example.com\"`. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** X.500 directory name (directoryName [4]). */\n\t\t\treadonly type: 'directoryName';\n\t\t\t/** Hex-encoded DER of the Name SEQUENCE. */\n\t\t\treadonly derHex: string;\n\t }\n\t| {\n\t\t\t/** Unrecognized {@linkcode GeneralName} tag, preserved as raw bytes. */\n\t\t\treadonly type: 'unknown';\n\t\t\t/** ASN.1 context tag number. */\n\t\t\treadonly tag: number;\n\t\t\t/** Raw content bytes of the element. */\n\t\t\treadonly value: Uint8Array;\n\t };\n\n/** Alias for {@linkcode SubjectAltName} — used where RFC 5280 says \"GeneralName\". */\nexport type GeneralName = SubjectAltName;\n\n/**\n * Revocation reason flags for CRL Distribution Points and Issuing Distribution Points\n * (RFC 5280 §4.2.1.13, §5.2.5).\n */\nexport type DistributionPointReason =\n\t| 'keyCompromise'\n\t| 'cACompromise'\n\t| 'affiliationChanged'\n\t| 'superseded'\n\t| 'cessationOfOperation'\n\t| 'certificateHold'\n\t| 'privilegeWithdrawn'\n\t| 'aACompromise';\n\n/**\n * Name component of a CRL Distribution Point (RFC 5280 §4.2.1.13).\n *\n * Supply exactly one of `fullName` or `relativeName`.\n */\nexport interface DistributionPointName {\n\t/** Absolute {@linkcode GeneralName}(s) identifying the distribution point (usually a URI). */\n\treadonly fullName?: readonly GeneralName[];\n\t/** Name relative to the issuer's DN; mutually exclusive with `fullName`. */\n\treadonly relativeName?: RelativeDistinguishedNameInput;\n}\n\n/**\n * Input for a single CRL Distribution Point (RFC 5280 §4.2.1.13).\n *\n * At least one of `distributionPoint` or `crlIssuer` must be provided.\n * The union enforces this constraint at the type level.\n */\nexport type DistributionPoint =\n\t| {\n\t\t\t/** Where to fetch the CRL (fullName or relativeName). */\n\t\t\treadonly distributionPoint: DistributionPointName;\n\t\t\t/** Revocation reason subset. Absent means all reasons. */\n\t\t\treadonly reasons?: readonly DistributionPointReason[];\n\t\t\t/** Entity that signed the CRL, when different from the cert issuer. */\n\t\t\treadonly crlIssuer?: readonly GeneralName[];\n\t }\n\t| {\n\t\t\t/** Where to fetch the CRL. Optional when `crlIssuer` is present. */\n\t\t\treadonly distributionPoint?: DistributionPointName;\n\t\t\t/** Revocation reason subset. Absent means all reasons. */\n\t\t\treadonly reasons?: readonly DistributionPointReason[];\n\t\t\t/** Entity that signed the CRL. Required when `distributionPoint` is absent. */\n\t\t\treadonly crlIssuer: readonly GeneralName[];\n\t };\n\n/** Base shape for Issuing Distribution Point (RFC 5280 §5.2.5) — no scope restriction. */\nexport interface IssuingDistributionPointBase {\n\t/** Where to fetch this CRL. */\n\treadonly distributionPoint?: DistributionPointName;\n\t/** Limits the CRL to these revocation reasons. Absent means all reasons. */\n\treadonly onlySomeReasons?: readonly DistributionPointReason[];\n\t/** When true, the CRL may contain entries from other CAs. Default false. */\n\treadonly indirectCrl?: boolean;\n\t/** Must be absent or false in this variant (no user-cert-only restriction). */\n\treadonly onlyContainsUserCerts?: false;\n\t/** Must be absent or false in this variant (no CA-cert-only restriction). */\n\treadonly onlyContainsCACerts?: false;\n\t/** When true, the CRL only covers attribute certificates. Default false. */\n\treadonly onlyContainsAttributeCerts?: boolean;\n}\n\n/** IDP scoped to end-entity (user) certificates only. Mutually exclusive with CA / attribute scopes. */\nexport interface IssuingDistributionPointForUserCerts\n\textends Omit<IssuingDistributionPointBase, 'onlyContainsUserCerts'> {\n\t/** This variant only covers end-entity certificates. */\n\treadonly onlyContainsUserCerts: true;\n\t/** Must be absent or false when the CRL is not CA-only. */\n\treadonly onlyContainsCACerts?: false;\n\t/** Must be absent or false when the CRL is not attribute-cert-only. */\n\treadonly onlyContainsAttributeCerts?: false;\n}\n\n/** IDP scoped to CA certificates only. Mutually exclusive with user / attribute scopes. */\nexport interface IssuingDistributionPointForCaCerts\n\textends Omit<IssuingDistributionPointBase, 'onlyContainsCACerts'> {\n\t/** Must be absent or false when the CRL is not user-cert-only. */\n\treadonly onlyContainsUserCerts?: false;\n\t/** This variant only covers CA certificates. */\n\treadonly onlyContainsCACerts: true;\n\t/** Must be absent or false when the CRL is not attribute-cert-only. */\n\treadonly onlyContainsAttributeCerts?: false;\n}\n\n/** IDP scoped to attribute certificates only. Mutually exclusive with user / CA scopes. */\nexport interface IssuingDistributionPointForAttributeCerts\n\textends Omit<IssuingDistributionPointBase, 'onlyContainsAttributeCerts'> {\n\t/** Must be absent or false when the CRL is not user-cert-only. */\n\treadonly onlyContainsUserCerts?: false;\n\t/** Must be absent or false when the CRL is not CA-only. */\n\treadonly onlyContainsCACerts?: false;\n\t/** This variant only covers attribute certificates. */\n\treadonly onlyContainsAttributeCerts: true;\n}\n\n/**\n * Input for the Issuing Distribution Point CRL extension (RFC 5280 §5.2.5).\n *\n * The union enforces that at most one of the `onlyContains*` flags is true.\n */\nexport type IssuingDistributionPoint =\n\t| IssuingDistributionPointBase\n\t| IssuingDistributionPointForUserCerts\n\t| IssuingDistributionPointForCaCerts\n\t| IssuingDistributionPointForAttributeCerts;\n\n/**\n * RFC 5280 §4.2.1.9 Basic Constraints.\n *\n * A certificate with `ca: true` may issue other certificates; `pathLength`\n * limits how many additional CAs may appear below it in the chain.\n */\nexport type BasicConstraints =\n\t| {\n\t\t\t/** End-entity certificate: not a CA. */\n\t\t\treadonly ca: false;\n\t\t\t/** Never present on end-entity certificates. */\n\t\t\treadonly pathLength?: undefined;\n\t }\n\t| {\n\t\t\t/** CA certificate: may issue other certificates. */\n\t\t\treadonly ca: true;\n\t\t\t/** Maximum number of intermediate CA certificates allowed below this CA. */\n\t\t\treadonly pathLength?: number;\n\t };\n\n/** A single certificate policy: an OID plus optional qualifiers. */\nexport interface PolicyInformation {\n\t/** Dotted-decimal OID of the policy (e.g. `\"2.23.140.1.2.1\"` for DV). */\n\treadonly policyIdentifier: string;\n\t/** Optional CPS URIs or user notices attached to this policy. */\n\treadonly policyQualifiers?: readonly PolicyQualifierInfo[];\n}\n\n/** RFC 5280 §4.2.1.4 — array of policy OIDs with optional qualifiers. */\nexport type CertificatePolicies = readonly {\n\t/** Dotted-decimal OID of the policy (e.g. `\"2.23.140.1.2.1\"` for DV). */\n\treadonly policyIdentifier: string;\n\t/** Optional CPS URIs or user notices attached to this policy. */\n\treadonly policyQualifiers?: readonly (\n\t\t| {\n\t\t\t\treadonly type: 'cps';\n\t\t\t\treadonly uri: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'userNotice';\n\t\t\t\treadonly noticeRef?: {\n\t\t\t\t\treadonly organization: string;\n\t\t\t\t\treadonly noticeNumbers: readonly number[];\n\t\t\t\t};\n\t\t\t\treadonly explicitText?: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'oid';\n\t\t\t\treadonly oid: string;\n\t\t\t\treadonly qualifierDer: Uint8Array;\n\t\t }\n\t)[];\n}[];\n\n/** CPS (Certification Practice Statement) URI policy qualifier. */\nexport interface CpsPolicyQualifierInfo {\n\t/** Discriminant for the `'cps'` qualifier variant. */\n\treadonly type: 'cps';\n\t/** URL of the Certification Practice Statement document. */\n\treadonly uri: string;\n}\n\n/** Reference to a numbered notice within an organization's practice statement. */\nexport interface PolicyNoticeReference {\n\t/** Organization name that published the notice. */\n\treadonly organization: string;\n\t/** One-based notice numbers within that organization's documentation. */\n\treadonly noticeNumbers: readonly number[];\n}\n\n/** UserNotice policy qualifier — human-readable notice text and/or a notice reference. */\nexport interface UserNoticePolicyQualifierInfo {\n\t/** Discriminant for the `'userNotice'` qualifier variant. */\n\treadonly type: 'userNotice';\n\t/** Pointer to a numbered notice in an organization's practice statement. */\n\treadonly noticeRef?: PolicyNoticeReference;\n\t/** Free-form text to display to relying parties. */\n\treadonly explicitText?: string;\n}\n\n/** Opaque policy qualifier identified by a custom OID, carried as raw DER. */\nexport interface CustomPolicyQualifierInfo {\n\t/** Discriminant for the custom-OID qualifier variant. */\n\treadonly type: 'oid';\n\t/** Dotted-decimal OID of the qualifier. */\n\treadonly oid: string;\n\t/** DER-encoded qualifier payload. */\n\treadonly qualifierDer: Uint8Array;\n}\n\n/** Discriminated union of all supported policy qualifier types. */\nexport type PolicyQualifierInfo =\n\t| CpsPolicyQualifierInfo\n\t| UserNoticePolicyQualifierInfo\n\t| CustomPolicyQualifierInfo;\n\n/** Maps a policy OID in the issuer's domain to an equivalent OID in the subject's domain. */\nexport interface PolicyMapping {\n\t/** Policy OID as defined by the issuing CA. Must not be anyPolicy. */\n\treadonly issuerDomainPolicy: string;\n\t/** Equivalent policy OID in the subject CA's domain. Must not be anyPolicy. */\n\treadonly subjectDomainPolicy: string;\n}\n\n/** RFC 5280 §4.2.1.5 — array of issuer-to-subject policy OID pairs. */\nexport type PolicyMappings = readonly {\n\t/** Policy OID as defined by the issuing CA. Must not be anyPolicy. */\n\treadonly issuerDomainPolicy: string;\n\t/** Equivalent policy OID in the subject CA's domain. Must not be anyPolicy. */\n\treadonly subjectDomainPolicy: string;\n}[];\n\n/**\n * RFC 5280 §4.2.1.11 Policy Constraints.\n *\n * At least one field must be present. Values are certificate-count\n * thresholds measured from the current certificate toward the end entity.\n */\nexport interface PolicyConstraints {\n\t/** After this many certificates, an acceptable policy must be in the path. */\n\treadonly requireExplicitPolicy?: number;\n\t/** After this many certificates, policy mapping is no longer allowed. */\n\treadonly inhibitPolicyMapping?: number;\n}\n\n/**\n * RFC 5280 §4.2.1.14 Inhibit anyPolicy.\n *\n * After `skipCerts` additional certificates in the path, the special\n * anyPolicy OID is no longer considered a match.\n */\nexport interface InhibitAnyPolicy {\n\t/** Number of additional certificates before anyPolicy stops being valid. */\n\treadonly skipCerts: number;\n}\n\n/**\n * Input for `createCertificate`, `createSelfSignedCertificate`,\n * and `createCertificateSigningRequest`.\n *\n * Every field is optional. Omitted extensions are not encoded. Built-in\n * extensions (SKI, AKI, basicConstraints defaults) are handled automatically\n * by the builder.\n */\nexport interface CertificateExtensionsInput {\n\t/** Subject Alternative Names (dns, ip, email, uri, srv, directoryName). */\n\treadonly subjectAltNames?: readonly SubjectAltName[];\n\t/** Key Usage flags (digitalSignature, keyCertSign, etc.). */\n\treadonly keyUsage?: readonly KeyUsage[];\n\t/** Basic Constraints (CA flag + optional pathLength). Defaults to `{ ca: false }` for certs. */\n\treadonly basicConstraints?: BasicConstraints;\n\t/** Extended Key Usage purposes (serverAuth, clientAuth, etc.). */\n\treadonly extendedKeyUsage?: readonly ExtendedKeyUsage[];\n\t/** Name Constraints — permitted and/or excluded subtrees. */\n\treadonly nameConstraints?: NameConstraints;\n\t/** Certificate Policies with optional qualifiers. */\n\treadonly certificatePolicies?: CertificatePolicies;\n\t/** Policy Mappings between issuer and subject policy domains. */\n\treadonly policyMappings?: PolicyMappings;\n\t/** Policy Constraints (requireExplicitPolicy / inhibitPolicyMapping thresholds). */\n\treadonly policyConstraints?: PolicyConstraints;\n\t/** Inhibit anyPolicy skip-certs threshold. */\n\treadonly inhibitAnyPolicy?: InhibitAnyPolicy;\n\t/** Authority Information Access — OCSP responder and CA issuer URIs. */\n\treadonly authorityInfoAccess?: readonly AuthorityInformationAccess[];\n\t/** CRL Distribution Points — where to check revocation status. */\n\treadonly crlDistributionPoints?: readonly DistributionPoint[];\n\t/** Arbitrary extensions not covered by the built-in fields. */\n\treadonly customExtensions?: readonly CustomExtension[];\n}\n\n/** An extension not covered by the typed fields in {@linkcode CertificateExtensionsInput}. */\nexport interface CustomExtension {\n\t/** Dotted-decimal OID of the extension. */\n\treadonly oid: string;\n\t/** Pre-encoded DER content for the extnValue OCTET STRING. */\n\treadonly value: Uint8Array;\n\t/** Whether the extension is critical. Default `false`. */\n\treadonly critical?: boolean;\n}\n\n// Name constraints (RFC 5280 §4.2.1.10)\n\n/**\n * A name form used as a constraint base in namEConstraints.\n * Distinct from {@linkcode SubjectAltName} because IP constraints carry\n * address + mask bytes (8 for IPv4, 32 for IPv6) rather than bare addresses.\n */\nexport type NameConstraintForm =\n\t| {\n\t\t\t/** DNS domain constraint (dNSName [2]). */\n\t\t\treadonly type: 'dns';\n\t\t\t/** Domain suffix, e.g. `\".example.com\"` or `\"example.com\"`. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** Email constraint (rfc822Name [1]). */\n\t\t\treadonly type: 'email';\n\t\t\t/** Email domain or full address pattern. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** URI constraint (uniformResourceIdentifier [6]). */\n\t\t\treadonly type: 'uri';\n\t\t\t/** Host or domain component of a URI. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** IP range constraint (iPAddress [7]). */\n\t\t\treadonly type: 'ip';\n\t\t\t/** Network address bytes (4 for IPv4, 16 for IPv6). */\n\t\t\treadonly addressBytes: Uint8Array;\n\t\t\t/** Subnet mask bytes (same length as addressBytes). */\n\t\t\treadonly maskBytes: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Directory name constraint (directoryName [4]). */\n\t\t\treadonly type: 'directoryName';\n\t\t\t/** Hex-encoded DER of the Name SEQUENCE. */\n\t\t\treadonly derHex: string;\n\t };\n\n/**\n * Name constraint forms parsed from DER but not supported for encoding or\n * validation. Preserved for diagnostic round-tripping.\n */\nexport type UnsupportedNameConstraintForm =\n\t| {\n\t\t\t/** otherName [0] — raw bytes. */\n\t\t\treadonly type: 'otherName';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\t/** x400Address [3] — raw bytes. */\n\t\t\treadonly type: 'x400Address';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\t/** ediPartyName [5] — raw bytes. */\n\t\t\treadonly type: 'ediPartyName';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\t/** registeredID [8] — decoded OID string. */\n\t\t\treadonly type: 'registeredID';\n\t\t\treadonly value: string;\n\t };\n\n/** Union of supported and unsupported name constraint forms as produced by parsing. */\nexport type ParsedNameConstraintForm =\n\t| {\n\t\t\treadonly type: 'dns';\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\treadonly type: 'email';\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\treadonly type: 'uri';\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\treadonly type: 'ip';\n\t\t\treadonly addressBytes: Uint8Array;\n\t\t\treadonly maskBytes: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly type: 'directoryName';\n\t\t\treadonly derHex: string;\n\t }\n\t| {\n\t\t\treadonly type: 'otherName';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly type: 'x400Address';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly type: 'ediPartyName';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly type: 'registeredID';\n\t\t\treadonly value: string;\n\t };\n\n/** A single subtree entry in a Name Constraints permitted/excluded list. */\nexport interface GeneralSubtree<\n\tTForm extends ParsedNameConstraintForm =\n\t\t| {\n\t\t\t\treadonly type: 'dns';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'email';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'uri';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'ip';\n\t\t\t\treadonly addressBytes: Uint8Array;\n\t\t\t\treadonly maskBytes: Uint8Array;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'directoryName';\n\t\t\t\treadonly derHex: string;\n\t\t },\n> {\n\t/** The name form that defines this constraint boundary. */\n\treadonly base: TForm;\n}\n\n/**\n * RFC 5280 §4.2.1.10 Name Constraints.\n *\n * A CA certificate may restrict the namespace of all subject names in\n * subsequent certificates in the path.\n */\nexport interface NameConstraints<\n\tTForm extends ParsedNameConstraintForm =\n\t\t| {\n\t\t\t\treadonly type: 'dns';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'email';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'uri';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'ip';\n\t\t\t\treadonly addressBytes: Uint8Array;\n\t\t\t\treadonly maskBytes: Uint8Array;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'directoryName';\n\t\t\t\treadonly derHex: string;\n\t\t },\n> {\n\t/** Names that MUST fall within these subtrees to be valid. */\n\treadonly permittedSubtrees?: readonly GeneralSubtree<TForm>[];\n\t/** Names that MUST NOT fall within these subtrees. Takes precedence over permitted. */\n\treadonly excludedSubtrees?: readonly GeneralSubtree<TForm>[];\n}\n\n/** Well-known AIA access methods: OCSP responder or CA issuer certificate. */\nexport type KnownAuthorityInfoAccessMethod = 'ocsp' | 'caIssuers';\n\n/** AIA access method identified by a custom OID not in the well-known set. */\nexport interface CustomAuthorityInfoAccessMethod {\n\t/** Discriminant for the custom-OID access method variant. */\n\treadonly type: 'oid';\n\t/** Dotted-decimal OID of the access method. */\n\treadonly value: string;\n}\n\n/** AIA access method — either a well-known string or a custom OID. */\nexport type AuthorityInfoAccessMethod =\n\t| KnownAuthorityInfoAccessMethod\n\t| CustomAuthorityInfoAccessMethod;\n\n/** A single entry in the Authority Information Access extension (RFC 5280 §4.2.2.1). */\nexport interface AuthorityInformationAccess {\n\t/** Access method (`'ocsp'`, `'caIssuers'`, or custom OID). */\n\treadonly method:\n\t\t| 'ocsp'\n\t\t| 'caIssuers'\n\t\t| {\n\t\t\t\treadonly type: 'oid';\n\t\t\t\treadonly value: string;\n\t\t };\n\t/** URI where the resource can be fetched. */\n\treadonly uri: string;\n}\n\n/** Well-known Extended Key Usage purpose strings (RFC 5280 §4.2.1.12). */\nexport type KnownExtendedKeyUsage =\n\t| 'serverAuth'\n\t| 'clientAuth'\n\t| 'codeSigning'\n\t| 'emailProtection'\n\t| 'timeStamping'\n\t| 'ocspSigning';\n\n/** Extended Key Usage purpose identified by a custom OID. */\nexport interface CustomExtendedKeyUsage {\n\t/** Discriminant for the custom-OID EKU variant. */\n\treadonly type: 'oid';\n\t/** Dotted-decimal OID of the usage purpose. */\n\treadonly value: string;\n}\n\n/** Extended Key Usage — either a well-known purpose string or a custom OID. */\nexport type ExtendedKeyUsage =\n\t| 'serverAuth'\n\t| 'clientAuth'\n\t| 'codeSigning'\n\t| 'emailProtection'\n\t| 'timeStamping'\n\t| 'ocspSigning'\n\t| {\n\t\t\treadonly type: 'oid';\n\t\t\treadonly value: string;\n\t };\n\n/** Map from well-known EKU names to their dotted-decimal OIDs. */\nconst EXTENDED_KEY_USAGE_OIDS: Record<KnownExtendedKeyUsage, string> = {\n\tserverAuth: OIDS.serverAuth,\n\tclientAuth: OIDS.clientAuth,\n\tcodeSigning: OIDS.codeSigning,\n\temailProtection: OIDS.emailProtection,\n\ttimeStamping: OIDS.timeStamping,\n\tocspSigning: OIDS.ocspSigning,\n};\n\n/** Map from well-known AIA method names to their dotted-decimal OIDs. */\nconst AUTHORITY_INFO_ACCESS_METHOD_OIDS: Record<KnownAuthorityInfoAccessMethod, string> = {\n\tocsp: OIDS.ocspAccessMethod,\n\tcaIssuers: OIDS.caIssuersAccessMethod,\n};\n\n/**\n * Build the v3 extensions block for a certificate.\n *\n * Automatically adds SKI, AKI (when issuer key is available), and\n * basicConstraints (defaults to `{ ca: false }`). Additional extensions\n * come from the caller's {@linkcode CertificateExtensionsInput}.\n *\n * @param subjectPublicKeyInfo DER-encoded SPKI of the subject.\n * @param issuerPublicKeyInfo DER-encoded SPKI of the issuer, or `undefined` for self-signed.\n * @param input Optional extension configuration.\n * @param subjectIsEmpty Whether the certificate subject DN is empty. When `true`, the\n * subjectAltName extension is marked critical per RFC 5280 §4.2.1.6.\n * @returns Array of DER-encoded Extension SEQUENCEs.\n */\nexport function buildCertificateExtensions(\n\tsubjectPublicKeyInfo: Uint8Array,\n\tissuerPublicKeyInfo: Uint8Array | undefined,\n\tinput: CertificateExtensionsInput | undefined,\n\tsubjectIsEmpty = false,\n): Uint8Array[] {\n\tconst extensions: Uint8Array[] = [];\n\tconst seen = new Set<string>();\n\tconst basicConstraints = input?.basicConstraints ?? { ca: false };\n\tpushKnownExtension(extensions, seen, BASIC_CONSTRAINTS_EXTENSION_DEFINITION, basicConstraints);\n\tpushKnownExtension(\n\t\textensions,\n\t\tseen,\n\t\tSUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n\t\tbuildSubjectKeyIdentifier(subjectPublicKeyInfo),\n\t);\n\tif (issuerPublicKeyInfo !== undefined) {\n\t\tpushKnownExtension(\n\t\t\textensions,\n\t\t\tseen,\n\t\t\tAUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n\t\t\tbuildSubjectKeyIdentifier(issuerPublicKeyInfo),\n\t\t);\n\t}\n\tappendConfiguredExtensions(extensions, seen, input, 'certificate', {\n\t\tincludeBasicConstraints: false,\n\t\tsubjectIsEmpty,\n\t});\n\treturn extensions;\n}\n\n/**\n * Build the extensions for a CSR's extensionRequest attribute.\n *\n * Unlike {@linkcode buildCertificateExtensions}, SKI/AKI are not auto-generated.\n *\n * @param input Optional extension configuration.\n * @returns Array of DER-encoded Extension SEQUENCEs.\n */\nexport function buildRequestedExtensions(\n\tinput: CertificateExtensionsInput | undefined,\n): Uint8Array[] {\n\tconst extensions: Uint8Array[] = [];\n\tconst seen = new Set<string>();\n\tappendConfiguredExtensions(extensions, seen, input, 'csr', { includeBasicConstraints: true });\n\treturn extensions;\n}\n\n/** Encode and push each configured extension from the input, enforcing no duplicates. */\nfunction appendConfiguredExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput | undefined,\n\tcontext: ExtensionRegistryContext,\n\toptions: {\n\t\treadonly includeBasicConstraints: boolean;\n\t\t/** When true, SAN is marked critical per RFC 5280 §4.2.1.6. */\n\t\treadonly subjectIsEmpty?: boolean;\n\t},\n): void {\n\tif (input === undefined) {\n\t\treturn;\n\t}\n\tappendConstraintExtensions(encoded, seen, input, options.includeBasicConstraints);\n\tappendIdentityExtensions(encoded, seen, input, options.subjectIsEmpty === true);\n\tappendPolicyExtensions(encoded, seen, input);\n\tappendAccessExtensions(encoded, seen, input);\n\tappendCustomExtensions(encoded, seen, input, context);\n}\n\nfunction appendConstraintExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput,\n\tincludeBasicConstraints: boolean,\n): void {\n\tif (includeBasicConstraints && input.basicConstraints !== undefined) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tBASIC_CONSTRAINTS_EXTENSION_DEFINITION,\n\t\t\tinput.basicConstraints,\n\t\t);\n\t}\n\tif (input.keyUsage !== undefined && input.keyUsage.length > 0) {\n\t\tpushKnownExtension(encoded, seen, KEY_USAGE_EXTENSION_DEFINITION, input.keyUsage);\n\t}\n\tif (input.nameConstraints !== undefined) {\n\t\tpushKnownExtension(encoded, seen, NAME_CONSTRAINTS_EXTENSION_DEFINITION, input.nameConstraints);\n\t}\n}\n\nfunction appendIdentityExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput,\n\tsubjectIsEmpty: boolean,\n): void {\n\tif (input.subjectAltNames !== undefined && input.subjectAltNames.length > 0) {\n\t\t// RFC 5280 §4.2.1.6: SAN MUST be critical when subject DN is empty.\n\t\tconst sanCritical = subjectIsEmpty ? true : undefined;\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tSUBJECT_ALT_NAME_EXTENSION_DEFINITION,\n\t\t\tinput.subjectAltNames,\n\t\t\tsanCritical,\n\t\t);\n\t}\n\tif (input.extendedKeyUsage !== undefined && input.extendedKeyUsage.length > 0) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tEXTENDED_KEY_USAGE_EXTENSION_DEFINITION,\n\t\t\tinput.extendedKeyUsage,\n\t\t);\n\t}\n}\n\n/** Appends configured certificate-policy extensions while enforcing unique OIDs. */\nfunction appendPolicyExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput,\n): void {\n\tif (input.certificatePolicies !== undefined && input.certificatePolicies.length > 0) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tCERTIFICATE_POLICIES_EXTENSION_DEFINITION,\n\t\t\tinput.certificatePolicies,\n\t\t);\n\t}\n\tif (input.policyMappings !== undefined && input.policyMappings.length > 0) {\n\t\tpushKnownExtension(encoded, seen, POLICY_MAPPINGS_EXTENSION_DEFINITION, input.policyMappings);\n\t}\n\tif (input.policyConstraints !== undefined) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tPOLICY_CONSTRAINTS_EXTENSION_DEFINITION,\n\t\t\tinput.policyConstraints,\n\t\t);\n\t}\n\tif (input.inhibitAnyPolicy !== undefined) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tINHIBIT_ANY_POLICY_EXTENSION_DEFINITION,\n\t\t\tinput.inhibitAnyPolicy,\n\t\t);\n\t}\n}\n\nfunction appendAccessExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput,\n): void {\n\tif (input.authorityInfoAccess !== undefined && input.authorityInfoAccess.length > 0) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tAUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION,\n\t\t\tinput.authorityInfoAccess,\n\t\t);\n\t}\n\tif (input.crlDistributionPoints !== undefined && input.crlDistributionPoints.length > 0) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tCRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION,\n\t\t\tinput.crlDistributionPoints,\n\t\t);\n\t}\n}\n\nfunction appendCustomExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput,\n\tcontext: ExtensionRegistryContext,\n): void {\n\tif (input.customExtensions !== undefined) {\n\t\tfor (const extension of input.customExtensions) {\n\t\t\tconst knownDefinition = getExtensionDefinition(extension.oid);\n\t\t\tif (knownDefinition !== undefined && !knownDefinition.contexts.includes(context)) {\n\t\t\t\tthrow new Error(`Extension ${extension.oid} is not supported in ${context} context`);\n\t\t\t}\n\t\t\tpushExtension(\n\t\t\t\tencoded,\n\t\t\t\tseen,\n\t\t\t\textension.oid,\n\t\t\t\tnew Uint8Array(extension.value),\n\t\t\t\textension.critical ?? false,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** Encode a known extension via its registry definition and push it. */\nfunction pushKnownExtension<TParsed, TInput>(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tdefinition: ExtensionDefinition<TParsed, TInput>,\n\tvalue: TInput,\n\tcritical = definition.defaultCritical,\n): void {\n\tpushExtension(encoded, seen, definition.oid, definition.encode(value), critical);\n}\n\n/**\n * Encode a single X.509 Extension SEQUENCE (OID + optional critical BOOLEAN + OCTET STRING).\n *\n * @param oid Dotted-decimal extension OID.\n * @param extnValue DER-encoded extension payload.\n * @param critical Whether to mark the extension as critical. Default `false`.\n */\nexport function encodeExtension(oid: string, extnValue: Uint8Array, critical = false): Uint8Array {\n\tconst fields = [objectIdentifier(oid)];\n\tif (critical) {\n\t\tfields.push(bool(true));\n\t}\n\tfields.push(octetString(extnValue));\n\treturn sequence(fields);\n}\n\n/**\n * DER-encode a {@linkcode BasicConstraints} value.\n *\n * @param input CA flag and optional pathLength.\n * @returns DER SEQUENCE suitable for wrapping in an Extension OCTET STRING.\n */\nexport function encodeBasicConstraints(input: BasicConstraints): Uint8Array {\n\tconst fields: Uint8Array[] = [];\n\tif (input.ca) {\n\t\tfields.push(bool(true));\n\t}\n\tif (input.pathLength !== undefined) {\n\t\tif (!input.ca) {\n\t\t\tthrow new Error('pathLength requires ca=true');\n\t\t}\n\t\tfields.push(integerFromNumber(input.pathLength));\n\t}\n\treturn sequence(fields);\n}\n\n/**\n * DER-encode a Key Usage BIT STRING from an array of {@linkcode KeyUsage} flags.\n *\n * @param usages Flags to set in the bit string.\n */\nexport function encodeKeyUsage(usages: readonly KeyUsage[]): Uint8Array {\n\treturn encodeKeyUsageExtension(usages);\n}\n\n/**\n * DER-encode a single {@linkcode SubjectAltName} GeneralName element.\n *\n * @param value The SAN entry to encode.\n */\nexport function encodeSubjectAltName(value: SubjectAltName): Uint8Array {\n\tswitch (value.type) {\n\t\tcase 'dns':\n\t\t\treturn implicitPrimitiveContext(2, new TextEncoder().encode(value.value));\n\t\tcase 'email':\n\t\t\treturn implicitPrimitiveContext(1, new TextEncoder().encode(value.value));\n\t\tcase 'uri':\n\t\t\treturn implicitPrimitiveContext(6, new TextEncoder().encode(value.value));\n\t\tcase 'srv':\n\t\t\treturn implicitConstructedContext(\n\t\t\t\t0,\n\t\t\t\tsequence([objectIdentifier(OIDS.idOnDnsSrv), explicitContext(0, ia5String(value.value))]),\n\t\t\t);\n\t\tcase 'ip':\n\t\t\treturn implicitPrimitiveContext(7, encodeIpAddress(value.value));\n\t\tcase 'directoryName':\n\t\t\treturn implicitConstructedContext(4, extractDirectoryNameContent(value.derHex));\n\t\tcase 'unknown':\n\t\t\treturn tlv(value.tag, value.value);\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = value;\n\t\t\tthrow new Error(`Unhandled SubjectAltName type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * DER-encode an Extended Key Usage SEQUENCE OF OIDs.\n *\n * @param usages EKU purposes to encode.\n */\nexport function encodeExtendedKeyUsage(usages: readonly ExtendedKeyUsage[]): Uint8Array {\n\treturn sequence(usages.map((usage) => objectIdentifier(getExtendedKeyUsageOid(usage))));\n}\n\n/**\n * DER-encode an Authority Information Access SEQUENCE.\n *\n * @param entries AIA entries (OCSP, caIssuers, or custom) to encode.\n */\nexport function encodeAuthorityInfoAccess(\n\tentries: readonly AuthorityInformationAccess[],\n): Uint8Array {\n\treturn sequence(\n\t\tentries.map((entry) =>\n\t\t\tsequence([\n\t\t\t\tobjectIdentifier(getAuthorityInfoAccessMethodOid(entry.method)),\n\t\t\t\timplicitPrimitiveContext(6, new TextEncoder().encode(entry.uri)),\n\t\t\t]),\n\t\t),\n\t);\n}\n\n/**\n * DER-encode a CRL Distribution Points SEQUENCE.\n *\n * @param points Distribution points to encode.\n */\nexport function encodeCrlDistributionPoints(points: readonly DistributionPoint[]): Uint8Array {\n\treturn sequence(points.map((point) => sequence(encodeDistributionPoint(point))));\n}\n\n/**\n * DER-encode a Name Constraints extension value.\n *\n * @param constraints Permitted and/or excluded subtrees.\n */\nexport function encodeNameConstraints(constraints: NameConstraints): Uint8Array {\n\tconst parts: Uint8Array[] = [];\n\tif (constraints.permittedSubtrees !== undefined && constraints.permittedSubtrees.length > 0) {\n\t\tparts.push(\n\t\t\timplicitConstructedContext(\n\t\t\t\t0,\n\t\t\t\tconcatBytes(constraints.permittedSubtrees.map(encodeGeneralSubtree)),\n\t\t\t),\n\t\t);\n\t}\n\tif (constraints.excludedSubtrees !== undefined && constraints.excludedSubtrees.length > 0) {\n\t\tparts.push(\n\t\t\timplicitConstructedContext(\n\t\t\t\t1,\n\t\t\t\tconcatBytes(constraints.excludedSubtrees.map(encodeGeneralSubtree)),\n\t\t\t),\n\t\t);\n\t}\n\treturn sequence(parts);\n}\n\n/**\n * DER-encode a Certificate Policies extension value.\n *\n * @param policies Non-empty array of policy information entries.\n */\nexport function encodeCertificatePolicies(policies: CertificatePolicies): Uint8Array {\n\tif (policies.length === 0) {\n\t\tthrow new Error('certificatePolicies must not be empty');\n\t}\n\treturn sequence(policies.map(encodePolicyInformation));\n}\n\n/**\n * DER-encode a Policy Mappings extension value.\n *\n * @param mappings Non-empty array of issuer-to-subject policy pairs. Neither OID may be anyPolicy.\n */\nexport function encodePolicyMappings(mappings: PolicyMappings): Uint8Array {\n\tif (mappings.length === 0) {\n\t\tthrow new Error('policyMappings must not be empty');\n\t}\n\treturn sequence(\n\t\tmappings.map((mapping) => {\n\t\t\tvalidatePolicyOid(mapping.issuerDomainPolicy);\n\t\t\tvalidatePolicyOid(mapping.subjectDomainPolicy);\n\t\t\tif (\n\t\t\t\tmapping.issuerDomainPolicy === OIDS.anyPolicy ||\n\t\t\t\tmapping.subjectDomainPolicy === OIDS.anyPolicy\n\t\t\t) {\n\t\t\t\tthrow new Error('policyMappings must not use anyPolicy');\n\t\t\t}\n\t\t\treturn sequence([\n\t\t\t\tobjectIdentifier(mapping.issuerDomainPolicy),\n\t\t\t\tobjectIdentifier(mapping.subjectDomainPolicy),\n\t\t\t]);\n\t\t}),\n\t);\n}\n\n/**\n * DER-encode a Policy Constraints extension value.\n *\n * @param constraints At least one of `requireExplicitPolicy` or `inhibitPolicyMapping` must be set.\n */\nexport function encodePolicyConstraints(constraints: PolicyConstraints): Uint8Array {\n\tconst fields: Uint8Array[] = [];\n\tif (constraints.requireExplicitPolicy !== undefined) {\n\t\tfields.push(\n\t\t\timplicitPrimitiveContext(0, encodeIntegerContent(constraints.requireExplicitPolicy)),\n\t\t);\n\t}\n\tif (constraints.inhibitPolicyMapping !== undefined) {\n\t\tfields.push(\n\t\t\timplicitPrimitiveContext(1, encodeIntegerContent(constraints.inhibitPolicyMapping)),\n\t\t);\n\t}\n\tif (fields.length === 0) {\n\t\tthrow new Error('policyConstraints must set requireExplicitPolicy or inhibitPolicyMapping');\n\t}\n\treturn sequence(fields);\n}\n\n/**\n * DER-encode an Inhibit anyPolicy extension value (single INTEGER).\n *\n * @param input The skipCerts threshold.\n */\nexport function encodeInhibitAnyPolicy(input: InhibitAnyPolicy): Uint8Array {\n\treturn integerFromNumber(input.skipCerts);\n}\n\n/** DER-encode a single PolicyInformation SEQUENCE. */\nfunction encodePolicyInformation(policy: PolicyInformation): Uint8Array {\n\tvalidatePolicyOid(policy.policyIdentifier);\n\tconst fields = [objectIdentifier(policy.policyIdentifier)];\n\tif (policy.policyQualifiers !== undefined && policy.policyQualifiers.length > 0) {\n\t\tfields.push(sequence(policy.policyQualifiers.map(encodePolicyQualifierInfo)));\n\t}\n\treturn sequence(fields);\n}\n\n/** DER-encode a single PolicyQualifierInfo SEQUENCE. */\nfunction encodePolicyQualifierInfo(qualifier: PolicyQualifierInfo): Uint8Array {\n\tswitch (qualifier.type) {\n\t\tcase 'cps':\n\t\t\treturn sequence([objectIdentifier(OIDS.cpsPolicyQualifier), ia5String(qualifier.uri)]);\n\t\tcase 'userNotice':\n\t\t\treturn sequence([\n\t\t\t\tobjectIdentifier(OIDS.userNoticePolicyQualifier),\n\t\t\t\tencodeUserNoticePolicyQualifierInfo(qualifier),\n\t\t\t]);\n\t\tcase 'oid':\n\t\t\tvalidateOid(qualifier.oid);\n\t\t\treturn sequence([objectIdentifier(qualifier.oid), new Uint8Array(qualifier.qualifierDer)]);\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = qualifier;\n\t\t\tthrow new Error(`Unhandled PolicyQualifierInfo type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** DER-encode a UserNotice qualifier SEQUENCE. */\nfunction encodeUserNoticePolicyQualifierInfo(qualifier: UserNoticePolicyQualifierInfo): Uint8Array {\n\tconst fields: Uint8Array[] = [];\n\tif (qualifier.noticeRef !== undefined) {\n\t\tfields.push(encodePolicyNoticeReference(qualifier.noticeRef));\n\t}\n\tif (qualifier.explicitText !== undefined) {\n\t\tfields.push(utf8String(qualifier.explicitText));\n\t}\n\treturn sequence(fields);\n}\n\n/** DER-encode a NoticeReference SEQUENCE. */\nfunction encodePolicyNoticeReference(reference: PolicyNoticeReference): Uint8Array {\n\treturn sequence([\n\t\tutf8String(reference.organization),\n\t\tsequence(reference.noticeNumbers.map((noticeNumber) => integerFromNumber(noticeNumber))),\n\t]);\n}\n\n/** Encode an INTEGER and return only the content bytes (no TLV wrapper). */\nfunction encodeIntegerContent(value: number): Uint8Array {\n\treturn readElement(integerFromNumber(value)).value;\n}\n\n/** DER-encode a GeneralSubtree SEQUENCE (base name only; min/max omitted per RFC 5280). */\nfunction encodeGeneralSubtree(subtree: GeneralSubtree): Uint8Array {\n\treturn sequence([encodeNameConstraintForm(subtree.base)]);\n}\n\n/** DER-encode the fields of a single DistributionPoint. */\nfunction encodeDistributionPoint(point: DistributionPoint): Uint8Array[] {\n\tif (point.crlIssuer !== undefined && point.crlIssuer.length === 0) {\n\t\tthrow new Error('DistributionPoint crlIssuer must not be empty');\n\t}\n\tif (point.distributionPoint === undefined && point.crlIssuer === undefined) {\n\t\tthrow new Error('DistributionPoint must contain distributionPoint or crlIssuer');\n\t}\n\tconst fields: Uint8Array[] = [];\n\tif (point.distributionPoint !== undefined) {\n\t\tfields.push(\n\t\t\timplicitConstructedContext(0, encodeDistributionPointName(point.distributionPoint)),\n\t\t);\n\t}\n\tif (point.reasons !== undefined && point.reasons.length > 0) {\n\t\tfields.push(\n\t\t\timplicitPrimitiveContext(1, encodeDistributionPointReasonFlagsContent(point.reasons)),\n\t\t);\n\t}\n\tif (point.crlIssuer !== undefined && point.crlIssuer.length > 0) {\n\t\tfields.push(\n\t\t\timplicitConstructedContext(2, concatBytes(point.crlIssuer.map(encodeSubjectAltName))),\n\t\t);\n\t}\n\treturn fields;\n}\n\n/** DER-encode a DistributionPointName (fullName or relativeName). */\nfunction encodeDistributionPointName(name: DistributionPointName): Uint8Array {\n\tif (name.fullName !== undefined && name.relativeName !== undefined) {\n\t\tthrow new Error('DistributionPointName cannot contain both fullName and relativeName');\n\t}\n\tif (name.fullName !== undefined) {\n\t\tif (name.fullName.length === 0) {\n\t\t\tthrow new Error('DistributionPointName fullName must not be empty');\n\t\t}\n\t\treturn implicitConstructedContext(0, concatBytes(name.fullName.map(encodeSubjectAltName)));\n\t}\n\tif (name.relativeName !== undefined) {\n\t\tconst relativeName = encodeRelativeDistinguishedName(name.relativeName);\n\t\tconst relativeNameElement = readElement(relativeName);\n\t\treturn implicitConstructedContext(\n\t\t\t1,\n\t\t\trelativeName.slice(relativeNameElement.start, relativeNameElement.end),\n\t\t);\n\t}\n\tthrow new Error('DistributionPointName must contain fullName or relativeName');\n}\n\n/** DER-encode a NameConstraintForm as an implicit-tagged {@linkcode GeneralName}. */\nfunction encodeNameConstraintForm(form: NameConstraintForm): Uint8Array {\n\tswitch (form.type) {\n\t\tcase 'dns':\n\t\t\treturn implicitPrimitiveContext(2, new TextEncoder().encode(form.value));\n\t\tcase 'email':\n\t\t\treturn implicitPrimitiveContext(1, new TextEncoder().encode(form.value));\n\t\tcase 'uri':\n\t\t\treturn implicitPrimitiveContext(6, new TextEncoder().encode(form.value));\n\t\tcase 'ip':\n\t\t\treturn implicitPrimitiveContext(7, concatBytes([form.addressBytes, form.maskBytes]));\n\t\tcase 'directoryName':\n\t\t\treturn implicitConstructedContext(4, extractDirectoryNameContent(form.derHex));\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/** Extract the content bytes from a hex-encoded DER SEQUENCE (strips the outer TLV). */\nfunction extractDirectoryNameContent(derHex: string): Uint8Array {\n\tconst element = readRootElement(hexToBytes(derHex), { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('directoryName derHex must encode a DER SEQUENCE');\n\t}\n\treturn new Uint8Array(element.value);\n}\n\n/**\n * Resolve an {@linkcode ExtendedKeyUsage} to its dotted-decimal OID.\n *\n * @param usage Well-known string or custom OID object.\n */\nexport function getExtendedKeyUsageOid(usage: ExtendedKeyUsage): string {\n\tif (typeof usage === 'string') {\n\t\treturn EXTENDED_KEY_USAGE_OIDS[usage];\n\t}\n\tvalidateOid(usage.value);\n\treturn usage.value;\n}\n\n/**\n * Map a dotted-decimal OID to an {@linkcode ExtendedKeyUsage} value.\n *\n * Returns a well-known string for recognized OIDs, or `{ type: 'oid', value }` otherwise.\n */\nexport function parseExtendedKeyUsageOid(oid: string): ExtendedKeyUsage {\n\tswitch (oid) {\n\t\tcase OIDS.serverAuth:\n\t\t\treturn 'serverAuth';\n\t\tcase OIDS.clientAuth:\n\t\t\treturn 'clientAuth';\n\t\tcase OIDS.codeSigning:\n\t\t\treturn 'codeSigning';\n\t\tcase OIDS.emailProtection:\n\t\t\treturn 'emailProtection';\n\t\tcase OIDS.timeStamping:\n\t\t\treturn 'timeStamping';\n\t\tcase OIDS.ocspSigning:\n\t\t\treturn 'ocspSigning';\n\t}\n\treturn { type: 'oid', value: oid };\n}\n\n/**\n * Resolve an {@linkcode AuthorityInfoAccessMethod} to its dotted-decimal OID.\n *\n * @param method Well-known string or custom OID object.\n */\nexport function getAuthorityInfoAccessMethodOid(method: AuthorityInfoAccessMethod): string {\n\tif (typeof method === 'string') {\n\t\treturn AUTHORITY_INFO_ACCESS_METHOD_OIDS[method];\n\t}\n\tvalidateOid(method.value);\n\treturn method.value;\n}\n\n/**\n * Map a dotted-decimal OID to an {@linkcode AuthorityInfoAccessMethod} value.\n *\n * Returns `'ocsp'` or `'caIssuers'` for recognized OIDs, or `{ type: 'oid', value }` otherwise.\n */\nexport function parseAuthorityInfoAccessMethodOid(oid: string): AuthorityInfoAccessMethod {\n\tswitch (oid) {\n\t\tcase OIDS.ocspAccessMethod:\n\t\t\treturn 'ocsp';\n\t\tcase OIDS.caIssuersAccessMethod:\n\t\t\treturn 'caIssuers';\n\t}\n\treturn { type: 'oid', value: oid };\n}\n\n/** Parse a dotted-decimal/colon-hex IP string to raw address bytes. */\nfunction encodeIpAddress(input: string): Uint8Array {\n\treturn parseIpAddressToBytes(input);\n}\n\n/** @internal Compute the SKI as SHA-1 of the subjectPublicKey BIT STRING content. */\nexport function buildSubjectKeyIdentifier(subjectPublicKeyInfo: Uint8Array): Uint8Array {\n\tconst topLevel = readSequenceChildren(subjectPublicKeyInfo);\n\tconst subjectPublicKey = topLevel[1];\n\tif (subjectPublicKey === undefined || subjectPublicKey.tag !== 0x03) {\n\t\tthrow new Error('SPKI missing subject public key bit string');\n\t}\n\tconst publicKeyBytes = subjectPublicKey.value.slice(1);\n\treturn sha1(publicKeyBytes);\n}\n\n/** Throw if the string is not a valid dotted-decimal OID. */\nfunction validateOid(oid: string): void {\n\tif (!/^\\d+(?:\\.\\d+)+$/.test(oid)) {\n\t\tthrow new Error(`Invalid OID: ${oid}`);\n\t}\n}\n\n/** Validate that a policy OID is syntactically valid. */\nfunction validatePolicyOid(oid: string): void {\n\tvalidateOid(oid);\n}\n\n/** Encode and push an extension, rejecting duplicate OIDs. */\nfunction pushExtension(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\toid: string,\n\tvalue: Uint8Array,\n\tcritical = false,\n): void {\n\tvalidateOid(oid);\n\tif (seen.has(oid)) {\n\t\tthrow new Error(`Duplicate extension OID: ${oid}`);\n\t}\n\tseen.add(oid);\n\tencoded.push(encodeExtension(oid, value, critical));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqqBA,MAAM,IAAiE;CACtE,YAAY,EAAK;CACjB,YAAY,EAAK;CACjB,aAAa,EAAK;CAClB,iBAAiB,EAAK;CACtB,cAAc,EAAK;CACnB,aAAa,EAAK;AACnB,GAGM,IAAoF;CACzF,MAAM,EAAK;CACX,WAAW,EAAK;AACjB;;;;;;;;;;;;;;;AAgBA,SAAgB,2BACf,GACA,GACA,GACA,IAAiB,IACF;CACf,IAAM,IAA2B,CAAC,GAC5B,oBAAO,IAAI,IA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K,iBACT,OAAO;EACR,KAAK,EAAK,cACT,OAAO;EACR,KAAK,EAAK,aACT,OAAO;CACT;CACA,OAAO;EAAE,MAAM;EAAO,OAAO;CAAI;AAClC;;;;;;AAOA,SAAgB,gCAAgC,GAA2C;CAK1F,OAJI,OAAO,KAAW,WACd,EAAkC,MAE1C,YAAY,EAAO,KAAK,GACjB,EAAO;AACf;;;;;;AAOA,SAAgB,kCAAkC,GAAwC;CACzF,QAAQ,GAAR;EACC,KAAK,EAAK,kBACT,OAAO;EACR,KAAK,EAAK,uBACT,OAAO;CACT;CACA,OAAO;EAAE,MAAM;EAAO,OAAO;CAAI;AAClC;;AAGA,SAAS,gBAAgB,GAA2B;CACnD,OAAO,EAAsB,CAAK;AACnC;;AAGA,SAAgB,0BAA0B,GAA8C;CAEvF,IAAM,IADW,EAAqB,CACN,CAAC,CAAC;CAClC,IAAI,MAAqB,KAAA,KAAa,EAAiB,QAAQ,GAC9D,MAAU,MAAM,4CAA4C;CAG7D,OAAO,EADgB,EAAiB,MAAM,MAAM,CAC3B,CAAC;AAC3B;;AAGA,SAAS,YAAY,GAAmB;CACvC,IAAI,CAAC,kBAAkB,KAAK,CAAG,GAC9B,MAAU,MAAM,gBAAgB,GAAK;AAEvC;;AAGA,SAAS,kBAAkB,GAAmB;CAC7C,YAAY,CAAG;AAChB;;AAGA,SAAS,cACR,GACA,GACA,GACA,GACA,IAAW,IACJ;CAEP,IADA,YAAY,CAAG,GACX,EAAK,IAAI,CAAG,GACf,MAAU,MAAM,4BAA4B,GAAK;CAGlD,AADA,EAAK,IAAI,CAAG,GACZ,EAAQ,KAAK,gBAAgB,GAAK,GAAO,CAAQ,CAAC;AACnD"}
1
+ {"version":3,"file":"extensions.js","names":["_exhaustive"],"sources":["../../src/x509/extensions.ts"],"sourcesContent":["/**\n * Typed certificate and CSR extension model plus ASN.1 encoder helpers.\n *\n * Defines input types for every supported X.509v3 extension (RFC 5280) and\n * the DER encoders consumed by certificate and CSR builder flows.\n *\n * @module\n */\n\nimport {\n\tcanonicalizeOid,\n\tchildrenOf,\n\tdecodeObjectIdentifier,\n\thexToBytes,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tbool,\n\tconcatBytes,\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tia5Bytes,\n\tia5String,\n\timplicitConstructedContext,\n\timplicitPrimitiveContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\treadSequenceChildren,\n\tsequence,\n\ttlv,\n\tutf8String,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { sha1 } from '#micro509/internal/crypto/hash';\nimport { parseIpAddressToBytes } from '#micro509/internal/shared/ip';\nimport {\n\tencodeDistributionPointReasonFlagsContent,\n\tencodeKeyUsageExtension,\n} from '#micro509/internal/x509/extension-bits';\nimport { throwExtensionEncoderError } from '#micro509/internal/x509/extension-errors';\nimport type {\n\tExtensionDefinition,\n\tExtensionRegistryContext,\n} from '#micro509/internal/x509/extension-registry';\nimport {\n\tAUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION,\n\tAUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n\tBASIC_CONSTRAINTS_EXTENSION_DEFINITION,\n\tCERTIFICATE_POLICIES_EXTENSION_DEFINITION,\n\tCRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION,\n\tEXTENDED_KEY_USAGE_EXTENSION_DEFINITION,\n\tgetExtensionDefinition,\n\tINHIBIT_ANY_POLICY_EXTENSION_DEFINITION,\n\tKEY_USAGE_EXTENSION_DEFINITION,\n\tNAME_CONSTRAINTS_EXTENSION_DEFINITION,\n\tPOLICY_CONSTRAINTS_EXTENSION_DEFINITION,\n\tPOLICY_MAPPINGS_EXTENSION_DEFINITION,\n\tSUBJECT_ALT_NAME_EXTENSION_DEFINITION,\n\tSUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n} from '#micro509/internal/x509/extension-registry';\nimport { GENERAL_NAME_WIRE_TAGS } from '#micro509/internal/x509/general-name-tags';\nimport { isResultError } from '#micro509/result/result';\nimport type { RelativeDistinguishedNameInput } from '#micro509/x509/name';\nimport { encodeRelativeDistinguishedName } from '#micro509/x509/name';\n\nexport type { ExtensionEncoderErrorCode } from '#micro509/internal/x509/extension-errors';\nexport type {\n\tNameAttribute,\n\tNameFieldKey,\n\tRelativeDistinguishedNameInput,\n} from '#micro509/x509/name';\n\n/**\n * A decoded BIT STRING flag set.\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 ({@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1}) requires to be zero.\n * Extension flag decoding rejects such encodings, so parsed extension values\n * always report `false`.\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/**\n * RFC 5280 §4.2.1.3 Key Usage bit flag.\n *\n * Each value corresponds to one bit in the KeyUsage BIT STRING.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.3 RFC 5280 §4.2.1.3}\n */\nexport type KeyUsage =\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\n/**\n * RFC 5280 §4.2.1.6 Subject Alternative Name / GeneralName.\n *\n * Discriminated union keyed on `type`.\n *\n * The `'unknown'` variant preserves unrecognized {@linkcode GeneralName} tags for round-trip fidelity.\n */\nexport type SubjectAltName =\n\t| {\n\t\t\t/** DNS hostname (dNSName [2]). */\n\t\t\treadonly type: 'dns';\n\t\t\t/** Fully-qualified domain name, e.g. `\"example.com\"`. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** IP address (iPAddress [7]). */\n\t\t\treadonly type: 'ip';\n\t\t\t/** Dotted-decimal IPv4 or colon-hex IPv6 string. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** Email address (rfc822Name [1]). */\n\t\t\treadonly type: 'email';\n\t\t\t/** RFC 2821 §4.1.2 Mailbox (`Local-part@Domain`), e.g. `\"admin@example.com\"`. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** URI (uniformResourceIdentifier [6]). */\n\t\t\treadonly type: 'uri';\n\t\t\t/** Absolute URI string. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** SRV-ID otherName (id-on-dnsSRV). */\n\t\t\treadonly type: 'srv';\n\t\t\t/** SRV service name, e.g. `\"_imaps.example.com\"`. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** X.500 directory name (directoryName [4]). */\n\t\t\treadonly type: 'directoryName';\n\t\t\t/** Hex-encoded DER of the Name SEQUENCE. */\n\t\t\treadonly derHex: string;\n\t }\n\t| {\n\t\t\t/** Unrecognized {@linkcode GeneralName} tag, preserved as raw bytes. */\n\t\t\treadonly type: 'unknown';\n\t\t\t/** ASN.1 context tag number. */\n\t\t\treadonly tag: number;\n\t\t\t/** Raw content bytes of the element. */\n\t\t\treadonly value: Uint8Array;\n\t };\n\n/** Alias for {@linkcode SubjectAltName} — used where RFC 5280 says \"GeneralName\". */\nexport type GeneralName = SubjectAltName;\n\n/**\n * Revocation reason flags for CRL Distribution Points and Issuing Distribution Points\n * (RFC 5280 §4.2.1.13, §5.2.5).\n */\nexport type DistributionPointReason =\n\t| 'keyCompromise'\n\t| 'cACompromise'\n\t| 'affiliationChanged'\n\t| 'superseded'\n\t| 'cessationOfOperation'\n\t| 'certificateHold'\n\t| 'privilegeWithdrawn'\n\t| 'aACompromise';\n\n/**\n * Name component of a CRL Distribution Point, mirroring RFC 5280 §4.2.1.13\n * `DistributionPointName ::= CHOICE { fullName [0] GeneralNames,\n * nameRelativeToCRLIssuer [1] RelativeDistinguishedName }`.\n */\nexport type DistributionPointName =\n\t| {\n\t\t\t/** The `fullName [0]` alternative. */\n\t\t\treadonly type: 'fullName';\n\t\t\t/** Absolute {@linkcode GeneralName}(s) identifying the distribution point (usually a URI). */\n\t\t\treadonly fullName: readonly GeneralName[];\n\t }\n\t| {\n\t\t\t/** The `nameRelativeToCRLIssuer [1]` alternative. */\n\t\t\treadonly type: 'relativeName';\n\t\t\t/** Name relative to the issuer's DN. */\n\t\t\treadonly relativeName: RelativeDistinguishedNameInput;\n\t };\n\n/**\n * Input for a single CRL Distribution Point (RFC 5280 §4.2.1.13).\n *\n * At least one of `distributionPoint` or `crlIssuer` must be provided.\n * The union enforces this constraint at the type level.\n */\nexport type DistributionPoint =\n\t| {\n\t\t\t/** Where to fetch the CRL (fullName or relativeName). */\n\t\t\treadonly distributionPoint: DistributionPointName;\n\t\t\t/** Revocation reason subset. Absent means all reasons. */\n\t\t\treadonly reasons?: readonly DistributionPointReason[];\n\t\t\t/** Entity that signed the CRL, when different from the cert issuer. */\n\t\t\treadonly crlIssuer?: readonly GeneralName[];\n\t }\n\t| {\n\t\t\t/** Where to fetch the CRL. Optional when `crlIssuer` is present. */\n\t\t\treadonly distributionPoint?: DistributionPointName;\n\t\t\t/** Revocation reason subset. Absent means all reasons. */\n\t\t\treadonly reasons?: readonly DistributionPointReason[];\n\t\t\t/** Entity that signed the CRL. Required when `distributionPoint` is absent. */\n\t\t\treadonly crlIssuer: readonly GeneralName[];\n\t };\n\n/** Base shape for Issuing Distribution Point (RFC 5280 §5.2.5) — no scope restriction. */\nexport interface IssuingDistributionPointBase {\n\t/** Where to fetch this CRL. */\n\treadonly distributionPoint?: DistributionPointName;\n\t/** Limits the CRL to these revocation reasons. Absent means all reasons. */\n\treadonly onlySomeReasons?: readonly DistributionPointReason[];\n\t/** When true, the CRL may contain entries from other CAs. Default false. */\n\treadonly indirectCrl?: boolean;\n\t/** Must be absent or false in this variant (no user-cert-only restriction). */\n\treadonly onlyContainsUserCerts?: false;\n\t/** Must be absent or false in this variant (no CA-cert-only restriction). */\n\treadonly onlyContainsCACerts?: false;\n\t/** When true, the CRL only covers attribute certificates. Default false. */\n\treadonly onlyContainsAttributeCerts?: boolean;\n}\n\n/** IDP scoped to end-entity (user) certificates only. Mutually exclusive with CA / attribute scopes. */\nexport interface IssuingDistributionPointForUserCerts\n\textends Omit<IssuingDistributionPointBase, 'onlyContainsUserCerts'> {\n\t/** This variant only covers end-entity certificates. */\n\treadonly onlyContainsUserCerts: true;\n\t/** Must be absent or false when the CRL is not CA-only. */\n\treadonly onlyContainsCACerts?: false;\n\t/** Must be absent or false when the CRL is not attribute-cert-only. */\n\treadonly onlyContainsAttributeCerts?: false;\n}\n\n/** IDP scoped to CA certificates only. Mutually exclusive with user / attribute scopes. */\nexport interface IssuingDistributionPointForCaCerts\n\textends Omit<IssuingDistributionPointBase, 'onlyContainsCACerts'> {\n\t/** Must be absent or false when the CRL is not user-cert-only. */\n\treadonly onlyContainsUserCerts?: false;\n\t/** This variant only covers CA certificates. */\n\treadonly onlyContainsCACerts: true;\n\t/** Must be absent or false when the CRL is not attribute-cert-only. */\n\treadonly onlyContainsAttributeCerts?: false;\n}\n\n/** IDP scoped to attribute certificates only. Mutually exclusive with user / CA scopes. */\nexport interface IssuingDistributionPointForAttributeCerts\n\textends Omit<IssuingDistributionPointBase, 'onlyContainsAttributeCerts'> {\n\t/** Must be absent or false when the CRL is not user-cert-only. */\n\treadonly onlyContainsUserCerts?: false;\n\t/** Must be absent or false when the CRL is not CA-only. */\n\treadonly onlyContainsCACerts?: false;\n\t/** This variant only covers attribute certificates. */\n\treadonly onlyContainsAttributeCerts: true;\n}\n\n/**\n * Input for the Issuing Distribution Point CRL extension (RFC 5280 §5.2.5).\n *\n * The union enforces that at most one of the `onlyContains*` flags is true.\n */\nexport type IssuingDistributionPoint =\n\t| IssuingDistributionPointBase\n\t| IssuingDistributionPointForUserCerts\n\t| IssuingDistributionPointForCaCerts\n\t| IssuingDistributionPointForAttributeCerts;\n\n/**\n * RFC 5280 §4.2.1.9 Basic Constraints.\n *\n * A certificate with `ca: true` may issue other certificates; `pathLength`\n * limits how many additional CAs may appear below it in the chain.\n */\nexport type BasicConstraints =\n\t| {\n\t\t\t/** End-entity certificate: not a CA. */\n\t\t\treadonly ca: false;\n\t\t\t/** Never present on end-entity certificates. */\n\t\t\treadonly pathLength?: undefined;\n\t }\n\t| {\n\t\t\t/** CA certificate: may issue other certificates. */\n\t\t\treadonly ca: true;\n\t\t\t/** Maximum number of intermediate CA certificates allowed below this CA. */\n\t\t\treadonly pathLength?: number;\n\t };\n\n/** A single certificate policy: an OID plus optional qualifiers. */\nexport interface PolicyInformation {\n\t/** Dotted-decimal OID of the policy (e.g. `\"2.23.140.1.2.1\"` for DV). */\n\treadonly policyIdentifier: string;\n\t/** Optional CPS URIs or user notices attached to this policy. */\n\treadonly policyQualifiers?: readonly PolicyQualifierInfo[];\n}\n\n/** RFC 5280 §4.2.1.4 — array of policy OIDs with optional qualifiers. */\nexport type CertificatePolicies = readonly {\n\t/** Dotted-decimal OID of the policy (e.g. `\"2.23.140.1.2.1\"` for DV). */\n\treadonly policyIdentifier: string;\n\t/** Optional CPS URIs or user notices attached to this policy. */\n\treadonly policyQualifiers?: readonly (\n\t\t| {\n\t\t\t\treadonly type: 'cps';\n\t\t\t\treadonly uri: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'userNotice';\n\t\t\t\treadonly noticeRef?: {\n\t\t\t\t\treadonly organization: string;\n\t\t\t\t\treadonly noticeNumbers: readonly number[];\n\t\t\t\t};\n\t\t\t\treadonly explicitText?: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'oid';\n\t\t\t\treadonly oid: string;\n\t\t\t\treadonly qualifierDer: Uint8Array;\n\t\t }\n\t)[];\n}[];\n\n/** CPS (Certification Practice Statement) URI policy qualifier. */\nexport interface CpsPolicyQualifierInfo {\n\t/** Discriminant for the `'cps'` qualifier variant. */\n\treadonly type: 'cps';\n\t/** URL of the Certification Practice Statement document. */\n\treadonly uri: string;\n}\n\n/** Reference to a numbered notice within an organization's practice statement. */\nexport interface PolicyNoticeReference {\n\t/** Organization name that published the notice. */\n\treadonly organization: string;\n\t/** One-based notice numbers within that organization's documentation. */\n\treadonly noticeNumbers: readonly number[];\n}\n\n/** UserNotice policy qualifier — human-readable notice text and/or a notice reference. */\nexport interface UserNoticePolicyQualifierInfo {\n\t/** Discriminant for the `'userNotice'` qualifier variant. */\n\treadonly type: 'userNotice';\n\t/** Pointer to a numbered notice in an organization's practice statement. */\n\treadonly noticeRef?: PolicyNoticeReference;\n\t/** Free-form text to display to relying parties. */\n\treadonly explicitText?: string;\n}\n\n/** Opaque policy qualifier identified by a custom OID, carried as raw DER. */\nexport interface CustomPolicyQualifierInfo {\n\t/** Discriminant for the custom-OID qualifier variant. */\n\treadonly type: 'oid';\n\t/** Dotted-decimal OID of the qualifier. */\n\treadonly oid: string;\n\t/** DER-encoded qualifier payload. */\n\treadonly qualifierDer: Uint8Array;\n}\n\n/** Discriminated union of all supported policy qualifier types. */\nexport type PolicyQualifierInfo =\n\t| CpsPolicyQualifierInfo\n\t| UserNoticePolicyQualifierInfo\n\t| CustomPolicyQualifierInfo;\n\n/** Maps a policy OID in the issuer's domain to an equivalent OID in the subject's domain. */\nexport interface PolicyMapping {\n\t/** Policy OID as defined by the issuing CA. Must not be anyPolicy. */\n\treadonly issuerDomainPolicy: string;\n\t/** Equivalent policy OID in the subject CA's domain. Must not be anyPolicy. */\n\treadonly subjectDomainPolicy: string;\n}\n\n/** RFC 5280 §4.2.1.5 — array of issuer-to-subject policy OID pairs. */\nexport type PolicyMappings = readonly {\n\t/** Policy OID as defined by the issuing CA. Must not be anyPolicy. */\n\treadonly issuerDomainPolicy: string;\n\t/** Equivalent policy OID in the subject CA's domain. Must not be anyPolicy. */\n\treadonly subjectDomainPolicy: string;\n}[];\n\n/**\n * RFC 5280 §4.2.1.11 Policy Constraints.\n *\n * At least one field must be present. Values are certificate-count\n * thresholds measured from the current certificate toward the end entity.\n */\nexport interface PolicyConstraints {\n\t/** After this many certificates, an acceptable policy must be in the path. */\n\treadonly requireExplicitPolicy?: number;\n\t/** After this many certificates, policy mapping is no longer allowed. */\n\treadonly inhibitPolicyMapping?: number;\n}\n\n/**\n * RFC 5280 §4.2.1.14 Inhibit anyPolicy.\n *\n * After `skipCerts` additional non-self-issued certificates in the path, the\n * special anyPolicy OID is no longer considered a match, except when it\n * appears in an intermediate self-issued CA certificate.\n */\nexport interface InhibitAnyPolicy {\n\t/** Number of additional non-self-issued certificates before anyPolicy stops being valid. */\n\treadonly skipCerts: number;\n}\n\n/**\n * Input for `createCertificate`, `createSelfSignedCertificate`,\n * and `createCertificateSigningRequest`.\n *\n * Every field is optional. Omitted extensions are not encoded. Built-in\n * extensions (SKI, AKI, basicConstraints defaults) are handled automatically\n * by the builder.\n */\nexport interface CertificateExtensionsInput {\n\t/** Subject Alternative Names (dns, ip, email, uri, srv, directoryName). */\n\treadonly subjectAltNames?: readonly SubjectAltName[];\n\t/** Key Usage flags (digitalSignature, keyCertSign, etc.). */\n\treadonly keyUsage?: readonly KeyUsage[];\n\t/** Basic Constraints (CA flag + optional pathLength). Defaults to `{ ca: false }` for certs. */\n\treadonly basicConstraints?: BasicConstraints;\n\t/** Extended Key Usage purposes (serverAuth, clientAuth, etc.). */\n\treadonly extendedKeyUsage?: readonly ExtendedKeyUsage[];\n\t/** Name Constraints — permitted and/or excluded subtrees. */\n\treadonly nameConstraints?: NameConstraints;\n\t/** Certificate Policies with optional qualifiers. */\n\treadonly certificatePolicies?: CertificatePolicies;\n\t/** Policy Mappings between issuer and subject policy domains. */\n\treadonly policyMappings?: PolicyMappings;\n\t/** Policy Constraints (requireExplicitPolicy / inhibitPolicyMapping thresholds). */\n\treadonly policyConstraints?: PolicyConstraints;\n\t/** Inhibit anyPolicy skip-certs threshold. */\n\treadonly inhibitAnyPolicy?: InhibitAnyPolicy;\n\t/** Authority Information Access — OCSP responder and CA issuer locations. */\n\treadonly authorityInfoAccess?: readonly AuthorityInformationAccessInput[];\n\t/** CRL Distribution Points — where to check revocation status. */\n\treadonly crlDistributionPoints?: readonly DistributionPoint[];\n\t/** Arbitrary extensions not covered by the built-in fields. */\n\treadonly customExtensions?: readonly CustomExtension[];\n}\n\n/** An extension not covered by the typed fields in {@linkcode CertificateExtensionsInput}. */\nexport interface CustomExtension {\n\t/** Dotted-decimal OID of the extension. */\n\treadonly oid: string;\n\t/** Pre-encoded DER content for the extnValue OCTET STRING. */\n\treadonly value: Uint8Array;\n\t/** Whether the extension is critical. Default `false`. */\n\treadonly critical?: boolean;\n}\n\n// Name constraints (RFC 5280 §4.2.1.10)\n\n/**\n * A name form used as a constraint base in namEConstraints.\n * Distinct from {@linkcode SubjectAltName} because IP constraints carry\n * address + mask bytes (8 for IPv4, 32 for IPv6) rather than bare addresses.\n */\nexport type NameConstraintForm =\n\t| {\n\t\t\t/** DNS domain constraint (dNSName [2]). */\n\t\t\treadonly type: 'dns';\n\t\t\t/** Domain suffix, e.g. `\".example.com\"` or `\"example.com\"`. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** Email constraint (rfc822Name [1]). */\n\t\t\treadonly type: 'email';\n\t\t\t/** Email domain or full address pattern. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** URI constraint (uniformResourceIdentifier [6]). */\n\t\t\treadonly type: 'uri';\n\t\t\t/** Host or domain component of a URI. */\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\t/** IP range constraint (iPAddress [7]). */\n\t\t\treadonly type: 'ip';\n\t\t\t/** Network address bytes (4 for IPv4, 16 for IPv6). */\n\t\t\treadonly addressBytes: Uint8Array;\n\t\t\t/** Subnet mask bytes (same length as addressBytes). */\n\t\t\treadonly maskBytes: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Directory name constraint (directoryName [4]). */\n\t\t\treadonly type: 'directoryName';\n\t\t\t/** Hex-encoded DER of the Name SEQUENCE. */\n\t\t\treadonly derHex: string;\n\t };\n\n/**\n * Name constraint forms parsed from DER but not supported for encoding or\n * validation. Preserved for diagnostic round-tripping.\n */\nexport type UnsupportedNameConstraintForm =\n\t| {\n\t\t\t/** otherName [0] — raw bytes. */\n\t\t\treadonly type: 'otherName';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\t/** x400Address [3] — raw bytes. */\n\t\t\treadonly type: 'x400Address';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\t/** ediPartyName [5] — raw bytes. */\n\t\t\treadonly type: 'ediPartyName';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\t/** registeredID [8] — decoded OID string. */\n\t\t\treadonly type: 'registeredID';\n\t\t\treadonly value: string;\n\t };\n\n/** Union of supported and unsupported name constraint forms as produced by parsing. */\nexport type ParsedNameConstraintForm =\n\t| {\n\t\t\treadonly type: 'dns';\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\treadonly type: 'email';\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\treadonly type: 'uri';\n\t\t\treadonly value: string;\n\t }\n\t| {\n\t\t\treadonly type: 'ip';\n\t\t\treadonly addressBytes: Uint8Array;\n\t\t\treadonly maskBytes: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly type: 'directoryName';\n\t\t\treadonly derHex: string;\n\t }\n\t| {\n\t\t\treadonly type: 'otherName';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly type: 'x400Address';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly type: 'ediPartyName';\n\t\t\treadonly value: Uint8Array;\n\t }\n\t| {\n\t\t\treadonly type: 'registeredID';\n\t\t\treadonly value: string;\n\t };\n\n/** A single subtree entry in a Name Constraints permitted/excluded list. */\nexport interface GeneralSubtree<\n\tTForm extends ParsedNameConstraintForm =\n\t\t| {\n\t\t\t\treadonly type: 'dns';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'email';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'uri';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'ip';\n\t\t\t\treadonly addressBytes: Uint8Array;\n\t\t\t\treadonly maskBytes: Uint8Array;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'directoryName';\n\t\t\t\treadonly derHex: string;\n\t\t },\n> {\n\t/** The name form that defines this constraint boundary. */\n\treadonly base: TForm;\n}\n\n/**\n * RFC 5280 §4.2.1.10 Name Constraints.\n *\n * A CA certificate may restrict the namespace of all subject names in\n * subsequent certificates in the path.\n */\nexport interface NameConstraints<\n\tTForm extends ParsedNameConstraintForm =\n\t\t| {\n\t\t\t\treadonly type: 'dns';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'email';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'uri';\n\t\t\t\treadonly value: string;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'ip';\n\t\t\t\treadonly addressBytes: Uint8Array;\n\t\t\t\treadonly maskBytes: Uint8Array;\n\t\t }\n\t\t| {\n\t\t\t\treadonly type: 'directoryName';\n\t\t\t\treadonly derHex: string;\n\t\t },\n> {\n\t/** Names that MUST fall within these subtrees to be valid. */\n\treadonly permittedSubtrees?: readonly GeneralSubtree<TForm>[];\n\t/** Names that MUST NOT fall within these subtrees. Takes precedence over permitted. */\n\treadonly excludedSubtrees?: readonly GeneralSubtree<TForm>[];\n}\n\n/** Well-known AIA access methods: OCSP responder or CA issuer certificate. */\nexport type KnownAuthorityInfoAccessMethod = 'ocsp' | 'caIssuers';\n\n/** AIA access method identified by a custom OID not in the well-known set. */\nexport interface CustomAuthorityInfoAccessMethod {\n\t/** Discriminant for the custom-OID access method variant. */\n\treadonly type: 'oid';\n\t/** Dotted-decimal OID of the access method. */\n\treadonly value: string;\n}\n\n/** AIA access method — either a well-known string or a custom OID. */\nexport type AuthorityInfoAccessMethod =\n\t| KnownAuthorityInfoAccessMethod\n\t| CustomAuthorityInfoAccessMethod;\n\n/** A single entry in the Authority Information Access extension (RFC 5280 §4.2.2.1). */\nexport interface AuthorityInformationAccess {\n\t/** Access method (`'ocsp'`, `'caIssuers'`, or custom OID). */\n\treadonly method:\n\t\t| 'ocsp'\n\t\t| 'caIssuers'\n\t\t| {\n\t\t\t\treadonly type: 'oid';\n\t\t\t\treadonly value: string;\n\t\t };\n\t/** accessLocation GeneralName where the resource is available (usually a URI). */\n\treadonly location: GeneralName;\n}\n\n/**\n * Builder input for one Authority Information Access entry.\n *\n * Parsed AIA locations stay broad ({@linkcode AuthorityInformationAccess}), but\n * an `'ocsp'` entry must supply a URI location, since RFC 6960 §3.1 defines the\n * `id-ad-ocsp` location as a URI; `directoryName` is defined for `caIssuers`.\n */\nexport type AuthorityInformationAccessInput =\n\t| {\n\t\t\t/** OCSP responder access method. */\n\t\t\treadonly method: 'ocsp';\n\t\t\t/** OCSP responder URI (RFC 6960 §3.1). */\n\t\t\treadonly location: { readonly type: 'uri'; readonly value: string };\n\t }\n\t| {\n\t\t\t/** caIssuers or a custom access method. */\n\t\t\treadonly method: 'caIssuers' | CustomAuthorityInfoAccessMethod;\n\t\t\t/** Any accessLocation GeneralName. */\n\t\t\treadonly location: GeneralName;\n\t };\n\n/** Well-known Extended Key Usage purpose strings (RFC 5280 §4.2.1.12). */\nexport type KnownExtendedKeyUsage =\n\t| 'serverAuth'\n\t| 'clientAuth'\n\t| 'codeSigning'\n\t| 'emailProtection'\n\t| 'timeStamping'\n\t| 'ocspSigning';\n\n/** Extended Key Usage purpose identified by a custom OID. */\nexport interface CustomExtendedKeyUsage {\n\t/** Discriminant for the custom-OID EKU variant. */\n\treadonly type: 'oid';\n\t/** Dotted-decimal OID of the usage purpose. */\n\treadonly value: string;\n}\n\n/** Extended Key Usage — either a well-known purpose string or a custom OID. */\nexport type ExtendedKeyUsage =\n\t| 'serverAuth'\n\t| 'clientAuth'\n\t| 'codeSigning'\n\t| 'emailProtection'\n\t| 'timeStamping'\n\t| 'ocspSigning'\n\t| {\n\t\t\treadonly type: 'oid';\n\t\t\treadonly value: string;\n\t };\n\n/** Map from well-known EKU names to their dotted-decimal OIDs. */\nconst EXTENDED_KEY_USAGE_OIDS: Record<KnownExtendedKeyUsage, string> = {\n\tserverAuth: OIDS.serverAuth,\n\tclientAuth: OIDS.clientAuth,\n\tcodeSigning: OIDS.codeSigning,\n\temailProtection: OIDS.emailProtection,\n\ttimeStamping: OIDS.timeStamping,\n\tocspSigning: OIDS.ocspSigning,\n};\n\n/** Map from well-known AIA method names to their dotted-decimal OIDs. */\nconst AUTHORITY_INFO_ACCESS_METHOD_OIDS: Record<KnownAuthorityInfoAccessMethod, string> = {\n\tocsp: OIDS.ocspAccessMethod,\n\tcaIssuers: OIDS.caIssuersAccessMethod,\n};\n\n/**\n * Build the v3 extensions block for a certificate.\n *\n * Automatically adds SKI, AKI (when issuer key is available), and\n * basicConstraints (defaults to `{ ca: false }`). Additional extensions\n * come from the caller's {@linkcode CertificateExtensionsInput}.\n *\n * @param subjectPublicKeyInfo DER-encoded SPKI of the subject.\n * @param issuerPublicKeyInfo DER-encoded SPKI of the issuer, or `undefined` for self-signed.\n * @param input Optional extension configuration.\n * @param subjectIsEmpty Whether the certificate subject DN is empty. When `true`, a\n * subjectAltName extension is required and marked critical per RFC 5280 §4.2.1.6.\n * @returns Array of DER-encoded Extension SEQUENCEs.\n */\nexport function buildCertificateExtensions(\n\tsubjectPublicKeyInfo: Uint8Array,\n\tissuerPublicKeyInfo: Uint8Array | undefined,\n\tinput: CertificateExtensionsInput | undefined,\n\tsubjectIsEmpty = false,\n): Uint8Array[] {\n\tassertCustomExtensionsValid(input, 'certificate');\n\tif (subjectIsEmpty) {\n\t\tassertEmptySubjectHasCriticalSubjectAltName(input);\n\t}\n\tassertPathLengthKeyUsage(input);\n\tassertSafeCurveKeyUsage(subjectPublicKeyInfo, input);\n\tconst extensions: Uint8Array[] = [];\n\tconst seen = new Set<string>();\n\tconst basicConstraints = input?.basicConstraints ?? { ca: false };\n\tpushKnownExtension(extensions, seen, BASIC_CONSTRAINTS_EXTENSION_DEFINITION, basicConstraints);\n\tpushKnownExtension(\n\t\textensions,\n\t\tseen,\n\t\tSUBJECT_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n\t\tbuildSubjectKeyIdentifier(subjectPublicKeyInfo),\n\t);\n\tif (issuerPublicKeyInfo !== undefined) {\n\t\tpushKnownExtension(\n\t\t\textensions,\n\t\t\tseen,\n\t\t\tAUTHORITY_KEY_IDENTIFIER_EXTENSION_DEFINITION,\n\t\t\tbuildSubjectKeyIdentifier(issuerPublicKeyInfo),\n\t\t);\n\t}\n\tappendConfiguredExtensions(extensions, seen, input, {\n\t\tincludeBasicConstraints: false,\n\t\tsubjectIsEmpty,\n\t});\n\treturn extensions;\n}\n\n/**\n * Build the extensions for a CSR's extensionRequest attribute.\n *\n * Unlike {@linkcode buildCertificateExtensions}, SKI/AKI are not auto-generated.\n *\n * @param input Optional extension configuration.\n * @returns Array of DER-encoded Extension SEQUENCEs.\n */\nexport function buildRequestedExtensions(\n\tinput: CertificateExtensionsInput | undefined,\n): Uint8Array[] {\n\tassertCustomExtensionsValid(input, 'csr');\n\tconst extensions: Uint8Array[] = [];\n\tconst seen = new Set<string>();\n\tappendConfiguredExtensions(extensions, seen, input, { includeBasicConstraints: true });\n\treturn extensions;\n}\n\n/** Encode and push each configured extension from the input, enforcing no duplicates. */\nfunction appendConfiguredExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput | undefined,\n\toptions: {\n\t\treadonly includeBasicConstraints: boolean;\n\t\t/** When true, SAN is marked critical per RFC 5280 §4.2.1.6. */\n\t\treadonly subjectIsEmpty?: boolean;\n\t},\n): void {\n\tif (input === undefined) {\n\t\treturn;\n\t}\n\tappendConstraintExtensions(encoded, seen, input, options.includeBasicConstraints);\n\tappendIdentityExtensions(encoded, seen, input, options.subjectIsEmpty === true);\n\tappendPolicyExtensions(encoded, seen, input);\n\tappendAccessExtensions(encoded, seen, input);\n\tappendCustomExtensions(encoded, seen, input);\n}\n\n/**\n * RFC 5280 §4.2.1.9: pathLenConstraint requires the keyUsage extension to assert keyCertSign.\n * Absent, empty, or keyCertSign-less keyUsage is rejected. Known extensions supplied through\n * customExtensions participate in the effective view.\n */\nfunction assertPathLengthKeyUsage(input: CertificateExtensionsInput | undefined): void {\n\tconst basicConstraints = resolveEffectiveBasicConstraints(input);\n\tif (basicConstraints?.pathLength === undefined) {\n\t\treturn;\n\t}\n\tconst keyUsage = resolveEffectiveKeyUsage(input);\n\tif (keyUsage === undefined || keyUsage.length === 0 || !keyUsage.includes('keyCertSign')) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'path_length_requires_key_cert_sign',\n\t\t\t'basicConstraints pathLength requires the keyUsage keyCertSign bit',\n\t\t);\n\t}\n}\n\n/** RFC 9295 §3: an end-entity id-Ed25519 or id-Ed448 certificate needs one of these. */\nconst EDWARDS_END_ENTITY_KEY_USAGE = ['nonRepudiation', 'digitalSignature', 'cRLSign'] as const;\n\n/** RFC 9295 §3: bits an id-Ed25519 or id-Ed448 certificate must never assert. */\nconst EDWARDS_FORBIDDEN_KEY_USAGE = [\n\t'keyEncipherment',\n\t'dataEncipherment',\n\t'keyAgreement',\n\t'encipherOnly',\n\t'decipherOnly',\n] as const;\n\n/** RFC 9295 §3: bits an id-X25519 or id-X448 certificate must never assert. */\nconst MONTGOMERY_FORBIDDEN_KEY_USAGE = [\n\t'digitalSignature',\n\t'nonRepudiation',\n\t'keyEncipherment',\n\t'dataEncipherment',\n\t'keyCertSign',\n\t'cRLSign',\n] as const;\n\n/**\n * RFC 9295 §3, which replaces RFC 8410 §5, constrains a keyUsage extension on a\n * certificate whose subject key names one of the four 1.3.101 curves.\n *\n * id-X25519 and id-X448 require `keyAgreement`, admit one of `encipherOnly` and\n * `decipherOnly`, and forbid the rest.\n *\n * id-Ed25519 and id-Ed448 split on whether the certificate is a certification\n * authority. A CA MUST assert `keyCertSign` and MAY add `nonRepudiation`,\n * `digitalSignature`, or `cRLSign`. Any other certificate MUST assert at least\n * one of those three and MUST NOT assert `keyCertSign`. Both forbid the key\n * agreement and encipherment bits. A CRL issuer is the case where `cRLSign` is\n * the bit chosen, and a CRL issuer that is also a CA is the CA case, so the two\n * branches cover the section's four paragraphs.\n *\n * The rule binds only a keyUsage that reaches the wire, so an absent one, and an\n * empty one the builder therefore omits, leave the key unconstrained.\n */\nfunction assertSafeCurveKeyUsage(\n\tsubjectPublicKeyInfo: Uint8Array,\n\tinput: CertificateExtensionsInput | undefined,\n): void {\n\tconst keyUsage = resolveEffectiveKeyUsage(input);\n\tif (keyUsage === undefined || keyUsage.length === 0) {\n\t\treturn;\n\t}\n\tconst algorithm = readSubjectKeyAlgorithmOid(subjectPublicKeyInfo);\n\tif (algorithm === undefined) {\n\t\treturn;\n\t}\n\tif (oidEquals(algorithm, OIDS.x25519) || oidEquals(algorithm, OIDS.x448)) {\n\t\tassertMontgomeryKeyUsage(keyUsage);\n\t\treturn;\n\t}\n\tif (oidEquals(algorithm, OIDS.ed25519) || oidEquals(algorithm, OIDS.ed448)) {\n\t\tassertEdwardsKeyUsage(keyUsage, resolveEffectiveBasicConstraints(input)?.ca === true);\n\t}\n}\n\n/** The X25519 and X448 half of RFC 9295 §3. */\nfunction assertMontgomeryKeyUsage(keyUsage: readonly KeyUsage[]): void {\n\tif (!keyUsage.includes('keyAgreement')) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'montgomery_key_usage_requires_key_agreement',\n\t\t\t'keyUsage on an X25519 or X448 certificate must set keyAgreement',\n\t\t);\n\t}\n\tconst asserted = MONTGOMERY_FORBIDDEN_KEY_USAGE.filter((flag: KeyUsage) =>\n\t\tkeyUsage.includes(flag),\n\t);\n\tif (asserted.length > 0) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'montgomery_key_usage_forbids_signature_bit',\n\t\t\t`keyUsage on an X25519 or X448 certificate must not set ${asserted.join(', ')}`,\n\t\t);\n\t}\n\tif (keyUsage.includes('encipherOnly') && keyUsage.includes('decipherOnly')) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'montgomery_key_usage_forbids_both_cipher_bits',\n\t\t\t'keyUsage on an X25519 or X448 certificate must not set both encipherOnly and decipherOnly',\n\t\t);\n\t}\n}\n\n/** The Ed25519 and Ed448 half of RFC 9295 §3. */\nfunction assertEdwardsKeyUsage(\n\tkeyUsage: readonly KeyUsage[],\n\tisCertificationAuthority: boolean,\n): void {\n\tif (isCertificationAuthority) {\n\t\tif (!keyUsage.includes('keyCertSign')) {\n\t\t\tthrowExtensionEncoderError(\n\t\t\t\t'edwards_key_usage_requires_key_cert_sign',\n\t\t\t\t'keyUsage on an Ed25519 or Ed448 certification authority certificate must set keyCertSign',\n\t\t\t);\n\t\t}\n\t} else if (!EDWARDS_END_ENTITY_KEY_USAGE.some((flag: KeyUsage) => keyUsage.includes(flag))) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'edwards_key_usage_requires_signing_bit',\n\t\t\t`keyUsage on an Ed25519 or Ed448 certificate must set one of ${EDWARDS_END_ENTITY_KEY_USAGE.join(', ')}`,\n\t\t);\n\t}\n\tconst asserted = EDWARDS_FORBIDDEN_KEY_USAGE.filter((flag: KeyUsage) => keyUsage.includes(flag));\n\tif (asserted.length > 0) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'edwards_key_usage_forbids_agreement_bit',\n\t\t\t`keyUsage on an Ed25519 or Ed448 certificate must not set ${asserted.join(', ')}`,\n\t\t);\n\t}\n\tif (!isCertificationAuthority && keyUsage.includes('keyCertSign')) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'edwards_key_usage_forbids_key_cert_sign',\n\t\t\t'keyUsage on an Ed25519 or Ed448 end-entity certificate must not set keyCertSign',\n\t\t);\n\t}\n}\n\n/** The algorithm OID of a SubjectPublicKeyInfo, or `undefined` when the field is not an OID. */\nfunction readSubjectKeyAlgorithmOid(subjectPublicKeyInfo: Uint8Array): string | undefined {\n\tconst algorithm = readSequenceChildren(subjectPublicKeyInfo)[0];\n\tif (algorithm === undefined || algorithm.tag !== 0x30) {\n\t\treturn undefined;\n\t}\n\tconst oid = childrenOf(subjectPublicKeyInfo, algorithm)[0];\n\treturn oid?.tag === 0x06 ? decodeObjectIdentifier(oid.value) : undefined;\n}\n\n/**\n * RFC 5280 §4.2.1.9: basicConstraints is critical in a CA certificate whose key\n * validates signatures on certificates. Both conjuncts live in other extensions,\n * so the rule sits here rather than in the basicConstraints profile hook.\n *\n * §4.2.1.3 restricts a key only through a keyUsage extension that reaches the\n * wire, so an absent keyUsage, and an empty one the builder therefore omits,\n * leave the key free to validate certificate signatures. Only an emitted keyUsage\n * without keyCertSign takes the certificate out of the clause's scope.\n *\n * Only a custom extension can carry the wrong criticality; the typed field is\n * always emitted with the registry default.\n */\nfunction assertCaBasicConstraintsCritical(input: CertificateExtensionsInput | undefined): void {\n\tconst custom = input?.customExtensions?.find((extension) =>\n\t\toidEquals(extension.oid, OIDS.basicConstraints),\n\t);\n\tif (custom === undefined || custom.critical === true) {\n\t\treturn;\n\t}\n\tconst basicConstraints = BASIC_CONSTRAINTS_EXTENSION_DEFINITION.decode(\n\t\tnew Uint8Array(custom.value),\n\t);\n\tif (!basicConstraints.ca) {\n\t\treturn;\n\t}\n\tconst keyUsage = resolveEffectiveKeyUsage(input);\n\tconst mayValidateCertificates =\n\t\tkeyUsage === undefined || keyUsage.length === 0 || keyUsage.includes('keyCertSign');\n\tif (mayValidateCertificates) {\n\t\tassertExtensionCriticality('basicConstraints', true, false);\n\t}\n}\n\n/**\n * RFC 5280 §4.2.1.6: an empty subject DN requires a subjectAltName extension\n * present, marked critical, and carrying at least one non-empty GeneralName.\n */\nfunction assertEmptySubjectHasCriticalSubjectAltName(\n\tinput: CertificateExtensionsInput | undefined,\n): void {\n\tif (input?.subjectAltNames?.some(subjectAltNameHasIdentity) === true) {\n\t\treturn;\n\t}\n\tconst criticalCustomSan = input?.customExtensions?.some(\n\t\t(extension) =>\n\t\t\toidEquals(extension.oid, OIDS.subjectAltName) &&\n\t\t\textension.critical === true &&\n\t\t\tcustomSubjectAltNameHasIdentity(extension.value),\n\t);\n\tif (criticalCustomSan === true) {\n\t\treturn;\n\t}\n\tthrowExtensionEncoderError(\n\t\t'empty_subject_requires_subject_alt_name',\n\t\t'An empty subject requires a critical subjectAltName extension',\n\t);\n}\n\n/**\n * Canonical OID equality: matches even when arcs carry redundant leading zeros.\n *\n * Both sides must be encodable. Callers run after `assertCustomExtensionsValid`,\n * which rejects an OID that cannot be canonicalized.\n */\nfunction oidEquals(candidate: string, known: string): boolean {\n\treturn candidate === known || canonicalizeOid(candidate) === canonicalizeOid(known);\n}\n\n/** First customExtensions value whose OID canonically matches `oid`. */\nfunction findCustomExtensionValue(\n\tinput: CertificateExtensionsInput | undefined,\n\toid: string,\n): Uint8Array | undefined {\n\treturn input?.customExtensions?.find((extension) => oidEquals(extension.oid, oid))?.value;\n}\n\n/** The subset of a DistributionPointName the RFC 5280 §4.2.1.13 rules read. */\ntype ProfileDistributionPointName<TRelativeName> =\n\t| { readonly type: 'fullName'; readonly fullName: readonly GeneralName[] }\n\t| { readonly type: 'relativeName'; readonly relativeName: TRelativeName };\n\n/** The subset of a distribution point the RFC 5280 §4.2.1.13 rules read. */\ninterface ProfileDistributionPoint<TRelativeName> {\n\t/** Where to fetch the CRL. */\n\treadonly distributionPoint?: ProfileDistributionPointName<TRelativeName>;\n\t/** Entity that signed the CRL, when different from the certificate issuer. */\n\treadonly crlIssuer?: readonly GeneralName[];\n}\n\n/**\n * Rejects a custom extension carrying a known OID whose payload is not the DER\n * that OID's schema defines, and a known extension offered in the wrong context.\n *\n * Runs before every cross-field guard so the effective-value resolvers below can\n * decode a custom payload without having to tolerate failure.\n */\nfunction assertCustomExtensionsValid(\n\tinput: CertificateExtensionsInput | undefined,\n\tcontext: ExtensionRegistryContext,\n): void {\n\tfor (const extension of input?.customExtensions ?? []) {\n\t\tconst oid = validateOid(extension.oid);\n\t\tconst definition = getExtensionDefinition(oid);\n\t\tif (definition === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!definition.contexts.includes(context)) {\n\t\t\tthrowExtensionEncoderError(\n\t\t\t\t'extension_not_supported_in_context',\n\t\t\t\t`Extension ${extension.oid} is not supported in ${context} context`,\n\t\t\t);\n\t\t}\n\t\tassertKnownExtensionPayload(\n\t\t\tdefinition,\n\t\t\tnew Uint8Array(extension.value),\n\t\t\textension.critical ?? false,\n\t\t\textension.oid,\n\t\t);\n\t}\n}\n\n/**\n * Decode a custom payload once through its known OID's definition and apply that\n * extension's profile rules to the decoded value and its criticality.\n *\n * A profile violation already carries its own code and propagates unchanged; a\n * decode failure means the payload is not the DER the OID's schema defines.\n */\nfunction assertKnownExtensionPayload(\n\tdefinition: {\n\t\treadonly oid: string;\n\t\tassertDerProfile(valueDer: Uint8Array, critical: boolean): void;\n\t},\n\tvalue: Uint8Array,\n\tcritical: boolean,\n\tsubmittedOid: string,\n): void {\n\ttry {\n\t\tdefinition.assertDerProfile(value, critical);\n\t} catch (error) {\n\t\tif (isResultError(error)) {\n\t\t\tthrow error;\n\t\t}\n\t\tthrowExtensionEncoderError(\n\t\t\t'malformed_known_extension_value',\n\t\t\t`Custom extension ${submittedOid} does not decode as ${definition.oid}`,\n\t\t);\n\t}\n}\n\n/** Effective basicConstraints across the typed field and any custom-known extension. */\nfunction resolveEffectiveBasicConstraints(\n\tinput: CertificateExtensionsInput | undefined,\n): BasicConstraints | undefined {\n\tif (input?.basicConstraints !== undefined) {\n\t\treturn input.basicConstraints;\n\t}\n\tconst custom = findCustomExtensionValue(input, OIDS.basicConstraints);\n\treturn custom === undefined ? undefined : BASIC_CONSTRAINTS_EXTENSION_DEFINITION.decode(custom);\n}\n\n/** Effective keyUsage flags across the typed field and any custom-known extension. */\nfunction resolveEffectiveKeyUsage(\n\tinput: CertificateExtensionsInput | undefined,\n): readonly KeyUsage[] | undefined {\n\tif (input?.keyUsage !== undefined) {\n\t\treturn input.keyUsage;\n\t}\n\tconst custom = findCustomExtensionValue(input, OIDS.keyUsage);\n\treturn custom === undefined ? undefined : KEY_USAGE_EXTENSION_DEFINITION.decode(custom).flags;\n}\n\n/** Whether a typed GeneralName carries a non-empty identity value. */\nfunction subjectAltNameHasIdentity(name: SubjectAltName): boolean {\n\treturn name.type === 'directoryName' ? name.derHex.length > 0 : name.value.length > 0;\n}\n\n/** Whether a custom subjectAltName value decodes to at least one non-empty GeneralName. */\nfunction customSubjectAltNameHasIdentity(value: Uint8Array): boolean {\n\treturn SUBJECT_ALT_NAME_EXTENSION_DEFINITION.decode(value).some(subjectAltNameHasIdentity);\n}\n\nfunction appendConstraintExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput,\n\tincludeBasicConstraints: boolean,\n): void {\n\tassertPathLengthKeyUsage(input);\n\tassertCaBasicConstraintsCritical(input);\n\tif (includeBasicConstraints && input.basicConstraints !== undefined) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tBASIC_CONSTRAINTS_EXTENSION_DEFINITION,\n\t\t\tinput.basicConstraints,\n\t\t);\n\t}\n\tif (input.keyUsage !== undefined && input.keyUsage.length > 0) {\n\t\tpushKnownExtension(encoded, seen, KEY_USAGE_EXTENSION_DEFINITION, input.keyUsage);\n\t}\n\tif (input.nameConstraints !== undefined) {\n\t\tpushKnownExtension(encoded, seen, NAME_CONSTRAINTS_EXTENSION_DEFINITION, input.nameConstraints);\n\t}\n}\n\nfunction appendIdentityExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput,\n\tsubjectIsEmpty: boolean,\n): void {\n\tif (input.subjectAltNames !== undefined && input.subjectAltNames.length > 0) {\n\t\t// RFC 5280 §4.2.1.6: SAN MUST be critical when subject DN is empty.\n\t\tconst sanCritical = subjectIsEmpty ? true : undefined;\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tSUBJECT_ALT_NAME_EXTENSION_DEFINITION,\n\t\t\tinput.subjectAltNames,\n\t\t\tsanCritical,\n\t\t);\n\t}\n\tif (input.extendedKeyUsage !== undefined && input.extendedKeyUsage.length > 0) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tEXTENDED_KEY_USAGE_EXTENSION_DEFINITION,\n\t\t\tinput.extendedKeyUsage,\n\t\t);\n\t}\n}\n\n/** Appends configured certificate-policy extensions while enforcing unique OIDs. */\nfunction appendPolicyExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput,\n): void {\n\tif (input.certificatePolicies !== undefined && input.certificatePolicies.length > 0) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tCERTIFICATE_POLICIES_EXTENSION_DEFINITION,\n\t\t\tinput.certificatePolicies,\n\t\t);\n\t}\n\tif (input.policyMappings !== undefined && input.policyMappings.length > 0) {\n\t\tpushKnownExtension(encoded, seen, POLICY_MAPPINGS_EXTENSION_DEFINITION, input.policyMappings);\n\t}\n\tif (input.policyConstraints !== undefined) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tPOLICY_CONSTRAINTS_EXTENSION_DEFINITION,\n\t\t\tinput.policyConstraints,\n\t\t);\n\t}\n\tif (input.inhibitAnyPolicy !== undefined) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tINHIBIT_ANY_POLICY_EXTENSION_DEFINITION,\n\t\t\tinput.inhibitAnyPolicy,\n\t\t);\n\t}\n}\n\nfunction appendAccessExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput,\n): void {\n\tif (input.authorityInfoAccess !== undefined && input.authorityInfoAccess.length > 0) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tAUTHORITY_INFO_ACCESS_EXTENSION_DEFINITION,\n\t\t\tinput.authorityInfoAccess,\n\t\t);\n\t}\n\tif (input.crlDistributionPoints !== undefined && input.crlDistributionPoints.length > 0) {\n\t\tpushKnownExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\tCRL_DISTRIBUTION_POINTS_EXTENSION_DEFINITION,\n\t\t\tinput.crlDistributionPoints,\n\t\t);\n\t}\n}\n\n/** Push each custom extension. Context and payload were checked by `assertCustomExtensionsValid`. */\nfunction appendCustomExtensions(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tinput: CertificateExtensionsInput,\n): void {\n\tfor (const extension of input.customExtensions ?? []) {\n\t\tpushExtension(\n\t\t\tencoded,\n\t\t\tseen,\n\t\t\textension.oid,\n\t\t\tnew Uint8Array(extension.value),\n\t\t\textension.critical ?? false,\n\t\t);\n\t}\n}\n\n/** Encode a known extension via its registry definition and push it. */\nfunction pushKnownExtension<TParsed, TInput>(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\tdefinition: ExtensionDefinition<TParsed, TInput>,\n\tvalue: TInput,\n\tcritical = definition.defaultCritical,\n): void {\n\tpushExtension(encoded, seen, definition.oid, definition.encode(value), critical);\n}\n\n/**\n * Encode a single X.509 Extension SEQUENCE (OID + optional critical BOOLEAN + OCTET STRING).\n *\n * @param oid Dotted-decimal extension OID.\n * @param extnValue DER-encoded extension payload.\n * @param critical Whether to mark the extension as critical. Default `false`.\n */\nexport function encodeExtension(oid: string, extnValue: Uint8Array, critical = false): Uint8Array {\n\tvalidateOid(oid);\n\tconst fields = [objectIdentifier(oid)];\n\tif (critical) {\n\t\tfields.push(bool(true));\n\t}\n\tfields.push(octetString(extnValue));\n\treturn sequence(fields);\n}\n\n/**\n * DER-encode a {@linkcode BasicConstraints} value.\n *\n * @param input CA flag and optional pathLength.\n * @returns DER SEQUENCE suitable for wrapping in an Extension OCTET STRING.\n */\nexport function encodeBasicConstraints(input: BasicConstraints): Uint8Array {\n\tconst fields: Uint8Array[] = [];\n\tif (input.ca) {\n\t\tfields.push(bool(true));\n\t}\n\tif (input.pathLength !== undefined) {\n\t\tif (!input.ca) {\n\t\t\tthrowExtensionEncoderError(\n\t\t\t\t'path_length_requires_ca',\n\t\t\t\t'basicConstraints pathLength requires ca = true',\n\t\t\t);\n\t\t}\n\t\tfields.push(integerFromNumber(input.pathLength));\n\t}\n\treturn sequence(fields);\n}\n\n/**\n * DER-encode a Key Usage BIT STRING from an array of {@linkcode KeyUsage} flags.\n *\n * @param usages Flags to set in the bit string.\n */\nexport function encodeKeyUsage(usages: readonly KeyUsage[]): Uint8Array {\n\treturn encodeKeyUsageExtension(usages);\n}\n\nfunction encodeIa5Content(value: string): Uint8Array {\n\ttry {\n\t\treturn ia5Bytes(value);\n\t} catch {\n\t\tthrowExtensionEncoderError(\n\t\t\t'invalid_ia5_string',\n\t\t\t'Invalid IA5String: contains non-ASCII characters',\n\t\t);\n\t}\n}\n\n/** RFC 5280 §4.2.1.6: reject an empty GeneralName string value (empty dNSName, rfc822Name, URI, or SRV name). */\nfunction requireNonEmptyName(value: string): string {\n\tif (value.length === 0) {\n\t\tthrowExtensionEncoderError('empty_general_name_value', 'GeneralName value must not be empty');\n\t}\n\treturn value;\n}\n\n/**\n * DER-encode a single {@linkcode SubjectAltName} GeneralName element.\n *\n * @param value The SAN entry to encode.\n */\nexport function encodeSubjectAltName(value: SubjectAltName): Uint8Array {\n\tswitch (value.type) {\n\t\tcase 'dns':\n\t\t\treturn implicitPrimitiveContext(2, encodeIa5Content(requireNonEmptyName(value.value)));\n\t\tcase 'email':\n\t\t\treturn implicitPrimitiveContext(1, encodeIa5Content(requireNonEmptyName(value.value)));\n\t\tcase 'uri':\n\t\t\treturn implicitPrimitiveContext(6, encodeIa5Content(requireNonEmptyName(value.value)));\n\t\tcase 'srv':\n\t\t\treturn implicitConstructedContext(\n\t\t\t\t0,\n\t\t\t\tconcatBytes([\n\t\t\t\t\tobjectIdentifier(OIDS.idOnDnsSrv),\n\t\t\t\t\texplicitContext(0, tlv(0x16, encodeIa5Content(requireNonEmptyName(value.value)))),\n\t\t\t\t]),\n\t\t\t);\n\t\tcase 'ip':\n\t\t\treturn implicitPrimitiveContext(7, encodeIpAddress(value.value));\n\t\tcase 'directoryName':\n\t\t\treturn implicitConstructedContext(4, readDirectoryNameTlv(value.derHex));\n\t\tcase 'unknown':\n\t\t\tif (!GENERAL_NAME_WIRE_TAGS.has(value.tag)) {\n\t\t\t\tthrowExtensionEncoderError(\n\t\t\t\t\t'invalid_general_name_tag',\n\t\t\t\t\t`Invalid GeneralName tag: ${value.tag}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn tlv(value.tag, value.value);\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = value;\n\t\t\tthrow new Error(`Unhandled SubjectAltName type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * DER-encode an Extended Key Usage SEQUENCE OF OIDs.\n *\n * @param usages EKU purposes to encode.\n */\nexport function encodeExtendedKeyUsage(usages: readonly ExtendedKeyUsage[]): Uint8Array {\n\tif (usages.length === 0) {\n\t\tthrowExtensionEncoderError('extended_key_usage_empty', 'extendedKeyUsage must not be empty');\n\t}\n\treturn sequence(usages.map((usage) => objectIdentifier(getExtendedKeyUsageOid(usage))));\n}\n\n/**\n * DER-encode an Authority Information Access SEQUENCE.\n *\n * @param entries AIA entries (OCSP, caIssuers, or custom) to encode.\n */\nexport function encodeAuthorityInfoAccess(\n\tentries: readonly AuthorityInformationAccessInput[],\n): Uint8Array {\n\tassertAuthorityInfoAccessProfile(entries);\n\treturn sequence(\n\t\tentries.map((entry) =>\n\t\t\tsequence([\n\t\t\t\tobjectIdentifier(getAuthorityInfoAccessMethodOid(entry.method)),\n\t\t\t\tencodeSubjectAltName(entry.location),\n\t\t\t]),\n\t\t),\n\t);\n}\n\n/**\n * @internal RFC 5280 §4.2.2.1 and RFC 6960 §3.1 rules for Authority Information\n * Access: at least one entry, and an id-ad-ocsp location that is a URI.\n *\n * The method OID is resolved before the URI check so a custom-OID wrapper cannot\n * smuggle a non-URI OCSP location past the input union.\n */\nexport function assertAuthorityInfoAccessProfile(\n\tentries: readonly AuthorityInformationAccess[],\n): void {\n\tif (entries.length === 0) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'authority_info_access_empty',\n\t\t\t'authorityInfoAccess must not be empty',\n\t\t);\n\t}\n\tfor (const entry of entries) {\n\t\tconst methodOid = getAuthorityInfoAccessMethodOid(entry.method);\n\t\tif (methodOid === OIDS.ocspAccessMethod && entry.location.type !== 'uri') {\n\t\t\tthrowExtensionEncoderError(\n\t\t\t\t'authority_info_access_ocsp_not_uri',\n\t\t\t\t'authorityInfoAccess OCSP location must be a URI',\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * DER-encode a CRL Distribution Points SEQUENCE.\n *\n * @param points Distribution points to encode.\n */\nexport function encodeCrlDistributionPoints(points: readonly DistributionPoint[]): Uint8Array {\n\tassertCrlDistributionPointsProfile(points);\n\treturn sequence(points.map((point) => sequence(encodeDistributionPoint(point))));\n}\n\n/**\n * @internal RFC 5280 §4.2.1.13 profile rules for a CRLDistributionPoints value,\n * stated over the fields a typed {@linkcode DistributionPoint} and a decoded\n * `ParsedDistributionPoint` share.\n *\n * `TRelativeName` differs between the two: builder input carries an unencoded RDN,\n * a decoded point carries the parsed one. The rules only read its presence.\n */\nexport function assertCrlDistributionPointsProfile<TRelativeName>(\n\tpoints: readonly ProfileDistributionPoint<TRelativeName>[],\n): void {\n\tif (points.length === 0) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'crl_distribution_points_empty',\n\t\t\t'cRLDistributionPoints must not be empty',\n\t\t);\n\t}\n\tfor (const point of points) {\n\t\tassertDistributionPointProfile(point);\n\t}\n}\n\n/** RFC 5280 §4.2.1.13 rules for one distribution point. */\nfunction assertDistributionPointProfile<TRelativeName>(\n\tpoint: ProfileDistributionPoint<TRelativeName>,\n): void {\n\tif (point.crlIssuer !== undefined && point.crlIssuer.length === 0) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'distribution_point_crl_issuer_empty',\n\t\t\t'DistributionPoint crlIssuer must not be empty',\n\t\t);\n\t}\n\tif (point.distributionPoint === undefined && point.crlIssuer === undefined) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'distribution_point_empty',\n\t\t\t'DistributionPoint must contain distributionPoint or crlIssuer',\n\t\t);\n\t}\n\tassertCrlIssuerDistinguishedNames(point);\n\tif (\n\t\tpoint.distributionPoint?.type === 'fullName' &&\n\t\tpoint.distributionPoint.fullName.length === 0\n\t) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'distribution_point_full_name_empty',\n\t\t\t'DistributionPointName fullName must not be empty',\n\t\t);\n\t}\n}\n\n/**\n * DER-encode a Name Constraints extension value.\n *\n * @param constraints Permitted and/or excluded subtrees.\n */\nexport function encodeNameConstraints(constraints: NameConstraints): Uint8Array {\n\tassertNameConstraintsProfile(constraints);\n\tconst parts: Uint8Array[] = [];\n\tif (constraints.permittedSubtrees !== undefined && constraints.permittedSubtrees.length > 0) {\n\t\tparts.push(\n\t\t\timplicitConstructedContext(\n\t\t\t\t0,\n\t\t\t\tconcatBytes(constraints.permittedSubtrees.map(encodeGeneralSubtree)),\n\t\t\t),\n\t\t);\n\t}\n\tif (constraints.excludedSubtrees !== undefined && constraints.excludedSubtrees.length > 0) {\n\t\tparts.push(\n\t\t\timplicitConstructedContext(\n\t\t\t\t1,\n\t\t\t\tconcatBytes(constraints.excludedSubtrees.map(encodeGeneralSubtree)),\n\t\t\t),\n\t\t);\n\t}\n\treturn sequence(parts);\n}\n\n/**\n * @internal RFC 5280 fixes the criticality of several extensions: nameConstraints\n * (§4.2.1.10), policyConstraints (§4.2.1.11), and inhibitAnyPolicy (§4.2.1.14) are\n * critical; authorityKeyIdentifier (§4.2.1.1), subjectKeyIdentifier (§4.2.1.2),\n * and authorityInfoAccess (§4.2.2.1) are not.\n *\n * @param label Extension name quoted in the diagnostic.\n * @param required The criticality RFC 5280 mandates.\n * @param critical The criticality the caller asked for.\n */\nexport function assertExtensionCriticality(\n\tlabel: string,\n\trequired: boolean,\n\tcritical: boolean,\n): void {\n\tif (critical === required) {\n\t\treturn;\n\t}\n\tthrowExtensionEncoderError(\n\t\trequired ? 'extension_must_be_critical' : 'extension_must_be_non_critical',\n\t\t`The ${label} extension must be marked ${required ? 'critical' : 'non-critical'}`,\n\t);\n}\n\n/**\n * @internal RFC 5280 §4.2.1.10: a nameConstraints extension states at least one\n * of permittedSubtrees and excludedSubtrees, and neither may be an empty set.\n */\nexport function assertNameConstraintsProfile(constraints: {\n\treadonly permittedSubtrees?: readonly unknown[];\n\treadonly excludedSubtrees?: readonly unknown[];\n}): void {\n\tconst permitted = constraints.permittedSubtrees?.length ?? 0;\n\tconst excluded = constraints.excludedSubtrees?.length ?? 0;\n\tif (permitted === 0 && excluded === 0) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'name_constraints_empty',\n\t\t\t'nameConstraints must set permittedSubtrees or excludedSubtrees',\n\t\t);\n\t}\n}\n\n/**\n * DER-encode a Certificate Policies extension value.\n *\n * @param policies Non-empty array of policy information entries.\n */\nexport function encodeCertificatePolicies(policies: CertificatePolicies): Uint8Array {\n\tif (policies.length === 0) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'certificate_policies_empty',\n\t\t\t'certificatePolicies must not be empty',\n\t\t);\n\t}\n\tconst seen = new Set<string>();\n\tfor (const policy of policies) {\n\t\tconst key = validatePolicyOid(policy.policyIdentifier);\n\t\tif (seen.has(key)) {\n\t\t\tthrowExtensionEncoderError(\n\t\t\t\t'duplicate_policy_oid',\n\t\t\t\t`Duplicate certificate policy OID: ${policy.policyIdentifier}`,\n\t\t\t);\n\t\t}\n\t\tseen.add(key);\n\t}\n\treturn sequence(policies.map(encodePolicyInformation));\n}\n\n/**\n * DER-encode a Policy Mappings extension value.\n *\n * @param mappings Non-empty array of issuer-to-subject policy pairs. Neither OID may be anyPolicy.\n */\nexport function encodePolicyMappings(mappings: PolicyMappings): Uint8Array {\n\tif (mappings.length === 0) {\n\t\tthrowExtensionEncoderError('policy_mappings_empty', 'policyMappings must not be empty');\n\t}\n\treturn sequence(\n\t\tmappings.map((mapping) => {\n\t\t\tconst issuerDomainPolicy = validatePolicyOid(mapping.issuerDomainPolicy);\n\t\t\tconst subjectDomainPolicy = validatePolicyOid(mapping.subjectDomainPolicy);\n\t\t\tif (issuerDomainPolicy === OIDS.anyPolicy || subjectDomainPolicy === OIDS.anyPolicy) {\n\t\t\t\tthrowExtensionEncoderError(\n\t\t\t\t\t'policy_mappings_any_policy',\n\t\t\t\t\t'policyMappings must not use anyPolicy',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn sequence([\n\t\t\t\tobjectIdentifier(mapping.issuerDomainPolicy),\n\t\t\t\tobjectIdentifier(mapping.subjectDomainPolicy),\n\t\t\t]);\n\t\t}),\n\t);\n}\n\n/**\n * DER-encode a Policy Constraints extension value.\n *\n * @param constraints At least one of `requireExplicitPolicy` or `inhibitPolicyMapping` must be set.\n */\nexport function encodePolicyConstraints(constraints: PolicyConstraints): Uint8Array {\n\tconst fields: Uint8Array[] = [];\n\tif (constraints.requireExplicitPolicy !== undefined) {\n\t\tfields.push(\n\t\t\timplicitPrimitiveContext(0, encodeIntegerContent(constraints.requireExplicitPolicy)),\n\t\t);\n\t}\n\tif (constraints.inhibitPolicyMapping !== undefined) {\n\t\tfields.push(\n\t\t\timplicitPrimitiveContext(1, encodeIntegerContent(constraints.inhibitPolicyMapping)),\n\t\t);\n\t}\n\tif (fields.length === 0) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'policy_constraints_empty',\n\t\t\t'policyConstraints must set requireExplicitPolicy or inhibitPolicyMapping',\n\t\t);\n\t}\n\treturn sequence(fields);\n}\n\n/**\n * DER-encode an Inhibit anyPolicy extension value (single INTEGER).\n *\n * @param input The skipCerts threshold.\n */\nexport function encodeInhibitAnyPolicy(input: InhibitAnyPolicy): Uint8Array {\n\treturn integerFromNumber(input.skipCerts);\n}\n\n/** DER-encode a single PolicyInformation SEQUENCE. */\nfunction encodePolicyInformation(policy: PolicyInformation): Uint8Array {\n\tvalidatePolicyOid(policy.policyIdentifier);\n\tconst fields = [objectIdentifier(policy.policyIdentifier)];\n\tif (policy.policyQualifiers !== undefined && policy.policyQualifiers.length > 0) {\n\t\tfields.push(sequence(policy.policyQualifiers.map(encodePolicyQualifierInfo)));\n\t}\n\treturn sequence(fields);\n}\n\n/** DER-encode a single PolicyQualifierInfo SEQUENCE. */\nfunction encodePolicyQualifierInfo(qualifier: PolicyQualifierInfo): Uint8Array {\n\tswitch (qualifier.type) {\n\t\tcase 'cps':\n\t\t\treturn sequence([objectIdentifier(OIDS.cpsPolicyQualifier), ia5String(qualifier.uri)]);\n\t\tcase 'userNotice':\n\t\t\treturn sequence([\n\t\t\t\tobjectIdentifier(OIDS.userNoticePolicyQualifier),\n\t\t\t\tencodeUserNoticePolicyQualifierInfo(qualifier),\n\t\t\t]);\n\t\tcase 'oid': {\n\t\t\tvalidateOid(qualifier.oid);\n\t\t\tconst encodedOid = objectIdentifier(qualifier.oid);\n\t\t\tconst canonicalOid = toHex(encodedOid);\n\t\t\tif (\n\t\t\t\tcanonicalOid === toHex(objectIdentifier(OIDS.cpsPolicyQualifier)) ||\n\t\t\t\tcanonicalOid === toHex(objectIdentifier(OIDS.userNoticePolicyQualifier))\n\t\t\t) {\n\t\t\t\tthrowExtensionEncoderError(\n\t\t\t\t\t'reserved_policy_qualifier_oid',\n\t\t\t\t\t'Policy qualifier must use the typed cps or userNotice variant, not a built-in OID',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn sequence([encodedOid, new Uint8Array(qualifier.qualifierDer)]);\n\t\t}\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = qualifier;\n\t\t\tthrow new Error(`Unhandled PolicyQualifierInfo type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** DER-encode a UserNotice qualifier SEQUENCE. */\nfunction assertDisplayText(value: string): void {\n\tconst length = [...value].length;\n\tif (length === 0 || length > 200) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'display_text_out_of_range',\n\t\t\t'DisplayText must be 1 to 200 characters',\n\t\t);\n\t}\n}\n\nfunction encodeUserNoticePolicyQualifierInfo(qualifier: UserNoticePolicyQualifierInfo): Uint8Array {\n\tconst fields: Uint8Array[] = [];\n\tif (qualifier.noticeRef !== undefined) {\n\t\tfields.push(encodePolicyNoticeReference(qualifier.noticeRef));\n\t}\n\tif (qualifier.explicitText !== undefined) {\n\t\tassertDisplayText(qualifier.explicitText);\n\t\tfields.push(utf8String(qualifier.explicitText));\n\t}\n\treturn sequence(fields);\n}\n\n/** DER-encode a NoticeReference SEQUENCE. */\nfunction encodePolicyNoticeReference(reference: PolicyNoticeReference): Uint8Array {\n\tassertDisplayText(reference.organization);\n\treturn sequence([\n\t\tutf8String(reference.organization),\n\t\tsequence(reference.noticeNumbers.map((noticeNumber) => integerFromNumber(noticeNumber))),\n\t]);\n}\n\n/** Encode an INTEGER and return only the content bytes (no TLV wrapper). */\nfunction encodeIntegerContent(value: number): Uint8Array {\n\treturn readElement(integerFromNumber(value)).value;\n}\n\n/** DER-encode a GeneralSubtree SEQUENCE (base name only; min/max omitted per RFC 5280). */\nfunction encodeGeneralSubtree(subtree: GeneralSubtree): Uint8Array {\n\treturn sequence([encodeNameConstraintForm(subtree.base)]);\n}\n\n/**\n * RFC 5280 §4.2.1.13: cRLIssuer, when present, only contains the CRL issuer's\n * distinguished name; nameRelativeToCRLIssuer additionally requires exactly one.\n *\n * Applies to a typed {@linkcode DistributionPoint} and to a decoded\n * {@linkcode ParsedDistributionPoint} alike, so the rule holds whether the value\n * arrives through `crlDistributionPoints` or through `customExtensions`.\n */\nfunction assertCrlIssuerDistinguishedNames<TRelativeName>(\n\tpoint: ProfileDistributionPoint<TRelativeName>,\n): void {\n\tif (point.crlIssuer === undefined) {\n\t\treturn;\n\t}\n\tif (point.crlIssuer.some((name) => name.type !== 'directoryName')) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'distribution_point_crl_issuer_not_directory_name',\n\t\t\t'DistributionPoint cRLIssuer must only contain directoryName entries',\n\t\t);\n\t}\n\tif (point.distributionPoint?.type === 'relativeName' && point.crlIssuer.length > 1) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'distribution_point_relative_name_multiple_crl_issuers',\n\t\t\t'DistributionPointName relativeName requires at most one cRLIssuer distinguished name',\n\t\t);\n\t}\n}\n\n/** DER-encode the fields of a single DistributionPoint, already profile-checked. */\nfunction encodeDistributionPoint(point: DistributionPoint): Uint8Array[] {\n\tconst fields: Uint8Array[] = [];\n\tif (point.distributionPoint !== undefined) {\n\t\tfields.push(\n\t\t\timplicitConstructedContext(0, encodeDistributionPointName(point.distributionPoint)),\n\t\t);\n\t}\n\tif (point.reasons !== undefined && point.reasons.length > 0) {\n\t\tfields.push(\n\t\t\timplicitPrimitiveContext(1, encodeDistributionPointReasonFlagsContent(point.reasons)),\n\t\t);\n\t}\n\tif (point.crlIssuer !== undefined) {\n\t\tfields.push(\n\t\t\timplicitConstructedContext(2, concatBytes(point.crlIssuer.map(encodeSubjectAltName))),\n\t\t);\n\t}\n\treturn fields;\n}\n\n/** DER-encode a DistributionPointName (fullName or relativeName). */\nfunction encodeDistributionPointName(name: DistributionPointName): Uint8Array {\n\tswitch (name.type) {\n\t\tcase 'fullName': {\n\t\t\tif (name.fullName.length === 0) {\n\t\t\t\tthrowExtensionEncoderError(\n\t\t\t\t\t'distribution_point_full_name_empty',\n\t\t\t\t\t'DistributionPointName fullName must not be empty',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn implicitConstructedContext(0, concatBytes(name.fullName.map(encodeSubjectAltName)));\n\t\t}\n\t\tcase 'relativeName': {\n\t\t\tconst relativeName = encodeRelativeDistinguishedName(name.relativeName);\n\t\t\tconst relativeNameElement = readElement(relativeName);\n\t\t\treturn implicitConstructedContext(\n\t\t\t\t1,\n\t\t\t\trelativeName.slice(relativeNameElement.start, relativeNameElement.end),\n\t\t\t);\n\t\t}\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = name;\n\t\t\tthrow new Error(`Unhandled DistributionPointName type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** DER-encode a NameConstraintForm as an implicit-tagged {@linkcode GeneralName}. */\nfunction encodeNameConstraintForm(form: NameConstraintForm): Uint8Array {\n\tswitch (form.type) {\n\t\tcase 'dns':\n\t\t\treturn implicitPrimitiveContext(2, ia5Bytes(form.value));\n\t\tcase 'email':\n\t\t\treturn implicitPrimitiveContext(1, ia5Bytes(form.value));\n\t\tcase 'uri':\n\t\t\treturn implicitPrimitiveContext(6, ia5Bytes(form.value));\n\t\tcase 'ip': {\n\t\t\tconst total = form.addressBytes.length + form.maskBytes.length;\n\t\t\tif (form.addressBytes.length !== form.maskBytes.length || (total !== 8 && total !== 32)) {\n\t\t\t\tthrowExtensionEncoderError(\n\t\t\t\t\t'invalid_ip_name_constraint',\n\t\t\t\t\t'IP name constraint must be 8 octets (IPv4) or 32 octets (IPv6)',\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn implicitPrimitiveContext(7, concatBytes([form.addressBytes, form.maskBytes]));\n\t\t}\n\t\tcase 'directoryName':\n\t\t\treturn implicitConstructedContext(4, readDirectoryNameTlv(form.derHex));\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/** Returns the complete Name TLV from a hex-encoded DER SEQUENCE, validating the root tag. */\nfunction readDirectoryNameTlv(derHex: string): Uint8Array {\n\tconst bytes = hexToBytes(derHex);\n\tconst element = readRootElement(bytes, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\tif (element.tag !== 0x30) {\n\t\tthrowExtensionEncoderError(\n\t\t\t'directory_name_not_sequence',\n\t\t\t'directoryName derHex must encode a DER SEQUENCE',\n\t\t);\n\t}\n\treturn bytes.slice(element.start - element.headerLength, element.end);\n}\n\n/**\n * Resolve an {@linkcode ExtendedKeyUsage} to its dotted-decimal OID.\n *\n * @param usage Well-known string or custom OID object.\n */\nexport function getExtendedKeyUsageOid(usage: ExtendedKeyUsage): string {\n\tif (typeof usage === 'string') {\n\t\treturn EXTENDED_KEY_USAGE_OIDS[usage];\n\t}\n\treturn validateOid(usage.value);\n}\n\n/**\n * Map a dotted-decimal OID to an {@linkcode ExtendedKeyUsage} value.\n *\n * Returns a well-known string for recognized OIDs, or `{ type: 'oid', value }` otherwise.\n */\nexport function parseExtendedKeyUsageOid(oid: string): ExtendedKeyUsage {\n\tswitch (oid) {\n\t\tcase OIDS.serverAuth:\n\t\t\treturn 'serverAuth';\n\t\tcase OIDS.clientAuth:\n\t\t\treturn 'clientAuth';\n\t\tcase OIDS.codeSigning:\n\t\t\treturn 'codeSigning';\n\t\tcase OIDS.emailProtection:\n\t\t\treturn 'emailProtection';\n\t\tcase OIDS.timeStamping:\n\t\t\treturn 'timeStamping';\n\t\tcase OIDS.ocspSigning:\n\t\t\treturn 'ocspSigning';\n\t}\n\treturn { type: 'oid', value: oid };\n}\n\n/**\n * Resolve an {@linkcode AuthorityInfoAccessMethod} to its dotted-decimal OID.\n *\n * @param method Well-known string or custom OID object.\n */\nexport function getAuthorityInfoAccessMethodOid(method: AuthorityInfoAccessMethod): string {\n\tif (typeof method === 'string') {\n\t\treturn AUTHORITY_INFO_ACCESS_METHOD_OIDS[method];\n\t}\n\treturn validateOid(method.value);\n}\n\n/**\n * Map a dotted-decimal OID to an {@linkcode AuthorityInfoAccessMethod} value.\n *\n * Returns `'ocsp'` or `'caIssuers'` for recognized OIDs, or `{ type: 'oid', value }` otherwise.\n */\nexport function parseAuthorityInfoAccessMethodOid(oid: string): AuthorityInfoAccessMethod {\n\tswitch (oid) {\n\t\tcase OIDS.ocspAccessMethod:\n\t\t\treturn 'ocsp';\n\t\tcase OIDS.caIssuersAccessMethod:\n\t\t\treturn 'caIssuers';\n\t}\n\treturn { type: 'oid', value: oid };\n}\n\n/** Parse a dotted-decimal/colon-hex IP string to raw address bytes. */\nfunction encodeIpAddress(input: string): Uint8Array {\n\treturn parseIpAddressToBytes(input);\n}\n\n/**\n * Computes a key identifier from a DER `SubjectPublicKeyInfo` using method (1)\n * of RFC 5280 §4.2.1.2: \"the 160-bit SHA-1 hash of the value of the BIT STRING\n * subjectPublicKey (excluding the tag, length, and number of unused bits)\".\n * A parsed certificate carries the input as `subjectPublicKeyInfoDer`.\n */\nexport function buildSubjectKeyIdentifier(subjectPublicKeyInfo: Uint8Array): Uint8Array {\n\tconst topLevel = readSequenceChildren(subjectPublicKeyInfo);\n\tconst subjectPublicKey = topLevel[1];\n\tif (subjectPublicKey === undefined || subjectPublicKey.tag !== 0x03) {\n\t\tthrow new Error('SPKI missing subject public key bit string');\n\t}\n\tconst publicKeyBytes = subjectPublicKey.value.slice(1);\n\treturn sha1(publicKeyBytes);\n}\n\n/**\n * Throw if the string is not an encodable dotted-decimal OID, and return its\n * canonical spelling.\n *\n * Syntax alone is not enough. X.660 bounds the first arc to 0, 1, or 2 and the\n * second to under 40 beneath arcs 0 and 1, so `3.1` and `1.40` parse as decimals\n * yet cannot be encoded.\n */\nfunction validateOid(oid: string): string {\n\tif (!/^\\d+(?:\\.\\d+)+$/.test(oid)) {\n\t\tthrowExtensionEncoderError('invalid_oid', `Invalid OID: ${oid}`);\n\t}\n\ttry {\n\t\treturn canonicalizeOid(oid);\n\t} catch {\n\t\tthrowExtensionEncoderError('invalid_oid', `Invalid OID: ${oid}`);\n\t}\n}\n\n/** Validate a policy OID and return its canonical spelling. */\nfunction validatePolicyOid(oid: string): string {\n\treturn validateOid(oid);\n}\n\n/**\n * Encode and push an extension, rejecting duplicate OIDs.\n *\n * Duplicate identity is the canonical OID, because two spellings that differ only\n * by leading zeros in an arc encode to the same wire bytes. The diagnostic quotes\n * the OID as submitted, which is the string the caller can find in their input.\n */\nfunction pushExtension(\n\tencoded: Uint8Array[],\n\tseen: Set<string>,\n\toid: string,\n\tvalue: Uint8Array,\n\tcritical = false,\n): void {\n\tconst identity = validateOid(oid);\n\tif (seen.has(identity)) {\n\t\tthrowExtensionEncoderError('duplicate_extension_oid', `Duplicate extension OID: ${oid}`);\n\t}\n\tseen.add(identity);\n\tencoded.push(encodeExtension(oid, value, critical));\n}\n\nexport {\n\tallOnesMaskForIpAddress,\n\tdecodeIpAddress,\n\tnormalizeIpAddress,\n\tparseIpAddressToBytes,\n} from '#micro509/internal/shared/ip';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA8sBA,MAAM,IAAiE;CACtE,YAAY,EAAK;CACjB,YAAY,EAAK;CACjB,aAAa,EAAK;CAClB,iBAAiB,EAAK;CACtB,cAAc,EAAK;CACnB,aAAa,EAAK;AACnB,GAGM,IAAoF;CACzF,MAAM,EAAK;CACX,WAAW,EAAK;AACjB;;;;;;;;;;;;;;;AAgBA,SAAgB,2BACf,GACA,GACA,GACA,IAAiB,IACF;CAMf,AALA,4BAA4B,GAAO,aAAa,GAC5C,KACH,4CAA4C,CAAK,GAElD,yBAAyB,CAAK,GAC9B,wBAAwB,GAAsB,CAAK;CACnD,IAAM,IAA2B,CAAC,GAC5B,oBAAO,IAAI,IAAY;CAqB7B,OAnBA,mBAAmB,GAAY,GAAM,GADZ,GAAO,oBAAoB,EAAE,IAAI,GAAM,CAC6B,GAC7F,mBACC,GACA,GACA,GACA,0BAA0B,CAAoB,CAC/C,GACI,MAAwB,KAAA,KAC3B,mBACC,GACA,GACA,GACA,0BAA0B,CAAmB,CAC9C,GAED,2BAA2B,GAAY,GAAM,GAAO;EACnD,yBAAyB;EACzB;CACD,CAAC,GACM;AACR;;;;;;;;;AAUA,SAAgB,yBACf,GACe;CACf,4BAA4B,GAAO,KAAK;CACxC,IAAM,IAA2B,CAAC;CAGl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v": return "SRV";
45
45
  case "directoryName": return "DirName";
46
46
  case "unknown": return `[tag ${String(e.tag)}]`;
47
+ default: throw Error(`Unhandled SubjectAltName type: ${String(e)}`);
47
48
  }
48
49
  }
49
50
  /**
@@ -96,6 +97,7 @@ function subjectAltNameText(e) {
96
97
  case "srv": return e.value;
97
98
  case "directoryName": return directoryNameText(e.derHex);
98
99
  case "unknown": return t(e.value);
100
+ default: throw Error(`Unhandled SubjectAltName type: ${String(e)}`);
99
101
  }
100
102
  }
101
103
  function directoryNameText(t) {
@@ -1 +1 @@
1
- {"version":3,"file":"name-text.js","names":[],"sources":["../../src/x509/name-text.ts"],"sourcesContent":["/**\n * Human-readable text for parsed names.\n *\n * Renders a {@linkcode ParsedName} or {@linkcode SubjectAltName} as a display string,\n * covering every variant of the union without the caller narrowing it by hand.\n *\n * @module micro509/x509/name-text\n */\n\nimport { hexToBytes, toHex } from '#micro509/internal/asn1/asn1';\nimport { DN_ATTRIBUTE_KEYWORDS } from '#micro509/internal/x509/name-fields';\nimport type { SubjectAltName } from '#micro509/x509/extensions';\nimport type {\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\nimport { parseDistinguishedNameDer } from '#micro509/x509/parse';\n\n/** Options for {@linkcode subjectAltNameToString}. */\nexport interface SubjectAltNameTextOptions {\n\t/** Prepend `{@linkcode subjectAltNameLabel}:` to the value, as `openssl x509 -text` does. Defaults to `false`. */\n\treadonly prefix?: boolean;\n}\n\n/**\n * Renders one {@linkcode SubjectAltName} as text.\n *\n * | variant | rendering |\n * | --- | --- |\n * | `dns`, `ip`, `email`, `uri`, `srv` | the value itself |\n * | `directoryName` | {@linkcode distinguishedNameToString} of the embedded name, or the DER hex if it does not decode |\n * | `unknown` | lowercase hex of the raw content bytes |\n *\n * @example Render every SAN of a parsed certificate\n * ```ts\n * const names = (parsed.subjectAltNames ?? []).map((name) => subjectAltNameToString(name));\n * // ['example.com', '192.0.2.1', 'CN=Example CA,C=US']\n *\n * subjectAltNameToString({ type: 'dns', value: 'example.com' }, { prefix: true }); // 'DNS:example.com'\n * ```\n */\nexport function subjectAltNameToString(\n\tname: SubjectAltName,\n\toptions?: SubjectAltNameTextOptions,\n): string {\n\tconst text = subjectAltNameText(name);\n\treturn options?.prefix === true ? `${subjectAltNameLabel(name)}:${text}` : text;\n}\n\n/**\n * The `openssl x509 -text` label for a {@linkcode SubjectAltName} variant —\n * `DNS`, `IP Address`, `email`, `URI`, `SRV`, `DirName`, or `[tag <n>]` for an unrecognized tag.\n */\nexport function subjectAltNameLabel(name: SubjectAltName): string {\n\tswitch (name.type) {\n\t\tcase 'dns':\n\t\t\treturn 'DNS';\n\t\tcase 'ip':\n\t\t\treturn 'IP Address';\n\t\tcase 'email':\n\t\t\treturn 'email';\n\t\tcase 'uri':\n\t\t\treturn 'URI';\n\t\tcase 'srv':\n\t\t\treturn 'SRV';\n\t\tcase 'directoryName':\n\t\t\treturn 'DirName';\n\t\tcase 'unknown':\n\t\t\treturn `[tag ${String(name.tag)}]`;\n\t}\n}\n\n/**\n * Renders a {@linkcode ParsedName} as an RFC 4514 distinguished name string, e.g. `CN=Example CA,O=Acme,C=US`.\n *\n * RDNs are emitted in reverse encoding order and multi-valued RDNs are joined with `+`,\n * both per RFC 4514 [§2](https://datatracker.ietf.org/doc/html/rfc4514#section-2).\n * Attribute types outside the RFC 4514 [§3](https://datatracker.ietf.org/doc/html/rfc4514#section-3)\n * keyword table use the short names `openssl` prints, falling back to the dotted OID.\n *\n * @example\n * ```ts\n * distinguishedNameToString(parsed.subject); // 'CN=example.com,O=Acme\\\\, Inc.,C=US'\n * ```\n */\nexport function distinguishedNameToString(name: ParsedName): string {\n\treturn [...name.rdns]\n\t\t.reverse()\n\t\t.map((rdn) => relativeDistinguishedNameToString(rdn))\n\t\t.join(',');\n}\n\n/** Renders one {@linkcode ParsedRelativeDistinguishedName}, joining a multi-valued RDN's attributes with `+`. */\nexport function relativeDistinguishedNameToString(rdn: ParsedRelativeDistinguishedName): string {\n\treturn rdn.attributes.map((attribute) => attributeToString(attribute)).join('+');\n}\n\n/** Characters RFC 4514 [§2.4](https://datatracker.ietf.org/doc/html/rfc4514#section-2.4) escapes wherever they appear. */\nconst ESCAPED_CHARACTERS = new Set(['\"', '+', ',', ';', '<', '>', '\\\\']);\n\nfunction attributeToString(attribute: ParsedNameAttribute): string {\n\tconst keyword = DN_ATTRIBUTE_KEYWORDS[attribute.oid] ?? attribute.oid;\n\treturn `${keyword}=${escapeAttributeValue(attribute.value)}`;\n}\n\nfunction escapeAttributeValue(value: string): string {\n\tconst characters = [...value];\n\treturn characters\n\t\t.map((character, index) => {\n\t\t\tif (ESCAPED_CHARACTERS.has(character)) {\n\t\t\t\treturn `\\\\${character}`;\n\t\t\t}\n\t\t\tconst code = character.codePointAt(0) ?? 0;\n\t\t\tif (code < 0x20 || code === 0x7f) {\n\t\t\t\treturn `\\\\${code.toString(16).padStart(2, '0')}`;\n\t\t\t}\n\t\t\tif (character === ' ' && (index === 0 || index === characters.length - 1)) {\n\t\t\t\treturn '\\\\ ';\n\t\t\t}\n\t\t\treturn character === '#' && index === 0 ? '\\\\#' : character;\n\t\t})\n\t\t.join('');\n}\n\nfunction subjectAltNameText(name: SubjectAltName): string {\n\tswitch (name.type) {\n\t\tcase 'dns':\n\t\tcase 'ip':\n\t\tcase 'email':\n\t\tcase 'uri':\n\t\tcase 'srv':\n\t\t\treturn name.value;\n\t\tcase 'directoryName':\n\t\t\treturn directoryNameText(name.derHex);\n\t\tcase 'unknown':\n\t\t\treturn toHex(name.value);\n\t}\n}\n\nfunction directoryNameText(derHex: string): string {\n\ttry {\n\t\treturn distinguishedNameToString(parseDistinguishedNameDer(hexToBytes(derHex)));\n\t} catch {\n\t\treturn derHex;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,uBACf,GACA,GACS;CACT,IAAM,IAAO,mBAAmB,CAAI;CACpC,OAAO,GAAS,WA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SAAS,mBAAmB,GAA8B;CACzD,QAAQ,EAAK,MAAb;EACC,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,OACJ,OAAO,EAAK;EACb,KAAK,iBACJ,OAAO,kBAAkB,EAAK,MAAM;EACrC,KAAK,WACJ,OAAO,EAAM,EAAK,KAAK;CACzB;AACD;AAEA,SAAS,kBAAkB,GAAwB;CAClD,IAAI;EACH,OAAO,0BAA0B,EAA0B,EAAW,CAAM,CAAC,CAAC;CAC/E,QAAQ;EACP,OAAO;CACR;AACD"}
1
+ {"version":3,"file":"name-text.js","names":["_exhaustive"],"sources":["../../src/x509/name-text.ts"],"sourcesContent":["/**\n * Human-readable text for parsed names.\n *\n * Renders a {@linkcode ParsedName} or {@linkcode SubjectAltName} as a display string,\n * covering every variant of the union without the caller narrowing it by hand.\n *\n * @module micro509/x509/name-text\n */\n\nimport { hexToBytes, toHex } from '#micro509/internal/asn1/asn1';\nimport { DN_ATTRIBUTE_KEYWORDS } from '#micro509/internal/x509/name-fields';\nimport type { SubjectAltName } from '#micro509/x509/extensions';\nimport type {\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\nimport { parseDistinguishedNameDer } from '#micro509/x509/parse';\n\n/** Options for {@linkcode subjectAltNameToString}. */\nexport interface SubjectAltNameTextOptions {\n\t/** Prepend `{@linkcode subjectAltNameLabel}:` to the value, as `openssl x509 -text` does. Defaults to `false`. */\n\treadonly prefix?: boolean;\n}\n\n/**\n * Renders one {@linkcode SubjectAltName} as text.\n *\n * | variant | rendering |\n * | --- | --- |\n * | `dns`, `ip`, `email`, `uri`, `srv` | the value itself |\n * | `directoryName` | {@linkcode distinguishedNameToString} of the embedded name, or the DER hex if it does not decode |\n * | `unknown` | lowercase hex of the raw content bytes |\n *\n * @example Render every SAN of a parsed certificate\n * ```ts\n * const names = (parsed.subjectAltNames ?? []).map((name) => subjectAltNameToString(name));\n * // ['example.com', '192.0.2.1', 'CN=Example CA,C=US']\n *\n * subjectAltNameToString({ type: 'dns', value: 'example.com' }, { prefix: true }); // 'DNS:example.com'\n * ```\n */\nexport function subjectAltNameToString(\n\tname: SubjectAltName,\n\toptions?: SubjectAltNameTextOptions,\n): string {\n\tconst text = subjectAltNameText(name);\n\treturn options?.prefix === true ? `${subjectAltNameLabel(name)}:${text}` : text;\n}\n\n/**\n * The `openssl x509 -text` label for a {@linkcode SubjectAltName} variant —\n * `DNS`, `IP Address`, `email`, `URI`, `SRV`, `DirName`, or `[tag <n>]` for an unrecognized tag.\n */\nexport function subjectAltNameLabel(name: SubjectAltName): string {\n\tswitch (name.type) {\n\t\tcase 'dns':\n\t\t\treturn 'DNS';\n\t\tcase 'ip':\n\t\t\treturn 'IP Address';\n\t\tcase 'email':\n\t\t\treturn 'email';\n\t\tcase 'uri':\n\t\t\treturn 'URI';\n\t\tcase 'srv':\n\t\t\treturn 'SRV';\n\t\tcase 'directoryName':\n\t\t\treturn 'DirName';\n\t\tcase 'unknown':\n\t\t\treturn `[tag ${String(name.tag)}]`;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = name;\n\t\t\tthrow new Error(`Unhandled SubjectAltName type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/**\n * Renders a {@linkcode ParsedName} as an RFC 4514 distinguished name string, e.g. `CN=Example CA,O=Acme,C=US`.\n *\n * RDNs are emitted in reverse encoding order and multi-valued RDNs are joined with `+`,\n * both per RFC 4514 [§2](https://datatracker.ietf.org/doc/html/rfc4514#section-2).\n * Attribute types outside the RFC 4514 [§3](https://datatracker.ietf.org/doc/html/rfc4514#section-3)\n * keyword table use the short names `openssl` prints, falling back to the dotted OID.\n *\n * @example\n * ```ts\n * distinguishedNameToString(parsed.subject); // 'CN=example.com,O=Acme\\\\, Inc.,C=US'\n * ```\n */\nexport function distinguishedNameToString(name: ParsedName): string {\n\treturn [...name.rdns]\n\t\t.reverse()\n\t\t.map((rdn) => relativeDistinguishedNameToString(rdn))\n\t\t.join(',');\n}\n\n/** Renders one {@linkcode ParsedRelativeDistinguishedName}, joining a multi-valued RDN's attributes with `+`. */\nexport function relativeDistinguishedNameToString(rdn: ParsedRelativeDistinguishedName): string {\n\treturn rdn.attributes.map((attribute) => attributeToString(attribute)).join('+');\n}\n\n/** Characters RFC 4514 [§2.4](https://datatracker.ietf.org/doc/html/rfc4514#section-2.4) escapes wherever they appear. */\nconst ESCAPED_CHARACTERS = new Set(['\"', '+', ',', ';', '<', '>', '\\\\']);\n\nfunction attributeToString(attribute: ParsedNameAttribute): string {\n\tconst keyword = DN_ATTRIBUTE_KEYWORDS[attribute.oid] ?? attribute.oid;\n\treturn `${keyword}=${escapeAttributeValue(attribute.value)}`;\n}\n\nfunction escapeAttributeValue(value: string): string {\n\tconst characters = [...value];\n\treturn characters\n\t\t.map((character, index) => {\n\t\t\tif (ESCAPED_CHARACTERS.has(character)) {\n\t\t\t\treturn `\\\\${character}`;\n\t\t\t}\n\t\t\tconst code = character.codePointAt(0) ?? 0;\n\t\t\tif (code < 0x20 || code === 0x7f) {\n\t\t\t\treturn `\\\\${code.toString(16).padStart(2, '0')}`;\n\t\t\t}\n\t\t\tif (character === ' ' && (index === 0 || index === characters.length - 1)) {\n\t\t\t\treturn '\\\\ ';\n\t\t\t}\n\t\t\treturn character === '#' && index === 0 ? '\\\\#' : character;\n\t\t})\n\t\t.join('');\n}\n\nfunction subjectAltNameText(name: SubjectAltName): string {\n\tswitch (name.type) {\n\t\tcase 'dns':\n\t\tcase 'ip':\n\t\tcase 'email':\n\t\tcase 'uri':\n\t\tcase 'srv':\n\t\t\treturn name.value;\n\t\tcase 'directoryName':\n\t\t\treturn directoryNameText(name.derHex);\n\t\tcase 'unknown':\n\t\t\treturn toHex(name.value);\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = name;\n\t\t\tthrow new Error(`Unhandled SubjectAltName type: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\nfunction directoryNameText(derHex: string): string {\n\ttry {\n\t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IAAO,EAAU,YAAY,CAAC,KAAK;EAOzC,OANI,IAAO,MAAQ,MAAS,MACpB,KAAK,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,MAE1C,MAAc,QAAQ,MAAU,KAAK,MAAU,EAAW,SAAS,KAC/D,QAED,MAAc,OAAO,MAAU,IAAI,QAAQ;CACnD,CAAC,CAAC,CACD,KAAK,EAAE;AACV;AAEA,SAAS,mBAAmB,GAA8B;CACzD,QAAQ,EAAK,MAAb;EACC,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,OACJ,OAAO,EAAK;EACb,KAAK,iBACJ,OAAO,kBAAkB,EAAK,MAAM;EACrC,KAAK,WACJ,OAAO,EAAM,EAAK,KAAK;EACxB,SAEC,MAAU,MAAM,kCAAkC,OAAOA,CAAW,GAAG;CAEzE;AACD;AAEA,SAAS,kBAAkB,GAAwB;CAClD,IAAI;EACH,OAAO,0BAA0B,EAA0B,EAAW,CAAM,CAAC,CAAC;CAC/E,QAAQ;EACP,OAAO;CACR;AACD"}
@@ -1,6 +1,9 @@
1
+ import { canonicalDnKey, compareDistinguishedNames, isWithinDirectoryNameSubtree } from "../internal/shared/dn.js";
1
2
  //#region src/x509/name.d.ts
3
+ /** Machine-readable reason a distinguished-name encoder rejected its construction input. */
4
+ type NameEncoderErrorCode = "relative_distinguished_name_empty" | "unsupported_name_field" | "name_attribute_empty" | "name_attribute_too_long" | "invalid_country_code";
2
5
  /**
3
- * Union of recognized X.501 attribute type shorthand names.
6
+ * Union of recognized distinguished-name attribute type shorthand names.
4
7
  *
5
8
  * Each key maps to an OID + ASN.1 string encoding in `NAME_FIELD_DEFINITIONS`.
6
9
  */
@@ -38,7 +41,7 @@ interface NameObject {
38
41
  readonly title?: string;
39
42
  /** First / given name (GN). */
40
43
  readonly givenName?: string;
41
- /** RFC 822 email address. Encoded as IA5String, not UTF-8. */
44
+ /** PKCS #9 emailAddress attribute (RFC 2985 §5.2.1). Encoded as IA5String, not UTF-8. RFC 5280 §4.1.2.6 deprecates it in favour of a subjectAltName rfc822Name. */
42
45
  readonly emailAddress?: string;
43
46
  }
44
47
  /**
@@ -106,7 +109,7 @@ type RelativeDistinguishedNameInput = readonly NameAttribute[];
106
109
  *
107
110
  * @param input Name fields in convenience-object form or caller-ordered attribute form.
108
111
  * @returns DER-encoded X.509 `Name` bytes.
109
- * @throws {Error} If the input produces no attributes, contains an unsupported field key, or uses an invalid country code.
112
+ * @throws {ResultError} If a value exceeds its RFC 5280 A.1 bound, an ordered attribute value is empty, a field key is unsupported, or a country code is not two characters. An input with no attributes encodes an empty Name (`30 00`) rather than throwing.
110
113
  */
111
114
  declare function encodeName(input: NameInput): Uint8Array;
112
115
  /**
@@ -132,9 +135,9 @@ declare function encodeName(input: NameInput): Uint8Array;
132
135
  *
133
136
  * @param attributes Attribute list to encode inside one RDN.
134
137
  * @returns DER-encoded RelativeDistinguishedName bytes.
135
- * @throws {Error} If the attribute list is empty, contains an unsupported field key, or uses an invalid country code.
138
+ * @throws {ResultError} If the attribute list is empty, contains an unsupported field key, an empty or over-long value, or an invalid country code.
136
139
  */
137
140
  declare function encodeRelativeDistinguishedName(attributes: RelativeDistinguishedNameInput): Uint8Array;
138
141
  //#endregion
139
- export { NameAttribute, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName };
142
+ export { NameAttribute, NameEncoderErrorCode, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, canonicalDnKey, compareDistinguishedNames, encodeName, encodeRelativeDistinguishedName, isWithinDirectoryNameSubtree };
140
143
  //# sourceMappingURL=name.d.ts.map
package/dist/x509/name.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { objectIdentifier as e, sequence as t, setOf as n } from "../internal/asn1/der.js";
2
- import { NAME_FIELD_DEFINITIONS as r, NAME_OBJECT_ORDER as i, nameFieldKeyFromOid as a } from "../internal/x509/name-fields.js";
2
+ import { throwMicro509Error as r } from "../result/result.js";
3
+ import { NAME_FIELD_DEFINITIONS as i, NAME_OBJECT_ORDER as a, nameFieldKeyFromOid as o } from "../internal/x509/name-fields.js";
4
+ import { canonicalDnKey as s, compareDistinguishedNames as c, isWithinDirectoryNameSubtree as l } from "../internal/shared/dn.js";
3
5
  //#region src/x509/name.ts
4
6
  /**
5
7
  * Distinguished-name input and DER encoding helpers.
@@ -64,6 +66,10 @@ import { NAME_FIELD_DEFINITIONS as r, NAME_OBJECT_ORDER as i, nameFieldKeyFromOi
64
66
  *
65
67
  * @module
66
68
  */
69
+ /** Throws a {@link ResultError} for a distinguished-name encoder input-validation failure. */
70
+ function throwNameEncoderError(e, t) {
71
+ r(e, t);
72
+ }
67
73
  /**
68
74
  * DER-encodes an X.509 `Name`.
69
75
  *
@@ -98,7 +104,7 @@ import { NAME_FIELD_DEFINITIONS as r, NAME_OBJECT_ORDER as i, nameFieldKeyFromOi
98
104
  *
99
105
  * @param input Name fields in convenience-object form or caller-ordered attribute form.
100
106
  * @returns DER-encoded X.509 `Name` bytes.
101
- * @throws {Error} If the input produces no attributes, contains an unsupported field key, or uses an invalid country code.
107
+ * @throws {ResultError} If a value exceeds its RFC 5280 A.1 bound, an ordered attribute value is empty, a field key is unsupported, or a country code is not two characters. An input with no attributes encodes an empty Name (`30 00`) rather than throwing.
102
108
  */
103
109
  function encodeName(e) {
104
110
  let n = isNameAttributes(e) ? e : nameObjectToAttributes(e);
@@ -131,11 +137,10 @@ function isNameInputEmpty(e) {
131
137
  *
132
138
  * @param attributes Attribute list to encode inside one RDN.
133
139
  * @returns DER-encoded RelativeDistinguishedName bytes.
134
- * @throws {Error} If the attribute list is empty, contains an unsupported field key, or uses an invalid country code.
140
+ * @throws {ResultError} If the attribute list is empty, contains an unsupported field key, an empty or over-long value, or an invalid country code.
135
141
  */
136
142
  function encodeRelativeDistinguishedName(e) {
137
- if (e.length === 0) throw Error("Relative distinguished name must contain at least one attribute");
138
- return n(e.map(encodeNameAttribute));
143
+ return e.length === 0 && throwNameEncoderError("relative_distinguished_name_empty", "Relative distinguished name must contain at least one attribute"), n(e.map(encodeNameAttribute));
139
144
  }
140
145
  /** Narrows a {@linkcode NameInput} to the ordered-attribute-array form. */
141
146
  function isNameAttributes(e) {
@@ -148,18 +153,18 @@ function encodeNameAttributeAsSet(e) {
148
153
  /**
149
154
  * DER-encodes one name attribute SEQUENCE.
150
155
  *
151
- * Throws for unsupported field keys and invalid country codes.
156
+ * Throws for unsupported field keys, empty or over-long values, and invalid country codes.
152
157
  */
153
158
  function encodeNameAttribute(n) {
154
- let i = r[n.type];
155
- if (i === void 0) throw Error(`Unsupported name field: ${n.type}`);
156
- if (n.type === "country" && n.value.length !== 2) throw Error("Country must be a 2-character code");
157
- return t([e(i.oid), i.encode(n.value)]);
159
+ let r = i[n.type];
160
+ r === void 0 && throwNameEncoderError("unsupported_name_field", `Unsupported name field: ${n.type}`);
161
+ let a = [...n.value].length;
162
+ return a === 0 && throwNameEncoderError("name_attribute_empty", `Name attribute ${n.type} must not be empty`), n.type === "country" && n.value.length !== 2 && throwNameEncoderError("invalid_country_code", "Country must be a 2-character code"), r.maxLength !== void 0 && a > r.maxLength && throwNameEncoderError("name_attribute_too_long", `Name attribute ${n.type} must be at most ${r.maxLength} characters`), t([e(r.oid), r.encode(n.value)]);
158
163
  }
159
164
  /** Converts a {@linkcode NameObject} to ordered attributes per `NAME_OBJECT_ORDER`. */
160
165
  function nameObjectToAttributes(e) {
161
166
  let t = [];
162
- for (let n of i) {
167
+ for (let n of a) {
163
168
  let r = e[n];
164
169
  typeof r == "string" && r.length > 0 && t.push({
165
170
  type: n,
@@ -169,6 +174,6 @@ function nameObjectToAttributes(e) {
169
174
  return t;
170
175
  }
171
176
  //#endregion
172
- export { encodeName, encodeRelativeDistinguishedName, isNameInputEmpty, a as nameFieldKeyFromOid };
177
+ export { s as canonicalDnKey, c as compareDistinguishedNames, encodeName, encodeRelativeDistinguishedName, isNameInputEmpty, l as isWithinDirectoryNameSubtree, o as nameFieldKeyFromOid };
173
178
 
174
179
  //# sourceMappingURL=name.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"name.js","names":[],"sources":["../../src/x509/name.ts"],"sourcesContent":["/**\n * Distinguished-name input and DER encoding helpers.\n *\n * Encodes X.509 `Name` values used for certificate subjects, issuers,\n * and CSR subjects.\\\n * A `Name` is a DER `SEQUENCE` of RelativeDistinguishedNames (RDNs), and each\n * RDN is a `SET OF` one or more name attributes.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1 RFC 5280 Appendix A.1}\n *\n * Use {@linkcode encodeName} for the common case where each attribute occupies\n * its own RDN.\\\n * Use {@linkcode encodeRelativeDistinguishedName} when you need one\n * multi-valued RDN.\n *\n * `NameObject` favors convenience: populated fields are emitted in the\n * canonical order from `NAME_OBJECT_ORDER`.\\\n * `NameAttribute` arrays favor control: caller order is preserved, but each\n * entry still becomes its own single-attribute RDN.\n *\n * Attribute OIDs and ASN.1 string encodings come from\n * `NAME_FIELD_DEFINITIONS`.\n *\n * @example\n * ```ts\n * import { encodeName } from 'micro509/x509';\n *\n * const subjectDer = encodeName({\n * \tcountry: 'US',\n * \torganization: 'ACME Inc',\n * \tcommonName: 'example.com',\n * });\n *\n * // DER for: C=US, O=ACME Inc, CN=example.com\n * ```\n *\n * @example\n * ```ts\n * import { encodeName } from 'micro509/x509';\n *\n * const subjectDer = encodeName([\n * \t{ type: 'commonName', value: 'example.com' },\n * \t{ type: 'organization', value: 'ACME Inc' },\n * \t{ type: 'country', value: 'US' },\n * ]);\n *\n * // preserves caller-supplied attribute order\n * ```\n *\n * @example\n * ```ts\n * import { encodeRelativeDistinguishedName } from 'micro509/x509';\n *\n * const rdnDer = encodeRelativeDistinguishedName([\n * \t{ type: 'commonName', value: 'example.com' },\n * \t{ type: 'serialNumber', value: 'device-7' },\n * ]);\n *\n * // one multi-valued RDN containing CN + serialNumber\n * ```\n *\n * @module\n */\n\nimport { objectIdentifier, sequence, setOf } from '#micro509/internal/asn1/der';\nimport { NAME_FIELD_DEFINITIONS, NAME_OBJECT_ORDER } from '#micro509/internal/x509/name-fields';\n\n/**\n * Union of recognized X.501 attribute type shorthand names.\n *\n * Each key maps to an OID + ASN.1 string encoding in `NAME_FIELD_DEFINITIONS`.\n */\nexport type NameFieldKey =\n\t| 'commonName'\n\t| 'surname'\n\t| 'serialNumber'\n\t| 'country'\n\t| 'locality'\n\t| 'state'\n\t| 'street'\n\t| 'organization'\n\t| 'organizationalUnit'\n\t| 'title'\n\t| 'givenName'\n\t| 'emailAddress';\n\n/**\n * Convenience object form of an X.501 distinguished name.\n *\n * Populated fields are emitted in the order defined by\n * `NAME_OBJECT_ORDER`.\\\n * Each populated field becomes its own single-attribute RDN.\n *\n * For caller-controlled ordering, pass a {@linkcode NameAttribute} array to {@linkcode encodeName}.\\\n * For multi-valued RDNs, use {@linkcode encodeRelativeDistinguishedName}.\n */\nexport interface NameObject {\n\t/** Subject or issuer common name (CN). */\n\treadonly commonName?: string;\n\t/** Subject surname (SN). */\n\treadonly surname?: string;\n\t/** Device or entity serial number — not the certificate serial. */\n\treadonly serialNumber?: string;\n\t/** ISO 3166 two-letter country code (C). Must be exactly 2 characters. */\n\treadonly country?: string;\n\t/** City or locality (L). */\n\treadonly locality?: string;\n\t/** State or province (ST). */\n\treadonly state?: string;\n\t/** Street address. */\n\treadonly street?: string;\n\t/** Organization name (O). */\n\treadonly organization?: string;\n\t/** Organizational unit (OU). Deprecated in modern CA practice. */\n\treadonly organizationalUnit?: string;\n\t/** Job title or functional designation. */\n\treadonly title?: string;\n\t/** First / given name (GN). */\n\treadonly givenName?: string;\n\t/** RFC 822 email address. Encoded as IA5String, not UTF-8. */\n\treadonly emailAddress?: string;\n}\n\n/**\n * Single name attribute within a distinguished name.\n *\n * RFC 5280 / X.501 call this structure an `AttributeTypeAndValue`.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1 RFC 5280 Appendix A.1}\n * {@linkcode encodeName} places each attribute in its own single-attribute RDN.\\\n * {@linkcode encodeRelativeDistinguishedName} packs several attributes into one RDN.\n */\nexport interface NameAttribute {\n\t/** Which attribute type this pair represents. */\n\treadonly type: NameFieldKey;\n\t/** The string value for this attribute (encoding chosen per field definition). */\n\treadonly value: string;\n}\n\n/**\n * Input for {@linkcode encodeName}.\n *\n * Accepts either a {@linkcode NameObject} convenience shape or an ordered array of {@linkcode NameAttribute} pairs.\\\n * Both forms encode one attribute per RDN.\n */\nexport type NameInput = NameObject | readonly NameAttribute[];\n\n/**\n * Input for {@linkcode encodeRelativeDistinguishedName}.\n *\n * Each entry becomes one name attribute inside the RDN's `SET OF`.\\\n * Use this shape for multi-valued RDNs.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1 RFC 5280 Appendix A.1}\n */\nexport type RelativeDistinguishedNameInput = readonly NameAttribute[];\n\nexport { nameFieldKeyFromOid } from '#micro509/internal/x509/name-fields';\n\n/**\n * DER-encodes an X.509 `Name`.\n *\n * Returns a DER `SEQUENCE` of RelativeDistinguishedNames (RDNs).\\\n * Each RDN emitted by this helper contains exactly one name attribute.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1 RFC 5280 Appendix A.1}\n *\n * {@linkcode NameObject} input emits populated fields in the canonical order from `NAME_OBJECT_ORDER`.\\\n * {@linkcode NameAttribute} array input preserves caller-supplied ordering,\n * but each entry still becomes its own single-attribute RDN.\n *\n * Attribute OIDs and ASN.1 string encodings come from `NAME_FIELD_DEFINITIONS`.\\\n * Empty strings and `undefined` fields are ignored when the input is a {@linkcode NameObject}.\n *\n * @example\n * ```ts\n * const der = encodeName({ country: 'US', commonName: 'example.com' });\n *\n * // emits two single-attribute RDNs: C=US, then CN=example.com\n * ```\n *\n * @example\n * ```ts\n * const der = encodeName([\n * \t{ type: 'country', value: 'US' },\n * \t{ type: 'commonName', value: 'example.com' },\n * ]);\n *\n * // preserves caller order: C first, then CN\n * ```\n *\n * @param input Name fields in convenience-object form or caller-ordered attribute form.\n * @returns DER-encoded X.509 `Name` bytes.\n * @throws {Error} If the input produces no attributes, contains an unsupported field key, or uses an invalid country code.\n */\nexport function encodeName(input: NameInput): Uint8Array {\n\tconst attributes = isNameAttributes(input) ? input : nameObjectToAttributes(input);\n\tif (attributes.length === 0) {\n\t\treturn sequence([]);\n\t}\n\n\treturn sequence(attributes.map(encodeNameAttributeAsSet));\n}\n\n/** True when a {@linkcode NameInput} resolves to zero attributes (empty DN). */\nexport function isNameInputEmpty(input: NameInput): boolean {\n\tconst attributes = isNameAttributes(input) ? input : nameObjectToAttributes(input);\n\treturn attributes.length === 0;\n}\n\n/**\n * DER-encodes a single RelativeDistinguishedName (RDN).\n *\n * Returns a DER `SET OF` name attributes for one X.509 name segment.\\\n * Use this when you need a multi-valued RDN.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1 RFC 5280 Appendix A.1}\n *\n * Attribute OIDs and ASN.1 string encodings come from\n * `NAME_FIELD_DEFINITIONS`.\n *\n * @example\n * ```ts\n * const rdn = encodeRelativeDistinguishedName([\n * \t{ type: 'commonName', value: 'example.com' },\n * \t{ type: 'serialNumber', value: 'device-7' },\n * ]);\n *\n * // emits one RDN with both attributes in the same SET\n * ```\n *\n * @param attributes Attribute list to encode inside one RDN.\n * @returns DER-encoded RelativeDistinguishedName bytes.\n * @throws {Error} If the attribute list is empty, contains an unsupported field key, or uses an invalid country code.\n */\nexport function encodeRelativeDistinguishedName(\n\tattributes: RelativeDistinguishedNameInput,\n): Uint8Array {\n\tif (attributes.length === 0) {\n\t\tthrow new Error('Relative distinguished name must contain at least one attribute');\n\t}\n\treturn setOf(attributes.map(encodeNameAttribute));\n}\n\n/** Narrows a {@linkcode NameInput} to the ordered-attribute-array form. */\nfunction isNameAttributes(input: NameInput): input is readonly NameAttribute[] {\n\treturn Array.isArray(input);\n}\n\n/** Wraps a single attribute in a SET OF for the Name SEQUENCE. */\nfunction encodeNameAttributeAsSet(attribute: NameAttribute): Uint8Array {\n\treturn setOf([encodeNameAttribute(attribute)]);\n}\n\n/**\n * DER-encodes one name attribute SEQUENCE.\n *\n * Throws for unsupported field keys and invalid country codes.\n */\nfunction encodeNameAttribute(attribute: NameAttribute): Uint8Array {\n\tconst definition = NAME_FIELD_DEFINITIONS[attribute.type];\n\tif (definition === undefined) {\n\t\tthrow new Error(`Unsupported name field: ${attribute.type}`);\n\t}\n\tif (attribute.type === 'country' && attribute.value.length !== 2) {\n\t\tthrow new Error('Country must be a 2-character code');\n\t}\n\treturn sequence([objectIdentifier(definition.oid), definition.encode(attribute.value)]);\n}\n\n/** Converts a {@linkcode NameObject} to ordered attributes per `NAME_OBJECT_ORDER`. */\nfunction nameObjectToAttributes(input: NameObject): readonly NameAttribute[] {\n\tconst attributes: NameAttribute[] = [];\n\tfor (const key of NAME_OBJECT_ORDER) {\n\t\tconst value = input[key];\n\t\tif (typeof value === 'string' && value.length > 0) {\n\t\t\tattributes.push({ type: key, value });\n\t\t}\n\t}\n\treturn attributes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmMA,SAAgB,WAAW,GAA8B;CACxD,IAAM,IAAa,iBAAiB,CAAK,IAAI,IAAQ,uBAAuB,CAAK;CAKjF,OAJI,EAAW,WAAW,IAClB,EAAS,CAAC,CAAC,IAGZ,EAAS,EAAW,IAAI,wBAAwB,CAAC;AACzD;;AAGA,SAAgB,iBAAiB,GAA2B;CAE3D,QADmB,iBAAiB,CAAK,IAAI,IAAQ,uBAAuB,CAAK,EAAA,CAC/D,WAAW;AAC9B;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,gCACf,GACa;CACb,IAAI,EAAW,WAAW,GACzB,MAAU,MAAM,iEAAiE;CAElF,OAAO,EAAM,EAAW,IAAI,mBAAmB,CAAC;AACjD;;AAGA,SAAS,iBAAiB,GAAqD;CAC9E,OAAO,MAAM,QAAQ,CAAK;AAC3B;;AAGA,SAAS,yBAAyB,GAAsC;CACvE,OAAO,EAAM,CAAC,oBAAoB,CAAS,CAAC,CAAC;AAC9C;;;;;;AAOA,SAAS,oBAAoB,GAAsC;CAClE,IAAM,IAAa,EAAuB,EAAU;CACpD,IAAI,MAAe,KAAA,GAClB,MAAU,MAAM,2BAA2B,EAAU,MAAM;CAE5D,IAAI,EAAU,SAAS,aAAa,EAAU,MAAM,WAAW,GAC9D,MAAU,MAAM,oCAAoC;CAErD,OAAO,EAAS,CAAC,EAAiB,EAAW,GAAG,GAAG,EAAW,OAAO,EAAU,KAAK,CAAC,CAAC;AACvF;;AAGA,SAAS,uBAAuB,GAA6C;CAC5E,IAAM,IAA8B,CAAC;CACrC,KAAK,IAAM,KAAO,GAAmB;EACpC,IAAM,IAAQ,EAAM;EACpB,AAAI,OAAO,KAAU,YAAY,EAAM,SAAS,KAC/C,EAAW,KAAK;GAAE,MAAM;GAAK;EAAM,CAAC;CAEtC;CACA,OAAO;AACR"}
1
+ {"version":3,"file":"name.js","names":[],"sources":["../../src/x509/name.ts"],"sourcesContent":["/**\n * Distinguished-name input and DER encoding helpers.\n *\n * Encodes X.509 `Name` values used for certificate subjects, issuers,\n * and CSR subjects.\\\n * A `Name` is a DER `SEQUENCE` of RelativeDistinguishedNames (RDNs), and each\n * RDN is a `SET OF` one or more name attributes.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1 RFC 5280 Appendix A.1}\n *\n * Use {@linkcode encodeName} for the common case where each attribute occupies\n * its own RDN.\\\n * Use {@linkcode encodeRelativeDistinguishedName} when you need one\n * multi-valued RDN.\n *\n * `NameObject` favors convenience: populated fields are emitted in the\n * canonical order from `NAME_OBJECT_ORDER`.\\\n * `NameAttribute` arrays favor control: caller order is preserved, but each\n * entry still becomes its own single-attribute RDN.\n *\n * Attribute OIDs and ASN.1 string encodings come from\n * `NAME_FIELD_DEFINITIONS`.\n *\n * @example\n * ```ts\n * import { encodeName } from 'micro509/x509';\n *\n * const subjectDer = encodeName({\n * \tcountry: 'US',\n * \torganization: 'ACME Inc',\n * \tcommonName: 'example.com',\n * });\n *\n * // DER for: C=US, O=ACME Inc, CN=example.com\n * ```\n *\n * @example\n * ```ts\n * import { encodeName } from 'micro509/x509';\n *\n * const subjectDer = encodeName([\n * \t{ type: 'commonName', value: 'example.com' },\n * \t{ type: 'organization', value: 'ACME Inc' },\n * \t{ type: 'country', value: 'US' },\n * ]);\n *\n * // preserves caller-supplied attribute order\n * ```\n *\n * @example\n * ```ts\n * import { encodeRelativeDistinguishedName } from 'micro509/x509';\n *\n * const rdnDer = encodeRelativeDistinguishedName([\n * \t{ type: 'commonName', value: 'example.com' },\n * \t{ type: 'serialNumber', value: 'device-7' },\n * ]);\n *\n * // one multi-valued RDN containing CN + serialNumber\n * ```\n *\n * @module\n */\n\nimport { objectIdentifier, sequence, setOf } from '#micro509/internal/asn1/der';\nimport { NAME_FIELD_DEFINITIONS, NAME_OBJECT_ORDER } from '#micro509/internal/x509/name-fields';\nimport { throwMicro509Error } from '#micro509/result/result';\n\n/** Machine-readable reason a distinguished-name encoder rejected its construction input. */\nexport type NameEncoderErrorCode =\n\t| 'relative_distinguished_name_empty'\n\t| 'unsupported_name_field'\n\t| 'name_attribute_empty'\n\t| 'name_attribute_too_long'\n\t| 'invalid_country_code';\n\n/** Throws a {@link ResultError} for a distinguished-name encoder input-validation failure. */\nfunction throwNameEncoderError(code: NameEncoderErrorCode, message: string): never {\n\tthrowMicro509Error(code, message);\n}\n\n/**\n * Union of recognized distinguished-name attribute type shorthand names.\n *\n * Each key maps to an OID + ASN.1 string encoding in `NAME_FIELD_DEFINITIONS`.\n */\nexport type NameFieldKey =\n\t| 'commonName'\n\t| 'surname'\n\t| 'serialNumber'\n\t| 'country'\n\t| 'locality'\n\t| 'state'\n\t| 'street'\n\t| 'organization'\n\t| 'organizationalUnit'\n\t| 'title'\n\t| 'givenName'\n\t| 'emailAddress';\n\n/**\n * Convenience object form of an X.501 distinguished name.\n *\n * Populated fields are emitted in the order defined by\n * `NAME_OBJECT_ORDER`.\\\n * Each populated field becomes its own single-attribute RDN.\n *\n * For caller-controlled ordering, pass a {@linkcode NameAttribute} array to {@linkcode encodeName}.\\\n * For multi-valued RDNs, use {@linkcode encodeRelativeDistinguishedName}.\n */\nexport interface NameObject {\n\t/** Subject or issuer common name (CN). */\n\treadonly commonName?: string;\n\t/** Subject surname (SN). */\n\treadonly surname?: string;\n\t/** Device or entity serial number — not the certificate serial. */\n\treadonly serialNumber?: string;\n\t/** ISO 3166 two-letter country code (C). Must be exactly 2 characters. */\n\treadonly country?: string;\n\t/** City or locality (L). */\n\treadonly locality?: string;\n\t/** State or province (ST). */\n\treadonly state?: string;\n\t/** Street address. */\n\treadonly street?: string;\n\t/** Organization name (O). */\n\treadonly organization?: string;\n\t/** Organizational unit (OU). Deprecated in modern CA practice. */\n\treadonly organizationalUnit?: string;\n\t/** Job title or functional designation. */\n\treadonly title?: string;\n\t/** First / given name (GN). */\n\treadonly givenName?: string;\n\t/** PKCS #9 emailAddress attribute (RFC 2985 §5.2.1). Encoded as IA5String, not UTF-8. RFC 5280 §4.1.2.6 deprecates it in favour of a subjectAltName rfc822Name. */\n\treadonly emailAddress?: string;\n}\n\n/**\n * Single name attribute within a distinguished name.\n *\n * RFC 5280 / X.501 call this structure an `AttributeTypeAndValue`.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1 RFC 5280 Appendix A.1}\n * {@linkcode encodeName} places each attribute in its own single-attribute RDN.\\\n * {@linkcode encodeRelativeDistinguishedName} packs several attributes into one RDN.\n */\nexport interface NameAttribute {\n\t/** Which attribute type this pair represents. */\n\treadonly type: NameFieldKey;\n\t/** The string value for this attribute (encoding chosen per field definition). */\n\treadonly value: string;\n}\n\n/**\n * Input for {@linkcode encodeName}.\n *\n * Accepts either a {@linkcode NameObject} convenience shape or an ordered array of {@linkcode NameAttribute} pairs.\\\n * Both forms encode one attribute per RDN.\n */\nexport type NameInput = NameObject | readonly NameAttribute[];\n\n/**\n * Input for {@linkcode encodeRelativeDistinguishedName}.\n *\n * Each entry becomes one name attribute inside the RDN's `SET OF`.\\\n * Use this shape for multi-valued RDNs.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1 RFC 5280 Appendix A.1}\n */\nexport type RelativeDistinguishedNameInput = readonly NameAttribute[];\n\nexport { nameFieldKeyFromOid } from '#micro509/internal/x509/name-fields';\n\n/**\n * DER-encodes an X.509 `Name`.\n *\n * Returns a DER `SEQUENCE` of RelativeDistinguishedNames (RDNs).\\\n * Each RDN emitted by this helper contains exactly one name attribute.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1 RFC 5280 Appendix A.1}\n *\n * {@linkcode NameObject} input emits populated fields in the canonical order from `NAME_OBJECT_ORDER`.\\\n * {@linkcode NameAttribute} array input preserves caller-supplied ordering,\n * but each entry still becomes its own single-attribute RDN.\n *\n * Attribute OIDs and ASN.1 string encodings come from `NAME_FIELD_DEFINITIONS`.\\\n * Empty strings and `undefined` fields are ignored when the input is a {@linkcode NameObject}.\n *\n * @example\n * ```ts\n * const der = encodeName({ country: 'US', commonName: 'example.com' });\n *\n * // emits two single-attribute RDNs: C=US, then CN=example.com\n * ```\n *\n * @example\n * ```ts\n * const der = encodeName([\n * \t{ type: 'country', value: 'US' },\n * \t{ type: 'commonName', value: 'example.com' },\n * ]);\n *\n * // preserves caller order: C first, then CN\n * ```\n *\n * @param input Name fields in convenience-object form or caller-ordered attribute form.\n * @returns DER-encoded X.509 `Name` bytes.\n * @throws {ResultError} If a value exceeds its RFC 5280 A.1 bound, an ordered attribute value is empty, a field key is unsupported, or a country code is not two characters. An input with no attributes encodes an empty Name (`30 00`) rather than throwing.\n */\nexport function encodeName(input: NameInput): Uint8Array {\n\tconst attributes = isNameAttributes(input) ? input : nameObjectToAttributes(input);\n\tif (attributes.length === 0) {\n\t\treturn sequence([]);\n\t}\n\n\treturn sequence(attributes.map(encodeNameAttributeAsSet));\n}\n\n/** True when a {@linkcode NameInput} resolves to zero attributes (empty DN). */\nexport function isNameInputEmpty(input: NameInput): boolean {\n\tconst attributes = isNameAttributes(input) ? input : nameObjectToAttributes(input);\n\treturn attributes.length === 0;\n}\n\n/**\n * DER-encodes a single RelativeDistinguishedName (RDN).\n *\n * Returns a DER `SET OF` name attributes for one X.509 name segment.\\\n * Use this when you need a multi-valued RDN.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1 RFC 5280 Appendix A.1}\n *\n * Attribute OIDs and ASN.1 string encodings come from\n * `NAME_FIELD_DEFINITIONS`.\n *\n * @example\n * ```ts\n * const rdn = encodeRelativeDistinguishedName([\n * \t{ type: 'commonName', value: 'example.com' },\n * \t{ type: 'serialNumber', value: 'device-7' },\n * ]);\n *\n * // emits one RDN with both attributes in the same SET\n * ```\n *\n * @param attributes Attribute list to encode inside one RDN.\n * @returns DER-encoded RelativeDistinguishedName bytes.\n * @throws {ResultError} If the attribute list is empty, contains an unsupported field key, an empty or over-long value, or an invalid country code.\n */\nexport function encodeRelativeDistinguishedName(\n\tattributes: RelativeDistinguishedNameInput,\n): Uint8Array {\n\tif (attributes.length === 0) {\n\t\tthrowNameEncoderError(\n\t\t\t'relative_distinguished_name_empty',\n\t\t\t'Relative distinguished name must contain at least one attribute',\n\t\t);\n\t}\n\treturn setOf(attributes.map(encodeNameAttribute));\n}\n\n/** Narrows a {@linkcode NameInput} to the ordered-attribute-array form. */\nfunction isNameAttributes(input: NameInput): input is readonly NameAttribute[] {\n\treturn Array.isArray(input);\n}\n\n/** Wraps a single attribute in a SET OF for the Name SEQUENCE. */\nfunction encodeNameAttributeAsSet(attribute: NameAttribute): Uint8Array {\n\treturn setOf([encodeNameAttribute(attribute)]);\n}\n\n/**\n * DER-encodes one name attribute SEQUENCE.\n *\n * Throws for unsupported field keys, empty or over-long values, and invalid country codes.\n */\nfunction encodeNameAttribute(attribute: NameAttribute): Uint8Array {\n\tconst definition = NAME_FIELD_DEFINITIONS[attribute.type];\n\tif (definition === undefined) {\n\t\tthrowNameEncoderError('unsupported_name_field', `Unsupported name field: ${attribute.type}`);\n\t}\n\tconst length = [...attribute.value].length;\n\tif (length === 0) {\n\t\tthrowNameEncoderError(\n\t\t\t'name_attribute_empty',\n\t\t\t`Name attribute ${attribute.type} must not be empty`,\n\t\t);\n\t}\n\tif (attribute.type === 'country' && attribute.value.length !== 2) {\n\t\tthrowNameEncoderError('invalid_country_code', 'Country must be a 2-character code');\n\t}\n\tif (definition.maxLength !== undefined && length > definition.maxLength) {\n\t\tthrowNameEncoderError(\n\t\t\t'name_attribute_too_long',\n\t\t\t`Name attribute ${attribute.type} must be at most ${definition.maxLength} characters`,\n\t\t);\n\t}\n\treturn sequence([objectIdentifier(definition.oid), definition.encode(attribute.value)]);\n}\n\n/** Converts a {@linkcode NameObject} to ordered attributes per `NAME_OBJECT_ORDER`. */\nfunction nameObjectToAttributes(input: NameObject): readonly NameAttribute[] {\n\tconst attributes: NameAttribute[] = [];\n\tfor (const key of NAME_OBJECT_ORDER) {\n\t\tconst value = input[key];\n\t\tif (typeof value === 'string' && value.length > 0) {\n\t\t\tattributes.push({ type: key, value });\n\t\t}\n\t}\n\treturn attributes;\n}\n\nexport {\n\tcanonicalDnKey,\n\tcompareDistinguishedNames,\n\tisWithinDirectoryNameSubtree,\n} from '#micro509/internal/shared/dn';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAS,sBAAsB,GAA4B,GAAwB;CAClF,EAAmB,GAAM,CAAO;AACjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkIA,SAAgB,WAAW,GAA8B;CACxD,IAAM,IAAa,iBAAiB,CAAK,IAAI,IAAQ,uBAAuB,CAAK;CAKjF,OAJI,EAAW,WAAW,IAClB,EAAS,CAAC,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