from __future__ import annotations import hmac import logging import secrets import time logger = logging.getLogger(__name__) _PAIRING_CODES: dict[str, tuple[str, float]] = {} _CODE_TTL_SECONDS = 300 class TelegramPairing: id_label = "telegramUserId" 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("Telegram pairing code generated for peer %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) return False if not hmac.compare_digest(stored_code, code): return False _PAIRING_CODES.pop(peer_id, None) return True def normalize_allow_entry(self, entry: str) -> str: stripped = entry.strip() for prefix in ("tg:", "telegram:"): if stripped.startswith(prefix): return stripped[len(prefix):] return stripped async def notify_approval(self, config: dict, peer_id: str, account_id: str | None = None) -> None: logger.info("Telegram pairing approved for peer %s", peer_id) try: from yuxi.channel.extensions.telegram.config import TelegramConfigAdapter adapter = TelegramConfigAdapter() adapter._config = config account = await adapter.resolve_account(account_id or "default") token = account.get("token", "") if not token: return import httpx async with httpx.AsyncClient(timeout=httpx.Timeout(5.0)) as client: await client.post( f"https://api.telegram.org/bot{token}/sendMessage", json={ "chat_id": peer_id, "text": "✅ 您的访问请求已批准。现在可以直接向我发送消息了。", "parse_mode": "HTML", }, ) except Exception: logger.warning("Failed to send approval notification to peer %s", peer_id, exc_info=True)