feat(backend): paired devices with device tokens, scope, limits and terminal login

Platform v2 step 1.8 (APPS_PLATFORM D-8, section 6.3).
- devices + device_pair_requests tables (Alembic 0007_devices); sessions.device_id
  becomes a FK. Device tokens are stored as sha256 only; the plain token is generated
  when the device picks it up, once.
- /api/devices: pair-request (public, rate-limited, LAN-only in the proxy) + polling
  with a per-request secret; manager approve/list/rename/config/login mode/link/
  reassign/revoke (key core.devices.manage); the device's own /me and /me/users.
- Approving or reassigning checks the app's licence and its `devices` limit
  (license.limit_reached); after a downgrade the newest devices beyond the limit are
  refused, the oldest keep working.
- X-Xenia-Device: core/access/context.py loads the device (device.not_paired /
  device.revoked), tags logs with device=, throttles last_seen_at. check() and
  module_required() apply the app's scope (device.out_of_scope); require_device(app).
- POST /api/auth/login {client: "terminal"} uses the device's login mode (device ->
  auth.default_login_mode -> app's first mode); tap/none only here. The session is
  bound to the device (device.required without its header) and replaces the
  device's previous user. Revoke/reassign end the device's sessions.
- Registry: a device app with user logins must declare '<app>.access'.
- Proxy: location /api/devices/pair-request LAN-only on the :443 servers (both copies).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 09:44:40 +02:00
co-authored by Claude Opus 5.5
parent 1d7a521e05
commit 91da3aeb27
25 changed files with 1208 additions and 48 deletions
+35 -9
View File
@@ -14,7 +14,9 @@ Login modes (settings, declared in modules/core/manifest.py)
- auth.waiter_require_username: the waiter must type their username, not just pick a name
Agent notes:
- Clients: "manager", "waiter" now; "terminal" (devices) in 1.8; "support" in 1.10.
- Clients: "manager", "waiter", "terminal" (a user on a paired device, step 1.8; the row's
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().
"""
from __future__ import annotations
@@ -24,6 +26,7 @@ import threading
import time
import uuid
from datetime import timedelta
from typing import NamedTuple, Optional
from core.errors import XeniaError
from core.timeutil import utcnow
@@ -35,7 +38,15 @@ CACHE_TTL_S = 10
LAST_SEEN_EVERY_S = 60
_lock = threading.Lock()
_cache: dict[str, tuple[float, int | None]] = {} # sid -> (checked_at monotonic, user_id) for ACTIVE sessions
class Active(NamedTuple):
"""What validate() knows about an active session."""
user_id: Optional[int] # None = the support account
device_id: Optional[int] # set for terminal sessions: the device they belong to
_cache: dict[str, tuple[float, Active]] = {} # sid -> (checked_at monotonic, info) for ACTIVE sessions
def _setting(db, key: str, default: str) -> str:
@@ -50,8 +61,10 @@ def single_session_rule(db, client: str) -> str:
# ── lifecycle ────────────────────────────────────────────────────────────────
def start(db, user, client: str, request=None, *, legacy_manager: bool = False):
"""Create a session for user (None user_id for the support ghost). Commits."""
def start(db, user, client: str, request=None, *, legacy_manager: bool = False, device=None):
"""Create a session for user (None user_id for the support ghost). Commits.
`device`: the paired device of a terminal login; its previous sessions are replaced
(a shared screen shows one user at a time)."""
from models.session import LoginSession
if client not in CLIENTS:
raise ValueError(f"unknown client {client!r}")
@@ -68,8 +81,12 @@ def start(db, user, client: str, request=None, *, legacy_manager: bool = False):
raise XeniaError("auth.session_exists", client=client)
for s in active:
_end_row(s, "replaced")
if device is not None:
for s in db.query(LoginSession).filter(LoginSession.device_id == device.id, LoginSession.ended_at.is_(None)):
_end_row(s, "replaced")
now = utcnow()
row = LoginSession(id=uuid.uuid4().hex, user_id=user_id, client=client, created_at=now, last_seen_at=now,
device_id=(device.id if device is not None else None),
ip=(request.client.host if request is not None and request.client else None),
user_agent=(request.headers.get("user-agent", "")[:300] if request is not None else None))
db.add(row)
@@ -105,8 +122,17 @@ def end_for_user(db, user_id: int, reason: str) -> int:
return len(rows)
def validate(sid: str | None, db=None) -> int | None:
"""User id of an active session (None for support). Raises auth.session_ended."""
def end_for_device(db, device_id: int, reason: str) -> int:
from models.session import LoginSession
rows = db.query(LoginSession).filter(LoginSession.device_id == device_id, LoginSession.ended_at.is_(None)).all()
for r in rows:
_end_row(r, reason)
db.commit()
return len(rows)
def validate(sid: str | None, db=None) -> Active:
"""(user_id, device_id) of an active session. Raises auth.session_ended."""
if not sid:
raise XeniaError("auth.session_ended")
now_m = time.monotonic()
@@ -125,7 +151,7 @@ def validate(sid: str | None, db=None) -> int | None:
with _lock:
_cache.pop(sid, None)
raise XeniaError("auth.session_ended")
user_id = row.user_id
info = Active(row.user_id, row.device_id)
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
finally:
if own:
@@ -133,8 +159,8 @@ def validate(sid: str | None, db=None) -> int | None:
if stale:
_touch(sid)
with _lock:
_cache[sid] = (now_m, user_id)
return user_id
_cache[sid] = (now_m, info)
return info
def _touch(sid: str) -> None: