- authz/catalog.py: 42 named permissions in groups and tiers (person, admin, host); authz/roles.py: built-in Operator (the owner), Admin (assignable with team mode), Member, Guest, Viewer + custom clones, in roles.json - a person = role + allow/deny overrides (authz/policy.py); users.json's old switches (cli, mcp, createProjects, scratchBash, codeMode, computers.enabled) migrate once to exactly what they allowed, backup kept - authz/scopes.py: what a credential acting for someone keeps (cli, worker.read|run, bot, phone) — a scope only narrows - authz/routes.py: (method, path) -> permission for all 310 /api routes; the gate asks Caller.allows() for every caller kind, replacing GUEST_ROUTES, CLI_ROUTES and the worker READ/RUN_ROUTES regex lists - golden route x caller matrix (authz/matrix.golden.txt, test_authz_matrix) - the claude bot reads the admin app minus people/security/the machine; the phone key reads its unread notifications only - loopback without the host token is logged (loopback_tokenless), refusals are perm_denied lines; the hub's own MCP calls send the token - /api/roles CRUD, /api/me and /api/users carry role/allow/deny/perms - worker-bound scheduled items and conversation-meta respect the binding Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
354 lines
15 KiB
Python
354 lines
15 KiB
Python
"""
|
|
A guest's own computers — workers they pair from their portal.
|
|
|
|
The owner switches it on per guest (``users.json`` ``computers: {enabled,
|
|
max}``, default off, max ``DEFAULT_MAX_COMPUTERS``). The guest then adds a
|
|
computer from Me → *My computers*: the portal mints a one-time enroll code and
|
|
shows the installer's one line (``POST /api/me/computers``); the machine dials
|
|
out to the guest host and pairs through the worker link (``workers/link.py``).
|
|
|
|
Everything such a machine's Claude Code sends bills the **owner's** default
|
|
account through the Claude proxy (Gabriel's call, form
|
|
``guest-workers-guests-own-computers_q9ztmc``), held to the guest's budget and
|
|
models and to ``guestDefaults.computerLimits`` (``claudeproxy/limits.py``).
|
|
There are no lab projects on a guest's computer (same form): a run there starts
|
|
in the machine's start folder — or, picked in the composer's project pill, in
|
|
one of the projects deduced from where its conversations wrote
|
|
(projects/worker_projects.py; ``users/runs.computer_project``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter, HTTPException
|
|
from pydantic import BaseModel
|
|
|
|
import schemas
|
|
from core.http import _r
|
|
from core.i18n import tr
|
|
from core.state import State
|
|
from users.caller import CallerDep, OwnerDep
|
|
from users.deliver import GUEST_PUBLIC_URL
|
|
from users.store import DEFAULT_MAX_COMPUTERS, clean_computers
|
|
from workers import guests, link
|
|
|
|
INSTALL_URL = "https://git.gabvdl.xyz/gabrielvidal/ai-agent/raw/branch/main/worker/install.sh"
|
|
|
|
|
|
def policy(deps, uid: str) -> dict:
|
|
"""``{"enabled", "max"}`` for this guest: ``computers.pair`` (their role,
|
|
or an override — authz/) and how many."""
|
|
from authz import policy as authz_policy
|
|
u = deps.users.get(uid) or {}
|
|
return {**clean_computers(u.get("computers"), {"max": DEFAULT_MAX_COMPUTERS}),
|
|
"enabled": authz_policy.has(u, "computers.pair")}
|
|
|
|
|
|
def of(deps, uid: str) -> list[dict]:
|
|
"""The guest's computers (records)."""
|
|
return [w for w in deps.worker_store.list() if guests.owner_of(w) == uid]
|
|
|
|
|
|
def may_add(deps, uid: str, lang: str = "en") -> str | None:
|
|
"""Why this guest can't add a computer now, else None."""
|
|
p = policy(deps, uid)
|
|
if not p["enabled"]:
|
|
return tr(lang, "adding your own computers isn't switched on for you")
|
|
if len(of(deps, uid)) >= p["max"]:
|
|
return tr(lang, "you already have {n} computers — remove one first", n=p["max"])
|
|
return None
|
|
|
|
|
|
def public(deps, w: dict) -> dict:
|
|
"""What the guest (and the owner's view of them) sees of a computer."""
|
|
st = deps.worker_store.status(w["id"])
|
|
from claudeproxy import limits
|
|
from users import runs as guest_runs
|
|
return {"id": w["id"], "name": w.get("name"), "hostname": w.get("hostname"),
|
|
"platform": w.get("platform"), "machine": w.get("machine"),
|
|
"status": "pairing" if w.get("pending") else st.get("status", "unknown"),
|
|
"lastSeen": st.get("lastSeen"), "running": st.get("running", 0),
|
|
"pairedAt": w.get("pairedAt"), "enrolledAt": w.get("enrolledAt"),
|
|
"cwd": w.get("cwd"), "lastError": st.get("lastError"),
|
|
"spentUsd": round(limits.LEDGER.spent("worker", w["id"]), 4),
|
|
"paused": bool(w.get("paused")),
|
|
"mirroredMb": round(guests.MIRROR.used(w["id"]) / 1048576, 1),
|
|
"launcher": (st.get("terminal") or {}).get("launcher"),
|
|
"syncedSessions": (st.get("terminal") or {}).get("synced") or 0,
|
|
# its own Claude login: their runs there bill it first (users/runs)
|
|
"ownClaude": guest_runs.computer_own(deps, guests.owner_of(w), w),
|
|
# its Setup checklist and what it can install from here (workers/tools.py)
|
|
"tools": st.get("tools") if isinstance(st.get("tools"), dict) else None,
|
|
"toolsCheckedAt": st.get("toolsCheckedAt"),
|
|
"toolInstall": st.get("toolInstall") if isinstance(st.get("toolInstall"), dict) else None,
|
|
"toolJobs": st.get("toolJobs") if isinstance(st.get("toolJobs"), dict) else None}
|
|
|
|
|
|
def install_command(code: str) -> str:
|
|
return (f"curl -fsSL {INSTALL_URL} | WORKER_HUB={GUEST_PUBLIC_URL} "
|
|
f"WORKER_ENROLL={code} bash")
|
|
|
|
|
|
def waiting(deps, uid: str, lang: str = "en") -> dict | None:
|
|
"""Why this guest's computers can't call Claude right now — their month's
|
|
budget is spent, or the owner's plan is past the guests' ceiling — as
|
|
``{kind, message}`` (the banner on their Me page), else None."""
|
|
import accounts as accounts_mod
|
|
from claudeproxy import limits
|
|
from users import runs as guest_runs
|
|
u = deps.users.get(uid) or {}
|
|
budget = u.get("budgetUsd")
|
|
if budget is not None and guest_runs.month_spend_all(deps, uid) >= float(budget):
|
|
return {"kind": "budget", "message": tr(lang, "your monthly budget is spent — "
|
|
"your computers wait until the 1st")}
|
|
lim = deps.users.defaults()["computerLimits"]
|
|
pct = limits.window_pct(deps.usage_poller, accounts_mod.DEFAULT)
|
|
if pct.get("five_hour", 0) >= lim["fiveHourPct"] or \
|
|
pct.get("seven_day", 0) >= lim["sevenDayPct"]:
|
|
return {"kind": "plan", "message": tr(lang, "the shared Claude plan is busy — "
|
|
"your computers wait until it frees up")}
|
|
return None
|
|
|
|
|
|
def listing(deps, uid: str, lang: str = "en") -> dict:
|
|
from claudeproxy import limits
|
|
from users import runs as guest_runs
|
|
p = policy(deps, uid)
|
|
mine = of(deps, uid)
|
|
u = deps.users.get(uid) or {}
|
|
return {"computers": [public(deps, w) for w in mine], "enabled": p["enabled"],
|
|
"max": p["max"], "limits": deps.users.defaults()["computerLimits"],
|
|
"spentUsd": round(limits.LEDGER.spent("guest", uid), 4),
|
|
"monthUsd": round(guest_runs.month_spend_all(deps, uid), 4),
|
|
"budgetUsd": u.get("budgetUsd"),
|
|
"waiting": waiting(deps, uid, lang),
|
|
"enrolling": link.ENROLL.pending(uid)}
|
|
|
|
|
|
def remove(deps, wid: str, who: str | None) -> bool:
|
|
from workers.store import unpair
|
|
w = deps.worker_store.get(wid)
|
|
if not w:
|
|
return False
|
|
gone = unpair(deps.worker_store, wid)
|
|
if gone:
|
|
from security.service import record
|
|
record(deps, "guest_worker_removed", who=guests.owner_of(w),
|
|
detail=f"{w.get('name')} (by {who or 'owner'})", data={"worker": wid})
|
|
deps.hub.publish({"type": "workers"})
|
|
return gone
|
|
|
|
|
|
# ── routes ───────────────────────────────────────────────────────────────────
|
|
router = APIRouter()
|
|
|
|
|
|
def _guest(caller):
|
|
if caller is None or caller.role != "guest":
|
|
raise HTTPException(404, "not a guest")
|
|
return caller
|
|
|
|
|
|
def _mine(deps, caller, wid: str) -> dict:
|
|
w = deps.worker_store.get(wid)
|
|
if not w or guests.owner_of(w) != caller.id:
|
|
raise HTTPException(404, {"message": tr(caller.lang, "no such computer"),
|
|
"kind": "computer_unknown"})
|
|
return w
|
|
|
|
|
|
@router.get("/api/me/computers", responses=_r(schemas.ComputersResponse))
|
|
def my_computers(deps: State, caller: CallerDep):
|
|
"""The caller's own computers, whether they may add one, and the limits."""
|
|
caller = _guest(caller)
|
|
return listing(deps, caller.id, caller.lang)
|
|
|
|
|
|
@router.post("/api/me/computers", responses=_r(schemas.ComputerEnroll))
|
|
def add_computer(deps: State, caller: CallerDep):
|
|
"""A one-time code (an hour) and the install line that uses it."""
|
|
caller = _guest(caller)
|
|
problem = may_add(deps, caller.id, caller.lang)
|
|
if problem:
|
|
raise HTTPException(403, {"message": problem, "kind": "computers_refused"})
|
|
out = link.ENROLL.mint(caller.id)
|
|
deps.hub.publish({"type": "workers"})
|
|
return {**out, "command": install_command(out["code"])}
|
|
|
|
|
|
class ComputerPatch(BaseModel):
|
|
name: str | None = None
|
|
# Pause it: no run starts there and the proxy refuses its calls.
|
|
paused: bool | None = None
|
|
# Its terminal `claude` asks which Claude to use (workers/terminal.py).
|
|
launcher: bool | None = None
|
|
|
|
|
|
@router.patch("/api/me/computers/{wid}", responses=_r(schemas.Computer))
|
|
def rename_computer(deps: State, caller: CallerDep, wid: str, body: ComputerPatch):
|
|
caller = _guest(caller)
|
|
_mine(deps, caller, wid)
|
|
changes: dict = {}
|
|
if body.name and body.name.strip():
|
|
changes["name"] = body.name.strip()[:60]
|
|
if body.paused is not None:
|
|
changes["paused"] = bool(body.paused)
|
|
if body.launcher is not None:
|
|
out = _call(deps, caller, wid, "/terminal/launcher", {"on": bool(body.launcher)}, "PUT")
|
|
held = deps.worker_store.status(wid).get("terminal") or {}
|
|
deps.worker_store.set_status(wid, terminal={**held, "launcher": out.get("launcher")})
|
|
if changes:
|
|
deps.worker_store.patch(wid, changes)
|
|
if changes or body.launcher is not None:
|
|
deps.hub.publish({"type": "workers"})
|
|
return public(deps, deps.worker_store.get(wid) or {"id": wid})
|
|
|
|
|
|
# ── its own terminal sessions (workers/terminal.py) ──────────────────────────
|
|
def _call(deps, caller, wid: str, path: str, payload=None, method: str = "GET") -> dict:
|
|
"""One call to the guest's computer; 409 ``computer_offline`` when it
|
|
can't take it (offline, or a sidecar from before the launcher)."""
|
|
from workers.store import sidecar_request
|
|
w = _mine(deps, caller, wid)
|
|
if not deps.worker_store.online(wid):
|
|
raise HTTPException(409, {"message": tr(caller.lang, "this computer is offline"),
|
|
"kind": "computer_offline"})
|
|
if deps.worker_store.status(wid).get("terminal") is None:
|
|
raise HTTPException(409, {"message": tr(caller.lang, "this computer hasn't "
|
|
"updated yet — try again in a few minutes"),
|
|
"kind": "computer_outdated"})
|
|
return sidecar_request(w["url"], w["token"], path, payload, method=method,
|
|
timeout=20, label=f"computer {w.get('name') or wid}")
|
|
|
|
|
|
def _sid(caller, sid: str) -> str:
|
|
from workers.terminal import SID_RE
|
|
sid = (sid or "").strip().lower()
|
|
if not SID_RE.match(sid):
|
|
raise HTTPException(400, {"message": tr(caller.lang, "not a session id"),
|
|
"kind": "session_id"})
|
|
return sid
|
|
|
|
|
|
def _in_app(deps, wid: str, sid: str) -> str | None:
|
|
m = deps.meta_store.peek(sid) or {}
|
|
if m.get("worker") == wid:
|
|
return "run"
|
|
if m.get("workerSource") == wid:
|
|
return m.get("terminal") or "run"
|
|
return None
|
|
|
|
|
|
def _conversation_id(deps, proj: str, sid: str) -> str:
|
|
"""The public id (a UUIDv7) of a session the app has: the indexed
|
|
conversation's, else the one its transcript will be archived under (the
|
|
mirror keeps Claude Code's ``<project>/<sid>.jsonl`` layout)."""
|
|
from conversations import ids
|
|
from conversations.catalog import _conv_ids_by_session
|
|
return _conv_ids_by_session(deps).get(sid) or ids.uid_for_rel(f"{proj}/{sid}.jsonl")
|
|
|
|
|
|
@router.get("/api/me/computers/{wid}/sessions", responses=_r(schemas.TerminalSessions))
|
|
def computer_sessions(deps: State, caller: CallerDep, wid: str):
|
|
"""The computer's recent Claude Code sessions — read from it now, never
|
|
kept — and how the app has each."""
|
|
caller = _guest(caller)
|
|
out = _call(deps, caller, wid, "/terminal/sessions?limit=40")
|
|
rows = []
|
|
for r in out.get("sessions") or []:
|
|
sid = str(r.get("id") or "")
|
|
how = _in_app(deps, wid, sid)
|
|
proj = r.get("project")
|
|
rows.append({**{k: r.get(k) for k in ("id", "title", "prompt", "cwd", "mtime", "synced")},
|
|
"inApp": how,
|
|
"conversationId": _conversation_id(deps, proj, sid) if how and proj else None})
|
|
return {"sessions": rows, "launcher": bool(out.get("launcher", True))}
|
|
|
|
|
|
@router.post("/api/me/computers/{wid}/sessions/{sid}/sync")
|
|
def sync_session(deps: State, caller: CallerDep, wid: str, sid: str):
|
|
"""Share one of the computer's sessions: the next mirror pass takes it."""
|
|
caller = _guest(caller)
|
|
out = _call(deps, caller, wid, "/terminal/sync", {"sid": _sid(caller, sid)})
|
|
deps.feed_mirror and deps.feed_mirror.rewind(wid)
|
|
return {"ok": bool(out.get("ok"))}
|
|
|
|
|
|
@router.delete("/api/me/computers/{wid}/sessions/{sid}/sync")
|
|
def unsync_session(deps: State, caller: CallerDep, wid: str, sid: str):
|
|
"""Stop syncing it: what the app already has stays."""
|
|
caller = _guest(caller)
|
|
sid = _sid(caller, sid)
|
|
return {"ok": bool(_call(deps, caller, wid, f"/terminal/sync/{sid}", None, "DELETE").get("ok"))}
|
|
|
|
|
|
@router.delete("/api/me/computers/{wid}")
|
|
def remove_computer(deps: State, caller: CallerDep, wid: str):
|
|
caller = _guest(caller)
|
|
_mine(deps, caller, wid)
|
|
return {"ok": remove(deps, wid, caller.id)}
|
|
|
|
|
|
@router.get("/api/users/{uid}/computers", responses=_r(schemas.ComputersResponse))
|
|
def user_computers(deps: State, _: OwnerDep, uid: str):
|
|
"""A guest's computers, for their page (Settings → Users)."""
|
|
if not deps.users.get(uid):
|
|
raise HTTPException(404, "no such user")
|
|
return listing(deps, uid)
|
|
|
|
|
|
@router.delete("/api/users/{uid}/computers/{wid}")
|
|
def user_remove_computer(deps: State, _: OwnerDep, uid: str, wid: str):
|
|
w = deps.worker_store.get(wid)
|
|
if not w or guests.owner_of(w) != uid:
|
|
raise HTTPException(404, "no such computer")
|
|
return {"ok": remove(deps, wid, None)}
|
|
|
|
|
|
# ── its tools: the Setup checklist's Install / Update, gh's Sign in ─────────
|
|
class ComputerToolsBody(BaseModel):
|
|
tools: list[str]
|
|
action: str = "install"
|
|
|
|
|
|
@router.post("/api/me/computers/{wid}/tools", responses=_r(schemas.Computer))
|
|
def install_computer_tools(deps: State, caller: CallerDep, wid: str, body: ComputerToolsBody):
|
|
"""Install claude / gh / pi on the guest's own computer (workers/tools.py:
|
|
the hub names the tools, the computer's own checkout holds the recipes)."""
|
|
from workers import tools as tools_mod
|
|
caller = _guest(caller)
|
|
w = _mine(deps, caller, wid)
|
|
names = tools_mod.check(deps.worker_store, w, body.tools, body.action,
|
|
msg=lambda s, **kw: tr(caller.lang, s, **kw))
|
|
tools_mod.install(deps.worker_store, w, names, body.action)
|
|
deps.hub.publish({"type": "workers"})
|
|
return public(deps, deps.worker_store.get(wid) or w)
|
|
|
|
|
|
def _gh(deps, caller, wid: str, method: str) -> dict:
|
|
from workers import tools as tools_mod
|
|
caller = _guest(caller)
|
|
w = _mine(deps, caller, wid)
|
|
if not deps.worker_store.online(wid):
|
|
raise HTTPException(409, {"message": tr(caller.lang, "this computer is offline"),
|
|
"kind": "computer_offline"})
|
|
out = tools_mod.gh_login(w, method)
|
|
if method == "GET" and out.get("state") == "complete":
|
|
deps.worker_monitor.check(wid)
|
|
return out
|
|
|
|
|
|
@router.post("/api/me/computers/{wid}/gh-login", responses=_r(schemas.GhLogin))
|
|
def computer_gh_login(deps: State, caller: CallerDep, wid: str):
|
|
"""gh's sign-in on their computer, to their own GitHub account."""
|
|
return _gh(deps, caller, wid, "POST")
|
|
|
|
|
|
@router.get("/api/me/computers/{wid}/gh-login", responses=_r(schemas.GhLogin))
|
|
def computer_gh_login_state(deps: State, caller: CallerDep, wid: str):
|
|
return _gh(deps, caller, wid, "GET")
|
|
|
|
|
|
@router.delete("/api/me/computers/{wid}/gh-login")
|
|
def computer_gh_login_cancel(deps: State, caller: CallerDep, wid: str):
|
|
return _gh(deps, caller, wid, "DELETE")
|