import crypto from 'node:crypto'; export const TOTP_PERIOD_SECONDS = 30; export const TOTP_DIGITS = 6; export const TOTP_WINDOW = 1; const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; export function generateTotpSecret() { return encodeBase32(crypto.randomBytes(20)); } export function totpProvisioningUri(issuer, account, secret) { const normalizedIssuer = String(issuer ?? '').trim(); const normalizedAccount = String(account ?? '').trim(); const label = normalizedIssuer ? `${normalizedIssuer}:${normalizedAccount}` : normalizedAccount; const params = new URLSearchParams({ secret: normalizeSecret(secret), algorithm: 'SHA1', digits: String(TOTP_DIGITS), period: String(TOTP_PERIOD_SECONDS), }); if (normalizedIssuer) params.set('issuer', normalizedIssuer); return `otpauth://totp/${encodeURIComponent(label)}?${params.toString()}`; } export function verifyTotp(secret, token, now = Date.now()) { const normalizedSecret = normalizeSecret(secret); const normalizedToken = normalizeToken(token); if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return false; let key; try { key = decodeBase32(normalizedSecret); } catch { return false; } if (key.length === 0) return false; const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS); for (let offset = -TOTP_WINDOW; offset <= TOTP_WINDOW; offset += 1) { if (period + offset < 0) continue; const counter = Buffer.alloc(8); counter.writeBigUInt64BE(BigInt(period + offset)); const digest = crypto.createHmac('sha1', key).update(counter).digest(); const index = digest[digest.length - 1] & 0x0f; const value = ((digest[index] & 0x7f) << 24) | (digest[index + 1] << 16) | (digest[index + 2] << 8) | digest[index + 3]; const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0'); if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return true; } return false; } function normalizeSecret(value) { return String(value ?? '').trim().toUpperCase().replaceAll(' ', '').replaceAll('=', ''); } function normalizeToken(value) { const token = String(value ?? '').trim(); return /^\d{6}$/.test(token) ? token : ''; } function encodeBase32(buffer) { let output = ''; let bits = 0; let value = 0; for (const byte of buffer) { value = (value << 8) | byte; bits += 8; while (bits >= 5) { output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31]; bits -= 5; } } if (bits > 0) output += BASE32_ALPHABET[(value << (5 - bits)) & 31]; return output; } function decodeBase32(value) { let bits = 0; let buffer = 0; const output = []; for (const character of value) { const index = BASE32_ALPHABET.indexOf(character); if (index < 0) throw new Error('invalid base32 secret'); buffer = (buffer << 5) | index; bits += 5; while (bits >= 8) { bits -= 8; output.push((buffer >>> bits) & 255); } buffer &= bits === 0 ? 0 : (1 << bits) - 1; } return Buffer.from(output); }