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>
169 lines
5.5 KiB
Python
169 lines
5.5 KiB
Python
"""Which modules are on, right now (APPS_PLATFORM D-4, D-19, §5.3).
|
||
|
||
effective(m) = entitled(m) and enabled(m) and every dependency of m is effective
|
||
|
||
- enabled: the site_modules table (no row = enabled). Core modules are always enabled.
|
||
- entitled: from the license (step 1.4). Until then every module is entitled.
|
||
- The enabled map is cached in memory; set_enabled() updates the cache in the same
|
||
request, so a change applies at once, with no restart. Listeners (the worker
|
||
supervisor) are told about every change.
|
||
|
||
module_required(key) is the FastAPI dependency main.py adds to each non-core router.
|
||
|
||
Agent notes:
|
||
- Always change enablement through set_enabled(), never by writing SiteModule rows,
|
||
or the cache and the workers won't follow.
|
||
- Entitlement comes from core/modules/entitlements.py (license ∪ free tier, step 1.4).
|
||
A blocked request says why: module.not_licensed (402) before module.disabled (403).
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import threading
|
||
from typing import Callable
|
||
|
||
from fastapi import Depends, Request
|
||
from sqlalchemy.orm import Session
|
||
|
||
from core.errors import XeniaError
|
||
from core.modules.registry import registry
|
||
from database import get_db
|
||
|
||
logger = logging.getLogger("xenia.modules")
|
||
|
||
_lock = threading.Lock()
|
||
_enabled_cache: dict[str, bool] | None = None
|
||
_listeners: list[Callable[[frozenset[str]], None]] = []
|
||
|
||
|
||
def invalidate() -> None:
|
||
global _enabled_cache
|
||
with _lock:
|
||
_enabled_cache = None
|
||
|
||
|
||
def add_listener(fn: Callable[[frozenset[str]], None]) -> None:
|
||
"""fn(effective_keys) is called after every enablement change."""
|
||
_listeners.append(fn)
|
||
|
||
|
||
def _load(db: Session) -> dict[str, bool]:
|
||
from models.site_module import SiteModule
|
||
rows = {r.key: bool(r.enabled) for r in db.query(SiteModule).all()}
|
||
return {k: (True if m.kind == "core" else rows.get(k, True)) for k, m in registry().items()}
|
||
|
||
|
||
def enabled_map(db: Session | None = None) -> dict[str, bool]:
|
||
global _enabled_cache
|
||
with _lock:
|
||
cached = _enabled_cache
|
||
if cached is not None:
|
||
return cached
|
||
if db is None:
|
||
from database import SessionLocal
|
||
own = SessionLocal()
|
||
try:
|
||
loaded = _load(own)
|
||
finally:
|
||
own.close()
|
||
else:
|
||
loaded = _load(db)
|
||
with _lock:
|
||
_enabled_cache = loaded
|
||
return loaded
|
||
|
||
|
||
def _entitled(key: str) -> bool:
|
||
from core.modules import entitlements
|
||
return entitlements.current().entitled(key)
|
||
|
||
|
||
def notify() -> None:
|
||
"""Tell listeners (the worker supervisor) the effective set may have changed,
|
||
e.g. after the license was re-evaluated."""
|
||
eff = effective_set()
|
||
for fn in list(_listeners):
|
||
try:
|
||
fn(eff)
|
||
except Exception:
|
||
logger.exception("module listener failed")
|
||
|
||
|
||
def effective_set(db: Session | None = None) -> frozenset[str]:
|
||
reg = registry()
|
||
enabled = enabled_map(db)
|
||
memo: dict[str, bool] = {}
|
||
|
||
def eff(k: str) -> bool:
|
||
if k not in memo:
|
||
memo[k] = _entitled(k) and enabled.get(k, True) and all(eff(d) for d in reg[k].depends)
|
||
return memo[k]
|
||
|
||
return frozenset(k for k in reg if eff(k))
|
||
|
||
|
||
def is_effective(key: str, db: Session | None = None) -> bool:
|
||
return key in effective_set(db)
|
||
|
||
|
||
def set_enabled(db: Session, key: str, enabled: bool, user_id: int | None = None) -> frozenset[str]:
|
||
"""Enable/disable a module (commits). Returns the new effective set."""
|
||
from models.site_module import SiteModule
|
||
global _enabled_cache
|
||
reg = registry()
|
||
if key not in reg:
|
||
raise XeniaError("module.unknown", module=key)
|
||
if not reg[key].can_disable and not enabled:
|
||
raise XeniaError("module.cannot_disable", module=key)
|
||
row = db.get(SiteModule, key)
|
||
if row is None:
|
||
row = SiteModule(key=key)
|
||
db.add(row)
|
||
row.enabled = enabled
|
||
row.updated_by = user_id if user_id else None
|
||
db.commit()
|
||
loaded = _load(db)
|
||
with _lock:
|
||
_enabled_cache = loaded
|
||
eff = effective_set(db)
|
||
logger.info("module.%s key=%s by_user=%s effective=%d", "enabled" if enabled else "disabled", key, user_id, len(eff))
|
||
for fn in list(_listeners):
|
||
try:
|
||
fn(eff)
|
||
except Exception:
|
||
logger.exception("module listener failed")
|
||
return eff
|
||
|
||
|
||
def blocked_error(key: str, db: Session | None = None) -> XeniaError:
|
||
"""Why `key` isn't effective: not licensed (itself or a dependency) beats turned off."""
|
||
reg = registry()
|
||
seen, stack = set(), [key]
|
||
while stack:
|
||
k = stack.pop()
|
||
if k in seen:
|
||
continue
|
||
seen.add(k)
|
||
if not _entitled(k):
|
||
return XeniaError("module.not_licensed", module=k)
|
||
stack.extend(reg[k].depends)
|
||
enabled = enabled_map(db)
|
||
off = next((k for k in [key, *sorted(seen - {key})] if not enabled.get(k, True)), key)
|
||
return XeniaError("module.disabled", module=off)
|
||
|
||
|
||
def module_required(key: str):
|
||
"""FastAPI dependency: the endpoint answers `module.disabled` unless the module is effective."""
|
||
if key not in registry():
|
||
raise ValueError(f"module_required: unknown module {key!r}")
|
||
|
||
def _check(request: Request, db: Session = Depends(get_db)) -> None:
|
||
if not is_effective(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}"
|
||
return _check
|