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
@@ -17,8 +17,9 @@ Agent notes:
- last_seen_at is written at most every LAST_SEEN_EVERY_S.
- A user session started on a device (client "terminal") is bound to it: routers.deps.
get_current_user refuses it without that device's header (device.required), so scope
can't be escaped by dropping the header. SSE/WebSocket (token in the query, browsers
can't set headers there) only stream events and are not bound; revisit in phase 3.
can't be escaped by dropping the header. The WebSocket (routers/ws.py, 3.1a) applies the
same rule with the device token in its first frame; the legacy SSE stream doesn't (it
goes in phase 4).
"""
from __future__ import annotations
+1
View File
@@ -81,6 +81,7 @@ CODES: dict[str, tuple[int, str]] = {
"validation.unknown_language": (422, "Unsupported language: {language}."),
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
"validation.setting_value": (422, "{key} can't be set to {value!r}."),
"validation.device_config": (422, "This device setting is not valid: {key}."),
# server
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
# domain
+5 -2
View File
@@ -26,7 +26,7 @@ from pydantic import BaseModel
from sqlalchemy.orm import Session
from core import i18n, timeutil
from core.modules import entitlements, state
from core.modules import device_config, entitlements, state
from core.modules.registry import all_permissions, registry
from database import get_db
from core.access.deps import require
@@ -70,7 +70,8 @@ def _module_out(m, enabled: dict, effective: frozenset) -> dict:
"value": ent.limit(m.key, lim.key)} for lim in m.limits],
"settings": [{"key": sd.key, "type": sd.type, "default": sd.default, "description": sd.description}
for sd in m.settings],
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope)}
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope),
"config": device_config.describe(m.device_app.config)}
if m.device_app else None),
"workers": len(m.workers),
}
@@ -141,5 +142,7 @@ class ModuleToggle(BaseModel):
def set_module(key: str, body: ModuleToggle, db: Session = Depends(get_db),
user=Depends(require("core.modules.manage"))):
effective = state.set_enabled(db, key, body.enabled, user_id=getattr(user, "id", None) or None)
from services import ws_bus
ws_bus.notify_device(every_device=True) # paired screens re-read their app_status (3.1a)
enabled = state.enabled_map(db)
return _module_out(registry()[key], enabled, effective)
+100
View File
@@ -0,0 +1,100 @@
"""Per-device settings of an app (plan step 3.1a): what the manager may store in
devices.config and what the device reads back.
- validate(fields, config, db) -> dict | None: the cleaned config to store. Unknown keys,
wrong types, values outside choices/min/max and refs to missing rows raise
validation.device_config {key}. None/{} -> None (all defaults).
- effective(fields, stored, db=None) -> dict: every field, its stored value when still
valid, else its default. What GET /api/devices/me returns, so a screen never handles
a missing or stale value (an old free-form config, a prep zone that was deleted).
- for_app(app_key) -> the app's ConfigFields (from its manifest's DeviceApp.config).
Agent notes:
- Fields are declared in the app's manifest (core/modules/model.py ConfigField). A new
field needs its label in packages/i18n/locales/{en,el}/modules.json
(`<app>.config.<key>.label`, plus `.choices.<value>` per choice); test_module_texts fails
otherwise. The manager renders the fields generically (DeviceConfigFields.jsx).
- `ref` sources: "prep_zones" (PrepZone ids), "devices:<app_key>" (live devices of that app).
"""
from __future__ import annotations
from core.errors import XeniaError
MAX_STR = 200
def for_app(app_key: str) -> tuple:
from core.access.context import device_app
da = device_app(app_key)
return tuple(da.config) if da else ()
def _bad(key: str):
return XeniaError("validation.device_config", key=key)
def _ref_exists(source: str, value: int, db) -> bool:
if source == "prep_zones":
from models.prep_zone import PrepZone
return db.get(PrepZone, value) is not None
if source.startswith("devices:"):
from models.device import Device
d = db.get(Device, value)
return d is not None and d.revoked_at is None and d.app_key == source.split(":", 1)[1]
return False
def _clean(f, value, db, *, strict: bool):
"""The value as stored, or raise (strict) / return the default (not strict)."""
def bad():
if strict:
raise _bad(f.key)
return f.default
if f.type == "bool":
return value if isinstance(value, bool) else bad()
if f.type == "int":
if isinstance(value, bool) or not isinstance(value, int):
return bad()
if (f.choices and value not in f.choices) or (f.min is not None and value < f.min) \
or (f.max is not None and value > f.max):
return bad()
return value
if f.type == "str":
return value.strip() if isinstance(value, str) and len(value) <= MAX_STR else bad()
if f.type == "enum":
return value if value in f.choices else bad()
if f.type == "ref":
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int):
return bad()
if db is not None and not _ref_exists(f.choices_from or "", value, db):
return bad()
return value
return bad()
def validate(fields, config, db) -> dict | None:
if config is None:
return None
if not isinstance(config, dict):
raise _bad("config")
by_key = {f.key: f for f in fields}
out = {}
for key, value in config.items():
f = by_key.get(key)
if f is None:
raise _bad(key)
out[key] = _clean(f, value, db, strict=True)
return out or None
def effective(fields, stored, db=None) -> dict:
stored = stored if isinstance(stored, dict) else {}
return {f.key: (_clean(f, stored[f.key], db, strict=False) if f.key in stored else f.default) for f in fields}
def describe(fields) -> list[dict]:
"""The fields for the manager (module catalogue)."""
return [{"key": f.key, "type": f.type, "default": f.default, "choices": list(f.choices),
"min": f.min, "max": f.max, "choices_from": f.choices_from} for f in fields]
+19
View File
@@ -54,11 +54,30 @@ class SettingDef:
choices: tuple[str, ...] = () # for type "enum"
ConfigType = Literal["bool", "int", "str", "enum", "ref"]
@dataclass(frozen=True)
class ConfigField:
"""One setting of a device running an app (plan step 3.1a). Stored in devices.config,
validated by core/modules/device_config.py, edited in the manager's pair/edit dialogs.
Texts: modules:<app>.config.<key>.label (+ .hint optional, + .choices.<value> for each
choice), checked by tests/test_module_texts.py."""
key: str
type: ConfigType
default: object = None
choices: tuple = () # enum, or int limited to these values
min: Optional[int] = None # int
max: Optional[int] = None # int
choices_from: Optional[str] = None # ref: "prep_zones" | "devices:<app_key>"; value = id or None
@dataclass(frozen=True)
class DeviceApp:
"""For kind="app" modules that run on a paired device (step 1.8, D-8)."""
login_modes: tuple[str, ...] = ("pin", "tap", "password")
scope: tuple[str, ...] = () # permission-key patterns the device token may use
config: tuple[ConfigField, ...] = () # per-device settings (3.1a)
@dataclass(frozen=True)
+3
View File
@@ -21,6 +21,7 @@ Agent notes:
device_id binds it to that device, and a new login on the device replaces the old one),
"support" (1.10).
- Never trust a JWT alone: always go through validate().
- Ending a session also closes its live sockets (services.ws_bus.end_session, plan 3.1a).
"""
from __future__ import annotations
@@ -100,6 +101,8 @@ def _end_row(row, reason: str) -> None:
row.end_reason = reason
with _lock:
_cache.pop(row.id, None)
from services import ws_bus
ws_bus.end_session(row.id, reason) # its open sockets get session.ended and close (3.1a)
logger.info("session.ended sid=%s user=%s client=%s reason=%s", row.id[:8], row.user_id, row.client, reason)