micro509 0.17.1 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +165 -6
- package/dist/crypto/crypto.d.ts +12 -4
- package/dist/crypto/crypto.js +30 -17
- package/dist/crypto/crypto.js.map +1 -1
- package/dist/crypto.d.ts +8 -2
- package/dist/der/der.d.ts +14 -4
- package/dist/der/der.js +19 -19
- package/dist/der/der.js.map +1 -1
- package/dist/der.d.ts +26 -2
- package/dist/der.js +4 -4
- package/dist/index.d.ts +84 -16
- package/dist/index.js +19 -19
- package/dist/internal/asn1/asn1.d.ts +1 -2
- package/dist/internal/asn1/asn1.js +10 -2
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/ber.js.map +1 -1
- package/dist/internal/asn1/decode-refusal.js.map +1 -1
- package/dist/internal/asn1/der.d.ts +1 -2
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js +71 -353
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/asn1/oids.json.js +357 -0
- package/dist/internal/asn1/oids.json.js.map +1 -0
- package/dist/internal/crypto/algorithm-names.js +1 -1
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/ecdsa.js.map +1 -1
- package/dist/internal/crypto/hash.js.map +1 -1
- package/dist/internal/crypto/pbes2.d.ts +1 -2
- package/dist/internal/crypto/pbes2.js +70 -70
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/prime-ec.js +37 -0
- package/dist/internal/crypto/prime-ec.js.map +1 -0
- package/dist/internal/crypto/rsa-pss.js +50 -50
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +41 -2
- package/dist/internal/crypto/sig-verify.js +125 -38
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/crypto/signing.d.ts +1 -2
- package/dist/internal/crypto/signing.js +26 -26
- package/dist/internal/crypto/signing.js.map +1 -1
- package/dist/internal/jose/base64url.js.map +1 -1
- package/dist/internal/jose/json-data.js +108 -0
- package/dist/internal/jose/json-data.js.map +1 -0
- package/dist/internal/jose/strict-json.d.ts +1 -2
- package/dist/internal/jose/strict-json.js.map +1 -1
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.d.ts +1 -2
- package/dist/internal/shared/dn.js +1 -1
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/idna.js.map +1 -1
- package/dist/internal/shared/ip.d.ts +1 -2
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/shared/mailbox.js.map +1 -1
- package/dist/internal/shared/punycode.js.map +1 -1
- package/dist/internal/shared/uri-host.js.map +1 -1
- package/dist/internal/verify/name-constraints-engine.js +64 -64
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/verify/policy-engine.js +1 -1
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/verify/spki-distrust.js.map +1 -1
- package/dist/internal/verify/verify-path.d.ts +1 -2
- package/dist/internal/verify/verify-path.js +234 -128
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/internal/x509/directory-name.js +10 -10
- package/dist/internal/x509/directory-name.js.map +1 -1
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.d.ts +1 -2
- package/dist/internal/x509/extension-errors.js.map +1 -1
- package/dist/internal/x509/extension-registry.js +18 -18
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-profile.js +9 -9
- package/dist/internal/x509/general-name-profile.js.map +1 -1
- package/dist/internal/x509/general-name.js +32 -32
- package/dist/internal/x509/general-name.js.map +1 -1
- package/dist/internal/x509/name-fields.js +1 -1
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/internal/x509/or-address.js.map +1 -1
- package/dist/jose/base64url.d.ts +4 -0
- package/dist/jose/base64url.js +14 -0
- package/dist/jose/base64url.js.map +1 -0
- package/dist/jose/errors.d.ts +9 -3
- package/dist/jose/errors.js.map +1 -1
- package/dist/jose/jwe.d.ts +64 -0
- package/dist/jose/jwe.js +188 -0
- package/dist/jose/jwe.js.map +1 -0
- package/dist/jose/jwks.d.ts +38 -10
- package/dist/jose/jwks.js +156 -96
- package/dist/jose/jwks.js.map +1 -1
- package/dist/jose/jws.d.ts +8 -6
- package/dist/jose/jws.js +216 -170
- package/dist/jose/jws.js.map +1 -1
- package/dist/jose/jwt.d.ts +8 -2
- package/dist/jose/jwt.js +98 -98
- package/dist/jose/jwt.js.map +1 -1
- package/dist/jose/remote-jwks.d.ts +1 -2
- package/dist/jose/remote-jwks.js +106 -108
- package/dist/jose/remote-jwks.js.map +1 -1
- package/dist/jose.d.ts +15 -4
- package/dist/jose.js +7 -5
- package/dist/kdf/argon2-arithmetic.js.map +1 -1
- package/dist/kdf/argon2-core.js.map +1 -1
- package/dist/kdf/argon2-memory.js.map +1 -1
- package/dist/kdf/argon2-portable.js.map +1 -1
- package/dist/kdf/argon2.d.ts +7 -2
- package/dist/kdf/argon2.js.map +1 -1
- package/dist/kdf.d.ts +6 -0
- package/dist/keys/keys.d.ts +31 -6
- package/dist/keys/keys.js +315 -233
- package/dist/keys/keys.js.map +1 -1
- package/dist/keys.d.ts +11 -2
- package/dist/keys.js +2 -2
- package/dist/pem/pem.d.ts +1 -2
- package/dist/pem/pem.js +40 -25
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.d.ts +6 -0
- package/dist/pkcs/pfx.d.ts +2 -3
- package/dist/pkcs/pfx.js +142 -142
- package/dist/pkcs/pfx.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.d.ts +1 -2
- package/dist/pkcs/pkcs12-mac.js +122 -122
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +24 -3
- package/dist/pkcs/pkcs7.js +294 -256
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/pkcs.d.ts +10 -1
- package/dist/pkcs.js +4 -4
- package/dist/result/result.d.ts +1 -2
- package/dist/result/result.js.map +1 -1
- package/dist/result.d.ts +6 -0
- package/dist/revocation/chain.d.ts +69 -16
- package/dist/revocation/chain.js +431 -303
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +67 -14
- package/dist/revocation/crl.js +656 -366
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +78 -24
- package/dist/revocation/ocsp.js +622 -436
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +68 -14
- package/dist/revocation/revocation.js +195 -74
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +14 -5
- package/dist/revocation.js +4 -4
- package/dist/ssh/ssh.d.ts +2 -3
- package/dist/ssh/ssh.js +165 -170
- package/dist/ssh/ssh.js.map +1 -1
- package/dist/ssh/wire.d.ts +1 -2
- package/dist/ssh/wire.js +10 -10
- package/dist/ssh/wire.js.map +1 -1
- package/dist/ssh.d.ts +8 -0
- package/dist/verify/identity.d.ts +3 -4
- package/dist/verify/identity.js +33 -33
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/name-constraints.d.ts +9 -2
- package/dist/verify/policy.d.ts +9 -2
- package/dist/verify/verify.d.ts +85 -34
- package/dist/verify/verify.js +276 -226
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +12 -2
- package/dist/x509/certificate.d.ts +4 -5
- package/dist/x509/certificate.js +40 -40
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.d.ts +3 -4
- package/dist/x509/csr.js +15 -15
- package/dist/x509/csr.js.map +1 -1
- package/dist/x509/extensions.d.ts +1 -2
- package/dist/x509/extensions.js +165 -165
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/fingerprint.d.ts +1 -2
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509/name-text.d.ts +1 -2
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.d.ts +1 -2
- package/dist/x509/name.js +15 -15
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +9 -6
- package/dist/x509/parse.js +394 -394
- package/dist/x509/parse.js.map +1 -1
- package/dist/x509.d.ts +17 -4
- package/dist/x509.js +8 -8
- package/package.json +32 -33
- package/dist/internal/asn1/oids2.js +0 -75
- package/dist/internal/asn1/oids2.js.map +0 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { KeyAlgorithmInput, KeyPairMaterial } from "../keys/keys.js";
|
|
2
1
|
import { SignatureProfileInput } from "../internal/crypto/signing.js";
|
|
2
|
+
import { KeyAlgorithmInput, KeyPairMaterial } from "../keys/keys.js";
|
|
3
3
|
import { canonicalDnKey, compareDistinguishedNames, isWithinDirectoryNameSubtree } from "../internal/shared/dn.js";
|
|
4
|
-
import {
|
|
4
|
+
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
5
|
import { ExtensionEncoderErrorCode } from "../internal/x509/extension-errors.js";
|
|
6
6
|
import { allOnesMaskForIpAddress, decodeIpAddress, normalizeIpAddress, parseIpAddressToBytes } from "../internal/shared/ip.js";
|
|
7
|
-
import {
|
|
7
|
+
import { NameAttribute, NameEncoderErrorCode, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName } from "./name.js";
|
|
8
8
|
import { ParsedCertificate } from "./parse.js";
|
|
9
9
|
/** Machine-readable reason a certificate builder rejected its construction input. */
|
|
10
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";
|
|
@@ -208,5 +208,4 @@ export declare function createSelfSignedCertificate(input: CreateSelfSignedCerti
|
|
|
208
208
|
* @returns The encoded certificate material.
|
|
209
209
|
*/
|
|
210
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 };
|
|
212
|
-
//# sourceMappingURL=certificate.d.ts.map
|
|
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 };
|
package/dist/x509/certificate.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { getCrypto as
|
|
5
|
-
import { base64Encode as
|
|
6
|
-
import { pemEncode as d } from "../pem/pem.js";
|
|
1
|
+
import { rethrowDecodeRefusal as e } from "../internal/asn1/decode-refusal.js";
|
|
2
|
+
import { bitString as t, explicitContext as n, integer as r, integerFromNumber as i, sequence as a, time as o } from "../internal/asn1/der.js";
|
|
3
|
+
import { encodeAlgorithmIdentifier as s, getSignatureAlgorithm as c, signBytes as l } from "../internal/crypto/signing.js";
|
|
4
|
+
import { getCrypto as u } from "../internal/crypto/webcrypto.js";
|
|
5
|
+
import { base64Encode as d } from "../internal/shared/base64.js";
|
|
7
6
|
import { exportSpkiDer as f, generateKeyPair as p } from "../keys/keys.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import { buildCertificateExtensions as
|
|
7
|
+
import { pemEncode as m } from "../pem/pem.js";
|
|
8
|
+
import { DECODE_REFUSAL_CODES as h, throwMicro509Error as g } from "../result/result.js";
|
|
9
|
+
import { buildCertificateExtensions as _, buildSubjectKeyIdentifier as v, issuerKeyIdentifier as y } from "./extensions.js";
|
|
10
|
+
import { encodeName as b, isNameInputEmpty as x } from "./name.js";
|
|
11
11
|
import { parseCertificateFromSource as S } from "./parse.js";
|
|
12
12
|
// src/x509/certificate.ts
|
|
13
13
|
/**
|
|
@@ -82,31 +82,31 @@ function createCertificate(e) {
|
|
|
82
82
|
* `input.issuerCertificate`, or from its own subject key when `authority` is
|
|
83
83
|
* `'subject'` (RFC 5280 §4.2.1.1).
|
|
84
84
|
*/
|
|
85
|
-
async function issueCertificate(e,
|
|
86
|
-
let
|
|
87
|
-
|
|
88
|
-
let
|
|
89
|
-
|
|
85
|
+
async function issueCertificate(e, r) {
|
|
86
|
+
let u = await f(e.publicKey), d = r === "subject" ? v(u) : e.issuerCertificate === void 0 ? void 0 : y(issuerCertificateOf(e.issuerCertificate)), p = c(e.signerPrivateKey, e.signature), m = resolveValidity(e.validity);
|
|
87
|
+
x(e.issuer) && g("issuer_distinguished_name_empty", "issuer must be a non-empty distinguished name");
|
|
88
|
+
let h = x(e.subject), S = _(u, d, e.extensions, h), C = a([
|
|
89
|
+
n(0, i(2)),
|
|
90
90
|
encodeSerialNumber(e.serialNumber),
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
]), w = await
|
|
98
|
-
return materializeCertificate(
|
|
91
|
+
s(p),
|
|
92
|
+
b(e.issuer),
|
|
93
|
+
a([o(m.notBefore), o(m.notAfter)]),
|
|
94
|
+
b(e.subject),
|
|
95
|
+
u,
|
|
96
|
+
n(3, a(S))
|
|
97
|
+
]), w = await l(e.signerPrivateKey, p, C);
|
|
98
|
+
return materializeCertificate(a([
|
|
99
99
|
C,
|
|
100
|
-
|
|
101
|
-
|
|
100
|
+
s(p),
|
|
101
|
+
t(w)
|
|
102
102
|
]));
|
|
103
103
|
}
|
|
104
104
|
/** The parsed issuer certificate of a certificate being built. */
|
|
105
|
-
function issuerCertificateOf(
|
|
105
|
+
function issuerCertificateOf(t) {
|
|
106
106
|
try {
|
|
107
|
-
return S(
|
|
108
|
-
} catch (
|
|
109
|
-
return
|
|
107
|
+
return S(t);
|
|
108
|
+
} catch (t) {
|
|
109
|
+
return e(t, h), g("issuer_certificate_invalid", "issuerCertificate must be a PEM, DER or parsed certificate");
|
|
110
110
|
}
|
|
111
111
|
}
|
|
112
112
|
/**
|
|
@@ -118,8 +118,8 @@ function issuerCertificateOf(r) {
|
|
|
118
118
|
function materializeCertificate(e) {
|
|
119
119
|
return {
|
|
120
120
|
der: e,
|
|
121
|
-
pem:
|
|
122
|
-
base64:
|
|
121
|
+
pem: m("CERTIFICATE", e),
|
|
122
|
+
base64: d(e)
|
|
123
123
|
};
|
|
124
124
|
}
|
|
125
125
|
/**
|
|
@@ -129,10 +129,10 @@ function materializeCertificate(e) {
|
|
|
129
129
|
* @returns A concrete `notBefore` and `notAfter` pair.
|
|
130
130
|
*/
|
|
131
131
|
function resolveValidity(e) {
|
|
132
|
-
let
|
|
133
|
-
return (Number.isNaN(
|
|
134
|
-
notBefore:
|
|
135
|
-
notAfter:
|
|
132
|
+
let t = e?.notBefore ?? /* @__PURE__ */ new Date(), n = e?.notAfter ?? addDays(t, e?.days ?? 30);
|
|
133
|
+
return (Number.isNaN(t.getTime()) || Number.isNaN(n.getTime())) && g("validity_date_invalid", "notBefore and notAfter must be valid dates"), n.getTime() <= t.getTime() && g("validity_not_after_before_not_before", "notAfter must be after notBefore"), {
|
|
134
|
+
notBefore: t,
|
|
135
|
+
notAfter: n
|
|
136
136
|
};
|
|
137
137
|
}
|
|
138
138
|
/**
|
|
@@ -155,11 +155,11 @@ function addDays(e, t) {
|
|
|
155
155
|
* `serial_number_too_long` when RFC 5280 §4.1.2.2 forbids the value.
|
|
156
156
|
*/
|
|
157
157
|
function encodeSerialNumber(e) {
|
|
158
|
-
if (e === void 0) return
|
|
159
|
-
let
|
|
160
|
-
for (;
|
|
161
|
-
let
|
|
162
|
-
return i === void 0 &&
|
|
158
|
+
if (e === void 0) return r(randomSerialNumber());
|
|
159
|
+
let t = 0;
|
|
160
|
+
for (; t < e.length && e[t] === 0;) t += 1;
|
|
161
|
+
let n = e.subarray(t), i = n[0];
|
|
162
|
+
return i === void 0 && g("serial_number_not_positive", "serialNumber must be a positive integer"), n.length + +(i >= 128) > 20 && g("serial_number_too_long", "serialNumber must not exceed 20 octets"), r(n);
|
|
163
163
|
}
|
|
164
164
|
/**
|
|
165
165
|
* Generate a random positive serial number suitable for certificate issuance.
|
|
@@ -167,7 +167,7 @@ function encodeSerialNumber(e) {
|
|
|
167
167
|
* @returns A 16-byte positive serial number.
|
|
168
168
|
*/
|
|
169
169
|
function randomSerialNumber() {
|
|
170
|
-
let e =
|
|
170
|
+
let e = u().getRandomValues(/* @__PURE__ */ new Uint8Array(16));
|
|
171
171
|
return e[0] = (e[0] ?? 0) & 127, (e[0] ?? 0) === 0 && (e[0] = 1), e;
|
|
172
172
|
}
|
|
173
173
|
export { createCertificate, createSelfSignedCertificate };
|
|
@@ -1 +1 @@
|
|
|
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,IA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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
|
+
{"version":3,"file":"certificate.js","names":["rethrowDecodeRefusal","bitString","explicitContext","integer","integerFromNumber","sequence","time","encodeAlgorithmIdentifier","getSignatureAlgorithm","signBytes","getCrypto","base64Encode","exportSpkiDer","generateKeyPair","pemEncode","DECODE_REFUSAL_CODES","throwMicro509Error","buildCertificateExtensions","buildSubjectKeyIdentifier","issuerKeyIdentifier","encodeName","isNameInputEmpty","parseCertificateFromSource","input","keyPair","authority","subjectPublicKeyInfo","authorityKeyIdentifier","signatureAlgorithm","validity","subjectIsEmpty","extensions","tbsCertificate","signatureValue","source","error","der","notBefore","notAfter","date","days","out","serialNumber","start","magnitude","first","serial"],"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,4BACrBuB,GACuC;CACvC,IAAMC,IAAUD,EAAM,WAAY,MAAMV,EAAgBU,EAAM,SAAS;CAavE,OAAO;EAAE,aAAA,MAFiB,iBAAiB;GAT1C,QAAQA,EAAM;GACd,SAASA,EAAM;GACf,WAAWC,EAAQ;GACnB,kBAAkBA,EAAQ;GAC1B,GAAID,EAAM,aAAa,KAAA,IAA2C,CAAC,IAAh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AAgB,MAChD7B,EACC,0BACA,wCACD,GAEMb,EAAQyC,CAAS;AACzB;;;;;;AAOA,SAAS,qBAAiC;CACzC,IAAME,IAASpC,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC;CAM7D,OAJAoC,EAAO,MADOA,EAAO,MAAM,KACP,MACfA,EAAO,MAAM,OAAO,MACxBA,EAAO,KAAK,IAENA;AACR"}
|
package/dist/x509/csr.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { SignatureProfileInput } from "../internal/crypto/signing.js";
|
|
2
2
|
import { canonicalDnKey, compareDistinguishedNames, isWithinDirectoryNameSubtree } from "../internal/shared/dn.js";
|
|
3
|
-
import {
|
|
3
|
+
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";
|
|
4
4
|
import { ExtensionEncoderErrorCode } from "../internal/x509/extension-errors.js";
|
|
5
5
|
import { allOnesMaskForIpAddress, decodeIpAddress, normalizeIpAddress, parseIpAddressToBytes } from "../internal/shared/ip.js";
|
|
6
|
-
import {
|
|
6
|
+
import { NameAttribute, NameEncoderErrorCode, NameFieldKey, NameInput, NameObject, RelativeDistinguishedNameInput, encodeName, encodeRelativeDistinguishedName } from "./name.js";
|
|
7
7
|
/** Input for {@linkcode createCertificateSigningRequest}. */
|
|
8
8
|
export interface CreateCsrInput {
|
|
9
9
|
/** Distinguished name for the CSR subject (e.g. `{ commonName: 'example.com' }`). */
|
|
@@ -51,5 +51,4 @@ export interface CsrMaterial {
|
|
|
51
51
|
* ```
|
|
52
52
|
*/
|
|
53
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 };
|
|
55
|
-
//# sourceMappingURL=csr.d.ts.map
|
|
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 };
|
package/dist/x509/csr.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { bitString as e, concatBytes as t, implicitConstructedContext as n, integerFromNumber as r, objectIdentifier as i, sequence as a, setOf as o } from "../internal/asn1/der.js";
|
|
2
|
-
import { OIDS as s } from "../internal/asn1/
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { exportSpkiDer as
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
2
|
+
import { OIDS as s } from "../internal/asn1/oids.js";
|
|
3
|
+
import { encodeAlgorithmIdentifier as c, getSignatureAlgorithm as l, signBytes as u } from "../internal/crypto/signing.js";
|
|
4
|
+
import { base64Encode as d } from "../internal/shared/base64.js";
|
|
5
|
+
import { exportSpkiDer as f } from "../keys/keys.js";
|
|
6
|
+
import { pemEncode as p } from "../pem/pem.js";
|
|
7
|
+
import { buildRequestedExtensions as m } from "./extensions.js";
|
|
8
|
+
import { encodeName as h } from "./name.js";
|
|
9
9
|
// src/x509/csr.ts
|
|
10
10
|
/**
|
|
11
11
|
* PKCS#10 Certificate Signing Request (CSR) creation.
|
|
@@ -40,25 +40,25 @@ import { buildRequestedExtensions as h } from "./extensions.js";
|
|
|
40
40
|
* ```
|
|
41
41
|
*/
|
|
42
42
|
async function createCertificateSigningRequest(i) {
|
|
43
|
-
let o =
|
|
43
|
+
let o = l(i.signerPrivateKey, i.signature), s = await f(i.publicKey), m = buildAttributes(i.extensions), g = a([
|
|
44
44
|
r(0),
|
|
45
|
-
|
|
45
|
+
h(i.subject),
|
|
46
46
|
s,
|
|
47
|
-
n(0, t(
|
|
48
|
-
]), _ = await
|
|
47
|
+
n(0, t(m))
|
|
48
|
+
]), _ = await u(i.signerPrivateKey, o, g), v = a([
|
|
49
49
|
g,
|
|
50
|
-
|
|
50
|
+
c(o),
|
|
51
51
|
e(_)
|
|
52
52
|
]);
|
|
53
53
|
return {
|
|
54
54
|
der: v,
|
|
55
|
-
pem:
|
|
56
|
-
base64:
|
|
55
|
+
pem: p("CERTIFICATE REQUEST", v),
|
|
56
|
+
base64: d(v)
|
|
57
57
|
};
|
|
58
58
|
}
|
|
59
59
|
/** Encodes extensions into a CSR extensionRequest attribute, or returns empty. */
|
|
60
60
|
function buildAttributes(e) {
|
|
61
|
-
let t =
|
|
61
|
+
let t = m(e);
|
|
62
62
|
return t.length === 0 ? [] : [a([i(s.extensionRequest), o([a(t)])])];
|
|
63
63
|
}
|
|
64
64
|
export { createCertificateSigningRequest };
|
package/dist/x509/csr.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"csr.js","names":["
|
|
1
|
+
{"version":3,"file":"csr.js","names":["bitString","concatBytes","implicitConstructedContext","integerFromNumber","objectIdentifier","sequence","setOf","OIDS","encodeAlgorithmIdentifier","getSignatureAlgorithm","signBytes","base64Encode","exportSpkiDer","pemEncode","buildRequestedExtensions","encodeName","input","signatureAlgorithm","spki","attributes","certificationRequestInfo","normalizedSignature","der","extensions","builtExtensions"],"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,gCAAgCgB,GAA6C;CAClG,IAAMC,IAAqBR,EAAsBO,EAAM,kBAAkBA,EAAM,SAAS,GAClFE,IAAO,MAAMN,EAAcI,EAAM,SAAS,GAC1CG,IAAa,gBAAgBH,EAAM,UAAU,GAC7CI,IAA2Bf,EAAS;EACzCF,EAAkB,CAAC;EACnBY,EAAWC,EAAM,OAAO;EACxBE;EACAhB,EAA2B,GAAGD,EAAYkB,CAAU,CAAC;CACtD,CAAC,GACKE,IAAsB,MAAMX,EACjCM,EAAM,kBACNC,GACAG,CACD,GAEME,IAAMjB,EAAS;EACpBe;EACAZ,EAA0BS,CAAkB;EAC5CjB,EAAUqB,CAAmB;CAC9B,CAAC;CACD,OAAO;EACNC;EACA,KAAKT,EAAU,uBAAuBS,CAAG;EACzC,QAAQX,EAAaW,CAAG;CACzB;AACD;;AAGA,SAAS,gBAAgBC,GAAkE;CAC1F,IAAMC,IAAkBV,EAAyBS,CAAU;CAI3D,OAHIC,EAAgB,WAAW,IACvB,CAAC,IAEF,CAACnB,EAAS,CAACD,EAAiBG,EAAK,gBAAgB,GAAGD,EAAM,CAACD,EAASmB,CAAe,CAAC,CAAC,CAAC,CAAC,CAAC;AAChG"}
|
|
@@ -729,5 +729,4 @@ export declare function parseAuthorityInfoAccessMethodOid(oid: string): Authorit
|
|
|
729
729
|
* A parsed certificate carries the input as `subjectPublicKeyInfoDer`.
|
|
730
730
|
*/
|
|
731
731
|
export declare function buildSubjectKeyIdentifier(subjectPublicKeyInfo: Uint8Array): Uint8Array;
|
|
732
|
-
export { type ExtensionEncoderErrorCode, allOnesMaskForIpAddress, decodeIpAddress, normalizeIpAddress, parseIpAddressToBytes };
|
|
733
|
-
//# sourceMappingURL=extensions.d.ts.map
|
|
732
|
+
export { type ExtensionEncoderErrorCode, allOnesMaskForIpAddress, decodeIpAddress, normalizeIpAddress, parseIpAddressToBytes };
|