Files
ai-agent/backend/users/store.py
gabrielvidalandClaude Opus 5.5 36528b2953 fix(plugins): leftovers of the plugin migration — read-only plugin reads, conversation.started, a clean OpenAPI dump
- `GET /api/plugins/{pid}/actions/{action}?payload=` runs an action the
  manifest marks `readOnly`; a read-only account (the screenshot bot) may only
  use safe methods, so its plugin frames send actions as GETs and plugin pages
  (Plans, Approvals, Forms) show their data instead of "method not allowed".
- Core now fires the `conversation.started` hub event it already accepted from
  manifests (prompt ≤ 4,000 chars, projects, worker, owner, origin) — Plans
  links the run its *Implement* opens.
- The plugin conversation bridge's rows carry `worker` ("local" = the lab), so
  Approvals can refuse requests from another machine again.
- The catch-all `/proxy/tools/plugins/{pid}/proxy/{path}` is out of the OpenAPI
  spec (six methods, one operation id): `frontend/openapi.json` is a full
  re-dump again and `src/generated/` is regenerated from it.
- `projects.create` and the `createProjects` switch are retired (New project is
  the `new-project` plugin's grant); the carry-over reads the old permission
  off the raw record. Mocks and the roles catalog dump follow.
- The worker outbox mirror loses the `frm` answer branch and the `secrets`
  hook the retired form engine used; its docstring no longer names /api/forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:23:21 +01:00

926 lines
42 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), ``whatsNew``, ``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`), ``tools``
(``{"groups", "pro", "budgetUsd"}`` — toolproxy/), ``apps`` and
``clarifier`` (the clarifier fields they set themselves — runs/clarifier.py).
``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: ``promptShortcuts`` (the list a new guest's composer starts
with — copied into their own settings on first load, theirs to edit after)
and ``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), ``newProjects`` — what a guest
allowed to create projects may pick (:data:`DEFAULT_NEW_PROJECTS`) — and
``computerLimits``, what the Claude proxy holds a guest's computers to
(:data:`DEFAULT_COMPUTER_LIMITS`), and ``cronLimits``, how many scheduled
jobs of their own a guest may have (``cron/guests.py``).
* ``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 LANGS, clean_pref, effective_lang
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")
# A new guest's composer chips — generic wrap-ups, nothing lab-specific (no
# worktree script, no deploy target). The owner rewrites them in Settings → Users.
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.)
# What a guest allowed to create projects gets (Settings → Users → Every guest
# → New projects): ``quota`` projects all told; the ``templates`` offered, of
# which ``approve`` wait for the owner's OK (a backend on the zipgo host); the
# site ``visibility`` choices; the creator's grant ``level``; and the
# ``domain`` their address bucket sits under.
NEW_PROJECT_VISIBILITY = ("public", "password", "geo")
DEFAULT_NEW_PROJECTS = {
"quota": 10,
"templates": ["react-vite", "vite-react-pocketbase"],
"approve": ["vite-react-pocketbase"],
"visibility": list(NEW_PROJECT_VISIBILITY),
"visibilityDefault": "public",
"level": "ship",
"domain": "gabvdl.xyz",
}
_TEMPLATE_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
_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_new_projects(raw, base: dict | None = None) -> dict:
"""The New projects policy, each key validated; a key that's missing or
malformed keeps ``base``'s value (the defaults)."""
out = json.loads(json.dumps(base or DEFAULT_NEW_PROJECTS))
raw = raw if isinstance(raw, dict) else {}
try:
if "quota" in raw:
out["quota"] = max(0, min(1000, int(raw["quota"])))
except (TypeError, ValueError):
pass
for key in ("templates", "approve"):
if isinstance(raw.get(key), (list, tuple)):
out[key] = list(dict.fromkeys(
t.strip() for t in raw[key]
if isinstance(t, str) and _TEMPLATE_NAME_RE.match(t.strip())))
out["approve"] = [t for t in out["approve"] if t in out["templates"]]
if isinstance(raw.get("visibility"), (list, tuple)):
vis = [v for v in raw["visibility"] if v in NEW_PROJECT_VISIBILITY]
out["visibility"] = list(dict.fromkeys(vis)) or ["public"]
if raw.get("visibilityDefault") in NEW_PROJECT_VISIBILITY:
out["visibilityDefault"] = raw["visibilityDefault"]
if out["visibilityDefault"] not in out["visibility"]:
out["visibilityDefault"] = out["visibility"][0]
if raw.get("level") in ("chat", "ship"):
out["level"] = raw["level"]
dom = str(raw.get("domain") or "").strip().lower()
if dom and _DOMAIN_RE.match(dom):
out["domain"] = dom
return out
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"])}
# A guest's paid tools (toolproxy/): which groups are on (Movies only, by
# default), whether Nano Banana Pro is, and the monthly tools budget — apart
# from their Claude budget; only the tools that cost money (Nano Banana) spend it.
TOOL_GROUPS = ("images", "video", "3d", "analytics", "media", "meta")
# Movies is free and on for every guest (form
# ``movies-widget-guests-what-s-new_uqbyga``, 2026-11-18) — and switching it
# on switches their Jellyfin app on (users/routes.py ``_movies_bring_jellyfin``).
DEFAULT_TOOL_GROUPS = ("media",)
DEFAULT_TOOLS_BUDGET_USD = 10.0
def clean_tools(raw, base: dict | None = None) -> dict:
"""A guest's ``tools``: ``{"groups": [...], "pro": bool, "budgetUsd": float}``."""
cur = {"groups": list(DEFAULT_TOOL_GROUPS), "pro": False,
"budgetUsd": DEFAULT_TOOLS_BUDGET_USD, **(base or {})}
if isinstance(raw, dict):
if isinstance(raw.get("groups"), (list, tuple)):
cur["groups"] = [g for g in TOOL_GROUPS if g in raw["groups"]]
if raw.get("pro") is not None:
cur["pro"] = bool(raw["pro"])
if raw.get("budgetUsd") is not None:
try:
cur["budgetUsd"] = min(10000.0, max(0.0, float(raw["budgetUsd"])))
except (TypeError, ValueError):
pass
try:
budget = float(cur["budgetUsd"])
except (TypeError, ValueError):
budget = DEFAULT_TOOLS_BUDGET_USD
return {"groups": [g for g in TOOL_GROUPS if g in (cur.get("groups") or [])],
"pro": bool(cur.get("pro")), "budgetUsd": budget}
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}
# A guest's own scheduled jobs (cron/guests.py): how many each may have, and
# the model a new one starts on (qwen | sonnet).
DEFAULT_CRON_LIMITS = {"maxJobs": 5, "defaultModel": "qwen"}
def clean_cron_limits(raw, base: dict | None = None) -> dict:
cur = {**DEFAULT_CRON_LIMITS, **(base or {})}
if isinstance(raw, dict):
if raw.get("maxJobs") is not None:
try:
cur["maxJobs"] = min(50, max(0, int(raw["maxJobs"])))
except (TypeError, ValueError):
pass
if raw.get("defaultModel") in ("qwen", "sonnet"):
cur["defaultModel"] = raw["defaultModel"]
model = cur["defaultModel"] if cur.get("defaultModel") in ("qwen", "sonnet") else "qwen"
return {"maxJobs": int(cur["maxJobs"]), "defaultModel": model}
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": {
"promptShortcuts": [dict(s) for s in DEFAULT_GUEST_SHORTCUTS],
"sharedSkills": list(DEFAULT_SHARED_SKILLS),
"newProjects": dict(DEFAULT_NEW_PROJECTS)}})
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 {"promptShortcuts": [dict(s) for s in d.get("promptShortcuts") or []],
"sharedSkills": list(d.get("sharedSkills") or []),
# An install from before New projects has no key: defaults.
"newProjects": clean_new_projects(d.get("newProjects") or {}),
"computerLimits": clean_computer_limits(d.get("computerLimits")),
"cronLimits": clean_cron_limits(d.get("cronLimits"))}
def set_defaults(self, fields: dict) -> dict:
with self._lock:
d = self._data.setdefault("guestDefaults", {})
if "promptShortcuts" in fields:
d["promptShortcuts"] = clean_shortcuts(fields["promptShortcuts"])
if "sharedSkills" in fields:
d["sharedSkills"] = clean_skill_refs(fields["sharedSkills"])
if "newProjects" in fields:
d["newProjects"] = clean_new_projects(
fields["newProjects"], clean_new_projects(d.get("newProjects") or {}))
if "computerLimits" in fields:
d["computerLimits"] = clean_computer_limits(
fields["computerLimits"], clean_computer_limits(d.get("computerLimits")))
if "cronLimits" in fields:
d["cronLimits"] = clean_cron_limits(
fields["cronLimits"], clean_cron_limits(d.get("cronLimits")))
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
def emails(self) -> list[str]:
"""Every enabled user's address (the mail trigger's half of the list)."""
return [u["email"] for u in self.all() if not u.get("disabled")]
# ── 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": "", "whatsNew": True, "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
if "tools" in clean and isinstance(fields.get("tools"), dict):
# A partial change (just the budget, just one group) keeps the rest.
clean["tools"] = clean_tools(fields["tools"], clean_tools(u.get("tools")))
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 (``en``/``fr``; anything
else leaves what was there). Writes only when it changed."""
if lang not in LANGS:
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."""
return effective_lang(self.get(uid), accept_language)
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 "whatsNew" in fields and fields["whatsNew"] is not None:
out["whatsNew"] = bool(fields["whatsNew"])
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 "tools" in fields and fields["tools"] is not None:
out["tools"] = clean_tools(fields["tools"])
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")]