"""Password KDF (Argon2id) and opaque bearer-token helpers.""" from __future__ import annotations import hashlib import secrets from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerifyMismatchError, VerificationError # Argon2id is the default of argon2-cffi's PasswordHasher. Parameters are kept # modest so the local test suite stays fast while still using a real KDF. _hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1) def hash_password(password: str) -> str: return _hasher.hash(password) def verify_password(password_hash: str, password: str) -> bool: try: return _hasher.verify(password_hash, password) except (VerifyMismatchError, VerificationError, InvalidHashError): return False def new_token() -> str: """Opaque bearer token with >= 256 bits of entropy.""" return secrets.token_urlsafe(32) def token_hash(token: str) -> str: """Sessions are identified by a SHA-256 of the token, never the token itself.""" return hashlib.sha256(token.encode("utf-8")).hexdigest()