Files
ai-agent/backend/users/routes.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

858 lines
39 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, clean_tools, 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,
# The owner is always English; a guest's stored pick (auto = their
# browser's — the PWA resolves it, frontend/src/i18n).
"lang": "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.shortcuts import guest_shortcuts
out["sharedShortcuts"] = guest_shortcuts(deps)
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)
out["tools"] = tools_view(u)
return out
def tools_view(u: dict) -> dict:
"""A guest's paid tools (toolproxy/): the switches and this month's usage
against their tools budget."""
from toolproxy.ledger import LEDGER
return {**clean_tools(u.get("tools")), "usage": LEDGER.summary("who", u["id"])}
# ── 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 | fr (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."""
if caller.is_owner:
raise HTTPException(400, "the owner's settings live in Settings")
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": "", "whatsNew": True,
"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"]))},
"tools": tools_view(u),
"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
whatsNew: bool | None = None # the feature carousel opens on its own (whatsnew/)
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
tools: dict | None = None # {groups, pro, budgetUsd} — their paid tools (toolproxy/)
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"], None):
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")
def _movies_bring_jellyfin(deps, uid: str, before: set | None) -> 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. Only when Movies has just come
on (``before``: the groups before the change, None for a new guest), so
switching Jellyfin back off by hand sticks. True when it switched it on."""
if not any(a["group"] == "jellyfin" for a in idp.APPS):
return False
u = deps.users.get(uid) or {}
if "media" not in clean_tools(u.get("tools"))["groups"]:
return False
if before is not None and "media" in before:
return False
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 ""
had = set(clean_tools(cur.get("tools"))["groups"])
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 "tools" in fields and _movies_bring_jellyfin(deps, uid, had):
u = deps.users.get(uid) or u
fields["apps"] = u.get("apps")
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.whats_new.forget_user(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):
promptShortcuts: list[dict] | None = None
sharedSkills: list[str] | None = None
newProjects: dict | None = None # schemas.NewProjectPolicy
computerLimits: dict | None = None # schemas.ComputerLimits
cronLimits: dict | None = None # schemas.GuestCronLimits
@router.get("/api/guest-defaults", responses=_r(schemas.GuestDefaults))
def guest_defaults_get(deps: State, _: OwnerDep):
return deps.users.defaults()
@router.put("/api/guest-defaults", responses=_r(schemas.GuestDefaults))
def guest_defaults_put(deps: State, _: OwnerDep, body: GuestDefaultsBody):
"""The starting shortcuts a new guest gets and the skills every guest run
is handed (sidecar ``shared_skills``) — a skill toggle in the catalog
sends the whole list."""
out = deps.users.set_defaults(body.model_dump(exclude_none=True))
deps.hub.publish({"type": "users"})
return 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))