Functional Weave
Code in Rust

auth.recovery-codes@1.0.0

impl/python/consume_recovery_code.py

1,566 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.

import re
from typing import Sequence

from .auth_recovery_codes_hash_recovery_code import hash_recovery_code  ← hashRecoveryCode, another function of this group · built into the same file, even by a slim install
from .auth_recovery_codes_normalise_recovery_code import normalise_recovery_code  ← normaliseRecoveryCode, another function of this group · built into the same file, even by a slim install
from .auth_recovery_codes_types import RecoveryCheck
from .crypto_constant_time_equal import constant_time_equal  ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune
from .encoding_hex_hex_decode import hex_decode

_HASH = re.compile(r"[0-9a-f]{64}")


def consume_recovery_code(code: str, hashes: Sequence[str]) -> RecoveryCheck:
    """One recovery-code attempt as a pure state change: the stored hashes in,
    whether the code matched and the hashes to store from now on out. Every
    stored hash is compared in constant time, with no early exit."""
    if isinstance(hashes, (str, dict)) or not hasattr(hashes, "__len__"):
        raise TypeError("hashes must be a list of 64 lowercase hex characters each")
    for h in hashes:
        if not isinstance(h, str) or not _HASH.fullmatch(h):
            raise ValueError("hashes must be a list of 64 lowercase hex characters each")
    if normalise_recovery_code(code) is None:
        return RecoveryCheck(valid=False, index=None, remaining=list(hashes))
    attempt = hex_decode(hash_recovery_code(code))
    index = -1
    for i, h in enumerate(hashes):
        same = constant_time_equal(attempt, hex_decode(h))
        if same and index < 0:
            index = i
    if index < 0:
        return RecoveryCheck(valid=False, index=None, remaining=list(hashes))
    return RecoveryCheck(valid=True, index=index, remaining=[h for i, h in enumerate(hashes) if i != index])