Files
lan-clipboard/backend/app/api/ws.py
T
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

107 lines
4.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, bearer_token
from app.config import get_settings
from app.db import _session_factory
from app.services.sessions import is_session_valid, resolve_session
from app.services.tokens import is_token_valid, resolve_token
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_session(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 _resolve_token(plain: str, ip: str | None) -> tuple[int, int] | None:
with _session_factory()() as db:
token = resolve_token(db, plain, ip)
return (token.id, token.user_id) if token else None
def _still_valid(conn: Connection) -> bool:
with _session_factory()() as db:
if conn.token_id is not None:
return is_token_valid(db, conn.token_id)
return conn.session_id is not None and is_session_valid(db, conn.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):
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:
plain = bearer_token(websocket.headers.get("authorization"))
origin = websocket.headers.get("origin")
# Origin check protects the cookie-authenticated socket against cross-site hijacking.
# The desktop agent sends a token and no Origin; browsers always send Origin and
# cannot set an Authorization header on WebSockets.
origin_ok = (origin or "").rstrip("/") in get_settings().allowed_origin_list
if not origin_ok and not (plain is not None and origin is None):
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
ip = websocket.client.host if websocket.client else None
if plain is not None:
ids = await run_in_threadpool(_resolve_token, plain, ip)
else:
ids = await run_in_threadpool(_resolve_session, websocket.cookies.get(SESSION_COOKIE))
if ids is None:
await websocket.close(code=CLOSE_UNAUTHORIZED)
return
credential_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, token_id=credential_id)
if plain is not None
else Connection(websocket=websocket, user_id=user_id, session_id=credential_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)