import secrets import time import logging logger = logging.getLogger(__name__) _PAIRING_CODES: dict[str, tuple[str, float]] = {} _CODE_TTL_SECONDS = 300 class IntercomPairing: id_label = "intercomContactId" async def generate_code(self, peer_id: str) -> str: code = f"{secrets.randbelow(1_000_000):06d}" _PAIRING_CODES[peer_id] = (code, time.monotonic()) logger.info("Intercom pairing code generated for contact %s", peer_id) return code async def verify_code(self, peer_id: str, code: str) -> bool: stored = _PAIRING_CODES.get(peer_id) if stored is None: return False stored_code, created_at = stored if time.monotonic() - created_at > _CODE_TTL_SECONDS: _PAIRING_CODES.pop(peer_id, None) logger.info("Intercom pairing code expired for contact %s", peer_id) return False if not secrets.compare_digest(stored_code, code): return False _PAIRING_CODES.pop(peer_id, None) logger.info("Intercom pairing code verified for contact %s", peer_id) return True def normalize_allow_entry(self, entry: str) -> str: stripped = entry.strip() for prefix in ("intercom:", "contact:"): if stripped.lower().startswith(prefix): stripped = stripped[len(prefix) :].strip() return stripped async def notify_approval(self, config: dict, peer_id: str, account_id: str | None = None) -> None: logger.info("Intercom pairing approved for contact %s (account=%s)", peer_id, account_id or "default")