40 lines
1.2 KiB
Python
40 lines
1.2 KiB
Python
import secrets
|
|
import time
|
|
|
|
from .defaults import PAIRING_CODE_LENGTH, PAIRING_CODE_TTL
|
|
|
|
|
|
class BlueskyPairing:
|
|
id_label = "DID"
|
|
|
|
def __init__(self):
|
|
self._pending: dict[str, dict] = {}
|
|
|
|
def generate_code(self, sender_did: str, sender_handle: str = "") -> str:
|
|
self._cleanup_expired()
|
|
|
|
code = secrets.token_hex(PAIRING_CODE_LENGTH // 2)[:PAIRING_CODE_LENGTH].upper()
|
|
self._pending[code] = {
|
|
"did": sender_did,
|
|
"handle": sender_handle,
|
|
"created_at": time.time(),
|
|
}
|
|
return code
|
|
|
|
def verify_code(self, code: str) -> dict | None:
|
|
self._cleanup_expired()
|
|
return self._pending.pop(code, None)
|
|
|
|
def normalize_allow_entry(self, entry: str) -> str:
|
|
return entry.replace("did:", "").strip().lower()
|
|
|
|
def get_pending(self) -> list[dict]:
|
|
self._cleanup_expired()
|
|
return [{"code": code, **entry} for code, entry in self._pending.items()]
|
|
|
|
def _cleanup_expired(self):
|
|
now = time.time()
|
|
expired = [code for code, entry in self._pending.items() if now - entry["created_at"] > PAIRING_CODE_TTL]
|
|
for code in expired:
|
|
del self._pending[code]
|