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:
@@ -151,6 +151,7 @@ Routers are mounted from the module manifests (`local_backend/modules/<key>/mani
|
|||||||
|
|
||||||
**CS-14. Every route declares who may call it** (branch `platform-v2`, D-7, D-17).
|
**CS-14. Every route declares who may call it** (branch `platform-v2`, D-7, D-17).
|
||||||
Use `core.access.deps.require("<module>.<area>.<action>")` (or `require_any`, `public()`, `require_device(app)`), or `Depends(get_current_user)` for "any signed-in user". The guard `tests/guards/test_route_access.py` fails a route with no marker or with an unknown key. New keys are declared as `Perm(...)` in the owning manifest, with their default roles. Inside code use `core.access.check.holds(user, key)` / `can(user, key)`, never role names or `perm_*` attributes (`tests/guards/test_no_perm_reads.py`). The v1 booleans exist only in `core/access/legacy.py` for the current frontends.
|
Use `core.access.deps.require("<module>.<area>.<action>")` (or `require_any`, `public()`, `require_device(app)`), or `Depends(get_current_user)` for "any signed-in user". The guard `tests/guards/test_route_access.py` fails a route with no marker or with an unknown key. New keys are declared as `Perm(...)` in the owning manifest, with their default roles. Inside code use `core.access.check.holds(user, key)` / `can(user, key)`, never role names or `perm_*` attributes (`tests/guards/test_no_perm_reads.py`). The v1 booleans exist only in `core/access/legacy.py` for the current frontends.
|
||||||
|
Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>`; a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.access`. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header.
|
||||||
|
|
||||||
Everything else still needs manual checks before committing:
|
Everything else still needs manual checks before committing:
|
||||||
- the backend starts cleanly against an **existing** `pos.db` (this catches missing migrations)
|
- the backend starts cleanly against an **existing** `pos.db` (this catches missing migrations)
|
||||||
|
|||||||
+55
@@ -109,6 +109,7 @@ cat > "$SCRIPT_DIR/nginx-proxy/nginx.conf" << 'EOF'
|
|||||||
# :443 waiter.* / manager.* / bare IP → https (needs certs/cert.pem + key.pem)
|
# :443 waiter.* / manager.* / bare IP → https (needs certs/cert.pem + key.pem)
|
||||||
# :4443 → manager over https
|
# :4443 → manager over https
|
||||||
# :8443 → native app over TLS (backend-managed key, pinned), LAN only
|
# :8443 → native app over TLS (backend-managed key, pinned), LAN only
|
||||||
|
# /api/devices/pair-request on :443 → LAN only (device pairing, D-8)
|
||||||
#
|
#
|
||||||
# Every proxied location forwards WebSocket upgrades (/api/ws/connect) and
|
# Every proxied location forwards WebSocket upgrades (/api/ws/connect) and
|
||||||
# disables buffering (SSE), otherwise live events never reach phones / KDS.
|
# disables buffering (SSE), otherwise live events never reach phones / KDS.
|
||||||
@@ -203,6 +204,24 @@ server {
|
|||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
|
location /api/devices/pair-request {
|
||||||
|
allow 10.0.0.0/8;
|
||||||
|
allow 172.16.0.0/12;
|
||||||
|
allow 192.168.0.0/16;
|
||||||
|
allow 127.0.0.0/8;
|
||||||
|
allow fc00::/7;
|
||||||
|
allow fe80::/10;
|
||||||
|
allow ::1;
|
||||||
|
deny all;
|
||||||
|
proxy_pass http://backend:8000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://waiter_pwa:80;
|
proxy_pass http://waiter_pwa:80;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
@@ -227,6 +246,24 @@ server {
|
|||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
|
location /api/devices/pair-request {
|
||||||
|
allow 10.0.0.0/8;
|
||||||
|
allow 172.16.0.0/12;
|
||||||
|
allow 192.168.0.0/16;
|
||||||
|
allow 127.0.0.0/8;
|
||||||
|
allow fc00::/7;
|
||||||
|
allow fe80::/10;
|
||||||
|
allow ::1;
|
||||||
|
deny all;
|
||||||
|
proxy_pass http://backend:8000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://manager_dashboard:80;
|
proxy_pass http://manager_dashboard:80;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
@@ -251,6 +288,24 @@ server {
|
|||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
|
location /api/devices/pair-request {
|
||||||
|
allow 10.0.0.0/8;
|
||||||
|
allow 172.16.0.0/12;
|
||||||
|
allow 192.168.0.0/16;
|
||||||
|
allow 127.0.0.0/8;
|
||||||
|
allow fc00::/7;
|
||||||
|
allow fe80::/10;
|
||||||
|
allow ::1;
|
||||||
|
deny all;
|
||||||
|
proxy_pass http://backend:8000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass http://backend:8000;
|
proxy_pass http://backend:8000;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""Access control (APPS_PLATFORM §3, D-7, D-8, D-17).
|
"""Access control (APPS_PLATFORM §3, D-7, D-8, D-17).
|
||||||
|
|
||||||
allowed(key) = module_of(key) is effective (licence ∪ free) ∩ enabled
|
allowed(key) = module_of(key) is effective (licence ∪ free) ∩ enabled
|
||||||
AND (no device OR key in the device app's scope) step 1.8
|
AND (no device OR key in the device app's scope) devices (D-8)
|
||||||
AND (user is superadmin OR user holds key user_permissions
|
AND (user is superadmin OR user holds key user_permissions
|
||||||
OR a valid manager-override token for key) step 1.9
|
OR a valid manager-override token for key) step 1.9
|
||||||
|
|
||||||
@@ -10,13 +10,18 @@ Use it through the route markers in core/access/deps.py:
|
|||||||
require_any("a.b", "c.d") any of several keys
|
require_any("a.b", "c.d") any of several keys
|
||||||
signed_in any logged-in user (routers.deps.get_current_user)
|
signed_in any logged-in user (routers.deps.get_current_user)
|
||||||
public() deliberately open (health, login, pairing...)
|
public() deliberately open (health, login, pairing...)
|
||||||
require_device("kds") device-only endpoints (step 1.8)
|
require_device("kds") device-only endpoints: a paired device running kds
|
||||||
|
require_device() any paired device (returns the Device)
|
||||||
and inside code with can(user, key) for conditional behaviour (e.g. managers see all orders).
|
and inside code with can(user, key) for conditional behaviour (e.g. managers see all orders).
|
||||||
|
|
||||||
Every route must carry one of these markers somewhere in its dependencies; the guard
|
Every route must carry one of these markers somewhere in its dependencies; the guard
|
||||||
tests/guards/test_route_access.py fails otherwise.
|
tests/guards/test_route_access.py fails otherwise.
|
||||||
|
|
||||||
Files: templates.py (role templates from manifests), check.py (the decision),
|
Devices (D-8): a request with header X-Xenia-Device carries a paired device
|
||||||
|
(context.py). Its scope limits both keys (check) and which modules' routes it may reach
|
||||||
|
(module_required), and a user session started on a device only works with that device.
|
||||||
|
|
||||||
|
Files: context.py (device lookup, scope, get_context), templates.py (role templates from manifests), check.py (the decision),
|
||||||
deps.py (route markers), legacy.py (temporary v1 perm_* projection for the current
|
deps.py (route markers), legacy.py (temporary v1 perm_* projection for the current
|
||||||
frontends, §3.3), queries.py (find users holding a key).
|
frontends, §3.3), queries.py (find users holding a key).
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ from core.modules.registry import all_permissions
|
|||||||
@dataclass
|
@dataclass
|
||||||
class AccessContext:
|
class AccessContext:
|
||||||
user: Any = None # User row, or the support ghost (step 1.10); None for device-only calls
|
user: Any = None # User row, or the support ghost (step 1.10); None for device-only calls
|
||||||
session: Any = None # step 1.6
|
session: Any = None # session id (sid) of the user's login
|
||||||
device: Any = None # step 1.8
|
device: Any = None # Device row when the call comes from a paired device (D-8)
|
||||||
override_keys: frozenset = frozenset() # step 1.9
|
override_keys: frozenset = frozenset() # step 1.9
|
||||||
|
|
||||||
|
|
||||||
@@ -49,7 +49,10 @@ def check(ctx: AccessContext, key: str, db=None) -> None:
|
|||||||
module = module_of(key)
|
module = module_of(key)
|
||||||
if not is_effective(module, db):
|
if not is_effective(module, db):
|
||||||
raise blocked_error(module, db)
|
raise blocked_error(module, db)
|
||||||
# device scope: step 1.8
|
if ctx.device is not None:
|
||||||
|
from core.access.context import in_scope
|
||||||
|
if not in_scope(ctx.device.app_key, key):
|
||||||
|
raise XeniaError("device.out_of_scope", app=ctx.device.app_key, key=key)
|
||||||
if holds(ctx.user, key) or key in ctx.override_keys:
|
if holds(ctx.user, key) or key in ctx.override_keys:
|
||||||
return
|
return
|
||||||
raise XeniaError("access.denied", key=key)
|
raise XeniaError("access.denied", key=key)
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
"""Who is calling: the request's device and user (APPS_PLATFORM §3.1, D-8, step 1.8).
|
||||||
|
|
||||||
|
- current_device(request, db): the paired device named by header `X-Xenia-Device`, or None
|
||||||
|
when the header is absent. Unknown token -> device.not_paired; revoked -> device.revoked;
|
||||||
|
beyond its app's `devices` limit -> license.limit_reached. Cached on request.state, so
|
||||||
|
the several dependencies that need it look it up once per request.
|
||||||
|
- get_context: FastAPI dependency -> AccessContext(user | None, session sid | None, device | None).
|
||||||
|
For endpoints that accept a device alone or a device + user.
|
||||||
|
- Device scope (D-8): a device may only use permission keys of its own app plus the
|
||||||
|
patterns in its manifest's DeviceApp.scope (in_scope), and only routes of those modules
|
||||||
|
(module_in_scope, applied by core.modules.state.module_required to every non-core router).
|
||||||
|
Core routes stay reachable (login, /me, bootstrap, live events); keyed core routes are
|
||||||
|
still checked key by key.
|
||||||
|
|
||||||
|
Agent notes:
|
||||||
|
- The token is a long random secret; only its sha256 is stored (models/device.py).
|
||||||
|
- last_seen_at is written at most every LAST_SEEN_EVERY_S.
|
||||||
|
- A user session started on a device (client "terminal") is bound to it: routers.deps.
|
||||||
|
get_current_user refuses it without that device's header (device.required), so scope
|
||||||
|
can't be escaped by dropping the header. SSE/WebSocket (token in the query, browsers
|
||||||
|
can't set headers there) only stream events and are not bound; revisit in phase 3.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
from datetime import timedelta
|
||||||
|
from fnmatch import fnmatchcase
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import Depends, Request
|
||||||
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from core.access.check import AccessContext
|
||||||
|
from core.errors import XeniaError
|
||||||
|
from core.timeutil import utcnow
|
||||||
|
from database import get_db
|
||||||
|
|
||||||
|
DEVICE_HEADER = "X-Xenia-Device"
|
||||||
|
LAST_SEEN_EVERY_S = 60
|
||||||
|
_NO_DEVICE = object()
|
||||||
|
_optional_bearer = HTTPBearer(auto_error=False)
|
||||||
|
|
||||||
|
|
||||||
|
def hash_token(token: str) -> str:
|
||||||
|
return hashlib.sha256(token.encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def device_app(app_key: str):
|
||||||
|
"""The DeviceApp of an app module, or None."""
|
||||||
|
from core.modules.registry import registry
|
||||||
|
m = registry().get(app_key)
|
||||||
|
return m.device_app if m is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def scope_patterns(app_key: str) -> tuple[str, ...]:
|
||||||
|
da = device_app(app_key)
|
||||||
|
return (f"{app_key}.*",) + (tuple(da.scope) if da else ())
|
||||||
|
|
||||||
|
|
||||||
|
def in_scope(app_key: str, key: str) -> bool:
|
||||||
|
"""May a device running `app_key` use permission `key`?"""
|
||||||
|
return any(fnmatchcase(key, p) for p in scope_patterns(app_key))
|
||||||
|
|
||||||
|
|
||||||
|
def module_in_scope(app_key: str, module: str) -> bool:
|
||||||
|
"""May a device running `app_key` call routes of `module` at all?"""
|
||||||
|
return module == app_key or any(p.split(".", 1)[0] == module for p in scope_patterns(app_key))
|
||||||
|
|
||||||
|
|
||||||
|
def over_limit(db, device) -> Optional[int]:
|
||||||
|
"""The app's device limit if this device is beyond it (oldest devices keep working
|
||||||
|
after a downgrade, D-6), else None."""
|
||||||
|
from core.modules import entitlements
|
||||||
|
from models.device import Device
|
||||||
|
cap = entitlements.limit(device.app_key, "devices")
|
||||||
|
if cap is None:
|
||||||
|
return None
|
||||||
|
older = db.query(Device).filter(Device.app_key == device.app_key, Device.revoked_at.is_(None),
|
||||||
|
Device.id < device.id).count()
|
||||||
|
return cap if older >= cap else None
|
||||||
|
|
||||||
|
|
||||||
|
def lookup_device(db, token: str):
|
||||||
|
"""The Device for a raw token, applying revocation and the limit. Raises XeniaError."""
|
||||||
|
from core.logging import set_log_context
|
||||||
|
from models.device import Device
|
||||||
|
dev = db.query(Device).filter(Device.token_hash == hash_token(token)).first()
|
||||||
|
if dev is None:
|
||||||
|
raise XeniaError("device.not_paired")
|
||||||
|
if dev.revoked_at is not None:
|
||||||
|
raise XeniaError("device.revoked")
|
||||||
|
cap = over_limit(db, dev)
|
||||||
|
if cap is not None:
|
||||||
|
raise XeniaError("license.limit_reached", module=dev.app_key, limit="devices", max=cap)
|
||||||
|
set_log_context(device=dev.id)
|
||||||
|
now = utcnow()
|
||||||
|
if dev.last_seen_at is None or now - dev.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S):
|
||||||
|
dev.last_seen_at = now
|
||||||
|
db.commit() # runs before the endpoint body, so nothing else is pending yet
|
||||||
|
return dev
|
||||||
|
|
||||||
|
|
||||||
|
def current_device(request: Request, db) -> Optional[object]:
|
||||||
|
cached = getattr(request.state, "xenia_device", _NO_DEVICE)
|
||||||
|
if cached is not _NO_DEVICE:
|
||||||
|
return cached
|
||||||
|
token = request.headers.get(DEVICE_HEADER)
|
||||||
|
dev = lookup_device(db, token) if token else None
|
||||||
|
request.state.xenia_device = dev
|
||||||
|
return dev
|
||||||
|
|
||||||
|
|
||||||
|
def check_device_scope(device, module: str) -> None:
|
||||||
|
if device is not None and not module_in_scope(device.app_key, module):
|
||||||
|
raise XeniaError("device.out_of_scope", app=device.app_key, key=module)
|
||||||
|
|
||||||
|
|
||||||
|
def get_context(request: Request, db: Session = Depends(get_db),
|
||||||
|
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer)) -> AccessContext:
|
||||||
|
"""Device (if any) + user (if a bearer token is sent). An invalid token is an error here:
|
||||||
|
endpoints that want "anonymous unless valid" (bootstrap) handle that themselves."""
|
||||||
|
from routers.deps import user_from_token
|
||||||
|
device = current_device(request, db)
|
||||||
|
user = sid = None
|
||||||
|
if credentials:
|
||||||
|
user, sid = user_from_token(credentials.credentials, request, db)
|
||||||
|
return AccessContext(user=user, session=sid, device=device)
|
||||||
@@ -6,10 +6,11 @@ any route without a marker, so "forgot to protect" can't ship.
|
|||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from fastapi import Depends
|
from fastapi import Depends, Request
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from core.access.check import AccessContext, check
|
from core.access.check import AccessContext, check
|
||||||
|
from core.access.context import current_device
|
||||||
from core.errors import XeniaError
|
from core.errors import XeniaError
|
||||||
from database import get_db
|
from database import get_db
|
||||||
|
|
||||||
@@ -25,8 +26,8 @@ def require(key: str):
|
|||||||
# tests/guards/test_route_access.py checks every marker's key exists.
|
# tests/guards/test_route_access.py checks every marker's key exists.
|
||||||
from routers.deps import get_current_user
|
from routers.deps import get_current_user
|
||||||
|
|
||||||
def _dep(user=Depends(get_current_user), db: Session = Depends(get_db)):
|
def _dep(request: Request, user=Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
check(AccessContext(user=user), key, db)
|
check(AccessContext(user=user, device=current_device(request, db)), key, db)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
_dep.__name__ = f"require_{key.replace('.', '_')}"
|
_dep.__name__ = f"require_{key.replace('.', '_')}"
|
||||||
@@ -37,11 +38,12 @@ def require_any(*keys: str):
|
|||||||
"""The user must hold at least one of `keys` (in an effective module). Returns the user."""
|
"""The user must hold at least one of `keys` (in an effective module). Returns the user."""
|
||||||
from routers.deps import get_current_user
|
from routers.deps import get_current_user
|
||||||
|
|
||||||
def _dep(user=Depends(get_current_user), db: Session = Depends(get_db)):
|
def _dep(request: Request, user=Depends(get_current_user), db: Session = Depends(get_db)):
|
||||||
last = None
|
last = None
|
||||||
|
ctx = AccessContext(user=user, device=current_device(request, db))
|
||||||
for k in keys:
|
for k in keys:
|
||||||
try:
|
try:
|
||||||
check(AccessContext(user=user), k, db)
|
check(ctx, k, db)
|
||||||
return user
|
return user
|
||||||
except XeniaError as e:
|
except XeniaError as e:
|
||||||
last = e
|
last = e
|
||||||
@@ -58,8 +60,22 @@ def public():
|
|||||||
return _mark(_dep, "public")
|
return _mark(_dep, "public")
|
||||||
|
|
||||||
|
|
||||||
def require_device(app_key: str):
|
def require_device(app_key: str | None = None):
|
||||||
"""Device-only endpoint for paired devices running `app_key` (implemented in step 1.8)."""
|
"""Device-only endpoint (D-8): the request must carry a valid X-Xenia-Device token.
|
||||||
def _dep():
|
With `app_key`, the device must run that app and the app's module must be effective
|
||||||
raise XeniaError("device.not_paired")
|
(licensed and enabled). Without it, any paired device (e.g. GET /api/devices/me, which
|
||||||
return _mark(_dep, "require_device", app_key)
|
must answer even when the app is turned off so the screen can say so). Returns the Device."""
|
||||||
|
def _dep(request: Request, db: Session = Depends(get_db)):
|
||||||
|
dev = current_device(request, db)
|
||||||
|
if dev is None:
|
||||||
|
raise XeniaError("device.not_paired")
|
||||||
|
if app_key is not None:
|
||||||
|
if dev.app_key != app_key:
|
||||||
|
raise XeniaError("device.out_of_scope", app=dev.app_key, key=app_key)
|
||||||
|
from core.modules.state import blocked_error, is_effective
|
||||||
|
if not is_effective(app_key, db):
|
||||||
|
raise blocked_error(app_key, db)
|
||||||
|
return dev
|
||||||
|
|
||||||
|
_dep.__name__ = f"require_device_{app_key or 'any'}"
|
||||||
|
return _mark(_dep, "require_device", app_key or "*")
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"module.not_licensed": (402, "This site's license doesn't include {module}."),
|
"module.not_licensed": (402, "This site's license doesn't include {module}."),
|
||||||
"module.unknown": (404, "There is no module {module}."),
|
"module.unknown": (404, "There is no module {module}."),
|
||||||
"module.cannot_disable": (400, "{module} is part of the core and can't be turned off."),
|
"module.cannot_disable": (400, "{module} is part of the core and can't be turned off."),
|
||||||
"license.limit_reached": (402, "License limit reached for {limit} ({max})."),
|
"license.limit_reached": (402, "License limit reached for {module} {limit} ({max})."),
|
||||||
"license.expired": (402, "The license has expired."),
|
"license.expired": (402, "The license has expired."),
|
||||||
"license.history_limited": (402, "This license shows only the last {days} days of history ({module})."),
|
"license.history_limited": (402, "This license shows only the last {days} days of history ({module})."),
|
||||||
# identity
|
# identity
|
||||||
@@ -60,6 +60,14 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"auth.session_not_found": (404, "Session not found."),
|
"auth.session_not_found": (404, "Session not found."),
|
||||||
"device.revoked": (401, "This device was removed. Pair it again."),
|
"device.revoked": (401, "This device was removed. Pair it again."),
|
||||||
"device.not_paired": (401, "This device isn't paired with the venue."),
|
"device.not_paired": (401, "This device isn't paired with the venue."),
|
||||||
|
"device.out_of_scope": (403, "A {app} device can't do this ({key})."),
|
||||||
|
"device.required": (401, "This login belongs to a paired device. Use it from that device."),
|
||||||
|
"device.not_found": (404, "Device {device_id} not found."),
|
||||||
|
"device.pair_code_invalid": (404, "That pairing code is wrong or has expired."),
|
||||||
|
"device.pair_rate_limited": (429, "Too many pairing requests. Wait a few minutes and try again."),
|
||||||
|
"device.not_an_app": (422, "{app} is not an app that runs on a device."),
|
||||||
|
"device.login_mode_invalid": (422, "A {app} device can't use the login mode {mode}."),
|
||||||
|
"device.link_invalid": (422, "Device {device_id} can't be linked to this device."),
|
||||||
# validation
|
# validation
|
||||||
"validation.invalid": (422, "Some fields are invalid."),
|
"validation.invalid": (422, "Some fields are invalid."),
|
||||||
"validation.unknown_language": (422, "Unsupported language: {language}."),
|
"validation.unknown_language": (422, "Unsupported language: {language}."),
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ from core.access.deps import public
|
|||||||
|
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends
|
from fastapi import APIRouter, Depends, Request
|
||||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
@@ -76,13 +76,14 @@ def _module_out(m, enabled: dict, effective: frozenset) -> dict:
|
|||||||
|
|
||||||
@router.get("/bootstrap", dependencies=[Depends(public())])
|
@router.get("/bootstrap", dependencies=[Depends(public())])
|
||||||
def bootstrap(
|
def bootstrap(
|
||||||
|
request: Request,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer),
|
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer),
|
||||||
):
|
):
|
||||||
user = None
|
user = None
|
||||||
if credentials:
|
if credentials:
|
||||||
try:
|
try:
|
||||||
user = get_current_user(credentials, db)
|
user = get_current_user(request, credentials, db)
|
||||||
except Exception:
|
except Exception:
|
||||||
user = None # an expired/invalid token just means "not logged in" here
|
user = None # an expired/invalid token just means "not logged in" here
|
||||||
effective = state.effective_set(db)
|
effective = state.effective_set(db)
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ from core.modules.model import Module
|
|||||||
MODULES_DIR = Path(__file__).resolve().parents[2] / "modules"
|
MODULES_DIR = Path(__file__).resolve().parents[2] / "modules"
|
||||||
_KEY = re.compile(r"^[a-z][a-z0-9_]*$")
|
_KEY = re.compile(r"^[a-z][a-z0-9_]*$")
|
||||||
_KINDS = {"core", "feature", "app", "integration"}
|
_KINDS = {"core", "feature", "app", "integration"}
|
||||||
|
_LOGIN_MODES = {"pin", "password", "tap", "none"}
|
||||||
|
|
||||||
|
|
||||||
class ManifestError(ValueError):
|
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)}")
|
raise ManifestError(f"{where}: kind {m.kind!r} not in {sorted(_KINDS)}")
|
||||||
if m.device_app and m.kind != "app":
|
if m.device_app and m.kind != "app":
|
||||||
raise ManifestError(f"{where}: device_app is only for 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:
|
for p in m.permissions:
|
||||||
if not p.key.startswith(m.key + "."):
|
if not p.key.startswith(m.key + "."):
|
||||||
raise ManifestError(f"{where}: permission {p.key!r} must start with {m.key + '.'!r}")
|
raise ManifestError(f"{where}: permission {p.key!r} must start with {m.key + '.'!r}")
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ import logging
|
|||||||
import threading
|
import threading
|
||||||
from typing import Callable
|
from typing import Callable
|
||||||
|
|
||||||
from fastapi import Depends
|
from fastapi import Depends, Request
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from core.errors import XeniaError
|
from core.errors import XeniaError
|
||||||
@@ -157,9 +157,12 @@ def module_required(key: str):
|
|||||||
if key not in registry():
|
if key not in registry():
|
||||||
raise ValueError(f"module_required: unknown module {key!r}")
|
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):
|
if not is_effective(key, db):
|
||||||
raise blocked_error(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}"
|
_check.__name__ = f"module_required_{key}"
|
||||||
return _check
|
return _check
|
||||||
|
|||||||
@@ -14,7 +14,9 @@ Login modes (settings, declared in modules/core/manifest.py)
|
|||||||
- auth.waiter_require_username: the waiter must type their username, not just pick a name
|
- auth.waiter_require_username: the waiter must type their username, not just pick a name
|
||||||
|
|
||||||
Agent notes:
|
Agent notes:
|
||||||
- Clients: "manager", "waiter" now; "terminal" (devices) in 1.8; "support" in 1.10.
|
- 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().
|
- Never trust a JWT alone: always go through validate().
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -24,6 +26,7 @@ import threading
|
|||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
from typing import NamedTuple, Optional
|
||||||
|
|
||||||
from core.errors import XeniaError
|
from core.errors import XeniaError
|
||||||
from core.timeutil import utcnow
|
from core.timeutil import utcnow
|
||||||
@@ -35,7 +38,15 @@ CACHE_TTL_S = 10
|
|||||||
LAST_SEEN_EVERY_S = 60
|
LAST_SEEN_EVERY_S = 60
|
||||||
|
|
||||||
_lock = threading.Lock()
|
_lock = threading.Lock()
|
||||||
_cache: dict[str, tuple[float, int | None]] = {} # sid -> (checked_at monotonic, user_id) for ACTIVE sessions
|
|
||||||
|
|
||||||
|
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:
|
def _setting(db, key: str, default: str) -> str:
|
||||||
@@ -50,8 +61,10 @@ def single_session_rule(db, client: str) -> str:
|
|||||||
|
|
||||||
# ── lifecycle ────────────────────────────────────────────────────────────────
|
# ── lifecycle ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def start(db, user, client: str, request=None, *, legacy_manager: bool = False):
|
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."""
|
"""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
|
from models.session import LoginSession
|
||||||
if client not in CLIENTS:
|
if client not in CLIENTS:
|
||||||
raise ValueError(f"unknown client {client!r}")
|
raise ValueError(f"unknown client {client!r}")
|
||||||
@@ -68,8 +81,12 @@ def start(db, user, client: str, request=None, *, legacy_manager: bool = False):
|
|||||||
raise XeniaError("auth.session_exists", client=client)
|
raise XeniaError("auth.session_exists", client=client)
|
||||||
for s in active:
|
for s in active:
|
||||||
_end_row(s, "replaced")
|
_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()
|
now = utcnow()
|
||||||
row = LoginSession(id=uuid.uuid4().hex, user_id=user_id, client=client, created_at=now, last_seen_at=now,
|
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),
|
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))
|
user_agent=(request.headers.get("user-agent", "")[:300] if request is not None else None))
|
||||||
db.add(row)
|
db.add(row)
|
||||||
@@ -105,8 +122,17 @@ def end_for_user(db, user_id: int, reason: str) -> int:
|
|||||||
return len(rows)
|
return len(rows)
|
||||||
|
|
||||||
|
|
||||||
def validate(sid: str | None, db=None) -> int | None:
|
def end_for_device(db, device_id: int, reason: str) -> int:
|
||||||
"""User id of an active session (None for support). Raises auth.session_ended."""
|
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:
|
if not sid:
|
||||||
raise XeniaError("auth.session_ended")
|
raise XeniaError("auth.session_ended")
|
||||||
now_m = time.monotonic()
|
now_m = time.monotonic()
|
||||||
@@ -125,7 +151,7 @@ def validate(sid: str | None, db=None) -> int | None:
|
|||||||
with _lock:
|
with _lock:
|
||||||
_cache.pop(sid, None)
|
_cache.pop(sid, None)
|
||||||
raise XeniaError("auth.session_ended")
|
raise XeniaError("auth.session_ended")
|
||||||
user_id = row.user_id
|
info = Active(row.user_id, row.device_id)
|
||||||
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
|
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
|
||||||
finally:
|
finally:
|
||||||
if own:
|
if own:
|
||||||
@@ -133,8 +159,8 @@ def validate(sid: str | None, db=None) -> int | None:
|
|||||||
if stale:
|
if stale:
|
||||||
_touch(sid)
|
_touch(sid)
|
||||||
with _lock:
|
with _lock:
|
||||||
_cache[sid] = (now_m, user_id)
|
_cache[sid] = (now_m, info)
|
||||||
return user_id
|
return info
|
||||||
|
|
||||||
|
|
||||||
def _touch(sid: str) -> None:
|
def _touch(sid: str) -> None:
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""devices, pairing requests, session device FK (D-8, §6.3, step 1.8)
|
||||||
|
|
||||||
|
Hand-edited: the sessions FK gets a name (SQLite batch mode can't create or drop an
|
||||||
|
unnamed constraint). No data moves: sessions.device_id was always NULL before this.
|
||||||
|
|
||||||
|
Revision ID: 0007_devices
|
||||||
|
Revises: 0006_sessions
|
||||||
|
Create Date: 2026-11-13 09:33:18.938342
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0007_devices'
|
||||||
|
down_revision = '0006_sessions'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('devices',
|
||||||
|
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column('uuid', sa.String(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('app_key', sa.String(), nullable=False),
|
||||||
|
sa.Column('config', sa.JSON(), nullable=True),
|
||||||
|
sa.Column('login_mode', sa.String(), nullable=True),
|
||||||
|
sa.Column('token_hash', sa.String(), nullable=True),
|
||||||
|
sa.Column('linked_device_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('user_agent', sa.String(), nullable=True),
|
||||||
|
sa.Column('paired_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('paired_by', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('claimed_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.Column('last_seen_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.Column('revoked_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.Column('revoked_by', sa.Integer(), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['linked_device_id'], ['devices.id'], ondelete='SET NULL'),
|
||||||
|
sa.ForeignKeyConstraint(['paired_by'], ['users.id'], ondelete='SET NULL'),
|
||||||
|
sa.ForeignKeyConstraint(['revoked_by'], ['users.id'], ondelete='SET NULL'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('token_hash'),
|
||||||
|
sa.UniqueConstraint('uuid'),
|
||||||
|
sqlite_autoincrement=True
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('devices', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_devices_app_key'), ['app_key'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_devices_revoked_at'), ['revoked_at'], unique=False)
|
||||||
|
|
||||||
|
op.create_table('device_pair_requests',
|
||||||
|
sa.Column('code', sa.String(), nullable=False),
|
||||||
|
sa.Column('secret_hash', sa.String(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('expires_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('device_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('ip', sa.String(), nullable=True),
|
||||||
|
sa.Column('user_agent', sa.String(), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['device_id'], ['devices.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('code')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('device_pair_requests', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_device_pair_requests_expires_at'), ['expires_at'], unique=False)
|
||||||
|
|
||||||
|
with op.batch_alter_table('sessions', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_sessions_device_id'), ['device_id'], unique=False)
|
||||||
|
batch_op.create_foreign_key('fk_sessions_device_id_devices', 'devices', ['device_id'], ['id'])
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('sessions', schema=None) as batch_op:
|
||||||
|
batch_op.drop_constraint('fk_sessions_device_id_devices', type_='foreignkey')
|
||||||
|
batch_op.drop_index(batch_op.f('ix_sessions_device_id'))
|
||||||
|
|
||||||
|
with op.batch_alter_table('device_pair_requests', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_device_pair_requests_expires_at'))
|
||||||
|
|
||||||
|
op.drop_table('device_pair_requests')
|
||||||
|
with op.batch_alter_table('devices', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_devices_revoked_at'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_devices_app_key'))
|
||||||
|
|
||||||
|
op.drop_table('devices')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -30,3 +30,4 @@ import models.sync_event # noqa: F401
|
|||||||
import models.site_module # noqa: F401 SiteModule (module enablement, step 1.3)
|
import models.site_module # noqa: F401 SiteModule (module enablement, step 1.3)
|
||||||
import models.user_permission # noqa: F401 UserPermission (permission keys, step 1.5)
|
import models.user_permission # noqa: F401 UserPermission (permission keys, step 1.5)
|
||||||
import models.session # noqa: F401 LoginSession (step 1.6)
|
import models.session # noqa: F401 LoginSession (step 1.6)
|
||||||
|
import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""Paired devices and pairing requests (APPS_PLATFORM D-8, §6.3, plan step 1.8).
|
||||||
|
|
||||||
|
A device is shared or unattended hardware (counter PC, KDS screen, TV, tablet) that runs
|
||||||
|
exactly one app module (`app_key`). It proves itself with a long random token, sent as
|
||||||
|
header `X-Xenia-Device`; only its sha256 is stored. Personal phones and the manager's
|
||||||
|
browser are NOT devices (they are user sessions).
|
||||||
|
|
||||||
|
Pairing: the device asks for a code (device_pair_requests row, 10 min), a manager enters
|
||||||
|
the code and creates the Device row, the device's next poll generates the token, stores
|
||||||
|
its hash and deletes the request. So the plain token is never stored anywhere.
|
||||||
|
|
||||||
|
Devices are never deleted: revoked rows keep their token hash so the device is told
|
||||||
|
`device.revoked` (not "unknown"), and old sessions/audit rows keep a valid device_id.
|
||||||
|
Read and written through routers/devices.py and core/access/context.py.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Device(Base):
|
||||||
|
__tablename__ = "devices"
|
||||||
|
__table_args__ = {"sqlite_autoincrement": True} # ids are never reused (sessions point at them)
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
uuid = Column(String, nullable=False, unique=True) # public identifier
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
app_key = Column(String, nullable=False, index=True) # a kind="app" module with device_app
|
||||||
|
config = Column(JSON, nullable=True) # app-specific (e.g. KDS prep zone)
|
||||||
|
login_mode = Column(String, nullable=True) # NULL = site default auth.default_login_mode
|
||||||
|
token_hash = Column(String, nullable=True, unique=True) # sha256 hex; NULL until the device picks it up
|
||||||
|
linked_device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True)
|
||||||
|
user_agent = Column(String, nullable=True) # from the pairing request
|
||||||
|
paired_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
|
paired_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||||
|
claimed_at = Column(UTCDateTime, nullable=True) # when the device received its token
|
||||||
|
last_seen_at = Column(UTCDateTime, nullable=True)
|
||||||
|
revoked_at = Column(UTCDateTime, nullable=True, index=True)
|
||||||
|
revoked_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||||
|
|
||||||
|
|
||||||
|
class DevicePairRequest(Base):
|
||||||
|
__tablename__ = "device_pair_requests"
|
||||||
|
|
||||||
|
code = Column(String, primary_key=True) # 6 chars, shown on the device
|
||||||
|
secret_hash = Column(String, nullable=False) # only the requester may poll
|
||||||
|
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
|
expires_at = Column(UTCDateTime, nullable=False, index=True)
|
||||||
|
device_id = Column(Integer, ForeignKey("devices.id", ondelete="CASCADE"), nullable=True) # set on approval
|
||||||
|
ip = Column(String, nullable=True)
|
||||||
|
user_agent = Column(String, nullable=True)
|
||||||
@@ -17,11 +17,11 @@ class LoginSession(Base):
|
|||||||
id = Column(String, primary_key=True) # uuid4 hex
|
id = Column(String, primary_key=True) # uuid4 hex
|
||||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=True, index=True)
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=True, index=True)
|
||||||
# NULL user_id = the support account (synthetic, no users row; step 1.10)
|
# NULL user_id = the support account (synthetic, no users row; step 1.10)
|
||||||
device_id = Column(Integer, nullable=True) # step 1.8
|
device_id = Column(Integer, ForeignKey("devices.id"), nullable=True, index=True) # terminal sessions: the device
|
||||||
client = Column(String, nullable=False) # manager | waiter | terminal | support
|
client = Column(String, nullable=False) # manager | waiter | terminal | support
|
||||||
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
last_seen_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
last_seen_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
ended_at = Column(UTCDateTime, nullable=True, index=True)
|
ended_at = Column(UTCDateTime, nullable=True, index=True)
|
||||||
end_reason = Column(String, nullable=True) # logout | replaced | ended_by_manager | user_blocked | refreshed
|
end_reason = Column(String, nullable=True) # logout | replaced | ended_by_manager | user_blocked | refreshed | device_revoked | device_reassigned
|
||||||
ip = Column(String, nullable=True)
|
ip = Column(String, nullable=True)
|
||||||
user_agent = Column(String, nullable=True)
|
user_agent = Column(String, nullable=True)
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ MODULE = Module(
|
|||||||
Perm('core.staff.manage', 'Add and edit staff', roles=('owner', 'store_manager', 'staff_manager')),
|
Perm('core.staff.manage', 'Add and edit staff', roles=('owner', 'store_manager', 'staff_manager')),
|
||||||
Perm('core.settings.manage', 'Change venue settings', roles=('owner',)),
|
Perm('core.settings.manage', 'Change venue settings', roles=('owner',)),
|
||||||
Perm('core.modules.manage', 'Turn apps, features and integrations on or off', roles=('owner',)),
|
Perm('core.modules.manage', 'Turn apps, features and integrations on or off', roles=('owner',)),
|
||||||
|
Perm('core.devices.manage', 'Pair, rename, reassign and remove devices', roles=('owner', 'store_manager')),
|
||||||
Perm('core.system.admin', 'Support-only maintenance (superadmin)', roles=()),
|
Perm('core.system.admin', 'Support-only maintenance (superadmin)', roles=()),
|
||||||
),
|
),
|
||||||
settings=(
|
settings=(
|
||||||
@@ -22,6 +23,7 @@ MODULE = Module(
|
|||||||
SettingDef('security.autofill_username', 'true', "Auto-fill username when only one manager exists: 'true' | 'false'", type='bool'),
|
SettingDef('security.autofill_username', 'true', "Auto-fill username when only one manager exists: 'true' | 'false'", type='bool'),
|
||||||
SettingDef('auth.manager_login_mode', 'password', "How managers log in on the dashboard: 'password' | 'pin' (never username-only, D-8)", type='enum', choices=('password', 'pin')),
|
SettingDef('auth.manager_login_mode', 'password', "How managers log in on the dashboard: 'password' | 'pin' (never username-only, D-8)", type='enum', choices=('password', 'pin')),
|
||||||
SettingDef('auth.waiter_login_mode', 'pin', "How waiters log in: 'pin' | 'password' | 'tap' (tap = pick your name; only on paired devices)", type='enum', choices=('pin', 'password', 'tap')),
|
SettingDef('auth.waiter_login_mode', 'pin', "How waiters log in: 'pin' | 'password' | 'tap' (tap = pick your name; only on paired devices)", type='enum', choices=('pin', 'password', 'tap')),
|
||||||
|
SettingDef('auth.default_login_mode', 'pin', "How staff log in on paired devices (KDS, counter POS) unless the device sets its own: 'pin' | 'password' | 'tap' | 'none'. Apps that can't use it fall back to their first mode.", type='enum', choices=('pin', 'password', 'tap', 'none')),
|
||||||
SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'),
|
SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'),
|
||||||
SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
||||||
SettingDef('auth.single_session_waiter', 'off', "One waiter session per user (no double login): 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
SettingDef('auth.single_session_waiter', 'off', "One waiter session per user (no double login): 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
||||||
@@ -41,6 +43,7 @@ MODULE = Module(
|
|||||||
Mount('routers.sse', '/api/sse'),
|
Mount('routers.sse', '/api/sse'),
|
||||||
Mount('routers.ws', '/api/ws'),
|
Mount('routers.ws', '/api/ws'),
|
||||||
Mount('routers.recovery', '/api/recovery'),
|
Mount('routers.recovery', '/api/recovery'),
|
||||||
|
Mount('routers.devices', '/api/devices'),
|
||||||
Mount('core.modules.api', '/api/platform'),
|
Mount('core.modules.api', '/api/platform'),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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:
|
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
|
"""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)."""
|
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")
|
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
|
# Support access (synthetic superadmin). >>> replaced by challenge codes in step 1.10
|
||||||
if (client == "manager" and settings.MASTER_USERNAME and settings.MASTER_PASSWORD
|
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))
|
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())])
|
@router.post("/login", response_model=TokenResponse, dependencies=[Depends(public())])
|
||||||
def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)):
|
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)."""
|
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,
|
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)
|
user_id=body.user_id, pin=body.pin, password=body.password, legacy=body.client is None)
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from core.timeutil import utcnow
|
from core.timeutil import utcnow
|
||||||
import jwt
|
import jwt
|
||||||
from datetime import datetime, timedelta, timezone
|
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 fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||||
from sqlalchemy.orm import Session
|
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")
|
return jwt.encode(payload, settings.SECRET_KEY, algorithm="HS256")
|
||||||
|
|
||||||
|
|
||||||
def decode_token(token: str, db: Session | None = None) -> dict:
|
def decode_session(token: str, db: Session | None = None):
|
||||||
"""Verify the JWT AND its session (auth.session_ended once logged out/ended/replaced).
|
"""Verify the JWT AND its session -> (payload, sessions.Active).
|
||||||
Used by get_current_user and by the SSE/WebSocket endpoints (token in the query)."""
|
auth.session_ended once logged out/ended/replaced."""
|
||||||
from core import sessions
|
from core import sessions
|
||||||
from core.errors import XeniaError
|
from core.errors import XeniaError
|
||||||
try:
|
try:
|
||||||
@@ -67,23 +67,41 @@ def decode_token(token: str, db: Session | None = None) -> dict:
|
|||||||
raise XeniaError("auth.session_ended")
|
raise XeniaError("auth.session_ended")
|
||||||
except jwt.InvalidTokenError:
|
except jwt.InvalidTokenError:
|
||||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||||
sessions.validate(payload.get("sid"), db)
|
return payload, sessions.validate(payload.get("sid"), db)
|
||||||
return payload
|
|
||||||
|
|
||||||
|
|
||||||
def get_current_user(
|
def decode_token(token: str, db: Session | None = None) -> dict:
|
||||||
credentials: HTTPAuthorizationCredentials = Depends(bearer),
|
"""decode_session without the session info. Used by the SSE/WebSocket endpoints
|
||||||
db: Session = Depends(get_db),
|
(token in the query) and token refresh."""
|
||||||
) -> User:
|
return decode_session(token, db)[0]
|
||||||
payload = decode_token(credentials.credentials, db)
|
|
||||||
|
|
||||||
|
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":
|
if int(payload["sub"]) == MASTER_USER_ID and payload.get("role") == "superadmin":
|
||||||
set_log_context(user="support")
|
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()
|
user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first()
|
||||||
if not user:
|
if not user:
|
||||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
||||||
set_log_context(user=user.id)
|
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):
|
# Logged-in, no specific key. An explicit access marker for the route guard (D-17):
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -3,7 +3,7 @@ from schemas.user import UserOut
|
|||||||
|
|
||||||
|
|
||||||
class LoginRequest(BaseModel):
|
class LoginRequest(BaseModel):
|
||||||
client: str | None = None # "manager" | "waiter"; None = the current manager UI (v1 rules)
|
client: str | None = None # "manager" | "waiter" | "terminal" (paired device); None = the current manager UI (v1 rules)
|
||||||
username: str | None = None
|
username: str | None = None
|
||||||
user_id: int | None = None # waiter picks their name (when the username isn't required)
|
user_id: int | None = None # waiter picks their name (when the username isn't required)
|
||||||
pin: str | None = None
|
pin: str | None = None
|
||||||
|
|||||||
@@ -85,6 +85,8 @@ def _venue_time():
|
|||||||
i18n.invalidate()
|
i18n.invalidate()
|
||||||
from core import sessions
|
from core import sessions
|
||||||
sessions.clear_cache()
|
sessions.clear_cache()
|
||||||
|
from routers import devices
|
||||||
|
devices.reset_rate_limit()
|
||||||
from core.modules import state as module_state
|
from core.modules import state as module_state
|
||||||
module_state.invalidate() # module enablement is cached; each test starts from the DB
|
module_state.invalidate() # module enablement is cached; each test starts from the DB
|
||||||
|
|
||||||
|
|||||||
@@ -49,3 +49,14 @@ def test_every_marker_key_exists():
|
|||||||
if kind in ("require", "require_any"):
|
if kind in ("require", "require_any"):
|
||||||
bad |= set(keys) - known
|
bad |= set(keys) - known
|
||||||
assert bad == set(), f"unknown permission keys in route markers: {sorted(bad)}"
|
assert bad == set(), f"unknown permission keys in route markers: {sorted(bad)}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_require_device_names_a_device_app():
|
||||||
|
from core.modules.registry import registry
|
||||||
|
apps = {k for k, m in registry().items() if m.device_app}
|
||||||
|
bad = set()
|
||||||
|
for r in _routes():
|
||||||
|
for kind, *args in _markers(r.dependant):
|
||||||
|
if kind == "require_device" and args[0] != "*" and args[0] not in apps:
|
||||||
|
bad.add(args[0])
|
||||||
|
assert bad == set(), f"require_device() with modules that aren't device apps: {sorted(bad)}"
|
||||||
|
|||||||
@@ -0,0 +1,298 @@
|
|||||||
|
"""Devices, pairing, device tokens, limits, scope (plan step 1.8, APPS_PLATFORM D-8, §6.3)."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from conftest import TEST_PIN
|
||||||
|
from core.modules import entitlements as E
|
||||||
|
|
||||||
|
NOW = datetime(2026, 11, 12, 12, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def install(**modules):
|
||||||
|
"""Licensed with exactly these modules (+ core/free tier)."""
|
||||||
|
E.set_current(E.compute({"v": 2, "site_id": "site-A", "modules": modules}, True, False, NOW, False), notify=False)
|
||||||
|
|
||||||
|
|
||||||
|
def err(r):
|
||||||
|
return r.json()["error"]["code"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def owner_h(make_user, login):
|
||||||
|
return login(make_user(role="owner"))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def pair(client, owner_h):
|
||||||
|
"""pair(app_key, name=..., **fields) -> (device_token, device json from the manager API)."""
|
||||||
|
def _pair(app_key, name=None, **fields):
|
||||||
|
req = client.post("/api/devices/pair-request")
|
||||||
|
assert req.status_code == 201, req.text
|
||||||
|
code, secret = req.json()["code"], req.json()["secret"]
|
||||||
|
r = client.post("/api/devices", headers=owner_h,
|
||||||
|
json={"code": code, "app_key": app_key, "name": name or f"{app_key} screen", **fields})
|
||||||
|
if r.status_code != 201:
|
||||||
|
return None, r
|
||||||
|
poll = client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})
|
||||||
|
assert poll.status_code == 200 and poll.json()["status"] == "paired", poll.text
|
||||||
|
return poll.json()["device_token"], r
|
||||||
|
return _pair
|
||||||
|
|
||||||
|
|
||||||
|
def dev_h(token, extra=None):
|
||||||
|
return {"X-Xenia-Device": token, **(extra or {})}
|
||||||
|
|
||||||
|
|
||||||
|
# ── pairing flow ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_pairing_flow(client, owner_h):
|
||||||
|
req = client.post("/api/devices/pair-request", headers={"User-Agent": "KDS-Box"})
|
||||||
|
assert req.status_code == 201
|
||||||
|
body = req.json()
|
||||||
|
code, secret = body["code"], body["secret"]
|
||||||
|
assert len(code) == 6 and set(code) <= set("ABCDEFGHJKLMNPQRSTUVWXYZ23456789")
|
||||||
|
|
||||||
|
# only the requester (who holds the secret) may poll
|
||||||
|
assert err(client.get(f"/api/devices/pair-request/{code}")) == "device.pair_code_invalid"
|
||||||
|
assert err(client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": "nope"})) \
|
||||||
|
== "device.pair_code_invalid"
|
||||||
|
poll = client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})
|
||||||
|
assert poll.json()["status"] == "pending"
|
||||||
|
|
||||||
|
# the manager types the code (case and dashes don't matter)
|
||||||
|
typed = f"{code[:3].lower()}-{code[3:]}"
|
||||||
|
r = client.post("/api/devices", headers=owner_h,
|
||||||
|
json={"code": typed, "app_key": "kds", "name": "Bar KDS", "config": {"prep_zone_id": 2}})
|
||||||
|
assert r.status_code == 201, r.text
|
||||||
|
d = r.json()
|
||||||
|
assert d["claimed"] is False and d["user_agent"] == "KDS-Box" and d["effective_login_mode"] == "pin"
|
||||||
|
# a code is used once
|
||||||
|
assert err(client.post("/api/devices", headers=owner_h, json={"code": code, "app_key": "kds", "name": "x"})) \
|
||||||
|
== "device.pair_code_invalid"
|
||||||
|
|
||||||
|
poll = client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})
|
||||||
|
assert poll.status_code == 200
|
||||||
|
token = poll.json()["device_token"]
|
||||||
|
assert poll.json()["device"]["config"] == {"prep_zone_id": 2} and poll.json()["device"]["app_status"] == "ok"
|
||||||
|
# the token is handed out exactly once
|
||||||
|
assert err(client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})) \
|
||||||
|
== "device.pair_code_invalid"
|
||||||
|
|
||||||
|
me = client.get("/api/devices/me", headers=dev_h(token))
|
||||||
|
assert me.status_code == 200 and me.json()["name"] == "Bar KDS" and me.json()["app_key"] == "kds"
|
||||||
|
listed = client.get("/api/devices", headers=owner_h).json()
|
||||||
|
assert [x["name"] for x in listed] == ["Bar KDS"] and listed[0]["claimed"] and listed[0]["last_seen_at"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_token_and_no_token(client):
|
||||||
|
assert err(client.get("/api/devices/me")) == "device.not_paired"
|
||||||
|
assert err(client.get("/api/devices/me", headers=dev_h("forged"))) == "device.not_paired"
|
||||||
|
|
||||||
|
|
||||||
|
def test_pair_request_rate_limited(client):
|
||||||
|
from routers import devices
|
||||||
|
for _ in range(devices.RATE_PER_IP):
|
||||||
|
assert client.post("/api/devices/pair-request").status_code == 201
|
||||||
|
r = client.post("/api/devices/pair-request")
|
||||||
|
assert r.status_code == 429 and err(r) == "device.pair_rate_limited"
|
||||||
|
|
||||||
|
|
||||||
|
def test_device_management_needs_key(client, make_user, login):
|
||||||
|
chef_h = login(make_user(role="chef"))
|
||||||
|
assert err(client.get("/api/devices", headers=chef_h)) == "access.denied"
|
||||||
|
|
||||||
|
|
||||||
|
def test_approve_validation(client, owner_h, pair):
|
||||||
|
_, r = pair("reports")
|
||||||
|
assert err(r) == "device.not_an_app"
|
||||||
|
_, r = pair("signage", login_mode="pin")
|
||||||
|
assert err(r) == "device.login_mode_invalid"
|
||||||
|
_, r = pair("kds", linked_device_id=999)
|
||||||
|
assert err(r) == "device.link_invalid"
|
||||||
|
|
||||||
|
|
||||||
|
def test_rename_mode_link(client, owner_h, pair):
|
||||||
|
_, pos = pair("pos_counter", "Counter 1")
|
||||||
|
_, disp = pair("customer_display", "Counter 1 display")
|
||||||
|
pid, did = pos.json()["id"], disp.json()["id"]
|
||||||
|
r = client.patch(f"/api/devices/{did}", headers=owner_h, json={"linked_device_id": pid, "name": "Front display"})
|
||||||
|
assert r.status_code == 200 and r.json()["linked_device_id"] == pid and r.json()["name"] == "Front display"
|
||||||
|
assert err(client.patch(f"/api/devices/{did}", headers=owner_h, json={"linked_device_id": did})) == "device.link_invalid"
|
||||||
|
r = client.patch(f"/api/devices/{pid}", headers=owner_h, json={"login_mode": "tap"})
|
||||||
|
assert r.json()["login_mode"] == "tap" and r.json()["effective_login_mode"] == "tap"
|
||||||
|
r = client.patch(f"/api/devices/{pid}", headers=owner_h, json={"login_mode": ""})
|
||||||
|
assert r.json()["login_mode"] is None and r.json()["effective_login_mode"] == "pin"
|
||||||
|
assert client.get(f"/api/devices/{did}", headers=owner_h).json()["effective_login_mode"] == "none"
|
||||||
|
assert err(client.get("/api/devices/4242", headers=owner_h)) == "device.not_found"
|
||||||
|
|
||||||
|
|
||||||
|
# ── limits (D-6) ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_third_kds_refused_with_limit_two(client, owner_h, pair): # "done when" 1
|
||||||
|
install(ordering={}, kds={"limits": {"devices": 2}})
|
||||||
|
t1, _ = pair("kds", "KDS 1")
|
||||||
|
t2, _ = pair("kds", "KDS 2")
|
||||||
|
assert t1 and t2
|
||||||
|
_, r = pair("kds", "KDS 3")
|
||||||
|
assert r.status_code == 402
|
||||||
|
assert r.json()["error"] == {"code": "license.limit_reached",
|
||||||
|
"params": {"module": "kds", "limit": "devices", "max": 2},
|
||||||
|
"message": "License limit reached for kds devices (2)."}
|
||||||
|
# revoking one frees its place
|
||||||
|
first = client.get("/api/devices", headers=owner_h).json()[0]["id"]
|
||||||
|
client.post(f"/api/devices/{first}/revoke", headers=owner_h)
|
||||||
|
t3, r = pair("kds", "KDS 3")
|
||||||
|
assert t3, r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_downgrade_blocks_newest_devices(client, owner_h, pair):
|
||||||
|
install(ordering={}, kds={"limits": {"devices": 3}})
|
||||||
|
tokens = [pair("kds", f"KDS {i}")[0] for i in range(3)]
|
||||||
|
install(ordering={}, kds={"limits": {"devices": 2}})
|
||||||
|
assert client.get("/api/devices/me", headers=dev_h(tokens[1])).status_code == 200
|
||||||
|
r = client.get("/api/devices/me", headers=dev_h(tokens[2]))
|
||||||
|
assert r.status_code == 402 and err(r) == "license.limit_reached"
|
||||||
|
|
||||||
|
|
||||||
|
def test_unlicensed_app_cannot_be_paired(client, pair):
|
||||||
|
install(ordering={})
|
||||||
|
_, r = pair("kds")
|
||||||
|
assert r.status_code == 402 and r.json()["error"]["params"] == {"module": "kds"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_disabled_app_reports_status_on_me(client, owner_h, pair, make_user, login):
|
||||||
|
token, _ = pair("kds")
|
||||||
|
admin_h = login(make_user(role="superadmin"))
|
||||||
|
assert client.put("/api/platform/modules/kds", headers=admin_h, json={"enabled": False}).status_code == 200
|
||||||
|
me = client.get("/api/devices/me", headers=dev_h(token))
|
||||||
|
assert me.status_code == 200 and me.json()["app_status"] == "module.disabled"
|
||||||
|
|
||||||
|
|
||||||
|
# ── revoke ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_revoked_device_next_call_fails(client, owner_h, pair, make_user): # "done when" 2
|
||||||
|
token, r = pair("kds")
|
||||||
|
chef = make_user(role="chef")
|
||||||
|
s = client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id, "pin": TEST_PIN})
|
||||||
|
user_h = {"Authorization": f"Bearer {s.json()['access_token']}"}
|
||||||
|
assert client.get("/api/kds/orders", headers=dev_h(token, user_h)).status_code == 200
|
||||||
|
|
||||||
|
assert client.post(f"/api/devices/{r.json()['id']}/revoke", headers=owner_h).json()["revoked_at"]
|
||||||
|
for resp in (client.get("/api/devices/me", headers=dev_h(token)),
|
||||||
|
client.get("/api/kds/orders", headers=dev_h(token, user_h))):
|
||||||
|
assert resp.status_code == 401 and err(resp) == "device.revoked"
|
||||||
|
# its user session ended too, and it's gone from the default list
|
||||||
|
assert err(client.get("/api/auth/me", headers=user_h)) == "auth.session_ended"
|
||||||
|
assert client.get("/api/devices", headers=owner_h).json() == []
|
||||||
|
assert len(client.get("/api/devices?include_revoked=true", headers=owner_h).json()) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_reassign_checks_limit_and_ends_sessions(client, owner_h, pair, make_user):
|
||||||
|
install(ordering={}, kds={"limits": {"devices": 1}}, pos_counter={"limits": {"devices": 1}})
|
||||||
|
k_token, k = pair("kds")
|
||||||
|
_, p = pair("pos_counter")
|
||||||
|
r = client.post(f"/api/devices/{p.json()['id']}/reassign", headers=owner_h, json={"app_key": "kds"})
|
||||||
|
assert err(r) == "license.limit_reached"
|
||||||
|
|
||||||
|
chef = make_user(role="chef")
|
||||||
|
s = client.post("/api/auth/login", headers=dev_h(k_token), json={"client": "terminal", "user_id": chef.id, "pin": TEST_PIN})
|
||||||
|
user_h = {"Authorization": f"Bearer {s.json()['access_token']}"}
|
||||||
|
client.post(f"/api/devices/{p.json()['id']}/revoke", headers=owner_h)
|
||||||
|
r = client.post(f"/api/devices/{k.json()['id']}/reassign", headers=owner_h, json={"app_key": "pos_counter"})
|
||||||
|
assert r.status_code == 200 and r.json()["app_key"] == "pos_counter"
|
||||||
|
assert err(client.get("/api/auth/me", headers=dev_h(k_token, user_h))) == "auth.session_ended"
|
||||||
|
assert client.get("/api/devices/me", headers=dev_h(k_token)).json()["app_key"] == "pos_counter"
|
||||||
|
|
||||||
|
|
||||||
|
# ── scope (D-8) ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_signage_token_cannot_call_orders(client, owner_h, pair): # "done when" 3
|
||||||
|
token, _ = pair("signage")
|
||||||
|
assert client.get("/api/orders/", headers=owner_h).status_code == 200 # control: no device
|
||||||
|
r = client.get("/api/orders/", headers=dev_h(token, owner_h))
|
||||||
|
assert r.status_code == 403 and r.json()["error"]["params"] == {"app": "signage", "key": "ordering"}
|
||||||
|
r = client.get("/api/orders/", headers=dev_h(token))
|
||||||
|
assert r.status_code == 403 and err(r) == "device.out_of_scope"
|
||||||
|
|
||||||
|
|
||||||
|
def test_keyed_core_route_out_of_device_scope(client, owner_h, pair):
|
||||||
|
token, _ = pair("kds")
|
||||||
|
assert client.get("/api/auth/sessions", headers=owner_h).status_code == 200
|
||||||
|
r = client.get("/api/auth/sessions", headers=dev_h(token, owner_h))
|
||||||
|
assert r.status_code == 403 and r.json()["error"]["params"] == {"app": "kds", "key": "core.staff.manage"}
|
||||||
|
assert client.get("/api/auth/me", headers=dev_h(token, owner_h)).status_code == 200 # core basics stay
|
||||||
|
|
||||||
|
|
||||||
|
def test_require_device_with_app():
|
||||||
|
from core.access.context import in_scope, module_in_scope
|
||||||
|
assert in_scope("kds", "kds.bump") and not in_scope("kds", "ordering.orders.cancel")
|
||||||
|
assert in_scope("pos_counter", "ordering.orders.cancel") and module_in_scope("pos_counter", "ordering")
|
||||||
|
assert not module_in_scope("signage", "ordering") and module_in_scope("signage", "signage")
|
||||||
|
|
||||||
|
|
||||||
|
# ── device login ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_terminal_login_needs_a_device(client, make_user): # tap without a device is refused
|
||||||
|
chef = make_user(role="chef")
|
||||||
|
r = client.post("/api/auth/login", json={"client": "terminal", "user_id": chef.id})
|
||||||
|
assert r.status_code == 401 and err(r) == "device.not_paired"
|
||||||
|
r = client.post("/api/auth/login", headers=dev_h("forged"), json={"client": "terminal", "user_id": chef.id})
|
||||||
|
assert err(r) == "device.not_paired"
|
||||||
|
|
||||||
|
|
||||||
|
def test_terminal_modes(client, owner_h, pair, make_user):
|
||||||
|
token, r = pair("kds", login_mode="tap")
|
||||||
|
chef, waiter = make_user(role="chef"), make_user(role="waiter")
|
||||||
|
s = client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id})
|
||||||
|
assert s.status_code == 200, s.text
|
||||||
|
assert err(client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": waiter.id})) \
|
||||||
|
== "auth.client_not_allowed"
|
||||||
|
|
||||||
|
client.patch(f"/api/devices/{r.json()['id']}", headers=owner_h, json={"login_mode": "pin"})
|
||||||
|
assert err(client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id})) \
|
||||||
|
== "auth.login_mode_not_allowed"
|
||||||
|
r2 = client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id, "pin": "0000"})
|
||||||
|
assert err(r2) == "auth.invalid_credentials"
|
||||||
|
|
||||||
|
sig, _ = pair("signage")
|
||||||
|
r3 = client.post("/api/auth/login", headers=dev_h(sig), json={"client": "terminal", "user_id": chef.id})
|
||||||
|
assert r3.json()["error"] == {"code": "auth.login_mode_not_allowed", "params": {"mode": "none"},
|
||||||
|
"message": "This way of logging in isn't enabled (none)."}
|
||||||
|
|
||||||
|
users = client.get("/api/devices/me/users", headers=dev_h(token)).json()
|
||||||
|
assert chef.id in {u["id"] for u in users} and waiter.id not in {u["id"] for u in users}
|
||||||
|
assert client.get("/api/devices/me/users", headers=dev_h(sig)).json() == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_site_default_login_mode(client, owner_h, pair, make_user, login):
|
||||||
|
admin_h = login(make_user(role="superadmin"))
|
||||||
|
assert client.put("/api/settings/auth.default_login_mode", headers=admin_h, json={"value": "tap"}).status_code == 200
|
||||||
|
token, r = pair("kds")
|
||||||
|
assert r.json()["effective_login_mode"] == "tap"
|
||||||
|
chef = make_user(role="chef")
|
||||||
|
assert client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id}).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_terminal_session_bound_to_device(client, pair, make_user):
|
||||||
|
token, _ = pair("kds")
|
||||||
|
other, _ = pair("kds", "other")
|
||||||
|
chef = make_user(role="chef")
|
||||||
|
s = client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id, "pin": TEST_PIN})
|
||||||
|
user_h = {"Authorization": f"Bearer {s.json()['access_token']}"}
|
||||||
|
assert client.get("/api/kds/orders", headers=dev_h(token, user_h)).status_code == 200
|
||||||
|
r = client.get("/api/kds/orders", headers=user_h) # header dropped
|
||||||
|
assert r.status_code == 401 and err(r) == "device.required"
|
||||||
|
assert err(client.get("/api/kds/orders", headers=dev_h(other, user_h))) == "device.required" # another device
|
||||||
|
|
||||||
|
# a new login on the same device replaces the previous user
|
||||||
|
chef2 = make_user(role="chef")
|
||||||
|
client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef2.id, "pin": TEST_PIN})
|
||||||
|
assert err(client.get("/api/auth/me", headers=dev_h(token, user_h))) == "auth.session_ended"
|
||||||
|
|
||||||
|
|
||||||
|
def test_waiter_tap_still_needs_device(client, make_user, login):
|
||||||
|
admin_h = login(make_user(role="superadmin"))
|
||||||
|
client.put("/api/settings/auth.waiter_login_mode", headers=admin_h, json={"value": "tap"})
|
||||||
|
w = make_user(role="waiter")
|
||||||
|
assert err(client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id})) == "auth.mode_needs_device"
|
||||||
@@ -59,6 +59,9 @@ def _m(key="x", **kw):
|
|||||||
([_m("a", routers=(Mount("routers.tabs", "/a"),)), _m("b", routers=(Mount("routers.tabs", "/b"),))], "already mounted"),
|
([_m("a", routers=(Mount("routers.tabs", "/a"),)), _m("b", routers=(Mount("routers.tabs", "/b"),))], "already mounted"),
|
||||||
([_m("x", device_app=DeviceApp())], "only for kind='app'"),
|
([_m("x", device_app=DeviceApp())], "only for kind='app'"),
|
||||||
([_m("x"), _m("x")], "duplicate key"),
|
([_m("x"), _m("x")], "duplicate key"),
|
||||||
|
([_m("x", kind="app", device_app=DeviceApp(login_modes=("pin",)))], "must declare the permission 'x.access'"),
|
||||||
|
([_m("x", kind="app", device_app=DeviceApp(login_modes=("face",)))], "login_modes must be"),
|
||||||
|
([_m("x", kind="app", device_app=DeviceApp(login_modes=()))], "login_modes must be"),
|
||||||
([_m("Bad-Key")], "must match"),
|
([_m("Bad-Key")], "must match"),
|
||||||
([_m("x", workers=("no_colon",))], "package.module:function"),
|
([_m("x", workers=("no_colon",))], "package.module:function"),
|
||||||
([_m("x", settings=(SettingDef("x.e", "c", "d", type="enum", choices=("a", "b")),))], "not in choices"),
|
([_m("x", settings=(SettingDef("x.e", "c", "d", type="enum", choices=("a", "b")),))], "not in choices"),
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
# :443 waiter.* / manager.* / bare IP → https (needs certs/cert.pem + key.pem)
|
# :443 waiter.* / manager.* / bare IP → https (needs certs/cert.pem + key.pem)
|
||||||
# :4443 → manager over https
|
# :4443 → manager over https
|
||||||
# :8443 → native app over TLS (backend-managed key, pinned), LAN only
|
# :8443 → native app over TLS (backend-managed key, pinned), LAN only
|
||||||
|
# /api/devices/pair-request on :443 → LAN only (device pairing, D-8)
|
||||||
#
|
#
|
||||||
# Every proxied location forwards WebSocket upgrades (/api/ws/connect) and
|
# Every proxied location forwards WebSocket upgrades (/api/ws/connect) and
|
||||||
# disables buffering (SSE), otherwise live events never reach phones / KDS.
|
# disables buffering (SSE), otherwise live events never reach phones / KDS.
|
||||||
@@ -103,6 +104,24 @@ server {
|
|||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
|
location /api/devices/pair-request {
|
||||||
|
allow 10.0.0.0/8;
|
||||||
|
allow 172.16.0.0/12;
|
||||||
|
allow 192.168.0.0/16;
|
||||||
|
allow 127.0.0.0/8;
|
||||||
|
allow fc00::/7;
|
||||||
|
allow fe80::/10;
|
||||||
|
allow ::1;
|
||||||
|
deny all;
|
||||||
|
proxy_pass http://backend:8000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://waiter_pwa:80;
|
proxy_pass http://waiter_pwa:80;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
@@ -127,6 +146,24 @@ server {
|
|||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
|
location /api/devices/pair-request {
|
||||||
|
allow 10.0.0.0/8;
|
||||||
|
allow 172.16.0.0/12;
|
||||||
|
allow 192.168.0.0/16;
|
||||||
|
allow 127.0.0.0/8;
|
||||||
|
allow fc00::/7;
|
||||||
|
allow fe80::/10;
|
||||||
|
allow ::1;
|
||||||
|
deny all;
|
||||||
|
proxy_pass http://backend:8000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://manager_dashboard:80;
|
proxy_pass http://manager_dashboard:80;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
@@ -151,6 +188,24 @@ server {
|
|||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
|
location /api/devices/pair-request {
|
||||||
|
allow 10.0.0.0/8;
|
||||||
|
allow 172.16.0.0/12;
|
||||||
|
allow 192.168.0.0/16;
|
||||||
|
allow 127.0.0.0/8;
|
||||||
|
allow fc00::/7;
|
||||||
|
allow fe80::/10;
|
||||||
|
allow ::1;
|
||||||
|
deny all;
|
||||||
|
proxy_pass http://backend:8000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass http://backend:8000;
|
proxy_pass http://backend:8000;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|||||||
Reference in New Issue
Block a user