forked from stack-auth/stack-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashes.tsx
More file actions
51 lines (46 loc) · 1.62 KB
/
hashes.tsx
File metadata and controls
51 lines (46 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import bcrypt from 'bcryptjs';
import { StackAssertionError } from './errors';
export async function sha512(input: Uint8Array | string): Promise<Uint8Array> {
const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
return new Uint8Array(await crypto.subtle.digest("SHA-512", bytes));
}
export async function hashPassword(password: string) {
const passwordBytes = new TextEncoder().encode(password);
if (passwordBytes.length >= 72) {
throw new StackAssertionError(`Password is too long for bcrypt`, { len: passwordBytes.length });
}
const salt = await bcrypt.genSalt(10);
return await bcrypt.hash(password, salt);
}
export async function comparePassword(password: string, hash: string): Promise<boolean> {
switch (await getPasswordHashAlgorithm(hash)) {
case "bcrypt": {
return await bcrypt.compare(password, hash);
}
default: {
return false;
}
}
}
export async function isPasswordHashValid(hash: string) {
return !!(await getPasswordHashAlgorithm(hash));
}
export async function getPasswordHashAlgorithm(hash: string): Promise<"bcrypt" | undefined> {
if (typeof hash !== "string") {
throw new StackAssertionError(`Passed non-string value to getPasswordHashAlgorithm`, { hash });
}
if (hash.match(/^\$2[ayb]\$.{56}$/)) {
try {
if (bcrypt.getRounds(hash) > 16) {
return undefined;
}
await bcrypt.compare("any string", hash);
return "bcrypt";
} catch (e) {
console.warn(`Error while checking bcrypt password hash. Assuming the hash is invalid`, e);
return undefined;
}
} else {
return undefined;
}
}