Functional Weave
Code in Rust

auth.totp@1.0.0

impl/python/verify_totp.py

2,453 bytes · the Python implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import List, Optional

from .auth_totp_hotp_code import check_totp_settings, hotp_from_key, totp_secret_key  ← hotpCode, another function of this group · built into the same file, even by a slim install
from .auth_totp_totp_code import check_totp_now  ← totpCode, another function of this group · built into the same file, even by a slim install
from .auth_totp_types import TotpCheck, TotpSettings
from .crypto_constant_time_equal import constant_time_equal  ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune


def _ascii(text: str) -> List[int]:
    return [ord(ch) & 255 for ch in text]


def verify_totp(
    secret: str,
    code: str,
    now: int,
    settings: TotpSettings,
    window: int,
    drift: int,
    last_used_step: Optional[int],
) -> TotpCheck:
    """Checks a typed code against the steps around now (centred on the
    user's known drift), closest first, earlier first on a tie. Every step in
    the window is compared in constant time. A step at or before
    last_used_step is refused as replayed."""
    check_totp_now(now)
    check_totp_settings(settings)
    if type(window) is not int or window < 0 or window > 10:
        raise ValueError("window must be a whole number from 0 to 10")
    if type(drift) is not int or drift < -1000 or drift > 1000:
        raise ValueError("drift must be a whole number from -1000 to 1000")
    if last_used_step is not None and type(last_used_step) is not int:
        raise TypeError("lastUsedStep must be a whole number or null")
    if not isinstance(code, str):
        raise TypeError("code must be text")
    key = totp_secret_key(secret)
    typed = code.replace(" ", "")
    if len(typed) != settings.digits or not all("0" <= ch <= "9" for ch in typed):
        return TotpCheck(valid=False, step=None, drift=None, reason="malformed_code")
    expected = now // settings.period
    centre = expected + drift
    typed_bytes = _ascii(typed)
    accepted = None
    replayed = False
    for distance in range(window + 1):
        for step in [centre] if distance == 0 else [centre - distance, centre + distance]:
            if step < 0:
                continue
            if not constant_time_equal(_ascii(hotp_from_key(key, step, settings.digits, settings.algorithm)), typed_bytes):
                continue
            if last_used_step is not None and step <= last_used_step:
                replayed = True
            elif accepted is None:
                accepted = step
    if accepted is not None:
        return TotpCheck(valid=True, step=accepted, drift=accepted - expected, reason=None)
    return TotpCheck(valid=False, step=None, drift=None, reason="replayed" if replayed else "wrong_code")