Files
dbildhauerandClaude Opus 5.5 d8377c8a04 feat: api-tokens pro gerät (backend)
Tokens werden einmal angezeigt und nur gehasht gespeichert. Anmeldung
per Authorization: Bearer für Clips, Dateien, Projektliste/-anlage und
den Live-Sync (WebSocket ohne Origin). Konto, Admin, Sessions, Tokens
und Projektverwaltung bleiben der Browser-Session vorbehalten. Widerruf
schließt die Verbindungen des Tokens sofort.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 14:52:04 +01:00

85 lines
2.7 KiB
Python

"""In-process registry of WebSocket connections, keyed by user.
All methods run on the event loop; sync request handlers reach them via BackgroundTasks.
This only works with a single worker process (see CLAUDE.md).
"""
import asyncio
import json
import logging
from collections import defaultdict
from dataclasses import dataclass
from typing import Any
from fastapi import WebSocket
logger = logging.getLogger(__name__)
SEND_TIMEOUT_SECONDS = 5
CLOSE_UNAUTHORIZED = 4401
@dataclass(eq=False)
class Connection:
websocket: WebSocket
user_id: int
# Exactly one of these: browser session or device token
session_id: int | None = None
token_id: int | None = None
class Hub:
def __init__(self) -> None:
self._by_user: dict[int, set[Connection]] = defaultdict(set)
def count(self, user_id: int) -> int:
return len(self._by_user.get(user_id, ()))
def add(self, conn: Connection) -> None:
self._by_user[conn.user_id].add(conn)
def remove(self, conn: Connection) -> None:
conns = self._by_user.get(conn.user_id)
if conns is not None:
conns.discard(conn)
if not conns:
del self._by_user[conn.user_id]
async def broadcast(self, user_id: int, message: dict[str, Any]) -> None:
"""Send a message to every connection of one user; dead connections are dropped."""
text = json.dumps(message)
for conn in list(self._by_user.get(user_id, ())):
try:
await asyncio.wait_for(conn.websocket.send_text(text), SEND_TIMEOUT_SECONDS)
except Exception:
logger.info("Dropping unresponsive WebSocket of user %s", user_id)
self.remove(conn)
await self._close(conn, 1011)
async def close_session(self, session_id: int) -> None:
await self._close_where(lambda c: c.session_id == session_id)
async def close_token(self, token_id: int) -> None:
await self._close_where(lambda c: c.token_id == token_id)
async def close_user(self, user_id: int, except_session_id: int | None = None) -> None:
await self._close_where(
lambda c: c.user_id == user_id and c.session_id != except_session_id
)
async def _close_where(self, predicate) -> None:
targets = [c for conns in self._by_user.values() for c in conns if predicate(c)]
for conn in targets:
self.remove(conn)
await self._close(conn, CLOSE_UNAUTHORIZED)
@staticmethod
async def _close(conn: Connection, code: int) -> None:
try:
await conn.websocket.close(code=code)
except Exception: # already closed or broken
logger.debug("WebSocket already closed", exc_info=True)
hub = Hub()