Files
faunosteo/packages/supabase/tests/sandbox/totp.ts
T
bchanot ef1f4b593f test(supabase): V1-2.1 re-runnable sandbox suite, two-session cases, caps timing
F18 and workspaces no longer leave the seed owner changed. Ten two-session
scenarios with a blocking session, seed-owner AR-1 acceptance, shim columns
against the image, save/submit/approve/publish timed at the caps.
2026-10-28 18:14:10 +01:00

41 lines
1.4 KiB
TypeScript

/**
* 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)
}
/** 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')
}