Andrew commited on
Commit
12ba18c
·
1 Parent(s): a790ffc

feat(auth): Add password hashing and recovery key generation utilities

Browse files
Files changed (1) hide show
  1. src/lib/server/passwords.ts +33 -0
src/lib/server/passwords.ts ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { scrypt, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { promisify } from "util";
3
+
4
+ const scryptAsync = promisify(scrypt);
5
+
6
+ /**
7
+ * Hashes a password using scrypt with a random salt.
8
+ * Returns the salt and hash combined as a string.
9
+ */
10
+ export async function hashPassword(password: string): Promise<string> {
11
+ const salt = randomBytes(16).toString("hex");
12
+ const derivedKey = (await scryptAsync(password, salt, 64)) as Buffer;
13
+ return `${salt}:${derivedKey.toString("hex")}`;
14
+ }
15
+
16
+ /**
17
+ * Verifies a password against a stored hash (salt:hash).
18
+ */
19
+ export async function verifyPassword(password: string, storedHash: string): Promise<boolean> {
20
+ const [salt, key] = storedHash.split(":");
21
+ if (!salt || !key) return false;
22
+
23
+ const keyBuffer = Buffer.from(key, "hex");
24
+ const derivedKey = (await scryptAsync(password, salt, 64)) as Buffer;
25
+ return timingSafeEqual(keyBuffer, derivedKey);
26
+ }
27
+
28
+ /**
29
+ * Generates a secure random recovery key.
30
+ */
31
+ export function generateRecoveryKey(): string {
32
+ return `rk-${randomBytes(24).toString("hex")}`;
33
+ }