feat(backend): live connection and per-device settings for paired screens (platform-v2 3.1a)

- WebSocket: credentials may come in the first frame ({cursor, token?, device?}).
  A device token alone connects a paired screen (login-none apps get every event, a
  sign-in app only events addressed to it); a terminal session's JWT needs its own
  device, as over HTTP. Refusals send {type: refused, data: {code}} + close 4001/4003.
- ws_bus: registry of open sockets by user, session and device. Ending a session
  closes its sockets (session.ended); revoke/reassign close the device's sockets
  (device.revoked / device.updated); edits and module on/off send device.updated.
  Events can target devices (device_ids=..., sync_events.target_device_ids, rev 0014).
  Pushes go through each socket's own loop (call_soon_threadsafe).
- Device config: DeviceApp.config = typed ConfigFields, validated on pair/edit/
  reassign (validation.device_config), effective values (defaults filled) in both
  device views and the module catalogue. First field: auto_sign_out_minutes (KDS, POS).
- Manager: DeviceConfigFields renders an app's fields in the pair and edit dialogs.
- @xenia/api createLiveClient: `credentials` and `onRefused` options.
- Tests: tests/test_live.py (11), module texts for config fields, live client,
  devices logic, manager.mjs device setting + live socket checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 16:31:59 +02:00
co-authored by Claude Opus 5.5
parent 034426f870
commit bda5cde92b
31 changed files with 974 additions and 145 deletions
+121 -45
View File
@@ -1,19 +1,36 @@
"""
WebSocket endpoint — one persistent connection per connected client (waiter PWA, KDS).
Authentication: JWT token passed as query param ?token=<jwt>
(Same pattern as SSE — browser WebSocket API also cannot set custom headers.)
WebSocket endpoint — one persistent connection per client (waiter app, manager, terminal).
Protocol:
1. Client connects: ws://host/api/ws?token=<jwt>
2. Client immediately sends: { "cursor": <last_seq_id> }
(0 = first connect / no history; any positive int = resume from that point)
3. Server replays all missed events (seq > cursor) as individual frames
4. Server sends { "type": "ready" } to signal end of replay / start of live stream
5. Live events arrive as: { "seq": 123, "type": "...", "data": { ... } }
6. Every 25s server sends: { "type": "ping" }
7. Client may respond: { "type": "pong" } (ignored if not sent)
8. On disconnect/error the client reconnects and repeats from step 2
1. Client connects: ws://host/api/ws/connect (terminal: no query)
or: ws://host/api/ws/connect?token=<jwt> (waiter, manager)
2. Client immediately sends its first frame:
{ "cursor": <last_seq_id>, "token"?: <jwt>, "device"?: <device token> }
(cursor 0 = first connect / no history). Credentials in the frame stay out of URLs
and proxy logs; the terminal always sends them there.
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
@@ -24,44 +41,99 @@ import logging
from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect, Query
from starlette.websockets import WebSocketState
from routers.deps import decode_token
from services.ws_bus import connect, disconnect, get_events_since
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, token: str = Query(...)):
# ── Auth ──────────────────────────────────────────────────────────────────
try:
payload = decode_token(token)
user_id: int = int(payload["sub"])
except Exception:
await websocket.close(code=4001)
return
async def ws_endpoint(websocket: WebSocket, token: str | None = Query(None)):
await websocket.accept()
# ── Wait for cursor frame ─────────────────────────────────────────────────
cursor = 0
# ── First frame: cursor (+ credentials) ───────────────────────────────────
cursor, device_token = 0, None
try:
raw = await asyncio.wait_for(websocket.receive_text(), timeout=10.0)
msg = json.loads(raw)
cursor = int(msg.get("cursor", 0))
except (asyncio.TimeoutError, Exception):
pass # no cursor sent — treat as fresh connect (cursor=0)
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 token
device_token = msg.get("device") or None
except WebSocketDisconnect:
return
except Exception:
pass # no (valid) first frame: fresh connect, credentials from the query only
# ── Register this connection ──────────────────────────────────────────────
q = await connect(user_id)
# ── 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:
missed = get_events_since(cursor, user_id)
for event in missed:
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
@@ -69,20 +141,24 @@ async def ws_endpoint(websocket: WebSocket, token: str = Query(...)):
# ── 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(q.get(), timeout=KEEPALIVE_INTERVAL)
if websocket.client_state == WebSocketState.CONNECTED:
await websocket.send_text(frame)
frame = await asyncio.wait_for(conn.queue.get(), timeout=KEEPALIVE_INTERVAL)
except asyncio.TimeoutError:
# Send keepalive ping
if websocket.client_state == WebSocketState.CONNECTED:
await websocket.send_text(json.dumps({"type": "ping"}))
else:
break
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 for user %s: %s", user_id, e)
logger.debug("ws_endpoint: connection closed (user %s, device %s): %s", conn.user_id, conn.device_id, e)
finally:
await disconnect(user_id, q)
await ws_bus.disconnect(conn)