totp.ts

769 B · raw

1import { TOTP, URI } from "otpauth";23export type TOTPAlgorithm = "SHA1" | "SHA256" | "SHA512";45export function generateTOTP(6  base32Secret: string,7  algorithm: TOTPAlgorithm = "SHA1"8): { code: string; remaining: number } {9  const totp = new TOTP({ secret: base32Secret, digits: 6, period: 30, algorithm });10  const code = totp.generate();11  const remaining = 30 - (Math.floor(Date.now() / 1000) % 30);12  return { code, remaining };13}1415export function parseOtpauthURI(uri: string): { secret: string; algorithm?: TOTPAlgorithm } | null {16  try {17    const parsed = URI.parse(uri);18    if (parsed instanceof TOTP) {19      return { secret: parsed.secret.base32, algorithm: parsed.algorithm as TOTPAlgorithm };20    }21    return null;22  } catch {23    return null;24  }25}