feat(auth): password hashing service

This commit is contained in:
2026-05-20 22:45:21 +02:00
parent afd51571c5
commit 0e6bc8c640
4 changed files with 54 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
import { describe, it, expect } from 'vitest';
import { hashPassword, verifyPassword } from './passwords.js';
describe('passwords', () => {
it('hashes a password and verifies it', async () => {
const hash = await hashPassword('correcthorse');
expect(hash).toMatch(/^\$2[aby]\$/);
expect(await verifyPassword('correcthorse', hash)).toBe(true);
});
it('rejects a wrong password', async () => {
const hash = await hashPassword('correcthorse');
expect(await verifyPassword('wrong', hash)).toBe(false);
});
it('returns false on malformed hash', async () => {
expect(await verifyPassword('x', 'not-a-bcrypt-hash')).toBe(false);
});
});

View File

@@ -0,0 +1,15 @@
import bcrypt from 'bcryptjs';
const COST = 12;
export async function hashPassword(plain: string): Promise<string> {
return bcrypt.hash(plain, COST);
}
export async function verifyPassword(plain: string, hash: string): Promise<boolean> {
try {
return await bcrypt.compare(plain, hash);
} catch {
return false;
}
}