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

870 lines
40 KiB
Python

"""Built-in login, ``/api/me``, the owner's user admin and conversation sharing."""
from __future__ import annotations
import dataclasses
import os
import threading
import time
from typing import Literal
from fastapi import APIRouter, HTTPException, Request, Response
from pydantic import BaseModel, Field
import schemas
from core.config import HUB_LABEL
from core.http import _r
from core.i18n import primary_lang, tr
from core.state import State
from projects.catalog import ROOT_SLUG
from security import service as security
from users import access, computers, idp, mailer, oidc, push_style, session, webpush
from users.caller import (OWNER_ID, OWNER_NAME, SESSION_COOKIE, CallerDep,
OwnerDep, guest_from_record, on_guest_surface, on_owner_surface,
request_host, request_lang)
from users.deliver import GUEST_PUBLIC_URL
from users.store import (DEFAULT_MODELS, auto_fresh, IMPERSONATE_TTL_S, INVITE_TTL_S,
LEVELS, LINK_TTL_S, NOTIFY_CHANNELS,
clean_computers, code_mode, norm_email, scratch_bash,
valid_email)
router = APIRouter()
# One login mail per address per this many seconds (the endpoint is public).
_LINK_COOLDOWN_S = 60
def _origin(request: Request) -> str:
"""Where a login link should land: the guest host this request came in on
(the session cookie is per host, so a link asked for on one guest address
must sign in that one), else the guest surface's public URL, else the
host this request came in on."""
proto = request.headers.get("x-forwarded-proto") or request.url.scheme
if on_guest_surface(request):
return f"{proto}://{request_host(request)}"
if GUEST_PUBLIC_URL:
return GUEST_PUBLIC_URL
return f"{proto}://{request.headers.get('host') or request_host(request)}"
_secure = session.secure
def _me(deps, caller) -> dict:
out = {"id": caller.id, "role": caller.role, "name": caller.name,
"email": caller.email, "readonly": caller.readonly,
# What they may do (authz/): their role and its permissions plus
# their overrides — the UI hides what they can't reach.
"roleId": caller.role_id or ("operator" if caller.is_owner else None),
"perms": sorted(caller.perms),
# a credential scope's read-only permissions (authz/scopes.py):
# pages the app may show, calls it may not write
"readPerms": sorted(caller.read_perms),
"projects": [{"slug": s, "level": l} for s, l in sorted(caller.projects.items())],
"models": list(caller.models), "budgetUsd": caller.budget_usd,
"notify": None, "spentUsd": None, "mail": mailer.enabled(),
"impersonating": bool(caller.impersonator),
# The hub machine's display name (core/config.HUB_LABEL) — every
# label of the local runner in the app reads it.
"hubName": HUB_LABEL,
# Their stored pick (auto = their browser's — the PWA resolves it,
# frontend/src/i18n): the owner's own (English unless they picked
# one), a guest's below.
"lang": deps.users.owner_lang() if caller.is_owner else "en"}
# Whether (and where) they may start a project: the ``new-project`` live
# plugin's composer mode, None when it isn't installed or granted.
from users import runs as guest_runs
out["newProjects"] = guest_runs.new_project_access(deps, caller)
if not caller.is_owner:
u = deps.users.get(caller.id) or {}
out["lang"] = u.get("lang") or "auto"
out["autoFresh"] = auto_fresh(u)
out["codeMode"] = code_mode(u)
out["notify"] = u.get("notify") or {"channels": ["in_app"]}
from settings.unsend import owner_curve
out["unsendCurve"] = owner_curve(deps)
from accounts import guest as guest_claude
from conversations.catalog import _conversation_cards
from users.runs import month_spend
cards = list(_conversation_cards(deps, False))
out["spentUsd"] = round(month_spend(deps, caller.id, cards), 4)
out["claude"] = guest_claude.status(deps, caller.id, cards)
return out
# ── login ────────────────────────────────────────────────────────────────────
class LinkRequest(BaseModel):
email: str
# Sign-in mails per rolling hour, all users together: the per-user cooldown
# alone let one address be mailed ~1,440 times a day from the public host.
LINK_MAILS_PER_HOUR = int(os.environ.get("LINK_MAILS_PER_HOUR", "30"))
# …and per address, well under the total: whoever keeps asking for one
# guest's link can't use up everybody's (nor mail them 30 times an hour).
LINK_MAILS_PER_USER_HOUR = int(os.environ.get("LINK_MAILS_PER_USER_HOUR", "4"))
_link_sent: list[float] = []
_link_sent_to: dict[str, list[float]] = {}
_link_lock = threading.Lock()
def _link_budget(uid: str = "") -> bool:
now = time.time()
with _link_lock:
_link_sent[:] = [t for t in _link_sent if now - t < 3600]
mine = [t for t in _link_sent_to.get(uid, []) if now - t < 3600]
if len(_link_sent) >= LINK_MAILS_PER_HOUR or \
(uid and len(mine) >= LINK_MAILS_PER_USER_HOUR):
return False
_link_sent.append(now)
if uid:
_link_sent_to[uid] = [*mine, now]
return True
def _background(fn, *args) -> None:
"""Run ``fn`` off the request thread (tests run it inline)."""
threading.Thread(target=fn, args=args, daemon=True).start()
def _send_login_mail(deps, u: dict, origin: str, lang: str) -> None:
"""Mint ``u``'s sign-in link (and code, unless their codes are locked)
and mail it — if their cooldown and the hourly budgets allow."""
if time.time() - deps.auth.last_link_at(u["id"]) < _LINK_COOLDOWN_S \
or not _link_budget(u["id"]):
return
token, code = deps.auth.mint_login(u["id"])
try:
mailer.login_mail(u["email"], u.get("name") or u["id"],
f"{origin}/login?token={token}", LINK_TTL_S // 60, lang,
code=code)
except mailer.MailError:
pass
@router.post("/api/auth/request-link", responses=_r(schemas.OkResponse))
def request_link(deps: State, request: Request, body: LinkRequest):
"""Mail a one-time sign-in link. Always answers ok — whether the address
is a user is nobody's business but the owner's. The minting and the SMTP
exchange happen off the request, so how long the answer takes doesn't
tell a guest's address from a stranger's either."""
_no_mail_login(request)
u = deps.users.by_email(body.email)
security.record(deps, "link_request", who=u["id"] if u else None, request=request,
detail=("" if u else f"no user: {body.email.strip()[:120]}"))
if u and not u.get("disabled") and mailer.enabled():
_background(_send_login_mail, deps, u, _origin(request),
deps.users.lang_of(u["id"], _accept(request)))
return {"ok": True}
# Wrong sign-in codes per address (IP): 20 in 10 minutes and it is refused
# for an hour, whoever's code it tries next (``ip_locked`` in the Security
# log). The mailed link keeps working — it is a long secret.
_BAD_CODES = None
def _bad_codes():
global _BAD_CODES
if _BAD_CODES is None:
from workers.guests import BadTokens
_BAD_CODES = BadTokens()
return _BAD_CODES
def _no_mail_login(request: Request) -> None:
"""Guests sign in through the identity provider (users/oidc.py) once one
is configured: the mailed link and code are gone (sessions opened with
them stay valid)."""
if oidc.enabled():
raise HTTPException(410, {"message": tr(request_lang(request),
"sign in with the button on the sign-in page"),
"kind": "oidc"})
def _code_refused(request: Request) -> HTTPException:
return HTTPException(401, {"message": tr(request_lang(request),
"this code is wrong or expired"),
"kind": "code_invalid"})
class LoginBody(BaseModel):
"""The mailed link's ``token``, or the mail's ``email`` + ``code`` (what a
home-screen app types in: the link itself opens in the browser)."""
token: str = Field("", max_length=200)
email: str = Field("", max_length=320)
code: str = Field("", max_length=20)
@router.post("/api/auth/login", responses=_r(schemas.Me))
def login(deps: State, request: Request, response: Response, body: LoginBody):
_no_mail_login(request)
if body.token:
uid = deps.auth.consume_link(body.token)
else:
ip = security.client_ip(request)
if _bad_codes().locked(ip):
raise _code_refused(request)
who = deps.users.by_email(body.email) if body.email.strip() else None
uid = deps.auth.consume_code(who["id"], body.code) if who else None
if not uid:
locked = bool(who) and deps.auth.codes_locked(who["id"])
security.record(deps, "code_failed", who=who["id"] if who else None,
request=request,
detail=("codes locked for this address: too many wrong ones "
"in 24 h — the mailed link still works" if locked
else "" if who
else f"no user: {body.email.strip()[:120]}"))
if _bad_codes().fail(ip):
security.record(deps, "ip_locked", request=request,
detail=f"{ip}: {_bad_codes().LIMIT} wrong sign-in codes in "
f"{_bad_codes().WINDOW_S // 60} min — codes refused "
f"for {_bad_codes().LOCK_S // 60} min")
raise _code_refused(request)
u = deps.users.active(uid) if uid else None
if not u:
raise HTTPException(401, {"message": tr(request_lang(request),
"this link is invalid or expired"),
"kind": "link_invalid"})
session.open_session(deps, request, response, u["id"])
return _me(deps, guest_from_record(deps.users.get(u["id"]) or u, _accept(request)))
def _accept(request: Request) -> str:
return request.headers.get("accept-language", "")
@router.post("/api/auth/logout", responses=_r(schemas.OkResponse))
def logout(deps: State, request: Request, response: Response):
if on_owner_surface(request):
# On the internet address, a guest cookie beside the owner's is either
# the owner's impersonation (*Back to admin*: only that one goes) or
# one a guest's *.gabvdl.xyz site planted — which must never turn
# *Sign out* into a no-op. So: the owner's session goes unless that
# cookie is a live impersonation.
imp = deps.auth.session(request.cookies.get(SESSION_COOKIE, ""))
if not (imp and imp.get("imp")):
from remoteaccess.sessions import COOKIE
deps.owner_sessions.close(request.cookies.get(COOKIE, ""))
response.delete_cookie(COOKIE, path="/", secure=True, httponly=True)
return {"ok": True}
deps.auth.close_session(request.cookies.get(SESSION_COOKIE, ""))
response.delete_cookie(SESSION_COOKIE, path="/")
return {"ok": True}
# ── me ───────────────────────────────────────────────────────────────────────
@router.get("/api/me", responses=_r(schemas.Me))
def me(deps: State, request: Request, caller: CallerDep):
if not caller.is_owner and not caller.impersonator:
# What ``lang: auto`` means for them off a request (pushes, mails):
# this browser's language. Never the owner's, viewing as them.
deps.users.set_browser_lang(caller.id, primary_lang(_accept(request)))
return {**_me(deps, caller), "surface": _surface(request)}
def _surface(request: Request) -> str:
"""Which address this is: ``guest``, ``remote`` (the owner's internet
address) or ``admin``."""
if on_guest_surface(request):
return "guest"
return "remote" if on_owner_surface(request) else "admin"
class MePatch(BaseModel):
name: str | None = None
notify: dict | None = None
lang: str | None = None # auto | en | an installed language (Settings → Display)
autoFresh: bool | None = None # Settings → Fresh context
@router.put("/api/me", responses=_r(schemas.Me))
def me_update(deps: State, request: Request, caller: CallerDep, body: MePatch):
"""A guest's own preferences: display name, notification channels and
the language the app speaks to them. The owner: their language only (the
rest of their settings live in Settings)."""
if caller.is_owner:
extra = body.model_dump(exclude_none=True)
if set(extra) != {"lang"}:
raise HTTPException(400, "the owner's settings live in Settings")
if caller.readonly:
raise HTTPException(403, "read-only")
try:
deps.users.set_owner_lang(extra["lang"])
except ValueError as e:
raise HTTPException(400, str(e))
return {**_me(deps, caller), "surface": _surface(request)}
try:
deps.users.update(caller.id, body.model_dump(exclude_none=True))
except ValueError as e:
raise HTTPException(400, str(e))
u = deps.users.get(caller.id)
me_now = guest_from_record(u, _accept(request))
if caller.impersonator:
me_now = dataclasses.replace(me_now, impersonator=caller.impersonator)
return {**_me(deps, me_now), "surface": _surface(request)}
# ── web push (users/webpush.py) ──────────────────────────────────────────────
# Guests and the owner alike: a device is the browser's, filed under the
# caller's id (``owner`` for the owner — beside the webhooks, not instead).
def _push_view(deps, uid: str, lang: str = "en") -> dict:
return {"publicKey": webpush.public_key(), "devices": deps.push.of(uid),
"prefs": push_style.prefs_view(deps.push.levels(uid), lang)}
@router.get("/api/me/push", responses=_r(schemas.PushDevices))
def me_push(deps: State, caller: CallerDep):
"""The key a browser subscribes with and the caller's devices."""
return _push_view(deps, caller.id, caller.lang)
class PushSubscribeBody(BaseModel):
subscription: dict # PushSubscription.toJSON(): endpoint + keys
label: str = ""
@router.post("/api/me/push", responses=_r(schemas.PushDevices))
def me_push_add(deps: State, caller: CallerDep, body: PushSubscribeBody):
"""This browser turned push on: record it, and switch a guest's
``webpush`` channel on — subscribing is them saying yes."""
if caller.impersonator:
# The owner's browser would keep getting the guest's pushes.
raise HTTPException(400, "not while viewing as a guest")
try:
deps.push.add(caller.id, body.subscription, body.label)
except ValueError as e:
raise HTTPException(400, str(e))
channels = list(((deps.users.get(caller.id) or {}).get("notify") or {})
.get("channels") or ["in_app"])
if not caller.is_owner and "webpush" not in channels:
deps.users.update(caller.id, {"notify": {"channels": channels + ["webpush"]}})
deps.hub.publish({"type": "users"})
return _push_view(deps, caller.id, caller.lang)
@router.delete("/api/me/push/{device}", responses=_r(schemas.PushDevices))
def me_push_remove(deps: State, caller: CallerDep, device: str):
if not deps.push.remove(caller.id, device):
raise HTTPException(404, "no such device")
deps.hub.publish({"type": "users"})
return _push_view(deps, caller.id, caller.lang)
class PushPrefsBody(BaseModel):
levels: dict[str, str] # group → buzz | silent | off (users/push_style.py)
@router.put("/api/me/push/prefs", responses=_r(schemas.PushDevices))
def me_push_prefs(deps: State, caller: CallerDep, body: PushPrefsBody):
"""What each group of push kinds does on the caller's devices — the
browser's one notification channel, split by kind in the app."""
deps.push.set_levels(caller.id, body.levels)
deps.hub.publish({"type": "users"})
return _push_view(deps, caller.id, caller.lang)
def _test_push(deps, uid: str, by: str | None, caller_lang: str = "en") -> dict:
"""A test push on every device of ``uid``, in their language; ``by``
None ⇒ they sent it themselves."""
if not deps.push.count(uid):
raise HTTPException(400, tr(caller_lang, "no device has push turned on"))
lang = deps.users.lang_of(uid)
results = webpush.send(deps.push, uid, {
"kind": "test", "id": f"test-{int(time.time())}",
"title": tr(lang, "🔔 Push works"),
"body": tr(lang, "Sent by {by}. This is how you'll hear when a conversation "
"finishes or needs you.", by=by or tr(lang, "you")),
"url": "/"})
deps.hub.publish({"type": "users"})
return {"results": results, "devices": deps.push.of(uid)}
@router.post("/api/me/push/test", responses=_r(schemas.PushTestResult))
def me_push_test(deps: State, caller: CallerDep):
"""A test notification on every device of the caller."""
return _test_push(deps, caller.id, None, caller.lang)
# ── user admin (owner) ───────────────────────────────────────────────────────
def _spend(deps) -> dict[str, dict]:
from conversations.catalog import _conversation_cards
from users.runs import spend_by_user, with_computers
return with_computers(spend_by_user(list(_conversation_cards(deps, False))),
[u["id"] for u in deps.users.all()], deps)
def _public(deps, u: dict, spend: dict | None = None) -> dict:
"""A user as the admin page shows them: the record, their live sessions
and what their conversations cost (this month — what the budget is
checked against — and all time)."""
from accounts import guest as guest_claude
s = (spend if spend is not None else _spend(deps)).get(u["id"]) or {}
from authz import policy as authz_policy
return {"bucket": "", "domain": "",
"lang": "auto", **u,
# Role + overrides (authz/), the effective set, and the old
# switches read off it (the Access tab's panels still show them).
"role": authz_policy.role_of(u), "allow": list(u.get("allow") or ()),
"deny": list(u.get("deny") or ()), "perms": sorted(authz_policy.effective(u)),
**authz_policy.switches_view(u),
"sessions": len(deps.auth.sessions_of(u["id"])),
"spentUsd": round(s.get("month", 0.0), 4),
"totalSpentUsd": round(s.get("total", 0.0) + s.get("machineTotal", 0.0), 4),
"computersSpentUsd": round(s.get("computersMonth", 0.0), 4),
"creditUsd": round(s.get("creditMonth", 0.0), 4),
"conversations": s.get("conversations", 0),
"claude": {**guest_claude.status(deps, u["id"]),
"spentUsd": round(s.get("ownMonth", 0.0), 4),
"totalSpentUsd": round(s.get("ownTotal", 0.0), 4),
"conversations": s.get("ownConversations", 0)},
"computers": {**computers.policy(deps, u["id"]),
"count": len(computers.of(deps, u["id"]))},
"pushDevices": deps.push.of(u["id"]),
"autoFresh": auto_fresh(u),
"scratchBash": scratch_bash(u),
"codeMode": code_mode(u),
"apps": idp.clean_apps(u.get("apps")),
# Their mirror in the identity provider (users/idp.py), when one is set up.
"idp": ({"id": u.get("idpId"), **(u.get("idpSync") or {})}
if idp.enabled() else None)}
@router.get("/api/users", responses=_r(schemas.UsersResponse))
def users_list(deps: State, _: OwnerDep):
spend = _spend(deps)
return {"users": [_public(deps, u, spend) for u in
sorted(deps.users.all(), key=lambda u: u.get("name") or "")],
"levels": list(LEVELS), "channels": list(NOTIFY_CHANNELS),
"defaultModels": list(DEFAULT_MODELS), "mail": mailer.enabled(),
"guestUrl": GUEST_PUBLIC_URL or None,
"idp": {**idp.status(), "login": oidc.enabled()}}
class UserBody(BaseModel):
email: str | None = None
name: str | None = None
projects: dict | None = None
models: list[str] | None = None
budgetUsd: float | None = None
notify: dict | None = None
disabled: bool | None = None
role: str | None = None # their role (authz/roles.py): guest, member, viewer, a custom one
allow: list[str] | None = None # person-level permissions added to the role's
deny: list[str] | None = None # …and taken away from it
# The old switches: each sets an override of its permission (authz/policy.py).
cli: bool | None = None # their runs may use the ai-agent CLI (users/cli.py)
mcp: bool | None = None # they may connect AI apps over MCP (mcpserver/)
bucket: str | None = None # <name>.<bucket>.<domain>; blank ⇒ their id
domain: str | None = None # their own root domain; blank ⇒ the shared one
lang: str | None = None # auto | en | fr — the language the app speaks to them
computers: dict | None = None # {enabled, max} — their own computers (users/computers.py)
autoFresh: bool | None = None # an expired-cache reply compacts first, no confirm
scratchBash: bool | None = None # Bash in their No project conversations (users/runs.py)
codeMode: bool | None = None # Claude Code's Code Mode (beta) — the composer's chip
apps: dict | None = None # {group: bool} — the other apps of the identity provider (users/idp.py)
budgetCredit: dict | None = None # {month: YYYY-MM, usd, note} — taken off that month's spend
def _check_grants(projects: dict | None) -> None:
if projects and ROOT_SLUG in projects:
raise HTTPException(400, f"the {ROOT_SLUG!r} repo can't be granted to a guest")
@router.post("/api/users", responses=_r(schemas.GuestUser))
def users_create(deps: State, _: OwnerDep, body: UserBody):
if not body.email or not valid_email(body.email):
raise HTTPException(400, "a valid email is required")
_check_grants(body.projects)
fields = body.model_dump(exclude_none=True)
fields.pop("email", None)
try:
u = deps.users.create(norm_email(body.email), fields.pop("name", None), **fields)
except ValueError as e:
raise HTTPException(400, str(e))
if movies_bring_jellyfin(deps, u["id"]):
u = deps.users.get(u["id"]) or u
if idp.enabled():
idp.sync(deps, u)
u = deps.users.get(u["id"]) or u
deps.hub.publish({"type": "users"})
return _public(deps, u)
# What a change must touch for the guest's mirror in the identity provider.
_IDP_FIELDS = ("email", "name", "disabled", "apps")
MOVIES_PLUGIN = "movies"
def movies_bring_jellyfin(deps, uid: str) -> bool:
"""Movies on ⇒ the Jellyfin app on (form
``movies-widget-guests-what-s-new_uqbyga``, 2026-11-18): a movie they ask
for is no use without a login to watch it. Called when the ``movies``
managed plugin has just come on for them — a new guest it is on for by
default, or the owner's grant (``plugins/routes.update_user_managed_grant``)
— so switching Jellyfin back off by hand sticks. True when it switched it
on (the caller syncs the identity provider)."""
if not any(a["group"] == "jellyfin" for a in idp.APPS):
return False
store = getattr(deps, "plugin_store", None)
if store is None:
return False
try:
rec = store.get_raw("owner", MOVIES_PLUGIN)
if not rec or not rec.get("enabled") or not (rec.get("manifest") or {}).get("managed"):
return False
if not store.effective_grant(uid, MOVIES_PLUGIN, rec["manifest"]).get("enabled"):
return False
except Exception: # noqa: BLE001 — a plugin store hiccup never blocks a guest change
return False
u = deps.users.get(uid) or {}
apps = dict(u.get("apps") or {})
if apps.get("jellyfin"):
return False
deps.users.update(uid, {"apps": {**apps, "jellyfin": True}})
return True
@router.put("/api/users/{uid}", responses=_r(schemas.GuestUser))
def users_update(deps: State, _: OwnerDep, uid: str, body: UserBody):
from users import edge
_check_grants(body.projects)
cur = deps.users.get(uid) or {}
was = cur.get("domain") or ""
fields = body.model_dump(exclude_none=True)
try:
u = deps.users.update(uid, fields)
except KeyError:
raise HTTPException(404, "no such user")
except ValueError as e:
raise HTTPException(400, str(e))
if u.get("disabled"):
deps.auth.revoke_user(uid)
if idp.enabled() and (any(k in fields for k in _IDP_FIELDS) or not u.get("idpId")):
idp.sync(deps, u)
u = deps.users.get(uid) or u
if (u.get("domain") or "") not in ("", was):
# A new root domain of their own: wire it into the public edge.
edge.setup_later(deps, u["domain"])
deps.hub.publish({"type": "users"})
return _public(deps, u)
@router.delete("/api/users/{uid}", responses=_r(schemas.OkResponse))
def users_delete(deps: State, _: OwnerDep, uid: str):
"""Delete a guest for good (*disable* is the reversible one): the record,
their sessions and pending links, their ui-state, their place in the
conversations shared with them, and their own Claude login on the host.
Their conversations, transcripts and projects stay, still ``owner: <id>``
— the id is retired, so no later user inherits them."""
from accounts import guest as guest_claude
u = deps.users.get(uid)
if not u or not deps.users.delete(uid, tombstone=True):
raise HTTPException(404, "no such user")
deps.auth.revoke_user(uid)
deps.mcp.revoke_user(uid) # their AI-app connections end with them
deps.ui_state.delete_prefix(f"u.{uid}.")
deps.push.forget_user(uid)
for sid in access.forget_user(deps, uid):
deps.hub.publish({"type": "meta", "id": sid})
if (u.get("claude") or {}).get("connectedAt"):
guest_claude.sign_out_later(deps, uid)
idp.remove(u) # …and their account at the identity provider
deps.hub.publish({"type": "users"})
return {"ok": True}
@router.post("/api/users/idp-sync", responses=_r(schemas.IdpSyncResult))
def users_idp_sync(deps: State, _: OwnerDep):
"""Mirror every guest into the identity provider now (the migration, or
after Pocket ID lost its data): ``{uid: {ok, error, at}}``."""
if not idp.enabled():
raise HTTPException(409, "no identity provider configured (POCKET_ID_API_KEY)")
out = idp.sync_all(deps)
deps.hub.publish({"type": "users"})
return {"results": out}
@router.get("/api/users/{uid}/activity", responses=_r(schemas.UserActivity))
def users_activity(deps: State, _: OwnerDep, uid: str, limit: int = 50):
"""One guest's page: spend per day (30 days) and per project (this
month), their latest conversations — all from the memoized cards."""
from conversations.catalog import _conversation_cards
from users.runs import activity_of
if not deps.users.get(uid):
raise HTTPException(404, "no such user")
return activity_of(
_conversation_cards(deps, False), uid,
lambda c: access.project_of(deps.meta_store.peek(c.get("sessionId") or "")),
limit=max(1, min(limit, 200)))
@router.post("/api/users/{uid}/push-test", responses=_r(schemas.PushTestResult))
def users_push_test(deps: State, _: OwnerDep, uid: str):
"""The owner checks a guest's push: a test on every device of theirs."""
if not deps.users.active(uid):
raise HTTPException(404, "no such (enabled) user")
return _test_push(deps, uid, OWNER_NAME)
class LinkBody(BaseModel):
send: bool = False
# Which mail ``send`` sends: the invitation, the note that the guest
# surface moved (a new address: every guest is signed out, and the app on
# their home screen must be added again from it), or the one telling them
# they now sign in through the identity provider (users/oidc.py).
mail: Literal["invite", "moved", "sso"] = "invite"
@router.post("/api/users/{uid}/login-link", responses=_r(schemas.LoginLink))
def users_login_link(deps: State, request: Request, _: OwnerDep, uid: str,
body: LinkBody):
"""An invitation link — to copy into a message, or mailed (``send``) with
an invitation note. Lives ``INVITE_TTL_S`` (days), unlike the quarter-hour
link a guest asks for on the login page; still single-use."""
u = deps.users.active(uid)
if not u:
raise HTTPException(404, "no such (enabled) user")
sso = oidc.enabled()
if sso:
# A Pocket ID login code: it signs them in there once (then they add a
# passkey), and the provider carries on to this app's sign-in.
try:
lc = idp.login_code(deps, u, INVITE_TTL_S)
except idp.IdpError as e:
raise HTTPException(502, str(e))
url = f"{_origin(request)}/api/auth/oidc/start?lc={lc}"
elif body.mail == "sso":
raise HTTPException(409, "no identity provider configured (OIDC_*)")
else:
url = f"{_origin(request)}/login?token={deps.auth.mint_link(uid, INVITE_TTL_S)}"
sent = False
if body.send:
# Their language as set on their page (no browser seen yet: auto ⇒ English).
lang = deps.users.lang_of(uid)
try:
if body.mail == "sso":
mailer.sso_mail(u["email"], u.get("name") or uid, url,
home=GUEST_PUBLIC_URL or _origin(request),
apps=[a for a in idp.APPS
if (u.get("apps") or {}).get(a["group"])],
expires=_human_ttl(INVITE_TTL_S, lang), lang=lang)
elif body.mail == "moved":
mailer.moved_mail(u["email"], u.get("name") or uid, url,
home=GUEST_PUBLIC_URL or _origin(request),
expires=_human_ttl(INVITE_TTL_S, lang), lang=lang)
else:
mailer.invite_mail(
u["email"], u.get("name") or uid, url, inviter=OWNER_NAME,
projects=sorted((u.get("projects") or {}).keys()),
expires=_human_ttl(INVITE_TTL_S, lang),
home=f"{GUEST_PUBLIC_URL}/login" if GUEST_PUBLIC_URL else None,
lang=lang, sso=sso)
sent = True
except mailer.MailError as e:
raise HTTPException(502, str(e))
return {"url": url, "sent": sent, "expiresInS": INVITE_TTL_S}
def _human_ttl(s: int, lang: str = "en") -> str:
if s >= 2 * 86400:
return tr(lang, "{n} days", n=s // 86400)
if s >= 2 * 3600:
return tr(lang, "{n} hours", n=s // 3600)
return tr(lang, "{n} minutes", n=max(1, s // 60))
@router.delete("/api/users/{uid}/sessions")
def users_revoke(deps: State, _: OwnerDep, uid: str):
return {"revoked": deps.auth.revoke_user(uid)}
@router.post("/api/users/{uid}/impersonate", responses=_r(schemas.OkResponse))
def users_impersonate(deps: State, request: Request, response: Response,
owner: OwnerDep, uid: str):
"""Look at the app as this guest: a short-lived session for them, set on
*this* (the admin) host. Every request then is the guest's — their
routes, their conversations, their composer — until ``/api/auth/logout``
(the PWA's *Back to admin*) or ``IMPERSONATE_TTL_S``. It only ever
narrows what the browser can do, and the cookie is host-only: the guest
host never sees it."""
u = deps.users.active(uid)
if not u:
raise HTTPException(404, "no such (enabled) user")
deps.auth.close_session(request.cookies.get(SESSION_COOKIE, ""))
token = deps.auth.open_session(uid, request.headers.get("user-agent", ""),
impersonator=owner.id)
response.set_cookie(SESSION_COOKIE, token, max_age=IMPERSONATE_TTL_S,
httponly=True, secure=_secure(request), samesite="lax",
path="/")
return {"ok": True}
# ── what every guest gets ────────────────────────────────────────────────────
class GuestDefaultsBody(BaseModel):
sharedSkills: list[str] | None = None
computerLimits: dict | None = None # schemas.ComputerLimits
def _guest_defaults_out(deps, out: dict) -> dict:
"""``guestDefaults`` + the guests' root domain (the new-project plugin's
setting since 2026-11-27 — read-only here)."""
from users import domains as user_domains
return {**out, "domain": user_domains.default_domain(deps)}
@router.get("/api/guest-defaults", responses=_r(schemas.GuestDefaults))
def guest_defaults_get(deps: State, _: OwnerDep):
return _guest_defaults_out(deps, deps.users.defaults())
@router.put("/api/guest-defaults", responses=_r(schemas.GuestDefaults))
def guest_defaults_put(deps: State, _: OwnerDep, body: GuestDefaultsBody):
"""What every guest gets: the skills every guest run is handed (sidecar
``shared_skills`` — a skill toggle in the catalog sends the whole list)
and the computer limits. (Their prompt shortcuts are the
prompt-shortcuts plugin's since 2026-11-27, the New projects policy —
quota, templates, visibility, level, domain — the new-project plugin's,
and their scheduled jobs' limits the cron-jobs plugin's since 2026-11-28.)"""
out = deps.users.set_defaults(body.model_dump(exclude_none=True))
deps.hub.publish({"type": "users"})
return _guest_defaults_out(deps, out)
@router.get("/api/guest-skills", responses=_r(schemas.GuestSkillsResponse))
def guest_skills(deps: State, caller: CallerDep):
"""The skills the caller's runs can use, for the composer's mentions: the
owner's shared ones (as ``shared:<name>``, the plugin's namespace) and
the granted projects' own ``.claude/skills``."""
from dashboards import skills as skills_mod
shared = deps.users.defaults()["sharedSkills"]
cat = skills_mod.catalog()
by_ref = {skills_mod.share_ref(s): s for s in cat}
out, seen = [], set()
for ref in shared:
s = by_ref.get(ref)
if s and s["name"] not in seen:
seen.add(s["name"])
out.append({"name": f"shared:{s['name']}", "description": s["description"],
"triggerWords": s["triggerWords"], "source": "shared"})
for s in cat:
if s["sourceKind"] == "project" and caller.can(s["source"], "chat"):
out.append({"name": s["name"], "description": s["description"],
"triggerWords": s["triggerWords"], "source": s["source"]})
return {"skills": out}
# ── conversation sharing ─────────────────────────────────────────────────────
def _name(deps, uid: str) -> str:
if uid == OWNER_ID:
return OWNER_NAME
u = deps.users.get(uid) or {}
return u.get("name") or uid
def _share_state(deps, sid: str, caller) -> dict:
meta = deps.meta_store.peek(sid)
slug = access.project_of(meta)
owner = meta.get("owner")
candidates = [{"id": u["id"], "name": u.get("name") or u["id"],
"level": (u.get("projects") or {}).get(slug)}
for u in deps.users.all()
if not u.get("disabled") and u["id"] != owner]
audience = access.audience(meta)
return {"sessionId": sid, "owner": owner, "project": slug,
"participants": list(meta.get("participants") or []),
"candidates": candidates,
"notifying": caller.id in audience,
"audience": [{"id": u, "name": _name(deps, u)} for u in audience]}
@router.get("/api/conversation-share", responses=_r(schemas.ConversationShare))
def share_get(deps: State, caller: CallerDep, id: str):
sid = access.session_of(id)
access.ensure_visible(deps, caller, sid)
out = _share_state(deps, sid, caller)
if not caller.is_owner:
# A guest only sees who's in it — not the owner's whole guest list.
out["candidates"] = [c for c in out["candidates"] if c["level"]]
return out
class ShareBody(BaseModel):
id: str
participants: list[str]
@router.put("/api/conversation-share", responses=_r(schemas.ConversationShare))
def share_put(deps: State, caller: CallerDep, body: ShareBody):
"""Who else may read and write this conversation. The owner can share
anything with anyone; the guest who started a conversation can share it
with users who already have access to its project."""
sid = access.session_of(body.id)
access.ensure_visible(deps, caller, sid)
meta = deps.meta_store.peek(sid)
slug = access.project_of(meta)
if not caller.is_owner and meta.get("owner") != caller.id:
raise HTTPException(403, tr(caller.lang, "only the conversation's owner can share it"))
want = list(dict.fromkeys(p for p in body.participants if p))
for uid in want:
u = deps.users.active(uid)
if not u:
raise HTTPException(400, tr(caller.lang, "unknown user '{user}'", user=uid))
if not caller.is_owner and not (u.get("projects") or {}).get(slug):
raise HTTPException(403, tr(caller.lang, "{name} has no access to '{project}'",
name=u.get("name") or uid, project=slug))
deps.meta_store.update(sid, {"participants": [u for u in want
if u != meta.get("owner")]})
deps.hub.publish({"type": "meta", "id": sid})
return _share_state(deps, sid, caller)
class FollowBody(BaseModel):
id: str
on: bool
@router.put("/api/conversation-follow", responses=_r(schemas.ConversationShare))
def follow_put(deps: State, caller: CallerDep, body: FollowBody):
"""Turn the caller's notifications for one conversation on or off — the
bell in its header. On for the owner on a guest's conversation means
*follow it*; off for anyone means *mute it* (users/access.audience)."""
sid = access.session_of(body.id)
access.ensure_visible(deps, caller, sid)
access.set_follow(deps, sid, caller.id, body.on)
out = _share_state(deps, sid, caller)
if not caller.is_owner:
out["candidates"] = [c for c in out["candidates"] if c["level"]]
return out
# ── a guest's own root domain (users/edge.py) ────────────────────────────────
def _own_domain(deps, uid: str) -> str:
u = deps.users.get(uid)
if not u:
raise HTTPException(404, "no such user")
if not (u.get("domain") or "").strip():
raise HTTPException(404, f"{uid} has no root domain of their own")
return u["domain"]
@router.get("/api/users/{uid}/domain", responses=_r(schemas.DomainStatus))
def user_domain_status(deps: State, _: OwnerDep, uid: str, cached: bool = False):
"""Where a guest's own root domain stands at the public edge: DNS,
routing, zipgo folder, certificate. ``cached`` answers with the last
check when there is one (instant) instead of checking again."""
from users import edge
domain = _own_domain(deps, uid)
return (cached and edge.last(domain)) or edge.status(deps, domain)
@router.post("/api/users/{uid}/domain/setup", responses=_r(schemas.DomainStatus))
def user_domain_setup(deps: State, _: OwnerDep, uid: str):
"""Wire a guest's own root domain into the public edge — again: saving it
already did, this finishes the job once the DNS has propagated.
Idempotent."""
from users import edge
return edge.setup(deps, _own_domain(deps, uid))