@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,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
+ };