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
+31 -13
View File
@@ -1,7 +1,7 @@
from core.timeutil import utcnow
import jwt
from datetime import datetime, timedelta, timezone
from fastapi import Depends, HTTPException, status
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
@@ -56,9 +56,9 @@ def make_token(user: User, sid: str) -> str:
return jwt.encode(payload, settings.SECRET_KEY, algorithm="HS256")
def decode_token(token: str, db: Session | None = None) -> dict:
"""Verify the JWT AND its session (auth.session_ended once logged out/ended/replaced).
Used by get_current_user and by the SSE/WebSocket endpoints (token in the query)."""
def decode_session(token: str, db: Session | None = None):
"""Verify the JWT AND its session -> (payload, sessions.Active).
auth.session_ended once logged out/ended/replaced."""
from core import sessions
from core.errors import XeniaError
try:
@@ -67,23 +67,41 @@ def decode_token(token: str, db: Session | None = None) -> dict:
raise XeniaError("auth.session_ended")
except jwt.InvalidTokenError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
sessions.validate(payload.get("sid"), db)
return payload
return payload, sessions.validate(payload.get("sid"), db)
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(bearer),
db: Session = Depends(get_db),
) -> User:
payload = decode_token(credentials.credentials, db)
def decode_token(token: str, db: Session | None = None) -> dict:
"""decode_session without the session info. Used by the SSE/WebSocket endpoints
(token in the query) and token refresh."""
return decode_session(token, db)[0]
def user_from_token(token: str, request: Request, db: Session):
"""(user, sid) for a bearer token. A session started on a paired device (terminal) is
only accepted together with that device's X-Xenia-Device header (D-8)."""
from core.access.context import current_device
from core.errors import XeniaError
payload, info = decode_session(token, db)
if info.device_id is not None:
dev = current_device(request, db)
if dev is None or dev.id != info.device_id:
raise XeniaError("device.required")
if int(payload["sub"]) == MASTER_USER_ID and payload.get("role") == "superadmin":
set_log_context(user="support")
return _make_ghost_superadmin()
return _make_ghost_superadmin(), payload.get("sid")
user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first()
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
set_log_context(user=user.id)
return user
return user, payload.get("sid")
def get_current_user(
request: Request,
credentials: HTTPAuthorizationCredentials = Depends(bearer),
db: Session = Depends(get_db),
) -> User:
return user_from_token(credentials.credentials, request, db)[0]
# Logged-in, no specific key. An explicit access marker for the route guard (D-17):