micro509 0.13.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 (165) hide show
  1. package/CHANGELOG.md +2064 -0
  2. package/README.md +111 -183
  3. package/dist/crypto/crypto.d.ts +104 -0
  4. package/dist/crypto/crypto.js +105 -0
  5. package/dist/crypto/crypto.js.map +1 -0
  6. package/dist/crypto.d.ts +4 -0
  7. package/dist/crypto.js +1 -0
  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 +18 -14
  12. package/dist/index.js +19 -17
  13. package/dist/internal/asn1/asn1.d.ts +3 -6
  14. package/dist/internal/asn1/asn1.js +355 -44
  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 +42 -43
  21. package/dist/internal/asn1/der.js +148 -56
  22. package/dist/internal/asn1/der.js.map +1 -1
  23. package/dist/internal/asn1/oids.js +90 -54
  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 +5 -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 +51 -0
  34. package/dist/internal/crypto/pbes2.js +86 -34
  35. package/dist/internal/crypto/pbes2.js.map +1 -1
  36. package/dist/internal/crypto/rsa-pss.js +48 -44
  37. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  38. package/dist/internal/crypto/sig-verify.d.ts +28 -0
  39. package/dist/internal/crypto/sig-verify.js +111 -62
  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 +8 -3
  47. package/dist/internal/shared/base64.js.map +1 -1
  48. package/dist/internal/shared/dn.d.ts +13 -0
  49. package/dist/internal/shared/dn.js +101 -48
  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 +66 -0
  56. package/dist/internal/shared/ip.js +19 -3
  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 +4 -0
  73. package/dist/internal/verify/verify-path.js +264 -128
  74. package/dist/internal/verify/verify-path.js.map +1 -1
  75. package/dist/internal/x509/directory-name.js +23 -0
  76. package/dist/internal/x509/directory-name.js.map +1 -0
  77. package/dist/internal/x509/extension-bits.js +15 -13
  78. package/dist/internal/x509/extension-bits.js.map +1 -1
  79. package/dist/internal/x509/extension-errors.d.ts +3 -0
  80. package/dist/internal/x509/extension-errors.js +19 -0
  81. package/dist/internal/x509/extension-errors.js.map +1 -0
  82. package/dist/internal/x509/extension-registry.js +157 -81
  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 +27 -0
  87. package/dist/internal/x509/general-name-tags.js.map +1 -0
  88. package/dist/internal/x509/general-name.js +183 -0
  89. package/dist/internal/x509/general-name.js.map +1 -0
  90. package/dist/internal/x509/name-fields.js +21 -12
  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 +124 -95
  95. package/dist/keys/keys.js +362 -214
  96. package/dist/keys/keys.js.map +1 -1
  97. package/dist/keys.d.ts +3 -2
  98. package/dist/keys.js +3 -2
  99. package/dist/pem/pem.d.ts +17 -19
  100. package/dist/pem/pem.js +122 -41
  101. package/dist/pem/pem.js.map +1 -1
  102. package/dist/pem.js +1 -2
  103. package/dist/pkcs/pfx.d.ts +57 -32
  104. package/dist/pkcs/pfx.js +209 -173
  105. package/dist/pkcs/pfx.js.map +1 -1
  106. package/dist/pkcs/pkcs12-mac.d.ts +104 -27
  107. package/dist/pkcs/pkcs12-mac.js +266 -79
  108. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  109. package/dist/pkcs/pkcs7.d.ts +123 -53
  110. package/dist/pkcs/pkcs7.js +314 -238
  111. package/dist/pkcs/pkcs7.js.map +1 -1
  112. package/dist/pkcs.d.ts +5 -4
  113. package/dist/result/result.d.ts +43 -28
  114. package/dist/result/result.js +27 -14
  115. package/dist/result/result.js.map +1 -1
  116. package/dist/result.d.ts +2 -2
  117. package/dist/result.js +1 -2
  118. package/dist/revocation/chain.d.ts +101 -23
  119. package/dist/revocation/chain.js +456 -206
  120. package/dist/revocation/chain.js.map +1 -1
  121. package/dist/revocation/crl.d.ts +140 -65
  122. package/dist/revocation/crl.js +691 -391
  123. package/dist/revocation/crl.js.map +1 -1
  124. package/dist/revocation/ocsp.d.ts +145 -69
  125. package/dist/revocation/ocsp.js +347 -297
  126. package/dist/revocation/ocsp.js.map +1 -1
  127. package/dist/revocation/revocation.d.ts +48 -36
  128. package/dist/revocation/revocation.js +112 -63
  129. package/dist/revocation/revocation.js.map +1 -1
  130. package/dist/revocation.d.ts +5 -5
  131. package/dist/revocation.js +5 -5
  132. package/dist/verify/identity.d.ts +18 -20
  133. package/dist/verify/identity.js +120 -90
  134. package/dist/verify/identity.js.map +1 -1
  135. package/dist/verify/name-constraints.d.ts +1 -4
  136. package/dist/verify/policy.d.ts +15 -8
  137. package/dist/verify/verify.d.ts +86 -46
  138. package/dist/verify/verify.js +309 -143
  139. package/dist/verify/verify.js.map +1 -1
  140. package/dist/verify.d.ts +3 -2
  141. package/dist/verify.js +4 -3
  142. package/dist/x509/certificate.d.ts +50 -28
  143. package/dist/x509/certificate.js +69 -36
  144. package/dist/x509/certificate.js.map +1 -1
  145. package/dist/x509/csr.d.ts +9 -8
  146. package/dist/x509/csr.js +10 -11
  147. package/dist/x509/csr.js.map +1 -1
  148. package/dist/x509/extensions.d.ts +207 -82
  149. package/dist/x509/extensions.js +561 -128
  150. package/dist/x509/extensions.js.map +1 -1
  151. package/dist/x509/fingerprint.d.ts +4 -7
  152. package/dist/x509/fingerprint.js +1 -2
  153. package/dist/x509/fingerprint.js.map +1 -1
  154. package/dist/x509/name-text.d.ts +7 -9
  155. package/dist/x509/name-text.js +20 -4
  156. package/dist/x509/name-text.js.map +1 -1
  157. package/dist/x509/name.d.ts +15 -14
  158. package/dist/x509/name.js +23 -19
  159. package/dist/x509/name.js.map +1 -1
  160. package/dist/x509/parse.d.ts +165 -64
  161. package/dist/x509/parse.js +444 -459
  162. package/dist/x509/parse.js.map +1 -1
  163. package/dist/x509.d.ts +8 -5
  164. package/dist/x509.js +10 -8
  165. package/package.json +90 -65
@@ -1,15 +1,20 @@
1
1
  import { KeyAlgorithmInput, KeyPairMaterial } from "../keys/keys.js";
2
- import { NameAttribute, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName } from "./name.js";
3
- import { AuthorityInfoAccessMethod, AuthorityInformationAccess, 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, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid } from "./extensions.js";
4
2
  import { SignatureProfileInput } from "../internal/crypto/signing.js";
5
- //#region src/x509/certificate.d.ts
3
+ import { canonicalDnKey, compareDistinguishedNames, isWithinDirectoryNameSubtree } from "../internal/shared/dn.js";
4
+ import { NameAttribute, NameEncoderErrorCode, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName } from "./name.js";
5
+ import { ExtensionEncoderErrorCode } from "../internal/x509/extension-errors.js";
6
+ import { allOnesMaskForIpAddress, decodeIpAddress, normalizeIpAddress, parseIpAddressToBytes } from "../internal/shared/ip.js";
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
+ /** Machine-readable reason a certificate builder rejected its construction input. */
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";
6
11
  /**
7
12
  * Configures the certificate validity window.
8
13
  *
9
14
  * If `notAfter` is omitted, it is derived from `notBefore` plus `days`. If both
10
15
  * `notAfter` and `days` are omitted, the certificate is valid for 30 days.
11
16
  */
12
- interface ValidityInput {
17
+ export interface ValidityInput {
13
18
  /**
14
19
  * Start of the validity window.
15
20
  *
@@ -30,7 +35,7 @@ interface ValidityInput {
30
35
  /**
31
36
  * Input for {@linkcode createCertificate}.
32
37
  */
33
- interface CreateCertificateInput {
38
+ export interface CreateCertificateInput {
34
39
  /**
35
40
  * Issuer distinguished name.
36
41
  */
@@ -48,12 +53,12 @@ interface CreateCertificateInput {
48
53
  */
49
54
  readonly signerPrivateKey: CryptoKey;
50
55
  /**
51
- * Issuer public key.
52
- *
53
- * Provide this when extension builders need issuer key material, such as
54
- * 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.
55
60
  */
56
- readonly issuerPublicKey?: CryptoKey;
61
+ readonly issuerCertificate?: string | Uint8Array | ParsedCertificate;
57
62
  /**
58
63
  * Validity window configuration.
59
64
  */
@@ -61,6 +66,7 @@ interface CreateCertificateInput {
61
66
  /**
62
67
  * DER integer bytes for the certificate serial number.
63
68
  *
69
+ * RFC 5280 §4.1.2.2 requires a positive value of at most 20 octets.
64
70
  * When omitted, a random positive 16-byte serial number is generated.
65
71
  */
66
72
  readonly serialNumber?: Uint8Array;
@@ -79,29 +85,46 @@ interface CreateCertificateInput {
79
85
  /**
80
86
  * Input for {@linkcode createSelfSignedCertificate}.
81
87
  */
82
- interface CreateSelfSignedCertificateInput {
88
+ export type CreateSelfSignedCertificateInput = CreateSelfSignedCertificateBase & SelfSignedKeySource;
89
+ /**
90
+ * Where {@linkcode createSelfSignedCertificate} gets its key pair.
91
+ *
92
+ * Supplying `keyPair` makes `algorithm` unreachable, since generation is skipped.
93
+ */
94
+ export type SelfSignedKeySource = {
83
95
  /**
84
- * Subject distinguished name used as both subject and issuer.
96
+ * Existing key pair to reuse for both subject and issuer.
85
97
  */
86
- readonly subject: NameInput;
98
+ readonly keyPair: KeyPairMaterial;
87
99
  /**
88
- * Key generation parameters.
89
- *
90
- * Ignored when `keyPair` is provided.
100
+ * Unavailable in this variant; the supplied `keyPair` is used as-is.
101
+ */
102
+ readonly algorithm?: never;
103
+ } | {
104
+ /**
105
+ * Generate a new key pair for both subject and issuer.
106
+ */
107
+ readonly keyPair?: never;
108
+ /**
109
+ * Key generation parameters. Defaults to the {@linkcode generateKeyPair} default.
91
110
  */
92
111
  readonly algorithm?: KeyAlgorithmInput;
112
+ };
113
+ /** Fields common to both {@linkcode SelfSignedKeySource} variants. */
114
+ export interface CreateSelfSignedCertificateBase {
93
115
  /**
94
- * Existing key pair to reuse for both subject and issuer.
95
- *
96
- * When omitted, a new key pair is generated.
116
+ * Subject distinguished name used as both subject and issuer.
97
117
  */
98
- readonly keyPair?: KeyPairMaterial;
118
+ readonly subject: NameInput;
99
119
  /**
100
120
  * Validity window configuration.
101
121
  */
102
122
  readonly validity?: ValidityInput;
103
123
  /**
104
124
  * DER integer bytes for the certificate serial number.
125
+ *
126
+ * RFC 5280 §4.1.2.2 requires a positive value of at most 20 octets.
127
+ * When omitted, a random positive 16-byte serial number is generated.
105
128
  */
106
129
  readonly serialNumber?: Uint8Array;
107
130
  /**
@@ -116,7 +139,7 @@ interface CreateSelfSignedCertificateInput {
116
139
  /**
117
140
  * Encoded certificate material in common interchange formats.
118
141
  */
119
- interface CertificateMaterial {
142
+ export interface CertificateMaterial {
120
143
  /**
121
144
  * DER-encoded certificate bytes.
122
145
  */
@@ -133,7 +156,7 @@ interface CertificateMaterial {
133
156
  /**
134
157
  * Result returned by {@linkcode createSelfSignedCertificate}.
135
158
  */
136
- interface SelfSignedCertificateResult {
159
+ export interface SelfSignedCertificateResult {
137
160
  /**
138
161
  * Encoded certificate outputs.
139
162
  */
@@ -161,7 +184,7 @@ interface SelfSignedCertificateResult {
161
184
  * @param input Certificate subject, key, validity, and extension settings.
162
185
  * @returns The certificate plus the key pair used to sign it.
163
186
  */
164
- declare function createSelfSignedCertificate(input: CreateSelfSignedCertificateInput): Promise<SelfSignedCertificateResult>;
187
+ export declare function createSelfSignedCertificate(input: CreateSelfSignedCertificateInput): Promise<SelfSignedCertificateResult>;
165
188
  /**
166
189
  * Create an X.509 certificate signed by `input.signerPrivateKey`.
167
190
  *
@@ -176,15 +199,14 @@ declare function createSelfSignedCertificate(input: CreateSelfSignedCertificateI
176
199
  * issuer: { commonName: 'Example Root CA' },
177
200
  * subject: { commonName: 'example.com' },
178
201
  * publicKey: leafKeys.publicKey,
179
- * signerPrivateKey: issuerKeys.privateKey,
180
- * issuerPublicKey: issuerKeys.publicKey,
202
+ * signerPrivateKey: issuer.keyPair.privateKey,
203
+ * issuerCertificate: issuer.certificate.der,
181
204
  * });
182
205
  * ```
183
206
  *
184
207
  * @param input Issuer, subject, key, validity, and extension settings.
185
208
  * @returns The encoded certificate material.
186
209
  */
187
- declare function createCertificate(input: CreateCertificateInput): Promise<CertificateMaterial>;
188
- //#endregion
189
- export { type AuthorityInfoAccessMethod, type AuthorityInformationAccess, type BasicConstraints, type CertificateExtensionsInput, CertificateMaterial, type CertificatePolicies, type CpsPolicyQualifierInfo, CreateCertificateInput, CreateSelfSignedCertificateInput, type CustomAuthorityInfoAccessMethod, type CustomExtendedKeyUsage, type CustomExtension, type CustomPolicyQualifierInfo, type DistributionPoint, type DistributionPointName, type DistributionPointReason, type ExtendedKeyUsage, 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 NameInput, type NameObject, type ParsedBitFlags, type ParsedNameConstraintForm, type PolicyConstraints, type PolicyInformation, type PolicyMapping, type PolicyMappings, type PolicyNoticeReference, type PolicyQualifierInfo, SelfSignedCertificateResult, type SignatureProfileInput, type SubjectAltName, type UnsupportedNameConstraintForm, type UserNoticePolicyQualifierInfo, ValidityInput, type buildCertificateExtensions, type buildRequestedExtensions, createCertificate, createSelfSignedCertificate, 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 parseAuthorityInfoAccessMethodOid, type parseExtendedKeyUsageOid };
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 };
190
212
  //# sourceMappingURL=certificate.d.ts.map
@@ -1,12 +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 { pemEncode as c } from "../pem/pem.js";
5
- import { exportSpkiDer as l, generateKeyPair as u } from "../keys/keys.js";
6
- import { encodeName as d, isNameInputEmpty as f } from "./name.js";
7
- import { buildCertificateExtensions as p } from "./extensions.js";
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
8
  import { encodeAlgorithmIdentifier as m, getSignatureAlgorithm as h, signBytes as g } from "../internal/crypto/signing.js";
9
- //#region src/x509/certificate.ts
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
10
13
  /**
11
14
  * Create X.509 certificates from typed names, extensions, and WebCrypto keys.
12
15
  *
@@ -34,19 +37,18 @@ import { encodeAlgorithmIdentifier as m, getSignatureAlgorithm as h, signBytes a
34
37
  * @returns The certificate plus the key pair used to sign it.
35
38
  */
36
39
  async function createSelfSignedCertificate(e) {
37
- let t = e.keyPair ?? await u(e.algorithm);
40
+ let t = e.keyPair ?? await p(e.algorithm);
38
41
  return {
39
- certificate: await createCertificate({
42
+ certificate: await issueCertificate({
40
43
  issuer: e.subject,
41
44
  subject: e.subject,
42
45
  publicKey: t.publicKey,
43
46
  signerPrivateKey: t.privateKey,
44
- issuerPublicKey: t.publicKey,
45
47
  ...e.validity === void 0 ? {} : { validity: e.validity },
46
48
  ...e.serialNumber === void 0 ? {} : { serialNumber: e.serialNumber },
47
49
  ...e.extensions === void 0 ? {} : { extensions: e.extensions },
48
50
  ...e.signature === void 0 ? {} : { signature: e.signature }
49
- }),
51
+ }, "subject"),
50
52
  keyPair: t
51
53
  };
52
54
  }
@@ -64,31 +66,49 @@ async function createSelfSignedCertificate(e) {
64
66
  * issuer: { commonName: 'Example Root CA' },
65
67
  * subject: { commonName: 'example.com' },
66
68
  * publicKey: leafKeys.publicKey,
67
- * signerPrivateKey: issuerKeys.privateKey,
68
- * issuerPublicKey: issuerKeys.publicKey,
69
+ * signerPrivateKey: issuer.keyPair.privateKey,
70
+ * issuerCertificate: issuer.certificate.der,
69
71
  * });
70
72
  * ```
71
73
  *
72
74
  * @param input Issuer, subject, key, validity, and extension settings.
73
75
  * @returns The encoded certificate material.
74
76
  */
75
- async function createCertificate(o) {
76
- let s = await l(o.publicKey), c = o.issuerPublicKey ? await l(o.issuerPublicKey) : void 0, u = h(o.signerPrivateKey, o.signature), _ = resolveValidity(o.validity), v = f(o.subject), y = p(s, c, o.extensions, v), b = i([
77
- t(0, r(2)),
78
- n(o.serialNumber ?? randomSerialNumber()),
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),
79
91
  m(u),
80
- d(o.issuer),
81
- i([a(_.notBefore), a(_.notAfter)]),
82
- d(o.subject),
83
- s,
84
- t(3, i(y))
85
- ]), x = await g(o.signerPrivateKey, u, b);
86
- return materializeCertificate(i([
87
- b,
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,
88
100
  m(u),
89
- e(x)
101
+ r(w)
90
102
  ]));
91
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
+ }
92
112
  /**
93
113
  * Convert DER bytes into all exported certificate encodings.
94
114
  *
@@ -98,8 +118,8 @@ async function createCertificate(o) {
98
118
  function materializeCertificate(e) {
99
119
  return {
100
120
  der: e,
101
- pem: c("CERTIFICATE", e),
102
- base64: s(e)
121
+ pem: d("CERTIFICATE", e),
122
+ base64: u(e)
103
123
  };
104
124
  }
105
125
  /**
@@ -109,11 +129,10 @@ function materializeCertificate(e) {
109
129
  * @returns A concrete `notBefore` and `notAfter` pair.
110
130
  */
111
131
  function resolveValidity(e) {
112
- let t = e?.notBefore ?? /* @__PURE__ */ new Date(), n = e?.notAfter ?? addDays(t, e?.days ?? 30);
113
- if (n.getTime() <= t.getTime()) throw Error("notAfter must be after notBefore");
114
- return {
115
- notBefore: t,
116
- 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
117
136
  };
118
137
  }
119
138
  /**
@@ -128,15 +147,29 @@ function addDays(e, t) {
128
147
  return n.setUTCDate(n.getUTCDate() + t), n;
129
148
  }
130
149
  /**
150
+ * Encode a certificate serial number as a DER INTEGER.
151
+ *
152
+ * @param serialNumber Serial number bytes, big-endian; a random one is generated when omitted.
153
+ * @returns The DER INTEGER element.
154
+ * @throws a `ResultError` with code `serial_number_not_positive` or
155
+ * `serial_number_too_long` when RFC 5280 §4.1.2.2 forbids the value.
156
+ */
157
+ function encodeSerialNumber(e) {
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);
163
+ }
164
+ /**
131
165
  * Generate a random positive serial number suitable for certificate issuance.
132
166
  *
133
167
  * @returns A 16-byte positive serial number.
134
168
  */
135
169
  function randomSerialNumber() {
136
- let e = o().getRandomValues(/* @__PURE__ */ new Uint8Array(16));
170
+ let e = l().getRandomValues(/* @__PURE__ */ new Uint8Array(16));
137
171
  return e[0] = (e[0] ?? 0) & 127, (e[0] ?? 0) === 0 && (e[0] = 1), e;
138
172
  }
139
- //#endregion
140
173
  export { createCertificate, createSelfSignedCertificate };
141
174
 
142
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 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/**\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 * 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 interface CreateSelfSignedCertificateInput {\n\t/**\n\t * Subject distinguished name used as both subject and issuer.\n\t */\n\treadonly subject: NameInput;\n\t/**\n\t * Key generation parameters.\n\t *\n\t * Ignored when `keyPair` is provided.\n\t */\n\treadonly algorithm?: KeyAlgorithmInput;\n\t/**\n\t * Existing key pair to reuse for both subject and issuer.\n\t *\n\t * When omitted, a new key pair is generated.\n\t */\n\treadonly keyPair?: KeyPairMaterial;\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\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\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\tinteger(input.serialNumber ?? randomSerialNumber()),\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\tthrow new Error('notAfter must be after notBefore');\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/**\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,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,GACzC,IAAiB,EAAiB,EAAM,OAAO,GAC/C,IAAa,EAClB,GACA,GACA,EAAM,YACN,CACD,GACM,IAAiB,EAAS;EAC/B,EAAgB,GAAG,EAAkB,CAAC,CAAC;EACvC,EAAQ,EAAM,gBAAgB,mBAAmB,CAAC;EAClD,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;CACxE,IAAI,EAAS,QAAQ,KAAK,EAAU,QAAQ,GAC3C,MAAU,MAAM,kCAAkC;CAEnD,OAAO;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;;;;;;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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkPA,eAAsB,4BACrB,GACuC;CACvC,IAAMA,IAAUC,EAAM,WAAY,MAAMC,EAAgBD,EAAM,SAAS;CAavE,OAAO;EAAE,aAAA,MAFiB,iBAAiB;GAT1C,QAAQA,EAAM;GACd,SAASA,EAAM;GACf,WAAWD,EAAQ;GACnB,kBAAkBA,EAAQ;GAC1B,GAAIC,EAAM,aAAa,KAAA,IAA2C,CAAC,IAAhC,EAAE,UAAUA,EAAM,SAAS;GAC9D,GAAIA,EAAM,iBAAiB,KAAA,IAAmD,CAAC,IAAxC,EAAE,cAAcA,EAAM,aAAa;GAC1E,GAAIA,EAAM,eAAe,KAAA,IAA+C,CAAC,IAApC,EAAE,YAAYA,EAAM,WAAW;GACpE,GAAIA,EAAM,cAAc,KAAA,IAA6C,CAAC,IAAlC,EAAE,WAAWA,EAAM,UAAU;EAER,GAAG,SAAS;EAEhD;CAAQ;AAC/B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,kBAAkB,GAA6D;CAC9F,OAAO,iBAAiBA,GAAO,QAAQ;AACxC;;;;;;AAOA,eAAe,iBACd,GACA,GAC+B;CAC/B,IAAME,IAAuB,MAAMC,EAAcH,EAAM,SAAS,GAC1DI,IACLC,MAAc,YACXC,EAA0BJ,CAAoB,IAC9CF,EAAM,sBAAsB,KAAA,IAC3B,KAAA,IACAO,EAAoB,oBAAoBP,EAAM,iBAAiB,CAAC,GAC/DQ,IAAqBC,EAAsBT,EAAM,kBAAkBA,EAAM,SAAS,GAClFU,IAAW,gBAAgBV,EAAM,QAAQ;CAC/C,AAAIW,EAAiBX,EAAM,MAAM,KAChCY,EACC,mCACA,+CACD;CAED,IAAMC,IAAiBF,EAAiBX,EAAM,OAAO,GAC/Cc,IAAaC,EAClBb,GACAE,GACAJ,EAAM,YACNa,CACD,GACMG,IAAiBC,EAAS;EAC/BC,EAAgB,GAAGC,EAAkB,CAAC,CAAC;EACvC,mBAAmBnB,EAAM,YAAY;EACrCoB,EAA0BZ,CAAkB;EAC5Ca,EAAWrB,EAAM,MAAM;EACvBiB,EAAS,CAACK,EAAKZ,EAAS,SAAS,GAAGY,EAAKZ,EAAS,QAAQ,CAAC,CAAC;EAC5DW,EAAWrB,EAAM,OAAO;EACxBE;EACAgB,EAAgB,GAAGD,EAASH,CAAU,CAAC;CACxC,CAAC,GAEKS,IAAiB,MAAMC,EAC5BxB,EAAM,kBACNQ,GACAQ,CACD;CAOA,OAAO,uBANgBC,EAAS;EAC/BD;EACAI,EAA0BZ,CAAkB;EAC5CiB,EAAUF,CAAc;CACzB,CAE2C,CAAC;AAC7C;;AAGA,SAAS,oBAAoB,GAAoE;CAChG,IAAI;EACH,OAAOG,EAA2BC,CAAM;CACzC,SAASC,GAAO;EAEf,OADAC,EAAqBD,GAAOE,CAAoB,GACzClB,EACN,8BACA,4DACD;CACD;AACD;;;;;;;AAQA,SAAS,uBAAuB,GAAsC;CACrE,OAAO;EACN;EACA,KAAKmB,EAAU,eAAeC,CAAG;EACjC,QAAQC,EAAaD,CAAG;CACzB;AACD;;;;;;;AAsBA,SAAS,gBAAgB,GAAoD;CAC5E,IAAME,IAAYlC,GAAO,6BAAa,IAAI,KAAK,GACzCmC,IAAWnC,GAAO,YAAY,QAAQkC,GAAWlC,GAAO,QAAQ,EAAE;CAaxE,QAZI,OAAO,MAAMkC,EAAU,QAAQ,CAAC,KAAK,OAAO,MAAMC,EAAS,QAAQ,CAAC,MACvEvB,EACC,yBACA,4CACD,GAEGuB,EAAS,QAAQ,KAAKD,EAAU,QAAQ,KAC3CtB,EACC,wCACA,kCACD,GAEM;EAAE;EAAW;CAAS;AAC9B;;;;;;;;AASA,SAAS,QAAQ,GAAY,GAAoB;CAChD,IAAMwB,IAAM,IAAI,KAAKC,EAAK,QAAQ,CAAC;CAEnC,OADAD,EAAI,WAAWA,EAAI,WAAW,IAAIE,CAAI,GAC/BF;AACR;;;;;;;;;AAaA,SAAS,mBAAmB,GAAkD;CAC7E,IAAIG,MAAiB,KAAA,GACpB,OAAOC,EAAQ,mBAAmB,CAAC;CAEpC,IAAIC,IAAQ;CACZ,OAAOA,IAAQF,EAAa,UAAUA,EAAaE,OAAW,IAC7D,KAAS;CAEV,IAAMC,IAAYH,EAAa,SAASE,CAAK,GACvCE,IAAQD,EAAU;CAaxB,OAZIC,MAAU,KAAA,KACb/B,EACC,8BACA,yCACD,GAEG8B,EAAU,SAAU,OAAS,OAAgB,MAChD9B,EACC,0BACA,wCACD,GAEM4B,EAAQE,CAAS;AACzB;;;;;;AAOA,SAAS,qBAAiC;CACzC,IAAME,IAASC,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC;CAM7D,OAJA,EAAO,MADOD,EAAO,MAAM,KACP,MACfA,EAAO,MAAM,OAAO,MACxB,EAAO,KAAK,IAENA;AACR"}
@@ -1,9 +1,11 @@
1
- import { NameAttribute, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName } from "./name.js";
2
- import { AuthorityInfoAccessMethod, AuthorityInformationAccess, 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, encodeAuthorityInfoAccess, encodeBasicConstraints, encodeCertificatePolicies, encodeCrlDistributionPoints, encodeExtendedKeyUsage, encodeExtension, encodeInhibitAnyPolicy, encodeKeyUsage, encodeNameConstraints, encodePolicyConstraints, encodePolicyMappings, encodeSubjectAltName, getAuthorityInfoAccessMethodOid, getExtendedKeyUsageOid, parseAuthorityInfoAccessMethodOid, parseExtendedKeyUsageOid } from "./extensions.js";
3
1
  import { SignatureProfileInput } from "../internal/crypto/signing.js";
4
- //#region src/x509/csr.d.ts
2
+ import { canonicalDnKey, compareDistinguishedNames, isWithinDirectoryNameSubtree } from "../internal/shared/dn.js";
3
+ import { NameAttribute, NameEncoderErrorCode, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName } from "./name.js";
4
+ import { ExtensionEncoderErrorCode } from "../internal/x509/extension-errors.js";
5
+ import { allOnesMaskForIpAddress, decodeIpAddress, normalizeIpAddress, parseIpAddressToBytes } from "../internal/shared/ip.js";
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";
5
7
  /** Input for {@linkcode createCertificateSigningRequest}. */
6
- interface CreateCsrInput {
8
+ export interface CreateCsrInput {
7
9
  /** Distinguished name for the CSR subject (e.g. `{ commonName: 'example.com' }`). */
8
10
  readonly subject: NameInput;
9
11
  /** WebCrypto public key to embed in the CSR's SubjectPublicKeyInfo. */
@@ -16,7 +18,7 @@ interface CreateCsrInput {
16
18
  readonly signature?: SignatureProfileInput;
17
19
  }
18
20
  /** DER, PEM, and base64 encodings of a CSR produced by {@linkcode createCertificateSigningRequest}. */
19
- interface CsrMaterial {
21
+ export interface CsrMaterial {
20
22
  /** Raw DER-encoded PKCS#10 CertificationRequest. */
21
23
  readonly der: Uint8Array;
22
24
  /** PEM-armored CSR (`-----BEGIN CERTIFICATE REQUEST-----`). */
@@ -48,7 +50,6 @@ interface CsrMaterial {
48
50
  * console.log(csr.pem);
49
51
  * ```
50
52
  */
51
- declare function createCertificateSigningRequest(input: CreateCsrInput): Promise<CsrMaterial>;
52
- //#endregion
53
- export { type AuthorityInfoAccessMethod, type AuthorityInformationAccess, 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 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 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 buildCertificateExtensions, type buildRequestedExtensions, createCertificateSigningRequest, 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 parseAuthorityInfoAccessMethodOid, type parseExtendedKeyUsageOid };
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 };
54
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"}