Files
gabrielvidalandClaude Fable 5.2 df9c0ac5f3 feat(plugins): the MCP server leaves core for the hub-mcp plugin; a worker's CLI gets Full
The hub as an MCP server (OAuth 2.1, the consent page, /mcp, Settings → AI
apps) is the `hub-mcp` live plugin now (ai-agent-plugins). Core keeps nothing
about MCP: four generic plugin contracts replace backend/mcpserver/.
Gabriel's picks: form move-the-hub-mcp-server-into-a-plugin_2od10i.

New contracts (docs/plugins.md → "HTTP endpoints, the hub's API and asks"):
- `endpoints[]` (plugins/endpoints.py): HTTP a plugin answers on the hub's own
  address — under /x/<pluginId>/… or a protocol path (/mcp, /oauth/…,
  /.well-known/…). The request goes to the endpoint's action with what the
  host vouches for (client address, surface, and `caller`: who the browser is
  signed in as, by the gate's own rules — core/auth.identify); the answer
  comes back through header and type allowlists, and HTML never runs a script
  (forced CSP). Body cap, per-address rate, 16 runs at once on their own
  threads. An endpoint's action answers HTTP only: the action routes refuse it
  and the manifest can't wire it to anything else — its payload is the host's
  word on who is asking.
- `hub.api` (plugins/hubapi.py, plugins/actas.py): the hub's API for the
  plugin's handlers, as the owner or — `X-AIA-As-User`, the `cli` scope — as a
  guest the plugin is granted to. The CLI is its library (AIA_CLI_DIR; the
  names a plugin leans on are pinned by cli/test_library_surface.py).
  `hub/via` stamps meta.via = {kind: "plugin", …}: the "via Claude.ai" pill.
- `notify.ask` and `security.record` (plugins/hubsignals.py): a tappable
  question to the owner and its answer; a `plugin_event` Security log line.

Removed: backend/mcpserver/, schemas/mcp.py, cli/mcp_tools.py + mcp_server.py,
the frontend's business/aiApps (Settings → AI apps, /connect/<id> — both old
addresses redirect), /api/mcp*, /api/me/ai-apps, the `mcp` SSE event, the
mcp.connect / mcp.manage permissions and the per-guest AI apps switch (the
plugin's managed grant). A retired permission still in a record reads without
it and is never refused (authz/catalog.RETIRED).

Carry-over (carryover.hub_mcp, at start and after the plugin's install):
/data/mcp.json → the plugin's store, same shape, so connected apps keep
working — minus the connections bound to a worker, which are dropped with
their tokens rather than left as plain owner connections; every guest who
held mcp.connect gets the grant; whoever was pushed about mcp_connected is
pushed about plugin events.

Workers: the `ai-agent` CLI switch gains Full — the lab's CLI as the owner
(every command but worktrees, any machine, the plugins' commands), what the
EVOX2's unbound MCP connection gave. The worker-side CLI no longer filters
commands: the hub's switch decides. "Acts as" is gone; workers/bound.py stays
as the CLI's narrowing.

Until the plugin is installed after a deploy, /mcp and /oauth/* answer 404.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 13:50:25 +01:00

176 lines
7.1 KiB
Python

"""
The security log and its switches — see docs/security.md.
* ``/data/security-log.jsonl`` — one event per line, append-only: guest
sign-ins and link requests, guest runs, the guard hook's hits, sandbox
denials, anonymous edge requests on the admin host, the owner's lock/stop
actions. Past ``MAX_BYTES`` the older half is dropped.
* ``/data/security.json`` — ``{guestsLocked, lockedAt, pushKinds, devices}``:
the *Lock guests* switch, which kinds push the owner, and the devices
(IP + user agent) each guest has signed in from, so a new one stands out.
"""
from __future__ import annotations
import datetime
import hashlib
import json
import os
import pathlib
import secrets
import threading
from users.store import _JsonFile
MAX_BYTES = int(os.environ.get("SECURITY_LOG_MAX_BYTES", str(8 * 1024 * 1024)))
# What pushes the owner by default (Gabriel's picks, form 2026-11-01): a run
# the guard stopped, an owner run that tripped a rule (allowed, but he hears
# of it), a guest signing in from a new device, a burst of sandbox denials —
# plus the edge tripwire (someone trying what made them the owner until then).
DEFAULT_PUSH_KINDS = ("guard_block", "guard_owner", "new_device", "sandbox_burst",
"edge_anonymous", "cross_site", "owner_login",
"remote_passkey_added", "remote_passkey_invited")
# Defaults that postdate the first security.json: offered once (see __init__).
NEW_DEFAULT_KINDS = ("cross_site", "owner_login", "remote_passkey_added",
"remote_passkey_invited")
DEVICES_PER_USER = 20
def _now_iso() -> str:
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
class SecurityState(_JsonFile):
def __init__(self, path: str):
super().__init__(path, {"guestsLocked": False, "lockedAt": None,
"pushKinds": list(DEFAULT_PUSH_KINDS), "devices": {}})
# A default added after this file was written (``cross_site``,
# 2026-11-15) is switched on once; unticking it afterwards sticks.
with self._lock:
offered = set(self._data.get("offered") or ())
fresh = [k for k in NEW_DEFAULT_KINDS if k not in offered]
if fresh:
kinds = set(self._data.get("pushKinds") or ()) | set(fresh)
self._data["pushKinds"] = sorted(kinds)
self._data["offered"] = sorted(offered | set(NEW_DEFAULT_KINDS))
try:
self._save()
except OSError:
pass
# "An AI app connected" was core's ``mcp_connected`` until the MCP
# server became the hub-mcp plugin (2026-11-28): whoever was pushed
# about it is pushed about plugins' events instead.
kinds = list(self._data.get("pushKinds") or ())
if "mcp_connected" in kinds:
self._data["pushKinds"] = sorted((set(kinds) - {"mcp_connected"})
| {"plugin_event"})
try:
self._save()
except OSError:
pass
def get(self) -> dict:
with self._lock:
return {"guestsLocked": bool(self._data.get("guestsLocked")),
"lockedAt": self._data.get("lockedAt"),
"remoteLocked": bool(self._data.get("remoteLocked")),
"remoteLockedAt": self._data.get("remoteLockedAt"),
"pushKinds": list(self._data.get("pushKinds") or [])}
def guests_locked(self) -> bool:
with self._lock:
return bool(self._data.get("guestsLocked"))
def remote_locked(self) -> bool:
"""*Internet access* switched off: nobody signs in as the owner on the
internet address (``OWNER_HOSTS``) — the admin host is unaffected."""
with self._lock:
return bool(self._data.get("remoteLocked"))
def set_remote_locked(self, locked: bool) -> None:
with self._lock:
self._data["remoteLocked"] = bool(locked)
self._data["remoteLockedAt"] = _now_iso() if locked else None
self._save()
def set_locked(self, locked: bool) -> dict:
with self._lock:
self._data["guestsLocked"] = bool(locked)
self._data["lockedAt"] = _now_iso() if locked else None
self._save()
return self.get()
def set_push_kinds(self, kinds: list[str]) -> dict:
with self._lock:
self._data["pushKinds"] = sorted({str(k) for k in kinds})
self._save()
return self.get()
def see_device(self, uid: str, ip: str, ua: str) -> dict:
"""Record that ``uid`` signed in from ``ip`` with ``ua``; which of the
two is new for them (``{"ip": bool, "ua": bool, "first": bool}``)."""
ua_key = hashlib.sha256((ua or "").encode()).hexdigest()[:16]
with self._lock:
seen = self._data.setdefault("devices", {}).setdefault(uid, [])
first = not seen
new_ip = bool(ip) and all(d.get("ip") != ip for d in seen)
new_ua = all(d.get("ua") != ua_key for d in seen)
seen.append({"ip": ip, "ua": ua_key, "at": _now_iso()})
del seen[:-DEVICES_PER_USER]
self._save()
return {"ip": new_ip, "ua": new_ua, "first": first}
class SecurityLog:
def __init__(self, path: str):
self.path = pathlib.Path(path)
self._lock = threading.Lock()
def append(self, event: dict) -> dict:
ev = {"id": f"sec_{secrets.token_hex(6)}", "at": _now_iso(), **event}
line = json.dumps(ev, separators=(",", ":"), ensure_ascii=False) + "\n"
with self._lock:
self.path.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
with os.fdopen(fd, "a", encoding="utf-8") as f:
f.write(line)
self._rotate()
return ev
def _rotate(self) -> None:
try:
if self.path.stat().st_size <= MAX_BYTES:
return
lines = self.path.read_text(encoding="utf-8").splitlines(keepends=True)
except OSError:
return
tmp = self.path.with_suffix(".tmp")
tmp.write_text("".join(lines[len(lines) // 2:]), encoding="utf-8")
os.chmod(tmp, 0o600)
os.replace(tmp, self.path)
def events(self, *, kinds: set[str] | None = None, who: str | None = None,
since: str | None = None, limit: int = 200) -> list[dict]:
"""Newest first."""
try:
with self._lock:
lines = self.path.read_text(encoding="utf-8").splitlines()
except OSError:
return []
out: list[dict] = []
for line in reversed(lines):
try:
ev = json.loads(line)
except ValueError:
continue
if since and (ev.get("at") or "") < since:
break
if kinds and ev.get("kind") not in kinds:
continue
if who and ev.get("who") != who:
continue
out.append(ev)
if len(out) >= limit:
break
return out