Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat: give Alfa the reach MCP has, and a gate so they cannot drift apart again
Rahman7ed3ff523504
diff --git a/app/api/v1/camoufox/service/route.ts b/app/api/v1/camoufox/service/route.tsindex f3f431d0..cb997a69 100644--- a/app/api/v1/camoufox/service/route.ts+++ b/app/api/v1/camoufox/service/route.ts@@ -1,7 +1,7 @@import { NextResponse } from "next/server";import { verifyAuth } from "@/lib/agent/server";import { camoufoxStatus, setCamoufoxEnabled } from "@/lib/camoufox/service";-import { apiError, audit, readJson } from "@/lib/host";+import { apiError, audit, rateLimited, readJson } from "@/lib/host";export const runtime = "nodejs";export const dynamic = "force-dynamic";@@ -23,6 +23,13 @@ export async function GET(req: Request) {// POST /camoufox/service {action:"start"|"stop"} → the status AFTER the change.export async function POST(req: Request) {if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ // Each start forks systemctl and boots a browser on an X display. This route had+ // no limit at all, which was survivable while the only caller was a toggle in the+ // UI and stopped being so when an MCP bearer could reach it. Same shape and+ // number as the managed-app bucket, which is the same kind of operation.+ if (rateLimited("camoufox", 12, 60_000)) {+ return NextResponse.json({ error: "too many operations" }, { status: 429 });+ }try {const { action } = (await readJson(req)) as { action?: unknown };if (action !== "start" && action !== "stop") {diff --git a/docs/MCP.md b/docs/MCP.mdindex 29ac155b..1047a2dc 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -63,6 +63,12 @@ Picked per token, on the consent screen, capped by `OS_MCP_MAX_SCOPE`.| `write` | + `fs_write` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` || `exec` | + `exec_run` `browser_power` |+Alfa — the in-app assistant — has the same capabilities under dot.case names, and+`lib/mcp/parity.test.ts` fails if one surface gains a tool the other lacks without a+written reason. The two catalogs stay separate on purpose (different transport,+different guard) but may not drift by accident, which they did: MCP shipped the+managed-app and browser tools before Alfa had them.+The tiering is about blast radius, not about which layer the call lands in.`apps_logs` reads a daemon's journal, so "why is hermes down?" is answerable froma `read` token — the same question through `exec_run` would need a full shell.@@ -161,6 +167,13 @@ registrations/hour/IP. Token exchange: 30/min/IP. All in-memory (process-local,resets on restart) — enough to blunt a runaway agent, which is the realisticfailure mode for an endpoint whose top scope is a shell.+Those are per TOKEN and say nothing about which tool ran, so each mutating tool+also carries the **per-operation** limit its `/api/v1` route already applies, on+the SAME bucket key — MCP and the browser share one allowance rather than getting+one each. `exec_run` 60/min, fs writes 120/min, fs copy/delete 60/min,+`apps_power` and `browser_power` 12/min per app. Without this a write-scope token+could restart a daemon 120×/min while the UI was capped at 12.+## Layout```diff --git a/frontend/slices/appshell/lib/host-api.tsx b/frontend/slices/appshell/lib/host-api.tsxindex 3da71be6..ea61d612 100644--- a/frontend/slices/appshell/lib/host-api.tsx+++ b/frontend/slices/appshell/lib/host-api.tsx@@ -64,6 +64,12 @@ export type Process = {export type AppManifest = { name: string; slug: string; runtime: string; entry: string };+/** A managed application on the host (hermes, openclaw) — the thing that actually+ * has server state, unlike the UI app list, which lives in localStorage. */+export type ManagedAppSummary = { id: string; name: string; installed: boolean; running: boolean };+export type ManagedAppAction = "start" | "stop" | "restart" | "backup";+export type BrowserState = { installed: boolean; running: boolean; autostart: boolean };+export type OsApi = {mode: "mock" | "live";auth: {@@ -100,10 +106,17 @@ export type OsApi = {statsStream: (onEvent: (s: Partial<SysStats>) => void) => Unsub;processes: () => Promise<Process[]>;};+ // Managed apps, not the UI app list. `start`/`stop` used to sit here pointed at+ // /apps/:slug/start and /apps/:slug/stop — neither of which is a route — while+ // `list` hit /apps, which returns [] by construction.apps: {- list: () => Promise<AppManifest[]>;- start: (slug: string) => Promise<{ slug: string; state: string }>;- stop: (slug: string) => Promise<{ ok: boolean }>;+ list: () => Promise<ManagedAppSummary[]>;+ logs: (id: string) => Promise<{ available: boolean; entries: string[] }>;+ power: (id: string, action: ManagedAppAction) => Promise<ManagedAppSummary>;+ };+ browser: {+ status: () => Promise<BrowserState>;+ power: (on: boolean) => Promise<BrowserState>;};};diff --git a/frontend/slices/assistant/host-tools/catalog-mutate.ts b/frontend/slices/assistant/host-tools/catalog-mutate.tsindex 9fb88f7e..1deafc33 100644--- a/frontend/slices/assistant/host-tools/catalog-mutate.ts+++ b/frontend/slices/assistant/host-tools/catalog-mutate.ts@@ -87,6 +87,39 @@ export const MUTATE_TOOLS: HostTool[] = [return `forgot ${hits.length}: ${hits.map((m) => m.text).join("; ")}`;},},+ {+ name: "apps.power",+ group: "apps",+ label: "Start/stop app",+ effect: "mutate",+ description:+ "Start, stop, restart or back up a managed application (hermes, openclaw). Bounded to those apps and those four verbs — this exists so restarting a daemon does not require exec.run, which the destructive-command filter refuses for systemctl anyway. Check apps.list or apps.logs first.",+ parameters: obj({+ "id!": str("Managed app id from apps.list, e.g. hermes"),+ "action!": str("start | stop | restart | backup"),+ }),+ run: async (api, a) => {+ const action = String(a.action);+ if (!["start", "stop", "restart", "backup"].includes(action))+ return `unknown action "${action}" — use start, stop, restart or backup`;+ const r = await api.apps.power(String(a.id), action as "start" | "stop" | "restart" | "backup");+ return `${r.name}: ${r.running ? "running" : "stopped"} (after ${action})`;+ },+ },+ {+ name: "browser.power",+ group: "apps",+ label: "Browser on/off",+ effect: "mutate",+ description:+ "Start or stop the Camoufox browser session. Starting boots a real Firefox on a headless display holding the user's live logins; it self-terminates after 2h. Stop it when the user is done.",+ parameters: obj({ "on!": str("true to start, false to stop") }),+ run: async (api, a) => {+ const on = String(a.on).toLowerCase() === "true";+ const s = await api.browser.power(on);+ return `camoufox is now ${s.running ? "running" : "stopped"}`;+ },+ },{name: "exec.run",group: "terminal",diff --git a/frontend/slices/assistant/host-tools/catalog.ts b/frontend/slices/assistant/host-tools/catalog.tsindex c03e82a2..ab747425 100644--- a/frontend/slices/assistant/host-tools/catalog.ts+++ b/frontend/slices/assistant/host-tools/catalog.ts@@ -89,11 +89,43 @@ const READ_TOOLS: HostTool[] = [group: "apps",label: "List apps",effect: "read",- description: "List installed host apps (name + slug).",+ description:+ "List the managed applications on this VPS (hermes, openclaw) with whether each is installed and running. This is NOT the mso app list (Files, Terminal, …) — those are UI windows with no server state; use app.open for those.",parameters: obj({}),run: async (api) => {const apps = await api.apps.list();- return apps.length ? apps.map((x) => `${x.name} (${x.slug})`).join("\n") : "no apps installed";+ if (!apps.length) return "no managed applications on this host";+ return apps+ .map((x) => `${x.name} (${x.id}) — ${x.installed ? (x.running ? "running" : "installed, stopped") : "not installed"}`)+ .join("\n");+ },+ },+ {+ name: "apps.logs",+ group: "apps",+ label: "App logs",+ effect: "read",+ description:+ "Recent log output for a managed application. USE THIS to answer 'why is hermes down' — it reads the journal and changes nothing, where the same question through exec.run needs a command the user must approve. Call apps.list first for the ids.",+ parameters: obj({ "id!": str("Managed app id from apps.list, e.g. hermes") }),+ run: async (api, a) => {+ const r = await api.apps.logs(String(a.id));+ if (!r.available) return `no logs available for ${a.id}`;+ return clip(r.entries.join("\n") || "(empty)");+ },+ },+ {+ name: "browser.status",+ group: "apps",+ label: "Browser status",+ effect: "read",+ description:+ "Whether the Camoufox browser session (a real Firefox on a headless display) is installed and running. The viewer URL and its one-time VNC password are NOT returned — that profile holds live logins, so the user opens it from Settings themselves.",+ parameters: obj({}),+ run: async (api) => {+ const s = await api.browser.status();+ if (!s.installed) return "camoufox is not installed on this host";+ return `camoufox is ${s.running ? "running" : "stopped"} (autostart ${s.autostart ? "on" : "off"})`;},},{diff --git a/frontend/slices/assistant/host-tools/registry.test.ts b/frontend/slices/assistant/host-tools/registry.test.tsindex b96fd839..2558e17b 100644--- a/frontend/slices/assistant/host-tools/registry.test.ts+++ b/frontend/slices/assistant/host-tools/registry.test.ts@@ -7,8 +7,8 @@ import { findHostTool, HOST_AI_TOOLS } from "./registry";describe("host-tools registry", () => {it("classifies reads as read; fs mutations + exec as mutate", () => {const eff = (n: string) => findHostTool(n)?.effect;- for (const n of ["fs.list", "fs.read", "fs.search", "fs.usage", "sys.stats", "sys.processes", "apps.list", "skills.list", "skills.read", "memory.remember"]) expect(eff(n)).toBe("read");- for (const n of ["fs.write", "fs.mkdir", "fs.move", "fs.copy", "fs.delete", "exec.run", "memory.forget"]) expect(eff(n)).toBe("mutate");+ for (const n of ["fs.list", "fs.read", "fs.search", "fs.usage", "sys.stats", "sys.processes", "apps.list", "apps.logs", "browser.status", "skills.list", "skills.read", "memory.remember"]) expect(eff(n)).toBe("read");+ for (const n of ["fs.write", "fs.mkdir", "fs.move", "fs.copy", "fs.delete", "exec.run", "memory.forget", "apps.power", "browser.power"]) expect(eff(n)).toBe("mutate");});it("memory.forget parks a card; memory.remember does not", () => {diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.tsindex 407dc084..93227327 100644--- a/lib/mcp/dispatch.ts+++ b/lib/mcp/dispatch.ts@@ -1,4 +1,4 @@-import { audit } from "@/lib/host";+import { audit, rateLimited } from "@/lib/host";import { TOOLS, TOOLS_BY_NAME } from "./tools";import { allows, type Scope } from "./scope";@@ -81,6 +81,20 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Pfor (const k of tool.inputSchema.required ?? []) {if (args[k] == null) return fail(id, -32602, `${name} needs { ${(tool.inputSchema.required ?? []).join(", ")} }`);}+ // The per-token bucket in app/mcp/route.ts does not know which tool ran, so+ // without this an MCP client could restart a daemon 120x/min while the UI and+ // the CLI share a 12/min bucket for the same operation. Deliberately the SAME+ // key the route uses, so the two share one bucket instead of getting one each.+ if (tool.limit) {+ const suffix = tool.limit.keyArg ? String(args[tool.limit.keyArg] ?? "") : (actor ?? "mcp");+ if (rateLimited(`${tool.limit.key}:${suffix}`, tool.limit.max, tool.limit.windowMs)) {+ void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: "rate limited" });+ return ok(id, {+ content: [{ type: "text", text: `error: ${name} is rate limited (${tool.limit.max} per ${Math.round(tool.limit.windowMs / 1000)}s). Wait and retry.` }],+ isError: true,+ });+ }+ }// MCP tools call lib/host directly, so the ROUTE-level audit that covers// /api/v1 never runs for them. Without this, every write, delete and exec// that arrived over MCP would be missing from the one forensic trail therediff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.tsnew file mode 100644index 00000000..4f41e87a--- /dev/null+++ b/lib/mcp/parity.test.ts@@ -0,0 +1,99 @@+import { describe, it, expect, vi } from "vitest";+vi.mock("server-only", () => ({}));++const { TOOLS } = await import("./tools");+const { HOST_TOOLS } = await import("@/frontend/slices/assistant/host-tools/catalog");++// THE GATE. Alfa and MCP are two catalogs on purpose — different transport,+// different guard (an approval card vs a scope tier), different handlers — and+// unifying them was considered and rejected: they share zero names, zero+// descriptions and zero handlers, so a shared registry would be an abstraction+// with two divergent consumers.+//+// What they must NOT do is drift by ACCIDENT, which is exactly what happened:+// MCP shipped apps_logs / apps_power / browser_status / browser_power and Alfa+// silently had less reach over the box than a remote ChatGPT connector, while+// Alfa's apps.list had been answering "no apps installed" for months. Nobody+// decided either one.+//+// So: every capability must appear in BOTH catalogs, or be listed below with a+// reason. Adding a tool to one surface alone fails this test until someone writes+// down why.++/** MCP is snake_case, Alfa is dot.case. Same capability, different convention. */+const capability = (name: string) => name.replace(/[._]/g, ".");++/** Deliberately one-sided, each with the reason. Keep this list SHORT — every+ * entry is a place the two surfaces disagree, and a reader has to trust the+ * reason. If a reason stops being true, delete the line and add the tool. */+const ALFA_ONLY: Record<string, string> = {+ "app.open": "openWindow is browser store state; an MCP client has no window to open",+ "skills.list": "the skill catalog is the assistant's own prompt furniture, not host control",+ "skills.read": "same — and /api/skills reads outside the fs jail, so it stays off a bearer-reached surface",+ "memory.remember": "writes into the owner's Alfa recall, which an MCP client does not share",+ "memory.forget": "same store; an MCP client has its own memory",+};++const MCP_ONLY: Record<string, string> = {};++describe("Alfa ↔ MCP capability parity", () => {+ const alfa = new Set(HOST_TOOLS.map((t) => capability(t.name)));+ const mcp = new Set(TOOLS.map((t) => capability(t.name)));++ it("every MCP tool has an Alfa counterpart, or a written reason", () => {+ const orphans = [...mcp].filter((c) => !alfa.has(c) && !(c in MCP_ONLY));+ expect(orphans, "add the tool to Alfa's catalog, or add it to MCP_ONLY with a reason").toEqual([]);+ });++ it("every Alfa tool has an MCP counterpart, or a written reason", () => {+ const orphans = [...alfa].filter((c) => !mcp.has(c) && !(c in ALFA_ONLY));+ expect(orphans, "add the tool to lib/mcp, or add it to ALFA_ONLY with a reason").toEqual([]);+ });++ it("the exemption lists name tools that still exist", () => {+ // A stale exemption is worse than none: it silently excuses a capability that+ // was renamed or deleted, and the gate stops covering it.+ for (const c of Object.keys(ALFA_ONLY)) expect(alfa, `ALFA_ONLY names ${c}`).toContain(c);+ for (const c of Object.keys(MCP_ONLY)) expect(mcp, `MCP_ONLY names ${c}`).toContain(c);+ });++ it("a capability that mutates on one surface mutates on the other", () => {+ // The guards differ (card vs scope) but the CLASSIFICATION must not: a tool+ // that parks an approval card in Alfa and sits in MCP's read tier would be+ // reachable with no human and no scope check at all.+ const alfaEffect = new Map(HOST_TOOLS.map((t) => [capability(t.name), t.effect]));+ for (const t of TOOLS) {+ const c = capability(t.name);+ const a = alfaEffect.get(c);+ if (!a) continue;+ const mcpMutates = t.scope !== "read";+ expect(mcpMutates, `${t.name} is ${t.scope} in MCP but ${a} in Alfa`).toBe(a === "mutate");+ }+ });+});++describe("MCP rate limits mirror the routes", () => {+ it("every mutating tool carries a per-operation limit", () => {+ // The token bucket in app/mcp/route.ts is per TOKEN and tool-blind, so without+ // this a write-scope token got 120/min on a daemon restart the UI limits to 12.+ for (const t of TOOLS) {+ if (t.scope === "read") continue;+ expect(t.limit?.max, `${t.name} has no limit — mirror its route's rateLimited()`).toBeGreaterThan(0);+ }+ });++ it("never grants more than the route it mirrors", () => {+ // Numbers lifted from the route files. The route is the authority; MCP may be+ // stricter, never laxer.+ const ROUTE_LIMITS: Record<string, number> = {+ "fs.write": 120, "fs.mkdir": 120, "fs.move": 120, "fs.copy": 60,+ "fs.delete": 60, "exec": 60, "managed-app": 12, "camoufox": 12,+ };+ for (const t of TOOLS) {+ if (!t.limit) continue;+ const route = ROUTE_LIMITS[t.limit.key];+ expect(route, `${t.name} limits on key "${t.limit.key}", which no route uses`).toBeDefined();+ expect(t.limit.max, `${t.name} allows more than its route`).toBeLessThanOrEqual(route);+ }+ });+});diff --git a/lib/mcp/tool-kit.ts b/lib/mcp/tool-kit.tsindex 22bdf3ee..bacc63b6 100644--- a/lib/mcp/tool-kit.ts+++ b/lib/mcp/tool-kit.ts@@ -33,6 +33,18 @@ export interface McpTool {* NOT a generic result→outcome mapper: one call site is not a pattern. */outcome?: (result: unknown) => { ok: boolean; action?: AuditAction; detail?: string };};+ /** Per-OPERATION rate limit, mirroring the one its /api/v1 route already applies.+ *+ * The token bucket in app/mcp/route.ts is per TOKEN (120/min, 5000/day) and says+ * nothing about which tool was called, so an MCP client got the same allowance+ * for `apps_power` as for `fs_list` — while the browser and the CLI hit+ * `managed-app:<id>` at 12/min going through the route. That is a 10x gap on a+ * daemon restart, available to a WRITE-scope token that holds no shell.+ *+ * `keyArg` puts the bucket on the same key the route uses, so MCP and the UI+ * share it rather than getting one each. Numbers here must MATCH the route's,+ * never undercut them — the route is the authority. */+ limit?: { max: number; windowMs: number; keyArg?: string; key: string };}export const str = (a: Record<string, unknown>, k: string): string => {diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.tsindex 900a7e95..82c1f659 100644--- a/lib/mcp/tools.ts+++ b/lib/mcp/tools.ts@@ -11,6 +11,7 @@ import { READ_TOOLS } from "./tools-read";const MUTATE_TOOLS: McpTool[] = [{name: "fs_write",+ limit: { key: "fs.write", max: 120, windowMs: 60_000 },audit: { action: "fs.write" as const, targetArg: "path" },description:"Create or overwrite a text file on the VPS. Overwrites without warning — fs_read first if you need " +@@ -25,6 +26,7 @@ const MUTATE_TOOLS: McpTool[] = [},{name: "fs_mkdir",+ limit: { key: "fs.mkdir", max: 120, windowMs: 60_000 },audit: { action: "fs.mkdir" as const, targetArg: "path" },description: "Create a directory (and any missing parents) on the VPS.",scope: "write",@@ -34,6 +36,7 @@ const MUTATE_TOOLS: McpTool[] = [},{name: "fs_move",+ limit: { key: "fs.move", max: 120, windowMs: 60_000 },audit: { action: "fs.move" as const, targetArg: "from" },description: "Move or rename a file or directory. Refuses when the source holds credential paths.",scope: "write",@@ -42,6 +45,7 @@ const MUTATE_TOOLS: McpTool[] = [},{name: "fs_copy",+ limit: { key: "fs.copy", max: 60, windowMs: 60_000 },audit: { action: "fs.copy" as const, targetArg: "from" },description: "Copy a file or directory. The cockpit's own secrets are skipped rather than duplicated.",scope: "write",@@ -50,6 +54,7 @@ const MUTATE_TOOLS: McpTool[] = [},{name: "fs_delete",+ limit: { key: "fs.delete", max: 60, windowMs: 60_000 },audit: { action: "fs.delete" as const, targetArg: "path" },description:"Delete a file or directory on the VPS. PERMANENT — there is no trash and no undo. " +@@ -62,6 +67,7 @@ const MUTATE_TOOLS: McpTool[] = [{name: "apps_power",+ limit: { key: "managed-app", max: 12, windowMs: 60_000, keyArg: "id" },audit: { action: "managed-app.action" as const, targetArg: "id" },description:"Start, stop or restart a managed application on the VPS. Bounded to the known apps and the " +@@ -83,6 +89,7 @@ const MUTATE_TOOLS: McpTool[] = [},{name: "exec_run",+ limit: { key: "exec", max: 60, windowMs: 60_000 },audit: {action: "exec.run" as const,targetArg: "command",@@ -111,6 +118,7 @@ const MUTATE_TOOLS: McpTool[] = [},{name: "browser_power",+ limit: { key: "camoufox", max: 12, windowMs: 60_000 },audit: { action: "camoufox.power" as const, targetArg: "on" },description:"Start or stop the Camoufox browser session on the VPS. Starting boots a real Firefox on a headless " +diff --git a/lib/os-api/http-adapter.ts b/lib/os-api/http-adapter.tsindex e625779c..0f835196 100644--- a/lib/os-api/http-adapter.ts+++ b/lib/os-api/http-adapter.ts@@ -90,9 +90,13 @@ export function HttpAdapter(cfg: { url?: string }): OsApi {processes: () => req("GET", "/sys/processes"),},apps: {- list: () => req("GET", "/apps"),- start: (slug) => req("POST", `/apps/${slug}/start`),- stop: (slug) => req("POST", `/apps/${slug}/stop`),+ list: () => req("GET", "/managed-apps"),+ logs: (id) => req("GET", `/managed-apps/${encodeURIComponent(id)}/logs`),+ power: (id, action) => req("POST", `/managed-apps/${encodeURIComponent(id)}`, { body: { action } }),+ },+ browser: {+ status: () => req("GET", "/camoufox/service"),+ power: (on) => req("POST", "/camoufox/service", { body: { action: on ? "start" : "stop" } }),},};}diff --git a/lib/os-api/mock-adapter.ts b/lib/os-api/mock-adapter.tsindex d4ab2608..2618198d 100644--- a/lib/os-api/mock-adapter.ts+++ b/lib/os-api/mock-adapter.ts@@ -56,9 +56,19 @@ export function MockAdapter(): OsApi {]),},apps: {- list: () => delay([]),- start: (slug) => delay({ slug, state: "running" }, 400),- stop: (slug) => delay({ ok: true }),+ list: () =>+ delay([+ { id: "hermes", name: "Hermes", installed: true, running: true },+ { id: "openclaw", name: "OpenClaw", installed: true, running: false },+ ]),+ logs: (id) =>+ delay({ available: true, entries: [`[mock] ${id}: nothing to report — this is mock mode`] }),+ power: (id, action) =>+ delay({ id, name: id, installed: true, running: action !== "stop" }, 400),+ },+ browser: {+ status: () => delay({ installed: true, running: false, autostart: false }),+ power: (on) => delay({ installed: true, running: on, autostart: false }, 400),},};}