@push.rocks/smartcrypto 3.1.0 → 3.3.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.
@@ -1,5 +1,6 @@
1
1
  import { SmartCryptoError, createSmartCryptoError } from './smartcrypto.errors.js';
2
2
  import {
3
+ decodeDerElement,
3
4
  derTags,
4
5
  encodeDerBitString,
5
6
  encodeDerBoolean,
@@ -10,9 +11,16 @@ import {
10
11
  encodeDerSequence,
11
12
  encodeDerSmallInteger,
12
13
  encodeDerUnsignedInteger,
14
+ readDerBitString,
15
+ readDerOid,
16
+ readDerSequence,
17
+ readDerSmallInteger,
18
+ type IDerElement,
13
19
  } from './smartcrypto.der.js';
14
- import { getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
15
- import { encodePem } from './smartcrypto.pem.js';
20
+ import { createSha256Hasher } from './smartcrypto.hash.js';
21
+ import { encodeBase64, getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
22
+ import { decodeFirstPemBlock, encodePem } from './smartcrypto.pem.js';
23
+ import { decodeRsaPublicKey, encodeSubjectPublicKeyInfo } from './smartcrypto.rsa.js';
16
24
 
17
25
  /** The key a self-signed certificate is issued for, signed with SHA-256. */
18
26
  export type TSelfSignedCertificateKeyAlgorithm = 'RSA-2048' | 'ECDSA-P256';
@@ -28,8 +36,18 @@ export interface ISelfSignedCertificateOptions {
28
36
  notBefore?: Date;
29
37
  /** End of the validity period, truncated to whole seconds. Defaults to `notBefore` plus 365 days. */
30
38
  notAfter?: Date;
31
- /** Defaults to `RSA-2048`. */
39
+ /**
40
+ * Defaults to `RSA-2048`, or to `ECDSA-P256` when `privateKeyPem` is given; a
41
+ * supplied key requires `ECDSA-P256`.
42
+ */
32
43
  keyAlgorithm?: TSelfSignedCertificateKeyAlgorithm;
44
+ /**
45
+ * An existing ECDSA P-256 key as an unencrypted PKCS#8 `PRIVATE KEY` PEM, such
46
+ * as the `privateKeyPem` of an earlier certificate. The certificate is issued
47
+ * for this key, so its public key and pin stay the same across certificates.
48
+ * Omitted, a fresh key is generated.
49
+ */
50
+ privateKeyPem?: string;
33
51
  }
34
52
 
35
53
  export interface ISelfSignedCertificate {
@@ -52,6 +70,8 @@ interface ISelfSignedKeyProfile {
52
70
 
53
71
  const oids = {
54
72
  commonName: '2.5.4.3',
73
+ ecPublicKey: '1.2.840.10045.2.1',
74
+ prime256v1: '1.2.840.10045.3.1.7',
55
75
  basicConstraints: '2.5.29.19',
56
76
  keyUsage: '2.5.29.15',
57
77
  extendedKeyUsage: '2.5.29.37',
@@ -106,6 +126,7 @@ const keyProfiles: Record<TSelfSignedCertificateKeyAlgorithm, ISelfSignedKeyProf
106
126
  };
107
127
 
108
128
  const invalidArgument = () => createSmartCryptoError('INVALID_ARGUMENT');
129
+ const invalidKey = (detailArg?: string) => createSmartCryptoError('INVALID_KEY', detailArg);
109
130
 
110
131
  const isKeyAlgorithm = (valueArg: unknown): valueArg is TSelfSignedCertificateKeyAlgorithm =>
111
132
  valueArg === 'RSA-2048' || valueArg === 'ECDSA-P256';
@@ -240,14 +261,126 @@ const createSerialNumber = (): Uint8Array => {
240
261
  return encodeDerUnsignedInteger(serialNumber);
241
262
  };
242
263
 
264
+ // ========================================
265
+ // Keys
266
+ // ========================================
267
+ /**
268
+ * Imports an unencrypted PKCS#8 ECDSA P-256 private key and derives its public
269
+ * key. The algorithm identifier is checked before WebCrypto sees the key, so a
270
+ * key of another type or curve fails with a named `INVALID_KEY`.
271
+ */
272
+ const importEcdsaP256KeyPair = async (privateKeyPemArg: unknown): Promise<CryptoKeyPair> => {
273
+ if (typeof privateKeyPemArg !== 'string') {
274
+ throw invalidArgument();
275
+ }
276
+ const privateKeyInfo = decodeFirstPemBlock(privateKeyPemArg, ['PRIVATE KEY']).body;
277
+ try {
278
+ // PrivateKeyInfo / OneAsymmetricKey (RFC 5958): version, algorithm, privateKey, ...
279
+ const [version, algorithm] = readDerSequence(decodeDerElement(privateKeyInfo), 3, 5);
280
+ if (readDerSmallInteger(version) > 1) {
281
+ throw invalidKey();
282
+ }
283
+ const [algorithmOid, namedCurve] = readDerSequence(algorithm, 1, 2);
284
+ if (
285
+ readDerOid(algorithmOid) !== oids.ecPublicKey
286
+ || namedCurve?.tag !== derTags.oid
287
+ || readDerOid(namedCurve) !== oids.prime256v1
288
+ ) {
289
+ throw invalidKey('the private key is not an ECDSA P-256 key');
290
+ }
291
+ const subtle = getWebCrypto().subtle;
292
+ const ecdsaP256 = { name: 'ECDSA', namedCurve: 'P-256' };
293
+ let privateKey: CryptoKey;
294
+ try {
295
+ privateKey = await subtle.importKey('pkcs8', toArrayBuffer(privateKeyInfo), ecdsaP256, true, [
296
+ 'sign',
297
+ ]);
298
+ } catch {
299
+ throw invalidKey();
300
+ }
301
+ // WebCrypto exports an EC private key as a JWK with its public point (x, y).
302
+ const { kty, crv, x, y } = await subtle.exportKey('jwk', privateKey);
303
+ const publicKey = await subtle.importKey('jwk', { kty, crv, x, y }, ecdsaP256, true, ['verify']);
304
+ return { privateKey, publicKey };
305
+ } finally {
306
+ privateKeyInfo.fill(0);
307
+ }
308
+ };
309
+
310
+ const generateKeyPair = (profileArg: ISelfSignedKeyProfile): Promise<CryptoKeyPair> =>
311
+ getWebCrypto().subtle.generateKey(profileArg.generateParams, true, ['sign', 'verify']);
312
+
313
+ // ========================================
314
+ // Public-key pins
315
+ // ========================================
316
+ /** Requires a DER `SubjectPublicKeyInfo` and returns it unchanged. */
317
+ const requireSubjectPublicKeyInfo = (derArg: Uint8Array): Uint8Array => {
318
+ const [algorithm, subjectPublicKey] = readDerSequence(decodeDerElement(derArg), 2, 2);
319
+ readDerOid(readDerSequence(algorithm, 1, 2)[0]);
320
+ readDerBitString(subjectPublicKey);
321
+ return derArg;
322
+ };
323
+
324
+ /** The DER `subjectPublicKeyInfo` of a DER X.509 certificate (RFC 5280 4.1). */
325
+ const readCertificateSubjectPublicKeyInfo = (derArg: Uint8Array): Uint8Array => {
326
+ const [tbsCertificate] = readDerSequence(decodeDerElement(derArg), 3, 3);
327
+ // version [0] (optional), serialNumber, signature, issuer, validity, subject, subjectPublicKeyInfo, ...
328
+ const fields: IDerElement[] = readDerSequence(tbsCertificate, 6, 10);
329
+ const subjectPublicKeyInfo =
330
+ fields[fields[0].tag === derTags.contextSpecificConstructed0 ? 6 : 5];
331
+ if (!subjectPublicKeyInfo) {
332
+ throw invalidKey();
333
+ }
334
+ // The strict DER reader admits one encoding per element, so re-encoding yields the original bytes.
335
+ return requireSubjectPublicKeyInfo(
336
+ encodeDerElement(subjectPublicKeyInfo.tag, subjectPublicKeyInfo.content),
337
+ );
338
+ };
339
+
340
+ const decodeHex = (hexArg: string): Uint8Array =>
341
+ new Uint8Array((hexArg.match(/../g) ?? []).map((byteArg) => parseInt(byteArg, 16)));
342
+
343
+ /**
344
+ * Computes the RFC 7469 `pin-sha256` of a public key: the SHA-256 digest of the
345
+ * DER `SubjectPublicKeyInfo`, as standard padded base64 (44 characters). The key
346
+ * is given as DER `SubjectPublicKeyInfo` bytes (WebCrypto `exportKey('spki')`,
347
+ * Node.js `KeyObject.export({ type: 'spki', format: 'der' })`), or as the first
348
+ * PEM block of a string: `PUBLIC KEY` (SPKI), `RSA PUBLIC KEY` (PKCS#1, pinned as
349
+ * its rsaEncryption SPKI) or `CERTIFICATE` (the certificate's subject public
350
+ * key). Synchronous, so it fits TLS identity callbacks. Malformed keys fail
351
+ * with `INVALID_KEY`, other input types with `INVALID_ARGUMENT`.
352
+ */
353
+ export const computePublicKeyPinSha256 = (publicKeyArg: string | Uint8Array): string => {
354
+ let subjectPublicKeyInfo: Uint8Array;
355
+ if (publicKeyArg instanceof Uint8Array) {
356
+ subjectPublicKeyInfo = requireSubjectPublicKeyInfo(publicKeyArg);
357
+ } else if (typeof publicKeyArg === 'string') {
358
+ const block = decodeFirstPemBlock(publicKeyArg, ['PUBLIC KEY', 'RSA PUBLIC KEY', 'CERTIFICATE']);
359
+ subjectPublicKeyInfo =
360
+ block.type === 'PUBLIC KEY'
361
+ ? requireSubjectPublicKeyInfo(block.body)
362
+ : block.type === 'RSA PUBLIC KEY'
363
+ ? encodeSubjectPublicKeyInfo(decodeRsaPublicKey(block.body))
364
+ : readCertificateSubjectPublicKeyInfo(block.body);
365
+ } else {
366
+ throw invalidArgument();
367
+ }
368
+ return encodeBase64(decodeHex(createSha256Hasher().update(subjectPublicKeyInfo).digest()));
369
+ };
370
+
371
+ // ========================================
372
+ // Certificate creation
373
+ // ========================================
243
374
  /**
244
375
  * Creates a self-signed X.509 v3 end-entity certificate and its key with
245
376
  * WebCrypto, for TLS servers that need a certificate without a CA, such as
246
377
  * test servers and fallback certificates. The certificate carries
247
378
  * `basicConstraints` CA:FALSE and `keyUsage` (both critical),
248
379
  * `extendedKeyUsage` serverAuth, and the requested subject alternative names.
249
- * Invalid options fail with `INVALID_ARGUMENT`; WebCrypto failures with
250
- * `CRYPTO_OPERATION_FAILED`.
380
+ * With `privateKeyPem` the certificate is issued for that ECDSA P-256 key
381
+ * instead of a fresh one. Invalid options fail with `INVALID_ARGUMENT`, a
382
+ * supplied key that is malformed or not ECDSA P-256 with `INVALID_KEY`, and
383
+ * WebCrypto failures with `CRYPTO_OPERATION_FAILED`.
251
384
  */
252
385
  export const createSelfSignedCertificate = async (
253
386
  optionsArg: ISelfSignedCertificateOptions,
@@ -256,8 +389,9 @@ export const createSelfSignedCertificate = async (
256
389
  throw invalidArgument();
257
390
  }
258
391
  const commonName = requireCommonName(optionsArg.commonName);
259
- const keyAlgorithm = optionsArg.keyAlgorithm ?? 'RSA-2048';
260
- if (!isKeyAlgorithm(keyAlgorithm)) {
392
+ const suppliesKey = optionsArg.privateKeyPem !== undefined;
393
+ const keyAlgorithm = optionsArg.keyAlgorithm ?? (suppliesKey ? 'ECDSA-P256' : 'RSA-2048');
394
+ if (!isKeyAlgorithm(keyAlgorithm) || (suppliesKey && keyAlgorithm !== 'ECDSA-P256')) {
261
395
  throw invalidArgument();
262
396
  }
263
397
  const profile = keyProfiles[keyAlgorithm];
@@ -278,7 +412,9 @@ export const createSelfSignedCertificate = async (
278
412
  const subtle = getWebCrypto().subtle;
279
413
  let privateKeyInfo: Uint8Array | undefined;
280
414
  try {
281
- const keyPair = await subtle.generateKey(profile.generateParams, true, ['sign', 'verify']);
415
+ const keyPair = suppliesKey
416
+ ? await importEcdsaP256KeyPair(optionsArg.privateKeyPem)
417
+ : await generateKeyPair(profile);
282
418
  const subjectPublicKeyInfo = new Uint8Array(await subtle.exportKey('spki', keyPair.publicKey));
283
419
  const extensions = [
284
420
  encodeExtension(oids.basicConstraints, true, encodeDerSequence()),
package/ts_node/index.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from './smartcrypto.hash.js';
2
+ export * from './smartcrypto.argon2.js';
@@ -0,0 +1,438 @@
1
+ import * as plugins from './smartcrypto.plugins.js';
2
+ import { createSmartCryptoError } from '../ts/smartcrypto.errors.js';
3
+
4
+ /**
5
+ * Argon2id password hashing in the PHC string format, on `node:crypto.argon2`
6
+ * (Node.js 24.7.0 or later; checked at call time, not declared in `engines`).
7
+ *
8
+ * Only Argon2id version 19 (0x13) is read and written, the one variant and
9
+ * version `node:crypto.argon2` computes that the stored verifiers use. The
10
+ * limits are the PHC string format's Argon2 limits (C2SP phc-strings).
11
+ */
12
+
13
+ /** The decoded fields of an Argon2id PHC string. */
14
+ export interface IArgon2idPhc {
15
+ /** Argon2 version; always 19 (0x13). */
16
+ version: 19;
17
+ /** Memory cost `m` in KiB. */
18
+ memoryCost: number;
19
+ /** Number of passes `t`. */
20
+ timeCost: number;
21
+ /** Degree of parallelism (lanes) `p`. */
22
+ parallelism: number;
23
+ /** Salt, 8 to 48 bytes. */
24
+ salt: Uint8Array;
25
+ /** Digest (Argon2 tag), 12 to 64 bytes. */
26
+ digest: Uint8Array;
27
+ }
28
+
29
+ /** Cost and length options of `hashArgon2id()`; omitted fields use `argon2idDefaultOptions`. */
30
+ export interface IArgon2idHashOptions {
31
+ /** Memory cost in KiB, at least `8 * parallelism` and at most 2^32-1. */
32
+ memoryCost?: number;
33
+ /** Number of passes, 1 to 2^32-1. */
34
+ timeCost?: number;
35
+ /** Degree of parallelism, 1 to 255. */
36
+ parallelism?: number;
37
+ /** Random salt length in bytes, 8 to 48. */
38
+ saltLength?: number;
39
+ /** Digest length in bytes, 12 to 64. */
40
+ hashLength?: number;
41
+ }
42
+
43
+ /** The defaults: the cost and lengths of the stored CoreMail credential verifiers. */
44
+ export const argon2idDefaultOptions: Readonly<Required<IArgon2idHashOptions>> = Object.freeze({
45
+ memoryCost: 65_536,
46
+ timeCost: 3,
47
+ parallelism: 1,
48
+ saltLength: 16,
49
+ hashLength: 32,
50
+ });
51
+
52
+ /**
53
+ * Upper bounds on the cost `verifyArgon2id()` accepts from a hash; omitted
54
+ * fields use `argon2idDefaultVerifyLimits`. The hash sets the cost of its own
55
+ * verification, so the limits keep an untrusted or corrupted hash from costing
56
+ * unbounded memory or CPU.
57
+ */
58
+ export interface IArgon2idVerifyLimits {
59
+ /** Largest accepted memory cost `m` in KiB, 8 to 2^32-1. */
60
+ maxMemoryCost?: number;
61
+ /** Largest accepted number of passes `t`, 1 to 2^32-1. */
62
+ maxTimeCost?: number;
63
+ /** Largest accepted parallelism `p`, 1 to 255. */
64
+ maxParallelism?: number;
65
+ }
66
+
67
+ /** The default verify limits: 1 GiB of memory, 10 passes, 16 lanes. */
68
+ export const argon2idDefaultVerifyLimits: Readonly<Required<IArgon2idVerifyLimits>> = Object.freeze({
69
+ maxMemoryCost: 1_048_576,
70
+ maxTimeCost: 10,
71
+ maxParallelism: 16,
72
+ });
73
+
74
+ const argon2idVersion = 19;
75
+ const maximumUint32 = 2 ** 32 - 1;
76
+ const maximumParallelism = 255;
77
+ const saltLengthRange = { minimum: 8, maximum: 48 } as const;
78
+ const digestLengthRange = { minimum: 12, maximum: 64 } as const;
79
+ /** The longest valid string: `$argon2id$v=19$m=<10>,t=<10>,p=<3>$<64>$<86>` is 198 characters. */
80
+ const maximumPhcLength = 256;
81
+
82
+ const decimalPattern = /^(?:0|[1-9][0-9]*)$/;
83
+ const b64Pattern = /^[A-Za-z0-9+/]+$/;
84
+
85
+ /** The parameter orders read: `m,t,p` (PHC order) and `m,p,t` (written by the `argon2` npm package). */
86
+ const acceptedParameterOrders: readonly string[] = ['m,t,p', 'm,p,t'];
87
+
88
+ type TArgon2idParameterName = 'm' | 't' | 'p';
89
+
90
+ const invalidHash = (detailArg: string) =>
91
+ createSmartCryptoError('INVALID_PASSWORD_HASH', detailArg);
92
+
93
+ const requireInteger = (
94
+ valueArg: unknown,
95
+ minimumArg: number,
96
+ maximumArg: number,
97
+ detailArg: string,
98
+ ): number => {
99
+ if (
100
+ typeof valueArg !== 'number'
101
+ || !Number.isInteger(valueArg)
102
+ || valueArg < minimumArg
103
+ || valueArg > maximumArg
104
+ ) {
105
+ throw createSmartCryptoError('INVALID_ARGUMENT', detailArg);
106
+ }
107
+ return valueArg;
108
+ };
109
+
110
+ /** Validates the cost parameters shared by encoding and hashing. */
111
+ const requireCost = (
112
+ memoryCostArg: unknown,
113
+ timeCostArg: unknown,
114
+ parallelismArg: unknown,
115
+ ): { memoryCost: number; timeCost: number; parallelism: number } => {
116
+ const parallelism = requireInteger(
117
+ parallelismArg,
118
+ 1,
119
+ maximumParallelism,
120
+ 'parallelism must be an integer from 1 to 255',
121
+ );
122
+ const memoryCost = requireInteger(
123
+ memoryCostArg,
124
+ 8 * parallelism,
125
+ maximumUint32,
126
+ 'memoryCost must be an integer from 8 * parallelism to 2^32-1',
127
+ );
128
+ const timeCost = requireInteger(
129
+ timeCostArg,
130
+ 1,
131
+ maximumUint32,
132
+ 'timeCost must be an integer from 1 to 2^32-1',
133
+ );
134
+ return { memoryCost, timeCost, parallelism };
135
+ };
136
+
137
+ const requireBytes = (
138
+ valueArg: unknown,
139
+ rangeArg: { minimum: number; maximum: number },
140
+ detailArg: string,
141
+ ): Uint8Array => {
142
+ if (
143
+ !(valueArg instanceof Uint8Array)
144
+ || valueArg.byteLength < rangeArg.minimum
145
+ || valueArg.byteLength > rangeArg.maximum
146
+ ) {
147
+ throw createSmartCryptoError('INVALID_ARGUMENT', detailArg);
148
+ }
149
+ return valueArg;
150
+ };
151
+
152
+ const encodeB64 = (valueArg: Uint8Array): string =>
153
+ Buffer.from(valueArg.buffer, valueArg.byteOffset, valueArg.byteLength)
154
+ .toString('base64')
155
+ .replace(/=+$/, '');
156
+
157
+ /** Decodes canonical B64: standard alphabet, no padding, zero trailing bits. */
158
+ const decodeB64 = (
159
+ valueArg: string,
160
+ rangeArg: { minimum: number; maximum: number },
161
+ fieldArg: 'salt' | 'digest',
162
+ ): Uint8Array => {
163
+ if (valueArg.includes('=')) {
164
+ throw invalidHash(`${fieldArg} must be base64 without padding`);
165
+ }
166
+ if (!b64Pattern.test(valueArg) || valueArg.length % 4 === 1) {
167
+ throw invalidHash(`${fieldArg} must be standard base64`);
168
+ }
169
+ const decoded = new Uint8Array(Buffer.from(valueArg, 'base64'));
170
+ if (encodeB64(decoded) !== valueArg) {
171
+ throw invalidHash(`${fieldArg} must be canonical base64`);
172
+ }
173
+ if (decoded.byteLength < rangeArg.minimum || decoded.byteLength > rangeArg.maximum) {
174
+ throw invalidHash(
175
+ `${fieldArg} must be ${rangeArg.minimum} to ${rangeArg.maximum} bytes`,
176
+ );
177
+ }
178
+ return decoded;
179
+ };
180
+
181
+ const parseDecimal = (valueArg: string, nameArg: TArgon2idParameterName): number => {
182
+ const maximumDigits = nameArg === 'p' ? 3 : 10;
183
+ if (!decimalPattern.test(valueArg) || valueArg.length > maximumDigits) {
184
+ throw invalidHash(`parameter ${nameArg} must be a decimal integer without sign or leading zeros`);
185
+ }
186
+ return Number(valueArg);
187
+ };
188
+
189
+ /** Reads the `m`, `t` and `p` parameters, each exactly once, in an accepted order. */
190
+ const parseParameters = (
191
+ blockArg: string,
192
+ ): { memoryCost: number; timeCost: number; parallelism: number } => {
193
+ const values = new Map<TArgon2idParameterName, number>();
194
+ const names: string[] = [];
195
+ for (const entry of blockArg.split(',')) {
196
+ const separatorIndex = entry.indexOf('=');
197
+ if (separatorIndex < 1) {
198
+ throw invalidHash('parameters must be name=value pairs');
199
+ }
200
+ const name = entry.slice(0, separatorIndex);
201
+ if (name !== 'm' && name !== 't' && name !== 'p') {
202
+ throw invalidHash('only the parameters m, t and p are supported');
203
+ }
204
+ if (values.has(name)) {
205
+ throw invalidHash(`parameter ${name} must appear once`);
206
+ }
207
+ values.set(name, parseDecimal(entry.slice(separatorIndex + 1), name));
208
+ names.push(name);
209
+ }
210
+ const memoryCost = values.get('m');
211
+ const timeCost = values.get('t');
212
+ const parallelism = values.get('p');
213
+ if (memoryCost === undefined || timeCost === undefined || parallelism === undefined) {
214
+ throw invalidHash('parameters m, t and p are required');
215
+ }
216
+ if (!acceptedParameterOrders.includes(names.join(','))) {
217
+ throw invalidHash('parameters must appear in the order m,t,p or m,p,t');
218
+ }
219
+ if (parallelism < 1 || parallelism > maximumParallelism) {
220
+ throw invalidHash('parameter p must be from 1 to 255');
221
+ }
222
+ if (memoryCost < 8 * parallelism || memoryCost > maximumUint32) {
223
+ throw invalidHash('parameter m must be from 8 * p to 2^32-1');
224
+ }
225
+ if (timeCost < 1 || timeCost > maximumUint32) {
226
+ throw invalidHash('parameter t must be from 1 to 2^32-1');
227
+ }
228
+ return { memoryCost, timeCost, parallelism };
229
+ };
230
+
231
+ /**
232
+ * Parses an Argon2id PHC string, `$argon2id$v=19$m=<kib>,t=<passes>,p=<lanes>$<salt>$<digest>`.
233
+ *
234
+ * Reads the parameter orders `m,t,p` and `m,p,t`; rejects other variants and
235
+ * versions (`UNSUPPORTED_PROFILE`, `UNSUPPORTED_VERSION`) and every other
236
+ * deviation (`INVALID_PASSWORD_HASH`): unknown, duplicate, missing or
237
+ * out-of-range parameters, padded, non-canonical or invalid base64, and
238
+ * salt or digest lengths outside 8 to 48 and 12 to 64 bytes.
239
+ */
240
+ export const parseArgon2idPhc = (phcArg: string): IArgon2idPhc => {
241
+ if (typeof phcArg !== 'string') {
242
+ throw createSmartCryptoError('INVALID_ARGUMENT', 'the hash must be a string');
243
+ }
244
+ if (phcArg.length > maximumPhcLength) {
245
+ throw invalidHash(`the hash must not exceed ${maximumPhcLength} characters`);
246
+ }
247
+ const fields = phcArg.split('$');
248
+ if (fields[0] !== '' || fields.length < 2) {
249
+ throw invalidHash('the hash must be a PHC string starting with $');
250
+ }
251
+ const variant = fields[1];
252
+ if (!/^[a-z0-9-]{1,32}$/.test(variant)) {
253
+ throw invalidHash('the hash must start with a PHC function identifier');
254
+ }
255
+ if (variant !== 'argon2id') {
256
+ throw createSmartCryptoError('UNSUPPORTED_PROFILE', 'only argon2id is supported');
257
+ }
258
+ if (fields.length !== 6) {
259
+ throw invalidHash('the hash must carry version, parameters, salt and digest');
260
+ }
261
+ const [, , versionField, parameterField, saltField, digestField] = fields;
262
+ if (!versionField.startsWith('v=')) {
263
+ throw invalidHash('the hash must carry the version field v=19');
264
+ }
265
+ if (versionField !== `v=${argon2idVersion}`) {
266
+ throw createSmartCryptoError('UNSUPPORTED_VERSION', 'only argon2 version 19 is supported');
267
+ }
268
+ const cost = parseParameters(parameterField);
269
+ return {
270
+ version: argon2idVersion,
271
+ ...cost,
272
+ salt: decodeB64(saltField, saltLengthRange, 'salt'),
273
+ digest: decodeB64(digestField, digestLengthRange, 'digest'),
274
+ };
275
+ };
276
+
277
+ /** Encodes Argon2id fields as a PHC string in the canonical `m,t,p` order. */
278
+ export const encodeArgon2idPhc = (phcArg: IArgon2idPhc): string => {
279
+ if (phcArg?.version !== argon2idVersion) {
280
+ throw createSmartCryptoError('UNSUPPORTED_VERSION', 'only argon2 version 19 is supported');
281
+ }
282
+ const { memoryCost, timeCost, parallelism } = requireCost(
283
+ phcArg.memoryCost,
284
+ phcArg.timeCost,
285
+ phcArg.parallelism,
286
+ );
287
+ const salt = requireBytes(phcArg.salt, saltLengthRange, 'salt must be 8 to 48 bytes');
288
+ const digest = requireBytes(phcArg.digest, digestLengthRange, 'digest must be 12 to 64 bytes');
289
+ return `$argon2id$v=${argon2idVersion}$m=${memoryCost},t=${timeCost},p=${parallelism}`
290
+ + `$${encodeB64(salt)}$${encodeB64(digest)}`;
291
+ };
292
+
293
+ /** Passwords are strings, hashed as UTF-8, or bytes. */
294
+ const requirePassword = (passwordArg: unknown): Uint8Array => {
295
+ if (typeof passwordArg === 'string') {
296
+ return Buffer.from(passwordArg, 'utf8');
297
+ }
298
+ if (passwordArg instanceof Uint8Array) {
299
+ return passwordArg;
300
+ }
301
+ throw createSmartCryptoError('INVALID_ARGUMENT', 'the password must be a string or a Uint8Array');
302
+ };
303
+
304
+ /** Runs `node:crypto.argon2` (Argon2id, version 0x13) as a promise. */
305
+ const deriveArgon2id = (
306
+ passwordArg: Uint8Array,
307
+ costArg: { memoryCost: number; timeCost: number; parallelism: number },
308
+ saltArg: Uint8Array,
309
+ tagLengthArg: number,
310
+ ): Promise<Buffer> => {
311
+ if (typeof plugins.crypto.argon2 !== 'function') {
312
+ return Promise.reject(
313
+ createSmartCryptoError(
314
+ 'CRYPTO_OPERATION_FAILED',
315
+ 'Argon2id requires Node.js ≥24.7.0 crypto.argon2, which this runtime lacks',
316
+ ),
317
+ );
318
+ }
319
+ return new Promise<Buffer>((resolve, reject) => {
320
+ try {
321
+ plugins.crypto.argon2(
322
+ 'argon2id',
323
+ {
324
+ message: passwordArg,
325
+ nonce: saltArg,
326
+ parallelism: costArg.parallelism,
327
+ tagLength: tagLengthArg,
328
+ memory: costArg.memoryCost,
329
+ passes: costArg.timeCost,
330
+ },
331
+ (errorArg, derivedKeyArg) => {
332
+ if (errorArg) {
333
+ reject(argon2Failure(errorArg));
334
+ return;
335
+ }
336
+ resolve(derivedKeyArg);
337
+ },
338
+ );
339
+ } catch (error) {
340
+ reject(argon2Failure(error));
341
+ }
342
+ });
343
+ };
344
+
345
+ /** Maps a `node:crypto` failure to an error without its details; only a missing Argon2 is named. */
346
+ const argon2Failure = (errorArg: unknown) =>
347
+ createSmartCryptoError(
348
+ 'CRYPTO_OPERATION_FAILED',
349
+ errorArg instanceof Error
350
+ && 'code' in errorArg
351
+ && errorArg.code === 'ERR_CRYPTO_ARGON2_NOT_SUPPORTED'
352
+ ? 'the OpenSSL of this Node.js does not support Argon2'
353
+ : 'Argon2id derivation failed',
354
+ );
355
+
356
+ /**
357
+ * Hashes a password with Argon2id and returns the PHC string
358
+ * `$argon2id$v=19$m=<kib>,t=<passes>,p=<lanes>$<salt>$<digest>` (base64 without padding).
359
+ * The salt is random; omitted options use `argon2idDefaultOptions`.
360
+ */
361
+ export const hashArgon2id = async (
362
+ passwordArg: string | Uint8Array,
363
+ optionsArg: IArgon2idHashOptions = {},
364
+ ): Promise<string> => {
365
+ const password = requirePassword(passwordArg);
366
+ const options = { ...argon2idDefaultOptions, ...optionsArg };
367
+ const cost = requireCost(options.memoryCost, options.timeCost, options.parallelism);
368
+ const saltLength = requireInteger(
369
+ options.saltLength,
370
+ saltLengthRange.minimum,
371
+ saltLengthRange.maximum,
372
+ 'saltLength must be an integer from 8 to 48',
373
+ );
374
+ const hashLength = requireInteger(
375
+ options.hashLength,
376
+ digestLengthRange.minimum,
377
+ digestLengthRange.maximum,
378
+ 'hashLength must be an integer from 12 to 64',
379
+ );
380
+ const salt = new Uint8Array(plugins.crypto.randomBytes(saltLength));
381
+ const digest = await deriveArgon2id(password, cost, salt, hashLength);
382
+ return encodeArgon2idPhc({ version: argon2idVersion, ...cost, salt, digest });
383
+ };
384
+
385
+ /** Validates verify limits against the PHC parameter ranges. */
386
+ const requireVerifyLimits = (
387
+ limitsArg: IArgon2idVerifyLimits,
388
+ ): Required<IArgon2idVerifyLimits> => {
389
+ const limits = { ...argon2idDefaultVerifyLimits, ...limitsArg };
390
+ return {
391
+ maxMemoryCost: requireInteger(
392
+ limits.maxMemoryCost,
393
+ 8,
394
+ maximumUint32,
395
+ 'maxMemoryCost must be an integer from 8 to 2^32-1',
396
+ ),
397
+ maxTimeCost: requireInteger(
398
+ limits.maxTimeCost,
399
+ 1,
400
+ maximumUint32,
401
+ 'maxTimeCost must be an integer from 1 to 2^32-1',
402
+ ),
403
+ maxParallelism: requireInteger(
404
+ limits.maxParallelism,
405
+ 1,
406
+ maximumParallelism,
407
+ 'maxParallelism must be an integer from 1 to 255',
408
+ ),
409
+ };
410
+ };
411
+
412
+ /**
413
+ * Verifies a password against an Argon2id PHC string. Resolves `false` for a
414
+ * wrong password; rejects with `SmartCryptoError` for a hash `parseArgon2idPhc()`
415
+ * refuses, and with `INVALID_PASSWORD_HASH` before any hashing for a hash whose
416
+ * cost exceeds the limits (`argon2idDefaultVerifyLimits` by default). The
417
+ * digests are compared in constant time.
418
+ */
419
+ export const verifyArgon2id = async (
420
+ phcArg: string,
421
+ passwordArg: string | Uint8Array,
422
+ limitsArg: IArgon2idVerifyLimits = {},
423
+ ): Promise<boolean> => {
424
+ const limits = requireVerifyLimits(limitsArg);
425
+ const phc = parseArgon2idPhc(phcArg);
426
+ const password = requirePassword(passwordArg);
427
+ if (phc.memoryCost > limits.maxMemoryCost) {
428
+ throw invalidHash('parameter m exceeds the maxMemoryCost limit');
429
+ }
430
+ if (phc.timeCost > limits.maxTimeCost) {
431
+ throw invalidHash('parameter t exceeds the maxTimeCost limit');
432
+ }
433
+ if (phc.parallelism > limits.maxParallelism) {
434
+ throw invalidHash('parameter p exceeds the maxParallelism limit');
435
+ }
436
+ const computed = await deriveArgon2id(password, phc, phc.salt, phc.digest.byteLength);
437
+ return plugins.crypto.timingSafeEqual(computed, phc.digest);
438
+ };