Files
gabrielvidalandClaude Opus 5.5 4d0dcfa3ff refactor(toolproxy): the tools are plugins — retire the core brokers, the guests' tool groups and the hub editions
Since 2026-11-25 nanobanana, video-extract, 3d-gen, 3d-render, matomo,
movies and meta are live plugins with their own proxies and managed grants,
but the core still served the old path next to them — and its hub editions
won over the plugin skills on workers. This finishes the move (form
ai-agent-moves-to-ai-agent-plugins_o2qxmd, move A). Rebased on 41665fa2,
which had already removed the core's Meta Business.

- gone: toolproxy/{matomo,media,webroutes,owned,catalog}.py, the nanobanana /
  3d-gen / 3d-render / video-extract / matomo / movies routes and the movies
  webhook, cli/skills/{nanobanana,3d-gen,3d-render,video-extract,matomo,
  movies}, the guests' `tools` groups (users store, Caller.tool_groups,
  Me/GuestUser.tools, tools.matomoSites), the User page's Paid tools and
  Tools budget panels
- kept: the /proxy/tools door (tokens, whoami — now the caller's plugins and
  spend — and the shared client), the tool ledger, the tools chip, a guest
  job's tool token (c6e15991: tool_scope still gives one with plugin skills)
- labsync: a plugin skill wins over a lab skill of the same name; plugin
  skills with a proxy keep their hub.json
- guest runs get their plugins' skills on spawn, resume, reply, fork and No
  project runs alike (deps passed to scope_for / scratch_scope everywhere)
- Movies brings Jellyfin when the movies grant comes on (new guest, or the
  owner's switch)
- plugins/carryover_tools.py: tool groups → grants / installs (never over an
  explicit grant), Meta keys + saved days (only where the plugin has none),
  Matomo viewers, Seerr users and pending requests, 3d-gen ownership → the
  plugins' data, once
- matomo_sites: users.json tools.matomoSites → the matomo grant's
  `extraSites` (list grantField, sibling ai-agent-plugins PR), and the grant
  on for an `analytics` guest — once per guest, so Cel (analytics + site 11
  after the groups moved) gets it; an explicit grant only gets extraSites
  when it has none; waits for a matomo manifest with the field
- Me → Budget's Tools card reads the guest's managed plugins

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:44:24 +01:00

204 lines
7.5 KiB
Python

"""
Who is calling the tool proxy — the bearer tokens and the caller they name.
Two kinds of bearer, both answered on any host (the proxy is outside ``/api``:
no Authelia, no trusted-caller gate — the token is the whole auth):
* a **run token** (``aiat1.<uid>.<exp>.<sig>``) — minted for a guest's run on
the lab (``users/runs.scope_for`` → the run's ``AIA_TOOLS_TOKEN``), an HMAC
with a key only the hub holds; it names the guest, and expires;
* a **worker's proxy token** — the one its Claude proxy already uses
(``claudeproxy.service``), shipped to the machine in the plugin skills'
``hub.json`` (``workers/labsync``): a guest's computer is that guest, an
owner's worker is the owner;
* the lab's **internal token** (the owner, on the lab), and a plugin
**handler token** (``aiah1.…``, the plugin routes only).
What a caller may then do is the plugin side's call (``plugins/metering.py``:
grants, limits, budgets) — the per-tool groups, Pro switch and tools budget
that used to be checked here left with the core brokers (2026-11-26).
"""
from __future__ import annotations
import base64
import dataclasses
import hashlib
import hmac
import os
import pathlib
import re
import secrets
import threading
import time
KEY_PATH = pathlib.Path(os.environ.get("TOOLS_TOKEN_KEY", "/data/tools-token.key"))
TOKEN_TTL_S = int(os.environ.get("TOOLS_TOKEN_TTL_S", str(3 * 86400)))
PREFIX = "aiat1"
# A plugin handler's own token (``plugins/runner.py``): names the user AND the
# plugin, so ``/proxy/tools/plugins/<pid>/…`` can tell the plugin's code from
# the guest's run calling the same door (handler-only proxy rules).
HANDLER_PREFIX = "aiah1"
_PID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
_UID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
_key_lock = threading.Lock()
_key: bytes | None = None
def _secret() -> bytes:
global _key
if _key is not None:
return _key
with _key_lock:
if _key is None:
try:
k = KEY_PATH.read_bytes().strip()
except OSError:
k = b""
if len(k) < 32:
k = base64.urlsafe_b64encode(secrets.token_bytes(32))
try:
KEY_PATH.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(KEY_PATH, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "wb") as f:
f.write(k)
except OSError:
pass
_key = k
return _key
def _sig(payload: str) -> str:
d = hmac.new(_secret(), payload.encode(), hashlib.sha256).digest()
return base64.urlsafe_b64encode(d).decode().rstrip("=")
def mint(uid: str, ttl: int = TOKEN_TTL_S, now: float | None = None) -> str:
exp = int((now if now is not None else time.time()) + ttl)
payload = f"{PREFIX}.{uid}.{exp}"
return f"{payload}.{_sig(payload)}"
def verify(token: str, now: float | None = None) -> str | None:
"""The guest a run token names, when it is ours and still good."""
parts = (token or "").split(".")
if len(parts) != 4 or parts[0] != PREFIX or not _UID_RE.match(parts[1]):
return None
try:
exp = int(parts[2])
except ValueError:
return None
if exp < (now if now is not None else time.time()):
return None
if not hmac.compare_digest(_sig(".".join(parts[:3])), parts[3]):
return None
return parts[1]
def mint_handler(uid: str, pid: str, ttl: int, now: float | None = None) -> str:
"""A token for one plugin handler run: ``aiah1.<uid>.<pid>.<exp>.<sig>``."""
exp = int((now if now is not None else time.time()) + ttl)
payload = f"{HANDLER_PREFIX}.{uid}.{pid}.{exp}"
return f"{payload}.{_sig(payload)}"
def verify_handler(token: str, now: float | None = None) -> tuple[str, str] | None:
"""``(uid, pid)`` a handler token names, when it is ours and still good."""
parts = (token or "").split(".")
if (len(parts) != 5 or parts[0] != HANDLER_PREFIX or not _UID_RE.match(parts[1])
or not _PID_RE.match(parts[2])):
return None
try:
exp = int(parts[3])
except ValueError:
return None
if exp < (now if now is not None else time.time()):
return None
if not hmac.compare_digest(_sig(".".join(parts[:4])), parts[4]):
return None
return parts[1], parts[2]
@dataclasses.dataclass
class Who:
uid: str | None # the guest; None = the owner
worker: dict | None = None
via: str = "run" # "run" | "worker" | "lab" | "handler"
handler: str | None = None # the plugin id a handler token is for
@property
def is_owner(self) -> bool:
return self.uid is None
@property
def key(self) -> str:
return self.uid or "owner"
def row(self) -> dict:
"""The ledger fields naming the caller."""
out: dict = {"who": self.key, "via": self.via}
if self.uid:
out["guest"] = self.uid
if self.worker:
out["worker"] = self.worker["id"]
return out
def resolve(deps, token: str, *, guest_surface: bool,
allow_handler: bool = False) -> Who | None:
"""The caller a bearer names (None: no one). A plugin handler's token is
only honoured where the caller asks for it (the plugin routes), and never
out on the public guest host — handlers call the hub over loopback."""
if (token or "").startswith(HANDLER_PREFIX + "."):
if not allow_handler or guest_surface:
return None
got = verify_handler(token)
if not got:
return None
uid, pid = got
return Who(None if uid == "owner" else uid, None, "handler", pid)
if (token or "").startswith(PREFIX + "."):
uid = verify(token)
if not uid:
return None
if uid == "owner":
return None if guest_surface else Who(None, None, "run")
return Who(uid, None, "run")
# The lab's own skills (``nanobanana`` in ~/homelab) hold the hub's
# internal token from the root .env: the owner, on the lab — never on the
# public guest host.
from core.auth import INTERNAL_API_TOKEN
if (INTERNAL_API_TOKEN and token and not guest_surface
and hmac.compare_digest(token, INTERNAL_API_TOKEN)):
return Who(None, None, "lab")
from claudeproxy import service
from workers import guests
w = service.worker_for_token(deps.worker_store, token)
if not w:
return None
if guest_surface and not guests.is_guest(w):
# The owner's workers reach the hub over the tailnet; out on the public
# guest host their tokens are no one's.
return None
return Who(guests.owner_of(w), w, "worker")
# ── which conversation ───────────────────────────────────────────────────────
_SID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
def session_of(deps, who: Who, raw: str | None) -> str | None:
"""The conversation a call came from (its Claude Code session id,
``X-Claude-Code-Session-Id``), kept only when it is the caller's: a
guest's own conversation — never one that is someone else's."""
sid = (raw or "").strip().lower()
if not _SID_RE.match(sid):
return None
if who.is_owner:
return sid
try:
meta = deps.meta_store.peek(sid) or {}
except Exception:
return None
return sid if meta.get("owner") == who.uid else None