from __future__ import annotations import base64 import hashlib import hmac import json import os import time from typing import Any from app.config import jwt_secret ITERATIONS = 200_000 TOKEN_TTL = 12 * 60 * 60 def hash_password(password: str) -> str: salt = os.urandom(16) digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, ITERATIONS) return f"{salt.hex()}${digest.hex()}" def verify_password(password: str, stored: str) -> bool: salt_hex, digest_hex = stored.split("$", 1) digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), ITERATIONS) return hmac.compare_digest(digest.hex(), digest_hex) def _encode(data: dict[str, Any]) -> str: raw = json.dumps(data, separators=(",", ":")).encode("utf-8") return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") def _decode(raw: str) -> dict[str, Any]: padded = raw + "=" * (-len(raw) % 4) return json.loads(base64.urlsafe_b64decode(padded.encode("ascii"))) def issue_token(payload: dict[str, Any]) -> str: body = {**payload, "exp": int(time.time()) + TOKEN_TTL} raw = _encode(body) signature = hmac.new(jwt_secret().encode("utf-8"), raw.encode("ascii"), hashlib.sha256).hexdigest() return f"{raw}.{signature}" def read_token(token: str) -> dict[str, Any] | None: raw, _, signature = token.partition(".") if not raw or not signature: return None expected = hmac.new(jwt_secret().encode("utf-8"), raw.encode("ascii"), hashlib.sha256).hexdigest() if not hmac.compare_digest(expected, signature): return None try: body = _decode(raw) except (ValueError, json.JSONDecodeError): return None if int(body.get("exp") or 0) < int(time.time()): return None return body