/** * RFC 6238 TOTP codes for the sandbox MFA tests (contract * docs/development/V1-2_ANATOMICAL_SHEETS.md ยง15): HMAC-SHA1, 30 s steps, * 6 digits, the parameters GoTrue v2.197.0 uses. Node `crypto` only, no * dependency. The secret stays in the test's memory: never printed, logged or * written anywhere. */ import { createHmac } from 'node:crypto' const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' export const TOTP_STEP_SECONDS = 30 function base32Decode(text: string): Buffer { const clean = text.replace(/=+$/, '').toUpperCase() const bytes: number[] = [] let buffer = 0 let bits = 0 for (const char of clean) { const value = BASE32.indexOf(char) if (value < 0) throw new Error('totp: secret is not base32') buffer = (buffer << 5) | value bits += 5 if (bits >= 8) { bits -= 8 bytes.push((buffer >> bits) & 0xff) } } return Buffer.from(bytes) } /** * A code the authenticator would show now, never one about to change: a code * sent in its last seconds may reach GoTrue in the next step. */ export async function currentCode(secret: string): Promise { const step = TOTP_STEP_SECONDS * 1000 const left = step - (Date.now() % step) if (left < 3000) await new Promise((resolve) => setTimeout(resolve, left + 200)) return totpCode(secret) } /** The 6-digit code of `secret` for the step holding `at` (ms since epoch). */ export function totpCode(secret: string, at = Date.now()): string { const counter = Buffer.alloc(8) counter.writeBigUInt64BE(BigInt(Math.floor(at / 1000 / TOTP_STEP_SECONDS))) const mac = createHmac('sha1', base32Decode(secret)).update(counter).digest() const offset = mac[mac.length - 1] & 0x0f const value = (mac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000 return value.toString().padStart(6, '0') }