Files
crosscode-platform/apps/accounts/backend/src/lib/recoveryCodes.ts
T
joshuaandClaude Opus 5.5 069b66fd30 Accounts 1.0.0 backend: OIDC provider, sign-in steps, account and admin API
oidc-provider 9.13.3 with PKCE, ES256, crosscode.identity/1 claims and
back-channel logout; clients are the linked products (Connect). Sign-in
steps (password, sign-up, email check, 2FA and its setup, privacy notice,
news question, password reset) survive to the product. Account page and
admin API, church profile, export and deletion fan-out, Hub v2 client,
jobs. End-to-end tests with a test product on openid-client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:33:49 +02:00

28 lines
1.1 KiB
TypeScript

/**
* 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));