from __future__ import annotations import logging import secrets import time logger = logging.getLogger(__name__) CODE_TTL = 300 class DingTalkPairing: def __init__(self): self._codes: dict[str, tuple[str, float]] = {} async def generate_code(self, peer_id: str) -> str: code = f"{secrets.randbelow(1_000_000):06d}" self._codes[peer_id] = (code, time.monotonic()) self._evict_expired() return code async def verify_code(self, peer_id: str, code: str) -> bool: self._evict_expired() entry = self._codes.get(peer_id) if entry is None: return False stored_code, _ts = entry if stored_code == code: del self._codes[peer_id] return True return False def _evict_expired(self) -> None: now = time.monotonic() expired = [pid for pid, (_code, ts) in self._codes.items() if now - ts > CODE_TTL] for pid in expired: del self._codes[pid]