Files
gabrielvidalandClaude Opus 5.5 118b6db0df feat(plugins): the lab Chrome leaves the core for the lab-chrome plugin
Settings → Browser, the conversation's Browser dock (noVNC live view and
take-over) and the container's on-demand life move into the lab-chrome
live plugin (ai-agent-plugins). The core keeps the Chrome chip (the
harness capability chrome) and gains three generic hooks:

- sockets[] + aiAgentPlugin.openSocket(id): a frame's websocket, opened by
  the host with the reader's cookies and relayed over postMessage to
  WS /api/plugins/{pid}/sockets/{sid}, which bridges only to the declared
  upstream (owner only, the gate's handshake rules, never the guest host;
  operator approval). GET …/sockets/{sid}/probe → {up, open, lastActiveAt}
  for the plugin's handlers.
- provides chrome.lab (plugins/chrome_bridge.py): {op: status} → the chip
  default and whether guests' runs keep --chrome; {op: ensure} before a
  lab --chrome run launches (spawn and resume).
- ui.slots[].size on app.modal (full = near full screen, frame filling it);
  conversation.gizmos' update and hub/conversations rows carry chrome.

Gone: backend/chrome/, /api/chrome*, schemas/chrome.py, the SSE chrome
event, the lab.integrations permission, BrowserDock/BrowserSettings/store,
the Browser header button and eye switch, @novnc/novnc. /settings/browser
redirects to /settings/plugin/lab-chrome; carryover.chrome moves
/data/chrome.json into the plugin's config.

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

320 lines
13 KiB
Python

"""``sockets[]`` — websockets a plugin's frames open through the host.
A sandboxed frame has no network (an opaque ``"null"`` origin, no cookies),
so a plugin that needs a live stream into the host's network (the
``lab-chrome`` plugin's noVNC view of the lab Chrome, since 2026-11-26 — it
replaced the core's ``/api/chrome/ws``) declares the target and the host
relays it:
"sockets": [{"id": "vnc", "url": "ws://chrome:6080/websockify",
"subprotocols": ["binary"], "label": "Lab Chrome screen"}]
* **The frame** calls ``aiAgentPlugin.openSocket("vnc", {protocols})`` — a
WebSocket-like channel (``send`` / ``close`` / ``onopen`` / ``onmessage`` /
``onclose`` / ``onerror`` / ``readyState`` / ``protocol`` /
``binaryType``; noVNC's RFB takes it as its channel). The host
(``PluginSandboxFrame``) opens the real websocket below, with the reader's
cookies, and relays frames both ways over postMessage.
* **The route** ``WS /api/plugins/{pid}/sockets/{sid}`` bridges it to the
declared ``url`` — and only that one: no path, query or host of the
caller's ever reaches the upstream. **Owner only** (the same handshake
rules as the app's gate — :func:`ws_caller`), never on the guest host, the
owner's enabled and approved install only; on the owner's internet address
the session is re-checked every :data:`REMOTE_RECHECK_S` while the socket is
open. A declared socket needs operator approval (it reaches the host's
network) and is in the approval fingerprint.
* **Its life**: ``GET /proxy/tools/plugins/{pid}/sockets/{sid}/probe`` (the
plugin's own handlers, the owner's) → ``{up, open, lastActiveAt}`` — whether
the upstream answers a TCP connect now, how many relays are open, and when
one last carried a frame (epoch seconds, 0 = never since the hub started):
what a plugin's idle job needs to know that someone is watching.
"""
from __future__ import annotations
import asyncio
import logging
import re
import socket
import threading
import time
import urllib.parse
from typing import Any
from fastapi import APIRouter, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import JSONResponse
from starlette.concurrency import run_in_threadpool
# (plugins.store / users.caller are imported where used: the manifest
# validator imports this module for ``parse``, and they import it.)
log = logging.getLogger(__name__)
router = APIRouter(include_in_schema=False)
MAX_SOCKETS = 4
_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_-]{0,47}$")
_URL_RE = re.compile(r"^wss?://[A-Za-z0-9][A-Za-z0-9.-]{0,252}(:\d{1,5})?(/[A-Za-z0-9._~/-]{0,200})?$")
_PROTO_RE = re.compile(r"^[A-Za-z0-9._-]{1,32}$")
# How often an open relay on the owner's internet address re-checks its session.
REMOTE_RECHECK_S = 5.0
PROBE_TIMEOUT_S = 1.5
# (pid, sid) → {"open": int, "at": float} — the relays open now and when one
# last carried a frame (in memory: a restart forgets, which reads as idle).
_activity: dict[tuple[str, str], dict[str, float]] = {}
_activity_lock = threading.Lock()
# ── the manifest's ``sockets[]`` ─────────────────────────────────────────────
def parse(raw: Any, errors: list[str]) -> list[dict[str, Any]]:
"""The normalized ``sockets[]`` (``[]`` when absent), errors appended."""
if raw is None:
return []
if not isinstance(raw, list):
errors.append("sockets must be a list")
return []
if len(raw) > MAX_SOCKETS:
errors.append(f"sockets: at most {MAX_SOCKETS}")
return []
out: list[dict[str, Any]] = []
seen: set[str] = set()
for i, so in enumerate(raw):
if not isinstance(so, dict):
errors.append(f"sockets[{i}] must be an object")
continue
sid = str(so.get("id") or "").strip()
url = str(so.get("url") or "").strip()
if not _KEY_RE.match(sid) or sid in seen:
errors.append(f"sockets[{i}].id invalid or duplicate")
continue
parts = urllib.parse.urlsplit(url) if _URL_RE.match(url) else None
if parts is None or not parts.hostname or (parts.port is not None and not 0 < parts.port < 65536):
errors.append(f"sockets[{i}].url must be ws://host[:port][/path] or wss://… (no query, no credentials)")
continue
item: dict[str, Any] = {"id": sid, "url": url}
protos = so.get("subprotocols")
if protos is not None:
if (not isinstance(protos, list) or len(protos) > 4
or not all(isinstance(p, str) and _PROTO_RE.match(p) for p in protos)):
errors.append(f"sockets[{i}].subprotocols: up to 4 tokens")
continue
if protos:
item["subprotocols"] = list(protos)
if so.get("label") is not None:
lab = str(so.get("label") or "").strip()
if not lab or len(lab) > 60:
errors.append(f"sockets[{i}].label must be 1..60 characters")
continue
item["label"] = lab
seen.add(sid)
out.append(item)
return out
def declared(rec: dict[str, Any] | None, sid: str) -> dict[str, Any] | None:
for so in ((rec or {}).get("manifest") or {}).get("sockets") or []:
if so.get("id") == sid:
return so
return None
def _owner_rec(deps, pid: str) -> dict[str, Any] | None:
"""The owner's enabled, approved install of ``pid``."""
from plugins.store import OWNER_UID
try:
rec = deps.plugin_store.get_raw(OWNER_UID, pid)
except Exception: # noqa: BLE001 — no plugin store (tests)
return None
if not rec or not rec.get("enabled") or rec.get("needsApproval"):
return None
return rec
def activity(pid: str, sid: str) -> dict[str, float]:
with _activity_lock:
a = _activity.get((pid, sid)) or {}
return {"open": int(a.get("open", 0)), "at": float(a.get("at", 0.0))}
def _stamp(pid: str, sid: str, delta: int = 0) -> None:
with _activity_lock:
a = _activity.setdefault((pid, sid), {"open": 0, "at": 0.0})
a["open"] = max(0, int(a["open"]) + delta)
a["at"] = time.time()
# ── who opens it: the app gate's rules, on the handshake ─────────────────────
# The HTTP middleware (core/auth.py) never sees a websocket, so the caller is
# decided here: the same trusted-caller rules, on the handshake request.
async def ws_caller(ws: WebSocket):
"""The caller of a websocket handshake (the owner, a guest), or None."""
from core import auth as auth_mod
from users.caller import OWNER
# The owner's internet address: the owner's own session, nothing else
# (and not from a page elsewhere) — like the gate.
if auth_mod.on_owner_surface(ws): # type: ignore[arg-type]
if auth_mod.cross_site(ws) or auth_mod.remote_session(ws) is None: # type: ignore[arg-type]
return None
return auth_mod._guest_session(ws) or OWNER # type: ignore[arg-type]
# A guest session cookie decides first, exactly like the gate.
guest = auth_mod._guest_session(ws) # type: ignore[arg-type]
if guest is not None:
return guest
if auth_mod.on_guest_surface(ws): # type: ignore[arg-type]
return None
# A websocket handshake is a GET that carries the Authelia cookie from any
# same-site page (a guest's site on *.gabvdl.xyz) and no preflight: it
# must come from this very origin, or a page elsewhere drives the browser.
if auth_mod.cross_site(ws): # type: ignore[arg-type]
return None
client = ws.client.host if ws.client else ""
if client not in auth_mod._trusted_ips():
if not auth_mod._token_ok(ws.headers.get("x-internal-auth", "")):
return None
# Through Traefik, only the Authelia user who is the owner — not "came
# from Traefik", and not a read-only account.
if auth_mod.via_edge(ws) and auth_mod.edge_role(ws) != "owner": # type: ignore[arg-type]
return None
return OWNER
def _pick_protocol(offered: str, allowed: list[str]) -> str | None:
"""The first subprotocol the client offered that the socket declares."""
want = [p.strip() for p in (offered or "").split(",") if p.strip()]
for p in want:
if p in allowed:
return p
return None
@router.websocket("/api/plugins/{pid}/sockets/{sid}")
async def plugin_socket(ws: WebSocket, pid: str, sid: str):
"""Bridge a frame's channel (relayed by the app) to the plugin's declared
upstream. Binary and text frames both ways; either side closing closes the
other."""
caller = await ws_caller(ws)
if caller is None or not caller.is_owner:
await ws.close(code=4403)
return
deps = ws.app.state.ai
rec = _owner_rec(deps, pid)
so = declared(rec, sid)
if so is None:
await ws.close(code=4404)
return
try:
import websockets
except ImportError: # pragma: no cover
await ws.close(code=1011)
return
protos = list(so.get("subprotocols") or [])
chosen = _pick_protocol(ws.headers.get("sec-websocket-protocol", ""), protos)
try:
upstream = await websockets.connect(
so["url"], subprotocols=protos or None, max_size=None,
open_timeout=5, ping_interval=20, ping_timeout=20)
except Exception as e: # the upstream is down
log.info("plugin socket %s/%s: upstream unreachable: %s", pid, sid, e)
await ws.close(code=4502)
return
await ws.accept(subprotocol=chosen)
_stamp(pid, sid, +1)
async def client_to_upstream():
try:
while True:
msg = await ws.receive()
if msg.get("type") == "websocket.disconnect":
break
data = msg.get("bytes")
if data is None and msg.get("text") is not None:
data = msg["text"]
if data:
_stamp(pid, sid)
await upstream.send(data)
except (WebSocketDisconnect, RuntimeError):
pass
except Exception as e: # noqa: BLE001 — the upstream went
log.info("plugin socket %s/%s: send failed: %s", pid, sid, e)
finally:
await upstream.close()
async def upstream_to_client():
try:
async for data in upstream:
_stamp(pid, sid)
if isinstance(data, str):
await ws.send_text(data)
else:
await ws.send_bytes(data)
except Exception: # noqa: BLE001
pass
finally:
try:
await ws.close()
except Exception: # noqa: BLE001
pass
from core import auth as auth_mod
remote = auth_mod.on_owner_surface(ws) # type: ignore[arg-type]
async def remote_watch():
# The owner's internet address: the session behind this relay can end
# while it is open (signed out, its passkey removed, internet access
# switched off) — the handshake was checked once, so look again.
while True:
await asyncio.sleep(REMOTE_RECHECK_S)
if auth_mod.remote_session(ws) is None: # type: ignore[arg-type]
log.info("plugin socket %s/%s: the internet session ended — closing", pid, sid)
try:
await upstream.close()
finally:
try:
await ws.close(code=4403)
except Exception: # noqa: BLE001
pass
return
watcher = asyncio.create_task(remote_watch()) if remote else None
try:
await asyncio.gather(client_to_upstream(), upstream_to_client(), return_exceptions=True)
finally:
if watcher:
watcher.cancel()
_stamp(pid, sid, -1)
# ── the plugin's handlers: is the upstream up, is anyone watching ────────────
def _reachable(url: str) -> bool:
u = urllib.parse.urlsplit(url)
port = u.port or (443 if u.scheme == "wss" else 80)
try:
with socket.create_connection((u.hostname or "", port), timeout=PROBE_TIMEOUT_S):
return True
except OSError:
return False
@router.get("/proxy/tools/plugins/{pid}/sockets/{sid}/probe")
async def plugin_socket_probe(pid: str, sid: str, request: Request):
"""``{up, open, lastActiveAt}`` for the plugin's own handlers (the
owner's): a TCP connect to the declared upstream now, the relays open,
when one last carried a frame."""
from plugins.proxyroutes import _active_plugin, _error, _who
who, err = _who(request, pid)
if err:
return err
if who.handler != pid:
return _error(403, "a socket probe is for the plugin's own handlers", "handler_only")
if not who.is_owner:
return _error(403, "plugin sockets are owner-only", "capability")
_, rec, _, _, err = _active_plugin(request.app.state.ai, who, pid)
if err:
return err
so = declared(rec, sid)
if so is None:
return _error(404, f"socket '{sid}' not declared", "not_found")
up = await run_in_threadpool(_reachable, so["url"])
a = activity(pid, sid)
return JSONResponse({"up": up, "open": a["open"], "lastActiveAt": a["at"]})