Files
xenia-pos-local/local_backend/routers/deps.py
T
bonaminandClaude Opus 5.5 3a522e457d feat(backend): support access by offline challenge codes replaces the master account
Platform v2 step 1.10 (APPS_PLATFORM D-16, section 6.5).
- POST /api/auth/support/challenge (public): an 8-character challenge, stored 15 min
  (support_challenges, revision 0009; at most 5 open). POST /api/auth/support/verify
  {challenge, code}: code = base32(HMAC(SUPPORT_SECRET, site_id + challenge))[:10];
  single use, 5 wrong codes burn the challenge. Opens a 4 h support session
  (client=support, synthetic superadmin) with a hard end: sessions.expires_at.
- core/support_codes.py (stdlib only) is the derivation; tools/support_code.py
  (--init, --site-secret <SITE_ID>, <SITE_ID> <CHALLENGE>) uses it on the builder's
  machine with the master key in %USERPROFILE%/.xenia/support_master_key.txt.
- MASTER_USERNAME/MASTER_PASSWORD removed (config, login, docker-compose.yml,
  .env.example); SUPPORT_SECRET added; install.sh asks for it.
- e2e: backends get SUPPORT_SECRET from a test master key and log in with challenge
  codes (lib/support.mjs, license_e2e.py); install.mjs expects the new prompt.
- Pack rule CS-15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 10:52:16 +02:00

129 lines
5.0 KiB
Python

from core.timeutil import utcnow
import jwt
from datetime import datetime, timedelta, timezone
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from database import get_db
from config import settings
from models.user import User
from core.logging import set_log_context
bearer = HTTPBearer()
# A token is only as good as its session (core/sessions.py, D-9): logout and "end
# session" work at once, survive restarts, and nothing lives only in memory.
TOKEN_EXPIRY_HOURS = 8
SUPPORT_USER_ID = 0 # sentinel — never a real DB row
def make_support_user():
"""The support account (D-16): a synthetic superadmin, never a DB row. Its sessions have
client="support" and user_id NULL; it only exists through POST /api/auth/support/verify."""
from types import SimpleNamespace
return SimpleNamespace(
id=SUPPORT_USER_ID,
username="support",
full_name="Xenia Support",
role="superadmin",
is_active=True,
pin_hash=None,
password_hash=None,
email=None,
nickname=None,
mobile_phone=None,
note=None,
avatar_url=None,
waiter_settings=None,
hourly_rate=None,
created_at=datetime(2024, 1, 1, tzinfo=timezone.utc),
zone_assignments=[],
permission_rows=[], # superadmin holds every key without rows (D-7)
)
def make_token(user: User, sid: str, hours: float = TOKEN_EXPIRY_HOURS) -> str:
"""JWT for an existing session row (core.sessions.start). `sid` is what makes it revocable."""
payload = {
"sub": str(user.id),
"sid": sid,
"username": user.username,
"role": user.role,
"exp": utcnow() + timedelta(hours=hours),
}
return jwt.encode(payload, settings.SECRET_KEY, algorithm="HS256")
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:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
except jwt.ExpiredSignatureError:
raise XeniaError("auth.session_ended")
except jwt.InvalidTokenError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
return payload, sessions.validate(payload.get("sid"), 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)
request.state.xenia_sid = payload.get("sid") # manager overrides are bound to the session (D-10)
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 info.user_id is None: # only support sessions have no user (core/sessions.py)
set_log_context(user="support")
return make_support_user(), 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, 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):
# endpoints that only need "some signed-in user" depend on get_current_user directly.
get_current_user.__xenia_access__ = ("signed_in",)
# ── v1 names, now permission keys (APPS_PLATFORM D-7, step 1.5) ──────────────
# Kept as aliases so the ~200 existing route signatures stay as they are. New code
# uses core.access.deps.require("<key>") directly.
from core.access.deps import require # noqa: E402
require_manager = require("core.dashboard.access")
require_staff_manager = require("core.staff.manage")
require_reports = require("reports.view")
require_history = require("history.view")
require_menu_manager = require("catalog.menu.manage")
require_settings_manager = require("core.settings.manage")
require_kds = require("kds.access")
require_tables_manager = require("catalog.tables.manage")
require_superadmin = require("core.system.admin") # no role template: superadmin only
require_sysadmin = require_superadmin