/** * Authenticator-app codes (RFC 6238: SHA-1, 6 digits, 30 seconds), as Cross Events 2.3 and the Hub, * so secrets moved from Events keep working. `matchStep` returns the step a code belongs to, so a * code that was used once is refused the second time. */ import crypto from 'node:crypto'; const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; export const STEP = 30; export function base32Encode(buf: Uint8Array): string { let bits = 0; let value = 0; let out = ''; for (const byte of buf) { value = (value << 8) | byte; bits += 8; while (bits >= 5) { out += BASE32[(value >>> (bits - 5)) & 31]; bits -= 5; } } if (bits > 0) out += BASE32[(value << (5 - bits)) & 31]; return out; } export function base32Decode(str: string): Buffer { let bits = 0; let value = 0; const out: number[] = []; for (const ch of String(str).toUpperCase().replace(/=+$/, '')) { const idx = BASE32.indexOf(ch); if (idx === -1) continue; value = (value << 5) | idx; bits += 5; if (bits >= 8) { out.push((value >>> (bits - 8)) & 255); bits -= 8; } } return Buffer.from(out); } export const generateSecret = () => base32Encode(crypto.randomBytes(20)); export function codeAt(secret: string, counter: number): string { const buf = Buffer.alloc(8); buf.writeBigUInt64BE(BigInt(counter)); const hmac = crypto.createHmac('sha1', base32Decode(secret)).update(buf).digest(); const offset = hmac[hmac.length - 1]! & 0xf; const num = ((hmac[offset]! & 0x7f) << 24) | (hmac[offset + 1]! << 16) | (hmac[offset + 2]! << 8) | hmac[offset + 3]!; return String(num % 1_000_000).padStart(6, '0'); } /** The step `code` is right for (now, or one either side for clock drift), or null. Steps up to `afterStep` were used. */ export function matchStep(secret: string, code: unknown, { now = Date.now(), afterStep = -1 } = {}): number | null { const clean = String(code ?? '').replace(/\D/g, ''); if (clean.length !== 6) return null; const counter = Math.floor(now / 1000 / STEP); for (const c of [counter - 1, counter, counter + 1]) { if (c <= afterStep) continue; if (crypto.timingSafeEqual(Buffer.from(codeAt(secret, c)), Buffer.from(clean))) return c; } return null; } /** The otpauth:// link an authenticator app scans as a QR code. */ export function otpauthUrl(secret: string, account: string, issuer: string): string { const label = `${issuer}:${account}`; return `otpauth://totp/${encodeURIComponent(label)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`; }