import { TOTP, URI } from "otpauth"; export type TOTPAlgorithm = "SHA1" | "SHA256" | "SHA512"; export function generateTOTP( base32Secret: string, algorithm: TOTPAlgorithm = "SHA1" ): { code: string; remaining: number } { const totp = new TOTP({ secret: base32Secret, digits: 6, period: 30, algorithm }); const code = totp.generate(); const remaining = 30 - (Math.floor(Date.now() / 1000) % 30); return { code, remaining }; } export function parseOtpauthURI(uri: string): { secret: string; algorithm?: TOTPAlgorithm } | null { try { const parsed = URI.parse(uri); if (parsed instanceof TOTP) { return { secret: parsed.secret.base32, algorithm: parsed.algorithm as TOTPAlgorithm }; } return null; } catch { return null; } }