/** * Recovery codes: 10 single-use codes each time 2FA is turned on, shown once ("abcd-efgh-jkmn"). * Only their hashes are kept. Letters that are easy to mix up are left out. */ import crypto from 'node:crypto'; import { hashToken } from './crypto.js'; const ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789'; export const RECOVERY_CODE_COUNT = 10; function one(): string { const chars = Array.from({ length: 12 }, () => ALPHABET[crypto.randomInt(0, ALPHABET.length)]); return `${chars.slice(0, 4).join('')}-${chars.slice(4, 8).join('')}-${chars.slice(8).join('')}`; } export function newRecoveryCodes(): { codes: string[]; hashes: string[] } { const codes = Array.from({ length: RECOVERY_CODE_COUNT }, one); return { codes, hashes: codes.map(hashRecoveryCode) }; } /** As typed: case and dashes or spaces don't matter. */ export function normaliseRecoveryCode(input: unknown): string { const clean = String(input ?? '').toLowerCase().replace(/[^a-z0-9]/g, ''); return clean.length === 12 ? `${clean.slice(0, 4)}-${clean.slice(4, 8)}-${clean.slice(8)}` : clean; } export const hashRecoveryCode = (code: string) => hashToken(normaliseRecoveryCode(code));