Removes backend/templates/ (catalog, routes, router mount), the Template* schemas, the three /api/template* routes from authz and its golden matrix, the frontend Templates page, its api.ts fetchers and mocks, and the Projects panel's third tab (Projects | Services now). /templates and /templates?t=<name> redirect to /plugins/templates/templates[/<name>]; the page.templates telemetry feature follows the plugin's paths. openapi.json is left for the Batch 1 re-dump. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
689 lines
28 KiB
Python
689 lines
28 KiB
Python
"""Hub capability bridges for live plugins (mounted under ``/proxy/tools/plugins/{pid}/hub/*``):
|
|
|
|
* ``askform.bridge`` — create, list, inspect, revoke, close, recheck and check
|
|
health of forms via the hub's ask-form mirror (``backend/askform/``).
|
|
* ``conversations.reply`` — post an app-tagged turn into a conversation via
|
|
``runs/reply.py`` (always preserving guest scope and active-user checks).
|
|
* ``notify.send`` clear — ``POST …/hub/notify/clear`` dismisses a push tag on
|
|
devices (``users/deliver.py``).
|
|
* ``users.read`` — safe user metadata (name, email, lang, web address, projects).
|
|
* ``scaffold.run`` — host sidecar ``/scaffold/check``, ``/scaffold``,
|
|
``/relocate``, template catalog and project grant (owner/managed handler only).
|
|
* ``ship.run`` — the zipgo deploy broker: host sidecar ``/ship/deploy``, a
|
|
project's deploy-config scan and the security log (owner handler only; a
|
|
guest's run reaches it through a ``runAs: "owner"`` action, its requester in
|
|
``AIA_USER_CONTEXT.requester``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import os
|
|
import pathlib
|
|
import re
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from plugins.proxyroutes import _active_plugin, _error, _who
|
|
from plugins.store import OWNER_UID
|
|
|
|
log = logging.getLogger("plugins.hubbridge")
|
|
router = APIRouter(include_in_schema=False)
|
|
|
|
_SID_RE = re.compile(r"^[A-Za-z0-9-]{4,64}$")
|
|
_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
|
|
_NOT_APPS = ("homelab-service", "skill-cli")
|
|
SCAFFOLD_TIMEOUT_S = float(os.environ.get("NEW_PROJECT_SCAFFOLD_TIMEOUT_S", "960"))
|
|
|
|
|
|
async def _json_body(request: Request) -> dict[str, Any]:
|
|
try:
|
|
b = await request.json()
|
|
except Exception:
|
|
return {}
|
|
return b if isinstance(b, dict) else {}
|
|
|
|
|
|
def _detail(e: HTTPException) -> tuple[str, str]:
|
|
d = e.detail
|
|
if isinstance(d, dict):
|
|
return str(d.get("message") or d), str(d.get("kind") or "error")
|
|
return str(d), "error"
|
|
|
|
|
|
def _check_cap(request: Request, pid: str, cap: str, *, owner_only: bool = False,
|
|
handler_only: bool = False):
|
|
who, err = _who(request, pid)
|
|
if err:
|
|
return None, None, None, err
|
|
if handler_only and who.handler != pid:
|
|
return None, None, None, _error(403, f"{cap} is only available to the plugin's own handlers", "handler_only")
|
|
if owner_only and not who.is_owner:
|
|
return None, None, None, _error(403, f"{cap} is owner-only", "capability")
|
|
deps = request.app.state.ai
|
|
uid, rec, _g, _m, err = _active_plugin(deps, who, pid)
|
|
if err:
|
|
return None, None, None, err
|
|
if cap not in (rec["manifest"].get("capabilities") or []):
|
|
return None, None, None, _error(403, f"plugin lacks {cap} capability", "capability")
|
|
return deps, who, rec, None
|
|
|
|
|
|
def _caller_for_who(deps, who):
|
|
from users.caller import OWNER, guest_from_record
|
|
if who.is_owner:
|
|
return OWNER
|
|
u = deps.users.active(who.uid)
|
|
return guest_from_record(u) if u else None
|
|
|
|
|
|
# ── askform.bridge ───────────────────────────────────────────────────────────
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/askform/create")
|
|
async def hub_askform_create(pid: str, request: Request):
|
|
deps, who, _rec, err = _check_cap(request, pid, "askform.bridge", handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
if not body.get("title"):
|
|
return _error(400, "title is required")
|
|
fields = body.get("fields")
|
|
if not isinstance(fields, list) or not fields:
|
|
return _error(400, "fields must be a non-empty list")
|
|
meta = dict(body.get("meta") or {}) if isinstance(body.get("meta"), dict) else {}
|
|
if body.get("sessionId") and not meta.get("session"):
|
|
meta["session"] = str(body["sessionId"]).strip()
|
|
if body.get("ownerOnly"):
|
|
if not who.is_owner:
|
|
return _error(403, "ownerOnly forms require owner context", "capability")
|
|
meta["ownerOnly"] = True
|
|
if body.get("noPush"):
|
|
meta["noPush"] = True
|
|
# Non-owners may only stamp their own sessions
|
|
if not who.is_owner and meta.get("session"):
|
|
from toolproxy import access as tp_access
|
|
if not tp_access.session_of(deps, who, str(meta["session"])):
|
|
return _error(403, "that conversation isn't yours", "session")
|
|
payload: dict[str, Any] = {
|
|
"title": str(body["title"])[:200],
|
|
"fields": fields,
|
|
"meta": meta,
|
|
}
|
|
for k in ("name", "description", "ttl", "lang", "multi", "maxAnswers",
|
|
"hideCount", "public", "noSnapshot", "assets"):
|
|
if k in body and body[k] is not None:
|
|
payload[k] = body[k]
|
|
machine = str(body.get("machine") or "lab").strip() or "lab"
|
|
|
|
def _go():
|
|
from askform import service as af
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
raise HTTPException(403, "user is not active")
|
|
rec = af.create_form(deps, payload, machine=machine)
|
|
return af.public(deps, caller, [rec], lite=False)[0]
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/askform/forms")
|
|
async def hub_askform_list(pid: str, request: Request, session: str = "",
|
|
status: str = "", limit: int = 100):
|
|
deps, who, _rec, err = _check_cap(request, pid, "askform.bridge", handler_only=True)
|
|
if err:
|
|
return err
|
|
|
|
def _go():
|
|
from askform import service as af
|
|
from users import access
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
raise HTTPException(403, "user is not active")
|
|
items = deps.askform_store.list(status=status or None, session=session or None,
|
|
limit=max(1, min(500, int(limit))))
|
|
if not caller.is_owner:
|
|
items = [r for r in items if not af.is_owner_only(r)
|
|
and r.get("sessionId") and access.visible(deps, caller, r["sessionId"])]
|
|
pub = af.public(deps, caller, items, lite=True)
|
|
return {"forms": pub, "count": len(pub)}
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/askform/forms/{fid}")
|
|
async def hub_askform_get(pid: str, fid: str, request: Request, fields: int = 1, refresh: int = 0):
|
|
deps, who, _rec, err = _check_cap(request, pid, "askform.bridge", handler_only=True)
|
|
if err:
|
|
return err
|
|
|
|
def _go():
|
|
from askform import service as af
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
raise HTTPException(403, "user is not active")
|
|
af.visible(deps, caller, deps.askform_store.get(fid))
|
|
if refresh:
|
|
rec = af.recheck(deps, fid)
|
|
elif fields:
|
|
rec = af.with_fields(deps, fid)
|
|
else:
|
|
rec = deps.askform_store.get(fid)
|
|
return af.public(deps, caller, [rec], lite=not bool(fields))[0]
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/askform/forms/{fid}/{verb}")
|
|
async def hub_askform_verb(pid: str, fid: str, verb: str, request: Request):
|
|
deps, who, _rec, err = _check_cap(request, pid, "askform.bridge", handler_only=True)
|
|
if err:
|
|
return err
|
|
if verb not in ("revoke", "close", "recheck"):
|
|
return _error(400, f"unknown verb {verb!r}")
|
|
|
|
def _go():
|
|
from askform import service as af
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
raise HTTPException(403, "user is not active")
|
|
af.visible(deps, caller, deps.askform_store.get(fid))
|
|
if verb == "recheck":
|
|
rec = af.recheck(deps, fid)
|
|
else:
|
|
rec = af.end(deps, fid, close=(verb == "close"))
|
|
return af.public(deps, caller, [rec], lite=(verb != "recheck"))[0]
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/askform/health")
|
|
async def hub_askform_health(pid: str, request: Request):
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "askform.bridge",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
|
|
def _go():
|
|
from askform import service as af
|
|
from workers.store import sidecar_request
|
|
out = []
|
|
for m in af.machines(deps):
|
|
try:
|
|
h = sidecar_request(m["url"], m["token"], "/ask-form/health", None,
|
|
method="GET", timeout=6, label=m["label"])
|
|
except HTTPException as e:
|
|
d = e.detail if isinstance(e.detail, dict) else {"message": str(e.detail)}
|
|
h = {"installed": None, "ok": False, "error": d.get("message")}
|
|
out.append({"machine": m["id"], "label": m["label"], **h})
|
|
return {"machines": out}
|
|
|
|
return await run_in_threadpool(_go)
|
|
|
|
|
|
# ── notify.send clear ────────────────────────────────────────────────────────
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/notify/clear")
|
|
async def hub_notify_clear(pid: str, request: Request):
|
|
deps, who, _rec, err = _check_cap(request, pid, "notify.send")
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
tag = str(body.get("tag") or "").strip()[:120]
|
|
if not tag:
|
|
return _error(400, "tag is required")
|
|
kind = str(body.get("kind") or "notify")[:24]
|
|
sid = str(body.get("session") or body.get("sessionId") or "").strip()
|
|
if not who.is_owner and sid:
|
|
from toolproxy import access as tp_access
|
|
if not tp_access.session_of(deps, who, sid):
|
|
return _error(403, "that conversation isn't yours", "session")
|
|
if body.get("ownerOnly"):
|
|
sid = ""
|
|
|
|
def _go():
|
|
from users import deliver
|
|
deliver.clear(deps, sid, tag, kind)
|
|
|
|
await run_in_threadpool(_go)
|
|
return {"ok": True}
|
|
|
|
|
|
# ── conversations.reply ──────────────────────────────────────────────────────
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/conversations/{sid}/reply")
|
|
async def hub_conversation_reply(pid: str, sid: str, request: Request):
|
|
"""Post an app-tagged turn into ``sid`` via ``runs/reply.py.say`` (preserves
|
|
guest scope and active-user check)."""
|
|
deps, who, _rec, err = _check_cap(request, pid, "conversations.reply", handler_only=True)
|
|
if err:
|
|
return err
|
|
if not _SID_RE.match(sid):
|
|
return _error(400, "bad session id")
|
|
body = await _json_body(request)
|
|
text = str(body.get("text") or body.get("prompt") or "").strip()
|
|
if not text or len(text) > 100_000:
|
|
return _error(400, "text is required (<= 100 000 chars)")
|
|
if not who.is_owner:
|
|
meta = deps.meta_store.peek(sid) or {}
|
|
if meta.get("owner") != who.uid:
|
|
return _error(403, "that conversation isn't yours", "session")
|
|
tag_name = str(body.get("tagName") or pid)[:40]
|
|
tag_user = re.sub(r"[^a-z0-9_-]", "", str(body.get("tagUser") or pid).lower()) or pid
|
|
tag = f'<ai-agent-from user="{tag_user}" name="{tag_name}" role="app"/>'
|
|
harness = body.get("harness") if "harness" in body else "claude"
|
|
if harness is not None and harness not in ("claude", "pi", "opencode", "agy"):
|
|
return _error(400, "bad harness")
|
|
inbox_only = bool(body.get("inboxOnly", False))
|
|
|
|
def _go():
|
|
from runs.reply import say
|
|
out = say(deps, sid, text, tag=tag, harness=harness, inbox_only=inbox_only)
|
|
return {"ok": out is not None, "result": out}
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
# ── users.read ───────────────────────────────────────────────────────────────
|
|
def _safe_user(deps, uid: str) -> dict[str, Any] | None:
|
|
from users import domains as user_domains
|
|
from users.caller import OWNER_ID, OWNER_NAME
|
|
dom_default = user_domains.default_domain(deps)
|
|
if uid == OWNER_ID:
|
|
return {
|
|
"id": OWNER_ID, "name": OWNER_NAME, "email": "", "lang": "en",
|
|
"isOwner": True, "active": True, "domain": "", "bucket": "",
|
|
"projects": {},
|
|
"address": {"bucket": None, "domain": dom_default, "base": None, "apex": False},
|
|
}
|
|
u = deps.users.get(uid)
|
|
if not u:
|
|
return None
|
|
bucket, domain = user_domains.address_of(u, dom_default)
|
|
return {
|
|
"id": u["id"],
|
|
"name": u.get("name") or u["id"],
|
|
"email": u.get("email") or "",
|
|
"lang": u.get("lang") or "en",
|
|
"isOwner": False,
|
|
"active": bool(deps.users.active(u["id"])),
|
|
"domain": (u.get("domain") or "").strip(),
|
|
"bucket": (u.get("bucket") or "").strip(),
|
|
"projects": dict(u.get("projects") or {}),
|
|
"address": {
|
|
"bucket": bucket,
|
|
"domain": domain,
|
|
"base": user_domains.base_of(bucket, domain),
|
|
"apex": bool((u.get("domain") or "").strip()) and not bucket,
|
|
},
|
|
}
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/users")
|
|
async def hub_users_list(pid: str, request: Request):
|
|
deps, who, _rec, err = _check_cap(request, pid, "users.read", handler_only=True)
|
|
if err:
|
|
return err
|
|
|
|
def _go():
|
|
from users.caller import OWNER_ID
|
|
if not who.is_owner:
|
|
me = _safe_user(deps, who.uid)
|
|
return {"users": [me] if me else []}
|
|
rows = [_safe_user(deps, OWNER_ID)]
|
|
for u in deps.users.all():
|
|
if u.get("id"):
|
|
su = _safe_user(deps, u["id"])
|
|
if su:
|
|
rows.append(su)
|
|
return {"users": rows}
|
|
|
|
return await run_in_threadpool(_go)
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/users/{uid}")
|
|
async def hub_user_one(pid: str, uid: str, request: Request):
|
|
deps, who, _rec, err = _check_cap(request, pid, "users.read", handler_only=True)
|
|
if err:
|
|
return err
|
|
if not who.is_owner and uid != who.uid:
|
|
return _error(403, "users.read for other users is owner-only", "capability")
|
|
|
|
def _go():
|
|
from users.caller import OWNER_ID
|
|
target = OWNER_ID if uid == OWNER_UID else uid
|
|
return _safe_user(deps, target)
|
|
|
|
out = await run_in_threadpool(_go)
|
|
if not out:
|
|
return _error(404, "unknown user")
|
|
return out
|
|
|
|
|
|
# ── scaffold.run ─────────────────────────────────────────────────────────────
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/scaffold/templates")
|
|
async def hub_scaffold_templates(pid: str, request: Request):
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "scaffold.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
return await run_in_threadpool(_app_templates)
|
|
|
|
|
|
def _templates_dir() -> pathlib.Path:
|
|
return pathlib.Path(os.environ.get("TEMPLATES_DIR", "/workspace/projects/templates")).resolve()
|
|
|
|
|
|
def _template_description(d: pathlib.Path) -> str:
|
|
"""package.json's ``description``, else the README's first prose line —
|
|
an unfilled ``@@PLACEHOLDER@@`` reads as none (the Templates plugin's rule)."""
|
|
try:
|
|
desc = json.loads((d / "package.json").read_text(encoding="utf-8", errors="replace")).get("description")
|
|
if isinstance(desc, str) and desc.strip() and "@@" not in desc:
|
|
return desc.strip()
|
|
except (OSError, ValueError, AttributeError):
|
|
pass
|
|
for cand in ("README.md", "README", "readme.md"):
|
|
try:
|
|
text = (d / cand).read_text(encoding="utf-8", errors="replace")
|
|
except OSError:
|
|
continue
|
|
for line in text.splitlines():
|
|
t = line.strip()
|
|
if t and not t.startswith(("#", "![")) and "@@" not in t:
|
|
return t
|
|
return ""
|
|
return ""
|
|
|
|
|
|
def _app_templates() -> dict[str, Any]:
|
|
"""The scaffoldable app templates (a ``package.json`` / ``pyproject.toml``
|
|
at the root; not the service / skill ones) with their description."""
|
|
root = _templates_dir()
|
|
out = []
|
|
if root.is_dir():
|
|
for d in sorted(root.iterdir()):
|
|
if not d.is_dir() or d.name.startswith(".") or d.name.startswith(_NOT_APPS):
|
|
continue
|
|
if (d / "package.json").is_file() or (d / "pyproject.toml").is_file():
|
|
out.append({"name": d.name, "description": _template_description(d)})
|
|
return {"templates": out}
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/scaffold/check")
|
|
async def hub_scaffold_check(pid: str, request: Request):
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "scaffold.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
template = str(body.get("template") or "").strip()
|
|
vars_in = body.get("vars") if isinstance(body.get("vars"), dict) else {}
|
|
if not _SLUG_RE.match(template):
|
|
return _error(400, "invalid template name")
|
|
|
|
def _go():
|
|
from runs.sidecar_client import _sidecar_call
|
|
return _sidecar_call(deps, "/scaffold/check", {"template": template, "vars": vars_in}, timeout=90)
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/scaffold/run")
|
|
async def hub_scaffold_run(pid: str, request: Request):
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "scaffold.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
template = str(body.get("template") or "").strip()
|
|
vars_in = body.get("vars") if isinstance(body.get("vars"), dict) else {}
|
|
if not _SLUG_RE.match(template):
|
|
return _error(400, "invalid template name")
|
|
payload = {
|
|
"template": template,
|
|
"vars": vars_in,
|
|
"password": bool(body.get("password", False)),
|
|
}
|
|
|
|
def _go():
|
|
from runs.sidecar_client import _sidecar_call
|
|
return _sidecar_call(deps, "/scaffold", payload, timeout=SCAFFOLD_TIMEOUT_S)
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/scaffold/grant-project")
|
|
async def hub_scaffold_grant_project(pid: str, request: Request):
|
|
"""Grant a guest access to a newly scaffolded project."""
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "scaffold.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
uid = str(body.get("uid") or "").strip()
|
|
slug = str(body.get("slug") or "").strip()
|
|
level = str(body.get("level") or "ship").strip()
|
|
if not uid or not _SLUG_RE.match(slug) or level not in ("read", "chat", "ship"):
|
|
return _error(400, "uid, valid slug and level (read|chat|ship) required")
|
|
|
|
def _go():
|
|
u = deps.users.get(uid)
|
|
if not u:
|
|
raise HTTPException(404, f"unknown user {uid}")
|
|
deps.users.update(uid, {"projects": {**(u.get("projects") or {}), slug: level}})
|
|
deps.hub.publish({"type": "users"})
|
|
return {"ok": True, "uid": uid, "slug": slug, "level": level}
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/scaffold/relocate")
|
|
async def hub_scaffold_relocate(pid: str, request: Request):
|
|
"""Relocate session ``sid`` into project ``slug`` and resume it with ``prompt``."""
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "scaffold.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
sid = str(body.get("sessionId") or "").strip()
|
|
slug = str(body.get("slug") or "").strip()
|
|
prompt = str(body.get("prompt") or "").strip()
|
|
if not _SID_RE.match(sid) or not _SLUG_RE.match(slug) or not prompt:
|
|
return _error(400, "sessionId, slug and prompt are required")
|
|
|
|
def _go():
|
|
from runs.reply import caller_of, requester_of
|
|
from runs.service import _send_message, _session_account
|
|
from runs.sidecar_client import _sidecar_call
|
|
from users import runs as guest_runs
|
|
from users.caller import OWNER_ID
|
|
|
|
cwd = guest_runs.project_cwd(slug)
|
|
_sidecar_call(deps, "/relocate", {"sessionId": sid, "cwd": cwd,
|
|
"account": _session_account(deps, sid)}, timeout=30)
|
|
deps.meta_store.update(sid, {"projects": [slug], "state": "running"})
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
requester = requester_of(deps, sid)
|
|
scope = None
|
|
if requester != OWNER_ID:
|
|
caller = caller_of(deps, requester)
|
|
if caller is None:
|
|
raise HTTPException(403, f"guest {requester} is not active")
|
|
scope = guest_runs.scope_for(caller, slug, caller.level(slug),
|
|
guest_runs.shared_skills(deps),
|
|
new_projects=guest_runs.new_project_line(deps, caller),
|
|
deps=deps)
|
|
out = _send_message(deps, prompt, session_id=sid, cwd=cwd, harness="claude", scope=scope)
|
|
return {"ok": True, "sessionId": out.get("sessionId") or sid, "cwd": cwd}
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
# ── ship.run ─────────────────────────────────────────────────────────────────
|
|
_HOST_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$")
|
|
_DEPLOY_HOST_RE = re.compile(r"""(?:\bHOST=["']?|\s-d\s+["']?|--domain[= ]["']?)([a-z0-9.-]+\.[a-z]{2,})""")
|
|
_BUILD_DIR_RE = re.compile(r"^[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$")
|
|
_SHIP_AUDIT_KINDS = ("guard_block", "ship_deploy")
|
|
|
|
|
|
def _ship_project(slug: Any) -> tuple[str, pathlib.Path] | None:
|
|
from projects.catalog import _safe_entry
|
|
if not isinstance(slug, str) or not _SLUG_RE.match(slug.strip()):
|
|
return None
|
|
entry = _safe_entry(slug.strip())
|
|
return (entry.name, entry) if entry is not None else None
|
|
|
|
|
|
def _zipgo_deploy(root: pathlib.Path) -> dict[str, Any]:
|
|
try:
|
|
z = json.loads((root / "package.json").read_text()).get("zipgo") or {}
|
|
dep = z.get("deploy") if isinstance(z, dict) else None
|
|
return dep if isinstance(dep, dict) else {}
|
|
except (OSError, ValueError, AttributeError):
|
|
return {}
|
|
|
|
|
|
def ship_scan(root: pathlib.Path) -> dict[str, Any]:
|
|
"""The hosts a project's own deploy config names — ``package.json``
|
|
``zipgo.deploy`` keys and ``scripts/deploy*.sh`` ``HOST=`` / ``-d`` /
|
|
``--domain`` — and each ``zipgo.deploy`` host's build dir (``ship/service.py``'s
|
|
scan). A seed for the owner's list, never an allowlist by itself."""
|
|
dep = _zipgo_deploy(root)
|
|
hosts: set[str] = {h.lower() for h in dep if isinstance(h, str)}
|
|
for f in sorted((root / "scripts").glob("deploy*.sh"))[:10]:
|
|
try:
|
|
hosts.update(m.group(1) for m in _DEPLOY_HOST_RE.finditer(f.read_text()[:200_000]))
|
|
except OSError:
|
|
pass
|
|
build_dirs = {h.lower(): v.strip().strip("/") for h, v in dep.items()
|
|
if isinstance(h, str) and isinstance(v, str) and v.strip().strip("/")}
|
|
return {"hosts": sorted(h for h in hosts if _HOST_RE.match(h)), "buildDirs": build_dirs}
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/ship/scan")
|
|
async def hub_ship_scan(pid: str, request: Request, project: str = ""):
|
|
_deps, _who_c, _rec, err = _check_cap(request, pid, "ship.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
hit = _ship_project(project)
|
|
if hit is None:
|
|
return _error(404, "unknown project")
|
|
out = await run_in_threadpool(ship_scan, hit[1])
|
|
return {"project": hit[0], **out}
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/ship/deploy")
|
|
async def hub_ship_deploy(pid: str, request: Request):
|
|
"""Publish ``project``'s build dir to ``host`` through the host sidecar's
|
|
zipgo broker. The plugin decided it may (its rules: the guest's ``ship``
|
|
grant, the host allowlist); the hub checks the shape, runs it and writes
|
|
the tamper-proof ``ship_deploy`` security event naming ``actor``."""
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "ship.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
hit = _ship_project(body.get("project"))
|
|
if hit is None:
|
|
return _error(404, "unknown project")
|
|
slug, root = hit
|
|
host = str(body.get("host") or "").strip().lower()
|
|
if not _HOST_RE.match(host):
|
|
return _error(400, "invalid host")
|
|
bdir = body.get("dir")
|
|
if bdir is None or not str(bdir).strip():
|
|
sub = _zipgo_deploy(root).get(host)
|
|
bdir = sub.strip().strip("/") if isinstance(sub, str) and sub.strip().strip("/") else "dist"
|
|
bdir = str(bdir).strip().strip("/")
|
|
if not _BUILD_DIR_RE.match(bdir) or ".." in bdir.split("/"):
|
|
return _error(400, "invalid build dir")
|
|
actor = str(body.get("actor") or "owner")[:64]
|
|
sid = str(body.get("sessionId") or "")[:80] or None
|
|
|
|
def _go():
|
|
from runs.sidecar_client import _sidecar_call
|
|
from security import service as security
|
|
out = _sidecar_call(deps, "/ship/deploy", {"project": slug, "host": host, "dir": bdir},
|
|
timeout=280)
|
|
security.record(deps, "ship_deploy", who=actor, sid=sid,
|
|
detail=f"{slug} → {host}", data={"plugin": pid, "dir": bdir})
|
|
return out
|
|
|
|
try:
|
|
out = await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
out = out if isinstance(out, dict) else {}
|
|
return {"ok": True, "url": out.get("url") or f"https://{host}", "host": host,
|
|
"project": slug, "dir": bdir, "output": out.get("output") or ""}
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/ship/audit")
|
|
async def hub_ship_audit(pid: str, request: Request):
|
|
"""A ``guard_block`` (a refused deploy) or ``ship_deploy`` event in the
|
|
hub's security log, from the ship plugin's own handlers."""
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "ship.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
kind = body.get("kind")
|
|
if kind not in _SHIP_AUDIT_KINDS:
|
|
return _error(400, f"kind must be one of {', '.join(_SHIP_AUDIT_KINDS)}")
|
|
actor = str(body.get("actor") or "").strip()[:64]
|
|
if not actor:
|
|
return _error(400, "actor is required")
|
|
project = str(body.get("project") or "")[:64]
|
|
host = str(body.get("host") or "")[:253]
|
|
detail = str(body.get("detail") or "").strip()
|
|
if not detail:
|
|
detail = f"ship deploy to {host or '?'} refused" if kind == "guard_block" else f"{project} → {host}"
|
|
sid = str(body.get("sessionId") or "")[:80] or None
|
|
|
|
def _go():
|
|
from security import service as security
|
|
return security.record(deps, kind, who=actor, sid=sid, detail=detail[:500],
|
|
data={"plugin": pid, **({"project": project} if project else {}),
|
|
**({"host": host} if host else {})})
|
|
|
|
await run_in_threadpool(_go)
|
|
return {"ok": True}
|