Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
fix(security): revalidate durable authority and bound follow-up scan paths
rahmanefaff0713f4630
diff --git a/.env.example b/.env.exampleindex 4504fc32..1f80ba10 100644--- a/.env.example+++ b/.env.example@@ -291,6 +291,8 @@ OS_SESSION_SECRET=# Runtime/service port aliases used by installer and local A2A origin discovery.# MSO_PORT=4005# PORT=4005+# Production Node listener bind address (installer flags override this).+# HOSTNAME=0.0.0.0# Session context is estimated provider-neutrally and compacted when it reaches this# threshold. Raw/older context is first written as a SANITIZED gzip backup; secrets# are recursively redacted before archival. Defaults: 700k threshold, 140k recent.diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.tsindex 208d13c3..f5553fc9 100644--- a/app/api/auth/logout/route.ts+++ b/app/api/auth/logout/route.ts@@ -1,3 +1,4 @@+import { invalidateDeviceSessions } from "@/lib/auth/device-store";import { NextResponse } from "next/server";import { SESSION_COOKIE, getSessionActor } from "@/lib/auth/require-session";import { hostOnlyClearHeader, sessionCookieAttrs } from "@/lib/auth/session-cookie";@@ -6,7 +7,9 @@ import { audit } from "@/lib/host/audit-api";export const runtime = "nodejs";export async function POST(req: Request) {- audit({ action: "auth.logout", actor: await getSessionActor(), ok: true });+ const actor = await getSessionActor();+ if (actor) await invalidateDeviceSessions(actor);+ audit({ action: "auth.logout", actor, ok: true });const res = NextResponse.json({ success: true });// Same attributes as login, Max-Age=0 — a clear only matches a cookie with the// same Domain, so the two paths must read the same config or logout silentlydiff --git a/app/api/internal/socket-policy/route.ts b/app/api/internal/socket-policy/route.tsnew file mode 100644index 00000000..9da29618--- /dev/null+++ b/app/api/internal/socket-policy/route.ts@@ -0,0 +1,17 @@+import { NextRequest } from "next/server";+import { constantTimeEq } from "@/lib/auth/session";+import { readRequestJson } from "@/lib/security/request-body";+import { socketPolicy } from "@/lib/managed-apps/socket-policy";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++export async function POST(req: Request) {+ const secret = process.env.MSO_SOCKET_POLICY_SECRET ?? "";+ if (secret.length < 32 || !constantTimeEq(req.headers.get("authorization") ?? "", `Bearer ${secret}`)) return new Response(null, { status: 404 });+ try {+ const input = await readRequestJson(req, 32 * 1024) as { url: string; headers: Record<string, string> };+ const decision = await socketPolicy(new NextRequest(input.url, { headers: input.headers }));+ return Response.json(decision, { status: decision ? 200 : 403, headers: { "Cache-Control": "no-store" } });+ } catch { return new Response(null, { status: 403 }); }+}diff --git a/app/api/v1/a2a/route-credentials.ts b/app/api/v1/a2a/route-credentials.tsindex 85bebe73..6b1ac66c 100644--- a/app/api/v1/a2a/route-credentials.ts+++ b/app/api/v1/a2a/route-credentials.ts@@ -29,6 +29,7 @@ export async function handleA2ACredentialAction(const agent = await registerA2AAgent(url,typeof body.alias === "string" ? body.alias : undefined,+ "exec",);void audit({action: "a2a.registry",diff --git a/app/api/v1/a2a/route-get.ts b/app/api/v1/a2a/route-get.tsindex 3ee2e37d..119116d0 100644--- a/app/api/v1/a2a/route-get.ts+++ b/app/api/v1/a2a/route-get.ts@@ -66,7 +66,7 @@ export async function handleA2AGet(req: NextRequest, actor: string) {return NextResponse.json({ error: "too_many_requests" }, { status: 429 });const url = req.nextUrl.searchParams.get("url") || "";return url- ? NextResponse.json(await discoverA2AAgent(url))+ ? NextResponse.json(await discoverA2AAgent(url, undefined, "exec")): NextResponse.json({ error: "url_required" }, { status: 400 });}if (action === "task") {@@ -87,7 +87,7 @@ export async function handleA2AGet(req: NextRequest, actor: string) {{ status: 400 },);return NextResponse.json(- await getA2ATask(await resolveA2AAgent(target), taskId, historyLength),+ await getA2ATask(await resolveA2AAgent(target, "exec"), taskId, historyLength),);}return NextResponse.json({ error: "unknown_action" }, { status: 400 });diff --git a/app/api/v1/a2a/route-messages.ts b/app/api/v1/a2a/route-messages.tsindex 499171ee..e6cbf8c2 100644--- a/app/api/v1/a2a/route-messages.ts+++ b/app/api/v1/a2a/route-messages.ts@@ -77,7 +77,7 @@ export async function handleA2AMessageAction({ error: "target_and_message_required" },{ status: 400 },);- const peer = await resolveA2AAgent(target);+ const peer = await resolveA2AAgent(target, "exec");const encoder = new TextEncoder();const stream = new ReadableStream<Uint8Array>({async start(controller) {@@ -123,7 +123,7 @@ export async function handleA2AMessageAction({ status: 400 },);const response = await sendA2AMessage(- await resolveA2AAgent(target),+ await resolveA2AAgent(target, "exec"),message,{contextId:@@ -144,7 +144,7 @@ export async function handleA2AMessageAction({ error: "target_and_taskId_required" },{ status: 400 },);- const response = await cancelA2ATask(await resolveA2AAgent(target), taskId);+ const response = await cancelA2ATask(await resolveA2AAgent(target, "exec"), taskId);void audit({action: "a2a.cancel",actor,@@ -163,7 +163,7 @@ export async function handleA2AMessageAction({ status: 400 },);const result = await handoffA2A(- await resolveA2AAgent(target),+ await resolveA2AAgent(target, "exec"),objective,typeof body.context === "string" ? body.context : undefined,{diff --git a/app/api/v1/agent-tools/route.test.ts b/app/api/v1/agent-tools/route.test.tsindex e40de336..611b2c57 100644--- a/app/api/v1/agent-tools/route.test.ts+++ b/app/api/v1/agent-tools/route.test.ts@@ -110,7 +110,7 @@ describe("/api/v1/agent-tools", () => {expect.objectContaining({ method: "tools/call", params: { name: "write_tool", arguments: { name: "x" } } }),"exec","cli:dev-owner",- { principal: "cli:dev-owner", sessionId: "mso_test_session" },+ { principal: "cli:dev-owner", sessionId: "mso_test_session", authorizationGrant: { kind: "device", session: { device_id: "dev-owner" } } },);});});diff --git a/app/api/v1/agent-tools/route.ts b/app/api/v1/agent-tools/route.tsindex 8019e348..ba804543 100644--- a/app/api/v1/agent-tools/route.ts+++ b/app/api/v1/agent-tools/route.ts@@ -57,7 +57,7 @@ export async function POST(req: NextRequest) {{ id: "cli-call", method: "tools/call", params: { name, arguments: body.input ?? {} } },scope,principal,- { principal, sessionId },+ { principal, sessionId, authorizationGrant: { kind: "device", session: context.session } },);const result = (rpc.result ?? {}) as { content?: Array<{ type?: string; text?: string }>; isError?: boolean };if ((rpc as { error?: unknown }).error) return NextResponse.json(rpc, { status: 400 });diff --git a/app/api/v1/camoufox/session/route.ts b/app/api/v1/camoufox/session/route.tsindex 84ccd1e4..f4d4d3e3 100644--- a/app/api/v1/camoufox/session/route.ts+++ b/app/api/v1/camoufox/session/route.ts@@ -40,7 +40,7 @@ export async function GET() {if (!viewerOrigin || secret.length < 32) {return NextResponse.json({ error: "viewer_unconfigured" }, { status: 503 });}- const viewerTicket = createCamoufoxViewerTicket(context.session.device_id, secret);+ const viewerTicket = createCamoufoxViewerTicket(context.session.device_id, secret, Date.now(), context.session.issued_at);const password = (await fs.readFile(/* turbopackIgnore: true */ PASSWD_FILE, "utf8").catch(() => "")).trim();// Absent file = the operator has not set one. Say so plainly rather than 500 — thediff --git a/app/api/v1/channels/discord/[id]/route.test.ts b/app/api/v1/channels/discord/[id]/route.test.tsindex a169b5ee..0c097cb6 100644--- a/app/api/v1/channels/discord/[id]/route.test.ts+++ b/app/api/v1/channels/discord/[id]/route.test.ts@@ -12,7 +12,7 @@ vi.mock("@/lib/channels", () => {});const { POST } = await import("./route");-const request = () => new NextRequest("https://mso.example.test/api/v1/channels/discord/channel-2", {+const request = () => new NextRequest("https://mso.example.test/api/v1/channels/discord/22222222-2222-4222-8222-222222222222", {method: "POST",headers: { "content-type": "application/json", "x-signature-timestamp": "1", "x-signature-ed25519": "aa".repeat(64) },body: JSON.stringify({ id: "1", type: 2 }),@@ -28,14 +28,14 @@ beforeEach(() => {describe("Discord interactions route", () => {it("returns Discord PONG without starting a workflow", async () => {mocks.receive.mockResolvedValue({ event: null, ping: true });- const response = await POST(request(), { params: Promise.resolve({ id: "channel-2" }) });+ const response = await POST(request(), { params: Promise.resolve({ id: "22222222-2222-4222-8222-222222222222" }) });expect(response.status).toBe(200);await expect(response.json()).resolves.toEqual({ type: 1 });expect(mocks.dispatch).not.toHaveBeenCalled();});it("dispatches verified non-PING interactions", async () => {- const response = await POST(request(), { params: Promise.resolve({ id: "channel-2" }) });+ const response = await POST(request(), { params: Promise.resolve({ id: "22222222-2222-4222-8222-222222222222" }) });expect(response.status).toBe(200);expect(mocks.dispatch).toHaveBeenCalledTimes(1);await expect(response.json()).resolves.toMatchObject({ type: 4 });diff --git a/app/api/v1/channels/discord/[id]/route.ts b/app/api/v1/channels/discord/[id]/route.tsindex 6527cf2f..164a19c4 100644--- a/app/api/v1/channels/discord/[id]/route.ts+++ b/app/api/v1/channels/discord/[id]/route.ts@@ -1,7 +1,7 @@import { readRequestText, RequestBodyError } from "@/lib/security/request-body";import { NextRequest, NextResponse } from "next/server";import { ChannelError, dispatchChannelInbound, receiveDiscord } from "@/lib/channels";-import { rateLimitedUntrusted } from "@/lib/host/rate-limit";+import { admitChannelWebhook } from "@/lib/channels/webhook-admission";import { channelWorkflowRuntime } from "../../workflow-runtime";export const runtime = "nodejs";@@ -10,7 +10,7 @@ export const dynamic = "force-dynamic";export async function POST(req: NextRequest, context: { params: Promise<{ id: string }> }) {try {const { id } = await context.params;- if (rateLimitedUntrusted(`channel-discord:${id}`, 120, 60_000)) return NextResponse.json({ error: "rate_limited" }, { status: 429 });+ admitChannelWebhook(req, id);const body = await readRequestText(req, 1024 * 1024);const result = await receiveDiscord(id, body, req.headers.get("x-signature-timestamp"), req.headers.get("x-signature-ed25519"));if (result.ping) return NextResponse.json({ type: 1 });diff --git a/app/api/v1/channels/telegram/[id]/route.test.ts b/app/api/v1/channels/telegram/[id]/route.test.tsindex c86cdc44..d1d32f27 100644--- a/app/api/v1/channels/telegram/[id]/route.test.ts+++ b/app/api/v1/channels/telegram/[id]/route.test.ts@@ -12,7 +12,7 @@ vi.mock("@/lib/channels", () => {});const { POST } = await import("./route");-const request = () => new NextRequest("https://mso.example.test/api/v1/channels/telegram/channel-1", {+const request = () => new NextRequest("https://mso.example.test/api/v1/channels/telegram/11111111-1111-4111-8111-111111111111", {method: "POST",headers: { "content-type": "application/json", "x-telegram-bot-api-secret-token": "secret_123" },body: JSON.stringify({ update_id: 7 }),@@ -27,9 +27,9 @@ beforeEach(() => {describe("Telegram channel webhook route", () => {it("dispatches only after provider verification returns an event", async () => {- const response = await POST(request(), { params: Promise.resolve({ id: "channel-1" }) });+ const response = await POST(request(), { params: Promise.resolve({ id: "11111111-1111-4111-8111-111111111111" }) });expect(response.status).toBe(200);- expect(mocks.receive).toHaveBeenCalledWith("channel-1", { update_id: 7 }, "secret_123");+ expect(mocks.receive).toHaveBeenCalledWith("11111111-1111-4111-8111-111111111111", { update_id: 7 }, "secret_123");expect(mocks.dispatch).toHaveBeenCalledTimes(1);await expect(response.json()).resolves.toMatchObject({ ok: true, eventId: "7", workflow: { runId: "run-1" } });});@@ -37,7 +37,7 @@ describe("Telegram channel webhook route", () => {it("preserves provider-native verification failures", async () => {const { ChannelError } = await import("@/lib/channels");mocks.receive.mockRejectedValue(new ChannelError("invalid_webhook_signature", 401));- const response = await POST(request(), { params: Promise.resolve({ id: "channel-1" }) });+ const response = await POST(request(), { params: Promise.resolve({ id: "11111111-1111-4111-8111-111111111111" }) });expect(response.status).toBe(401);expect(mocks.dispatch).not.toHaveBeenCalled();});diff --git a/app/api/v1/channels/telegram/[id]/route.ts b/app/api/v1/channels/telegram/[id]/route.tsindex 00132d5e..8cfc4e65 100644--- a/app/api/v1/channels/telegram/[id]/route.ts+++ b/app/api/v1/channels/telegram/[id]/route.ts@@ -1,6 +1,6 @@import { NextRequest, NextResponse } from "next/server";import { ChannelError, dispatchChannelInbound, receiveTelegram } from "@/lib/channels";-import { rateLimitedUntrusted } from "@/lib/host/rate-limit";+import { admitChannelWebhook } from "@/lib/channels/webhook-admission";import { channelWorkflowRuntime } from "../../workflow-runtime";import { readSetupJson } from "@/lib/infra/setup-http";@@ -10,7 +10,7 @@ export const dynamic = "force-dynamic";export async function POST(req: NextRequest, context: { params: Promise<{ id: string }> }) {try {const { id } = await context.params;- if (rateLimitedUntrusted(`channel-telegram:${id}`, 120, 60_000)) return NextResponse.json({ error: "rate_limited" }, { status: 429 });+ admitChannelWebhook(req, id);const body = await readSetupJson(req, 1024 * 1024);const event = await receiveTelegram(id, body, req.headers.get("x-telegram-bot-api-secret-token"));const dispatched = await dispatchChannelInbound(id, event, channelWorkflowRuntime());diff --git a/app/api/v1/fs/list/route.ts b/app/api/v1/fs/list/route.tsindex 87b441d9..1975bc94 100644--- a/app/api/v1/fs/list/route.ts+++ b/app/api/v1/fs/list/route.ts@@ -1,4 +1,6 @@import { NextResponse } from "next/server";+import { getSessionActor } from "@/lib/auth/require-session";+import { rateLimited } from "@/lib/host/limits-api";import { verifyAuth } from "@/lib/agent/server";import { apiError } from "@/lib/host/request-api";import { listDir } from "@/lib/host/fs-api";@@ -10,9 +12,13 @@ export async function GET(req: Request) {if (!(await verifyAuth(req)))return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const actor = await getSessionActor();+ if (!actor) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ if (rateLimited(`fs.enumerate:${actor}`, 30, 60_000)) return NextResponse.json({ error: "rate_limited" }, { status: 429 });+const path = new URL(req.url).searchParams.get("path") ?? "~";try {- return NextResponse.json(await listDir(path, true));+ return NextResponse.json(await listDir(path, true, req.signal));} catch (e) {return apiError("fs/list", e);}diff --git a/app/api/v1/fs/search/route.ts b/app/api/v1/fs/search/route.tsindex c911156b..1c5f188b 100644--- a/app/api/v1/fs/search/route.ts+++ b/app/api/v1/fs/search/route.ts@@ -1,4 +1,6 @@import { NextResponse } from "next/server";+import { getSessionActor } from "@/lib/auth/require-session";+import { rateLimited } from "@/lib/host/limits-api";import { verifyAuth } from "@/lib/agent/server";import { apiError } from "@/lib/host/request-api";import { searchFs } from "@/lib/host/fs-api";@@ -11,11 +13,15 @@ export async function GET(req: Request) {if (!(await verifyAuth(req)))return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const actor = await getSessionActor();+ if (!actor) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ if (rateLimited(`fs.enumerate:${actor}`, 30, 60_000)) return NextResponse.json({ error: "rate_limited" }, { status: 429 });+const url = new URL(req.url);const q = url.searchParams.get("q") ?? "";const root = url.searchParams.get("root") ?? undefined;try {- return NextResponse.json(await searchFs(q, { root }));+ return NextResponse.json(await searchFs(q, { root, signal: req.signal }));} catch (e) {return apiError("fs/search", e);}diff --git a/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts b/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.tsindex 75858b8e..929379eb 100644--- a/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts+++ b/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts@@ -1,6 +1,7 @@import { NextResponse } from "next/server";import { verifyAuth } from "@/lib/agent/server";import { getManagedAppDefinition, isManagedAppId } from "@/lib/managed-apps/catalog";+import { managedAppUpstream } from "@/lib/managed-apps/upstream-target";import {MANAGED_APP_HOST_HEADER,cockpitOrigin,@@ -110,10 +111,9 @@ async function proxy(req: Request, context: { params: Promise<{ id: string; pathreturn fail(req, "service workers are not proxied", 404);}const definition = getManagedAppDefinition(params.id);- const base = new URL(definition.dashboardUrl);- if (base.protocol !== "http:" || !["127.0.0.1", "localhost", "::1"].includes(base.hostname)) {- return fail(req, "upstream target is not loopback", 502);- }+ let base: URL;+ try { base = managedAppUpstream(definition.dashboardUrl); }+ catch { return fail(req, "upstream target is not loopback", 502); }const target = new URL(`/${segments.map(encodeURIComponent).join("/")}`, base);target.search = new URL(req.url).search;const headers = buildUpstreamHeaders(req, base, params.id, "");diff --git a/app/api/v1/organization/route.ts b/app/api/v1/organization/route.tsindex e4070084..8c75314b 100644--- a/app/api/v1/organization/route.ts+++ b/app/api/v1/organization/route.ts@@ -31,11 +31,11 @@ export async function POST(req: NextRequest) {const revision = String(body.expected_revision || ""); if (!revision) throw new Error("expected_revision is required");let chart;if (action === "unit_upsert") chart = await upsertOrganizationUnit(revision, body.unit as Record<string, unknown>);- else if (action === "seat_upsert") chart = await upsertOrganizationSeat(revision, body.seat as Record<string, unknown>);+ else if (action === "seat_upsert") chart = await upsertOrganizationSeat(revision, body.seat as Record<string, unknown>, session.context.role === "owner" ? "exec" : "write");else if (action === "unit_delete") chart = await deleteOrganizationUnit(revision, String(body.id || ""));else if (action === "seat_delete") chart = await deleteOrganizationSeat(revision, String(body.id || ""));else if (isOrganizationFlowAction(action)) chart = await mutateOrganizationFlow(revision, action, (body.data ?? {}) as Record<string, unknown>, { principal: session.principal });- else if (action === "replace") { if (!roleAtLeast(session.context.role, "owner")) return fail("owner_required", 403); chart = await replaceOrganization(revision, body.chart as never); }+ else if (action === "replace") { if (!roleAtLeast(session.context.role, "owner")) return fail("owner_required", 403); chart = await replaceOrganization(revision, body.chart as never, "exec"); }else throw new Error("unknown organization action");void audit({ action: "agent.organization", actor: session.context.session.device_id, target: action, detail: `organization ${action}` });return NextResponse.json({ chart, runtime: await organizationRuntime(session.principal) }, { headers });diff --git a/app/api/v1/sys/services/route.test.ts b/app/api/v1/sys/services/route.test.tsindex 57aacdcc..fd47cae0 100644--- a/app/api/v1/sys/services/route.test.ts+++ b/app/api/v1/sys/services/route.test.ts@@ -27,6 +27,14 @@ beforeEach(() => {});describe("system service API", () => {+ it("rejects oversized action bodies without reading them", async () => {+ const { POST } = await import("./route");+ const request = new Request("https://mso.example/api/v1/sys/services", { method: "POST", headers: { "content-length": "1000000" }, body: "{}" });+ const parse = vi.spyOn(request, "json");+ expect((await POST(request)).status).toBe(413);+ expect(parse).not.toHaveBeenCalled();+ expect(mocks.power).not.toHaveBeenCalled();+ });it("returns bounded inventory through the viewer policy", async () => {const { GET } = await import("./route");const request = new Request("https://mso.example/api/v1/sys/services");diff --git a/app/api/v1/sys/services/route.ts b/app/api/v1/sys/services/route.tsindex aff3410e..aef05942 100644--- a/app/api/v1/sys/services/route.ts+++ b/app/api/v1/sys/services/route.ts@@ -6,6 +6,7 @@ import { rateLimited } from "@/lib/host/limits-api";import { listSystemServices, servicePower } from "@/lib/host/services";import { getSessionActor } from "@/lib/auth/require-session";import type { ServiceAction, ServiceScope } from "@/lib/os-api/types";+import { readRequestJson, RequestBodyError } from "@/lib/security/request-body";export const dynamic = "force-dynamic";@@ -24,13 +25,13 @@ export async function GET(req: Request) {export async function POST(req: Request) {if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });- let body: { scope?: ServiceScope; unit?: string; action?: ServiceAction };- try { body = await req.json(); }- catch { return NextResponse.json({ error: "invalid request body" }, { status: 400 }); }const actor = await getSessionActor();if (rateLimited(`sys-service-action:${actor ?? "unknown"}`, 12, 60_000)) {return NextResponse.json({ error: "too many service actions" }, { status: 429 });}+ let body: { scope?: ServiceScope; unit?: string; action?: ServiceAction };+ try { body = await readRequestJson(req, 4096); }+ catch (error) { return NextResponse.json({ error: "invalid request body" }, { status: error instanceof RequestBodyError ? error.status : 400 }); }try {const service = await servicePower(body.scope as ServiceScope, body.unit as string, body.action as ServiceAction);await audit({diff --git a/app/api/v1/term/stream/route.test.ts b/app/api/v1/term/stream/route.test.tsnew file mode 100644index 00000000..63a669cc--- /dev/null+++ b/app/api/v1/term/stream/route.test.ts@@ -0,0 +1,32 @@+import { afterAll, afterEach, expect, it, vi } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import type { SessionPayload } from "@/lib/auth/session";++const mocks = vi.hoisted(() => ({ session: null as SessionPayload | null, data: null as ((chunk: string, offset: number) => void) | null, detach: vi.fn(), close: vi.fn() }));+vi.mock("@/lib/agent/server", () => ({ verifyAuth: async () => true }));+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: async () => ({ session: mocks.session, role: "owner" }) }));+vi.mock("@/lib/host/terminal-api", () => ({ hasPty: () => true, closePty: mocks.close, attachPty: (_id: string, _owner: string, _from: number, callbacks: { onData: typeof mocks.data }) => { mocks.data = callbacks.onData; return mocks.detach; } }));++const root = await mkdtemp(path.join(os.tmpdir(), "mso-term-live-"));+process.env.OS_DEVICE_STORE = path.join(root, "devices.json");+const devices = await import("@/lib/auth/device-store");+const { GET } = await import("./route");+const id = "a".repeat(32);+await devices.approveDevice(id); await devices.approveDevice("b".repeat(32));+afterEach(() => { mocks.close.mockClear(); mocks.detach.mockClear(); });+afterAll(async () => { delete process.env.OS_DEVICE_STORE; await rm(root, { recursive: true, force: true }); });++it("rechecks live Owner authority before data delivery and kills the PTY after demotion", async () => {+ const policy = await devices.currentSessionPolicy("host");+ mocks.session = { device_id: id, issued_at: Date.now(), expires_at: Date.now() + 60_000, cookie_scope: policy.scope, cookie_epoch: policy.epoch };+ const response = await GET(new Request("https://host.test/api/v1/term/stream?id=pty"));+ const reader = response.body!.getReader();+ mocks.data!("permitted", 9);+ expect(new TextDecoder().decode((await reader.read()).value)).toContain("event: data");+ await devices.setDeviceRole(id, "viewer");+ mocks.data!("private-output-after-demotion", 30);+ expect((await reader.read()).done).toBe(true);+ expect(mocks.detach).toHaveBeenCalled(); expect(mocks.close).toHaveBeenCalledWith("pty", id);+});diff --git a/app/api/v1/term/stream/route.ts b/app/api/v1/term/stream/route.tsindex 1bf1feab..4faa474b 100644--- a/app/api/v1/term/stream/route.ts+++ b/app/api/v1/term/stream/route.ts@@ -1,7 +1,8 @@import { NextResponse } from "next/server";import { verifyAuth } from "@/lib/agent/server";-import { getSessionActor } from "@/lib/auth/require-session";-import { attachPty, hasPty } from "@/lib/host/terminal-api";+import { getSessionContext } from "@/lib/auth/require-session";+import { liveSessionAuthorized } from "@/lib/auth/live-authorization";+import { attachPty, closePty, hasPty } from "@/lib/host/terminal-api";export const runtime = "nodejs";export const dynamic = "force-dynamic";@@ -18,7 +19,8 @@ export async function GET(req: Request) {if (!(await verifyAuth(req)))return NextResponse.json({ error: "unauthorized" }, { status: 401 });- const actor = await getSessionActor();+ const context = await getSessionContext();+ const actor = context?.session.device_id;if (!actor) return NextResponse.json({ error: "unauthorized" }, { status: 401 });const id = new URL(req.url).searchParams.get("id") ?? "";if (!id || !hasPty(id, actor))@@ -29,13 +31,17 @@ export async function GET(req: Request) {const enc = new TextEncoder();let detach: (() => void) | null = null;let heartbeat: ReturnType<typeof setInterval> | null = null;+ let authorityTimer: ReturnType<typeof setInterval> | null = null;let closed = false;+ let pendingBytes = 0;+ let delivery = Promise.resolve();const stream = new ReadableStream<Uint8Array>({start(controller) {const cleanup = () => {closed = true;if (heartbeat) clearInterval(heartbeat);+ if (authorityTimer) clearInterval(authorityTimer);detach?.();};const send = (s: string) => {@@ -55,13 +61,28 @@ export async function GET(req: Request) {/* already closed */}};+ const authorized = async () => {+ const valid = await liveSessionAuthorized(context!.session, "owner").catch(() => false);+ if (!valid && !closed) {+ end();+ try { closePty(id, actor); } catch { /* Already reaped. */ }+ }+ return valid && !closed;+ };+ const deliver = (frame: string, finish = false) => {+ pendingBytes += Buffer.byteLength(frame);+ // ponytail: cap queued output at 256 KiB; reconnect replays the PTY buffer.+ if (pendingBytes > 256 * 1024) { end(); return; }+ delivery = delivery.then(async () => {+ if (await authorized()) { send(frame); if (finish) end(); }+ }).finally(() => { pendingBytes -= Buffer.byteLength(frame); });+ };try {detach = attachPty(id, actor, from, {onData: (chunk, off) =>- send(`id: ${off}\nevent: data\ndata: ${Buffer.from(chunk, "utf8").toString("base64")}\n\n`),+ deliver(`id: ${off}\nevent: data\ndata: ${Buffer.from(chunk, "utf8").toString("base64")}\n\n`),onExit: (code) => {- send(`event: exit\ndata: ${code}\n\n`);- end();+ deliver(`event: exit\ndata: ${code}\n\n`, true);},});} catch {@@ -71,11 +92,13 @@ export async function GET(req: Request) {return;}if (!closed) heartbeat = setInterval(() => send(`: ping\n\n`), HEARTBEAT_MS);+ if (!closed) authorityTimer = setInterval(() => { void authorized(); }, 1000);req.signal.addEventListener("abort", cleanup, { once: true });},cancel() {closed = true;if (heartbeat) clearInterval(heartbeat);+ if (authorityTimer) clearInterval(authorityTimer);detach?.();},});diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.tsindex ad95d8e2..26a3ba0d 100644--- a/app/mcp/route.test.ts+++ b/app/mcp/route.test.ts@@ -167,6 +167,7 @@ describe("/mcp request boundary", () => {expect(hash).not.toContain(rawConversation);expect(mocks.dispatch).toHaveBeenCalledWith(body, "read", `mcp:${token.hash.slice(0, 16)}`, {principal: `mcp-client:${token.clientId}`,+ authorizationGrant: expect.objectContaining({ kind: "mcp", id: token.hash, fingerprint: expect.stringMatching(/^[a-f0-9]{64}$/) }),sessionId: "20260901_100000_aabbccdd",toolProfile: "chatgpt",trustedOpenAiFileParams: true,diff --git a/app/mcp/route.ts b/app/mcp/route.tsindex 9865a553..73114879 100644--- a/app/mcp/route.ts+++ b/app/mcp/route.ts@@ -1,3 +1,4 @@+import { mcpAuthorizationGrant } from "@/lib/mcp/durable-grant";import { TENANT_MEMORY_TOOLS } from "@/lib/tenancy/memory-tools";import { tenantPreviewEnabled } from "@/lib/tenancy/mode";import { resolveMcpTenant, tenantRuntimeConfigurationPresent } from "@/lib/tenancy/runtime";@@ -109,6 +110,7 @@ export async function POST(req: Request) {void touchToken(token.hash).catch(() => {});const actor = `mcp:${token.hash.slice(0, 16)}`;const agentContext = {+ authorizationGrant: mcpAuthorizationGrant(token, expectedResource),principal,...(resolved.agentSessionId ? { sessionId: resolved.agentSessionId } : {}),toolProfile,diff --git a/bin/mso.test.ts b/bin/mso.test.tsindex 9f0d3fe8..b809451b 100644--- a/bin/mso.test.ts+++ b/bin/mso.test.ts@@ -139,6 +139,7 @@ describe("bin/mso", () => {// Internal transport between scripts/mso-agent.mjs and the authenticated// server-side MCP catalog. It is not a user-facing CLI verb by design."/api/v1/agent-tools",+ "POST /api/internal/socket-policy", // Private Node-to-Next policy RPC, authenticated by a fresh per-process secret.];// The CLI writes each call as `jget "/path"` / `jpost "/path"` / `jdel "/path"`,diff --git a/docs/A2A.md b/docs/A2A.mdindex 3d3067bc..4f24d9ef 100644--- a/docs/A2A.md+++ b/docs/A2A.md@@ -17,6 +17,8 @@ A remote agent is a separate trust domain. MSO keeps that boundary explicit:- Agent discovery uses `/.well-known/agent-card.json` and accepts only public **HTTPS** Agent Card/interface URLs.- Outbound HTTP reuses MSO's SSRF guard: public-address validation, DNS re-resolution with resolved-IP pinning, redirect refusal, and rejection of loopback/private/link-local/metadata targets.+- Exact-loopback discovery additionally requires the current caller to hold `exec` authority at card discovery, selected-interface resolution, refresh and credential materialization, even when the deployment enables loopback transport.+- Outbound authentication values are removed from returned JSON/SSE keys and values, protocol errors and transport errors if a peer reflects them.- Remote JSON responses and SSE events are bounded. Normal message text is limited to 24 KiB.- `~/.mso/private/a2a-agents.json` stores sanitized public Agent Card metadata and a local credential-profile pointer, never a secret.- Outbound credential secrets live separately in `~/.mso/private/a2a-credentials.json` under owner-only `0700/0600` storage. List/state APIs return summaries only.@@ -116,7 +118,7 @@ A2A is a **transport boundary**, not MSO's visual orchestration graph and not it- **Organization** owns stable unit/seat identity, reporting lines, and the pointer from a seat to its current Project Agent, Local Agent, or remote A2A executor.- **A2A** owns discovery, authentication, message/task lifecycle, streaming, cancellation, and the remote trust boundary.-A Workflow `agent` node may target an `orgSeatId`. If that seat currently maps to an A2A peer, runtime resolution reaches the existing `a2a_handoff` path; changing the concrete peer later does not rewrite the workflow. Likewise, a saved Session workflow can be called through Execute Workflow or bounded Repeat Until without turning A2A itself into a loop engine. This separation keeps transport credentials and remote task state out of portable workflow definitions and organization metadata.+A Workflow `agent` node may target an `orgSeatId`. If that seat currently maps to an A2A peer, runtime resolution reaches the existing `a2a_handoff` path; the saved graph pins the reviewed seat target digest. Changing a shared execution target requires `exec`; a graph whose target later changes refuses dispatch until explicitly reviewed and saved again. Legacy seat-bound graphs without a digest also require review and resave. Likewise, a saved Session workflow can be called through Execute Workflow or bounded Repeat Until without turning A2A itself into a loop engine. This separation keeps transport credentials and remote task state out of portable workflow definitions and organization metadata.See [Workflow Graph](./WORKFLOW-GRAPH.md) and [Organization](./ORGANIZATION.md).diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 9c1648b1..4dea3438 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Fixed**+- `security` revalidate durable authority and bound follow-up scan paths- `heartbeat` preserve relative env paths in cron- `ux` reuse existing loading and glass styles within the shell budget- `heartbeat` use parseable multiline shell case statementsdiff --git a/docs/LOCAL-AGENTS.md b/docs/LOCAL-AGENTS.mdindex 66fe0240..0a4b906b 100644--- a/docs/LOCAL-AGENTS.md+++ b/docs/LOCAL-AGENTS.md@@ -154,6 +154,14 @@ Payloads are limited to **16 KiB**, known secret-shaped values are redacted befoReceiving a local message grants no capability. Standby state is control-plane metadata, not authorization. A request is auto-executable only when its durable mailbox metadata was created by an `exec`-scoped caller; a `write` caller may enqueue the same structured request but cannot authorize execution. `notify` and `reply` never wake the model worker. The bounded durable-session worker still uses the target session's normal capability/scope enforcement and receives only the explicit objective plus saved safe session context.+Standby persists a server-created authorization reference, never the raw bearer. Both+the arming credential and each executable request's credential are revalidated before+claim/dispatch and before every capability call: current scope, token expiry/revocation,+resource binding, profile, tool allowlist and argument constraints all still apply.+Browser grants also recheck the live approved owner device, session generation and+expiry. Recovery never promotes an old `authorized: true` flag into authority; legacy+records without a live reference are blocked and must be armed again.+Standby uses one active command per session. A durable message claim plus a session execution lease prevents event/restart races from creating overlapping workers. On crash, an expired claim can be recovered idempotently; MSO promises at-most-one **active** execution, not impossible-to-prove exactly-once external side effects after a process dies between an external mutation and its completion marker. `workflow_finish` and `workflow_cancel` disarm the matching standby record, and every dispatch revalidates the exact workflow before model execution.## MCP toolsdiff --git a/docs/MANAGED-APPS.md b/docs/MANAGED-APPS.mdindex 7d8663e3..5517e1ed 100644--- a/docs/MANAGED-APPS.md+++ b/docs/MANAGED-APPS.md@@ -27,6 +27,20 @@ flowchart LRP --> N```+## Live proxy authority++Production starts through `node scripts/server.mjs` (also used by `bun start` and the+gateway runtime). The public Node server owns WebSocket upgrades and forwards normal+HTTP to Next on a private loopback socket. Its private, process-secret policy endpoint+reuses the same live device/session checks as HTTP. Managed dashboards and Camoufox+revalidate before both socket directions deliver data and every second while idle.+Logout, device revocation/demotion, expiry or session-policy rotation closes access.+The process caps active proxy sockets at 32 and refuses redirects/off-loopback targets.+The stock development server refuses these upgrades; use the production entry point+for authenticated dashboard/viewer sockets. Terminal event streams similarly recheck+owner authority before delivery and while idle, closing their PTY on authority loss.+Managed-app health probes refuse redirects rather than follow them away from loopback.+## 1. Current application model| App | MSO-managed runtime | Internal dashboard upstream | Direct browser access | State directory |diff --git a/docs/MCP.md b/docs/MCP.mdindex 787a5e8b..bd911acc 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -237,7 +237,7 @@ Skill candidates contain only deterministic redacted tool guidance. Project-func`tool_forge_evaluate` re-checks the current tool catalog/scope and runs 1–8 executable fixtures only in the dedicated cached Docker sandbox. The sandbox uses no network, a read-only root and project mount, all Linux capabilities dropped, `no-new-privileges`, non-root execution, and CPU/memory/PID limits. `bun run forge:sandbox` provisions the labelled local image from the host's already-trusted Node binary and shared libraries; evaluation never pulls from a registry and records the exact image ID plus project source SHA-256.-`tool_forge_promote` is exec-scope and requires literal confirmation `PROMOTE <candidate_id>`. Promotion immediately re-runs evaluation, rejects candidate/target/toolset/source/image drift, never overwrites an existing Skill/function, writes atomically, and verifies the resulting project capability. A promoted project function still requires normal `project_function_call` exec scope and approval.+`tool_forge_promote` is exec-scope and requires literal confirmation `PROMOTE <candidate_id>`. Promotion immediately re-runs evaluation, rejects candidate/target/toolset/source/image drift, never overwrites an existing Skill/function, writes atomically, and verifies the resulting project capability. A promoted project Skill remains repository-controlled and untrusted until the operator reviews and copies it to the external operator skill root. A promoted project function still requires normal `project_function_call` exec scope and approval.## Opt-in project MCP/function capabilities@@ -421,11 +421,12 @@ already at its cap; a path hint may not leave it.`skills_list` merges the global roots with the per-project roots of every project:`.mso/skills`, `.claude/skills`, `.hermes/skills`, `.agents/skills`, `.codex/skills`.-A project skill becomes `local` only when all three hold: the skill directory realpaths-back *inside* its project; the directory and its `SKILL.md` are owned by MSO's uid; and-`SKILL.md` is a regular file, not a symlink. Otherwise it is cataloged `untrusted` —-metadata visible, instructions withheld until the operator reviews it and moves it into-`~/.mso/skills`. The generic HOME agent roots keep their existing untrusted behaviour.+Project roots are repository-controlled input and are always cataloged `untrusted`,+with metadata visible and instructions withheld. Same-uid ownership does not establish+operator review. The directory must still resolve inside its project and `SKILL.md`+must be a regular non-symlink file to enter the catalog. The operator can explicitly+review and copy instructions into the separate `~/.mso/skills` root. Generic HOME+agent roots retain their existing untrusted behaviour.The `SKILL.md` reader is `O_NOFOLLOW` **at the supplied path**, not at a canonicalizedsubstitute. It previously realpath'd first and opened the *target*, so a@@ -742,7 +743,7 @@ lib/host/project-roots.ts every configured project container + bounded enumeratlib/host/project-meta.ts symlink-refusing package.json / .git readerslib/host/guarded-write.ts optimistic SHA-256 file overwrite guardlib/skills/catalog.ts global + per-project SKILL.md roots, ids and provenance-lib/skills/project-skills.ts per-project roots and their earned-trust checks+lib/skills/project-skills.ts per-project roots and their containment checkslib/skills/semantic.ts local hybrid embedding/search primitiveslib/skills/search.ts unified skill/tool/recipe rankinglib/skills/memory.ts migrated multi-run exact-id workflow and recipe storediff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 48704352..4ffd128e 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,11 @@+## 2026-10-08: Close follow-up scan authority and resource gaps++The latest scan of main `40e30906` reported 14 remaining issues. Exact-loopback A2A now carries the current caller's exec authority across discovery, selected interfaces and credential materialization; reflected outbound secrets are removed from JSON, SSE and errors. Project skill ownership no longer promotes repository instructions into trusted guidance. Organization seat targets require exec changes and saved graphs pin their reviewed target digest. Durable standby retains live credential references and rechecks both request and worker grants, including per-capability constraints, after recovery.++Production socket forwarding owns live device checks in both directions and while idle; logout invalidates viewer tickets/cookies and cockpit sessions durably, and terminal streams stop on owner-authority loss. Health probes refuse redirects. Webhook admission uses a fixed global pre-auth budget independent of attacker-controlled IDs/source-map churn. Filesystem guards check lexical paths and protected canonical aliases; writes use random exclusive no-follow temporary descriptors. Enumeration streams within entry/time/response/concurrency ceilings, and service actions limit bytes before parsing.++Regression checks exercise real token stores, sockets, terminal streams, aliases and queued/recovered execution. No gate budgets were raised and no dependency was added. Cloud findings remain tied to the scanned historical revision until separate reassessment; repository checks do not establish production deployment.+## 2026-10-08: Preserve heartbeat configuration across cron working directoriesThe final audit reproduced a cron check silently becoming disabled when installation used a caller-relative env file. The shared heartbeat entry point now anchors that path to the installation working directory before validating it, preserving symlink rejection. A regression executes the generated cron command from HOME and confirms the enabled health check still runs.diff --git a/lib/a2a/client-card.ts b/lib/a2a/client-card.tsindex abc362fa..d88bc990 100644--- a/lib/a2a/client-card.ts+++ b/lib/a2a/client-card.ts@@ -4,6 +4,8 @@ import type {A2ADiscoveredAgent,A2ASecurityScheme,} from "./types";+import type { Scope } from "@/lib/capabilities/scope";+import { assertA2ADestinationAuthority } from "./destination-authority";import {a2aObject,a2aTransport,@@ -214,7 +216,9 @@ export function selectA2AInterface(card: A2AAgentCard): A2AAgentInterface {export async function discoverA2AAgent(source: string,fetchImpl: A2AFetchLike = a2aTransport,+ scope: Scope = "read",): Promise<A2ADiscoveredAgent> {+ assertA2ADestinationAuthority(source, scope);const cardUrl = a2aAgentCardUrl(source);const raw = await fetchA2AJson(cardUrl,@@ -222,5 +226,7 @@ export async function discoverA2AAgent(fetchImpl,);const card = normalizeA2AAgentCard(raw);- return { cardUrl, card, selectedInterface: selectA2AInterface(card) };+ const selectedInterface = selectA2AInterface(card);+ assertA2ADestinationAuthority(selectedInterface.url, scope);+ return { cardUrl, card, selectedInterface, authorityScope: scope };}diff --git a/lib/a2a/client-core.ts b/lib/a2a/client-core.tsindex dbf08b6e..2bc9c631 100644--- a/lib/a2a/client-core.ts+++ b/lib/a2a/client-core.ts@@ -2,6 +2,8 @@ import { a2aCredentialHeaders, getA2AOutboundCredential } from "./credentials";import { validateStoredA2ACredentialBinding } from "./credential-scheme";import { getOrCreateA2ALocalBearer, isOwnA2ALoopbackUrl } from "./local-auth";import { a2aNetworkFetch, assertA2AUrl } from "./network";+import { assertA2ADestinationAuthority } from "./destination-authority";+import { a2aResponseRedactor } from "./response-redaction";export { assertA2AUrl } from "./network";import type {A2AAgentInterface,@@ -80,15 +82,18 @@ export async function fetchA2AJson(fetchImpl: A2AFetchLike,): Promise<unknown> {const safe = assertA2AUrl(url).toString();- const response = await fetchImpl(safe, {- ...init,- redirect: "error",- signal: init.signal ?? AbortSignal.timeout(A2A_TIMEOUT_MS),- });- const body = await boundedA2AJson(response);- if (!response.ok)- throw new Error(`A2A endpoint returned HTTP ${response.status}`);- return body;+ const redact = a2aResponseRedactor(Object.fromEntries([...new Headers(init.headers)].filter(([key]) => !["content-type", "accept", "a2a-version"].includes(key))));+ try {+ const response = await fetchImpl(safe, {+ ...init,+ redirect: "error",+ signal: init.signal ?? AbortSignal.timeout(A2A_TIMEOUT_MS),+ });+ const body = await boundedA2AJson(response);+ if (!response.ok)+ throw new Error(`A2A endpoint returned HTTP ${response.status}`);+ return redact(body);+ } catch (error) { throw new Error(String(redact(error instanceof Error ? error.message : String(error)))); }}export function assertA2AMessage(value: string): string {@@ -135,6 +140,8 @@ export function a2aHeaders(export async function a2aAuthorizationHeaders(target: A2ADiscoveredAgent,): Promise<Record<string, string>> {+ assertA2ADestinationAuthority(target.cardUrl, target.authorityScope);+ assertA2ADestinationAuthority(target.selectedInterface.url, target.authorityScope);const localScheme = target.card.securitySchemes?.msoLocal;if (isOwnA2ALoopbackUrl(target.selectedInterface.url) &&diff --git a/lib/a2a/client-security.test.ts b/lib/a2a/client-security.test.tsnew file mode 100644index 00000000..8f73f97b--- /dev/null+++ b/lib/a2a/client-security.test.ts@@ -0,0 +1,41 @@+import { afterAll, expect, it, vi } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++const root = await mkdtemp(path.join(os.tmpdir(), "mso-a2a-security-"));+process.env.OS_A2A_CREDENTIAL_STORE = path.join(root, "credentials.json");+process.env.OS_A2A_ALLOW_LOOPBACK = "1";+const { createA2AOutboundCredential } = await import("./credentials-outbound");+const { discoverA2AAgent, getA2ATask } = await import("./client");+const { sendA2AStreamingMessage } = await import("./client-stream");+const card = (url = "https://peer.example/a2a") => ({ name: "Peer", description: "peer", version: "1.0", supportedInterfaces: [{ url, protocolBinding: "JSONRPC", protocolVersion: "1.0" }], capabilities: { streaming: true }, securitySchemes: { bearer: { httpAuthSecurityScheme: { scheme: "bearer" } } }, securityRequirements: [{ schemes: { bearer: { list: [] } } }], defaultInputModes: ["text/plain"], defaultOutputModes: ["text/plain"], skills: [] });+afterAll(async () => { delete process.env.OS_A2A_CREDENTIAL_STORE; delete process.env.OS_A2A_ALLOW_LOOPBACK; await rm(root, { recursive: true, force: true }); });++it("blocks read/write loopback before discovery and after a public card selects it", async () => {+ const fetch = vi.fn(async () => Response.json(card("http://127.0.0.1:3000/a2a/v1")));+ for (const scope of ["read", "write"] as const) {+ await expect(discoverA2AAgent("http://127.0.0.1:3000/", fetch, scope)).rejects.toThrow("exec authority");+ expect(fetch).not.toHaveBeenCalled();+ await expect(discoverA2AAgent("https://peer.example", fetch, scope)).rejects.toThrow("exec authority");+ fetch.mockClear();+ }+});++it("redacts the actual outbound secret from nested task results, protocol errors and SSE", async () => {+ const peer = await discoverA2AAgent("https://peer.example", async () => Response.json(card()));+ const secret = "arbitrary-outbound-secret-7940";+ const profile = await createA2AOutboundCredential({ agentId: "agent_peer", label: "Peer", kind: "bearer", secret, schemeName: "bearer" });+ const target = { ...peer, credentialProfileId: profile.id };+ const result = await getA2ATask(target, "task", 10, async (_url, init) => {+ expect(new Headers(init?.headers).get("authorization")).toBe(`Bearer ${secret}`);+ return Response.json({ result: { nested: [secret, { [secret]: `Bearer ${secret}` }] } });+ });+ expect(JSON.stringify(result)).not.toContain(secret);+ await expect(getA2ATask(target, "task", 10, async () => Response.json({ error: { message: secret } }))).rejects.toThrow("[redacted]");+ const events: unknown[] = [];+ for await (const value of sendA2AStreamingMessage(target, "hello", {}, async () => new Response(`data: ${JSON.stringify({ result: { text: secret } })}\n\n`, { headers: { "content-type": "text/event-stream" } }))) events.push(value);+ expect(JSON.stringify(events)).not.toContain(secret);+ const stream = sendA2AStreamingMessage(target, "hello", {}, async () => { throw new Error(secret); });+ await expect(stream.next()).rejects.toThrow("[redacted]");+});diff --git a/lib/a2a/client-stream.ts b/lib/a2a/client-stream.tsindex 11bd9675..fa39357e 100644--- a/lib/a2a/client-stream.ts+++ b/lib/a2a/client-stream.ts@@ -18,10 +18,12 @@ import {type A2AFetchLike,} from "./client-core";import { a2aSendParams } from "./client-ops";+import { a2aResponseRedactor } from "./response-redaction";async function* a2aSseEvents(response: Response,binding: A2AStandardBinding,+ redact: (value: unknown) => unknown,): AsyncGenerator<unknown> {if (!response.ok || !response.body)throw new Error(`A2A streaming endpoint returned HTTP ${response.status}`);@@ -53,7 +55,7 @@ async function* a2aSseEvents();let parsed: unknown;try {- parsed = JSON.parse(data);+ parsed = redact(JSON.parse(data));} catch {throw new Error("A2A streaming endpoint returned invalid SSE JSON");}@@ -95,33 +97,38 @@ export async function* sendA2AStreamingMessage(a2aSendParams(target, message, options),);const signal = a2aStreamSignal(options.signal);- let response: Response;- if (binding === "JSONRPC") {- response = await fetchImpl(assertA2AUrl(iface.url).toString(), {- method: "POST",- redirect: "error",- signal,- headers: a2aHeaders(iface, "application/json", auth, "text/event-stream"),- body: JSON.stringify({- jsonrpc: "2.0",- id: randomUUID(),- method: "SendStreamingMessage",- params,- }),- });- } else {- response = await fetchImpl(a2aRestOperationUrl(iface, "message:stream"), {- method: "POST",- redirect: "error",- signal,- headers: a2aHeaders(- iface,- "application/a2a+json",- auth,- "text/event-stream",- ),- body: JSON.stringify(params),- });+ const redact = a2aResponseRedactor(auth);+ try {+ let response: Response;+ if (binding === "JSONRPC") {+ response = await fetchImpl(assertA2AUrl(iface.url).toString(), {+ method: "POST",+ redirect: "error",+ signal,+ headers: a2aHeaders(iface, "application/json", auth, "text/event-stream"),+ body: JSON.stringify({+ jsonrpc: "2.0",+ id: randomUUID(),+ method: "SendStreamingMessage",+ params,+ }),+ });+ } else {+ response = await fetchImpl(a2aRestOperationUrl(iface, "message:stream"), {+ method: "POST",+ redirect: "error",+ signal,+ headers: a2aHeaders(+ iface,+ "application/a2a+json",+ auth,+ "text/event-stream",+ ),+ body: JSON.stringify(params),+ });+ }+ yield* a2aSseEvents(response, binding, redact);+ } catch (error) {+ throw new Error(String(redact(error instanceof Error ? error.message : String(error))));}- yield* a2aSseEvents(response, binding);}diff --git a/lib/a2a/destination-authority.ts b/lib/a2a/destination-authority.tsnew file mode 100644index 00000000..eab57595--- /dev/null+++ b/lib/a2a/destination-authority.ts@@ -0,0 +1,6 @@+import type { Scope } from "@/lib/capabilities/scope";+import { isA2ALoopbackUrl } from "./network";++export function assertA2ADestinationAuthority(url: string, scope: Scope = "read") {+ if (isA2ALoopbackUrl(url) && scope !== "exec") throw new Error("A2A loopback requires exec authority");+}diff --git a/lib/a2a/local-loopback-integration.test.ts b/lib/a2a/local-loopback-integration.test.tsindex ce2474a9..8f919430 100644--- a/lib/a2a/local-loopback-integration.test.ts+++ b/lib/a2a/local-loopback-integration.test.ts@@ -112,12 +112,12 @@ afterAll(async () => {describe("registered same-host A2A over exact loopback", () => {it("discovers/registers a virtual session card and handoffs without a manual credential", async () => {const cardUrl = `${origin}/.well-known/agent-card.json?session=bece`;- const registered = await registerA2AAgent(cardUrl, "bece");+ const registered = await registerA2AAgent(cardUrl, "bece", "exec");expect(registered.alias).toBe("bece");expect(registered.cardUrl).toBe(cardUrl);expect(registered.credentialProfileId).toBeUndefined();- const agent = await resolveA2AAgent("bece");+ const agent = await resolveA2AAgent("bece", "exec");const result = await handoffA2A(agent,"review the current work",diff --git a/lib/a2a/response-redaction.ts b/lib/a2a/response-redaction.tsnew file mode 100644index 00000000..f50bb16f--- /dev/null+++ b/lib/a2a/response-redaction.ts@@ -0,0 +1,11 @@+/** Peer data may echo credentials in values, object keys, or JSON-RPC errors. */+export function a2aResponseRedactor(auth: Record<string, string>) {+ const secrets = [...new Set(Object.values(auth).flatMap((value) => [value, value.replace(/^Bearer\s+/i, "")]).filter(Boolean))].sort((a, b) => b.length - a.length);+ const redact = (value: unknown): unknown => {+ if (typeof value === "string") return secrets.reduce((text, secret) => text.split(secret).join("[redacted]"), value);+ if (Array.isArray(value)) return value.map(redact);+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [String(redact(key)), redact(item)]));+ return value;+ };+ return redact;+}diff --git a/lib/a2a/store.ts b/lib/a2a/store.tsindex 619a3370..0eada69e 100644--- a/lib/a2a/store.ts+++ b/lib/a2a/store.ts@@ -5,6 +5,7 @@ import os from "node:os";import path from "node:path";import { withSecurityStoreLock } from "@/lib/security-store-lock";import { discoverA2AAgent } from "./client";+import type { Scope } from "@/lib/capabilities/scope";import { getA2AOutboundCredential } from "./credentials";import type { A2ADiscoveredAgent, A2ARegisteredAgent } from "./types";@@ -87,8 +88,9 @@ export async function listA2AAgents(): Promise<A2ARegisteredAgent[]> {export async function registerA2AAgent(source: string,requestedAlias?: string,+ scope: Scope = "read",): Promise<A2ARegisteredAgent> {- const discovered = await discoverA2AAgent(source);+ const discovered = await discoverA2AAgent(source, undefined, scope);const now = new Date().toISOString();const id = idFor(discovered.cardUrl);return withSecurityStoreLock(A2A_STORE_PATH, async () => {@@ -175,10 +177,11 @@ export async function setA2AAgentCredential(export async function resolveA2AAgent(ref: string,+ scope: Scope = "read",): Promise<A2ADiscoveredAgent> {const raw = String(ref || "").trim();if (!raw) throw new Error("A2A target is required");- if (/^https?:\/\//i.test(raw)) return discoverA2AAgent(raw);+ if (/^https?:\/\//i.test(raw)) return discoverA2AAgent(raw, undefined, scope);const q = raw.toLowerCase();const agents = await listA2AAgents();const exact = agents.filter(@@ -195,7 +198,7 @@ export async function resolveA2AAgent(throw new Error(`A2A target is ambiguous: ${exact.map((row) => row.alias).join(", ")}`,);- const discovered = await discoverA2AAgent(exact[0].cardUrl);+ const discovered = await discoverA2AAgent(exact[0].cardUrl, undefined, scope);return {...discovered,...(exact[0].credentialProfileIddiff --git a/lib/a2a/types.ts b/lib/a2a/types.tsindex b752e2c5..b339ec1c 100644--- a/lib/a2a/types.ts+++ b/lib/a2a/types.ts@@ -42,6 +42,7 @@ export type A2AAgentCard = {};export type A2ADiscoveredAgent = {+ authorityScope?: "read" | "write" | "exec";cardUrl: string;card: A2AAgentCard;selectedInterface: A2AAgentInterface;diff --git a/lib/agent/local-agent-messaging.ts b/lib/agent/local-agent-messaging.tsindex 400b65cb..40a81f1d 100644--- a/lib/agent/local-agent-messaging.ts+++ b/lib/agent/local-agent-messaging.ts@@ -1,3 +1,4 @@+import type { AuthorizationGrant } from "@/lib/capabilities/authorization-grant";import { randomUUID } from "node:crypto";import { redactText } from "@/lib/security/redact-text";import { getAgentSession } from "./session-store";@@ -72,6 +73,8 @@ export async function sendLocalAgentMessage(input: {requiresUserRelay?: boolean;requireActiveTarget?: boolean;executionAuthorized?: boolean;+ authorizationGrant?: AuthorizationGrant;+ authorizationArguments?: Record<string, unknown>;}): Promise<{status: LocalAgentDeliveryStatus;targetStatus: LocalAgentTarget["status"];@@ -96,7 +99,7 @@ export async function sendLocalAgentMessage(input: {// Auto execution is encoded explicitly at persistence time. A write-scope// caller can enqueue a request but can never turn standby into an exec grant.const executionRequested = intent === "request";- const executionAuthorized = executionRequested && input.executionAuthorized === true;+ const executionAuthorized = executionRequested && input.executionAuthorized === true && !!input.authorizationGrant;const standbyAccepted = executionAuthorized && target.standbyArmed && target.standbyState !== "blocked";const busy = target.status === "busy" || target.standbyState === "working";let message = await enqueueLocalAgentMessage({@@ -115,6 +118,7 @@ export async function sendLocalAgentMessage(input: {execution: {requested: true,authorized: executionAuthorized,+ ...(executionAuthorized ? { authorizationGrant: input.authorizationGrant, authorizationArguments: input.authorizationArguments ?? { target: input.target, message: input.text, intent: input.intent ?? "notify", ...(input.kind ? { kind: input.kind } : {}) } } : {}),state: "pending",attempts: 0,},diff --git a/lib/agent/local-agent-standby-drain-race.test.ts b/lib/agent/local-agent-standby-drain-race.test.tsindex 228d1aef..835a032a 100644--- a/lib/agent/local-agent-standby-drain-race.test.ts+++ b/lib/agent/local-agent-standby-drain-race.test.ts@@ -29,7 +29,7 @@ vi.mock("./local-agent-standby-store", () => ({}));const standby = await import("./local-agent-standby");-const capabilities = { list: () => [], invoke: vi.fn(async () => ({ content: [] })) };+const capabilities = { authorize: async () => true, list: () => [], invoke: vi.fn(async () => ({ content: [] })) };function deferred<T>() {let resolve!: (value: T) => void;@@ -42,6 +42,7 @@ beforeEach(async () => {mocks.active = true;mocks.record = {principal: "owner", principalHash: "owner-hash", sessionId: "worker",+ authorizationGrant: { kind: "mcp", id: "a".repeat(64), fingerprint: "fixture", resource: "https://fixture.example/mcp" },workflowActor: "owner:worker", workflowId: "workflow", armed: true, state: "waiting",armedAt: "2026-10-01T00:00:00Z", updatedAt: "2026-10-01T00:00:00Z",};diff --git a/lib/agent/local-agent-standby-execution.ts b/lib/agent/local-agent-standby-execution.tsindex 8211f0a1..8fb5e984 100644--- a/lib/agent/local-agent-standby-execution.ts+++ b/lib/agent/local-agent-standby-execution.ts@@ -9,6 +9,7 @@ import {import { replyLocalAgentMessage } from "./local-agent-messaging";import {acquireLocalAgentStandbyExecution,+ blockLocalAgentStandby,getLocalAgentStandbyRecord,releaseLocalAgentStandbyExecution,updateLocalAgentStandbyTask,@@ -109,6 +110,10 @@ export async function executeLocalAgentStandbyMessage(input: {runtimeId: string;}): Promise<{ advanced: boolean; fatal: boolean }> {const { record, message, capabilities } = input;+ if (!record.authorizationGrant || !capabilities.authorize || !await capabilities.authorize(record.authorizationGrant, record.principal, "local_agent_standby", record.authorizationArguments ?? { mode: "listen" })) {+ await blockLocalAgentStandby(record.principal, record.sessionId, "standby execution grant is revoked or expired");+ return { advanced: false, fatal: true };+ }const claimant = `${input.runtimeId}:${randomUUID()}`;const slot = await acquireLocalAgentStandbyExecution({principal: record.principal,@@ -136,6 +141,10 @@ export async function executeLocalAgentStandbyMessage(input: {}try {+ if (!claimed.execution?.authorizationGrant || !await capabilities.authorize(claimed.execution.authorizationGrant, record.principal, "local_agent_message_send", claimed.execution.authorizationArguments)) {+ await finishExecution({ record, claimed, claimant, state: "failed", error: "request execution grant is revoked or expired" });+ return { advanced: true, fatal: false };+ }const fresh = await getLocalAgentStandbyRecord(record.principal, record.sessionId);if (!fresh?.armed || fresh.workflowId !== record.workflowId)throw new Error("standby workflow is no longer active");@@ -146,7 +155,15 @@ export async function executeLocalAgentStandbyMessage(input: {record.principal,record.sessionId,claimed.text,- capabilities,+ {+ list: (scope) => capabilities.list(scope),+ async invoke(call) {+ const current = await getLocalAgentStandbyRecord(record.principal, record.sessionId);+ if (!current?.armed || current.workflowId !== record.workflowId || JSON.stringify(current.authorizationGrant) !== JSON.stringify(record.authorizationGrant)) return { content: [{ type: "text", text: "error: standby execution is no longer authorized" }], isError: true };+ if (!await capabilities.authorize!(record.authorizationGrant!, record.principal, call.name, call.args) || !await capabilities.authorize!(claimed.execution!.authorizationGrant!, record.principal, call.name, call.args)) return { content: [{ type: "text", text: "error: durable execution grant is revoked or does not allow this capability" }], isError: true };+ return capabilities.invoke({ ...call, principal: record.principal, authorizationGrant: record.authorizationGrant });+ },+ },undefined,{workflowId: fresh.workflowId,diff --git a/lib/agent/local-agent-standby-live-grant.test.ts b/lib/agent/local-agent-standby-live-grant.test.tsnew file mode 100644index 00000000..91a154f8--- /dev/null+++ b/lib/agent/local-agent-standby-live-grant.test.ts@@ -0,0 +1,21 @@+import { afterAll, afterEach, expect, it } from "vitest";+import { arm, authorizationGrant, capabilities, cleanupStandbyFixture, completedTask, eventually, messaging, mocks, owner, pair, resetStandbyRuntime, standbyStore, token } from "./local-agent-standby-test-fixture";++afterEach(resetStandbyRuntime);+afterAll(cleanupStandbyFixture);++it("rechecks the durable credential before each capability during an already-started worker", async () => {+ const { coordinator, worker } = await pair();+ const credentials = await import("@/lib/mcp/store");+ mocks.handoff.mockImplementation(async (_principal, _session, _message, runtime) => {+ await credentials.revokeToken((await credentials.validateToken(token))!.hash);+ const result = await runtime.invoke({ name: "host_exec", args: {}, scope: "exec", principal: owner });+ expect(result.isError).toBe(true);+ return completedTask();+ });+ await arm(worker.id);+ await messaging.sendLocalAgentMessage({ principal: owner, senderSessionId: coordinator.id, target: worker.id, text: "exercise active grant", intent: "request", executionAuthorized: true, authorizationGrant });+ await eventually(async () => (await standbyStore.getLocalAgentStandbyRecord(owner, worker.id))?.lastMessageId);+ expect(mocks.handoff).toHaveBeenCalledOnce();+ expect(capabilities.invoke).not.toHaveBeenCalled();+});diff --git a/lib/agent/local-agent-standby-recovery.test.ts b/lib/agent/local-agent-standby-recovery.test.tsindex 0642e09a..ead756ab 100644--- a/lib/agent/local-agent-standby-recovery.test.ts+++ b/lib/agent/local-agent-standby-recovery.test.ts@@ -1,6 +1,7 @@import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";import {arm,+ authorizationGrant,capabilities,cleanupStandbyFixture,events,@@ -15,6 +16,7 @@ import {resetStandbyRuntime,standby,standbyStore,+ token,workflowActor,workflowId,} from "./local-agent-standby-test-fixture";@@ -37,6 +39,7 @@ describe("durable local-agent standby recovery and security", () => {text: "survive restart",intent: "request",executionAuthorized: true,+ authorizationGrant,});expect(sent.status).toBe("accepted_for_standby");await new Promise((resolve) => setTimeout(resolve, 20));@@ -59,6 +62,7 @@ describe("durable local-agent standby recovery and security", () => {text: "FYI only",intent: "notify",executionAuthorized: true,+ authorizationGrant,});const writeOnly = await messaging.sendLocalAgentMessage({principal: owner,@@ -94,6 +98,7 @@ describe("durable local-agent standby recovery and security", () => {text: "do not auto execute",intent: "request",executionAuthorized: true,+ authorizationGrant,});await new Promise((resolve) => setTimeout(resolve, 50));expect(afterStop.status).not.toBe("accepted_for_standby");@@ -121,4 +126,16 @@ describe("durable local-agent standby recovery and security", () => {workflowId,})).rejects.toThrow(/session not found/i);});++ it("blocks recovered standby before claiming queued work after its durable token is revoked", async () => {+ const { coordinator, worker } = await pair();+ await arm(worker.id); standby.resetLocalAgentStandbyRuntimeForTest();+ const sent = await messaging.sendLocalAgentMessage({ principal: owner, senderSessionId: coordinator.id, target: worker.id, text: "queued before restart", intent: "request", executionAuthorized: true, authorizationGrant });+ const credentials = await import("@/lib/mcp/store");+ await credentials.revokeToken((await credentials.validateToken(token))!.hash);+ await standby.ensureLocalAgentStandbyRuntime(capabilities);+ const blocked = await eventually(async () => { const row = await standbyStore.getLocalAgentStandbyRecord(owner, worker.id); return row?.state === "blocked" ? row : null; });+ expect(blocked.armed).toBe(false); expect(mocks.handoff).not.toHaveBeenCalled();+ expect((await mailbox.getLocalAgentInboxMessage(owner, worker.id, sent.message.id))?.execution?.state).toBe("pending");+ });});diff --git a/lib/agent/local-agent-standby-store.ts b/lib/agent/local-agent-standby-store.tsindex 00a9db74..324392da 100644--- a/lib/agent/local-agent-standby-store.ts+++ b/lib/agent/local-agent-standby-store.ts@@ -1,3 +1,4 @@+import type { AuthorizationGrant } from "@/lib/capabilities/authorization-grant";import { getAgentSession } from "./session-store";import { principalHash } from "./session-files";import {@@ -41,6 +42,8 @@ export async function armLocalAgentStandbyRecord(input: {principal: string;sessionId: string;workflowActor: string;+ authorizationGrant?: AuthorizationGrant;+ authorizationArguments?: Record<string, unknown>;workflowId: string;now?: number;}): Promise<LocalAgentStandbyRecord> {@@ -59,6 +62,8 @@ export async function armLocalAgentStandbyRecord(input: {principal: input.principal,sessionId: input.sessionId,workflowActor: input.workflowActor,+ ...(input.authorizationGrant ? { authorizationGrant: input.authorizationGrant } : {}),+ authorizationArguments: input.authorizationArguments ?? { mode: "listen" },workflowId: input.workflowId,armed: true,state: "waiting",diff --git a/lib/agent/local-agent-standby-test-fixture.ts b/lib/agent/local-agent-standby-test-fixture.tsindex 733b8ede..0cfd61a1 100644--- a/lib/agent/local-agent-standby-test-fixture.ts+++ b/lib/agent/local-agent-standby-test-fixture.ts@@ -9,6 +9,8 @@ process.env.OS_LOCAL_AGENT_PRESENCE_STORE = path.join(root, "presence.json");process.env.OS_LOCAL_AGENT_MESSAGE_STORE = path.join(root, "messages.json");process.env.OS_LOCAL_AGENT_STANDBY_STORE = path.join(root, "standby.json");process.env.OS_A2A_TASK_STORE = path.join(root, "tasks.json");+process.env.OS_MCP_STORE = path.join(root, "mcp.json");+process.env.OS_MCP_MAX_SCOPE = "exec";process.env.OS_LOCAL_AGENT_LEASE_MS = "15000";process.env.NEXT_PUBLIC_OS_DEMO = "0";@@ -38,7 +40,14 @@ export const owner = "mcp-client:standby-owner";export const other = "mcp-client:foreign";export const workflowActor = "mcp:standby-owner";export const workflowId = "11111111-1111-4111-8111-111111111111";+const tokenStore = await import("@/lib/mcp/store");+export const token = "standby-fixture-token-" + root;+await tokenStore.storeToken(token, { label: "standby fixture", clientId: "standby-owner", scope: "exec" });+const credential = (await tokenStore.validateToken(token))!;+const grants = await import("@/lib/mcp/durable-grant");+export const authorizationGrant = grants.mcpAuthorizationGrant(credential, "https://fixture.example/mcp");export const capabilities = {+ authorize: grants.authorizeDurableGrant,list: () => [],invoke: vi.fn(async () => ({ content: [] })),};@@ -80,6 +89,7 @@ export async function arm(workerId: string) {workflowActor,workflowId,capabilities,+ authorizationGrant,});}diff --git a/lib/agent/local-agent-standby.test.ts b/lib/agent/local-agent-standby.test.tsindex b17fa95c..152a8366 100644--- a/lib/agent/local-agent-standby.test.ts+++ b/lib/agent/local-agent-standby.test.ts@@ -1,7 +1,7 @@import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";import {arm,- capabilities,+ authorizationGrant,cleanupStandbyFixture,completedTask,directory,@@ -61,6 +61,7 @@ describe("server-native durable local-agent standby execution", () => {intent: "request",requiresUserRelay: true,executionAuthorized: true,+ authorizationGrant,});expect(sent.status).toBe("accepted_for_standby");const reply = await eventually(() =>@@ -71,7 +72,7 @@ describe("server-native durable local-agent standby execution", () => {owner,worker.id,"perform one bounded task",- capabilities,+ expect.objectContaining({ invoke: expect.any(Function) }),undefined,{ workflowId, workflowActor, fixedWorkflow: true },);@@ -109,6 +110,7 @@ describe("server-native durable local-agent standby execution", () => {text: "deduplicate me",intent: "request",executionAuthorized: true,+ authorizationGrant,});events.publishLocalAgentStandbyMessage(worker.id, sent.message);events.publishLocalAgentStandbyMessage(worker.id, sent.message);@@ -145,6 +147,7 @@ describe("server-native durable local-agent standby execution", () => {text: "first",intent: "request",executionAuthorized: true,+ authorizationGrant,});await eventually(async () => mocks.handoff.mock.calls.length === 1 ? true : null);const second = await messaging.sendLocalAgentMessage({@@ -154,6 +157,7 @@ describe("server-native durable local-agent standby execution", () => {text: "second",intent: "request",executionAuthorized: true,+ authorizationGrant,});await new Promise((resolve) => setTimeout(resolve, 30));expect(mocks.handoff).toHaveBeenCalledTimes(1);diff --git a/lib/agent/local-agent-standby.ts b/lib/agent/local-agent-standby.tsindex bc063f81..1d4f7a28 100644--- a/lib/agent/local-agent-standby.ts+++ b/lib/agent/local-agent-standby.ts@@ -1,3 +1,4 @@+import type { AuthorizationGrant } from "@/lib/capabilities/authorization-grant";import { randomUUID } from "node:crypto";import type { CapabilityRuntime } from "@/lib/capabilities/runtime";import { activeWorkflowForActor } from "@/lib/workflow";@@ -50,7 +51,9 @@ function installSubscription(record: LocalAgentStandbyRecord): void {async function validateRecord(record: LocalAgentStandbyRecord,+ capabilities: CapabilityRuntime,): Promise<{ valid: true } | { valid: false; reason: string }> {+ if (!record.authorizationGrant || !capabilities.authorize || !await capabilities.authorize(record.authorizationGrant, record.principal, "local_agent_standby", record.authorizationArguments ?? { mode: "listen" })) return { valid: false, reason: "standby execution grant is revoked, expired or unavailable" };const session = await getAgentSession(record.principal, record.sessionId).catch(() => null);if (!session) return { valid: false, reason: "standby session no longer exists" };const workflow = await activeWorkflowForActor(record.workflowActor, record.workflowId)@@ -81,8 +84,9 @@ export async function drainStandbySession(flight.rerun = false;for (let processed = 0; processed < 100; processed += 1) {const record = await getLocalAgentStandbyRecord(principal, sessionId);+ if (inFlightSessions.get(key) !== flight) break;if (!record?.armed) break;- const validation = await validateRecord(record);+ const validation = await validateRecord(record, capabilities);if (!validation.valid) {await blockLocalAgentStandby(principal, sessionId, validation.reason);removeSubscription(sessionId);@@ -130,8 +134,11 @@ export async function armLocalAgentStandby(input: {sessionId: string;workflowActor: string;workflowId: string;+ authorizationGrant?: AuthorizationGrant;+ authorizationArguments?: Record<string, unknown>;capabilities: CapabilityRuntime;}) {+ if (!input.authorizationGrant || !input.capabilities.authorize || !await input.capabilities.authorize(input.authorizationGrant, input.principal, "local_agent_standby", input.authorizationArguments ?? { mode: "listen" })) throw new Error("standby requires a live exec authorization grant");if (!await activeWorkflowForActor(input.workflowActor, input.workflowId))throw new Error("workflow_id was not found for this MSO session");runtimeCapabilities = input.capabilities;diff --git a/lib/agent/local-agent-types.ts b/lib/agent/local-agent-types.tsindex 20103600..5c15f498 100644--- a/lib/agent/local-agent-types.ts+++ b/lib/agent/local-agent-types.ts@@ -1,3 +1,4 @@+import type { AuthorizationGrant } from "@/lib/capabilities/authorization-grant";import type { AgentSessionSource, AgentSessionTitleSource } from "./session-types";export type LocalAgentPresenceState = "ready" | "idle" | "busy" | "ended";@@ -18,6 +19,8 @@ export type LocalAgentMessageExecutionState = "pending" | "claimed" | "completedexport interface LocalAgentMessageExecution {requested: true;authorized: boolean;+ authorizationGrant?: AuthorizationGrant;+ authorizationArguments?: Record<string, unknown>;state: LocalAgentMessageExecutionState;attempts?: number;claimedBy?: string;@@ -32,6 +35,8 @@ export interface LocalAgentStandbyRecord {principal: string;sessionId: string;workflowActor: string;+ authorizationGrant?: AuthorizationGrant;+ authorizationArguments?: Record<string, unknown>;workflowId: string;armed: boolean;state: LocalAgentStandbyState;diff --git a/lib/agent/organization-runtime.ts b/lib/agent/organization-runtime.tsindex 2e6403b9..5bed3338 100644--- a/lib/agent/organization-runtime.ts+++ b/lib/agent/organization-runtime.ts@@ -1,8 +1,13 @@+import { createHash } from "node:crypto";import type { OrganizationSeat, OrganizationSeatRuntime } from "@/lib/contracts/organization";import { listA2AAgents } from "@/lib/a2a";import { listLocalAgents } from "./local-agent-directory";import { getOrganizationChart } from "./organization-store";+export function organizationTargetDigest(seat: OrganizationSeat): string {+ return createHash("sha256").update(JSON.stringify({ id: seat.id, target: seat.target })).digest("hex");+}+export function organizationLocalAgentPrincipal(principal: string): string { return principal.startsWith("web:") ? `cli:${principal.slice(4)}` : principal; }export async function resolveOrganizationSeat(ref: string): Promise<OrganizationSeat> {diff --git a/lib/agent/organization-store.test.ts b/lib/agent/organization-store.test.tsindex a5f56f00..4ed62fe5 100644--- a/lib/agent/organization-store.test.ts+++ b/lib/agent/organization-store.test.ts@@ -10,13 +10,24 @@ afterEach(async () => { delete process.env.OS_ORGANIZATION_STORE; await rm(dir,async function store() { return import("./organization-store"); }describe("organization store", () => {+ it("requires exec to introduce or redirect shared execution targets", async () => {+ const api = await store();+ let chart = await api.getOrganizationChart();+ chart = await api.upsertOrganizationUnit(chart.revision, { id: "unit_a", key: "a", name: "A", kind: "company" });+ const seat = { id: "seat_a", unitId: "unit_a", name: "A", title: "Executor", role: "executor", state: "active", seatMode: "on_demand", target: { kind: "project-agent", project: "reviewed" } };+ await expect(api.upsertOrganizationSeat(chart.revision, seat, "write")).rejects.toThrow("exec authority");+ chart = await api.upsertOrganizationSeat(chart.revision, seat, "exec");+ await expect(api.upsertOrganizationSeat(chart.revision, { ...seat, target: { kind: "project-agent", project: "redirected" } }, "write")).rejects.toThrow("exec authority");+ await expect(api.upsertOrganizationSeat(chart.revision, { ...seat, title: "Reviewed executor" }, "write")).resolves.toMatchObject({ seats: [{ title: "Reviewed executor" }] });+ await expect(api.replaceOrganization(chart.revision, chart, "write")).rejects.toThrow("exec authority");+ });it("persists units/seats privately with revision checks and reporting guards", async () => {const api = await store();let chart = await api.getOrganizationChart();expect(chart.units).toEqual([]); expect(chart.seats).toEqual([]);chart = await api.upsertOrganizationUnit(chart.revision, { id: "unit_root", key: "root", name: "Root", kind: "holding", status: "active", sortOrder: 0 });chart = await api.upsertOrganizationSeat(chart.revision, { id: "seat_ceo", unitId: "unit_root", name: "CEO", title: "Chief Executive Officer", role: "ceo", state: "active", seatMode: "permanent", target: { kind: "none" }, responsibilities: [] });- chart = await api.upsertOrganizationSeat(chart.revision, { id: "seat_cto", unitId: "unit_root", name: "CTO", title: "Chief Technology Officer", role: "cto", state: "active", seatMode: "on_demand", reportsToSeatId: "seat_ceo", target: { kind: "project-agent", project: "mso" }, responsibilities: ["Technology"] });+ chart = await api.upsertOrganizationSeat(chart.revision, { id: "seat_cto", unitId: "unit_root", name: "CTO", title: "Chief Technology Officer", role: "cto", state: "active", seatMode: "on_demand", reportsToSeatId: "seat_ceo", target: { kind: "project-agent", project: "mso" }, responsibilities: ["Technology"] }, "exec");await expect(api.upsertOrganizationSeat(chart.revision, { ...chart.seats.find((s) => s.id === "seat_ceo"), reportsToSeatId: "seat_cto" })).rejects.toThrow(/cycle/i);await expect(api.deleteOrganizationSeat(chart.revision, "seat_ceo")).rejects.toThrow(/direct reports/i);await expect(api.upsertOrganizationUnit("stale", { id: "unit_other", key: "other", name: "Other", kind: "team" })).rejects.toThrow(/revision changed/i);diff --git a/lib/agent/organization-store.ts b/lib/agent/organization-store.tsindex 5c18cb9a..c65c6552 100644--- a/lib/agent/organization-store.ts+++ b/lib/agent/organization-store.ts@@ -1,3 +1,4 @@+import type { Scope } from "@/lib/capabilities/scope";import { isOrganizationFlowAction } from "@/lib/contracts/organization-flow";import { changeOrganizationFlow } from "./organization-flow-mutations";import { createHash, randomUUID } from "node:crypto";@@ -36,10 +37,10 @@ export async function getOrganizationChart() { return structuredClone(await readasync function mutate(expectedRevision: string, fn: (chart: OrganizationChart) => OrganizationChart) { return withSecurityStoreLock(ORGANIZATION_STORE_PATH, async () => { const current = await readUnlocked(); if (current.revision !== expectedRevision) throw new Error("organization revision changed; refresh before editing"); const next = fn(current); await writeUnlocked(next); return structuredClone(next); }); }const touch = (row: Record<string, unknown>, previous?: { createdAt?: string }) => ({ ...row, createdAt: previous?.createdAt || row.createdAt || new Date().toISOString(), updatedAt: new Date().toISOString() });export async function upsertOrganizationUnit(expectedRevision: string, raw: Record<string, unknown>) { return mutate(expectedRevision, (chart) => { const id = typeof raw.id === "string" && raw.id ? raw.id : `unit_${randomUUID()}`; const previous = chart.units.find((u) => u.id === id); const unit = parseOrganizationUnit(touch({ ...raw, id, ...(raw.projectFlow === undefined && previous?.projectFlow ? { projectFlow: previous.projectFlow } : {}) }, previous)); const units = [...chart.units.filter((u) => u.id !== id), unit]; return materialize(chart.name, units, chart.seats); }); }-export async function upsertOrganizationSeat(expectedRevision: string, raw: Record<string, unknown>) { return mutate(expectedRevision, (chart) => { const id = typeof raw.id === "string" && raw.id ? raw.id : `seat_${randomUUID()}`; const previous = chart.seats.find((s) => s.id === id); const seat = parseOrganizationSeat(touch({ ...raw, id }, previous)); const seats = [...chart.seats.filter((s) => s.id !== id), seat]; return materialize(chart.name, chart.units, seats); }); }+export async function upsertOrganizationSeat(expectedRevision: string, raw: Record<string, unknown>, scope: Scope = "write") { return mutate(expectedRevision, (chart) => { const id = typeof raw.id === "string" && raw.id ? raw.id : `seat_${randomUUID()}`; const previous = chart.seats.find((s) => s.id === id); const seat = parseOrganizationSeat(touch({ ...raw, id }, previous)); if (scope !== "exec" && JSON.stringify(previous?.target ?? { kind: "none" }) !== JSON.stringify(seat.target)) throw new Error("exec authority is required to change organization execution bindings"); const seats = [...chart.seats.filter((s) => s.id !== id), seat]; return materialize(chart.name, chart.units, seats); }); }export async function deleteOrganizationUnit(expectedRevision: string, id: string) { return mutate(expectedRevision, (chart) => { if (chart.units.some((u) => u.parentUnitId === id) || chart.seats.some((s) => s.unitId === id)) throw new Error("organization unit still has children or seats"); return materialize(chart.name, chart.units.filter((u) => u.id !== id), chart.seats); }); }export async function deleteOrganizationSeat(expectedRevision: string, id: string) { return mutate(expectedRevision, (chart) => { if (chart.seats.some((s) => s.reportsToSeatId === id)) throw new Error("organization seat still has direct reports"); return materialize(chart.name, chart.units, chart.seats.filter((s) => s.id !== id)); }); }-export async function replaceOrganization(expectedRevision: string, raw: { name?: unknown; units?: unknown; seats?: unknown }) { return mutate(expectedRevision, () => { const units = Array.isArray(raw.units) ? raw.units.map((v) => parseOrganizationUnit(v)) : []; const seats = Array.isArray(raw.seats) ? raw.seats.map((v) => parseOrganizationSeat(v)) : []; return materialize(String(raw.name || "Organization"), units, seats); }); }+export async function replaceOrganization(expectedRevision: string, raw: { name?: unknown; units?: unknown; seats?: unknown }, scope: Scope = "write") { if (scope !== "exec") throw new Error("exec authority is required to replace organization bindings"); return mutate(expectedRevision, () => { const units = Array.isArray(raw.units) ? raw.units.map((v) => parseOrganizationUnit(v)) : []; const seats = Array.isArray(raw.seats) ? raw.seats.map((v) => parseOrganizationSeat(v)) : []; return materialize(String(raw.name || "Organization"), units, seats); }); }export async function mutateOrganizationFlow(diff --git a/lib/auth/device-store.ts b/lib/auth/device-store.tsindex 9c77eb2c..74002510 100644--- a/lib/auth/device-store.ts+++ b/lib/auth/device-store.ts@@ -5,10 +5,7 @@ import os from "os";import path from "path";import { withSecurityStoreLock } from "@/lib/security-store-lock";import {- DeviceRoleError,- isDeviceRole,- storedDeviceRole,- type DeviceRole,+ DeviceRoleError, isDeviceRole, storedDeviceRole, type DeviceRole,} from "./roles";// Server-side device allowlist, implemented for the VPS control plane. The login@@ -21,6 +18,7 @@ export interface ApprovedDevice {label: string;approvedAt: number;lastSeen?: number;+ sessionsRevokedAt?: number;role: DeviceRole;}@@ -72,6 +70,7 @@ function normalizeApproved(raw: unknown): Record<string, ApprovedDevice> {out[id] = {label: typeof row.label === "string" && row.label ? row.label.slice(0, 80) : "approved device",approvedAt: finiteTime(row.approvedAt, 0),+ ...(typeof row.sessionsRevokedAt === "number" && Number.isFinite(row.sessionsRevokedAt) ? { sessionsRevokedAt: row.sessionsRevokedAt } : {}),...(typeof row.lastSeen === "number" && Number.isFinite(row.lastSeen) ? { lastSeen: row.lastSeen } : {}),// Stores written before delegated roles had no role field. Preserve their// historical full access, while malformed future values fail down to viewer.@@ -175,10 +174,18 @@ export async function getApprovedDevice(deviceId: string): Promise<ApprovedDevicreturn store.approved[deviceId] ?? null;}-export async function isApproved(deviceId: string): Promise<boolean> {- return (await getApprovedDevice(deviceId)) !== null;+export function invalidateDeviceSessions(deviceId: string): Promise<void> {+ return mutate(async () => {+ const store = await read();+ if (store.approved[deviceId]) {+ store.approved[deviceId].sessionsRevokedAt = Date.now();+ await write(store);+ }+ });}+export async function isApproved(deviceId: string): Promise<boolean> { return (await getApprovedDevice(deviceId)) !== null; }+/** Mark an approved device as just-seen (best effort). */export function touchApproved(deviceId: string): Promise<void> {return mutate(async () => {diff --git a/lib/auth/live-authorization.ts b/lib/auth/live-authorization.tsnew file mode 100644index 00000000..57f8eed8--- /dev/null+++ b/lib/auth/live-authorization.ts@@ -0,0 +1,12 @@+import { currentSessionPolicy, getApprovedDevice } from "./device-store";+import { configuredSessionCookieScope } from "./session-cookie";+import { deviceSessionValid } from "./live-session";+import { roleAtLeast, type DeviceRole } from "./roles";+import type { SessionPayload } from "./session";++export async function liveSessionAuthorized(session: SessionPayload, role: DeviceRole): Promise<boolean> {+ if (!session.device_id) return false;+ const [device, policy] = await Promise.all([getApprovedDevice(session.device_id), currentSessionPolicy(configuredSessionCookieScope())]);+ return deviceSessionValid(session, device) && roleAtLeast(device.role, role) &&+ session.cookie_scope === policy.scope && session.cookie_epoch === policy.epoch;+}diff --git a/lib/auth/live-session.test.ts b/lib/auth/live-session.test.tsnew file mode 100644index 00000000..b46344e6--- /dev/null+++ b/lib/auth/live-session.test.ts@@ -0,0 +1,26 @@+import { afterAll, expect, it } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import path from "node:path";+import os from "node:os";+import { deviceSessionValid } from "./live-session";+import { createCamoufoxViewerCookie, createCamoufoxViewerTicket, verifyCamoufoxViewerCookie, verifyCamoufoxViewerTicket } from "@/lib/camoufox/viewer-auth";++const root = await mkdtemp(path.join(os.tmpdir(), "mso-live-session-"));+process.env.OS_DEVICE_STORE = path.join(root, "devices.json");+const devices = await import("./device-store");+afterAll(async () => { delete process.env.OS_DEVICE_STORE; await rm(root, { recursive: true, force: true }); });++it("invalidates derived viewer cookies and tickets durably at logout and after reapproval", async () => {+ const id = "a".repeat(32), secret = "s".repeat(32);+ await devices.approveDevice(id); await devices.approveDevice("b".repeat(32));+ const issued = Date.now();+ const ticket = verifyCamoufoxViewerTicket(createCamoufoxViewerTicket(id, secret, issued, issued), secret)!;+ const cookie = verifyCamoufoxViewerCookie(createCamoufoxViewerCookie(id, secret, Date.now(), ticket.issued_at), secret)!;+ expect(deviceSessionValid(cookie, await devices.getApprovedDevice(id))).toBe(true);+ await devices.invalidateDeviceSessions(id);+ expect(deviceSessionValid(cookie, await devices.getApprovedDevice(id))).toBe(false);+ const replay = verifyCamoufoxViewerCookie(createCamoufoxViewerCookie(id, secret, Date.now(), ticket.issued_at), secret)!;+ expect(deviceSessionValid(replay, await devices.getApprovedDevice(id))).toBe(false);+ await devices.revokeDevice(id); await devices.approveDevice(id);+ expect(deviceSessionValid(cookie, await devices.getApprovedDevice(id))).toBe(false);+});diff --git a/lib/auth/live-session.ts b/lib/auth/live-session.tsnew file mode 100644index 00000000..0ce2047f--- /dev/null+++ b/lib/auth/live-session.ts@@ -0,0 +1,9 @@+import type { ApprovedDevice } from "./device-store";+import type { SessionPayload } from "./session";++/** Durable logout and reapproval boundaries apply to every derived session. */+export function deviceSessionValid(session: SessionPayload, device: ApprovedDevice | null): device is ApprovedDevice {+ return !!device && Number.isFinite(session.issued_at) && Number.isFinite(session.expires_at) &&+ session.expires_at > Date.now() && session.issued_at >= device.approvedAt &&+ (device.sessionsRevokedAt === undefined || session.issued_at > device.sessionsRevokedAt);+}diff --git a/lib/auth/require-session.ts b/lib/auth/require-session.tsindex 34f97d6f..cacfc660 100644--- a/lib/auth/require-session.ts+++ b/lib/auth/require-session.ts@@ -1,3 +1,4 @@+import { deviceSessionValid } from "./live-session";import { cookies } from "next/headers";import { configuredSessionCookieScope } from "./session-cookie";import { verifySession, type SessionPayload } from "./session";@@ -28,7 +29,7 @@ export async function getSessionContext(): Promise<SessionContext | null> {const session = verifySession(value, secret());if (!session?.device_id || session.cookie_scope !== policy.scope || session.cookie_epoch !== policy.epoch) continue;const device = await getApprovedDevice(session.device_id);- if (!device) continue;+ if (!deviceSessionValid(session, device)) continue;return { session, device, role: device.role };}return null;diff --git a/lib/camoufox/viewer-auth.ts b/lib/camoufox/viewer-auth.tsindex 232d5ea9..ad70b29b 100644--- a/lib/camoufox/viewer-auth.ts+++ b/lib/camoufox/viewer-auth.ts@@ -17,9 +17,9 @@ function payload(deviceId: string, now: number, ttlMs: number): SessionPayload {};}-export function createCamoufoxViewerTicket(deviceId: string, secret: string, now = Date.now()): string {+export function createCamoufoxViewerTicket(deviceId: string, secret: string, now = Date.now(), issuedAt = now): string {if (secret.length < MIN_SECRET_LEN) throw new Error("viewer signing secret is not configured");- return signSession(payload(deviceId, now, CAMOUFOX_VIEWER_TICKET_TTL_MS), ticketSecret(secret));+ return signSession({ ...payload(deviceId, now, CAMOUFOX_VIEWER_TICKET_TTL_MS), issued_at: issuedAt }, ticketSecret(secret));}export function verifyCamoufoxViewerTicket(token: string, secret: string): SessionPayload | null {@@ -27,9 +27,9 @@ export function verifyCamoufoxViewerTicket(token: string, secret: string): Sessireturn verifySession(token, ticketSecret(secret));}-export function createCamoufoxViewerCookie(deviceId: string, secret: string, now = Date.now()): string {+export function createCamoufoxViewerCookie(deviceId: string, secret: string, now = Date.now(), issuedAt = now): string {if (secret.length < MIN_SECRET_LEN) throw new Error("viewer signing secret is not configured");- return signSession(payload(deviceId, now, CAMOUFOX_VIEWER_COOKIE_TTL_MS), cookieSecret(secret));+ return signSession({ ...payload(deviceId, now, CAMOUFOX_VIEWER_COOKIE_TTL_MS), issued_at: issuedAt }, cookieSecret(secret));}export function verifyCamoufoxViewerCookie(token: string, secret: string): SessionPayload | null {diff --git a/lib/camoufox/viewer-gate.test.ts b/lib/camoufox/viewer-gate.test.tsindex 9b8d5250..19686175 100644--- a/lib/camoufox/viewer-gate.test.ts+++ b/lib/camoufox/viewer-gate.test.ts@@ -153,8 +153,6 @@ describe("the Camoufox split-origin VNC bridge", () => {it("maps an approved sibling viewer to loopback noVNC and strips credentials upstream", async () => {const proxy = await load();const res = await proxy(vnc(viewerCookie(), CAMOUFOX_VIEWER_PUBLIC_PREFIX + "/websockify", {- upgrade: "websocket",- connection: "Upgrade",authorization: "Bearer must-not-leak",}));const target = new URL(rewriteOf(res)!);diff --git a/lib/camoufox/viewer-gate.ts b/lib/camoufox/viewer-gate.tsindex 12b5cf0f..a202b2df 100644--- a/lib/camoufox/viewer-gate.ts+++ b/lib/camoufox/viewer-gate.ts@@ -1,4 +1,5 @@import { NextResponse, type NextRequest } from "next/server";+import { deviceSessionValid } from "@/lib/auth/live-session";import { getApprovedDevice } from "@/lib/auth/device-store";import { roleAtLeast } from "@/lib/auth/roles";import { camoufoxViewerCsp } from "./origin";@@ -39,7 +40,7 @@ async function approvedDevice(token: string, kind: "ticket" | "cookie"): Promise: verifyCamoufoxViewerCookie(token, secret);if (!payload?.device_id) return null;const device = await getApprovedDevice(payload.device_id);- return device && roleAtLeast(device.role, "operator") ? payload.device_id : null;+ return deviceSessionValid(payload, device) && device && roleAtLeast(device.role, "operator") ? payload.device_id : null;}async function hasViewerSession(request: NextRequest): Promise<boolean> {@@ -113,7 +114,7 @@ async function exchangeTicket(request: NextRequest) {const response = new NextResponse(null, { status: 204 });response.cookies.set(CAMOUFOX_VIEWER_COOKIE,- createCamoufoxViewerCookie(deviceId, process.env.OS_SESSION_SECRET ?? ""),+ createCamoufoxViewerCookie(deviceId, process.env.OS_SESSION_SECRET ?? "", Date.now(), verifyCamoufoxViewerTicket(match[1], process.env.OS_SESSION_SECRET ?? "")!.issued_at),{httpOnly: true,secure: true,diff --git a/lib/capabilities/actors.ts b/lib/capabilities/actors.tsindex 34fd71b9..34f65248 100644--- a/lib/capabilities/actors.ts+++ b/lib/capabilities/actors.ts@@ -1,7 +1,8 @@import type { TenantContext } from "@/lib/tenancy/authority";+import type { AuthorizationGrant } from "./authorization-grant";import type { CapabilityToolProfile } from "./tool";-export interface CapabilityAgentContext { tenantContext?: TenantContext; principal?: string; sessionId?: string; workflowActorOverride?: string; toolProfile?: CapabilityToolProfile; trustedOpenAiFileParams?: boolean; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }+export interface CapabilityAgentContext { authorizationGrant?: AuthorizationGrant; tenantContext?: TenantContext; principal?: string; sessionId?: string; workflowActorOverride?: string; toolProfile?: CapabilityToolProfile; trustedOpenAiFileParams?: boolean; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }export function workflowActor(actor: string | undefined, context?: CapabilityAgentContext): string | undefined {if (context?.workflowActorOverride) return context.workflowActorOverride;return context?.principal && context.sessionId ? `${context.principal}#session:${context.sessionId}` : actor;diff --git a/lib/capabilities/authorization-grant.ts b/lib/capabilities/authorization-grant.tsnew file mode 100644index 00000000..c7684c5d--- /dev/null+++ b/lib/capabilities/authorization-grant.ts@@ -0,0 +1,6 @@+import type { SessionPayload } from "@/lib/auth/session";++/** References server-owned authority; never a bearer secret or caller input. */+export type AuthorizationGrant =+ | { kind: "mcp"; id: string; resource: string; fingerprint: string }+ | { kind: "device"; session: SessionPayload };diff --git a/lib/capabilities/execute.ts b/lib/capabilities/execute.tsindex a1fbfd8d..ed7b1b9e 100644--- a/lib/capabilities/execute.ts+++ b/lib/capabilities/execute.ts@@ -133,6 +133,7 @@ export async function executeCapabilityCall(input: {allowedTools: context?.allowedTools,toolArgumentConstraints: context?.toolArgumentConstraints,capabilities: context?.capabilities,+ authorizationGrant: context?.authorizationGrant,toolProfile: context?.toolProfile,trustedOpenAiFileParams: context?.trustedOpenAiFileParams,});diff --git a/lib/capabilities/runtime.ts b/lib/capabilities/runtime.tsindex f1398e15..702efd89 100644--- a/lib/capabilities/runtime.ts+++ b/lib/capabilities/runtime.ts@@ -1,3 +1,4 @@+import type { AuthorizationGrant } from "@/lib/capabilities/authorization-grant";import type { TenantContext } from "@/lib/tenancy/authority";import type { Scope } from "./scope";@@ -18,6 +19,7 @@ export interface CapabilityInvocation {scope: Scope;actor?: string;principal?: string;+ authorizationGrant?: AuthorizationGrant;sessionId?: string;/** Optional fixed workflow context used by durable delegated workers. */workflowId?: string;@@ -30,6 +32,7 @@ export interface CapabilityInvocationResult {}export interface CapabilityRuntime {+ authorize?(grant: AuthorizationGrant, principal: string, name?: string, args?: Record<string, unknown>): Promise<boolean>;list(scope: Scope): CapabilityDescriptor[];invoke(input: CapabilityInvocation): Promise<CapabilityInvocationResult>;}diff --git a/lib/capabilities/tool.ts b/lib/capabilities/tool.tsindex 04f28cc8..970c5a02 100644--- a/lib/capabilities/tool.ts+++ b/lib/capabilities/tool.ts@@ -1,3 +1,4 @@+import type { AuthorizationGrant } from "@/lib/capabilities/authorization-grant";import type { TenantContext } from "@/lib/tenancy/authority";import type { AuditAction } from "@/lib/contracts/audit";import type { CapabilityRuntime } from "./runtime";@@ -60,6 +61,7 @@ export interface CapabilityRunContext {tenantContext?: TenantContext;actor?: string;principal?: string;+ authorizationGrant?: AuthorizationGrant;sessionId?: string;scope: Scope;workflowId?: string;diff --git a/lib/channels/service.ts b/lib/channels/service.tsindex 1a823e5b..8d66de9e 100644--- a/lib/channels/service.ts+++ b/lib/channels/service.ts@@ -1,6 +1,7 @@import { directConnectionValues, integrationSnapshot, resolveIntegration } from "@/lib/infra/connection-service";import { IntegrationError } from "@/lib/infra/identity";import { ChannelError } from "./errors";+import { rateLimited } from "@/lib/host/rate-limit";import { channelProvider, listChannelProviders } from "./registry";import { parseChannelPatch } from "./schema";import {@@ -119,6 +120,7 @@ export async function receiveTelegram(id: string, raw: unknown, suppliedSecret:const credential = await values(channel);if (!credential.webhookSecret) throw new ChannelError("telegram_webhook_secret_required", 503);if (!verifyTelegramSecret(credential, suppliedSecret)) throw new ChannelError("invalid_webhook_signature", 401);+ if (rateLimited(`channel-authenticated:${id}`, 120, 60_000)) throw new ChannelError("rate_limited", 429);return normalizeTelegramUpdate(raw);}@@ -134,6 +136,7 @@ export async function receiveDiscord(const credential = await values(channel);if (!credential.publicKey) throw new ChannelError("discord_public_key_required", 503);if (!verifyDiscordSignature(credential, timestamp, signature, bodyText)) throw new ChannelError("invalid_webhook_signature", 401);+ if (rateLimited(`channel-authenticated:${id}`, 120, 60_000)) throw new ChannelError("rate_limited", 429);let raw: unknown;try { raw = JSON.parse(bodyText); } catch { throw new ChannelError("invalid_discord_interaction"); }if (!discordApplicationMatches(credential, raw)) throw new ChannelError("discord_application_mismatch", 401);diff --git a/lib/channels/webhook-admission.test.ts b/lib/channels/webhook-admission.test.tsnew file mode 100644index 00000000..d068e522--- /dev/null+++ b/lib/channels/webhook-admission.test.ts@@ -0,0 +1,12 @@+import { expect, it, vi } from "vitest";+import { randomUUID } from "node:crypto";++it("bounds ID/IP churn without evicting the global ingress budget", async () => {+ vi.resetModules();+ const { admitChannelWebhook } = await import("./webhook-admission");+ const { rateLimitedUntrusted } = await import("@/lib/host/rate-limit");+ for (let n = 0; n < 600; n++) admitChannelWebhook(new Request("https://host.test", { headers: { "x-forwarded-for": `spoof-${n}` } }), randomUUID());+ for (let n = 0; n < 5000; n++) rateLimitedUntrusted(`unrelated:${n}`, 1, 60_000);+ expect(() => admitChannelWebhook(new Request("https://host.test"), randomUUID())).toThrow("rate_limited");+ expect(() => admitChannelWebhook(new Request("https://host.test"), "arbitrary-id")).toThrow("channel_not_found");+});diff --git a/lib/channels/webhook-admission.ts b/lib/channels/webhook-admission.tsnew file mode 100644index 00000000..c00197ad--- /dev/null+++ b/lib/channels/webhook-admission.ts@@ -0,0 +1,14 @@+import { createHash } from "node:crypto";+import { rateLimitedUntrusted } from "@/lib/host/rate-limit";+import { clientIp } from "@/lib/host/request-ip";+import { ChannelError } from "./errors";++let window = { count: 0, resetAt: 0 };++export function admitChannelWebhook(req: Request, id: string) {+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) throw new ChannelError("channel_not_found", 404);+ const source = createHash("sha256").update(clientIp(req).slice(0, 256)).digest("hex");+ if (Date.now() >= window.resetAt) window = { count: 0, resetAt: Date.now() + 60_000 };+ if (++window.count > 600 || rateLimitedUntrusted(`channel-ingress:source:${source}`, 60, 60_000))+ throw new ChannelError("rate_limited", 429);+}diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.tsindex d70ba0f7..c1108a2f 100644--- a/lib/config/env-example.test.ts+++ b/lib/config/env-example.test.ts@@ -48,6 +48,7 @@ const NOT_A_KNOB: Record<string, string> = {E2E_DEMO: "desktop browser harness only: preview has no authentication; never production configuration",E2E_CAPTURE_ONLY: "desktop browser harness only: capture baseline before native behavior assertions",CHROME_PATH: "MCP Page browser contract harness executable override, not production configuration",+ MSO_SOCKET_POLICY_SECRET: "generated fresh by the production process; never an operator knob",E2E_PASSWORD: "test harness",E2E_DEVICE: "test harness",E2E_HEADED: "test harness",diff --git a/lib/forge/forge.test.ts b/lib/forge/forge.test.tsindex e4671396..dafe1c36 100644--- a/lib/forge/forge.test.ts+++ b/lib/forge/forge.test.ts@@ -64,7 +64,8 @@ describe("eval-gated Tool Forge", () => {const evaluated = { ...candidate, state: "evaluated" as const, evaluation };const promotion = await promoteForgeCandidate(evaluated);const skillDir = path.dirname(promotion.path);- expect(await projectSkillTrust(skillDir, project)).toBe("local");+ expect(await projectSkillTrust(skillDir, project)).toBe("untrusted");+ expect(promotion.verification).toContain("operator review");await expect(promoteForgeCandidate(evaluated)).rejects.toThrow(/overwrite an existing Skill/i);});diff --git a/lib/forge/promote.ts b/lib/forge/promote.tsindex 401d3013..b906ebf0 100644--- a/lib/forge/promote.ts+++ b/lib/forge/promote.ts@@ -2,7 +2,7 @@ import { forgeTargetHash } from "./target-hash";import { createHash } from "node:crypto";import { promises as fs } from "node:fs";import path from "node:path";-import { projectSkillTrust } from "@/lib/skills/project-skills";+import { projectSkillReadable } from "@/lib/skills/project-skills";import { readProjectFunctionsManifest } from "@/lib/host/project-function-manifest";import { forgeCandidateHash } from "./evaluate";import { validateForgeCommand } from "./sandbox";@@ -38,9 +38,8 @@ async function promoteSkill(candidate: ForgeCandidate): Promise<ForgePromotion>const file = path.join(dir, "SKILL.md");try {await fs.writeFile(file, candidate.skill!.content, { mode: 0o600, flag: "wx" });- const trust = await projectSkillTrust(dir, candidate.projectPath);- if (trust !== "local") throw new Error(`promoted Skill did not earn local trust (${trust})`);- return { at: new Date().toISOString(), path: file, verification: "projectSkillTrust=local" };+ if (!await projectSkillReadable(dir, candidate.projectPath)) throw new Error("promoted Skill failed project containment/shape checks");+ return { at: new Date().toISOString(), path: file, verification: "project-contained; untrusted until operator review" };} catch (error) {await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined); throw error;}diff --git a/lib/host/api-error.ts b/lib/host/api-error.tsindex 29085708..1d4e6b14 100644--- a/lib/host/api-error.ts+++ b/lib/host/api-error.ts@@ -12,7 +12,7 @@ export function apiError(fallback: { status?: number; error?: string } = {},): NextResponse {if (e instanceof HostError)- return NextResponse.json({ error: e.message }, { status: 400 });+ return NextResponse.json({ error: e.message }, { status: e.status });// A missing path or a permission denial is a fact about the REQUEST, not a// server fault. They used to fall through to 500, which sends a client (and a// reader of the logs) hunting a broken server when the file simply is not therediff --git a/lib/host/fs-enumeration.test.ts b/lib/host/fs-enumeration.test.tsnew file mode 100644index 00000000..edcd50a7--- /dev/null+++ b/lib/host/fs-enumeration.test.ts@@ -0,0 +1,21 @@+import { afterAll, expect, it } from "vitest";+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++const root = await mkdtemp(path.join(os.tmpdir(), "mso-enumeration-"));+process.env.OS_FS_READ_ROOTS = root;+const { listDir, searchFs } = await import("./fs-enumeration");+afterAll(async () => { delete process.env.OS_FS_READ_ROOTS; await rm(root, { recursive: true, force: true }); });++it("bounds oversized listings, sparse searches and concurrent work, releasing admission after failure", async () => {+ const large = path.join(root, "large"); await mkdir(large);+ for (let n = 0; n < 10_001; n++) await writeFile(path.join(large, `entry-${n}`), "");+ await expect(listDir(large)).rejects.toMatchObject({ status: 413 });+ await expect(searchFs("no-match", { root: large })).rejects.toMatchObject({ status: 413 });+ const first = listDir(large), second = listDir(large);+ await expect(listDir(large)).rejects.toMatchObject({ status: 429 });+ await Promise.allSettled([first, second]);+ await expect(listDir(root)).resolves.toMatchObject({ entries: [{ name: "large" }] });+ await expect(listDir(root, true, AbortSignal.abort())).rejects.toMatchObject({ status: 408 });+}, 15_000);diff --git a/lib/host/fs-enumeration.ts b/lib/host/fs-enumeration.tsnew file mode 100644index 00000000..6fe347c7--- /dev/null+++ b/lib/host/fs-enumeration.ts@@ -0,0 +1,89 @@+import { promises as fs } from "node:fs";+import path from "node:path";+import type { FsList } from "@/lib/os-api/types";+import { HostError } from "./host-error";+import { isCredentialPath, resolveReadable, resolveRoots } from "./paths";+import { projectAliasTarget } from "./project-aliases";++const MAX_ENTRIES = 10_000, MAX_BYTES = 256 * 1024, TIME_MS = 5_000;+let active = 0;+// ponytail: two process-wide scans; per-tenant admission if tenant browsing is added.+async function bounded<T>(signal: AbortSignal | undefined, run: (charge: (bytes?: number) => void) => Promise<T>): Promise<T> {+ if (active >= 2) throw new HostError("Filesystem enumeration busy", 429);+ active++;+ const deadline = Date.now() + TIME_MS;+ let entries = 0, bytes = 0;+ const charge = (size = 0) => {+ if (signal?.aborted) throw new HostError("Filesystem enumeration cancelled", 408);+ if (Date.now() > deadline || ++entries > MAX_ENTRIES || (bytes += size) > MAX_BYTES)+ throw new HostError("Filesystem enumeration budget exceeded; choose a narrower directory", 413);+ };+ let timer: ReturnType<typeof setTimeout> | undefined;+ const work = run(charge).finally(() => { active--; });+ try {+ return await Promise.race([work, new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new HostError("Filesystem enumeration deadline exceeded", 408)), TIME_MS);+ })]);+ } finally { clearTimeout(timer); }+}++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 SEARCH_SKIP = new Set(["node_modules", ".git", ".next", "dist", "build", ".cache", "vendor", ".pnpm-store", ".turbo"]);+export async function searchFs(query: string, opts: { root?: string; max?: number; maxDepth?: number; signal?: AbortSignal } = {}): Promise<{ name: string; path: string; kind: "dir" }[]> {+ const q = query.trim().toLowerCase();+ if (!q) return [];+ return bounded(opts.signal, async (charge) => {+ const root = await resolveReadable(opts.root ?? "~/projects");+ const max = Number.isFinite(opts.max) ? Math.max(1, Math.min(100, Math.trunc(opts.max!))) : 30;+ const maxDepth = Number.isFinite(opts.maxDepth) ? Math.max(0, Math.min(8, Math.trunc(opts.maxDepth!))) : 6;+ const out: { name: string; path: string; kind: "dir" }[] = [];+ const alias = projectAliasTarget(query);+ if (alias) {+ charge();+ const candidate = await resolveReadable(path.join(root, alias)).catch(() => null);+ if (candidate && (await fs.stat(candidate).catch(() => null))?.isDirectory()) return [{ name: alias, path: candidate, kind: "dir" }];+ }+ async function walk(dirPath: string, depth: number): Promise<void> {+ if (out.length >= max || depth > maxDepth) return;+ 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);+ }+ if (!SEARCH_SKIP.has(e.name) && !e.name.startsWith(".")) await walk(hitPath, depth + 1);+ }+ }+ await walk(root, 0);+ return out;+ });+}diff --git a/lib/host/fs.test.ts b/lib/host/fs.test.tsindex d37a6cfe..bcb61516 100644--- a/lib/host/fs.test.ts+++ b/lib/host/fs.test.ts@@ -45,6 +45,15 @@ function useRoots(read: string, write: string) {}describe("writeFile (atomic write inside WRITE roots)", () => {+ it("never follows the old predictable temporary symlink", async () => {+ useRoots(readRoot, writeRoot);+ const target = path.join(writeRoot, "scan-write.txt");+ const victim = path.join(outside, "scan-victim.txt");+ writeFileSync(victim, "untouched");+ symlinkSync(victim, `${target}.tmp-${process.pid}`);+ await writeFile(target, "safe");+ expect(readFileSync(victim, "utf8")).toBe("untouched");+ });it("writes a new file inside the write root", async () => {useRoots(readRoot, writeRoot);const target = path.join(writeRoot, "fresh.txt");diff --git a/lib/host/fs.ts b/lib/host/fs.tsindex 90e69d5f..52e7c7ce 100644--- a/lib/host/fs.ts+++ b/lib/host/fs.ts@@ -2,57 +2,21 @@// 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 path from "path";-import type { FsList, FsUsage } from "@/lib/os-api/types";+import { randomUUID } from "node:crypto";+import type { FsUsage } from "@/lib/os-api/types";import { HostError } from "./host-error";-import { projectAliasTarget } from "./project-aliases";import {appSecretCopyFilter,assertNoAppSecretDescendants,assertNoCredentialDescendants,assertNoSensitiveDescendants,assertNotRoot,- isSensitivePath,resolveReadable,- resolveRoots,safeMkdirPath,safeWritePath,} from "./paths";-export async function listDir(requested: string, includeHidden = true): Promise<FsList> {- const real = await resolveReadable(requested || "~");- const stat = await fs.stat(real);- if (!stat.isDirectory()) throw new HostError("Not a directory");-- const raw = await fs.readdir(real, { withFileTypes: true });- const entries = raw- .filter((e) => includeHidden || !e.name.startsWith("."))- // Sensitive credential dirs don't even appear in listings (they're also- // unreadable via resolveReadable — this just removes the temptation).- .filter((e) => !isSensitivePath(path.join(real, e.name)))- .map((e) => {- const isDir = e.isDirectory() || e.isSymbolicLink();- return {- name: e.name,- kind: isDir ? ("dir" as const) : ("file" as const),- size: 0, // per-entry stat skipped for speed (matches prior agent behavior)- ext: e.name.includes(".") ? e.name.split(".").pop() : undefined,- };- })- .sort((a, b) => (a.kind !== b.kind ? (a.kind === "dir" ? -1 : 1) : a.name.localeCompare(b.name)));-- const parentCandidate = path.dirname(real);- let parent: string | null = null;- if (parentCandidate !== real) {- try {- await resolveReadable(parentCandidate);- parent = parentCandidate;- } catch {- parent = null;- }- }- return { path: real, entries, roots: resolveRoots(), parent };-}+export { listDir, searchFs } from "./fs-enumeration";export async function readFile(requested: string): Promise<string> {const p = await resolveReadable(requested);@@ -74,9 +38,10 @@ 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-${process.pid}`;- await fs.writeFile(tmp, content ?? "", { mode: 0o644 });- await fs.rename(tmp, 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); }}export async function makeDir(requested: string): Promise<void> {@@ -122,49 +87,6 @@ export async function copy(from: string, to: string): Promise<void> {await fs.cp(src, dest, { recursive: true, filter: appSecretCopyFilter(src) });}-// Folder name search under a READ-root dir (default ~/projects). Depth/result-// bounded; skips heavy/noise dirs so it stays snappy on a real projects tree.-const SEARCH_SKIP = new Set([- "node_modules", ".git", ".next", "dist", "build", ".cache", "vendor", ".pnpm-store", ".turbo",-]);--export async function searchFs(- query: string,- opts: { root?: string; max?: number; maxDepth?: number } = {},-): Promise<{ name: string; path: string; kind: "dir" }[]> {- const q = query.trim().toLowerCase();- if (!q) return [];- const root = await resolveReadable(opts.root ?? "~/projects"); // jailed to read roots- const max = opts.max ?? 30;- const maxDepth = opts.maxDepth ?? 6;- const out: { name: string; path: string; kind: "dir" }[] = [];- const alias = projectAliasTarget(query);- if (alias) {- const candidate = await resolveReadable(path.join(root, alias)).catch(() => null);- if (candidate && (await fs.stat(candidate).catch(() => null))?.isDirectory())- return [{ name: alias, path: candidate, kind: "dir" }];- }-- async function walk(dir: string, depth: number): Promise<void> {- if (out.length >= max || depth > maxDepth) return;- let ents: import("fs").Dirent[];- try {- ents = await fs.readdir(dir, { withFileTypes: true });- } catch {- return;- }- for (const e of ents) {- if (out.length >= max) return;- if (!e.isDirectory()) continue;- const hitPath = path.join(dir, e.name);- if (e.name.toLowerCase().includes(q) && !out.some((hit) => hit.path === hitPath)) out.push({ name: e.name, path: hitPath, kind: "dir" });- if (!SEARCH_SKIP.has(e.name) && !e.name.startsWith(".")) await walk(path.join(dir, e.name), depth + 1);- }- }- await walk(root, 0);- return out;-}-export async function usage(requested: string): Promise<FsUsage> {const p = await resolveReadable(requested || "~");const s = await fs.statfs(p);diff --git a/lib/host/host-error.ts b/lib/host/host-error.tsindex 9379d58d..a2062ba3 100644--- a/lib/host/host-error.ts+++ b/lib/host/host-error.ts@@ -5,7 +5,7 @@// Node ENOENT/EACCES errors carrying absolute paths, unexpected exceptions) is// internal: api-error.ts logs it server-side and returns a generic message.export class HostError extends Error {- constructor(message: string) {+ constructor(message: string, public readonly status = 400) {super(message);this.name = "HostError";}diff --git a/lib/host/path-credentials.ts b/lib/host/path-credentials.tsindex 024ba443..f72a594f 100644--- a/lib/host/path-credentials.ts+++ b/lib/host/path-credentials.ts@@ -71,7 +71,9 @@ export function isSensitivePath(real: string): boolean {const h = homeDir();return SENSITIVE_HOME.some((n) => {const p = path.join(h, n);- return real === p || isUnderRoot(real, p);+ let canonical = p;+ try { canonical = realpathSync.native(p); } catch { /* Missing sensitive root. */ }+ return isUnderRoot(real, p) || isUnderRoot(real, canonical);});}@@ -88,7 +90,10 @@ export function isAppSecret(real: string): boolean {export function isCredentialPath(real: string): boolean {const store = path.join(homeDir(), ".mso");if (real === store || isUnderRoot(real, store)) return true;+ try { if (isUnderRoot(real, realpathSync.native(store))) return true; } catch { /* No store yet. */ }if (isSensitivePath(real)) return true;+ const names = path.resolve(real).split(path.sep);+ if (names.some((name) => name.startsWith(".env") && name !== ".env.example")) return true;const base = path.basename(real);// Private keys land anywhere (heredoc dumps, deploy keys, downloaded service// accounts). Their basename/extension is the reliable marker outside fixed ~/ paths.diff --git a/lib/host/path-recursive.ts b/lib/host/path-recursive.tsindex 7be43bc8..990c1338 100644--- a/lib/host/path-recursive.ts+++ b/lib/host/path-recursive.ts@@ -1,4 +1,4 @@-import { existsSync, promises as fs, readdirSync } from "fs";+import { existsSync, promises as fs, readdirSync, realpathSync } from "fs";import path from "path";import { HostError } from "./host-error";import { appDir, isAppSecret, isCredentialPath, SENSITIVE_HOME } from "./path-credentials";@@ -25,10 +25,10 @@ function appSecretsUnder(realBase: string): string[] {// explicitly. Filtered by existence so the callers never refuse (or exclude) over// a path that isn't on this box.function sensitiveUnder(realBase: string): string[] {- if (process.env.OS_FS_ALLOW_SENSITIVE === "1") return [];const h = homeDir();- return [...SENSITIVE_HOME, ".mso"]+ return [...(process.env.OS_FS_ALLOW_SENSITIVE === "1" ? [] : SENSITIVE_HOME), ".mso"].map((n) => path.join(h, n))+ .flatMap((p) => { try { return [p, realpathSync(p)]; } catch { return [p]; } }).filter((p) => p !== realBase && isUnderRoot(p, realBase) && existsSync(p));}diff --git a/lib/host/paths-credentials.test.ts b/lib/host/paths-credentials.test.tsindex bd0f658d..0561fb42 100644--- a/lib/host/paths-credentials.test.ts+++ b/lib/host/paths-credentials.test.ts@@ -108,6 +108,21 @@ describe("recursive credential guard", () => {rmSync(outside, { recursive: true, force: true });});+ it("denies canonical aliases of protected MSO state even with the sensitive escape hatch", () => {+ vi.stubEnv("HOME", fakeHome);+ const target = path.join(fakeHome, "safe", "protected-alias");+ const protectedPath = path.join(fakeHome, ".mso");+ mkdirSync(target);+ symlinkSync(target, protectedPath, process.platform === "win32" ? "junction" : "dir");+ try {+ expect(isCredentialPath(path.join(target, "auth.json"))).toBe(true);+ expect(sensitiveExcludes(fakeHome)).toContain("safe/protected-alias/*");+ vi.stubEnv("OS_FS_ALLOW_SENSITIVE", "1");+ expect(isCredentialPath(path.join(target, "auth.json"))).toBe(true);+ expect(sensitiveExcludes(fakeHome)).toContain("safe/protected-alias/*");+ } finally { rmSync(protectedPath); rmSync(target, { recursive: true }); }+ });+it("honours the OS_FS_ALLOW_SENSITIVE escape hatch", () => {vi.stubEnv("HOME", fakeHome);vi.stubEnv("OS_FS_ALLOW_SENSITIVE", "1");diff --git a/lib/host/paths.test.ts b/lib/host/paths.test.tsindex c5769aef..9cc84037 100644--- a/lib/host/paths.test.ts+++ b/lib/host/paths.test.ts@@ -61,6 +61,13 @@ describe("isUnderRoot", () => {});describe("resolveReadable bounds", () => {+ it("rejects a credential name before resolving its symlink", async () => {+ useRoots(readRoot, writeRoot);+ const link = path.join(writeRoot, ".env.scan");+ symlinkSync(path.join(writeRoot, "wfile.txt"), link);+ await expect(resolveReadable(link)).rejects.toThrow(/credential/i);+ await expect(safeWritePath(link, true)).rejects.toThrow(/credential/i);+ });it("resolves a path inside the read root", async () => {useRoots(readRoot, writeRoot);await expect(resolveReadable(path.join(readRoot, "inside.txt"))).resolves.toBe(diff --git a/lib/host/paths.ts b/lib/host/paths.tsindex bf4c7ed2..d9da0b3b 100644--- a/lib/host/paths.ts+++ b/lib/host/paths.ts@@ -75,6 +75,7 @@ export async function resolveReadable(requested: string): Promise<string> {else if (requested.startsWith("~/")) absolute = path.join(h, requested.slice(2));else absolute = path.resolve(requested);const normalized = path.resolve(absolute);+ assertNotCredential(normalized);const configured = lexicalRoots(readRootList());// Keep each filesystem sink inside the SAFE branch of CodeQL's documented@@ -114,6 +115,7 @@ export async function safeMkdirPath(requested: string): Promise<string> {else if (requested.startsWith("~/")) absolute = path.join(h, requested.slice(2));else absolute = path.resolve(requested);const normalized = path.resolve(absolute);+ assertNotCredential(normalized);const configured = lexicalRoots(writeRootList());for (const root of configured) {@@ -125,6 +127,7 @@ export async function safeMkdirPath(requested: string): Promise<string> {try {const realAncestor = await fs.realpath(ancestor);if (!isUnderRoot(realAncestor, realRoot)) throw new HostError("Path outside writable roots");+ assertNotCredential(path.join(realAncestor, path.relative(ancestor, normalized)));break;} catch (error) {if (error instanceof HostError) throw error;@@ -148,6 +151,7 @@ export async function safeWritePath(requested: string, mustExist: boolean): Promelse if (requested.startsWith("~/")) absolute = path.join(h, requested.slice(2));else absolute = path.resolve(requested);const normalized = path.resolve(absolute);+ assertNotCredential(normalized);const configured = lexicalRoots(writeRootList());const lexicalTarget = mustExist ? normalized : path.dirname(normalized);diff --git a/lib/managed-apps/manager.test.ts b/lib/managed-apps/manager.test.tsindex 0da6b4b4..082797dd 100644--- a/lib/managed-apps/manager.test.ts+++ b/lib/managed-apps/manager.test.ts@@ -44,6 +44,15 @@ afterEach(() => {vi.restoreAllMocks();});+it("never follows a managed-app health redirect outside its reviewed loopback endpoint", async () => {+ systemctl({ "hermes-dashboard.service": ACTIVE });+ const request = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 302, headers: { location: "https://attacker.example/" } }));+ await getManagedApp("hermes");+ const health = request.mock.calls.find(([, init]) => init?.redirect === "error");+ expect(health).toBeDefined();+ expect(["127.0.0.1", "localhost", "[::1]"]).toContain(new URL(String(health![0])).hostname);+});+describe("public-IP dashboard fallback", () => {it("does not advertise 9Router's host port without explicit public exposure", async () => {vi.spyOn(os, "networkInterfaces").mockReturnValue({diff --git a/lib/managed-apps/manager.ts b/lib/managed-apps/manager.tsindex ccfd74aa..cf4a0516 100644--- a/lib/managed-apps/manager.ts+++ b/lib/managed-apps/manager.ts@@ -1,5 +1,6 @@import "server-only";import os from "node:os";+import { managedAppUpstream } from "./upstream-target";import { createBackup } from "./backups";import { getManagedAppDefinition, listManagedAppDefinitions } from "./catalog";import { dockerUsable, requireDocker, runDocker } from "./docker";@@ -67,7 +68,11 @@ async function running(installation: Installation): Promise<boolean> {async function health(definition: ManagedAppDefinition): Promise<boolean | null> {try {- const response = await fetch(`${definition.dashboardUrl.replace(/\/$/, "")}${definition.healthPath ?? "/health"}`, { cache: "no-store", signal: AbortSignal.timeout(4_000) });+ const base = managedAppUpstream(definition.dashboardUrl);+ const target = new URL(definition.healthPath ?? "/health", base);+ if (target.origin !== base.origin) return null;+ const response = await fetch(target, { cache: "no-store", redirect: "error", signal: AbortSignal.timeout(4_000) });+ await response.body?.cancel();return response.ok;} catch {return null;diff --git a/lib/managed-apps/socket-lifetime.test.ts b/lib/managed-apps/socket-lifetime.test.tsnew file mode 100644index 00000000..98ac1b58--- /dev/null+++ b/lib/managed-apps/socket-lifetime.test.ts@@ -0,0 +1,47 @@+import { afterEach, expect, it } from "vitest";+import { createServer, type Server } from "node:http";+import { connect, type Socket } from "node:net";+import { once } from "node:events";+import { attachSocketProxy } from "../../scripts/server-sockets.mjs";++const servers: Server[] = [], sockets: Socket[] = [];+afterEach(async () => {+ for (const socket of sockets.splice(0)) socket.destroy();+ await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));+});+async function listen(server: Server) {+ servers.push(server); server.listen(0, "127.0.0.1"); await once(server, "listening");+ return (server.address() as { port: number }).port;+}++it("stops both forwarding directions and closes idle sockets when live authority disappears", async () => {+ const seen: string[] = [];+ const upstream = createServer();+ let remote: Socket | undefined;+ upstream.on("upgrade", (_request, socket) => {+ remote = socket as Socket; sockets.push(remote);+ socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n");+ socket.on("data", (chunk) => { seen.push(chunk.toString()); socket.write(chunk); });+ });+ const upstreamPort = await listen(upstream);+ let allowed = true;+ const proxy = createServer();+ attachSocketProxy(proxy, async () => allowed ? { identity: "device", target: `http://127.0.0.1:${upstreamPort}/socket`, headers: { upgrade: "websocket", connection: "Upgrade" } } : null);+ const proxyPort = await listen(proxy);+ const client = connect(proxyPort, "127.0.0.1"); sockets.push(client);+ const handshake = once(client, "data");+ client.write("GET /socket HTTP/1.1\r\nHost: app.test\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n");+ expect((await handshake)[0].toString()).toContain("101 Switching Protocols");+ const echo = once(client, "data"); client.write("permitted"); await echo;+ expect(seen).toEqual(["permitted"]);+ allowed = false;+ const closed = once(client, "close"); remote!.write("private-output-after-revoke");+ await closed;+ expect(seen).toEqual(["permitted"]);++ allowed = true;+ const idle = connect(proxyPort, "127.0.0.1"); sockets.push(idle);+ const ready = once(idle, "data"); idle.write("GET /socket HTTP/1.1\r\nHost: app.test\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"); await ready;+ allowed = false;+ await once(idle, "close");+}, 5000);diff --git a/lib/managed-apps/socket-policy.test.ts b/lib/managed-apps/socket-policy.test.tsnew file mode 100644index 00000000..499e2692--- /dev/null+++ b/lib/managed-apps/socket-policy.test.ts@@ -0,0 +1,32 @@+import { afterAll, expect, it } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { NextRequest } from "next/server";+import { signSession } from "@/lib/auth/session";+import { CAMOUFOX_VIEWER_COOKIE, createCamoufoxViewerCookie } from "@/lib/camoufox/viewer-auth";++const root = await mkdtemp(path.join(os.tmpdir(), "mso-socket-policy-"));+process.env.OS_DEVICE_STORE = path.join(root, "devices.json");+process.env.OS_SESSION_SECRET = "s".repeat(32);+process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";+process.env.CAMOUFOX_VIEWER_ORIGIN = "https://viewer.example.net";+process.env.OS_PUBLIC_ORIGIN = "https://mso.example.com";+const devices = await import("@/lib/auth/device-store");+const { socketPolicy } = await import("./socket-policy");+afterAll(async () => { for (const key of ["OS_DEVICE_STORE", "OS_SESSION_SECRET", "NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", "CAMOUFOX_VIEWER_ORIGIN", "OS_PUBLIC_ORIGIN"]) delete process.env[key]; await rm(root, { recursive: true, force: true }); });++it("enforces session generation and live role/revocation for managed and viewer sockets", async () => {+ const id = "a".repeat(32); await devices.approveDevice(id); await devices.approveDevice("b".repeat(32));+ const issued = Date.now(), policy = await devices.currentSessionPolicy("host");+ const signed = signSession({ device_id: id, issued_at: issued, expires_at: issued + 60_000, cookie_scope: policy.scope, cookie_epoch: policy.epoch }, process.env.OS_SESSION_SECRET!);+ const managed = new NextRequest("https://hermes.mso.example.com/socket?ticket=upstream", { headers: { host: "hermes.mso.example.com", origin: "https://hermes.mso.example.com", upgrade: "websocket", connection: "Upgrade", cookie: `session=${signed}`, authorization: "must-not-reach-upstream" } });+ const viewer = new NextRequest("https://viewer.example.net/_mso-camoufox/websockify", { headers: { host: "viewer.example.net", origin: "https://viewer.example.net", upgrade: "websocket", cookie: `${CAMOUFOX_VIEWER_COOKIE}=${createCamoufoxViewerCookie(id, process.env.OS_SESSION_SECRET!, issued)}` } });+ const decision = await socketPolicy(managed);+ expect(decision?.identity).toBe(id); expect(decision?.headers.cookie).toBeUndefined(); expect(decision?.headers.authorization).toBeUndefined();+ expect(await socketPolicy(viewer)).not.toBeNull();+ await devices.invalidateDeviceSessions(id);+ expect(await socketPolicy(managed)).toBeNull(); expect(await socketPolicy(viewer)).toBeNull();+ await devices.setDeviceRole(id, "viewer"); expect(await socketPolicy(managed)).toBeNull();+ await devices.revokeDevice(id); expect(await socketPolicy(managed)).toBeNull();+});diff --git a/lib/managed-apps/socket-policy.ts b/lib/managed-apps/socket-policy.tsnew file mode 100644index 00000000..453036ff--- /dev/null+++ b/lib/managed-apps/socket-policy.ts@@ -0,0 +1,41 @@+import type { NextRequest } from "next/server";+import { verifySession } from "@/lib/auth/session";+import { liveSessionAuthorized } from "@/lib/auth/live-authorization";+import { CAMOUFOX_VIEWER_COOKIE, verifyCamoufoxViewerCookie } from "@/lib/camoufox/viewer-auth";+import { getApprovedDevice } from "@/lib/auth/device-store";+import { deviceSessionValid } from "@/lib/auth/live-session";+import { roleAtLeast } from "@/lib/auth/roles";+import { isCamoufoxViewerHost } from "@/lib/camoufox/origin";+import { camoufoxViewerUpstreamPath } from "@/lib/camoufox/viewer-gate";+import { managedAppIdForHost } from "./origin";+import { getManagedAppDefinition } from "./catalog";+import { managedAppUpstream } from "./upstream-target";+import { upstreamSocketHeaders } from "./proxy-headers";+import { IS_DEMO } from "@/lib/demo";++export async function socketPolicy(request: NextRequest) {+ if (IS_DEMO || request.method !== "GET") return null;+ const host = request.headers.get("host") ?? "", origin = request.headers.get("origin");+ if (origin) { try { if (new URL(origin).host !== host) return null; } catch { return null; } }+ if (!/(?:^|,)\s*websocket\s*(?:,|$)/i.test(request.headers.get("upgrade") ?? "")) return null;+ const viewer = isCamoufoxViewerHost(host), app = managedAppIdForHost(host);+ if (!viewer && !app) return null;+ const secret = process.env.OS_SESSION_SECRET ?? "";+ let identity: string | undefined;+ for (const { value } of request.cookies.getAll(viewer ? CAMOUFOX_VIEWER_COOKIE : "session")) {+ const session = viewer ? verifyCamoufoxViewerCookie(value, secret) : verifySession(value, secret);+ if (!session?.device_id) continue;+ if (viewer) {+ const device = await getApprovedDevice(session.device_id);+ if (!deviceSessionValid(session, device) || !roleAtLeast(device.role, "operator")) continue;+ } else if (!await liveSessionAuthorized(session, "operator")) continue;+ identity = session.device_id; break;+ }+ if (!identity) return null;+ let base: URL;+ try { base = managedAppUpstream(viewer ? process.env.CAMOUFOX_NOVNC_URL ?? "http://127.0.0.1:6080" : getManagedAppDefinition(app!).dashboardUrl); } catch { return null; }+ const pathname = viewer ? camoufoxViewerUpstreamPath(request.nextUrl.pathname) : request.nextUrl.pathname;+ if (!pathname || pathname.startsWith("/_next")) return null;+ const target = new URL(base); target.pathname = pathname; target.search = request.nextUrl.search;+ return { identity, target: target.toString(), headers: Object.fromEntries(upstreamSocketHeaders(request.headers, app ?? undefined, base)) };+}diff --git a/lib/managed-apps/upstream-target.ts b/lib/managed-apps/upstream-target.tsnew file mode 100644index 00000000..16583a42--- /dev/null+++ b/lib/managed-apps/upstream-target.ts@@ -0,0 +1,7 @@+/** Owner-configured endpoint, restricted to an exact local socket and no credentials. */+export function managedAppUpstream(raw: string): URL {+ const url = new URL(raw);+ if (url.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) || url.username || url.password || url.search || url.hash)+ throw new Error("upstream target is not loopback");+ return url;+}diff --git a/lib/mcp/capability-runtime.ts b/lib/mcp/capability-runtime.tsindex 738ce136..8d89e596 100644--- a/lib/mcp/capability-runtime.ts+++ b/lib/mcp/capability-runtime.ts@@ -1,3 +1,4 @@+import { authorizeDurableGrant } from "./durable-grant";import { allows } from "@/lib/capabilities/scope";import { executeCapabilityCall } from "@/lib/capabilities/execute";import { boundedResultText } from "@/lib/capabilities/result-budget";@@ -14,6 +15,7 @@ function successResult(toolName: string, result: unknown): CapabilityInvocationR/** Concrete MSO catalog composed once; MCP/A2A/subagents are adapters over it. */export const msoCapabilityRuntime: CapabilityRuntime = {+ authorize: authorizeDurableGrant,list(scope) {return TOOLS.filter((tool) => allows(scope, tool.scope)).map((tool) => ({name: tool.name,@@ -23,6 +25,7 @@ export const msoCapabilityRuntime: CapabilityRuntime = {}));},async invoke(input) {+ if (input.authorizationGrant && (!input.principal || !await authorizeDurableGrant(input.authorizationGrant, input.principal, input.name, input.args))) return { content: [{ type: "text", text: "error: durable execution grant is revoked, expired or does not allow this tool" }], isError: true };const tool = TOOLS_BY_NAME.get(input.name);if (!tool) return { content: [{ type: "text", text: `error: unknown tool: ${input.name}` }], isError: true };const args = { ...(input.args ?? {}) };@@ -35,6 +38,7 @@ export const msoCapabilityRuntime: CapabilityRuntime = {context: {tenantContext: input.tenantContext,principal: input.principal,+ authorizationGrant: input.authorizationGrant,sessionId: input.sessionId,...(input.workflowActor ? { workflowActorOverride: input.workflowActor } : {}),capabilities: msoCapabilityRuntime,diff --git a/lib/mcp/collision-e2e.test.ts b/lib/mcp/collision-e2e.test.tsindex 4bd32508..a197e585 100644--- a/lib/mcp/collision-e2e.test.ts+++ b/lib/mcp/collision-e2e.test.ts@@ -117,11 +117,10 @@ describe("the 8-hex collision pair stays distinct on every surface", () => {expect(only.skills[0].description).toContain("bravo");});- it("skills_read on the SECOND id returns the SECOND project's instructions", async () => {- const result = await run("skills_read", { name: `${idB()}/deploy` }) as { content: string; project: { id: string } };- expect(result.project.id).toBe(idB());- expect(result.content).toContain("bravo");- expect(result.content).not.toContain("alpha");+ it("skills_read refuses repository instructions even for an exact project id", async () => {+ const result = await run("skills_read", { name: `${idB()}/deploy` }) as { instructionsWithheld: boolean; trust: string; content?: string; project: { id: string } };+ expect(result).toMatchObject({ trust: "untrusted", instructionsWithheld: true, project: { id: idB() } });+ expect(result.content).toBeUndefined();});it("skills_read refuses the ambiguous bare name and offers both exact ids", async () => {@@ -132,10 +131,11 @@ describe("the 8-hex collision pair stays distinct on every surface", () => {it("skills_search surfaces both, each carrying its own project id", async () => {// Identity is independent of the scanner deadline, covered by catalog deadline tests.const now = Date.now(); vi.spyOn(Date, "now").mockReturnValue(now);- const { hits } = await searchSkillMemory("deploy the widget service");+ const { hits } = await searchSkillMemory("deploy the widget service", { includeUntrusted: true });const deploys = hits.filter((h) => h.kind === "skill" && h.id.endsWith("/deploy"));expect(deploys.map((h) => h.id).sort()).toEqual([`${idA()}/deploy`, `${idB()}/deploy`].sort());expect(deploys.find((h) => h.id === `${idB()}/deploy`)?.project?.id).toBe(idB());+ expect(deploys.every((h) => h.trust === "untrusted")).toBe(true);});it("workflow_start resolves the SECOND project from its exact id, not the first", async () => {diff --git a/lib/mcp/dispatch-types.ts b/lib/mcp/dispatch-types.tsindex 99fca8c1..b88b4d71 100644--- a/lib/mcp/dispatch-types.ts+++ b/lib/mcp/dispatch-types.ts@@ -1,3 +1,4 @@+import type { AuthorizationGrant } from "@/lib/capabilities/authorization-grant";import type { TenantContext } from "@/lib/tenancy/authority";import type { CapabilityRuntime } from "@/lib/capabilities/runtime";import type { McpToolProfile } from "./tool-contract";@@ -22,6 +23,7 @@ export interface RpcRequest {export interface McpAgentContext {tenantContext?: TenantContext;principal?: string;+ authorizationGrant?: AuthorizationGrant;sessionId?: string;toolProfile?: McpToolProfile;trustedOpenAiFileParams?: boolean;diff --git a/lib/mcp/durable-grant.test.ts b/lib/mcp/durable-grant.test.tsnew file mode 100644index 00000000..9ffbde46--- /dev/null+++ b/lib/mcp/durable-grant.test.ts@@ -0,0 +1,32 @@+import { afterAll, expect, it } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++const root = await mkdtemp(path.join(os.tmpdir(), "mso-durable-grant-"));+process.env.OS_MCP_STORE = path.join(root, "mcp.json");+process.env.OS_MCP_MAX_SCOPE = "exec";+const store = await import("./store");+const state = await import("./store-state");+const { authorizeDurableGrant, mcpAuthorizationGrant } = await import("./durable-grant");+afterAll(async () => { delete process.env.OS_MCP_STORE; delete process.env.OS_MCP_MAX_SCOPE; await rm(root, { recursive: true, force: true }); });++it("rechecks token identity, scope, resource, tool/argument limits, expiry and revocation", async () => {+ await store.storeToken("credential", { clientId: "durable", label: "worker", scope: "exec", resource: "https://fixture.test/mcp", allowedTools: ["project_agent_run"], toolArgumentConstraints: { project_agent_run: { project: ["reviewed"] } } });+ const token = (await store.validateToken("credential"))!, grant = mcpAuthorizationGrant(token, token.resource!);+ if (grant.kind !== "mcp") throw new Error("fixture grant kind");+ const check = (name = "project_agent_run", args = { project: "reviewed" }) => authorizeDurableGrant(grant, "mcp-client:durable", name, args);+ expect(await check()).toBe(true);+ expect(await check("host_exec")).toBe(false);+ expect(await check("project_agent_run", { project: "other" })).toBe(false);+ expect(await authorizeDurableGrant(grant, "mcp-client:other")).toBe(false);+ expect(await authorizeDurableGrant({ ...grant, resource: "https://other.test/mcp" }, "mcp-client:durable")).toBe(false);+ await state.mutateMcpStore(async () => { const current = await state.readMcpStore(); current.tokens[token.hash].expiresAt = Date.now() - 1; await state.commitMcpStore(current); });+ expect(await check()).toBe(false);+ await store.storeToken("credential", { clientId: "durable", label: "replacement", scope: "exec" });+ expect(await check()).toBe(false);+ const fresh = (await store.validateToken("credential"))!, freshGrant = mcpAuthorizationGrant(fresh, "https://fixture.test/mcp");+ expect(await authorizeDurableGrant(freshGrant, "mcp-client:durable")).toBe(true);+ await store.revokeToken(fresh.hash);+ expect(await authorizeDurableGrant(freshGrant, "mcp-client:durable")).toBe(false);+});diff --git a/lib/mcp/durable-grant.ts b/lib/mcp/durable-grant.tsnew file mode 100644index 00000000..0eb98c30--- /dev/null+++ b/lib/mcp/durable-grant.ts@@ -0,0 +1,37 @@+import { createHash } from "node:crypto";+import type { AuthorizationGrant } from "@/lib/capabilities/authorization-grant";+import { deviceSessionValid } from "@/lib/auth/live-session";+import { currentSessionPolicy, getApprovedDevice } from "@/lib/auth/device-store";+import { configuredSessionCookieScope } from "@/lib/auth/session-cookie";+import { maxScope } from "./scope";+import { readMcpStore } from "./store-state";+import type { McpToken } from "./store-types";+import { toolAllowedForProfile } from "./tool-contract";++function fingerprint(token: McpToken): string {+ const { lastUsedAt: _used, revokedAt: _revoked, ...authority } = token;+ return createHash("sha256").update(JSON.stringify(authority)).digest("hex");+}++export function mcpAuthorizationGrant(token: McpToken & { hash: string }, resource: string): AuthorizationGrant {+ const { hash, ...authority } = token;+ return { kind: "mcp", id: hash, resource, fingerprint: fingerprint(authority) };+}++export async function authorizeDurableGrant(grant: AuthorizationGrant, principal: string, name?: string, args: Record<string, unknown> = {}): Promise<boolean> {+ if (!grant || typeof grant !== "object" || maxScope() !== "exec") return false;+ if (grant.kind === "device") {+ const session = grant.session;+ if (!session.device_id || !["cli:", "web:"].some((prefix) => principal === prefix + session.device_id)) return false;+ const [device, policy] = await Promise.all([getApprovedDevice(session.device_id), currentSessionPolicy(configuredSessionCookieScope())]);+ return deviceSessionValid(session, device) && device.role === "owner" && session.cookie_scope === policy.scope && session.cookie_epoch === policy.epoch;+ }+ if (grant.kind !== "mcp" || !/^[a-f0-9]{64}$/.test(grant.id)) return false;+ const store = await readMcpStore(), token = store.tokens[grant.id];+ if (!token || token.revokedAt || token.scope !== "exec" || token.tenantBinding || token.tenantSubject ||+ token.expiresAt > 0 && token.expiresAt <= Date.now() || token.resource && token.resource !== grant.resource ||+ fingerprint(token) !== grant.fingerprint || principal !== (token.clientId ? `mcp-client:${token.clientId}` : `mcp-token:${grant.id}`)) return false;+ if (!name) return true;+ if (!toolAllowedForProfile(name, token.profile ?? store.clients[token.clientId]?.profile ?? "full") || token.allowedTools && !token.allowedTools.includes(name)) return false;+ return Object.entries(token.toolArgumentConstraints?.[name] ?? {}).every(([key, allowed]) => typeof args[key] === "string" && allowed.includes(args[key] as string));+}diff --git a/lib/mcp/tools-a2a.test.ts b/lib/mcp/tools-a2a.test.tsindex 34cd7de2..d6309660 100644--- a/lib/mcp/tools-a2a.test.ts+++ b/lib/mcp/tools-a2a.test.ts@@ -45,7 +45,7 @@ describe("MCP A2A tools", () => {const out = await tool!.run({ target: "peer", objective: "research", context: "facts only" }, {principal: "mcp-client:test", sessionId, workflowId, scope: "exec", actor: "test",});- expect(mocks.resolve).toHaveBeenCalledWith("peer");+ expect(mocks.resolve).toHaveBeenCalledWith("peer", "exec");expect(mocks.handoff).toHaveBeenCalledWith(peer, "research", "facts only", expect.objectContaining({sourceSessionHash: expect.stringMatching(/^[a-f0-9]{24}$/),sourceWorkflowHash: expect.stringMatching(/^[a-f0-9]{24}$/),@@ -70,22 +70,23 @@ describe("MCP A2A tools", () => {describe("A2A discovery network authority", () => {- it("keeps public HTTPS discovery readable but requires exec for loopback HTTP", async () => {+ it("forwards caller authority into shared discovery for public and loopback targets", async () => {mocks.discover.mockResolvedValue(peer);const tool = byName.get("a2a_agent_discover")!;await expect(tool.run({ url: "https://peer.example" }, {principal: "mcp-client:test", scope: "read", actor: "test",})).resolves.toMatchObject({ name: "Peer" });- expect(mocks.discover).toHaveBeenCalledWith("https://peer.example");+ expect(mocks.discover).toHaveBeenCalledWith("https://peer.example", undefined, "read");mocks.discover.mockClear();await expect(tool.run({ url: "http://127.0.0.1:4555/card" }, {principal: "mcp-client:test", scope: "read", actor: "test",- })).rejects.toThrow(/requires exec/);- expect(mocks.discover).not.toHaveBeenCalled();+ })).resolves.toMatchObject({ name: "Peer" });+ expect(mocks.discover).toHaveBeenCalledWith("http://127.0.0.1:4555/card", undefined, "read");await expect(tool.run({ url: "http://127.0.0.1:4555/card" }, {principal: "mcp-client:test", scope: "exec", actor: "test",})).resolves.toMatchObject({ name: "Peer" });+ expect(mocks.discover).toHaveBeenLastCalledWith("http://127.0.0.1:4555/card", undefined, "exec");});});diff --git a/lib/mcp/tools-a2a.ts b/lib/mcp/tools-a2a.tsindex d9f66459..a67780bb 100644--- a/lib/mcp/tools-a2a.ts+++ b/lib/mcp/tools-a2a.ts@@ -1,4 +1,3 @@-import { isA2ALoopbackUrl } from "@/lib/a2a/network";import { createHash } from "node:crypto";import { cancelA2ATask, discoverA2AAgent, getA2ATask, handoffA2A, listA2AAgents, registerA2AAgent, removeA2AAgent, resolveA2AAgent, sendA2AMessage } from "@/lib/a2a";import type { A2ADiscoveredAgent, A2ARegisteredAgent } from "@/lib/a2a";@@ -20,7 +19,7 @@ function cardSummary(row: A2ADiscoveredAgent | A2ARegisteredAgent) {skills: card.skills.map((skill) => ({ id: skill.id, name: skill.name, description: skill.description, tags: skill.tags })),};}-async function target(ref: string) { return resolveA2AAgent(ref); }+async function target(ref: string, scope: "read" | "write" | "exec") { return resolveA2AAgent(ref, scope); }export const A2A_TOOLS: McpTool[] = [{@@ -36,8 +35,7 @@ export const A2A_TOOLS: McpTool[] = [inputSchema: S({ url: { type: "string", description: "Public agent origin or direct Agent Card URL." } }, ["url"]),run: async (a, context) => {const url = str(a, "url");- if (isA2ALoopbackUrl(url) && context.scope !== "exec") throw new Error("A2A loopback discovery requires exec authority");- return cardSummary(await discoverA2AAgent(url));+ return cardSummary(await discoverA2AAgent(url, undefined, context.scope));},},{@@ -45,7 +43,7 @@ export const A2A_TOOLS: McpTool[] = [description: "Register or refresh one public A2A v1 agent in MSO's private host registry. This stores the Agent Card and alias only; credentials are deliberately unsupported in this phase.",scope: "write", annotations: { openWorldHint: true }, limit: { key: "a2a.registry", max: 20, windowMs: 60_000 }, audit: { action: "a2a.registry", targetArg: "url" },inputSchema: S({ url: { type: "string", description: "Public agent origin or direct Agent Card URL." }, alias: { type: "string", description: "Optional local alias (lowercase letters/digits/._-)." } }, ["url"]),- run: async (a) => cardSummary(await registerA2AAgent(str(a, "url"), optionalString(a, "alias"))),+ run: async (a, context) => cardSummary(await registerA2AAgent(str(a, "url"), optionalString(a, "alias"), context.scope)),},{name: "a2a_agent_remove",@@ -64,8 +62,8 @@ export const A2A_TOOLS: McpTool[] = [context_id: { type: "string", description: "Optional A2A contextId supplied by that remote agent." }, task_id: { type: "string", description: "Optional A2A taskId to continue." },return_immediately: { type: "boolean", description: "Default true: return the task quickly instead of blocking for completion." },}, ["target", "message"]),- run: async (a) => {- const agent = await target(str(a, "target")); const result = await sendA2AMessage(agent, str(a, "message"), {+ run: async (a, context) => {+ const agent = await target(str(a, "target"), context.scope); const result = await sendA2AMessage(agent, str(a, "message"), {contextId: optionalString(a, "context_id"), taskId: optionalString(a, "task_id"), returnImmediately: a.return_immediately !== false,}); return { agent: cardSummary(agent), response: result };},@@ -76,14 +74,14 @@ export const A2A_TOOLS: McpTool[] = [scope: "read", annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true }, limit: { key: "a2a.task", max: 60, windowMs: 60_000 },result: { maxTextBytes: 64 * 1024, overflowHint: "A2A task response was compacted; request less history." },inputSchema: S({ target: { type: "string" }, task_id: { type: "string" }, history_length: { type: "number", description: "0-100, default 10." } }, ["target", "task_id"]),- run: async (a) => getA2ATask(await target(str(a, "target")), str(a, "task_id"), Math.max(0, Math.min(100, Number(a.history_length) || 10))),+ run: async (a, context) => getA2ATask(await target(str(a, "target"), context.scope), str(a, "task_id"), Math.max(0, Math.min(100, Number(a.history_length) || 10))),},{name: "a2a_task_cancel",description: "Request cancellation of one in-progress A2A v1 task. The remote agent remains authoritative about whether cancellation is allowed.",scope: "exec", annotations: { destructiveHint: true, openWorldHint: true }, limit: { key: "a2a.cancel", max: 30, windowMs: 60_000 }, audit: { action: "a2a.cancel", targetArg: "task_id" },inputSchema: S({ target: { type: "string" }, task_id: { type: "string" } }, ["target", "task_id"]),- run: async (a) => cancelA2ATask(await target(str(a, "target")), str(a, "task_id")),+ run: async (a, context) => cancelA2ATask(await target(str(a, "target"), context.scope), str(a, "task_id")),},{name: "a2a_handoff",@@ -96,7 +94,7 @@ export const A2A_TOOLS: McpTool[] = [return_immediately: { type: "boolean", description: "Default true." },}, ["target", "objective"]),run: async (a, context) => {- const agent = await target(str(a, "target"));+ const agent = await target(str(a, "target"), context.scope);const result = await handoffA2A(agent, str(a, "objective"), optionalString(a, "context"), {returnImmediately: a.return_immediately !== false, sourceSessionHash: anonymousHash(context.sessionId), sourceWorkflowHash: anonymousHash(context.workflowId),});diff --git a/lib/mcp/tools-discovery-read.test.ts b/lib/mcp/tools-discovery-read.test.tsindex ef8d93ef..9b3da113 100644--- a/lib/mcp/tools-discovery-read.test.ts+++ b/lib/mcp/tools-discovery-read.test.ts@@ -69,13 +69,10 @@ afterAll(async () => {});describe("skills_read reads the exact catalog id only", () => {- it("returns instructions for a trusted project skill", async () => {- const result = await run("skills_read", { name: await skillId(widgetA, "widget-deploy") }) as- { content: string; project: { name: string }; trust: string };- expect(result.trust).toBe("local");- expect(result.project.name).toBe("widget");- expect(result.content).toContain("# widget-deploy");- expect(result.content).toContain("root A");+ it("withholds repository-controlled project instructions pending operator review", async () => {+ const result = await run("skills_read", { name: await skillId(widgetA, "widget-deploy") }) as { content?: string };+ expect(result).toMatchObject({ trust: "untrusted", instructionsWithheld: true });+ expect(result.content).toBeUndefined();});it("returns instructions for an official global skill", async () => {diff --git a/lib/mcp/tools-discovery.test.ts b/lib/mcp/tools-discovery.test.tsindex f71445a9..92aa5bb2 100644--- a/lib/mcp/tools-discovery.test.ts+++ b/lib/mcp/tools-discovery.test.ts@@ -129,7 +129,7 @@ describe("skills_list spans global and project roots", () => {expect(ids).toContain("mso"); // official, from this repo's claude-skills/expect(ids).toContain(deployA);expect(skills.find((s) => s.id === deployA)).toMatchObject({- trust: "local", instructionsReadable: true, project: { name: "widget" },+ trust: "untrusted", instructionsReadable: false, project: { name: "widget" },});expect(scan).toHaveProperty("truncated");});diff --git a/lib/mcp/tools-learning.test.ts b/lib/mcp/tools-learning.test.tsindex 138f7d5f..4c91054b 100644--- a/lib/mcp/tools-learning.test.ts+++ b/lib/mcp/tools-learning.test.ts@@ -102,7 +102,7 @@ describe("workflow_start bootstrap", () => {]));});- it("searches skills from EVERY project, not just the one the workflow names", async () => {+ it("does not promote repository-owned instructions into trusted workflow guidance", async () => {const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;const result = await start.run({intent: "harvest and verify the orchard dataset export",@@ -110,12 +110,8 @@ describe("workflow_start bootstrap", () => {}, { actor: "mcp:global-skills", scope: "write" as const }) as {search: { hits: Array<{ kind: string; id: string; name: string; trust?: string; project?: { name: string } }> };};- expect(result.search.hits).toEqual(expect.arrayContaining([- expect.objectContaining({- kind: "skill", id: await siblingSkillId(), name: "orchard-harvest",- trust: "local", project: expect.objectContaining({ name: "orchard", path: sibling }),- }),- ]));+ const siblingId = await siblingSkillId();+ expect(result.search.hits.some((hit) => hit.id === siblingId)).toBe(false);});it("tells the client when the discovery scan was incomplete", async () => {diff --git a/lib/mcp/tools-local-agents.ts b/lib/mcp/tools-local-agents.tsindex 2d53a858..f8e0b92e 100644--- a/lib/mcp/tools-local-agents.ts+++ b/lib/mcp/tools-local-agents.ts@@ -68,6 +68,8 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [principal: current.principal,sessionId: current.sessionId,workflowActor: context.workflowActor,+ authorizationGrant: context.authorizationGrant,+ authorizationArguments: a,workflowId: context.workflowId,capabilities: context.capabilities,});@@ -98,6 +100,8 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [intent: typeof a.intent === "string" ? a.intent : undefined,requiresUserRelay: a.requires_user_relay === true,executionAuthorized: context.scope === "exec",+ authorizationGrant: context.authorizationGrant,+ authorizationArguments: a,});},},diff --git a/lib/mcp/tools-organization.ts b/lib/mcp/tools-organization.tsindex a3ec2f87..3efc4246 100644--- a/lib/mcp/tools-organization.ts+++ b/lib/mcp/tools-organization.ts@@ -25,11 +25,11 @@ export const ORGANIZATION_TOOLS: McpTool[] = [run: async (a, context) => {const action = str(a, "action"), revision = str(a, "expected_revision"), data = a.data && typeof a.data === "object" && !Array.isArray(a.data) ? a.data as Record<string, unknown> : {};if (action === "unit_upsert") return { chart: await upsertOrganizationUnit(revision, data) };- if (action === "seat_upsert") return { chart: await upsertOrganizationSeat(revision, data) };+ if (action === "seat_upsert") return { chart: await upsertOrganizationSeat(revision, data, context.scope) };if (action === "unit_delete") return { chart: await deleteOrganizationUnit(revision, str(a, "id")) };if (action === "seat_delete") return { chart: await deleteOrganizationSeat(revision, str(a, "id")) };if (isOrganizationFlowAction(action)) return { chart: await mutateOrganizationFlow(revision, action, data, { principal: context.principal }) };- if (action === "replace") return { chart: await replaceOrganization(revision, data as never) };+ if (action === "replace") return { chart: await replaceOrganization(revision, data as never, context.scope) };throw new Error("unsupported organization action");},},diff --git a/lib/skills/catalog-scan.ts b/lib/skills/catalog-scan.tsindex 864f4fed..124f1d48 100644--- a/lib/skills/catalog-scan.ts+++ b/lib/skills/catalog-scan.ts@@ -7,7 +7,7 @@ import { promises as fs } from "fs";import path from "path";import { readBoundedRegularFile } from "@/lib/host/bounded-read";import { SKILL_FILE, SKILL_SCAN_LIMITS, type ProjectRef, type SkillInfo, type SkillSource, type SkillTrust } from "./catalog-types";-import { projectSkillTrust } from "./project-skills";+import { projectSkillTrust, projectSkillReadable } from "./project-skills";import { readSkillContract } from "./skill-contract";export type RootSpec = {@@ -31,7 +31,7 @@ export type RootSpec = {* SKILL.md is untrusted content we decline rather than truncate.** Parent containment is a SEPARATE concern and belongs to the caller (`scanRoot` for the- * root, `projectSkillTrust` for a project): canonicalizing the parent here would drag the+ * root, `projectSkillReadable` for a project): canonicalizing the parent here would drag the* final component through `realpath` again and reopen exactly this hole.*/export async function readSkillFile(file: string): Promise<string | null> {@@ -114,13 +114,13 @@ export async function scanRoot(processed += 1;// Never follow a directory symlink into an attacker-controlled tree. For project- // skills, containment/ownership/shape are established BEFORE SKILL.md is opened.+ // skills, containment/shape are established BEFORE SKILL.md is opened.if (entry.isDirectory()) {const dir = path.join(spec.path, entry.name);let trust = spec.trust;if (spec.project) {trust = await projectSkillTrust(dir, spec.project.path);- if (trust !== "local") { consumed = seen; continue; }+ if (!await projectSkillReadable(dir, spec.project.path)) { consumed = seen; continue; }}const md = await readSkillFile(path.join(dir, SKILL_FILE));if (md !== null) {diff --git a/lib/skills/project-skills.test.ts b/lib/skills/project-skills.test.tsindex c71d8968..34e0b618 100644--- a/lib/skills/project-skills.test.ts+++ b/lib/skills/project-skills.test.ts@@ -43,7 +43,7 @@ describe("per-project skill discovery", () => {const rows = await catalog(app, home, [one, two]);expect(rows.map((r) => `${r.id}:${r.trust}`).sort()).toEqual(- [`${idFor(one, "ship")}:local`, `${idFor(two, "audit")}:local`].sort());+ [`${idFor(one, "ship")}:untrusted`, `${idFor(two, "audit")}:untrusted`].sort());expect(rows[0]).toMatchObject({ name: "ship", source: "project", project: { name: "one", path: one } });});@@ -121,14 +121,14 @@ describe("project skill trust is earned, not assumed", () => {await expect(projectSkillTrust(dir, proj)).resolves.toBe("untrusted");});- it("trusts a contained, owner-owned, regular-file skill", async () => {+ it("withholds repository instructions even for a contained, owner-owned regular file", async () => {const workspace = await temp();const proj = path.join(workspace, "one");const dir = await skill(path.join(proj, ".hermes/skills"), "patrol", "hermes patrol");- await expect(projectSkillTrust(dir, proj)).resolves.toBe("local");+ await expect(projectSkillTrust(dir, proj)).resolves.toBe("untrusted");});- it("keeps the generic HOME agent roots untrusted even though project roots are promoted", async () => {+ it("keeps the generic HOME agent roots untrusted alongside project roots", async () => {const app = await temp();const home = await temp();await skill(path.join(home, ".claude/skills"), "wander", "discovered in home");diff --git a/lib/skills/project-skills.ts b/lib/skills/project-skills.tsindex cfbf3fa0..923f9128 100644--- a/lib/skills/project-skills.ts+++ b/lib/skills/project-skills.ts@@ -1,20 +1,3 @@-// Per-PROJECT skill roots, across every configured project container.-//-// A skill that lives with the repository it automates is the normal case, and MSO-// was blind to all of them: only global roots (~/.mso/skills, the MSO repo, ~/.claude-// and friends) were cataloged, so an agent working in project X could not see X's own-// SKILL.md. That is capability scoping nobody chose.-//-// Trust is EARNED per directory, never assumed from the path. A project skill reaches-// `local` only when all three hold:-// 1. containment — the skill directory realpaths back inside the project directory,-// so a `.claude/skills -> /tmp/attacker` symlink is discovered, not followed;-// 2. ownership — the skill directory and its SKILL.md belong to the uid MSO runs-// as, so a world-writable drop-in cannot become executable instructions;-// 3. shape — SKILL.md is a regular file, not a symlink to somewhere else.-// Anything else is cataloged as `untrusted`: visible for inspection, instructions-// withheld. The generic HOME agent roots (~/.claude/skills, …) keep their existing-// untrusted behaviour — this promotion is for project-scoped roots only.import { promises as fs } from "fs";import path from "path";import { listProjectDirs, shortId } from "@/lib/host/project-roots";@@ -33,22 +16,6 @@ export const PROJECT_SKILL_DIRS = [export type ProjectSkillRoot = { path: string; project: ProjectRef; priority: number };-function currentUid(): number | undefined {- return typeof process.getuid === "function" ? process.getuid() : undefined;-}--async function ownedByUs(target: string): Promise<boolean> {- const uid = currentUid();- if (uid === undefined) return true; // no uid concept (Windows); containment + shape still apply- const stat = await fs.lstat(target).catch(() => null);- return !!stat && stat.uid === uid;-}--function contains(parent: string, child: string): boolean {- const rel = path.relative(parent, child);- return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));-}-/** The same short-hash identity `lib/host/project-roots` assigns a container, so a* skill's `project.rootId` and a `projects_list` row's `rootId` are the same value. */export function projectRefFor(dir: string, containerPath: string): ProjectRef {@@ -59,19 +26,20 @@ export function projectRefFor(dir: string, containerPath: string): ProjectRef {return { id: `${rootId}/${name}`, name, path: dir, rootId };}-/**- * The trust decision for ONE project skill directory. Exported so the catalog and- * its tests exercise the same three checks rather than a reimplementation.- */-export async function projectSkillTrust(skillDir: string, projectPath: string): Promise<SkillTrust> {- const projectReal = await fs.realpath(projectPath).catch(() => null);- const dirReal = await fs.realpath(skillDir).catch(() => null);- if (!projectReal || !dirReal || !contains(projectReal, dirReal)) return "untrusted";- const file = path.join(dirReal, SKILL_FILE);- const stat = await fs.lstat(file).catch(() => null);- if (!stat?.isFile() || stat.isSymbolicLink()) return "untrusted";- if (!(await ownedByUs(dirReal)) || !(await ownedByUs(file))) return "untrusted";- return "local";+/** Repository content remains untrusted even when checked out by the host owner.+ * Review and copy approved instructions into the external operator skill root. */+export async function projectSkillTrust(_skillDir: string, _projectPath: string): Promise<SkillTrust> {+ return "untrusted";+}++export async function projectSkillReadable(skillDir: string, projectPath: string): Promise<boolean> {+ const project = await fs.realpath(projectPath).catch(() => null);+ const dir = await fs.realpath(skillDir).catch(() => null);+ if (!project || !dir) return false;+ const relative = path.relative(project, dir);+ if (relative.startsWith("..") || path.isAbsolute(relative)) return false;+ const file = await fs.lstat(path.join(skillDir, SKILL_FILE)).catch(() => null);+ return !!file?.isFile() && !file.isSymbolicLink();}/** Every project on the box, already containment- and ownership-checked bydiff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.tsindex 2748de87..c24d1939 100644--- a/lib/workflow/graph-runtime.ts+++ b/lib/workflow/graph-runtime.ts@@ -11,7 +11,7 @@ import { graphObject } from "./graph-schema";import { bindLoopItem, bindWorkflowValue } from "./graph-bindings";import { executeFlowNode, workflowItems, type FlowNodeResult } from "./graph-flow-nodes";import { workflowVariableValues } from "./variables";-import { organizationLocalAgentPrincipal, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";+import { organizationLocalAgentPrincipal, organizationTargetDigest, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";import { workflowCacheDelete, workflowCacheGet, workflowCacheSet } from "./cache-store";import { deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "./data-table-store";import { repeatWorkflow, runWorkflowGraphChild } from "./graph-repeat";@@ -170,6 +170,7 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graphif (typeof config.message !== "string" || !config.message.trim()) throw new Error("agent node requires message");if (typeof config.orgSeatId === "string" && config.orgSeatId) {const seat = await resolveOrganizationSeat(config.orgSeatId), target = seat.target;+ if (config.orgTargetDigest !== organizationTargetDigest(seat)) throw new Error("organization execution binding changed; review and save the workflow before running it");if (seat.state !== "active" || seat.seatMode === "inactive") throw new Error(`organization seat ${seat.title} is not active`);if (target.kind === "project-agent") { const args: Record<string, unknown> = { project: target.project, message: config.message, wait: config.wait !== false, plan_mode: Boolean(config.plan_mode), max_scope: ["read", "write", "exec"].includes(String(config.max_scope)) ? config.max_scope : "write" }; if (context.workflowId) args.workflow_id = context.workflowId; return { output: await callTool("project_agent_run", args, context, resolve), log: `Organization seat ${seat.title} routed to project agent.` }; }if (target.kind === "local-agent") return { output: await callTool("local_agent_request", { target: target.ref, objective: config.message, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, { ...context, principal: organizationLocalAgentPrincipal(principal) }, resolve), log: `Organization seat ${seat.title} routed to local agent.` };diff --git a/lib/workflow/graph-store.ts b/lib/workflow/graph-store.tsindex e6ce0089..42265bbc 100644--- a/lib/workflow/graph-store.ts+++ b/lib/workflow/graph-store.ts@@ -1,3 +1,4 @@+import { organizationTargetDigest, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";import { createHash, randomUUID } from "node:crypto";import { promises as fs } from "node:fs";import path from "node:path";@@ -80,8 +81,20 @@ export async function getWorkflowGraph(principal: string, id: string): Promise<Wreturn (await listWorkflowGraphs(principal)).find((graph) => graph.id === id) ?? null;}+async function bindOrganizationTargets(definition: WorkflowGraphDefinition): Promise<WorkflowGraphDefinition> {+ for (const node of definition.nodes) {+ delete node.config.orgTargetDigest;+ if (node.type === "agent" && typeof node.config.orgSeatId === "string" && node.config.orgSeatId) {+ const seat = await resolveOrganizationSeat(node.config.orgSeatId);+ node.config.orgSeatId = seat.id;+ node.config.orgTargetDigest = organizationTargetDigest(seat);+ }+ }+ return definition;+}+export async function createWorkflowGraph(principal: string, raw: unknown, reason: WorkflowGraphVersionReason = "create", options: { remember?: boolean } = {}): Promise<WorkflowGraph> {- const owner = workflowGraphOwner(principal), definition = parseWorkflowGraphDefinition(raw);+ const owner = workflowGraphOwner(principal), definition = await bindOrganizationTargets(parseWorkflowGraphDefinition(raw));const graph = await withGraphLock(owner, async () => {const store = await readWorkflowGraphStore(owner, principal);if (store.graphs.length >= MAX_GRAPHS) throw new Error("private workflow graph limit reached");@@ -94,7 +107,7 @@ export async function createWorkflowGraph(principal: string, raw: unknown, reaso}export async function updateWorkflowGraph(principal: string, id: string, expectedRevision: string, raw: unknown, reason: WorkflowGraphVersionReason = "update", options: { remember?: boolean } = {}): Promise<WorkflowGraph> {- const owner = workflowGraphOwner(principal), definition = parseWorkflowGraphDefinition(raw);+ const owner = workflowGraphOwner(principal), definition = await bindOrganizationTargets(parseWorkflowGraphDefinition(raw));const graph = await withGraphLock(owner, async () => {const store = await readWorkflowGraphStore(owner, principal), index = store.graphs.findIndex((graph) => graph.id === id);if (index < 0) throw new Error("workflow graph not found");diff --git a/lib/workflow/organization-agent-routing.test.ts b/lib/workflow/organization-agent-routing.test.tsindex 4522e9c5..1c1154fc 100644--- a/lib/workflow/organization-agent-routing.test.ts+++ b/lib/workflow/organization-agent-routing.test.ts@@ -18,10 +18,26 @@ const engine = await import("./graph-engine");afterAll(async () => { delete process.env.OS_ORGANIZATION_STORE; await rm(dir, { recursive: true, force: true }); });describe("workflow organization seat routing", () => {+ it("refuses a saved workflow after even an exec principal redirects its shared target", async () => {+ let chart = await org.getOrganizationChart();+ chart = await org.upsertOrganizationUnit(chart.revision, { id: "unit_drift", key: "drift", name: "Drift", kind: "division" });+ const seat = { id: "seat_drift", unitId: "unit_drift", name: "Executor", title: "Executor", role: "executor", state: "active", seatMode: "on_demand", target: { kind: "project-agent", project: "reviewed" } };+ chart = await org.upsertOrganizationSeat(chart.revision, seat, "exec");+ const graph = await graphs.createWorkflowGraph("binding-review-owner", { name: "Reviewed route", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [+ { id: "start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },+ { id: "agent", name: "Executor", type: "agent", position: { x: 100, y: 0 }, config: { orgSeatId: seat.id, message: "Work" } },+ ], edges: [{ id: "edge", source: "start", target: "agent" }] });+ await org.upsertOrganizationSeat(chart.revision, { ...seat, target: { kind: "project-agent", project: "redirected" } }, "exec");+ const invoke = vi.fn();+ const tool: CapabilityTool = { name: "project_agent_run", description: "fixture", scope: "exec", inputSchema: { type: "object", properties: {} }, run: invoke };+ const started = await engine.startWorkflowGraph(graph, {}, "binding-drift-once", { principal: "binding-review-owner", actor: "binding-review-owner", sessionId: "session", scope: "exec" }, () => tool);+ const done = await engine.workflowGraphRunStatus("binding-review-owner", started.id, 5000);+ expect(done.state).toBe("failed"); expect(done.error).toContain("binding changed"); expect(invoke).not.toHaveBeenCalled();+ });it("routes an Agent node through the seat's project-agent binding", async () => {let chart = await org.getOrganizationChart();chart = await org.upsertOrganizationUnit(chart.revision, { id: "unit_product", key: "product", name: "Product", kind: "division" });- chart = await org.upsertOrganizationSeat(chart.revision, { id: "seat_cto", unitId: "unit_product", name: "CTO", title: "CTO", role: "cto", state: "active", seatMode: "on_demand", target: { kind: "project-agent", project: "project-from-org" } });+ chart = await org.upsertOrganizationSeat(chart.revision, { id: "seat_cto", unitId: "unit_product", name: "CTO", title: "CTO", role: "cto", state: "active", seatMode: "on_demand", target: { kind: "project-agent", project: "project-from-org" } }, "exec");const graph = await graphs.createWorkflowGraph("org-route-owner", { name: "Org route", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [{ id: "start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },{ id: "agent", name: "CTO", type: "agent", position: { x: 120, y: 0 }, config: { orgSeatId: "seat_cto", message: "Ship it", wait: true } },@@ -39,7 +55,7 @@ describe("workflow organization seat routing", () => {it("bridges a Web workflow principal to the same device's native Local Agent namespace", async () => {await devices.approveDevice("aabbccddeeff00112233445566778899", "fixture", "owner");let chart = await org.getOrganizationChart();- chart = await org.upsertOrganizationSeat(chart.revision, { id: "seat_local", unitId: "unit_product", name: "Operator", title: "Operator", role: "operator", state: "active", seatMode: "on_demand", target: { kind: "local-agent", ref: "milo" } });+ chart = await org.upsertOrganizationSeat(chart.revision, { id: "seat_local", unitId: "unit_product", name: "Operator", title: "Operator", role: "operator", state: "active", seatMode: "on_demand", target: { kind: "local-agent", ref: "milo" } }, "exec");const graph = await graphs.createWorkflowGraph("web:aabbccddeeff00112233445566778899", { name: "Local route", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [{ id: "start-local", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },{ id: "agent-local", name: "Operator", type: "agent", position: { x: 120, y: 0 }, config: { orgSeatId: "seat_local", message: "Inspect" } },diff --git a/package.json b/package.jsonindex a501a22b..21e9325c 100644--- a/package.json+++ b/package.json@@ -9,7 +9,7 @@"scripts": {"dev": "next dev --hostname 0.0.0.0 --port 3000","build": "bash scripts/build-safe.sh",- "start": "next start",+ "start": "node scripts/server.mjs","lint": "eslint . --max-warnings=0","typecheck": "tsc --noEmit","test": "node scripts/check-test-toolchain.mjs && vitest run",diff --git a/proxy-websocket.test.ts b/proxy-websocket.test.tsindex 7b1ca81f..e46dfe93 100644--- a/proxy-websocket.test.ts+++ b/proxy-websocket.test.ts@@ -1,7 +1,4 @@-// The WebSocket branch of proxy.ts, split out of proxy.test.ts to stay under the-// 220-line rule. It is the one path where MIDDLEWARE, not a route handler, is all-// that stands between the public internet and an agent gateway: the upgrade never-// reaches the proxy route, so that route's verifyAuth() never runs.+// Socket authorization policy; live forwarding is exercised in socket-lifetime.test.ts.import { describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { signSession } from "./lib/auth/session";@@ -18,7 +15,7 @@ vi.mock("@/lib/auth/device-store", () => ({async function loadProxy(template: string) {vi.resetModules();vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", template);- return (await import("./proxy")).proxy;+ return (await import("./lib/managed-apps/socket-policy")).socketPolicy;}/** As it arrives from Traefik: passHostHeader:true, so Host is the public name. */@@ -28,7 +25,8 @@ function req(host: string, path: string, headers: Record<string, string> = {}):return new NextRequest(`https://${host}${path}`, { headers: h });}-const rewriteOf = (res: Response) => res.headers.get("x-middleware-rewrite");+type Decision = Awaited<ReturnType<typeof import("./lib/managed-apps/socket-policy").socketPolicy>>;+const rewriteOf = (res: Decision) => res?.target ?? null;// A Next route handler cannot service an Upgrade, so before this the OpenClaw// dashboard's gateway socket had nowhere to land and every one of its feature@@ -69,27 +67,27 @@ describe("WebSocket upgrade on an app host", () => {it("requires operator or owner for a managed-app upgrade", async () => {const proxy = await load();approved.role = "viewer";- expect((await proxy(upgradeReq("openclaw.mso.example.com", "/chat", session()))).status).toBe(404);+ expect(await proxy(upgradeReq("openclaw.mso.example.com", "/chat", session()))).toBeNull();approved.role = "operator";expect(rewriteOf(await proxy(upgradeReq("openclaw.mso.example.com", "/chat", session())))).toBe(`${GATEWAY}/chat`);});it("rejects a still-valid HMAC minted under a previous cookie scope", async () =>- expect((await (await load())(upgradeReq("openclaw.mso.example.com", "/chat", session("domain:mso.example.com")))).status).toBe(404));+ expect(await (await load())(upgradeReq("openclaw.mso.example.com", "/chat", session("domain:mso.example.com")))).toBeNull());it("refuses an upgrade carrying no session — nothing downstream would have", async () => {const proxy = await load();const res = await proxy(upgradeReq("openclaw.mso.example.com"));- expect(res.status).toBe(404);+ expect(res).toBeNull();expect(rewriteOf(res)).toBeNull();});it("refuses a forged cookie, and a real one whose device was revoked", async () => {const proxy = await load();- expect((await proxy(upgradeReq("openclaw.mso.example.com", "/", "not-a-real-cookie"))).status).toBe(404);+ expect(await proxy(upgradeReq("openclaw.mso.example.com", "/", "not-a-real-cookie"))).toBeNull();// Valid HMAC is not enough: revoking a device must kill its live sockets too.approved.value = false;- expect((await proxy(upgradeReq("openclaw.mso.example.com", "/", session()))).status).toBe(404);+ expect(await proxy(upgradeReq("openclaw.mso.example.com", "/", session()))).toBeNull();});it("refuses to relay off-box when the gateway env points somewhere public", async () => {@@ -97,7 +95,7 @@ describe("WebSocket upgrade on an app host", () => {vi.stubEnv("OS_SESSION_SECRET", SECRET);approved.value = true;const proxy = await loadProxy(TEMPLATE);- expect((await proxy(upgradeReq("openclaw.mso.example.com", "/", session()))).status).toBe(404);+ expect(await proxy(upgradeReq("openclaw.mso.example.com", "/", session()))).toBeNull();});it("leaves the cockpit host alone — the branch is app-hosts only", async () => {@@ -108,12 +106,9 @@ describe("WebSocket upgrade on an app host", () => {expect(rewriteOf(res)).toBeNull();});- it("does not fire for an ordinary request that merely mentions upgrade", async () => {- const proxy = await load();- const res = await proxy(- req("openclaw.mso.example.com", "/chat", { upgrade: "h2c", cookie: `session=${session()}` }),- );- expect(rewriteOf(res)).toContain("/api/v1/managed-apps/openclaw/proxy");+ it("leaves ordinary requests to the HTTP proxy", async () => {+ const policy = await load();+ expect(await policy(req("openclaw.mso.example.com", "/chat", { upgrade: "h2c", cookie: `session=${session()}` }))).toBeNull();});});@@ -140,7 +135,7 @@ describe("per-app upgrade adapters", () => {"x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https",...extra,}));- const header = (name: string) => res.headers.get(`x-middleware-request-${name}`);+ const header = (name: string) => res?.headers[name] ?? null;return { rewrite: rewriteOf(res), header };}diff --git a/proxy.ts b/proxy.tsindex 2cba760f..8d497b38 100644--- a/proxy.ts+++ b/proxy.ts@@ -26,13 +26,7 @@ import {proxyPrefix,upstreamSocketHeaders,} from "@/lib/managed-apps/proxy-headers";-import { getManagedAppDefinition } from "@/lib/managed-apps/catalog";import { projectIngressDecision, projectIngressHeaders } from "@/lib/managed-apps/project-ingress";-import { verifySession } from "@/lib/auth/session";-import { configuredSessionCookieScope } from "@/lib/auth/session-cookie";-import { currentSessionPolicy, getApprovedDevice } from "@/lib/auth/device-store";-import { roleAtLeast, type DeviceRole } from "@/lib/auth/roles";-import { IS_DEMO } from "@/lib/demo";import { camoufoxViewerCsp, isCamoufoxViewerHost } from "@/lib/camoufox/origin";import {camoufoxViewerAuthorized,@@ -49,7 +43,6 @@ const WEBSOCKET_UPGRADE = /(?:^|,)\s*websocket\s*(?:,|$)/i;// Mirrors SESSION_COOKIE in lib/auth/require-session.ts. Not imported from there:// that module pulls in next/headers, which middleware cannot use.-const SESSION_COOKIE = "session";// Only loopback. dashboardUrl comes from HERMES_DASHBOARD_URL / OPENCLAW_DASHBOARD_URL,// and the upgrade hop below is the one place a rewrite leaves this server — an env@@ -62,28 +55,6 @@ const LOOPBACK_HOST =const CAMOUFOX_NOVNC_URL =process.env.CAMOUFOX_NOVNC_URL ?? "http://127.0.0.1:6080";-// The same read require-session.ts does, minus next/headers: verify EVERY `session=`-// cookie and accept the first that both holds up and is still an approved device.-// Cookies are not isolated by port or path (RFC 6265 §8.5), so document.cookie on the-// same host can add a second one that sorts ahead of the real one; checking only the-// first would let a forged value decide. Revocation is re-checked here too — a valid-// HMAC alone must not outlive the device being removed.-async function hasApprovedSession(- request: NextRequest,- minimumRole: DeviceRole = "viewer",-): Promise<boolean> {- if (IS_DEMO) return false;- const secret = process.env.OS_SESSION_SECRET ?? "";- const policy = await currentSessionPolicy(configuredSessionCookieScope());- for (const { value } of request.cookies.getAll(SESSION_COOKIE)) {- const payload = verifySession(value, secret);- if (!payload?.device_id || payload.cookie_scope !== policy.scope || payload.cookie_epoch !== policy.epoch) continue;- const device = await getApprovedDevice(payload.device_id);- if (device && roleAtLeast(device.role, minimumRole)) return true;- }- return false;-}-// Paths the matcher used to exclude. A matcher cannot exclude by HOST and /_next/*// must be blockable on an app host, so they reach middleware now and are waved// through here instead — identical outcome on the cockpit (no nonce, no policy, no@@ -186,6 +157,7 @@ export async function proxy(request: NextRequest) {// operator obtains a 60-second ticket on the cockpit, carries it only in the URL// fragment, and exchanges it here for a host-only HttpOnly viewer cookie.if (isCamoufoxViewerHost(host)) {+ if (WEBSOCKET_UPGRADE.test(request.headers.get("upgrade") ?? "")) return notFound();const viewerGate = await gateCamoufoxViewer(request, pathname);if (!camoufoxViewerAuthorized(viewerGate)) return viewerGate;if (request.method !== "GET" && request.method !== "HEAD") return notFound();@@ -253,37 +225,9 @@ export async function proxy(request: NextRequest) {if (pathname === "/_next" || pathname.startsWith("/_next/"))return notFound();- // A WebSocket upgrade. A route handler cannot service one — which is why every- // OpenClaw panel sat dead and its windows opened on a terminal instead — but a- // rewrite is not always internal: when the destination origin differs from the- // one Next derived for this request, Next PROXIES it, and its proxy carries the- // upgrade (101 + both pipes). That is the same fork the comment below relies on- // to keep the ordinary rewrite internal; here we want the other side of it.- //- // The upgrade never reaches the proxy route, so the route's verifyAuth() never- // runs and NOTHING below this line protects the socket. Hence the session check- // right here: without it this is an unauthenticated relay from the public- // internet into the agent's gateway.- //- // The head is the same for both apps, and that took a wrong turn to establish:- // Hermes and OpenClaw do want opposite things, but neither difference survives as- // a header. See upstreamSocketHeaders for what was tried and why it was reverted.- // What genuinely differs between them is READINESS, and that already lives per-app- // in feature-cli.ts. The query string is passed verbatim — Hermes' `?ticket=` is- // that socket's entire credential.- if (WEBSOCKET_UPGRADE.test(request.headers.get("upgrade") ?? "")) {- if (!(await hasApprovedSession(request, "operator"))) return notFound();- const base = new URL(getManagedAppDefinition(managedApp).dashboardUrl);- if (!LOOPBACK_HOST.test(base.hostname)) return notFound();- return NextResponse.rewrite(- new URL(`${pathname}${request.nextUrl.search}`, base),- {- request: {- headers: upstreamSocketHeaders(request.headers, managedApp, base),- },- },- );- }+ // The production server owns upgrades and validates live authority in both+ // directions. Stock Next rewrites cannot revoke an already-open socket.+ if (WEBSOCKET_UPGRADE.test(request.headers.get("upgrade") ?? "")) return notFound();const headers = new Headers(request.headers);// set(), not append(): this overwrites whatever copy the client sent.@@ -343,6 +287,7 @@ export async function proxy(request: NextRequest) {MUTATING.has(request.method) &&isApi &&!isMachineProtocol &&+ pathname !== "/api/internal/socket-policy" &&!isWorkflowWebhook &&pathname !== "/api/integrations/setup" &&crossOriginMutation(request)diff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjsindex 631550ad..ebf87a6f 100644--- a/scripts/e2e/release-fixture.mjs+++ b/scripts/e2e/release-fixture.mjs@@ -69,7 +69,7 @@ export async function releaseFixture({ live = false, surfaceApps = [] } = {}) {await new Promise(resolve => reservation.close(resolve));const base = `http://localhost:${port}`;env.OS_PUBLIC_ORIGIN = base;- const server = spawn(process.execPath, ["node_modules/next/dist/bin/next", "start", "--hostname", "127.0.0.1", "--port", String(port)], { env, stdio: ["ignore", "pipe", "pipe"] });+ const server = spawn(process.execPath, ["scripts/server.mjs", "--hostname", "127.0.0.1", "--port", String(port)], { env, stdio: ["ignore", "pipe", "pipe"] });let logs = "";const capture = chunk => { logs = (logs + chunk.toString()).slice(-8000); };server.stdout.on("data", capture); server.stderr.on("data", capture);diff --git a/scripts/lib/gateway-runtime.sh b/scripts/lib/gateway-runtime.shindex a30a6ea4..e6fca312 100644--- a/scripts/lib/gateway-runtime.sh+++ b/scripts/lib/gateway-runtime.sh@@ -71,8 +71,8 @@ gateway_start_runtime_if_needed() {return 0fi- next="$ROOT/node_modules/next/dist/bin/next"- [ -f "$next" ] || gateway_fail "MSO runtime is down and Next is missing; run: mso update"+ next="$ROOT/scripts/server.mjs"+ [ -f "$next" ] || gateway_fail "MSO runtime is down and the production entry point is missing; run: mso update"[ -f "$ROOT/.next/BUILD_ID" ] || gateway_fail "MSO runtime is down and no production build exists; run: mso update"IFS=$'\t' read -r host port < <(gateway_loopback_host_port)[ "$host" = "127.0.0.1" ] || [ "$host" = "localhost" ] \@@ -88,7 +88,7 @@ gateway_start_runtime_if_needed() {(cd "$ROOT" || exit 1nohup /bin/bash "$ROOT/scripts/lib/gateway-held-child.sh" "$$" "$parent_ticks" "$gate" \- env MSO_RUNTIME_INSTANCE_ID="$instance" node "$next" start --hostname 127.0.0.1 --port "$port" \+ env MSO_RUNTIME_INSTANCE_ID="$instance" node "$next" --hostname 127.0.0.1 --port "$port" \>>"$RUNTIME_LOG" 2>&1 &printf '%s\n' "$!") >"$STATE_ROOT/.runtime-pid.$$"diff --git a/scripts/lib/live-runtime.mjs b/scripts/lib/live-runtime.mjsindex b480d6cc..2eb777c8 100644--- a/scripts/lib/live-runtime.mjs+++ b/scripts/lib/live-runtime.mjs@@ -11,6 +11,7 @@ function runtimeCommand(comm, cmdline) {return (/\bnext-server\b/i.test(text) ||/node_modules\/next\/dist\/bin\/next\s+start\b/i.test(text) ||+ /scripts\/server\.mjs(?:\s|$)/i.test(text) ||/\b(?:npm|bun|pnpm)\s+run\s+start(?:\s|$)/i.test(text) ||/\byarn\s+start(?:\s|$)/i.test(text));diff --git a/scripts/mso-gateway-active-recovery.test.ts b/scripts/mso-gateway-active-recovery.test.tsindex 442edddf..ebf53eb0 100644--- a/scripts/mso-gateway-active-recovery.test.ts+++ b/scripts/mso-gateway-active-recovery.test.ts@@ -14,8 +14,8 @@ describe("mso active tunnel runtime recovery", () => {fs.copyFileSync(path.join(ROOT, "package.json"), path.join(root, "package.json"));fs.mkdirSync(path.join(root, ".next"), { recursive: true }); fs.writeFileSync(path.join(root, ".next/BUILD_ID"), "fixture\n");fs.mkdirSync(path.join(root, "node_modules/next/dist/bin"), { recursive: true });- fs.writeFileSync(path.join(root, "node_modules/next/dist/bin/next"), `-const http=require('http'); const args=process.argv.slice(2); const port=Number(args[args.indexOf('--port')+1]);+ fs.writeFileSync(path.join(root, "scripts/server.mjs"), `+import http from 'node:http'; const args=process.argv.slice(2); const port=Number(args[args.indexOf('--port')+1]);http.createServer((req,res)=>{res.setHeader('content-type','application/json');res.end(JSON.stringify({status:'ok',buildId:'recovered-build',runtimeInstanceId:process.env.MSO_RUNTIME_INSTANCE_ID,version:${JSON.stringify(VERSION)}}));}).listen(port,'127.0.0.1');process.on('SIGTERM',()=>process.exit(0));`);diff --git a/scripts/mso-gateway-runtime-signal.test.ts b/scripts/mso-gateway-runtime-signal.test.tsindex 8c4bbca8..ad910a0a 100644--- a/scripts/mso-gateway-runtime-signal.test.ts+++ b/scripts/mso-gateway-runtime-signal.test.ts@@ -21,8 +21,8 @@ describe("mso fallback runtime signal safety", () => {fs.mkdirSync(path.join(root, ".next"), { recursive: true }); fs.writeFileSync(path.join(root, ".next/BUILD_ID"), "fixture\n");fs.mkdirSync(path.join(root, "node_modules/next/dist/bin"), { recursive: true });const pidFile = path.join(f.dir, "runtime-pid");- fs.writeFileSync(path.join(root, "node_modules/next/dist/bin/next"), `-const http=require('http'), fs=require('fs'); const args=process.argv.slice(2);+ fs.writeFileSync(path.join(root, "scripts/server.mjs"), `+import http from 'node:http'; import fs from 'node:fs'; const args=process.argv.slice(2);const port=Number(args[args.indexOf('--port')+1]); fs.writeFileSync(process.env.MSO_TEST_RUNTIME_PID_FILE, String(process.pid));http.createServer((req,res)=>{res.setHeader('content-type','application/json');res.end(JSON.stringify({status:'ok',buildId:'fixture',runtimeInstanceId:process.env.MSO_RUNTIME_INSTANCE_ID,version:${JSON.stringify(VERSION)}}));}).listen(port,'127.0.0.1');process.on('SIGTERM',()=>process.exit(0));diff --git a/scripts/proxy-session-policy.test.ts b/scripts/proxy-session-policy.test.tsindex ad7a08a1..b91ec5f6 100644--- a/scripts/proxy-session-policy.test.ts+++ b/scripts/proxy-session-policy.test.ts@@ -14,7 +14,7 @@ async function loadProxy() {vi.stubEnv("OS_SESSION_SECRET", SECRET);vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", "{id}.mso.example.com");vi.stubEnv("OPENCLAW_DASHBOARD_URL", "http://127.0.0.1:18789");- return (await import("../proxy")).proxy;+ return (await import("../lib/managed-apps/socket-policy")).socketPolicy;}function upgrade(cookieEpoch: string) {@@ -31,7 +31,7 @@ function upgrade(cookieEpoch: string) {describe("proxy session policy epoch", () => {it("rejects a retained token from an older generation of the same scope", async () => {const proxy = await loadProxy();- expect((await proxy(upgrade("epoch-9999999999999999"))).status).toBe(404);- expect((await proxy(upgrade(EPOCH))).headers.get("x-middleware-rewrite")).toBe("http://127.0.0.1:18789/chat");+ expect(await proxy(upgrade("epoch-9999999999999999"))).toBeNull();+ expect((await proxy(upgrade(EPOCH)))?.target).toBe("http://127.0.0.1:18789/chat");});});diff --git a/scripts/server-sockets.mjs b/scripts/server-sockets.mjsnew file mode 100644index 00000000..0884c95d--- /dev/null+++ b/scripts/server-sockets.mjs@@ -0,0 +1,69 @@+import http from "node:http";++/** Keep authority attached to both socket directions for their entire lifetime. */+export function attachSocketProxy(server, authorize) {+ const connections = new Set();+ let active = 0;+ server.on("upgrade", async (request, client, head) => {+ // ponytail: 32 active sockets per process; shard only if real demand exceeds this.+ if (active >= 32 || (request.url?.length ?? 0) > 8192) { client.destroy(); return; }+ active += 1;+ client.pause();+ let upstream, poll, ended = false;+ const close = () => {+ if (ended) return;+ ended = true; active -= 1;+ connections.delete(close);+ clearInterval(poll); client.destroy(); upstream?.destroy();+ };+ connections.add(close);+ client.once("error", close); client.once("close", close);+ try {+ const policy = await authorize(request);+ if (!policy || ended) { close(); return; }+ const target = new URL(policy.target);+ if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || target.username || target.password) { close(); return; }+ const valid = async () => {+ const fresh = await authorize(request).catch(() => null);+ const ok = !ended && fresh?.identity === policy.identity && fresh?.target === policy.target;+ if (!ok) close();+ return ok;+ };+ const pending = http.request(target, { headers: policy.headers, timeout: 5000 });+ client.once("close", () => pending.destroy());+ pending.once("error", close); pending.once("timeout", () => { pending.destroy(); close(); });+ pending.once("response", (response) => { response.destroy(); close(); });+ pending.once("upgrade", async (response, socket, upstreamHead) => {+ upstream = socket;+ socket.pause(); socket.once("error", close); socket.once("close", close);+ if (!await valid()) return;+ const headers = ["upgrade", "connection", "sec-websocket-accept", "sec-websocket-protocol", "sec-websocket-extensions"];+ const handshake = headers.flatMap((name) => typeof response.headers[name] === "string" ? [`${name}: ${response.headers[name]}`] : []);+ client.write(`HTTP/1.1 101 Switching Protocols\r\n${handshake.join("\r\n")}\r\n\r\n`);+ if (upstreamHead.length) client.write(upstreamHead);+ if (head.length) socket.write(head);+ const forward = (source, destination) => {+ source.on("data", (chunk) => {+ source.pause();+ void valid().then((ok) => {+ if (ok) destination.write(chunk, () => { if (!ended) source.resume(); });+ }).catch(close);+ });+ source.once("end", close);+ source.resume();+ };+ forward(client, socket); forward(socket, client);+ // Idle connections are checked too; traffic is checked before every delivery.+ let checking = false;+ poll = setInterval(() => {+ if (checking) return;+ checking = true;+ void valid().finally(() => { checking = false; });+ }, 1000);+ poll.unref();+ });+ pending.end();+ } catch { close(); }+ });+ return () => { for (const close of connections) close(); };+}diff --git a/scripts/server.mjs b/scripts/server.mjsnew file mode 100644index 00000000..19c460cc--- /dev/null+++ b/scripts/server.mjs@@ -0,0 +1,41 @@+import next from "next";+import { createServer, request as httpRequest } from "node:http";+import { randomBytes } from "node:crypto";+import { attachSocketProxy } from "./server-sockets.mjs";++const args = process.argv.slice(2);+const argument = (name, fallback) => args.includes(name) ? args[args.indexOf(name) + 1] : fallback;+const hostname = argument("--hostname", process.env.HOSTNAME ?? "0.0.0.0");+const port = Number(argument("--port", process.env.PORT ?? "3000"));+if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("invalid runtime port");+process.env.MSO_SOCKET_POLICY_SECRET = randomBytes(32).toString("hex");+const internal = createServer();+const app = next({ dev: false, hostname, port, httpServer: internal });+await app.prepare();+internal.on("request", app.getRequestHandler());+await new Promise((resolve) => internal.listen(0, "127.0.0.1", resolve));+const internalOrigin = `http://127.0.0.1:${internal.address().port}`;+// Next owns HTTP on a private socket; only our public server receives upgrades.+const server = createServer((incoming, outgoing) => {+ const hop = httpRequest({ hostname: "127.0.0.1", port: internal.address().port, path: incoming.url, method: incoming.method, headers: incoming.headers }, (response) => {+ outgoing.writeHead(response.statusCode, response.headers); response.pipe(outgoing);+ });+ hop.once("error", () => { if (!outgoing.headersSent) outgoing.writeHead(502); outgoing.end(); });+ incoming.once("aborted", () => hop.destroy());+ outgoing.once("close", () => hop.destroy());+ incoming.pipe(hop);+});+const closeSockets = attachSocketProxy(server, async (request) => {+ const headers = Object.fromEntries(Object.entries(request.headers).filter(([, value]) => typeof value === "string"));+ const host = headers.host;+ if (!host || !request.url?.startsWith("/")) return null;+ const response = await fetch(`${internalOrigin}/api/internal/socket-policy`, {+ method: "POST", redirect: "error", signal: AbortSignal.timeout(3000),+ headers: { "content-type": "application/json", authorization: `Bearer ${process.env.MSO_SOCKET_POLICY_SECRET}` },+ body: JSON.stringify({ url: `http://${host}${request.url}`, headers }),+ });+ return response.ok ? response.json() : null;+});+server.listen(port, hostname);+const shutdown = () => { closeSockets(); server.closeAllConnections(); internal.closeAllConnections(); internal.close(); server.close(() => process.exit(0)); };+process.once("SIGTERM", shutdown); process.once("SIGINT", shutdown);