"""Signed-in dashboard sessions, for OIDC and authenticator-code sign-in. Stdlib only. A session is a random id in an HttpOnly, SameSite=Lax cookie; only its SHA-256 is kept, in memory, so a dashboard restart signs everyone out. """ import hashlib import secrets import threading import time SESSION_COOKIE = "llmhost_session" SESSION_TTL = 12 * 3600 def parse_cookies(header: str) -> dict: out = {} for part in (header or "").split(";"): k, sep, v = part.strip().partition("=") if sep: out.setdefault(k, v) return out def cookie(name, value, max_age, secure, path="/"): attrs = [f"{name}={value}", f"Path={path}", f"Max-Age={max_age}", "HttpOnly", "SameSite=Lax"] if secure: attrs.append("Secure") return "; ".join(attrs) class Sessions: def __init__(self, ttl=SESSION_TTL): self.ttl = ttl self.lock = threading.Lock() self.items = {} # sha256(id) -> {user, name, exp} @staticmethod def _h(sid: str) -> str: return hashlib.sha256(sid.encode()).hexdigest() def create(self, user, name=None) -> str: sid = secrets.token_urlsafe(32) now = time.time() with self.lock: for h in [h for h, s in self.items.items() if s["exp"] < now]: del self.items[h] self.items[self._h(sid)] = {"user": user, "name": name or user, "exp": now + self.ttl} return sid def get(self, cookie_header: str): sid = parse_cookies(cookie_header).get(SESSION_COOKIE) if not sid: return None with self.lock: s = self.items.get(self._h(sid)) if s and s["exp"] < time.time(): del self.items[self._h(sid)] s = None return s def end(self, cookie_header: str): sid = parse_cookies(cookie_header).get(SESSION_COOKIE) if sid: with self.lock: self.items.pop(self._h(sid), None)