35 lines
1.0 KiB
Python
35 lines
1.0 KiB
Python
|
|
import logging
|
||
|
|
import secrets
|
||
|
|
import time
|
||
|
|
|
||
|
|
logger = logging.getLogger("yuxi.channel.xmpp.pairing")
|
||
|
|
|
||
|
|
_PAIRING_CODES: dict[str, tuple[str, float]] = {}
|
||
|
|
_CODE_TTL_SECONDS = 300
|
||
|
|
|
||
|
|
|
||
|
|
async def generate_xmpp_pairing_code(peer_id: str) -> str:
|
||
|
|
code = f"{secrets.randbelow(1_000_000):06d}"
|
||
|
|
_PAIRING_CODES[peer_id] = (code, time.monotonic())
|
||
|
|
logger.info("XMPP pairing code generated for peer %s", peer_id)
|
||
|
|
return code
|
||
|
|
|
||
|
|
|
||
|
|
async def verify_xmpp_pairing_code(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 secrets.compare_digest(stored_code, code):
|
||
|
|
return False
|
||
|
|
_PAIRING_CODES.pop(peer_id, None)
|
||
|
|
logger.info("XMPP pairing code verified for peer %s", peer_id)
|
||
|
|
return True
|
||
|
|
|
||
|
|
|
||
|
|
def normalize_xmpp_allow_entry(entry: str) -> str:
|
||
|
|
return entry.strip().split("/")[0].lower()
|