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>
521 lines
23 KiB
Python
521 lines
23 KiB
Python
"""``endpoints[]`` — HTTP a live plugin answers on the hub's own address
|
||
(since 2026-11-28; the ``hub-mcp`` plugin's ``/mcp``, ``/oauth/*`` and consent
|
||
page, which were core's ``mcpserver/``). Docs: docs/plugins.md → "HTTP
|
||
endpoints, the hub's API and asks".
|
||
|
||
```json
|
||
"endpoints": [ { "id": "mcp", "path": "/mcp", "methods": ["POST"], "action": "http_mcp",
|
||
"maxBodyKb": 2048, "surfaces": ["public"], "browser": false } ]
|
||
```
|
||
|
||
A plugin serves under its own prefix ``/x/<pluginId>/…`` or on a *protocol
|
||
path* a standard gives no choice about (``/mcp``, ``/oauth/…``,
|
||
``/.well-known/…``) — nothing else on the host can be claimed. The request is
|
||
handed to the endpoint's action, run **as the owner** (the install's user) on
|
||
this module's own threads; what the handler prints is the response, through a
|
||
short allowlist of headers and types. None of these paths is under ``/api``,
|
||
so the trusted-caller gate never sees them: the handler checks its own
|
||
credential (a bearer token, a one-time code), and what the *host* vouches for
|
||
is in the payload — the client's address, the surface, and who the browser is
|
||
signed in as (``caller``, by the gate's own rules: :func:`core.auth.identify`).
|
||
|
||
HTML a plugin serves here is on the app's origin, so it never runs a script:
|
||
every ``text/html`` answer carries :data:`HTML_CSP`.
|
||
|
||
Owner's installs only, operator approval, the whole declaration in the
|
||
approval fingerprint (only when declared — other plugins' fingerprints don't
|
||
move).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import base64
|
||
import concurrent.futures
|
||
import dataclasses
|
||
import json
|
||
import logging
|
||
import os
|
||
import pathlib
|
||
import re
|
||
import threading
|
||
import time
|
||
from typing import Any
|
||
|
||
from fastapi import APIRouter, Request
|
||
from fastapi.responses import JSONResponse, Response
|
||
|
||
log = logging.getLogger(__name__)
|
||
router = APIRouter(include_in_schema=False)
|
||
|
||
MAX_ENDPOINTS = 16
|
||
METHODS = ("GET", "POST", "PUT", "PATCH", "DELETE")
|
||
SURFACES = ("admin", "public")
|
||
# Paths a standard fixes: an OAuth server's metadata and endpoints, MCP's.
|
||
PROTOCOL_EXACT = ("/mcp",)
|
||
PROTOCOL_PREFIXES = ("/oauth/", "/.well-known/")
|
||
PATH_RE = re.compile(r"^/[A-Za-z0-9._~/-]{1,199}$")
|
||
DEFAULT_BODY_KB, MAX_BODY_KB = 64, 4096
|
||
DEFAULT_PER_IP, MAX_PER_IP = 120, 6000
|
||
MAX_INFLIGHT = 16
|
||
MAX_RESPONSE = 4 * 1024 * 1024
|
||
_KEYS = frozenset({"id", "path", "methods", "action", "maxBodyKb", "perIpPerMin",
|
||
"surfaces", "browser", "description"})
|
||
|
||
# What a handler sees of the request's headers, and may set on the answer.
|
||
REQUEST_HEADERS = ("authorization", "content-type", "accept", "accept-language",
|
||
"user-agent", "origin", "mcp-session-id", "mcp-protocol-version",
|
||
"last-event-id")
|
||
RESPONSE_HEADERS = {h.lower(): h for h in (
|
||
"Content-Type", "Cache-Control", "Pragma", "WWW-Authenticate", "Location", "Allow",
|
||
"Retry-After", "Vary", "Access-Control-Allow-Origin", "Mcp-Session-Id",
|
||
"MCP-Protocol-Version")}
|
||
INLINE_TYPES = ("application/json", "text/plain", "text/html")
|
||
# A plugin's page on the app's own origin: forms, links and a meta refresh.
|
||
HTML_CSP = ("default-src 'none'; style-src 'unsafe-inline'; img-src data:; "
|
||
"form-action 'self'; base-uri 'none'; frame-ancestors 'none'")
|
||
|
||
_pool = concurrent.futures.ThreadPoolExecutor(max_workers=MAX_INFLIGHT,
|
||
thread_name_prefix="plugin-endpoint")
|
||
_inflight = 0
|
||
_hits: dict[tuple[str, str], list[float]] = {} # (endpoint key, address) → times
|
||
_lock = threading.Lock()
|
||
|
||
|
||
# ── manifest ─────────────────────────────────────────────────────────────────
|
||
def allowed_path(pid: str, base: str, prefix: bool = False) -> bool:
|
||
"""May plugin ``pid`` claim ``base`` — exactly, or (``prefix``) everything
|
||
under it?"""
|
||
own = f"/x/{pid}"
|
||
if base == own or base.startswith(own + "/"):
|
||
return True
|
||
if base in PROTOCOL_EXACT and not prefix:
|
||
return True
|
||
for p in PROTOCOL_PREFIXES:
|
||
if base.startswith(p) and len(base) > len(p): # /oauth/token, /oauth/v2/*
|
||
return True
|
||
if prefix and base == p.rstrip("/"): # /oauth/*
|
||
return True
|
||
return False
|
||
|
||
|
||
def parse(raw: Any, pid: str, actions: dict[str, Any], errors: list[str]) -> list[dict[str, Any]]:
|
||
"""Validate ``endpoints[]`` into normalized dicts (errors appended)."""
|
||
from plugins.manifest import _KEY_RE
|
||
if raw is None:
|
||
return []
|
||
if not isinstance(raw, list) or len(raw) > MAX_ENDPOINTS:
|
||
errors.append(f"endpoints must be a list ({MAX_ENDPOINTS} max)")
|
||
return []
|
||
out: list[dict[str, Any]] = []
|
||
seen: set[str] = set()
|
||
paths: set[tuple[str, bool]] = set()
|
||
for i, e in enumerate(raw):
|
||
lb = f"endpoints[{i}]"
|
||
if not isinstance(e, dict):
|
||
errors.append(f"{lb} must be an object")
|
||
continue
|
||
bad = sorted(set(e) - _KEYS)
|
||
if bad:
|
||
errors.append(f"{lb}: unknown keys {', '.join(bad)}")
|
||
eid = str(e.get("id") or "").strip()
|
||
if not _KEY_RE.match(eid) or eid in seen:
|
||
errors.append(f"{lb}.id invalid or duplicate")
|
||
continue
|
||
seen.add(eid)
|
||
lb = f"endpoints.{eid}"
|
||
path = e.get("path")
|
||
if not isinstance(path, str):
|
||
errors.append(f"{lb}.path is required")
|
||
continue
|
||
prefix = path.endswith("/*")
|
||
base = path[:-2] if prefix else path
|
||
if not PATH_RE.match(base) or ".." in base or "//" in base \
|
||
or (base.endswith("/") and not prefix and base != "/"):
|
||
errors.append(f"{lb}.path must be a plain absolute path (a trailing /* for a prefix)")
|
||
continue
|
||
if not allowed_path(pid, base, prefix):
|
||
errors.append(f"{lb}.path must be under /x/{pid}/ or a protocol path "
|
||
f"(/mcp, /oauth/…, /.well-known/…)")
|
||
continue
|
||
if (base, prefix) in paths:
|
||
errors.append(f"{lb}.path {path!r} is declared twice")
|
||
continue
|
||
paths.add((base, prefix))
|
||
methods = e.get("methods") or ["GET"]
|
||
if not isinstance(methods, list) or not methods \
|
||
or any(not isinstance(m, str) or m.upper() not in METHODS for m in methods):
|
||
errors.append(f"{lb}.methods must be a list of {', '.join(METHODS)}")
|
||
continue
|
||
action = e.get("action")
|
||
if not isinstance(action, str) or action not in actions:
|
||
errors.append(f"{lb}.action must name a declared action")
|
||
continue
|
||
surfaces = e.get("surfaces") or list(SURFACES)
|
||
if not isinstance(surfaces, list) or not surfaces \
|
||
or any(s not in SURFACES for s in surfaces):
|
||
errors.append(f"{lb}.surfaces must be a list of {', '.join(SURFACES)}")
|
||
continue
|
||
try:
|
||
body_kb = int(DEFAULT_BODY_KB if e.get("maxBodyKb") is None else e["maxBodyKb"])
|
||
per_ip = int(DEFAULT_PER_IP if e.get("perIpPerMin") is None else e["perIpPerMin"])
|
||
except (TypeError, ValueError):
|
||
errors.append(f"{lb}.maxBodyKb / perIpPerMin must be integers")
|
||
continue
|
||
if not 1 <= body_kb <= MAX_BODY_KB:
|
||
errors.append(f"{lb}.maxBodyKb must be 1–{MAX_BODY_KB}")
|
||
continue
|
||
if not 1 <= per_ip <= MAX_PER_IP:
|
||
errors.append(f"{lb}.perIpPerMin must be 1–{MAX_PER_IP}")
|
||
continue
|
||
item: dict[str, Any] = {
|
||
"id": eid, "path": path, "methods": sorted({m.upper() for m in methods}),
|
||
"action": action, "maxBodyKb": body_kb, "perIpPerMin": per_ip,
|
||
"surfaces": [s for s in SURFACES if s in surfaces],
|
||
"browser": bool(e.get("browser", False)),
|
||
}
|
||
if isinstance(e.get("description"), str) and e["description"].strip():
|
||
item["description"] = e["description"].strip()[:200]
|
||
out.append(item)
|
||
return out
|
||
|
||
|
||
def endpoint_actions(manifest: dict[str, Any]) -> frozenset[str]:
|
||
"""The actions that answer HTTP. **Only the dispatcher below runs them**:
|
||
their payload says who the browser is (``request.caller``), which is the
|
||
host's word — through the action routes it would be the caller's own
|
||
(a guest granted the plugin posting ``{"request": {"caller": {"isOwner":
|
||
true}}}``). The action routes refuse them (plugins/routes.py,
|
||
plugins/proxyroutes.py) and the manifest may not wire them to anything
|
||
else (:func:`cross_check`)."""
|
||
return frozenset(e["action"] for e in (manifest.get("endpoints") or []))
|
||
|
||
|
||
def cross_check(out: dict[str, Any], errors: list[str]) -> None:
|
||
"""An endpoint's action is nothing else: not a command, a webhook's, an
|
||
event's, a provider's, an exported or a settings action."""
|
||
acts = endpoint_actions(out)
|
||
if not acts:
|
||
return
|
||
used: dict[str, str] = {}
|
||
for name, c in (out.get("commands") or {}).items():
|
||
used.setdefault(c.get("action"), f"commands.{name}")
|
||
for wh in out.get("webhooks") or []:
|
||
if wh.get("action"):
|
||
used.setdefault(wh["action"], f"webhooks.{wh['id']}")
|
||
for ev in out.get("events") or []:
|
||
if ev.get("action"):
|
||
used.setdefault(ev["action"], f"events.{ev['id']}")
|
||
for key, act in (out.get("provides") or {}).items():
|
||
used.setdefault(act, f"provides.{key}")
|
||
for act in out.get("exports") or []:
|
||
used.setdefault(act, "exports")
|
||
st = out.get("settings") or {}
|
||
for key in ("testAction", "statusAction"):
|
||
if st.get(key):
|
||
used.setdefault(st[key], f"settings.{key}")
|
||
for act in sorted(acts & set(used)):
|
||
errors.append(f"action '{act}' answers an endpoint: it can't also be {used[act]} "
|
||
"(its payload carries what the host vouches for)")
|
||
|
||
|
||
def signature(manifest: dict[str, Any]) -> list:
|
||
"""What of ``endpoints`` the approval fingerprint covers."""
|
||
return [(e["id"], e["path"], e["methods"], e["action"], e["surfaces"], e["browser"])
|
||
for e in (manifest.get("endpoints") or [])]
|
||
|
||
|
||
def consent_items(manifest: dict[str, Any]) -> list[dict[str, Any]]:
|
||
"""The consent card / info page lines."""
|
||
eps = manifest.get("endpoints") or []
|
||
if not eps:
|
||
return []
|
||
paths = ", ".join(f"{'/'.join(e['methods'])} {e['path']}" for e in eps)
|
||
pub = any("public" in e["surfaces"] for e in eps)
|
||
where = "the hub's own address, the internet-facing one included" if pub \
|
||
else "the hub's admin address"
|
||
return [{"kind": "endpoints", "privileged": True,
|
||
"label": f"Answers HTTP on {where}, as its own code: {paths}"}]
|
||
|
||
|
||
# ── the registry ─────────────────────────────────────────────────────────────
|
||
@dataclasses.dataclass(frozen=True)
|
||
class Route:
|
||
pid: str
|
||
ep: dict
|
||
base: str
|
||
prefix: bool
|
||
rec: dict
|
||
|
||
|
||
_registry: tuple[int, list[Route], list[dict]] | None = None
|
||
|
||
|
||
def _build(deps) -> tuple[list[Route], list[dict]]:
|
||
from plugins.store import OWNER_UID
|
||
routes: list[Route] = []
|
||
shadowed: list[dict] = []
|
||
taken: dict[tuple[str, bool], str] = {}
|
||
for rec in deps.plugin_store.active_declaring(OWNER_UID, "endpoints"): # sorted by id
|
||
mf = rec.get("manifest") or {}
|
||
pid = mf.get("id") or rec.get("id")
|
||
for ep in mf.get("endpoints") or []:
|
||
prefix = ep["path"].endswith("/*")
|
||
base = ep["path"][:-2] if prefix else ep["path"]
|
||
if (base, prefix) in taken:
|
||
shadowed.append({"plugin": pid, "endpoint": ep["id"], "path": ep["path"],
|
||
"by": taken[(base, prefix)]})
|
||
continue
|
||
taken[(base, prefix)] = pid
|
||
routes.append(Route(pid, ep, base, prefix, rec))
|
||
# An exact path before any prefix, then the longest prefix.
|
||
routes.sort(key=lambda r: (r.prefix, -len(r.base), r.pid))
|
||
return routes, shadowed
|
||
|
||
|
||
def registry(deps) -> tuple[list[Route], list[dict]]:
|
||
"""(routes, shadowed claims) of the owner's active plugins — rebuilt when
|
||
the plugin store moves."""
|
||
global _registry
|
||
v = deps.plugin_store.version
|
||
cur = _registry
|
||
if cur is None or cur[0] != v:
|
||
routes, shadowed = _build(deps)
|
||
_registry = cur = (v, routes, shadowed)
|
||
return cur[1], cur[2]
|
||
|
||
|
||
def shadowed_for(deps, pid: str) -> list[dict]:
|
||
"""Claims of ``pid`` another plugin answers (its info page)."""
|
||
return [s for s in registry(deps)[1] if s["plugin"] == pid]
|
||
|
||
|
||
def match(deps, path: str) -> tuple[Route, str] | None:
|
||
"""The route answering ``path`` and what a prefix left over."""
|
||
for r in registry(deps)[0]:
|
||
if not r.prefix:
|
||
if path == r.base:
|
||
return r, ""
|
||
elif path.startswith(r.base + "/"):
|
||
return r, path[len(r.base) + 1:]
|
||
return None
|
||
|
||
|
||
# ── the request ──────────────────────────────────────────────────────────────
|
||
def hub_urls(request: Request | None = None) -> dict[str, str]:
|
||
"""The hub's configured addresses: ``admin`` (``AI_AGENT_VIEW_URL``) and
|
||
``public`` (``GUEST_PUBLIC_URL``) — ``""`` for one that isn't configured."""
|
||
from users.deliver import GUEST_PUBLIC_URL
|
||
return {"admin": (os.environ.get("AI_AGENT_VIEW_URL") or "").rstrip("/"),
|
||
"public": (GUEST_PUBLIC_URL or "").rstrip("/")}
|
||
|
||
|
||
def _origin(request: Request, surface: str) -> str:
|
||
"""This surface's configured address; the request's own scheme and host
|
||
only when none is (a standalone hub: nothing in front rewrites it)."""
|
||
url = hub_urls()[surface]
|
||
if url:
|
||
return url
|
||
from users.caller import request_host
|
||
host = (request.headers.get("host") or "").strip() or request_host(request)
|
||
scheme = (request.headers.get("x-forwarded-proto") or request.url.scheme or "http")
|
||
scheme = "https" if scheme.split(",")[0].strip().lower() == "https" else "http"
|
||
return f"{scheme}://{host}" if re.fullmatch(r"[A-Za-z0-9.\-\[\]:]{1,255}", host) else ""
|
||
|
||
|
||
def _error(status: int, message: str, kind: str, headers: dict | None = None) -> JSONResponse:
|
||
return JSONResponse({"error": {"message": message, "kind": kind}}, status_code=status,
|
||
headers={"Cache-Control": "no-store", **(headers or {})})
|
||
|
||
|
||
def _rate_ok(key: str, ip: str, per_min: int) -> bool:
|
||
now = time.time()
|
||
with _lock:
|
||
if len(_hits) > 4096: # addresses gone quiet
|
||
for k in [k for k, ts in _hits.items() if not ts or now - ts[-1] > 60]:
|
||
del _hits[k]
|
||
ts = [t for t in _hits.get((key, ip), ()) if now - t < 60]
|
||
if len(ts) >= per_min:
|
||
_hits[(key, ip)] = ts
|
||
return False
|
||
ts.append(now)
|
||
_hits[(key, ip)] = ts
|
||
return True
|
||
|
||
|
||
class _TooLarge(Exception):
|
||
pass
|
||
|
||
|
||
async def _read_body(request: Request, cap: int) -> bytes:
|
||
try:
|
||
if int(request.headers.get("content-length") or 0) > cap:
|
||
raise _TooLarge
|
||
except ValueError:
|
||
raise _TooLarge from None
|
||
out = bytearray()
|
||
async for chunk in request.stream():
|
||
out += chunk
|
||
if len(out) > cap:
|
||
raise _TooLarge
|
||
return bytes(out)
|
||
|
||
|
||
def _caller_view(deps, request: Request, pid: str) -> dict | None:
|
||
from core.auth import identify
|
||
c = identify(request)
|
||
if c is None:
|
||
return None
|
||
if c.is_owner:
|
||
active = True
|
||
else:
|
||
rec, _grant, _managed = deps.plugin_store.resolve_active_for_caller(c.id, pid)
|
||
active = bool(rec)
|
||
out = {"uid": c.id, "isOwner": bool(c.is_owner), "name": getattr(c, "name", "") or "",
|
||
"lang": getattr(c, "lang", "") or "en", "active": active}
|
||
if getattr(c, "impersonator", None):
|
||
# the owner looking through this guest's eyes: not the guest's own act
|
||
out["impersonatedBy"] = c.impersonator
|
||
return out
|
||
|
||
|
||
def _payload(deps, request: Request, route: Route, rest: str, surface: str,
|
||
body: bytes) -> dict:
|
||
from core.auth import cross_site
|
||
from security.service import client_ip
|
||
req: dict[str, Any] = {
|
||
"method": "GET" if request.method == "HEAD" else request.method,
|
||
"path": request.scope.get("path") or "",
|
||
"rest": rest,
|
||
"query": (request.scope.get("query_string") or b"").decode("latin-1"),
|
||
"headers": {h: request.headers[h] for h in REQUEST_HEADERS if h in request.headers},
|
||
"ip": client_ip(request) or "",
|
||
"host": (request.headers.get("host") or "").split(":")[0].strip().rstrip(".").lower(),
|
||
"origin": _origin(request, surface),
|
||
"surface": surface,
|
||
"sameOrigin": not cross_site(request),
|
||
"caller": _caller_view(deps, request, route.pid),
|
||
}
|
||
try:
|
||
req["body"] = body.decode("utf-8")
|
||
except UnicodeDecodeError:
|
||
req["bodyBase64"] = base64.b64encode(body).decode()
|
||
return {"trigger": "endpoint", "endpoint": route.ep["id"], "request": req}
|
||
|
||
|
||
# ── the answer ───────────────────────────────────────────────────────────────
|
||
def build_response(out: Any, *, head: bool = False) -> Response:
|
||
"""A handler's answer → the HTTP response, through the header and type
|
||
allowlists."""
|
||
if not isinstance(out, dict) or not ({"status", "json", "body", "bodyBase64", "headers"}
|
||
& set(out)):
|
||
return _error(502, "the plugin answered no response", "bad_response")
|
||
try:
|
||
status = int(out.get("status") or 200)
|
||
except (TypeError, ValueError):
|
||
status = 0
|
||
if not 200 <= status <= 599:
|
||
return _error(502, "the plugin answered an invalid status", "bad_response")
|
||
headers: dict[str, str] = {}
|
||
for k, v in (out.get("headers") or {}).items() if isinstance(out.get("headers"), dict) else ():
|
||
name = RESPONSE_HEADERS.get(str(k).lower())
|
||
if name and isinstance(v, (str, int)) and "\n" not in str(v) and "\r" not in str(v):
|
||
headers[name] = str(v)[:4096]
|
||
ctype = headers.pop("Content-Type", "")
|
||
if "json" in out:
|
||
content = json.dumps(out["json"]).encode()
|
||
ctype = ctype if ctype.split(";")[0].strip().lower().endswith("json") else "application/json"
|
||
elif isinstance(out.get("bodyBase64"), str):
|
||
try:
|
||
content = base64.b64decode(out["bodyBase64"], validate=True)
|
||
except ValueError:
|
||
return _error(502, "the plugin answered an invalid body", "bad_response")
|
||
else:
|
||
content = str(out.get("body") or "").encode()
|
||
ctype = ctype or "text/plain; charset=utf-8"
|
||
if len(content) > MAX_RESPONSE:
|
||
return _error(502, "the plugin's answer is too large", "bad_response")
|
||
if 300 <= status < 400 and status != 304 and not headers.get("Location"):
|
||
return _error(502, "the plugin answered a redirect to nowhere", "bad_response")
|
||
base_type = ctype.split(";")[0].strip().lower()
|
||
headers["X-Content-Type-Options"] = "nosniff"
|
||
headers["Referrer-Policy"] = "no-referrer"
|
||
if content:
|
||
if base_type == "text/html":
|
||
headers["Content-Security-Policy"] = HTML_CSP
|
||
headers.setdefault("Cache-Control", "no-store")
|
||
if "charset" not in ctype.lower():
|
||
ctype = "text/html; charset=utf-8"
|
||
elif base_type not in INLINE_TYPES and not base_type.endswith("+json"):
|
||
ctype = "application/octet-stream"
|
||
headers["Content-Disposition"] = "attachment"
|
||
headers["Content-Type"] = ctype
|
||
return Response(b"" if head else content, status_code=status, headers=headers)
|
||
|
||
|
||
def _run(deps, route: Route, payload: dict) -> Any:
|
||
from plugins.runner import run_script
|
||
from plugins.store import OWNER_UID
|
||
act = (route.rec["manifest"].get("actions") or {})[route.ep["action"]]
|
||
return run_script(deps, deps.plugin_store, OWNER_UID, route.rec, act["script"],
|
||
payload=payload, timeout_sec=int(act.get("timeoutSec") or 30))
|
||
|
||
|
||
@router.api_route("/mcp", methods=[*METHODS, "HEAD"])
|
||
@router.api_route("/oauth/{rest:path}", methods=[*METHODS, "HEAD"])
|
||
@router.api_route("/.well-known/{rest:path}", methods=[*METHODS, "HEAD"])
|
||
@router.api_route("/x/{rest:path}", methods=[*METHODS, "HEAD"])
|
||
async def plugin_endpoint(request: Request, rest: str = ""):
|
||
"""A path a plugin may claim: its handler's answer, or 404."""
|
||
global _inflight
|
||
from core.auth import _refuse_cross_site, cross_site
|
||
from plugins.runner import ActionError
|
||
from security.service import client_ip
|
||
from users.caller import on_owner_surface, on_public_surface
|
||
deps = request.app.state.ai
|
||
not_found = _error(404, "not found", "not_found")
|
||
if on_owner_surface(request):
|
||
return not_found
|
||
hit = match(deps, request.scope.get("path") or "")
|
||
if hit is None:
|
||
return not_found
|
||
route, left = hit
|
||
ep = route.ep
|
||
surface = "public" if on_public_surface(request) else "admin"
|
||
if surface not in ep["surfaces"]:
|
||
return not_found
|
||
method = "GET" if request.method == "HEAD" else request.method
|
||
if method not in ep["methods"]:
|
||
return _error(405, "method not allowed", "method", {"Allow": ", ".join(ep["methods"])})
|
||
if ep["browser"] and method not in ("GET",) and cross_site(request):
|
||
return _refuse_cross_site(request)
|
||
key = f"{route.pid}/{ep['id']}"
|
||
if not _rate_ok(key, client_ip(request) or "?", ep["perIpPerMin"]):
|
||
return _error(429, "too many requests from this address", "rate", {"Retry-After": "30"})
|
||
try:
|
||
body = await _read_body(request, ep["maxBodyKb"] * 1024)
|
||
except _TooLarge:
|
||
return _error(413, "request too large", "too_large")
|
||
with _lock:
|
||
if _inflight >= MAX_INFLIGHT:
|
||
return _error(503, "busy — try again", "busy", {"Retry-After": "2"})
|
||
_inflight += 1
|
||
try:
|
||
payload = _payload(deps, request, route, left, surface, body)
|
||
loop = asyncio.get_running_loop()
|
||
try:
|
||
out = await loop.run_in_executor(_pool, _run, deps, route, payload)
|
||
except ActionError as e:
|
||
# A handler's own `_error` (it names a kind) keeps its words; a
|
||
# crash or a timeout is the host's — the script's stderr never
|
||
# reaches the internet.
|
||
if e.kind != "action_failed":
|
||
return _error(e.status, e.message, e.kind)
|
||
log.warning("endpoint %s failed: %s", key, e.message)
|
||
return _error(504 if e.status == 504 else 502, "the plugin's endpoint failed",
|
||
"endpoint_failed")
|
||
return build_response(out, head=request.method == "HEAD")
|
||
finally:
|
||
with _lock:
|
||
_inflight -= 1
|