"""Opaque Bearer sessions backed by Redis/Valkey, TTL-bound, AOF-persistent.""" import json import os import secrets import uuid from datetime import datetime, timedelta, timezone import redis.asyncio as redis _client: redis.Redis | None = None TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) def init(url: str) -> None: global _client _client = redis.from_url(url, decode_responses=True, socket_timeout=3, socket_connect_timeout=3) async def close() -> None: if _client is not None: await _client.close() def client() -> redis.Redis: if _client is None: raise RuntimeError("session store is not initialized") return _client async def ping() -> bool: try: return bool(await client().ping()) except Exception: # noqa: BLE001 - readiness probe return False async def create(user_id: uuid.UUID) -> tuple[str, datetime]: token = secrets.token_urlsafe(32) # 256 bits of entropy, opaque and non-guessable expires_at = datetime.now(timezone.utc) + timedelta(seconds=TTL_SECONDS) payload = json.dumps({"user_id": str(user_id), "expires_at": expires_at.isoformat()}) await client().set(f"session:{token}", payload, ex=TTL_SECONDS) return token, expires_at async def resolve(token: str) -> uuid.UUID | None: raw = await client().get(f"session:{token}") if raw is None: return None data = json.loads(raw) return uuid.UUID(data["user_id"]) async def revoke(token: str) -> None: await client().delete(f"session:{token}")