Source code for s365b.auth.totp

"""Time-based one-time passwords (RFC 6238) for break-glass accounts."""

from __future__ import annotations

import time

import pyotp

[docs] STEP_SECONDS = 30
[docs] def new_secret() -> str: """Create a new random TOTP secret. Returns: Base32 secret. """ return pyotp.random_base32()
[docs] def provisioning_uri(secret: str, username: str, issuer: str) -> str: """Return the ``otpauth://`` URI shown as a QR code during enrolment. Args: secret: Base32 secret. username: Account name shown in the authenticator app. issuer: Product name shown in the authenticator app (from branding). Returns: The URI. """ return pyotp.TOTP(secret).provisioning_uri(name=username, issuer_name=issuer)
[docs] def verify( secret: str, code: str, last_step: int | None, *, now: float | None = None ) -> int | None: """Verify a TOTP code, rejecting replays. Accepts the current code and the one before or after (clock drift), but never a code from a time step at or before ``last_step``. Args: secret: Base32 secret. code: Six-digit code from the user. last_step: Time step of the last accepted code for this account. now: Current Unix time (tests). Returns: The matched time step (store it as the new ``last_step``), or ``None`` if the code is wrong or was already used. """ code = code.strip().replace(" ", "") if not (code.isdigit() and len(code) == 6): return None t = time.time() if now is None else now totp = pyotp.TOTP(secret) current = int(t // STEP_SECONDS) for step in (current - 1, current, current + 1): if last_step is not None and step <= last_step: continue if pyotp.utils.strings_equal(totp.at(step * STEP_SECONDS), code): return step return None