@push.rocks/smartcrypto 3.0.0 → 3.2.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.
@@ -0,0 +1,327 @@
1
+ import { SmartCryptoError, createSmartCryptoError } from './smartcrypto.errors.js';
2
+ import {
3
+ derTags,
4
+ encodeDerBitString,
5
+ encodeDerBoolean,
6
+ encodeDerElement,
7
+ encodeDerNull,
8
+ encodeDerOctetString,
9
+ encodeDerOid,
10
+ encodeDerSequence,
11
+ encodeDerSmallInteger,
12
+ encodeDerUnsignedInteger,
13
+ } from './smartcrypto.der.js';
14
+ import { getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
15
+ import { encodePem } from './smartcrypto.pem.js';
16
+
17
+ /** The key a self-signed certificate is issued for, signed with SHA-256. */
18
+ export type TSelfSignedCertificateKeyAlgorithm = 'RSA-2048' | 'ECDSA-P256';
19
+
20
+ export interface ISelfSignedCertificateOptions {
21
+ /** The subject and issuer common name, 1 to 64 characters. */
22
+ commonName: string;
23
+ /** `dNSName` subject alternative names, such as `localhost` or `*.example.com`. */
24
+ dnsNames?: string[];
25
+ /** `iPAddress` subject alternative names in IPv4 dotted-quad or IPv6 text form. */
26
+ ipAddresses?: string[];
27
+ /** Start of the validity period, truncated to whole seconds. Defaults to now. */
28
+ notBefore?: Date;
29
+ /** End of the validity period, truncated to whole seconds. Defaults to `notBefore` plus 365 days. */
30
+ notAfter?: Date;
31
+ /** Defaults to `RSA-2048`. */
32
+ keyAlgorithm?: TSelfSignedCertificateKeyAlgorithm;
33
+ }
34
+
35
+ export interface ISelfSignedCertificate {
36
+ /** The certificate as a `-----BEGIN CERTIFICATE-----` PEM. */
37
+ certificatePem: string;
38
+ /** The certificate's key as an unencrypted PKCS#8 `-----BEGIN PRIVATE KEY-----` PEM. */
39
+ privateKeyPem: string;
40
+ }
41
+
42
+ interface ISelfSignedKeyProfile {
43
+ generateParams: RsaHashedKeyGenParams | EcKeyGenParams;
44
+ signParams: Algorithm | EcdsaParams;
45
+ /** The DER `AlgorithmIdentifier` of the certificate signature. */
46
+ encodeSignatureAlgorithm: () => Uint8Array;
47
+ /** The DER `signatureValue` content for a WebCrypto signature. */
48
+ encodeSignature: (signatureArg: Uint8Array) => Uint8Array;
49
+ /** The `KeyUsage` bits as one byte and its count of trailing padding bits. */
50
+ keyUsage: { bits: number; unusedBits: number };
51
+ }
52
+
53
+ const oids = {
54
+ commonName: '2.5.4.3',
55
+ basicConstraints: '2.5.29.19',
56
+ keyUsage: '2.5.29.15',
57
+ extendedKeyUsage: '2.5.29.37',
58
+ subjectAltName: '2.5.29.17',
59
+ serverAuth: '1.3.6.1.5.5.7.3.1',
60
+ sha256WithRsaEncryption: '1.2.840.113549.1.1.11',
61
+ ecdsaWithSha256: '1.2.840.10045.4.3.2',
62
+ } as const;
63
+
64
+ const generalNameTags = {
65
+ dnsName: 0x82,
66
+ ipAddress: 0x87,
67
+ } as const;
68
+
69
+ const p256CoordinateBytes = 32;
70
+ const serialNumberBytes = 16;
71
+ const defaultValidityMilliseconds = 365 * 24 * 60 * 60 * 1000;
72
+
73
+ const keyProfiles: Record<TSelfSignedCertificateKeyAlgorithm, ISelfSignedKeyProfile> = {
74
+ 'RSA-2048': {
75
+ generateParams: {
76
+ name: 'RSASSA-PKCS1-v1_5',
77
+ modulusLength: 2048,
78
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
79
+ hash: 'SHA-256',
80
+ },
81
+ signParams: { name: 'RSASSA-PKCS1-v1_5' },
82
+ encodeSignatureAlgorithm: () =>
83
+ encodeDerSequence(encodeDerOid(oids.sha256WithRsaEncryption), encodeDerNull()),
84
+ encodeSignature: (signatureArg) => signatureArg,
85
+ // digitalSignature (0) and keyEncipherment (2)
86
+ keyUsage: { bits: 0xa0, unusedBits: 5 },
87
+ },
88
+ 'ECDSA-P256': {
89
+ generateParams: { name: 'ECDSA', namedCurve: 'P-256' },
90
+ signParams: { name: 'ECDSA', hash: 'SHA-256' },
91
+ // RFC 5758: the parameters of ecdsa-with-SHA256 are absent.
92
+ encodeSignatureAlgorithm: () => encodeDerSequence(encodeDerOid(oids.ecdsaWithSha256)),
93
+ // WebCrypto returns r || s; X.509 carries Ecdsa-Sig-Value ::= SEQUENCE { r, s }.
94
+ encodeSignature: (signatureArg) => {
95
+ if (signatureArg.byteLength !== 2 * p256CoordinateBytes) {
96
+ throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
97
+ }
98
+ return encodeDerSequence(
99
+ encodeDerUnsignedInteger(signatureArg.subarray(0, p256CoordinateBytes)),
100
+ encodeDerUnsignedInteger(signatureArg.subarray(p256CoordinateBytes)),
101
+ );
102
+ },
103
+ // digitalSignature (0)
104
+ keyUsage: { bits: 0x80, unusedBits: 7 },
105
+ },
106
+ };
107
+
108
+ const invalidArgument = () => createSmartCryptoError('INVALID_ARGUMENT');
109
+
110
+ const isKeyAlgorithm = (valueArg: unknown): valueArg is TSelfSignedCertificateKeyAlgorithm =>
111
+ valueArg === 'RSA-2048' || valueArg === 'ECDSA-P256';
112
+
113
+ // ========================================
114
+ // Input validation
115
+ // ========================================
116
+ const controlCharacterPattern = /[\u0000-\u001f\u007f-\u009f]/;
117
+ const dnsNamePattern = /^[\x21-\x7e]{1,253}$/;
118
+ const ipv4Pattern = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
119
+ const ipv6GroupPattern = /^[0-9A-Fa-f]{1,4}$/;
120
+
121
+ const requireCommonName = (valueArg: unknown): string => {
122
+ if (
123
+ typeof valueArg !== 'string'
124
+ || valueArg.length < 1
125
+ || [...valueArg].length > 64
126
+ || controlCharacterPattern.test(valueArg)
127
+ ) {
128
+ throw invalidArgument();
129
+ }
130
+ return valueArg;
131
+ };
132
+
133
+ const isStringList = (valueArg: unknown): valueArg is string[] =>
134
+ Array.isArray(valueArg) && valueArg.every((entryArg: unknown) => typeof entryArg === 'string');
135
+
136
+ const requireStringList = (valueArg: unknown): string[] => {
137
+ if (valueArg === undefined) {
138
+ return [];
139
+ }
140
+ if (!isStringList(valueArg)) {
141
+ throw invalidArgument();
142
+ }
143
+ return [...valueArg];
144
+ };
145
+
146
+ const requireDate = (valueArg: unknown, defaultArg: number): number => {
147
+ if (valueArg === undefined) {
148
+ return Math.floor(defaultArg / 1000) * 1000;
149
+ }
150
+ if (!(valueArg instanceof Date) || !Number.isFinite(valueArg.getTime())) {
151
+ throw invalidArgument();
152
+ }
153
+ return Math.floor(valueArg.getTime() / 1000) * 1000;
154
+ };
155
+
156
+ const parseIpv6Groups = (textArg: string): number[] => {
157
+ if (textArg === '') {
158
+ return [];
159
+ }
160
+ return textArg.split(':').map((groupArg) => {
161
+ if (!ipv6GroupPattern.test(groupArg)) {
162
+ throw invalidArgument();
163
+ }
164
+ return parseInt(groupArg, 16);
165
+ });
166
+ };
167
+
168
+ /** Encodes an IPv4 or IPv6 address as the 4 or 16 network-order bytes of an `iPAddress`. */
169
+ const encodeIpAddress = (addressArg: string): Uint8Array => {
170
+ const ipv4Match = ipv4Pattern.exec(addressArg);
171
+ if (ipv4Match) {
172
+ return new Uint8Array(ipv4Match.slice(1).map(Number));
173
+ }
174
+ const halves = addressArg.split('::');
175
+ if (halves.length > 2) {
176
+ throw invalidArgument();
177
+ }
178
+ const head = parseIpv6Groups(halves[0]);
179
+ const tail = halves.length === 2 ? parseIpv6Groups(halves[1]) : [];
180
+ const elidedGroups = 8 - head.length - tail.length;
181
+ if (halves.length === 2 ? elidedGroups < 1 : elidedGroups !== 0) {
182
+ throw invalidArgument();
183
+ }
184
+ const groups = [...head, ...new Array<number>(elidedGroups).fill(0), ...tail];
185
+ return new Uint8Array(groups.flatMap((groupArg) => [groupArg >> 8, groupArg & 0xff]));
186
+ };
187
+
188
+ const encodeDnsName = (nameArg: string): Uint8Array => {
189
+ if (!dnsNamePattern.test(nameArg)) {
190
+ throw invalidArgument();
191
+ }
192
+ return encodeDerElement(generalNameTags.dnsName, new TextEncoder().encode(nameArg));
193
+ };
194
+
195
+ // ========================================
196
+ // Certificate encoding
197
+ // ========================================
198
+ /** RFC 5280 4.1.2.5: UTCTime through 2049, GeneralizedTime from 2050. */
199
+ const encodeTime = (timestampArg: number): Uint8Array => {
200
+ const date = new Date(timestampArg);
201
+ const year = date.getUTCFullYear();
202
+ if (year < 1950 || year > 9999) {
203
+ throw invalidArgument();
204
+ }
205
+ const rest = [
206
+ date.getUTCMonth() + 1,
207
+ date.getUTCDate(),
208
+ date.getUTCHours(),
209
+ date.getUTCMinutes(),
210
+ date.getUTCSeconds(),
211
+ ]
212
+ .map((valueArg) => String(valueArg).padStart(2, '0'))
213
+ .join('');
214
+ return year < 2050
215
+ ? encodeDerElement(derTags.utcTime, new TextEncoder().encode(`${String(year % 100).padStart(2, '0')}${rest}Z`))
216
+ : encodeDerElement(derTags.generalizedTime, new TextEncoder().encode(`${year}${rest}Z`));
217
+ };
218
+
219
+ /** A Name with the single RDN `CN=<commonName>`. */
220
+ const encodeCommonNameName = (commonNameArg: string): Uint8Array =>
221
+ encodeDerSequence(
222
+ encodeDerElement(
223
+ derTags.set,
224
+ encodeDerSequence(
225
+ encodeDerOid(oids.commonName),
226
+ encodeDerElement(derTags.utf8String, new TextEncoder().encode(commonNameArg)),
227
+ ),
228
+ ),
229
+ );
230
+
231
+ const encodeExtension = (oidArg: string, criticalArg: boolean, valueArg: Uint8Array): Uint8Array =>
232
+ criticalArg
233
+ ? encodeDerSequence(encodeDerOid(oidArg), encodeDerBoolean(true), encodeDerOctetString(valueArg))
234
+ : encodeDerSequence(encodeDerOid(oidArg), encodeDerOctetString(valueArg));
235
+
236
+ /** A positive 16-byte serial number (RFC 5280 4.1.2.2 allows up to 20 octets). */
237
+ const createSerialNumber = (): Uint8Array => {
238
+ const serialNumber = getWebCrypto().getRandomValues(new Uint8Array(serialNumberBytes));
239
+ serialNumber[0] = (serialNumber[0] & 0x7f) | 0x40;
240
+ return encodeDerUnsignedInteger(serialNumber);
241
+ };
242
+
243
+ /**
244
+ * Creates a self-signed X.509 v3 end-entity certificate and its key with
245
+ * WebCrypto, for TLS servers that need a certificate without a CA, such as
246
+ * test servers and fallback certificates. The certificate carries
247
+ * `basicConstraints` CA:FALSE and `keyUsage` (both critical),
248
+ * `extendedKeyUsage` serverAuth, and the requested subject alternative names.
249
+ * Invalid options fail with `INVALID_ARGUMENT`; WebCrypto failures with
250
+ * `CRYPTO_OPERATION_FAILED`.
251
+ */
252
+ export const createSelfSignedCertificate = async (
253
+ optionsArg: ISelfSignedCertificateOptions,
254
+ ): Promise<ISelfSignedCertificate> => {
255
+ if (optionsArg === null || typeof optionsArg !== 'object') {
256
+ throw invalidArgument();
257
+ }
258
+ const commonName = requireCommonName(optionsArg.commonName);
259
+ const keyAlgorithm = optionsArg.keyAlgorithm ?? 'RSA-2048';
260
+ if (!isKeyAlgorithm(keyAlgorithm)) {
261
+ throw invalidArgument();
262
+ }
263
+ const profile = keyProfiles[keyAlgorithm];
264
+ const generalNames = [
265
+ ...requireStringList(optionsArg.dnsNames).map(encodeDnsName),
266
+ ...requireStringList(optionsArg.ipAddresses).map((addressArg) =>
267
+ encodeDerElement(generalNameTags.ipAddress, encodeIpAddress(addressArg)),
268
+ ),
269
+ ];
270
+ const notBefore = requireDate(optionsArg.notBefore, Date.now());
271
+ const notAfter = requireDate(optionsArg.notAfter, notBefore + defaultValidityMilliseconds);
272
+ if (notAfter <= notBefore) {
273
+ throw invalidArgument();
274
+ }
275
+ const validity = encodeDerSequence(encodeTime(notBefore), encodeTime(notAfter));
276
+ const name = encodeCommonNameName(commonName);
277
+
278
+ const subtle = getWebCrypto().subtle;
279
+ let privateKeyInfo: Uint8Array | undefined;
280
+ try {
281
+ const keyPair = await subtle.generateKey(profile.generateParams, true, ['sign', 'verify']);
282
+ const subjectPublicKeyInfo = new Uint8Array(await subtle.exportKey('spki', keyPair.publicKey));
283
+ const extensions = [
284
+ encodeExtension(oids.basicConstraints, true, encodeDerSequence()),
285
+ encodeExtension(
286
+ oids.keyUsage,
287
+ true,
288
+ encodeDerBitString(new Uint8Array([profile.keyUsage.bits]), profile.keyUsage.unusedBits),
289
+ ),
290
+ encodeExtension(oids.extendedKeyUsage, false, encodeDerSequence(encodeDerOid(oids.serverAuth))),
291
+ ...(generalNames.length > 0
292
+ ? [encodeExtension(oids.subjectAltName, false, encodeDerSequence(...generalNames))]
293
+ : []),
294
+ ];
295
+ const signatureAlgorithm = profile.encodeSignatureAlgorithm();
296
+ const tbsCertificate = encodeDerSequence(
297
+ encodeDerElement(derTags.contextSpecificConstructed0, encodeDerSmallInteger(2)),
298
+ createSerialNumber(),
299
+ signatureAlgorithm,
300
+ name,
301
+ validity,
302
+ name,
303
+ subjectPublicKeyInfo,
304
+ encodeDerElement(derTags.contextSpecificConstructed3, encodeDerSequence(...extensions)),
305
+ );
306
+ const signature = new Uint8Array(
307
+ await subtle.sign(profile.signParams, keyPair.privateKey, toArrayBuffer(tbsCertificate)),
308
+ );
309
+ const certificate = encodeDerSequence(
310
+ tbsCertificate,
311
+ signatureAlgorithm,
312
+ encodeDerBitString(profile.encodeSignature(signature)),
313
+ );
314
+ privateKeyInfo = new Uint8Array(await subtle.exportKey('pkcs8', keyPair.privateKey));
315
+ return {
316
+ certificatePem: encodePem('CERTIFICATE', certificate),
317
+ privateKeyPem: encodePem('PRIVATE KEY', privateKeyInfo),
318
+ };
319
+ } catch (error) {
320
+ if (error instanceof SmartCryptoError) {
321
+ throw error;
322
+ }
323
+ throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
324
+ } finally {
325
+ privateKeyInfo?.fill(0);
326
+ }
327
+ };
package/ts_node/index.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from './smartcrypto.hash.js';
2
+ export * from './smartcrypto.argon2.js';