ForcePilot/backend/package/yuxi/channel/extensions/feishu/pairing.py

51 lines
1.5 KiB
Python
Raw Normal View History

from __future__ import annotations
import logging
import secrets
import time
logger = logging.getLogger(__name__)
CODE_TTL = 300
class FeishuPairingAdapter:
id_label = "feishuOpenId"
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 normalize_allow_entry(self, entry: str) -> str:
entry = entry.strip()
if entry.startswith("open_id:"):
return entry[len("open_id:"):]
if entry.startswith("user:"):
return entry[len("user:"):]
return entry
async def notify_approval(self, config: dict, peer_id: str, account_id: str | None = None) -> None:
logger.info("feishu pairing approved for peer %s", peer_id)
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]