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): close rescan authorization and isolation gaps
Abdurrahman Fakhrul9d6d4f58f7f4
diff --git a/.env.example b/.env.exampleindex 9de0148c..fa5ef9e6 100644--- a/.env.example+++ b/.env.example@@ -14,9 +14,8 @@ OS_SESSION_SECRET=# Session lifetime in hours (default 24). Keep it short — a live session can run# shell commands. Raise only behind a trusted network.# SESSION_EXPIRY_HOURS=24-# The session cookie is host-only by default. Widening it (OS_SESSION_COOKIE_DOMAIN)-# is ONLY for split-origin managed apps — see that section below; do not set one-# without the other.+# The cockpit session cookie is always host-only. The obsolete OS_SESSION_COOKIE_DOMAIN+# setting is used only for clearing legacy cookies. App hosts use separate tickets.# Experimental source-only tenancy seam. Default legacy leaves current behavior unchanged.# tenant-preview denies unimplemented capabilities and has no live registry/storage adapter.@@ -192,51 +191,12 @@ OS_SESSION_SECRET=# and `window.open('/')` did the same from a plain tab. No CSP can stop either (a# policy binds a realm, not a reference across realms). Only a separate origin can.#-# Set BOTH of the following to serve each dashboard from its OWN host — same-# process, cross-origin — so `window.top` is opaque:-#-# 1. NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE — `{id}` is the app id, so this-# yields hermes.mso.example.com, openclaw.mso.example.com, and 9router.mso.example.com.-# Provision ONLY the explicit managed-app hosts you use; each needs its-# own DNS record + TLS pointing at this app. On such a host the-# middleware rewrites EVERY path into that app's proxy and 404s the rest, so-# the cockpit API does not exist there.-# 2. OS_SESSION_COOKIE_DOMAIN — the session cookie is host-only by default and-# would NOT be sent to those hosts, so the framed dashboard 401s on every-# request. This adds `Domain=`, which sends it to the domain AND every-# subdomain of it.-#-# THE CONSEQUENCE OF SETTING (2) WITHOUT (1): the session cookie is handed to-# every host under that domain, and each one still serves the whole cockpit —-# /api/v1/exec/run included. Anything that can answer on a *.mso.example.com name-# (a future subdomain, a stale DNS record someone else points here, a wildcard-# certificate reused by another service) receives the credential. Only the-# middleware host gating makes the widened cookie safe. Set both, or neither.-#-# Malformed values fail closed to host-only rather than emitting a broken header:-# the domain must be ≥2 DNS labels, not an IP, and must domain-match the request-# host, otherwise the browser drops the whole cookie and login 200s with no-# session. Signed browser sessions are bound to a durable cookie-policy generation-# in the private auth store. Every actual scope transition rotates that generation,-# including returning to an earlier Domain, so older retained/captured tokens never-# become valid again. Sign in again after every scope change.-#-# NEXT_PUBLIC_ is baked into the CLIENT bundle at BUILD time (the server and the-# middleware read it at runtime), so set it BEFORE `bun run build` — not just before-# the restart. Built without it, the browser still points the iframe at the old-# same-origin proxy URL while the server has already stopped answering there, and-# the app window comes up blank.-#-# AND THEN SIGN OUT AND BACK IN. The Domain is attached to the cookie when it is-# ISSUED and never afterwards — there is no sliding refresh — so every session that-# existed before you set this stays host-only and is never sent to the app hosts.-# The cockpit keeps working perfectly and only the dashboards 401, which reads as-# "the app host is broken" and is not. Nothing server-side can detect it either: a-# Cookie header carries no Domain, so a cookie that was never sent looks exactly-# like one that never existed. Turning this on is a three-step change — set, build,-# re-login — and skipping the third is the one that wastes an afternoon.+# Set the template before building. Provision each exact app host with DNS/TLS.+# App dashboards exchange a 60-second ticket for an audience-bound, host-only+# HttpOnly cookie. Cockpit sessions remain host-only and are never sent to apps.+# Existing Domain sessions are invalidated; sign in again after upgrading.# NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE={id}.mso.example.com-# OS_SESSION_COOKIE_DOMAIN=mso.example.com+# OS_SESSION_COOKIE_DOMAIN is obsolete; retained only to clear legacy cookies.# --- Camoufox viewer origin: separate auth, safe sibling by default ---# The Browser viewer does not reuse the cockpit session cookie. An authenticateddiff --git a/app/api/auth/session-cookie.test.ts b/app/api/auth/session-cookie.test.tsindex 102d4e45..20f03ace 100644--- a/app/api/auth/session-cookie.test.ts+++ b/app/api/auth/session-cookie.test.ts@@ -81,9 +81,9 @@ describe("session cookie on the wire — OS_SESSION_COOKIE_DOMAIN set", () => {process.env.OS_SESSION_COOKIE_DOMAIN = "mso.example.com";});- it("login widens to the domain, keeping every other attribute", async () => {+ it("login stays host-only even with a legacy Domain configured", async () => {const [cookie] = await login();- expect(cookie).toContain("Domain=mso.example.com");+ expect(cookie.toLowerCase()).not.toContain("domain=");expect(cookie).toContain("HttpOnly");expect(cookie).toContain("Secure");expect(cookie.toLowerCase()).toContain("samesite=strict");diff --git a/app/api/v1/fs/upload/route.ts b/app/api/v1/fs/upload/route.tsindex a2a69610..1c30a6ae 100644--- a/app/api/v1/fs/upload/route.ts+++ b/app/api/v1/fs/upload/route.ts@@ -6,6 +6,7 @@ import { apiError, invalidRequest } from "@/lib/host/request-api";import { audit } from "@/lib/host/audit-api";import { boundaryFromContentType, parseMultipart, resolveUploadDest, streamFileInto, UploadTooLargeError } from "@/lib/host/fs-api";import { rateLimited } from "@/lib/host/limits-api";+import { managedAppIdForHost, isUnclaimedAppNamespaceHost } from "@/lib/managed-apps/origin";export const runtime = "nodejs";export const dynamic = "force-dynamic";@@ -16,15 +17,34 @@ const FS_UPLOAD_WINDOW_MS = 60_000;// Total request cap, enforced as a RUNNING counter across all parts BEFORE// buffering past it (the body never lands fully in RAM — each part streams to a-// temp file). Sits below next.config `proxyClientMaxBodySize` (256mb).+// temp file). This authenticated route bypasses proxy body cloning.const MAX_TOTAL = 200 * 1024 * 1024; // 200 MiB+let activeUploads = 0;// POST multipart/form-data {dest, file[]} → stream each file (binary-safe) into// dest within WRITE roots. Each `file` part's filename carries its relPath, so// dropped folders keep their structure. The client sends `dest` first.export async function POST(req: Request) {+ const host = req.headers.get("host") ?? new URL(req.url).host;+ if (managedAppIdForHost(host) || isUnclaimedAppNamespaceHost(host))+ return new NextResponse("Not Found", { status: 404 });+ const site = req.headers.get("sec-fetch-site");+ const origin = req.headers.get("origin");+ if (site && site !== "same-origin" && site !== "none")+ return NextResponse.json({ error: "cross_origin_blocked" }, { status: 403 });+ if (origin) {+ try { if (new URL(origin).host !== host) return NextResponse.json({ error: "cross_origin_blocked" }, { status: 403 }); }+ catch { return NextResponse.json({ error: "cross_origin_blocked" }, { status: 403 }); }+ }if (!(await verifyAuth(req)))return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ if (activeUploads >= 4) return NextResponse.json({ error: "uploads_busy" }, { status: 429 });+ activeUploads++;+ try { return await streamUpload(req); }+ finally { activeUploads--; }+}++async function streamUpload(req: Request) {const actor = await getSessionActor();if (rateLimited(`fs.upload:${actor ?? "anon"}`, FS_UPLOAD_MAX, FS_UPLOAD_WINDOW_MS)) {diff --git a/app/api/v1/fs/upload/security.test.ts b/app/api/v1/fs/upload/security.test.tsnew file mode 100644index 00000000..76a774bc--- /dev/null+++ b/app/api/v1/fs/upload/security.test.ts@@ -0,0 +1,30 @@+import { NextRequest } from "next/server";+import { beforeEach, expect, it, vi } from "vitest";+const mocks = vi.hoisted(() => ({ auth: vi.fn(), parse: vi.fn() }));+vi.mock("@/lib/agent/server", () => ({ verifyAuth: mocks.auth }));+vi.mock("@/lib/auth/require-session", () => ({ getSessionActor: async () => "test-owner" }));+vi.mock("@/lib/host/audit-api", () => ({ audit: vi.fn() }));+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: () => false }));+vi.mock("@/lib/host/fs-api", () => ({ boundaryFromContentType: () => "boundary", parseMultipart: mocks.parse, resolveUploadDest: vi.fn(), streamFileInto: vi.fn(), UploadTooLargeError: class extends Error {} }));+beforeEach(() => { vi.resetModules(); mocks.auth.mockReset().mockResolvedValue(false); mocks.parse.mockReset(); vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", "{id}.mso.example.com"); });+const request = (host = "mso.example.com", site = "same-origin") => new NextRequest(`https://${host}/api/v1/fs/upload`, { method: "POST", headers: { host, "sec-fetch-site": site, "content-type": "multipart/form-data; boundary=boundary" }, body: "untouched" });+it("rejects unauthenticated, app-host and cross-origin uploads before parsing any body", async () => {+ const { POST } = await import("./route");+ expect((await POST(request())).status).toBe(401);+ mocks.auth.mockResolvedValue(true);+ expect((await POST(request("hermes.mso.example.com"))).status).toBe(404);+ expect((await POST(request("mso.example.com", "same-site"))).status).toBe(403);+ expect(mocks.parse).not.toHaveBeenCalled();+});+it("admits only four concurrent streams and releases slots after completion", async () => {+ mocks.auth.mockResolvedValue(true);+ let release!: () => void; const wait = new Promise<void>(resolve => { release = resolve; });+ mocks.parse.mockImplementation(async function* () { await wait; });+ const { POST } = await import("./route");+ const pending = Array.from({ length: 8 }, () => POST(request()));+ const blocked = await Promise.race(pending);+ expect(blocked.status).toBe(429); release();+ const statuses = (await Promise.all(pending)).map(result => result.status);+ expect(statuses.filter(status => status === 429)).toHaveLength(4);+ expect((await POST(request())).status).toBe(400);+});diff --git a/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts b/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.tsindex 929379eb..ed8c9a5e 100644--- a/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts+++ b/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts@@ -1,5 +1,5 @@import { NextResponse } from "next/server";-import { verifyAuth } from "@/lib/agent/server";+import { managedAppSession } from "@/lib/managed-apps/session";import { getManagedAppDefinition, isManagedAppId } from "@/lib/managed-apps/catalog";import { managedAppUpstream } from "@/lib/managed-apps/upstream-target";import {@@ -76,7 +76,6 @@ async function readBody(req: Request, limit: number): Promise<ArrayBuffer | null}async function proxy(req: Request, context: { params: Promise<{ id: string; path?: string[] }> }) {- if (!(await verifyAuth(req))) return fail(req, "unauthorized", 401);const params = await context.params;if (!isManagedAppId(params.id)) return fail(req, "unknown managed application", 404);// The dashboard is served from its OWN host and nowhere else. The middleware@@ -94,6 +93,7 @@ async function proxy(req: Request, context: { params: Promise<{ id: string; path// fall back to the CLI view and to opening the app in a browser of the user's own.if (!splitOriginEnabled()) return fail(req, "managed application dashboards are not served on this origin", 404);if (req.headers.get(MANAGED_APP_HOST_HEADER) !== params.id) return fail(req, "not found", 404);+ if (!(await managedAppSession(req, params.id))) return fail(req, "unauthorized", 401);const appOrigin = managedAppOrigin(params.id);if (!appOrigin) return fail(req, "managed application origin is unavailable", 500);// On the app's own host the app IS the origin root — cookies at Path=/, Locationsdiff --git a/app/api/v1/managed-apps/[id]/session/route.ts b/app/api/v1/managed-apps/[id]/session/route.tsnew file mode 100644index 00000000..faf229eb--- /dev/null+++ b/app/api/v1/managed-apps/[id]/session/route.ts@@ -0,0 +1,16 @@+import { NextResponse } from "next/server";+import { getSessionContext } from "@/lib/auth/require-session";+import { roleAtLeast } from "@/lib/auth/roles";+import { isManagedAppId } from "@/lib/managed-apps/catalog";+import { managedAppOrigin } from "@/lib/managed-apps/origin";+import { createManagedAppTicket } from "@/lib/managed-apps/session";+import { IS_DEMO } from "@/lib/demo";++export const dynamic = "force-dynamic";+export async function GET(_req: Request, context: { params: Promise<{ id: string }> }) {+ const session = await getSessionContext();+ if (IS_DEMO || !session || !roleAtLeast(session.role, "operator")) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const { id } = await context.params;+ if (!isManagedAppId(id) || !managedAppOrigin(id)) return NextResponse.json({ error: "unavailable" }, { status: 404 });+ return NextResponse.json({ origin: managedAppOrigin(id), ticket: createManagedAppTicket(id, session.session, process.env.OS_SESSION_SECRET ?? "") }, { headers: { "cache-control": "no-store" } });+}diff --git a/app/api/v1/managed-apps/proxy-split-origin.test.ts b/app/api/v1/managed-apps/proxy-split-origin.test.tsindex ccf64552..d1a4e15c 100644--- a/app/api/v1/managed-apps/proxy-split-origin.test.ts+++ b/app/api/v1/managed-apps/proxy-split-origin.test.ts@@ -10,7 +10,7 @@ type CatalogModule = typeof import("@/lib/managed-apps/catalog");import { beforeEach, describe, expect, it, vi } from "vitest";import { MANAGED_APP_HOST_HEADER } from "@/lib/managed-apps/origin";-vi.mock("@/lib/agent/server", () => ({ verifyAuth: vi.fn(async () => true) }));+vi.mock("@/lib/managed-apps/session", () => ({ managedAppSession: vi.fn(async () => ({ device_id: "test" })) }));const dashboardUrl = { current: "http://127.0.0.1:9119" };vi.mock("@/lib/managed-apps/catalog", async () => {diff --git a/app/api/v1/managed-apps/proxy.test.ts b/app/api/v1/managed-apps/proxy.test.tsindex 640d52de..7ff1de87 100644--- a/app/api/v1/managed-apps/proxy.test.ts+++ b/app/api/v1/managed-apps/proxy.test.ts@@ -7,7 +7,7 @@ type CatalogModule = typeof import("@/lib/managed-apps/catalog");// proxy-containment.test.ts.import { beforeEach, describe, expect, it, vi } from "vitest";-vi.mock("@/lib/agent/server", () => ({ verifyAuth: vi.fn(async () => true) }));+vi.mock("@/lib/managed-apps/session", () => ({ managedAppSession: vi.fn(async () => ({ device_id: "test" })) }));const dashboardUrl = { current: "http://127.0.0.1:9119" };vi.mock("@/lib/managed-apps/catalog", async () => {@@ -51,8 +51,8 @@ beforeEach(async () => {vi.resetModules();dashboardUrl.current = "http://127.0.0.1:9119";fetchMock.mockReset();- const { verifyAuth } = await import("@/lib/agent/server");- vi.mocked(verifyAuth).mockResolvedValue(true);+ const { managedAppSession } = await import("@/lib/managed-apps/session");+ vi.mocked(managedAppSession).mockResolvedValue({ device_id: "test" } as never);});describe("managed-app proxy cookie isolation", () => {@@ -205,8 +205,8 @@ describe("managed-app proxy cookie isolation", () => {describe("managed-app proxy guards", () => {it("returns 401 and never calls the upstream without a session", async () => {- const { verifyAuth } = await import("@/lib/agent/server");- vi.mocked(verifyAuth).mockResolvedValueOnce(false);+ const { managedAppSession } = await import("@/lib/managed-apps/session");+ vi.mocked(managedAppSession).mockResolvedValueOnce(null);const { GET } = await import("./[id]/proxy/[[...path]]/route");const res = await GET(req("chat", { headers: { cookie: "__Host-mapp_hermes_session=x" } }), ctx(["chat"]));expect(res.status).toBe(401);@@ -220,15 +220,15 @@ describe("managed-app proxy guards", () => {// 401 here is most often a session issued before OS_SESSION_COOKIE_DOMAIN was set —// host-only, so never sent to this host — which no status code can convey.it("renders a failure as a page for the frame and as JSON for the upstream's fetch", async () => {- const { verifyAuth } = await import("@/lib/agent/server");+ const { managedAppSession } = await import("@/lib/managed-apps/session");const { GET } = await import("./[id]/proxy/[[...path]]/route");- vi.mocked(verifyAuth).mockResolvedValueOnce(false);+ vi.mocked(managedAppSession).mockResolvedValueOnce(null);const framed = await GET(req("chat", { headers: { "sec-fetch-dest": "iframe" } }), ctx(["chat"]));expect(framed.headers.get("content-type")).toContain("text/html");expect(await framed.text()).toContain("sign in again");- vi.mocked(verifyAuth).mockResolvedValueOnce(false);+ vi.mocked(managedAppSession).mockResolvedValueOnce(null);const xhr = await GET(req("api/status", { headers: { "sec-fetch-dest": "empty" } }), ctx(["api", "status"]));expect(xhr.headers.get("content-type")).toContain("application/json");expect(await xhr.json()).toEqual({ error: "unauthorized" });diff --git a/docs/BATONLY-FEDERATION.md b/docs/BATONLY-FEDERATION.mdindex 993791a2..6f70dfe0 100644--- a/docs/BATONLY-FEDERATION.md+++ b/docs/BATONLY-FEDERATION.md@@ -34,8 +34,27 @@ For `source=mso`:3. Require Batonly's request scope to equal the tool's declared scope.4. Require explicit confirmation for every write/exec operation.5. Refuse recursive `project_mcp_call` back into the Baton MCP.-6. Execute through `executeCapabilityCall` with principal `batonly-federation`, preserving required args, rate limits, workflow correlation, activity and audit.-7. Sanitize/bound the result before returning it to Baton.+6. Consume an exact, one-use local Owner approval; remote scope and confirmation are only request data.+7. Execute through `executeCapabilityCall` with principal `batonly-federation`, preserving required args, rate limits, workflow correlation, activity and audit.+8. Sanitize/bound the result before returning it to Baton.++## Local Owner approval++Both sources deny execution by default. An Owner using the trusted local terminal must review the entire request and resolve its `projectId` to an exact local project. Approval is a private entry in `~/.mso/private/federation-approvals.json` (directory 0700, file 0600, owned by the MSO Unix user), keyed by the request's exact `id`:++```json+{+ "reviewed-request-id": {+ "principal": "batonly-federation",+ "requestDigest": "sha256-of-the-exact-reviewed-request",+ "expiresAt": 0+ }+}+```++Compute `requestDigest` with the exported `federationRequestDigest(request)` from `lib/federation/local-approval.ts`, using the reviewed `id`, `projectId`, `source` (`mso` or `si-coder`), `operation`, `scope` and `arguments`. Set `expiresAt` to a future Unix timestamp in milliseconds, at most 24 hours away; zero in the example intentionally grants nothing. Make updates atomically under `withSecurityStoreLock` using the same private path. Do not copy a remote digest without reviewing the corresponding arguments. Removing an unused entry revokes it; changing any reviewed field requires a new approval. MSO persists `usedAt` before dispatch, so retries and concurrent replays cannot reuse the entry.++MSO project arguments and execution directories must match the approved local project. Durable jobs and agent/workflow delegation are unavailable through federation until they can carry and revalidate the local grant. Local approval does not override the deployment capability ceiling or credential filters. Never keep this approval file in a project or accept it from Baton.## SI-Coder executiondiff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 7f745c4e..a6458952 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -12,6 +12,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Fixed**+- `security` close rescan authorization and isolation gaps- `agent-vault` reuse shared styles within the shell bundle budget- `security` pin bounded MCP store reads to one descriptor- `oauth` keep registered consent within narrow viewportsdiff --git a/docs/MANAGED-APPS.md b/docs/MANAGED-APPS.mdindex 5517e1ed..f3e89a91 100644--- a/docs/MANAGED-APPS.md+++ b/docs/MANAGED-APPS.md@@ -185,6 +185,11 @@ Snapshots live under:They may contain credentials and should be protected like the app's original state. Thesnapshot directory is private and its manifest is `0600`.+Stop every app service before taking a snapshot, updating or restoring. MSO checks all+catalog units in both systemd scopes and all discovered containers under the operation+lease; an external restart detected during the copy aborts it and removes the incomplete+snapshot. A restore reports its safety snapshot if copying had already begun.+Snapshots skip symlinks and recursively exclude reinstallable/cache trees such as`node_modules`, `.venv`, `venv`, `__pycache__`, `.git`, `.cache`, and nested `backups`.The manifest records the app, original source path, reason, file/byte counts and exclusions.diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 85246edb..50605fad 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -10,6 +10,15 @@ Bounded capture projects canonical agent/project pages, progress logs, platformRegressions cover repo isolation, source preservation, corrupt manifests, secret/transcript exclusion, path/symlink refusal, private permissions, owner access and scope/audit parity. Synthetic browser journeys exercise note reads, changed/old snapshots, search, mobile reflow and live role revocation. The fixed snapshot ceiling refuses further capture without deleting history; no automatic schedule or native desktop launch is added to the portable feature. Agent Vault follows Settings in the mobile catalog so existing first-page apps stay reachable. Compact expandable details keep notes reachable in short landscape windows, and shared sidebar styles preserve the existing shell CSS budget. Compact ChatGPT one-line descriptions use a smaller character cap to admit the two tools within the existing scanner budget, retaining all names, schemas, scopes and permission checks.+## 2026-10-09: Close the ten findings from the b2f4f607 cloud scan++Remote federation scope/confirmation fields no longer grant local authority. Every MSO and standalone SI-Coder request needs a private, one-use Owner approval bound to its exact request, project, operation, scope and arguments, with a maximum 24-hour expiry. Missing, revoked, expired, changed and replayed approvals fail closed. Durable federation delegation remains unavailable until it can propagate a revocable local grant.++Opened filesystem descriptors reject virtual kernel filesystems even through bind mounts; text/binary reads count actual bytes. Isolated workflows pin their worktree boundary throughout capability calls and validate actual write descriptors and process directories. Hermes lifecycle/state checks include every catalog unit and both systemd scopes; backup/update snapshots require every service to be stopped and recheck throughout copying; restore rechecks after its undo snapshot and during copying. The operation lease prevents concurrent MSO lifecycle actions; a detected external restart aborts the snapshot or restore.++Owner channel configuration binds the exact graph owner, node and revision, rejecting ambiguous IDs and requiring legacy bindings to be reviewed again. Organization local sessions retain the original web execution principal despite using a CLI alias to find the stored session; delegated calls recheck the live device. Discord rejects stale/future signed requests, and a bounded durable admission receipt precedes session allocation. Stored A2A credentials require exec authority even for task reads.++Cockpit cookies are always host-only, invalidating legacy Domain sessions. Managed-app dashboards and sockets use separate origin- and purpose-bound credentials bootstrapped from a short-lived ticket; users must sign in again and reopen dashboard windows. Public middleware body cloning is bounded to 1 MiB; the exact upload endpoint bypasses cloning, enforces its own app-host/CSRF/Owner gate before reading, streams up to 200 MiB and admits four concurrent uploads. Tests cover the real filesystem/store boundaries, signature purposes, role/revocation, colliding graph IDs, concurrent replay admission, all-unit stop and service restart before restore. Independent cloud reassessment remains required after release.## 2026-10-09: Pin the bounded MCP store read and review the inference-test alertdiff --git a/frontend/slices/managed-apps/feature-app.tsx b/frontend/slices/managed-apps/feature-app.tsxindex 5ba15017..40d411c3 100644--- a/frontend/slices/managed-apps/feature-app.tsx+++ b/frontend/slices/managed-apps/feature-app.tsx@@ -1,7 +1,7 @@"use client";import { ExternalLink, RefreshCw, TerminalSquare } from "lucide-react";-import { Suspense, useCallback, useState } from "react";+import { Suspense, useCallback, useEffect, useState } from "react";import type { AppProps } from "@/features/appshell";import { Terminal } from "@/features/os-terminal";import type { ManagedAppFeature } from "@/lib/managed-apps/types";@@ -18,9 +18,26 @@ export function ManagedFeatureApp({ feature, publicDashboardUrl }: AppProps & {// not iframe an http:// public IP inside an https:// cockpit (mixed content), and we// never fall back to a same-origin vendor iframe.const [generation, setGeneration] = useState(0);+ const [authorization, setAuthorization] = useState<{ source: string; url: string } | null>(null);+ const [authorizationError, setAuthorizationError] = useState(false);const [view, setView] = useState<"ui" | "cli">(() => (uiAvailable ? "ui" : "cli"));const reload = useCallback(() => setGeneration((value) => value + 1), []);+ useEffect(() => {+ if (surface.kind !== "embedded" || !embeddedSource) return;+ const controller = new AbortController();+ void fetch(`/api/v1/managed-apps/${feature.applicationId}/session`, { cache: "no-store", signal: controller.signal }).then(async response => {+ if (!response.ok) throw new Error("authorization failed");+ const data = await response.json();+ const url = new URL(embeddedSource);+ if (url.origin !== data.origin || typeof data.ticket !== "string") throw new Error("authorization origin mismatch");+ const fragment = new URLSearchParams(url.hash.slice(1));+ fragment.set("app_ticket", data.ticket); url.hash = fragment.toString();+ setAuthorization({ source: embeddedSource, url: url.toString() }); setAuthorizationError(false);+ }).catch(() => { if (!controller.signal.aborted) setAuthorizationError(true); });+ return () => controller.abort();+ }, [embeddedSource, feature.applicationId, generation, surface.kind]);+ const authorizedSource = authorization?.source === embeddedSource ? authorization.url : null;return (<div className="flex h-full min-h-0 flex-col bg-background text-foreground">@@ -33,7 +50,7 @@ export function ManagedFeatureApp({ feature, publicDashboardUrl }: AppProps & {{uiAvailable ? (<>{!directSource ? <button type="button" onClick={reload} className="rounded-md border border-border p-2 text-muted-foreground hover:text-foreground" aria-label="Refresh feature"><RefreshCw className="size-3.5" /></button> : null}- <a href={surface.source ?? undefined} target="_blank" rel="noreferrer" className="rounded-md border border-border p-2 text-muted-foreground hover:text-foreground" aria-label="Open feature in dedicated tab"><ExternalLink className="size-3.5" /></a>+ <a href={directSource ?? authorizedSource ?? undefined} target="_blank" rel="noreferrer" className="rounded-md border border-border p-2 text-muted-foreground hover:text-foreground" aria-label="Open feature in dedicated tab"><ExternalLink className="size-3.5" /></a></>) : null}</header>@@ -75,10 +92,12 @@ export function ManagedFeatureApp({ feature, publicDashboardUrl }: AppProps & {</a></div></div>+ ) : !authorizedSource ? (+ <p className="p-3 text-sm">{authorizationError ? "Application authorization failed. Refresh to retry." : "Authorizing application..."}</p>) : (<iframekey={generation}- src={surface.kind === "embedded" ? surface.source ?? undefined : undefined}+ src={authorizedSource}title={`${feature.applicationId} ${feature.title}`}className="min-h-0 flex-1 border-0 bg-background"// allow-same-origin stays, and is the whole point: these SPAs need their owndiff --git a/lib/a2a/store.test.ts b/lib/a2a/store.test.tsindex f5fadca8..10ae714b 100644--- a/lib/a2a/store.test.ts+++ b/lib/a2a/store.test.ts@@ -51,6 +51,13 @@ it("stores registered public Agent Cards in a private atomic registry", async ());expect(registered.alias).toBe("research");expect(await store.listA2AAgents()).toHaveLength(1);+ const registry = JSON.parse(await fs.readFile(process.env.OS_A2A_STORE, "utf8"));+ registry.agents[0].credentialProfileId = "stored-owner-credential";+ await fs.writeFile(process.env.OS_A2A_STORE, JSON.stringify(registry), { mode: 0o600 });+ vi.mocked(client.discoverA2AAgent).mockClear();+ for (const scope of ["read", "write"] as const) await expect(store.resolveA2AAgent("research", scope)).rejects.toThrow(/exec authority/);+ expect(client.discoverA2AAgent).not.toHaveBeenCalled();+ expect((await store.resolveA2AAgent("research", "exec")).credentialProfileId).toBe("stored-owner-credential");const stat = await fs.stat(process.env.OS_A2A_STORE);expect(stat.mode & 0o777).toBe(0o600);expect(diff --git a/lib/a2a/store.ts b/lib/a2a/store.tsindex 0eada69e..fcbdc7b7 100644--- a/lib/a2a/store.ts+++ b/lib/a2a/store.ts@@ -198,6 +198,7 @@ export async function resolveA2AAgent(throw new Error(`A2A target is ambiguous: ${exact.map((row) => row.alias).join(", ")}`,);+ if (exact[0].credentialProfileId && scope !== "exec") throw new Error("Stored A2A credentials require exec authority");const discovered = await discoverA2AAgent(exact[0].cardUrl, undefined, scope);return {...discovered,diff --git a/lib/agent/subagent-runner.test.ts b/lib/agent/subagent-runner.test.tsindex a3e0fae2..eff378a6 100644--- a/lib/agent/subagent-runner.test.ts+++ b/lib/agent/subagent-runner.test.ts@@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const stream = vi.fn();const dispatch = vi.fn();+const device = vi.hoisted(() => vi.fn());+vi.mock("@/lib/auth/device-store", () => ({ getApprovedDevice: device }));vi.mock("./session-store", () => ({getAgentSession: vi.fn(async () => ({ id: "session-a", cwd: "/srv/project", title: "parent", history: [{ role: "user", text: "TOP SECRET PARENT TRANSCRIPT" }], memorySnapshot: { user: "TOP SECRET MEMORY" } })),}));@@ -24,6 +26,16 @@ const { runSessionSubagent } = await import("./subagent-runner");describe("same-session subagent runner", () => {beforeEach(() => { stream.mockReset(); dispatch.mockReset(); });+ it.each([null, { role: "operator" }])("stops after original Owner authority changes during a model round: %j", async changed => {+ device.mockResolvedValue({ role: "owner" });+ stream.mockImplementationOnce(async ({ emit }) => {+ device.mockResolvedValue(changed);+ emit("tool_use", { id: "write", name: "fs_write", input: {} });+ });+ await expect(runSessionSubagent({ principal: "cli:device", parentSessionId: "session-a", objective: "inspect", maxScope: "exec", capabilities, authority: { principal: "web:device", scope: "exec" } })).rejects.toThrow(/revoked|demoted/);+ expect(stream).toHaveBeenCalledTimes(1); expect(dispatch).not.toHaveBeenCalled();+ expect(device).toHaveBeenCalledWith("device");+ });it("uses isolated context, read scope by default, and returns only final result", async () => {let seenTools: string[] = [], firstPayload = "";diff --git a/lib/agent/subagent-runner.ts b/lib/agent/subagent-runner.tsindex 8b9fbdc4..51796c04 100644--- a/lib/agent/subagent-runner.ts+++ b/lib/agent/subagent-runner.ts@@ -74,7 +74,7 @@ export async function runSessionSubagent(input: {const maxTurns = Math.max(1, Math.min(maxTurnsLimit(), Math.trunc(input.maxTurns || DEFAULT_TURNS)));const timeoutMs = Math.max(1_000, Math.min(MAX_TIMEOUT_MS, Math.trunc(input.timeoutMs || DEFAULT_TIMEOUT_MS)));const subagentId = `subagent_${randomUUID()}`;- const authority = { ...input.authority, principal: input.principal, scope: maxScope, capabilities: input.capabilities };+ const authority = { ...input.authority, principal: input.authority?.principal ?? input.principal, scope: maxScope, capabilities: input.capabilities };const toolDefs = (context: CapabilityRunContext) => input.capabilities.list(context.scope, context).filter((tool) => allows(context.scope, tool.scope) && allowedTool(tool.name) && (!context.allowedTools || context.allowedTools.includes(tool.name)));const prepared = await prepareSelectedModel();const messages: OaMsg[] = [{ role: "user", text: objective }];@@ -113,7 +113,7 @@ export async function runSessionSubagent(input: {}const invoked = await input.capabilities.invoke({...current, name: call.name, args: call.input ?? {},- actor: `${input.principal}#${subagentId}`, principal: input.principal,+ actor: `${input.principal}#${subagentId}`, principal: current.principal,});const outcome = resultText({ result: invoked });results.push({ id: call.id, content: outcome.content, ...(outcome.isError ? { isError: true } : {}) });diff --git a/lib/auth/require-session.test.ts b/lib/auth/require-session.test.tsindex 48792af5..f9bd3a97 100644--- a/lib/auth/require-session.test.ts+++ b/lib/auth/require-session.test.ts@@ -58,7 +58,7 @@ describe("getSession with a shadowed cookie", () => {});- it("never revives a retained token when cookie scope changes away and later returns", async () => {+ it("never revives legacy Domain tokens even when the obsolete setting returns", async () => {const { getSession } = await import("./require-session");process.env.OS_SESSION_COOKIE_DOMAIN = "example.com";policy.scope = "domain:example.com"; policy.generation = 1;@@ -67,13 +67,14 @@ describe("getSession with a shadowed cookie", () => {cookie_scope: "domain:example.com", cookie_epoch: epoch(),}, SECRET);jar.push({ name: "session", value: retained });- expect(await getSession()).toMatchObject({ device_id: "dev-1" });-+ expect(await getSession()).toBeNull();delete process.env.OS_SESSION_COOKIE_DOMAIN;expect(await getSession()).toBeNull();process.env.OS_SESSION_COOKIE_DOMAIN = "example.com";expect(await getSession()).toBeNull();- expect(policy.generation).toBe(3);+ expect(policy.generation).toBe(2);+ jar.push({ name: "session", value: valid() });+ expect(await getSession()).toMatchObject({ device_id: "dev-1" });});it("rechecks the live device role for every authorization decision", async () => {const { getSessionContext, requireSession } = await import("./require-session");diff --git a/lib/auth/session-cookie.test.ts b/lib/auth/session-cookie.test.tsindex e7f14ba7..ef60b9c3 100644--- a/lib/auth/session-cookie.test.ts+++ b/lib/auth/session-cookie.test.ts@@ -27,7 +27,7 @@ describe("configuredSessionCookieScope", () => {delete process.env.OS_SESSION_COOKIE_DOMAIN;expect(configuredSessionCookieScope()).toBe("host");process.env.OS_SESSION_COOKIE_DOMAIN = " .MSO.Example.com ";- expect(configuredSessionCookieScope()).toBe("domain:mso.example.com");+ expect(configuredSessionCookieScope()).toBe("host");process.env.OS_SESSION_COOKIE_DOMAIN = "bad; Domain=evil.test";expect(configuredSessionCookieScope()).toBe("host");});diff --git a/lib/auth/session-cookie.ts b/lib/auth/session-cookie.tsindex 4991a4ec..5ee86290 100644--- a/lib/auth/session-cookie.ts+++ b/lib/auth/session-cookie.ts@@ -1,33 +1,5 @@-// Attributes of the `session` cookie, in ONE place so the SET (login) and CLEAR-// (logout) paths cannot drift. A cookie cleared without the same Domain leaves-// the original alive in the jar — a logout that does not log out.-//-// Default (OS_SESSION_COOKIE_DOMAIN unset) = host-only, exactly as before: no-// Domain attribute, so the cookie goes back only to the host that set it. That-// stays the default for dev, demo and the rollback path.-//-// Setting it widens the cookie to a domain AND every subdomain of it. The only-// reason to do that is the split-origin managed-app hosts (`hermes.os.…`,-// `openclaw.os.…`) — separate ORIGINS served by this same process, so the-// framed dashboard's requests are authenticated by the same session. It is one-// half of a pair with NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE + the middleware-// host gating; without that gating the session reaches every host under the-// domain and each one exposes the full cockpit API. See .env.example.-//-// Deliberately NOT named `__Host-session`: that prefix forbids Domain outright-// (the browser rejects such a Set-Cookie), so the prefix and this env var are-// mutually exclusive. Renaming the cookie to a `__Host-` prefix means deleting-// this module and the split-origin cookie plan with it.-//-// SameSite stays "strict" and the cross-origin iframe does NOT need it loosened:-// SameSite is evaluated per SITE — scheme + registrable domain — not per origin.-// `mso.example.com` and `hermes.mso.example.com` share the registrable domain-// `example.com` on the same scheme, so the frame's navigation and every-// subresource it fetches are same-site (RFC 6265bis §5.2); for a nested document-// the "site for cookies" is non-null when the top-level document and every-// ancestor are same-site with it, which holds here. Cross-ORIGIN (what the-// window.top opacity needs) is not cross-SITE (what SameSite gates). Only moving-// an app host to a different registrable domain would force a change.+// Cockpit sessions are always host-only. The legacy Domain is retained only+// for logout cleanup; policy scope changes invalidate previously widened tokens./** One DNS label: 1-63 chars, alphanumeric, inner hyphens allowed. */const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;@@ -64,6 +36,11 @@ function requestHostname(req: Request): string {* Changing the cookie Domain invalidates existing signed sessions, including a* broader Domain cookie the browser may retain until its original expiry. */export function configuredSessionCookieScope(): string {+ return "host";+}++// Retained only to clear cookies issued before host-only authorization.+function legacySessionCookieScope(): string {const raw = process.env.OS_SESSION_COOKIE_DOMAIN?.trim().toLowerCase() ?? "";const domain = raw.startsWith(".") ? raw.slice(1) : raw;return isCookieDomain(domain) ? `domain:${domain}` : "host";@@ -71,7 +48,7 @@ export function configuredSessionCookieScope(): string {/** The validated Domain for this request, or undefined for host-only. */export function sessionCookieDomain(req: Request): string | undefined {- const scope = configuredSessionCookieScope();+ const scope = legacySessionCookieScope();if (!scope.startsWith("domain:")) return undefined;const domain = scope.slice("domain:".length);const host = requestHostname(req);@@ -89,7 +66,7 @@ export type SessionCookieAttrs = {/** Attributes for both writing (maxAge = lifetime) and clearing (maxAge = 0). */export function sessionCookieAttrs(req: Request, maxAge: number): SessionCookieAttrs {- const domain = sessionCookieDomain(req);+ const domain = maxAge === 0 ? sessionCookieDomain(req) : undefined;return {httpOnly: true,secure: true,diff --git a/lib/camoufox/origin.test.ts b/lib/camoufox/origin.test.tsindex 597db02b..866c342f 100644--- a/lib/camoufox/origin.test.ts+++ b/lib/camoufox/origin.test.ts@@ -46,13 +46,13 @@ describe("Camoufox split origin", () => {expect(mod.isCamoufoxViewerHost("browser.example.net:443")).toBe(true);});- it("refuses explicit viewer origins that can receive the cockpit Domain cookie", async () => {+ it("refuses the cockpit origin while allowing separately authenticated subdomains", async () => {for (const value of ["https://camoufox.mso.example.com","https://mso.example.com",]) {const mod = await load("{id}.mso.example.com", "https://mso.example.com", value);- expect(mod.camoufoxViewerOrigin()).toBe("https://camoufox.example.com");+ expect(mod.camoufoxViewerOrigin()).toBe(value === "https://mso.example.com" ? "https://camoufox.example.com" : value);vi.unstubAllEnvs();}});@@ -70,14 +70,14 @@ describe("Camoufox split origin", () => {}});- it("fails closed when a broad two-label Domain cookie leaves no safe automatic sibling", async () => {+ it("ignores the obsolete broad Domain setting when deriving the isolated sibling", async () => {const mod = await load("{id}.mso.example.com","https://mso.example.com","","example.com",);- expect(mod.camoufoxViewerOrigin()).toBeNull();+ expect(mod.camoufoxViewerOrigin()).toBe("https://camoufox.example.com");expect(mod.isCamoufoxViewerHost("camoufox.mso.example.com")).toBe(false);});diff --git a/lib/capabilities/execute.ts b/lib/capabilities/execute.tsindex ed7b1b9e..9a2a2f0b 100644--- a/lib/capabilities/execute.ts+++ b/lib/capabilities/execute.ts@@ -13,6 +13,7 @@ import { activityTarget, newActivityId, recordCapabilityActivity } from "./activimport { recipeActor, workflowActor, type CapabilityAgentContext } from "./actors";import { capabilityRateLimited } from "./rate-limit";import { flowFields, recordAgentEvent, sessionDetail, workflowFromResult } from "./execution-support";+import { withIsolatedFilesystem } from "@/lib/host/fs-api";export interface CapabilityExecutionContext extends CapabilityAgentContext {capabilities?: CapabilityRuntime;@@ -121,7 +122,10 @@ export async function executeCapabilityCall(input: {if (titleHint && context?.principal && context.sessionId && !["agent_session_current", "workflow_status", "agent_subagent_run"].includes(name))await maybeAutoTitleAgentSession(context.principal, context.sessionId, titleHint).catch(() => undefined);- const result = await tool.run(args, {+ const needsIsolation = !lifecycle && tool.scope !== "read" && activeWorkflow?.orchestration?.isolation === "isolated-worktree";+ const isolatedRoot = needsIsolation ? activeWorkflow?.orchestration?.workspacePath : undefined;+ if (needsIsolation && !isolatedRoot) throw new Error("isolated workflow has no verified workspace");+ const result = await withIsolatedFilesystem(isolatedRoot, () => tool.run(args, {actor,principal: context?.principal,tenantContext: context?.tenantContext,@@ -136,7 +140,7 @@ export async function executeCapabilityCall(input: {authorizationGrant: context?.authorizationGrant,toolProfile: context?.toolProfile,trustedOpenAiFileParams: context?.trustedOpenAiFileParams,- });+ }));const reportedFailure = capabilityReportedFailure(result) || trail?.outcome?.(result)?.ok === false;const completedState = reportedFailure ? "failed" : "completed";if (trail) {diff --git a/lib/capabilities/live-authority.ts b/lib/capabilities/live-authority.tsindex 49d93593..5e019d9c 100644--- a/lib/capabilities/live-authority.ts+++ b/lib/capabilities/live-authority.ts@@ -1,8 +1,13 @@import type { CapabilityRunContext } from "./tool";import { clampScope } from "./scope-policy";+import { getApprovedDevice } from "@/lib/auth/device-store";/** Async workers retain the initiating grant, never a snapshot of its validity. */export async function liveCapabilityContext(context: CapabilityRunContext, name?: string, args?: Record<string, unknown>): Promise<CapabilityRunContext> {+ if (context.principal?.startsWith("web:")) {+ const device = await getApprovedDevice(context.principal.slice(4));+ if (!device || device.role === "viewer" || context.scope === "exec" && device.role !== "owner") throw new Error("execution device revoked or demoted");+ }if (context.authorizationGrant && (!context.principal || !await context.capabilities?.authorize?.(context.authorizationGrant, context.principal, name, args))) {throw new Error("execution authorization revoked, expired or changed");}diff --git a/lib/capabilities/live-device-authority.test.ts b/lib/capabilities/live-device-authority.test.tsnew file mode 100644index 00000000..42623bb4--- /dev/null+++ b/lib/capabilities/live-device-authority.test.ts@@ -0,0 +1,11 @@+import { expect, it, vi } from "vitest";+const device = vi.hoisted(() => vi.fn());+vi.mock("@/lib/auth/device-store", () => ({ getApprovedDevice: device }));+import { liveCapabilityContext } from "./live-authority";+it("preserves and rechecks a delegated web principal after revocation or demotion", async () => {+ const context = { principal: "web:owner-device", scope: "exec" as const };+ device.mockResolvedValue({ role: "owner" }); expect((await liveCapabilityContext(context, "fs_write")).principal).toBe(context.principal);+ device.mockResolvedValue({ role: "operator" }); await expect(liveCapabilityContext(context, "fs_write")).rejects.toThrow(/demoted/);+ await expect(liveCapabilityContext(context)).rejects.toThrow(/demoted/);+ device.mockResolvedValue(null); await expect(liveCapabilityContext(context, "fs_write")).rejects.toThrow(/revoked/);+});diff --git a/lib/channels/event-admission.test.ts b/lib/channels/event-admission.test.tsnew file mode 100644index 00000000..ddbe1bf7--- /dev/null+++ b/lib/channels/event-admission.test.ts@@ -0,0 +1,15 @@+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, expect, it, vi } from "vitest";+import { admitChannelEvent } from "./event-admission";+let home: string;+afterEach(async () => { vi.restoreAllMocks(); if (home) await fs.rm(home, { recursive: true, force: true }); });+it("atomically admits one replayed event before any durable session allocation", async () => {+ home = await fs.mkdtemp(path.join(os.tmpdir(), "mso-channel-admit-")); vi.spyOn(os, "homedir").mockReturnValue(home);+ const attempts = await Promise.all([admitChannelEvent("one", "event"), admitChannelEvent("one", "event"), admitChannelEvent("one", "event")]);+ expect(attempts.filter(Boolean)).toHaveLength(1);+ vi.resetModules(); const reloaded = await import("./event-admission"); expect(await reloaded.admitChannelEvent("one", "event")).toBe(false);+ expect(await reloaded.admitChannelEvent("two", "event")).toBe(true);+ expect((await fs.stat(path.join(home, ".mso/private/channel-events.json"))).mode & 0o777).toBe(0o600);+});diff --git a/lib/channels/event-admission.ts b/lib/channels/event-admission.tsnew file mode 100644index 00000000..deb77433--- /dev/null+++ b/lib/channels/event-admission.ts@@ -0,0 +1,27 @@+import { createHash } from "node:crypto";+import os from "node:os";+import path from "node:path";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import { readWorkflowJson, writeWorkflowFile } from "@/lib/workflow/private-file";+import { ChannelError } from "./errors";++/** Separate from prunable workflow receipts; reserve before writing any durable session. */+export async function admitChannelEvent(channelId: string, eventId: string): Promise<boolean> {+ if (!eventId || eventId.length > 512) throw new ChannelError("invalid_event_id");+ const file = path.join(os.homedir(), ".mso", "private", "channel-events.json");+ const key = createHash("sha256").update(JSON.stringify([channelId, eventId])).digest("hex");+ return withSecurityStoreLock(file, async () => {+ let receipts: Record<string, number>;+ try { receipts = await readWorkflowJson(file, 1024 * 1024, "channel event admission") as Record<string, number>; }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; receipts = {}; }+ for (const [id, expiry] of Object.entries(receipts)) {+ if (!/^[a-f0-9]{64}$/.test(id) || !Number.isSafeInteger(expiry)) throw new ChannelError("invalid_event_admission_store");+ if (expiry <= Date.now()) delete receipts[id];+ }+ if (receipts[key]) return false;+ if (Object.keys(receipts).length >= 4096) throw new ChannelError("event_admission_capacity", 429);+ receipts[key] = Date.now() + 10 * 60 * 1000;+ await writeWorkflowFile(file, JSON.stringify(receipts));+ return true;+ });+}diff --git a/lib/channels/providers.test.ts b/lib/channels/providers.test.tsindex 41f1a7ce..5120ab7d 100644--- a/lib/channels/providers.test.ts+++ b/lib/channels/providers.test.ts@@ -18,7 +18,7 @@ describe("channel provider verification", () => {const { privateKey, publicKey } = generateKeyPairSync("ed25519");const der = publicKey.export({ format: "der", type: "spki" });const publicKeyHex = Buffer.from(der).subarray(-32).toString("hex");- const timestamp = "1727000000";+ const timestamp = String(Math.floor(Date.now() / 1000));const body = JSON.stringify({ id: "123456789012345678", type: 2, application_id: "222222222222222222", channel_id: "333333333333333333", data: { name: "ask" }, member: { user: { id: "444444444444444444" } } });const signature = sign(null, Buffer.from(timestamp + body), privateKey).toString("hex");diff --git a/lib/channels/providers/discord.test.ts b/lib/channels/providers/discord.test.tsindex b035defb..7f6a21d9 100644--- a/lib/channels/providers/discord.test.ts+++ b/lib/channels/providers/discord.test.ts@@ -7,11 +7,15 @@ describe("discord channel adapter", () => {const { publicKey, privateKey } = generateKeyPairSync("ed25519");const spki = publicKey.export({ format: "der", type: "spki" });const publicKeyHex = Buffer.from(spki).subarray(-32).toString("hex");- const timestamp = "1700000000";+ const timestamp = String(Math.floor(Date.now() / 1000));const body = JSON.stringify({ id: "123456789012345678", application_id: "111111111111111111", type: 1 });const signature = sign(null, Buffer.from(timestamp + body), privateKey).toString("hex");expect(verifyDiscordSignature({ publicKey: publicKeyHex }, timestamp, signature, body)).toBe(true);expect(verifyDiscordSignature({ publicKey: publicKeyHex }, timestamp, signature, body + "x")).toBe(false);+ for (const offset of [-3600, 3600]) {+ const stale = String(Math.floor(Date.now() / 1000) + offset);+ expect(verifyDiscordSignature({ publicKey: publicKeyHex }, stale, sign(null, Buffer.from(stale + body), privateKey).toString("hex"), body)).toBe(false);+ }});it("normalizes commands to the shared inbound event contract", () => {diff --git a/lib/channels/providers/discord.ts b/lib/channels/providers/discord.tsindex 28520ce2..25216ece 100644--- a/lib/channels/providers/discord.ts+++ b/lib/channels/providers/discord.ts@@ -43,6 +43,7 @@ export async function sendDiscordText(values: Record<string, string>, target: stexport function verifyDiscordSignature(values: Record<string, string>, timestamp: string | null, signature: string | null, body: string) {const keyHex = values.publicKey;if (!keyHex || !PUBLIC_KEY.test(keyHex) || !timestamp || !signature || !/^[0-9a-f]{128}$/i.test(signature)) return false;+ if (!/^[0-9]{10,11}$/.test(timestamp) || Math.abs(Date.now() - Number(timestamp) * 1000) > 5 * 60 * 1000) return false;try {const key = createPublicKey({ key: Buffer.concat([SPKI_ED25519_PREFIX, Buffer.from(keyHex, "hex")]), format: "der", type: "spki" });return verify(null, Buffer.from(timestamp + body), key, Buffer.from(signature, "hex"));diff --git a/lib/channels/service.ts b/lib/channels/service.tsindex 8d66de9e..6c67946c 100644--- a/lib/channels/service.ts+++ b/lib/channels/service.ts@@ -4,6 +4,7 @@ import { ChannelError } from "./errors";import { rateLimited } from "@/lib/host/rate-limit";import { channelProvider, listChannelProviders } from "./registry";import { parseChannelPatch } from "./schema";+import { reviewedChannelBinding } from "@/lib/workflow/graph-triggers";import {channelById,createChannel,@@ -72,14 +73,14 @@ async function assertCredentialRef(input: ReturnType<typeof parseChannelPatch>)export async function createChannelConfig(raw: Record<string, unknown>) {const parsed = parseChannelPatch(raw);await assertCredentialRef(parsed);- return createChannel(raw);+ return createChannel(raw, parsed.workflowId ? await reviewedChannelBinding(parsed.workflowId, "") : undefined);}export async function updateChannelConfig(id: string, expectedRevision: number, raw: Record<string, unknown>) {const previous = await channelById(id);const parsed = parseChannelPatch(raw, previous);await assertCredentialRef(parsed);- return updateChannel(id, expectedRevision, raw);+ return updateChannel(id, expectedRevision, raw, raw.workflowId !== undefined && parsed.workflowId ? await reviewedChannelBinding(parsed.workflowId, id) : undefined);}export const deleteChannelConfig = deleteChannel;diff --git a/lib/channels/store.ts b/lib/channels/store.tsindex 2df02207..bf12e238 100644--- a/lib/channels/store.ts+++ b/lib/channels/store.ts@@ -29,6 +29,7 @@ function validateState(value: unknown): ChannelState {return {id: row.id,...parsed,+ ...(row.workflowBinding ? { workflowBinding: validBinding(row.workflowBinding) } : {}),createdAt: row.createdAt,updatedAt: row.updatedAt,...(row.lastCheck ? { lastCheck: row.lastCheck } : {}),@@ -85,16 +86,21 @@ async function mutate<T>(fn: (state: ChannelState) => T | Promise<T>, bumpRevisi});}-export async function createChannel(raw: Record<string, unknown>) {+function validBinding(binding: NonNullable<ChannelRecord["workflowBinding"]>) {+ if (!/^[a-f0-9]{64}$/.test(binding.owner) || !/^[A-Za-z0-9_.:-]{1,96}$/.test(binding.nodeId) || !/^[a-f0-9]{64}$/.test(binding.revision)) throw new ChannelError("invalid_workflow_binding");+ return binding;+}++export async function createChannel(raw: Record<string, unknown>, binding?: ChannelRecord["workflowBinding"]) {return mutate((state) => {const now = new Date().toISOString();- const row: ChannelRecord = { id: randomUUID(), ...parseChannelPatch(raw), createdAt: now, updatedAt: now };+ const row: ChannelRecord = { id: randomUUID(), ...parseChannelPatch(raw), ...(binding ? { workflowBinding: validBinding(binding) } : {}), createdAt: now, updatedAt: now };state.channels.push(row);return structuredClone(row);});}-export async function updateChannel(id: string, expectedRevision: number, raw: Record<string, unknown>) {+export async function updateChannel(id: string, expectedRevision: number, raw: Record<string, unknown>, binding?: ChannelRecord["workflowBinding"]) {return mutate((state) => {if (state.revision !== expectedRevision) throw new ChannelError("channel_revision_changed", 409);const index = state.channels.findIndex((row) => row.id === id);@@ -107,6 +113,7 @@ export async function updateChannel(id: string, expectedRevision: number, raw: RcreatedAt: previous.createdAt,updatedAt: new Date().toISOString(),};+ if (raw.workflowId !== undefined) { delete row.workflowBinding; if (binding) row.workflowBinding = validBinding(binding); }state.channels[index] = row;return structuredClone(row);});diff --git a/lib/channels/types.ts b/lib/channels/types.tsindex 98867416..40b97ab8 100644--- a/lib/channels/types.ts+++ b/lib/channels/types.ts@@ -20,6 +20,7 @@ export type ChannelRecord = {enabled: boolean;defaultTarget?: string;workflowId?: string;+ workflowBinding?: { owner: string; nodeId: string; revision: string };createdAt: string;updatedAt: string;lastCheck?: ChannelCheck;diff --git a/lib/channels/workflow.ts b/lib/channels/workflow.tsindex a1f03c37..f45c16eb 100644--- a/lib/channels/workflow.ts+++ b/lib/channels/workflow.ts@@ -7,6 +7,8 @@ import { startWorkflowGraph } from "@/lib/workflow/graph-engine";import { ChannelError } from "./errors";import { channelById, recordChannelActivity } from "./store";import type { ChannelInboundEvent } from "./types";+import { admitChannelEvent } from "./event-admission";+import { createHash } from "node:crypto";export type ChannelWorkflowRuntime = {scope: Scope;@@ -31,8 +33,9 @@ export async function dispatchChannelInbound(await recordChannelActivity(channelId);if (!channel.workflowId) return { workflow: null };- const source = await findActiveChannelSource(channel.workflowId, channel.id);+ const source = await findActiveChannelSource(channel.workflowId, channel.id, channel.workflowBinding);if (!source) throw new ChannelError("channel_workflow_trigger_not_found", 409);+ if (!await admitChannelEvent(channelId, event.eventId)) return { workflow: null, duplicate: true };const session = await createAgentSession(source.principal, "cli", {title: "Channel: " + channel.name,@@ -45,7 +48,7 @@ export async function dispatchChannelInbound(scope: runtime.scope,...(runtime.capabilities ? { capabilities: runtime.capabilities } : {}),} as const;- const idempotency = ["channel", channel.id, event.eventId].join(":").slice(0, 128);+ const idempotency = "channel:" + createHash("sha256").update(JSON.stringify([channel.id, event.eventId])).digest("hex");const run = await startWorkflowGraph(source.graph,workflowInput(channel, event),diff --git a/lib/federation/local-approval.test.ts b/lib/federation/local-approval.test.tsnew file mode 100644index 00000000..85946304--- /dev/null+++ b/lib/federation/local-approval.test.ts@@ -0,0 +1,16 @@+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+vi.mock("@/lib/host/projects-api", () => ({ resolveProjectHint: vi.fn(async (id: string) => id === "local" ? { path: "/reviewed", matchedBy: "exact" } : null) }));+import { consumeFederationApproval, federationRequestDigest } from "./local-approval";+import { FEDERATION_WORKER_ID } from "./security";+const request = { id: "request-1", projectId: "local", source: "mso", operation: "exec_run", scope: "exec", arguments: { command: "true" } };+let home: string, file: string;+beforeEach(async () => { home = await fs.mkdtemp(path.join(os.tmpdir(), "mso-fed-approval-")); vi.spyOn(os, "homedir").mockReturnValue(home); file = path.join(home, ".mso/private/federation-approvals.json"); });+afterEach(async () => { vi.restoreAllMocks(); await fs.rm(home, { recursive: true, force: true }); });+async function grant(expiresAt = Date.now() + 60000) { await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 }); await fs.writeFile(file, JSON.stringify({ [request.id]: { principal: FEDERATION_WORKER_ID, requestDigest: federationRequestDigest(request), expiresAt } }), { mode: 0o600 }); }+it("denies a scope-labelled confirmed remote request without local approval", async () => { await expect(consumeFederationApproval(request)).rejects.toThrow(/Owner approval/); });+it("consumes one exact reviewed request and rejects replay", async () => { await grant(); expect(await consumeFederationApproval(request)).toBe("/reviewed"); await expect(consumeFederationApproval(request)).rejects.toThrow(/already used/); });+it.each(["operation", "scope", "arguments", "source"])("rejects a changed %s without consuming the grant", async field => { await grant(); await expect(consumeFederationApproval({ ...request, [field]: field === "arguments" ? { command: "other" } : "other" })).rejects.toThrow(/changed/); expect(await consumeFederationApproval(request)).toBe("/reviewed"); });+it("rejects expiry, revocation and unknown projects", async () => { await grant(Date.now() - 1); await expect(consumeFederationApproval(request)).rejects.toThrow(/expired/); await grant(); await expect(consumeFederationApproval({ ...request, projectId: "remote-path" })).rejects.toThrow(/exact local project/); await fs.unlink(file); await expect(consumeFederationApproval(request)).rejects.toThrow(/Owner approval/); });diff --git a/lib/federation/local-approval.ts b/lib/federation/local-approval.tsnew file mode 100644index 00000000..dfb42aae--- /dev/null+++ b/lib/federation/local-approval.ts@@ -0,0 +1,49 @@+import { createHash } from "node:crypto";+import { constants, promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import { resolveProjectHint } from "@/lib/host/projects-api";+import { FEDERATION_WORKER_ID, validateFederationArguments } from "./security";++type Request = { id: string; projectId: string; source: string; operation: string; scope: string; arguments?: Record<string, unknown> };+type Approval = { principal: string; requestDigest: string; expiresAt: number; usedAt?: number };+const approvalFile = () => path.join(os.homedir(), ".mso", "private", "federation-approvals.json");+function canonical(value: unknown): unknown {+ if (Array.isArray(value)) return value.map(canonical);+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonical(child)]));+ return value;+}+/** Owner reviews the entire request, including exact project, operation, scope and arguments. */+export function federationRequestDigest(request: Request): string {+ return createHash("sha256").update(JSON.stringify(canonical({ id: request.id, projectId: request.projectId, source: request.source, operation: request.operation, scope: request.scope, arguments: validateFederationArguments(request.arguments ?? {}) }))).digest("hex");+}+export async function consumeFederationApproval(request: Request): Promise<string> {+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(request.id)) throw new Error("invalid federation request identity");+ const project = await resolveProjectHint(request.projectId);+ if (!project || project.matchedBy === "fuzzy") throw new Error("federation requires an exact local project");+ const file = approvalFile();+ return withSecurityStoreLock(file, async () => {+ let handle;+ try {+ handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);+ const before = await handle.stat();+ if (!before.isFile() || before.size > 512 * 1024 || before.mode & 0o077 || typeof process.getuid === "function" && before.uid !== process.getuid()) throw new Error("unsafe federation approval store");+ const bytes = Buffer.alloc(before.size + 1); let used = 0;+ while (used < bytes.length) { const { bytesRead } = await handle.read(bytes, used, bytes.length - used, used); if (!bytesRead) break; used += bytesRead; }+ const after = await handle.stat();+ if (used !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs) throw new Error("federation approval store changed");+ const approvals = JSON.parse(bytes.subarray(0, used).toString("utf8")) as Record<string, Approval>;+ const approval = Object.hasOwn(approvals, request.id) ? approvals[request.id] : undefined;+ if (!approval || approval.principal !== FEDERATION_WORKER_ID || approval.requestDigest !== federationRequestDigest(request) || !Number.isSafeInteger(approval.expiresAt) || approval.expiresAt <= Date.now() || approval.expiresAt > Date.now() + 86400000 || approval.usedAt) throw new Error("federation local approval missing, expired, revoked, changed or already used");+ approval.usedAt = Date.now();+ const temp = file + "." + process.pid + ".tmp";+ try { await fs.writeFile(temp, JSON.stringify(approvals), { flag: "wx", mode: 0o600 }); await fs.rename(temp, file); }+ finally { await fs.unlink(temp).catch(() => undefined); }+ return project.path;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new Error("federation requires local Owner approval");+ throw error;+ } finally { await handle?.close(); }+ });+}diff --git a/lib/federation/si-coder-runtime.ts b/lib/federation/si-coder-runtime.tsindex 5a51ec56..225a7984 100644--- a/lib/federation/si-coder-runtime.ts+++ b/lib/federation/si-coder-runtime.ts@@ -5,6 +5,7 @@ import { callMcpServerTool, listMcpServerTools } from "@/lib/host/project-mcp-climport type { ProjectMcpServer } from "@/lib/host/project-mcp-config";import { inspectScInstallation } from "@/lib/host/sc-installation.mjs";import { validateFederationArguments } from "./security";+import { consumeFederationApproval } from "./local-approval";export type FederationExecutionScope = "read" | "write" | "exec";@@ -100,6 +101,8 @@ export async function inspectSiCoderFederationRuntime(cwd: string) {}export async function executeSiCoderFederation(input: {+ id: string;+ projectId: string;cwd: string;operation: string;arguments: Record<string, unknown>;@@ -111,7 +114,8 @@ export async function executeSiCoderFederation(input: {if (input.scope !== expectedScope) throw new Error(`SI-Coder scope mismatch: request=${input.scope}, runtime=${expectedScope}`);if (expectedScope !== "read" && !input.confirmed) throw new Error("SI-Coder write/exec federation requires explicit confirmation");- const server = await standaloneServer(input.cwd);+ const projectPath = await consumeFederationApproval({ ...input, source: "si-coder" });+ const server = await standaloneServer(projectPath);const tools = await listMcpServerTools(server);const tool = tools.find((candidate) => candidate.name === input.operation);if (!tool) throw new Error(`unknown SI-Coder federation function: ${input.operation}`);diff --git a/lib/host/exec.ts b/lib/host/exec.tsindex 7c1a3e36..d9588167 100644--- a/lib/host/exec.ts+++ b/lib/host/exec.ts@@ -11,6 +11,7 @@ import { HostError } from "./host-error";import { homeDir, isUnderRoot, resolveWriteRoots } from "./paths";import { childEnv } from "./child-env";import { matchDestructive } from "./destructive-patterns";+import { isolatedCwd } from "./fs-isolation";const TIMEOUT_MS = 30_000;const MAX_OUTPUT = 1_000_000; // 1 MiB per stream@@ -33,7 +34,7 @@ export function destructiveReason(cmd: string): string | null {// Shared by one-shot commands, async jobs and PTYs. Only omitted cwd defaults.export async function resolveCwd(requested?: string): Promise<string> {const home = homeDir();- if (requested === undefined) return home;+ if (requested === undefined) return isolatedCwd(home);if (typeof requested !== "string" || !requested.trim()) throw new HostError("Working directory must not be empty");const absolute = requested === "~" ? home : requested.startsWith("~/")? path.join(home, requested.slice(2))@@ -47,7 +48,7 @@ export async function resolveCwd(requested?: string): Promise<string> {}const roots = await resolveWriteRoots();if (!roots.some((r) => isUnderRoot(real, r))) throw new HostError("Working directory is outside writable roots");- return real;+ return isolatedCwd(real);}export async function runCommand(cmd: string, cwd?: string, artifactEnv: Record<string, string> = {}): Promise<ExecResult> {diff --git a/lib/host/fs-api.ts b/lib/host/fs-api.tsindex 2ae8849e..6b20282f 100644--- a/lib/host/fs-api.ts+++ b/lib/host/fs-api.ts@@ -9,3 +9,4 @@ export { sha256Text, utf8Bytes } from "./hash";export { writeFileGuarded } from "./guarded-write";export { assertDelegatedWritePath } from "./delegated-write";export { readFileBytes } from "./fs-read-bytes";+export { withIsolatedFilesystem } from "./fs-isolation";diff --git a/lib/host/fs-descriptors.ts b/lib/host/fs-descriptors.tsindex 9b70eccc..f3ee14ab 100644--- a/lib/host/fs-descriptors.ts+++ b/lib/host/fs-descriptors.ts@@ -4,13 +4,18 @@ import path from "node:path";import { HostError } from "./host-error";import { isCredentialPath } from "./path-credentials";import { isUnderRoot, readRootList, writeRootList } from "./path-roots";+import { assertIsolatedPath } from "./fs-isolation";const fdPath = (fd: number) => `/proc/self/fd/${fd}`;+const VIRTUAL_FILESYSTEMS = new Set([0x9fa0, 0x62656572, 0x64626720, 0x73636673, 0x74726163, 0x27e0eb, 0x63677270, 0xcafe4a11, 0x62656570, 0x1cd1, 0x6e736673, 0xde5e81e4]);/** Validate the object we actually opened, not a pathname that can be exchanged. */export async function descriptorPath(handle: FileHandle, write: boolean): Promise<string> {if (process.platform !== "linux") throw new HostError("Secure host filesystem access requires Linux/WSL descriptor support");+ // Mount type follows the held descriptor, including virtual filesystems bind-mounted inside a read root.+ if (VIRTUAL_FILESYSTEMS.has((await fs.statfs(fdPath(handle.fd))).type)) throw new HostError("Virtual kernel filesystems are blocked");const real = await fs.realpath(fdPath(handle.fd));+ if (write) await assertIsolatedPath(real);if (isCredentialPath(real)) throw new HostError("Access to credential/sensitive files is blocked");for (const root of write ? writeRootList() : readRootList()) {const canonical = path.resolve(/* turbopackIgnore: true */ root);@@ -19,6 +24,19 @@ export async function descriptorPath(handle: FileHandle, write: boolean): Promisthrow new HostError(`Path outside ${write ? "writable" : "readable"} roots`);}+export async function readBoundedBytes(handle: FileHandle, maxBytes: number): Promise<Buffer> {+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new HostError("Invalid file byte limit");+ const chunks: Buffer[] = []; let size = 0;+ while (true) {+ const chunk = Buffer.alloc(Math.min(64 * 1024, maxBytes - size + 1));+ const { bytesRead } = await handle.read(chunk);+ if (!bytesRead) return Buffer.concat(chunks, size);+ size += bytesRead;+ if (size > maxBytes) throw new HostError("File too large");+ chunks.push(chunk.subarray(0, bytesRead));+ }+}+export async function openReadableHandle(resolved: string, write = false): Promise<FileHandle> {const handle = await fs.open(resolved, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);try { await descriptorPath(handle, write); return handle; }diff --git a/lib/host/fs-isolation.test.ts b/lib/host/fs-isolation.test.tsnew file mode 100644index 00000000..76976f15--- /dev/null+++ b/lib/host/fs-isolation.test.ts@@ -0,0 +1,63 @@+import { promises as fs, renameSync, symlinkSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { execFile } from "node:child_process";+import { promisify } from "node:util";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { withIsolatedFilesystem, isolatedCwd } from "./fs-isolation";+import { writeFile, makeDir, remove, copy, move, readFile } from "./fs";+import { readBoundedBytes } from "./fs-descriptors";+import { uploadInto } from "./fs-upload";++let base: string, root: string, outside: string;+beforeEach(async () => {+ base = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "mso-isolation-")));+ root = path.join(base, "worktree"); outside = path.join(base, "outside");+ await fs.mkdir(root); await fs.mkdir(outside); await fs.writeFile(path.join(outside, "data"), "unchanged");+ await fs.symlink(outside, path.join(root, "escape"));+ vi.stubEnv("OS_FS_READ_ROOTS", base); vi.stubEnv("OS_FS_WRITE_ROOTS", base);+});+afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); await fs.rm(base, { recursive: true, force: true }); });+it.each(["write", "mkdir", "delete", "copy", "move", "upload", "exec"])("rejects an inside-worktree symlink for %s despite broad host roots", async operation => {+ const target = path.join(root, "escape", "data");+ await expect(withIsolatedFilesystem(root, async () => {+ if (operation === "write") return writeFile(target, "changed");+ if (operation === "mkdir") return makeDir(path.join(root, "escape", "new"));+ if (operation === "delete") return remove(target);+ if (operation === "copy") return copy(target, path.join(root, "escape", "new"));+ if (operation === "move") return move(target, path.join(root, "escape", "new"));+ if (operation === "upload") return uploadInto(path.join(root, "escape"), [{ relPath: "data", data: Buffer.from("changed") }]);+ return isolatedCwd(outside);+ })).rejects.toThrow(/isolated|ENOTDIR/);+ expect(await fs.readFile(path.join(outside, "data"), "utf8")).toBe("unchanged");+});+it("rejects an ancestor exchange into another globally writable project", async () => {+ const nested = path.join(root, "nested"); await fs.mkdir(nested);+ const open = fs.open.bind(fs); let swapped = false;+ vi.spyOn(fs, "open").mockImplementation((...args: Parameters<typeof fs.open>) => {+ if (!swapped && String(args[0]) === nested) { swapped = true; renameSync(nested, nested + "-held"); symlinkSync(outside, nested); }+ return open(...args);+ });+ await expect(withIsolatedFilesystem(root, () => writeFile(path.join(nested, "data"), "changed"))).rejects.toThrow(/isolated|ENOTDIR/);+ expect(swapped).toBe(true); expect(await fs.readFile(path.join(outside, "data"), "utf8")).toBe("unchanged");+});+it("executes in a pinned legitimate directory", async () => {+ await withIsolatedFilesystem(root, async () => {+ const cwd = await isolatedCwd(root);+ expect((await promisify(execFile)(process.execPath, ["-e", "process.stdout.write(process.cwd())"], { cwd })).stdout).toBe(root);+ await writeFile(path.join(root, "safe"), "ok");+ });+ expect(await fs.readFile(path.join(root, "safe"), "utf8")).toBe("ok");+});+it("rejects virtual filesystem bytes even when aliased beneath an ordinary root", async () => {+ vi.spyOn(fs, "statfs").mockResolvedValue({ type: 0x9fa0 } as never);+ await expect(readFile(path.join(outside, "data"))).rejects.toThrow(/virtual/i);+});+it("bounds bytes actually read rather than trusting prior metadata", async () => {+ const file = path.join(root, "growing"); await fs.writeFile(file, "a");+ const handle = await fs.open(file, "r");+ try {+ expect((await handle.stat()).size).toBe(1); await fs.appendFile(file, "bcdef");+ await expect(readBoundedBytes(handle, 4)).rejects.toThrow(/large|limit/);+ } finally { await handle.close(); }+});diff --git a/lib/host/fs-isolation.ts b/lib/host/fs-isolation.tsnew file mode 100644index 00000000..17f6d993--- /dev/null+++ b/lib/host/fs-isolation.ts@@ -0,0 +1,34 @@+import { AsyncLocalStorage } from "node:async_hooks";+import { constants, promises as fs } from "node:fs";+import type { FileHandle } from "node:fs/promises";+import path from "node:path";+import { HostError } from "./host-error";+import { isUnderRoot } from "./path-roots";++type Boundary = { root: string; handle: FileHandle; held: FileHandle[] };+const boundary = new AsyncLocalStorage<Boundary>();+export async function assertIsolatedPath(real: string): Promise<void> {+ const current = boundary.getStore();+ if (!current) return;+ if (await fs.realpath(`/proc/self/fd/${current.handle.fd}`) !== current.root || !isUnderRoot(real, current.root)) throw new HostError("Path escapes the pinned isolated workflow workspace");+}+/** Hold the worktree across the complete capability call; host descriptors recheck it before writes. */+export async function withIsolatedFilesystem<T>(root: string | undefined, run: () => Promise<T>): Promise<T> {+ if (!root) return run();+ if (process.platform !== "linux") throw new HostError("Isolated source execution requires Linux/WSL descriptors");+ const canonical = await fs.realpath(root);+ const handle = await fs.open(canonical, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);+ const current = { root: canonical, handle, held: [] as FileHandle[] };+ try { return await boundary.run(current, run); }+ finally { await Promise.all([...current.held, handle].map((item) => item.close())); }+}+export async function isolatedCwd(real: string): Promise<string> {+ const current = boundary.getStore();+ if (!current) return real;+ await assertIsolatedPath(real);+ const handle = await fs.open(real, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);+ try { await assertIsolatedPath(await fs.realpath(`/proc/self/fd/${handle.fd}`)); }+ catch (error) { await handle.close(); throw error; }+ current.held.push(handle);+ return path.join("/proc/self/fd", String(handle.fd));+}diff --git a/lib/host/fs-read-bytes.ts b/lib/host/fs-read-bytes.tsindex 2f78681a..bc977dc0 100644--- a/lib/host/fs-read-bytes.ts+++ b/lib/host/fs-read-bytes.ts@@ -1,4 +1,4 @@-import { openReadableHandle } from "./fs-descriptors";+import { openReadableHandle, readBoundedBytes } from "./fs-descriptors";import { HostError } from "./host-error";import { resolveReadable } from "./paths";@@ -13,7 +13,7 @@ export async function readFileBytes(requested: string, maxBytes = 10 * 1024 * 10if (!Number.isFinite(maxBytes) || maxBytes < 1 || stat.size > maxBytes) {throw new HostError(`File too large to export (max ${Math.floor(maxBytes / (1024 * 1024))} MiB)`);}- return await handle.readFile();+ return await readBoundedBytes(handle, maxBytes);} catch (error) {if ((error as NodeJS.ErrnoException).code === "ELOOP") throw new HostError("Refusing symlink file");throw error;diff --git a/lib/host/fs.ts b/lib/host/fs.tsindex 5dadd5e1..d364a9bc 100644--- a/lib/host/fs.ts+++ b/lib/host/fs.ts@@ -4,7 +4,7 @@import { promises as fs, constants as fsConstants, type ReadStream } from "fs";import type { FileHandle } from "node:fs/promises";import path from "node:path";-import { openReadableHandle, pinDirectory } from "./fs-descriptors";+import { openReadableHandle, pinDirectory, readBoundedBytes } from "./fs-descriptors";import { copyPinned, removePinned } from "./fs-recursive";import { randomUUID } from "node:crypto";import type { FsUsage } from "@/lib/os-api/types";@@ -29,7 +29,7 @@ export async function readFile(requested: string): Promise<string> {const stat = await handle.stat();if (!stat.isFile()) throw new HostError(stat.isDirectory() ? "Is a directory" : "Not a regular file");if (stat.size > 5_000_000) throw new HostError("File too large to read (max 5 MiB)");- return await handle.readFile("utf8");+ return (await readBoundedBytes(handle, 5_000_000)).toString("utf8");} catch (error) {if ((error as NodeJS.ErrnoException).code === "ELOOP") throw new HostError("Refusing symlink file");throw error;diff --git a/lib/host/project-function-runner.ts b/lib/host/project-function-runner.tsindex d31ce569..b0b5d234 100644--- a/lib/host/project-function-runner.ts+++ b/lib/host/project-function-runner.ts@@ -3,6 +3,7 @@// only on stdin. No shell, no interpolation, credential-scrubbed environment.import { spawn, type ChildProcessWithoutNullStreams } from "child_process";import { childEnv } from "./child-env";+import { isolatedCwd } from "./fs-isolation";import { PROJECT_FUNCTIONS_REL, readProjectFunctionsManifest, type ProjectFunction } from "./project-function-manifest";const MAX_INPUT_BYTES = 128 * 1024;@@ -54,9 +55,10 @@ export async function runProjectFunction(const payload = JSON.stringify(input);if (Buffer.byteLength(payload) > MAX_INPUT_BYTES) throw new Error(`project function input exceeds ${MAX_INPUT_BYTES} bytes`);+ const cwd = await isolatedCwd(projectPath);return new Promise((resolve) => {const child = spawn(definition.command[0], definition.command.slice(1), {- cwd: projectPath,+ cwd,env: { ...childEnv(), MSO_PROJECT_FUNCTION: definition.name } as unknown as NodeJS.ProcessEnv,shell: false,stdio: ["pipe", "pipe", "pipe"],diff --git a/lib/host/workflow-embed-cookie.test.ts b/lib/host/workflow-embed-cookie.test.tsindex 43158935..ca82bd6e 100644--- a/lib/host/workflow-embed-cookie.test.ts+++ b/lib/host/workflow-embed-cookie.test.ts@@ -4,16 +4,16 @@ const cockpit = "https://mso.example.com";const app = { id: "editor", title: "Editor", description: "Reviewed external editor", origin: "https://n8n.mso.example.com", startPath: "/editor", externalAuthPath: "/signin", renderer: "iframe" as const, presentation: "inline" as const, environment: "production" as const, placements: ["n8n", "mcp-page"] as Array<"n8n" | "mcp-page"> };afterEach(() => vi.unstubAllEnvs());describe("external editor session-cookie isolation", () => {- it.each(["mso.example.com", ".MSO.EXAMPLE.COM", " example.com "])("blocks frames AND navigation under cookie domain %s", domain => {+ it.each(["mso.example.com", ".MSO.EXAMPLE.COM", " example.com "])("keeps frames and navigation on the same host/another port blocked despite obsolete domain %s", domain => {vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", domain);- const result = workflowEmbeds([app], [cockpit])[0];+ const result = workflowEmbeds([{ ...app, origin: cockpit + ":8443" }], [cockpit])[0];expect(result).toMatchObject({ id: "editor", renderer: "remote", blocked: true });expect(result.url).toBeUndefined(); expect(result.loginUrl).toBeUndefined();expect(result.reason).toContain("session cookie");});it("does not offer unsafe top-level navigation for remote-only providers", () => {vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", "mso.example.com");- expect(workflowEmbeds([{ ...app, renderer: "remote" }], [cockpit])[0].url).toBeUndefined();+ expect(workflowEmbeds([{ ...app, origin: cockpit + ":8443", renderer: "remote" }], [cockpit])[0].url).toBeUndefined();});it("allows a separately hosted editor and rejects label-prefix tricks", () => {vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", "mso.example.com");@@ -29,11 +29,13 @@ describe("external editor session-cookie isolation", () => {});it("rechecks runtime cookie policy through settings, list and shared Page readers", async () => {vi.stubEnv("OS_PUBLIC_ORIGIN", cockpit);- vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app]));+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([{ ...app, origin: cockpit + ":8443" }]));vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", "mso.example.com");expect((await listWorkflowEmbeds("http://localhost:4005"))[0].url).toBeUndefined();expect((await workflowEmbedSettings("http://localhost:4005")).apps[0].url).toBeUndefined();vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", "");+ expect((await listWorkflowEmbeds("http://localhost:4005"))[0].url).toBeUndefined();+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app]));expect((await listWorkflowEmbeds("http://localhost:4005"))[0].renderer).toBe("iframe");});});diff --git a/lib/managed-apps/backups-quota.test.ts b/lib/managed-apps/backups-quota.test.tsindex 0beda54e..bd2aaf06 100644--- a/lib/managed-apps/backups-quota.test.ts+++ b/lib/managed-apps/backups-quota.test.ts@@ -16,6 +16,14 @@ afterEach(async () => {});describe("managed-app backup quotas", () => {+ it("removes a snapshot if an app restarts while copying", async () => {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-backup-restart-")); roots.push(root);+ vi.spyOn(os, "homedir").mockReturnValue(root);+ await fs.mkdir(path.join(root, "state")); await fs.writeFile(path.join(root, "state", "config.json"), "{}");+ const guard = vi.fn().mockResolvedValueOnce(undefined).mockResolvedValueOnce(undefined).mockRejectedValue(new Error("gateway restarted"));+ await expect(createBackup(definition(root), "pre-update", guard)).rejects.toThrow(/restarted/);+ expect(await listBackups("openclaw")).toEqual([]);+ });it("rejects growth after preflight and removes the incomplete snapshot", async () => {const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-backup-growth-")); roots.push(root);vi.spyOn(os, "homedir").mockReturnValue(root);@@ -27,7 +35,7 @@ describe("managed-app backup quotas", () => {try { await huge.truncate(513 * 1024 * 1024); } finally { await huge.close(); }return copy(source, target, options);});- await expect(createBackup(definition(root), "pre-update")).rejects.toThrow(/backup changed/);+ await expect(createBackup(definition(root), "pre-update", async () => {})).rejects.toThrow(/backup changed/);expect(await listBackups("openclaw")).toEqual([]);});it("rate-limits manual snapshots", async () => {@@ -35,8 +43,8 @@ describe("managed-app backup quotas", () => {vi.spyOn(os, "homedir").mockReturnValue(root);await fs.mkdir(path.join(root, "state"), { recursive: true });await fs.writeFile(path.join(root, "state", "config.json"), "{}");- await createBackup(definition(root), "manual");- await expect(createBackup(definition(root), "manual")).rejects.toThrow(/one per minute/);+ await createBackup(definition(root), "manual", async () => {});+ await expect(createBackup(definition(root), "manual", async () => {})).rejects.toThrow(/one per minute/);});it("rejects a state tree larger than the per-backup ceiling before copying", async () => {@@ -46,7 +54,7 @@ describe("managed-app backup quotas", () => {const huge = path.join(root, "state", "huge.bin");const handle = await fs.open(huge, "w");try { await handle.truncate(513 * 1024 * 1024); } finally { await handle.close(); }- await expect(createBackup(definition(root), "pre-update")).rejects.toThrow(/512 MiB state limit/);+ await expect(createBackup(definition(root), "pre-update", async () => {})).rejects.toThrow(/512 MiB state limit/);expect(await listBackups("openclaw")).toEqual([]);});});diff --git a/lib/managed-apps/backups.ts b/lib/managed-apps/backups.tsindex 8eb620d8..de5bdd41 100644--- a/lib/managed-apps/backups.ts+++ b/lib/managed-apps/backups.ts@@ -77,7 +77,8 @@ export function backupsRoot(id: ManagedAppId): string {return path.join(os.homedir(), ".mso", "backups", id);}-export async function createBackup(definition: ManagedAppDefinition, reason: ManagedAppBackup["reason"]): Promise<ManagedAppBackup> {+export async function createBackup(definition: ManagedAppDefinition, reason: ManagedAppBackup["reason"], assertQuiescent: () => Promise<void>): Promise<ManagedAppBackup> {+ await assertQuiescent();const source = stateDirFor(definition);const existing = await listBackups(definition.id);if (reason === "manual" && existing[0] && Date.now() - Date.parse(existing[0].createdAt) < MANUAL_BACKUP_MIN_INTERVAL_MS) {@@ -95,6 +96,7 @@ export async function createBackup(definition: ManagedAppDefinition, reason: Manconst skipped = { symlinks: 0, dirs: 0 };let files = 0;let bytes = 0;+ let checkedAt = 0;await fs.cp(source, target, {recursive: true,preserveTimestamps: true,@@ -105,6 +107,7 @@ export async function createBackup(definition: ManagedAppDefinition, reason: Man// whole backup over them — which is what this used to do — meant the// feature never once ran.filter: async (entry) => {+ if (Date.now() - checkedAt >= 1000) { await assertQuiescent(); checkedAt = Date.now(); }if (SKIPPED.has(path.basename(entry))) {skipped.dirs += 1;return false;@@ -121,7 +124,7 @@ export async function createBackup(definition: ManagedAppDefinition, reason: Man}return true;},- }).catch(async error => { await fs.rm(target, { recursive: true, force: true }); throw error; });+ }).then(assertQuiescent).catch(async error => { await fs.rm(target, { recursive: true, force: true }); throw error; });const manifest: ManagedAppBackup = {id,applicationId: definition.id,diff --git a/lib/managed-apps/catalog.ts b/lib/managed-apps/catalog.tsindex 8d59d0e1..8ad901c9 100644--- a/lib/managed-apps/catalog.ts+++ b/lib/managed-apps/catalog.ts@@ -21,8 +21,8 @@ const definitions = {// creates hermes-gateway.service, and scripts/managed-app-install writes// hermes-dashboard.service itself because upstream ships no installer for it.// Dashboard stays FIRST and that ordering is load-bearing — it is the unit serving- // dashboardUrl below, so it is what start/stop must act on and what "is there- // anything to frame" must read. The gateway is messaging plumbing (Telegram,+ // dashboardUrl below, so it remains the primary log/health surface; lifecycle+ // and quiescence checks cover every installed unit/container. The gateway is messaging plumbing (Telegram,// Discord, WhatsApp) and binds nothing on 9119; ranking it first would report a// healthy Hermes while the iframe showed a connection refused.serviceNames: ["hermes-dashboard.service", "hermes-gateway.service", "hermes.service"],@@ -39,8 +39,7 @@ const definitions = {name: "OpenClaw",description: "OpenClaw runtime and control surface",command: "openclaw",- // Live unit first: `openclaw.service` does not exist on this host, and detection- // stops at the first name whose LoadState is not `not-found`.+ // Live unit first for log display; lifecycle/quiescence includes every installed name.serviceNames: ["openclaw-gateway.service", "openclaw.service"],containerNames: ["openclaw", "openclaw-gateway"],dashboardUrl: process.env.OPENCLAW_DASHBOARD_URL ?? "http://127.0.0.1:18789",diff --git a/lib/managed-apps/manager-lifecycle.test.ts b/lib/managed-apps/manager-lifecycle.test.tsnew file mode 100644index 00000000..6fe06f9e--- /dev/null+++ b/lib/managed-apps/manager-lifecycle.test.ts@@ -0,0 +1,74 @@+// Regressions: stopped versus missing service detection, and backups of real installs.+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, expect, it, vi } from "vitest";++vi.mock("server-only", () => ({}));+vi.mock("./runner", () => ({+ runProgram: vi.fn(),+ commandExists: vi.fn().mockResolvedValue(false),+ resolveCommand: vi.fn().mockResolvedValue(null),+ requireProgram: vi.fn(),+}));+// Stub the host user bus so service behavior is deterministic.+vi.mock("./user-bus", () => ({+ userBusEnv: vi.fn(() => ({ XDG_RUNTIME_DIR: "/run/user/1000" })),+ userBusUnavailable: vi.fn(() => false),+}));++const { runProgram, commandExists } = await import("./runner");+const { getManagedApp, performManagedAppAction } = await import("./manager");++const ok = (stdout: string) => ({ code: 0, stdout, stderr: "" });+/** systemd 255 on an unknown unit: rc 0 from `show`, LoadState=not-found. */+const NOT_FOUND = ok("LoadState=not-found\nActiveState=inactive\n");+const ACTIVE = ok("LoadState=loaded\nActiveState=active\n");+const STOPPED = ok("LoadState=loaded\nActiveState=inactive\n");++afterEach(() => vi.restoreAllMocks());++it("reports a live Hermes gateway and stops every installed unit in both scopes", async () => {+ const home = await fs.mkdtemp(path.join(os.tmpdir(), "mso-service-set-"));+ vi.spyOn(os, "homedir").mockReturnValue(home);+ const states: Record<string, typeof ACTIVE> = { "hermes-dashboard.service": STOPPED, "hermes-gateway.service": ACTIVE };+ vi.mocked(runProgram).mockImplementation(async (command, args) => {+ const unit = args[args.length - 1];+ if (command === "systemctl" && args.includes("show")) return states[unit] ?? NOT_FOUND;+ if (command === "systemctl" && args.includes("stop") && states[unit]) { states[unit] = STOPPED; return ok(""); }+ return ok("");+ });+ vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 200 }));+ expect((await getManagedApp("hermes")).state).toBe("running");+ expect((await performManagedAppAction("hermes", "stop")).state).toBe("stopped");+ for (const unit of Object.keys(states)) expect(vi.mocked(runProgram).mock.calls.some(([command, args]) => command === "systemctl" && args.includes("stop") && args.includes(unit))).toBe(true);+ await fs.rm(home, { recursive: true, force: true });+});++it("stops every discovered Hermes container before reporting stopped", async () => {+ const home = await fs.mkdtemp(path.join(os.tmpdir(), "mso-container-set-"));+ vi.spyOn(os, "homedir").mockReturnValue(home);+ vi.mocked(commandExists).mockImplementation(async command => command === "docker");+ const states = new Map([["hermes", true], ["hermes-dashboard", true]]);+ vi.mocked(runProgram).mockImplementation(async (command, args) => {+ if (command === "systemctl") return NOT_FOUND;+ if (command === "docker" && args[0] === "ps") return ok([...states.keys()].join("\n"));+ if (command === "docker" && args[0] === "inspect") return ok(String(states.get(args[args.length - 1])));+ if (command === "docker" && args[0] === "stop") states.set(args[1], false);+ return ok("");+ });+ vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 200 }));+ expect((await getManagedApp("hermes")).state).toBe("running");+ expect((await performManagedAppAction("hermes", "stop")).state).toBe("stopped");+ expect([...states.values()]).toEqual([false, false]);+ await fs.rm(home, { recursive: true, force: true });+});++it("treats a system-scope gateway as live even if the user-scope instance is inactive", async () => {+ vi.mocked(runProgram).mockImplementation(async (command, args) => command === "systemctl" && args.includes("show") && args.includes("hermes-gateway.service") ? args.includes("--user") ? STOPPED : ACTIVE : NOT_FOUND);+ vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 200 }));+ expect((await getManagedApp("hermes")).state).toBe("running");+ const { assertManagedAppStopped } = await import("./manager");+ await expect(assertManagedAppStopped("hermes")).rejects.toThrow(/stop all/);+});+diff --git a/lib/managed-apps/manager.test.ts b/lib/managed-apps/manager.test.tsindex 8d365dd3..d3ad08d7 100644--- a/lib/managed-apps/manager.test.ts+++ b/lib/managed-apps/manager.test.ts@@ -196,7 +196,7 @@ describe("backup copies a real install instead of refusing it", () => {});it("skips symlinks and vendor trees, keeps the state, and records what it left out", async () => {- systemctl({ "openclaw-gateway.service": ACTIVE });+ systemctl({ "openclaw-gateway.service": STOPPED });await performManagedAppAction("openclaw", "backup");const root = path.join(home, ".mso", "backups", "openclaw");diff --git a/lib/managed-apps/manager.ts b/lib/managed-apps/manager.tsindex cf4a0516..3a2ae391 100644--- a/lib/managed-apps/manager.ts+++ b/lib/managed-apps/manager.ts@@ -13,18 +13,14 @@ import type { ManagedAppAction, ManagedAppDefinition, ManagedAppId, ManagedAppLointerface Installation {type: "systemd" | "docker" | "package" | "not-installed";- serviceName?: string;- containerName?: string;+ serviceName?: string; serviceNames?: string[];+ containerName?: string; containerNames?: string[];}// `is-active` cannot tell "this unit is stopped" from "this unit does not exist":-// on systemd 255 an unknown unit prints `inactive` with rc 4 and an empty stderr,-// so the old text match never fired and the FIRST configured name always won the-// detection. Real consequence: OpenClaw's catalog listed a non-existent-// `openclaw.service` first, so its card read "stopped" and start/stop/restart 409'd-// while its gateway was serving. `show -p LoadState` distinguishes them, and one-// call returns both facts.-async function systemdState(service: string): Promise<"active" | "inactive" | "missing"> {+// `show -p LoadState` distinguishes absent units from installed stopped units.+async function systemdState(service: string, strict = false): Promise<"active" | "inactive" | "missing"> {+ let present = false;for (const scope of [["--user"], []]) {// The user scope needs a bus address. mso.service is a SYSTEM unit with// `User=`, which inherits no login session and therefore no@@ -35,33 +31,38 @@ async function systemdState(service: string): Promise<"active" | "inactive" | "mconst result = await runProgram("systemctl", [...scope, "show", "-p", "LoadState", "-p", "ActiveState", service], 10_000, env);// Non-zero here is no systemctl at all, or no user bus — not an answer about// the unit, so try the next scope rather than concluding anything.- if (result.code !== 0) continue;+ if (result.code !== 0) { if (strict) throw new Error("Cannot confirm all managed-app service states"); continue; }const load = /LoadState=(\S+)/.exec(result.stdout)?.[1];if (!load || load === "not-found") continue;- return /ActiveState=active/.test(result.stdout) ? "active" : "inactive";+ present = true;+ if (/ActiveState=(?:active|activating|deactivating|reloading)\b/.test(result.stdout)) return "active";}- return "missing";+ return present ? "inactive" : "missing";}-async function detect(definition: ManagedAppDefinition): Promise<Installation> {+async function detect(definition: ManagedAppDefinition, strict = false): Promise<Installation> {+ const serviceNames: string[] = [];for (const serviceName of definition.serviceNames) {- if (await systemdState(serviceName) !== "missing") return { type: "systemd", serviceName };+ if (await systemdState(serviceName, strict) !== "missing") serviceNames.push(serviceName);}+ let containerNames: string[] = [];if (await dockerUsable()) {const result = await runDocker(["ps", "-a", "--format", "{{.Names}}"], 10_000);+ if (result.code !== 0) throw new Error("Cannot confirm managed-app container inventory");const names = new Set(result.stdout.split(/\r?\n/).map((name) => name.trim()));- const containerName = definition.containerNames.find((name) => names.has(name));- if (containerName) return { type: "docker", containerName };- }+ containerNames = definition.containerNames.filter((name) => names.has(name));+ } else if (strict && await commandExists("docker")) throw new Error("Cannot confirm managed-app Docker state");+ if (serviceNames.length || containerNames.length) return { type: serviceNames.length ? "systemd" : "docker", ...(serviceNames.length ? { serviceName: serviceNames[0], serviceNames } : {}), ...(containerNames.length ? { containerName: containerNames[0], containerNames } : {}) };if (definition.commandProvesInstall !== false && await commandExists(definition.command)) return { type: "package" };return { type: "not-installed" };}-async function running(installation: Installation): Promise<boolean> {- if (installation.type === "systemd" && installation.serviceName) return (await systemdState(installation.serviceName)) === "active";- if (installation.type === "docker" && installation.containerName) {- const result = await runDocker(["inspect", "--format", "{{.State.Running}}", installation.containerName], 10_000);- return result.code === 0 && result.stdout.trim() === "true";+async function running(installation: Installation, strict = false): Promise<boolean> {+ if (installation.serviceNames && (await Promise.all(installation.serviceNames.map(name => systemdState(name, strict)))).some((state) => state === "active")) return true;+ for (const containerName of installation.containerNames ?? []) {+ const result = await runDocker(["inspect", "--format", "{{.State.Running}}", containerName], 10_000);+ if (result.code !== 0 || !["true", "false"].includes(result.stdout.trim())) throw new Error("Cannot confirm managed-app container state");+ if (result.stdout.trim() === "true") return true;}return false;}@@ -193,14 +194,26 @@ export async function listManagedApps(): Promise<ManagedAppView[]> {return views;}+export async function assertManagedAppStopped(id: ManagedAppId): Promise<void> {+ if (await running(await detect(getManagedAppDefinition(id), true), true)) throw new Error("Cannot confirm app is stopped; stop all app services before backup or restore");+}+async function runLifecycle(installation: Installation, action: "start" | "stop" | "restart"): Promise<void> {+ if (installation.serviceNames || installation.containerNames) {+ for (const serviceName of installation.serviceNames ?? []) await runLifecycle({ type: "systemd", serviceName }, action);+ for (const containerName of installation.containerNames ?? []) await runLifecycle({ type: "docker", containerName }, action);+ if (action === "stop" && await running(installation)) throw new Error("A managed-app service is still active after stop");+ return;+ }if (installation.type === "systemd" && installation.serviceName) {let lastError = "";+ let succeeded = false;for (const args of [["--user", action, installation.serviceName], [action, installation.serviceName]]) {const result = await runProgram("systemctl", args, 30_000, args[0] === "--user" ? userBusEnv() : undefined);- if (result.code === 0) return;+ if (result.code === 0) succeeded = true;lastError = result.stderr.trim() || result.stdout.trim() || `systemctl exited ${result.code}`;}+ if (succeeded) return;// Falling through to the generic throw below reported every one of these as// "operation unsupported for detected installation type" — served as a 409,// and flatly untrue: the installation type was detected fine, systemctl just@@ -224,7 +237,7 @@ export async function performManagedAppAction(id: ManagedAppId, action: ManagedAconst definition = getManagedAppDefinition(id);const installation = await detect(definition);if (!actionsFor(installation).includes(action)) throw new Error("operation unsupported for detected installation type");- if (action === "backup") await createBackup(definition, "manual");+ if (action === "backup") await createBackup(definition, "manual", () => assertManagedAppStopped(id));else await runLifecycle(installation, action);} finally {releaseOperation(id);diff --git a/lib/managed-apps/restore.test.ts b/lib/managed-apps/restore.test.tsindex b724c9eb..8478e92f 100644--- a/lib/managed-apps/restore.test.ts+++ b/lib/managed-apps/restore.test.ts@@ -11,7 +11,7 @@ vi.mock("server-only", () => ({}));// The app must be stopped, and asking systemd about it in a unit test would be// asking about the real host's units.const mocks = vi.hoisted(() => ({ state: { value: "stopped" } }));-vi.mock("./manager", () => ({ getManagedApp: async () => ({ state: mocks.state.value, name: "Hermes" }) }));+vi.mock("./manager", () => ({ getManagedApp: async () => ({ state: mocks.state.value, name: "Hermes" }), assertManagedAppStopped: vi.fn().mockResolvedValue(undefined) }));delete process.env.HERMES_HOME;@@ -84,13 +84,20 @@ describe("what restore refuses before a byte moves", () => {});it("refuses while the app is running rather than stopping it", async () => {- const backup = await createBackup(definition(), "manual");+ const backup = await createBackup(definition(), "manual", async () => {});for (const live of ["running", "starting", "unhealthy"]) {mocks.state.value = live;await expect(restore(backup.id)).rejects.toThrow(`is ${live}; stop it before restoring`);}});+ it("refuses before overwriting when a service restarts during the safety backup", async () => {+ const backup = await createBackup(definition(), "manual", async () => {});+ await fs.writeFile(path.join(state, "config.yaml"), "current state");+ await expect(restoreManagedAppBackup("hermes", backup.id, text => { if (text.includes("current state saved")) mocks.state.value = "running"; })).rejects.toThrow(/stop it/);+ expect(await fs.readFile(path.join(state, "config.yaml"), "utf8")).toBe("current state");+ });+it("refuses to write through a symlink that points out of the state dir", async () => {const outside = path.join(home, "outside.txt");await fs.writeFile(outside, "untouched");@@ -109,7 +116,7 @@ describe("what restore refuses before a byte moves", () => {// part snapshot, part itself, and the message said only "refusing".const outside = path.join(home, "outside.txt");await fs.writeFile(outside, "untouched");- const backup = await createBackup(definition(), "manual");+ const backup = await createBackup(definition(), "manual", async () => {});// A file in the snapshot whose counterpart in the state dir became a link.await fs.writeFile(path.join(home, ".mso", "backups", "hermes", backup.id, "token.txt"), "would follow the link");await fs.symlink(outside, path.join(state, "token.txt"));@@ -130,7 +137,7 @@ describe("what restore refuses before a byte moves", () => {// the snapshot has a directory writes every file under it somewhere else.const elsewhere = path.join(home, "elsewhere");await fs.mkdir(elsewhere);- const backup = await createBackup(definition(), "manual");+ const backup = await createBackup(definition(), "manual", async () => {});await fs.rm(path.join(state, "sessions"), { recursive: true, force: true });await fs.symlink(elsewhere, path.join(state, "sessions"));@@ -140,7 +147,7 @@ describe("what restore refuses before a byte moves", () => {it("leaves no safety backup behind when it refuses", async () => {mocks.state.value = "running";- const backup = await createBackup(definition(), "manual");+ const backup = await createBackup(definition(), "manual", async () => {});await expect(restore(backup.id)).rejects.toThrow();expect((await listBackups("hermes")).map((entry) => entry.reason)).toEqual(["manual"]);});@@ -148,7 +155,7 @@ describe("what restore refuses before a byte moves", () => {describe("what a restore actually does", () => {it("overwrites the snapshot's files, keeps the current state as an undo, and says what it could not bring back", async () => {- const backup = await createBackup(definition(), "manual");+ const backup = await createBackup(definition(), "manual", async () => {});await fs.writeFile(path.join(state, "config.yaml"), "version: 2\n");await fs.writeFile(path.join(state, "added-later.txt"), "new");await fs.writeFile(path.join(state, "node_modules", "pkg", "index.js"), "rebuilt");@@ -177,7 +184,7 @@ describe("what a restore actually does", () => {});it("never copies its own manifest into the application's state dir", async () => {- const backup = await createBackup(definition(), "manual");+ const backup = await createBackup(definition(), "manual", async () => {});await restore(backup.id);await expect(fs.stat(path.join(state, "manifest.json"))).rejects.toThrow();});@@ -188,7 +195,7 @@ describe("what a restore actually does", () => {// by the time anyone wants it back, the directory it names is gone. This// used to refuse with "the application state directory does not exist" —// the one backup the UI calls the operator's only way back, unrestorable.- const backup = await createBackup(definition(), "pre-uninstall");+ const backup = await createBackup(definition(), "pre-uninstall", async () => {});await fs.rm(state, { recursive: true, force: true });const result = await restore(backup.id);@@ -211,7 +218,7 @@ describe("what a restore actually does", () => {const freshCatalog = await import("./catalog");await fs.mkdir(path.join(home, "nowhere", "hermes"), { recursive: true });await fs.writeFile(path.join(home, "nowhere", "hermes", "config.yaml"), "version: 1\n");- const backup = await freshBackups.createBackup(freshCatalog.getManagedAppDefinition("hermes"), "pre-uninstall");+ const backup = await freshBackups.createBackup(freshCatalog.getManagedAppDefinition("hermes"), "pre-uninstall", async () => {});await fs.rm(path.join(home, "nowhere"), { recursive: true, force: true });await expect(fresh.restoreManagedAppBackup("hermes", backup.id, append)).rejects.toThrow("so is its parent");@@ -244,7 +251,7 @@ describe("what a restore actually does", () => {});it("refuses when the state dir is itself a symlink", async () => {- const backup = await createBackup(definition(), "manual");+ const backup = await createBackup(definition(), "manual", async () => {});const elsewhere = path.join(home, "moved-hermes");await fs.rename(state, elsewhere);await fs.symlink(elsewhere, state);diff --git a/lib/managed-apps/restore.ts b/lib/managed-apps/restore.tsindex 05d99649..4fd5b2fc 100644--- a/lib/managed-apps/restore.ts+++ b/lib/managed-apps/restore.ts@@ -4,7 +4,7 @@ import os from "node:os";import path from "node:path";import { BACKUP_SKIPPED_DIRS, backupsRoot, createBackup, isManagedAppBackupId, readBackupManifest, stateDirFor } from "./backups";import { getManagedAppDefinition } from "./catalog";-import { getManagedApp } from "./manager";+import { getManagedApp, assertManagedAppStopped } from "./manager";import type { ManagedAppDefinition, ManagedAppId } from "./types";import type { ManagedAppRestoreResult } from "./update-types";@@ -55,6 +55,7 @@ async function assertStopped(id: ManagedAppId): Promise<void> {// then would copy a snapshot over the live state of a running application.if (view.diagnostic) throw new Error(`cannot confirm ${view.name} is stopped — refusing to restore. ${view.diagnostic}`);if (RESTORE_BLOCKING_STATES.has(view.state)) throw new Error(`${view.name} is ${view.state}; stop it before restoring a backup`);+ await assertManagedAppStopped(id);}/** The state dir is GONE — the normal case for the restore that matters most:@@ -158,18 +159,21 @@ export async function restoreManagedAppBackup(id: ManagedAppId, backupId: string// The undo. Taken AFTER the gates so a refused restore does not litter, and// before the first write so the current state is always recoverable.- const safety = await createBackup(definition, "pre-restore");+ const safety = await createBackup(definition, "pre-restore", () => assertStopped(id));append(`[mso] current state saved as ${safety.id} (${safety.files ?? "?"} files) before overwriting\n`);+ await assertStopped(id);const manifestFile = path.join(dir, "manifest.json");let filesRestored = 0;let bytesRestored = 0;+ let checkedAt = 0;try {await fs.cp(dir, target, {recursive: true,force: true,preserveTimestamps: true,filter: async (from, to) => {+ if (Date.now() - checkedAt >= 1000) { await assertStopped(id); checkedAt = Date.now(); }if (from === manifestFile) return false; // ours, not the app'sconst entry = await fs.lstat(from);// A snapshot contains no symlinks by construction; one that appeareddiff --git a/lib/managed-apps/session.test.ts b/lib/managed-apps/session.test.tsnew file mode 100644index 00000000..63818bf6--- /dev/null+++ b/lib/managed-apps/session.test.ts@@ -0,0 +1,36 @@+import { NextRequest } from "next/server";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { signSession, verifySession } from "@/lib/auth/session";+const device = vi.hoisted(() => ({ role: "owner", approved: true }));+vi.mock("@/lib/auth/device-store", () => ({ getApprovedDevice: async () => device.approved ? { approvedAt: 1, role: device.role } : null, currentSessionPolicy: async (scope: string) => ({ scope, epoch: "epoch-0000000000000000" }) }));+const secret = "s".repeat(32);+beforeEach(() => { vi.resetModules(); vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", "{id}.mso.example.com"); vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.com"); vi.stubEnv("OS_SESSION_SECRET", secret); device.role = "owner"; device.approved = true; });+afterEach(() => vi.unstubAllEnvs());+const payload = () => ({ issued_at: Date.now(), expires_at: Date.now() + 3600000, device_id: "a".repeat(32), cookie_scope: "host", cookie_epoch: "epoch-0000000000000000" });+it("binds tickets and cookies to one app origin and separate signing purposes", async () => {+ const auth = await import("./session"), session = payload();+ const ticket = auth.createManagedAppTicket("hermes", session, secret), cookie = auth.createManagedAppCookie("hermes", session, secret);+ expect(auth.verifyManagedAppSession("hermes", ticket, secret, "ticket")).not.toBeNull();+ expect(auth.verifyManagedAppSession("openclaw", ticket, secret, "ticket")).toBeNull();+ expect(auth.verifyManagedAppSession("hermes", ticket, secret)).toBeNull();+ expect(auth.verifyManagedAppSession("hermes", signSession(session, secret), secret)).toBeNull();+ expect(verifySession(cookie, secret)).toBeNull(); expect(verifySession(ticket, secret)).toBeNull();+ expect(auth.verifyManagedAppSession("hermes", auth.createManagedAppTicket("hermes", session, secret, Date.now() - 120000), secret, "ticket")).toBeNull();+});+it("exchanges a fresh ticket for a host-only cookie and rechecks revocation and role", async () => {+ const auth = await import("./session");+ const ticket = auth.createManagedAppTicket("hermes", payload(), secret);+ const exchange = await auth.gateManagedApp(new NextRequest("https://hermes.mso.example.com/__mso_app_auth", { method: "POST", headers: { origin: "https://hermes.mso.example.com", authorization: "Bearer " + ticket } }), "hermes");+ expect(exchange?.status).toBe(204);+ const cookie = exchange!.headers.getSetCookie()[0]; expect(cookie).toContain("__Host-mso-managed-app="); expect(cookie).not.toMatch(/Domain=/i); expect(cookie).toContain("Secure"); expect(cookie).toContain("HttpOnly");+ const request = new Request("https://hermes.mso.example.com/", { headers: { cookie: cookie.split(";")[0] } });+ expect(await auth.managedAppSession(request, "hermes")).not.toBeNull();+ device.role = "viewer"; expect(await auth.managedAppSession(request, "hermes")).toBeNull();+ device.role = "owner"; device.approved = false; expect(await auth.managedAppSession(request, "hermes")).toBeNull();+});+it("refuses cockpit cookies, wrong-origin exchange and unauthenticated subresources", async () => {+ const auth = await import("./session");+ const request = new NextRequest("https://hermes.mso.example.com/api", { headers: { cookie: "session=" + signSession(payload(), secret) } });+ expect((await auth.gateManagedApp(request, "hermes"))?.status).toBe(401);+ expect((await auth.gateManagedApp(new NextRequest("https://hermes.mso.example.com/__mso_app_auth", { method: "POST", headers: { origin: "https://mso.example.com" } }), "hermes"))?.status).toBe(403);+});diff --git a/lib/managed-apps/session.ts b/lib/managed-apps/session.tsnew file mode 100644index 00000000..092dae49--- /dev/null+++ b/lib/managed-apps/session.ts@@ -0,0 +1,61 @@+import { NextResponse, type NextRequest } from "next/server";+import { MIN_SECRET_LEN, signSession, verifySession, type SessionPayload } from "@/lib/auth/session";+import { liveSessionAuthorized } from "@/lib/auth/live-authorization";+import { managedAppOrigin, cockpitOrigin } from "./origin";+import type { ManagedAppId } from "./types";++export const MANAGED_APP_SESSION_COOKIE = "__Host-mso-managed-app";+const TICKET_TTL = 60_000;+const COOKIE_TTL = 2 * 60 * 60 * 1000;+function key(id: ManagedAppId, kind: "ticket" | "cookie", secret: string): string {+ const origin = managedAppOrigin(id);+ if (!origin || secret.length < MIN_SECRET_LEN) throw new Error("managed application authorization is unavailable");+ return `managed-app:${origin}:${kind}:${secret}`;+}+export function createManagedAppTicket(id: ManagedAppId, session: SessionPayload, secret: string, now = Date.now()): string {+ return signSession({ ...session, expires_at: Math.min(session.expires_at, now + TICKET_TTL) }, key(id, "ticket", secret));+}+export function createManagedAppCookie(id: ManagedAppId, session: SessionPayload, secret: string): string {+ return signSession({ ...session, expires_at: Date.now() + COOKIE_TTL }, key(id, "cookie", secret));+}+export function verifyManagedAppSession(id: ManagedAppId, token: string, secret: string, kind: "ticket" | "cookie" = "cookie"): SessionPayload | null {+ try { return verifySession(token, key(id, kind, secret)); } catch { return null; }+}+export async function managedAppSession(request: Request, id: ManagedAppId): Promise<SessionPayload | null> {+ const secret = process.env.OS_SESSION_SECRET ?? "";+ const candidates = (request.headers.get("cookie") ?? "").split(";");+ for (const candidate of candidates) {+ const [name, ...parts] = candidate.trim().split("=");+ if (name !== MANAGED_APP_SESSION_COOKIE) continue;+ const session = verifyManagedAppSession(id, parts.join("="), secret);+ if (session && await liveSessionAuthorized(session, "operator")) return session;+ }+ return null;+}++const SCRIPT = "(async()=>{const p=new URLSearchParams(location.hash.slice(1));const t=p.get('app_ticket');p.delete('app_ticket');history.replaceState(null,'',location.pathname+location.search+(p.toString()?'#'+p.toString():''));if(!t){document.body.textContent='Open this application from MSO to authorize it.';return;}const r=await fetch('/__mso_app_auth',{method:'POST',headers:{authorization:'Bearer '+t},credentials:'include',cache:'no-store'});if(!r.ok){document.body.textContent='Application authorization failed. Reopen it from MSO.';return;}location.reload();})().catch(()=>{document.body.textContent='Application authorization failed.';});";+function response(body: string | null, status: number, contentType = "text/plain; charset=utf-8") {+ return new NextResponse(body, { status, headers: {+ "content-type": contentType, "cache-control": "no-store, no-transform",+ "cdn-cache-control": "no-store", "cloudflare-cdn-cache-control": "no-store",+ "referrer-policy": "no-referrer", "x-content-type-options": "nosniff",+ "content-security-policy": `default-src 'none'; script-src 'self'; connect-src 'self'; frame-ancestors ${cockpitOrigin() ?? "'none'"}`,+ } });+}+// An app receives a purpose- and origin-bound credential, never the cockpit cookie.+export async function gateManagedApp(request: NextRequest, id: ManagedAppId): Promise<NextResponse | null> {+ if (request.nextUrl.pathname === "/__mso_app_bootstrap.js") return request.method === "GET" ? response(SCRIPT, 200, "application/javascript; charset=utf-8") : response(null, 404);+ if (request.nextUrl.pathname === "/__mso_app_auth") {+ if (request.method !== "POST" || request.headers.get("origin") !== managedAppOrigin(id)) return response(null, 403);+ const token = /^Bearer ([A-Za-z0-9._-]{20,4096})$/.exec(request.headers.get("authorization") ?? "")?.[1];+ const secret = process.env.OS_SESSION_SECRET ?? "";+ const session = token ? verifyManagedAppSession(id, token, secret, "ticket") : null;+ if (!session || !await liveSessionAuthorized(session, "operator")) return response(null, 401);+ const result = response(null, 204);+ result.cookies.set(MANAGED_APP_SESSION_COOKIE, createManagedAppCookie(id, session, secret), { httpOnly: true, secure: true, sameSite: "strict", path: "/", maxAge: COOKIE_TTL / 1000 });+ return result;+ }+ if (await managedAppSession(request, id)) return null;+ if (request.method !== "GET" || request.headers.get("sec-fetch-dest") !== "iframe" && request.headers.get("sec-fetch-dest") !== "document") return response(null, 401);+ return response('<!doctype html><meta charset="utf-8"><title>MSO application authorization</title><body><p>Authorizing application...</p><script src="/__mso_app_bootstrap.js" defer></script></body>', 200, "text/html; charset=utf-8");+}diff --git a/lib/managed-apps/socket-policy.test.ts b/lib/managed-apps/socket-policy.test.tsindex 499e2692..4fbc5234 100644--- a/lib/managed-apps/socket-policy.test.ts+++ b/lib/managed-apps/socket-policy.test.ts@@ -3,7 +3,6 @@ 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-"));@@ -14,13 +13,14 @@ 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");+const { createManagedAppCookie } = await import("./session");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 signed = createManagedAppCookie("hermes", { 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: `__Host-mso-managed-app=${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();diff --git a/lib/managed-apps/socket-policy.ts b/lib/managed-apps/socket-policy.tsindex 453036ff..d13dfef7 100644--- a/lib/managed-apps/socket-policy.ts+++ b/lib/managed-apps/socket-policy.ts@@ -1,6 +1,6 @@import type { NextRequest } from "next/server";-import { verifySession } from "@/lib/auth/session";import { liveSessionAuthorized } from "@/lib/auth/live-authorization";+import { MANAGED_APP_SESSION_COOKIE, verifyManagedAppSession } from "./session";import { CAMOUFOX_VIEWER_COOKIE, verifyCamoufoxViewerCookie } from "@/lib/camoufox/viewer-auth";import { getApprovedDevice } from "@/lib/auth/device-store";import { deviceSessionValid } from "@/lib/auth/live-session";@@ -22,8 +22,8 @@ export async function socketPolicy(request: NextRequest) {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);+ for (const { value } of request.cookies.getAll(viewer ? CAMOUFOX_VIEWER_COOKIE : MANAGED_APP_SESSION_COOKIE)) {+ const session = viewer ? verifyCamoufoxViewerCookie(value, secret) : verifyManagedAppSession(app!, value, secret);if (!session?.device_id) continue;if (viewer) {const device = await getApprovedDevice(session.device_id);diff --git a/lib/managed-apps/update.test.ts b/lib/managed-apps/update.test.tsindex a5f9d928..b2578ccc 100644--- a/lib/managed-apps/update.test.ts+++ b/lib/managed-apps/update.test.ts@@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { ManagedAppJob } from "./types";vi.mock("server-only", () => ({}));+vi.mock("./manager", () => ({ assertManagedAppStopped: vi.fn().mockResolvedValue(undefined) }));// The catalog reads HERMES_HOME at module load and it MOVES the backup source.// Cleared before the dynamic import below so a set env var cannot point a testdiff --git a/lib/managed-apps/update.ts b/lib/managed-apps/update.tsindex 54520b51..21d0a972 100644--- a/lib/managed-apps/update.ts+++ b/lib/managed-apps/update.ts@@ -5,6 +5,7 @@ import { createBackup, isManagedAppBackupId, stateDirFor } from "./backups";import { getManagedAppDefinition } from "./catalog";import { startManagedAppJob } from "./jobs";import { activeOperation } from "./lock";+import { assertManagedAppStopped } from "./manager";import { restoreManagedAppBackup } from "./restore";import { resolveCommand, runProgram } from "./runner";import type { ManagedAppDefinition, ManagedAppId, ManagedAppJob } from "./types";@@ -127,7 +128,7 @@ async function snapshot(definition: ManagedAppDefinition, reason: ManagedAppBack}let backup: ManagedAppBackup;try {- backup = await createBackup(definition, reason);+ backup = await createBackup(definition, reason, () => assertManagedAppStopped(definition.id));} catch (error) {throw new Error(`${reason} backup failed, nothing was run: ${message(error)}`);}diff --git a/lib/mcp/federation/batonly-worker.test.ts b/lib/mcp/federation/batonly-worker.test.tsindex a3036bf0..137562e4 100644--- a/lib/mcp/federation/batonly-worker.test.ts+++ b/lib/mcp/federation/batonly-worker.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from "vitest";vi.mock("server-only", () => ({}));+vi.mock("@/lib/federation/local-approval", () => ({ consumeFederationApproval: vi.fn(async () => "/reviewed-project") }));vi.mock("@/lib/federation/si-coder-runtime", () => ({inspectSiCoderFederationRuntime: vi.fn(async () => ({version: "0.9.8",diff --git a/lib/mcp/federation/execution.ts b/lib/mcp/federation/execution.tsindex 6283972f..230b491b 100644--- a/lib/mcp/federation/execution.ts+++ b/lib/mcp/federation/execution.ts@@ -1,6 +1,8 @@import { executeCapabilityCall } from "@/lib/capabilities/execute";import { validateFederationArguments, FEDERATION_WORKER_ID } from "@/lib/federation/security";import { executeSiCoderFederation } from "@/lib/federation/si-coder-runtime";+import { consumeFederationApproval } from "@/lib/federation/local-approval";+import { resolveProjectHint } from "@/lib/host/projects-api";import { msoCapabilityRuntime } from "../capability-runtime";import { TOOLS_BY_NAME } from "../tools";import { BATON_SERVER, type FederationRequest } from "./types";@@ -25,6 +27,14 @@ export async function executeMsoFederation(request: FederationRequest) {if (recursiveMsoRequest(request.operation, args)) {throw new Error("recursive Batonly project MCP federation is not allowed");}+ // shortcut: durable federation jobs/delegation stay closed until they propagate a revocable local grant.+ if (["exec_job_start", "agent_subagent_run", "local_agent_request", "project_agent_run", "a2a_agent_spawn", "workflow_graph_run", "flow_run"].includes(tool.name)) throw new Error("federation durable delegation requires a propagated local grant");+ const projectPath = await consumeFederationApproval(request);+ if (typeof args.project === "string" && (await resolveProjectHint(args.project))?.path !== projectPath) throw new Error("federation project argument differs from the approved project");+ if (["exec_run", "exec_job_start"].includes(tool.name)) {+ if (args.cwd !== undefined && args.cwd !== projectPath) throw new Error("federation cwd differs from the approved project");+ args.cwd = projectPath;+ }const outcome = await executeCapabilityCall({tool,@@ -50,6 +60,8 @@ export async function executeFederationRequest(request: FederationRequest, cwd =? executeMsoFederation({ ...request, arguments: args }): executeSiCoderFederation({cwd,+ id: request.id,+ projectId: request.projectId,operation: request.operation,arguments: args,scope: request.scope,diff --git a/lib/mcp/surface-cookie.test.ts b/lib/mcp/surface-cookie.test.tsindex b687da87..abdf3344 100644--- a/lib/mcp/surface-cookie.test.ts+++ b/lib/mcp/surface-cookie.test.ts@@ -1,13 +1,16 @@import { afterEach, expect, it, vi } from "vitest";import { surfaceApps, surfaceAppById, resolveSurfaceRoute } from "./surface-catalog";afterEach(() => vi.unstubAllEnvs());-it("rejects Page access to an external editor in the cockpit cookie domain", async () => {+it("rejects Page access on another cockpit port and allows a separately authenticated sibling", async () => {vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.com");vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", ".mso.example.com");- vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([{ id: "external", title: "External editor", origin: "https://editor.mso.example.com", startPath: "/", renderer: "iframe", presentation: "inline", environment: "production", placements: ["mcp-page"] }]));+ const app = { id: "external", title: "External editor", origin: "https://mso.example.com:8443", startPath: "/", renderer: "iframe", presentation: "inline", environment: "production", placements: ["mcp-page"] };+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app]));expect(await surfaceApps()).toEqual([]);expect(await surfaceAppById("external")).toBeUndefined();await expect(resolveSurfaceRoute("/apps/external")).rejects.toThrow("unknown MSO Page app");vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", "");+ expect(await surfaceApps()).toEqual([]);+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([{ ...app, origin: "https://editor.mso.example.com" }]));expect((await surfaceApps())[0].id).toBe("external");});diff --git a/lib/mcp/tools-a2a.ts b/lib/mcp/tools-a2a.tsindex a67780bb..9baf03c4 100644--- a/lib/mcp/tools-a2a.ts+++ b/lib/mcp/tools-a2a.ts@@ -70,7 +70,7 @@ export const A2A_TOOLS: McpTool[] = [},{name: "a2a_task_get",- description: "Read the latest state of a task previously returned by an A2A v1 agent. This is the A2A status/poll operation.",+ description: "Read the latest state of an A2A v1 task. Public peers are read-scoped; registered peers using stored credentials require exec authority.",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"]),diff --git a/lib/mcp/tools-local-agents.test.ts b/lib/mcp/tools-local-agents.test.tsindex 050edb11..3930193e 100644--- a/lib/mcp/tools-local-agents.test.ts+++ b/lib/mcp/tools-local-agents.test.ts@@ -8,6 +8,12 @@ const { LOCAL_AGENT_TOOLS } = await import("./tools-local-agents");const local = new Map(LOCAL_AGENT_TOOLS.map((tool) => [tool.name, tool]));describe("native local session agent MCP tools", () => {+ it("uses the Organization storage alias while retaining the web authority", async () => {+ const { handoffOwnerLocalSession } = await import("@/lib/a2a/local-session");+ const context = { principal: "web:device", sessionId: "parent", scope: "exec" as const, capabilities: { list: () => [], invoke: vi.fn() } };+ await local.get("local_agent_request")!.run({ target: "target", objective: "inspect" }, context);+ expect(handoffOwnerLocalSession).toHaveBeenCalledWith("cli:device", "target", "inspect", context.capabilities, "parent", { authority: context });+ });it("carries the initiating grant and restrictions into on-demand workers", async () => {const { handoffOwnerLocalSession } = await import("@/lib/a2a/local-session");const context = { principal: "mcp-client:fixture", sessionId: "parent", scope: "exec" as const, authorizationGrant: { kind: "mcp" as const, id: "a".repeat(64), resource: "https://fixture.invalid/mcp", fingerprint: "fixture" }, allowedTools: ["local_agent_request", "project_get"], toolArgumentConstraints: { project_get: { project: ["reviewed"] } }, capabilities: { list: () => [], invoke: vi.fn() } };diff --git a/lib/mcp/tools-local-agents.ts b/lib/mcp/tools-local-agents.tsindex bb8c358d..cd9d596f 100644--- a/lib/mcp/tools-local-agents.ts+++ b/lib/mcp/tools-local-agents.ts@@ -1,4 +1,5 @@import { listLocalAgents } from "@/lib/agent/local-agent-directory";+import { organizationLocalAgentPrincipal } from "@/lib/agent/organization-runtime";import { updateLocalAgentMessageState } from "@/lib/agent/local-agent-mailbox";import { replyLocalAgentMessage, sendLocalAgentMessage, waitForLocalAgentInbox, waitForLocalAgentReply } from "@/lib/agent/local-agent-messaging";import {@@ -119,7 +120,7 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [run: async (a, context) => {const current = sessionContext(context);if (!context.capabilities) throw new Error("capability runtime unavailable for local-agent delegation");- const result = await handoffOwnerLocalSession(current.principal, str(a, "target"), str(a, "objective"), context.capabilities, current.sessionId, { authority: context });+ const result = await handoffOwnerLocalSession(organizationLocalAgentPrincipal(current.principal), str(a, "target"), str(a, "objective"), context.capabilities, current.sessionId, { authority: context });return { mode: "durable_session_worker", ...result };},},diff --git a/lib/mcp/workflow-workspace-guard.test.ts b/lib/mcp/workflow-workspace-guard.test.tsindex 7fa41160..7ac70763 100644--- a/lib/mcp/workflow-workspace-guard.test.ts+++ b/lib/mcp/workflow-workspace-guard.test.ts@@ -3,7 +3,7 @@ import os from "node:os";import path from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import { resetWorkflowStoreCache, startWorkflow } from "@/lib/workflow";-import { requireWorkflowExecCwd, requireWorkflowMutationPath } from "./workflow-workspace-guard";+import { requireWorkflowExecCwd, requireWorkflowMutationPath, requireWorkflowProjectTarget } from "./workflow-workspace-guard";const roots: string[] = [];afterEach(async () => {@@ -30,6 +30,13 @@ async function isolatedFixture() {}describe("workflow source workspace guard", () => {+ it("rejects symlinked mutation, execution and project targets inside the worktree", async () => {+ const { project, workspace, context } = await isolatedFixture();+ const link = path.join(workspace, "escape"); await fs.symlink(project, link);+ await expect(requireWorkflowMutationPath(context, path.join(link, "new.ts"))).rejects.toThrow(/symlinks/);+ await expect(requireWorkflowExecCwd(context, link)).rejects.toThrow(/symlinks/);+ await expect(requireWorkflowProjectTarget(context, link)).rejects.toThrow(/symlinks/);+ });it("allows mutation in the task worktree and rejects canonical/host writes", async () => {const { project, workspace, context } = await isolatedFixture();await expect(requireWorkflowMutationPath(context, path.join(workspace, "src/a.ts"))).resolves.toBeUndefined();diff --git a/lib/mcp/workflow-workspace-guard.ts b/lib/mcp/workflow-workspace-guard.tsindex c3d03d6c..3d490b4a 100644--- a/lib/mcp/workflow-workspace-guard.ts+++ b/lib/mcp/workflow-workspace-guard.ts@@ -2,6 +2,7 @@ import type { CapabilityRunContext } from "@/lib/capabilities/tool";import { activeWorkflowForActor } from "@/lib/workflow";import os from "node:os";import path from "node:path";+import { promises as fs } from "node:fs";function absolute(value: string): string {if (value === "~") return os.homedir();@@ -14,6 +15,17 @@ function inside(root: string, candidate: string): boolean {return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));}+async function canonicalWorkspaceTarget(root: string, target: string): Promise<void> {+ const canonicalRoot = await fs.realpath(root);+ let current = root;+ for (const part of path.relative(root, target).split(path.sep).filter(Boolean)) {+ current = path.join(current, part);+ const stat = await fs.lstat(current).catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return null; throw error; });+ if (!stat) break;+ if (stat.isSymbolicLink() || !inside(canonicalRoot, await fs.realpath(current))) throw new Error("source-isolated workflow cannot traverse workspace symlinks");+ }+}+async function isolatedWorkspace(context: CapabilityRunContext) {const actor = context.workflowActor ?? context.actor;if (!actor || !context.workflowId) return null;@@ -36,6 +48,7 @@ export async function requireWorkflowMutationPath(context: CapabilityRunContext,if (!inside(isolated.workspace, target)) {throw new Error(`workflow ${isolated.workflowId} is source-isolated; mutate only inside ${isolated.workspace}`);}+ await canonicalWorkspaceTarget(isolated.workspace, target);}/** Shell is the widest authority surface. During isolated source work it must@@ -49,6 +62,7 @@ export async function requireWorkflowExecCwd(context: CapabilityRunContext, rawCif (!inside(isolated.workspace, cwd)) {throw new Error(`workflow ${isolated.workflowId} is source-isolated; exec cwd must stay inside ${isolated.workspace}`);}+ await canonicalWorkspaceTarget(isolated.workspace, cwd);}export async function requireWorkflowProjectTarget(context: CapabilityRunContext, projectPath: string): Promise<void> {@@ -57,4 +71,5 @@ export async function requireWorkflowProjectTarget(context: CapabilityRunContextif (!inside(isolated.workspace, absolute(projectPath))) {throw new Error(`workflow ${isolated.workflowId} is source-isolated; project execution must target ${isolated.workspace}`);}+ await canonicalWorkspaceTarget(isolated.workspace, absolute(projectPath));}diff --git a/lib/surfaces/cookie-policy.ts b/lib/surfaces/cookie-policy.tsindex fc2a24e1..8dd54c74 100644--- a/lib/surfaces/cookie-policy.ts+++ b/lib/surfaces/cookie-policy.ts@@ -1,5 +1,3 @@-import { sessionCookieDomain } from "@/lib/auth/session-cookie";-/** A different origin is not enough: cookies are domain scoped, never port scoped.* Registry review is presentation approval, not permission to receive MSO credentials. */export function externalSurfaceSharesSession(origin: string, cockpitOrigins: string[]): boolean {@@ -12,6 +10,5 @@ export function externalSurfaceSharesSession(origin: string, cockpitOrigins: str// Exact cockpit navigation is allowed; consumers still refuse to frame it.if (cockpits.some(url => url.origin === target.origin)) return false;if (cockpits.some(url => hostname(url) === hostname(target))) return true;- // Reuse the actual validated cookie-domain authority, including legacy leading dots.- return sessionCookieDomain(new Request(target, { headers: { host: hostname(target) } })) !== undefined;+ return false;}diff --git a/lib/workflow/channel-binding.test.ts b/lib/workflow/channel-binding.test.tsnew file mode 100644index 00000000..e8ecf79c--- /dev/null+++ b/lib/workflow/channel-binding.test.ts@@ -0,0 +1,20 @@+import { beforeEach, expect, it, vi } from "vitest";+const mocks = vi.hoisted(() => ({ sources: vi.fn(), device: vi.fn() }));+vi.mock("./graph-store", () => ({ listWorkflowGraphTriggerSources: mocks.sources }));+vi.mock("@/lib/auth/device-store", () => ({ getApprovedDevice: mocks.device }));+import { reviewedChannelBinding, findActiveChannelSource } from "./graph-triggers";+const owner = "a".repeat(64), other = "b".repeat(64), revision = "c".repeat(64);+const source = (principal: string, hash: string) => ({ principal, owner: hash, graph: { id: "shared", revision, nodes: [{ id: "trigger", type: "channel_trigger", config: {} }] } });+beforeEach(() => { mocks.sources.mockReset(); mocks.device.mockImplementation(async id => ({ role: id === "owner-device" ? "owner" : "operator" })); });+it("selects only a reviewed Owner source when another principal's graph ID collides", async () => {+ const attacker = source("web:operator-device", other), reviewed = source("web:owner-device", owner);+ mocks.sources.mockResolvedValue([attacker, reviewed]);+ const binding = await reviewedChannelBinding("shared", "channel"); expect(binding).toEqual({ owner, nodeId: "trigger", revision });+ expect((await findActiveChannelSource("shared", "channel", binding))?.principal).toBe("web:owner-device");+ expect(await findActiveChannelSource("shared", "channel")).toBeNull();+ expect(await findActiveChannelSource("shared", "channel", { ...binding, revision: "d".repeat(64) })).toBeNull();+});+it("refuses ambiguous Owner bindings rather than choosing the first graph", async () => {+ mocks.sources.mockResolvedValue([source("web:owner-device", owner), source("web:owner-device", other)]);+ await expect(reviewedChannelBinding("shared", "channel")).rejects.toThrow(/unambiguous/);+});diff --git a/lib/workflow/graph-authority.test.ts b/lib/workflow/graph-authority.test.tsindex fa9e14e0..4d0064ea 100644--- a/lib/workflow/graph-authority.test.ts+++ b/lib/workflow/graph-authority.test.ts@@ -39,14 +39,14 @@ describe("live workflow execution authority", () => {expect(() => requireWorkflowScope(effective, "exec")).toThrow();});it("rechecks demotion and revocation without cached grants", async () => {- mocks.device.mockResolvedValueOnce({role: "owner"}).mockResolvedValueOnce({role: "operator"}).mockResolvedValueOnce(null);+ mocks.device.mockResolvedValueOnce({role: "owner"}).mockResolvedValueOnce({role: "owner"}).mockResolvedValueOnce({role: "operator"}).mockResolvedValueOnce({role: "operator"}).mockResolvedValueOnce(null);expect((await workflowExecutionContext(context)).scope).toBe("exec");expect((await workflowExecutionContext(context)).scope).toBe("write");await expect(workflowExecutionContext(context)).rejects.toThrow(/revoked/);});it("does not revive Viewer execution", async () => {mocks.device.mockResolvedValue({role: "viewer"});- await expect(workflowExecutionContext(context)).rejects.toThrow(/operator/);+ await expect(workflowExecutionContext(context)).rejects.toThrow(/revoked|operator/);});it("preserves caller and deployment ceilings", async () => {mocks.device.mockResolvedValue({role: "owner"});diff --git a/lib/workflow/graph-authority.ts b/lib/workflow/graph-authority.tsindex 39d01414..77ca04e3 100644--- a/lib/workflow/graph-authority.ts+++ b/lib/workflow/graph-authority.ts@@ -10,7 +10,6 @@ export async function workflowExecutionContext(context: CapabilityRunContext,trigger?: WorkflowGraphRun["trigger"],): Promise<CapabilityRunContext> {- context = await liveCapabilityContext(context);const principal = context.principal ?? context.actor;if (!principal) throw new Error("workflow requires an authenticated principal");const unattended = trigger && ["schedule", "webhook", "channel"].includes(trigger.type);@@ -35,7 +34,7 @@ export async function workflowExecutionContext(toolArgumentConstraints = { ...toolArgumentConstraints, apps_power: { ...toolArgumentConstraints?.apps_power, action: prior ? actions.filter((action) => prior.includes(action)) : actions } };}}- return { ...context, allowedTools, toolArgumentConstraints, scope: scopeRank(context.scope) < scopeRank(ceiling) ? context.scope : ceiling };+ return liveCapabilityContext({ ...context, allowedTools, toolArgumentConstraints, scope: scopeRank(context.scope) < scopeRank(ceiling) ? context.scope : ceiling });}export function requireWorkflowScope(context: CapabilityRunContext, required: Scope): void {diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.tsindex 9ec13689..4f1c6b12 100644--- a/lib/workflow/graph-runtime.ts+++ b/lib/workflow/graph-runtime.ts@@ -12,7 +12,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, organizationTargetDigest, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";+import { 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";@@ -175,7 +175,7 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graphif (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.` };+ 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, resolve), log: `Organization seat ${seat.title} routed to local agent.` };if (target.kind === "a2a") return { output: await callTool("a2a_handoff", { target: target.ref, objective: config.message, return_immediately: config.wait === false, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Organization seat ${seat.title} routed to A2A agent.` };throw new Error(`organization seat ${seat.title} has no execution target`);}diff --git a/lib/workflow/graph-triggers.ts b/lib/workflow/graph-triggers.tsindex 4a6f61f1..7feada54 100644--- a/lib/workflow/graph-triggers.ts+++ b/lib/workflow/graph-triggers.ts@@ -7,6 +7,7 @@ import { listWorkflowGraphTriggerSources } from "./graph-store";import { scheduleBucket } from "./schedule";import { startWorkflowGraph, workflowGraphRunId } from "./graph-engine";import { readWorkflowGraphRun } from "./graph-run-store";+import { getApprovedDevice } from "@/lib/auth/device-store";const g=globalThis as typeof globalThis&{__msoWorkflowScheduler?:ReturnType<typeof setInterval>;__msoWorkflowSchedulerBusy?:boolean};function key(parts:string[]){return `trigger:${createHash("sha256").update(parts.join(":" )).digest("hex").slice(0,48)}`;}@@ -21,4 +22,23 @@ export async function tickWorkflowScheduler(resolve:Resolver,now=new Date(),capaexport function startWorkflowScheduler(resolve:Resolver,capabilities?:CapabilityRuntime){if(process.env.NODE_ENV==="test"||g.__msoWorkflowScheduler)return;void tickWorkflowScheduler(resolve,new Date(),capabilities);g.__msoWorkflowScheduler=setInterval(()=>void tickWorkflowScheduler(resolve,new Date(),capabilities),15_000);g.__msoWorkflowScheduler.unref();}export async function findActiveWebhookSource(graphId:string,nodeId:string){for(const source of await listWorkflowGraphTriggerSources()){if(source.graph.id!==graphId)continue;const node=source.graph.nodes.find((row)=>row.id===nodeId&&row.type==="webhook"&&!row.disabled);if(node)return{...source,node};}return null;}-export async function findActiveChannelSource(graphId:string,channelId:string){for(const source of await listWorkflowGraphTriggerSources()){if(source.graph.id!==graphId)continue;const nodes=source.graph.nodes.filter((row)=>row.type==="channel_trigger"&&!row.disabled),node=nodes.find((row)=>row.config.channelId===channelId)??nodes.find((row)=>!row.config.channelId);if(node)return{...source,node};}return null;}+type ChannelBinding = { owner: string; nodeId: string; revision: string };+export async function reviewedChannelBinding(graphId: string, channelId: string): Promise<ChannelBinding> {+ const matches = [];+ for (const source of await listWorkflowGraphTriggerSources()) {+ if (source.graph.id !== graphId || !source.principal.startsWith("web:") || (await getApprovedDevice(source.principal.slice(4)))?.role !== "owner") continue;+ const nodes = source.graph.nodes.filter((node) => node.type === "channel_trigger" && !node.disabled && (!node.config.channelId || node.config.channelId === channelId));+ for (const node of nodes) matches.push({ owner: source.owner, nodeId: node.id, revision: source.graph.revision });+ }+ if (matches.length !== 1) throw new Error("Choose one unambiguous Owner channel trigger before saving");+ return matches[0];+}+export async function findActiveChannelSource(graphId: string, channelId: string, binding?: ChannelBinding) {+ if (!binding) return null;+ for (const source of await listWorkflowGraphTriggerSources()) {+ if (source.graph.id !== graphId || source.owner !== binding.owner || source.graph.revision !== binding.revision) continue;+ const node = source.graph.nodes.find((row) => row.id === binding.nodeId && row.type === "channel_trigger" && !row.disabled && (!row.config.channelId || row.config.channelId === channelId));+ if (node) return { ...source, node };+ }+ return null;+}diff --git a/lib/workflow/organization-agent-routing.test.ts b/lib/workflow/organization-agent-routing.test.tsindex 1c1154fc..506d1921 100644--- a/lib/workflow/organization-agent-routing.test.ts+++ b/lib/workflow/organization-agent-routing.test.ts@@ -65,7 +65,7 @@ describe("workflow organization seat routing", () => {const context = { principal: "web:aabbccddeeff00112233445566778899", actor: "web:aabbccddeeff00112233445566778899", sessionId: "session", scope: "exec" as const };const started = await engine.startWorkflowGraph(graph, {}, "org-local-once", context, (name) => name === tool.name ? tool : undefined);const done = await engine.workflowGraphRunStatus("web:aabbccddeeff00112233445566778899", started.id, 5000);- expect(done.state).toBe("completed"); expect(seenPrincipal).toBe("cli:aabbccddeeff00112233445566778899");+ expect(done.state).toBe("completed"); expect(seenPrincipal).toBe(context.principal);});});diff --git a/next.config.mjs b/next.config.mjsindex 4c632d3b..d7bef962 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -1,4 +1,5 @@import { execSync } from "node:child_process";+import { PROXY_BODY_LIMIT } from "./scripts/server-body-policy.mjs";// Build id baked into the client bundle so a redeploy can be detected.const BUILD_ID =@@ -83,11 +84,9 @@ const nextConfig = {}: {}),// proxy.ts clones request bodies; the default clone cap is 10MB, which- // silently truncated large /api/v1/fs/upload payloads. Raise it so big- // media uploads land intact (proxy* is the Next 16 name of the option).- // Kept just above the upload route's 200 MiB running cap (which streams to- // disk and returns 413 past it) so the route — not the proxy — owns rejection.- proxyClientMaxBodySize: "256mb",+ // The authenticated upload route bypasses cloning and streams its own 200 MiB cap.+ // Public middleware requests keep a small aggregate buffer ceiling.+ proxyClientMaxBodySize: PROXY_BODY_LIMIT,// Tree-shake heavy icon/radix barrels — keeps the OS shell bundle lean.optimizePackageImports: ["lucide-react",diff --git a/proxy-websocket.test.ts b/proxy-websocket.test.tsindex e46dfe93..ccab4339 100644--- a/proxy-websocket.test.ts+++ b/proxy-websocket.test.ts@@ -1,7 +1,8 @@// 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";+import { createManagedAppCookie } from "./lib/managed-apps/session";+vi.hoisted(() => { process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com"; });const approved = vi.hoisted(() => ({ value: true, role: "owner" as "viewer" | "operator" | "owner" }));vi.mock("@/lib/auth/device-store", () => ({@@ -40,12 +41,12 @@ describe("WebSocket upgrade on an app host", () => {/** A real signed cookie — the branch verifies the HMAC, so a placeholder won't do. */function session(cookieScope = "host"): string {const now = Date.now();- return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1", cookie_scope: cookieScope, cookie_epoch: "epoch-0000000000000000" }, SECRET);+ return createManagedAppCookie("openclaw", { issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1", cookie_scope: cookieScope, cookie_epoch: "epoch-0000000000000000" }, SECRET);}function upgradeReq(host: string, path = "/", cookie?: string) {const headers: Record<string, string> = { upgrade: "websocket", connection: "Upgrade" };- if (cookie) headers.cookie = `session=${cookie}`;+ if (cookie) headers.cookie = `__Host-mso-managed-app=${cookie}`;return req(host, path, headers);}@@ -118,9 +119,9 @@ describe("WebSocket upgrade on an app host", () => {describe("per-app upgrade adapters", () => {const SECRET = "y".repeat(48);- function signed(): string {+ function signed(host: string): string {const now = Date.now();- return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1", cookie_scope: "host", cookie_epoch: "epoch-0000000000000000" }, SECRET);+ return createManagedAppCookie(host.startsWith("hermes.") ? "hermes" : "openclaw", { issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1", cookie_scope: "host", cookie_epoch: "epoch-0000000000000000" }, SECRET);}async function upstream(host: string, path: string, extra: Record<string, string> = {}) {@@ -131,7 +132,7 @@ describe("per-app upgrade adapters", () => {const proxy = await loadProxy(TEMPLATE);const res = await proxy(req(host, path, {upgrade: "websocket", connection: "Upgrade",- cookie: `session=${signed()}`, origin: `https://${host}`,+ cookie: `__Host-mso-managed-app=${signed(host)}`, origin: `https://${host}`,"x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https",...extra,}));diff --git a/proxy.test.ts b/proxy.test.tsindex b6c602d1..ca54d1b2 100644--- a/proxy.test.ts+++ b/proxy.test.ts@@ -9,6 +9,7 @@// request headers handed to the route.import { afterEach, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";+vi.mock("@/lib/managed-apps/session", () => ({ gateManagedApp: vi.fn(async () => null) }));const TEMPLATE = "{id}.mso.example.com";const HERMES = "/api/v1/managed-apps/hermes/proxy";diff --git a/proxy.ts b/proxy.tsindex 8d497b38..71b28774 100644--- a/proxy.ts+++ b/proxy.ts@@ -34,6 +34,7 @@ import {gateCamoufoxViewer,} from "@/lib/camoufox/viewer-gate";import { applyPrivatePageCachePolicy } from "@/lib/auth/page-cache";+import { gateManagedApp } from "@/lib/managed-apps/session";const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);@@ -140,6 +141,9 @@ function contentSecurityPolicy(nonce: string): string {export async function proxy(request: NextRequest) {const { pathname } = request.nextUrl;+ const contentLength = request.headers.get("content-length");+ if (contentLength && Number(contentLength) > 1024 * 1024)+ return NextResponse.json({ error: "request_too_large" }, { status: 413 });// Which app host this is, if any. The HOST header is authoritative and// x-forwarded-host is deliberately NOT consulted here: Traefik routes on Host@@ -228,6 +232,8 @@ export async function proxy(request: NextRequest) {// 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 gate = await gateManagedApp(request, managedApp);+ if (gate) return gate;const headers = new Headers(request.headers);// set(), not append(): this overwrites whatever copy the client sent.@@ -330,5 +336,5 @@ export async function proxy(request: NextRequest) {// a path middleware never sees — a Traefik-level block is not available. The// cockpit short-circuits those in MATCHER_EXCLUDED above.export const config = {- matcher: ["/(.*)"],+ matcher: ["/((?!api/v1/fs/upload$).*)"],};diff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjsindex 7dd48a59..4afd4cb0 100644--- a/scripts/e2e/release-fixture.mjs+++ b/scripts/e2e/release-fixture.mjs@@ -96,6 +96,6 @@ export async function releaseFixture({ live = false, surfaceApps = [] } = {}) {const setAiConfig = async config => {await writeFile(env.OS_CONFIG_STORE, JSON.stringify(config, null, 2), { mode: 0o600 });};- return { dir, base, device, password, vaultProject: fixtureProject, setRole, seedMcp, mcpToken, setAiConfig, seedSessions: () => seedSessionMonitor(env), revokeProvider: () => { providerStatus = 401; }, close };+ return { dir, base, device, password, pid: server.pid, vaultProject: fixtureProject, setRole, seedMcp, mcpToken, setAiConfig, seedSessions: () => seedSessionMonitor(env), revokeProvider: () => { providerStatus = 401; }, close };} catch (error) { await close(); throw error; }}diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjsindex 4d667a20..80511771 100644--- a/scripts/e2e/release.mjs+++ b/scripts/e2e/release.mjs@@ -16,6 +16,7 @@ import { aiProviderSwitchJourney } from "./ai-provider-switch.mjs";import { shellNoticesJourney } from "./shell-notices.mjs";execFileSync(process.execPath, ["scripts/e2e/socket-authority.mjs"], { stdio: "inherit", timeout: 30000 });+execFileSync(process.execPath, ["scripts/e2e/request-bodies.mjs"], { stdio: "inherit", timeout: 60000 });execFileSync(process.execPath, ["scripts/e2e/shell-apps.mjs"], { stdio: "inherit" });execFileSync(process.execPath, ["scripts/e2e/mcp-page.mjs"], { stdio: "inherit" });execFileSync(process.execPath, ["scripts/e2e/workflow-embeds.mjs"], { stdio: "inherit" });diff --git a/scripts/e2e/request-bodies.mjs b/scripts/e2e/request-bodies.mjsnew file mode 100644index 00000000..31f9df2e--- /dev/null+++ b/scripts/e2e/request-bodies.mjs@@ -0,0 +1,40 @@+import assert from "node:assert/strict";+import { readFile, stat } from "node:fs/promises";+import { Readable } from "node:stream";+import { releaseFixture } from "./release-fixture.mjs";++const fixture = await releaseFixture();+const rss = async () => Number(/VmRSS:\s+(\d+)/.exec(await readFile(`/proc/${fixture.pid}/status`, "utf8"))[1]) * 1024;+try {+ const baseline = await rss(); let peak = baseline;+ const sample = setInterval(() => { void rss().then(value => { peak = Math.max(peak, value); }).catch(() => {}); }, 20);+ try {+ const oversized = await fetch(fixture.base + "/api/auth/login", { method: "POST", body: Buffer.alloc(2 * 1024 * 1024) });+ assert.equal(oversized.status, 413);+ const login = await fetch(fixture.base + "/api/auth/login", { method: "POST", headers: { "content-type": "application/json", origin: fixture.base }, body: JSON.stringify({ password: fixture.password, deviceId: fixture.device }) });+ assert.equal(login.status, 200); const cookie = login.headers.get("set-cookie").split(";")[0];+ const concurrent = await Promise.all(Array.from({ length: 8 }, () => fetch(fixture.base + "/api/auth/login", { method: "POST", headers: { origin: fixture.base }, body: Buffer.alloc(900 * 1024) })));+ assert.ok(concurrent.every(result => [413, 429].includes(result.status)) && concurrent.some(result => result.status === 413));+ const boundary = "mso-synthetic-stream";+ const dest = `--${boundary}\r\nContent-Disposition: form-data; name="dest"\r\n\r\n${fixture.dir}\r\n`;+ const head = name => `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\nContent-Type: application/octet-stream\r\n\r\n`;+ const end = `\r\n--${boundary}--\r\n`;+ const overhead = Buffer.byteLength(dest + head("a.bin") + "\r\n" + head("b.bin") + end);+ const sizes = [100 * 1024 * 1024 - overhead, 100 * 1024 * 1024];+ const chunk = Buffer.alloc(64 * 1024);+ async function* body() {+ yield Buffer.from(dest);+ for (const [index, size] of sizes.entries()) {+ yield Buffer.from(head(index ? "b.bin" : "a.bin"));+ for (let written = 0; written < size; written += chunk.length) yield chunk.subarray(0, Math.min(chunk.length, size - written));+ if (!index) yield Buffer.from("\r\n");+ }+ yield Buffer.from(end);+ }+ const upload = await fetch(fixture.base + "/api/v1/fs/upload", { method: "POST", headers: { cookie, origin: fixture.base, "content-type": `multipart/form-data; boundary=${boundary}`, "content-length": String(200 * 1024 * 1024) }, body: Readable.from(body()), duplex: "half" });+ assert.equal(upload.status, 200); assert.deepEqual(await upload.json(), { written: 2, failed: [] });+ assert.equal((await stat(fixture.dir + "/a.bin")).size, sizes[0]); assert.equal((await stat(fixture.dir + "/b.bin")).size, sizes[1]);+ assert.ok(peak - baseline < 128 * 1024 * 1024, `streaming memory grew ${peak - baseline} bytes`);+ console.log("PASS production request bounds: oversized public body, eight near-limit requests, exact 200 MiB authenticated streaming upload, bounded RSS");+ } finally { clearInterval(sample); }+} finally { await fixture.close(); }diff --git a/scripts/e2e/socket-authority.mjs b/scripts/e2e/socket-authority.mjsindex b606239d..3dc801ad 100644--- a/scripts/e2e/socket-authority.mjs+++ b/scripts/e2e/socket-authority.mjs@@ -23,12 +23,20 @@ try {const response = await fetch(fixture.base + "/api/auth/login", { method: "POST", headers: { "content-type": "application/json", origin: fixture.base }, body: JSON.stringify({ password: fixture.password, deviceId: fixture.device }) });assert.equal(response.status, 200);const cookie = response.headers.get("set-cookie").split(";")[0];+ const ticketResponse = await fetch(fixture.base + "/api/v1/managed-apps/hermes/session", { headers: { cookie } });+ assert.equal(ticketResponse.status, 200);+ const authorization = await ticketResponse.json();+ const exchange = await fetch(fixture.base + "/__mso_app_auth", { method: "POST", headers: { host: new URL(authorization.origin).host, origin: authorization.origin, authorization: "Bearer " + authorization.ticket } });+ assert.equal(exchange.status, 204);+ const appCookie = exchange.headers.get("set-cookie").split(";")[0];+ assert.match(appCookie, /^__Host-mso-managed-app=/);+ assert.equal((await fetch(fixture.base + "/api/v1/exec/run", { method: "POST", headers: { cookie: appCookie, origin: fixture.base, "content-type": "application/json" }, body: JSON.stringify({ command: "true" }) })).status, 401);assert.equal((await fetch(fixture.base + "/api/internal/socket-policy", { method: "POST" })).status, 404);async function open() {const client = connect(Number(new URL(fixture.base).port), "127.0.0.1"); sockets.add(client);client.on("error", () => {});const first = Promise.race([once(client, "data").then(([data]) => data.toString()), once(client, "close").then(() => "")]);- client.write(`GET /socket HTTP/1.1\r\nHost: hermes.mso.example.com\r\nOrigin: http://hermes.mso.example.com\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nCookie: ${cookie}\r\nAuthorization: must-not-forward\r\n\r\n`);+ client.write(`GET /socket HTTP/1.1\r\nHost: hermes.mso.example.com\r\nOrigin: http://hermes.mso.example.com\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nCookie: ${appCookie}\r\nAuthorization: must-not-forward\r\n\r\n`);return { client, handshake: await first };}const { client, handshake } = await open(); assert.match(handshake, /101 Switching Protocols/);diff --git a/scripts/managed-app-loopback.test.ts b/scripts/managed-app-loopback.test.tsindex 2b3a33cf..91cf2b26 100644--- a/scripts/managed-app-loopback.test.ts+++ b/scripts/managed-app-loopback.test.ts@@ -1,5 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";+vi.mock("@/lib/managed-apps/session", () => ({ gateManagedApp: vi.fn(async () => null) }));const TEMPLATE = "{id}.mso.example.com";const HERMES = "/api/v1/managed-apps/hermes/proxy";diff --git a/scripts/proxy-session-policy.test.ts b/scripts/proxy-session-policy.test.tsindex b91ec5f6..d49b4caa 100644--- a/scripts/proxy-session-policy.test.ts+++ b/scripts/proxy-session-policy.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";-import { signSession } from "../lib/auth/session";+import { createManagedAppCookie } from "../lib/managed-apps/session";+vi.hoisted(() => { process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com"; });const SECRET = "e".repeat(48);const EPOCH = "epoch-0000000000000000";@@ -19,12 +20,12 @@ async function loadProxy() {function upgrade(cookieEpoch: string) {const now = Date.now();- const token = signSession({+ const token = createManagedAppCookie("openclaw", {issued_at: now, expires_at: now + 60_000, device_id: "dev-1",cookie_scope: "host", cookie_epoch: cookieEpoch,}, SECRET);return new NextRequest("https://openclaw.mso.example.com/chat", {- headers: { host: "openclaw.mso.example.com", upgrade: "websocket", connection: "Upgrade", cookie: `session=${token}` },+ headers: { host: "openclaw.mso.example.com", upgrade: "websocket", connection: "Upgrade", cookie: `__Host-mso-managed-app=${token}` },});}diff --git a/scripts/server-body-policy.mjs b/scripts/server-body-policy.mjsnew file mode 100644index 00000000..a7be3e57--- /dev/null+++ b/scripts/server-body-policy.mjs@@ -0,0 +1,5 @@+export const PROXY_BODY_LIMIT = 1024 * 1024;+export function requestBodyLimit(url) {+ try { return new URL(url, "http://localhost").pathname === "/api/v1/fs/upload" ? 200 * 1024 * 1024 : PROXY_BODY_LIMIT; }+ catch { return PROXY_BODY_LIMIT; }+}diff --git a/scripts/server.mjs b/scripts/server.mjsindex 19c460cc..55d07a30 100644--- a/scripts/server.mjs+++ b/scripts/server.mjs@@ -2,6 +2,7 @@ import next from "next";import { createServer, request as httpRequest } from "node:http";import { randomBytes } from "node:crypto";import { attachSocketProxy } from "./server-sockets.mjs";+import { requestBodyLimit } from "./server-body-policy.mjs";const args = process.argv.slice(2);const argument = (name, fallback) => args.includes(name) ? args[args.indexOf(name) + 1] : fallback;@@ -15,14 +16,28 @@ 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}`;+let activeBodies = 0;// Next owns HTTP on a private socket; only our public server receives upgrades.const server = createServer((incoming, outgoing) => {+ const limit = requestBodyLimit(incoming.url);+ const hasBody = Number(incoming.headers["content-length"] ?? 0) > 0 || incoming.headers["transfer-encoding"];+ const reject = (status) => { outgoing.once("finish", () => incoming.destroy()); outgoing.writeHead(status, { connection: "close" }); outgoing.end(); };+ if (Number(incoming.headers["content-length"] ?? 0) > limit) return reject(413);+ if (hasBody && activeBodies >= 32) return reject(429);+ if (hasBody) { activeBodies++; outgoing.once("close", () => { activeBodies--; }); }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());+ let size = 0;+ incoming.on("data", chunk => {+ size += chunk.length;+ if (size <= limit) return;+ incoming.unpipe(hop); hop.destroy();+ if (!outgoing.headersSent) reject(413); else outgoing.destroy();+ });incoming.pipe(hop);});const closeSockets = attachSocketProxy(server, async (request) => {