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
+3 -2
View File
@@ -68,6 +68,7 @@ A v1 database (tables, no `alembic_version`) is refused at startup; v1 data come
**CS-2. New real-time events need both ends.**
If the backend emits a new event type, handle it in `waiter_pwa/src/context/SSEContext.jsx` (and in the manager, if relevant), or state explicitly that it's ignored.
Events carry IDs; clients re-fetch the full object (`/api/orders/{id}`) instead of trusting partial payloads.
Control frames from `routers/ws.py` (3.1a) are not stored and have no seq: `device.updated` (a paired screen re-reads `GET /api/devices/me`), and just before the server closes a socket `session.ended` (4001) or `device.revoked` / `device.updated` (4003). The waiter and the manager ignore them (their next request gets the 401 that signs them out); the terminal acts on them. Events for one device: `ws_bus.broadcast_sync(type, data, device_ids=[…])`.
**CS-3. The waiter app must survive bad networks.**
Waiters walk in and out of WiFi range and phones sleep. Any new waiter flow must:
@@ -162,7 +163,7 @@ Routers are mounted from the module manifests (`local_backend/modules/<key>/mani
**CS-14. Every route declares who may call it** (branch `platform-v2`, D-7, D-17).
Use `core.access.deps.require("<module>.<area>.<action>")` (or `require_any`, `public()`, `require_device(app)`), or `Depends(get_current_user)` for "any signed-in user". The guard `tests/guards/test_route_access.py` fails a route with no marker or with an unknown key. New keys are declared as `Perm(...)` in the owning manifest, with their default roles. Inside code use `core.access.check.holds(user, key)` / `can(user, key)`, never role names or `perm_*` attributes (`tests/guards/test_no_perm_reads.py`). The v1 booleans are gone (step 2.99): `UserOut` carries only `permissions` (keys).
Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>`; a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.access`. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header.
Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>` (on the WebSocket: `device` in the first frame); a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.access`. Per-device settings are `ConfigField`s in `DeviceApp.config` (validated by `core/modules/device_config.py`, rendered by the manager's `DeviceConfigFields`), each with texts `modules:<app>.config.<key>.label` (+ `.choices.<value>`), never free JSON. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header.
Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overridable=True)` and a user without it gets `access.override_possible`; the client gets a manager's one-time token from `POST /api/access/override {key, username, pin}` and retries with `X-Xenia-Override`. `require()` routes handle it in `check()`; an endpoint with its own rule calls `require_override(request, db, key, target="order:12")` where the rule says no, **after** its other checks (a used token is spent).
**CS-16. Shared UI lives in `packages/ui` and never restyles an app** (branch `platform-v2`, D-15, §9).
@@ -172,7 +173,7 @@ Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`),
New UI text goes into `packages/i18n/locales/en/<ns>.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. Module names, their limits and **every permission key** have texts in `modules.json` (`modules:<module>.name`, `.limits.<key>`, `.permissions.<rest of the key, nested by its dots>`); `tests/test_module_texts.py` fails for a new module or key without them in both languages. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` at the app root.
**CS-18. Frontends talk to the backend through `@xenia/api` and read access from bootstrap** (branch `platform-v2`, D-7, D-10, §9).
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand). In the manager there is one connection, `live/LiveProvider.jsx` (opened with the signed-in shell); components listen with `useLiveEvent(type, handler)` (`'ready'` fires after each reconnect: refetch then).
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand). A paired device passes `credentials: () => ({ device, token })` (sent in the first frame, never in the URL) and `onRefused(code)`. In the manager there is one connection, `live/LiveProvider.jsx` (opened with the signed-in shell); components listen with `useLiveEvent(type, handler)` (`'ready'` fires after each reconnect: refetch then).
**CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16).
There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret <SITE_ID>`, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`).