@maiyunnet/kebab 9.27.0 → 9.28.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,3 @@
1
+ import type { IPasswordOptions } from '#kebab/lib/crypto.js';
2
+ export declare function hash(password: string, options: IPasswordOptions): Promise<string | false>;
3
+ export declare function verify(password: string, encoded: string): Promise<boolean | null>;
@@ -0,0 +1,60 @@
1
+ import * as crypto from 'node:crypto';
2
+ import { promisify } from 'node:util';
3
+ const argon2 = typeof crypto.argon2 === 'function' ? promisify(crypto.argon2) : undefined;
4
+ function valid(memory, passes, parallelism) {
5
+ return Number.isInteger(memory) && Number.isInteger(passes) && Number.isInteger(parallelism) &&
6
+ parallelism >= 1 && parallelism <= 8 && memory >= 8 * parallelism && memory <= 262144 &&
7
+ passes >= 1 && passes <= 10;
8
+ }
9
+ function base64(value) {
10
+ return value.toString('base64').replace(/=+$/, '');
11
+ }
12
+ export async function hash(password, options) {
13
+ try {
14
+ const { memory = 65536, passes = 3, parallelism = 1 } = options;
15
+ if (!argon2 || !valid(memory, passes, parallelism)) {
16
+ return false;
17
+ }
18
+ const salt = crypto.randomBytes(16);
19
+ const tag = await argon2('argon2id', {
20
+ message: password, nonce: salt, tagLength: 32, memory, passes, parallelism,
21
+ });
22
+ return `$argon2id$v=19$m=${memory},t=${passes},p=${parallelism}$${base64(salt)}$${base64(tag)}`;
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ export async function verify(password, encoded) {
29
+ if (typeof encoded !== 'string' || encoded.length > 256) {
30
+ return false;
31
+ }
32
+ const match = /^\$argon2id\$v=19\$m=([1-9]\d*),t=([1-9]\d*),p=([1-9]\d*)\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)$/.exec(encoded);
33
+ if (match?.[0] !== encoded) {
34
+ return false;
35
+ }
36
+ const memory = Number(match[1]);
37
+ const passes = Number(match[2]);
38
+ const parallelism = Number(match[3]);
39
+ if (!valid(memory, passes, parallelism)) {
40
+ return false;
41
+ }
42
+ const salt = Buffer.from(match[4], 'base64');
43
+ const expected = Buffer.from(match[5], 'base64');
44
+ if (salt.length < 8 || salt.length > 64 || expected.length < 16 || expected.length > 64 ||
45
+ base64(salt) !== match[4] || base64(expected) !== match[5]) {
46
+ return false;
47
+ }
48
+ if (!argon2) {
49
+ return null;
50
+ }
51
+ try {
52
+ const actual = await argon2('argon2id', {
53
+ message: password, nonce: salt, tagLength: expected.length, memory, passes, parallelism,
54
+ });
55
+ return crypto.timingSafeEqual(actual, expected);
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ }