Files
xenia-pos-local/local_backend/core/modules/registry.py
T
bonaminandClaude Opus 5.5 91da3aeb27 feat(backend): paired devices with device tokens, scope, limits and terminal login
Platform v2 step 1.8 (APPS_PLATFORM D-8, section 6.3).
- devices + device_pair_requests tables (Alembic 0007_devices); sessions.device_id
  becomes a FK. Device tokens are stored as sha256 only; the plain token is generated
  when the device picks it up, once.
- /api/devices: pair-request (public, rate-limited, LAN-only in the proxy) + polling
  with a per-request secret; manager approve/list/rename/config/login mode/link/
  reassign/revoke (key core.devices.manage); the device's own /me and /me/users.
- Approving or reassigning checks the app's licence and its `devices` limit
  (license.limit_reached); after a downgrade the newest devices beyond the limit are
  refused, the oldest keep working.
- X-Xenia-Device: core/access/context.py loads the device (device.not_paired /
  device.revoked), tags logs with device=, throttles last_seen_at. check() and
  module_required() apply the app's scope (device.out_of_scope); require_device(app).
- POST /api/auth/login {client: "terminal"} uses the device's login mode (device ->
  auth.default_login_mode -> app's first mode); tap/none only here. The session is
  bound to the device (device.required without its header) and replaces the
  device's previous user. Revoke/reassign end the device's sessions.
- Registry: a device app with user logins must declare '<app>.access'.
- Proxy: location /api/devices/pair-request LAN-only on the :443 servers (both copies).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:44:40 +02:00

145 lines
6.0 KiB
Python

"""Loads and validates every module manifest (APPS_PLATFORM §4.1).
registry() returns the validated, immutable catalogue, built once per process from
local_backend/modules/<key>/manifest.py. Any problem raises ManifestError at startup,
so a broken manifest never reaches a running site.
Checks: key format and folder name, kind, unique keys, dependencies exist and have no
cycles, permission keys prefixed by their module and unique, roles exist, limit keys
unique per module, setting keys unique across modules, every Mount importable and
claimed by exactly one module, device_app only on apps, workers given as "mod:func".
"""
from __future__ import annotations
import importlib
import pkgutil
import re
from functools import lru_cache
from pathlib import Path
from core.modules.model import Module
MODULES_DIR = Path(__file__).resolve().parents[2] / "modules"
_KEY = re.compile(r"^[a-z][a-z0-9_]*$")
_KINDS = {"core", "feature", "app", "integration"}
_LOGIN_MODES = {"pin", "password", "tap", "none"}
class ManifestError(ValueError):
pass
def _discover() -> list[Module]:
found = []
for info in pkgutil.iter_modules([str(MODULES_DIR)]):
if not info.ispkg:
continue
mod = importlib.import_module(f"modules.{info.name}.manifest")
m = getattr(mod, "MODULE", None)
if not isinstance(m, Module):
raise ManifestError(f"modules/{info.name}/manifest.py must define MODULE = Module(...)")
if m.key != info.name:
raise ManifestError(f"modules/{info.name}: MODULE.key is {m.key!r}, must equal the folder name")
found.append(m)
return found
def validate(modules: list[Module], check_imports: bool = True) -> dict[str, Module]:
from roles import VALID_ROLES
by_key: dict[str, Module] = {}
perm_keys: set[str] = set()
setting_keys: dict[str, str] = {}
mounts: dict[tuple[str, str], str] = {}
for m in modules:
where = f"module {m.key!r}"
if not _KEY.match(m.key):
raise ManifestError(f"{where}: key must match {_KEY.pattern}")
if m.key in by_key:
raise ManifestError(f"{where}: duplicate key")
if m.kind not in _KINDS:
raise ManifestError(f"{where}: kind {m.kind!r} not in {sorted(_KINDS)}")
if m.device_app and m.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:
if not p.key.startswith(m.key + "."):
raise ManifestError(f"{where}: permission {p.key!r} must start with {m.key + '.'!r}")
if p.key in perm_keys:
raise ManifestError(f"{where}: duplicate permission {p.key!r}")
perm_keys.add(p.key)
bad = set(p.roles) - (set(VALID_ROLES) - {"superadmin"})
if bad:
raise ManifestError(f"{where}: permission {p.key!r} has unknown roles {sorted(bad)} "
"(superadmin is implicit and never listed)")
limit_keys = [lim.key for lim in m.limits]
if len(limit_keys) != len(set(limit_keys)):
raise ManifestError(f"{where}: duplicate limit keys")
for sd in m.settings:
if sd.key in setting_keys:
raise ManifestError(f"{where}: setting {sd.key!r} already declared by {setting_keys[sd.key]!r}")
if sd.type == "enum" and sd.default not in sd.choices:
raise ManifestError(f"{where}: setting {sd.key!r} default not in choices")
setting_keys[sd.key] = m.key
for mt in m.routers:
ident = (mt.module, mt.attr)
if ident in mounts:
raise ManifestError(f"{where}: router {mt.module}.{mt.attr} already mounted by {mounts[ident]!r}")
mounts[ident] = m.key
if check_imports:
try:
obj = getattr(importlib.import_module(mt.module), mt.attr)
except (ImportError, AttributeError) as e:
raise ManifestError(f"{where}: cannot import router {mt.module}.{mt.attr}: {e}") from e
if not hasattr(obj, "routes"):
raise ManifestError(f"{where}: {mt.module}.{mt.attr} is not an APIRouter")
for w in m.workers:
if ":" not in w:
raise ManifestError(f"{where}: worker {w!r} must be 'package.module:function'")
by_key[m.key] = m
for m in modules:
for d in m.depends:
if d not in by_key:
raise ManifestError(f"module {m.key!r}: depends on unknown module {d!r}")
# cycles
state: dict[str, int] = {}
def visit(k, path):
if state.get(k) == 1:
raise ManifestError(f"dependency cycle: {' -> '.join(path + [k])}")
if state.get(k) == 2:
return
state[k] = 1
for d in by_key[k].depends:
visit(d, path + [k])
state[k] = 2
for k in by_key:
visit(k, [])
return by_key
@lru_cache(maxsize=1)
def registry() -> dict[str, Module]:
"""The validated catalogue: {key: Module}, in discovery (alphabetical) order."""
return validate(_discover())
def setting_defs() -> dict:
"""{setting key: (SettingDef, module key)} across all modules."""
return {sd.key: (sd, m.key) for m in registry().values() for sd in m.settings}
def all_permissions() -> dict:
"""{permission key: (Perm, module key)} across all modules."""
return {p.key: (p, m.key) for m in registry().values() for p in m.permissions}