39 lines
1.1 KiB
Python
39 lines
1.1 KiB
Python
|
|
import logging
|
||
|
|
import secrets
|
||
|
|
import time
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
_PAIRING_CODES: dict[str, tuple[str, float]] = {}
|
||
|
|
_CODE_TTL_SECONDS = 300
|
||
|
|
|
||
|
|
|
||
|
|
async def generate_mc_pairing_code(peer_id: str) -> str:
|
||
|
|
code = f"{secrets.randbelow(1_000_000):06d}"
|
||
|
|
_PAIRING_CODES[peer_id] = (code, time.monotonic())
|
||
|
|
logger.info("MC pairing code generated for peer %s", peer_id)
|
||
|
|
return code
|
||
|
|
|
||
|
|
|
||
|
|
async def verify_mc_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("MC pairing code verified for peer %s", peer_id)
|
||
|
|
return True
|
||
|
|
|
||
|
|
|
||
|
|
def normalize_mc_allow_entry(entry: str) -> str:
|
||
|
|
stripped = entry.strip()
|
||
|
|
for prefix in ("minecraft:", "mc:"):
|
||
|
|
if stripped.lower().startswith(prefix):
|
||
|
|
stripped = stripped[len(prefix) :]
|
||
|
|
return stripped.lower()
|