Files
gabrielvidalandClaude Opus 5.5 af80c5bf27 feat(i18n): French leaves the core — a translation kind of plugin
The core speaks English only; every other language is a kind: "translation" plugin
(translation-<lang>; the French one is translation-fr in ai-agent-plugins, seeded once at start).

- plugins: kind translation (typed_manifest.parse_translation: lang, name, englishName, flag,
  locale, promptLine, ui/backend JSON dictionaries — strict, operator-only, in the fingerprint);
  a top-level "languages" field on any plugin (default ["en"]) shown on its page; seeding takes
  translation-*; plugins/translations.py reads the enabled ones (first by id wins a code).
- core/i18n: tr / langs / localized / clean_pref / effective_lang read the installed
  translations; a pick whose translation is gone reads English and is kept; browserLang records
  any base code. core/i18n_fr.py and FRENCH_LINE are gone (language_line = the plugin's promptLine).
- The owner picks a language too (users.json ownerLang, PUT /api/me {lang}; English by default).
- Public GET /api/i18n/languages and /api/i18n/{lang} (ETag/304), guest host and sign-in included.
- Coverage: backend/core/i18n_keys/{ui,backend}.json (kept by the two i18n tests,
  UPDATE_I18N_KEYS=1); a translation's page shows translated / missing / stale / placeholder
  mismatches.
- Frontend: frontend/src/i18n/fr removed; the dictionary comes from the hub, cached in
  localStorage and revalidated in the background (first boot in a language waits <= 4 s, any
  failure is English); Lang is a string; number/currency style from the translation's locale;
  LanguageSelect lists English + installed translations (hidden when none); Settings → Plugins
  has a Translations kind (tab, catalog filter, group) and a Translation section with the
  missing-strings count; mock is English only.
- Tests: test_i18n.py rewritten on a made-up translation; i18n_testkit.speaking() for the
  tests that need a second language. authz golden, openapi.json + src/generated regenerated;
  docs/plugins.md (Translations), CLAUDE.md, i18n README, docs/settings.md.

Changelog
- Added: languages are plugins — Settings → Plugins → Translations; the owner can pick a language.
- Changed: French moved to the translation-fr plugin (seeded at start: nothing changes for guests).
- Removed: the core's built-in French dictionaries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:07:22 +01:00

860 lines
39 KiB
Python

"""
The people other than the owner who can use the app — **guests** — and the
login state that proves who a browser is.
Two JSON files under ``/data``, both whole-file rewrites (temp file + rename,
like ``meta.py``):
* ``users.json`` — ``{"users": {<id>: {...}}}``. The owner is *not* in it: the
owner is whoever reaches the admin host (Authelia) or the trusted loopback,
exactly as before this file existed. A user record:
``id`` (slug), ``email``, ``name``, ``role`` (their role — authz/roles.py:
``guest`` by default, ``member``, ``viewer`` or a custom one), ``allow`` /
``deny`` (person-level permissions added to / taken from the role —
authz/policy.py; these replaced the old ``cli``, ``mcp``,
``createProjects`` (retired), ``scratchBash``, ``codeMode`` and
``computers.enabled`` switches on 2026-11-23, ``authz: 1`` marks a migrated
record), ``projects`` (``{slug: "view"|"chat"|"ship"}``), ``models``
(aliases a run may use), ``budgetUsd`` (monthly cap), ``notify``
(``{"channels": [...]}`` — ``in_app``, ``webpush``), ``bucket`` (their
address bucket, ``<name>.<bucket>.<domain>``; blank ⇒ their id),
``domain`` (a root domain of their own), ``lang`` (``auto`` |
``en`` | ``fr``), ``browserLang``, ``disabled``, ``createdAt``,
``lastLoginAt``, ``computers`` (``{"max"}`` — how many computers of their
own: users/computers.py), ``autoFresh``, ``claude`` once they connected
their own Claude login (:meth:`UsersStore.set_claude`), ``apps`` and
``clarifier`` (the clarifier fields they set themselves — runs/clarifier.py).
An older record may still carry ``tools`` (``{groups, pro, budgetUsd,
matomoSites}``, the paid tool groups before they became managed plugins,
2026-11-26): read once by ``plugins/carryover_tools`` (``tool_grants``,
``matomo_sites``), never written again.
``deleted`` keeps the id (and who it was) of every deleted user, so a
new user never gets one back: conversations stay ``owner: <id>``, and the
guest's Claude login dir and Gitea account are named after it.
Beside ``users``, ``guestDefaults`` holds what the owner sets for every
guest at once: ``sharedSkills`` (the owner's skills every guest run gets, as a
generated Claude Code plugin — ``name`` for one of the lab repo's skills,
``<project>/<name>`` for a project's), ``computerLimits``, what the Claude
proxy holds a guest's computers to (:data:`DEFAULT_COMPUTER_LIMITS`). A
``cronLimits`` left there by a hub from before 2026-11-28 (how many
scheduled jobs of their own a guest may have — now the ``cron-jobs``
plugin's grant fields and settings) is only read by its carry-over
(:meth:`UsersStore.legacy_cron_limits`). A
``promptShortcuts`` left there by a hub from before settings v4 (the old
starting shortcuts) is only read by the prompt-shortcuts carry-over
(:meth:`UsersStore.legacy_guest_shortcuts`). A ``newProjects`` left there
by a hub from before 2026-11-27 (the core's copy of the New project policy,
now the ``new-project`` plugin's settings) is only read by the new-project
carry-over and as ``users/domains.default_domain``'s last fallback
(:meth:`UsersStore.legacy_new_projects`).
* ``auth.json`` — ``{"links": {...}, "sessions": {...}}``. One-time login
links (sent by mail) and browser sessions. Only **sha256 hashes** of the
tokens are stored: a leaked file can't be replayed.
"""
from __future__ import annotations
import datetime
import hashlib
import hmac
import json
import os
import pathlib
import re
import secrets
import threading
import time
from core.i18n import clean_pref, effective_lang, is_code
DEFAULT_ROLE = "guest"
LEVELS = ("view", "chat", "ship")
DEFAULT_MODELS = ("opus", "sonnet", "haiku")
DEFAULT_BUDGET_USD = float(os.environ.get("GUEST_DEFAULT_BUDGET_USD", "500"))
# No per-push mail any more (2026-11-01, Gabriel: a weekly recap will do
# that job); a stored "email" is dropped on load.
NOTIFY_CHANNELS = ("in_app", "webpush")
# A guest's *Auto fresh* when they never set it (Gabriel, 2026-11-05: on for
# guests — they shouldn't have to weigh a cache-cost estimate on every reply).
AUTO_FRESH_DEFAULT = True
def auto_fresh(user: dict | None) -> bool:
"""A guest's *Auto fresh*: their own pick, else on."""
v = (user or {}).get("autoFresh")
return AUTO_FRESH_DEFAULT if v is None else bool(v)
# Bash in a guest's *No project* conversation (users/runs.scratch_scope): on
# unless the owner switched it off for them (Settings → Users → <guest> →
# Access). Off, that run has no shell at all — it reads, searches and writes
# in its scratch folder. On, it can run commands on the lab like any run of
# theirs (and, until the guest sandbox is on, Bash is not confined to that
# folder — docs/security.md).
SCRATCH_BASH_DEFAULT = True
def scratch_bash(user: dict | None) -> bool:
"""May ``user``'s *No project* runs use Bash (``runs.scratch.bash``: in
the Guest role by default, an override per person — authz/)."""
from authz import policy
return policy.has(user, "runs.scratch.bash")
def code_mode(user: dict | None) -> bool:
"""May ``user`` start conversations in Claude Code's Code Mode (beta) —
the composer's *Code β* chip (``runs.codemode``)."""
from authz import policy
return policy.has(user, "runs.codemode")
LINK_TTL_S = int(os.environ.get("LOGIN_LINK_TTL_S", str(15 * 60)))
# The sign-in mail's code (AuthStore.mint_login): its length, and how many
# wrong guesses its address gets before it stops working.
CODE_DIGITS = 6
CODE_TRIES = 5
# …and how many wrong codes one address gets in CODE_MISS_WINDOW_S, whatever
# the number of mails asked for: past it their codes are refused and their
# mails carry the link alone, until the window has rolled. Five tries per
# mail alone were 150 guesses an hour, for as long as someone kept asking.
CODE_MISSES_MAX = int(os.environ.get("LOGIN_CODE_MISSES_MAX", "10"))
CODE_MISS_WINDOW_S = 24 * 3600
# A link the owner hands out (Settings → Users: copy or mail it) is an
# *invitation*: read whenever the guest gets to their inbox, so it lives for
# days, not the quarter-hour of a link the guest asked for themselves.
INVITE_TTL_S = int(os.environ.get("INVITE_LINK_TTL_S", str(3 * 24 * 3600)))
SESSION_TTL_S = int(os.environ.get("SESSION_TTL_S", str(30 * 24 * 3600)))
# The owner's "view as this guest" session (Settings → Users → Impersonate):
# long enough to test a flow, short enough not to leave the admin stuck as a
# guest on a forgotten tab.
IMPERSONATE_TTL_S = int(os.environ.get("IMPERSONATE_TTL_S", str(4 * 3600)))
# A session's expiry slides forward when used, but its file write is batched:
# only once this much of the TTL has elapsed since the last bump.
_SESSION_BUMP_S = 6 * 3600
# What a fresh install shares with guests: the ones a guest run is told to use
# (ask-form, notify-done; new-frontend-project — the New project form), and
# two read-only helpers. Missing ones are skipped.
DEFAULT_SHARED_SKILLS = ("ask-form", "notify-done", "screenshot", "page-scrape",
"new-frontend-project")
# The starting chips a new guest got before settings v4 (2026-11-07) — only
# the prompt-shortcuts carry-over reads them now, for a hub whose users.json
# never stored its own list (plugins/carryover.py).
DEFAULT_GUEST_SHORTCUTS = (
{"id": "commit", "label": "Commit", "icon": "GitCommitHorizontal",
"guideline": "Commit your changes when done (and push them if you can ship this project).",
"defaultOn": True, "shared": True},
{"id": "ask", "label": "Ask me", "icon": "MessageCircleQuestion",
"guideline": "Ask me clarifying questions with the ask-form skill before starting if anything is unclear.",
"defaultOn": False, "shared": True},
)
# (No "Notify" chip since 2026-11-06: every composed prompt ends with the
# notify line — the frontend's NOTIFY_GUIDELINE.)
_BUCKET_RE = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$")
_DOMAIN_RE = re.compile(r"^[a-z0-9-]+(?:\.[a-z0-9-]+)+$")
_SKILL_REF_RE = re.compile(r"^(?:[A-Za-z0-9][A-Za-z0-9._-]{0,63}/)?[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
_SHORTCUT_KEYS = {"id", "label", "icon", "guideline", "defaultOn", "labelOff",
"guidelineOff", "children", "triggers", "shared", "runner"}
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
def _now_iso() -> str:
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _hash(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
def norm_email(email: str) -> str:
return (email or "").strip().lower()
def valid_email(email: str) -> bool:
return bool(_EMAIL_RE.match(norm_email(email)))
def slug_for(email: str, name: str | None, taken: set[str]) -> str:
"""A readable id: the name (or the mail's local part), slugged, deduped."""
base = re.sub(r"[^a-z0-9]+", "-", (name or norm_email(email).split("@")[0])
.lower()).strip("-")[:32] or "guest"
cand, n = base, 2
while cand in taken or cand == "owner":
cand, n = f"{base}-{n}", n + 1
return cand
def clean_projects(raw) -> dict[str, str]:
"""``{slug: level}`` with unknown levels dropped (a typo grants nothing)."""
out: dict[str, str] = {}
if isinstance(raw, dict):
for slug, level in raw.items():
if isinstance(slug, str) and slug.strip() and level in LEVELS:
out[slug.strip()] = level
return out
def clean_skill_refs(raw) -> list[str]:
"""``name`` / ``<project>/<name>`` refs, deduped; anything path-like dropped."""
if not isinstance(raw, (list, tuple)):
return []
return list(dict.fromkeys(r.strip() for r in raw
if isinstance(r, str) and _SKILL_REF_RE.match(r.strip())))[:64]
def clean_shortcuts(raw) -> list[dict]:
"""Prompt shortcuts in the frontend's ``PromptShortcut`` shape — known keys
only, each one with an id, a label and a guideline. Always shared: a
guest's runs only ever land on the lab."""
out: list[dict] = []
seen: set[str] = set()
for sc in raw if isinstance(raw, (list, tuple)) else []:
if not isinstance(sc, dict):
continue
sid = str(sc.get("id") or "").strip()[:40]
if not sid or sid in seen or not str(sc.get("label") or "").strip():
continue
seen.add(sid)
clean = {k: v for k, v in sc.items() if k in _SHORTCUT_KEYS}
for k in ("label", "icon", "labelOff"):
if k in clean:
clean[k] = str(clean[k])[:80]
for k in ("guideline", "guidelineOff"):
if k in clean:
clean[k] = str(clean[k])[:2000]
for k in ("children", "triggers"):
if k in clean:
clean[k] = [str(x)[:80] for x in clean[k] if isinstance(x, str)][:32] \
if isinstance(clean[k], list) else []
clean["id"] = sid
clean["defaultOn"] = bool(clean.get("defaultOn"))
clean["shared"] = True
clean.pop("runner", None)
out.append(clean)
return out[:40]
def clean_bucket(raw) -> str:
"""A guest's address bucket: one DNS label, or blank (⇒ their id)."""
b = str(raw or "").strip().lower()
if not _BUCKET_RE.match(b):
raise ValueError(f"{b!r} isn't a valid address bucket (one DNS label)")
return b
def clean_domain(raw) -> str:
"""A guest's own root domain (``domvidal.xyz``), or blank (⇒ the shared
one). Pasted forms — a URL, a trailing dot or slash — are reduced to the
bare name."""
d = str(raw or "").strip().lower()
d = re.sub(r"^[a-z]+://", "", d).split("/")[0].rstrip(".")
if d and not _DOMAIN_RE.match(d):
raise ValueError(f"{d!r} isn't a valid domain name")
return d
# A guest's own computers (users/computers.py): how many by default once the
# owner switches it on, and what they are held to — the owner's plan
# utilization past which their calls wait (5 h / 7 d, %), the calls one
# computer may have in flight, the calls a guest may make a minute (all their
# computers), how often their tokens rotate (days), and how much of their
# transcripts the hub mirrors a month per computer (MB).
DEFAULT_MAX_COMPUTERS = 3
DEFAULT_COMPUTER_LIMITS = {"fiveHourPct": 80, "sevenDayPct": 85, "inFlight": 10,
"perMinute": 60, "rotateDays": 7, "mirrorMb": 500}
def clean_computers(raw, base: dict | None = None) -> dict:
"""A guest's ``computers``: ``{"enabled": bool, "max": 1..10}``."""
cur = {"enabled": False, "max": DEFAULT_MAX_COMPUTERS, **(base or {})}
if isinstance(raw, dict):
if raw.get("enabled") is not None:
cur["enabled"] = bool(raw["enabled"])
if raw.get("max") is not None:
try:
cur["max"] = min(10, max(1, int(raw["max"])))
except (TypeError, ValueError):
pass
return {"enabled": bool(cur["enabled"]), "max": int(cur["max"])}
def clean_computer_limits(raw, base: dict | None = None) -> dict:
cur = {**DEFAULT_COMPUTER_LIMITS, **(base or {})}
bounds = {"fiveHourPct": (1, 100), "sevenDayPct": (1, 100), "inFlight": (1, 50),
"perMinute": (1, 1000), "rotateDays": (1, 90), "mirrorMb": (10, 100_000)}
if isinstance(raw, dict):
for k, (lo, hi) in bounds.items():
if raw.get(k) is not None:
try:
cur[k] = min(hi, max(lo, int(raw[k])))
except (TypeError, ValueError):
pass
return {k: int(cur[k]) for k in bounds}
def clean_channels(raw) -> list[str]:
if not isinstance(raw, (list, tuple)):
return ["in_app"]
out = [c for c in raw if c in NOTIFY_CHANNELS]
return list(dict.fromkeys(out)) or ["in_app"]
class _JsonFile:
def __init__(self, path: str, empty: dict):
self.path = pathlib.Path(path)
self._empty = empty
self._lock = threading.RLock()
self._data = self._load()
def _load(self) -> dict:
try:
data = json.loads(self.path.read_text(encoding="utf-8"))
if isinstance(data, dict):
return {**json.loads(json.dumps(self._empty)), **data}
except (OSError, ValueError):
pass
return json.loads(json.dumps(self._empty))
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(self.path.suffix + ".tmp")
tmp.write_text(json.dumps(self._data, indent=2, sort_keys=True),
encoding="utf-8")
os.chmod(tmp, 0o600)
os.replace(tmp, self.path)
class UsersStore(_JsonFile):
def __init__(self, path: str):
super().__init__(path, {"users": {}, "guestDefaults": {
"sharedSkills": list(DEFAULT_SHARED_SKILLS)}})
with self._lock:
stale = False
for u in self._data["users"].values():
was = (u.get("notify") or {}).get("channels")
if was is not None and was != clean_channels(was):
u["notify"] = {**u["notify"], "channels": clean_channels(was)}
stale = True
# Roles (authz/, 2026-11-23): the Access tab's switches become a
# role + overrides that allow exactly what they did. A copy of
# the file from before is kept beside it.
from authz import policy
pending = [u for u in self._data["users"].values() if not u.get(policy.MARK)]
if pending and self.path.exists():
bak = self.path.with_name(self.path.name + time.strftime(".bak-authz-%Y%m%d%H%M%S"))
try:
bak.write_bytes(self.path.read_bytes())
os.chmod(bak, 0o600)
except OSError:
pass
for u in pending:
policy.migrate(u)
stale = True
if stale:
self._save()
# ── what every guest gets ────────────────────────────────────────────────
def defaults(self) -> dict:
with self._lock:
d = self._data.get("guestDefaults") or {}
return {"sharedSkills": list(d.get("sharedSkills") or []),
"computerLimits": clean_computer_limits(d.get("computerLimits"))}
def legacy_guest_shortcuts(self) -> list[dict]:
"""The pre-v4 starting shortcuts (``guestDefaults.promptShortcuts``,
else the shipped ones a fresh file got) — for the prompt-shortcuts
carry-over only."""
with self._lock:
d = self._data.get("guestDefaults") or {}
raw = d["promptShortcuts"] if "promptShortcuts" in d else DEFAULT_GUEST_SHORTCUTS
return clean_shortcuts(raw)
def legacy_cron_limits(self) -> dict:
"""The pre-plugin scheduled-jobs limits (``guestDefaults.cronLimits``:
``maxJobs``, ``defaultModel``) as stored, ``{}`` without them — for
the cron-jobs carry-over only."""
with self._lock:
raw = (self._data.get("guestDefaults") or {}).get("cronLimits")
return json.loads(json.dumps(raw)) if isinstance(raw, dict) else {}
def legacy_new_projects(self) -> dict:
"""The pre-plugin New project policy (``guestDefaults.newProjects``)
as stored, ``{}`` without one — for the new-project carry-over and the
guests' root-domain fallback only."""
with self._lock:
raw = (self._data.get("guestDefaults") or {}).get("newProjects")
return json.loads(json.dumps(raw)) if isinstance(raw, dict) else {}
def set_defaults(self, fields: dict) -> dict:
with self._lock:
d = self._data.setdefault("guestDefaults", {})
if "sharedSkills" in fields:
d["sharedSkills"] = clean_skill_refs(fields["sharedSkills"])
if "computerLimits" in fields:
d["computerLimits"] = clean_computer_limits(
fields["computerLimits"], clean_computer_limits(d.get("computerLimits")))
self._save()
return self.defaults()
# ── reads ────────────────────────────────────────────────────────────────
def all(self) -> list[dict]:
with self._lock:
return [dict(u) for u in self._data["users"].values()]
def get(self, uid: str) -> dict | None:
with self._lock:
u = self._data["users"].get(uid)
return dict(u) if u else None
def by_email(self, email: str) -> dict | None:
e = norm_email(email)
with self._lock:
for u in self._data["users"].values():
if u.get("email") == e:
return dict(u)
return None
def active(self, uid: str) -> dict | None:
u = self.get(uid)
return u if u and not u.get("disabled") else None
# ── writes ───────────────────────────────────────────────────────────────
def create(self, email: str, name: str | None = None, **fields) -> dict:
e = norm_email(email)
if not valid_email(e):
raise ValueError("invalid email")
with self._lock:
if self.by_email(e):
raise ValueError("a user with this email already exists")
uid = slug_for(e, name, set(self._data["users"])
| set(self._data.get("deleted") or {}))
u = {"id": uid, "email": e, "name": " ".join((name or "").split())[:80] or uid,
"role": "guest", "projects": {}, "models": list(DEFAULT_MODELS),
"budgetUsd": DEFAULT_BUDGET_USD,
"notify": {"channels": ["in_app"]},
"role": DEFAULT_ROLE, "allow": [], "deny": [], "authz": 1, "bucket": "",
"domain": "", "lang": "auto", "disabled": False,
"createdAt": _now_iso(), "lastLoginAt": None}
clean = self._clean(fields)
switches = clean.pop("_switches", None)
u.update(clean)
if switches:
from authz import policy
u.update(policy.set_switch(u, switches))
self._data["users"][uid] = u
self._save()
return dict(u)
def update(self, uid: str, fields: dict) -> dict:
with self._lock:
u = self._data["users"].get(uid)
if u is None:
raise KeyError(uid)
clean = self._clean(fields)
if "email" in fields:
e = norm_email(fields["email"])
if not valid_email(e):
raise ValueError("invalid email")
other = self.by_email(e)
if other and other["id"] != uid:
raise ValueError("a user with this email already exists")
clean["email"] = e
credit = clean.pop("budgetCredit", None)
if credit:
# One month's credit (users/runs.month_credit); 0 takes it back.
credits = dict(u.get("budgetCredits") or {})
if credit["usd"] > 0:
credits[credit["month"]] = {"usd": credit["usd"], "note": credit["note"],
"at": _now_iso()}
else:
credits.pop(credit["month"], None)
clean["budgetCredits"] = credits
switches = clean.pop("_switches", None)
u.update(clean)
if switches:
# An old switch (cli, mcp, …): an override relative to their role.
from authz import policy
u.update(policy.set_switch(u, switches))
self._save()
return dict(u)
def set_claude(self, uid: str, info: dict | None) -> dict | None:
"""Record (or, with None, forget) the guest's own Claude login:
``{"account": "guest-<uid>", "email", "subscriptionType",
"connectedAt"}``. The login itself lives on the host (the sidecar's
``~/.claude-guests/<uid>``); this is what the app shows and routes on."""
with self._lock:
u = self._data["users"].get(uid)
if u is None:
raise KeyError(uid)
if info is None:
bill = (u.pop("claude", None) or {}).get("bill")
if bill:
# their pick still steers their own computers' runs
u["claude"] = {"bill": bill}
else:
bill = (u.get("claude") or {}).get("bill")
u["claude"] = {k: info.get(k) for k in
("account", "email", "subscriptionType", "connectedAt")}
if bill:
u["claude"]["bill"] = bill # a re-login keeps their pick
self._save()
return dict(u)
def set_claude_bill(self, uid: str, bill: str) -> dict:
"""The guest's pick on their composer's account chip: ``own`` (their
own Claude first, the owner's as the fallback — the default) or
``host`` (the owner's account, under their budget and models). Kept
with their login record — alone (``{"bill"}``, no ``connectedAt``)
for a guest whose own Claude is only their computer's login."""
if bill not in ("own", "host"):
raise ValueError("bill must be 'own' or 'host'")
with self._lock:
u = self._data["users"].get(uid)
if u is None:
raise KeyError(uid)
u.setdefault("claude", {})["bill"] = bill
self._save()
return dict(u)
def delete(self, uid: str, *, tombstone: bool = False) -> bool:
"""Drop the record. With ``tombstone`` (the owner's *Delete user*)
the id is retired for good — see ``deleted`` above."""
with self._lock:
u = self._data["users"].pop(uid, None)
if u is None:
return False
if tombstone:
self._data.setdefault("deleted", {})[uid] = {
"email": u.get("email"), "name": u.get("name"),
"deletedAt": _now_iso()}
self._save()
return True
def set_browser_lang(self, uid: str, lang: str | None) -> bool:
"""Remember the guest's browser language (a base code — ``fr``,
``de``: kept even when no translation speaks it yet, so ``auto``
follows it the day one is installed; anything else leaves what was
there). Writes only when it changed."""
if not is_code(lang):
return False
with self._lock:
u = self._data["users"].get(uid)
if u is None or u.get("browserLang") == lang:
return False
u["browserLang"] = lang
self._save()
return True
def lang_of(self, uid: str, accept_language: str | None = None) -> str:
"""The language the app speaks to ``uid`` (``core.i18n.effective_lang``):
their ``lang`` unless ``auto``, else their recorded browser language,
else ``accept_language``'s, else English. The owner: their own pick
(:meth:`owner_lang`)."""
if uid == "owner":
return effective_lang({"lang": self.owner_lang()}, accept_language)
return effective_lang(self.get(uid), accept_language)
# ── the owner's own language (Settings → Display) ────────────────────────
# The owner has no record here; their pick sits beside the users. English
# by default (never ``auto`` unless they pick it). A pick whose translation
# is gone is kept and reads English.
def owner_lang(self) -> str:
with self._lock:
v = self._data.get("ownerLang")
return v if isinstance(v, str) and v else "en"
def set_owner_lang(self, value) -> str:
"""Store the owner's pick (``core.i18n.clean_pref``; ValueError)."""
v = clean_pref(value)
with self._lock:
if self._data.get("ownerLang") != v:
self._data["ownerLang"] = v
self._save()
return v
def by_idp(self, idp_id: str) -> dict | None:
"""The guest whose Pocket ID user (the OIDC ``sub``) is ``idp_id``."""
if not idp_id:
return None
with self._lock:
for u in self._data["users"].values():
if u.get("idpId") == idp_id:
return dict(u)
return None
def set_idp(self, uid: str, idp_id: str | None, state: dict | None = None) -> None:
"""Record a guest's Pocket ID id (``None`` keeps the one known) and the
last sync's ``{ok, error, at}`` (users/idp.py)."""
with self._lock:
u = self._data["users"].get(uid)
if u is None:
return
if idp_id:
u["idpId"] = idp_id
if state is not None:
u["idpSync"] = dict(state)
self._save()
def touch_login(self, uid: str) -> None:
with self._lock:
u = self._data["users"].get(uid)
if u is not None:
u["lastLoginAt"] = _now_iso()
self._save()
@staticmethod
def _clean(fields: dict) -> dict:
out: dict = {}
if "name" in fields and isinstance(fields["name"], str):
out["name"] = " ".join(fields["name"].split())[:80] # one line: it goes into prompts
if "projects" in fields:
out["projects"] = clean_projects(fields["projects"])
if "models" in fields and isinstance(fields["models"], (list, tuple)):
out["models"] = [m for m in fields["models"]
if isinstance(m, str) and m.strip()][:40]
if "budgetUsd" in fields:
try:
out["budgetUsd"] = max(0.0, float(fields["budgetUsd"]))
except (TypeError, ValueError):
pass
c = fields.get("budgetCredit")
if isinstance(c, dict):
month = str(c.get("month") or "")
try:
usd = round(max(0.0, float(c.get("usd") or 0)), 4)
except (TypeError, ValueError):
usd = None
if not re.fullmatch(r"20\d\d-(0[1-9]|1[0-2])", month) or usd is None:
raise ValueError("budgetCredit needs {month: YYYY-MM, usd >= 0}")
out["budgetCredit"] = {"month": month, "usd": usd,
"note": " ".join(str(c.get("note") or "").split())[:200]}
if "notify" in fields and isinstance(fields["notify"], dict):
out["notify"] = {"channels": clean_channels(
fields["notify"].get("channels"))}
if "disabled" in fields:
out["disabled"] = bool(fields["disabled"])
from authz import catalog as authz_cat, policy, roles as authz_roles
if fields.get("role") is not None:
if not authz_roles.store().assignable(fields["role"]):
raise ValueError(f"unknown role: {fields['role']!r}")
out["role"] = fields["role"]
for key in ("allow", "deny"):
if fields.get(key) is not None:
if not isinstance(fields[key], (list, tuple)):
raise ValueError(f"{key} must be a list of permissions")
bad = set(fields[key]) - authz_cat.PERSON_PERMS
if bad:
raise ValueError(f"{key}: not a person-level permission: {sorted(bad)}")
out[key] = authz_cat.clean(fields[key], authz_cat.PERSON_PERMS)
if "deny" in out:
out["deny"] = [p for p in out["deny"] if p not in authz_cat.CORE]
# The Access tab's old switches — permissions now (authz/policy.py).
switches = {perm: bool(fields[key]) for key, (perm, _) in policy.SWITCHES.items()
if fields.get(key) is not None}
comp = fields.get("computers")
if isinstance(comp, dict) and comp.get("enabled") is not None:
switches[policy.COMPUTERS_PERM] = bool(comp["enabled"])
if switches:
out["_switches"] = switches
if "bucket" in fields and fields["bucket"] is not None:
out["bucket"] = clean_bucket(fields["bucket"])
if "domain" in fields and fields["domain"] is not None:
out["domain"] = clean_domain(fields["domain"])
if "lang" in fields and fields["lang"] is not None:
out["lang"] = clean_pref(fields["lang"])
if "autoFresh" in fields and fields["autoFresh"] is not None:
out["autoFresh"] = bool(fields["autoFresh"])
if "clarifier" in fields and isinstance(fields["clarifier"], dict):
out["clarifier"] = dict(fields["clarifier"])
if isinstance(fields.get("computers"), dict) and fields["computers"].get("max") is not None:
# how many; whether at all is ``computers.pair`` (above)
out["computers"] = {"max": clean_computers(fields["computers"])["max"]}
if "apps" in fields and fields["apps"] is not None:
from users.idp import clean_apps
out["apps"] = clean_apps(fields["apps"])
return out
class AuthStore(_JsonFile):
"""One-time login links and browser sessions, keyed by token hash."""
def __init__(self, path: str):
super().__init__(path, {"links": {}, "sessions": {}})
def _prune(self, now: float) -> None:
for kind in ("links", "sessions"):
dead = [h for h, r in self._data[kind].items()
if r.get("exp", 0) < now]
for h in dead:
del self._data[kind][h]
# ── login links ──────────────────────────────────────────────────────────
def mint_link(self, uid: str, ttl_s: int = LINK_TTL_S) -> str:
return self._mint(uid, ttl_s)[0]
def mint_login(self, uid: str, ttl_s: int = LINK_TTL_S) -> tuple[str, str]:
"""A sign-in link plus the 6-digit code that stands in for it — the
one a guest types into a home-screen app, since the mailed link opens
in the browser, not in the app. Either one spends both."""
return self._mint(uid, ttl_s, with_code=True)
def _misses(self, uid: str, now: float) -> list[float]:
"""``uid``'s wrong codes still inside the window (caller holds the lock)."""
all_ = self._data.setdefault("codeMisses", {})
live = [t for t in all_.get(uid) or [] if now - t < CODE_MISS_WINDOW_S]
if live:
all_[uid] = live
else:
all_.pop(uid, None)
return live
def codes_locked(self, uid: str) -> bool:
"""Too many wrong codes for ``uid`` lately: no code works and none is
mailed — the link, a long secret, still signs them in."""
with self._lock:
return len(self._misses(uid, time.time())) >= CODE_MISSES_MAX
def _mint(self, uid: str, ttl_s: int, with_code: bool = False) -> tuple[str, str]:
token = secrets.token_urlsafe(32)
if with_code and self.codes_locked(uid):
with_code = False
code = f"{secrets.randbelow(10 ** CODE_DIGITS):0{CODE_DIGITS}d}" if with_code else ""
now = time.time()
rec = {"user": uid, "exp": now + ttl_s, "created": now}
if code:
rec.update(code=_hash(f"{uid}:{code}"), tries=0)
with self._lock:
self._prune(now)
self._data["links"][_hash(token)] = rec
self._save()
return token, code
def consume_code(self, uid: str, code: str) -> str | None:
"""``uid`` when ``code`` is one of their live sign-in codes — spent
with its link, once. A wrong code counts against every live code of
theirs; after CODE_TRIES misses a code stops working (its link still
does). Six digits and five tries per mail: ~1 in 200,000 per mail —
and CODE_MISSES_MAX misses a day per address, mails notwithstanding:
past it every code is refused, the right one included."""
code = "".join(ch for ch in (code or "") if ch.isdigit())
if not uid or len(code) != CODE_DIGITS:
return None # can't be a code: not a guess either
want = _hash(f"{uid}:{code}")
now = time.time()
with self._lock:
self._prune(now)
misses = self._misses(uid, now)
if len(misses) >= CODE_MISSES_MAX:
return None
mine = [(h, r) for h, r in self._data["links"].items()
if r.get("user") == uid and r.get("code")]
hit = next((h for h, r in mine if hmac.compare_digest(r["code"], want)), None)
if hit:
del self._data["links"][hit]
else:
for _, r in mine:
r["tries"] = int(r.get("tries") or 0) + 1
if r["tries"] >= CODE_TRIES:
r.pop("code", None)
self._data["codeMisses"][uid] = [*misses, now]
if len(misses) + 1 >= CODE_MISSES_MAX:
# No live code outlasts the lock: the next mail is link-only.
for _, r in mine:
r.pop("code", None)
self._save()
return uid if hit else None
def last_link_at(self, uid: str) -> float:
"""When the newest live link for ``uid`` was minted (0 = none)."""
with self._lock:
made = [r.get("created") or (r["exp"] - LINK_TTL_S)
for r in self._data["links"].values() if r.get("user") == uid]
return max(made) if made else 0.0
def consume_link(self, token: str) -> str | None:
"""The link's user id, once — the link is gone after this call."""
now = time.time()
with self._lock:
rec = self._data["links"].pop(_hash(token or ""), None)
self._prune(now)
self._save()
if not rec or rec.get("exp", 0) < now:
return None
return rec.get("user")
# ── sessions ─────────────────────────────────────────────────────────────
def open_session(self, uid: str, ua: str = "", impersonator: str | None = None) -> str:
"""A browser session for ``uid``. With ``impersonator`` it is the
owner looking through the guest's eyes: short-lived, never extended,
and not counted among the guest's own sessions."""
token = secrets.token_urlsafe(32)
now = time.time()
ttl = IMPERSONATE_TTL_S if impersonator else SESSION_TTL_S
rec = {"user": uid, "exp": now + ttl, "created": now, "seen": now,
"ua": (ua or "")[:160]}
if impersonator:
rec["imp"] = impersonator
with self._lock:
self._prune(now)
self._data["sessions"][_hash(token)] = rec
self._save()
return token
def session(self, token: str) -> dict | None:
"""The live session record behind ``token`` (``user``, ``imp``…)."""
if not token:
return None
h = _hash(token)
now = time.time()
with self._lock:
rec = self._data["sessions"].get(h)
if not rec:
return None
if rec.get("exp", 0) < now:
del self._data["sessions"][h]
self._save()
return None
if not rec.get("imp") and now - rec.get("seen", 0) > _SESSION_BUMP_S:
rec["seen"] = now
rec["exp"] = now + SESSION_TTL_S
self._save()
return dict(rec)
def session_user(self, token: str) -> str | None:
rec = self.session(token)
return rec.get("user") if rec else None
def close_session(self, token: str) -> None:
with self._lock:
if self._data["sessions"].pop(_hash(token or ""), None) is not None:
self._save()
def revoke_user(self, uid: str) -> int:
"""Drop every session and pending link of ``uid``."""
with self._lock:
n = 0
for kind in ("links", "sessions"):
for h in [h for h, r in self._data[kind].items()
if r.get("user") == uid]:
del self._data[kind][h]
n += kind == "sessions"
self._save()
return n
def sessions_of(self, uid: str) -> list[dict]:
"""The guest's own sessions (the owner's impersonations aren't)."""
with self._lock:
return [{"created": r.get("created"), "seen": r.get("seen"),
"ua": r.get("ua")}
for r in self._data["sessions"].values()
if r.get("user") == uid and not r.get("imp")]