Skip to content

armgit / mso

Public Imported from GitHub
0

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.

test(api): cover 30 more routes, and close the one fs route with no rate limit

Abdurrahman Fakhrulf878496c55ba
diff --git a/app/api/v1/editor/exec/route.test.ts b/app/api/v1/editor/exec/route.test.ts
new file mode 100644
index 00000000..b1fcf1fc
--- /dev/null
+++ b/app/api/v1/editor/exec/route.test.ts
@@ -0,0 +1,117 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ readFile: vi.fn(),
+ writeFile: vi.fn(),
+}));
+
+vi.mock("@/lib/agent/server", () => ({
+ verifyAuth: mocks.verifyAuth,
+}));
+vi.mock("@/lib/host/fs-api", () => ({
+ readFile: mocks.readFile,
+ writeFile: mocks.writeFile,
+ statReadable: vi.fn(),
+ fileStream: vi.fn(),
+}));
+
+import { GET, POST } from "./route";
+import { HEADLESS_TOOLS } from "@/features/image-editor/server";
+
+function makeReq(url: string, method = "GET", body?: unknown): Request {
+ return new Request(url, {
+ method,
+ headers: body ? { "content-type": "application/json" } : undefined,
+ body: typeof body === "string" ? body : body ? JSON.stringify(body) : undefined,
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.readFile.mockRejectedValue(new Error("ENOENT"));
+ mocks.writeFile.mockResolvedValue(undefined);
+});
+
+describe("GET /api/v1/editor/exec", () => {
+ it("refuses unauthenticated requests", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await GET(makeReq("https://mso.example/api/v1/editor/exec"));
+ expect(res.status).toBe(401);
+ });
+
+ it("returns available headless tools", async () => {
+ const res = await GET(makeReq("https://mso.example/api/v1/editor/exec"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ tools: HEADLESS_TOOLS });
+ });
+});
+
+describe("POST /api/v1/editor/exec", () => {
+ it("refuses unauthenticated requests", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await POST(makeReq("https://mso.example/api/v1/editor/exec", "POST", {}));
+ expect(res.status).toBe(401);
+ });
+
+ it("returns 400 on malformed json payload", async () => {
+ const res = await POST(makeReq("https://mso.example/api/v1/editor/exec", "POST", "{invalid-json"));
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "invalid json" });
+ });
+
+ it("executes commands on a new blank doc when no doc exists", async () => {
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/editor/exec", "POST", {
+ commands: [{ name: "doc.resize", args: { width: 500, height: 500 } }],
+ }),
+ );
+ expect(res.status).toBe(200);
+ const data = await res.json();
+ expect(data.doc.width).toBe(500);
+ expect(data.doc.height).toBe(500);
+ expect(data.results).toHaveLength(1);
+ expect(data.results[0]).toEqual({ name: "doc.resize", ok: true, result: "canvas → 500x500" });
+ });
+
+ it("refuses to overwrite a path containing non-JSON", async () => {
+ mocks.readFile.mockResolvedValue("not-json-content");
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/editor/exec", "POST", { path: "/tmp/not-doc.txt" }),
+ );
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({
+ error: `"/tmp/not-doc.txt" exists but is not JSON — refusing to overwrite`,
+ });
+ });
+
+ it("refuses to overwrite a path containing JSON that is not an editor doc", async () => {
+ mocks.readFile.mockResolvedValue(JSON.stringify({ someKey: "not an editor doc" }));
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/editor/exec", "POST", { path: "/tmp/package.json" }),
+ );
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({
+ error: `"/tmp/package.json" is not an editor document — refusing to overwrite`,
+ });
+ });
+
+ it("reads, mutates and writes an existing document", async () => {
+ const { blankDoc } = await import("@/features/image-editor/server");
+ const existingDoc = blankDoc(400, 300);
+ mocks.readFile.mockResolvedValue(JSON.stringify(existingDoc));
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/editor/exec", "POST", {
+ path: "/tmp/project.doc.json",
+ commands: [{ name: "doc.resize", args: { width: 800, height: 600 } }],
+ }),
+ );
+ expect(res.status).toBe(200);
+ expect(mocks.writeFile).toHaveBeenCalledWith("/tmp/project.doc.json", expect.stringContaining('"width":800'));
+ const body = await res.json();
+ expect(body.written).toBe("/tmp/project.doc.json");
+ expect(body.doc.width).toBe(800);
+ expect(body.doc.height).toBe(600);
+ });
+});
diff --git a/app/api/v1/exec/run/route.test.ts b/app/api/v1/exec/run/route.test.ts
index 0c329b23..2095da67 100644
--- a/app/api/v1/exec/run/route.test.ts
+++ b/app/api/v1/exec/run/route.test.ts
@@ -44,27 +44,21 @@ describe("/api/v1/exec/run", () => {
vi.useRealTimers();
});
- it("returns 200 with stdout for an authenticated safe command", async () => {
+ it("returns 200 with stdout for an authenticated safe command and audits success", async () => {
runCommandMock.mockResolvedValueOnce({ stdout: "hi\n", stderr: "", code: 0 });
const { POST } = await import("./route");
- const res = await POST(makeReq({ cmd: "echo hi" }));
+ const res = await POST(makeReq({ cmd: "echo hi", cwd: "/home" }));
expect(res.status).toBe(200);
const body = await res.json();
expect(body.stdout).toBe("hi\n");
expect(body.code).toBe(0);
- expect(runCommandMock).toHaveBeenCalledWith("echo hi", undefined);
- });
-
- it("returns 401 when verifyAuth rejects the caller", async () => {
- const { verifyAuth } = await import("@/lib/agent/server");
- vi.mocked(verifyAuth).mockResolvedValueOnce(false);
- const { POST } = await import("./route");
- const res = await POST(makeReq({ cmd: "echo hi" }));
- expect(res.status).toBe(401);
- expect(runCommandMock).not.toHaveBeenCalled();
+ expect(runCommandMock).toHaveBeenCalledWith("echo hi", "/home");
+ expect(auditMock).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "exec.run", ok: true, target: "echo hi", detail: "exit 0 @ /home" }),
+ );
});
- it("returns 200 with code 126 + 'refused:' stderr for destructive commands", async () => {
+ it("returns 200 with code 126 + 'refused:' stderr for destructive commands and audits blocked", async () => {
// The route doesn't itself reject destructive — runCommand returns the
// signed refusal envelope (stderr "refused: …", code 126) which the route
// then logs as audit.action=exec.blocked. We assert that mapping.
@@ -84,7 +78,7 @@ describe("/api/v1/exec/run", () => {
);
});
- it("returns 429 when burst limit exceeds 60 hits in 60s", async () => {
+ it("returns 429 when burst limit exceeds 60 hits in 60s and audits rate-limited", async () => {
runCommandMock.mockResolvedValue({ stdout: "", stderr: "", code: 0 });
const { POST } = await import("./route");
// 60 within window pass; 61st trips.
@@ -101,10 +95,21 @@ describe("/api/v1/exec/run", () => {
);
});
- it("returns 400 when the cmd field is missing", async () => {
+ it("returns 400 when command shape is invalid (missing cmd or invalid cwd)", async () => {
const { POST } = await import("./route");
- const res = await POST(makeReq({}));
- expect(res.status).toBe(400);
+ expect((await POST(makeReq({}))).status).toBe(400);
+ expect((await POST(makeReq({ cmd: 123 }))).status).toBe(400);
+ expect((await POST(makeReq({ cmd: "ls", cwd: 123 }))).status).toBe(400);
expect(runCommandMock).not.toHaveBeenCalled();
});
+
+ it("audits failure and returns error when runCommand throws", async () => {
+ runCommandMock.mockRejectedValueOnce(new Error("spawn failed"));
+ const { POST } = await import("./route");
+ const res = await POST(makeReq({ cmd: "broken" }));
+ expect(res.status).toBe(500);
+ expect(auditMock).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "exec.run", target: "broken", ok: false }),
+ );
+ });
});
diff --git a/app/api/v1/flows/route.test.ts b/app/api/v1/flows/route.test.ts
new file mode 100644
index 00000000..09fc202b
--- /dev/null
+++ b/app/api/v1/flows/route.test.ts
@@ -0,0 +1,128 @@
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+const mocks = vi.hoisted(() => ({
+ session: vi.fn(),
+ flowCatalog: vi.fn(async () => ({ project: { id: "p1" }, flows: [], revision: "rev-1" })),
+ flowStatus: vi.fn(async () => ({ run_id: "run-1", status: "completed" })),
+ createSession: vi.fn(async () => ({ id: "sess-1" })),
+ executeCapability: vi.fn(async (): Promise<Record<string, unknown>> => ({ kind: "success", result: { ok: true, run_id: "run-1" } })),
+}));
+
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: mocks.session,
+}));
+vi.mock("@/lib/workflow/automation-catalog", () => ({
+ flowCatalog: mocks.flowCatalog,
+}));
+vi.mock("@/lib/workflow/automation-engine", () => ({
+ flowStatus: mocks.flowStatus,
+}));
+vi.mock("@/lib/agent/session-store", () => ({
+ createAgentSession: mocks.createSession,
+}));
+vi.mock("@/lib/capabilities/execute", () => ({
+ executeCapabilityCall: mocks.executeCapability,
+}));
+
+import { GET, POST } from "./route";
+
+function makeReq(url: string, method = "GET", body?: unknown): NextRequest {
+ return new NextRequest(url, {
+ method,
+ headers: body ? { "content-type": "application/json" } : undefined,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-owner" }, role: "owner" });
+ mocks.flowCatalog.mockResolvedValue({ project: { id: "p1" }, flows: [], revision: "rev-1" });
+ mocks.flowStatus.mockResolvedValue({ run_id: "run-1", status: "completed" });
+ mocks.createSession.mockResolvedValue({ id: "sess-1" });
+ mocks.executeCapability.mockResolvedValue({ kind: "success", result: { ok: true, run_id: "run-1" } });
+});
+
+describe("GET /api/v1/flows", () => {
+ it("refuses unauthenticated callers", async () => {
+ mocks.session.mockResolvedValue(null);
+ const res = await GET(makeReq("https://mso.example/api/v1/flows"));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "owner_required" });
+ expect(mocks.flowCatalog).not.toHaveBeenCalled();
+ });
+
+ it.each(["viewer", "operator"])("refuses %s role with owner_required", async (role) => {
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-sub" }, role });
+ const res = await GET(makeReq("https://mso.example/api/v1/flows"));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "owner_required" });
+ });
+
+ it("returns catalog when no run_id query is present", async () => {
+ const res = await GET(makeReq("https://mso.example/api/v1/flows?project=p1&flow=deploy"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ project: "p1", flows: [], revision: "rev-1" });
+ expect(mocks.flowCatalog).toHaveBeenCalledWith("p1", "deploy");
+ });
+
+ it("returns flow status when run_id is supplied", async () => {
+ const res = await GET(makeReq("https://mso.example/api/v1/flows?run_id=run-1&wait_ms=100"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ run_id: "run-1", status: "completed" });
+ expect(mocks.flowStatus).toHaveBeenCalledWith(
+ "run-1",
+ expect.objectContaining({ principal: "cli:dev-owner" }),
+ 100,
+ );
+ });
+});
+
+describe("POST /api/v1/flows", () => {
+ it("refuses unauthenticated callers", async () => {
+ mocks.session.mockResolvedValue(null);
+ const res = await POST(makeReq("https://mso.example/api/v1/flows", "POST", { action: "run" }));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "owner_required" });
+ expect(mocks.createSession).not.toHaveBeenCalled();
+ });
+
+ it("executes automation run action", async () => {
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/flows", "POST", { action: "run", flow: "backup" }),
+ );
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true, run_id: "run-1" });
+ expect(mocks.createSession).toHaveBeenCalledWith("cli:dev-owner", "cli", {
+ title: "Automation: backup",
+ titleSource: "auto",
+ });
+ expect(mocks.executeCapability).toHaveBeenCalledWith(
+ expect.objectContaining({
+ actor: "cli:dev-owner",
+ args: { flow: "backup" },
+ }),
+ );
+ });
+
+ it("returns 400 when unknown action is requested", async () => {
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/flows", "POST", { action: "unknown_act" }),
+ );
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "unknown flow action" });
+ expect(mocks.executeCapability).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 when execution fails", async () => {
+ mocks.executeCapability.mockResolvedValue({ kind: "error", message: "flow step failed" });
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/flows", "POST", { action: "run" }),
+ );
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "flow step failed" });
+ });
+});
diff --git a/app/api/v1/fs/copy/route.test.ts b/app/api/v1/fs/copy/route.test.ts
new file mode 100644
index 00000000..624ecebe
--- /dev/null
+++ b/app/api/v1/fs/copy/route.test.ts
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HostError } from "@/lib/host/host-error";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ getSessionActor: vi.fn(async () => "test-actor"),
+ rateLimited: vi.fn(() => false),
+ copy: vi.fn(async () => undefined),
+ audit: vi.fn(),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.getSessionActor }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/host/fs-api", () => ({ copy: mocks.copy }));
+
+import { POST } from "./route";
+
+const post = (body: unknown) =>
+ POST(
+ new Request("https://mso.example/api/v1/fs/copy", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.getSessionActor.mockResolvedValue("test-actor");
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.copy.mockResolvedValue(undefined);
+});
+
+describe("POST /api/v1/fs/copy", () => {
+ it("returns 401 when unauthenticated and does not call copy", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await post({ from: "a.txt", to: "b.txt" });
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.copy).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 when rate limited and does not call copy", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await post({ from: "a.txt", to: "b.txt" });
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "Too many copy requests, slow down" });
+ expect(mocks.copy).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 when required fields are missing", async () => {
+ expect((await post({ to: "b.txt" })).status).toBe(400);
+ expect((await post({ from: "a.txt" })).status).toBe(400);
+ expect(mocks.copy).not.toHaveBeenCalled();
+ });
+
+ it("refuses path that escapes allowed roots with 400", async () => {
+ mocks.copy.mockRejectedValue(new HostError("Path outside writable roots"));
+ const res = await post({ from: "/etc/shadow", to: "/tmp/evil" });
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "Path outside writable roots" });
+ });
+
+ it("copies file successfully on happy path", async () => {
+ const res = await post({ from: "source.txt", to: "dest.txt" });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true });
+ expect(mocks.copy).toHaveBeenCalledWith("source.txt", "dest.txt");
+ });
+});
diff --git a/app/api/v1/fs/delete/route.test.ts b/app/api/v1/fs/delete/route.test.ts
new file mode 100644
index 00000000..b1a9515f
--- /dev/null
+++ b/app/api/v1/fs/delete/route.test.ts
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HostError } from "@/lib/host/host-error";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ getSessionActor: vi.fn(async () => "test-actor"),
+ rateLimited: vi.fn(() => false),
+ remove: vi.fn(async () => undefined),
+ audit: vi.fn(),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.getSessionActor }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/host/fs-api", () => ({ remove: mocks.remove }));
+
+import { DELETE } from "./route";
+
+const del = (body: unknown) =>
+ DELETE(
+ new Request("https://mso.example/api/v1/fs/delete", {
+ method: "DELETE",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.getSessionActor.mockResolvedValue("test-actor");
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.remove.mockResolvedValue(undefined);
+});
+
+describe("DELETE /api/v1/fs/delete", () => {
+ it("returns 401 when unauthenticated and does not call remove", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await del({ path: "target.txt" });
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.remove).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 when rate limited and does not call remove", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await del({ path: "target.txt" });
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "Too many delete requests, slow down" });
+ expect(mocks.remove).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 when path is missing or invalid", async () => {
+ expect((await del({})).status).toBe(400);
+ expect((await del({ path: "" })).status).toBe(400);
+ expect(mocks.remove).not.toHaveBeenCalled();
+ });
+
+ it("refuses path that escapes allowed roots with 400", async () => {
+ mocks.remove.mockRejectedValue(new HostError("Path outside writable roots"));
+ const res = await del({ path: "/etc/passwd" });
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "Path outside writable roots" });
+ });
+
+ it("removes file successfully on happy path", async () => {
+ const res = await del({ path: "clean-me.txt" });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true });
+ expect(mocks.remove).toHaveBeenCalledWith("clean-me.txt");
+ });
+});
diff --git a/app/api/v1/fs/list/route.test.ts b/app/api/v1/fs/list/route.test.ts
new file mode 100644
index 00000000..07e57282
--- /dev/null
+++ b/app/api/v1/fs/list/route.test.ts
@@ -0,0 +1,75 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HostError } from "@/lib/host/host-error";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ getSessionActor: vi.fn(async (): Promise<string | null> => "test-actor"),
+ rateLimited: vi.fn(() => false),
+ listDir: vi.fn(async () => []),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.getSessionActor }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/fs-api", () => ({ listDir: mocks.listDir }));
+
+import { GET } from "./route";
+
+const get = (url = "https://mso.example/api/v1/fs/list") => GET(new Request(url));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.getSessionActor.mockResolvedValue("test-actor");
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.listDir.mockResolvedValue([]);
+});
+
+describe("GET /api/v1/fs/list", () => {
+ it("returns 401 when unauthenticated and does not call listDir", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await get();
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.listDir).not.toHaveBeenCalled();
+ });
+
+ it("returns 401 when session actor is null and does not call listDir", async () => {
+ mocks.getSessionActor.mockResolvedValue(null);
+ const res = await get();
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.listDir).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 when rate limited and does not call listDir", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await get();
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "rate_limited" });
+ expect(mocks.listDir).not.toHaveBeenCalled();
+ });
+
+ it("refuses path that escapes allowed roots with 400", async () => {
+ mocks.listDir.mockRejectedValue(new HostError("Path outside readable roots"));
+ const res = await get("https://mso.example/api/v1/fs/list?path=/etc");
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "Path outside readable roots" });
+ });
+
+ it("lists directory successfully on happy path with default path ~", async () => {
+ const fixture = [{ name: "hello.txt", type: "file", size: 42 }];
+ mocks.listDir.mockResolvedValue(fixture as never);
+ const res = await get();
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual(fixture);
+ expect(mocks.listDir).toHaveBeenCalledWith("~", true, expect.anything());
+ });
+
+ it("passes custom path to listDir", async () => {
+ mocks.listDir.mockResolvedValue([] as never);
+ const res = await get("https://mso.example/api/v1/fs/list?path=subfolder");
+ expect(res.status).toBe(200);
+ expect(mocks.listDir).toHaveBeenCalledWith("subfolder", true, expect.anything());
+ });
+});
diff --git a/app/api/v1/fs/mkdir/route.test.ts b/app/api/v1/fs/mkdir/route.test.ts
new file mode 100644
index 00000000..304adf45
--- /dev/null
+++ b/app/api/v1/fs/mkdir/route.test.ts
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HostError } from "@/lib/host/host-error";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ getSessionActor: vi.fn(async () => "test-actor"),
+ rateLimited: vi.fn(() => false),
+ makeDir: vi.fn(async () => undefined),
+ audit: vi.fn(),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.getSessionActor }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/host/fs-api", () => ({ makeDir: mocks.makeDir }));
+
+import { POST } from "./route";
+
+const post = (body: unknown) =>
+ POST(
+ new Request("https://mso.example/api/v1/fs/mkdir", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.getSessionActor.mockResolvedValue("test-actor");
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.makeDir.mockResolvedValue(undefined);
+});
+
+describe("POST /api/v1/fs/mkdir", () => {
+ it("returns 401 when unauthenticated and does not call makeDir", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await post({ path: "new-folder" });
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.makeDir).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 when rate limited and does not call makeDir", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await post({ path: "new-folder" });
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "Too many mkdir requests, slow down" });
+ expect(mocks.makeDir).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 when path is missing or invalid", async () => {
+ expect((await post({})).status).toBe(400);
+ expect((await post({ path: "" })).status).toBe(400);
+ expect(mocks.makeDir).not.toHaveBeenCalled();
+ });
+
+ it("refuses path that escapes allowed roots with 400", async () => {
+ mocks.makeDir.mockRejectedValue(new HostError("Path outside writable roots"));
+ const res = await post({ path: "/etc/evil" });
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "Path outside writable roots" });
+ });
+
+ it("creates directory successfully on happy path", async () => {
+ const res = await post({ path: "valid-dir" });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ kind: "dir" });
+ expect(mocks.makeDir).toHaveBeenCalledWith("valid-dir");
+ });
+});
diff --git a/app/api/v1/fs/move/route.test.ts b/app/api/v1/fs/move/route.test.ts
new file mode 100644
index 00000000..847098b5
--- /dev/null
+++ b/app/api/v1/fs/move/route.test.ts
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HostError } from "@/lib/host/host-error";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ getSessionActor: vi.fn(async () => "test-actor"),
+ rateLimited: vi.fn(() => false),
+ move: vi.fn(async () => undefined),
+ audit: vi.fn(),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.getSessionActor }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/host/fs-api", () => ({ move: mocks.move }));
+
+import { POST } from "./route";
+
+const post = (body: unknown) =>
+ POST(
+ new Request("https://mso.example/api/v1/fs/move", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.getSessionActor.mockResolvedValue("test-actor");
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.move.mockResolvedValue(undefined);
+});
+
+describe("POST /api/v1/fs/move", () => {
+ it("returns 401 when unauthenticated and does not call move", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await post({ from: "a.txt", to: "b.txt" });
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.move).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 when rate limited and does not call move", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await post({ from: "a.txt", to: "b.txt" });
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "Too many move requests, slow down" });
+ expect(mocks.move).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 when required fields are missing", async () => {
+ expect((await post({ to: "b.txt" })).status).toBe(400);
+ expect((await post({ from: "a.txt" })).status).toBe(400);
+ expect(mocks.move).not.toHaveBeenCalled();
+ });
+
+ it("refuses path that escapes allowed roots with 400", async () => {
+ mocks.move.mockRejectedValue(new HostError("Path outside writable roots"));
+ const res = await post({ from: "/etc/shadow", to: "/tmp/evil" });
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "Path outside writable roots" });
+ });
+
+ it("moves file successfully on happy path", async () => {
+ const res = await post({ from: "old.txt", to: "new.txt" });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true });
+ expect(mocks.move).toHaveBeenCalledWith("old.txt", "new.txt");
+ });
+});
diff --git a/app/api/v1/fs/raw/route.test.ts b/app/api/v1/fs/raw/route.test.ts
index 85c836fc..d8d228d6 100644
--- a/app/api/v1/fs/raw/route.test.ts
+++ b/app/api/v1/fs/raw/route.test.ts
@@ -2,9 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mkdtemp, open, rm, writeFile, type FileHandle } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-let actor = "viewer";
+let actor = "viewer", authOk = true;
const handles: FileHandle[] = [], responses: Response[] = [];
-vi.mock("@/lib/agent/server", () => ({ verifyAuth: async () => true }));
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: async () => authOk }));
vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: async () => actor }));
vi.mock("@/lib/host/fs-api", async importOriginal => {
const original = await importOriginal() as typeof import("@/lib/host/fs-api");
@@ -15,7 +15,7 @@ vi.mock("@/lib/host/fs-api", async importOriginal => {
import { GET } from "./route";
let root: string, small: string, large: string;
beforeEach(async () => {
- actor = "viewer"; handles.length = 0; responses.length = 0;
+ actor = "viewer"; authOk = true; handles.length = 0; responses.length = 0;
root = await mkdtemp(path.join(os.tmpdir(), "mso-raw-bounds-"));
vi.stubEnv("OS_FS_READ_ROOTS", root);
small = path.join(root, "small.txt"); large = path.join(root, "large.mp4");
@@ -33,6 +33,24 @@ async function get(name = small, range?: string, signal?: AbortSignal) {
responses.push(response); return response;
}
describe("bounded Viewer raw file responses", () => {
+ it("returns 401 when unauthenticated and does not open descriptors", async () => {
+ authOk = false;
+ const response = await get();
+ expect(response.status).toBe(401);
+ expect(handles).toHaveLength(0);
+ });
+ it("refuses missing path parameter with 400", async () => {
+ const response = await GET(new Request("http://localhost/api/v1/fs/raw"));
+ expect(response.status).toBe(400);
+ expect(await response.json()).toEqual({ error: "path required" });
+ expect(handles).toHaveLength(0);
+ });
+ it("refuses paths escaping the allowed roots", async () => {
+ const response = await get("/etc/passwd");
+ expect(response.status).toBe(400);
+ expect(await response.json()).toEqual({ error: "Path outside readable roots" });
+ expect(handles).toHaveLength(0);
+ });
it("closes empty-file descriptors before returning an empty body", async () => {
await writeFile(small, "");
const response = await get();
diff --git a/app/api/v1/fs/read/handler.ts b/app/api/v1/fs/read/handler.ts
index d3c2416b..9ed3d2d1 100644
--- a/app/api/v1/fs/read/handler.ts
+++ b/app/api/v1/fs/read/handler.ts
@@ -1,12 +1,28 @@
import { NextResponse } from "next/server";
import { verifyAuth } from "@/lib/agent/server";
+import { getSessionActor } from "@/lib/auth/require-session";
import { apiError } from "@/lib/host/request-api";
+import { audit } from "@/lib/host/audit-api";
+import { rateLimited } from "@/lib/host/limits-api";
import { readFile } from "@/lib/host/fs-api";
+// Read is the cheapest way to pull bytes off the host, and it was the one fs route with no
+// ceiling: every sibling (write, delete, list, search) is rate-limited, while this one could be
+// driven in a loop for a 5 MiB file each time. The window matches the other read-shaped routes;
+// the cap is lower than write's 120 because a read returns content rather than an ack.
+const FS_READ_MAX = 60;
+const FS_READ_WINDOW_MS = 60_000;
+
export async function handleGetFsRead(req: Request): Promise<Response> {
if (!(await verifyAuth(req)))
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
+ const actor = await getSessionActor();
+ if (rateLimited(`fs.read:${actor ?? "anon"}`, FS_READ_MAX, FS_READ_WINDOW_MS)) {
+ audit({ action: "fs.read", actor, ok: false, detail: "rate-limited" });
+ return NextResponse.json({ error: "Too many read requests, slow down" }, { status: 429 });
+ }
+
const path = new URL(req.url).searchParams.get("path") ?? "~";
try {
return NextResponse.json(await readFile(path));
diff --git a/app/api/v1/fs/read/route.test.ts b/app/api/v1/fs/read/route.test.ts
new file mode 100644
index 00000000..d7800591
--- /dev/null
+++ b/app/api/v1/fs/read/route.test.ts
@@ -0,0 +1,74 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HostError } from "@/lib/host/host-error";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ actor: vi.fn(async () => "dev-1" as string | null),
+ rateLimited: vi.fn(() => false),
+ readFile: vi.fn(async () => "file-content"),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/host/fs-api", () => ({ readFile: mocks.readFile }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: vi.fn() }));
+
+import { GET } from "./route";
+
+const get = (url = "https://mso.example/api/v1/fs/read") => GET(new Request(url));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.actor.mockResolvedValue("dev-1");
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.readFile.mockResolvedValue("file-content");
+});
+
+describe("GET /api/v1/fs/read", () => {
+ it("returns 401 when unauthenticated and does not call readFile", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await get();
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.readFile).not.toHaveBeenCalled();
+ });
+
+ it("refuses path that escapes allowed roots with 400", async () => {
+ mocks.readFile.mockRejectedValue(new HostError("Path outside readable roots"));
+ const res = await get("https://mso.example/api/v1/fs/read?path=/etc/shadow");
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "Path outside readable roots" });
+ });
+
+ it("refuses files exceeding size limit with 400", async () => {
+ mocks.readFile.mockRejectedValue(new HostError("File too large to read (max 5 MiB)"));
+ const res = await get("https://mso.example/api/v1/fs/read?path=huge.bin");
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "File too large to read (max 5 MiB)" });
+ });
+
+ it("reads file successfully on happy path with default path ~", async () => {
+ mocks.readFile.mockResolvedValue("default content");
+ const res = await get();
+ expect(res.status).toBe(200);
+ expect(await res.json()).toBe("default content");
+ expect(mocks.readFile).toHaveBeenCalledWith("~");
+ });
+
+ it("returns 429 when rate limited and does not read", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await get();
+ expect(res.status).toBe(429);
+ expect(mocks.readFile).not.toHaveBeenCalled();
+ });
+
+ it("passes custom path to readFile", async () => {
+ mocks.readFile.mockResolvedValue("custom content");
+ const res = await get("https://mso.example/api/v1/fs/read?path=workspace/notes.txt");
+ expect(res.status).toBe(200);
+ expect(await res.json()).toBe("custom content");
+ expect(mocks.readFile).toHaveBeenCalledWith("workspace/notes.txt");
+ });
+});
diff --git a/app/api/v1/fs/search/route.test.ts b/app/api/v1/fs/search/route.test.ts
new file mode 100644
index 00000000..e5307500
--- /dev/null
+++ b/app/api/v1/fs/search/route.test.ts
@@ -0,0 +1,75 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HostError } from "@/lib/host/host-error";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ getSessionActor: vi.fn(async (): Promise<string | null> => "test-actor"),
+ rateLimited: vi.fn(() => false),
+ searchFs: vi.fn(async () => []),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.getSessionActor }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/fs-api", () => ({ searchFs: mocks.searchFs }));
+
+import { GET } from "./route";
+
+const get = (url = "https://mso.example/api/v1/fs/search") => GET(new Request(url));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.getSessionActor.mockResolvedValue("test-actor");
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.searchFs.mockResolvedValue([]);
+});
+
+describe("GET /api/v1/fs/search", () => {
+ it("returns 401 when unauthenticated and does not call searchFs", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await get();
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.searchFs).not.toHaveBeenCalled();
+ });
+
+ it("returns 401 when actor is null and does not call searchFs", async () => {
+ mocks.getSessionActor.mockResolvedValue(null);
+ const res = await get();
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.searchFs).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 when rate limited and does not call searchFs", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await get();
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "rate_limited" });
+ expect(mocks.searchFs).not.toHaveBeenCalled();
+ });
+
+ it("refuses path that escapes allowed roots with 400", async () => {
+ mocks.searchFs.mockRejectedValue(new HostError("Path outside readable roots"));
+ const res = await get("https://mso.example/api/v1/fs/search?q=test&root=/etc");
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "Path outside readable roots" });
+ });
+
+ it("searches filesystem successfully on happy path", async () => {
+ const fixture = [{ path: "test.txt", line: 1, text: "matched line" }];
+ mocks.searchFs.mockResolvedValue(fixture as never);
+ const res = await get("https://mso.example/api/v1/fs/search?q=matched&root=docs");
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual(fixture);
+ expect(mocks.searchFs).toHaveBeenCalledWith("matched", expect.objectContaining({ root: "docs" }));
+ });
+
+ it("defaults query to empty string and root to undefined", async () => {
+ mocks.searchFs.mockResolvedValue([] as never);
+ const res = await get();
+ expect(res.status).toBe(200);
+ expect(mocks.searchFs).toHaveBeenCalledWith("", expect.objectContaining({ root: undefined }));
+ });
+});
diff --git a/app/api/v1/fs/upload/route.test.ts b/app/api/v1/fs/upload/route.test.ts
new file mode 100644
index 00000000..bb6a05ea
--- /dev/null
+++ b/app/api/v1/fs/upload/route.test.ts
@@ -0,0 +1,139 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HostError } from "@/lib/host/host-error";
+
+const mocks = vi.hoisted(() => {
+ class UploadTooLargeError extends Error {}
+ return {
+ UploadTooLargeError,
+ verifyAuth: vi.fn(async () => true),
+ getSessionActor: vi.fn(async () => "test-actor"),
+ rateLimited: vi.fn(() => false),
+ resolveUploadDest: vi.fn(async () => "/safe/dest"),
+ streamFileInto: vi.fn(async () => "ok"),
+ parseMultipart: vi.fn(),
+ audit: vi.fn(),
+ };
+});
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.getSessionActor }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/host/fs-api", () => ({
+ boundaryFromContentType: (ct: string | null) => {
+ if (!ct || !ct.includes("boundary=")) throw new Error("bad boundary");
+ return "test-boundary";
+ },
+ parseMultipart: mocks.parseMultipart,
+ resolveUploadDest: mocks.resolveUploadDest,
+ streamFileInto: mocks.streamFileInto,
+ UploadTooLargeError: mocks.UploadTooLargeError,
+}));
+vi.mock("@/lib/managed-apps/origin", () => ({
+ managedAppIdForHost: () => null,
+ isUnclaimedAppNamespaceHost: () => false,
+}));
+
+import { POST } from "./route";
+
+const post = (opts: { body?: string; headers?: Record<string, string> } = {}) =>
+ POST(
+ new Request("https://mso.example/api/v1/fs/upload", {
+ method: "POST",
+ headers: {
+ host: "mso.example",
+ "content-type": "multipart/form-data; boundary=test-boundary",
+ "sec-fetch-site": "same-origin",
+ ...opts.headers,
+ },
+ body: opts.body ?? "content",
+ }),
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.getSessionActor.mockResolvedValue("test-actor");
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.resolveUploadDest.mockResolvedValue("/safe/dest");
+ mocks.streamFileInto.mockResolvedValue("ok");
+ mocks.parseMultipart.mockImplementation(async function* () {
+ yield {
+ name: "dest",
+ body: (async function* () {
+ yield new TextEncoder().encode("/safe/dest");
+ })(),
+ };
+ yield {
+ name: "file",
+ filename: "upload.txt",
+ body: (async function* () {
+ yield new Uint8Array([1, 2, 3]);
+ })(),
+ };
+ });
+});
+
+describe("POST /api/v1/fs/upload", () => {
+ it("returns 401 when unauthenticated and does not parse body or resolve dest", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await post();
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.parseMultipart).not.toHaveBeenCalled();
+ expect(mocks.resolveUploadDest).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 when rate limited and does not process upload", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await post();
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "Too many upload requests, slow down" });
+ expect(mocks.parseMultipart).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 when multipart header is missing or malformed", async () => {
+ const res = await post({ headers: { "content-type": "text/plain" } });
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "expected multipart/form-data" });
+ });
+
+ it("returns 400 when destination is missing in multipart body", async () => {
+ mocks.parseMultipart.mockImplementation(async function* () {
+ yield {
+ name: "file",
+ filename: "orphan.txt",
+ body: (async function* () {
+ yield new Uint8Array([1, 2]);
+ })(),
+ };
+ });
+ const res = await post();
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "Invalid request: dest" });
+ });
+
+ it("refuses destination that escapes allowed roots with 400", async () => {
+ mocks.resolveUploadDest.mockRejectedValue(new HostError("Path outside writable roots"));
+ const res = await post();
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "Path outside writable roots" });
+ });
+
+ it("returns 413 when upload exceeds total size limit", async () => {
+ mocks.parseMultipart.mockImplementation(async function* () {
+ throw new mocks.UploadTooLargeError("Upload exceeds 200 MiB limit");
+ });
+ const res = await post();
+ expect(res.status).toBe(413);
+ expect(await res.json()).toEqual({ error: "Upload exceeds 200 MiB limit" });
+ });
+
+ it("uploads file successfully on happy path", async () => {
+ const res = await post();
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ written: 1, failed: [] });
+ expect(mocks.resolveUploadDest).toHaveBeenCalledWith("/safe/dest");
+ expect(mocks.streamFileInto).toHaveBeenCalledWith("/safe/dest", "upload.txt", expect.anything());
+ });
+});
diff --git a/app/api/v1/fs/write/route.test.ts b/app/api/v1/fs/write/route.test.ts
new file mode 100644
index 00000000..810a510f
--- /dev/null
+++ b/app/api/v1/fs/write/route.test.ts
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HostError } from "@/lib/host/host-error";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ getSessionActor: vi.fn(async () => "test-actor"),
+ rateLimited: vi.fn(() => false),
+ writeFile: vi.fn(async () => undefined),
+ audit: vi.fn(),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.getSessionActor }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/host/fs-api", () => ({ writeFile: mocks.writeFile }));
+
+import { POST } from "./route";
+
+const post = (body: unknown) =>
+ POST(
+ new Request("https://mso.example/api/v1/fs/write", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.getSessionActor.mockResolvedValue("test-actor");
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.writeFile.mockResolvedValue(undefined);
+});
+
+describe("POST /api/v1/fs/write", () => {
+ it("returns 401 when unauthenticated and does not call writeFile", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await post({ path: "test.txt", content: "data" });
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.writeFile).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 when rate limited and does not call writeFile", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await post({ path: "test.txt", content: "data" });
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "Too many write requests, slow down" });
+ expect(mocks.writeFile).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 when path or content is missing", async () => {
+ expect((await post({ content: "data" })).status).toBe(400);
+ expect((await post({ path: "" })).status).toBe(400);
+ expect((await post({ path: "test.txt" })).status).toBe(400);
+ expect(mocks.writeFile).not.toHaveBeenCalled();
+ });
+
+ it("refuses path that escapes allowed roots with 400", async () => {
+ mocks.writeFile.mockRejectedValue(new HostError("Path outside writable roots"));
+ const res = await post({ path: "/etc/passwd", content: "evil" });
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "Path outside writable roots" });
+ });
+
+ it("writes file successfully on happy path with non-empty content", async () => {
+ const res = await post({ path: "hello.txt", content: "world" });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true });
+ expect(mocks.writeFile).toHaveBeenCalledWith("hello.txt", "world");
+ });
+
+ it("writes file successfully on happy path with empty content", async () => {
+ const res = await post({ path: "empty.txt", content: "" });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true });
+ expect(mocks.writeFile).toHaveBeenCalledWith("empty.txt", "");
+ });
+});
diff --git a/app/api/v1/infra/cloudflare/zones/route.test.ts b/app/api/v1/infra/cloudflare/zones/route.test.ts
new file mode 100644
index 00000000..454a622c
--- /dev/null
+++ b/app/api/v1/infra/cloudflare/zones/route.test.ts
@@ -0,0 +1,55 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ requireSession: vi.fn(async (_role?: string) => true),
+ listCloudflareZones: vi.fn(async () => [
+ { id: "zone-1", name: "example.com", status: "active" },
+ ]),
+ withIntegrationSelection: vi.fn(async (_sel: unknown, fn: () => Promise<unknown>) => fn()),
+}));
+
+vi.mock("@/lib/auth/require-session", () => ({ requireSession: mocks.requireSession }));
+vi.mock("@/lib/infra", () => ({
+ listCloudflareZones: mocks.listCloudflareZones,
+}));
+vi.mock("@/lib/infra/connection-service", () => ({
+ withIntegrationSelection: mocks.withIntegrationSelection,
+}));
+
+import { GET } from "./route";
+
+const req = (url = "https://mso.example.com/api/v1/infra/cloudflare/zones") => new Request(url);
+
+describe("GET /api/v1/infra/cloudflare/zones", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.requireSession.mockResolvedValue(true);
+ mocks.listCloudflareZones.mockResolvedValue([
+ { id: "zone-1", name: "example.com", status: "active" } as never,
+ ]);
+ });
+
+ it("returns 401 when unauthenticated", async () => {
+ mocks.requireSession.mockResolvedValue(false);
+ const res = await GET(req());
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "Unauthorized" });
+ expect(mocks.listCloudflareZones).not.toHaveBeenCalled();
+ });
+
+ it("returns 200 with zones list on happy path", async () => {
+ const res = await GET(req());
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ zones: [{ id: "zone-1", name: "example.com", status: "active" }],
+ });
+ expect(mocks.listCloudflareZones).toHaveBeenCalledOnce();
+ });
+
+ it("returns 503 when cloudflare integration fails", async () => {
+ mocks.listCloudflareZones.mockRejectedValueOnce(new Error("cloudflare API rate limit exceeded"));
+ const res = await GET(req());
+ expect(res.status).toBe(503);
+ expect(await res.json()).toEqual({ error: "cloudflare API rate limit exceeded" });
+ });
+});
diff --git a/app/api/v1/infra/dokploy/projects/route.test.ts b/app/api/v1/infra/dokploy/projects/route.test.ts
new file mode 100644
index 00000000..e65bdd3e
--- /dev/null
+++ b/app/api/v1/infra/dokploy/projects/route.test.ts
@@ -0,0 +1,55 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ requireSession: vi.fn(async (_role?: string) => true),
+ listDokployProjects: vi.fn(async () => [
+ { id: "proj-1", name: "Production", description: "Main stack" },
+ ]),
+ withIntegrationSelection: vi.fn(async (_sel: unknown, fn: () => Promise<unknown>) => fn()),
+}));
+
+vi.mock("@/lib/auth/require-session", () => ({ requireSession: mocks.requireSession }));
+vi.mock("@/lib/infra", () => ({
+ listDokployProjects: mocks.listDokployProjects,
+}));
+vi.mock("@/lib/infra/connection-service", () => ({
+ withIntegrationSelection: mocks.withIntegrationSelection,
+}));
+
+import { GET } from "./route";
+
+const req = (url = "https://mso.example.com/api/v1/infra/dokploy/projects") => new Request(url);
+
+describe("GET /api/v1/infra/dokploy/projects", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.requireSession.mockResolvedValue(true);
+ mocks.listDokployProjects.mockResolvedValue([
+ { id: "proj-1", name: "Production", description: "Main stack" } as never,
+ ]);
+ });
+
+ it("returns 401 when unauthenticated", async () => {
+ mocks.requireSession.mockResolvedValue(false);
+ const res = await GET(req());
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "Unauthorized" });
+ expect(mocks.listDokployProjects).not.toHaveBeenCalled();
+ });
+
+ it("returns 200 with projects list on happy path", async () => {
+ const res = await GET(req());
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ projects: [{ id: "proj-1", name: "Production", description: "Main stack" }],
+ });
+ expect(mocks.listDokployProjects).toHaveBeenCalledOnce();
+ });
+
+ it("returns 503 when dokploy integration fails", async () => {
+ mocks.listDokployProjects.mockRejectedValueOnce(new Error("dokploy API unreachable"));
+ const res = await GET(req());
+ expect(res.status).toBe(503);
+ expect(await res.json()).toEqual({ error: "dokploy API unreachable" });
+ });
+});
diff --git a/app/api/v1/infra/providers/doctor/route.test.ts b/app/api/v1/infra/providers/doctor/route.test.ts
new file mode 100644
index 00000000..91ea06ea
--- /dev/null
+++ b/app/api/v1/infra/providers/doctor/route.test.ts
@@ -0,0 +1,59 @@
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ requireSession: vi.fn(async (_role?: string) => true),
+ doctorInfraProvider: vi.fn(async (id: string) => ({ id, ok: true, message: "ready" })),
+ withIntegrationSelection: vi.fn(async (_sel: unknown, fn: () => Promise<unknown>) => fn()),
+}));
+
+vi.mock("@/lib/auth/require-session", () => ({ requireSession: mocks.requireSession }));
+vi.mock("@/lib/infra", () => ({
+ INFRA_PROVIDER_IDS: ["dokploy", "cloudflare", "hostinger"],
+ isInfraProviderId: (id: string) => ["dokploy", "cloudflare", "hostinger"].includes(id),
+ doctorInfraProvider: mocks.doctorInfraProvider,
+}));
+vi.mock("@/lib/infra/connection-service", () => ({
+ withIntegrationSelection: mocks.withIntegrationSelection,
+}));
+
+import { POST } from "./route";
+
+const postReq = (body?: unknown) =>
+ new NextRequest("https://mso.example.com/api/v1/infra/providers/doctor", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ });
+
+describe("POST /api/v1/infra/providers/doctor", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.requireSession.mockResolvedValue(true);
+ mocks.doctorInfraProvider.mockResolvedValue({ id: "dokploy", ok: true, message: "ready" });
+ });
+
+ it("returns 401 when unauthenticated", async () => {
+ mocks.requireSession.mockResolvedValue(false);
+ const res = await POST(postReq({ id: "dokploy" }));
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "Unauthorized" });
+ expect(mocks.doctorInfraProvider).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 for unknown provider id", async () => {
+ const res = await POST(postReq({ id: "unknown-provider" }));
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "unknown infrastructure provider" });
+ expect(mocks.doctorInfraProvider).not.toHaveBeenCalled();
+ });
+
+ it("runs doctor check and returns results on happy path", async () => {
+ const res = await POST(postReq({ id: "dokploy" }));
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.results).toHaveLength(1);
+ expect(body.results[0]).toEqual({ id: "dokploy", ok: true, message: "ready" });
+ expect(mocks.doctorInfraProvider).toHaveBeenCalledWith("dokploy");
+ });
+});
diff --git a/app/api/v1/infra/setup/route.test.ts b/app/api/v1/infra/setup/route.test.ts
new file mode 100644
index 00000000..bca5e9c6
--- /dev/null
+++ b/app/api/v1/infra/setup/route.test.ts
@@ -0,0 +1,91 @@
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ sessionContext: vi.fn(async (): Promise<{ role: string; session: { device_id: string } } | null> => ({
+ role: "owner",
+ session: { device_id: "dev-owner" },
+ })),
+ openIntegrationSetup: vi.fn(async (provider: string, deviceId: string) => ({
+ token: "grant-token-123",
+ provider,
+ deviceId,
+ })),
+ audit: vi.fn(async () => {}),
+}));
+
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: mocks.sessionContext,
+}));
+vi.mock("@/lib/infra/setup-capability", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/infra/setup-capability")>();
+ return {
+ ...actual,
+ openIntegrationSetup: mocks.openIntegrationSetup,
+ };
+});
+vi.mock("@/lib/host/audit-api", () => ({
+ audit: mocks.audit,
+}));
+
+import { POST } from "./route";
+
+const postReq = (body: unknown) =>
+ new NextRequest("https://mso.example.com/api/v1/infra/setup", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+describe("POST /api/v1/infra/setup", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.sessionContext.mockResolvedValue({
+ role: "owner",
+ session: { device_id: "dev-owner" },
+ } as never);
+ mocks.openIntegrationSetup.mockResolvedValue({
+ token: "grant-token-123",
+ provider: "dokploy",
+ deviceId: "dev-owner",
+ } as never);
+ });
+
+ it("returns 403 when session is non-owner", async () => {
+ mocks.sessionContext.mockResolvedValueOnce({
+ role: "operator",
+ session: { device_id: "dev-op" },
+ } as never);
+ const res = await POST(postReq({ provider: "dokploy" }));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "owner_required" });
+ expect(mocks.openIntegrationSetup).not.toHaveBeenCalled();
+ });
+
+ it("returns 403 when session is null (finding: collapses 401 into 403)", async () => {
+ mocks.sessionContext.mockResolvedValueOnce(null);
+ const res = await POST(postReq({ provider: "dokploy" }));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "owner_required" });
+ expect(mocks.openIntegrationSetup).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 for invalid body fields", async () => {
+ const res = await POST(postReq({ invalidKey: "value" }));
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "setup_unavailable" });
+ expect(mocks.openIntegrationSetup).not.toHaveBeenCalled();
+ });
+
+ it("opens integration setup and returns grant on happy path", async () => {
+ const res = await POST(postReq({ provider: "dokploy" }));
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.token).toBe("grant-token-123");
+ expect(body.setupUrl).toContain("/integrations");
+ expect(mocks.openIntegrationSetup).toHaveBeenCalledWith("dokploy", "dev-owner", undefined, expect.anything());
+ expect(mocks.audit).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "infra.write", actor: "dev-owner", target: "dokploy" }),
+ );
+ });
+});
diff --git a/app/api/v1/managed-apps/[id]/backups/route.test.ts b/app/api/v1/managed-apps/[id]/backups/route.test.ts
new file mode 100644
index 00000000..ea41af96
--- /dev/null
+++ b/app/api/v1/managed-apps/[id]/backups/route.test.ts
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ isManagedAppId: vi.fn((id: string) => id === "hermes" || id === "openclaw"),
+ listBackups: vi.fn(async (_id: string) => [
+ { id: "bak-20261031-120000", timestamp: 1730376000000, size: 1048576 },
+ ]),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/managed-apps/catalog", () => ({ isManagedAppId: mocks.isManagedAppId }));
+vi.mock("@/lib/managed-apps/backups", () => ({ listBackups: mocks.listBackups }));
+
+import { GET } from "./route";
+
+const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
+const req = (id: string) => new Request(`https://mso.example.com/api/v1/managed-apps/${id}/backups`);
+
+describe("GET /api/v1/managed-apps/[id]/backups", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ });
+
+ it("returns 401 when unauthenticated", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await GET(req("hermes"), ctx("hermes"));
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.listBackups).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 for unknown application id", async () => {
+ const res = await GET(req("unknown-app"), ctx("unknown-app"));
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "unknown managed application" });
+ expect(mocks.listBackups).not.toHaveBeenCalled();
+ });
+
+ it("returns backups list on happy path", async () => {
+ const res = await GET(req("hermes"), ctx("hermes"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ backups: [{ id: "bak-20261031-120000", timestamp: 1730376000000, size: 1048576 }],
+ });
+ expect(mocks.listBackups).toHaveBeenCalledWith("hermes");
+ });
+});
diff --git a/app/api/v1/managed-apps/[id]/install/route.test.ts b/app/api/v1/managed-apps/[id]/install/route.test.ts
new file mode 100644
index 00000000..3d423020
--- /dev/null
+++ b/app/api/v1/managed-apps/[id]/install/route.test.ts
@@ -0,0 +1,109 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ isDemo: { current: false },
+ rateLimited: vi.fn(() => false),
+ isManagedAppId: vi.fn((id: string) => id === "hermes" || id === "openclaw"),
+ startInstall: vi.fn(async (_id: string, _opts: unknown) => ({
+ id: "job-install-1234567890abcdef",
+ argv: ["install", "--provider", "openai"],
+ })),
+ rememberJobActor: vi.fn(),
+ audit: vi.fn(async () => {}),
+ actor: vi.fn(async () => "dev-owner"),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/demo", () => ({
+ get IS_DEMO() {
+ return mocks.isDemo.current;
+ },
+}));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));
+vi.mock("@/lib/managed-apps/catalog", () => ({
+ isManagedAppId: mocks.isManagedAppId,
+}));
+vi.mock("@/lib/managed-apps/install", () => ({
+ startInstall: mocks.startInstall,
+}));
+vi.mock("@/lib/managed-apps/job-audit", () => ({
+ rememberJobActor: mocks.rememberJobActor,
+}));
+
+import { POST } from "./route";
+
+const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
+const postReq = (id: string, body: unknown) =>
+ new Request(`https://mso.example.com/api/v1/managed-apps/${id}/install`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+describe("POST /api/v1/managed-apps/[id]/install", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.isDemo.current = false;
+ mocks.rateLimited.mockReturnValue(false);
+ });
+
+ it("returns 401 when unauthenticated", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await POST(postReq("hermes", { provider: "openai" }), ctx("hermes"));
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.startInstall).not.toHaveBeenCalled();
+ });
+
+ it("returns 403 in demo mode", async () => {
+ mocks.isDemo.current = true;
+ const res = await POST(postReq("hermes", { provider: "openai" }), ctx("hermes"));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "managed application actions are disabled in demo mode" });
+ expect(mocks.startInstall).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 for unknown application id", async () => {
+ const res = await POST(postReq("unknown-app", { provider: "openai" }), ctx("unknown-app"));
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "unknown managed application" });
+ expect(mocks.startInstall).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 when rate limited", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await POST(postReq("hermes", { provider: "openai" }), ctx("hermes"));
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "too many operations" });
+ expect(mocks.startInstall).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 for bad request fields", async () => {
+ const res = await POST(postReq("hermes", { apiKey: 12345 }), ctx("hermes"));
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "unsupported request field" });
+ });
+
+ it("starts install and returns 202 on happy path", async () => {
+ const res = await POST(postReq("hermes", { provider: "openai", apiKey: "sk-test" }), ctx("hermes"));
+ expect(res.status).toBe(202);
+ expect(await res.json()).toEqual({
+ job: { id: "job-install-1234567890abcdef", argv: ["install", "--provider", "openai"] },
+ });
+ expect(mocks.rememberJobActor).toHaveBeenCalledWith("job-install-1234567890abcdef", "dev-owner");
+ expect(mocks.audit).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "managed-app.action", target: "hermes", ok: true, detail: "install.start" }),
+ );
+ });
+
+ it("returns 409 when installation fails to start", async () => {
+ mocks.startInstall.mockRejectedValueOnce(new Error("lock contention"));
+ const res = await POST(postReq("hermes", { provider: "openai" }), ctx("hermes"));
+ expect(res.status).toBe(409);
+ expect(await res.json()).toEqual({ error: "lock contention" });
+ });
+});
diff --git a/app/api/v1/managed-apps/[id]/jobs/route.test.ts b/app/api/v1/managed-apps/[id]/jobs/route.test.ts
new file mode 100644
index 00000000..cc42f4d2
--- /dev/null
+++ b/app/api/v1/managed-apps/[id]/jobs/route.test.ts
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ isManagedAppId: vi.fn((id: string) => id === "hermes" || id === "openclaw"),
+ listManagedAppJobs: vi.fn(async (_id: string) => [
+ { id: "job-1", status: "running", applicationId: "hermes" },
+ ]),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/managed-apps/catalog", () => ({ isManagedAppId: mocks.isManagedAppId }));
+vi.mock("@/lib/managed-apps/jobs", () => ({ listManagedAppJobs: mocks.listManagedAppJobs }));
+
+import { GET } from "./route";
+
+const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
+const req = (id: string) => new Request(`https://mso.example.com/api/v1/managed-apps/${id}/jobs`);
+
+describe("GET /api/v1/managed-apps/[id]/jobs", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ });
+
+ it("returns 401 when unauthenticated", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await GET(req("hermes"), ctx("hermes"));
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.listManagedAppJobs).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 for unknown application id", async () => {
+ const res = await GET(req("unknown-app"), ctx("unknown-app"));
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "unknown managed application" });
+ expect(mocks.listManagedAppJobs).not.toHaveBeenCalled();
+ });
+
+ it("returns jobs list on happy path", async () => {
+ const res = await GET(req("hermes"), ctx("hermes"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ jobs: [{ id: "job-1", status: "running", applicationId: "hermes" }],
+ });
+ expect(mocks.listManagedAppJobs).toHaveBeenCalledWith("hermes");
+ });
+});
diff --git a/app/api/v1/managed-apps/[id]/logs/route.test.ts b/app/api/v1/managed-apps/[id]/logs/route.test.ts
new file mode 100644
index 00000000..d1048d56
--- /dev/null
+++ b/app/api/v1/managed-apps/[id]/logs/route.test.ts
@@ -0,0 +1,45 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ isManagedAppId: vi.fn((id: string) => id === "hermes" || id === "openclaw"),
+ getManagedAppLogs: vi.fn(async (_id: string) => ({ lines: ["started", "listening"] })),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/managed-apps/catalog", () => ({ isManagedAppId: mocks.isManagedAppId }));
+vi.mock("@/lib/managed-apps/manager", () => ({ getManagedAppLogs: mocks.getManagedAppLogs }));
+
+import { GET } from "./route";
+
+const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
+const req = (id: string) => new Request(`https://mso.example.com/api/v1/managed-apps/${id}/logs`);
+
+describe("GET /api/v1/managed-apps/[id]/logs", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ });
+
+ it("returns 401 when unauthenticated", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await GET(req("hermes"), ctx("hermes"));
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.getManagedAppLogs).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 for unknown application id", async () => {
+ const res = await GET(req("unknown-app"), ctx("unknown-app"));
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "unknown managed application" });
+ expect(mocks.getManagedAppLogs).not.toHaveBeenCalled();
+ });
+
+ it("returns app logs on happy path", async () => {
+ const res = await GET(req("hermes"), ctx("hermes"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ lines: ["started", "listening"] });
+ expect(mocks.getManagedAppLogs).toHaveBeenCalledWith("hermes");
+ });
+});
diff --git a/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.test.ts b/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.test.ts
new file mode 100644
index 00000000..e2c8e219
--- /dev/null
+++ b/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.test.ts
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ session: vi.fn(async (): Promise<{ device_id: string } | null> => ({ device_id: "test" })),
+ gateManagedApp: vi.fn(async () => null),
+ fetch: vi.fn(async () => new Response("upstream-ok", { status: 200 })),
+}));
+
+vi.mock("server-only", () => ({}));
+vi.stubGlobal("fetch", mocks.fetch);
+
+vi.mock("@/lib/managed-apps/origin", () => ({
+ MANAGED_APP_HOST_HEADER: "x-os-managed-app-host",
+ splitOriginEnabled: () => true,
+ managedAppOrigin: (id: string) => `https://${id}.mso.example.com`,
+ cockpitOrigin: () => "https://mso.example.com",
+ managedAppHost: (id: string) => `${id}.mso.example.com`,
+}));
+
+vi.mock("@/lib/managed-apps/session", () => ({
+ managedAppSession: mocks.session,
+ gateManagedApp: mocks.gateManagedApp,
+}));
+
+vi.mock("@/lib/managed-apps/catalog", () => ({
+ isManagedAppId: (id: string) => id === "hermes" || id === "openclaw",
+ getManagedAppDefinition: (id: string) => ({
+ id,
+ name: id,
+ dashboardUrl: "http://127.0.0.1:9119",
+ }),
+}));
+
+import { GET } from "./route";
+
+const APP_HOSTS = "{id}.mso.example.com";
+const ctx = (id: string, path: string[] = ["test"]) => ({
+ params: Promise.resolve({ id, path }),
+});
+
+function makeReq(id: string, path = "test", hostHeader: string | null = id) {
+ const headers = new Headers();
+ if (hostHeader) headers.set("x-os-managed-app-host", hostHeader);
+ return new Request(`https://${id}.mso.example.com/api/v1/managed-apps/${id}/proxy/${path}`, {
+ headers,
+ });
+}
+
+describe("GET /api/v1/managed-apps/[id]/proxy/[[...path]]", () => {
+ beforeEach(() => {
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", APP_HOSTS);
+ vi.clearAllMocks();
+ mocks.session.mockResolvedValue({ device_id: "test" } as never);
+ mocks.gateManagedApp.mockResolvedValue(null);
+ mocks.fetch.mockResolvedValue(new Response("upstream-ok", { status: 200 }));
+ });
+
+ it("returns 404 for unknown managed application", async () => {
+ const res = await GET(makeReq("unknown-app"), ctx("unknown-app"));
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "unknown managed application" });
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ });
+
+ it("returns 401 when the managed app gate/session returns null", async () => {
+ mocks.session.mockResolvedValueOnce(null);
+ const res = await GET(makeReq("hermes"), ctx("hermes"));
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ });
+
+ it("proxies to upstream and returns response when gate/session succeeds", async () => {
+ mocks.session.mockResolvedValueOnce({ device_id: "valid-session" } as never);
+ const res = await GET(makeReq("hermes", "chat"), ctx("hermes", ["chat"]));
+ expect(res.status).toBe(200);
+ expect(await res.text()).toBe("upstream-ok");
+ expect(mocks.fetch).toHaveBeenCalledOnce();
+ });
+
+ it("rejects path traversal segments with 400", async () => {
+ const res = await GET(makeReq("hermes", ".."), ctx("hermes", [".."]));
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "invalid upstream path" });
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/app/api/v1/managed-apps/[id]/route.test.ts b/app/api/v1/managed-apps/[id]/route.test.ts
new file mode 100644
index 00000000..5768d35a
--- /dev/null
+++ b/app/api/v1/managed-apps/[id]/route.test.ts
@@ -0,0 +1,130 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ isDemo: { current: false },
+ rateLimited: vi.fn(() => false),
+ isManagedAppId: vi.fn((id: string) => id === "hermes" || id === "openclaw"),
+ getManagedApp: vi.fn(async (id: string) => ({ id, name: id, state: "running" })),
+ performManagedAppAction: vi.fn(async (id: string, action: string) => ({ id, action, state: "running" })),
+ audit: vi.fn(async () => {}),
+ actor: vi.fn(async () => "dev-owner"),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/demo", () => ({
+ get IS_DEMO() {
+ return mocks.isDemo.current;
+ },
+}));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));
+vi.mock("@/lib/managed-apps/catalog", () => ({
+ isManagedAppId: mocks.isManagedAppId,
+}));
+vi.mock("@/lib/managed-apps/manager", () => ({
+ getManagedApp: mocks.getManagedApp,
+ performManagedAppAction: mocks.performManagedAppAction,
+}));
+
+import { GET, POST } from "./route";
+
+const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
+const getReq = (id: string) => new Request(`https://mso.example.com/api/v1/managed-apps/${id}`);
+const postReq = (id: string, body: unknown) =>
+ new Request(`https://mso.example.com/api/v1/managed-apps/${id}`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+describe("/api/v1/managed-apps/[id]", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.isDemo.current = false;
+ mocks.rateLimited.mockReturnValue(false);
+ });
+
+ describe("GET", () => {
+ it("returns 401 when unauthenticated", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await GET(getReq("hermes"), ctx("hermes"));
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.getManagedApp).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 for unknown application id", async () => {
+ const res = await GET(getReq("unknown-app"), ctx("unknown-app"));
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "unknown managed application" });
+ expect(mocks.getManagedApp).not.toHaveBeenCalled();
+ });
+
+ it("returns app status on happy path", async () => {
+ const res = await GET(getReq("hermes"), ctx("hermes"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ app: { id: "hermes", name: "hermes", state: "running" } });
+ });
+ });
+
+ describe("POST", () => {
+ it("returns 401 when unauthenticated", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await POST(postReq("hermes", { action: "start" }), ctx("hermes"));
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.performManagedAppAction).not.toHaveBeenCalled();
+ });
+
+ it("returns 403 in demo mode", async () => {
+ mocks.isDemo.current = true;
+ const res = await POST(postReq("hermes", { action: "start" }), ctx("hermes"));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "managed application actions are disabled in demo mode" });
+ expect(mocks.performManagedAppAction).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 for unknown application id", async () => {
+ const res = await POST(postReq("unknown-app", { action: "start" }), ctx("unknown-app"));
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "unknown managed application" });
+ expect(mocks.performManagedAppAction).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 when rate limited", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await POST(postReq("hermes", { action: "start" }), ctx("hermes"));
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "too many operations" });
+ expect(mocks.performManagedAppAction).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 for invalid action", async () => {
+ const res = await POST(postReq("hermes", { action: "destroy-the-world" }), ctx("hermes"));
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "unsupported managed application action" });
+ });
+
+ it("performs action and records audit on happy path", async () => {
+ const res = await POST(postReq("hermes", { action: "restart" }), ctx("hermes"));
+ expect(res.status).toBe(200);
+ expect(mocks.performManagedAppAction).toHaveBeenCalledWith("hermes", "restart");
+ expect(mocks.audit).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "managed-app.action", target: "hermes", ok: true, detail: "restart" }),
+ );
+ });
+
+ it("returns 409 when operation fails", async () => {
+ mocks.performManagedAppAction.mockRejectedValueOnce(new Error("process crashed"));
+ const res = await POST(postReq("hermes", { action: "restart" }), ctx("hermes"));
+ expect(res.status).toBe(409);
+ expect(await res.json()).toEqual({ error: "managed application operation failed" });
+ expect(mocks.audit).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "managed-app.action", target: "hermes", ok: false, detail: "restart" }),
+ );
+ });
+ });
+});
diff --git a/app/api/v1/managed-apps/[id]/update/route.test.ts b/app/api/v1/managed-apps/[id]/update/route.test.ts
new file mode 100644
index 00000000..e74d6681
--- /dev/null
+++ b/app/api/v1/managed-apps/[id]/update/route.test.ts
@@ -0,0 +1,131 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ isDemo: { current: false },
+ rateLimited: vi.fn(() => false),
+ isManagedAppId: vi.fn((id: string) => id === "hermes" || id === "openclaw"),
+ cachedUpdateStatus: vi.fn((_id: string) => ({ currentVersion: "1.0.0", updateAvailable: true })),
+ checkUpdate: vi.fn(async (_id: string, _force: boolean) => ({ updateAvailable: true, latestVersion: "1.1.0" })),
+ startUpdate: vi.fn(async (_id: string, _opts: unknown) => ({ id: "job-update-1234567890abcdef", argv: ["update"] })),
+ rememberJobActor: vi.fn(),
+ audit: vi.fn(async () => {}),
+ actor: vi.fn(async () => "dev-owner"),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/demo", () => ({
+ get IS_DEMO() {
+ return mocks.isDemo.current;
+ },
+}));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));
+vi.mock("@/lib/managed-apps/catalog", () => ({
+ isManagedAppId: mocks.isManagedAppId,
+}));
+vi.mock("@/lib/managed-apps/job-audit", () => ({
+ rememberJobActor: mocks.rememberJobActor,
+}));
+vi.mock("@/lib/managed-apps/update", () => ({
+ cachedUpdateStatus: mocks.cachedUpdateStatus,
+ checkUpdate: mocks.checkUpdate,
+ startUpdate: mocks.startUpdate,
+ setChannel: vi.fn(),
+ startRollback: vi.fn(),
+ startUninstall: vi.fn(),
+}));
+
+import { GET, POST } from "./route";
+
+const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
+const getReq = (id: string) => new Request(`https://mso.example.com/api/v1/managed-apps/${id}/update`);
+const postReq = (id: string, body: unknown) =>
+ new Request(`https://mso.example.com/api/v1/managed-apps/${id}/update`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+describe("/api/v1/managed-apps/[id]/update", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.isDemo.current = false;
+ mocks.rateLimited.mockReturnValue(false);
+ });
+
+ describe("GET", () => {
+ it("returns 401 when unauthenticated", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await GET(getReq("hermes"), ctx("hermes"));
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.cachedUpdateStatus).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 for unknown application id", async () => {
+ const res = await GET(getReq("unknown-app"), ctx("unknown-app"));
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "unknown managed application" });
+ expect(mocks.cachedUpdateStatus).not.toHaveBeenCalled();
+ });
+
+ it("returns cached update status on happy path", async () => {
+ const res = await GET(getReq("hermes"), ctx("hermes"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ currentVersion: "1.0.0", updateAvailable: true });
+ });
+ });
+
+ describe("POST", () => {
+ it("returns 401 when unauthenticated", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await POST(postReq("hermes", { action: "check" }), ctx("hermes"));
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.checkUpdate).not.toHaveBeenCalled();
+ });
+
+ it("returns 403 in demo mode", async () => {
+ mocks.isDemo.current = true;
+ const res = await POST(postReq("hermes", { action: "apply" }), ctx("hermes"));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "managed application actions are disabled in demo mode" });
+ expect(mocks.startUpdate).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 for unknown application id", async () => {
+ const res = await POST(postReq("unknown-app", { action: "check" }), ctx("unknown-app"));
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "unknown managed application" });
+ });
+
+ it("returns 400 for unsupported action", async () => {
+ const res = await POST(postReq("hermes", { action: "invalid-action" }), ctx("hermes"));
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "unsupported managed application action" });
+ });
+
+ it("returns 429 when rate limited", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await POST(postReq("hermes", { action: "check" }), ctx("hermes"));
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({ error: "too many operations" });
+ });
+
+ it("returns 200 for action check on happy path", async () => {
+ const res = await POST(postReq("hermes", { action: "check" }), ctx("hermes"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ status: { updateAvailable: true, latestVersion: "1.1.0" } });
+ });
+
+ it("returns 202 with job for action apply on happy path", async () => {
+ const res = await POST(postReq("hermes", { action: "apply" }), ctx("hermes"));
+ expect(res.status).toBe(202);
+ expect(await res.json()).toEqual({ job: { id: "job-update-1234567890abcdef", argv: ["update"] } });
+ expect(mocks.rememberJobActor).toHaveBeenCalledWith("job-update-1234567890abcdef", "dev-owner");
+ });
+ });
+});
diff --git a/app/api/v1/managed-apps/route.test.ts b/app/api/v1/managed-apps/route.test.ts
new file mode 100644
index 00000000..c651e2c3
--- /dev/null
+++ b/app/api/v1/managed-apps/route.test.ts
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ listManagedApps: vi.fn(async () => [
+ { id: "hermes", name: "Hermes", state: "running", dashboardUrl: "http://127.0.0.1:9119" },
+ ]),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/managed-apps/manager", () => ({ listManagedApps: mocks.listManagedApps }));
+
+import { GET } from "./route";
+
+const req = () => new Request("https://mso.example.com/api/v1/managed-apps");
+
+describe("GET /api/v1/managed-apps", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.listManagedApps.mockResolvedValue([
+ { id: "hermes", name: "Hermes", state: "running", dashboardUrl: "http://127.0.0.1:9119" } as never,
+ ]);
+ });
+
+ it("returns 401 when unauthenticated", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await GET(req());
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.listManagedApps).not.toHaveBeenCalled();
+ });
+
+ it("returns managed apps list on happy path", async () => {
+ const res = await GET(req());
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.apps).toHaveLength(1);
+ expect(body.apps[0].id).toBe("hermes");
+ expect(mocks.listManagedApps).toHaveBeenCalledOnce();
+ });
+
+ it("returns 503 when manager fails", async () => {
+ mocks.listManagedApps.mockRejectedValueOnce(new Error("daemon unreachable"));
+ const res = await GET(req());
+ expect(res.status).toBe(503);
+ expect(await res.json()).toEqual({ error: "managed applications unavailable" });
+ });
+});
diff --git a/app/api/v1/memory-graph/route.test.ts b/app/api/v1/memory-graph/route.test.ts
new file mode 100644
index 00000000..60fcb2da
--- /dev/null
+++ b/app/api/v1/memory-graph/route.test.ts
@@ -0,0 +1,71 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ session: vi.fn(),
+ collect: vi.fn(async () => ({ nodes: [], edges: [] })),
+}));
+
+vi.mock("@/lib/agent/server", () => ({
+ verifyAuth: mocks.verifyAuth,
+}));
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: mocks.session,
+}));
+vi.mock("@/lib/memory-graph/collect", () => ({
+ collectMemoryGraph: mocks.collect,
+}));
+
+import { GET } from "./route";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-owner" }, role: "owner" });
+ mocks.collect.mockResolvedValue({ nodes: [], edges: [] });
+});
+
+describe("GET /api/v1/memory-graph", () => {
+ it("refuses unauthenticated requests when verifyAuth fails", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await GET(new Request("https://mso.example/api/v1/memory-graph"));
+ expect(res.status).toBe(401);
+ expect(mocks.collect).not.toHaveBeenCalled();
+ });
+
+ it("refuses unauthenticated requests when session is missing", async () => {
+ mocks.session.mockResolvedValue(null);
+ const res = await GET(new Request("https://mso.example/api/v1/memory-graph"));
+ expect(res.status).toBe(401);
+ expect(mocks.collect).not.toHaveBeenCalled();
+ });
+
+ it.each(["viewer", "operator"])("refuses %s role with owner_required", async (role) => {
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-sub" }, role });
+ const res = await GET(new Request("https://mso.example/api/v1/memory-graph"));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "owner_required" });
+ expect(mocks.collect).not.toHaveBeenCalled();
+ });
+
+ it("collects memory graph with query parameters for owner", async () => {
+ const res = await GET(
+ new Request("https://mso.example/api/v1/memory-graph?root=%2Ftmp%2Fmem&project=p1"),
+ );
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ nodes: [], edges: [] });
+ expect(mocks.collect).toHaveBeenCalledWith({
+ root: "/tmp/mem",
+ project: "p1",
+ principal: "cli:dev-owner",
+ ownerView: true,
+ });
+ });
+
+ it("returns 500 when collectMemoryGraph throws", async () => {
+ mocks.collect.mockRejectedValue(new Error("graph collection error"));
+ const res = await GET(new Request("https://mso.example/api/v1/memory-graph"));
+ expect(res.status).toBe(500);
+ expect(await res.json()).toEqual({ error: "graph collection error" });
+ });
+});
diff --git a/app/api/v1/organization/route.test.ts b/app/api/v1/organization/route.test.ts
new file mode 100644
index 00000000..63f28605
--- /dev/null
+++ b/app/api/v1/organization/route.test.ts
@@ -0,0 +1,147 @@
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ session: vi.fn(),
+ rateLimited: vi.fn(() => false),
+ audit: vi.fn(),
+ getChart: vi.fn(async () => ({ name: "Default Org", revision: "rev-1", units: [], seats: [] })),
+ upsertUnit: vi.fn(async () => ({ name: "Default Org", revision: "rev-2" })),
+ replaceOrg: vi.fn(async () => ({ name: "Replaced Org", revision: "rev-3" })),
+ orgRuntime: vi.fn(async () => []),
+ resolveSeat: vi.fn(async () => ({ id: "seat-lead", title: "Lead" })),
+}));
+
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: mocks.session,
+}));
+vi.mock("@/lib/host/limits-api", () => ({
+ rateLimited: mocks.rateLimited,
+}));
+vi.mock("@/lib/host/audit-api", () => ({
+ audit: mocks.audit,
+}));
+vi.mock("@/lib/agent/organization-store", () => ({
+ getOrganizationChart: mocks.getChart,
+ upsertOrganizationUnit: mocks.upsertUnit,
+ upsertOrganizationSeat: vi.fn(),
+ deleteOrganizationUnit: vi.fn(),
+ deleteOrganizationSeat: vi.fn(),
+ mutateOrganizationFlow: vi.fn(),
+ replaceOrganization: mocks.replaceOrg,
+}));
+vi.mock("@/lib/agent/organization-runtime", () => ({
+ organizationRuntime: mocks.orgRuntime,
+ resolveOrganizationSeat: mocks.resolveSeat,
+}));
+
+import { GET, POST } from "./route";
+
+function makeReq(url: string, method = "GET", body?: unknown): NextRequest {
+ return new NextRequest(url, {
+ method,
+ headers: body ? { "content-type": "application/json" } : undefined,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-viewer" }, role: "viewer" });
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.getChart.mockResolvedValue({ name: "Default Org", revision: "rev-1", units: [], seats: [] });
+ mocks.upsertUnit.mockResolvedValue({ name: "Default Org", revision: "rev-2" });
+ mocks.replaceOrg.mockResolvedValue({ name: "Replaced Org", revision: "rev-3" });
+ mocks.orgRuntime.mockResolvedValue([]);
+ mocks.resolveSeat.mockResolvedValue({ id: "seat-lead", title: "Lead" });
+});
+
+describe("GET /api/v1/organization", () => {
+ it("refuses unauthenticated requests", async () => {
+ mocks.session.mockResolvedValue(null);
+ const res = await GET(makeReq("https://mso.example/api/v1/organization"));
+ expect(res.status).toBe(401);
+ expect(mocks.getChart).not.toHaveBeenCalled();
+ });
+
+ it("returns full chart and runtime for viewers", async () => {
+ const res = await GET(makeReq("https://mso.example/api/v1/organization"));
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.chart.revision).toBe("rev-1");
+ expect(mocks.getChart).toHaveBeenCalled();
+ });
+
+ it("resolves specific seat when seat parameter is provided", async () => {
+ const res = await GET(makeReq("https://mso.example/api/v1/organization?seat=seat-lead"));
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.seat).toEqual({ id: "seat-lead", title: "Lead" });
+ expect(mocks.resolveSeat).toHaveBeenCalledWith("seat-lead");
+ });
+});
+
+describe("POST /api/v1/organization", () => {
+ it("refuses viewer role with operator_required", async () => {
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-viewer" }, role: "viewer" });
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/organization", "POST", { action: "unit_upsert" }),
+ );
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "operator_required" });
+ });
+
+ it("returns 429 when rate limited", async () => {
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-op" }, role: "operator" });
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/organization", "POST", {
+ action: "unit_upsert",
+ expected_revision: "rev-1",
+ unit: { id: "u1" },
+ }),
+ );
+ expect(res.status).toBe(429);
+ expect(mocks.upsertUnit).not.toHaveBeenCalled();
+ });
+
+ it("mutates organization and audits for operator", async () => {
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-op" }, role: "operator" });
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/organization", "POST", {
+ action: "unit_upsert",
+ expected_revision: "rev-1",
+ unit: { id: "u1", name: "Engineering" },
+ }),
+ );
+ expect(res.status).toBe(200);
+ expect(mocks.upsertUnit).toHaveBeenCalledWith("rev-1", { id: "u1", name: "Engineering" });
+ expect(mocks.audit).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "agent.organization", target: "unit_upsert" }),
+ );
+ });
+
+ it("requires owner role for replace action", async () => {
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-op" }, role: "operator" });
+ const res = await POST(
+ makeReq("https://mso.example/api/v1/organization", "POST", {
+ action: "replace",
+ expected_revision: "rev-1",
+ chart: {},
+ }),
+ );
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "owner_required" });
+
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-owner" }, role: "owner" });
+ const ownerRes = await POST(
+ makeReq("https://mso.example/api/v1/organization", "POST", {
+ action: "replace",
+ expected_revision: "rev-1",
+ chart: {},
+ }),
+ );
+ expect(ownerRes.status).toBe(200);
+ expect(mocks.replaceOrg).toHaveBeenCalled();
+ });
+});
diff --git a/app/api/v1/project-mcp/route.test.ts b/app/api/v1/project-mcp/route.test.ts
new file mode 100644
index 00000000..7cb517fc
--- /dev/null
+++ b/app/api/v1/project-mcp/route.test.ts
@@ -0,0 +1,84 @@
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ session: vi.fn(),
+ demo: false,
+ execute: vi.fn(),
+}));
+
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: mocks.session,
+}));
+
+vi.mock("@/lib/demo", () => ({
+ get IS_DEMO() {
+ return mocks.demo;
+ },
+}));
+
+vi.mock("@/lib/capabilities/execute", () => ({
+ executeCapabilityCall: mocks.execute,
+}));
+
+import { POST } from "./route";
+
+function makeReq(body: unknown): NextRequest {
+ return new NextRequest("https://mso.example/api/v1/project-mcp", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.demo = false;
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-owner" }, role: "owner" });
+ mocks.execute.mockResolvedValue({ kind: "success", result: { ok: true, servers: [] } });
+});
+
+describe("POST /api/v1/project-mcp", () => {
+ it("refuses unauthenticated callers", async () => {
+ mocks.session.mockResolvedValue(null);
+ const res = await POST(makeReq({ action: "tools" }));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "owner_required" });
+ expect(mocks.execute).not.toHaveBeenCalled();
+ });
+
+ it.each(["viewer", "operator"])("refuses %s role", async (role) => {
+ mocks.session.mockResolvedValue({ session: { device_id: "dev-sub" }, role });
+ const res = await POST(makeReq({ action: "tools" }));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "owner_required" });
+ expect(mocks.execute).not.toHaveBeenCalled();
+ });
+
+ it("refuses when IS_DEMO is true even for owner", async () => {
+ mocks.demo = true;
+ const res = await POST(makeReq({ action: "tools" }));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "owner_required" });
+ expect(mocks.execute).not.toHaveBeenCalled();
+ });
+
+ it("executes project tools action successfully", async () => {
+ const res = await POST(makeReq({ action: "tools", server: "sqlite" }));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true, servers: [] });
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({
+ actor: "device:dev-owner",
+ args: { server: "sqlite" },
+ }),
+ );
+ });
+
+ it("returns 400 when capability execution reports failure", async () => {
+ mocks.execute.mockResolvedValue({ kind: "error", message: "server not found" });
+ const res = await POST(makeReq({ action: "manage" }));
+ expect(res.status).toBe(400);
+ expect(await res.json()).toEqual({ error: "server not found" });
+ });
+});
diff --git a/app/api/v1/stock/search/route.test.ts b/app/api/v1/stock/search/route.test.ts
new file mode 100644
index 00000000..02c7f414
--- /dev/null
+++ b/app/api/v1/stock/search/route.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ searchOpenverse: vi.fn(async () => [{ id: "ov-1", title: "Openverse Image" }]),
+ searchUnsplash: vi.fn(async () => [{ id: "un-1", title: "Unsplash Image" }]),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/app/api/v1/stock/providers", () => ({
+ searchOpenverse: mocks.searchOpenverse,
+ searchUnsplash: mocks.searchUnsplash,
+}));
+
+import { GET } from "./route";
+
+const originalKey = process.env.OS_UNSPLASH_ACCESS_KEY;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ delete process.env.OS_UNSPLASH_ACCESS_KEY;
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.searchOpenverse.mockResolvedValue([{ id: "ov-1", title: "Openverse Image" }]);
+ mocks.searchUnsplash.mockResolvedValue([{ id: "un-1", title: "Unsplash Image" }]);
+});
+
+afterEach(() => {
+ if (originalKey === undefined) {
+ delete process.env.OS_UNSPLASH_ACCESS_KEY;
+ } else {
+ process.env.OS_UNSPLASH_ACCESS_KEY = originalKey;
+ }
+});
+
+describe("GET /api/v1/stock/search", () => {
+ it("refuses unauthenticated requests", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await GET(new Request("https://mso.example/api/v1/stock/search?q=cat"));
+ expect(res.status).toBe(401);
+ expect(mocks.searchOpenverse).not.toHaveBeenCalled();
+ expect(mocks.searchUnsplash).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 when query parameter q is missing or empty", async () => {
+ expect((await GET(new Request("https://mso.example/api/v1/stock/search"))).status).toBe(400);
+ expect((await GET(new Request("https://mso.example/api/v1/stock/search?q=%20"))).status).toBe(400);
+ expect(mocks.searchOpenverse).not.toHaveBeenCalled();
+ });
+
+ it("falls back to Openverse when no Unsplash key is configured", async () => {
+ const res = await GET(new Request("https://mso.example/api/v1/stock/search?q=forest&page=2"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ results: [{ id: "ov-1", title: "Openverse Image" }] });
+ expect(mocks.searchOpenverse).toHaveBeenCalledWith("forest", 2);
+ expect(mocks.searchUnsplash).not.toHaveBeenCalled();
+ });
+
+ it("routes search to Unsplash when OS_UNSPLASH_ACCESS_KEY is present", async () => {
+ process.env.OS_UNSPLASH_ACCESS_KEY = "test-key";
+ const res = await GET(new Request("https://mso.example/api/v1/stock/search?q=mountains"));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ results: [{ id: "un-1", title: "Unsplash Image" }] });
+ expect(mocks.searchUnsplash).toHaveBeenCalledWith("mountains", 1, "test-key");
+ expect(mocks.searchOpenverse).not.toHaveBeenCalled();
+ });
+
+ it("returns 502 when upstream provider search throws", async () => {
+ mocks.searchOpenverse.mockRejectedValue(new Error("upstream timeout"));
+ const res = await GET(new Request("https://mso.example/api/v1/stock/search?q=ocean"));
+ expect(res.status).toBe(502);
+ });
+});
diff --git a/app/api/v1/temp-share/[id]/route.test.ts b/app/api/v1/temp-share/[id]/route.test.ts
new file mode 100644
index 00000000..49c12d59
--- /dev/null
+++ b/app/api/v1/temp-share/[id]/route.test.ts
@@ -0,0 +1,90 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ inspectTempShare: vi.fn(),
+ consumeTempShare: vi.fn(),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/host/temp-share-api", () => ({
+ inspectTempShare: mocks.inspectTempShare,
+ consumeTempShare: mocks.consumeTempShare,
+}));
+
+import { GET, HEAD } from "./route";
+
+const context = (id = "share-123") => ({ params: Promise.resolve({ id }) });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.inspectTempShare.mockResolvedValue({
+ name: "report.pdf",
+ mimeType: "application/pdf",
+ bytes: 1024,
+ expiresAt: Date.now() + 60_000,
+ downloadsLeft: 3,
+ });
+ mocks.consumeTempShare.mockResolvedValue({
+ name: "report.pdf",
+ mimeType: "application/pdf",
+ bytes: 1024,
+ expiresAt: Date.now() + 60_000,
+ downloadsLeft: 2,
+ data: Buffer.from("pdf-data"),
+ });
+});
+
+describe("HEAD /api/v1/temp-share/[id]", () => {
+ it("refuses unauthenticated requests", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await HEAD(new Request("https://mso.example/api/v1/temp-share/share-123"), context());
+ expect(res.status).toBe(401);
+ expect(mocks.inspectTempShare).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 when share is not found or expired", async () => {
+ mocks.inspectTempShare.mockRejectedValue(new Error("not found"));
+ const res = await HEAD(new Request("https://mso.example/api/v1/temp-share/share-123"), context());
+ expect(res.status).toBe(404);
+ });
+
+ it("returns 200 metadata headers without body on valid share", async () => {
+ const res = await HEAD(new Request("https://mso.example/api/v1/temp-share/share-123"), context());
+ expect(res.status).toBe(200);
+ expect(res.body).toBeNull();
+ expect(res.headers.get("content-type")).toBe("application/pdf");
+ expect(res.headers.get("content-length")).toBe("1024");
+ expect(res.headers.get("content-disposition")).toContain("inline");
+ expect(res.headers.get("x-temp-downloads-left")).toBe("3");
+ expect(mocks.inspectTempShare).toHaveBeenCalledWith("share-123");
+ });
+});
+
+describe("GET /api/v1/temp-share/[id]", () => {
+ it("refuses unauthenticated requests", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await GET(new Request("https://mso.example/api/v1/temp-share/share-123"), context());
+ expect(res.status).toBe(401);
+ expect(mocks.consumeTempShare).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 when share cannot be consumed", async () => {
+ mocks.consumeTempShare.mockRejectedValue(new Error("expired"));
+ const res = await GET(new Request("https://mso.example/api/v1/temp-share/share-123"), context());
+ expect(res.status).toBe(404);
+ });
+
+ it("consumes share and returns binary stream with attachment header if download=1", async () => {
+ const res = await GET(
+ new Request("https://mso.example/api/v1/temp-share/share-123?download=1"),
+ context("share-123"),
+ );
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-disposition")).toContain("attachment");
+ const text = await res.text();
+ expect(text).toBe("pdf-data");
+ expect(mocks.consumeTempShare).toHaveBeenCalledWith("share-123");
+ });
+});
diff --git a/app/api/v1/term/close/route.test.ts b/app/api/v1/term/close/route.test.ts
new file mode 100644
index 00000000..402341f8
--- /dev/null
+++ b/app/api/v1/term/close/route.test.ts
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ actor: vi.fn(async () => "test-device" as string | null),
+ audit: vi.fn(),
+ closePty: vi.fn(() => true),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/host/terminal-api", () => ({
+ openPty: vi.fn(),
+ closePty: mocks.closePty,
+ writePty: vi.fn(),
+ resizePty: vi.fn(),
+}));
+
+import { POST } from "./route";
+
+function makeReq(body: unknown): Request {
+ return new Request("https://mso.example/api/v1/term/close", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.actor.mockResolvedValue("test-device");
+ mocks.closePty.mockReturnValue(true);
+});
+
+describe("POST /api/v1/term/close", () => {
+ it("refuses unauthenticated requests", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await POST(makeReq({ id: "term-12345678" }));
+ expect(res.status).toBe(401);
+ expect(mocks.closePty).not.toHaveBeenCalled();
+ });
+
+ it("refuses requests when session actor is missing", async () => {
+ mocks.actor.mockResolvedValue(null);
+ const res = await POST(makeReq({ id: "term-12345678" }));
+ expect(res.status).toBe(401);
+ expect(mocks.closePty).not.toHaveBeenCalled();
+ });
+
+ it("validates required id parameter", async () => {
+ expect((await POST(makeReq({}))).status).toBe(400);
+ expect((await POST(makeReq({ id: "" }))).status).toBe(400);
+ expect(mocks.closePty).not.toHaveBeenCalled();
+ });
+
+ it("kills pty and audits when pty was active", async () => {
+ mocks.closePty.mockReturnValue(true);
+ const res = await POST(makeReq({ id: "term-12345678" }));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true });
+ expect(mocks.closePty).toHaveBeenCalledWith("term-12345678", "test-device");
+ expect(mocks.audit).toHaveBeenCalledWith({
+ action: "term.close",
+ actor: "test-device",
+ target: "pty term-123",
+ ok: true,
+ });
+ });
+
+ it("does not audit if closePty returned false (already closed)", async () => {
+ mocks.closePty.mockReturnValue(false);
+ const res = await POST(makeReq({ id: "term-12345678" }));
+ expect(res.status).toBe(200);
+ expect(mocks.closePty).toHaveBeenCalledWith("term-12345678", "test-device");
+ expect(mocks.audit).not.toHaveBeenCalled();
+ });
+
+ it("returns error status when closePty throws", async () => {
+ mocks.closePty.mockImplementation(() => {
+ throw new Error("close failed");
+ });
+ const res = await POST(makeReq({ id: "term-12345678" }));
+ expect(res.status).toBe(500);
+ });
+});
diff --git a/app/api/v1/term/input/route.test.ts b/app/api/v1/term/input/route.test.ts
new file mode 100644
index 00000000..3073f9fc
--- /dev/null
+++ b/app/api/v1/term/input/route.test.ts
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ actor: vi.fn(async () => "test-device" as string | null),
+ writePty: vi.fn(),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));
+vi.mock("@/lib/host/terminal-api", () => ({
+ openPty: vi.fn(),
+ closePty: vi.fn(),
+ writePty: mocks.writePty,
+ resizePty: vi.fn(),
+}));
+
+import { POST } from "./route";
+
+function makeReq(body: unknown): Request {
+ return new Request("https://mso.example/api/v1/term/input", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.actor.mockResolvedValue("test-device");
+ mocks.writePty.mockReturnValue(undefined);
+});
+
+describe("POST /api/v1/term/input", () => {
+ it("refuses unauthenticated requests", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await POST(makeReq({ id: "term-1", data: "ls\n" }));
+ expect(res.status).toBe(401);
+ expect(mocks.writePty).not.toHaveBeenCalled();
+ });
+
+ it("refuses requests when session actor is missing", async () => {
+ mocks.actor.mockResolvedValue(null);
+ const res = await POST(makeReq({ id: "term-1", data: "ls\n" }));
+ expect(res.status).toBe(401);
+ expect(mocks.writePty).not.toHaveBeenCalled();
+ });
+
+ it("validates required id and data fields", async () => {
+ expect((await POST(makeReq({ data: "ls\n" }))).status).toBe(400);
+ expect((await POST(makeReq({ id: "" }))).status).toBe(400);
+ expect((await POST(makeReq({ id: "term-1" }))).status).toBe(400);
+ expect(mocks.writePty).not.toHaveBeenCalled();
+ });
+
+ it("passes keystrokes to writePty", async () => {
+ const res = await POST(makeReq({ id: "term-1", data: "echo hi\n" }));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true });
+ expect(mocks.writePty).toHaveBeenCalledWith("term-1", "test-device", "echo hi\n");
+ });
+
+ it("allows empty data string", async () => {
+ const res = await POST(makeReq({ id: "term-1", data: "" }));
+ expect(res.status).toBe(200);
+ expect(mocks.writePty).toHaveBeenCalledWith("term-1", "test-device", "");
+ });
+
+ it("returns error status when writePty throws", async () => {
+ mocks.writePty.mockImplementation(() => {
+ throw new Error("PTY not found");
+ });
+ const res = await POST(makeReq({ id: "term-1", data: "hi" }));
+ expect(res.status).toBe(500);
+ });
+});
diff --git a/app/api/v1/term/open/route.test.ts b/app/api/v1/term/open/route.test.ts
new file mode 100644
index 00000000..b6902a03
--- /dev/null
+++ b/app/api/v1/term/open/route.test.ts
@@ -0,0 +1,88 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ actor: vi.fn(async () => "test-device"),
+ rateLimited: vi.fn(() => false),
+ audit: vi.fn(),
+ openPty: vi.fn(async () => ({ id: "pty-12345678", cwd: "/tmp" })),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/host/terminal-api", () => ({
+ openPty: mocks.openPty,
+ closePty: vi.fn(),
+ writePty: vi.fn(),
+ resizePty: vi.fn(),
+}));
+
+import { POST } from "./route";
+
+function makeReq(body: unknown): Request {
+ return new Request("https://mso.example/api/v1/term/open", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.actor.mockResolvedValue("test-device");
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.openPty.mockResolvedValue({ id: "pty-12345678", cwd: "/tmp" });
+});
+
+describe("POST /api/v1/term/open", () => {
+ it("refuses unauthenticated requests", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await POST(makeReq({ cols: 80, rows: 24 }));
+ expect(res.status).toBe(401);
+ expect(mocks.openPty).not.toHaveBeenCalled();
+ });
+
+ it("returns 429 and audits when rate limited", async () => {
+ mocks.rateLimited.mockReturnValue(true);
+ const res = await POST(makeReq({ cols: 80, rows: 24 }));
+ expect(res.status).toBe(429);
+ expect(mocks.audit).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "term.open", ok: false, detail: "rate-limited" }),
+ );
+ expect(mocks.openPty).not.toHaveBeenCalled();
+ });
+
+ it("validates cols and rows boundaries", async () => {
+ expect((await POST(makeReq({ cols: 1, rows: 24 }))).status).toBe(400);
+ expect((await POST(makeReq({ cols: 80, rows: 501 }))).status).toBe(400);
+ expect((await POST(makeReq({ cols: "bad", rows: 24 }))).status).toBe(400);
+ expect(mocks.openPty).not.toHaveBeenCalled();
+ });
+
+ it("spawns pty and audits success on valid request", async () => {
+ const res = await POST(makeReq({ cols: 120, rows: 40, cwd: "/home/user" }));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ id: "pty-12345678" });
+ expect(mocks.openPty).toHaveBeenCalledWith({
+ cols: 120,
+ rows: 40,
+ cwd: "/home/user",
+ owner: "test-device",
+ });
+ expect(mocks.audit).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "term.open", ok: true, target: "/tmp" }),
+ );
+ });
+
+ it("audits failure and returns error when openPty throws", async () => {
+ mocks.openPty.mockRejectedValue(new Error("pty spawn failed"));
+ const res = await POST(makeReq({ cols: 80, rows: 24 }));
+ expect(res.status).toBe(500);
+ expect(mocks.audit).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "term.open", ok: false }),
+ );
+ });
+});
diff --git a/app/api/v1/term/resize/route.test.ts b/app/api/v1/term/resize/route.test.ts
new file mode 100644
index 00000000..31444681
--- /dev/null
+++ b/app/api/v1/term/resize/route.test.ts
@@ -0,0 +1,71 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ actor: vi.fn(async () => "test-device" as string | null),
+ resizePty: vi.fn(),
+}));
+
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.actor }));
+vi.mock("@/lib/host/terminal-api", () => ({
+ openPty: vi.fn(),
+ closePty: vi.fn(),
+ writePty: vi.fn(),
+ resizePty: mocks.resizePty,
+}));
+
+import { POST } from "./route";
+
+function makeReq(body: unknown): Request {
+ return new Request("https://mso.example/api/v1/term/resize", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.actor.mockResolvedValue("test-device");
+ mocks.resizePty.mockReturnValue(undefined);
+});
+
+describe("POST /api/v1/term/resize", () => {
+ it("refuses unauthenticated requests", async () => {
+ mocks.verifyAuth.mockResolvedValue(false);
+ const res = await POST(makeReq({ id: "term-1", cols: 100, rows: 30 }));
+ expect(res.status).toBe(401);
+ expect(mocks.resizePty).not.toHaveBeenCalled();
+ });
+
+ it("refuses requests when session actor is missing", async () => {
+ mocks.actor.mockResolvedValue(null);
+ const res = await POST(makeReq({ id: "term-1", cols: 100, rows: 30 }));
+ expect(res.status).toBe(401);
+ expect(mocks.resizePty).not.toHaveBeenCalled();
+ });
+
+ it("validates id, cols, and rows", async () => {
+ expect((await POST(makeReq({ cols: 100, rows: 30 }))).status).toBe(400);
+ expect((await POST(makeReq({ id: "term-1", cols: 1, rows: 30 }))).status).toBe(400);
+ expect((await POST(makeReq({ id: "term-1", cols: 100, rows: 600 }))).status).toBe(400);
+ expect(mocks.resizePty).not.toHaveBeenCalled();
+ });
+
+ it("calls resizePty with validated dimensions", async () => {
+ const res = await POST(makeReq({ id: "term-1", cols: 120, rows: 40 }));
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true });
+ expect(mocks.resizePty).toHaveBeenCalledWith("term-1", "test-device", 120, 40);
+ });
+
+ it("returns error status when resizePty throws", async () => {
+ mocks.resizePty.mockImplementation(() => {
+ throw new Error("PTY not found");
+ });
+ const res = await POST(makeReq({ id: "term-1", cols: 100, rows: 30 }));
+ expect(res.status).toBe(500);
+ });
+});
diff --git a/app/api/v1/term/stream/route.test.ts b/app/api/v1/term/stream/route.test.ts
index 63a669cc..22cbdb77 100644
--- a/app/api/v1/term/stream/route.test.ts
+++ b/app/api/v1/term/stream/route.test.ts
@@ -4,10 +4,28 @@ import os from "node:os";
import path from "node:path";
import type { SessionPayload } from "@/lib/auth/session";
-const mocks = vi.hoisted(() => ({ session: null as SessionPayload | null, data: null as ((chunk: string, offset: number) => void) | null, detach: vi.fn(), close: vi.fn() }));
-vi.mock("@/lib/agent/server", () => ({ verifyAuth: async () => true }));
-vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: async () => ({ session: mocks.session, role: "owner" }) }));
-vi.mock("@/lib/host/terminal-api", () => ({ hasPty: () => true, closePty: mocks.close, attachPty: (_id: string, _owner: string, _from: number, callbacks: { onData: typeof mocks.data }) => { mocks.data = callbacks.onData; return mocks.detach; } }));
+const mocks = vi.hoisted(() => ({
+ verifyAuth: vi.fn(async () => true),
+ session: null as SessionPayload | null,
+ data: null as ((chunk: string, offset: number) => void) | null,
+ detach: vi.fn(),
+ close: vi.fn(),
+ attach: vi.fn(),
+ hasPty: vi.fn((_id: string, _actor: string) => true),
+}));
+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: async () => (mocks.session ? { session: mocks.session, role: "owner" } : null),
+}));
+vi.mock("@/lib/host/terminal-api", () => ({
+ hasPty: (id: string, actor: string) => mocks.hasPty(id, actor),
+ closePty: mocks.close,
+ attachPty: (id: string, owner: string, from: number, callbacks: { onData: typeof mocks.data }) => {
+ mocks.attach(id, owner, from);
+ mocks.data = callbacks.onData;
+ return mocks.detach;
+ },
+}));
const root = await mkdtemp(path.join(os.tmpdir(), "mso-term-live-"));
process.env.OS_DEVICE_STORE = path.join(root, "devices.json");
@@ -15,9 +33,41 @@ const devices = await import("@/lib/auth/device-store");
const { GET } = await import("./route");
const id = "a".repeat(32);
await devices.approveDevice(id); await devices.approveDevice("b".repeat(32));
-afterEach(() => { mocks.close.mockClear(); mocks.detach.mockClear(); });
+afterEach(() => {
+ mocks.close.mockClear();
+ mocks.detach.mockClear();
+ mocks.attach.mockClear();
+ mocks.verifyAuth.mockResolvedValue(true);
+ mocks.hasPty.mockReturnValue(true);
+});
afterAll(async () => { delete process.env.OS_DEVICE_STORE; await rm(root, { recursive: true, force: true }); });
+it("refuses the stream without an authenticated session instead of opening and closing it", async () => {
+ const policy = await devices.currentSessionPolicy("host");
+ mocks.session = { device_id: id, issued_at: Date.now(), expires_at: Date.now() + 60_000, cookie_scope: policy.scope, cookie_epoch: policy.epoch };
+ mocks.verifyAuth.mockResolvedValueOnce(false);
+ const unauthedRes = await GET(new Request("https://host.test/api/v1/term/stream?id=pty"));
+ expect(unauthedRes.status).toBe(401);
+ expect(await unauthedRes.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.attach).not.toHaveBeenCalled();
+
+ mocks.session = null;
+ mocks.verifyAuth.mockResolvedValueOnce(true);
+ const noSessionRes = await GET(new Request("https://host.test/api/v1/term/stream?id=pty"));
+ expect(noSessionRes.status).toBe(401);
+ expect(await noSessionRes.json()).toEqual({ error: "unauthorized" });
+ expect(mocks.attach).not.toHaveBeenCalled();
+});
+
+it("refuses with 400 without opening the stream when pty does not exist", async () => {
+ const policy = await devices.currentSessionPolicy("host");
+ mocks.session = { device_id: id, issued_at: Date.now(), expires_at: Date.now() + 60_000, cookie_scope: policy.scope, cookie_epoch: policy.epoch };
+ mocks.hasPty.mockReturnValueOnce(false);
+ const res = await GET(new Request("https://host.test/api/v1/term/stream?id=unknown-pty"));
+ expect(res.status).toBe(400);
+ expect(mocks.attach).not.toHaveBeenCalled();
+});
+
it("rechecks live Owner authority before data delivery and kills the PTY after demotion", async () => {
const policy = await devices.currentSessionPolicy("host");
mocks.session = { device_id: id, issued_at: Date.now(), expires_at: Date.now() + 60_000, cookie_scope: policy.scope, cookie_epoch: policy.epoch };
diff --git a/docs/BENCH-AFTER.md b/docs/BENCH-AFTER.md
index 8590550c..98f4d94f 100644
--- a/docs/BENCH-AFTER.md
+++ b/docs/BENCH-AFTER.md
@@ -124,8 +124,13 @@ that assumed `os.tmpdir()` was private).
3. **The gate is now trustworthy.** `gates-12.sh full` reports 17 passed / 0 failed / 0 skipped,
matching the CI step set, and the perf gate is wired into CI.
4. **The migration is not worth doing slice-by-slice.** Measured twice: an island costs 15.75 KiB
- gzip against a 1.64 KiB React chunk, and one Svelte component costs 2.8× the whole React slice
- it would replace.
+ gzip against a 1.64 KiB React chunk, and a hybrid shell adds a ~17.7 KiB runtime beside React
+ rather than replacing it. The earlier claim that "one Svelte component costs 2.8× the whole
+ React slice it replaces" was retracted in `docs/MSO-MIGRATION.md` §4.0 (which is authoritative):
+ that comparison was flawed because it measured a Svelte build including runtime against a React
+ chunk excluding runtime. Marginal Svelte component cost is negligible (~0.03 KiB per component,
+ 17.74 → 17.99 KiB across 10 components), but adding a second runtime beside React yields a net
+ +11.7 KiB regression even after the slice's own 6.27 KiB leaves.
So the accurate summary is that this work bought **portability and the ability to decide**, not
speed. Whether to spend the remaining 8–12 months on Phase 5 is a product decision that these
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 73fa3137..28b69587 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,13 +8,17 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
-- `tui` a tab row and a footer that stay put, painted through the frame writer
+- `tui` a tab row and a footer that stay put, painted through the frame writer (#191)
- `tui` a transcript model, because scrollback is the only transcript that exists (#187)
**Changed**
- `tui` paint the composer through a frame writer instead of appending (#189)
+**Tests**
+
+- `api` cover 30 more routes, and close the one fs route with no rate limit
+
## 2026-10-30
**Added**
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 8c8afe06..5a72f6ed 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,64 @@
+## 2026-10-30: Svelte marginal-cost retraction, status-code contract, and the CI-parity gate
+
+Four findings where empirical measurement corrected assumptions and hardened safety boundaries.
+
+**The "2.8×" retraction and marginal component costs.** Phase 4 was originally cancelled on the
+claim that "one Svelte component costs 2.8× the whole React slice it replaces" (17.75 KiB vs.
+6.27 KiB). That comparison was flawed: it compared a Svelte build including the Svelte runtime
+against a React slice chunk that excluded the React runtime (which the shell had already paid for).
+Compiling the same component 1, 2, 3, 5, 9, and 10 times into a single bundle revealed the actual
+marginal cost: 17.74 / 17.75 / 17.80 / 17.86 / 17.96 / 17.99 KiB gzip. The Svelte runtime is
+~17.7 KiB paid once, and each additional component costs ~0.03 KiB (all nine system-monitor
+components together are ~17.96 KiB). Phase 4 remains cancelled, but for the correct architectural
+reason: in a hybrid shell, Svelte adds a second ~17.7 KiB runtime *beside* React without removing
+React's 132.7 KiB floor, producing a net +11.7 KiB regression even after the slice's own 6.27 KiB
+is removed. Phase 5 is completely unaffected: React is replaced rather than joined, swapping
+132.7 KiB out for 33.07 KiB in (−99.6 KiB net measured reduction).
+
+**The status-code contract and the cannot-fail harness bug.** Mechanical extraction of 107 route
+handlers left a critical gap: an audit confirmed current parity, but nothing prevented future
+refactors from accidentally dropping auth checks. `app/api/status-contract.test.ts` locked down a
+15-assertion contract across the 20 most dangerous routes where a dropped gate is an RCE (`exec/run`),
+arbitrary file write/delete (`fs/write`, `fs/delete`), secret leak (`agent-vault`, `fs/raw`), or role
+escalation (`mcp/tokens`, `auth/devices`). Writing it surfaced a dangerous harness bug: the mock
+`getSessionActor` always resolved to `"dev-1"` regardless of the auth flag. Deleting `verifyAuth`
+from `exec/run` still left the route treated as authenticated through the session actor, keeping the
+suite 14/14 green. Because a test that cannot fail is worse than no test (it is falsely cited as
+coverage), `getSessionActor` was rewired to follow the auth flag. Running mutation testing confirmed
+the fix: removing `verifyAuth` from `exec/run` produced 1 failed | 13 passed, and restoring it
+yielded 15 passed. (The suite also documents that `fs/raw` has two independent gates—`verifyAuth`
+and `getSessionActor`—so defence in depth holds even if either is dropped alone).
+
+**Comment restoration on mechanical routes.** The refactor that moved 107 route handler bodies
+passed all behavior audits, but stripped critical context: 55 routes lost their design rationale.
+Restored 33 security-and-visibility comment blocks across 28 files explaining why routes are public
+(e.g., `/api/health` as an unauthenticated systemd WatchdogSec and Dokploy liveness probe), why
+they are owner-only, or why they reside under specific paths (e.g., `/api/mcp/tokens` kept under
+`/api` for cookie auth and proxy depth-2 CSRF gating, and `/api/changelog` session-gated so
+unauthenticated visitors cannot enumerate deployment specifics). A naive first attempt split
+multi-line comments line-by-line, creating fragmented syntax errors; this was redone cleanly
+block-by-block.
+
+**Three defects surfaced by the CI-parity gate.** Aligning local validation with CI via
+`gates-12.sh full` ran `vitest run --coverage` and provisioned the Forge container sandbox,
+immediately revealing three latent bugs:
+- `provision-forge-sandbox.sh` built an unstartable image (`exec: /usr/bin/node: permission denied`)
+ from three compounded issues: `install` preserved the host uid 1000 ownership (fixed by tarring
+ with `--owner=0 --group=0`), `umask 077` created `/usr` and `/usr/bin` as `drwx------` which failed
+ under container `--cap-drop ALL` lacking `CAP_DAC_OVERRIDE` (fixed by normalizing directory modes
+ to `0755`), and a blanket file `chmod 0644` cleared the executable bit on `ld-linux` and dynamic
+ libraries (fixed by restricting permissions normalization to directories only, preserving 0755
+ on binaries).
+- `lib/host/fs-zip.test.ts` assumed `os.tmpdir()` was private and counted `os-zip-*` directories
+ globally. Under vitest's multi-worker coverage pool, concurrent test workers created and cleaned
+ temp directories simultaneously, causing spurious failures. The test was rewritten to scope
+ assertions strictly to directories appearing during its own measured execution phase.
+- Consequently, `bun run coverage` went from 3 failed to 0 failed across 882 files / 5,772 tests.
+
+**Evidence.** `typecheck` 0, `lint` 0, `check-cycles` 2174 files / 0 cycles, `check-architecture`
+healthy at 43/43, `check-docs` current, `gates-12.sh full` 17 passed / 0 failed / 0 skipped, full
+vitest **887 files / 5,826 tests passed**.
+
## 2026-10-29: Phase 2 finished, `bun install` fixed, and Phase 6 measured out of existence
Three results, two of which were earned by measurement rather than assumed.
diff --git a/lib/contracts/audit.ts b/lib/contracts/audit.ts
index 26a7d1e8..d77406bc 100644
--- a/lib/contracts/audit.ts
+++ b/lib/contracts/audit.ts
@@ -7,6 +7,7 @@ export type AuditAction =
| "term.open"
| "term.write"
| "term.close"
+ | "fs.read"
| "fs.write"
| "fs.delete"
| "fs.move"
diff --git a/lib/mcp/fs-credential-boundary.test.ts b/lib/mcp/fs-credential-boundary.test.ts
index eb9db4dd..10ed5cd6 100644
--- a/lib/mcp/fs-credential-boundary.test.ts
+++ b/lib/mcp/fs-credential-boundary.test.ts
@@ -4,7 +4,13 @@ import os from "node:os";
import path from "node:path";
vi.mock("server-only", () => ({}));
vi.mock("@/lib/demo", () => ({ IS_DEMO: false }));
-vi.mock("@/lib/auth/require-session", () => ({ requireSession: async (role: string) => role === "viewer", getSessionContext: async () => ({ role: "viewer", session: { device_id: "candidate-viewer" } }) }));
+// fs/read now carries a rate limit like every other fs route. This suite is about the
+// credential boundary, not throttling, so the limiter is stubbed open and getSessionActor is
+// given an actor — otherwise ten back-to-back reads hit the real 60/min ceiling and the
+// refusals below would be indistinguishable from a 429.
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: () => false }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: () => {} }));
+vi.mock("@/lib/auth/require-session", () => ({ requireSession: async (role: string) => role === "viewer", getSessionContext: async () => ({ role: "viewer", session: { device_id: "candidate-viewer" } }), getSessionActor: async () => "candidate-viewer" }));
import { GET } from "@/app/api/v1/fs/read/route";
import { READ_TOOLS } from "./tools-read";
import { publicProjectMcpServers, readProjectMcpServers } from "@/lib/host/project-mcp-config";