Files
bonaminandClaude Opus 5.5 f85894a72e refactor(connect): one live connection, no token in any address (SSE removed)
Plan step 4.0. Owner (2026-11-17): no phone in use needs to keep working, so no
compatibility path.
- Removed the SSE channel: routers/sse.py (/api/sse/stream, which still accepted a JWT whose
  session had ended — a signed-out phone could keep listening), services/sse_bus.py (every
  backend module now calls services/ws_bus.broadcast_sync directly), waiter useSSE.js.
- Credentials only in the first frame: the waiter's useWebSocket and the manager's
  LiveProvider send {token} there like the terminal; routers/ws.py no longer reads ?token=
  (a token in a URL ends up in proxy and server logs).
- Waiter: SSEContext → LiveContext (LiveProvider, useLiveContext, liveAlive, the
  'live-event' / 'live-reconnected' window events), dead SSE compat code removed.
- Tests: a token in the address is refused, /api/sse/stream is 404; e2e browser (3 delivery
  modes) and manager assert no token in the live connection's address. Android taps now
  wait for their element (the fixed sleeps made the suite flaky, KI-009).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:49:21 +02:00

165 lines
7.4 KiB
Python

"""
WebSocket endpoint — one persistent connection per client (waiter app, manager, terminal).
Protocol:
1. Client connects: ws://host/api/ws/connect (no query: a token in a URL ends up in
proxy and server logs; the `?token=` form was removed in phase 4.0)
2. Client immediately sends its first frame:
{ "cursor": <last_seq_id>, "token"?: <jwt>, "device"?: <device token> }
(cursor 0 = first connect / no history). Every client (waiter, manager, terminal)
sends its credentials here.
3. Server checks who it is (below). Refused → { "type": "refused", "data": {code} }
and close code 4001 (sign in again) or 4003 (device problem).
4. Server replays missed events the socket may see (seq > cursor) as individual frames
5. Server sends { "type": "ready" } to signal end of replay / start of live stream
6. Live events arrive as: { "seq": 123, "type": "...", "data": { ... } }
7. Every 25s server sends: { "type": "ping" }; the client may answer { "type": "pong" }
8. Control frames (no seq): `device.updated` (re-read /api/devices/me); and before the
server closes the socket itself: `session.ended` (4001), `device.revoked` or
`device.updated` after an app change (4003).
9. On disconnect/error the client reconnects and repeats from step 2
Who may connect (plan step 3.1a, D-8):
- a user session JWT alone (manager, waiter). A terminal session's JWT (bound to a device)
only together with that device's token, like routers.deps.user_from_token over HTTP.
- a device token alone: a paired screen without a signed-in user. If its app signs nobody
in (login mode `none`: customer display, signage, menu tablet) it gets every event;
otherwise (a KDS on its sign-in screen) only events addressed to the device.
- a device token + a terminal JWT of that device: everything a user socket gets.
Agent notes:
- Auth uses a short-lived DB session (the app's get_db, so tests' override applies) that
is closed before streaming starts: an open socket holds no DB connection.
- Never log tokens.
"""
from core.access.deps import public
import asyncio
import json
import logging
from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect
from starlette.websockets import WebSocketState
from core.errors import XeniaError
from database import get_db
from services import ws_bus
router = APIRouter()
logger = logging.getLogger(__name__)
KEEPALIVE_INTERVAL = 25 # seconds
FIRST_FRAME_TIMEOUT = 10.0
class Refused(Exception):
def __init__(self, code: str, close: int):
super().__init__(code)
self.code, self.close = code, close
def _with_db(app, fn):
"""Run fn(db) with a DB session from the app's get_db (honours dependency overrides)."""
gen = app.dependency_overrides.get(get_db, get_db)()
db = next(gen)
try:
return fn(db)
finally:
gen.close()
def authenticate(db, token: str | None, device_token: str | None) -> dict:
"""-> kwargs for ws_bus.connect(). Raises Refused."""
from core.access.context import lookup_device
from routers.deps import decode_session
device = None
if device_token:
try:
device = lookup_device(db, device_token)
except XeniaError as e:
raise Refused(e.code, ws_bus.CLOSE_DEVICE)
if token:
try:
payload, info = decode_session(token, db)
except XeniaError as e:
raise Refused(e.code, ws_bus.CLOSE_SESSION)
except Exception:
raise Refused("auth.session_ended", ws_bus.CLOSE_SESSION)
if info.device_id is not None and (device is None or device.id != info.device_id):
raise Refused("device.required", ws_bus.CLOSE_DEVICE)
user_id = info.user_id if info.user_id is not None else 0 # 0 = the support account
if info.user_id is not None:
from models.user import User
if db.query(User.id).filter(User.id == info.user_id, User.is_active == True).first() is None: # noqa: E712
raise Refused("auth.session_ended", ws_bus.CLOSE_SESSION)
return {"user_id": user_id, "sid": payload.get("sid"),
"device_id": device.id if device else None, "app_key": device.app_key if device else None}
if device is None:
raise Refused("auth.session_ended", ws_bus.CLOSE_SESSION)
from routers.devices import effective_login_mode
signs_nobody_in = effective_login_mode(db, device) == "none"
return {"device_id": device.id, "app_key": device.app_key, "all_events": signs_nobody_in}
@router.websocket("/connect", dependencies=[Depends(public())])
async def ws_endpoint(websocket: WebSocket):
await websocket.accept()
# ── First frame: cursor + credentials ─────────────────────────────────────
cursor, token, device_token = 0, None, None
try:
msg = json.loads(await asyncio.wait_for(websocket.receive_text(), timeout=FIRST_FRAME_TIMEOUT))
if isinstance(msg, dict):
cursor = int(msg.get("cursor") or 0)
token = msg.get("token") or None
device_token = msg.get("device") or None
except WebSocketDisconnect:
return
except Exception:
pass # no (valid) first frame: no credentials → refused below
# ── Auth ──────────────────────────────────────────────────────────────────
try:
who = await asyncio.to_thread(_with_db, websocket.app, lambda db: authenticate(db, token, device_token))
except Refused as r:
try:
await websocket.send_text(json.dumps({"type": "refused", "data": {"code": r.code}}))
await websocket.close(code=r.close)
except Exception:
pass
return
conn = await ws_bus.connect(**who)
try:
# ── Replay missed events ──────────────────────────────────────────────
if cursor > 0:
for event in await asyncio.to_thread(ws_bus.get_events_since, cursor, conn):
await websocket.send_text(json.dumps(event))
# Signal end of replay / start of live stream
await websocket.send_text(json.dumps({"type": "ready"}))
# ── Live stream loop ──────────────────────────────────────────────────
while True:
if conn.closing is not None:
frame, code = conn.closing
await websocket.send_text(frame)
await websocket.close(code=code)
break
try:
frame = await asyncio.wait_for(conn.queue.get(), timeout=KEEPALIVE_INTERVAL)
except asyncio.TimeoutError:
frame = json.dumps({"type": "ping"})
if frame is None or conn.closing is not None:
continue # a wake-up: the loop head sends the closing frame
if websocket.client_state != WebSocketState.CONNECTED:
break
await websocket.send_text(frame)
except WebSocketDisconnect:
pass
except Exception as e:
logger.debug("ws_endpoint: connection closed (user %s, device %s): %s", conn.user_id, conn.device_id, e)
finally:
await ws_bus.disconnect(conn)