from __future__ import annotations import base64 import hashlib import hmac import secrets import sqlite3 import time from pathlib import Path from typing import Any from .auth import find_user_by_identifier, get_user, init_database, set_password from .mail_config import mask_email, password_recovery_available, send_password_reset_email from .settings import DATABASE_PATH RESET_TTL_SECONDS = 15 * 60 RESET_ATTEMPTS = 5 RESET_COOLDOWN_SECONDS = 60 PUBLIC_IP_LIMIT = 10 PUBLIC_IDENTIFIER_LIMIT = 5 RATE_WINDOW_SECONDS = 15 * 60 RESET_PBKDF2_ITERATIONS = 120_000 def _connect() -> sqlite3.Connection: Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True) conn = sqlite3.connect(DATABASE_PATH, timeout=10) conn.row_factory = sqlite3.Row conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA foreign_keys=ON") return conn def init_password_reset_database() -> None: # The reset table has a foreign key to users. Keep this initializer safe even # when it is called independently from the normal application startup order. init_database() with _connect() as conn: conn.executescript( """ CREATE TABLE IF NOT EXISTS password_reset_codes ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, code_hash TEXT NOT NULL, salt TEXT NOT NULL, iterations INTEGER NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, attempts_remaining INTEGER NOT NULL, consumed_at INTEGER NOT NULL DEFAULT 0, request_ip TEXT NOT NULL DEFAULT '', FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE ); CREATE INDEX IF NOT EXISTS idx_password_reset_user ON password_reset_codes(user_id, created_at DESC); CREATE TABLE IF NOT EXISTS auth_rate_limits ( rate_key TEXT PRIMARY KEY, window_started INTEGER NOT NULL, count INTEGER NOT NULL ); """ ) now = int(time.time()) conn.execute("DELETE FROM password_reset_codes WHERE created_at str: digest = hashlib.pbkdf2_hmac("sha256", code.encode("ascii"), salt, iterations) return base64.b64encode(digest).decode("ascii") def _rate_key(prefix: str, value: str) -> str: digest = hashlib.sha256(str(value or "").strip().lower().encode("utf-8")).hexdigest() return f"{prefix}:{digest}" def _allow_rate(rate_key: str, limit: int, window_seconds: int, now: int) -> bool: init_password_reset_database() with _connect() as conn: # Serialize increments so simultaneous public requests cannot all observe # the same counter and slip past the limit. conn.execute("BEGIN IMMEDIATE") row = conn.execute( "SELECT window_started,count FROM auth_rate_limits WHERE rate_key=?", (rate_key,), ).fetchone() if not row or now - int(row["window_started"]) >= window_seconds: conn.execute( """ INSERT INTO auth_rate_limits(rate_key,window_started,count) VALUES(?,?,1) ON CONFLICT(rate_key) DO UPDATE SET window_started=excluded.window_started,count=1 """, (rate_key, now), ) return True count = int(row["count"] or 0) if count >= limit: return False conn.execute("UPDATE auth_rate_limits SET count=count+1 WHERE rate_key=?", (rate_key,)) return True def public_reset_request_allowed(identifier: str, request_ip: str) -> bool: now = int(time.time()) ip_ok = _allow_rate(_rate_key("reset-ip", request_ip or "unknown"), PUBLIC_IP_LIMIT, RATE_WINDOW_SECONDS, now) identifier_ok = _allow_rate(_rate_key("reset-id", identifier), PUBLIC_IDENTIFIER_LIMIT, RATE_WINDOW_SECONDS, now) return ip_ok and identifier_ok def issue_password_reset(user_id: int, *, request_ip: str = "", language: str = "en") -> dict[str, Any]: init_password_reset_database() if not password_recovery_available(): raise RuntimeError("Password recovery mail is not configured") user = get_user(user_id) if not user: raise ValueError("User not found") email = str(user.get("email") or "").strip() if not email: raise ValueError("User does not have an email address") now = int(time.time()) code = f"{secrets.randbelow(1_000_000):06d}" salt = secrets.token_bytes(18) encoded_salt = base64.b64encode(salt).decode("ascii") code_hash = _hash_code(code, salt) with _connect() as conn: conn.execute("BEGIN IMMEDIATE") latest = conn.execute( """ SELECT created_at FROM password_reset_codes WHERE user_id=? AND consumed_at=0 ORDER BY created_at DESC LIMIT 1 """, (int(user_id),), ).fetchone() if latest and now - int(latest["created_at"] or 0) < RESET_COOLDOWN_SECONDS: raise RuntimeError("A reset code was sent recently. Please wait before requesting another one") conn.execute("UPDATE password_reset_codes SET consumed_at=? WHERE user_id=? AND consumed_at=0", (now, int(user_id))) cur = conn.execute( """ INSERT INTO password_reset_codes( user_id,code_hash,salt,iterations,created_at,expires_at, attempts_remaining,consumed_at,request_ip ) VALUES(?,?,?,?,?,?,?,?,?) """, ( int(user_id), code_hash, encoded_salt, RESET_PBKDF2_ITERATIONS, now, now + RESET_TTL_SECONDS, RESET_ATTEMPTS, 0, str(request_ip or "")[:120], ), ) reset_id = int(cur.lastrowid) try: send_password_reset_email(email, code, valid_minutes=RESET_TTL_SECONDS // 60, language=language) except Exception: with _connect() as conn: conn.execute("UPDATE password_reset_codes SET consumed_at=? WHERE id=?", (int(time.time()), reset_id)) raise return { "ok": True, "user_id": int(user_id), "username": str(user.get("username") or ""), "masked_email": mask_email(email), "expires_in": RESET_TTL_SECONDS, } def request_password_reset(identifier: str, *, request_ip: str = "", rate_checked: bool = False, language: str = "en") -> dict[str, Any]: identifier = str(identifier or "").strip() if not identifier: return {"ok": True, "delivered": False, "reason": "empty"} if not rate_checked and not public_reset_request_allowed(identifier, request_ip): return {"ok": True, "delivered": False, "reason": "rate_limited"} user = find_user_by_identifier(identifier) if not user or not str(user.get("email") or "").strip() or not password_recovery_available(): return {"ok": True, "delivered": False, "reason": "unavailable"} try: result = issue_password_reset(int(user["id"]), request_ip=request_ip, language=language) result["delivered"] = True return result except RuntimeError as exc: if "sent recently" in str(exc): return {"ok": True, "delivered": False, "reason": "cooldown", "user_id": int(user["id"]), "username": str(user["username"])} raise def confirm_password_reset(identifier: str, code: str, password: str) -> dict[str, Any]: init_password_reset_database() if len(str(password or "")) < 8: raise ValueError("Password must contain at least 8 characters") user = find_user_by_identifier(str(identifier or "").strip()) code = str(code or "").strip() if not user or not (len(code) == 6 and code.isdigit()): # Keep a small amount of work on the unknown-user path. hashlib.pbkdf2_hmac("sha256", code.encode("utf-8"), b"wgtools-reset-invalid", RESET_PBKDF2_ITERATIONS) raise ValueError("Invalid or expired reset code") now = int(time.time()) with _connect() as conn: conn.execute("BEGIN IMMEDIATE") row = conn.execute( """ SELECT * FROM password_reset_codes WHERE user_id=? AND consumed_at=0 ORDER BY created_at DESC LIMIT 1 """, (int(user["id"]),), ).fetchone() if not row or int(row["expires_at"] or 0) < now or int(row["attempts_remaining"] or 0) <= 0: if row: conn.execute("UPDATE password_reset_codes SET consumed_at=? WHERE id=?", (now, int(row["id"]))) conn.commit() raise ValueError("Invalid or expired reset code") salt = base64.b64decode(str(row["salt"])) candidate = _hash_code(code, salt, int(row["iterations"])) if not hmac.compare_digest(candidate, str(row["code_hash"])): remaining = max(0, int(row["attempts_remaining"]) - 1) conn.execute( "UPDATE password_reset_codes SET attempts_remaining=?,consumed_at=? WHERE id=?", (remaining, now if remaining <= 0 else 0, int(row["id"])), ) conn.commit() raise ValueError("Invalid or expired reset code") conn.execute("UPDATE password_reset_codes SET consumed_at=? WHERE id=?", (now, int(row["id"]))) set_password(int(user["id"]), password) return { "ok": True, "user_id": int(user["id"]), "username": str(user.get("username") or ""), "masked_email": mask_email(str(user.get("email") or "")), }