Files
xenia-pos-local/local_backend/routers/devices.py
T
bonaminandClaude Opus 5.5 bda5cde92b 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>
2026-11-14 16:31:59 +02:00

372 lines
16 KiB
Python

"""Devices: pairing, management, the device's own view (APPS_PLATFORM D-8, §6.3, step 1.8).
Pairing flow
1. The device: POST /pair-request -> {code, secret, expires_at}. It shows the 6-character
code and polls GET /pair-request/{code} with header X-Xenia-Pair-Secret: <secret>.
2. A manager: POST /api/devices {code, app_key, name, config?, login_mode?, linked_device_id?}.
The app must be licensed and enabled, and its `devices` limit not reached
(license.limit_reached, D-6).
3. The device's next poll gets {status: "paired", device_token, device} exactly once; the
token is generated right then and only its hash is stored. From then on the device sends
X-Xenia-Device: <token> (core/access/context.py).
The pairing endpoints are public but rate-limited here and LAN-only in the proxy
(nginx-proxy/nginx.conf + install.sh: location /api/devices/pair-request).
Agent notes:
- Revoke ends the device's sessions; its next call gets device.revoked and it goes back
to pairing (a new Device row). Reassign changes the app on the same row (limit checked,
sessions ended). Rows are never deleted.
- Login on a device: POST /api/auth/login {client: "terminal", ...} with the device header
(routers/auth.py). The login mode is effective_login_mode(); tap/none exist only here.
- `config` is validated against the app's ConfigFields (core/modules/device_config.py,
3.1a); both views return the effective config (every field, defaults filled).
- Live (3.1a): an edit sends `device.updated` to the device's open sockets; reassign sends
`device.updated` and closes them; revoke sends `device.revoked` and closes them
(services/ws_bus.py). The screen re-reads GET /me or goes back to pairing.
"""
from __future__ import annotations
import secrets
import threading
import time
import uuid as uuidlib
from collections import deque
from datetime import timedelta
from typing import Optional
from fastapi import APIRouter, Depends, Header, Request
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from core import sessions
from core.access.context import hash_token
from core.modules import device_config
from core.access.deps import public, require, require_device
from core.errors import XeniaError
from core.modules.registry import registry
from core.timeutil import iso_z, utcnow
from database import get_db
from models.device import Device, DevicePairRequest
from services import ws_bus
router = APIRouter()
PAIR_TTL = timedelta(minutes=10)
CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # no 0/O, 1/I: typed by a person
CODE_LEN = 6
POLL_AFTER_S = 3
RATE_WINDOW_S = 600
RATE_PER_IP = 10 # pairing requests per address per window
MAX_PENDING = 30 # open requests at once, venue-wide
_rate_lock = threading.Lock()
_rate: dict[str, deque] = {}
MANAGE = "core.devices.manage"
def reset_rate_limit() -> None:
with _rate_lock:
_rate.clear()
def _client_ip(request: Request) -> str:
# Behind the proxy every request comes from nginx; X-Real-IP is only used for the
# rate limit (not for security decisions, it can be forged).
return request.headers.get("x-real-ip") or (request.client.host if request.client else "?")
def _rate_ok(ip: str) -> bool:
now = time.monotonic()
with _rate_lock:
q = _rate.setdefault(ip, deque())
while q and now - q[0] > RATE_WINDOW_S:
q.popleft()
if len(q) >= RATE_PER_IP:
return False
q.append(now)
return True
# ── helpers ──────────────────────────────────────────────────────────────────
def _app(app_key: str):
m = registry().get(app_key)
if m is None or m.device_app is None:
raise XeniaError("device.not_an_app", app=app_key)
return m
def _require_effective(app_key: str, db) -> None:
from core.modules.state import blocked_error, is_effective
if not is_effective(app_key, db):
raise blocked_error(app_key, db)
def _check_limit(db, app_key: str, exclude_id: int | None = None) -> None:
from core.modules import entitlements
cap = entitlements.limit(app_key, "devices")
if cap is None:
return
q = db.query(Device).filter(Device.app_key == app_key, Device.revoked_at.is_(None))
if exclude_id is not None:
q = q.filter(Device.id != exclude_id)
if q.count() >= cap:
notify_limit(app_key, "devices", cap, db)
raise XeniaError("license.limit_reached", module=app_key, limit="devices", max=cap)
def notify_limit(module: str, limit: str, cap: int, db) -> None:
"""Tell the owners (once a day per module/limit, repeats are counted) that a limit stopped something."""
from core.notifications import notify
notify("license.limit_reached", "warning", "perm:core.modules.manage",
{"module": module, "limit": limit, "max": cap},
dedupe_key=f"license.limit_reached:{module}:{limit}", ttl=timedelta(days=1), db=db)
def _check_mode(app_key: str, mode: str | None) -> str | None:
if not mode:
return None # site default
if mode not in _app(app_key).device_app.login_modes:
raise XeniaError("device.login_mode_invalid", app=app_key, mode=mode)
return mode
def _check_link(db, self_id: int | None, target_id: int | None) -> int | None:
if not target_id:
return None
target = db.get(Device, target_id)
if target is None or target.revoked_at is not None or target.id == self_id:
raise XeniaError("device.link_invalid", device_id=target_id)
return target.id
def effective_login_mode(db, device) -> str:
"""The device's own mode, else the site default auth.default_login_mode; if the app
can't use that one, the app's first mode (signage etc.: 'none')."""
modes = _app(device.app_key).device_app.login_modes
mode = device.login_mode or sessions._setting(db, "auth.default_login_mode", "pin")
return mode if mode in modes else modes[0]
def _config(app_key: str, config, db) -> dict | None:
return device_config.validate(device_config.for_app(app_key), config, db)
def _effective_config(d: Device, db) -> dict:
return device_config.effective(device_config.for_app(d.app_key), d.config, db)
def _get(db, device_id: int) -> Device:
d = db.get(Device, device_id)
if d is None:
raise XeniaError("device.not_found", device_id=device_id)
return d
def _out(d: Device, db) -> dict:
"""Manager view of a device."""
return {
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key,
"config": _effective_config(d, db) if d.app_key in registry() else {},
"login_mode": d.login_mode,
"effective_login_mode": effective_login_mode(db, d) if d.app_key in registry() else None,
"linked_device_id": d.linked_device_id, "user_agent": d.user_agent,
"paired_at": iso_z(d.paired_at), "paired_by": d.paired_by,
"claimed": d.token_hash is not None, "claimed_at": iso_z(d.claimed_at),
"last_seen_at": iso_z(d.last_seen_at), "revoked_at": iso_z(d.revoked_at),
}
def _self_out(d: Device, db) -> dict:
"""What the device itself is told (GET /me, and the pairing answer)."""
from core.modules.state import blocked_error, is_effective
linked = db.get(Device, d.linked_device_id) if d.linked_device_id else None
status = "ok" if is_effective(d.app_key, db) else blocked_error(d.app_key, db).code
return {
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": _effective_config(d, db),
"login_mode": effective_login_mode(db, d),
"linked_device": ({"id": linked.id, "uuid": linked.uuid, "name": linked.name, "app_key": linked.app_key}
if linked is not None and linked.revoked_at is None else None),
"app_status": status, # "ok" | "module.disabled" | "module.not_licensed": show "app disabled"
}
# ── pairing (device side, public) ────────────────────────────────────────────
@router.post("/pair-request", status_code=201, dependencies=[Depends(public())])
def create_pair_request(request: Request, db: Session = Depends(get_db)):
now = utcnow()
db.query(DevicePairRequest).filter(DevicePairRequest.expires_at < now).delete()
db.commit()
if not _rate_ok(_client_ip(request)) or db.query(DevicePairRequest).count() >= MAX_PENDING:
raise XeniaError("device.pair_rate_limited")
while True:
code = "".join(secrets.choice(CODE_ALPHABET) for _ in range(CODE_LEN))
if db.get(DevicePairRequest, code) is None:
break
secret = secrets.token_urlsafe(24)
row = DevicePairRequest(code=code, secret_hash=hash_token(secret), created_at=now, expires_at=now + PAIR_TTL,
ip=_client_ip(request), user_agent=request.headers.get("user-agent", "")[:300])
db.add(row)
db.commit()
return {"code": code, "secret": secret, "expires_at": iso_z(row.expires_at), "poll_after_s": POLL_AFTER_S}
def _norm_code(code: str) -> str:
return "".join(ch for ch in code.upper() if ch.isalnum())
@router.get("/pair-request/{code}", dependencies=[Depends(public())])
def poll_pair_request(code: str, db: Session = Depends(get_db),
x_xenia_pair_secret: Optional[str] = Header(None)):
"""pending -> {status: "pending"}; approved -> {status: "paired", device_token, device} once."""
row = db.get(DevicePairRequest, _norm_code(code))
if (row is None or row.expires_at < utcnow() or not x_xenia_pair_secret
or not secrets.compare_digest(row.secret_hash, hash_token(x_xenia_pair_secret))):
raise XeniaError("device.pair_code_invalid")
if row.device_id is None:
return {"status": "pending", "expires_at": iso_z(row.expires_at)}
d = db.get(Device, row.device_id)
token = secrets.token_urlsafe(32)
d.token_hash = hash_token(token)
d.claimed_at = utcnow()
db.delete(row)
db.commit()
return {"status": "paired", "device_token": token, "device": _self_out(d, db)}
# ── management (manager) ─────────────────────────────────────────────────────
class PairApprove(BaseModel):
code: str
app_key: str
name: str = Field(min_length=1, max_length=60)
config: Optional[dict] = None
login_mode: Optional[str] = None # None/"" = site default
linked_device_id: Optional[int] = None
class DevicePatch(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=60)
config: Optional[dict] = None
login_mode: Optional[str] = None # "" or null = back to the site default
linked_device_id: Optional[int] = None # null/0 = unlink
class DeviceReassign(BaseModel):
app_key: str
config: Optional[dict] = None
@router.get("")
def list_devices(include_revoked: bool = False, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
q = db.query(Device)
if not include_revoked:
q = q.filter(Device.revoked_at.is_(None))
return [_out(d, db) for d in q.order_by(Device.id).all()]
@router.post("", status_code=201)
def approve_device(body: PairApprove, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
"""Enter the code shown on the device and choose what it runs."""
row = db.get(DevicePairRequest, _norm_code(body.code))
now = utcnow()
if row is None or row.expires_at < now or row.device_id is not None:
raise XeniaError("device.pair_code_invalid")
_app(body.app_key)
_require_effective(body.app_key, db)
_check_limit(db, body.app_key)
d = Device(uuid=uuidlib.uuid4().hex, name=body.name.strip(), app_key=body.app_key,
config=_config(body.app_key, body.config, db),
login_mode=_check_mode(body.app_key, body.login_mode),
linked_device_id=_check_link(db, None, body.linked_device_id),
user_agent=row.user_agent, paired_at=now, paired_by=getattr(user, "id", None) or None)
db.add(d)
db.flush()
row.device_id = d.id
row.expires_at = now + PAIR_TTL # the device has a fresh 10 minutes to pick up its token
db.commit()
return _out(d, db)
@router.get("/me")
def device_me(db: Session = Depends(get_db), device=Depends(require_device())):
"""The calling device: its app, config, login mode, linked device and whether its app
is currently usable (app_status)."""
return _self_out(device, db)
@router.get("/me/users")
def device_users(db: Session = Depends(get_db), device=Depends(require_device())):
"""Who can log in on this device (holders of '<app>.access'), for the name picker."""
from core.access.queries import users_with_key
from models.user import User
if effective_login_mode(db, device) == "none":
return []
users = users_with_key(db, f"{device.app_key}.access").order_by(User.full_name).all()
return [{"id": u.id, "full_name": u.full_name, "nickname": u.nickname, "avatar_url": u.avatar_url}
for u in users if u.role != "superadmin"]
@router.get("/{device_id}")
def get_device(device_id: int, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
return _out(_get(db, device_id), db)
@router.patch("/{device_id}")
def update_device(device_id: int, body: DevicePatch, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
"""Rename, change config or login mode, link/unlink (fields not sent are unchanged)."""
d = _get(db, device_id)
if d.revoked_at is not None:
raise XeniaError("device.revoked")
sent = body.model_fields_set
if "name" in sent and body.name:
d.name = body.name.strip()
if "config" in sent:
d.config = _config(d.app_key, body.config, db)
if "login_mode" in sent:
d.login_mode = _check_mode(d.app_key, body.login_mode)
if "linked_device_id" in sent:
d.linked_device_id = _check_link(db, d.id, body.linked_device_id)
db.commit()
ws_bus.notify_device([d.id])
return _out(d, db)
@router.post("/{device_id}/reassign")
def reassign_device(device_id: int, body: DeviceReassign, db: Session = Depends(get_db),
user=Depends(require(MANAGE))):
"""Run a different app on the same device. Its sessions end; the token stays valid."""
d = _get(db, device_id)
if d.revoked_at is not None:
raise XeniaError("device.revoked")
_app(body.app_key)
_require_effective(body.app_key, db)
if body.app_key != d.app_key:
_check_limit(db, body.app_key, exclude_id=d.id)
d.config = _config(body.app_key, body.config, db)
d.app_key = body.app_key
if d.login_mode and d.login_mode not in _app(body.app_key).device_app.login_modes:
d.login_mode = None
db.commit()
ws_bus.end_device(d.id, "device.updated", {"app_key": d.app_key}) # before the session's own close
sessions.end_for_device(db, d.id, "device_reassigned")
return _out(d, db)
@router.post("/{device_id}/revoke")
def revoke_device(device_id: int, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
"""Remove the device: its next call gets device.revoked and it must pair again."""
d = _get(db, device_id)
if d.revoked_at is None:
d.revoked_at = utcnow()
d.revoked_by = getattr(user, "id", None) or None
db.query(Device).filter(Device.linked_device_id == d.id).update({Device.linked_device_id: None})
db.query(DevicePairRequest).filter(DevicePairRequest.device_id == d.id).delete()
db.commit()
ws_bus.end_device(d.id, "device.revoked")
sessions.end_for_device(db, d.id, "device_revoked")
return _out(d, db)