Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(security): close remaining repository scan trust boundaries

Abdurrahman Fakhrul8f8f2cce4fc6
diff --git a/SECURITY.md b/SECURITY.md
index 6b6a3914..7b9f290d 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -82,6 +82,25 @@ and a credential denylist. MSO's own private state, `.env*`, SSH/GPG material an
sensitive-home paths are hidden/refused unless the supervised sensitive-path escape hatch is
explicitly enabled.
+Linux/WSL file reads validate the opened descriptor; raw downloads stream that same handle.
+Mutations and recursive walks hold directory descriptors, so exchanged ancestor paths cannot
+redirect an authorized operation. Uploads retain their directory handle until commit; ZIP reads
+build a bounded private snapshot before the external archiver runs. Configure resolved absolute
+roots: a root replaced with a symlink does not grant access to its new target. These guards fail
+closed without Linux `/proc` descriptor support; official macOS/Termux installs use a Linux guest.
+
+Workflow graphs recheck the live device before every action. Operator graphs can read and perform
+only reviewed managed-app start/stop/restart/backup actions; generic writes, installation, provider
+configuration and new write capabilities require Owner. The tool directory follows the same policy.
+Inbound A2A clamps token scope to the current deployment ceiling at dispatch, each model round and
+each tool invocation. Local-agent message streams retain the signed session and stop before another
+delivery or within one second while idle after revocation, demotion, logout, expiry or cookie-policy rotation.
+
+Managed-app cookies use host-only `__Host-` names, `Secure` and `Path=/` on HTTPS app origins.
+Legacy and duplicate names are refused, so existing app logins may need to be renewed after an update.
+OAuth discovery ignores forwarded authority, prefers the configured public origin and uses `no-store`.
+Fresh installation fetches and verifies the requested Git ref and fails instead of using the default branch.
+
`exec.run` / MCP `exec_run` runs as the MSO Linux user. The destructive-command matcher is a
short accident tripwire, not a sandbox. Interactive Terminal PTYs are even more direct: raw
keystrokes cannot be reliably parsed into commands, so authentication and PTY session
diff --git a/app/.well-known/oauth-authorization-server/route.ts b/app/.well-known/oauth-authorization-server/route.ts
index 33f4210d..367033ee 100644
--- a/app/.well-known/oauth-authorization-server/route.ts
+++ b/app/.well-known/oauth-authorization-server/route.ts
@@ -34,6 +34,6 @@ export async function GET(req: Request) {
scopes_supported: ["read", "write", "exec", "offline_access"],
authorization_response_iss_parameter_supported: true,
},
- { headers: { ...PUBLIC_CORS, "cache-control": "public, max-age=3600" } },
+ { headers: { ...PUBLIC_CORS, "cache-control": "no-store" } },
);
}
diff --git a/app/.well-known/oauth-discovery-security.test.ts b/app/.well-known/oauth-discovery-security.test.ts
new file mode 100644
index 00000000..43040a8c
--- /dev/null
+++ b/app/.well-known/oauth-discovery-security.test.ts
@@ -0,0 +1,21 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { GET as authorization } from "./oauth-authorization-server/route";
+import { GET as resource } from "./oauth-protected-resource/route";
+afterEach(() => vi.unstubAllEnvs());
+
+describe("OAuth discovery origin integrity", () => {
+ it.each([authorization, resource])("ignores forwarded authority with and without a pinned origin", async (get) => {
+ vi.stubEnv("OS_MCP_ENABLED", "1");
+ const req = new Request("https://mso.example.test/.well-known/oauth-authorization-server", {headers: {host: "mso.example.test", "x-forwarded-host": "attacker.example", "x-forwarded-proto": "http"}});
+ for (const pinned of ["", "https://public.example.test"]) {
+ vi.stubEnv("OS_PUBLIC_ORIGIN", pinned);
+ const response = await get(req);
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ const json = JSON.stringify(await response.json());
+ expect(json).toContain(pinned || "https://mso.example.test");
+ expect(json).not.toContain("attacker.example");
+ expect(json).not.toContain("http://");
+ }
+ });
+});
diff --git a/app/.well-known/oauth-protected-resource/route.ts b/app/.well-known/oauth-protected-resource/route.ts
index 68f017d9..34090add 100644
--- a/app/.well-known/oauth-protected-resource/route.ts
+++ b/app/.well-known/oauth-protected-resource/route.ts
@@ -28,6 +28,6 @@ export async function GET(req: Request) {
scopes_supported: ["read", "write", "exec", "offline_access"],
bearer_methods_supported: ["header"],
},
- { headers: { ...PUBLIC_CORS, "cache-control": "public, max-age=3600" } },
+ { headers: { ...PUBLIC_CORS, "cache-control": "no-store" } },
);
}
diff --git a/app/api/v1/editor/exec/route.ts b/app/api/v1/editor/exec/route.ts
index dc45becf..31b9ab40 100644
--- a/app/api/v1/editor/exec/route.ts
+++ b/app/api/v1/editor/exec/route.ts
@@ -39,7 +39,7 @@ async function docFromImagePath(path: string, name?: string): Promise<{ doc: Doc
const info = await statReadable(path);
const end = Math.min(info.size - 1, 262143);
const chunks: Buffer[] = [];
- for await (const c of fileStream(info.path, 0, end)) chunks.push(c as Buffer);
+ for await (const c of fileStream(info.handle, 0, Math.max(0, end))) chunks.push(c as Buffer);
const { width, height, fallback } = imageSize(Buffer.concat(chunks));
return { doc: buildDocFromImage(rawUrl(info.path), { name, width, height }), fallback };
}
diff --git a/app/api/v1/fs/raw/route.ts b/app/api/v1/fs/raw/route.ts
index 4f9135fe..f94d4810 100644
--- a/app/api/v1/fs/raw/route.ts
+++ b/app/api/v1/fs/raw/route.ts
@@ -17,7 +17,7 @@ export async function GET(req: Request) {
const path = new URL(req.url).searchParams.get("path") ?? "";
if (!path) return NextResponse.json({ error: "path required" }, { status: 400 });
- let info: { path: string; size: number; mime: string };
+ let info: Awaited<ReturnType<typeof statReadable>>;
try {
info = await statReadable(path);
} catch (e) {
@@ -46,12 +46,13 @@ export async function GET(req: Request) {
if (Number.isNaN(start)) start = 0;
if (Number.isNaN(end) || end >= info.size) end = info.size - 1;
if (start > end || start >= info.size) {
+ await info.handle.close();
return new Response(null, {
status: 416,
headers: { "content-range": `bytes */${info.size}` },
});
}
- return new Response(toWeb(fileStream(info.path, start, end)), {
+ return new Response(toWeb(fileStream(info.handle, start, end)), {
status: 206,
headers: {
...base,
@@ -61,7 +62,7 @@ export async function GET(req: Request) {
});
}
- return new Response(toWeb(fileStream(info.path)), {
+ return new Response(toWeb(fileStream(info.handle)), {
status: 200,
headers: { ...base, "content-length": String(info.size) },
});
diff --git a/app/api/v1/local-agents/route.ts b/app/api/v1/local-agents/route.ts
index 2c478121..f202b49f 100644
--- a/app/api/v1/local-agents/route.ts
+++ b/app/api/v1/local-agents/route.ts
@@ -7,12 +7,11 @@ import { listLocalAgents } from "@/lib/agent/local-agent-directory";
import { endLocalAgentPresence, touchLocalAgentPresence } from "@/lib/agent/local-agent-presence";
import { listLocalAgentInbox, updateLocalAgentMessageState } from "@/lib/agent/local-agent-mailbox";
import { flushLocalAgentQueue, replyLocalAgentMessage, sendLocalAgentMessage } from "@/lib/agent/local-agent-messaging";
-import { subscribeLocalAgentMessages } from "@/lib/agent/local-agent-events";
+import { localAgentStream } from "@/lib/agent/local-agent-stream";
import type { LocalAgentPresenceState } from "@/lib/agent/local-agent-types";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
-const SSE_HEARTBEAT_MS = 15_000;
const MAX_POST_BODY_BYTES = 128 * 1024;
class LocalAgentBodyTooLarge extends Error {}
@@ -37,11 +36,11 @@ async function readBoundedBody(req: Request): Promise<Record<string, unknown>> {
return value as Record<string, unknown>;
}
-async function ownerPrincipal(): Promise<{ principal: string; actor: string } | null> {
+async function ownerPrincipal(): Promise<{ principal: string; actor: string; session: import("@/lib/auth/session").SessionPayload } | null> {
const context = await getSessionContext();
if (context?.role !== "owner") return null;
const actor = context.session.device_id || "owner";
- return { principal: `cli:${actor}`, actor };
+ return { principal: `cli:${actor}`, actor, session: context.session };
}
async function requireCliSession(principal: string, id: string) {
@@ -71,54 +70,7 @@ export async function GET(req: NextRequest) {
if (url.searchParams.get("stream") === "1") {
if (!sessionId) return NextResponse.json({ error: "session_required" }, { status: 400 });
await requireCliSession(owner.principal, sessionId);
- const encoder = new TextEncoder();
- let unsubscribe = () => {};
- let heartbeat: ReturnType<typeof setInterval> | null = null;
- let closed = false;
- const stream = new ReadableStream<Uint8Array>({
- async start(controller) {
- const send = (event: string, value: unknown) => {
- if (closed) return;
- try {
- controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(value)}\n\n`));
- } catch {
- closed = true;
- }
- };
- // Subscribe before replaying the durable backlog so a send racing stream setup
- // can be duplicated (client dedupes by message id) but can never be missed.
- unsubscribe = subscribeLocalAgentMessages(sessionId, (message) => send("message", message));
- const backlog = await listLocalAgentInbox(owner.principal, sessionId, { limit: 200 });
- const pendingIds = backlog.filter((row) => row.state !== "read").map((row) => row.id);
- if (pendingIds.length)
- await updateLocalAgentMessageState(owner.principal, sessionId, pendingIds, "delivered");
- for (const row of backlog) send("message", { ...row, state: row.state === "read" ? "read" : "delivered" });
- heartbeat = setInterval(() => {
- if (!closed) {
- try { controller.enqueue(encoder.encode(": ping\n\n")); }
- catch { closed = true; }
- }
- }, SSE_HEARTBEAT_MS);
- req.signal.addEventListener("abort", () => {
- closed = true;
- unsubscribe();
- if (heartbeat) clearInterval(heartbeat);
- }, { once: true });
- },
- cancel() {
- closed = true;
- unsubscribe();
- if (heartbeat) clearInterval(heartbeat);
- },
- });
- return new Response(stream, {
- headers: {
- "content-type": "text/event-stream; charset=utf-8",
- "cache-control": "no-cache, no-transform",
- "x-accel-buffering": "no",
- connection: "keep-alive",
- },
- });
+ return localAgentStream(owner.principal, sessionId, owner.session, req.signal);
}
if (url.searchParams.get("inbox") === "1") {
diff --git a/app/api/v1/managed-apps/proxy-split-origin.test.ts b/app/api/v1/managed-apps/proxy-split-origin.test.ts
index cc692852..ccf64552 100644
--- a/app/api/v1/managed-apps/proxy-split-origin.test.ts
+++ b/app/api/v1/managed-apps/proxy-split-origin.test.ts
@@ -99,7 +99,7 @@ describe("the cockpit-origin URL stops answering", () => {
fetchMock.mockResolvedValueOnce(new Response("ok", { status: 200 }));
const { GET } = await route();
await GET(
- appReq("chat", { headers: { cookie: "session=mso-secret; mapp_hermes_session=upstream-sid" } }),
+ appReq("chat", { headers: { cookie: "session=mso-secret; __Host-mapp_hermes_session=upstream-sid" } }),
ctx(["chat"]),
);
expect((fetchMock.mock.calls[0][1].headers as Headers).get("cookie")).toBe("session=upstream-sid");
diff --git a/app/api/v1/managed-apps/proxy.test.ts b/app/api/v1/managed-apps/proxy.test.ts
index 05c22fb4..640d52de 100644
--- a/app/api/v1/managed-apps/proxy.test.ts
+++ b/app/api/v1/managed-apps/proxy.test.ts
@@ -38,7 +38,7 @@ const ctx = (path: string[]) => ({ params: Promise.resolve({ id: "hermes", path
function req(path: string, init: RequestInit = {}): Request {
const headers = new Headers(init.headers);
if (!headers.has(HOST_HEADER)) headers.set(HOST_HEADER, "hermes");
- return new Request(`http://localhost${PREFIX}/${path}`, { ...init, headers });
+ return new Request(`https://hermes.mso.example.com${PREFIX}/${path}`, { ...init, headers });
}
/** Headers of the single upstream fetch the route performed. */
@@ -62,7 +62,7 @@ describe("managed-app proxy cookie isolation", () => {
await GET(
req("chat", {
headers: {
- cookie: "session=mso-secret; mso-device=deadbeef; mapp_hermes_session=upstream-sid",
+ cookie: "session=mso-secret; mso-device=deadbeef; __Host-mapp_hermes_session=upstream-sid",
origin: "http://localhost",
referer: "https://hermes.mso.example.com/login?next=%2Fchat",
},
@@ -86,7 +86,7 @@ describe("managed-app proxy cookie isolation", () => {
expect(sentHeaders().has("cookie")).toBe(false);
});
- it("namespaces upstream set-cookie and pins it to the proxy path", async () => {
+ it("namespaces upstream set-cookie and pins it to the app host", async () => {
const upstream = new Response("ok", { status: 200 });
upstream.headers.append(
"set-cookie",
@@ -96,15 +96,14 @@ describe("managed-app proxy cookie isolation", () => {
const { GET } = await import("./[id]/proxy/[[...path]]/route");
const res = await GET(req("chat"), ctx(["chat"]));
const cookie = res.headers.getSetCookie()[0];
- expect(cookie).toContain("mapp_hermes_session=abc123");
+ expect(cookie).toContain("__Host-mapp_hermes_session=abc123");
// Root-mounted on the app host: the app owns "/" there, so that is the scope.
expect(cookie).toContain("Path=/");
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("Max-Age=3600");
expect(cookie).toContain("SameSite=Lax");
expect(cookie).not.toContain("Domain");
- // Plain http hop: a Secure cookie would be dropped by the browser.
- expect(cookie).not.toContain("Secure");
+ expect(cookie).toContain("Secure");
expect(res.headers.get("x-managed-app")).toBe("hermes");
});
@@ -140,8 +139,8 @@ describe("managed-app proxy cookie isolation", () => {
expect(res.headers.get("location")).not.toMatch(/^https?:\/\//);
const cookies = res.headers.getSetCookie();
expect(cookies).toHaveLength(2);
- expect(cookies[0]).toContain("mapp_hermes_session=sid1");
- expect(cookies[1]).toContain("mapp_hermes_csrftoken=tok2");
+ expect(cookies[0]).toContain("__Host-mapp_hermes_session=sid1");
+ expect(cookies[1]).toContain("__Host-mapp_hermes_csrftoken=tok2");
expect(cookies.every((cookie) => cookie.includes("Path=/"))).toBe(true);
// The urlencoded body reaches the upstream untouched.
const init = fetchMock.mock.calls[0][1];
@@ -209,7 +208,7 @@ describe("managed-app proxy guards", () => {
const { verifyAuth } = await import("@/lib/agent/server");
vi.mocked(verifyAuth).mockResolvedValueOnce(false);
const { GET } = await import("./[id]/proxy/[[...path]]/route");
- const res = await GET(req("chat", { headers: { cookie: "mapp_hermes_session=x" } }), ctx(["chat"]));
+ const res = await GET(req("chat", { headers: { cookie: "__Host-mapp_hermes_session=x" } }), ctx(["chat"]));
expect(res.status).toBe(401);
expect(fetchMock).not.toHaveBeenCalled();
// Without frame-ancestors, next.config's X-Frame-Options: DENY makes the browser
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.ts
index 32797d32..0dbc2891 100644
--- a/app/api/v1/workflows/route.ts
+++ b/app/api/v1/workflows/route.ts
@@ -19,6 +19,7 @@ import { listWorkflowGraphVersions, readWorkflowGraphVersion } from "@/lib/workf
import { resolveWorkflowGraphNodeTarget } from "@/lib/workflow/graph-target";
import { deleteWorkflowVariable, listWorkflowVariables, setWorkflowVariable } from "@/lib/workflow/variables";
import { workflowNodeCatalog } from "@/lib/workflow/node-catalog";
+import { workflowExecutionContext } from "@/lib/workflow/graph-authority";
import { workflowTemplate, workflowTemplates } from "@/lib/workflow/templates";
import { suggestWorkflowGraph } from "@/lib/workflow/ai-assist";
import { workflowMatchesQuery } from "@/lib/workflow/search";
@@ -34,7 +35,8 @@ function definition(graph:NonNullable<Awaited<ReturnType<typeof getWorkflowGraph
export async function GET(req:NextRequest){const q=req.nextUrl.searchParams,minimum=(q.has("variables")||q.has("data_tables")||q.has("data_table"))?"operator":"viewer",session=await auth(minimum);if(!session)return fail("unauthorized",401);try{
if(q.get("owner_view")==="1"){if(session.context.role!=="owner")return fail("owner_required",403);return NextResponse.json(await discoverOwnerGraphs(session.context.role,session.principal,Number(q.get("owner_offset"))||0),{headers});}
if(q.get("directory")==="1"){
- const query=(q.get("q")??"").toLowerCase().trim(),tools=msoCapabilityRuntime.list(maxScope()).filter((tool)=>!query||`${tool.name} ${tool.description} ${tool.scope}`.toLowerCase().includes(query)).slice(0,150);
+ const authority=session.context.role==="viewer"?{scope:"read" as const,allowedTools:undefined}:await workflowExecutionContext({principal:session.principal,scope:maxScope(),capabilities:msoCapabilityRuntime});
+ const query=(q.get("q")??"").toLowerCase().trim(),tools=msoCapabilityRuntime.list(authority.scope).filter((tool)=>(!authority.allowedTools||authority.allowedTools.includes(tool.name))&&(!query||`${tool.name} ${tool.description} ${tool.scope}`.toLowerCase().includes(query))).slice(0,150);
const operator=roleAtLeast(session.context.role,"operator");
const [graphs,sessions,projectResult,skillResult]=await Promise.all([listWorkflowGraphs(session.principal),listAgentSessions(session.principal,50),operator?listProjects({query:query||undefined,limit:100}):Promise.resolve(null),operator?catalogSkillsDetailed():Promise.resolve(null)]);
const projects=projectResult?.projects.map((row)=>({id:row.id,name:row.name,...(row.packageName?{packageName:row.packageName}:{}),...(row.packageVersion?{packageVersion:row.packageVersion}:{}),...(row.git?.branch?{branch:row.git.branch}:{}),...(row.git?.head?{head:row.git.head}:{})}))??[];
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index e7daea09..5919bd9e 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -4,6 +4,12 @@
Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;
this is the *what*, and it is what Settings → Account → About shows as “What's new”.
+## 2026-10-09
+
+**Fixed**
+
+- `security` close remaining repository scan trust boundaries
+
## 2026-10-08
**Fixed**
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 89f50122..a53016eb 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,11 @@
+## 2026-10-09: Close the seven remaining repository-scan trust boundaries
+
+The October 8 scan at `fe9d66ed` identified seven separate gaps. Workflow Operator grants now intersect caller tool/argument restrictions with reviewed bounded app actions and recheck the live role per node; both directories reflect the effective authority. A2A applies the live deployment ceiling at dispatch, every model round and every tool call. Fresh installs fetch the exact requested branch/tag/commit and stop on failure, with verified bootstrap hashes refreshed.
+
+Filesystem reads inspect opened handles and streams retain those handles. Writes, mkdir, copy, move, recursive delete, enumeration and uploads hold directory descriptors; ZIP reads create a bounded credential-filtered private snapshot. Canonical configured roots do not gain authority when replaced with symlinks. Official Linux/WSL and macOS/Termux Linux guests provide the required descriptor primitives; unsupported native hosts fail closed. Managed-app cookies are HTTPS host-only `__Host-` cookies; legacy/duplicate names are refused and existing app sessions may need a new login. OAuth discovery ignores untrusted forwarded authority and is not cacheable. Local-agent SSE retains signed-session authority, checks before delivery and during idle periods, bounds its queue and releases subscriptions/timers on closure.
+
+Regression tests exercise real ancestor exchanges, protected credential exchanges, pinned downloads/uploads, exact tag/raw-commit and missing-ref installations, both A2A transports and in-flight ceiling changes, Operator capability denial, cookie shadowing and signed-session revocation/demotion/logout/expiry/epoch rotation. Cloud reassessment is unavailable while the service reports exhausted credits; historical findings are not marked closed by local evidence. Runtime deployment requires the repository release path and a matching live build identity.
+
## 2026-10-08: Remove duplicate macOS chrome values from components
The user's SSOT/DRY follow-up exposed a real duplicate: menu width lived separately in placement metrics and CSS, and the macOS row height estimate had a separate h-6 class. One macOS geometry definition now feeds placement plus menu-bar/context/submenu widths and context row heights, retaining the 44px coarse-pointer floor. The macOS stylesheet owns common chrome font size, semantic weights and titlebar heights; JSX no longer repeats those reference values. Palette/material remain scoped to the skin and existing menu/window components still own behavior. A rendered submenu regression changes supplied geometry and proves that both panel and rows follow it; browser checks cover dropdown/context/widget widths, typography, themes, keyboard, bounds, touch and the Windows round trip. Menu width measurement waits for the existing opening animation to settle, matching the established context-menu geometry check; it never relaxes the 244px contract. No global primitive, app action, dependency or gate budget changed. Overall Figma migration progress remains unquantified until the remaining component inventory and acceptance scope are mapped; four completed incremental packages do not establish full-view fidelity.
diff --git a/lib/a2a/inbound-agent.test.ts b/lib/a2a/inbound-agent.test.ts
index 8a52a18f..ea8782a5 100644
--- a/lib/a2a/inbound-agent.test.ts
+++ b/lib/a2a/inbound-agent.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
prepare: vi.fn(async () => ({
@@ -24,8 +24,26 @@ const capabilities = {
};
const { runInboundA2AAgent } = await import("./inbound-agent");
+afterEach(() => { vi.unstubAllEnvs(); vi.clearAllMocks(); });
describe("inbound A2A model boundary", () => {
+ it("rechecks a lowered deployment ceiling after the model selects an exec tool", async () => {
+ vi.stubEnv("OS_MCP_MAX_SCOPE", "exec");
+ let turn = 0;
+ mocks.stream.mockImplementation(async ({ tools, emit }) => {
+ if (turn++ === 0) {
+ expect(tools.map((tool: { name: string }) => tool.name)).toContain("exec_run");
+ vi.stubEnv("OS_MCP_MAX_SCOPE", "read");
+ emit("tool_use", { id: "denied", name: "exec_run", input: {} });
+ } else {
+ expect(tools.map((tool: { name: string }) => tool.name)).not.toContain("exec_run");
+ emit("delta", "denied safely");
+ }
+ });
+ const result = await runInboundA2AAgent({ prompt: "run", scope: "exec", principal: "a2a:test", taskId: "lowered", signal: new AbortController().signal, capabilities });
+ expect(result.text).toBe("denied safely");
+ expect(mocks.invoke).not.toHaveBeenCalled();
+ });
it("hides owner memory and higher-scope tools while isolating workflows by task session", async () => {
let turn = 0;
mocks.stream.mockImplementation(async ({ tools, system, emit }) => {
diff --git a/lib/a2a/inbound-agent.ts b/lib/a2a/inbound-agent.ts
index 570efbe3..b208b612 100644
--- a/lib/a2a/inbound-agent.ts
+++ b/lib/a2a/inbound-agent.ts
@@ -1,4 +1,5 @@
import { allows, type Scope } from "@/lib/capabilities/scope";
+import { clampScope } from "@/lib/capabilities/scope-policy";
import type { CapabilityRuntime } from "@/lib/capabilities/runtime";
import {
prepareSelectedModel,
@@ -7,9 +8,7 @@ import {
import type { OaMsg, OaTool, OaToolUse } from "@/lib/ai/openai-stream";
import type { AgentSession } from "@/lib/agent/session-types";
import { buildMemoryContext } from "@/lib/agent/memory-context.mjs";
-const MAX_ROUNDS = 10;
-const MAX_RESULT_BYTES = 64 * 1024;
-const MAX_OUTPUT_BYTES = 64 * 1024;
+const MAX_ROUNDS = 10, MAX_RESULT_BYTES = 64 * 1024, MAX_OUTPUT_BYTES = 64 * 1024;
const FIXED_WORKFLOW_DENY = new Set(["workflow_start", "workflow_finish", "workflow_cancel", "local_agent_standby"]);
const EXTERNAL_TOOL_DENY = new Set([
"agent_session_current",
@@ -140,7 +139,6 @@ export async function runInboundA2AAgent(input: {
toolCalls: Array<{ name: string; ok: boolean }>;
}> {
const prepared = await prepareSelectedModel();
- const tools = modelTools(input.capabilities, input.scope, input.executionContext?.fixedWorkflow === true);
const messages: OaMsg[] = [
...sessionHistory(input.session),
{ role: "user", text: input.prompt },
@@ -149,6 +147,8 @@ export async function runInboundA2AAgent(input: {
let output = "";
for (let round = 1; round <= MAX_ROUNDS; round += 1) {
+ const scope = clampScope(input.scope);
+ const tools = modelTools(input.capabilities, scope, input.executionContext?.fixedWorkflow === true);
if (input.signal.aborted)
throw input.signal.reason instanceof Error
? input.signal.reason
@@ -159,7 +159,7 @@ export async function runInboundA2AAgent(input: {
prepared,
messages,
tools,
- system: inboundSystem(input.scope, input.session, input.prompt),
+ system: inboundSystem(scope, input.session, input.prompt),
signal: input.signal,
emit(event, data) {
if (event === "delta") {
@@ -176,8 +176,9 @@ export async function runInboundA2AAgent(input: {
const results: { id: string; content: string; isError?: boolean }[] = [];
for (const call of uses) {
- const tool = input.capabilities.list(input.scope).find((entry) => entry.name === call.name);
- if (!tool || EXTERNAL_TOOL_DENY.has(call.name) || !allows(input.scope, tool.scope)) {
+ const effectiveScope = clampScope(input.scope);
+ const tool = input.capabilities.list(effectiveScope).find((entry) => entry.name === call.name);
+ if (!tool || EXTERNAL_TOOL_DENY.has(call.name) || !allows(effectiveScope, tool.scope)) {
results.push({
id: call.id,
content: "error: tool is unavailable to this A2A credential",
@@ -189,7 +190,7 @@ export async function runInboundA2AAgent(input: {
const invoked = await input.capabilities.invoke({
name: call.name,
args: call.input ?? {},
- scope: input.scope,
+ scope: effectiveScope,
actor: input.principal,
principal: input.principal,
sessionId: input.taskId,
diff --git a/lib/a2a/server.test.ts b/lib/a2a/server.test.ts
index 5c447313..322b2213 100644
--- a/lib/a2a/server.test.ts
+++ b/lib/a2a/server.test.ts
@@ -1,8 +1,7 @@
-import { afterAll, describe, expect, it, vi } from "vitest";
+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import os from "node:os";
import path from "node:path";
-
const root = mkdtempSync(path.join(os.tmpdir(), "mso-a2a-server-"));
process.env.OS_A2A_CREDENTIAL_STORE = path.join(root, "outbound.json");
process.env.OS_A2A_INBOUND_TOKEN_STORE = path.join(root, "inbound.json");
@@ -10,7 +9,6 @@ process.env.OS_A2A_TASK_STORE = path.join(root, "tasks.json");
process.env.OS_A2A_INBOUND_ENABLED = "1";
process.env.OS_PUBLIC_ORIGIN = "https://mso.example.test";
process.env.NEXT_PUBLIC_OS_DEMO = "0";
-
const runner = vi.hoisted(() => vi.fn());
vi.mock("./inbound-agent", () => ({ runInboundA2AAgent: runner }));
const { createA2AInboundToken } = await import("./credentials");
@@ -19,8 +17,8 @@ const { handleA2ARequest } = await import("./server");
const { inboundAgentCard } = await import("./inbound-config");
const capabilities = { list: () => [], invoke: vi.fn(async () => ({ content: [] })) };
const handle = (req: Request) => handleA2ARequest(req, capabilities);
-
afterAll(() => rmSync(root, { recursive: true, force: true }));
+afterEach(() => vi.unstubAllEnvs());
const rpc = (token: string | null, body: object) =>
new Request("https://mso.example.test/a2a/v1", {
@@ -33,6 +31,13 @@ const rpc = (token: string | null, body: object) =>
});
describe("authenticated inbound A2A server", () => {
+ it.each(["SendMessage", "SendStreamingMessage"])("clamps exec credentials before %s task dispatch", async (method) => {
+ const { token } = await createA2AInboundToken(`clamp-${method}`, "exec");
+ vi.stubEnv("OS_MCP_MAX_SCOPE", "read");
+ runner.mockImplementationOnce(async ({ scope }) => { expect(scope).toBe("read"); return { text: "bounded", rounds: 1, toolCalls: [] }; });
+ const response = await handle(rpc(token, { jsonrpc: "2.0", id: method, method, params: { message: { messageId: method, role: "ROLE_USER", parts: [{ text: "inspect", mediaType: "text/plain" }] } } }));
+ expect(await response.text()).toContain('"mso.scope":"read"');
+ });
it("advertises a secured v1 JSONRPC Agent Card only on the configured HTTPS origin", () => {
const card = inboundAgentCard();
expect(card.supportedInterfaces[0]).toEqual({
diff --git a/lib/a2a/server.ts b/lib/a2a/server.ts
index 31d4d83a..ebcdb03f 100644
--- a/lib/a2a/server.ts
+++ b/lib/a2a/server.ts
@@ -4,6 +4,7 @@ import { clientIp } from "@/lib/host/request-ip";
import { resolveAgentSessionOwnerRef } from "@/lib/agent/session-query";
import type { AgentSession } from "@/lib/agent/session-types";
import type { CapabilityRuntime } from "@/lib/capabilities/runtime";
+import { clampScope } from "@/lib/capabilities/scope-policy";
import { a2aInboundOriginForRequest } from "./inbound-config";
import {
cancelA2AActiveTask,
@@ -37,6 +38,7 @@ export async function handleA2ARequest(req: Request, capabilities: CapabilityRun
return a2aJson({ error: "rate_limited" }, 429, { "retry-after": "60" });
const profile = await authenticateA2ARequest(req);
if (!profile) return a2aUnauthorized();
+ profile.scope = clampScope(profile.scope);
if (rateLimited(`a2a.inbound.token:${profile.id}`, 60, 60_000))
return a2aJson({ error: "rate_limited" }, 429, { "retry-after": "60" });
diff --git a/lib/agent/local-agent-stream.test.ts b/lib/agent/local-agent-stream.test.ts
new file mode 100644
index 00000000..8044608d
--- /dev/null
+++ b/lib/agent/local-agent-stream.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { SessionPayload } from "@/lib/auth/session";
+const mocks = vi.hoisted(() => ({device: vi.fn(), policy: vi.fn(), inbox: vi.fn(), update: vi.fn(), subscribe: vi.fn(), unsubscribe: vi.fn()}));
+vi.mock("@/lib/auth/device-store", () => ({getApprovedDevice: mocks.device, currentSessionPolicy: mocks.policy}));
+vi.mock("@/lib/auth/session-cookie", () => ({configuredSessionCookieScope: () => "host"}));
+vi.mock("./local-agent-events", () => ({subscribeLocalAgentMessages: mocks.subscribe}));
+vi.mock("./local-agent-mailbox", () => ({listLocalAgentInbox: mocks.inbox, updateLocalAgentMessageState: mocks.update}));
+import { localAgentStream } from "./local-agent-stream";
+let session: SessionPayload, device: {role: string; approvedAt: number; sessionsRevokedAt?: number} | null, epoch: string;
+let event: (value: unknown) => void;
+beforeEach(() => {
+ vi.useFakeTimers(); vi.resetAllMocks();
+ const now = Date.now(); epoch = "epoch-original-12345";
+ session = {device_id: "device", issued_at: now, expires_at: now + 60_000, cookie_scope: "host", cookie_epoch: epoch};
+ device = {role: "owner", approvedAt: now - 1000};
+ mocks.device.mockImplementation(async () => device);
+ mocks.policy.mockImplementation(async () => ({scope: "host", epoch}));
+ mocks.inbox.mockResolvedValue([]); mocks.update.mockResolvedValue(undefined);
+ mocks.subscribe.mockImplementation((_id, callback) => {event = callback; return mocks.unsubscribe;});
+});
+afterEach(() => vi.useRealTimers());
+async function open() {
+ const abort = new AbortController();
+ const response = localAgentStream("web:device", "session", session, abort.signal);
+ const reader = response.body!.getReader();
+ await vi.advanceTimersByTimeAsync(0);
+ return {reader, abort};
+}
+describe("local-agent SSE live signed-session authority", () => {
+ it.each(["revoked", "demoted", "logout", "expired", "epoch"])("closes before disclosing another message when %s", async (reason) => {
+ const {reader} = await open();
+ event({id: "before", text: "authorized"});
+ expect(new TextDecoder().decode((await reader.read()).value)).toContain("authorized");
+ if (reason === "revoked") device = null;
+ if (reason === "demoted") device!.role = "operator";
+ if (reason === "logout") device!.sessionsRevokedAt = session.issued_at;
+ if (reason === "expired") session.expires_at = Date.now();
+ if (reason === "epoch") epoch = "epoch-rotated-12345";
+ event({id: "after", text: "private-after-revocation"});
+ expect(await reader.read()).toEqual({done: true, value: undefined});
+ expect(mocks.unsubscribe).toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0);
+ });
+ it("closes an idle stream within one second of revocation", async () => {
+ const {reader} = await open(); device = null;
+ await vi.advanceTimersByTimeAsync(1000);
+ expect((await reader.read()).done).toBe(true);
+ expect(mocks.unsubscribe).toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0);
+ });
+ it("rechecks authorization after waiting for durable backlog", async () => {
+ let replay!: (rows: unknown[]) => void;
+ mocks.inbox.mockImplementation(() => new Promise(resolve => {replay = resolve;}));
+ const {reader} = await open(); device = null;
+ replay([{id: "private", state: "pending", text: "secret"}]);
+ expect((await reader.read()).done).toBe(true); expect(mocks.update).not.toHaveBeenCalled();
+ });
+ it.each(["cancel", "abort"])("removes subscriptions and timers on %s", async (how) => {
+ const {reader, abort} = await open();
+ if (how === "cancel") await reader.cancel(); else abort.abort();
+ expect(mocks.unsubscribe).toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0);
+ });
+ it("fails closed on authority-store errors", async () => {
+ const {reader} = await open(); mocks.device.mockRejectedValue(new Error("unavailable"));
+ event({text: "secret"}); expect((await reader.read()).done).toBe(true);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ it("disconnects consumers that do not drain the bounded byte queue", async () => {
+ const {reader} = await open();
+ event({text: "x".repeat(150_000)}); await vi.advanceTimersByTimeAsync(0);
+ event({text: "x".repeat(150_000)}); await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.unsubscribe).toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0);
+ await reader.cancel();
+ });
+});
diff --git a/lib/agent/local-agent-stream.ts b/lib/agent/local-agent-stream.ts
new file mode 100644
index 00000000..1aa8e6fd
--- /dev/null
+++ b/lib/agent/local-agent-stream.ts
@@ -0,0 +1,58 @@
+import { liveSessionAuthorized } from "@/lib/auth/live-authorization";
+import type { SessionPayload } from "@/lib/auth/session";
+import { subscribeLocalAgentMessages } from "./local-agent-events";
+import { listLocalAgentInbox, updateLocalAgentMessageState } from "./local-agent-mailbox";
+
+export function localAgentStream(principal: string, sessionId: string, session: SessionPayload, signal: AbortSignal): Response {
+ const encoder = new TextEncoder();
+ let unsubscribe = () => {};
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
+ let authorityTimer: ReturnType<typeof setInterval> | undefined;
+ let closed = false, pendingBytes = 0;
+ let delivery = Promise.resolve();
+ let end = () => {};
+ const cleanup = () => {
+ closed = true;
+ unsubscribe();
+ clearInterval(heartbeat);
+ clearInterval(authorityTimer);
+ signal.removeEventListener("abort", end);
+ };
+ const stream = new ReadableStream<Uint8Array>({
+ async start(controller) {
+ end = () => { if (closed) return; cleanup(); try { controller.close(); } catch { /* Already closed. */ } };
+ const authorized = async () => {
+ const valid = await liveSessionAuthorized(session, "owner").catch(() => false);
+ if (!valid) end();
+ return valid && !closed;
+ };
+ const send = (frame: string) => {
+ if (closed) return;
+ const bytes = encoder.encode(frame);
+ if ((controller.desiredSize ?? 0) < bytes.byteLength) { end(); return; }
+ try { controller.enqueue(bytes); } catch { end(); }
+ };
+ const deliver = (value: unknown) => {
+ const frame = `event: message\ndata: ${JSON.stringify(value)}\n\n`, bytes = Buffer.byteLength(frame);
+ pendingBytes += bytes;
+ if (pendingBytes > 256 * 1024) { end(); return; }
+ delivery = delivery.then(async () => { if (await authorized()) send(frame); }).finally(() => { pendingBytes -= bytes; });
+ };
+ signal.addEventListener("abort", end, { once: true });
+ if (signal.aborted || !await authorized()) { end(); return; }
+ // Subscribe before replay so racing messages are never missed; clients deduplicate ids.
+ unsubscribe = subscribeLocalAgentMessages(sessionId, deliver);
+ heartbeat = setInterval(() => send(": ping\n\n"), 15_000);
+ authorityTimer = setInterval(() => { void authorized(); }, 1000);
+ try {
+ const backlog = await listLocalAgentInbox(principal, sessionId, { limit: 200 });
+ if (!await authorized()) return;
+ const pendingIds = backlog.filter((row) => row.state !== "read").map((row) => row.id);
+ if (pendingIds.length) await updateLocalAgentMessageState(principal, sessionId, pendingIds, "delivered");
+ for (const row of backlog) deliver({ ...row, state: row.state === "read" ? "read" : "delivered" });
+ } catch { end(); }
+ },
+ cancel: cleanup,
+ }, new ByteLengthQueuingStrategy({ highWaterMark: 256 * 1024 }));
+ return new Response(stream, { headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache, no-transform", "x-accel-buffering": "no", connection: "keep-alive" } });
+}
diff --git a/lib/capabilities/scope-policy.ts b/lib/capabilities/scope-policy.ts
index d1742e04..7fe63f3d 100644
--- a/lib/capabilities/scope-policy.ts
+++ b/lib/capabilities/scope-policy.ts
@@ -1,4 +1,4 @@
-import { SCOPES, type Scope } from "./scope";
+import { SCOPES, scopeRank, type Scope } from "./scope";
/** Deployment ceiling shared by transports and unattended workflow execution. */
export function configuredCapabilityCeiling(): Scope {
@@ -7,3 +7,8 @@ export function configuredCapabilityCeiling(): Scope {
const scope = raw.trim();
return (SCOPES as readonly string[]).includes(scope) ? scope as Scope : "write";
}
+
+export function clampScope(asked: Scope): Scope {
+ const ceiling = configuredCapabilityCeiling();
+ return scopeRank(asked) > scopeRank(ceiling) ? ceiling : asked;
+}
diff --git a/lib/host/fs-archive-snapshot.ts b/lib/host/fs-archive-snapshot.ts
new file mode 100644
index 00000000..02b1e932
--- /dev/null
+++ b/lib/host/fs-archive-snapshot.ts
@@ -0,0 +1,59 @@
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import { descriptorPath, openReadableHandle, pinDirectory, type PinnedDirectory } from "./fs-descriptors";
+import { isCredentialPath } from "./path-credentials";
+import { HostError } from "./host-error";
+
+/** Zip walks only this private snapshot; every source read holds a verified descriptor. */
+export async function snapshotArchive(base: string, names: string[], exclude: string[], destination: string): Promise<void> {
+ const excluded = new Set(exclude), deadline = Date.now() + 60_000;
+ let files = 0, bytes = 0;
+ const charge = (size = 0) => {
+ bytes += size;
+ if (Date.now() > deadline) throw new HostError("Archive snapshot exceeded its time limit");
+ if (files > 50_000) throw new HostError("Archive selection exceeds the 50000 file limit");
+ if (bytes > 512 * 1024 * 1024) throw new HostError("Archive selection exceeds the 512 MiB input limit");
+ };
+ async function copy(parent: PinnedDirectory, name: string, dest: string): Promise<void> {
+ charge();
+ const real = await descriptorPath(parent.handle, false);
+ if (excluded.has(name) || isCredentialPath(path.join(real, name))) return;
+ const source = await parent.child(name);
+ const stat = await fs.lstat(source).catch((error: NodeJS.ErrnoException) => {
+ if (["ENOENT", "EACCES", "EPERM"].includes(error.code ?? "")) return null;
+ throw error;
+ });
+ if (!stat) return;
+ if (stat.isDirectory()) {
+ const dir = await pinDirectory(source, false);
+ try {
+ await fs.mkdir(dest, {mode: 0o700});
+ for (const child of await fs.readdir(`/proc/self/fd/${dir.handle.fd}`)) await copy(dir, child, path.join(dest, child));
+ } finally { await dir.handle.close(); }
+ return;
+ }
+ files++; charge();
+ if (stat.isSymbolicLink()) {await fs.symlink(await fs.readlink(source), dest); return;}
+ if (!stat.isFile()) return;
+ const input = await openReadableHandle(source).catch((error: NodeJS.ErrnoException) => {
+ if (["ENOENT", "EACCES", "EPERM"].includes(error.code ?? "")) return null;
+ throw error;
+ });
+ if (!input) return;
+ let output;
+ try {
+ if (!(await input.stat()).isFile()) throw new HostError("Archive source changed type");
+ output = await fs.open(dest, "wx", 0o600);
+ const chunk = Buffer.alloc(1024 * 1024);
+ while (true) {
+ const {bytesRead} = await input.read(chunk);
+ if (!bytesRead) break;
+ charge(bytesRead);
+ await output.writeFile(chunk.subarray(0, bytesRead));
+ }
+ } finally {await input.close(); await output?.close();}
+ }
+ const root = await pinDirectory(base, false);
+ try {for (const name of new Set(names)) await copy(root, name, path.join(destination, name));}
+ finally {await root.handle.close();}
+}
diff --git a/lib/host/fs-descriptors.ts b/lib/host/fs-descriptors.ts
new file mode 100644
index 00000000..9b70eccc
--- /dev/null
+++ b/lib/host/fs-descriptors.ts
@@ -0,0 +1,54 @@
+import { constants, promises as fs } from "node:fs";
+import type { FileHandle } from "node:fs/promises";
+import path from "node:path";
+import { HostError } from "./host-error";
+import { isCredentialPath } from "./path-credentials";
+import { isUnderRoot, readRootList, writeRootList } from "./path-roots";
+
+const fdPath = (fd: number) => `/proc/self/fd/${fd}`;
+
+/** Validate the object we actually opened, not a pathname that can be exchanged. */
+export async function descriptorPath(handle: FileHandle, write: boolean): Promise<string> {
+ if (process.platform !== "linux") throw new HostError("Secure host filesystem access requires Linux/WSL descriptor support");
+ const real = await fs.realpath(fdPath(handle.fd));
+ if (isCredentialPath(real)) throw new HostError("Access to credential/sensitive files is blocked");
+ for (const root of write ? writeRootList() : readRootList()) {
+ const canonical = path.resolve(/* turbopackIgnore: true */ root);
+ if (isUnderRoot(real, canonical)) return real;
+ }
+ throw new HostError(`Path outside ${write ? "writable" : "readable"} roots`);
+}
+
+export async function openReadableHandle(resolved: string, write = false): Promise<FileHandle> {
+ const handle = await fs.open(resolved, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ try { await descriptorPath(handle, write); return handle; }
+ catch (error) { await handle.close(); throw error; }
+}
+
+export interface PinnedDirectory {
+ handle: FileHandle;
+ child(name: string): Promise<string>;
+}
+
+/** Every child has one basename under a held directory; no mutable ancestor is reopened. */
+export async function pinDirectory(resolved: string, write: boolean, create = false): Promise<PinnedDirectory> {
+ let handle: FileHandle;
+ try { handle = await fs.open(resolved, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); }
+ catch (error) {
+ if (!create || (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ const parent = await pinDirectory(path.dirname(resolved), true, true);
+ try {
+ const target = await parent.child(path.basename(resolved));
+ await fs.mkdir(target, { mode: 0o700 }).catch((error: NodeJS.ErrnoException) => { if (error.code !== "EEXIST") throw error; });
+ handle = await fs.open(target, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
+ } finally { await parent.handle.close(); }
+ }
+ try { await descriptorPath(handle, write); }
+ catch (error) { await handle.close(); throw error; }
+ return { handle, async child(name) {
+ if (!name || name === "." || name === ".." || path.basename(name) !== name || name.includes("\0")) throw new HostError("Invalid item name");
+ const real = await descriptorPath(handle, write);
+ if (isCredentialPath(path.join(/* turbopackIgnore: true */ real, name))) throw new HostError("Access to credential/sensitive files is blocked");
+ return path.join(fdPath(handle.fd), name);
+ } };
+}
diff --git a/lib/host/fs-enumeration.ts b/lib/host/fs-enumeration.ts
index a126b894..d600aea4 100644
--- a/lib/host/fs-enumeration.ts
+++ b/lib/host/fs-enumeration.ts
@@ -4,6 +4,7 @@ import type { FsList } from "@/lib/os-api/types";
import { HostError } from "./host-error";
import { isCredentialPath, resolveReadable, resolveRoots } from "./paths";
import { projectAliasTarget } from "./project-aliases";
+import { descriptorPath, pinDirectory } from "./fs-descriptors";
const MAX_ENTRIES = 10_000, MAX_BYTES = 256 * 1024, TIME_MS = 5_000;
let active = 0;
@@ -33,21 +34,24 @@ async function bounded<T>(signal: AbortSignal | undefined, run: (charge: (bytes?
export async function listDir(requested: string, includeHidden = true, signal?: AbortSignal): Promise<FsList> {
return bounded(signal, async (charge) => {
charge();
- const real = await resolveReadable(requested || "~");
- const entries: FsList["entries"] = [];
- const dir = await fs.opendir(real);
- for await (const e of dir) {
- charge();
- if ((!includeHidden && e.name.startsWith(".")) || isCredentialPath(path.join(real, e.name))) continue;
- const entry = { name: e.name, kind: e.isDirectory() || e.isSymbolicLink() ? "dir" as const : "file" as const, size: 0, ext: e.name.includes(".") ? e.name.split(".").pop() : undefined };
- charge(Buffer.byteLength(JSON.stringify(entry)));
- if (entries.length >= 1000) throw new HostError("Directory exceeds 1000 entries; choose a narrower directory", 413);
- entries.push(entry);
- }
- entries.sort((a, b) => a.kind !== b.kind ? (a.kind === "dir" ? -1 : 1) : a.name.localeCompare(b.name));
- const candidate = path.dirname(real);
- const parent = candidate === real ? null : await resolveReadable(candidate).catch(() => null);
- return { path: real, entries, roots: resolveRoots(), parent };
+ const held = await pinDirectory(await resolveReadable(requested || "~"), false);
+ try {
+ const real = await descriptorPath(held.handle, false);
+ const entries: FsList["entries"] = [];
+ const dir = await fs.opendir(`/proc/self/fd/${held.handle.fd}`);
+ for await (const e of dir) {
+ charge();
+ if ((!includeHidden && e.name.startsWith(".")) || isCredentialPath(path.join(real, e.name))) continue;
+ const entry = { name: e.name, kind: e.isDirectory() || e.isSymbolicLink() ? "dir" as const : "file" as const, size: 0, ext: e.name.includes(".") ? e.name.split(".").pop() : undefined };
+ charge(Buffer.byteLength(JSON.stringify(entry)));
+ if (entries.length >= 1000) throw new HostError("Directory exceeds 1000 entries; choose a narrower directory", 413);
+ entries.push(entry);
+ }
+ entries.sort((a, b) => a.kind !== b.kind ? (a.kind === "dir" ? -1 : 1) : a.name.localeCompare(b.name));
+ const candidate = path.dirname(real);
+ const parent = candidate === real ? null : await resolveReadable(candidate).catch(() => null);
+ return { path: real, entries, roots: resolveRoots(), parent };
+ } finally { await held.handle.close(); }
});
}
@@ -71,20 +75,25 @@ export async function searchFs(query: string, opts: { root?: string; max?: numbe
charge();
const authorizedPath = await resolveReadable(dirPath).catch(() => null);
if (!authorizedPath) return;
- const dir = await fs.opendir(authorizedPath).catch(() => null);
- if (!dir) return;
- for await (const e of dir) {
- charge();
- if (out.length >= max) return;
- const hitPath = path.join(authorizedPath, e.name);
- if (!e.isDirectory() || isCredentialPath(hitPath)) continue;
- if (e.name.toLowerCase().includes(q)) {
- const hit = { name: e.name, path: hitPath, kind: "dir" as const };
- charge(Buffer.byteLength(JSON.stringify(hit)));
- out.push(hit);
+ const held = await pinDirectory(authorizedPath, false).catch(() => null);
+ if (!held) return;
+ try {
+ const real = await descriptorPath(held.handle, false);
+ const dir = await fs.opendir(`/proc/self/fd/${held.handle.fd}`).catch(() => null);
+ if (!dir) return;
+ for await (const e of dir) {
+ charge();
+ if (out.length >= max) return;
+ const hitPath = path.join(real, e.name);
+ if (!e.isDirectory() || isCredentialPath(hitPath)) continue;
+ if (e.name.toLowerCase().includes(q)) {
+ const hit = { name: e.name, path: hitPath, kind: "dir" as const };
+ charge(Buffer.byteLength(JSON.stringify(hit)));
+ out.push(hit);
+ }
+ if (!SEARCH_SKIP.has(e.name) && !e.name.startsWith(".")) await walk(hitPath, depth + 1);
}
- if (!SEARCH_SKIP.has(e.name) && !e.name.startsWith(".")) await walk(hitPath, depth + 1);
- }
+ } finally { await held.handle.close(); }
}
await walk(root, 0);
return out;
diff --git a/lib/host/fs-races.test.ts b/lib/host/fs-races.test.ts
new file mode 100644
index 00000000..507d3da5
--- /dev/null
+++ b/lib/host/fs-races.test.ts
@@ -0,0 +1,82 @@
+import { promises as fs, renameSync, symlinkSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { copy, fileStream, listDir, makeDir, move, readFile, remove, statReadable, writeFile } from "./fs";
+import { readFileBytes } from "./fs-read-bytes";
+import { streamFileInto, uploadInto } from "./fs-upload";
+import { uploadOneGuarded } from "./fs-upload-guarded";
+import { zipStream } from "./fs-zip";
+let base: string, root: string, ancestor: string, outside: string;
+beforeEach(async () => {
+ base = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "mso-fs-race-")));
+ root = path.join(base, "root"); ancestor = path.join(root, "dir"); outside = path.join(base, "outside");
+ await fs.mkdir(ancestor, {recursive: true}); await fs.mkdir(outside);
+ await fs.writeFile(path.join(ancestor, "data.txt"), "authorized");
+ await fs.writeFile(path.join(outside, "data.txt"), "outside-private");
+ vi.stubEnv("OS_FS_READ_ROOTS", root); vi.stubEnv("OS_FS_WRITE_ROOTS", root);
+});
+afterEach(async () => {vi.restoreAllMocks(); vi.unstubAllEnvs(); await fs.rm(base, {recursive: true, force: true});});
+function race(destination = outside) {
+ const open = fs.open.bind(fs); let swapped = false;
+ vi.spyOn(fs, "open").mockImplementation((...args: Parameters<typeof fs.open>) => {
+ if (!swapped && (String(args[0]).startsWith(ancestor) || /^\/proc\/self\/fd\/\d+\/dir$/.test(String(args[0])))) {
+ swapped = true; renameSync(ancestor, `${ancestor}-held`); symlinkSync(destination, ancestor, "dir");
+ }
+ return open(...args);
+ });
+ return () => expect(swapped).toBe(true);
+}
+describe("filesystem authorization against ancestor exchange", () => {
+ it.each(["text", "bytes", "raw", "write", "mkdir", "delete", "copy", "move", "list", "upload", "guarded"])("keeps outside files private and intact for %s", async (operation) => {
+ const swapped = race(), target = path.join(ancestor, "data.txt");
+ const run = async () => {
+ if (operation === "text") return readFile(target);
+ if (operation === "bytes") return readFileBytes(target);
+ if (operation === "raw") {const info = await statReadable(target); await info.handle.close(); return;}
+ if (operation === "write") return writeFile(target, "overwrite");
+ if (operation === "mkdir") return makeDir(path.join(ancestor, "new", "child"));
+ if (operation === "delete") return remove(target);
+ if (operation === "copy") return copy(target, path.join(root, "copied.txt"));
+ if (operation === "move") return move(target, path.join(root, "moved.txt"));
+ if (operation === "list") return listDir(ancestor);
+ if (operation === "guarded") return uploadOneGuarded({dest: ancestor, filename: "data.txt", data: Buffer.from("overwrite")});
+ const result = await uploadInto(ancestor, [{relPath: "data.txt", data: Buffer.from("overwrite")}]);
+ if (result.failed.length) throw new Error("upload refused");
+ };
+ await expect(run()).rejects.toThrow(); swapped();
+ expect(await fs.readFile(path.join(outside, "data.txt"), "utf8")).toBe("outside-private");
+ expect(await fs.readdir(outside)).toEqual(["data.txt"]);
+ });
+ it("does not disclose a credential directory exchanged inside an allowed root", async () => {
+ const secret = path.join(root, ".env-secrets"); await fs.mkdir(secret); await fs.writeFile(path.join(secret, "data.txt"), "credential");
+ race(secret);
+ await expect(readFile(path.join(ancestor, "data.txt"))).rejects.toThrow(/credential/);
+ });
+ it("does not let a replaced configured root grant access to an outside target", async () => {
+ renameSync(root, `${root}-held`); symlinkSync(outside, root, "dir");
+ await expect(readFile(path.join(root, "data.txt"))).rejects.toThrow(/outside readable roots/);
+ });
+ it("refuses an archive source exchanged after selection/preflight", async () => {
+ const swapped = race();
+ await expect(zipStream(root, ["dir"])).rejects.toThrow(); swapped();
+ expect(await fs.readFile(path.join(outside, "data.txt"), "utf8")).toBe("outside-private");
+ });
+ it("streams from the already verified descriptor after the pathname is exchanged", async () => {
+ const info = await statReadable(path.join(ancestor, "data.txt"));
+ renameSync(ancestor, `${ancestor}-held`); symlinkSync(outside, ancestor, "dir");
+ const chunks: Buffer[] = [];
+ for await (const chunk of fileStream(info.handle)) chunks.push(chunk as Buffer);
+ expect(Buffer.concat(chunks).toString()).toBe("authorized");
+ });
+ it("pins an upload destination throughout body consumption and drains the body", async () => {
+ async function* body() {
+ yield Buffer.from("first");
+ renameSync(ancestor, `${ancestor}-held`); symlinkSync(outside, ancestor, "dir");
+ yield Buffer.from("second");
+ }
+ expect(await streamFileInto(ancestor, "new.txt", body())).toBe("ok");
+ expect(await fs.readFile(path.join(`${ancestor}-held`, "new.txt"), "utf8")).toBe("firstsecond");
+ expect(await fs.readdir(outside)).toEqual(["data.txt"]);
+ });
+});
diff --git a/lib/host/fs-read-bytes.ts b/lib/host/fs-read-bytes.ts
index 1111f745..2f78681a 100644
--- a/lib/host/fs-read-bytes.ts
+++ b/lib/host/fs-read-bytes.ts
@@ -1,4 +1,4 @@
-import { promises as fs, constants as fsConstants } from "fs";
+import { openReadableHandle } from "./fs-descriptors";
import { HostError } from "./host-error";
import { resolveReadable } from "./paths";
@@ -7,7 +7,7 @@ export async function readFileBytes(requested: string, maxBytes = 10 * 1024 * 10
const p = await resolveReadable(requested);
let handle;
try {
- handle = await fs.open(p, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ handle = await openReadableHandle(p);
const stat = await handle.stat();
if (!stat.isFile()) throw new HostError(stat.isDirectory() ? "Is a directory" : "Not a regular file");
if (!Number.isFinite(maxBytes) || maxBytes < 1 || stat.size > maxBytes) {
diff --git a/lib/host/fs-recursive.ts b/lib/host/fs-recursive.ts
new file mode 100644
index 00000000..cd3201fa
--- /dev/null
+++ b/lib/host/fs-recursive.ts
@@ -0,0 +1,68 @@
+import { constants, promises as fs } from "node:fs";
+import path from "node:path";
+import { randomUUID } from "node:crypto";
+import { descriptorPath, openReadableHandle, pinDirectory } from "./fs-descriptors";
+import { isAppSecret } from "./path-credentials";
+import { HostError } from "./host-error";
+
+export async function removePinned(target: string): Promise<void> {
+ const stat = await fs.lstat(target);
+ if (!stat.isDirectory()) { await fs.unlink(target); return; }
+ const dir = await pinDirectory(target, true);
+ try {
+ for (const name of await fs.readdir(`/proc/self/fd/${dir.handle.fd}`)) await removePinned(await dir.child(name));
+ await descriptorPath(dir.handle, true);
+ const current = await fs.lstat(target), held = await dir.handle.stat();
+ if (current.dev !== held.dev || current.ino !== held.ino) throw new HostError("Directory changed during removal");
+ await fs.rmdir(target);
+ } finally { await dir.handle.close(); }
+}
+
+export async function copyPinned(source: string, destination: string): Promise<void> {
+ const stat = await fs.lstat(source);
+ if (stat.isDirectory()) {
+ const dir = await pinDirectory(source, true);
+ try {
+ const real = await descriptorPath(dir.handle, true);
+ await fs.mkdir(destination, { mode: stat.mode & 0o777 }).catch((error: NodeJS.ErrnoException) => { if (error.code !== "EEXIST") throw error; });
+ const dest = await pinDirectory(destination, true);
+ try {
+ for (const name of await fs.readdir(`/proc/self/fd/${dir.handle.fd}`)) {
+ if (isAppSecret(path.join(real, name))) continue;
+ await copyPinned(await dir.child(name), await dest.child(name));
+ }
+ } finally { await dest.handle.close(); }
+ } finally { await dir.handle.close(); }
+ return;
+ }
+ if (stat.isSymbolicLink()) {
+ // Copy the link itself; later reads still enforce the target's credential/root boundary.
+ const link = await fs.readlink(source);
+ const target = path.isAbsolute(link) ? link : path.resolve(/* turbopackIgnore: true */ await fs.realpath(/* turbopackIgnore: true */ path.dirname(source)), link);
+ const tmp = `${destination}.tmp-${randomUUID()}`;
+ try { await fs.symlink(target, tmp); await fs.rename(tmp, destination); }
+ finally { await fs.unlink(tmp).catch(() => undefined); }
+ return;
+ }
+ const input = await openReadableHandle(source, true), tmp = `${destination}.tmp-${randomUUID()}`;
+ let output;
+ try {
+ if (!(await input.stat()).isFile()) throw new HostError("Not a regular file");
+ output = await fs.open(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, stat.mode & 0o777);
+ const chunk = Buffer.alloc(1024 * 1024);
+ while (true) {
+ const { bytesRead } = await input.read(chunk);
+ if (!bytesRead) break;
+ let offset = 0;
+ while (offset < bytesRead) {
+ const {bytesWritten} = await output.write(chunk, offset, bytesRead - offset);
+ if (!bytesWritten) throw new HostError("Failed to copy file");
+ offset += bytesWritten;
+ }
+ }
+ await output.close();
+ await fs.rename(tmp, destination);
+ } finally {
+ await input.close(); await output?.close().catch(() => undefined); await fs.unlink(tmp).catch(() => undefined);
+ }
+}
diff --git a/lib/host/fs-upload-guarded.ts b/lib/host/fs-upload-guarded.ts
index 7ab52234..751dc441 100644
--- a/lib/host/fs-upload-guarded.ts
+++ b/lib/host/fs-upload-guarded.ts
@@ -1,9 +1,10 @@
import { createHash, randomUUID } from "crypto";
-import { promises as fs, constants as fsConstants } from "fs";
+import { promises as fs } from "fs";
import path from "path";
import { HostError } from "./host-error";
import { assertUploadTarget } from "./paths";
import { resolveUploadDest } from "./fs-upload";
+import { openReadableHandle, pinDirectory } from "./fs-descriptors";
export type UploadConflictPolicy = "error" | "rename" | "replace";
export type GuardedUploadResult = {
@@ -27,7 +28,7 @@ function safeName(name: string): string {
async function existingHash(full: string): Promise<string | null> {
let handle;
try {
- handle = await fs.open(full, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ handle = await openReadableHandle(full, true);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
if ((error as NodeJS.ErrnoException).code === "ELOOP") throw new HostError("Refusing symlink file");
@@ -87,34 +88,36 @@ export async function uploadOneGuarded(input: {
conflict?: UploadConflictPolicy; expectedSha256?: string;
}): Promise<GuardedUploadResult> {
const destReal = await resolveUploadDest(input.dest), filename = safeName(input.filename);
- const full = path.join(destReal, filename), sha256 = hash(input.data), policy = input.conflict ?? "error";
- await assertUploadTarget(full, destReal);
- await fs.mkdir(path.dirname(full), { recursive: true, mode: 0o700 });
- await assertUploadTarget(full, destReal);
+ const logicalFull = path.join(destReal, filename), sha256 = hash(input.data), policy = input.conflict ?? "error";
+ await assertUploadTarget(logicalFull, destReal);
+ const parent = await pinDirectory(destReal, true);
+ try {
+ const full = await parent.child(filename);
- let previous = await existingHash(full);
- if (previous === null) {
- if (policy === "replace") throw new HostError("replace requires an existing destination and expected_sha256");
- if (await createExclusive(full, input.data)) return { path: full, filename, status: "created", sha256 };
- previous = await existingHash(full);
- }
- if (previous === sha256) return { path: full, filename, status: "unchanged", sha256, previousSha256: previous };
- if (policy === "error") throw new HostError("destination already exists with different content; choose rename or guarded replace");
+ let previous = await existingHash(full);
+ if (previous === null) {
+ if (policy === "replace") throw new HostError("replace requires an existing destination and expected_sha256");
+ if (await createExclusive(await parent.child(filename), input.data)) return { path: logicalFull, filename, status: "created", sha256 };
+ previous = await existingHash(full);
+ }
+ if (previous === sha256) return { path: logicalFull, filename, status: "unchanged", sha256, previousSha256: previous };
+ if (policy === "error") throw new HostError("destination already exists with different content; choose rename or guarded replace");
- if (policy === "rename") {
- const alternate = renamed(filename, sha256), alternateFull = path.join(/*turbopackIgnore: true*/ destReal, alternate);
- await assertUploadTarget(alternateFull, destReal);
- const alternateHash = await existingHash(alternateFull);
- if (alternateHash === sha256) return { path: alternateFull, filename: alternate, status: "unchanged", sha256, previousSha256: alternateHash };
- if (alternateHash !== null || !(await createExclusive(alternateFull, input.data))) throw new HostError("deterministic renamed destination already exists with different content");
- return { path: alternateFull, filename: alternate, status: "renamed", sha256, previousSha256: previous ?? undefined };
- }
+ if (policy === "rename") {
+ const alternate = renamed(filename, sha256), alternateFull = await parent.child(alternate), logicalAlternate = path.join(/* turbopackIgnore: true */ destReal, alternate);
+ await assertUploadTarget(logicalAlternate, destReal);
+ const alternateHash = await existingHash(alternateFull);
+ if (alternateHash === sha256) return { path: logicalAlternate, filename: alternate, status: "unchanged", sha256, previousSha256: alternateHash };
+ if (alternateHash !== null || !(await createExclusive(await parent.child(alternate), input.data))) throw new HostError("deterministic renamed destination already exists with different content");
+ return { path: logicalAlternate, filename: alternate, status: "renamed", sha256, previousSha256: previous ?? undefined };
+ }
- const expected = input.expectedSha256?.toLowerCase();
- if (!expected || !SHA_RE.test(expected)) throw new HostError("replace requires expected_sha256 from a prior read/export");
- if (previous !== expected) throw new HostError("destination changed since inspection; refresh its SHA-256 before replacing");
- const rechecked = await existingHash(full);
- if (rechecked !== expected) throw new HostError("destination changed during replacement; retry only after a fresh read/export");
- await replaceAtomic(full, input.data);
- return { path: full, filename, status: "replaced", sha256, previousSha256: previous ?? undefined };
+ const expected = input.expectedSha256?.toLowerCase();
+ if (!expected || !SHA_RE.test(expected)) throw new HostError("replace requires expected_sha256 from a prior read/export");
+ if (previous !== expected) throw new HostError("destination changed since inspection; refresh its SHA-256 before replacing");
+ const rechecked = await existingHash(full);
+ if (rechecked !== expected) throw new HostError("destination changed during replacement; retry only after a fresh read/export");
+ await replaceAtomic(await parent.child(filename), input.data);
+ return { path: logicalFull, filename, status: "replaced", sha256, previousSha256: previous ?? undefined };
+ } finally { await parent.handle.close(); }
}
diff --git a/lib/host/fs-upload.ts b/lib/host/fs-upload.ts
index 313f784e..8421abe7 100644
--- a/lib/host/fs-upload.ts
+++ b/lib/host/fs-upload.ts
@@ -3,12 +3,12 @@
// enforces the SAME credential/sensitive denylist + realpath-bounds as
// writeFile/move/copy (so an upload can't write ~/.ssh/authorized_keys or escape
// the dest through a symlinked subdir). Split out of fs.ts for single responsibility.
-import { promises as fs, createWriteStream } from "fs";
+import { promises as fs } from "fs";
import { randomBytes } from "crypto";
-import { once } from "events";
import path from "path";
import { HostError } from "./host-error";
import { assertUploadTarget, safeWritePath } from "./paths";
+import { pinDirectory, type PinnedDirectory } from "./fs-descriptors";
const MAX_UPLOAD = 100 * 1024 * 1024; // 100 MiB per file
@@ -35,19 +35,22 @@ export async function uploadInto(
failed.push(relPath);
continue;
}
- const tmp = privateTempPath(full);
+ let parent: PinnedDirectory | undefined, tmp: string | undefined;
try {
- await fs.mkdir(path.dirname(full), { recursive: true, mode: 0o700 });
- await assertUploadTarget(full, destReal); // parent may have appeared since the first check
+ parent = await pinDirectory(path.dirname(full), true, true);
+ const target = await parent.child(path.basename(full));
+ tmp = privateTempPath(target);
await fs.writeFile(tmp, data, { mode: 0o600, flag: "wx" });
await fs.chmod(tmp, 0o644);
- if (options.overwrite === false) await fs.link(tmp, full);
- else await fs.rename(tmp, full);
+ const destination = await parent.child(path.basename(full));
+ if (options.overwrite === false) await fs.link(tmp, destination);
+ else await fs.rename(tmp, destination);
written++;
} catch {
failed.push(relPath);
} finally {
- await fs.rm(tmp, { force: true }).catch(() => {});
+ if (tmp) await fs.rm(tmp, { force: true }).catch(() => {});
+ await parent?.handle.close();
}
}
return { written, failed };
@@ -59,6 +62,8 @@ export async function uploadInto(
export async function resolveUploadDest(dest: string): Promise<string> {
const destReal = await safeWritePath(dest, true);
if (!(await fs.stat(destReal)).isDirectory()) throw new HostError("Destination is not a directory");
+ const held = await pinDirectory(destReal, true);
+ await held.handle.close();
return destReal;
}
@@ -83,35 +88,31 @@ export async function streamFileInto(
return "bad-path";
}
- await fs.mkdir(path.dirname(full), { recursive: true, mode: 0o700 });
- try { await assertUploadTarget(full, destReal); }
+ let parent: PinnedDirectory;
+ try { parent = await pinDirectory(path.dirname(full), true, true); }
catch { await drain(body); return "bad-path"; }
- const tmp = privateTempPath(full);
- const out = createWriteStream(tmp, { mode: 0o600, flags: "wx" });
- let bytes = 0;
- let tooLarge = false;
+ let tmp: string | undefined, handle: Awaited<ReturnType<typeof fs.open>> | undefined;
+ let bytes = 0, tooLarge = false, failed = false;
try {
- // ONE pass over the body iterator: keep consuming after the cap is hit so the
- // remaining bytes drain (parser advances), but stop writing to disk.
+ tmp = privateTempPath(await parent.child(path.basename(full)));
+ try { handle = await fs.open(/* turbopackIgnore: true */ tmp, "wx", 0o600); } catch { failed = true; }
for await (const chunk of body) {
- if (tooLarge) continue; // drain-only past the cap
+ if (tooLarge || failed) continue;
bytes += chunk.byteLength;
if (bytes > MAX_UPLOAD) { tooLarge = true; continue; }
- if (!out.write(chunk)) await once(out, "drain");
+ try { await handle!.writeFile(chunk); } catch { failed = true; }
}
- await new Promise<void>((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())));
- } catch {
- out.destroy();
- await fs.rm(tmp, { force: true });
- throw new HostError("Failed to write upload");
- }
- if (tooLarge) {
- await fs.rm(tmp, { force: true });
- return "too-large";
+ if (tooLarge) return "too-large";
+ if (failed) throw new HostError("Failed to write upload");
+ await handle!.chmod(0o644);
+ await handle!.close(); handle = undefined;
+ await fs.rename(tmp, await parent.child(path.basename(full)));
+ return "ok";
+ } finally {
+ await handle?.close().catch(() => undefined);
+ if (tmp) await fs.rm(tmp, { force: true }).catch(() => undefined);
+ await parent.handle.close();
}
- await fs.chmod(tmp, 0o644);
- await fs.rename(tmp, full);
- return "ok";
}
function privateTempPath(full: string): string {
diff --git a/lib/host/fs-zip.test.ts b/lib/host/fs-zip.test.ts
index eda43712..80ee9289 100644
--- a/lib/host/fs-zip.test.ts
+++ b/lib/host/fs-zip.test.ts
@@ -86,6 +86,11 @@ describe("zipStream against the real zip binary", () => {
expect(entries(await read(await zipStream(base, ["keep.txt"])))).toContain("keep.txt");
} finally { temporary.mockRestore(); }
});
+ it("reserves disk space for both the private snapshot and generated archive", async () => {
+ const capacity = vi.spyOn(fsp, "statfs").mockResolvedValueOnce({bavail: 64 * 1024 * 1024 + 6, bsize: 1} as never);
+ try {await expect(zipStream(base, ["keep.txt"])).rejects.toThrow(/temporary disk space/);}
+ finally {capacity.mockRestore();}
+ });
it("force-strips nested loose private keys from recursive archives", async () => {
const dir = path.join(base, "secrets-fixture");
diff --git a/lib/host/fs-zip.ts b/lib/host/fs-zip.ts
index f02678c9..4bf7f5c3 100644
--- a/lib/host/fs-zip.ts
+++ b/lib/host/fs-zip.ts
@@ -21,6 +21,7 @@ import os from "os";
import path from "path";
import type { Readable } from "stream";
import { HostError } from "./host-error";
+import { snapshotArchive } from "./fs-archive-snapshot";
import { appDir, isCredentialPath, looseCredentialExcludes, resolveReadable, sensitiveExcludes } from "./paths";
const ZIP_MAX_INPUT_BYTES = 512 * 1024 * 1024;
@@ -55,7 +56,7 @@ async function assertArchiveBudget(realBase: string, names: string[], exclude: s
}
const statfs = await fsp.statfs(os.tmpdir());
const free = Number(statfs.bavail) * Number(statfs.bsize);
- if (!Number.isFinite(free) || free < bytes + 64 * 1024 * 1024) {
+ if (!Number.isFinite(free) || free < bytes * 2 + 64 * 1024 * 1024) {
throw new HostError("Insufficient temporary disk space for archive generation");
}
}
@@ -92,11 +93,16 @@ export async function zipStream(
for (const n of exclude) assertSafeName(n);
if (zipGate.__msoZipActive) throw new HostError("Another archive is already being generated");
zipGate.__msoZipActive = true;
- let tmpDir: string;
+ let tmpDir = "";
+ let snapshot = "";
try {
await assertArchiveBudget(real, names, exclude);
tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), "os-zip-"));
+ snapshot = path.join(tmpDir, "snapshot");
+ await fsp.mkdir(snapshot, {mode: 0o700});
+ await snapshotArchive(real, names, exclude, snapshot);
} catch (error) {
+ if (tmpDir) await fsp.rm(tmpDir, {recursive: true, force: true});
zipGate.__msoZipActive = false;
throw error;
}
@@ -138,7 +144,7 @@ export async function zipStream(
const NOTHING_TO_DO = 12;
try {
await new Promise<void>((resolve, reject) => {
- const child = spawn("zip", args, { cwd: real, stdio: "ignore" });
+ const child = spawn("zip", args, { cwd: snapshot, stdio: "ignore" });
let timedOut = false;
const timer = setTimeout(() => { timedOut = true; child.kill("SIGKILL"); }, ZIP_PROCESS_TIMEOUT_MS);
child.on("error", (error) => { clearTimeout(timer); reject(error); }); // missing binary / spawn fail
diff --git a/lib/host/fs.test.ts b/lib/host/fs.test.ts
index bcb61516..35df30cf 100644
--- a/lib/host/fs.test.ts
+++ b/lib/host/fs.test.ts
@@ -7,6 +7,8 @@ import {
rmSync,
symlinkSync,
writeFileSync,
+ promises as fs,
+ readlinkSync,
} from "node:fs";
import os from "node:os";
import path from "node:path";
@@ -166,6 +168,38 @@ describe("remove", () => {
});
describe("recursive credential mutation guard", () => {
+ it("copies nested files and symlinks while retaining the symlink target", async () => {
+ useRoots(readRoot, writeRoot);
+ const source = path.join(writeRoot, "copy-source"), dest = path.join(writeRoot, "copy-result");
+ mkdirSync(path.join(source, "nested"), {recursive: true});
+ writeFileSync(path.join(source, "nested", "text.txt"), "payload");
+ symlinkSync("nested/text.txt", path.join(source, "alias"));
+ await copy(source, dest);
+ expect(readFileSync(path.join(dest, "nested", "text.txt"), "utf8")).toBe("payload");
+ expect(readFileSync(path.join(dest, "alias"), "utf8")).toBe("payload");
+ expect(readlinkSync(path.join(dest, "alias"))).toBe(path.join(source, "nested", "text.txt"));
+ await remove(dest);
+ expect(existsSync(dest)).toBe(false);
+ expect(readFileSync(path.join(source, "nested", "text.txt"), "utf8")).toBe("payload");
+ });
+ it("refuses a symlink directory destination without copying into its outside target", async () => {
+ useRoots(readRoot, writeRoot);
+ const source = path.join(writeRoot, "copy-dir"), dest = path.join(writeRoot, "copy-link");
+ mkdirSync(source); writeFileSync(path.join(source, "fresh.txt"), "payload"); symlinkSync(outside, dest);
+ await expect(copy(source, dest)).rejects.toThrow();
+ expect(existsSync(path.join(outside, "fresh.txt"))).toBe(false);
+ });
+ it.each([false, true])("keeps cross-device move source until the copy commits (copy failure=%s)", async (failure) => {
+ useRoots(readRoot, writeRoot);
+ const source = path.join(writeRoot, `cross-src-${failure}.txt`), dest = path.join(writeRoot, `cross-dst-${failure}.txt`);
+ writeFileSync(source, "payload");
+ const rename = vi.spyOn(fs, "rename").mockRejectedValueOnce(Object.assign(new Error("cross-device"), {code: "EXDEV"}));
+ if (failure) rename.mockRejectedValueOnce(Object.assign(new Error("copy failed"), {code: "EACCES"}));
+ try {
+ if (failure) {await expect(move(source, dest)).rejects.toThrow("copy failed"); expect(readFileSync(source, "utf8")).toBe("payload"); expect(existsSync(dest)).toBe(false);}
+ else {await move(source, dest); expect(existsSync(source)).toBe(false); expect(readFileSync(dest, "utf8")).toBe("payload");}
+ } finally {rename.mockRestore();}
+ });
it("refuses copy, move, and delete when a nested loose credential exists", async () => {
useRoots(readRoot, writeRoot);
const source = path.join(writeRoot, "credential-tree");
diff --git a/lib/host/fs.ts b/lib/host/fs.ts
index 52e7c7ce..5dadd5e1 100644
--- a/lib/host/fs.ts
+++ b/lib/host/fs.ts
@@ -1,12 +1,15 @@
// SERVER-ONLY. Host filesystem ops behind /api/v1/fs/*. Reads follow READ
// roots (browse), mutations follow WRITE roots (see paths.ts). Returns the
// os-rr shapes directly so route handlers are thin.
-import { promises as fs, constants as fsConstants, createReadStream, type ReadStream } from "fs";
+import { promises as fs, constants as fsConstants, type ReadStream } from "fs";
+import type { FileHandle } from "node:fs/promises";
+import path from "node:path";
+import { openReadableHandle, pinDirectory } from "./fs-descriptors";
+import { copyPinned, removePinned } from "./fs-recursive";
import { randomUUID } from "node:crypto";
import type { FsUsage } from "@/lib/os-api/types";
import { HostError } from "./host-error";
import {
- appSecretCopyFilter,
assertNoAppSecretDescendants,
assertNoCredentialDescendants,
assertNoSensitiveDescendants,
@@ -22,7 +25,7 @@ export async function readFile(requested: string): Promise<string> {
const p = await resolveReadable(requested);
let handle;
try {
- handle = await fs.open(p, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ handle = await openReadableHandle(p);
const stat = await handle.stat();
if (!stat.isFile()) throw new HostError(stat.isDirectory() ? "Is a directory" : "Not a regular file");
if (stat.size > 5_000_000) throw new HostError("File too large to read (max 5 MiB)");
@@ -38,22 +41,29 @@ export async function readFile(requested: string): Promise<string> {
export async function writeFile(requested: string, content: string): Promise<void> {
const p = await safeWritePath(requested, false);
await assertNotRoot(p);
- const tmp = `${p}.tmp-${randomUUID()}`;
- const handle = await fs.open(tmp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 0o600);
- try { await handle.writeFile(content ?? ""); await handle.close(); await fs.rename(tmp, p); }
- finally { await handle.close().catch(() => undefined); await fs.unlink(tmp).catch(() => undefined); }
+ const parent = await pinDirectory(path.dirname(p), true);
+ let handle, tmp: string | undefined;
+ try {
+ tmp = await parent.child(`${path.basename(p)}.tmp-${randomUUID()}`);
+ handle = await fs.open(tmp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 0o600);
+ await handle.writeFile(content ?? ""); await handle.close();
+ await fs.rename(tmp, await parent.child(path.basename(p)));
+ } finally { await handle?.close().catch(() => undefined); if (tmp) await fs.unlink(tmp).catch(() => undefined); await parent.handle.close(); }
}
export async function makeDir(requested: string): Promise<void> {
const p = await safeMkdirPath(requested);
- await fs.mkdir(p, { recursive: true });
+ const dir = await pinDirectory(p, true, true);
+ await dir.handle.close();
}
export async function remove(requested: string): Promise<void> {
const p = await safeWritePath(requested, true);
await assertNotRoot(p);
await assertNoCredentialDescendants(p);
- await fs.rm(p, { recursive: true, force: true });
+ const parent = await pinDirectory(path.dirname(p), true);
+ try { await removePinned(await parent.child(path.basename(p))); }
+ finally { await parent.handle.close(); }
}
export async function move(from: string, to: string): Promise<void> {
@@ -63,16 +73,18 @@ export async function move(from: string, to: string): Promise<void> {
assertNoAppSecretDescendants(src); // the cockpit's own .env* under a parent
await assertNoCredentialDescendants(src); // loose id_* / *.pem anywhere below
const dest = await safeWritePath(to, false);
+ const sourceParent = await pinDirectory(path.dirname(src), true);
+ let destParent;
try {
- await fs.rename(src, dest);
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code === "EXDEV") {
- await fs.cp(src, dest, { recursive: true });
- await fs.rm(src, { recursive: true, force: true });
- } else {
- throw err;
+ destParent = await pinDirectory(path.dirname(dest), true);
+ const source = await sourceParent.child(path.basename(src)), target = await destParent.child(path.basename(dest));
+ try { await fs.rename(source, target); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EXDEV") throw error;
+ await copyPinned(source, target);
+ await removePinned(await sourceParent.child(path.basename(src)));
}
- }
+ } finally { await sourceParent.handle.close(); await destParent?.handle.close(); }
}
export async function copy(from: string, to: string): Promise<void> {
@@ -84,7 +96,13 @@ export async function copy(from: string, to: string): Promise<void> {
const dest = await safeWritePath(to, false);
// Skip the cockpit's own .env* rather than refuse the copy — on the default
// roots APP_DIR sits under ~/projects, so refusing would block copying it.
- await fs.cp(src, dest, { recursive: true, filter: appSecretCopyFilter(src) });
+ if (dest === src || dest.startsWith(src + path.sep)) throw new HostError("Cannot copy a directory into itself");
+ const sourceParent = await pinDirectory(path.dirname(src), true);
+ let destParent;
+ try {
+ destParent = await pinDirectory(path.dirname(dest), true);
+ await copyPinned(await sourceParent.child(path.basename(src)), await destParent.child(path.basename(dest)));
+ } finally { await sourceParent.handle.close(); await destParent?.handle.close(); }
}
export async function usage(requested: string): Promise<FsUsage> {
@@ -125,14 +143,17 @@ export function mimeFor(p: string): string {
// Resolve + stat a readable file (within READ roots) for byte streaming.
export async function statReadable(
requested: string,
-): Promise<{ path: string; size: number; mime: string }> {
+): Promise<{ path: string; size: number; mime: string; handle: FileHandle }> {
const p = await resolveReadable(requested);
- const st = await fs.stat(p);
- if (st.isDirectory()) throw new HostError("Is a directory");
- return { path: p, size: st.size, mime: mimeFor(p) };
+ const handle = await openReadableHandle(p);
+ try {
+ const st = await handle.stat();
+ if (!st.isFile()) throw new HostError(st.isDirectory() ? "Is a directory" : "Not a regular file");
+ return { path: p, size: st.size, mime: mimeFor(p), handle };
+ } catch (error) { await handle.close(); throw error; }
}
-// Node read stream for a (pre-resolved) path, optionally a byte range.
-export function fileStream(p: string, start?: number, end?: number): ReadStream {
- return start !== undefined ? createReadStream(p, { start, end }) : createReadStream(p);
+// Transfer the verified handle to the stream, optionally for a byte range.
+export function fileStream(handle: FileHandle, start?: number, end?: number): ReadStream {
+ return handle.createReadStream({ autoClose: true, ...(start !== undefined ? { start, end } : {}) });
}
diff --git a/lib/host/path-recursive.ts b/lib/host/path-recursive.ts
index 990c1338..a136cc40 100644
--- a/lib/host/path-recursive.ts
+++ b/lib/host/path-recursive.ts
@@ -3,6 +3,7 @@ import path from "path";
import { HostError } from "./host-error";
import { appDir, isAppSecret, isCredentialPath, SENSITIVE_HOME } from "./path-credentials";
import { homeDir, isUnderRoot } from "./path-roots";
+import { descriptorPath, pinDirectory } from "./fs-descriptors";
/** The app's own secrets sitting UNDER `realBase` — empty when APP_DIR is not a
* descendant, or holds no secrets. The per-path gate is exact-or-under, so a
@@ -66,27 +67,30 @@ export async function assertNoCredentialDescendants(
const rootStat = await fs.lstat(realBase).catch(() => null);
if (!rootStat?.isDirectory()) return;
- const stack = [realBase];
- while (stack.length) {
- const dir = stack.pop()!;
- let entries: import("fs").Dirent[];
+ async function inspect(dir: string): Promise<void> {
+ const pinned = await pinDirectory(dir, true);
try {
- entries = await fs.readdir(dir, { withFileTypes: true });
- } catch (error) {
- throw new HostError(`Refusing recursive mutation: cannot inspect ${path.relative(realBase, dir) || "."}`);
- }
- for (const entry of entries) {
- const child = path.join(dir, entry.name);
- const credential = isCredentialPath(child);
- const ignoredAppSecret = options.ignoreAppSecrets === true && isAppSecret(child);
- if (credential && !ignoredAppSecret) {
- throw new HostError(
- `Refusing: this directory contains a credential path (${path.relative(realBase, child)})`,
- );
+ const real = await descriptorPath(pinned.handle, true);
+ let entries: import("fs").Dirent[];
+ try {
+ entries = await fs.readdir(`/proc/self/fd/${pinned.handle.fd}`, { withFileTypes: true });
+ } catch (error) {
+ throw new HostError(`Refusing recursive mutation: cannot inspect ${path.relative(realBase, dir) || "."}`);
}
- if (entry.isDirectory()) stack.push(child);
- }
+ for (const entry of entries) {
+ const child = path.join(real, entry.name);
+ const credential = isCredentialPath(child);
+ const ignoredAppSecret = options.ignoreAppSecrets === true && isAppSecret(child);
+ if (credential && !ignoredAppSecret) {
+ throw new HostError(
+ `Refusing: this directory contains a credential path (${path.relative(realBase, child)})`,
+ );
+ }
+ if (entry.isDirectory()) await inspect(await pinned.child(entry.name));
+ }
+ } finally { await pinned.handle.close(); }
}
+ await inspect(realBase);
}
// The app's own `.env*` needed the narrower fix the ~/ list can't give: on the
diff --git a/lib/managed-apps/proxy-cookie-browser.test.ts b/lib/managed-apps/proxy-cookie-browser.test.ts
new file mode 100644
index 00000000..e9de1fb0
--- /dev/null
+++ b/lib/managed-apps/proxy-cookie-browser.test.ts
@@ -0,0 +1,38 @@
+import { chromium } from "@playwright/test";
+import { expect, it } from "vitest";
+import { cookiePrefix, rewriteSetCookie, upstreamCookieHeader } from "./proxy-headers";
+
+it("the browser rejects sibling Domain/path shadows in either insertion order", async () => {
+ const browser = await chromium.launch({headless: true});
+ const hermes = "https://hermes.mso-cookie.test", sibling = "https://openclaw.mso-cookie.test";
+ try {
+ for (const shadowFirst of [true, false]) {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ let received: string | null = null;
+ await page.route("https://*.mso-cookie.test/**", async route => {
+ const request = route.request();
+ if (request.url() === `${hermes}/echo`) received = (await request.allHeaders()).cookie ?? null;
+ const headers: Record<string, string> = request.url() === `${hermes}/login`
+ ? {"set-cookie": rewriteSetCookie("session=real; HttpOnly", "hermes", true, "")!} : {};
+ await route.fulfill({status: 200, contentType: "text/html", headers, body: "<title>Cookie fixture</title>fixture"});
+ });
+ const inject = async () => {
+ await page.goto(sibling);
+ await page.evaluate(() => {
+ document.cookie = "__Host-mapp_hermes_session=forged; Domain=.mso-cookie.test; Path=/; Secure";
+ document.cookie = "__Host-mapp_hermes_session=path-shadow; Path=/echo; Secure";
+ document.cookie = "mapp_hermes_session=legacy-forged; Domain=.mso-cookie.test; Path=/; Secure";
+ });
+ };
+ if (shadowFirst) await inject();
+ await page.goto(`${hermes}/login`);
+ if (!shadowFirst) await inject();
+ await page.goto(`${hermes}/echo`);
+ expect(received).toContain("legacy-forged"); // The adversary's parent-domain cookie actually arrived.
+ expect(received).not.toContain("path-shadow");
+ expect(upstreamCookieHeader(received, cookiePrefix("hermes"))).toBe("session=real");
+ await context.close();
+ }
+ } finally {await browser.close();}
+});
diff --git a/lib/managed-apps/proxy-headers.test.ts b/lib/managed-apps/proxy-headers.test.ts
index 6540ed93..ac5f43c2 100644
--- a/lib/managed-apps/proxy-headers.test.ts
+++ b/lib/managed-apps/proxy-headers.test.ts
@@ -7,10 +7,30 @@ import {
isServiceWorkerPath,
proxyPrefix,
rewriteLocation,
+ rewriteSetCookie,
+ upstreamCookieHeader,
+ cookiePrefix,
} from "./proxy-headers";
const PREFIX = proxyPrefix("hermes");
+describe("host-bound app cookies", () => {
+ it("forces host-only Secure root cookies while preserving JS-readable CSRF cookies", () => {
+ expect(rewriteSetCookie("csrf=value; Domain=.mso.example.com; Path=/login; SameSite=None; Max-Age=60", "hermes", true, ""))
+ .toBe("__Host-mapp_hermes_csrf=value; Max-Age=60; Path=/; SameSite=Lax; Secure");
+ expect(rewriteSetCookie("session=s; HttpOnly", "hermes", true, "")).toContain("HttpOnly");
+ expect(rewriteSetCookie("session=s", "hermes", false, "")).toBeNull();
+ expect(rewriteSetCookie("session=s", "hermes", true, PREFIX)).toBeNull();
+ });
+ it.each(["real; __Host-mapp_hermes_session=shadow", "shadow; __Host-mapp_hermes_session=real"])("rejects duplicate session cookies regardless of path ordering: %s", (value) => {
+ expect(upstreamCookieHeader(`__Host-mapp_hermes_session=${value}`, cookiePrefix("hermes"))).toBeNull();
+ });
+ it("rejects legacy/domain cookie names and sibling namespaces", () => {
+ expect(upstreamCookieHeader("mapp_hermes_session=shadow; __Host-mapp_openclaw_session=sibling", cookiePrefix("hermes"))).toBeNull();
+ expect(upstreamCookieHeader("mapp_hermes_session=shadow; __Host-mapp_hermes_session=real", cookiePrefix("hermes"))).toBe("session=real");
+ });
+});
+
describe("buildUpstreamHeaders", () => {
const base = new URL("http://127.0.0.1:9119");
const withHeaders = (init: Record<string, string>) =>
@@ -37,7 +57,7 @@ describe("buildUpstreamHeaders", () => {
it("keeps the cockpit session cookie on this side of the boundary", () => {
const out = buildUpstreamHeaders(
- withHeaders({ cookie: "session=cockpit; mapp_hermes_hermes_session_at=upstream" }),
+ withHeaders({ cookie: "session=cockpit; __Host-mapp_hermes_hermes_session_at=upstream" }),
base,
"hermes",
);
diff --git a/lib/managed-apps/proxy-headers.ts b/lib/managed-apps/proxy-headers.ts
index a8545228..0804fb35 100644
--- a/lib/managed-apps/proxy-headers.ts
+++ b/lib/managed-apps/proxy-headers.ts
@@ -1,10 +1,8 @@
// Header plumbing for the managed-app reverse proxy (the [[...path]] route).
// Lives here so the cookie-isolation rules are unit-testable without Next.
//
-// Cookie model: every cookie crossing the boundary is namespaced per app AND
-// pinned to that app's proxy path. An upstream (Hermes, OpenClaw) therefore can
-// neither read nor overwrite the mso `session` cookie — which is unprefixed
-// and Path=/ — nor a sibling managed app's cookies.
+// App cookies require HTTPS split origins and the browser-enforced __Host- prefix.
+// A sibling cannot inject a Domain cookie that shadows another app's session.
// `authorization` is deliberately NOT forwarded and `www-authenticate` is
// deliberately NOT returned: together they turn the proxy into a credential
@@ -60,7 +58,7 @@ const RESPONSE_HEADERS = [
// hermes.mso.example.com — and Hermes' own cookies are `hermes_session_at` /
// `_rt` / `_provider` / `_pkce` / `hermes_sso_attempt`, any of which could just as
// easily have been called `session` (OpenClaw sets none at all today).
-export const cookiePrefix = (id: string): string => `mapp_${id}_`;
+export const cookiePrefix = (id: string): string => `__Host-mapp_${id}_`;
// Where the app is mounted on the COCKPIT origin. Every helper below takes the
// mount prefix as an optional argument defaulting to this, because on the app's
@@ -72,12 +70,16 @@ export const proxyPrefix = (id: string): string => `/api/v1/managed-apps/${id}/p
// names. Anything else (`session`, `mso-device`, …) never leaves the host.
export function upstreamCookieHeader(raw: string | null, prefix: string): string | null {
if (!raw) return null;
+ if (!prefix.startsWith("__Host-")) return null;
const out: string[] = [];
+ const names = new Set<string>();
for (const part of raw.split(";")) {
const eq = part.indexOf("=");
if (eq < 1) continue;
const name = part.slice(0, eq).trim();
if (!name.startsWith(prefix) || name.length === prefix.length) continue;
+ if (names.has(name)) return null;
+ names.add(name);
out.push(`${name.slice(prefix.length)}=${part.slice(eq + 1).trim()}`);
}
return out.length ? out.join("; ") : null;
@@ -165,11 +167,10 @@ export function readSetCookies(headers: Headers): string[] {
return single ? [single] : [];
}
-// Upstream → browser: namespace the name, pin Path to this app's proxy prefix,
-// drop Domain. HttpOnly and Max-Age/Expires are kept as the upstream sent them
-// (some dashboards read their own CSRF cookie from JS); SameSite is forced to
-// Lax — the proxy is same-origin with the OS, so the iframe still sends it.
+// Host-only cookies always use Secure and Path=/; insecure/path-mounted cookies
+// fail closed. Preserve HttpOnly/expiry as sent so JS-readable CSRF cookies work.
export function rewriteSetCookie(value: string, id: string, secure: boolean, prefix = proxyPrefix(id)): string | null {
+ if (!secure || prefix !== "") return null;
const semi = value.indexOf(";");
const pair = (semi === -1 ? value : value.slice(0, semi)).trim();
const eq = pair.indexOf("=");
@@ -178,8 +179,7 @@ export function rewriteSetCookie(value: string, id: string, secure: boolean, pre
.split(";")
.map((attr) => attr.trim())
.filter((attr) => attr && !/^(path|domain|samesite|secure)\b/i.test(attr));
- attrs.push(`Path=${prefix || "/"}`, "SameSite=Lax");
- if (secure) attrs.push("Secure");
+ attrs.push("Path=/", "SameSite=Lax", "Secure");
return [`${cookiePrefix(id)}${pair}`, ...attrs].join("; ");
}
diff --git a/lib/mcp/origin.ts b/lib/mcp/origin.ts
index 87b79abb..76db3c97 100644
--- a/lib/mcp/origin.ts
+++ b/lib/mcp/origin.ts
@@ -3,8 +3,7 @@
// way a connector fails with "MCP server does not implement OAuth".
//
// Precedence mirrors lib/managed-apps/proxy-headers: OS_PUBLIC_ORIGIN is
-// deployment-owned and wins; the real Host header comes next; X-Forwarded-Host is
-// client-settable and is consulted LAST.
+// deployment-owned and wins; otherwise use actual authority, never forwarded headers.
function normalizedConfiguredOrigin(): string | null {
const explicit = process.env.OS_PUBLIC_ORIGIN?.trim() ||
@@ -102,30 +101,16 @@ export function mcpCorsHeaders(req: Request): Record<string, string> {
}
export function getBaseUrl(req: Request): string {
- const explicit = process.env.OS_PUBLIC_ORIGIN?.trim() ||
- process.env.NEXT_PUBLIC_APP_URL?.trim() ||
- process.env.APP_URL?.trim();
- if (explicit) {
- try {
- return new URL(explicit).origin;
- } catch {
- // Misconfigured value — fall through to header resolution
- }
- }
-
+ const explicit = normalizedConfiguredOrigin();
+ if (explicit) return explicit;
const url = new URL(req.url);
- const forwardedHost = req.headers.get("x-forwarded-host")?.split(",")[0].trim();
- const host = forwardedHost || req.headers.get("host")?.trim() || url.host || "localhost:3000";
- const hostname = host.split(":")[0];
- const isLoopback = isLoopbackHostname(hostname);
-
- const forwardedProto = req.headers.get("x-forwarded-proto")?.split(",")[0].trim();
- const proto = forwardedProto || (isLoopback ? "http" : url.protocol ? url.protocol.replace(":", "") : "https");
-
+ const host = req.headers.get("host")?.trim() || url.host;
try {
- return new URL(`${proto}://${host}`).origin;
+ const actual = new URL(`${url.protocol}//${host}`);
+ if (!["http:", "https:"].includes(actual.protocol) || actual.username || actual.password) throw new Error("invalid origin");
+ return actual.origin;
} catch {
- return `${proto}://${host}`;
+ return url.origin;
}
}
diff --git a/lib/mcp/scope.ts b/lib/mcp/scope.ts
index b9aabb25..4e017ba8 100644
--- a/lib/mcp/scope.ts
+++ b/lib/mcp/scope.ts
@@ -1,7 +1,8 @@
import { configuredCapabilityCeiling } from "@/lib/capabilities/scope-policy";
// MCP-specific policy layered on the transport-neutral capability scope.
export { SCOPES, allows, parseScope, type Scope } from "@/lib/capabilities/scope";
-import { scopeRank, type Scope } from "@/lib/capabilities/scope";
+import { type Scope } from "@/lib/capabilities/scope";
+export { clampScope } from "@/lib/capabilities/scope-policy";
/** OAuth scope strings are cumulative so a standards-compliant host can see that an exec token also satisfies read/write tool schemes. */
export function oauthScopeString(scope: Scope, offline = false): string {
@@ -19,9 +20,4 @@ export function maxScope(): Scope {
return configuredCapabilityCeiling();
}
-export function clampScope(asked: Scope): Scope {
- const ceiling = maxScope();
- return scopeRank(asked) > scopeRank(ceiling) ? ceiling : asked;
-}
-
export function defaultConsentScope(ceiling: Scope): Scope { return ceiling; }
diff --git a/lib/workflow/graph-authority.test.ts b/lib/workflow/graph-authority.test.ts
index ff834fd7..46035a64 100644
--- a/lib/workflow/graph-authority.test.ts
+++ b/lib/workflow/graph-authority.test.ts
@@ -2,10 +2,36 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ device: vi.fn() }));
vi.mock("@/lib/auth/device-store", () => ({ getApprovedDevice: mocks.device }));
import { requireWorkflowScope, workflowExecutionContext } from "./graph-authority";
+import { executeCapabilityCall } from "@/lib/capabilities/execute";
const context = {principal: "web:aaaaaaaaaaaaaaaa", sessionId: "s", scope: "exec" as const};
beforeEach(() => { vi.stubEnv("OS_MCP_MAX_SCOPE", "exec"); mocks.device.mockReset(); });
afterEach(() => vi.unstubAllEnvs());
describe("live workflow execution authority", () => {
+ it.each(["fs_write", "fs_rm", "infra_provider_create", "org_agent_configure", "project_mcp_add", "integration_manage", "future_write"])("blocks Operator %s at the execution boundary", async (name) => {
+ mocks.device.mockResolvedValue({role: "operator"});
+ const run = vi.fn();
+ const effective = await workflowExecutionContext(context);
+ const outcome = await executeCapabilityCall({tool: {name, scope: "write", run} as never, args: {}, scope: effective.scope, context: effective});
+ expect(outcome).toMatchObject({kind: "error", message: expect.stringContaining("not allowed")});
+ expect(run).not.toHaveBeenCalled();
+ });
+ it("rejects Owner-only app actions even through a permitted Operator tool", async () => {
+ mocks.device.mockResolvedValue({role: "operator"});
+ const effective = await workflowExecutionContext(context), run = vi.fn();
+ const outcome = await executeCapabilityCall({tool: {name: "apps_power", scope: "write", run} as never, args: {action: "remove"}, scope: effective.scope, context: effective});
+ expect(outcome).toMatchObject({kind: "error", message: expect.stringContaining("input is not allowed")});
+ expect(run).not.toHaveBeenCalled();
+ });
+ it("allows only bounded Operator writes, intersects caller restrictions, and defaults new writes to Owner", async () => {
+ mocks.device.mockResolvedValue({role: "operator"});
+ const capabilities = {list: () => [{name: "sys_stats", scope: "read"}, {name: "fs_write", scope: "write"}, {name: "infra_provider_create", scope: "write"}, {name: "future_write", scope: "write"}]} as never;
+ const effective = await workflowExecutionContext({...context, capabilities});
+ expect(effective.allowedTools).toEqual(["sys_stats", "apps_power"]);
+ expect(effective.toolArgumentConstraints?.apps_power.action).toEqual(["start", "stop", "restart", "backup"]);
+ const restricted = await workflowExecutionContext({...context, capabilities, allowedTools: ["sys_stats", "fs_write"], toolArgumentConstraints: {apps_power: {action: ["restart", "remove"]}}});
+ expect(restricted.allowedTools).toEqual(["sys_stats"]);
+ expect(restricted.toolArgumentConstraints?.apps_power.action).toEqual(["restart"]);
+ });
it.each([undefined, "schedule", "webhook", "channel"] as const)("caps Operator authority for %s", async type => {
mocks.device.mockResolvedValue({role: "operator"});
const effective = await workflowExecutionContext(context, type ? {type, receivedAt: new Date().toISOString()} : undefined);
diff --git a/lib/workflow/graph-authority.ts b/lib/workflow/graph-authority.ts
index 5144cb4f..fd228277 100644
--- a/lib/workflow/graph-authority.ts
+++ b/lib/workflow/graph-authority.ts
@@ -16,13 +16,24 @@ export async function workflowExecutionContext(
throw new Error("unattended workflow requires a live approved device; stored client names are not execution grants");
}
let ceiling = configuredCapabilityCeiling();
+ let allowedTools = context.allowedTools;
+ let toolArgumentConstraints = context.toolArgumentConstraints;
if (principal.startsWith("web:")) {
const device = await getApprovedDevice(principal.slice(4));
if (!device || device.role === "viewer") throw new Error("workflow device is revoked or lacks operator authority");
const roleScope: Scope = device.role === "owner" ? "exec" : "write";
if (scopeRank(roleScope) < scopeRank(ceiling)) ceiling = roleScope;
+ if (device.role === "operator") {
+ // New write tools default to Owner until their bounded Operator parity is reviewed.
+ const permitted = [...(context.capabilities?.list("read") ?? []).filter((tool) => tool.scope === "read").map((tool) => tool.name), "apps_power"];
+ const priorTools = allowedTools;
+ allowedTools = priorTools ? permitted.filter((name) => priorTools.includes(name)) : permitted;
+ const actions = ["start", "stop", "restart", "backup"];
+ const prior = toolArgumentConstraints?.apps_power?.action;
+ toolArgumentConstraints = { ...toolArgumentConstraints, apps_power: { ...toolArgumentConstraints?.apps_power, action: prior ? actions.filter((action) => prior.includes(action)) : actions } };
+ }
}
- return { ...context, scope: scopeRank(context.scope) < scopeRank(ceiling) ? context.scope : ceiling };
+ return { ...context, allowedTools, toolArgumentConstraints, scope: scopeRank(context.scope) < scopeRank(ceiling) ? context.scope : ceiling };
}
export function requireWorkflowScope(context: CapabilityRunContext, required: Scope): void {
diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.ts
index c24d1939..c4dcdc66 100644
--- a/lib/workflow/graph-runtime.ts
+++ b/lib/workflow/graph-runtime.ts
@@ -134,7 +134,7 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graph
if (node.type === "directory") {
const source = typeof config.source === "string" ? config.source : "tools", query = String(config.query ?? "").toLowerCase().trim();
if (source === "tools") {
- const tools = context.capabilities?.list(context.scope) ?? [];
+ const tools = (context.capabilities?.list(context.scope) ?? []).filter((tool) => !context.allowedTools || context.allowedTools.includes(tool.name));
return { output: { tools: tools.filter((tool) => !query || `${tool.name} ${tool.description} ${tool.scope}`.toLowerCase().includes(query)).slice(0, Math.max(1, Math.min(100, Number(config.limit) || 50))) }, log: "MSO capability directory queried." };
}
if (source === "workflows") { const { listWorkflowGraphs } = await import("./graph-store"); const rows = await listWorkflowGraphs(principal); return { output: { workflows: rows.filter((row) => !query || `${row.name} ${row.description} ${(row.metadata.tags ?? []).join(" ")}`.toLowerCase().includes(query)).map((row) => ({ id: row.id, name: row.name, status: row.status, updatedAt: row.updatedAt, nodes: row.nodes.length })) }, log: "Workflow directory queried." }; }
diff --git a/scripts/install-core.sh b/scripts/install-core.sh
index 1b37e3dd..8b4b32d3 100755
--- a/scripts/install-core.sh
+++ b/scripts/install-core.sh
@@ -1,11 +1,9 @@
#!/usr/bin/env bash
# mso (Manef Shell OS) installer core — fetched and verified by scripts/install.sh.
-#
# curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
#
# Idempotent update; preserves .env.local. Fresh interactive installs use /dev/tty.
set -Eeuo pipefail
-
CANONICAL_REPO_URL="https://github.com/rahmanef63/mso.git"
REPO_URL="${MSO_REPO:-$CANONICAL_REPO_URL}"
DIR="${MSO_DIR:-$HOME/mso}"
@@ -432,18 +430,20 @@ if [ -d "$DIR/.git" ]; then
else
if install_repo_is_canonical_url "$REPO_URL"; then REPO_URL="$CANONICAL_REPO_URL"; fi
info "cloning $REPO_URL → $DIR"
- install_git_noninteractive git clone --quiet --branch "$REF" "$REPO_URL" "$DIR" 2>/dev/null || install_git_noninteractive git clone --quiet "$REPO_URL" "$DIR"
+ install_git_noninteractive git clone --quiet --no-checkout "$REPO_URL" "$DIR" || die "could not clone repository"
+ install_git_noninteractive git -C "$DIR" fetch --quiet origin "$REF" || die "could not fetch requested ref $REF"
+ target_commit="$(git -C "$DIR" rev-parse --verify 'FETCH_HEAD^{commit}')" || die "could not resolve requested ref $REF"
+ git -C "$DIR" checkout --quiet --detach "$target_commit" || die "could not check out requested ref $REF"
+ [ "$(git -C "$DIR" rev-parse HEAD)" = "$target_commit" ] || die "checkout does not match requested ref $REF"
fi
cd "$DIR"
# ---- post-checkout phases ----
-# Fresh installs have the requested checkout now, so the rest of the installer is
-# split into bounded repo-owned phases without adding bootstrap downloads.
+# Run repo-owned phases only from the verified requested checkout.
for phase in cli runtime-build service finalize; do
module="$DIR/scripts/install/$phase.sh"
[ -f "$module" ] || die "installer phase missing from checkout: $module"
# shellcheck source=/dev/null
. "$module"
done
-
INSTALL_PHASE=complete
# MSO_INSTALLER_CORE_EOF
diff --git a/scripts/install-remote-authority.test.ts b/scripts/install-remote-authority.test.ts
index 6300ae21..69a672a7 100644
--- a/scripts/install-remote-authority.test.ts
+++ b/scripts/install-remote-authority.test.ts
@@ -20,7 +20,7 @@ describe("installer Git remote authority", () => {
expect(core).toContain('GIT_TERMINAL_PROMPT=0');
expect(core).toContain('GIT_SSH_COMMAND="${GIT_SSH_COMMAND:-ssh -oBatchMode=yes}"');
expect(core).toContain('install_git_noninteractive git -C "$DIR" fetch --quiet origin "$REF"');
- expect(core).toContain('install_git_noninteractive git clone --quiet --branch "$REF" "$REPO_URL" "$DIR"');
+ expect(core).toContain('install_git_noninteractive git clone --quiet --no-checkout "$REPO_URL" "$DIR"');
});
it("converts canonical SSH clone requests to public HTTPS but leaves noncanonical URLs outside that rewrite", () => {
diff --git a/scripts/install-requested-ref.test.ts b/scripts/install-requested-ref.test.ts
new file mode 100644
index 00000000..33778f81
--- /dev/null
+++ b/scripts/install-requested-ref.test.ts
@@ -0,0 +1,42 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+let root: string, repo: string, exact: string;
+const git = (...args: string[]) => execFileSync("git", args, {cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"]}).trim();
+beforeEach(() => {
+ root = mkdtempSync(path.join(os.tmpdir(), "mso-install-ref-")); repo = root;
+ git("init", "-q", "-b", "main"); git("config", "user.name", "fixture"); git("config", "user.email", "[email protected]");
+ writeFileSync(path.join(repo, "marker"), "requested"); git("add", "marker"); git("commit", "-qm", "requested");
+ exact = git("rev-parse", "HEAD"); git("tag", "requested-tag");
+ writeFileSync(path.join(repo, "marker"), "default"); git("commit", "-qam", "default");
+});
+afterEach(() => rmSync(root, {recursive: true, force: true}));
+
+function checkout(ref: string) {
+ const core = readFileSync("scripts/install-core.sh", "utf8");
+ const start = core.indexOf(' install_git_noninteractive git clone --quiet --no-checkout');
+ const end = core.indexOf('\nfi\ncd "$DIR"', start);
+ expect(start).toBeGreaterThan(0); expect(end).toBeGreaterThan(start);
+ const script = 'set -eu\ndie() { echo "$*" >&2; exit 1; }\ninstall_git_noninteractive() { "$@"; }\n' + core.slice(start, end) + '\nprintf "checkout=%s\\n" "$(git -C "$DIR" rev-parse HEAD)"\n';
+ const dir = path.join(root, "installed");
+ const result = spawnSync("bash", ["-c", script], {encoding: "utf8", env: {...process.env, REPO_URL: repo, DIR: dir, REF: ref}});
+ return {dir, result};
+}
+describe("fresh installer requested-ref authority", () => {
+ it.each(["tag", "commit"])("checks out an exact %s instead of the default branch", (kind) => {
+ const {dir, result} = checkout(kind === "tag" ? "requested-tag" : exact);
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain(`checkout=${exact}`);
+ expect(readFileSync(path.join(dir, "marker"), "utf8")).toBe("requested");
+ });
+ it("fails closed for a missing ref without checking out or executing the default branch", () => {
+ const {dir, result} = checkout("missing-ref");
+ expect(result.status).not.toBe(0);
+ expect(result.stderr).toContain("could not fetch requested ref missing-ref");
+ expect(() => readFileSync(path.join(dir, "marker"))).toThrow();
+ expect(result.stdout).not.toContain("checkout=");
+ });
+});
diff --git a/scripts/install-termux.sh b/scripts/install-termux.sh
index 6689b82c..dae82c9c 100755
--- a/scripts/install-termux.sh
+++ b/scripts/install-termux.sh
@@ -7,7 +7,7 @@ DISTRO="${MSO_TERMUX_DISTRO:-mso-ubuntu}"
GUEST_USER="${MSO_TERMUX_USER:-mso}"
IMAGE="${MSO_TERMUX_IMAGE:-ubuntu:24.04}"
GUEST_INSTALL_URL_DEFAULT="https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install-core.sh"
-GUEST_INSTALL_SHA256_DEFAULT="d796e29308685f21dcccb3ab72a2e39fde698fdf3f33170940335977e5dee46d"
+GUEST_INSTALL_SHA256_DEFAULT="a13c9f9b77111eb943fe0908f4f9a01dd35691ab64f04da5f1a50492d5d6e3d3"
INSTALL_URL="${MSO_TERMUX_INSTALL_URL:-$GUEST_INSTALL_URL_DEFAULT}"
INSTALL_SHA256="${MSO_TERMUX_INSTALL_SHA256:-$GUEST_INSTALL_SHA256_DEFAULT}"
GUEST_REF="${MSO_TERMUX_REF:-main}"
diff --git a/scripts/install.sh b/scripts/install.sh
index 5f6a1174..48247788 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -11,10 +11,10 @@ umask 077
RAW_BASE="${MSO_INSTALL_RAW_BASE:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts}"
CORE_URL="${MSO_INSTALL_CORE_URL:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install-core.sh}"
-CORE_SHA256="d796e29308685f21dcccb3ab72a2e39fde698fdf3f33170940335977e5dee46d"
+CORE_SHA256="a13c9f9b77111eb943fe0908f4f9a01dd35691ab64f04da5f1a50492d5d6e3d3"
CORE_EOF='# MSO_INSTALLER_CORE_EOF'
MACOS_SHA256="668ec3c8bbf3ee36dc2ae70952c3ba43c6f73ebc3acd6956fa4be2f65a076bfe"
-TERMUX_SHA256="eb634d1ec3d5aec0bea6e34243b4b8664ecb2af0df0fd30df196b4a89b0f96f0"
+TERMUX_SHA256="8f0bf5c201065cdab3e2a9779669dbe01477447f78f53e02b61d178a1f814e90"
TMP_INSTALLER=''
TMP_PLATFORM=''