Files
lan-clipboard/backend/app/api/ws.py
T
dbildhauerandClaude Opus 5.5 0d89399090 feat: live-sync per websocket im backend
- /api/ws authentifiziert über das Session-Cookie, Origin-Pflicht gegen CSWSH
- Hub im Prozess verteilt clip.created/updated/deleted an alle Geräte des Benutzers
- Ereignisse erst nach erfolgreichem Commit (BackgroundTasks), keine bei Konflikt
- Logout, Session-Widerruf, Passwortänderung und Admin-Aktionen schließen
  betroffene Verbindungen (4401); Session wird alle 5 Minuten neu geprüft
- Heartbeat alle 30 s, höchstens 20 Verbindungen pro Benutzer
- CSP erlaubt wss:// zur eigenen Domain, eingehende WS-Nachrichten max. 64 KiB

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 11:15:43 +01:00

86 lines
3.0 KiB
Python

import asyncio
import time
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from fastapi.concurrency import run_in_threadpool
from app.api.deps import SESSION_COOKIE
from app.config import get_settings
from app.db import _session_factory
from app.services.sessions import is_session_valid, resolve_session
from app.ws.hub import CLOSE_UNAUTHORIZED, Connection, hub
router = APIRouter()
MAX_CONNECTIONS_PER_USER = 20
PING_INTERVAL_SECONDS = 30
REVALIDATE_INTERVAL_SECONDS = 300
CLOSE_TOO_MANY = 4429
def _resolve(token: str | None) -> tuple[int, int] | None:
with _session_factory()() as db:
session = resolve_session(db, token)
return (session.id, session.user_id) if session else None
def _still_valid(session_id: int) -> bool:
with _session_factory()() as db:
return is_session_valid(db, session_id)
async def _heartbeat(conn: Connection) -> None:
"""Keep the connection alive through the proxy and end it when the session ends."""
last_check = time.monotonic()
while True:
await asyncio.sleep(PING_INTERVAL_SECONDS)
await conn.websocket.send_json({"type": "ping"})
if time.monotonic() - last_check >= REVALIDATE_INTERVAL_SECONDS:
last_check = time.monotonic()
if not await run_in_threadpool(_still_valid, conn.session_id):
await conn.websocket.close(code=CLOSE_UNAUTHORIZED)
return
async def _drain(conn: Connection) -> None:
"""Clients do not send commands; reading only detects disconnects."""
while True:
await conn.websocket.receive_text()
@router.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket) -> None:
# Origin check protects the cookie-authenticated socket against cross-site hijacking
origin = (websocket.headers.get("origin") or "").rstrip("/")
if origin not in get_settings().allowed_origin_list:
await websocket.close(code=4403) # before accept: handshake is rejected
return
await websocket.accept()
# Accept first so the client sees the close code and can redirect to login
ids = await run_in_threadpool(_resolve, websocket.cookies.get(SESSION_COOKIE))
if ids is None:
await websocket.close(code=CLOSE_UNAUTHORIZED)
return
session_id, user_id = ids
if hub.count(user_id) >= MAX_CONNECTIONS_PER_USER:
await websocket.close(code=CLOSE_TOO_MANY)
return
conn = Connection(websocket=websocket, user_id=user_id, session_id=session_id)
hub.add(conn)
try:
await websocket.send_json({"type": "hello"})
tasks = [asyncio.create_task(_heartbeat(conn)), asyncio.create_task(_drain(conn))]
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in pending:
task.cancel()
for task in done:
exc = task.exception()
if exc is not None and not isinstance(exc, WebSocketDisconnect | RuntimeError):
raise exc
except WebSocketDisconnect:
pass
finally:
hub.remove(conn)