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
+128
View File
@@ -0,0 +1,128 @@
"""Who is calling: the request's device and user (APPS_PLATFORM §3.1, D-8, step 1.8).
- current_device(request, db): the paired device named by header `X-Xenia-Device`, or None
when the header is absent. Unknown token -> device.not_paired; revoked -> device.revoked;
beyond its app's `devices` limit -> license.limit_reached. Cached on request.state, so
the several dependencies that need it look it up once per request.
- get_context: FastAPI dependency -> AccessContext(user | None, session sid | None, device | None).
For endpoints that accept a device alone or a device + user.
- Device scope (D-8): a device may only use permission keys of its own app plus the
patterns in its manifest's DeviceApp.scope (in_scope), and only routes of those modules
(module_in_scope, applied by core.modules.state.module_required to every non-core router).
Core routes stay reachable (login, /me, bootstrap, live events); keyed core routes are
still checked key by key.
Agent notes:
- The token is a long random secret; only its sha256 is stored (models/device.py).
- 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.
"""
from __future__ import annotations
import hashlib
from datetime import timedelta
from fnmatch import fnmatchcase
from typing import Optional
from fastapi import Depends, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session
from core.access.check import AccessContext
from core.errors import XeniaError
from core.timeutil import utcnow
from database import get_db
DEVICE_HEADER = "X-Xenia-Device"
LAST_SEEN_EVERY_S = 60
_NO_DEVICE = object()
_optional_bearer = HTTPBearer(auto_error=False)
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
def device_app(app_key: str):
"""The DeviceApp of an app module, or None."""
from core.modules.registry import registry
m = registry().get(app_key)
return m.device_app if m is not None else None
def scope_patterns(app_key: str) -> tuple[str, ...]:
da = device_app(app_key)
return (f"{app_key}.*",) + (tuple(da.scope) if da else ())
def in_scope(app_key: str, key: str) -> bool:
"""May a device running `app_key` use permission `key`?"""
return any(fnmatchcase(key, p) for p in scope_patterns(app_key))
def module_in_scope(app_key: str, module: str) -> bool:
"""May a device running `app_key` call routes of `module` at all?"""
return module == app_key or any(p.split(".", 1)[0] == module for p in scope_patterns(app_key))
def over_limit(db, device) -> Optional[int]:
"""The app's device limit if this device is beyond it (oldest devices keep working
after a downgrade, D-6), else None."""
from core.modules import entitlements
from models.device import Device
cap = entitlements.limit(device.app_key, "devices")
if cap is None:
return None
older = db.query(Device).filter(Device.app_key == device.app_key, Device.revoked_at.is_(None),
Device.id < device.id).count()
return cap if older >= cap else None
def lookup_device(db, token: str):
"""The Device for a raw token, applying revocation and the limit. Raises XeniaError."""
from core.logging import set_log_context
from models.device import Device
dev = db.query(Device).filter(Device.token_hash == hash_token(token)).first()
if dev is None:
raise XeniaError("device.not_paired")
if dev.revoked_at is not None:
raise XeniaError("device.revoked")
cap = over_limit(db, dev)
if cap is not None:
raise XeniaError("license.limit_reached", module=dev.app_key, limit="devices", max=cap)
set_log_context(device=dev.id)
now = utcnow()
if dev.last_seen_at is None or now - dev.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S):
dev.last_seen_at = now
db.commit() # runs before the endpoint body, so nothing else is pending yet
return dev
def current_device(request: Request, db) -> Optional[object]:
cached = getattr(request.state, "xenia_device", _NO_DEVICE)
if cached is not _NO_DEVICE:
return cached
token = request.headers.get(DEVICE_HEADER)
dev = lookup_device(db, token) if token else None
request.state.xenia_device = dev
return dev
def check_device_scope(device, module: str) -> None:
if device is not None and not module_in_scope(device.app_key, module):
raise XeniaError("device.out_of_scope", app=device.app_key, key=module)
def get_context(request: Request, db: Session = Depends(get_db),
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer)) -> AccessContext:
"""Device (if any) + user (if a bearer token is sent). An invalid token is an error here:
endpoints that want "anonymous unless valid" (bootstrap) handle that themselves."""
from routers.deps import user_from_token
device = current_device(request, db)
user = sid = None
if credentials:
user, sid = user_from_token(credentials.credentials, request, db)
return AccessContext(user=user, session=sid, device=device)