import secrets import time import logging logger = logging.getLogger(__name__) CODE_TTL_SECONDS = 600 CODE_CLEANUP_INTERVAL = 300 class MessengerPairing: def __init__(self): self._codes: dict[str, dict] = {} self._last_cleanup = time.monotonic() async def generate_code(self, peer_id: str, account_id: str = "default") -> str: self._evict_expired() key = f"{account_id}:{peer_id}" code = str(secrets.randbelow(900000) + 100000) self._codes[key] = { "code": code, "created_at": time.monotonic(), "peer_id": peer_id, "account_id": account_id, } logger.info(f"messenger pairing code generated for {peer_id}: {code}") return code async def verify_code(self, peer_id: str, code: str, account_id: str = "default") -> bool: self._evict_expired() key = f"{account_id}:{peer_id}" entry = self._codes.get(key) if not entry: return False result = entry["code"] == code if result: del self._codes[key] logger.info(f"messenger pairing verified for {peer_id}") return result def _evict_expired(self): now = time.monotonic() if now - self._last_cleanup < CODE_CLEANUP_INTERVAL: return self._last_cleanup = now expired = [k for k, v in self._codes.items() if now - v["created_at"] > CODE_TTL_SECONDS] for k in expired: del self._codes[k]