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
+37 -2
View File
@@ -49,8 +49,10 @@ def do_login(db: Session, request: Request, *, client: str, username: str | None
pin: str | None, password: str | None, legacy: bool = False) -> TokenResponse:
"""The one login path. Applies the client's login mode, its access key and the
single-session rule, then creates a session (core/sessions.py)."""
if client not in ("manager", "waiter"):
if client not in ("manager", "waiter", "terminal"):
raise XeniaError("validation.invalid")
if client == "terminal":
return _terminal_login(db, request, username=username, user_id=user_id, pin=pin, password=password)
# Support access (synthetic superadmin). >>> replaced by challenge codes in step 1.10
if (client == "manager" and settings.MASTER_USERNAME and settings.MASTER_PASSWORD
@@ -94,9 +96,42 @@ def do_login(db: Session, request: Request, *, client: str, username: str | None
return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user))
def _terminal_login(db: Session, request: Request, *, username, user_id, pin, password) -> TokenResponse:
"""A user on a paired device (D-8). Needs the X-Xenia-Device header; the device's login
mode applies (tap and none exist only here). The user needs '<app>.access'. The session
is bound to the device and replaces the device's previous one."""
from core.access.context import current_device
from core.modules.state import blocked_error, is_effective
from routers.devices import effective_login_mode
device = current_device(request, db)
if device is None:
raise XeniaError("device.not_paired")
if not is_effective(device.app_key, db):
raise blocked_error(device.app_key, db)
mode = effective_login_mode(db, device)
if mode == "none":
raise XeniaError("auth.login_mode_not_allowed", mode="none") # the device works without a user
if mode == "pin" and not pin:
raise XeniaError("auth.login_mode_not_allowed", mode="password")
if mode == "password" and not password:
raise XeniaError("auth.login_mode_not_allowed", mode="pin")
q = db.query(User).filter(User.is_active == True) # noqa: E712
user = q.filter(User.username == username).first() if username else (
q.filter(User.id == user_id).first() if user_id is not None else None)
if user is None or (mode != "tap" and not _check_secret(user, pin, password, db)):
raise XeniaError("auth.invalid_credentials")
if not holds(user, f"{device.app_key}.access"):
raise XeniaError("auth.client_not_allowed", client=device.app_key)
row = sessions.start(db, user, "terminal", request, device=device)
return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user))
@router.post("/login", response_model=TokenResponse, dependencies=[Depends(public())])
def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)):
"""POST {client: "manager"|"waiter", username?, user_id?, pin?, password?}.
"""POST {client: "manager"|"waiter"|"terminal", username?, user_id?, pin?, password?}.
"terminal" = a user on a paired device: send the X-Xenia-Device header.
Without `client` (the current manager UI): a manager login with v1 rules (pin or password)."""
return do_login(db, request, client=body.client or "manager", username=body.username,
user_id=body.user_id, pin=body.pin, password=body.password, legacy=body.client is None)
+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):
+342
View File
@@ -0,0 +1,342 @@
"""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.
"""
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.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
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:
raise XeniaError("license.limit_reached", module=app_key, limit="devices", max=cap)
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 _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": d.config,
"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": d.config,
"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=body.config,
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 = body.config
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()
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.app_key = body.app_key
d.config = body.config
if d.login_mode and d.login_mode not in _app(body.app_key).device_app.login_modes:
d.login_mode = None
db.commit()
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()
sessions.end_for_device(db, d.id, "device_revoked")
return _out(d, db)