"""TOTP second factor (TODO 3.0, SPEC Q14). Built now rather than later, on purpose. Retrofitting 2FA means reopening the login flow, the session model, the user model and the audit log at once, and ``users.totp_secret`` was in the schema from Phase 1 for exactly this. Policy, from TODO 3.0: **enforced for ``admin``, opt-in for everyone else.** Over Tailscale the network layer already demands an enrolled device, so UI 2FA is belt-and-braces; the day this is served from a public domain it stops being optional. A ``require_2fa`` server setting flips the whole thing. """ from __future__ import annotations import pyotp # RFC 6238 defaults, which is also what every authenticator app assumes. DIGITS = 6 PERIOD_S = 30 # Accept the adjacent 30-second steps as well as the current one, so a phone # clock a few seconds out still works. One step either side is the usual # compromise: three windows is 90 seconds of exposure rather than 30, and # anything wider starts to matter. VALID_WINDOW = 1 ISSUER = "poorBird" def new_secret() -> str: """A fresh base32 secret for ``users.totp_secret``.""" return pyotp.random_base32() def provisioning_uri(secret: str, username: str) -> str: """The ``otpauth://`` URI an authenticator app scans as a QR code.""" return pyotp.TOTP(secret, digits=DIGITS, interval=PERIOD_S).provisioning_uri( name=username, issuer_name=ISSUER ) def verify(secret: str | None, code: str | None) -> bool: """True if ``code`` is currently valid for ``secret``. Returns False rather than raising for a missing secret, a missing code or a malformed one. pyotp compares with ``hmac.compare_digest`` internally, so a wrong code does not leak its position through timing. **Known limitation:** a code stays valid for its whole window, so it can be replayed within ~90 seconds by someone who observed it. Preventing that needs the last-accepted counter persisted per user, which is a column this schema does not have yet. Worth adding if this is ever exposed publicly; on a Tailscale-only LAN the observer has already had to get onto the network. Not silently ignored -- just not paid for yet. """ if not secret or not code: return False code = code.strip().replace(" ", "") if not code.isdigit() or len(code) != DIGITS: return False return pyotp.TOTP(secret, digits=DIGITS, interval=PERIOD_S).verify( code, valid_window=VALID_WINDOW )