/** * Passwords: Argon2id with Events' parameters. bcrypt hashes (imported from Cross Events, whose * older accounts still have them) verify too, and `needsRehash` tells the caller to store a new * Argon2id hash after a successful sign-in, as Events does. */ import argon2 from '@node-rs/argon2'; import bcrypt from 'bcryptjs'; const OPTIONS = { algorithm: 2 as const /* Argon2id */, memoryCost: 19456, timeCost: 2, parallelism: 1 }; const PREFIX = `$argon2id$v=19$m=${OPTIONS.memoryCost},t=${OPTIONS.timeCost},p=${OPTIONS.parallelism}$`; export const MIN_PASSWORD_LENGTH = 8; export const MAX_PASSWORD_LENGTH = 200; export function hashPassword(password: string): Promise { return argon2.hash(password, OPTIONS); } export async function verifyPassword(password: string, hash: string | null | undefined): Promise { if (!hash) return false; try { if (hash.startsWith('$argon2')) return await argon2.verify(hash, password); if (/^\$2[aby]\$/.test(hash)) return await bcrypt.compare(password, hash); } catch { return false; } return false; } export const needsRehash = (hash: string) => !hash.startsWith(PREFIX); /** A hash to compare against when there's no account, so a missing account takes as long. */ let dummy: Promise | null = null; export function dummyHash(): Promise { if (!dummy) dummy = hashPassword('no-such-account-placeholder'); return dummy; } export function passwordProblem(password: unknown): string | null { if (typeof password !== 'string' || password.length < MIN_PASSWORD_LENGTH) return `Use at least ${MIN_PASSWORD_LENGTH} characters.`; if (password.length > MAX_PASSWORD_LENGTH) return 'That password is too long.'; return null; }