Files
xenia-pos-local/local_backend/core/sessions.py
T
bonaminandClaude Opus 5.5 91da3aeb27 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>
2026-11-13 09:44:40 +02:00

200 lines
7.5 KiB
Python

"""Login sessions and login modes (APPS_PLATFORM D-8, D-9, §6.2, §6.4).
Sessions
- start(db, user, client, request) creates a row and applies the client's single-session
rule (setting auth.single_session_<client>: off | refuse_new | end_old).
- validate(sid) is called on every authenticated request (routers.deps.decode_token).
Results are cached for CACHE_TTL_S; end()/end_for_user() drop the cache entry at once,
so an ended session is refused on its very next request.
- last_seen_at is written at most every LAST_SEEN_EVERY_S, in its own DB session.
Login modes (settings, declared in modules/core/manifest.py)
- auth.manager_login_mode: password | pin (manager in a browser: never tap/none, D-8)
- auth.waiter_login_mode: pin | password | tap (tap needs a paired device: step 1.8)
- auth.waiter_require_username: the waiter must type their username, not just pick a name
Agent notes:
- 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
import logging
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
logger = logging.getLogger("xenia.sessions")
CLIENTS = ("manager", "waiter", "terminal", "support")
CACHE_TTL_S = 10
LAST_SEEN_EVERY_S = 60
_lock = threading.Lock()
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:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row and row.value else default
def single_session_rule(db, client: str) -> str:
return _setting(db, f"auth.single_session_{client}", "off") if client in ("manager", "waiter") else "off"
# ── lifecycle ────────────────────────────────────────────────────────────────
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}")
user_id = getattr(user, "id", None) or None
rule = single_session_rule(db, client)
if legacy_manager and rule == "refuse_new":
# The current manager UI re-logs-in to unlock its lock screen; refusing would lock
# the owner out. Until the phase 2 manager has a real unlock, treat it as end_old.
rule = "end_old"
if user_id is not None and rule != "off":
active = db.query(LoginSession).filter(LoginSession.user_id == user_id, LoginSession.client == client,
LoginSession.ended_at.is_(None)).all()
if active and rule == "refuse_new":
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)
db.commit()
logger.info("session.started sid=%s user=%s client=%s rule=%s", row.id[:8], user_id, client, rule)
return row
def _end_row(row, reason: str) -> None:
row.ended_at = utcnow()
row.end_reason = reason
with _lock:
_cache.pop(row.id, None)
logger.info("session.ended sid=%s user=%s client=%s reason=%s", row.id[:8], row.user_id, row.client, reason)
def end(db, sid: str, reason: str) -> bool:
from models.session import LoginSession
row = db.get(LoginSession, sid)
if row is None or row.ended_at is not None:
return False
_end_row(row, reason)
db.commit()
return True
def end_for_user(db, user_id: int, reason: str) -> int:
from models.session import LoginSession
rows = db.query(LoginSession).filter(LoginSession.user_id == user_id, LoginSession.ended_at.is_(None)).all()
for r in rows:
_end_row(r, reason)
db.commit()
return len(rows)
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()
with _lock:
hit = _cache.get(sid)
if hit and now_m - hit[0] < CACHE_TTL_S:
return hit[1]
from models.session import LoginSession
own = db is None
if own:
from database import SessionLocal
db = SessionLocal()
try:
row = db.get(LoginSession, sid)
if row is None or row.ended_at is not None:
with _lock:
_cache.pop(sid, None)
raise XeniaError("auth.session_ended")
info = Active(row.user_id, row.device_id)
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
finally:
if own:
db.close()
if stale:
_touch(sid)
with _lock:
_cache[sid] = (now_m, info)
return info
def _touch(sid: str) -> None:
from database import SessionLocal
from models.session import LoginSession
s = SessionLocal()
try:
row = s.get(LoginSession, sid)
if row is not None and row.ended_at is None:
row.last_seen_at = utcnow()
s.commit()
except Exception:
logger.debug("session.touch_failed sid=%s", sid[:8], exc_info=True)
finally:
s.close()
def clear_cache() -> None:
with _lock:
_cache.clear()
# ── login modes ──────────────────────────────────────────────────────────────
def manager_login_mode(db) -> str:
v = _setting(db, "auth.manager_login_mode", "password")
return v if v in ("password", "pin") else "password"
def waiter_login_mode(db) -> str:
v = _setting(db, "auth.waiter_login_mode", "pin")
return v if v in ("pin", "password", "tap") else "pin"
def waiter_requires_username(db) -> bool:
return _setting(db, "auth.waiter_require_username", "false") == "true"