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
+3 -2
View File
@@ -19,7 +19,7 @@ from core.access.deps import public
from typing import Optional
from fastapi import APIRouter, Depends
from fastapi import APIRouter, Depends, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
from sqlalchemy.orm import Session
@@ -76,13 +76,14 @@ def _module_out(m, enabled: dict, effective: frozenset) -> dict:
@router.get("/bootstrap", dependencies=[Depends(public())])
def bootstrap(
request: Request,
db: Session = Depends(get_db),
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer),
):
user = None
if credentials:
try:
user = get_current_user(credentials, db)
user = get_current_user(request, credentials, db)
except Exception:
user = None # an expired/invalid token just means "not logged in" here
effective = state.effective_set(db)
+8
View File
@@ -22,6 +22,7 @@ from core.modules.model import Module
MODULES_DIR = Path(__file__).resolve().parents[2] / "modules"
_KEY = re.compile(r"^[a-z][a-z0-9_]*$")
_KINDS = {"core", "feature", "app", "integration"}
_LOGIN_MODES = {"pin", "password", "tap", "none"}
class ManifestError(ValueError):
@@ -61,6 +62,13 @@ def validate(modules: list[Module], check_imports: bool = True) -> dict[str, Mod
raise ManifestError(f"{where}: kind {m.kind!r} not in {sorted(_KINDS)}")
if m.device_app and m.kind != "app":
raise ManifestError(f"{where}: device_app is only for kind='app'")
if m.device_app:
bad_modes = set(m.device_app.login_modes) - _LOGIN_MODES
if not m.device_app.login_modes or bad_modes:
raise ManifestError(f"{where}: device_app.login_modes must be a non-empty subset of {sorted(_LOGIN_MODES)}")
if set(m.device_app.login_modes) - {"none"} and f"{m.key}.access" not in {p.key for p in m.permissions}:
raise ManifestError(f"{where}: a device app with user logins must declare the permission "
f"'{m.key}.access' (who may log in on its devices)")
for p in m.permissions:
if not p.key.startswith(m.key + "."):
raise ManifestError(f"{where}: permission {p.key!r} must start with {m.key + '.'!r}")
+5 -2
View File
@@ -22,7 +22,7 @@ import logging
import threading
from typing import Callable
from fastapi import Depends
from fastapi import Depends, Request
from sqlalchemy.orm import Session
from core.errors import XeniaError
@@ -157,9 +157,12 @@ def module_required(key: str):
if key not in registry():
raise ValueError(f"module_required: unknown module {key!r}")
def _check(db: Session = Depends(get_db)) -> None:
def _check(request: Request, db: Session = Depends(get_db)) -> None:
if not is_effective(key, db):
raise blocked_error(key, db)
# A paired device may only reach its own app's routes and its scope's (D-8)
from core.access.context import check_device_scope, current_device
check_device_scope(current_device(request, db), key)
_check.__name__ = f"module_required_{key}"
return _check