micro509 0.14.0 → 0.15.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 (161) hide show
  1. package/CHANGELOG.md +2064 -0
  2. package/README.md +105 -225
  3. package/dist/crypto/crypto.d.ts +42 -11
  4. package/dist/crypto/crypto.js +53 -22
  5. package/dist/crypto/crypto.js.map +1 -1
  6. package/dist/crypto.d.ts +2 -2
  7. package/dist/crypto.js +1 -2
  8. package/dist/der/der.d.ts +41 -33
  9. package/dist/der/der.js +26 -24
  10. package/dist/der/der.js.map +1 -1
  11. package/dist/index.d.ts +10 -10
  12. package/dist/index.js +19 -19
  13. package/dist/internal/asn1/asn1.d.ts +3 -6
  14. package/dist/internal/asn1/asn1.js +343 -43
  15. package/dist/internal/asn1/asn1.js.map +1 -1
  16. package/dist/internal/asn1/ber.js +146 -0
  17. package/dist/internal/asn1/ber.js.map +1 -0
  18. package/dist/internal/asn1/decode-refusal.js +29 -0
  19. package/dist/internal/asn1/decode-refusal.js.map +1 -0
  20. package/dist/internal/asn1/der.d.ts +38 -41
  21. package/dist/internal/asn1/der.js +131 -52
  22. package/dist/internal/asn1/der.js.map +1 -1
  23. package/dist/internal/asn1/oids.js +83 -53
  24. package/dist/internal/asn1/oids.js.map +1 -1
  25. package/dist/internal/asn1/oids2.js +1 -2
  26. package/dist/internal/asn1/oids2.js.map +1 -1
  27. package/dist/internal/crypto/algorithm-names.js +1 -2
  28. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  29. package/dist/internal/crypto/ecdsa.js +13 -8
  30. package/dist/internal/crypto/ecdsa.js.map +1 -1
  31. package/dist/internal/crypto/hash.js +1 -2
  32. package/dist/internal/crypto/hash.js.map +1 -1
  33. package/dist/internal/crypto/pbes2.d.ts +24 -11
  34. package/dist/internal/crypto/pbes2.js +79 -26
  35. package/dist/internal/crypto/pbes2.js.map +1 -1
  36. package/dist/internal/crypto/rsa-pss.js +46 -44
  37. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  38. package/dist/internal/crypto/sig-verify.d.ts +4 -7
  39. package/dist/internal/crypto/sig-verify.js +107 -60
  40. package/dist/internal/crypto/sig-verify.js.map +1 -1
  41. package/dist/internal/crypto/signing.d.ts +1 -4
  42. package/dist/internal/crypto/signing.js +28 -29
  43. package/dist/internal/crypto/signing.js.map +1 -1
  44. package/dist/internal/crypto/webcrypto.js +1 -2
  45. package/dist/internal/crypto/webcrypto.js.map +1 -1
  46. package/dist/internal/shared/base64.js +1 -2
  47. package/dist/internal/shared/base64.js.map +1 -1
  48. package/dist/internal/shared/dn.d.ts +3 -6
  49. package/dist/internal/shared/dn.js +99 -53
  50. package/dist/internal/shared/dn.js.map +1 -1
  51. package/dist/internal/shared/idna-tables.js +7217 -0
  52. package/dist/internal/shared/idna-tables.js.map +1 -0
  53. package/dist/internal/shared/idna.js +296 -0
  54. package/dist/internal/shared/idna.js.map +1 -0
  55. package/dist/internal/shared/ip.d.ts +4 -7
  56. package/dist/internal/shared/ip.js +1 -2
  57. package/dist/internal/shared/ip.js.map +1 -1
  58. package/dist/internal/shared/mailbox.js +26 -0
  59. package/dist/internal/shared/mailbox.js.map +1 -0
  60. package/dist/internal/shared/punycode.js +101 -0
  61. package/dist/internal/shared/punycode.js.map +1 -0
  62. package/dist/internal/shared/rfc3454-tables.js +1 -2
  63. package/dist/internal/shared/rfc3454-tables.js.map +1 -1
  64. package/dist/internal/shared/rfc4518-tables.js +119 -0
  65. package/dist/internal/shared/rfc4518-tables.js.map +1 -0
  66. package/dist/internal/shared/uri-host.js +102 -0
  67. package/dist/internal/shared/uri-host.js.map +1 -0
  68. package/dist/internal/verify/name-constraints-engine.js +246 -131
  69. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  70. package/dist/internal/verify/policy-engine.js +6 -21
  71. package/dist/internal/verify/policy-engine.js.map +1 -1
  72. package/dist/internal/verify/verify-path.d.ts +1 -4
  73. package/dist/internal/verify/verify-path.js +267 -131
  74. package/dist/internal/verify/verify-path.js.map +1 -1
  75. package/dist/internal/x509/directory-name.js +1 -2
  76. package/dist/internal/x509/directory-name.js.map +1 -1
  77. package/dist/internal/x509/extension-bits.js +2 -3
  78. package/dist/internal/x509/extension-bits.js.map +1 -1
  79. package/dist/internal/x509/extension-errors.d.ts +1 -4
  80. package/dist/internal/x509/extension-errors.js +1 -2
  81. package/dist/internal/x509/extension-errors.js.map +1 -1
  82. package/dist/internal/x509/extension-registry.js +107 -89
  83. package/dist/internal/x509/extension-registry.js.map +1 -1
  84. package/dist/internal/x509/general-name-profile.js +129 -0
  85. package/dist/internal/x509/general-name-profile.js.map +1 -0
  86. package/dist/internal/x509/general-name-tags.js +1 -2
  87. package/dist/internal/x509/general-name-tags.js.map +1 -1
  88. package/dist/internal/x509/general-name.js +128 -42
  89. package/dist/internal/x509/general-name.js.map +1 -1
  90. package/dist/internal/x509/name-fields.js +1 -2
  91. package/dist/internal/x509/name-fields.js.map +1 -1
  92. package/dist/internal/x509/or-address.js +217 -0
  93. package/dist/internal/x509/or-address.js.map +1 -0
  94. package/dist/keys/keys.d.ts +112 -97
  95. package/dist/keys/keys.js +211 -204
  96. package/dist/keys/keys.js.map +1 -1
  97. package/dist/keys.d.ts +3 -3
  98. package/dist/pem/pem.d.ts +14 -17
  99. package/dist/pem/pem.js +16 -17
  100. package/dist/pem/pem.js.map +1 -1
  101. package/dist/pem.js +1 -2
  102. package/dist/pkcs/pfx.d.ts +57 -32
  103. package/dist/pkcs/pfx.js +209 -173
  104. package/dist/pkcs/pfx.js.map +1 -1
  105. package/dist/pkcs/pkcs12-mac.d.ts +104 -27
  106. package/dist/pkcs/pkcs12-mac.js +266 -79
  107. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  108. package/dist/pkcs/pkcs7.d.ts +43 -37
  109. package/dist/pkcs/pkcs7.js +218 -217
  110. package/dist/pkcs/pkcs7.js.map +1 -1
  111. package/dist/pkcs.d.ts +4 -3
  112. package/dist/result/result.d.ts +27 -20
  113. package/dist/result/result.js +8 -3
  114. package/dist/result/result.js.map +1 -1
  115. package/dist/result.d.ts +2 -2
  116. package/dist/result.js +1 -2
  117. package/dist/revocation/chain.d.ts +101 -23
  118. package/dist/revocation/chain.js +436 -182
  119. package/dist/revocation/chain.js.map +1 -1
  120. package/dist/revocation/crl.d.ts +131 -67
  121. package/dist/revocation/crl.js +444 -323
  122. package/dist/revocation/crl.js.map +1 -1
  123. package/dist/revocation/ocsp.d.ts +94 -59
  124. package/dist/revocation/ocsp.js +331 -293
  125. package/dist/revocation/ocsp.js.map +1 -1
  126. package/dist/revocation/revocation.d.ts +47 -35
  127. package/dist/revocation/revocation.js +88 -57
  128. package/dist/revocation/revocation.js.map +1 -1
  129. package/dist/revocation.d.ts +3 -3
  130. package/dist/verify/identity.d.ts +16 -19
  131. package/dist/verify/identity.js +118 -89
  132. package/dist/verify/identity.js.map +1 -1
  133. package/dist/verify/name-constraints.d.ts +1 -4
  134. package/dist/verify/policy.d.ts +9 -7
  135. package/dist/verify/verify.d.ts +84 -46
  136. package/dist/verify/verify.js +300 -152
  137. package/dist/verify/verify.js.map +1 -1
  138. package/dist/verify.d.ts +2 -2
  139. package/dist/x509/certificate.d.ts +20 -21
  140. package/dist/x509/certificate.js +62 -46
  141. package/dist/x509/certificate.js.map +1 -1
  142. package/dist/x509/csr.d.ts +5 -7
  143. package/dist/x509/csr.js +10 -11
  144. package/dist/x509/csr.js.map +1 -1
  145. package/dist/x509/extensions.d.ts +154 -66
  146. package/dist/x509/extensions.js +317 -151
  147. package/dist/x509/extensions.js.map +1 -1
  148. package/dist/x509/fingerprint.d.ts +4 -7
  149. package/dist/x509/fingerprint.js +1 -2
  150. package/dist/x509/fingerprint.js.map +1 -1
  151. package/dist/x509/name-text.d.ts +7 -9
  152. package/dist/x509/name-text.js +18 -4
  153. package/dist/x509/name-text.js.map +1 -1
  154. package/dist/x509/name.d.ts +9 -11
  155. package/dist/x509/name.js +18 -19
  156. package/dist/x509/name.js.map +1 -1
  157. package/dist/x509/parse.d.ts +84 -69
  158. package/dist/x509/parse.js +421 -400
  159. package/dist/x509/parse.js.map +1 -1
  160. package/dist/x509.d.ts +2 -2
  161. package/package.json +76 -59
@@ -4,17 +4,17 @@ import { canonicalDnKey, compareDistinguishedNames, isWithinDirectoryNameSubtree
4
4
  import { NameAttribute, NameEncoderErrorCode, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName } from "./name.js";
5
5
  import { ExtensionEncoderErrorCode } from "../internal/x509/extension-errors.js";
6
6
  import { allOnesMaskForIpAddress, decodeIpAddress, normalizeIpAddress, parseIpAddressToBytes } from "../internal/shared/ip.js";
7
- import { AuthorityInfoAccessMethod, AuthorityInformationAccess, AuthorityInformationAccessInput, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, CpsPolicyQualifierInfo, CustomAuthorityInfoAccessMethod, CustomExtendedKeyUsage, CustomExtension, CustomPolicyQualifierInfo, DistributionPoint, DistributionPointName, DistributionPointReason, ExtendedKeyUsage, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, KnownAuthorityInfoAccessMethod, KnownExtendedKeyUsage, NameConstraintForm, NameConstraints, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyNoticeReference, PolicyQualifierInfo, SubjectAltName, UnsupportedNameConstraintForm, UserNoticePolicyQualifierInfo, buildCertificateExtensions, buildRequestedExtensions, buildSubjectKeyIdentifier, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid } from "./extensions.js";
8
- //#region src/x509/certificate.d.ts
7
+ import { AuthorityInfoAccessMethod, AuthorityInformationAccess, AuthorityInformationAccessInput, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, CpsPolicyQualifierInfo, CustomAuthorityInfoAccessMethod, CustomExtendedKeyUsage, CustomExtension, CustomPolicyQualifierInfo, DisplayTextType, DistributionPoint, DistributionPointName, DistributionPointReason, ExtendedKeyUsage, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, KnownAuthorityInfoAccessMethod, KnownExtendedKeyUsage, NameConstraintForm, NameConstraints, OversizedDisplayText, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyNoticeReference, PolicyQualifierInfo, SubjectAltName, UnsupportedNameConstraintForm, UserNoticePolicyQualifierInfo, buildCertificateExtensions, buildRequestedExtensions, buildSubjectKeyIdentifier, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid } from "./extensions.js";
8
+ import { ParsedCertificate } from "./parse.js";
9
9
  /** Machine-readable reason a certificate builder rejected its construction input. */
10
- type CreateCertificateErrorCode = "issuer_distinguished_name_empty" | "serial_number_not_positive" | "serial_number_too_long" | "validity_not_after_before_not_before";
10
+ export type CreateCertificateErrorCode = "issuer_certificate_invalid" | "issuer_distinguished_name_empty" | "serial_number_not_positive" | "serial_number_too_long" | "validity_date_invalid" | "validity_not_after_before_not_before";
11
11
  /**
12
12
  * Configures the certificate validity window.
13
13
  *
14
14
  * If `notAfter` is omitted, it is derived from `notBefore` plus `days`. If both
15
15
  * `notAfter` and `days` are omitted, the certificate is valid for 30 days.
16
16
  */
17
- interface ValidityInput {
17
+ export interface ValidityInput {
18
18
  /**
19
19
  * Start of the validity window.
20
20
  *
@@ -35,7 +35,7 @@ interface ValidityInput {
35
35
  /**
36
36
  * Input for {@linkcode createCertificate}.
37
37
  */
38
- interface CreateCertificateInput {
38
+ export interface CreateCertificateInput {
39
39
  /**
40
40
  * Issuer distinguished name.
41
41
  */
@@ -53,12 +53,12 @@ interface CreateCertificateInput {
53
53
  */
54
54
  readonly signerPrivateKey: CryptoKey;
55
55
  /**
56
- * Issuer public key.
57
- *
58
- * Provide this when extension builders need issuer key material, such as
59
- * authority key identifier derivation.
56
+ * Certificate of the issuer. Its subject key identifier becomes the
57
+ * authority key identifier (RFC 5280 §4.2.1.1, §4.2.1.2). An issuer
58
+ * certificate without one yields a key identifier derived from its public
59
+ * key. Omit it to leave the authority key identifier out.
60
60
  */
61
- readonly issuerPublicKey?: CryptoKey;
61
+ readonly issuerCertificate?: string | Uint8Array | ParsedCertificate;
62
62
  /**
63
63
  * Validity window configuration.
64
64
  */
@@ -85,13 +85,13 @@ interface CreateCertificateInput {
85
85
  /**
86
86
  * Input for {@linkcode createSelfSignedCertificate}.
87
87
  */
88
- type CreateSelfSignedCertificateInput = CreateSelfSignedCertificateBase & SelfSignedKeySource;
88
+ export type CreateSelfSignedCertificateInput = CreateSelfSignedCertificateBase & SelfSignedKeySource;
89
89
  /**
90
90
  * Where {@linkcode createSelfSignedCertificate} gets its key pair.
91
91
  *
92
92
  * Supplying `keyPair` makes `algorithm` unreachable, since generation is skipped.
93
93
  */
94
- type SelfSignedKeySource = {
94
+ export type SelfSignedKeySource = {
95
95
  /**
96
96
  * Existing key pair to reuse for both subject and issuer.
97
97
  */
@@ -111,7 +111,7 @@ type SelfSignedKeySource = {
111
111
  readonly algorithm?: KeyAlgorithmInput;
112
112
  };
113
113
  /** Fields common to both {@linkcode SelfSignedKeySource} variants. */
114
- interface CreateSelfSignedCertificateBase {
114
+ export interface CreateSelfSignedCertificateBase {
115
115
  /**
116
116
  * Subject distinguished name used as both subject and issuer.
117
117
  */
@@ -139,7 +139,7 @@ interface CreateSelfSignedCertificateBase {
139
139
  /**
140
140
  * Encoded certificate material in common interchange formats.
141
141
  */
142
- interface CertificateMaterial {
142
+ export interface CertificateMaterial {
143
143
  /**
144
144
  * DER-encoded certificate bytes.
145
145
  */
@@ -156,7 +156,7 @@ interface CertificateMaterial {
156
156
  /**
157
157
  * Result returned by {@linkcode createSelfSignedCertificate}.
158
158
  */
159
- interface SelfSignedCertificateResult {
159
+ export interface SelfSignedCertificateResult {
160
160
  /**
161
161
  * Encoded certificate outputs.
162
162
  */
@@ -184,7 +184,7 @@ interface SelfSignedCertificateResult {
184
184
  * @param input Certificate subject, key, validity, and extension settings.
185
185
  * @returns The certificate plus the key pair used to sign it.
186
186
  */
187
- declare function createSelfSignedCertificate(input: CreateSelfSignedCertificateInput): Promise<SelfSignedCertificateResult>;
187
+ export declare function createSelfSignedCertificate(input: CreateSelfSignedCertificateInput): Promise<SelfSignedCertificateResult>;
188
188
  /**
189
189
  * Create an X.509 certificate signed by `input.signerPrivateKey`.
190
190
  *
@@ -199,15 +199,14 @@ declare function createSelfSignedCertificate(input: CreateSelfSignedCertificateI
199
199
  * issuer: { commonName: 'Example Root CA' },
200
200
  * subject: { commonName: 'example.com' },
201
201
  * publicKey: leafKeys.publicKey,
202
- * signerPrivateKey: issuerKeys.privateKey,
203
- * issuerPublicKey: issuerKeys.publicKey,
202
+ * signerPrivateKey: issuer.keyPair.privateKey,
203
+ * issuerCertificate: issuer.certificate.der,
204
204
  * });
205
205
  * ```
206
206
  *
207
207
  * @param input Issuer, subject, key, validity, and extension settings.
208
208
  * @returns The encoded certificate material.
209
209
  */
210
- declare function createCertificate(input: CreateCertificateInput): Promise<CertificateMaterial>;
211
- //#endregion
212
- export { type AuthorityInfoAccessMethod, type AuthorityInformationAccess, type AuthorityInformationAccessInput, type BasicConstraints, type CertificateExtensionsInput, CertificateMaterial, type CertificatePolicies, type CpsPolicyQualifierInfo, CreateCertificateErrorCode, CreateCertificateInput, CreateSelfSignedCertificateBase, CreateSelfSignedCertificateInput, type CustomAuthorityInfoAccessMethod, type CustomExtendedKeyUsage, type CustomExtension, type CustomPolicyQualifierInfo, type DistributionPoint, type DistributionPointName, type DistributionPointReason, type ExtendedKeyUsage, type ExtensionEncoderErrorCode, type GeneralName, type GeneralSubtree, type InhibitAnyPolicy, type IssuingDistributionPoint, type IssuingDistributionPointBase, type IssuingDistributionPointForAttributeCerts, type IssuingDistributionPointForCaCerts, type IssuingDistributionPointForUserCerts, type KeyUsage, type KnownAuthorityInfoAccessMethod, type KnownExtendedKeyUsage, type NameConstraintForm, type NameConstraints, type NameEncoderErrorCode, type NameInput, type NameObject, type ParsedBitFlags, type ParsedNameConstraintForm, type PolicyConstraints, type PolicyInformation, type PolicyMapping, type PolicyMappings, type PolicyNoticeReference, type PolicyQualifierInfo, SelfSignedCertificateResult, SelfSignedKeySource, type SignatureProfileInput, type SubjectAltName, type UnsupportedNameConstraintForm, type UserNoticePolicyQualifierInfo, ValidityInput, type allOnesMaskForIpAddress, type buildCertificateExtensions, type buildRequestedExtensions, type buildSubjectKeyIdentifier, type canonicalDnKey, type compareDistinguishedNames, createCertificate, createSelfSignedCertificate, type decodeIpAddress, type encodeAuthorityInfoAccess, type encodeBasicConstraints, type encodeCertificatePolicies, type encodeCrlDistributionPoints, type encodeExtendedKeyUsage, type encodeExtension, type encodeInhibitAnyPolicy, type encodeKeyUsage, type encodeName, type encodeNameConstraints, type encodePolicyConstraints, type encodePolicyMappings, type encodeRelativeDistinguishedName, type encodeSubjectAltName, type getAuthorityInfoAccessMethodOid, type getExtendedKeyUsageOid, type isWithinDirectoryNameSubtree, type normalizeIpAddress, type parseAuthorityInfoAccessMethodOid, type parseExtendedKeyUsageOid, type parseIpAddressToBytes };
210
+ export declare function createCertificate(input: CreateCertificateInput): Promise<CertificateMaterial>;
211
+ export type { AuthorityInfoAccessMethod, AuthorityInformationAccess, AuthorityInformationAccessInput, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, CpsPolicyQualifierInfo, CustomAuthorityInfoAccessMethod, CustomExtendedKeyUsage, CustomExtension, CustomPolicyQualifierInfo, DisplayTextType, DistributionPoint, DistributionPointName, DistributionPointReason, ExtendedKeyUsage, ExtensionEncoderErrorCode, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, KnownAuthorityInfoAccessMethod, KnownExtendedKeyUsage, NameConstraintForm, NameConstraints, NameEncoderErrorCode, NameInput, NameObject, OversizedDisplayText, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyNoticeReference, PolicyQualifierInfo, SignatureProfileInput, SubjectAltName, UnsupportedNameConstraintForm, UserNoticePolicyQualifierInfo, allOnesMaskForIpAddress, buildCertificateExtensions, buildRequestedExtensions, buildSubjectKeyIdentifier, canonicalDnKey, compareDistinguishedNames, decodeIpAddress, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeName, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeRelativeDistinguishedName, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, isWithinDirectoryNameSubtree, normalizeIpAddress, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid, parseIpAddressToBytes };
213
212
  //# sourceMappingURL=certificate.d.ts.map
@@ -1,13 +1,15 @@
1
- import { bitString as e, explicitContext as t, integer as n, integerFromNumber as r, sequence as i, time as a } from "../internal/asn1/der.js";
2
- import { getCrypto as o } from "../internal/crypto/webcrypto.js";
3
- import { base64Encode as s } from "../internal/shared/base64.js";
4
- import { throwMicro509Error as c } from "../result/result.js";
5
- import { pemEncode as l } from "../pem/pem.js";
6
- import { exportSpkiDer as u, generateKeyPair as d } from "../keys/keys.js";
7
- import { encodeName as f, isNameInputEmpty as p } from "./name.js";
8
- import { buildCertificateExtensions as m } from "./extensions.js";
9
- import { encodeAlgorithmIdentifier as h, getSignatureAlgorithm as g, signBytes as _ } from "../internal/crypto/signing.js";
10
- //#region src/x509/certificate.ts
1
+ import { DECODE_REFUSAL_CODES as e, throwMicro509Error as t } from "../result/result.js";
2
+ import { rethrowDecodeRefusal as n } from "../internal/asn1/decode-refusal.js";
3
+ import { bitString as r, explicitContext as i, integer as a, integerFromNumber as o, sequence as s, time as c } from "../internal/asn1/der.js";
4
+ import { getCrypto as l } from "../internal/crypto/webcrypto.js";
5
+ import { base64Encode as u } from "../internal/shared/base64.js";
6
+ import { pemEncode as d } from "../pem/pem.js";
7
+ import { exportSpkiDer as f, generateKeyPair as p } from "../keys/keys.js";
8
+ import { encodeAlgorithmIdentifier as m, getSignatureAlgorithm as h, signBytes as g } from "../internal/crypto/signing.js";
9
+ import { encodeName as _, isNameInputEmpty as v } from "./name.js";
10
+ import { buildCertificateExtensions as y, buildSubjectKeyIdentifier as b, issuerKeyIdentifier as x } from "./extensions.js";
11
+ import { parseCertificateFromSource as S } from "./parse.js";
12
+ // src/x509/certificate.ts
11
13
  /**
12
14
  * Create X.509 certificates from typed names, extensions, and WebCrypto keys.
13
15
  *
@@ -35,19 +37,18 @@ import { encodeAlgorithmIdentifier as h, getSignatureAlgorithm as g, signBytes a
35
37
  * @returns The certificate plus the key pair used to sign it.
36
38
  */
37
39
  async function createSelfSignedCertificate(e) {
38
- let t = e.keyPair ?? await d(e.algorithm);
40
+ let t = e.keyPair ?? await p(e.algorithm);
39
41
  return {
40
- certificate: await createCertificate({
42
+ certificate: await issueCertificate({
41
43
  issuer: e.subject,
42
44
  subject: e.subject,
43
45
  publicKey: t.publicKey,
44
46
  signerPrivateKey: t.privateKey,
45
- issuerPublicKey: t.publicKey,
46
47
  ...e.validity === void 0 ? {} : { validity: e.validity },
47
48
  ...e.serialNumber === void 0 ? {} : { serialNumber: e.serialNumber },
48
49
  ...e.extensions === void 0 ? {} : { extensions: e.extensions },
49
50
  ...e.signature === void 0 ? {} : { signature: e.signature }
50
- }),
51
+ }, "subject"),
51
52
  keyPair: t
52
53
  };
53
54
  }
@@ -65,33 +66,49 @@ async function createSelfSignedCertificate(e) {
65
66
  * issuer: { commonName: 'Example Root CA' },
66
67
  * subject: { commonName: 'example.com' },
67
68
  * publicKey: leafKeys.publicKey,
68
- * signerPrivateKey: issuerKeys.privateKey,
69
- * issuerPublicKey: issuerKeys.publicKey,
69
+ * signerPrivateKey: issuer.keyPair.privateKey,
70
+ * issuerCertificate: issuer.certificate.der,
70
71
  * });
71
72
  * ```
72
73
  *
73
74
  * @param input Issuer, subject, key, validity, and extension settings.
74
75
  * @returns The encoded certificate material.
75
76
  */
76
- async function createCertificate(n) {
77
- let o = await u(n.publicKey), s = n.issuerPublicKey ? await u(n.issuerPublicKey) : void 0, l = g(n.signerPrivateKey, n.signature), d = resolveValidity(n.validity);
78
- p(n.issuer) && c("issuer_distinguished_name_empty", "issuer must be a non-empty distinguished name");
79
- let v = p(n.subject), y = m(o, s, n.extensions, v), b = i([
80
- t(0, r(2)),
81
- encodeSerialNumber(n.serialNumber),
82
- h(l),
83
- f(n.issuer),
84
- i([a(d.notBefore), a(d.notAfter)]),
85
- f(n.subject),
86
- o,
87
- t(3, i(y))
88
- ]), x = await _(n.signerPrivateKey, l, b);
89
- return materializeCertificate(i([
90
- b,
91
- h(l),
92
- e(x)
77
+ function createCertificate(e) {
78
+ return issueCertificate(e, "issuer");
79
+ }
80
+ /**
81
+ * Signs a certificate whose authority key identifier comes from
82
+ * `input.issuerCertificate`, or from its own subject key when `authority` is
83
+ * `'subject'` (RFC 5280 §4.2.1.1).
84
+ */
85
+ async function issueCertificate(e, n) {
86
+ let a = await f(e.publicKey), l = n === "subject" ? b(a) : e.issuerCertificate === void 0 ? void 0 : x(issuerCertificateOf(e.issuerCertificate)), u = h(e.signerPrivateKey, e.signature), d = resolveValidity(e.validity);
87
+ v(e.issuer) && t("issuer_distinguished_name_empty", "issuer must be a non-empty distinguished name");
88
+ let p = v(e.subject), S = y(a, l, e.extensions, p), C = s([
89
+ i(0, o(2)),
90
+ encodeSerialNumber(e.serialNumber),
91
+ m(u),
92
+ _(e.issuer),
93
+ s([c(d.notBefore), c(d.notAfter)]),
94
+ _(e.subject),
95
+ a,
96
+ i(3, s(S))
97
+ ]), w = await g(e.signerPrivateKey, u, C);
98
+ return materializeCertificate(s([
99
+ C,
100
+ m(u),
101
+ r(w)
93
102
  ]));
94
103
  }
104
+ /** The parsed issuer certificate of a certificate being built. */
105
+ function issuerCertificateOf(r) {
106
+ try {
107
+ return S(r);
108
+ } catch (r) {
109
+ return n(r, e), t("issuer_certificate_invalid", "issuerCertificate must be a PEM, DER or parsed certificate");
110
+ }
111
+ }
95
112
  /**
96
113
  * Convert DER bytes into all exported certificate encodings.
97
114
  *
@@ -101,8 +118,8 @@ async function createCertificate(n) {
101
118
  function materializeCertificate(e) {
102
119
  return {
103
120
  der: e,
104
- pem: l("CERTIFICATE", e),
105
- base64: s(e)
121
+ pem: d("CERTIFICATE", e),
122
+ base64: u(e)
106
123
  };
107
124
  }
108
125
  /**
@@ -112,10 +129,10 @@ function materializeCertificate(e) {
112
129
  * @returns A concrete `notBefore` and `notAfter` pair.
113
130
  */
114
131
  function resolveValidity(e) {
115
- let t = e?.notBefore ?? /* @__PURE__ */ new Date(), n = e?.notAfter ?? addDays(t, e?.days ?? 30);
116
- return n.getTime() <= t.getTime() && c("validity_not_after_before_not_before", "notAfter must be after notBefore"), {
117
- notBefore: t,
118
- notAfter: n
132
+ let n = e?.notBefore ?? /* @__PURE__ */ new Date(), r = e?.notAfter ?? addDays(n, e?.days ?? 30);
133
+ return (Number.isNaN(n.getTime()) || Number.isNaN(r.getTime())) && t("validity_date_invalid", "notBefore and notAfter must be valid dates"), r.getTime() <= n.getTime() && t("validity_not_after_before_not_before", "notAfter must be after notBefore"), {
134
+ notBefore: n,
135
+ notAfter: r
119
136
  };
120
137
  }
121
138
  /**
@@ -138,11 +155,11 @@ function addDays(e, t) {
138
155
  * `serial_number_too_long` when RFC 5280 §4.1.2.2 forbids the value.
139
156
  */
140
157
  function encodeSerialNumber(e) {
141
- if (e === void 0) return n(randomSerialNumber());
142
- let t = 0;
143
- for (; t < e.length && e[t] === 0;) t += 1;
144
- let r = e.subarray(t), i = r[0];
145
- return i === void 0 && c("serial_number_not_positive", "serialNumber must be a positive integer"), r.length + +(i >= 128) > 20 && c("serial_number_too_long", "serialNumber must not exceed 20 octets"), n(r);
158
+ if (e === void 0) return a(randomSerialNumber());
159
+ let n = 0;
160
+ for (; n < e.length && e[n] === 0;) n += 1;
161
+ let r = e.subarray(n), i = r[0];
162
+ return i === void 0 && t("serial_number_not_positive", "serialNumber must be a positive integer"), r.length + +(i >= 128) > 20 && t("serial_number_too_long", "serialNumber must not exceed 20 octets"), a(r);
146
163
  }
147
164
  /**
148
165
  * Generate a random positive serial number suitable for certificate issuance.
@@ -150,10 +167,9 @@ function encodeSerialNumber(e) {
150
167
  * @returns A 16-byte positive serial number.
151
168
  */
152
169
  function randomSerialNumber() {
153
- let e = o().getRandomValues(/* @__PURE__ */ new Uint8Array(16));
170
+ let e = l().getRandomValues(/* @__PURE__ */ new Uint8Array(16));
154
171
  return e[0] = (e[0] ?? 0) & 127, (e[0] ?? 0) === 0 && (e[0] = 1), e;
155
172
  }
156
- //#endregion
157
173
  export { createCertificate, createSelfSignedCertificate };
158
174
 
159
175
  //# sourceMappingURL=certificate.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"certificate.js","names":[],"sources":["../../src/x509/certificate.ts"],"sourcesContent":["/**\n * Create X.509 certificates from typed names, extensions, and WebCrypto keys.\n *\n * Use this module to issue a certificate from an existing issuer key pair or to\n * generate a self-signed certificate in one step.\n *\n * @module\n */\n\nimport {\n\tbitString,\n\texplicitContext,\n\tinteger,\n\tintegerFromNumber,\n\tsequence,\n\ttime,\n} from '#micro509/internal/asn1/der';\nimport type { SignatureProfileInput } from '#micro509/internal/crypto/signing';\n\nexport type { SignatureProfileInput };\n\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport type { KeyAlgorithmInput, KeyPairMaterial } from '#micro509/keys/keys';\nimport { exportSpkiDer, generateKeyPair } from '#micro509/keys/keys';\nimport { pemEncode } from '#micro509/pem/pem';\nimport { throwMicro509Error } from '#micro509/result/result';\nimport type { CertificateExtensionsInput } from '#micro509/x509/extensions';\nimport { buildCertificateExtensions } from '#micro509/x509/extensions';\nimport type { NameInput } from '#micro509/x509/name';\nimport { encodeName, isNameInputEmpty } from '#micro509/x509/name';\n\nexport type * from '#micro509/x509/extensions';\nexport type * from '#micro509/x509/name';\n\n/** Machine-readable reason a certificate builder rejected its construction input. */\nexport type CreateCertificateErrorCode =\n\t| 'issuer_distinguished_name_empty'\n\t| 'serial_number_not_positive'\n\t| 'serial_number_too_long'\n\t| 'validity_not_after_before_not_before';\n\n/**\n * Configures the certificate validity window.\n *\n * If `notAfter` is omitted, it is derived from `notBefore` plus `days`. If both\n * `notAfter` and `days` are omitted, the certificate is valid for 30 days.\n */\nexport interface ValidityInput {\n\t/**\n\t * Start of the validity window.\n\t *\n\t * Defaults to the current time.\n\t */\n\treadonly notBefore?: Date;\n\t/**\n\t * End of the validity window.\n\t *\n\t * Must be later than `notBefore`.\n\t */\n\treadonly notAfter?: Date;\n\t/**\n\t * Number of days to add to `notBefore` when `notAfter` is omitted.\n\t */\n\treadonly days?: number;\n}\n\n/**\n * Input for {@linkcode createCertificate}.\n */\nexport interface CreateCertificateInput {\n\t/**\n\t * Issuer distinguished name.\n\t */\n\treadonly issuer: NameInput;\n\t/**\n\t * Subject distinguished name.\n\t */\n\treadonly subject: NameInput;\n\t/**\n\t * Subject public key to encode into the certificate.\n\t */\n\treadonly publicKey: CryptoKey;\n\t/**\n\t * Private key used to sign the certificate.\n\t */\n\treadonly signerPrivateKey: CryptoKey;\n\t/**\n\t * Issuer public key.\n\t *\n\t * Provide this when extension builders need issuer key material, such as\n\t * authority key identifier derivation.\n\t */\n\treadonly issuerPublicKey?: CryptoKey;\n\t/**\n\t * Validity window configuration.\n\t */\n\treadonly validity?: ValidityInput;\n\t/**\n\t * DER integer bytes for the certificate serial number.\n\t *\n\t * RFC 5280 §4.1.2.2 requires a positive value of at most 20 octets.\n\t * When omitted, a random positive 16-byte serial number is generated.\n\t */\n\treadonly serialNumber?: Uint8Array;\n\t/**\n\t * X.509 extensions to encode into the certificate.\n\t */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/**\n\t * Signature algorithm override.\n\t *\n\t * When omitted, the library selects a compatible profile from the signing\n\t * key.\n\t */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/**\n * Input for {@linkcode createSelfSignedCertificate}.\n */\nexport type CreateSelfSignedCertificateInput = CreateSelfSignedCertificateBase &\n\tSelfSignedKeySource;\n\n/**\n * Where {@linkcode createSelfSignedCertificate} gets its key pair.\n *\n * Supplying `keyPair` makes `algorithm` unreachable, since generation is skipped.\n */\nexport type SelfSignedKeySource =\n\t| {\n\t\t\t/**\n\t\t\t * Existing key pair to reuse for both subject and issuer.\n\t\t\t */\n\t\t\treadonly keyPair: KeyPairMaterial;\n\t\t\t/**\n\t\t\t * Unavailable in this variant; the supplied `keyPair` is used as-is.\n\t\t\t */\n\t\t\treadonly algorithm?: never;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * Generate a new key pair for both subject and issuer.\n\t\t\t */\n\t\t\treadonly keyPair?: never;\n\t\t\t/**\n\t\t\t * Key generation parameters. Defaults to the {@linkcode generateKeyPair} default.\n\t\t\t */\n\t\t\treadonly algorithm?: KeyAlgorithmInput;\n\t };\n\n/** Fields common to both {@linkcode SelfSignedKeySource} variants. */\nexport interface CreateSelfSignedCertificateBase {\n\t/**\n\t * Subject distinguished name used as both subject and issuer.\n\t */\n\treadonly subject: NameInput;\n\t/**\n\t * Validity window configuration.\n\t */\n\treadonly validity?: ValidityInput;\n\t/**\n\t * DER integer bytes for the certificate serial number.\n\t *\n\t * RFC 5280 §4.1.2.2 requires a positive value of at most 20 octets.\n\t * When omitted, a random positive 16-byte serial number is generated.\n\t */\n\treadonly serialNumber?: Uint8Array;\n\t/**\n\t * X.509 extensions to encode into the certificate.\n\t */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/**\n\t * Signature algorithm override.\n\t */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/**\n * Encoded certificate material in common interchange formats.\n */\nexport interface CertificateMaterial {\n\t/**\n\t * DER-encoded certificate bytes.\n\t */\n\treadonly der: Uint8Array;\n\t/**\n\t * PEM-encoded certificate.\n\t */\n\treadonly pem: string;\n\t/**\n\t * Base64 encoding of {@linkcode der} without PEM armor.\n\t */\n\treadonly base64: string;\n}\n\n/**\n * Result returned by {@linkcode createSelfSignedCertificate}.\n */\nexport interface SelfSignedCertificateResult {\n\t/**\n\t * Encoded certificate outputs.\n\t */\n\treadonly certificate: CertificateMaterial;\n\t/**\n\t * Key pair used to issue the certificate.\n\t */\n\treadonly keyPair: KeyPairMaterial;\n}\n\n/**\n * Create a self-signed certificate.\n *\n * Reuses `input.keyPair` when provided; otherwise generates a new key pair from\n * `input.algorithm`. The returned certificate uses `input.subject` as both\n * issuer and subject.\n *\n * @example\n * ```ts\n * const { certificate, keyPair } = await createSelfSignedCertificate({\n * \tsubject: { commonName: 'example.com' },\n * \talgorithm: { kind: 'ecdsa', curve: 'P-256' },\n * });\n * ```\n *\n * @param input Certificate subject, key, validity, and extension settings.\n * @returns The certificate plus the key pair used to sign it.\n */\nexport async function createSelfSignedCertificate(\n\tinput: CreateSelfSignedCertificateInput,\n): Promise<SelfSignedCertificateResult> {\n\tconst keyPair = input.keyPair ?? (await generateKeyPair(input.algorithm));\n\tconst certificateInput = {\n\t\tissuer: input.subject,\n\t\tsubject: input.subject,\n\t\tpublicKey: keyPair.publicKey,\n\t\tsignerPrivateKey: keyPair.privateKey,\n\t\tissuerPublicKey: keyPair.publicKey,\n\t\t...(input.validity !== undefined ? { validity: input.validity } : {}),\n\t\t...(input.serialNumber !== undefined ? { serialNumber: input.serialNumber } : {}),\n\t\t...(input.extensions !== undefined ? { extensions: input.extensions } : {}),\n\t\t...(input.signature !== undefined ? { signature: input.signature } : {}),\n\t} satisfies CreateCertificateInput;\n\tconst certificate = await createCertificate(certificateInput);\n\n\treturn { certificate, keyPair };\n}\n\n/**\n * Create an X.509 certificate signed by `input.signerPrivateKey`.\n *\n * The certificate encodes `input.subject`, `input.publicKey`, and any supplied\n * extensions. When `serialNumber` is omitted, a random positive serial number is\n * generated. When `validity` is omitted, the certificate is valid from now for\n * 30 days.\n *\n * @example\n * ```ts\n * const certificate = await createCertificate({\n * \tissuer: { commonName: 'Example Root CA' },\n * \tsubject: { commonName: 'example.com' },\n * \tpublicKey: leafKeys.publicKey,\n * \tsignerPrivateKey: issuerKeys.privateKey,\n * \tissuerPublicKey: issuerKeys.publicKey,\n * });\n * ```\n *\n * @param input Issuer, subject, key, validity, and extension settings.\n * @returns The encoded certificate material.\n */\nexport async function createCertificate(\n\tinput: CreateCertificateInput,\n): Promise<CertificateMaterial> {\n\tconst subjectPublicKeyInfo = await exportSpkiDer(input.publicKey);\n\tconst issuerPublicKeyInfo = input.issuerPublicKey\n\t\t? await exportSpkiDer(input.issuerPublicKey)\n\t\t: undefined;\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey, input.signature);\n\tconst validity = resolveValidity(input.validity);\n\tif (isNameInputEmpty(input.issuer)) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'issuer_distinguished_name_empty',\n\t\t\t'issuer must be a non-empty distinguished name',\n\t\t);\n\t}\n\tconst subjectIsEmpty = isNameInputEmpty(input.subject);\n\tconst extensions = buildCertificateExtensions(\n\t\tsubjectPublicKeyInfo,\n\t\tissuerPublicKeyInfo,\n\t\tinput.extensions,\n\t\tsubjectIsEmpty,\n\t);\n\tconst tbsCertificate = sequence([\n\t\texplicitContext(0, integerFromNumber(2)),\n\t\tencodeSerialNumber(input.serialNumber),\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tencodeName(input.issuer),\n\t\tsequence([time(validity.notBefore), time(validity.notAfter)]),\n\t\tencodeName(input.subject),\n\t\tsubjectPublicKeyInfo,\n\t\texplicitContext(3, sequence(extensions)),\n\t]);\n\n\tconst signatureValue = await signBytes(\n\t\tinput.signerPrivateKey,\n\t\tsignatureAlgorithm,\n\t\ttbsCertificate,\n\t);\n\tconst certificateDer = sequence([\n\t\ttbsCertificate,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(signatureValue),\n\t]);\n\n\treturn materializeCertificate(certificateDer);\n}\n\n/**\n * Convert DER bytes into all exported certificate encodings.\n *\n * @param der DER-encoded certificate bytes.\n * @returns DER, PEM, and base64 views of the same certificate.\n */\nfunction materializeCertificate(der: Uint8Array): CertificateMaterial {\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('CERTIFICATE', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/**\n * Normalized validity window used during certificate creation.\n */\ninterface ResolvedValidity {\n\t/**\n\t * Start of the validity window.\n\t */\n\treadonly notBefore: Date;\n\t/**\n\t * End of the validity window.\n\t */\n\treadonly notAfter: Date;\n}\n\n/**\n * Resolve defaults for a certificate validity window.\n *\n * @param input Optional validity settings.\n * @returns A concrete `notBefore` and `notAfter` pair.\n */\nfunction resolveValidity(input: ValidityInput | undefined): ResolvedValidity {\n\tconst notBefore = input?.notBefore ?? new Date();\n\tconst notAfter = input?.notAfter ?? addDays(notBefore, input?.days ?? 30);\n\tif (notAfter.getTime() <= notBefore.getTime()) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'validity_not_after_before_not_before',\n\t\t\t'notAfter must be after notBefore',\n\t\t);\n\t}\n\treturn { notBefore, notAfter };\n}\n\n/**\n * Return a new date offset by a whole number of UTC days.\n *\n * @param date Base date.\n * @param days Number of days to add.\n * @returns The shifted date.\n */\nfunction addDays(date: Date, days: number): Date {\n\tconst out = new Date(date.getTime());\n\tout.setUTCDate(out.getUTCDate() + days);\n\treturn out;\n}\n\n/** RFC 5280 §4.1.2.2: conforming CAs must not use serial numbers longer than this. */\nconst SERIAL_NUMBER_MAX_OCTETS = 20;\n\n/**\n * Encode a certificate serial number as a DER INTEGER.\n *\n * @param serialNumber Serial number bytes, big-endian; a random one is generated when omitted.\n * @returns The DER INTEGER element.\n * @throws a `ResultError` with code `serial_number_not_positive` or\n * `serial_number_too_long` when RFC 5280 §4.1.2.2 forbids the value.\n */\nfunction encodeSerialNumber(serialNumber: Uint8Array | undefined): Uint8Array {\n\tif (serialNumber === undefined) {\n\t\treturn integer(randomSerialNumber());\n\t}\n\tlet start = 0;\n\twhile (start < serialNumber.length && serialNumber[start] === 0) {\n\t\tstart += 1;\n\t}\n\tconst magnitude = serialNumber.subarray(start);\n\tconst first = magnitude[0];\n\tif (first === undefined) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'serial_number_not_positive',\n\t\t\t'serialNumber must be a positive integer',\n\t\t);\n\t}\n\tif (magnitude.length + (first >= 0x80 ? 1 : 0) > SERIAL_NUMBER_MAX_OCTETS) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'serial_number_too_long',\n\t\t\t`serialNumber must not exceed ${String(SERIAL_NUMBER_MAX_OCTETS)} octets`,\n\t\t);\n\t}\n\treturn integer(magnitude);\n}\n\n/**\n * Generate a random positive serial number suitable for certificate issuance.\n *\n * @returns A 16-byte positive serial number.\n */\nfunction randomSerialNumber(): Uint8Array {\n\tconst serial = getCrypto().getRandomValues(new Uint8Array(16));\n\tconst first = serial[0] ?? 0;\n\tserial[0] = first & 0x7f;\n\tif ((serial[0] ?? 0) === 0) {\n\t\tserial[0] = 1;\n\t}\n\treturn serial;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyOA,eAAsB,4BACrB,GACuC;CACvC,IAAM,IAAU,EAAM,WAAY,MAAM,EAAgB,EAAM,SAAS;CAcvE,OAAO;EAAE,aAAA,MAFiB,kBAAkB;GAV3C,QAAQ,EAAM;GACd,SAAS,EAAM;GACf,WAAW,EAAQ;GACnB,kBAAkB,EAAQ;GAC1B,iBAAiB,EAAQ;GACzB,GAAI,EAAM,aAAa,KAAA,IAA2C,CAAC,IAAhC,EAAE,UAAU,EAAM,SAAS;GAC9D,GAAI,EAAM,iBAAiB,KAAA,IAAmD,CAAC,IAAxC,EAAE,cAAc,EAAM,aAAa;GAC1E,GAAI,EAAM,eAAe,KAAA,IAA+C,CAAC,IAApC,EAAE,YAAY,EAAM,WAAW;GACpE,GAAI,EAAM,cAAc,KAAA,IAA6C,CAAC,IAAlC,EAAE,WAAW,EAAM,UAAU;EAEP,CAAC;EAEtC;CAAQ;AAC/B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,eAAsB,kBACrB,GAC+B;CAC/B,IAAM,IAAuB,MAAM,EAAc,EAAM,SAAS,GAC1D,IAAsB,EAAM,kBAC/B,MAAM,EAAc,EAAM,eAAe,IACzC,KAAA,GACG,IAAqB,EAAsB,EAAM,kBAAkB,EAAM,SAAS,GAClF,IAAW,gBAAgB,EAAM,QAAQ;CAC/C,AAAI,EAAiB,EAAM,MAAM,KAChC,EACC,mCACA,+CACD;CAED,IAAM,IAAiB,EAAiB,EAAM,OAAO,GAC/C,IAAa,EAClB,GACA,GACA,EAAM,YACN,CACD,GACM,IAAiB,EAAS;EAC/B,EAAgB,GAAG,EAAkB,CAAC,CAAC;EACvC,mBAAmB,EAAM,YAAY;EACrC,EAA0B,CAAkB;EAC5C,EAAW,EAAM,MAAM;EACvB,EAAS,CAAC,EAAK,EAAS,SAAS,GAAG,EAAK,EAAS,QAAQ,CAAC,CAAC;EAC5D,EAAW,EAAM,OAAO;EACxB;EACA,EAAgB,GAAG,EAAS,CAAU,CAAC;CACxC,CAAC,GAEK,IAAiB,MAAM,EAC5B,EAAM,kBACN,GACA,CACD;CAOA,OAAO,uBANgB,EAAS;EAC/B;EACA,EAA0B,CAAkB;EAC5C,EAAU,CAAc;CACzB,CAE2C,CAAC;AAC7C;;;;;;;AAQA,SAAS,uBAAuB,GAAsC;CACrE,OAAO;EACN;EACA,KAAK,EAAU,eAAe,CAAG;EACjC,QAAQ,EAAa,CAAG;CACzB;AACD;;;;;;;AAsBA,SAAS,gBAAgB,GAAoD;CAC5E,IAAM,IAAY,GAAO,6BAAa,IAAI,KAAK,GACzC,IAAW,GAAO,YAAY,QAAQ,GAAW,GAAO,QAAQ,EAAE;CAOxE,OANI,EAAS,QAAQ,KAAK,EAAU,QAAQ,KAC3C,EACC,wCACA,kCACD,GAEM;EAAE;EAAW;CAAS;AAC9B;;;;;;;;AASA,SAAS,QAAQ,GAAY,GAAoB;CAChD,IAAM,IAAM,IAAI,KAAK,EAAK,QAAQ,CAAC;CAEnC,OADA,EAAI,WAAW,EAAI,WAAW,IAAI,CAAI,GAC/B;AACR;;;;;;;;;AAaA,SAAS,mBAAmB,GAAkD;CAC7E,IAAI,MAAiB,KAAA,GACpB,OAAO,EAAQ,mBAAmB,CAAC;CAEpC,IAAI,IAAQ;CACZ,OAAO,IAAQ,EAAa,UAAU,EAAa,OAAW,IAC7D,KAAS;CAEV,IAAM,IAAY,EAAa,SAAS,CAAK,GACvC,IAAQ,EAAU;CAaxB,OAZI,MAAU,KAAA,KACb,EACC,8BACA,yCACD,GAEG,EAAU,SAAU,OAAS,OAAgB,MAChD,EACC,0BACA,wCACD,GAEM,EAAQ,CAAS;AACzB;;;;;;AAOA,SAAS,qBAAiC;CACzC,IAAM,IAAS,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC;CAM7D,OAJA,EAAO,MADO,EAAO,MAAM,KACP,MACf,EAAO,MAAM,OAAO,MACxB,EAAO,KAAK,IAEN;AACR"}
1
+ {"version":3,"file":"certificate.js","names":["keyPair","input","generateKeyPair","subjectPublicKeyInfo","exportSpkiDer","authorityKeyIdentifier","authority","buildSubjectKeyIdentifier","issuerKeyIdentifier","signatureAlgorithm","getSignatureAlgorithm","validity","isNameInputEmpty","throwMicro509Error","subjectIsEmpty","extensions","buildCertificateExtensions","tbsCertificate","sequence","explicitContext","integerFromNumber","encodeAlgorithmIdentifier","encodeName","time","signatureValue","signBytes","bitString","parseCertificateFromSource","source","error","rethrowDecodeRefusal","DECODE_REFUSAL_CODES","pemEncode","der","base64Encode","notBefore","notAfter","out","date","days","serialNumber","integer","start","magnitude","first","serial","getCrypto"],"sources":["../../src/x509/certificate.ts"],"sourcesContent":["/**\n * Create X.509 certificates from typed names, extensions, and WebCrypto keys.\n *\n * Use this module to issue a certificate from an existing issuer key pair or to\n * generate a self-signed certificate in one step.\n *\n * @module\n */\n\nimport { DECODE_REFUSAL_CODES, rethrowDecodeRefusal } from '#micro509/internal/asn1/decode-refusal';\nimport {\n\tbitString,\n\texplicitContext,\n\tinteger,\n\tintegerFromNumber,\n\tsequence,\n\ttime,\n} from '#micro509/internal/asn1/der';\nimport type { SignatureProfileInput } from '#micro509/internal/crypto/signing';\n\nexport type { SignatureProfileInput };\n\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport type { KeyAlgorithmInput, KeyPairMaterial } from '#micro509/keys/keys';\nimport { exportSpkiDer, generateKeyPair } from '#micro509/keys/keys';\nimport { pemEncode } from '#micro509/pem/pem';\nimport { throwMicro509Error } from '#micro509/result/result';\nimport type { CertificateExtensionsInput } from '#micro509/x509/extensions';\nimport {\n\tbuildCertificateExtensions,\n\tbuildSubjectKeyIdentifier,\n\tissuerKeyIdentifier,\n} from '#micro509/x509/extensions';\nimport type { NameInput } from '#micro509/x509/name';\nimport { encodeName, isNameInputEmpty } from '#micro509/x509/name';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateFromSource } from '#micro509/x509/parse';\n\nexport type * from '#micro509/x509/extensions';\nexport type * from '#micro509/x509/name';\n\n/** Machine-readable reason a certificate builder rejected its construction input. */\nexport type CreateCertificateErrorCode =\n\t| 'issuer_certificate_invalid'\n\t| 'issuer_distinguished_name_empty'\n\t| 'serial_number_not_positive'\n\t| 'serial_number_too_long'\n\t| 'validity_date_invalid'\n\t| 'validity_not_after_before_not_before';\n\n/**\n * Configures the certificate validity window.\n *\n * If `notAfter` is omitted, it is derived from `notBefore` plus `days`. If both\n * `notAfter` and `days` are omitted, the certificate is valid for 30 days.\n */\nexport interface ValidityInput {\n\t/**\n\t * Start of the validity window.\n\t *\n\t * Defaults to the current time.\n\t */\n\treadonly notBefore?: Date;\n\t/**\n\t * End of the validity window.\n\t *\n\t * Must be later than `notBefore`.\n\t */\n\treadonly notAfter?: Date;\n\t/**\n\t * Number of days to add to `notBefore` when `notAfter` is omitted.\n\t */\n\treadonly days?: number;\n}\n\n/**\n * Input for {@linkcode createCertificate}.\n */\nexport interface CreateCertificateInput {\n\t/**\n\t * Issuer distinguished name.\n\t */\n\treadonly issuer: NameInput;\n\t/**\n\t * Subject distinguished name.\n\t */\n\treadonly subject: NameInput;\n\t/**\n\t * Subject public key to encode into the certificate.\n\t */\n\treadonly publicKey: CryptoKey;\n\t/**\n\t * Private key used to sign the certificate.\n\t */\n\treadonly signerPrivateKey: CryptoKey;\n\t/**\n\t * Certificate of the issuer. Its subject key identifier becomes the\n\t * authority key identifier (RFC 5280 §4.2.1.1, §4.2.1.2). An issuer\n\t * certificate without one yields a key identifier derived from its public\n\t * key. Omit it to leave the authority key identifier out.\n\t */\n\treadonly issuerCertificate?: string | Uint8Array | ParsedCertificate;\n\t/**\n\t * Validity window configuration.\n\t */\n\treadonly validity?: ValidityInput;\n\t/**\n\t * DER integer bytes for the certificate serial number.\n\t *\n\t * RFC 5280 §4.1.2.2 requires a positive value of at most 20 octets.\n\t * When omitted, a random positive 16-byte serial number is generated.\n\t */\n\treadonly serialNumber?: Uint8Array;\n\t/**\n\t * X.509 extensions to encode into the certificate.\n\t */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/**\n\t * Signature algorithm override.\n\t *\n\t * When omitted, the library selects a compatible profile from the signing\n\t * key.\n\t */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/**\n * Input for {@linkcode createSelfSignedCertificate}.\n */\nexport type CreateSelfSignedCertificateInput = CreateSelfSignedCertificateBase &\n\tSelfSignedKeySource;\n\n/**\n * Where {@linkcode createSelfSignedCertificate} gets its key pair.\n *\n * Supplying `keyPair` makes `algorithm` unreachable, since generation is skipped.\n */\nexport type SelfSignedKeySource =\n\t| {\n\t\t\t/**\n\t\t\t * Existing key pair to reuse for both subject and issuer.\n\t\t\t */\n\t\t\treadonly keyPair: KeyPairMaterial;\n\t\t\t/**\n\t\t\t * Unavailable in this variant; the supplied `keyPair` is used as-is.\n\t\t\t */\n\t\t\treadonly algorithm?: never;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * Generate a new key pair for both subject and issuer.\n\t\t\t */\n\t\t\treadonly keyPair?: never;\n\t\t\t/**\n\t\t\t * Key generation parameters. Defaults to the {@linkcode generateKeyPair} default.\n\t\t\t */\n\t\t\treadonly algorithm?: KeyAlgorithmInput;\n\t };\n\n/** Fields common to both {@linkcode SelfSignedKeySource} variants. */\nexport interface CreateSelfSignedCertificateBase {\n\t/**\n\t * Subject distinguished name used as both subject and issuer.\n\t */\n\treadonly subject: NameInput;\n\t/**\n\t * Validity window configuration.\n\t */\n\treadonly validity?: ValidityInput;\n\t/**\n\t * DER integer bytes for the certificate serial number.\n\t *\n\t * RFC 5280 §4.1.2.2 requires a positive value of at most 20 octets.\n\t * When omitted, a random positive 16-byte serial number is generated.\n\t */\n\treadonly serialNumber?: Uint8Array;\n\t/**\n\t * X.509 extensions to encode into the certificate.\n\t */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/**\n\t * Signature algorithm override.\n\t */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/**\n * Encoded certificate material in common interchange formats.\n */\nexport interface CertificateMaterial {\n\t/**\n\t * DER-encoded certificate bytes.\n\t */\n\treadonly der: Uint8Array;\n\t/**\n\t * PEM-encoded certificate.\n\t */\n\treadonly pem: string;\n\t/**\n\t * Base64 encoding of {@linkcode der} without PEM armor.\n\t */\n\treadonly base64: string;\n}\n\n/**\n * Result returned by {@linkcode createSelfSignedCertificate}.\n */\nexport interface SelfSignedCertificateResult {\n\t/**\n\t * Encoded certificate outputs.\n\t */\n\treadonly certificate: CertificateMaterial;\n\t/**\n\t * Key pair used to issue the certificate.\n\t */\n\treadonly keyPair: KeyPairMaterial;\n}\n\n/**\n * Create a self-signed certificate.\n *\n * Reuses `input.keyPair` when provided; otherwise generates a new key pair from\n * `input.algorithm`. The returned certificate uses `input.subject` as both\n * issuer and subject.\n *\n * @example\n * ```ts\n * const { certificate, keyPair } = await createSelfSignedCertificate({\n * \tsubject: { commonName: 'example.com' },\n * \talgorithm: { kind: 'ecdsa', curve: 'P-256' },\n * });\n * ```\n *\n * @param input Certificate subject, key, validity, and extension settings.\n * @returns The certificate plus the key pair used to sign it.\n */\nexport async function createSelfSignedCertificate(\n\tinput: CreateSelfSignedCertificateInput,\n): Promise<SelfSignedCertificateResult> {\n\tconst keyPair = input.keyPair ?? (await generateKeyPair(input.algorithm));\n\tconst certificateInput = {\n\t\tissuer: input.subject,\n\t\tsubject: input.subject,\n\t\tpublicKey: keyPair.publicKey,\n\t\tsignerPrivateKey: keyPair.privateKey,\n\t\t...(input.validity !== undefined ? { validity: input.validity } : {}),\n\t\t...(input.serialNumber !== undefined ? { serialNumber: input.serialNumber } : {}),\n\t\t...(input.extensions !== undefined ? { extensions: input.extensions } : {}),\n\t\t...(input.signature !== undefined ? { signature: input.signature } : {}),\n\t} satisfies CreateCertificateInput;\n\tconst certificate = await issueCertificate(certificateInput, 'subject');\n\n\treturn { certificate, keyPair };\n}\n\n/**\n * Create an X.509 certificate signed by `input.signerPrivateKey`.\n *\n * The certificate encodes `input.subject`, `input.publicKey`, and any supplied\n * extensions. When `serialNumber` is omitted, a random positive serial number is\n * generated. When `validity` is omitted, the certificate is valid from now for\n * 30 days.\n *\n * @example\n * ```ts\n * const certificate = await createCertificate({\n * \tissuer: { commonName: 'Example Root CA' },\n * \tsubject: { commonName: 'example.com' },\n * \tpublicKey: leafKeys.publicKey,\n * \tsignerPrivateKey: issuer.keyPair.privateKey,\n * \tissuerCertificate: issuer.certificate.der,\n * });\n * ```\n *\n * @param input Issuer, subject, key, validity, and extension settings.\n * @returns The encoded certificate material.\n */\nexport function createCertificate(input: CreateCertificateInput): Promise<CertificateMaterial> {\n\treturn issueCertificate(input, 'issuer');\n}\n\n/**\n * Signs a certificate whose authority key identifier comes from\n * `input.issuerCertificate`, or from its own subject key when `authority` is\n * `'subject'` (RFC 5280 §4.2.1.1).\n */\nasync function issueCertificate(\n\tinput: CreateCertificateInput,\n\tauthority: 'issuer' | 'subject',\n): Promise<CertificateMaterial> {\n\tconst subjectPublicKeyInfo = await exportSpkiDer(input.publicKey);\n\tconst authorityKeyIdentifier =\n\t\tauthority === 'subject'\n\t\t\t? buildSubjectKeyIdentifier(subjectPublicKeyInfo)\n\t\t\t: input.issuerCertificate === undefined\n\t\t\t\t? undefined\n\t\t\t\t: issuerKeyIdentifier(issuerCertificateOf(input.issuerCertificate));\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey, input.signature);\n\tconst validity = resolveValidity(input.validity);\n\tif (isNameInputEmpty(input.issuer)) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'issuer_distinguished_name_empty',\n\t\t\t'issuer must be a non-empty distinguished name',\n\t\t);\n\t}\n\tconst subjectIsEmpty = isNameInputEmpty(input.subject);\n\tconst extensions = buildCertificateExtensions(\n\t\tsubjectPublicKeyInfo,\n\t\tauthorityKeyIdentifier,\n\t\tinput.extensions,\n\t\tsubjectIsEmpty,\n\t);\n\tconst tbsCertificate = sequence([\n\t\texplicitContext(0, integerFromNumber(2)),\n\t\tencodeSerialNumber(input.serialNumber),\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tencodeName(input.issuer),\n\t\tsequence([time(validity.notBefore), time(validity.notAfter)]),\n\t\tencodeName(input.subject),\n\t\tsubjectPublicKeyInfo,\n\t\texplicitContext(3, sequence(extensions)),\n\t]);\n\n\tconst signatureValue = await signBytes(\n\t\tinput.signerPrivateKey,\n\t\tsignatureAlgorithm,\n\t\ttbsCertificate,\n\t);\n\tconst certificateDer = sequence([\n\t\ttbsCertificate,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(signatureValue),\n\t]);\n\n\treturn materializeCertificate(certificateDer);\n}\n\n/** The parsed issuer certificate of a certificate being built. */\nfunction issuerCertificateOf(source: string | Uint8Array | ParsedCertificate): ParsedCertificate {\n\ttry {\n\t\treturn parseCertificateFromSource(source);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_REFUSAL_CODES);\n\t\treturn throwMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'issuer_certificate_invalid',\n\t\t\t'issuerCertificate must be a PEM, DER or parsed certificate',\n\t\t);\n\t}\n}\n\n/**\n * Convert DER bytes into all exported certificate encodings.\n *\n * @param der DER-encoded certificate bytes.\n * @returns DER, PEM, and base64 views of the same certificate.\n */\nfunction materializeCertificate(der: Uint8Array): CertificateMaterial {\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('CERTIFICATE', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/**\n * Normalized validity window used during certificate creation.\n */\ninterface ResolvedValidity {\n\t/**\n\t * Start of the validity window.\n\t */\n\treadonly notBefore: Date;\n\t/**\n\t * End of the validity window.\n\t */\n\treadonly notAfter: Date;\n}\n\n/**\n * Resolve defaults for a certificate validity window.\n *\n * @param input Optional validity settings.\n * @returns A concrete `notBefore` and `notAfter` pair.\n */\nfunction resolveValidity(input: ValidityInput | undefined): ResolvedValidity {\n\tconst notBefore = input?.notBefore ?? new Date();\n\tconst notAfter = input?.notAfter ?? addDays(notBefore, input?.days ?? 30);\n\tif (Number.isNaN(notBefore.getTime()) || Number.isNaN(notAfter.getTime())) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'validity_date_invalid',\n\t\t\t'notBefore and notAfter must be valid dates',\n\t\t);\n\t}\n\tif (notAfter.getTime() <= notBefore.getTime()) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'validity_not_after_before_not_before',\n\t\t\t'notAfter must be after notBefore',\n\t\t);\n\t}\n\treturn { notBefore, notAfter };\n}\n\n/**\n * Return a new date offset by a whole number of UTC days.\n *\n * @param date Base date.\n * @param days Number of days to add.\n * @returns The shifted date.\n */\nfunction addDays(date: Date, days: number): Date {\n\tconst out = new Date(date.getTime());\n\tout.setUTCDate(out.getUTCDate() + days);\n\treturn out;\n}\n\n/** RFC 5280 §4.1.2.2: conforming CAs must not use serial numbers longer than this. */\nconst SERIAL_NUMBER_MAX_OCTETS = 20;\n\n/**\n * Encode a certificate serial number as a DER INTEGER.\n *\n * @param serialNumber Serial number bytes, big-endian; a random one is generated when omitted.\n * @returns The DER INTEGER element.\n * @throws a `ResultError` with code `serial_number_not_positive` or\n * `serial_number_too_long` when RFC 5280 §4.1.2.2 forbids the value.\n */\nfunction encodeSerialNumber(serialNumber: Uint8Array | undefined): Uint8Array {\n\tif (serialNumber === undefined) {\n\t\treturn integer(randomSerialNumber());\n\t}\n\tlet start = 0;\n\twhile (start < serialNumber.length && serialNumber[start] === 0) {\n\t\tstart += 1;\n\t}\n\tconst magnitude = serialNumber.subarray(start);\n\tconst first = magnitude[0];\n\tif (first === undefined) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'serial_number_not_positive',\n\t\t\t'serialNumber must be a positive integer',\n\t\t);\n\t}\n\tif (magnitude.length + (first >= 0x80 ? 1 : 0) > SERIAL_NUMBER_MAX_OCTETS) {\n\t\tthrowMicro509Error<CreateCertificateErrorCode>(\n\t\t\t'serial_number_too_long',\n\t\t\t`serialNumber must not exceed ${String(SERIAL_NUMBER_MAX_OCTETS)} octets`,\n\t\t);\n\t}\n\treturn integer(magnitude);\n}\n\n/**\n * Generate a random positive serial number suitable for certificate issuance.\n *\n * @returns A 16-byte positive serial number.\n */\nfunction randomSerialNumber(): Uint8Array {\n\tconst serial = getCrypto().getRandomValues(new Uint8Array(16));\n\tconst first = serial[0] ?? 0;\n\tserial[0] = first & 0x7f;\n\tif ((serial[0] ?? 0) === 0) {\n\t\tserial[0] = 1;\n\t}\n\treturn serial;\n}\n"],"mappings":"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"}
@@ -3,10 +3,9 @@ import { canonicalDnKey, compareDistinguishedNames, isWithinDirectoryNameSubtree
3
3
  import { NameAttribute, NameEncoderErrorCode, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName } from "./name.js";
4
4
  import { ExtensionEncoderErrorCode } from "../internal/x509/extension-errors.js";
5
5
  import { allOnesMaskForIpAddress, decodeIpAddress, normalizeIpAddress, parseIpAddressToBytes } from "../internal/shared/ip.js";
6
- import { AuthorityInfoAccessMethod, AuthorityInformationAccess, AuthorityInformationAccessInput, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, CpsPolicyQualifierInfo, CustomAuthorityInfoAccessMethod, CustomExtendedKeyUsage, CustomExtension, CustomPolicyQualifierInfo, DistributionPoint, DistributionPointName, DistributionPointReason, ExtendedKeyUsage, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, KnownAuthorityInfoAccessMethod, KnownExtendedKeyUsage, NameConstraintForm, NameConstraints, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyNoticeReference, PolicyQualifierInfo, SubjectAltName, UnsupportedNameConstraintForm, UserNoticePolicyQualifierInfo, buildCertificateExtensions, buildRequestedExtensions, buildSubjectKeyIdentifier, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid } from "./extensions.js";
7
- //#region src/x509/csr.d.ts
6
+ import { AuthorityInfoAccessMethod, AuthorityInformationAccess, AuthorityInformationAccessInput, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, CpsPolicyQualifierInfo, CustomAuthorityInfoAccessMethod, CustomExtendedKeyUsage, CustomExtension, CustomPolicyQualifierInfo, DisplayTextType, DistributionPoint, DistributionPointName, DistributionPointReason, ExtendedKeyUsage, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, KnownAuthorityInfoAccessMethod, KnownExtendedKeyUsage, NameConstraintForm, NameConstraints, OversizedDisplayText, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyNoticeReference, PolicyQualifierInfo, SubjectAltName, UnsupportedNameConstraintForm, UserNoticePolicyQualifierInfo, buildCertificateExtensions, buildRequestedExtensions, buildSubjectKeyIdentifier, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid } from "./extensions.js";
8
7
  /** Input for {@linkcode createCertificateSigningRequest}. */
9
- interface CreateCsrInput {
8
+ export interface CreateCsrInput {
10
9
  /** Distinguished name for the CSR subject (e.g. `{ commonName: 'example.com' }`). */
11
10
  readonly subject: NameInput;
12
11
  /** WebCrypto public key to embed in the CSR's SubjectPublicKeyInfo. */
@@ -19,7 +18,7 @@ interface CreateCsrInput {
19
18
  readonly signature?: SignatureProfileInput;
20
19
  }
21
20
  /** DER, PEM, and base64 encodings of a CSR produced by {@linkcode createCertificateSigningRequest}. */
22
- interface CsrMaterial {
21
+ export interface CsrMaterial {
23
22
  /** Raw DER-encoded PKCS#10 CertificationRequest. */
24
23
  readonly der: Uint8Array;
25
24
  /** PEM-armored CSR (`-----BEGIN CERTIFICATE REQUEST-----`). */
@@ -51,7 +50,6 @@ interface CsrMaterial {
51
50
  * console.log(csr.pem);
52
51
  * ```
53
52
  */
54
- declare function createCertificateSigningRequest(input: CreateCsrInput): Promise<CsrMaterial>;
55
- //#endregion
56
- export { type AuthorityInfoAccessMethod, type AuthorityInformationAccess, type AuthorityInformationAccessInput, type BasicConstraints, type CertificateExtensionsInput, type CertificatePolicies, type CpsPolicyQualifierInfo, CreateCsrInput, CsrMaterial, type CustomAuthorityInfoAccessMethod, type CustomExtendedKeyUsage, type CustomExtension, type CustomPolicyQualifierInfo, type DistributionPoint, type DistributionPointName, type DistributionPointReason, type ExtendedKeyUsage, type ExtensionEncoderErrorCode, type GeneralName, type GeneralSubtree, type InhibitAnyPolicy, type IssuingDistributionPoint, type IssuingDistributionPointBase, type IssuingDistributionPointForAttributeCerts, type IssuingDistributionPointForCaCerts, type IssuingDistributionPointForUserCerts, type KeyUsage, type KnownAuthorityInfoAccessMethod, type KnownExtendedKeyUsage, type NameConstraintForm, type NameConstraints, type NameEncoderErrorCode, type NameInput, type NameObject, type ParsedBitFlags, type ParsedNameConstraintForm, type PolicyConstraints, type PolicyInformation, type PolicyMapping, type PolicyMappings, type PolicyNoticeReference, type PolicyQualifierInfo, type SubjectAltName, type UnsupportedNameConstraintForm, type UserNoticePolicyQualifierInfo, type allOnesMaskForIpAddress, type buildCertificateExtensions, type buildRequestedExtensions, type buildSubjectKeyIdentifier, type canonicalDnKey, type compareDistinguishedNames, createCertificateSigningRequest, type decodeIpAddress, type encodeAuthorityInfoAccess, type encodeBasicConstraints, type encodeCertificatePolicies, type encodeCrlDistributionPoints, type encodeExtendedKeyUsage, type encodeExtension, type encodeInhibitAnyPolicy, type encodeKeyUsage, type encodeName, type encodeNameConstraints, type encodePolicyConstraints, type encodePolicyMappings, type encodeRelativeDistinguishedName, type encodeSubjectAltName, type getAuthorityInfoAccessMethodOid, type getExtendedKeyUsageOid, type isWithinDirectoryNameSubtree, type normalizeIpAddress, type parseAuthorityInfoAccessMethodOid, type parseExtendedKeyUsageOid, type parseIpAddressToBytes };
53
+ export declare function createCertificateSigningRequest(input: CreateCsrInput): Promise<CsrMaterial>;
54
+ export type { AuthorityInfoAccessMethod, AuthorityInformationAccess, AuthorityInformationAccessInput, BasicConstraints, CertificateExtensionsInput, CertificatePolicies, CpsPolicyQualifierInfo, CustomAuthorityInfoAccessMethod, CustomExtendedKeyUsage, CustomExtension, CustomPolicyQualifierInfo, DisplayTextType, DistributionPoint, DistributionPointName, DistributionPointReason, ExtendedKeyUsage, ExtensionEncoderErrorCode, GeneralName, GeneralSubtree, InhibitAnyPolicy, IssuingDistributionPoint, IssuingDistributionPointBase, IssuingDistributionPointForAttributeCerts, IssuingDistributionPointForCaCerts, IssuingDistributionPointForUserCerts, KeyUsage, KnownAuthorityInfoAccessMethod, KnownExtendedKeyUsage, NameConstraintForm, NameConstraints, NameEncoderErrorCode, NameInput, NameObject, OversizedDisplayText, ParsedBitFlags, ParsedNameConstraintForm, PolicyConstraints, PolicyInformation, PolicyMapping, PolicyMappings, PolicyNoticeReference, PolicyQualifierInfo, SubjectAltName, UnsupportedNameConstraintForm, UserNoticePolicyQualifierInfo, allOnesMaskForIpAddress, buildCertificateExtensions, buildRequestedExtensions, buildSubjectKeyIdentifier, canonicalDnKey, compareDistinguishedNames, decodeIpAddress, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeName, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeRelativeDistinguishedName, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, isWithinDirectoryNameSubtree, normalizeIpAddress, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid, parseIpAddressToBytes };
57
55
  //# sourceMappingURL=csr.d.ts.map
package/dist/x509/csr.js CHANGED
@@ -3,10 +3,10 @@ import { OIDS as s } from "../internal/asn1/oids2.js";
3
3
  import { base64Encode as c } from "../internal/shared/base64.js";
4
4
  import { pemEncode as l } from "../pem/pem.js";
5
5
  import { exportSpkiDer as u } from "../keys/keys.js";
6
- import { encodeName as d } from "./name.js";
7
- import { buildRequestedExtensions as f } from "./extensions.js";
8
- import { encodeAlgorithmIdentifier as p, getSignatureAlgorithm as m, signBytes as h } from "../internal/crypto/signing.js";
9
- //#region src/x509/csr.ts
6
+ import { encodeAlgorithmIdentifier as d, getSignatureAlgorithm as f, signBytes as p } from "../internal/crypto/signing.js";
7
+ import { encodeName as m } from "./name.js";
8
+ import { buildRequestedExtensions as h } from "./extensions.js";
9
+ // src/x509/csr.ts
10
10
  /**
11
11
  * PKCS#10 Certificate Signing Request (CSR) creation.
12
12
  *
@@ -40,14 +40,14 @@ import { encodeAlgorithmIdentifier as p, getSignatureAlgorithm as m, signBytes a
40
40
  * ```
41
41
  */
42
42
  async function createCertificateSigningRequest(i) {
43
- let o = m(i.signerPrivateKey, i.signature), s = await u(i.publicKey), f = buildAttributes(i.extensions), g = a([
43
+ let o = f(i.signerPrivateKey, i.signature), s = await u(i.publicKey), h = buildAttributes(i.extensions), g = a([
44
44
  r(0),
45
- d(i.subject),
45
+ m(i.subject),
46
46
  s,
47
- n(0, t(f))
48
- ]), _ = await h(i.signerPrivateKey, o, g), v = a([
47
+ n(0, t(h))
48
+ ]), _ = await p(i.signerPrivateKey, o, g), v = a([
49
49
  g,
50
- p(o),
50
+ d(o),
51
51
  e(_)
52
52
  ]);
53
53
  return {
@@ -58,10 +58,9 @@ async function createCertificateSigningRequest(i) {
58
58
  }
59
59
  /** Encodes extensions into a CSR extensionRequest attribute, or returns empty. */
60
60
  function buildAttributes(e) {
61
- let t = f(e);
61
+ let t = h(e);
62
62
  return t.length === 0 ? [] : [a([i(s.extensionRequest), o([a(t)])])];
63
63
  }
64
- //#endregion
65
64
  export { createCertificateSigningRequest };
66
65
 
67
66
  //# sourceMappingURL=csr.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"csr.js","names":[],"sources":["../../src/x509/csr.ts"],"sourcesContent":["/**\n * PKCS#10 Certificate Signing Request (CSR) creation.\n *\n * Builds a CSR from a subject name, WebCrypto key pair, and optional extensions,\n * producing DER, PEM, and base64 outputs.\n *\n * @module\n */\n\nimport {\n\tbitString,\n\tconcatBytes,\n\timplicitConstructedContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\tsequence,\n\tsetOf,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport { exportSpkiDer } from '#micro509/keys/keys';\nimport { pemEncode } from '#micro509/pem/pem';\nimport type { SignatureProfileInput } from '#micro509/x509/certificate';\nimport type { CertificateExtensionsInput } from '#micro509/x509/extensions';\nimport { buildRequestedExtensions } from '#micro509/x509/extensions';\nimport type { NameInput } from '#micro509/x509/name';\nimport { encodeName } from '#micro509/x509/name';\n\nexport type * from '#micro509/x509/extensions';\nexport type * from '#micro509/x509/name';\n\n/** Input for {@linkcode createCertificateSigningRequest}. */\nexport interface CreateCsrInput {\n\t/** Distinguished name for the CSR subject (e.g. `{ commonName: 'example.com' }`). */\n\treadonly subject: NameInput;\n\t/** WebCrypto public key to embed in the CSR's SubjectPublicKeyInfo. */\n\treadonly publicKey: CryptoKey;\n\t/** WebCrypto private key used to self-sign the CSR (proves key possession). */\n\treadonly signerPrivateKey: CryptoKey;\n\t/** Requested X.509v3 extensions to include in the CSR attributes. */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/** Override the signature algorithm profile (hash, salt length, etc.). */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/** DER, PEM, and base64 encodings of a CSR produced by {@linkcode createCertificateSigningRequest}. */\nexport interface CsrMaterial {\n\t/** Raw DER-encoded PKCS#10 CertificationRequest. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored CSR (`-----BEGIN CERTIFICATE REQUEST-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/**\n * Creates a PKCS#10 Certificate Signing Request signed with the given private key.\n *\n * The CSR embeds the public key's SPKI, the subject name, and any requested extensions\n * as attributes. The signature proves possession of the private key.\n *\n * @example\n * ```ts\n * import { createCertificateSigningRequest } from 'micro509';\n *\n * const keyPair = await crypto.subtle.generateKey(\n * { name: 'ECDSA', namedCurve: 'P-256' },\n * true,\n * ['sign', 'verify'],\n * );\n * const csr = await createCertificateSigningRequest({\n * subject: { commonName: 'example.com' },\n * publicKey: keyPair.publicKey,\n * signerPrivateKey: keyPair.privateKey,\n * extensions: { subjectAltNames: [{ type: 'dns', value: 'example.com' }] },\n * });\n * console.log(csr.pem);\n * ```\n */\nexport async function createCertificateSigningRequest(input: CreateCsrInput): Promise<CsrMaterial> {\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey, input.signature);\n\tconst spki = await exportSpkiDer(input.publicKey);\n\tconst attributes = buildAttributes(input.extensions);\n\tconst certificationRequestInfo = sequence([\n\t\tintegerFromNumber(0),\n\t\tencodeName(input.subject),\n\t\tspki,\n\t\timplicitConstructedContext(0, concatBytes(attributes)),\n\t]);\n\tconst normalizedSignature = await signBytes(\n\t\tinput.signerPrivateKey,\n\t\tsignatureAlgorithm,\n\t\tcertificationRequestInfo,\n\t);\n\n\tconst der = sequence([\n\t\tcertificationRequestInfo,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(normalizedSignature),\n\t]);\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('CERTIFICATE REQUEST', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/** Encodes extensions into a CSR extensionRequest attribute, or returns empty. */\nfunction buildAttributes(extensions: CertificateExtensionsInput | undefined): Uint8Array[] {\n\tconst builtExtensions = buildRequestedExtensions(extensions);\n\tif (builtExtensions.length === 0) {\n\t\treturn [];\n\t}\n\treturn [sequence([objectIdentifier(OIDS.extensionRequest), setOf([sequence(builtExtensions)])])];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,eAAsB,gCAAgC,GAA6C;CAClG,IAAM,IAAqB,EAAsB,EAAM,kBAAkB,EAAM,SAAS,GAClF,IAAO,MAAM,EAAc,EAAM,SAAS,GAC1C,IAAa,gBAAgB,EAAM,UAAU,GAC7C,IAA2B,EAAS;EACzC,EAAkB,CAAC;EACnB,EAAW,EAAM,OAAO;EACxB;EACA,EAA2B,GAAG,EAAY,CAAU,CAAC;CACtD,CAAC,GACK,IAAsB,MAAM,EACjC,EAAM,kBACN,GACA,CACD,GAEM,IAAM,EAAS;EACpB;EACA,EAA0B,CAAkB;EAC5C,EAAU,CAAmB;CAC9B,CAAC;CACD,OAAO;EACN;EACA,KAAK,EAAU,uBAAuB,CAAG;EACzC,QAAQ,EAAa,CAAG;CACzB;AACD;;AAGA,SAAS,gBAAgB,GAAkE;CAC1F,IAAM,IAAkB,EAAyB,CAAU;CAI3D,OAHI,EAAgB,WAAW,IACvB,CAAC,IAEF,CAAC,EAAS,CAAC,EAAiB,EAAK,gBAAgB,GAAG,EAAM,CAAC,EAAS,CAAe,CAAC,CAAC,CAAC,CAAC,CAAC;AAChG"}
1
+ {"version":3,"file":"csr.js","names":["signatureAlgorithm","getSignatureAlgorithm","input","spki","exportSpkiDer","attributes","certificationRequestInfo","sequence","integerFromNumber","encodeName","implicitConstructedContext","concatBytes","normalizedSignature","signBytes","der","encodeAlgorithmIdentifier","bitString","pemEncode","base64Encode","builtExtensions","buildRequestedExtensions","extensions","objectIdentifier","OIDS","setOf"],"sources":["../../src/x509/csr.ts"],"sourcesContent":["/**\n * PKCS#10 Certificate Signing Request (CSR) creation.\n *\n * Builds a CSR from a subject name, WebCrypto key pair, and optional extensions,\n * producing DER, PEM, and base64 outputs.\n *\n * @module\n */\n\nimport {\n\tbitString,\n\tconcatBytes,\n\timplicitConstructedContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\tsequence,\n\tsetOf,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport {\n\tencodeAlgorithmIdentifier,\n\tgetSignatureAlgorithm,\n\tsignBytes,\n} from '#micro509/internal/crypto/signing';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport { exportSpkiDer } from '#micro509/keys/keys';\nimport { pemEncode } from '#micro509/pem/pem';\nimport type { SignatureProfileInput } from '#micro509/x509/certificate';\nimport type { CertificateExtensionsInput } from '#micro509/x509/extensions';\nimport { buildRequestedExtensions } from '#micro509/x509/extensions';\nimport type { NameInput } from '#micro509/x509/name';\nimport { encodeName } from '#micro509/x509/name';\n\nexport type * from '#micro509/x509/extensions';\nexport type * from '#micro509/x509/name';\n\n/** Input for {@linkcode createCertificateSigningRequest}. */\nexport interface CreateCsrInput {\n\t/** Distinguished name for the CSR subject (e.g. `{ commonName: 'example.com' }`). */\n\treadonly subject: NameInput;\n\t/** WebCrypto public key to embed in the CSR's SubjectPublicKeyInfo. */\n\treadonly publicKey: CryptoKey;\n\t/** WebCrypto private key used to self-sign the CSR (proves key possession). */\n\treadonly signerPrivateKey: CryptoKey;\n\t/** Requested X.509v3 extensions to include in the CSR attributes. */\n\treadonly extensions?: CertificateExtensionsInput;\n\t/** Override the signature algorithm profile (hash, salt length, etc.). */\n\treadonly signature?: SignatureProfileInput;\n}\n\n/** DER, PEM, and base64 encodings of a CSR produced by {@linkcode createCertificateSigningRequest}. */\nexport interface CsrMaterial {\n\t/** Raw DER-encoded PKCS#10 CertificationRequest. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored CSR (`-----BEGIN CERTIFICATE REQUEST-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/**\n * Creates a PKCS#10 Certificate Signing Request signed with the given private key.\n *\n * The CSR embeds the public key's SPKI, the subject name, and any requested extensions\n * as attributes. The signature proves possession of the private key.\n *\n * @example\n * ```ts\n * import { createCertificateSigningRequest } from 'micro509';\n *\n * const keyPair = await crypto.subtle.generateKey(\n * { name: 'ECDSA', namedCurve: 'P-256' },\n * true,\n * ['sign', 'verify'],\n * );\n * const csr = await createCertificateSigningRequest({\n * subject: { commonName: 'example.com' },\n * publicKey: keyPair.publicKey,\n * signerPrivateKey: keyPair.privateKey,\n * extensions: { subjectAltNames: [{ type: 'dns', value: 'example.com' }] },\n * });\n * console.log(csr.pem);\n * ```\n */\nexport async function createCertificateSigningRequest(input: CreateCsrInput): Promise<CsrMaterial> {\n\tconst signatureAlgorithm = getSignatureAlgorithm(input.signerPrivateKey, input.signature);\n\tconst spki = await exportSpkiDer(input.publicKey);\n\tconst attributes = buildAttributes(input.extensions);\n\tconst certificationRequestInfo = sequence([\n\t\tintegerFromNumber(0),\n\t\tencodeName(input.subject),\n\t\tspki,\n\t\timplicitConstructedContext(0, concatBytes(attributes)),\n\t]);\n\tconst normalizedSignature = await signBytes(\n\t\tinput.signerPrivateKey,\n\t\tsignatureAlgorithm,\n\t\tcertificationRequestInfo,\n\t);\n\n\tconst der = sequence([\n\t\tcertificationRequestInfo,\n\t\tencodeAlgorithmIdentifier(signatureAlgorithm),\n\t\tbitString(normalizedSignature),\n\t]);\n\treturn {\n\t\tder,\n\t\tpem: pemEncode('CERTIFICATE REQUEST', der),\n\t\tbase64: base64Encode(der),\n\t};\n}\n\n/** Encodes extensions into a CSR extensionRequest attribute, or returns empty. */\nfunction buildAttributes(extensions: CertificateExtensionsInput | undefined): Uint8Array[] {\n\tconst builtExtensions = buildRequestedExtensions(extensions);\n\tif (builtExtensions.length === 0) {\n\t\treturn [];\n\t}\n\treturn [sequence([objectIdentifier(OIDS.extensionRequest), setOf([sequence(builtExtensions)])])];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,eAAsB,gCAAgC,GAA6C;CAClG,IAAMA,IAAqBC,EAAsBC,EAAM,kBAAkBA,EAAM,SAAS,GAClFC,IAAO,MAAMC,EAAcF,EAAM,SAAS,GAC1CG,IAAa,gBAAgBH,EAAM,UAAU,GAC7CI,IAA2BC,EAAS;EACzCC,EAAkB,CAAC;EACnBC,EAAWP,EAAM,OAAO;EACxBC;EACAO,EAA2B,GAAGC,EAAYN,CAAU,CAAC;CACtD,CAAC,GACKO,IAAsB,MAAMC,EACjCX,EAAM,kBACNF,GACAM,CACD,GAEMQ,IAAMP,EAAS;EACpBD;EACAS,EAA0Bf,CAAkB;EAC5CgB,EAAUJ,CAAmB;CAC9B,CAAC;CACD,OAAO;EACN;EACA,KAAKK,EAAU,uBAAuBH,CAAG;EACzC,QAAQI,EAAaJ,CAAG;CACzB;AACD;;AAGA,SAAS,gBAAgB,GAAkE;CAC1F,IAAMK,IAAkBC,EAAyBC,CAAU;CAI3D,OAHIF,EAAgB,WAAW,IACvB,CAAC,IAEF,CAACZ,EAAS,CAACe,EAAiBC,EAAK,gBAAgB,GAAGC,EAAM,CAACjB,EAASY,CAAe,CAAC,CAAC,CAAC,CAAC,CAAC;AAChG"}