#!/usr/bin/env python3.14# -*- coding: utf-8 -*-"""A small in-memory sliding-window rate limiter for the auth endpoints.Slows brute force against the unauthenticated login/registration endpoints:at most `max_requests` per `window_seconds` for a given key (the client IP). Itis per-process and best-effort — coarse defense-in-depth alongside the single-usesecure-link tokens and SRP itself, not a distributed quota."""from__future__importannotations__all__=['RateLimiter']importtime#: Above this many tracked keys, drop the ones with no recent activity._PRUNE_THRESHOLD=1024classRateLimiter:"""Allow at most `max_requests` per `window_seconds` per key (sliding window)."""def__init__(self,max_requests:int,window_seconds:int)->None:self._max=max_requestsself._window=window_secondsself._hits:dict[str,list[float]]={}defallow(self,key:str)->bool:"""Record a hit for `key`; return False if it is over the limit in the window."""now=time.time()cutoff=now-self._windowhits=[tfortinself._hits.get(key,[])ift>cutoff]allowed=len(hits)<self._maxifallowed:hits.append(now)self._hits[key]=hitsiflen(self._hits)>_PRUNE_THRESHOLD:self._hits={k:vfork,vinself._hits.items()ifvandv[-1]>cutoff}returnallowed