""" TOTP module — Google Authenticator compatible 2FA codes. Uses pyotp (RFC 6238). """ import time import pyotp def generate_secret(length: int = 32) -> str: """Generate a new random TOTP secret (base32-encoded).""" return pyotp.random_base32(length=length) def get_code(secret: str) -> str: """Get current 6-digit TOTP code.""" return pyotp.TOTP(secret).now() def get_code_with_timer(secret: str) -> dict: """Get current code with timing info for GUI display.""" totp = pyotp.TOTP(secret) now = time.time() remaining = 30 - (int(now) % 30) return { "code": totp.now(), "remaining": remaining, "progress": remaining / 30.0, } def verify_code(secret: str, code: str) -> bool: """Verify a TOTP code (with +/- 1 period tolerance).""" return pyotp.TOTP(secret).verify(code, valid_window=1) def format_secret_uri(secret: str, account: str, issuer: str = "ServerManager") -> str: """Generate otpauth:// URI for QR code / authenticator apps.""" return pyotp.TOTP(secret).provisioning_uri(name=account, issuer_name=issuer)