Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
test(api): every route now has a test — 117 of 117
Abdurrahman Fakhrulf7191783360a
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 00000000..4ed9f231--- /dev/null+++ b/.gitattributes@@ -0,0 +1,15 @@+# docs/CHANGELOG.md is generated from git history by scripts/gen-changelog.mjs. It is+# rewritten wholesale on every regeneration, so two branches that both regenerate it always+# conflict textually even though neither is wrong — the resolver's only sensible action is to+# regenerate, which the `check-changelog` gate enforces anyway.+#+# `merge=ours` tells git to keep this side's copy during a merge instead of stopping on+# conflict. That removes the one recurring conflict from this repo's workflow; the changelog is+# then regenerated by the pre-push gate from the merged history, which is the only correct content+# either way. Enable per-clone with:+#+# git config merge.ours.driver true+#+# Without that config the attribute is inert (git falls back to a normal merge), so a clone that+# has not opted in still behaves safely — it just conflicts as before.+docs/CHANGELOG.md merge=oursdiff --git a/app/.well-known/agent-card.json/route.test.ts b/app/.well-known/agent-card.json/route.test.tsnew file mode 100644index 00000000..29829098--- /dev/null+++ b/app/.well-known/agent-card.json/route.test.ts@@ -0,0 +1,100 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { GET } from "./route";++afterEach(() => {+ vi.unstubAllEnvs();+});++beforeEach(() => {+ vi.stubEnv("NEXT_PUBLIC_OS_DEMO", "0");+ vi.stubEnv("OS_A2A_INBOUND_ENABLED", "1");+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.hub.acme.org");+});++describe("GET /.well-known/agent-card.json", () => {+ it("serves agent card without a session or auth headers (public-by-design)", async () => {+ // A2A discovery: peer agents probe the card without prior credentials+ const req = new Request("https://mso.hub.acme.org/.well-known/agent-card.json");+ const res = await GET(req);++ expect(res.status).toBe(200);+ expect(res.headers.get("content-type")).toBe("application/a2a+json; charset=utf-8");+ expect(res.headers.get("cache-control")).toBe("public, max-age=300");++ const body = await res.json();+ expect(body).toEqual({+ name: "MSO Agent",+ description: "Authenticated Manef Shell OS agent. Each bearer credential is capability-scoped by the owner.",+ version: "1.0.0",+ supportedInterfaces: [+ {+ url: "https://mso.hub.acme.org/a2a/v1",+ protocolBinding: "JSONRPC",+ protocolVersion: "1.0",+ },+ ],+ capabilities: {+ streaming: true,+ pushNotifications: false,+ extendedAgentCard: false,+ },+ securitySchemes: {+ msoBearer: {+ httpAuthSecurityScheme: {+ scheme: "Bearer",+ bearerFormat: "MSO-A2A",+ },+ },+ },+ securityRequirements: [+ {+ schemes: {+ msoBearer: { list: [] },+ },+ },+ ],+ defaultInputModes: ["text/plain"],+ defaultOutputModes: ["text/plain", "application/json"],+ skills: [+ {+ id: "mso-agent",+ name: "MSO Agent",+ description:+ "Inspect or operate this MSO host within the exact read/write/exec capability granted to the inbound credential.",+ tags: ["mso", "operations", "agent"],+ inputModes: ["text/plain"],+ outputModes: ["text/plain", "application/json"],+ },+ ],+ });+ });++ it("derives interface URL from configured origin, not a hardcoded host", async () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://peer.dynamic.org");+ const req = new Request("https://peer.dynamic.org/.well-known/agent-card.json");+ const res = await GET(req);++ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.supportedInterfaces[0].url).toBe("https://peer.dynamic.org/a2a/v1");+ });++ it("refuses external enumeration of internal session cards with 404", async () => {+ // Probing private session references over a non-loopback origin must be refused+ const req = new Request("https://mso.hub.acme.org/.well-known/agent-card.json?session=private-session");+ const res = await GET(req);++ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "not_found" });+ });++ it("returns 404 when inbound A2A is disabled", async () => {+ vi.stubEnv("OS_A2A_INBOUND_ENABLED", "0");+ vi.stubEnv("OS_A2A_ALLOW_LOOPBACK", "0");+ const req = new Request("https://mso.hub.acme.org/.well-known/agent-card.json");+ const res = await GET(req);++ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "not_found" });+ });+});diff --git a/app/.well-known/oauth-authorization-server/route.test.ts b/app/.well-known/oauth-authorization-server/route.test.tsnew file mode 100644index 00000000..50b796a4--- /dev/null+++ b/app/.well-known/oauth-authorization-server/route.test.ts@@ -0,0 +1,68 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { GET, OPTIONS } from "./route";++afterEach(() => {+ vi.unstubAllEnvs();+});++beforeEach(() => {+ vi.stubEnv("OS_MCP_ENABLED", "1");+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");+});++describe("GET /.well-known/oauth-authorization-server", () => {+ it("serves authorization server metadata without a session or auth headers (public-by-design)", async () => {+ // RFC 8414: MCP clients and OAuth tools inspect metadata prior to login+ const req = new Request("https://mso.example.test/.well-known/oauth-authorization-server");+ const res = await GET(req);++ expect(res.status).toBe(200);+ expect(res.headers.get("content-type")).toContain("application/json");+ expect(res.headers.get("cache-control")).toBe("no-store");+ expect(res.headers.get("access-control-allow-origin")).toBe("*");++ const body = await res.json();+ expect(body).toEqual({+ issuer: "https://mso.example.test",+ authorization_endpoint: "https://mso.example.test/oauth/authorize",+ token_endpoint: "https://mso.example.test/oauth/token",+ registration_endpoint: "https://mso.example.test/oauth/register",+ response_types_supported: ["code"],+ grant_types_supported: ["authorization_code", "refresh_token"],+ code_challenge_methods_supported: ["S256"],+ token_endpoint_auth_methods_supported: ["none"],+ scopes_supported: ["read", "write", "exec", "offline_access"],+ authorization_response_iss_parameter_supported: true,+ });+ });++ it("derives issuer and endpoints from configured origin, not a hardcoded host", async () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://auth.company.corp:9000");+ const req = new Request("https://auth.company.corp:9000/.well-known/oauth-authorization-server");+ const res = await GET(req);++ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.issuer).toBe("https://auth.company.corp:9000");+ expect(body.authorization_endpoint).toBe("https://auth.company.corp:9000/oauth/authorize");+ expect(body.token_endpoint).toBe("https://auth.company.corp:9000/oauth/token");+ expect(body.registration_endpoint).toBe("https://auth.company.corp:9000/oauth/register");+ });++ it("returns 404 when MCP is disabled via configuration", async () => {+ vi.stubEnv("OS_MCP_ENABLED", "0");+ const req = new Request("https://mso.example.test/.well-known/oauth-authorization-server");+ const res = await GET(req);++ expect(res.status).toBe(404);+ });+});++describe("OPTIONS /.well-known/oauth-authorization-server", () => {+ it("handles CORS preflight with 204 and wildcard origin", async () => {+ const res = await OPTIONS();+ expect(res.status).toBe(204);+ expect(res.headers.get("access-control-allow-origin")).toBe("*");+ expect(res.headers.get("access-control-allow-methods")).toContain("GET");+ });+});diff --git a/app/.well-known/oauth-protected-resource/route.test.ts b/app/.well-known/oauth-protected-resource/route.test.tsnew file mode 100644index 00000000..c6a5e461--- /dev/null+++ b/app/.well-known/oauth-protected-resource/route.test.ts@@ -0,0 +1,60 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { GET, OPTIONS } from "./route";++afterEach(() => {+ vi.unstubAllEnvs();+});++beforeEach(() => {+ vi.stubEnv("OS_MCP_ENABLED", "1");+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");+});++describe("GET /.well-known/oauth-protected-resource", () => {+ it("serves discovery document without a session or auth headers (public-by-design)", async () => {+ // RFC 9728: MCP clients probe discovery before authenticating; requiring a session breaks discovery+ const req = new Request("https://mso.example.test/.well-known/oauth-protected-resource");+ const res = await GET(req);++ expect(res.status).toBe(200);+ expect(res.headers.get("content-type")).toContain("application/json");+ expect(res.headers.get("cache-control")).toBe("no-store");+ expect(res.headers.get("access-control-allow-origin")).toBe("*");++ const body = await res.json();+ expect(body).toEqual({+ resource: "https://mso.example.test/mcp",+ authorization_servers: ["https://mso.example.test"],+ scopes_supported: ["read", "write", "exec", "offline_access"],+ bearer_methods_supported: ["header"],+ });+ });++ it("derives resource and authorization_servers from configured origin, not a hardcoded host", async () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://custom-gateway.internal:8443");+ const req = new Request("https://custom-gateway.internal:8443/.well-known/oauth-protected-resource");+ const res = await GET(req);++ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.resource).toBe("https://custom-gateway.internal:8443/mcp");+ expect(body.authorization_servers).toEqual(["https://custom-gateway.internal:8443"]);+ });++ it("returns 404 when MCP is disabled via configuration", async () => {+ vi.stubEnv("OS_MCP_ENABLED", "0");+ const req = new Request("https://mso.example.test/.well-known/oauth-protected-resource");+ const res = await GET(req);++ expect(res.status).toBe(404);+ });+});++describe("OPTIONS /.well-known/oauth-protected-resource", () => {+ it("handles CORS preflight with 204 and wildcard origin", async () => {+ const res = await OPTIONS();+ expect(res.status).toBe(204);+ expect(res.headers.get("access-control-allow-origin")).toBe("*");+ expect(res.headers.get("access-control-allow-methods")).toContain("GET");+ });+});diff --git a/app/a2a/v1/route.test.ts b/app/a2a/v1/route.test.tsnew file mode 100644index 00000000..2566353e--- /dev/null+++ b/app/a2a/v1/route.test.ts@@ -0,0 +1,144 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("server-only", () => ({}));++const mocks = vi.hoisted(() => ({+ authenticateA2AInboundToken: vi.fn(),+}));++vi.mock("@/lib/a2a/credentials", () => ({+ authenticateA2AInboundToken: mocks.authenticateA2AInboundToken,+}));++import { GET, POST } from "./route";++const ORIGIN = "https://mso.agent.test";++function makePost(body: string, headers: Record<string, string> = {}) {+ return new Request(`${ORIGIN}/a2a/v1`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ ...headers,+ },+ body,+ });+}++afterEach(() => {+ vi.unstubAllEnvs();+});++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv("NEXT_PUBLIC_OS_DEMO", "0");+ vi.stubEnv("OS_A2A_INBOUND_ENABLED", "1");+ vi.stubEnv("OS_PUBLIC_ORIGIN", ORIGIN);+ mocks.authenticateA2AInboundToken.mockResolvedValue(null);+});++describe("GET /a2a/v1", () => {+ it("refuses GET requests with 405 Method Not Allowed", async () => {+ const res = await GET();+ expect(res.status).toBe(405);+ expect(res.headers.get("allow")).toBe("POST");+ expect(await res.json()).toEqual({ error: "method_not_allowed" });+ });+});++describe("POST /a2a/v1 authentication and payload validation", () => {+ it("refuses unauthenticated requests without Authorization header with 401", async () => {+ const res = await POST(makePost(JSON.stringify({ jsonrpc: "2.0", method: "Ping" })));+ expect(res.status).toBe(401);+ expect(res.headers.get("www-authenticate")).toBe('Bearer realm="mso-a2a"');+ expect(await res.json()).toEqual({ error: "unauthorized" });+ });++ it("refuses invalid bearer tokens with 401", async () => {+ mocks.authenticateA2AInboundToken.mockResolvedValue(null);+ const res = await POST(+ makePost(JSON.stringify({ jsonrpc: "2.0", method: "Ping" }), {+ authorization: "Bearer invalid-token",+ }),+ );+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ });++ it("rejects malformed non-JSON payloads with JSON-RPC parse error (-32700)", async () => {+ mocks.authenticateA2AInboundToken.mockResolvedValue({+ id: "tok_test_1",+ label: "peer-token",+ scope: "read",+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ });++ const res = await POST(+ makePost("not a json payload {{{", {+ authorization: "Bearer valid-token",+ }),+ );++ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body).toEqual({+ jsonrpc: "2.0",+ id: null,+ error: {+ code: -32700,+ message: "Parse error",+ },+ });+ });++ it("rejects invalid JSON-RPC structure missing method or jsonrpc 2.0 with -32600", async () => {+ mocks.authenticateA2AInboundToken.mockResolvedValue({+ id: "tok_test_1",+ label: "peer-token",+ scope: "read",+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ });++ // Missing method+ const resMissingMethod = await POST(+ makePost(JSON.stringify({ jsonrpc: "2.0", id: "req-1" }), {+ authorization: "Bearer valid-token",+ }),+ );+ expect(resMissingMethod.status).toBe(200);+ expect(await resMissingMethod.json()).toEqual({+ jsonrpc: "2.0",+ id: "req-1",+ error: {+ code: -32600,+ message: "Invalid Request",+ },+ });++ // Wrong jsonrpc version+ const resWrongVersion = await POST(+ makePost(JSON.stringify({ jsonrpc: "1.0", method: "SendMessage", id: "req-2" }), {+ authorization: "Bearer valid-token",+ }),+ );+ expect(resWrongVersion.status).toBe(200);+ expect(await resWrongVersion.json()).toEqual({+ jsonrpc: "2.0",+ id: "req-2",+ error: {+ code: -32600,+ message: "Invalid Request",+ },+ });+ });++ it("returns 404 when A2A inbound is disabled via configuration", async () => {+ vi.stubEnv("OS_A2A_INBOUND_ENABLED", "0");+ vi.stubEnv("OS_A2A_ALLOW_LOOPBACK", "0");+ const res = await POST(makePost(JSON.stringify({ jsonrpc: "2.0", method: "Ping" })));+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "not_found" });+ });+});diff --git a/app/api/auth/logout/route.test.ts b/app/api/auth/logout/route.test.tsnew file mode 100644index 00000000..de391985--- /dev/null+++ b/app/api/auth/logout/route.test.ts@@ -0,0 +1,90 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ getSessionActor: vi.fn(async () => null as string | null),+ invalidateDeviceSessions: vi.fn(async () => {}),+ audit: vi.fn(),+}));++vi.mock("@/lib/auth/require-session", () => ({+ SESSION_COOKIE: "session",+ getSessionActor: mocks.getSessionActor,+}));+vi.mock("@/lib/auth/device-store", () => ({+ invalidateDeviceSessions: mocks.invalidateDeviceSessions,+}));+vi.mock("@/lib/host/audit-api", () => ({+ audit: mocks.audit,+}));++import { POST } from "./route";++const post = (host = "mso.example.com") =>+ POST(new Request("https://mso.example.com/api/auth/logout", {+ method: "POST",+ headers: { host },+ }));++beforeEach(() => {+ vi.clearAllMocks();+ delete process.env.OS_SESSION_COOKIE_DOMAIN;+ mocks.getSessionActor.mockResolvedValue(null);+ mocks.invalidateDeviceSessions.mockResolvedValue(undefined);+});++afterEach(() => {+ delete process.env.OS_SESSION_COOKIE_DOMAIN;+});++describe("POST /api/auth/logout — device session teardown and cookie clearing", () => {+ it("does not 500 when there was no session to begin with", async () => {+ mocks.getSessionActor.mockResolvedValue(null);+ const res = await post();++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ success: true });+ expect(mocks.invalidateDeviceSessions).not.toHaveBeenCalled();+ expect(mocks.audit).toHaveBeenCalledWith({ action: "auth.logout", actor: null, ok: true });++ const cookies = res.headers.getSetCookie();+ expect(cookies.length).toBeGreaterThanOrEqual(1);+ const cleared = cookies.find((c) => c.startsWith("session="));+ expect(cleared).toBeDefined();+ expect(cleared).toContain("Max-Age=0");+ });++ it("invalidates device sessions when an authenticated session exists", async () => {+ mocks.getSessionActor.mockResolvedValue("device-abc-123");+ const res = await post();++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ success: true });+ expect(mocks.invalidateDeviceSessions).toHaveBeenCalledWith("device-abc-123");+ expect(mocks.audit).toHaveBeenCalledWith({ action: "auth.logout", actor: "device-abc-123", ok: true });++ const cookies = res.headers.getSetCookie();+ const cleared = cookies.find((c) => c.startsWith("session="));+ expect(cleared).toBeDefined();+ expect(cleared).toContain("Max-Age=0");+ expect(cleared).toContain("HttpOnly");+ });++ it("clears both domain and pre-existing host-only cookies when domain cookie is active", async () => {+ process.env.OS_SESSION_COOKIE_DOMAIN = "mso.example.com";+ mocks.getSessionActor.mockResolvedValue("device-xyz");++ const res = await post("mso.example.com");+ expect(res.status).toBe(200);++ const cookies = res.headers.getSetCookie();+ expect(cookies).toHaveLength(2);++ const domainCookie = cookies.find((c) => c.includes("Domain=mso.example.com"));+ const hostOnlyCookie = cookies.find((c) => !c.toLowerCase().includes("domain="));++ expect(domainCookie).toBeDefined();+ expect(domainCookie).toContain("Max-Age=0");+ expect(hostOnlyCookie).toBeDefined();+ expect(hostOnlyCookie).toContain("Max-Age=0");+ });+});diff --git a/app/api/auth/me/route.test.ts b/app/api/auth/me/route.test.tsnew file mode 100644index 00000000..4055c0d0--- /dev/null+++ b/app/api/auth/me/route.test.ts@@ -0,0 +1,110 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { SessionContext } from "@/lib/auth/require-session";++const mocks = vi.hoisted(() => ({+ getSessionContext: vi.fn(async (): Promise<SessionContext | null> => null),+}));++vi.mock("@/lib/auth/require-session", () => ({+ getSessionContext: mocks.getSessionContext,+}));++import { GET } from "./route";++beforeEach(() => {+ vi.clearAllMocks();+ mocks.getSessionContext.mockResolvedValue(null);+});++describe("GET /api/auth/me — live shell authorization probe", () => {+ it("returns authenticated: false and null fields when no session exists", async () => {+ // Shell boots against this unauthenticated state; returning 401 or throwing breaks startup.+ const res = await GET();+ expect(res.status).toBe(200);+ expect(res.headers.get("cache-control")).toBe("no-store");+ expect(await res.json()).toEqual({+ authenticated: false,+ deviceId: null,+ deviceLabel: null,+ role: null,+ });+ });++ it("returns authenticated: true with owner role and device information", async () => {+ mocks.getSessionContext.mockResolvedValue({+ session: {+ device_id: "dev-owner-001",+ issued_at: 1000,+ expires_at: 2000,+ cookie_scope: "host",+ cookie_epoch: "epoch-0000000000000000",+ },+ device: {+ label: "Primary Laptop",+ approvedAt: 1000,+ role: "owner",+ },+ role: "owner",+ });++ const res = await GET();+ expect(res.status).toBe(200);+ expect(res.headers.get("cache-control")).toBe("no-store");+ expect(await res.json()).toEqual({+ authenticated: true,+ deviceId: "dev-owner-001",+ deviceLabel: "Primary Laptop",+ role: "owner",+ });+ });++ it("reflects operator role when session has operator permissions", async () => {+ mocks.getSessionContext.mockResolvedValue({+ session: {+ device_id: "dev-op-002",+ issued_at: 1000,+ expires_at: 2000,+ cookie_scope: "host",+ cookie_epoch: "epoch-0000000000000000",+ },+ device: {+ label: "Operator Terminal",+ approvedAt: 1000,+ role: "operator",+ },+ role: "operator",+ });++ const res = await GET();+ expect(res.status).toBe(200);+ expect(await res.json()).toMatchObject({+ authenticated: true,+ role: "operator",+ });+ });++ it("reflects viewer role when session has viewer permissions", async () => {+ mocks.getSessionContext.mockResolvedValue({+ session: {+ device_id: "dev-view-003",+ issued_at: 1000,+ expires_at: 2000,+ cookie_scope: "host",+ cookie_epoch: "epoch-0000000000000000",+ },+ device: {+ label: "Observer Screen",+ approvedAt: 1000,+ role: "viewer",+ },+ role: "viewer",+ });++ const res = await GET();+ expect(res.status).toBe(200);+ expect(await res.json()).toMatchObject({+ authenticated: true,+ role: "viewer",+ });+ });+});diff --git a/app/api/changelog/route.test.ts b/app/api/changelog/route.test.tsnew file mode 100644index 00000000..96ed12fb--- /dev/null+++ b/app/api/changelog/route.test.ts@@ -0,0 +1,62 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ requireSession: vi.fn(async () => true),+ readFile: vi.fn(async () => "# Changelog\n\n- Fix things"),+}));++vi.mock("@/lib/auth/require-session", () => ({+ requireSession: mocks.requireSession,+}));++vi.mock("node:fs", () => ({+ promises: {+ readFile: mocks.readFile,+ },+}));++import { GET } from "./route";++beforeEach(() => {+ vi.clearAllMocks();+ mocks.requireSession.mockResolvedValue(true);+ mocks.readFile.mockResolvedValue("# Changelog\n\n- Fix things");+});++describe("GET /api/changelog", () => {+ it("returns 401 when unauthenticated to prevent leaking deployment history", async () => {+ mocks.requireSession.mockResolvedValue(false);+ const res = await GET();+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "Unauthorized" });+ expect(mocks.readFile).not.toHaveBeenCalled();+ });++ it("returns empty markdown without 500 when changelog file is absent", async () => {+ // When changelog has never been generated, handler must return 200 with generated:false+ mocks.readFile.mockRejectedValue(new Error("ENOENT: no such file or directory"));+ const res = await GET();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ markdown: "", generated: false });+ });++ it("serves changelog content with generated:true when file exists", async () => {+ const res = await GET();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ markdown: "# Changelog\n\n- Fix things",+ generated: true,+ });+ });++ it("caps changelog body to 40,000 characters to prevent response bloat", async () => {+ const largeContent = "A".repeat(50_000);+ mocks.readFile.mockResolvedValue(largeContent);+ const res = await GET();+ expect(res.status).toBe(200);+ const data = await res.json();+ expect(data.generated).toBe(true);+ expect(data.markdown.length).toBe(40_000);+ expect(data.markdown).toBe("A".repeat(40_000));+ });+});diff --git a/app/api/integrations/google/callback/route.test.ts b/app/api/integrations/google/callback/route.test.tsnew file mode 100644index 00000000..c7918617--- /dev/null+++ b/app/api/integrations/google/callback/route.test.ts@@ -0,0 +1,135 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";++const mocks = vi.hoisted(() => ({+ completeGoogleAuthorization: vi.fn(),+ googleFlowCookie: vi.fn((state: string) => `__Host-mso-google-${state.slice(0, 16)}`),+}));++vi.mock("server-only", () => ({}));+vi.mock("@/lib/infra/google-oauth-flow", () => ({+ completeGoogleAuthorization: mocks.completeGoogleAuthorization,+ googleFlowCookie: mocks.googleFlowCookie,+}));++import { GET } from "./route";++const DEFAULT_ORIGIN = "https://mso.example.com";+const DEFAULT_HOST = "mso.example.com";+const VALID_STATE = "a".repeat(43);++function makeReq(+ search: string,+ options: { host?: string; cookies?: string } = {},+): NextRequest {+ const url = `${DEFAULT_ORIGIN}/api/integrations/google/callback${search}`;+ const headers: Record<string, string> = {+ host: options.host ?? DEFAULT_HOST,+ };+ if (options.cookies) {+ headers.cookie = options.cookies;+ }+ return new NextRequest(url, { headers });+}++beforeEach(() => {+ vi.clearAllMocks();+ process.env.OS_PUBLIC_ORIGIN = DEFAULT_ORIGIN;+ mocks.completeGoogleAuthorization.mockResolvedValue({+ user: "owner",+ provider: "google-search-console",+ connection: "primary",+ status: "authorized",+ verificationRequired: true,+ });+});++afterEach(() => {+ delete process.env.OS_PUBLIC_ORIGIN;+});++describe("GET /api/integrations/google/callback", () => {+ it("rejects request with 409 when public https origin is unconfigured", async () => {+ delete process.env.OS_PUBLIC_ORIGIN;+ const res = await GET(makeReq(`?state=${VALID_STATE}`));+ expect(res.status).toBe(409);+ expect(await res.json()).toEqual({ error: "google_public_https_origin_required" });+ expect(mocks.completeGoogleAuthorization).not.toHaveBeenCalled();+ });++ it("rejects mismatched host with 400 invalid_google_callback", async () => {+ // Validates host binding against configured origin to prevent DNS rebinding / host spoofing+ const res = await GET(makeReq(`?state=${VALID_STATE}`, { host: "evil.attacker.com" }));+ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "invalid_google_callback" });+ expect(mocks.completeGoogleAuthorization).not.toHaveBeenCalled();+ });++ it("redirects to retry when state parameter is malformed", async () => {+ // State must be exact 43-character base64url string+ for (const badState of ["short", "bad!char@" + "x".repeat(34), "x".repeat(44), ""]) {+ const res = await GET(makeReq(`?state=${encodeURIComponent(badState)}`));+ expect(res.status).toBe(303);+ const location = res.headers.get("location");+ expect(location).toBe(`${DEFAULT_ORIGIN}/integrations?google=retry`);+ }+ expect(mocks.completeGoogleAuthorization).not.toHaveBeenCalled();+ });++ it("redirects to retry when duplicate parameters or conflicting code/error are received", async () => {+ // Duplicate state parameter+ const dupState = await GET(makeReq(`?state=${VALID_STATE}&state=${VALID_STATE}`));+ expect(dupState.status).toBe(303);+ expect(dupState.headers.get("location")).toBe(`${DEFAULT_ORIGIN}/integrations?google=retry`);++ // Conflicting code and error+ const conflict = await GET(makeReq(`?state=${VALID_STATE}&code=somecode&error=access_denied`));+ expect(conflict.status).toBe(303);+ expect(conflict.headers.get("location")).toBe(`${DEFAULT_ORIGIN}/integrations?google=retry`);++ // Invalid issuer+ const badIss = await GET(makeReq(`?state=${VALID_STATE}&code=somecode&iss=https://evil.google.fake`));+ expect(badIss.status).toBe(303);+ expect(badIss.headers.get("location")).toBe(`${DEFAULT_ORIGIN}/integrations?google=retry`);+ expect(mocks.completeGoogleAuthorization).not.toHaveBeenCalled();+ });++ it("redirects to retry when binding cookie is missing or completeGoogleAuthorization fails", async () => {+ // No cookie provided+ const noCookie = await GET(makeReq(`?state=${VALID_STATE}&code=somecode`));+ expect(noCookie.status).toBe(303);+ expect(noCookie.headers.get("location")).toBe(`${DEFAULT_ORIGIN}/integrations?google=retry`);+ expect(mocks.completeGoogleAuthorization).not.toHaveBeenCalled();++ // Authorization flow completion throws+ const cookieName = mocks.googleFlowCookie(VALID_STATE);+ mocks.completeGoogleAuthorization.mockRejectedValue(new Error("expired"));+ const failedAuth = await GET(makeReq(`?state=${VALID_STATE}&code=somecode`, { cookies: `${cookieName}=binding123` }));+ expect(failedAuth.status).toBe(303);+ expect(failedAuth.headers.get("location")).toBe(`${DEFAULT_ORIGIN}/integrations?google=retry`);+ });++ it("authorizes successfully on valid callback and clears the flow binding cookie", async () => {+ const cookieName = mocks.googleFlowCookie(VALID_STATE);+ const req = makeReq(+ `?state=${VALID_STATE}&code=valid_auth_code&iss=https://accounts.google.com`,+ { cookies: `${cookieName}=binding_secret` },+ );++ const res = await GET(req);+ expect(res.status).toBe(303);+ expect(res.headers.get("location")).toBe(`${DEFAULT_ORIGIN}/integrations?google=authorized`);++ expect(mocks.completeGoogleAuthorization).toHaveBeenCalledWith(+ VALID_STATE,+ "binding_secret",+ "valid_auth_code",+ false,+ );++ // Flow binding cookie must be cleared on response+ const setCookie = res.headers.get("set-cookie");+ expect(setCookie).toContain(cookieName);+ expect(setCookie).toContain("Max-Age=0");+ });+});diff --git a/app/api/integrations/google/start/route.test.ts b/app/api/integrations/google/start/route.test.tsnew file mode 100644index 00000000..3a818919--- /dev/null+++ b/app/api/integrations/google/start/route.test.ts@@ -0,0 +1,142 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";++const mocks = vi.hoisted(() => ({+ getSessionContext: vi.fn(),+ beginGoogleAuthorization: vi.fn(),+ audit: vi.fn(),+}));++vi.mock("server-only", () => ({}));+vi.mock("@/lib/auth/require-session", () => ({+ getSessionContext: mocks.getSessionContext,+}));+vi.mock("@/lib/infra/google-oauth-flow", () => ({+ beginGoogleAuthorization: mocks.beginGoogleAuthorization,+}));+vi.mock("@/lib/host/audit-api", () => ({+ audit: mocks.audit,+}));++import { POST } from "./route";++const DEFAULT_ORIGIN = "https://mso.example.com";+const DEFAULT_HOST = "mso.example.com";++function makeReq(+ body: unknown,+ options: { origin?: string; host?: string } = {},+): NextRequest {+ return new NextRequest(`${DEFAULT_ORIGIN}/api/integrations/google/start`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ origin: options.origin ?? DEFAULT_ORIGIN,+ host: options.host ?? DEFAULT_HOST,+ },+ body: JSON.stringify(body),+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ process.env.OS_PUBLIC_ORIGIN = DEFAULT_ORIGIN;+ mocks.getSessionContext.mockResolvedValue({+ role: "owner",+ session: {+ device_id: "dev-owner-123",+ cookie_scope: "scope",+ cookie_epoch: 1,+ issued_at: 1000,+ expires_at: 2000,+ },+ });+ mocks.beginGoogleAuthorization.mockResolvedValue({+ authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?client_id=cid&state=flowstate12345678901234567890123456789012",+ cookieName: "__Host-mso-google-flow",+ binding: "flow-binding-val",+ expiresIn: 600,+ });+});++afterEach(() => {+ delete process.env.OS_PUBLIC_ORIGIN;+});++describe("POST /api/integrations/google/start", () => {+ it("refuses unauthenticated callers with 403 owner_required", async () => {+ // Only authenticated owner sessions may initiate Google OAuth authorization+ mocks.getSessionContext.mockResolvedValue(null);+ const res = await POST(makeReq({ user: "owner", provider: "google-search-console", connection: "primary" }));+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({ error: "owner_required" });+ expect(mocks.beginGoogleAuthorization).not.toHaveBeenCalled();+ });++ it("refuses non-owner roles with 403 owner_required", async () => {+ for (const role of ["viewer", "operator"]) {+ mocks.getSessionContext.mockResolvedValue({+ role,+ session: { device_id: "dev-123", cookie_scope: "scope", cookie_epoch: 1, issued_at: 1000, expires_at: 2000 },+ });+ const res = await POST(makeReq({ user: "owner", provider: "google-search-console", connection: "primary" }));+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({ error: "owner_required" });+ }+ expect(mocks.beginGoogleAuthorization).not.toHaveBeenCalled();+ });++ it("rejects mismatched origin or host with 403 google_same_origin_required", async () => {+ const badOrigin = await POST(makeReq({ user: "owner", provider: "google-search-console", connection: "primary" }, { origin: "https://evil.invalid" }));+ expect(badOrigin.status).toBe(403);+ expect(await badOrigin.json()).toEqual({ error: "google_same_origin_required" });++ const badHost = await POST(makeReq({ user: "owner", provider: "google-search-console", connection: "primary" }, { host: "evil.invalid" }));+ expect(badHost.status).toBe(403);+ expect(await badHost.json()).toEqual({ error: "google_same_origin_required" });+ expect(mocks.beginGoogleAuthorization).not.toHaveBeenCalled();+ });++ it("rejects non-google providers and extraneous fields with 400 invalid_google_request", async () => {+ // Non-Google provider is rejected+ const badProvider = await POST(makeReq({ user: "owner", provider: "github", connection: "primary" }));+ expect(badProvider.status).toBe(400);+ expect(await badProvider.json()).toEqual({ error: "invalid_google_request" });++ // Extraneous parameters are disallowed to prevent metadata smuggling+ const extraField = await POST(makeReq({ user: "owner", provider: "google-search-console", connection: "primary", extra: "forbidden" }));+ expect(extraField.status).toBe(400);+ expect(await extraField.json()).toEqual({ error: "invalid_google_request" });+ expect(mocks.beginGoogleAuthorization).not.toHaveBeenCalled();+ });++ it("starts flow on happy path, returning an authorizationUrl with state param and binding cookie", async () => {+ const res = await POST(makeReq({ user: "owner", provider: "google-search-console", connection: "primary" }));+ expect(res.status).toBe(200);++ const body = await res.json();+ expect(body.expiresIn).toBe(600);+ expect(body.authorizationUrl).toBeDefined();++ // Verify the returned URL carries the state parameter required for OAuth CSRF protection+ const parsedUrl = new URL(body.authorizationUrl);+ expect(parsedUrl.searchParams.has("state")).toBe(true);+ expect(parsedUrl.searchParams.get("state")).toBe("flowstate12345678901234567890123456789012");++ // Flow binding cookie must be set on the response+ const setCookie = res.headers.get("set-cookie");+ expect(setCookie).toContain("__Host-mso-google-flow=flow-binding-val");+ expect(setCookie).toContain("HttpOnly");++ // Action must be audited+ expect(mocks.audit).toHaveBeenCalledWith(+ expect.objectContaining({+ action: "infra.write",+ actor: "dev-owner-123",+ target: "owner/google-search-console/primary",+ ok: true,+ detail: "google.authorization.start",+ }),+ );+ });+});diff --git a/app/api/internal/socket-policy/route.test.ts b/app/api/internal/socket-policy/route.test.tsnew file mode 100644index 00000000..86edddb4--- /dev/null+++ b/app/api/internal/socket-policy/route.test.ts@@ -0,0 +1,121 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ socketPolicy: vi.fn(async () => ({ allowed: true, target: "http://127.0.0.1:8080" })),+}));++vi.mock("@/lib/managed-apps/socket-policy", () => ({+ socketPolicy: mocks.socketPolicy,+}));++import { POST } from "./route";++const VALID_SECRET = "test-secret-at-least-32-characters-long-policy-key";++function makeReq(options: {+ secret?: string;+ authHeader?: string;+ body?: unknown;+}): Request {+ const headers = new Headers();+ headers.set("content-type", "application/json");+ if (options.authHeader !== undefined) {+ headers.set("authorization", options.authHeader);+ } else if (options.secret !== undefined) {+ headers.set("authorization", `Bearer ${options.secret}`);+ }++ const rawBody =+ options.body === undefined+ ? JSON.stringify({ url: "https://mso.example/ws", headers: { host: "mso.example" } })+ : typeof options.body === "string"+ ? options.body+ : JSON.stringify(options.body);++ return new Request("https://mso.example/api/internal/socket-policy", {+ method: "POST",+ headers,+ body: rawBody,+ });+}++const originalSecret = process.env.MSO_SOCKET_POLICY_SECRET;++beforeEach(() => {+ vi.clearAllMocks();+ process.env.MSO_SOCKET_POLICY_SECRET = VALID_SECRET;+ mocks.socketPolicy.mockResolvedValue({ allowed: true, target: "http://127.0.0.1:8080" });+});++afterEach(() => {+ if (originalSecret !== undefined) {+ process.env.MSO_SOCKET_POLICY_SECRET = originalSecret;+ } else {+ delete process.env.MSO_SOCKET_POLICY_SECRET;+ }+});++describe("POST /api/internal/socket-policy", () => {+ describe("deliberate 404 stealth behavior", () => {+ // This route deliberately hides its existence behind 404 rather than 401/403.+ it("returns 404 when MSO_SOCKET_POLICY_SECRET is not configured", async () => {+ delete process.env.MSO_SOCKET_POLICY_SECRET;+ const res = await POST(makeReq({ secret: VALID_SECRET }));+ expect(res.status).toBe(404);+ expect(mocks.socketPolicy).not.toHaveBeenCalled();+ });++ it("returns 404 when configured secret is shorter than 32 characters", async () => {+ const shortSecret = "short-secret-under-32-bytes";+ process.env.MSO_SOCKET_POLICY_SECRET = shortSecret;+ const res = await POST(makeReq({ secret: shortSecret }));+ expect(res.status).toBe(404);+ expect(mocks.socketPolicy).not.toHaveBeenCalled();+ });++ it("returns 404 when authorization header is missing", async () => {+ const res = await POST(makeReq({}));+ expect(res.status).toBe(404);+ expect(mocks.socketPolicy).not.toHaveBeenCalled();+ });++ it("returns 404 when bearer token does not match secret", async () => {+ const res = await POST(makeReq({ secret: "wrong-bearer-secret-that-has-over-32-characters-here" }));+ expect(res.status).toBe(404);+ expect(mocks.socketPolicy).not.toHaveBeenCalled();+ });++ it("returns 404 when authorization scheme is not Bearer", async () => {+ const res = await POST(makeReq({ authHeader: `Basic ${VALID_SECRET}` }));+ expect(res.status).toBe(404);+ expect(mocks.socketPolicy).not.toHaveBeenCalled();+ });+ });++ describe("authenticated policy evaluation", () => {+ it("evaluates socket policy and returns 200 with no-store cache header on success", async () => {+ const res = await POST(+ makeReq({+ secret: VALID_SECRET,+ body: { url: "https://mso.example/ws", headers: { upgrade: "websocket" } },+ }),+ );+ expect(res.status).toBe(200);+ expect(res.headers.get("Cache-Control")).toBe("no-store");+ expect(await res.json()).toEqual({ allowed: true, target: "http://127.0.0.1:8080" });+ expect(mocks.socketPolicy).toHaveBeenCalledOnce();+ });++ it("returns 403 when socket policy evaluates to falsy / null decision", async () => {+ mocks.socketPolicy.mockResolvedValue(null as unknown as { allowed: boolean; target: string });+ const res = await POST(makeReq({ secret: VALID_SECRET }));+ expect(res.status).toBe(403);+ });++ it("returns 403 when request body is invalid JSON", async () => {+ const res = await POST(makeReq({ secret: VALID_SECRET, body: "not-json" }));+ expect(res.status).toBe(403);+ expect(mocks.socketPolicy).not.toHaveBeenCalled();+ });+ });+});diff --git a/app/api/mcp/activity/route.test.ts b/app/api/mcp/activity/route.test.tsnew file mode 100644index 00000000..edda10e4--- /dev/null+++ b/app/api/mcp/activity/route.test.ts@@ -0,0 +1,69 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+ readMcpActivity: vi.fn(async (_limit?: number): Promise<unknown[]> => []),+}));++vi.mock("@/lib/agent/server", () => ({+ verifyAuth: mocks.verifyAuth,+}));++vi.mock("@/lib/mcp/activity", () => ({+ readMcpActivity: mocks.readMcpActivity,+}));++import { GET } from "./route";++beforeEach(() => {+ vi.clearAllMocks();+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.readMcpActivity.mockResolvedValue([+ { id: "act-1", action: "tool_call", status: "completed" },+ ]);+});++describe("GET /api/mcp/activity", () => {+ // mcp/activity uses verifyAuth(req, "owner") and yields 401 { error: "unauthorized" }+ it("returns 401 { error: 'unauthorized' } when unauthenticated and does not read activity", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const req = new Request("https://mso.example/api/mcp/activity");+ const res = await GET(req);++ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(mocks.verifyAuth).toHaveBeenCalledWith(req, "owner");+ expect(mocks.readMcpActivity).not.toHaveBeenCalled();+ });++ it("returns 200 with entries and defaults limit to 80 when query is omitted", async () => {+ const entries = [{ id: "act-1", action: "tool_call", status: "completed" }];+ mocks.readMcpActivity.mockResolvedValue(entries);++ const req = new Request("https://mso.example/api/mcp/activity");+ const res = await GET(req);++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ entries });+ expect(mocks.readMcpActivity).toHaveBeenCalledWith(80);+ });++ // limit is clamped to [1, 200]+ it("clamps limit between 1 and 200 and handles invalid query values", async () => {+ await GET(new Request("https://mso.example/api/mcp/activity?limit=500"));+ expect(mocks.readMcpActivity).toHaveBeenCalledWith(200);++ await GET(new Request("https://mso.example/api/mcp/activity?limit=-5"));+ expect(mocks.readMcpActivity).toHaveBeenCalledWith(1);++ await GET(new Request("https://mso.example/api/mcp/activity?limit=0"));+ // "0" parses to 0, which falsy evaluates in `Number("0") || 80` -> 80+ expect(mocks.readMcpActivity).toHaveBeenCalledWith(80);++ await GET(new Request("https://mso.example/api/mcp/activity?limit=not-a-number"));+ expect(mocks.readMcpActivity).toHaveBeenCalledWith(80);++ await GET(new Request("https://mso.example/api/mcp/activity?limit=42"));+ expect(mocks.readMcpActivity).toHaveBeenCalledWith(42);+ });+});diff --git a/app/api/memory/route.test.ts b/app/api/memory/route.test.tsnew file mode 100644index 00000000..86d36d7f--- /dev/null+++ b/app/api/memory/route.test.ts@@ -0,0 +1,127 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";++const mocks = vi.hoisted(() => ({+ requireSession: vi.fn(async () => true),+ listMemories: vi.fn(async () => ["memory-1", "memory-2"]),+ addMemory: vi.fn(async (text: string) => ({ id: "mem-123", text })),+ removeMemory: vi.fn(async () => undefined),+}));++vi.mock("@/lib/auth/require-session", () => ({+ requireSession: mocks.requireSession,+}));++vi.mock("@/lib/agent/legacy-owner-memory", () => ({+ listMemories: mocks.listMemories,+ addMemory: mocks.addMemory,+ removeMemory: mocks.removeMemory,+}));++import { DELETE, GET, POST } from "./route";++const postReq = (body: unknown) =>+ new NextRequest("https://mso.example/api/memory", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: typeof body === "string" ? body : JSON.stringify(body),+ });++const deleteReq = (url: string) =>+ new NextRequest(url, {+ method: "DELETE",+ });++beforeEach(() => {+ vi.clearAllMocks();+ mocks.requireSession.mockResolvedValue(true);+ mocks.listMemories.mockResolvedValue(["memory-1", "memory-2"]);+ mocks.addMemory.mockImplementation(async (text: string) => ({ id: "mem-123", text }));+ mocks.removeMemory.mockResolvedValue(undefined);+});++describe("/api/memory", () => {+ describe("GET", () => {+ it("returns 401 when unauthenticated", async () => {+ mocks.requireSession.mockResolvedValue(false);+ const res = await GET();+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "Unauthorized" });+ expect(mocks.listMemories).not.toHaveBeenCalled();+ });++ it("returns list of memories on success", async () => {+ const res = await GET();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ memories: ["memory-1", "memory-2"] });+ expect(mocks.listMemories).toHaveBeenCalledOnce();+ });+ });++ describe("POST", () => {+ it("returns 401 when unauthenticated", async () => {+ mocks.requireSession.mockResolvedValue(false);+ const res = await POST(postReq({ text: "remember this" }));+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "Unauthorized" });+ expect(mocks.addMemory).not.toHaveBeenCalled();+ });++ it("returns 400 when body is invalid JSON", async () => {+ const res = await POST(postReq("not valid json {"));+ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "bad_request" });+ expect(mocks.addMemory).not.toHaveBeenCalled();+ });++ it("returns 400 when text is empty or missing", async () => {+ const emptyRes = await POST(postReq({ text: "" }));+ expect(emptyRes.status).toBe(400);+ expect(await emptyRes.json()).toEqual({ error: "text required" });++ const whitespaceRes = await POST(postReq({ text: " " }));+ expect(whitespaceRes.status).toBe(400);+ expect(await whitespaceRes.json()).toEqual({ error: "text required" });++ const missingRes = await POST(postReq({}));+ expect(missingRes.status).toBe(400);+ expect(await missingRes.json()).toEqual({ error: "text required" });++ expect(mocks.addMemory).not.toHaveBeenCalled();+ });++ it("adds memory and returns 200 on valid input", async () => {+ const res = await POST(postReq({ text: "prefer dark mode" }));+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ ok: true,+ memory: { id: "mem-123", text: "prefer dark mode" },+ });+ expect(mocks.addMemory).toHaveBeenCalledWith("prefer dark mode");+ });+ });++ describe("DELETE", () => {+ it("returns 401 when unauthenticated", async () => {+ mocks.requireSession.mockResolvedValue(false);+ const res = await DELETE(deleteReq("https://mso.example/api/memory?id=mem-123"));+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "Unauthorized" });+ expect(mocks.removeMemory).not.toHaveBeenCalled();+ });++ it("returns 400 when id search param is missing", async () => {+ const res = await DELETE(deleteReq("https://mso.example/api/memory"));+ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "id required" });+ expect(mocks.removeMemory).not.toHaveBeenCalled();+ });++ it("removes memory and returns 200 on success", async () => {+ const res = await DELETE(deleteReq("https://mso.example/api/memory?id=mem-123"));+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ ok: true });+ expect(mocks.removeMemory).toHaveBeenCalledWith("mem-123");+ });+ });+});diff --git a/app/api/models/providers/route.test.ts b/app/api/models/providers/route.test.tsnew file mode 100644index 00000000..b2de2a0e--- /dev/null+++ b/app/api/models/providers/route.test.ts@@ -0,0 +1,73 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";++const mocks = vi.hoisted(() => ({+ requireSession: vi.fn(async () => true),+ listProviderSummaries: vi.fn(async () => [+ { id: "mock-prov", name: "Mock Provider", connected: true },+ ]),+ providerSummariesFromCatalog: vi.fn(() => [+ { id: "offline-prov", name: "Offline Provider", connected: false },+ ]),+}));++vi.mock("@/lib/auth/require-session", () => ({+ requireSession: mocks.requireSession,+}));++vi.mock("@/lib/models/discovery.js", () => ({+ listProviderSummaries: mocks.listProviderSummaries,+ providerSummariesFromCatalog: mocks.providerSummariesFromCatalog,+}));++import { GET } from "./route";++const getReq = (url = "https://mso.example/api/models/providers") =>+ new NextRequest(url, { method: "GET" });++beforeEach(() => {+ vi.clearAllMocks();+ mocks.requireSession.mockResolvedValue(true);+ mocks.listProviderSummaries.mockResolvedValue([+ { id: "mock-prov", name: "Mock Provider", connected: true },+ ]);+ mocks.providerSummariesFromCatalog.mockReturnValue([+ { id: "offline-prov", name: "Offline Provider", connected: false },+ ]);+});++describe("GET /api/models/providers", () => {+ it("returns 401 when requireSession('owner') rejects caller", async () => {+ mocks.requireSession.mockResolvedValue(false);+ const res = await GET(getReq());+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "Unauthorized" });+ expect(mocks.requireSession).toHaveBeenCalledWith("owner");+ expect(mocks.listProviderSummaries).not.toHaveBeenCalled();+ });++ it("returns provider summaries with freeOnly=false by default", async () => {+ const res = await GET(getReq());+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ providers: [{ id: "mock-prov", name: "Mock Provider", connected: true }],+ });+ expect(mocks.listProviderSummaries).toHaveBeenCalledWith({ freeOnly: false });+ });++ it("passes freeOnly=true when ?free=1 query parameter is given", async () => {+ const res = await GET(getReq("https://mso.example/api/models/providers?free=1"));+ expect(res.status).toBe(200);+ expect(mocks.listProviderSummaries).toHaveBeenCalledWith({ freeOnly: true });+ });++ it("falls back to providerSummariesFromCatalog when discovery throws (offline box)", async () => {+ mocks.listProviderSummaries.mockRejectedValue(new Error("Network unreachable"));+ const res = await GET(getReq("https://mso.example/api/models/providers?free=1"));+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ providers: [{ id: "offline-prov", name: "Offline Provider", connected: false }],+ });+ expect(mocks.providerSummariesFromCatalog).toHaveBeenCalledWith({}, { freeOnly: true });+ });+});diff --git a/app/api/skills/route.test.ts b/app/api/skills/route.test.tsnew file mode 100644index 00000000..e5c8cb0d--- /dev/null+++ b/app/api/skills/route.test.ts@@ -0,0 +1,124 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++// app/api/skills is the last untested route, and it is worth its own file because of one+// branch: a bare skill name that matches several projects returns 409 "ambiguous" with+// candidates, NOT 404 and NOT a guess. Returning one project's instructions under another+// project's name is the exact bug that branch exists to prevent, so it gets an assertion.++const mocks = vi.hoisted(() => ({+ requireSession: vi.fn(async (_role?: string) => true),+ catalogSkillsDetailed: vi.fn(async () => ({ skills: [] as unknown[] })),+ resolveSkill: vi.fn(() => ({ skill: null, ambiguous: null }) as unknown),+ readSkillFile: vi.fn(async () => null as string | null),+ catalogGet: vi.fn(async () => ({ skills: [] as unknown[], scan: {} as unknown }) as unknown),+ listLearnedRecipes: vi.fn(async () => [] as unknown[]),+ searchSkillMemory: vi.fn(async () => ({ hits: [] }) as unknown),+}));++vi.mock("server-only", () => ({}));+vi.mock("@/lib/demo", () => ({ IS_DEMO: false }));+vi.mock("@/lib/auth/require-session", () => ({ requireSession: mocks.requireSession }));+vi.mock("@/lib/skills/catalog", () => ({+ catalogSkillsDetailed: mocks.catalogSkillsDetailed,+ resolveSkill: mocks.resolveSkill,+ readSkillFile: mocks.readSkillFile,+}));+vi.mock("@/lib/skills/catalog-ttl", () => ({ catalogTtl: { get: mocks.catalogGet } }));+vi.mock("@/lib/workflow", () => ({ listLearnedRecipes: mocks.listLearnedRecipes }));+vi.mock("@/lib/skills/search", () => ({ searchSkillMemory: mocks.searchSkillMemory }));++const { GET } = await import("./route");++// This handler reads req.nextUrl (NextRequest), not new URL(req.url). A plain Request makes it+// throw before any assertion, which would have made every test below a 500 rather than a check+// on the branch it names. Shim nextUrl onto the request the same way Next supplies it.+const get = (qs = "") => {+ const url = new URL(`https://mso.example/api/skills${qs}`);+ const req = new Request(url);+ Object.defineProperty(req, "nextUrl", { value: url, configurable: true });+ return GET(req as never);+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.requireSession.mockResolvedValue(true);+ mocks.catalogSkillsDetailed.mockResolvedValue({ skills: [] });+ mocks.resolveSkill.mockReturnValue({ skill: null, ambiguous: null });+ mocks.readSkillFile.mockResolvedValue(null);+ mocks.catalogGet.mockResolvedValue({ skills: [], scan: {} });+ mocks.listLearnedRecipes.mockResolvedValue([]);+});++describe("GET /api/skills", () => {+ it("returns 401 Unauthorized without an owner session", async () => {+ mocks.requireSession.mockResolvedValue(false);+ const res = await get();+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "Unauthorized" });+ // The catalog must not be read for a caller who cannot see it.+ expect(mocks.catalogGet).not.toHaveBeenCalled();+ });++ it("lists skills and learned recipes on the bare path", async () => {+ mocks.catalogGet.mockResolvedValue({ skills: [{ id: "a", name: "a" }], scan: { at: 1 } });+ mocks.listLearnedRecipes.mockResolvedValue([+ { id: "r1", intent: "i", project: "p", summary: "s", attempts: 2, successes: 2, failures: 0, fastestDurationMs: 9, updatedAt: 1 },+ ]);+ const res = await get();+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.skills).toHaveLength(1);+ expect(body.recipes[0].id).toBe("r1");+ });++ it("returns 409 ambiguous rather than guessing between projects", async () => {+ // The whole point of the branch: two projects ship a skill with this bare name.+ mocks.catalogSkillsDetailed.mockResolvedValue({ skills: [{ id: "x" }, { id: "y" }] });+ mocks.resolveSkill.mockReturnValue({ skill: null, ambiguous: ["proj-a/lint", "proj-b/lint"] });+ const res = await get("?name=lint");+ expect(res.status).toBe(409);+ const body = await res.json();+ expect(body.error).toBe("ambiguous");+ expect(body.candidates).toEqual(["proj-a/lint", "proj-b/lint"]);+ // A 409 must not carry content — that would be the guess this branch forbids.+ expect(body.content).toBeUndefined();+ });++ it("returns 404 when the name resolves to nothing", async () => {+ mocks.resolveSkill.mockReturnValue({ skill: null, ambiguous: null });+ const res = await get("?name=missing");+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "not_found" });+ });++ it("returns 404 when the file behind a known skill is gone", async () => {+ mocks.resolveSkill.mockReturnValue({ skill: { id: "a", name: "a", path: "/gone" }, ambiguous: null });+ mocks.readSkillFile.mockResolvedValue(null);+ const res = await get("?name=a");+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "not_found" });+ });++ it("truncates skill content at 24k and says so", async () => {+ mocks.resolveSkill.mockReturnValue({ skill: { id: "a", name: "a", path: "/f" }, ambiguous: null });+ mocks.readSkillFile.mockResolvedValue("x".repeat(30_000));+ const res = await get("?name=a");+ const body = await res.json();+ expect(body.content).toHaveLength(24_000);+ expect(body.truncated).toBe(true);+ });++ it("routes a query to memory search with the owner view forced on", async () => {+ const res = await get("?q=deploy");+ expect(res.status).toBe(200);+ expect(mocks.searchSkillMemory).toHaveBeenCalledWith(+ "deploy",+ expect.objectContaining({ recipeAccess: { ownerView: true } }),+ );+ });++ it("passes refresh through to the TTL cache", async () => {+ await get("?refresh=1");+ expect(mocks.catalogGet).toHaveBeenCalledWith({ refresh: true });+ });+});diff --git a/app/api/sw/route.test.ts b/app/api/sw/route.test.tsnew file mode 100644index 00000000..4dc44d14--- /dev/null+++ b/app/api/sw/route.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest";+import { GET } from "./route";++describe("GET /api/sw", () => {+ it("serves service worker as a public asset with 200 OK", async () => {+ const res = GET();+ expect(res.status).toBe(200);+ });++ it("sets required caching and service worker headers", async () => {+ const res = GET();+ expect(res.headers.get("Content-Type")).toBe("application/javascript; charset=utf-8");+ expect(res.headers.get("Cache-Control")).toBe("no-cache, no-store, must-revalidate");+ expect(res.headers.get("Service-Worker-Allowed")).toBe("/");+ });++ it("contains service worker lifecycle listeners and asset list", async () => {+ const res = GET();+ const text = await res.text();+ expect(text).toContain("self.addEventListener(\"install\"");+ expect(text).toContain("self.addEventListener(\"activate\"");+ expect(text).toContain("self.addEventListener(\"fetch\"");+ expect(text).toContain("/manifest.webmanifest");+ });+});diff --git a/app/api/v1/agent-groups/route.test.ts b/app/api/v1/agent-groups/route.test.tsnew file mode 100644index 00000000..2046608c--- /dev/null+++ b/app/api/v1/agent-groups/route.test.ts@@ -0,0 +1,134 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ getSessionContext: vi.fn(),+ agentGroupsSnapshot: vi.fn(async (): Promise<{ groups: unknown[] }> => ({ groups: [] })),+ getAgentGroup: vi.fn(async (_id?: string): Promise<unknown> => undefined),+ createAgentGroup: vi.fn(async (_data?: unknown): Promise<{ result: unknown }> => ({ result: {} })),+ updateAgentGroup: vi.fn(),+ deleteAgentGroup: vi.fn(),+ startAgentGroupRun: vi.fn(),+ stopAgentGroupRun: vi.fn(),+}));++vi.mock("@/lib/auth/require-session", () => ({+ getSessionContext: mocks.getSessionContext,+}));++vi.mock("@/lib/agent-group", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/lib/agent-group")>();+ return {+ ...actual,+ agentGroupsSnapshot: mocks.agentGroupsSnapshot,+ getAgentGroup: mocks.getAgentGroup,+ createAgentGroup: mocks.createAgentGroup,+ updateAgentGroup: mocks.updateAgentGroup,+ deleteAgentGroup: mocks.deleteAgentGroup,+ startAgentGroupRun: mocks.startAgentGroupRun,+ stopAgentGroupRun: mocks.stopAgentGroupRun,+ };+});++import { AgentGroupError } from "@/lib/agent-group";+import { GET, POST } from "./route";++beforeEach(() => {+ vi.clearAllMocks();+ mocks.getSessionContext.mockResolvedValue({+ role: "owner",+ session: { device_id: "dev-owner-1" },+ });+ mocks.agentGroupsSnapshot.mockResolvedValue({ groups: [{ id: "g1", name: "Alpha" }] });+ mocks.getAgentGroup.mockResolvedValue({ id: "g1", name: "Alpha" });+ mocks.createAgentGroup.mockResolvedValue({ result: { id: "g2", name: "Beta" } });+});++describe("agent-groups route contract", () => {+ describe("GET /api/v1/agent-groups", () => {+ // agent-groups rejects non-owners with 403 { error: "owner_required" }+ it("returns 403 { error: 'owner_required' } when session is missing", async () => {+ mocks.getSessionContext.mockResolvedValue(null);++ const res = await GET(new Request("https://mso.example/api/v1/agent-groups"));+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({ error: "owner_required" });+ expect(mocks.agentGroupsSnapshot).not.toHaveBeenCalled();+ });++ it("returns 403 { error: 'owner_required' } when caller role is not owner", async () => {+ mocks.getSessionContext.mockResolvedValue({+ role: "viewer",+ session: { device_id: "dev-viewer-1" },+ });++ const res = await GET(new Request("https://mso.example/api/v1/agent-groups"));+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({ error: "owner_required" });+ expect(mocks.agentGroupsSnapshot).not.toHaveBeenCalled();+ });++ it("returns 200 with snapshot when no id parameter given", async () => {+ const res = await GET(new Request("https://mso.example/api/v1/agent-groups"));+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ groups: [{ id: "g1", name: "Alpha" }] });+ expect(mocks.agentGroupsSnapshot).toHaveBeenCalledTimes(1);+ });++ it("returns 200 with specific group when id parameter is present", async () => {+ const res = await GET(new Request("https://mso.example/api/v1/agent-groups?id=g1"));+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ id: "g1", name: "Alpha" });+ expect(mocks.getAgentGroup).toHaveBeenCalledWith("g1");+ });++ it("maps AgentGroupError to status code and error code", async () => {+ mocks.getAgentGroup.mockRejectedValue(new AgentGroupError("agent_group_not_found", 404));++ const res = await GET(new Request("https://mso.example/api/v1/agent-groups?id=missing"));+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "agent_group_not_found" });+ });+ });++ describe("POST /api/v1/agent-groups", () => {+ it("returns 403 { error: 'owner_required' } when unauthenticated", async () => {+ mocks.getSessionContext.mockResolvedValue(null);++ const res = await POST(+ new Request("https://mso.example/api/v1/agent-groups", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ action: "create", data: { name: "New Group" } }),+ }),+ );+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({ error: "owner_required" });+ expect(mocks.createAgentGroup).not.toHaveBeenCalled();+ });++ it("executes valid action when owner", async () => {+ const res = await POST(+ new Request("https://mso.example/api/v1/agent-groups", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ action: "create", data: { name: "New Group" } }),+ }),+ );+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ id: "g2", name: "Beta" });+ expect(mocks.createAgentGroup).toHaveBeenCalledWith({ name: "New Group" });+ });++ it("returns 400 for unknown action", async () => {+ const res = await POST(+ new Request("https://mso.example/api/v1/agent-groups", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ action: "unsupported" }),+ }),+ );+ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "unknown_group_action" });+ });+ });+});diff --git a/app/api/v1/app-catalog/route.test.ts b/app/api/v1/app-catalog/route.test.tsnew file mode 100644index 00000000..ab718cb6--- /dev/null+++ b/app/api/v1/app-catalog/route.test.ts@@ -0,0 +1,64 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ getSessionContext: vi.fn(),+ loadAppCatalog: vi.fn(async (): Promise<{ apps: unknown[] }> => ({ apps: [] })),+}));++vi.mock("@/lib/auth/require-session", () => ({+ getSessionContext: mocks.getSessionContext,+}));++vi.mock("@/lib/host/app-catalog", () => ({+ loadAppCatalog: mocks.loadAppCatalog,+}));++import { GET } from "./route";++beforeEach(() => {+ vi.clearAllMocks();+ mocks.getSessionContext.mockResolvedValue({+ role: "owner",+ session: { device_id: "dev-owner-1" },+ });+ mocks.loadAppCatalog.mockResolvedValue({ apps: [{ id: "terminal", name: "Terminal" }] });+});++describe("GET /api/v1/app-catalog", () => {+ // app-catalog uses requireOwner which delegates to getSessionContext:+ // missing session returns 401 { error: "unauthorized" }+ it("returns 401 { error: 'unauthorized' } when session is missing and does not load catalog", async () => {+ mocks.getSessionContext.mockResolvedValue(null);++ const res = await GET();+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(res.headers.get("cache-control")).toBe("no-store, private");+ expect(mocks.loadAppCatalog).not.toHaveBeenCalled();+ });++ // non-owner role returns 403 { error: "owner_required" }+ it("returns 403 { error: 'owner_required' } when caller role is not owner", async () => {+ mocks.getSessionContext.mockResolvedValue({+ role: "viewer",+ session: { device_id: "dev-viewer-1" },+ });++ const res = await GET();+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({ error: "owner_required" });+ expect(res.headers.get("cache-control")).toBe("no-store, private");+ expect(mocks.loadAppCatalog).not.toHaveBeenCalled();+ });++ it("returns 200 with catalog data when caller is owner", async () => {+ const catalogData = { apps: [{ id: "app-1", title: "App One" }] };+ mocks.loadAppCatalog.mockResolvedValue(catalogData);++ const res = await GET();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual(catalogData);+ expect(res.headers.get("cache-control")).toBe("no-store, private");+ expect(mocks.loadAppCatalog).toHaveBeenCalledTimes(1);+ });+});diff --git a/app/api/v1/apps/route.test.ts b/app/api/v1/apps/route.test.tsnew file mode 100644index 00000000..864c1e1b--- /dev/null+++ b/app/api/v1/apps/route.test.ts@@ -0,0 +1,39 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+}));++vi.mock("@/lib/agent/server", () => ({+ verifyAuth: mocks.verifyAuth,+}));++import { GET } from "./route";++beforeEach(() => {+ vi.clearAllMocks();+ mocks.verifyAuth.mockResolvedValue(true);+});++describe("GET /api/v1/apps", () => {+ // apps uses verifyAuth (default role) and returns 401 { error: "unauthorized" }+ it("returns 401 { error: 'unauthorized' } when unauthenticated", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const req = new Request("https://mso.example/api/v1/apps");+ const res = await GET(req);++ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(mocks.verifyAuth).toHaveBeenCalledWith(req);+ });++ // runtime apps list is empty array by contract for localStorage app registry+ it("returns 200 with empty array when authenticated", async () => {+ const req = new Request("https://mso.example/api/v1/apps");+ const res = await GET(req);++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual([]);+ expect(mocks.verifyAuth).toHaveBeenCalledWith(req);+ });+});diff --git a/app/api/v1/camoufox/session/route.test.ts b/app/api/v1/camoufox/session/route.test.tsnew file mode 100644index 00000000..1cdb136f--- /dev/null+++ b/app/api/v1/camoufox/session/route.test.ts@@ -0,0 +1,125 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("server-only", () => ({}));++const mocks = vi.hoisted(() => ({+ demo: false,+ role: "operator" as string | null,+ deviceId: "test-device" as string | null,+ viewerOrigin: "https://viewer.mso.example.com" as string | null,+ createTicket: vi.fn(() => "ticket-123456"),+ readFile: vi.fn(async () => "vncpassword\n"),+}));++vi.mock("@/lib/demo", () => ({ get IS_DEMO() { return mocks.demo; } }));+vi.mock("@/lib/auth/require-session", () => ({+ getSessionContext: vi.fn(async () =>+ mocks.deviceId+ ? {+ role: mocks.role,+ session: {+ device_id: mocks.deviceId,+ issued_at: 1700000000000,+ expires_at: 1700003600000,+ },+ }+ : null,+ ),+}));+vi.mock("@/lib/camoufox/origin", () => ({+ camoufoxViewerOrigin: vi.fn(() => mocks.viewerOrigin),+}));+vi.mock("@/lib/camoufox/viewer-auth", () => ({+ createCamoufoxViewerTicket: mocks.createTicket,+}));+vi.mock("node:fs", () => ({+ promises: {+ readFile: mocks.readFile,+ },+}));++import { GET } from "./route";++const ORIGINAL_SECRET = process.env.OS_SESSION_SECRET;++beforeEach(() => {+ vi.clearAllMocks();+ mocks.demo = false;+ mocks.role = "operator";+ mocks.deviceId = "test-device";+ mocks.viewerOrigin = "https://viewer.mso.example.com";+ mocks.createTicket.mockReturnValue("ticket-123456");+ mocks.readFile.mockResolvedValue("vncpassword\n");+ process.env.OS_SESSION_SECRET = "a".repeat(32);+});++afterEach(() => {+ if (ORIGINAL_SECRET !== undefined) {+ process.env.OS_SESSION_SECRET = ORIGINAL_SECRET;+ } else {+ delete process.env.OS_SESSION_SECRET;+ }+});++describe("GET /api/v1/camoufox/session", () => {+ it("returns 404 unavailable when running in demo mode", async () => {+ // Demo environment has no host browser or VNC display+ mocks.demo = true;+ const res = await GET();+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "unavailable" });+ });++ it("returns 401 Unauthorized when session is missing or unauthenticated", async () => {+ mocks.deviceId = null;+ const res = await GET();+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "Unauthorized" });+ });++ it("returns 401 Unauthorized when device role is below operator", async () => {+ // Viewer role cannot control or view the host desktop+ mocks.role = "viewer";+ const res = await GET();+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "Unauthorized" });+ });++ it("returns 503 viewer_unconfigured when session signing secret is shorter than 32 chars", async () => {+ process.env.OS_SESSION_SECRET = "too-short-secret";+ const res = await GET();+ expect(res.status).toBe(503);+ expect(await res.json()).toEqual({ error: "viewer_unconfigured" });+ });++ it("returns 503 viewer_unconfigured when viewer origin is not configured", async () => {+ mocks.viewerOrigin = null;+ const res = await GET();+ expect(res.status).toBe(503);+ expect(await res.json()).toEqual({ error: "viewer_unconfigured" });+ });++ it("returns no_password_file reason when password file is missing or empty", async () => {+ mocks.readFile.mockRejectedValue(new Error("ENOENT"));+ const res = await GET();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ password: null,+ viewerOrigin: "https://viewer.mso.example.com",+ viewerTicket: "ticket-123456",+ viewerPathPrefix: "/_mso-camoufox",+ reason: "no_password_file",+ });+ });++ it("returns password and viewer ticket on happy path for operator", async () => {+ const res = await GET();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ password: "vncpassword",+ viewerOrigin: "https://viewer.mso.example.com",+ viewerTicket: "ticket-123456",+ viewerPathPrefix: "/_mso-camoufox",+ });+ });+});diff --git a/app/api/v1/federation/status/route.test.ts b/app/api/v1/federation/status/route.test.tsnew file mode 100644index 00000000..78c5c599--- /dev/null+++ b/app/api/v1/federation/status/route.test.ts@@ -0,0 +1,52 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+ getBatonlyFederationWorkerStatus: vi.fn(),+}));++vi.mock("@/lib/agent/server", () => ({+ verifyAuth: mocks.verifyAuth,+}));++vi.mock("@/lib/mcp/federation/batonly-worker", () => ({+ getBatonlyFederationWorkerStatus: mocks.getBatonlyFederationWorkerStatus,+}));++import { GET } from "./route";++beforeEach(() => {+ vi.clearAllMocks();+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.getBatonlyFederationWorkerStatus.mockReturnValue({+ running: true,+ connected: true,+ });+});++describe("GET /api/v1/federation/status", () => {+ // federation/status uses verifyAuth with "owner" and yields 401 { error: "unauthorized" }+ it("returns 401 { error: 'unauthorized' } when unauthenticated and does not query worker", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const req = new Request("https://mso.example/api/v1/federation/status");+ const res = await GET(req);++ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(mocks.verifyAuth).toHaveBeenCalledWith(req, "owner");+ expect(mocks.getBatonlyFederationWorkerStatus).not.toHaveBeenCalled();+ });++ it("returns 200 with worker status and no-store cache control when owner", async () => {+ const status = { running: true, connected: true, queueDepth: 0 };+ mocks.getBatonlyFederationWorkerStatus.mockReturnValue(status);++ const req = new Request("https://mso.example/api/v1/federation/status");+ const res = await GET(req);++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual(status);+ expect(res.headers.get("cache-control")).toBe("no-store");+ expect(mocks.getBatonlyFederationWorkerStatus).toHaveBeenCalledTimes(1);+ });+});diff --git a/app/api/v1/fs/usage/route.test.ts b/app/api/v1/fs/usage/route.test.tsnew file mode 100644index 00000000..3c041612--- /dev/null+++ b/app/api/v1/fs/usage/route.test.ts@@ -0,0 +1,62 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { HostError } from "@/lib/host/host-error";++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+ usage: vi.fn(async () => ({ used: 1024, total: 4096 })),+}));++vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));+vi.mock("@/lib/host/fs-api", () => ({ usage: mocks.usage }));++import { GET } from "./route";++const get = (url = "https://mso.example/api/v1/fs/usage") => GET(new Request(url));++beforeEach(() => {+ vi.clearAllMocks();+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.usage.mockResolvedValue({ used: 1024, total: 4096 });+});++describe("GET /api/v1/fs/usage", () => {+ it("returns 401 when unauthenticated and does not call usage", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const res = await get();+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(mocks.usage).not.toHaveBeenCalled();+ });++ it("refuses path that escapes allowed roots with 400", async () => {+ mocks.usage.mockRejectedValue(new HostError("Path outside readable roots"));+ const res = await get("https://mso.example/api/v1/fs/usage?path=/etc/shadow");+ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "Path outside readable roots" });+ expect(mocks.usage).toHaveBeenCalledWith("/etc/shadow");+ });++ it("returns 404 when requested path does not exist", async () => {+ const enoent = new Error("ENOENT: no such file or directory") as NodeJS.ErrnoException;+ enoent.code = "ENOENT";+ mocks.usage.mockRejectedValue(enoent);+ const res = await get("https://mso.example/api/v1/fs/usage?path=nonexistent");+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "Not found" });+ });++ it("defaults to ~ when path parameter is omitted", async () => {+ const res = await get();+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ used: 1024, total: 4096 });+ expect(mocks.usage).toHaveBeenCalledWith("~");+ });++ it("reads usage for a custom valid path", async () => {+ mocks.usage.mockResolvedValue({ used: 500, total: 2000 });+ const res = await get("https://mso.example/api/v1/fs/usage?path=workspace/proj");+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ used: 500, total: 2000 });+ expect(mocks.usage).toHaveBeenCalledWith("workspace/proj");+ });+});diff --git a/app/api/v1/fs/zip/route.test.ts b/app/api/v1/fs/zip/route.test.tsnew file mode 100644index 00000000..d1426a81--- /dev/null+++ b/app/api/v1/fs/zip/route.test.ts@@ -0,0 +1,107 @@+import { Readable } from "node:stream";+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),+ zipStream: vi.fn(async () => Readable.from([Buffer.from("PK-fake-zip")])),+ 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", () => ({ zipStream: mocks.zipStream }));++import { GET } from "./route";++const get = (url: string) => GET(new Request(url));++beforeEach(() => {+ vi.clearAllMocks();+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.getSessionActor.mockResolvedValue("test-actor");+ mocks.rateLimited.mockReturnValue(false);+ mocks.zipStream.mockResolvedValue(Readable.from([Buffer.from("PK-fake-zip")]));+});++describe("GET /api/v1/fs/zip", () => {+ it("returns 401 when unauthenticated and does not call zipStream", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const res = await get("https://mso.example/api/v1/fs/zip?base=workspace&n=file1.txt");+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(mocks.zipStream).not.toHaveBeenCalled();+ expect(mocks.rateLimited).not.toHaveBeenCalled();+ });++ it("returns 429 when rate limited and audits refusal", async () => {+ mocks.rateLimited.mockReturnValue(true);+ const res = await get("https://mso.example/api/v1/fs/zip?base=workspace&n=file1.txt");+ expect(res.status).toBe(429);+ expect(await res.json()).toEqual({ error: "Too many download requests, slow down" });+ expect(mocks.zipStream).not.toHaveBeenCalled();+ expect(mocks.audit).toHaveBeenCalledWith({+ action: "fs.zip",+ actor: "test-actor",+ ok: false,+ detail: "rate-limited",+ });+ });++ it("returns 400 when base is missing or empty", async () => {+ const res = await get("https://mso.example/api/v1/fs/zip?n=file1.txt");+ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "base + n required" });+ expect(mocks.zipStream).not.toHaveBeenCalled();+ });++ it("returns 400 when n parameter is missing", async () => {+ const res = await get("https://mso.example/api/v1/fs/zip?base=workspace");+ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "base + n required" });+ expect(mocks.zipStream).not.toHaveBeenCalled();+ });++ it("refuses path that escapes allowed roots with 400", async () => {+ mocks.zipStream.mockRejectedValue(new HostError("Path outside readable roots"));+ const res = await get("https://mso.example/api/v1/fs/zip?base=/etc&n=passwd");+ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "Path outside readable roots" });+ expect(mocks.audit).toHaveBeenCalledWith(+ expect.objectContaining({ action: "fs.zip", ok: false, target: "/etc" }),+ );+ });++ it("refuses selections exceeding selection or size limits with 400", async () => {+ mocks.zipStream.mockRejectedValue(new HostError("Archive exceeds 512 MiB input limit"));+ const res = await get("https://mso.example/api/v1/fs/zip?base=workspace&n=huge.bin");+ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "Archive exceeds 512 MiB input limit" });+ });++ it("streams zip archive successfully on happy path with default filename", async () => {+ const res = await get("https://mso.example/api/v1/fs/zip?base=workspace&n=file1.txt&n=file2.txt&x=node_modules");+ expect(res.status).toBe(200);+ expect(res.headers.get("content-type")).toBe("application/zip");+ expect(res.headers.get("content-disposition")).toBe('attachment; filename="archive.zip"');+ expect(res.headers.get("cache-control")).toBe("no-store");+ expect(mocks.zipStream).toHaveBeenCalledWith("workspace", ["file1.txt", "file2.txt"], ["node_modules"]);+ expect(mocks.audit).toHaveBeenCalledWith({+ action: "fs.zip",+ actor: "test-actor",+ target: "workspace",+ ok: true,+ detail: "2 items, skip 1",+ });+ });++ it("sanitizes custom filename to prevent header injection or unsafe paths", async () => {+ const res = await get("https://mso.example/api/v1/fs/zip?base=workspace&n=file.txt&name=my%20archive/../$test.zip");+ expect(res.status).toBe(200);+ expect(res.headers.get("content-disposition")).toBe('attachment; filename="my_archive_.._test.zip"');+ });+});diff --git a/app/api/v1/managed-apps/[id]/jobs/[jobId]/route.test.ts b/app/api/v1/managed-apps/[id]/jobs/[jobId]/route.test.tsnew file mode 100644index 00000000..cfbc9a39--- /dev/null+++ b/app/api/v1/managed-apps/[id]/jobs/[jobId]/route.test.ts@@ -0,0 +1,178 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ManagedAppJob } from "@/lib/managed-apps/types";++vi.mock("server-only", () => ({}));++const defaultJob: ManagedAppJob = {+ id: "job-123",+ applicationId: "hermes",+ kind: "update",+ argv: ["hermes", "update"],+ status: "running",+ startedAt: "2026-10-31T00:00:00Z",+ endedAt: null,+ exitCode: null,+ error: null,+ log: "starting...",+ logOffset: 11,+ runnerId: "runner-1",+ serverPid: 1234,+ updatedAt: "2026-10-31T00:00:01Z",+};++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async (_req: Request, _role?: string) => true),+ getSessionActor: vi.fn(async () => "test-owner"),+ demo: false,+ rateLimited: vi.fn(() => false),+ audit: vi.fn(async () => undefined),+ isManagedAppId: vi.fn((id: string) => id === "hermes" || id === "openclaw"),+ auditJobCompletion: vi.fn(),+ readManagedAppJob: vi.fn<(jobId: string, since?: number) => Promise<ManagedAppJob | null>>(+ async () => defaultJob,+ ),+ cancelManagedAppJob: vi.fn((_jobId: string, _id: string) => true),+}));++vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: mocks.getSessionActor }));+vi.mock("@/lib/demo", () => ({ get IS_DEMO() { return mocks.demo; } }));+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited }));+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));+vi.mock("@/lib/managed-apps/catalog", () => ({ isManagedAppId: mocks.isManagedAppId }));+vi.mock("@/lib/managed-apps/job-audit", () => ({ auditJobCompletion: mocks.auditJobCompletion }));+vi.mock("@/lib/managed-apps/jobs", () => ({+ readManagedAppJob: mocks.readManagedAppJob,+ cancelManagedAppJob: mocks.cancelManagedAppJob,+}));++import { DELETE, GET } from "./route";++const ctx = (id: string, jobId: string) => ({ params: Promise.resolve({ id, jobId }) });+const getReq = (id: string, jobId: string, query = "") =>+ new Request(`https://mso.example.com/api/v1/managed-apps/${id}/jobs/${jobId}${query}`);+const delReq = (id: string, jobId: string) =>+ new Request(`https://mso.example.com/api/v1/managed-apps/${id}/jobs/${jobId}`, { method: "DELETE" });++beforeEach(() => {+ vi.clearAllMocks();+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.getSessionActor.mockResolvedValue("test-owner");+ mocks.demo = false;+ mocks.rateLimited.mockReturnValue(false);+ mocks.isManagedAppId.mockImplementation((id: string) => id === "hermes" || id === "openclaw");+ mocks.readManagedAppJob.mockResolvedValue(defaultJob);+ mocks.cancelManagedAppJob.mockReturnValue(true);+});++describe("GET /api/v1/managed-apps/[id]/jobs/[jobId]", () => {+ it("returns 401 when unauthenticated and does not read job", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const res = await GET(getReq("hermes", "job-123"), ctx("hermes", "job-123"));+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(mocks.readManagedAppJob).not.toHaveBeenCalled();+ });++ it("returns 404 with distinct 'unknown managed application' error when app is unknown", async () => {+ const res = await GET(getReq("unknown-app", "job-123"), ctx("unknown-app", "job-123"));+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "unknown managed application" });+ expect(mocks.readManagedAppJob).not.toHaveBeenCalled();+ });++ it("returns 404 with distinct 'unknown job' error when job does not exist", async () => {+ mocks.readManagedAppJob.mockResolvedValue(null);+ const res = await GET(getReq("hermes", "job-404"), ctx("hermes", "job-404"));+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "unknown job" });+ });++ it("returns 404 with distinct 'unknown job' error when job belongs to a different app", async () => {+ // Cross-app isolation: a job ID from another app must not leak its transcript+ mocks.readManagedAppJob.mockResolvedValue({+ ...defaultJob,+ applicationId: "openclaw",+ });+ const res = await GET(getReq("hermes", "job-123"), ctx("hermes", "job-123"));+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "unknown job" });+ });++ it("returns job and audits completion on happy path with floored since param", async () => {+ const res = await GET(getReq("hermes", "job-123", "?since=10.7"), ctx("hermes", "job-123"));+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ job: defaultJob,+ });+ expect(mocks.readManagedAppJob).toHaveBeenCalledWith("job-123", 10);+ expect(mocks.auditJobCompletion).toHaveBeenCalled();+ });+});++describe("DELETE /api/v1/managed-apps/[id]/jobs/[jobId]", () => {+ it("returns 401 when caller is not owner and does not cancel job", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const res = await DELETE(delReq("hermes", "job-123"), ctx("hermes", "job-123"));+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(mocks.verifyAuth).toHaveBeenCalledWith(expect.any(Request), "owner");+ expect(mocks.cancelManagedAppJob).not.toHaveBeenCalled();+ });++ it("returns 403 demo mode is read-only when in demo mode", async () => {+ mocks.demo = true;+ const res = await DELETE(delReq("hermes", "job-123"), ctx("hermes", "job-123"));+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual({ error: "demo mode is read-only" });+ expect(mocks.cancelManagedAppJob).not.toHaveBeenCalled();+ });++ it("returns 404 with 'unknown managed application' when app is unknown on delete", async () => {+ const res = await DELETE(delReq("unknown-app", "job-123"), ctx("unknown-app", "job-123"));+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "unknown managed application" });+ expect(mocks.cancelManagedAppJob).not.toHaveBeenCalled();+ });++ it("returns 429 when rate limited on job cancellation", async () => {+ mocks.rateLimited.mockReturnValue(true);+ const res = await DELETE(delReq("hermes", "job-123"), ctx("hermes", "job-123"));+ expect(res.status).toBe(429);+ expect(await res.json()).toEqual({ error: "too many requests" });+ expect(mocks.cancelManagedAppJob).not.toHaveBeenCalled();+ });++ it("returns 404 and audits failure when job is not cancellable", async () => {+ // Non-cancellable when already terminal or during mandatory pre-flight backup+ mocks.cancelManagedAppJob.mockReturnValue(false);+ const res = await DELETE(delReq("hermes", "job-123"), ctx("hermes", "job-123"));+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "no cancellable job" });+ expect(mocks.audit).toHaveBeenCalledWith(+ expect.objectContaining({+ action: "managed-app.action",+ actor: "test-owner",+ target: "hermes",+ ok: false,+ detail: "job.cancel",+ }),+ );+ });++ it("returns 202 cancelled: true on happy path and audits success", async () => {+ const res = await DELETE(delReq("hermes", "job-123"), ctx("hermes", "job-123"));+ expect(res.status).toBe(202);+ expect(await res.json()).toEqual({ cancelled: true });+ expect(mocks.cancelManagedAppJob).toHaveBeenCalledWith("job-123", "hermes");+ expect(mocks.audit).toHaveBeenCalledWith(+ expect.objectContaining({+ action: "managed-app.action",+ actor: "test-owner",+ target: "hermes",+ ok: true,+ detail: "job.cancel",+ }),+ );+ });+});diff --git a/app/api/v1/sys/audit/route.test.ts b/app/api/v1/sys/audit/route.test.tsnew file mode 100644index 00000000..752b6d03--- /dev/null+++ b/app/api/v1/sys/audit/route.test.ts@@ -0,0 +1,76 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { AuditRecord } from "@/lib/host/audit";++const sampleRecord: AuditRecord = {+ action: "fs.read",+ actor: "operator-1",+ target: "/tmp",+ ts: "2026-10-31T00:00:00Z",+};++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+ readAuditTail: vi.fn<(opts?: { prefix?: string; limit?: number }) => Promise<AuditRecord[]>>(+ async () => [sampleRecord],+ ),+}));++vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));+vi.mock("@/lib/host/audit-api", () => ({ readAuditTail: mocks.readAuditTail }));++import { GET } from "./route";++function makeReq(url = "https://mso.example.com/api/v1/sys/audit"): Request {+ return new Request(url);+}++beforeEach(() => {+ vi.clearAllMocks();+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.readAuditTail.mockResolvedValue([sampleRecord]);+});++describe("GET /api/v1/sys/audit", () => {+ it("returns 401 when unauthenticated and does not call readAuditTail", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const res = await GET(makeReq());+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(mocks.readAuditTail).not.toHaveBeenCalled();+ });++ it("returns audit entries with default limit on happy path", async () => {+ const res = await GET(makeReq());+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ entries: [sampleRecord],+ });+ // Default limit is 50, prefix is undefined+ expect(mocks.readAuditTail).toHaveBeenCalledWith({ prefix: undefined, limit: 50 });+ });++ it("clamps limit between 1 and 200 and forwards prefix", async () => {+ // Upper clamp to 200 prevents unbounded memory allocations+ await GET(makeReq("https://mso.example.com/api/v1/sys/audit?limit=999&prefix=fs."));+ expect(mocks.readAuditTail).toHaveBeenCalledWith({ prefix: "fs.", limit: 200 });++ // Lower clamp to 1 prevents negative or 0 reads+ await GET(makeReq("https://mso.example.com/api/v1/sys/audit?limit=-10"));+ expect(mocks.readAuditTail).toHaveBeenCalledWith({ prefix: undefined, limit: 1 });+ });++ it("filters entries by actor prefix and caps results to limit", async () => {+ // When actor filter is requested, handler pulls up to 200 entries and filters by startsWith+ mocks.readAuditTail.mockResolvedValue([+ { action: "fs.read", actor: "operator-alice", ts: "2026-10-31T00:00:01Z" },+ { action: "fs.write", actor: "operator-bob", ts: "2026-10-31T00:00:02Z" },+ { action: "term.open", actor: "operator-alice-2", ts: "2026-10-31T00:00:03Z" },+ ]);+ const res = await GET(makeReq("https://mso.example.com/api/v1/sys/audit?actor=operator-alice&limit=1"));+ expect(res.status).toBe(200);+ expect(mocks.readAuditTail).toHaveBeenCalledWith({ prefix: undefined, limit: 200 });+ const body = await res.json();+ expect(body.entries).toHaveLength(1);+ expect(body.entries[0]).toEqual({ action: "fs.read", actor: "operator-alice", ts: "2026-10-31T00:00:01Z" });+ });+});diff --git a/app/api/v1/sys/processes/route.test.ts b/app/api/v1/sys/processes/route.test.tsnew file mode 100644index 00000000..8088a068--- /dev/null+++ b/app/api/v1/sys/processes/route.test.ts@@ -0,0 +1,63 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { HostError } from "@/lib/host/host-error";++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+ processes: vi.fn(async () => [+ { pid: 1234, name: "node", cpu: 1.5, mem: 45, status: "R" },+ ]),+}));++vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));+vi.mock("@/lib/host/system-api", () => ({ processes: mocks.processes }));++import { GET } from "./route";++function makeReq(): Request {+ return new Request("https://mso.example.com/api/v1/sys/processes");+}++beforeEach(() => {+ vi.clearAllMocks();+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.processes.mockResolvedValue([+ { pid: 1234, name: "node", cpu: 1.5, mem: 45, status: "R" },+ ]);+});++describe("GET /api/v1/sys/processes", () => {+ it("returns 401 when unauthenticated and does not call processes", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const res = await GET(makeReq());+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(mocks.processes).not.toHaveBeenCalled();+ });++ it("returns process list on happy path", async () => {+ const sample = [+ { pid: 42, name: "mso", cpu: 0.8, mem: 64, status: "S" },+ ];+ mocks.processes.mockResolvedValue(sample);+ const res = await GET(makeReq());+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual(sample);+ expect(mocks.processes).toHaveBeenCalledOnce();+ });++ it("translates HostError through apiError with custom status and message", async () => {+ // Curated HostError messages pass through with explicit status and message+ mocks.processes.mockRejectedValue(new HostError("Process table unavailable", 503));+ const res = await GET(makeReq());+ expect(res.status).toBe(503);+ expect(await res.json()).toEqual({ error: "Process table unavailable" });+ });++ it("translates unexpected exceptions to generic 500 error via apiError", async () => {+ // Raw exceptions must be masked to avoid leaking internal system details+ mocks.processes.mockRejectedValue(new Error("ps command failed unexpectedly"));+ const res = await GET(makeReq());+ expect(res.status).toBe(500);+ expect(await res.json()).toEqual({ error: "Operation failed" });+ });+});diff --git a/app/api/v1/sys/stats/route.test.ts b/app/api/v1/sys/stats/route.test.tsnew file mode 100644index 00000000..e7744dcb--- /dev/null+++ b/app/api/v1/sys/stats/route.test.ts@@ -0,0 +1,63 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { HostError } from "@/lib/host/host-error";++const defaultStats = {+ cpu: { pct: 12, cores: 4 },+ mem: { used: 2048, total: 8192 },+ disk: { used: 40000, total: 100000 },+ net: { rx: 0, tx: 0 },+ uptime: 123456,+};++const mocks = vi.hoisted(() => ({+ verifyAuth: vi.fn(async () => true),+ stats: vi.fn(async () => defaultStats),+}));++vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.verifyAuth }));+vi.mock("@/lib/host/system-api", () => ({ stats: mocks.stats }));++import { GET } from "./route";++function makeReq(): Request {+ return new Request("https://mso.example.com/api/v1/sys/stats");+}++beforeEach(() => {+ vi.clearAllMocks();+ mocks.verifyAuth.mockResolvedValue(true);+ mocks.stats.mockResolvedValue(defaultStats);+});++describe("GET /api/v1/sys/stats", () => {+ it("returns 401 when unauthenticated and does not call stats", async () => {+ mocks.verifyAuth.mockResolvedValue(false);+ const res = await GET(makeReq());+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ error: "unauthorized" });+ expect(mocks.stats).not.toHaveBeenCalled();+ });++ it("returns system stats on happy path", async () => {+ const res = await GET(makeReq());+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual(defaultStats);+ expect(mocks.stats).toHaveBeenCalledOnce();+ });++ it("translates HostError through apiError with custom status and message", async () => {+ // Specific host telemetry failure handled cleanly without crashing+ mocks.stats.mockRejectedValue(new HostError("Telemetry unavailable", 503));+ const res = await GET(makeReq());+ expect(res.status).toBe(503);+ expect(await res.json()).toEqual({ error: "Telemetry unavailable" });+ });++ it("translates unexpected exceptions to generic 500 error via apiError", async () => {+ // Unexpected internal exceptions return sanitized generic error+ mocks.stats.mockRejectedValue(new Error("proc stat read failed"));+ const res = await GET(makeReq());+ expect(res.status).toBe(500);+ expect(await res.json()).toEqual({ error: "Operation failed" });+ });+});diff --git a/app/integrations/embed/route.test.ts b/app/integrations/embed/route.test.tsnew file mode 100644index 00000000..eee6a86e--- /dev/null+++ b/app/integrations/embed/route.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it, vi } from "vitest";++vi.mock("server-only", () => ({}));++import { GET } from "./route";++describe("GET /integrations/embed", () => {+ it("renders public embedded manager HTML with same-origin framing without a session", async () => {+ // Public by design: serves the catalog iframe shell without requiring credentials+ const res = GET();+ expect(res.status).toBe(200);+ expect(res.headers.get("content-type")).toBe("text/html; charset=utf-8");+ expect(res.headers.get("cache-control")).toContain("no-store");+ expect(res.headers.get("referrer-policy")).toBe("no-referrer");+ expect(res.headers.get("x-content-type-options")).toBe("nosniff");+ expect(res.headers.get("x-frame-options")).toBe("SAMEORIGIN");+ expect(res.headers.get("content-security-policy")).toContain("frame-ancestors 'self'");++ const html = await res.text();+ expect(html).toContain("<!doctype html>");+ expect(html).toContain("INTEGRATIONS_CATALOG");+ // Embedded presentation hides the top site-bar+ expect(html).toContain(".site-bar{display:none}");+ });+});diff --git a/app/integrations/manager/route.test.ts b/app/integrations/manager/route.test.tsnew file mode 100644index 00000000..b64b2cd0--- /dev/null+++ b/app/integrations/manager/route.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it, vi } from "vitest";++vi.mock("server-only", () => ({}));++import { GET } from "./route";++describe("GET /integrations/manager", () => {+ it("serves the native embedded manager with same-origin framing without requiring auth", async () => {+ // Handler serves the manager interface without requiring an authenticated session+ const res = GET();+ expect(res.status).toBe(200);+ expect(res.headers.get("content-type")).toBe("text/html; charset=utf-8");+ expect(res.headers.get("cache-control")).toContain("no-store");+ expect(res.headers.get("referrer-policy")).toBe("no-referrer");+ expect(res.headers.get("x-content-type-options")).toBe("nosniff");+ expect(res.headers.get("x-frame-options")).toBe("SAMEORIGIN");+ expect(res.headers.get("content-security-policy")).toContain("frame-ancestors 'self'");++ const html = await res.text();+ expect(html).toContain("<!doctype html>");+ expect(html).toContain("INTEGRATIONS_CATALOG");+ // Embedded presentation hides the top site-bar+ expect(html).toContain(".site-bar{display:none}");+ });+});diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 28b69587..27154372 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -17,6 +17,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Tests**+- `api` every route now has a test — 117 of 117- `api` cover 30 more routes, and close the one fs route with no rate limit## 2026-10-30