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 credential sinks and revoke pending sessions
Abdurrahman Fakhrul6f777da7f448
diff --git a/app/api/integrations/google/start/route.ts b/app/api/integrations/google/start/route.tsindex d5ba0bd5..1977caa2 100644--- a/app/api/integrations/google/start/route.ts+++ b/app/api/integrations/google/start/route.ts@@ -18,7 +18,7 @@ export async function POST(req: NextRequest) {if (Object.keys(body).some(k => !["user", "provider", "connection"].includes(k)) || !isGoogleProvider(String(body.provider))) throw new IntegrationError("invalid_google_request");const user = identity(body.user, "user"), connection = identity(body.connection, "connection"), provider = String(body.provider);if (!isGoogleProvider(provider)) throw new IntegrationError("invalid_google_request");- const flow = await beginGoogleAuthorization(provider, { user, connection }, { deviceId: ctx.session.device_id, cookieScope: ctx.session.cookie_scope, cookieEpoch: ctx.session.cookie_epoch, sessionExpiresAt: ctx.session.expires_at });+ const flow = await beginGoogleAuthorization(provider, { user, connection }, { deviceId: ctx.session.device_id, cookieScope: ctx.session.cookie_scope, cookieEpoch: ctx.session.cookie_epoch, sessionIssuedAt: ctx.session.issued_at, sessionExpiresAt: ctx.session.expires_at });const response = NextResponse.json({ authorizationUrl: flow.authorizationUrl, expiresIn: flow.expiresIn }, { headers });response.cookies.set(flow.cookieName, flow.binding, { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: flow.expiresIn });void audit({ action: "infra.write", actor: ctx.session.device_id, target: `${user}/${provider}/${connection}`, ok: true, detail: "google.authorization.start" });diff --git a/app/api/v1/camoufox/session/route.ts b/app/api/v1/camoufox/session/route.tsindex f4d4d3e3..55aa67e4 100644--- a/app/api/v1/camoufox/session/route.ts+++ b/app/api/v1/camoufox/session/route.ts@@ -40,7 +40,7 @@ export async function GET() {if (!viewerOrigin || secret.length < 32) {return NextResponse.json({ error: "viewer_unconfigured" }, { status: 503 });}- const viewerTicket = createCamoufoxViewerTicket(context.session.device_id, secret, Date.now(), context.session.issued_at);+ const viewerTicket = createCamoufoxViewerTicket(context.session, secret);const password = (await fs.readFile(/* turbopackIgnore: true */ PASSWD_FILE, "utf8").catch(() => "")).trim();// Absent file = the operator has not set one. Say so plainly rather than 500 — thediff --git a/app/api/v1/sys/update/route.test.ts b/app/api/v1/sys/update/route.test.tsindex 496f3bd1..c9dce881 100644--- a/app/api/v1/sys/update/route.test.ts+++ b/app/api/v1/sys/update/route.test.ts@@ -23,6 +23,8 @@ vi.mock("@/lib/host/self-update", () => ({}));const auditMock = vi.fn();+const limited = vi.hoisted(() => ({ value: false }));+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: () => limited.value }));vi.mock("@/lib/host/audit-api", () => ({audit: (...args: unknown[]) => auditMock(...args),}));@@ -57,6 +59,8 @@ const post = (body: unknown) =>beforeEach(() => {authed.current = true;+ limited.value = false;+ vi.stubEnv("OS_PUBLIC_ORIGIN", "http://localhost");getStatus.mockReset().mockResolvedValue(status());startUpdate.mockReset().mockResolvedValue(status({ running: true }));auditMock.mockReset();@@ -72,14 +76,29 @@ describe("/api/v1/sys/update", () => {expect(startUpdate).not.toHaveBeenCalled();});- it("asks the remote by default, and skips it for the poller", async () => {+ it("never fetches the remote on GET, even with a legacy check flag", async () => {await GET(get());- expect(getStatus).toHaveBeenLastCalledWith(true);+ expect(getStatus).toHaveBeenLastCalledWith(false);+ await GET(get("http://localhost/api/v1/sys/update?check=1"));+ expect(getStatus).toHaveBeenLastCalledWith(false);// `?check=0` is what the panel polls with WHILE an update runs — a git fetch// every 3s during a build is pure noise.await GET(get("http://localhost/api/v1/sys/update?check=0"));expect(getStatus).toHaveBeenLastCalledWith(false);});+ it("requires an explicit same-origin POST and limits remote refreshes", async () => {+ for (const origin of [null, "http://evil.test"]) {+ const req = post({ action: "check" }); if (origin) req.headers.set("origin", origin);+ expect((await POST(req)).status).toBe(403);+ }+ expect(getStatus).not.toHaveBeenCalled(); expect(startUpdate).not.toHaveBeenCalled();+ const request = () => { const req = post({ action: "check" }); req.headers.set("origin", "http://localhost"); return req; };+ expect((await POST(request())).status).toBe(200);+ expect(getStatus).toHaveBeenCalledWith(true); expect(startUpdate).not.toHaveBeenCalled();+ expect(auditMock).toHaveBeenCalledWith(expect.objectContaining({ action: "sys.update", target: "check", ok: true }));+ getStatus.mockClear(); limited.value = true;+ expect((await POST(request())).status).toBe(429); expect(getStatus).not.toHaveBeenCalled();+ });it("passes rebuildOnly through only when it is exactly true", async () => {await POST(post({ rebuildOnly: true }));diff --git a/app/api/v1/sys/update/route.ts b/app/api/v1/sys/update/route.tsindex 577eb0c5..4c8c86ea 100644--- a/app/api/v1/sys/update/route.ts+++ b/app/api/v1/sys/update/route.ts@@ -2,21 +2,19 @@ import { NextResponse } from "next/server";import { verifyAuth } from "@/lib/agent/server";import { apiError, readJson } from "@/lib/host/request-api";import { audit } from "@/lib/host/audit-api";+import { rateLimited } from "@/lib/host/limits-api";import { getUpdateStatus, startUpdate } from "@/lib/host/self-update";export const dynamic = "force-dynamic";-// The GET runs `git fetch`, and the POST hands off to systemd-run. Neither is a-// static thing and both need the host, so this is Node, never the edge.+// Status reads and explicit update actions require the host runtime.export const runtime = "nodejs";// GET /sys/update → what version is running, what is on origin/main, and the log of-// the last run. `?check=0` skips the network round trip, which is what the panel-// polls with while an update is in flight.+// the last run. Reads never fetch or modify the repository.export async function GET(req: Request) {if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });try {- const check = new URL(req.url).searchParams.get("check") !== "0";- return NextResponse.json(await getUpdateStatus(check));+ return NextResponse.json(await getUpdateStatus(false));} catch (e) {return apiError("sys/update", e);}@@ -29,7 +27,15 @@ export async function GET(req: Request) {export async function POST(req: Request) {if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });try {- const body = (await readJson(req).catch(() => ({}))) as { rebuildOnly?: unknown };+ const body = (await readJson(req).catch(() => ({}))) as { rebuildOnly?: unknown; action?: unknown };+ if (body.action === "check") {+ const origin = new URL(process.env.OS_PUBLIC_ORIGIN || req.url).origin;+ if (req.headers.get("origin") !== origin) return NextResponse.json({ error: "same_origin_required" }, { status: 403 });+ if (rateLimited("sys-update-check", 6, 60_000)) return NextResponse.json({ error: "rate_limited" }, { status: 429 });+ const status = await getUpdateStatus(true);+ audit({ action: "sys.update", target: "check", ok: true });+ return NextResponse.json(status);+ }const rebuildOnly = body.rebuildOnly === true;const status = await startUpdate(rebuildOnly);audit({diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.tsindex 8c7824c7..ce078cee 100644--- a/app/mcp/route.test.ts+++ b/app/mcp/route.test.ts@@ -72,7 +72,7 @@ describe("/mcp request boundary", () => {mocks.validateToken.mockReset();mocks.touchToken.mockClear();mocks.getClient.mockReset().mockResolvedValue(null);- mocks.dispatch.mockClear();+ mocks.dispatch.mockReset().mockResolvedValue({ jsonrpc: "2.0", id: 1, result: {} });mocks.clampScope.mockClear();mocks.rateLimited.mockClear().mockReturnValue(false);mocks.rateLimitedUntrusted.mockClear().mockReturnValue(false);@@ -81,6 +81,14 @@ describe("/mcp request boundary", () => {mocks.findOrCreateAgentSessionForConversation.mockReset().mockResolvedValue({ id: "20260901_100000_aabbccdd", source: "mcp" });});afterEach(() => vi.unstubAllEnvs());+ it.each(["local_agent_inbox", "local_agent_request_wait"])("rechecks bearer authorization before returning %s output", async name => {+ const token = { hash: "d".repeat(64), scope: "read" as const, clientId: "client-wait", label: "Wait" };+ mocks.validateToken.mockResolvedValueOnce(token).mockResolvedValueOnce(token).mockResolvedValueOnce(null);+ mocks.dispatch.mockResolvedValueOnce({ jsonrpc: "2.0", id: 1, result: { private: "PRIVATE_LATE_RESULT" } } as never);+ const { POST } = await import("./route");+ const result = await POST(request(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name } })));+ expect(result.status).toBe(401); expect(await result.text()).not.toContain("PRIVATE_LATE_RESULT");+ });@@ -165,6 +173,8 @@ describe("/mcp request boundary", () => {expect(hash).not.toContain(rawConversation);expect(mocks.dispatch).toHaveBeenCalledWith(body, "read", `mcp:${token.hash.slice(0, 16)}`, {principal: `mcp-client:${token.clientId}`,+ liveAuthorization: expect.any(Function),+ signal: expect.any(AbortSignal),authorizationGrant: expect.objectContaining({ kind: "mcp", id: token.hash, fingerprint: expect.stringMatching(/^[a-f0-9]{64}$/) }),sessionId: "20260901_100000_aabbccdd",toolProfile: "chatgpt",diff --git a/app/mcp/route.ts b/app/mcp/route.tsindex 282ffc65..b82be19a 100644--- a/app/mcp/route.ts+++ b/app/mcp/route.ts@@ -1,4 +1,5 @@import { mcpAuthorizationGrant } from "@/lib/mcp/durable-grant";+import { registerMcpTokenWait } from "@/lib/mcp/token-waits";import { TENANT_MEMORY_TOOLS } from "@/lib/tenancy/memory-tools";import { tenantPreviewEnabled } from "@/lib/tenancy/mode";import { resolveMcpTenant, tenantRuntimeConfigurationPresent } from "@/lib/tenancy/runtime";@@ -108,8 +109,16 @@ export async function POST(req: Request) {void touchToken(token.hash).catch(() => {});const actor = `mcp:${token.hash.slice(0, 16)}`;+ const grant=mcpAuthorizationGrant(token,expectedResource);+ const liveAuthorization=async () => {+ req.signal.throwIfAborted();+ const current=await validateToken(bearer);+ if (!current || mcpAuthorizationGrant(current,expectedResource).fingerprint !== grant.fingerprint) throw new Error("MCP authorization revoked, expired or changed");+ };const agentContext = {- authorizationGrant: mcpAuthorizationGrant(token, expectedResource),+ authorizationGrant: grant,+ liveAuthorization,+ signal:req.signal,principal,...(resolved.agentSessionId ? { sessionId: resolved.agentSessionId } : {}),toolProfile,@@ -121,8 +130,14 @@ export async function POST(req: Request) {// persisted control-plane state and schedules eligible work; it never keeps// the current MCP request open for model execution.await ensureLocalAgentStandbyRuntime(msoCapabilityRuntime).catch(() => undefined);- const result = await dispatch(rpc, effectiveScope, actor, agentContext);- return Response.json(wire.modern ? modernMcpResult(result, MCP_SERVER_VERSION, rpc.method) : result, { status: wire.modern && (result.error as { code?: number } | undefined)?.code === -32601 ? 404 : 200, headers });+ const isWait=rpc.method==="tools/call" && ["local_agent_inbox","local_agent_request_wait"].includes(rpc.params?.name ?? "");+ const wait=isWait ? registerMcpTokenWait(token.hash,req.signal) : undefined;+ try {+ if (isWait && !await liveAuthorization().then(()=>true,()=>false)) return unauthorized("invalid, revoked or expired MCP token");+ const result = await dispatch(rpc, effectiveScope, actor, {...agentContext,signal:wait?.signal ?? req.signal});+ if (isWait && !await liveAuthorization().then(()=>true,()=>false)) return unauthorized("invalid, revoked or expired MCP token");+ return Response.json(wire.modern ? modernMcpResult(result, MCP_SERVER_VERSION, rpc.method) : result, { status: wire.modern && (result.error as { code?: number } | undefined)?.code === -32601 ? 404 : 200, headers });+ } finally {wait?.release();}}export async function GET(req: Request) {diff --git a/claude-skills/provider-automation/SKILL.md b/claude-skills/provider-automation/SKILL.mdindex 29df3cd5..6cfd074c 100644--- a/claude-skills/provider-automation/SKILL.md+++ b/claude-skills/provider-automation/SKILL.md@@ -15,7 +15,7 @@ Use for repeated provider API operations, project MCP chains, and declared proje## Fast route-1. Call `agent_session_open` once with a stable conversation key, unless this conversation already has a session. Carry returned `mso/sessionId` in request metadata.+1. With write/exec scope, call `agent_session_open` once with a stable conversation key, unless this conversation already has a session. Carry returned `mso/sessionId` in request metadata. Read tokens use the automatically conversation-bound session and `agent_session_current`; they cannot create, rename, relocate or acknowledge a session's messages.2. Call `flow_catalog` with the exact project. Inspect the selected flow to get its input schema, ordered steps and scope.3. Reuse an existing flow. For a new repeated pattern, inspect the provider operation or paged `project_mcp_tools` schema first; save a versioned definition with `flow_manage` and the catalog revision.4. Call `flow_run` with project, flow, nonsecret input and a unique logical operation key.diff --git a/docs/A2A.md b/docs/A2A.mdindex 4f24d9ef..3d75f4ac 100644--- a/docs/A2A.md+++ b/docs/A2A.md@@ -4,6 +4,8 @@ MSO implements **A2A v1** beside MCP. MCP remains the host tool/data control plaThe implementation has four independent pieces:+Inbound task streams close at terminal state, credential revocation, client disconnect or a five-minute deadline. Admission is bounded to eight streams per profile and sixty-four per process; queued events are bounded too. Resubscribe with valid credentials for a still-running task after the deadline. Revocation closes existing streams as well as refusing new requests.+1. **Outbound discovery/registry** — discover public HTTPS Agent Cards and keep sanitized peer metadata locally.2. **Outbound credentials + client** — attach a private API-key, Bearer, or OAuth2 access-token profile to a peer and call it over JSON-RPC or HTTP+JSON.3. **Streaming** — use A2A v1 `SendStreamingMessage` / SSE and keep task lifetime independent from an individual stream connection.diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 83bd54d9..2ff25575 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Fixed**+- `security` close credential sinks and revoke pending sessions- `mcp` preserve managed configuration behind credential guards- `security` bind receipts to authority and pin browser artifacts- `security` keep connected app bootstrap code staticdiff --git a/docs/INTEGRATIONS-NATIVE-GOOGLE.md b/docs/INTEGRATIONS-NATIVE-GOOGLE.mdindex f106474e..57142bd3 100644--- a/docs/INTEGRATIONS-NATIVE-GOOGLE.md+++ b/docs/INTEGRATIONS-NATIVE-GOOGLE.md@@ -4,6 +4,8 @@ MSO owns the provider connection, consent lifecycle and bounded API dispatch. Co## One identity model+Pending consent retains the initiating session's issue time and expiry. The callback checks the current device approval, role, cookie epoch and logout boundary before exchanging the code and again before saving tokens. Logout or reapproval invalidates unfinished consent; restart authorization from the current session. Older pending records without an issue time fail closed.+Credential owner → provider → named connection → source/authentication stays the existing MSO Integrations model. App configuration and a user's authorization are different records:- `google-oauth-app` / direct / `oauth-app`: the installation's Google Web application client ID and secret, entered only through the existing private setup form. Saving validates configuration format, not account access.diff --git a/docs/MCP.md b/docs/MCP.mdindex 57c0e5ed..4b0fa5e0 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -26,6 +26,10 @@ demo mode also forces MCP off. Existing installs keep their current `.env.local`## Settings navigation+`agent_session_open` requires write scope because it can create, rename and relocate a durable session. Read tokens use their automatically conversation-bound session and `agent_session_current`. `local_agent_inbox` never acknowledges messages; its legacy `acknowledge:true` argument is rejected. Use write-scoped `local_agent_inbox_acknowledge` with exact message IDs. These mailbox/session operations are MCP-only conversation capabilities, not host file APIs. Refresh cached client actions after a toolset signature change; existing tokens retain their original scope.++Foreground inbox/reply waits recheck the live bearer before reading and returning private data, and close on revocation, expiry or disconnect. Candidate previews apply the same credential-path policy as file reads, including cached/seeded entries. Project diffs keep per-file statistics but omit credential patches (including protected renames) and scrub recognizable secret values in ordinary source.+Settings → MCP separates **Access MSO** (external clients → MSO), **MSO Access** (host connections plus exact-project plugin installation), and **Sessions** (activity and handover). Under MSO Access, **Project plugins** lists SI-Coder and Batonly as available catalog entries. They are not installed into a fresh project, are never inherited from a parent/sibling project, and require an explicit project-scoped install. Registry declarations alone do not install code or configure credentials.Credential-dependent work follows one rule: **inspect MSO Integrations first**. Resolve the exact project/context → credential owner → provider → named connection before asking for setup. Reuse an existing explicit connection when it matches; refuse ambiguity instead of guessing. Secret values enter only private Integrations setup/export surfaces, never ordinary chat or MCP tool arguments.diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 508dde48..64d41247 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,13 @@+## 2026-10-10: Close the eight findings from the 1acc1424 cloud scan++Candidate indexes use canonical credential guards during walking, seeding, cache reuse and preview reads; version 2 invalidates older caches. Git diffs use NUL-delimited filename metadata and literal pathspecs, omit protected patches/renames and redact recognizable credentials while retaining file statistics and ordinary source.++A2A SSE closes on terminal task state, profile revocation, disconnect and a five-minute deadline, with eight streams per profile, sixty-four globally and bounded queued events. Application and Camoufox child cookies retain the original session issue time and expiry independently of their short-lived tickets; HTTP and continuous WebSocket authority share those boundaries.++Durable session opening now requires write scope. Inbox reads reject acknowledgement; the dedicated write-scoped acknowledgement tool preserves normal receiver behavior. MCP waits carry request cancellation, recheck live token authority and discard results after revocation. Token administration cancels registered waits after durable revocation. The changed toolset signature requires downstream client action refresh; no existing token gains privileges.++Update status GET is cache-only; explicit remote checking uses a same-origin, rate-limited, audited POST. Google consent binds issue time and verifies durable logout both before exchange and inside token persistence. Regression tests cover both HTTP/MCP credential sinks, protected Git renames, terminal/revoked/cancelled streams, child expiry, read/write separation, late private results and logout during consent. Independent verification of the released commit remains required.+## 2026-10-10: Close the five findings from the 34b69798 cloud scanRead roots default to the checkout and projects, not the whole home. Shared filesystem guards refuse additional Terraform, PyPI, Poetry, doctl, Azure and browser credential stores, plus raw project MCP/registry credentials. The dedicated project MCP inventory remains redacted. File Manager's initial listing selects an allowed root and canonicalizes its history; the sidebar no longer advertises disallowed Home paths. Explicit Owner root overrides remain available and subject to credential guards.diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.mdindex 74d6af7f..5300e0f3 100644--- a/docs/generated/MCP-CATALOG.md+++ b/docs/generated/MCP-CATALOG.md@@ -4,21 +4,21 @@## Full MSO catalog-<!-- mcp-toolset: server=1.16.0 version=2026.10.09.1 tools=117 read=59 write=35 exec=23 -->+<!-- mcp-toolset: server=1.17.0 version=2026.10.10.1 tools=118 read=58 write=37 exec=23 -->| Fact | Current source value ||---|---:|-| MCP server | `1.16.0` |-| Toolset | `2026.10.09.1` |-| Toolset changed at | `2026-10-09T14:00:00+00:00` |-| Transport tools | **119** |-| Model/operator tools | **117** |-| Read | **59** |-| Write | **35** |+| MCP server | `1.17.0` |+| Toolset | `2026.10.10.1` |+| Toolset changed at | `2026-10-10T07:40:00+00:00` |+| Transport tools | **120** |+| Model/operator tools | **118** |+| Read | **58** |+| Write | **37** || Exec | **23** || App-only bridges | **2** |-### Read (59)+### Read (58)- `a2a_agent_discover`- `a2a_agents_list`@@ -28,7 +28,6 @@- `agent_session_action_resolve`- `agent_session_current`- `agent_session_flow`-- `agent_session_open`- `agent_session_resume`- `agent_sessions_list`- `apps_list`@@ -80,13 +79,14 @@- `tool_forge_candidates`- `vps_status`-### Write (35)+### Write (37)- `a2a_agent_register`- `a2a_agent_remove`- `agent_memory_forget`- `agent_memory_remember`- `agent_session_note`+- `agent_session_open`- `agent_session_rename`- `apps_power`- `cloudflare_dns_upsert`@@ -102,6 +102,7 @@- `hostinger_dns_upsert`- `integration_manage`- `integration_setup_open`+- `local_agent_inbox_acknowledge`- `local_agent_message_send`- `local_agent_reply`- `organization_manage`@@ -151,20 +152,20 @@## ChatGPT model profile-<!-- mcp-chatgpt-profile: server=1.16.0 version=2026.10.09.1 tools=117 read=59 write=35 exec=23 app-only=2 total=119 -->+<!-- mcp-chatgpt-profile: server=1.17.0 version=2026.10.10.1 tools=118 read=58 write=37 exec=23 app-only=2 total=120 -->The ChatGPT profile automatically projects the complete MSO-owned generic model/operator catalog. OAuth scope is still enforced independently; app-only compatibility bridges stay app-only, and project-owned MCP tool names remain dynamic data behind the generic project bridge.| Fact | Current source value ||---|---:|-| ChatGPT transport tools | **119** |-| ChatGPT model/operator tools | **117** |-| Read | **59** |-| Write | **35** |+| ChatGPT transport tools | **120** |+| ChatGPT model/operator tools | **118** |+| Read | **58** |+| Write | **37** || Exec | **23** || App-only bridges | **2** |-### ChatGPT read (59)+### ChatGPT read (58)- `a2a_agent_discover`- `a2a_agents_list`@@ -174,7 +175,6 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/- `agent_session_action_resolve`- `agent_session_current`- `agent_session_flow`-- `agent_session_open`- `agent_session_resume`- `agent_sessions_list`- `apps_list`@@ -226,13 +226,14 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/- `tool_forge_candidates`- `vps_status`-### ChatGPT write (35)+### ChatGPT write (37)- `a2a_agent_register`- `a2a_agent_remove`- `agent_memory_forget`- `agent_memory_remember`- `agent_session_note`+- `agent_session_open`- `agent_session_rename`- `apps_power`- `cloudflare_dns_upsert`@@ -248,6 +249,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/- `hostinger_dns_upsert`- `integration_manage`- `integration_setup_open`+- `local_agent_inbox_acknowledge`- `local_agent_message_send`- `local_agent_reply`- `organization_manage`diff --git a/frontend/slices/os-settings/components/update-status-client.test.ts b/frontend/slices/os-settings/components/update-status-client.test.tsindex 81f0ac85..7f03bfbb 100644--- a/frontend/slices/os-settings/components/update-status-client.test.ts+++ b/frontend/slices/os-settings/components/update-status-client.test.ts@@ -1,7 +1,15 @@-import { describe, expect, it } from "vitest";-import { hasAvailableUpdate } from "./update-status-client";+import { afterEach, describe, expect, it, vi } from "vitest";+import { hasAvailableUpdate, readStatus } from "./update-status-client";+afterEach(() => vi.unstubAllGlobals());describe("software update navigation status", () => {+ it("polls without a mutation and refreshes with an explicit POST", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response("{}")); vi.stubGlobal("fetch", fetchMock);+ await readStatus(false);+ expect(fetchMock.mock.calls[0][1].method).toBeUndefined();+ fetchMock.mockResolvedValue(new Response("{}")); await readStatus(true);+ expect(fetchMock.mock.calls[1][1]).toMatchObject({ method: "POST", body: JSON.stringify({ action: "check" }) });+ });it("shows the badge for a verified remote update or a checked-out build waiting to run", () => {expect(hasAvailableUpdate({ behind: 2, pendingBuild: false, remoteChecked: true })).toBe(true);expect(hasAvailableUpdate({ behind: 0, pendingBuild: true, remoteChecked: false })).toBe(true);diff --git a/frontend/slices/os-settings/components/update-status-client.ts b/frontend/slices/os-settings/components/update-status-client.tsindex f4286e68..df5cfc66 100644--- a/frontend/slices/os-settings/components/update-status-client.ts+++ b/frontend/slices/os-settings/components/update-status-client.ts@@ -1,7 +1,8 @@import type { UpdateStatus } from "@/lib/host/self-update";export async function readStatus(check: boolean): Promise<UpdateStatus> {- const res = await fetch(`/api/v1/sys/update${check ? "" : "?check=0"}`, {+ const res = await fetch("/api/v1/sys/update", {+ ...(check ? { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ action: "check" }) } : {}),cache: "no-store",signal: AbortSignal.timeout(55_000),});diff --git a/lib/a2a/credentials-inbound.ts b/lib/a2a/credentials-inbound.tsindex e19bce60..b7759c92 100644--- a/lib/a2a/credentials-inbound.ts+++ b/lib/a2a/credentials-inbound.ts@@ -1,5 +1,6 @@import { expandOwnerStorePath } from "@/lib/owner-store-path.js";import { abortA2AProfileTasks } from "./task-active";+import { closeA2AProfileStreams } from "./server-events";import {createHash,randomBytes,@@ -96,6 +97,7 @@ export async function removeA2AInboundToken(id: string): Promise<boolean> {if (store.tokens.length !== before) {await writeA2APrivateStore(A2A_INBOUND_TOKEN_STORE_PATH, store);abortA2AProfileTasks(query);+ closeA2AProfileStreams(query);}return store.tokens.length !== before;});diff --git a/lib/a2a/server-events.ts b/lib/a2a/server-events.tsindex a3a192cb..e469e2a8 100644--- a/lib/a2a/server-events.ts+++ b/lib/a2a/server-events.ts@@ -3,6 +3,17 @@ import type { A2ATaskRecord } from "./tasks";export type A2AStreamResponse = Record<string, unknown>;type Listener = (event: A2AStreamResponse) => void;const listeners = new Map<string, Set<Listener>>();+const streams = new Map<() => void, string>();++export function registerA2AStream(profileId: string, close: () => void): (() => void) | null {+ if (streams.size >= 64 || [...streams.values()].filter(id=>id===profileId).length >= 8) return null;+ streams.set(close,profileId);+ return () => { streams.delete(close); };+}++export function closeA2AProfileStreams(profileId: string): void {+ for (const [close,id] of streams) if (id===profileId) close();+}export function publishA2AEvent(taskId: string, event: A2AStreamResponse) {for (const listener of listeners.get(taskId) ?? []) {diff --git a/lib/a2a/server-execution.ts b/lib/a2a/server-execution.tsindex 1564b554..f6dff84c 100644--- a/lib/a2a/server-execution.ts+++ b/lib/a2a/server-execution.ts@@ -8,8 +8,8 @@ import type { A2AAuthenticatedProfile } from "./server-protocol";import { runInboundA2AAgent } from "./inbound-agent";import {registerA2AActiveTask,+ getA2ATaskForPrincipal,releaseA2AActiveTask,- taskPublicView,updateA2ATask,type A2ATaskRecord,} from "./tasks";@@ -18,9 +18,10 @@ import {a2aStatusUpdate,publishA2AEvent,subscribeA2AEvent,+ registerA2AStream,type A2AStreamResponse,} from "./server-events";-import { a2aRpcOk, type A2ARpcId } from "./server-protocol";+import { A2A_TERMINAL_STATES, a2aRpcOk, type A2ARpcId } from "./server-protocol";export interface A2AExecutionContext {authority?: CapabilityRunContext;@@ -133,45 +134,60 @@ export function a2aSseResponse(capabilities: CapabilityRuntime,prompt?: string,session?: AgentSession,+ signal?: AbortSignal,): Response {const encoder = new TextEncoder();let closed = false;let unsubscribe: () => void = () => {};+ let close: () => void = () => {};+ const release = registerA2AStream(profile.id, () => close());+ if (!release) return new Response(JSON.stringify({error:"stream_limit"}), {status:429,headers:{"content-type":"application/json","retry-after":"60"}});const stream = new ReadableStream<Uint8Array>({- start(controller) {+ async start(controller) {+ const timer = setTimeout(()=>close(),5*60_000);+ timer.unref?.();+ close = () => {+ if (closed) return;+ closed = true;+ clearTimeout(timer);+ unsubscribe();+ release();+ signal?.removeEventListener("abort",close);+ try { controller.close(); } catch { /* Disconnected client. */ }+ };+ signal?.addEventListener("abort",close,{once:true});+ if (signal?.aborted) { close(); return; }const emit = (result: A2AStreamResponse) => {if (closed) return;try {+ if (controller.desiredSize !== null && controller.desiredSize <= 0) { close(); return; }controller.enqueue(encoder.encode(`data: ${JSON.stringify(a2aRpcOk(id, result))}\n\n`),);- } catch {- closed = true;- }+ } catch { close(); }+ const status = (result.statusUpdate as {status?:{state?:string}} | undefined)?.status ?? (result.task as {status?:{state?:string}} | undefined)?.status;+ if (status && A2A_TERMINAL_STATES.has(String(status.state))) close();};- emit({ task: taskPublicView(task) });- unsubscribe = subscribeA2AEvent(task.id, emit);+ try {+ if (!profile.local && !await getA2AInboundProfile(profile.id)) { close(); return; }+ if (closed) return;+ unsubscribe = subscribeA2AEvent(task.id,emit);+ const current = await getA2ATaskForPrincipal(task.id,task.principal,10);+ if (closed) return;+ if (!current) { close(); return; }+ emit({task:current});+ } catch { close(); return; }+ if (closed) return;if (prompt !== undefined) {void executeInboundA2ATask(task, profile, prompt, session, capabilities).finally(- () => {- unsubscribe();- if (!closed) {- closed = true;- try {- controller.close();- } catch {- // Client disconnected after task completion.- }- }- },+ () => close(),);}},cancel() {- closed = true;- unsubscribe(); // Task intentionally continues independently of this stream.+ close(); // Task intentionally continues independently of this stream.},- });+ }, {highWaterMark:16});return new Response(stream, {headers: {"content-type": "text/event-stream; charset=utf-8",diff --git a/lib/a2a/server-streams.test.ts b/lib/a2a/server-streams.test.tsnew file mode 100644index 00000000..01debf44--- /dev/null+++ b/lib/a2a/server-streams.test.ts@@ -0,0 +1,88 @@+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";+import { mkdtempSync, rmSync } from "node:fs";+import os from "node:os";+import path from "node:path";+const root = mkdtempSync(path.join(os.tmpdir(), "mso-a2a-streams-"));+process.env.OS_A2A_CREDENTIAL_STORE = path.join(root, "outbound.json");+process.env.OS_A2A_INBOUND_TOKEN_STORE = path.join(root, "inbound.json");+process.env.OS_A2A_TASK_STORE = path.join(root, "tasks.json");+process.env.OS_A2A_INBOUND_ENABLED = "1";+process.env.OS_PUBLIC_ORIGIN = "https://mso.example.test";+process.env.NEXT_PUBLIC_OS_DEMO = "0";+const runner = vi.hoisted(() => vi.fn());+vi.mock("./inbound-agent", () => ({ runInboundA2AAgent: runner }));+const { createA2AInboundToken, removeA2AInboundToken } = await import("./credentials");+const { createA2ATask } = await import("./tasks");+const { handleA2ARequest } = await import("./server");+const { a2aSseResponse } = await import("./server-execution");+const { publishA2AEvent, registerA2AStream } = await import("./server-events");+const capabilities = { list: () => [], invoke: vi.fn(async () => ({ content: [] })) };+const handle = (req: Request) => handleA2ARequest(req, capabilities);+afterAll(() => rmSync(root, { recursive: true, force: true }));+afterEach(() => vi.unstubAllEnvs());++const rpc = (token: string | null, body: object) =>+ new Request("https://mso.example.test/a2a/v1", {+ method: "POST",+ headers: {+ "content-type": "application/json",+ ...(token ? { authorization: `Bearer ${token}` } : {}),+ },+ body: JSON.stringify(body),+ });++describe("authenticated inbound A2A server", () => {+ it("closes standalone task subscriptions on terminal events and credential revocation", async () => {+ const {token,profile} = await createA2AInboundToken("subscription-lifecycle","read");+ const task = await createA2ATask(`a2a:${profile.id}`,"read",{messageId:"lifecycle",role:"ROLE_USER",parts:[{text:"inspect",mediaType:"text/plain"}]});+ const response = await handle(rpc(token,{jsonrpc:"2.0",id:"subscribe",method:"SubscribeToTask",params:{id:task.id}}));+ const reader = response.body!.getReader();+ expect((await reader.read()).done).toBe(false);+ publishA2AEvent(task.id,{statusUpdate:{status:{state:"TASK_STATE_COMPLETED"}}});+ expect(new TextDecoder().decode((await reader.read()).value)).toContain("TASK_STATE_COMPLETED");+ expect((await reader.read()).done).toBe(true);+ const revoked = a2aSseResponse("revoked",task,profile,capabilities).body!.getReader();+ await revoked.read();+ await removeA2AInboundToken(profile.id);+ publishA2AEvent(task.id,{artifactUpdate:{private:"must-not-deliver"}});+ expect(await revoked.read()).toEqual({done:true,value:undefined});+ });++ it("bounds simultaneous subscriptions and frees slots on disconnect", async () => {+ const {profile} = await createA2AInboundToken("subscription-limit","read");+ const task = await createA2ATask(`a2a:${profile.id}`,"read",{messageId:"limit",role:"ROLE_USER",parts:[{text:"inspect",mediaType:"text/plain"}]});+ const readers = Array.from({length:8},()=>a2aSseResponse("limit",task,profile,capabilities).body!.getReader());+ await Promise.all(readers.map(reader=>reader.read()));+ expect(a2aSseResponse("excess",task,profile,capabilities).status).toBe(429);+ await readers.pop()!.cancel();+ const freed = a2aSseResponse("freed",task,profile,capabilities);+ expect(freed.status).toBe(200);+ readers.push(freed.body!.getReader());+ await readers.at(-1)!.read();+ await removeA2AInboundToken(profile.id);+ expect((await Promise.all(readers.map(reader=>reader.read()))).every(row=>row.done)).toBe(true);+ const releases: Array<()=>void> = [];+ for(let i=0;i<64;i++) {+ const release = registerA2AStream(`global-fixture-${i}`,()=>{});+ expect(release).not.toBeNull(); releases.push(release!);+ }+ expect(registerA2AStream("global-excess",()=>{})).toBeNull();+ releases.forEach(release=>release());+ });++ it("closes subscriptions on request abort and an absolute deadline", async () => {+ const {profile} = await createA2AInboundToken("subscription-timeout","read");+ const task = await createA2ATask(`a2a:${profile.id}`,"read",{messageId:"timeout",role:"ROLE_USER",parts:[{text:"inspect",mediaType:"text/plain"}]});+ const abort = new AbortController();+ const disconnected = a2aSseResponse("abort",task,profile,capabilities,undefined,undefined,abort.signal).body!.getReader();+ await disconnected.read(); abort.abort();+ expect((await disconnected.read()).done).toBe(true);+ vi.useFakeTimers({toFake:["setTimeout","clearTimeout"]});+ try {+ const timed = a2aSseResponse("timeout",task,profile,capabilities).body!.getReader();+ await timed.read();+ await vi.advanceTimersByTimeAsync(5*60_000);+ expect((await timed.read()).done).toBe(true);+ } finally {vi.useRealTimers();}+ });+});diff --git a/lib/a2a/server.ts b/lib/a2a/server.tsindex 3ae6ecdb..dd22f769 100644--- a/lib/a2a/server.ts+++ b/lib/a2a/server.ts@@ -86,7 +86,7 @@ export async function handleA2ARequest(req: Request, capabilities: CapabilityRuntargetSession?.id,);if (method === "SendStreamingMessage")- return a2aSseResponse(id, task, profile, capabilities, parsed.prompt, targetSession);+ return a2aSseResponse(id, task, profile, capabilities, parsed.prompt, targetSession, req.signal);if (parsed.returnImmediately) {void executeInboundA2ATask(task, profile, parsed.prompt, targetSession, capabilities);return a2aJson(a2aRpcOk(id, { task: taskPublicView(task) }));@@ -147,7 +147,7 @@ export async function handleA2ARequest(req: Request, capabilities: CapabilityRun(row) => row.id === taskId,);return full- ? a2aSseResponse(id, full, profile, capabilities, undefined, targetSession)+ ? a2aSseResponse(id, full, profile, capabilities, undefined, targetSession, req.signal): a2aJson(a2aRpcError(id, -32001, "Task not found"));}return a2aJson(a2aRpcError(id, -32601, "Method not found"));diff --git a/lib/agent/local-agent-messaging-wait.ts b/lib/agent/local-agent-messaging-wait.tsindex 1e8d2232..577c278b 100644--- a/lib/agent/local-agent-messaging-wait.ts+++ b/lib/agent/local-agent-messaging-wait.ts@@ -15,15 +15,19 @@ export async function waitForLocalAgentInbox(input: {includeRead?: boolean;limit?: number;waitMs?: number;+ signal?:AbortSignal;+ authorize?:()=>Promise<void>;}): Promise<LocalAgentMessageView[]> {const limit = Math.max(1, Math.min(200, Math.trunc(input.limit ?? 100)));const waitMs = Number.isFinite(input.waitMs)? Math.max(0, Math.min(MAX_LOCAL_AGENT_INBOX_WAIT_MS, Math.trunc(input.waitMs ?? 0))): 0;- const read = () => listLocalAgentInbox(input.principal, input.sessionId, {- includeRead: input.includeRead === true,- limit,- });+ const read = async () => {+ input.signal?.throwIfAborted(); await input.authorize?.();+ const messages=await listLocalAgentInbox(input.principal,input.sessionId,{includeRead:input.includeRead===true,limit});+ input.signal?.throwIfAborted(); await input.authorize?.();+ return messages;+ };const initial = await read();if (initial.length || waitMs === 0) return initial;@@ -31,15 +35,29 @@ export async function waitForLocalAgentInbox(input: {const signalled = new Promise<void>((resolve) => { wake = resolve; });const unsubscribe = subscribeLocalAgentMessages(input.sessionId, () => wake());let timer: ReturnType<typeof setTimeout> | undefined;+ let authorizationTimer: ReturnType<typeof setInterval> | undefined;+ let abort=()=>{};try {// Close the read→subscribe race; durable mailbox remains authoritative.const afterSubscribe = await read();if (afterSubscribe.length) return afterSubscribe;const timedOut = new Promise<void>((resolve) => { timer = setTimeout(resolve, waitMs); });- await Promise.race([signalled, timedOut]);- return read();+ const revoked=new Promise<never>((_resolve,reject)=>{+ abort=()=>reject(input.signal?.reason ?? new Error("Local-agent wait aborted"));+ input.signal?.addEventListener("abort",abort,{once:true});+ if (input.signal?.aborted) abort();+ let checking=false;+ if(input.authorize) authorizationTimer=setInterval(()=>{+ if(checking) return;+ checking=true; void input.authorize!().catch(reject).finally(()=>{checking=false;});+ },100);+ });+ await Promise.race([signalled, timedOut,revoked]);+ return await read();} finally {if (timer) clearTimeout(timer);+ if (authorizationTimer) clearInterval(authorizationTimer);+ input.signal?.removeEventListener("abort",abort);unsubscribe();}}@@ -49,7 +67,10 @@ export async function waitForLocalAgentReply(input: {senderSessionId: string;requestMessageId: string;timeoutMs?: number;+ signal?:AbortSignal;+ authorize?:()=>Promise<void>;}) {+ input.signal?.throwIfAborted(); await input.authorize?.();const request = await getLocalAgentSentMessage(input.principal,input.senderSessionId,@@ -60,10 +81,12 @@ export async function waitForLocalAgentReply(input: {const timeoutMs = Math.max(0, Math.min(30_000, Math.trunc(input.timeoutMs ?? 5_000)));const startedAt = Date.now();while (true) {+ input.signal?.throwIfAborted(); await input.authorize?.();const reply = await findLocalAgentReply(input.principal, input.senderSessionId, request.id);const target = (await listLocalAgents(input.principal, { includeOffline: true })).find((row) => row.id === request.targetSessionId) ?? null;const elapsedMs = Date.now() - startedAt;+ input.signal?.throwIfAborted(); await input.authorize?.();if (reply) return { state: "replied" as const, elapsedMs, request, reply, target };if (target && !target.actionable && ["offline", "ended"].includes(target.status))return { state: "target_offline" as const, elapsedMs, request, reply: null, target };diff --git a/lib/auth/live-session.test.ts b/lib/auth/live-session.test.tsindex b46344e6..bc615659 100644--- a/lib/auth/live-session.test.ts+++ b/lib/auth/live-session.test.ts@@ -14,12 +14,12 @@ it("invalidates derived viewer cookies and tickets durably at logout and after rconst id = "a".repeat(32), secret = "s".repeat(32);await devices.approveDevice(id); await devices.approveDevice("b".repeat(32));const issued = Date.now();- const ticket = verifyCamoufoxViewerTicket(createCamoufoxViewerTicket(id, secret, issued, issued), secret)!;- const cookie = verifyCamoufoxViewerCookie(createCamoufoxViewerCookie(id, secret, Date.now(), ticket.issued_at), secret)!;+ const ticket = verifyCamoufoxViewerTicket(createCamoufoxViewerTicket({device_id:id,issued_at:issued,expires_at:issued+3_600_000}, secret, issued), secret)!;+ const cookie = verifyCamoufoxViewerCookie(createCamoufoxViewerCookie(ticket, secret), secret)!;expect(deviceSessionValid(cookie, await devices.getApprovedDevice(id))).toBe(true);await devices.invalidateDeviceSessions(id);expect(deviceSessionValid(cookie, await devices.getApprovedDevice(id))).toBe(false);- const replay = verifyCamoufoxViewerCookie(createCamoufoxViewerCookie(id, secret, Date.now(), ticket.issued_at), secret)!;+ const replay = verifyCamoufoxViewerCookie(createCamoufoxViewerCookie(ticket, secret), secret)!;expect(deviceSessionValid(replay, await devices.getApprovedDevice(id))).toBe(false);await devices.revokeDevice(id); await devices.approveDevice(id);expect(deviceSessionValid(cookie, await devices.getApprovedDevice(id))).toBe(false);diff --git a/lib/camoufox/viewer-auth.test.ts b/lib/camoufox/viewer-auth.test.tsindex c04484d9..df38ab48 100644--- a/lib/camoufox/viewer-auth.test.ts+++ b/lib/camoufox/viewer-auth.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import { signSession } from "@/lib/auth/session";import {CAMOUFOX_VIEWER_COOKIE_TTL_MS,@@ -12,11 +12,12 @@ import {describe("Camoufox sibling viewer credentials", () => {const secret = "s".repeat(48);const deviceId = "dev-1234567890abcdef";+ const parent = (now=Date.now()) => ({device_id:deviceId,issued_at:now,expires_at:now+3*60*60_000});it("keeps short-lived tickets and viewer cookies cryptographically separate", () => {const now = Date.now();- const ticket = createCamoufoxViewerTicket(deviceId, secret, now);- const cookie = createCamoufoxViewerCookie(deviceId, secret, now);+ const ticket = createCamoufoxViewerTicket(parent(now), secret, now);+ const cookie = createCamoufoxViewerCookie(parent(now), secret, now);expect(verifyCamoufoxViewerTicket(ticket, secret)?.device_id).toBe(deviceId);expect(verifyCamoufoxViewerCookie(cookie, secret)?.device_id).toBe(deviceId);expect(verifyCamoufoxViewerCookie(ticket, secret)).toBeNull();@@ -24,9 +25,11 @@ describe("Camoufox sibling viewer credentials", () => {});it("expires a ticket much sooner than the host-only viewer cookie", () => {- const oldTicket = createCamoufoxViewerTicket(deviceId, secret, Date.now() - CAMOUFOX_VIEWER_TICKET_TTL_MS - 1);+ const old = Date.now() - CAMOUFOX_VIEWER_TICKET_TTL_MS - 1;+ const oldTicket = createCamoufoxViewerTicket(parent(old), secret, old);expect(verifyCamoufoxViewerTicket(oldTicket, secret)).toBeNull();- const stillValidCookie = createCamoufoxViewerCookie(deviceId, secret, Date.now() - CAMOUFOX_VIEWER_COOKIE_TTL_MS + 60_000);+ const earlier = Date.now() - CAMOUFOX_VIEWER_COOKIE_TTL_MS + 60_000;+ const stillValidCookie = createCamoufoxViewerCookie(parent(earlier), secret, earlier);expect(verifyCamoufoxViewerCookie(stillValidCookie, secret)?.device_id).toBe(deviceId);});@@ -42,6 +45,21 @@ describe("Camoufox sibling viewer credentials", () => {expect(verifyCamoufoxViewerTicket(cockpit, secret)).toBeNull();expect(verifyCamoufoxViewerCookie(cockpit, secret)).toBeNull();expect(verifyCamoufoxViewerTicket("anything", "")).toBeNull();- expect(() => createCamoufoxViewerTicket(deviceId, "")).toThrow(/not configured/);+ expect(() => createCamoufoxViewerTicket(parent(), "")).toThrow(/not configured/);+ });++ it("retains the parent expiry and issued-at through ticket redemption", () => {+ vi.useFakeTimers({toFake:["Date"]});+ try {+ const now=Date.now(), session={...parent(now),expires_at:now+45_000};+ const ticket=createCamoufoxViewerTicket(session,secret);+ vi.setSystemTime(now+15_000);+ const redeemed=verifyCamoufoxViewerTicket(ticket,secret)!;+ const cookie=createCamoufoxViewerCookie(redeemed,secret);+ expect(verifyCamoufoxViewerCookie(cookie,secret)).toMatchObject({issued_at:now,expires_at:now+45_000,parent_expires_at:now+45_000});+ vi.setSystemTime(now+45_001);+ expect(verifyCamoufoxViewerCookie(cookie,secret)).toBeNull();+ expect(verifyCamoufoxViewerTicket(ticket,secret)).toBeNull();+ } finally {vi.useRealTimers();}});});diff --git a/lib/camoufox/viewer-auth.ts b/lib/camoufox/viewer-auth.tsindex ad70b29b..a50367c6 100644--- a/lib/camoufox/viewer-auth.ts+++ b/lib/camoufox/viewer-auth.ts@@ -6,33 +6,42 @@ export const CAMOUFOX_VIEWER_COOKIE_TTL_MS = 2 * 60 * 60 * 1000;const ticketSecret = (secret: string) => "camoufox-viewer-ticket:" + secret;const cookieSecret = (secret: string) => "camoufox-viewer-cookie:" + secret;+type ViewerParent = Pick<SessionPayload,"device_id"|"issued_at"|"expires_at"> & {parent_expires_at?:number};+type ViewerSession = SessionPayload & {parent_expires_at:number};-function payload(deviceId: string, now: number, ttlMs: number): SessionPayload {+function payload(parent: ViewerParent, now: number, ttlMs: number): ViewerSession {+ const parentExpiry = parent.parent_expires_at ?? parent.expires_at;+ if (!Number.isFinite(parentExpiry)) throw new Error("viewer parent expiry is required");return {- issued_at: now,- expires_at: now + ttlMs,- device_id: deviceId,+ issued_at: parent.issued_at,+ expires_at: Math.min(parentExpiry,now + ttlMs),+ parent_expires_at:parentExpiry,+ device_id: parent.device_id,cookie_scope: "camoufox-viewer",cookie_epoch: "camoufox-viewer-v1",};}-export function createCamoufoxViewerTicket(deviceId: string, secret: string, now = Date.now(), issuedAt = now): string {+export function createCamoufoxViewerTicket(parent: ViewerParent, secret: string, now = Date.now()): string {if (secret.length < MIN_SECRET_LEN) throw new Error("viewer signing secret is not configured");- return signSession({ ...payload(deviceId, now, CAMOUFOX_VIEWER_TICKET_TTL_MS), issued_at: issuedAt }, ticketSecret(secret));+ return signSession(payload(parent,now,CAMOUFOX_VIEWER_TICKET_TTL_MS),ticketSecret(secret));}-export function verifyCamoufoxViewerTicket(token: string, secret: string): SessionPayload | null {+function verifyViewerSession(token:string,secret:string): ViewerSession|null {+ const session = verifySession(token,secret) as ViewerSession|null;+ return session && Number.isFinite(session.parent_expires_at) && session.parent_expires_at >= session.expires_at ? session:null;+}+export function verifyCamoufoxViewerTicket(token: string, secret: string): ViewerSession | null {if (secret.length < MIN_SECRET_LEN) return null;- return verifySession(token, ticketSecret(secret));+ return verifyViewerSession(token, ticketSecret(secret));}-export function createCamoufoxViewerCookie(deviceId: string, secret: string, now = Date.now(), issuedAt = now): string {+export function createCamoufoxViewerCookie(parent: ViewerParent, secret: string, now = Date.now()): string {if (secret.length < MIN_SECRET_LEN) throw new Error("viewer signing secret is not configured");- return signSession({ ...payload(deviceId, now, CAMOUFOX_VIEWER_COOKIE_TTL_MS), issued_at: issuedAt }, cookieSecret(secret));+ return signSession(payload(parent,now,CAMOUFOX_VIEWER_COOKIE_TTL_MS),cookieSecret(secret));}-export function verifyCamoufoxViewerCookie(token: string, secret: string): SessionPayload | null {+export function verifyCamoufoxViewerCookie(token: string, secret: string): ViewerSession | null {if (secret.length < MIN_SECRET_LEN) return null;- return verifySession(token, cookieSecret(secret));+ return verifyViewerSession(token, cookieSecret(secret));}diff --git a/lib/camoufox/viewer-gate.test.ts b/lib/camoufox/viewer-gate.test.tsindex 19686175..58d8f8ce 100644--- a/lib/camoufox/viewer-gate.test.ts+++ b/lib/camoufox/viewer-gate.test.ts@@ -53,11 +53,11 @@ describe("the Camoufox split-origin VNC bridge", () => {}function viewerCookie(): string {- return createCamoufoxViewerCookie(DEVICE, SECRET);+ return createCamoufoxViewerCookie({device_id:DEVICE,issued_at:Date.now(),expires_at:Date.now()+3_600_000}, SECRET);}function viewerTicket(now = Date.now()): string {- return createCamoufoxViewerTicket(DEVICE, SECRET, now);+ return createCamoufoxViewerTicket({device_id:DEVICE,issued_at:now,expires_at:now+3_600_000}, SECRET, now);}async function load(novnc = NOVNC) {diff --git a/lib/camoufox/viewer-gate.ts b/lib/camoufox/viewer-gate.tsindex a202b2df..a3fa70fe 100644--- a/lib/camoufox/viewer-gate.ts+++ b/lib/camoufox/viewer-gate.ts@@ -32,7 +32,7 @@ function notFound() {return response;}-async function approvedDevice(token: string, kind: "ticket" | "cookie"): Promise<string | null> {+async function approvedDevice(token: string, kind: "ticket" | "cookie") {if (IS_DEMO) return null;const secret = process.env.OS_SESSION_SECRET ?? "";const payload = kind === "ticket"@@ -40,7 +40,7 @@ async function approvedDevice(token: string, kind: "ticket" | "cookie"): Promise: verifyCamoufoxViewerCookie(token, secret);if (!payload?.device_id) return null;const device = await getApprovedDevice(payload.device_id);- return deviceSessionValid(payload, device) && device && roleAtLeast(device.role, "operator") ? payload.device_id : null;+ return deviceSessionValid(payload, device) && device && roleAtLeast(device.role, "operator") ? payload : null;}async function hasViewerSession(request: NextRequest): Promise<boolean> {@@ -108,19 +108,19 @@ async function exchangeTicket(request: NextRequest) {if (request.method !== "POST") return notFound();const match = /^Bearer ([A-Za-z0-9._-]{20,4096})$/.exec(request.headers.get("authorization") ?? "");if (!match) return notFound();- const deviceId = await approvedDevice(match[1], "ticket");- if (!deviceId) return notFound();+ const session = await approvedDevice(match[1], "ticket");+ if (!session) return notFound();const response = new NextResponse(null, { status: 204 });response.cookies.set(CAMOUFOX_VIEWER_COOKIE,- createCamoufoxViewerCookie(deviceId, process.env.OS_SESSION_SECRET ?? "", Date.now(), verifyCamoufoxViewerTicket(match[1], process.env.OS_SESSION_SECRET ?? "")!.issued_at),+ createCamoufoxViewerCookie(session, process.env.OS_SESSION_SECRET ?? ""),{httpOnly: true,secure: true,sameSite: "strict",path: "/",- maxAge: Math.floor(CAMOUFOX_VIEWER_COOKIE_TTL_MS / 1000),+ maxAge:Math.max(0,Math.floor((Math.min(session.parent_expires_at,Date.now()+CAMOUFOX_VIEWER_COOKIE_TTL_MS)-Date.now())/1000)),},);noStore(response.headers);diff --git a/lib/capabilities/actors.ts b/lib/capabilities/actors.tsindex 715771c1..49ed5152 100644--- a/lib/capabilities/actors.ts+++ b/lib/capabilities/actors.ts@@ -2,7 +2,7 @@ import type { TenantContext } from "@/lib/tenancy/authority";import type { AuthorizationGrant } from "./authorization-grant";import type { CapabilityToolProfile } from "./tool";-export interface CapabilityAgentContext { authorizationGrant?: AuthorizationGrant; tenantContext?: TenantContext; principal?: string; sessionId?: string; workflowActorOverride?: string; toolProfile?: CapabilityToolProfile; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }+export interface CapabilityAgentContext { signal?:AbortSignal; liveAuthorization?:()=>Promise<void>; authorizationGrant?: AuthorizationGrant; tenantContext?: TenantContext; principal?: string; sessionId?: string; workflowActorOverride?: string; toolProfile?: CapabilityToolProfile; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }export function workflowActor(actor: string | undefined, context?: CapabilityAgentContext): string | undefined {if (context?.workflowActorOverride) return context.workflowActorOverride;return context?.principal && context.sessionId ? `${context.principal}#session:${context.sessionId}` : actor;diff --git a/lib/capabilities/execute.ts b/lib/capabilities/execute.tsindex 5a939954..0efba5c1 100644--- a/lib/capabilities/execute.ts+++ b/lib/capabilities/execute.ts@@ -126,6 +126,8 @@ export async function executeCapabilityCall(input: {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, {+ signal:context?.signal,+ liveAuthorization:context?.liveAuthorization,actor,principal: context?.principal,tenantContext: context?.tenantContext,diff --git a/lib/capabilities/runtime.ts b/lib/capabilities/runtime.tsindex b839b087..13d57f21 100644--- a/lib/capabilities/runtime.ts+++ b/lib/capabilities/runtime.ts@@ -23,6 +23,8 @@ export interface CapabilityInvocation {actor?: string;principal?: string;authorizationGrant?: AuthorizationGrant;+ signal?: AbortSignal;+ liveAuthorization?: () => Promise<void>;sessionId?: string;/** Optional fixed workflow context used by durable delegated workers. */workflowId?: string;diff --git a/lib/capabilities/tool.ts b/lib/capabilities/tool.tsindex 2f0cc6a2..5f318051 100644--- a/lib/capabilities/tool.ts+++ b/lib/capabilities/tool.ts@@ -58,6 +58,8 @@ export type CapabilityActionContract = {};export interface CapabilityRunContext {+ signal?:AbortSignal;+ liveAuthorization?:()=>Promise<void>;tenantContext?: TenantContext;actor?: string;principal?: string;diff --git a/lib/host/project-candidate-index-cache.ts b/lib/host/project-candidate-index-cache.tsindex fa04c9dc..ac580f9d 100644--- a/lib/host/project-candidate-index-cache.ts+++ b/lib/host/project-candidate-index-cache.ts@@ -2,8 +2,9 @@ import { createHash } from "node:crypto";import { constants, promises as fs } from "node:fs";import os from "node:os";import path from "node:path";+import { isCredentialPath } from "./path-credentials";-const INDEX_VERSION = 1;+const INDEX_VERSION = 2;const MAX_INDEX_ENTRIES = 8_000;const MAX_DIRS = 2_500;const MAX_DEPTH = 14;@@ -11,7 +12,7 @@ const MAX_DEPTH = 14;export type CandidateKind = "path" | "skill";export type CandidateEntry = { path: string; kind: CandidateKind; size: number };export type CandidateIndex = {- version: 1;+ version: 2;projectRoot: string;revision: string;entries: CandidateEntry[];@@ -40,7 +41,8 @@ function cacheFile(projectPath: string): string {return path.join(cacheRoot(), `${key}.json`);}-function ignoredFile(name: string, rel: string): boolean {+function ignoredFile(name: string, rel: string, root: string): boolean {+ if (isCredentialPath(path.resolve(root, rel))) return true;const lower = name.toLowerCase();if (/^\.env(?:\.|$)/i.test(name)) return true;if ([".npmrc", ".pypirc", "id_rsa", "id_ed25519", "cookies.json", "credentials.json", "auth.json"].includes(lower)) return true;@@ -98,11 +100,11 @@ async function buildIndex(projectPath: string, revision: string): Promise<Candidconst rel = relDir ? `${relDir}/${dirent.name}` : dirent.name;const absolute = path.join(dir, dirent.name);if (dirent.isDirectory()) {- if (!allowedDir(dirent.name, rel)) continue;+ if (!allowedDir(dirent.name, rel) || isCredentialPath(absolute)) continue;await walk(absolute, rel, depth + 1);continue;}- if (!dirent.isFile() || ignoredFile(dirent.name, rel)) continue;+ if (!dirent.isFile() || ignoredFile(dirent.name, rel, root)) continue;const stat = await fs.stat(absolute).catch(() => null);if (!stat?.isFile()) continue;entries.push({ path: rel.replace(/\\/g, "/"), kind: dirent.name === "SKILL.md" ? "skill" : "path", size: stat.size });@@ -160,10 +162,11 @@ export async function candidateEntriesFromSeed(projectPath: string, seedPaths: sconst out: CandidateEntry[] = [];for (const relRaw of seedPaths.slice(0, 64)) {const rel = relRaw.replace(/\\/g, "/").replace(/^\.\//, "");- if (!rel || rel.startsWith("../") || path.isAbsolute(rel) || ignoredFile(path.basename(rel), rel)) continue;+ if (!rel || rel.startsWith("../") || path.isAbsolute(rel) || ignoredFile(path.basename(rel), rel, root)) continue;const absolute = path.resolve(root, rel);const real = await fs.realpath(absolute).catch(() => "");if (!real || (real !== root && !real.startsWith(root + path.sep))) continue;+ if (isCredentialPath(real)) continue;const handle = await fs.open(real, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => null);if (!handle) continue;try {diff --git a/lib/host/project-candidate-index.test.ts b/lib/host/project-candidate-index.test.tsindex ce2e0856..7b8b0618 100644--- a/lib/host/project-candidate-index.test.ts+++ b/lib/host/project-candidate-index.test.ts@@ -79,4 +79,23 @@ describe("project candidate index", () => {expect(JSON.stringify(reused)).not.toContain("workflow-extra.ts");expect(JSON.stringify(reused)).not.toContain("SECRET=");});++ it("excludes canonical credential paths from fresh, cached and seeded searches", async () => {+ const project = await resetProject();+ const protectedPaths = [".mcp.json", ".netrc", ".mcp.json.backup.tmp", "nested/.netrc.old", "nested/.env.local", "nested/id_ed25519", "nested/key.pem"];+ for (const file of protectedPaths) {+ await fs.mkdir(path.dirname(path.join(project,file)), {recursive:true});+ await fs.writeFile(path.join(project,file), "needle private-fixture-value\n");+ }+ await fs.writeFile(path.join(project,"needle.txt"), "needle public text\n");+ for (const reuseOnly of [false,true]) {+ const result = await searchProjectCandidateIndex({projectPath:project,query:"needle .mcp.json .netrc",revision:"protected",seedPaths:protectedPaths.concat("needle.txt"),reuseOnly,limit:40});+ expect(JSON.stringify(result)).not.toContain("private-fixture-value");+ expect(result.candidates.map(row=>row.path)).not.toEqual(expect.arrayContaining(protectedPaths));+ expect(result.matches).toContainEqual({path:"needle.txt",line:1,preview:"needle public text"});+ }+ const cached = await searchProjectCandidateIndex({projectPath:project,query:".mcp.json needle",revision:"protected",limit:40});+ expect(cached.rebuilt).toBe(false);+ expect(cached.candidates.some(row=>protectedPaths.includes(row.path))).toBe(false);+ });});diff --git a/lib/host/project-candidate-index.ts b/lib/host/project-candidate-index.tsindex ba1fbfe1..223eefe4 100644--- a/lib/host/project-candidate-index.ts+++ b/lib/host/project-candidate-index.ts@@ -2,6 +2,8 @@ import { createHash } from "node:crypto";import { promises as fs } from "node:fs";import path from "node:path";import { readBoundedRegularFile } from "./bounded-read";+import { isCredentialPath } from "./path-credentials";+import { redactText } from "@/lib/security/redact-text";import { candidateEntriesFromSeed, loadCandidateIndex, type CandidateEntry } from "./project-candidate-index-cache";const MAX_CONTENT_BYTES = 128 * 1024;@@ -65,8 +67,10 @@ async function contentMatches(projectPath: string, candidates: ProjectCandidate[for (const candidate of candidates) {if (matches.length >= MAX_MATCHES) break;const absolute = path.resolve(root, candidate.path);+ if (isCredentialPath(absolute)) continue;const real = await fs.realpath(absolute).catch(() => "");if (!real || (real !== root && !real.startsWith(root + path.sep))) continue;+ if (isCredentialPath(real)) continue;const content = await readBoundedRegularFile(real, MAX_CONTENT_BYTES);if (content == null || content.includes("\u0000")) continue;const lines = content.split(/\r?\n/);@@ -74,7 +78,7 @@ async function contentMatches(projectPath: string, candidates: ProjectCandidate[for (let index = 0; index < lines.length && perFile < 3 && matches.length < MAX_MATCHES; index += 1) {const lower = lines[index].toLowerCase();if (!tokens.some((token) => lower.includes(token))) continue;- const preview = lines[index].trim().replace(/\s+/g, " ").slice(0, 220);+ const preview = redactText(lines[index].trim().replace(/\s+/g, " "), 220);if (!preview) continue;matches.push({ path: candidate.path, line: index + 1, preview });perFile += 1;@@ -107,11 +111,12 @@ export async function searchProjectCandidateIndex(input: {const reuseOnly = input.reuseOnly === true;const seeded = input.seedPaths?.length ? await candidateEntriesFromSeed(input.projectPath, input.seedPaths) : [];const loaded = reuseOnly- ? { index: { version: 1 as const, projectRoot: await fs.realpath(input.projectPath), revision: input.revision, entries: seeded, directories: [], truncated: false, truncationReasons: [], createdAt: new Date().toISOString() }, rebuilt: false }+ ? { index: { version: 2 as const, projectRoot: await fs.realpath(input.projectPath), revision: input.revision, entries: seeded, directories: [], truncated: false, truncationReasons: [], createdAt: new Date().toISOString() }, rebuilt: false }: await loadCandidateIndex(input.projectPath, input.revision);const source = reuseOnly ? seeded : loaded.index.entries;const tokens = queryTokens(query);const ranked = source+ .filter((entry) => !isCredentialPath(path.resolve(input.projectPath, entry.path))).map((entry) => ({ ...entry, score: rank(entry, tokens) })).filter((entry) => reuseOnly || tokens.length === 0 || entry.score > 0).sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));diff --git a/lib/host/project-experience.test.ts b/lib/host/project-experience.test.tsindex 2db4b684..d594530f 100644--- a/lib/host/project-experience.test.ts+++ b/lib/host/project-experience.test.ts@@ -60,6 +60,35 @@ describe("project experience host helpers", () => {await expect(readProjectKnowledge(project)).rejects.toThrow(/regular non-symlink/i);});+ it("suppresses protected Git patches in staged and historical diffs and redacts ordinary-file credentials", async () => {+ const repo = path.join(root,"private-diff");+ await mkdir(repo);+ const git = (args:string[]) => execFileSync("git",args,{cwd:repo,encoding:"utf8"}).trim();+ git(["init","-b","main"]); git(["config","user.email","[email protected]"]); git(["config","user.name","MSO Test"]);+ await writeFile(path.join(repo,"public.txt"),"public before\n");+ git(["add","."]); git(["commit","-m","before"]);+ const names = [".mcp.json",".netrc",".mcp.json.fixture.tmp",".env.local","private.pem","odd\tdir/.netrc"];+ for (const name of names) {+ await mkdir(path.dirname(path.join(repo,name)),{recursive:true});+ await writeFile(path.join(repo,name),"private-fixture-value\n");+ }+ await writeFile(path.join(repo,"public.txt"),"public after\nAPI_TOKEN=synthetic-private-token\n");+ git(["add","."]);+ const staged = await projectGitDiff(repo,{staged:true});+ expect(staged.unifiedDiff).not.toContain("private-fixture-value");+ expect(staged.unifiedDiff).not.toContain("synthetic-private-token");+ expect(staged.unifiedDiff).toContain("+public after");+ expect(staged.files.find(row=>row.file===".mcp.json")).toMatchObject({redacted:true});+ git(["commit","-m","private changes"]);+ const sha = git(["rev-parse","HEAD"]);+ const historic = await projectGitDiff(repo,{sha});+ expect(historic.unifiedDiff).toBe(staged.unifiedDiff);+ git(["mv",".mcp.json","safe-name.json"]);+ const renamed = await projectGitDiff(repo,{staged:true});+ expect(renamed.files.find(row=>row.file==="safe-name.json")).toMatchObject({redacted:true,previousFile:".mcp.json"});+ expect(renamed.unifiedDiff).not.toContain("private-fixture-value");+ });+it("refuses a symlinked knowledge directory inside readable roots", async () => {const outside = path.join(root, "other-project");await mkdir(outside);diff --git a/lib/host/project-experience.ts b/lib/host/project-experience.tsindex 670ff497..2b5f5acb 100644--- a/lib/host/project-experience.ts+++ b/lib/host/project-experience.ts@@ -5,6 +5,8 @@ import path from "node:path";import { BOUNDED_READ, readBoundedRegularFile } from "./bounded-read";import { resolveReadable } from "./paths";import { childEnv } from "./child-env";+import { isCredentialPath } from "./path-credentials";+import { redactText } from "@/lib/security/redact-text";const GIT_TIMEOUT_MS = 8_000;const GIT_MAX_BYTES = 256 * 1024;@@ -84,23 +86,31 @@ export async function projectGitDiff(projectPath: string, options: { sha?: strinconst sha = options.sha ? requireSha(options.sha, "sha") : undefined;const baseSha = options.baseSha ? requireSha(options.baseSha, "base_sha") : undefined;const range = sha ? (baseSha ? `${baseSha}..${sha}` : `${sha}^..${sha}`) : undefined;- const diffArgs = ["diff", "--no-ext-diff", "--unified=3"];- const statArgs = ["diff", "--no-ext-diff", "--numstat"];+ const diffArgs = ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--unified=3"];+ const statArgs = ["diff", "--no-ext-diff", "--no-textconv", "--find-renames", "--numstat", "-z"];if (!range && options.staged) { diffArgs.push("--cached"); statArgs.push("--cached"); }if (range) { diffArgs.push(range); statArgs.push(range); }- const [diff, stats] = await Promise.all([git(projectPath, diffArgs, 512 * 1024), git(projectPath, statArgs, 128 * 1024)]);- if (diff.code !== 0) throw new Error((diff.stderr || diff.stdout).trim().slice(0, 400) || "git diff failed");+ const stats = await git(projectPath, statArgs, 128 * 1024);if (stats.code !== 0) throw new Error((stats.stderr || stats.stdout).trim().slice(0, 400) || "git diff --numstat failed");- const files = stats.stdout.split("\n").filter(Boolean).slice(0, 200).map((line) => {- const [added = "0", deleted = "0", file = ""] = line.split("\t");- return { file, added: added === "-" ? null : Number(added), deleted: deleted === "-" ? null : Number(deleted) };- });+ const records = stats.stdout.split("\0");+ const files: Array<{file:string; previousFile?:string; added:number|null; deleted:number|null; redacted?:boolean}> = [];+ for (let index=0; index<records.length && records[index] && files.length<200; index+=1) {+ const [added="0",deleted="0",...name] = records[index].split("\t");+ const previousFile = name.join("\t") ? undefined : records[++index];+ const file = previousFile === undefined ? name.join("\t") : records[++index];+ if (!file) throw new Error("Invalid Git diff path metadata");+ const redacted = [file,previousFile].some(value=>value !== undefined && isCredentialPath(path.resolve(projectPath,value)));+ files.push({file,...(previousFile ? {previousFile} : {}),added:added==="-"?null:Number(added),deleted:deleted==="-"?null:Number(deleted),...(redacted?{redacted:true}:{})});+ }+ const readableFiles = files.filter((file) => !file.redacted);+ const diff = readableFiles.length ? await git(projectPath, [...diffArgs, "--", ...readableFiles.flatMap(({file,previousFile}) => (previousFile?[previousFile,file]:[file]).map(name=>`:(literal)${name}`))], 512 * 1024) : { code: 0, stdout: "", stderr: "" };+ if (diff.code !== 0) throw new Error(redactText((diff.stderr || diff.stdout).trim(), 400) || "git diff failed");const additions = files.reduce((sum, row) => sum + (row.added ?? 0), 0);const deletions = files.reduce((sum, row) => sum + (row.deleted ?? 0), 0);return {mode: range ? "commit" : options.staged ? "staged" : "working-tree",...(sha ? { sha } : {}), ...(baseSha ? { baseSha } : {}),- files, summary: { files: files.length, additions, deletions }, unifiedDiff: diff.stdout,+ files, summary: { files: files.length, additions, deletions }, unifiedDiff: redactText(diff.stdout),};}diff --git a/lib/infra/google-native-types.ts b/lib/infra/google-native-types.tsindex db184392..07c55ba5 100644--- a/lib/infra/google-native-types.ts+++ b/lib/infra/google-native-types.ts@@ -1,6 +1,6 @@/** Server-only OAuth grants live in the existing owner integration store, never a transfer DTO. */export type GoogleProvider = "google-search-console" | "google-analytics";-export type GoogleActor = { deviceId: string; cookieScope: string; cookieEpoch: string; sessionExpiresAt: number };+export type GoogleActor = { deviceId: string; cookieScope: string; cookieEpoch: string; sessionIssuedAt: number; sessionExpiresAt: number };export type GoogleGrant = {appConnection: string; appUid: string; appRevision: number; redirectUri: string;subject: string; email: string; scopes: string[];diff --git a/lib/infra/google-native.test.ts b/lib/infra/google-native.test.tsindex 4805cccf..3322739f 100644--- a/lib/infra/google-native.test.ts+++ b/lib/infra/google-native.test.ts@@ -2,13 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { mkdtemp, rm } from "node:fs/promises";import path from "node:path";import os from "node:os";-const security = vi.hoisted(() => ({ role: "owner", epoch: "test-cookie-epoch-123456789" }));-vi.mock("@/lib/auth/device-store", () => ({ currentSessionPolicy: async () => ({ epoch: security.epoch }), getApprovedDevice: async () => ({ role: security.role }) }));+const security = vi.hoisted(() => ({ role: "owner", epoch: "test-cookie-epoch-123456789", revokedAt: undefined as number | undefined }));+vi.mock("@/lib/auth/device-store", () => ({ currentSessionPolicy: async () => ({ epoch: security.epoch }), getApprovedDevice: async () => ({ role: security.role, approvedAt: 1, sessionsRevokedAt: security.revokedAt }) }));vi.mock("@/lib/auth/session-cookie", () => ({ configuredSessionCookieScope: () => "host" }));let root: string;let storage: typeof import("./connection-storage"), service: typeof import("./connection-service"), flow: typeof import("./google-oauth-flow"), native: typeof import("./google-native");const selector = { user: "test-owner", connection: "search" };-const actor = () => ({ deviceId: "test-device", cookieScope: "host", cookieEpoch: security.epoch, sessionExpiresAt: Date.now() + 600000 });+const actor = () => ({ deviceId: "test-device", cookieScope: "host", cookieEpoch: security.epoch, sessionIssuedAt: Date.now(), sessionExpiresAt: Date.now() + 600000 });const tokenResponse = () => ({ access_token: "TEST_ACCESS_NOT_REAL_123456", refresh_token: "TEST_REFRESH_NOT_REAL_123456", token_type: "Bearer", expires_in: 3600, scope: "openid email https://www.googleapis.com/auth/webmasters.readonly" });const accountResponse = () => ({ sub: "test-user-123", email: "[email protected]", email_verified: true });const response = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });@@ -23,6 +23,7 @@ beforeEach(async () => {vi.resetModules(); vi.stubEnv("OS_INFRA_STORE", path.join(root, "infra.json")); vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("No real network in this test")));security.role = "owner"; security.epoch = "test-cookie-epoch-123456789";+ security.revokedAt = undefined;storage = await import("./connection-storage"); service = await import("./connection-service"); flow = await import("./google-oauth-flow"); native = await import("./google-native");await storage.mutateIntegrationState(d => {d.users[selector.user] = { id: selector.user, uid: "owner-uid", label: "Test owner", connections: {}, defaults: {} }; d.defaultUser = selector.user;@@ -69,14 +70,24 @@ describe("native Google lifecycle — isolated store, mocked Google", () => {await expect(flow.completeGoogleAuthorization(next.state, next.binding, "TEST_CODE_2")).rejects.toThrow("account_changed_disconnect_first");expect((await service.resolveIntegration("google-search-console", selector)).google?.account?.email).toBe("[email protected]");});- it.each(["expired", "rotated-app", "role-revoked", "epoch-revoked"])("rejects a %s flow before token exchange", async kind => {+ it.each(["expired", "rotated-app", "role-revoked", "epoch-revoked", "logged-out"])("rejects a %s flow before token exchange", async kind => {const start = await begin();if (kind === "expired") await storage.mutateIntegrationState(d => { d.users[selector.user].connections["google-search-console"].search.googlePending!.expiresAt = 1; });if (kind === "rotated-app") await storage.mutateIntegrationState(d => { d.users[selector.user].connections["google-oauth-app"].app.revision++; });if (kind === "role-revoked") security.role = "operator";if (kind === "epoch-revoked") security.epoch = "another-cookie-epoch-123456";+ if (kind === "logged-out") security.revokedAt = Date.now();await expect(flow.completeGoogleAuthorization(start.state, start.binding, "TEST_CODE")).rejects.toThrow(); expect(fetch).not.toHaveBeenCalled();});+ it("does not persist a grant when logout happens during token exchange", async () => {+ const start = await begin();+ vi.mocked(fetch).mockResolvedValueOnce(response(tokenResponse())).mockImplementationOnce(async () => {+ security.revokedAt = Date.now(); return response(accountResponse());+ });+ await expect(flow.completeGoogleAuthorization(start.state, start.binding, "TEST_CODE")).rejects.toThrow("expired_or_invalid");+ const connection = (await storage.readIntegrationState()).users[selector.user].connections["google-search-console"].search;+ expect(connection.googleOAuth).toBeUndefined(); expect(connection.googlePending).toBeUndefined();+ });it("denial consumes the authorization without losing an older grant", async () => {await authorize(); const next = await begin();await expect(flow.completeGoogleAuthorization(next.state, next.binding, undefined, true)).rejects.toThrow("consent_denied");diff --git a/lib/infra/google-oauth-flow.ts b/lib/infra/google-oauth-flow.tsindex 03b28302..06832ea9 100644--- a/lib/infra/google-oauth-flow.ts+++ b/lib/infra/google-oauth-flow.ts@@ -1,6 +1,7 @@import { createHash, randomBytes } from "node:crypto";import { currentSessionPolicy, getApprovedDevice } from "@/lib/auth/device-store";import { configuredSessionCookieScope } from "@/lib/auth/session-cookie";+import { deviceSessionValid } from "@/lib/auth/live-session";import { mutateIntegrationState } from "./connection-storage";import { assertNotBusy, IntegrationError, type ConnectionSelector } from "./identity";import { googleTarget, googleApp } from "./google-native-state";@@ -15,7 +16,7 @@ const invalid = () => new IntegrationError("google_authorization_expired_or_invaexport async function assertGoogleActor(actor: GoogleActor) {if (!actor.deviceId || actor.sessionExpiresAt <= Date.now() || actor.cookieScope !== configuredSessionCookieScope()) throw invalid();const policy = await currentSessionPolicy(actor.cookieScope), device = await getApprovedDevice(actor.deviceId);- if (policy.epoch !== actor.cookieEpoch || device?.role !== "owner") throw invalid();+ if (policy.epoch !== actor.cookieEpoch || device?.role !== "owner" || !deviceSessionValid({ device_id: actor.deviceId, issued_at: actor.sessionIssuedAt, expires_at: actor.sessionExpiresAt, cookie_scope: actor.cookieScope, cookie_epoch: actor.cookieEpoch }, device)) throw invalid();}export async function beginGoogleAuthorization(provider: GoogleProvider, selection: ConnectionSelector, actor: GoogleActor) {await assertGoogleActor(actor);@@ -59,8 +60,8 @@ export async function completeGoogleAuthorization(state: string, binding: stringif (denied) throw new IntegrationError("google_consent_denied", 403);const tokens = await exchangeGoogleCode(lease.app.values, lease.provider, code!, pending.verifier);if (lease.c.googleOAuth?.subject && lease.c.googleOAuth.subject !== tokens.subject) throw new IntegrationError("google_account_changed_disconnect_first", 409);- await assertGoogleActor(pending.actor);- await mutateIntegrationState(d => {+ await mutateIntegrationState(async d => {+ await assertGoogleActor(pending.actor);const { c, app } = pinGoogle(d, lease);if (pending.expiresAt <= Date.now() || pending.redirectUri !== googleRedirectUri()) throw invalid();c.googleOAuth = { ...tokens, appConnection: app.id, appUid: app.uid, appRevision: app.revision, redirectUri: pending.redirectUri, state: "connected", updatedAt: Date.now() };diff --git a/lib/infra/google-routes.test.ts b/lib/infra/google-routes.test.tsindex f8b284c7..67957084 100644--- a/lib/infra/google-routes.test.ts+++ b/lib/infra/google-routes.test.ts@@ -7,7 +7,7 @@ vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));import { POST } from "@/app/api/integrations/google/start/route";import { GET } from "@/app/api/integrations/google/callback/route";const origin = "https://mso.example.test";-const actor = { role: "owner", session: { device_id: "test-device", cookie_scope: "host", cookie_epoch: "test-epoch-123456789", expires_at: 9999999999999 } };+const actor = { role: "owner", session: { device_id: "test-device", cookie_scope: "host", cookie_epoch: "test-epoch-123456789", issued_at: 1000, expires_at: 9999999999999 } };beforeEach(() => {vi.clearAllMocks(); vi.stubEnv("OS_PUBLIC_ORIGIN", origin);mocks.context.mockResolvedValue(actor);@@ -28,6 +28,7 @@ describe("native OAuth HTTP boundary", () => {it("sets a host-only finite HttpOnly/Secure/Lax binding without changing the main session cookie", async () => {const result = await POST(request()), cookie = result.headers.get("set-cookie")!;expect(result.status).toBe(200); expect(cookie).toContain("__Host-mso-google-test=");+ expect(mocks.begin).toHaveBeenCalledWith("google-search-console", { user: "test-owner", connection: "search" }, expect.objectContaining({ sessionIssuedAt: 1000 }));for (const attr of ["HttpOnly", "Secure", "SameSite=lax", "Max-Age=600", "Path=/"]) expect(cookie).toContain(attr);expect(cookie).not.toContain("Domain="); expect(cookie).not.toContain("session=");expect(result.headers.get("cache-control")).toContain("no-store");diff --git a/lib/managed-apps/session.test.ts b/lib/managed-apps/session.test.tsindex 63818bf6..1aaf5fd9 100644--- a/lib/managed-apps/session.test.ts+++ b/lib/managed-apps/session.test.ts@@ -34,3 +34,20 @@ it("refuses cockpit cookies, wrong-origin exchange and unauthenticated subresourexpect((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);});++it("does not extend the cockpit deadline when redeeming a ticket for an HTTP cookie", async () => {+ const auth=await import("./session");+ vi.useFakeTimers({toFake:["Date"]});+ try {+ const now=Date.now(), session={...payload(),expires_at:now+45_000};+ const ticket=auth.createManagedAppTicket("hermes",session,secret);+ vi.setSystemTime(now+15_000);+ 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].split(";")[0];+ const request=new Request("https://hermes.mso.example.com/",{headers:{cookie}});+ expect(await auth.managedAppSession(request,"hermes")).toMatchObject({issued_at:now,expires_at:now+45_000,parent_expires_at:now+45_000});+ vi.setSystemTime(now+45_001);+ expect(await auth.managedAppSession(request,"hermes")).toBeNull();+ } finally {vi.useRealTimers();}+});diff --git a/lib/managed-apps/session.ts b/lib/managed-apps/session.tsindex 092dae49..38a1072c 100644--- a/lib/managed-apps/session.ts+++ b/lib/managed-apps/session.ts@@ -7,19 +7,27 @@ 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;+type ManagedSession = SessionPayload & {parent_expires_at:number};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));+ const parentExpiry = (session as Partial<ManagedSession>).parent_expires_at ?? session.expires_at;+ const payload: ManagedSession = { ...session, parent_expires_at:parentExpiry, expires_at: Math.min(parentExpiry, now + TICKET_TTL) };+ return signSession(payload, 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 createManagedAppCookie(id: ManagedAppId, session: SessionPayload, secret: string, now=Date.now()): string {+ const parentExpiry = (session as Partial<ManagedSession>).parent_expires_at ?? session.expires_at;+ const payload: ManagedSession = { ...session, parent_expires_at:parentExpiry, expires_at:Math.min(parentExpiry,now + COOKIE_TTL) };+ return signSession(payload, 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 function verifyManagedAppSession(id: ManagedAppId, token: string, secret: string, kind: "ticket" | "cookie" = "cookie"): ManagedSession | null {+ try {+ const session = verifySession(token,key(id,kind,secret)) as ManagedSession|null;+ return session && Number.isFinite(session.parent_expires_at) && session.parent_expires_at >= session.expires_at ? session : null;+ } catch { return null; }}export async function managedAppSession(request: Request, id: ManagedAppId): Promise<SessionPayload | null> {const secret = process.env.OS_SESSION_SECRET ?? "";@@ -52,7 +60,7 @@ export async function gateManagedApp(request: NextRequest, id: ManagedAppId): Prconst 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 });+ result.cookies.set(MANAGED_APP_SESSION_COOKIE, createManagedAppCookie(id, session, secret), { httpOnly: true, secure: true, sameSite: "strict", path: "/", maxAge:Math.max(0,Math.floor((Math.min(session.parent_expires_at,Date.now()+COOKIE_TTL)-Date.now())/1000)) });return result;}if (await managedAppSession(request, id)) return null;diff --git a/lib/managed-apps/socket-policy.test.ts b/lib/managed-apps/socket-policy.test.tsindex 4fbc5234..7532f97d 100644--- a/lib/managed-apps/socket-policy.test.ts+++ b/lib/managed-apps/socket-policy.test.ts@@ -1,4 +1,4 @@-import { afterAll, expect, it } from "vitest";+import { afterAll, expect, it, vi } from "vitest";import { mkdtemp, rm } from "node:fs/promises";import os from "node:os";import path from "node:path";@@ -21,7 +21,7 @@ it("enforces session generation and live role/revocation for managed and viewerconst issued = Date.now(), policy = await devices.currentSessionPolicy("host");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 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({device_id:id,issued_at:issued,expires_at:issued+60_000}, process.env.OS_SESSION_SECRET!, issued)}` } });const decision = await socketPolicy(managed);expect(decision?.identity).toBe(id); expect(decision?.headers.cookie).toBeUndefined(); expect(decision?.headers.authorization).toBeUndefined();expect(await socketPolicy(viewer)).not.toBeNull();@@ -30,3 +30,19 @@ it("enforces session generation and live role/revocation for managed and viewerawait devices.setDeviceRole(id, "viewer"); expect(await socketPolicy(managed)).toBeNull();await devices.revokeDevice(id); expect(await socketPolicy(managed)).toBeNull();});++it("rejects managed-app and Camoufox WebSocket upgrades after their parent deadline", async () => {+ const id="c".repeat(32); await devices.approveDevice(id);+ const now=Date.now(), policy=await devices.currentSessionPolicy("host");+ const parent={device_id:id,issued_at:now,expires_at:now+45_000,cookie_scope:policy.scope,cookie_epoch:policy.epoch};+ const managedCookie=createManagedAppCookie("hermes",parent,process.env.OS_SESSION_SECRET!);+ const viewerCookie=createCamoufoxViewerCookie(parent,process.env.OS_SESSION_SECRET!);+ const managed=new NextRequest("https://hermes.mso.example.com/socket",{headers:{host:"hermes.mso.example.com",origin:"https://hermes.mso.example.com",upgrade:"websocket",cookie:`__Host-mso-managed-app=${managedCookie}`}});+ 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}=${viewerCookie}`}});+ expect(await socketPolicy(managed)).not.toBeNull(); expect(await socketPolicy(viewer)).not.toBeNull();+ vi.useFakeTimers({toFake:["Date"]});+ try {+ vi.setSystemTime(now+45_001);+ expect(await socketPolicy(managed)).toBeNull(); expect(await socketPolicy(viewer)).toBeNull();+ } finally {vi.useRealTimers();}+});diff --git a/lib/mcp/capability-runtime.ts b/lib/mcp/capability-runtime.tsindex c8284e6a..a52287b7 100644--- a/lib/mcp/capability-runtime.ts+++ b/lib/mcp/capability-runtime.ts@@ -40,6 +40,8 @@ export const msoCapabilityRuntime: CapabilityRuntime = {tenantContext: input.tenantContext,principal: input.principal,authorizationGrant: input.authorizationGrant,+ signal: input.signal,+ liveAuthorization: input.liveAuthorization,allowedTools: input.allowedTools,toolArgumentConstraints: input.toolArgumentConstraints,toolProfile: input.toolProfile,diff --git a/lib/mcp/dispatch-types.ts b/lib/mcp/dispatch-types.tsindex c2b2e562..f0d04828 100644--- a/lib/mcp/dispatch-types.ts+++ b/lib/mcp/dispatch-types.ts@@ -21,6 +21,8 @@ export interface RpcRequest {}export interface McpAgentContext {+ signal?:AbortSignal;+ liveAuthorization?:()=>Promise<void>;tenantContext?: TenantContext;principal?: string;authorizationGrant?: AuthorizationGrant;diff --git a/lib/mcp/durable-grant.ts b/lib/mcp/durable-grant.tsindex 0eb98c30..e51d0402 100644--- a/lib/mcp/durable-grant.ts+++ b/lib/mcp/durable-grant.ts@@ -13,7 +13,7 @@ function fingerprint(token: McpToken): string {return createHash("sha256").update(JSON.stringify(authority)).digest("hex");}-export function mcpAuthorizationGrant(token: McpToken & { hash: string }, resource: string): AuthorizationGrant {+export function mcpAuthorizationGrant(token: McpToken & { hash: string }, resource: string): Extract<AuthorizationGrant, { kind: "mcp" }> {const { hash, ...authority } = token;return { kind: "mcp", id: hash, resource, fingerprint: fingerprint(authority) };}diff --git a/lib/mcp/fs-credential-boundary.test.ts b/lib/mcp/fs-credential-boundary.test.tsindex 05cfd0eb..eb9db4dd 100644--- a/lib/mcp/fs-credential-boundary.test.ts+++ b/lib/mcp/fs-credential-boundary.test.ts@@ -4,21 +4,36 @@ import os from "node:os";import path from "node:path";vi.mock("server-only", () => ({}));vi.mock("@/lib/demo", () => ({ IS_DEMO: false }));-vi.mock("@/lib/auth/require-session", () => ({ requireSession: async (role: string) => role === "viewer" }));+vi.mock("@/lib/auth/require-session", () => ({ requireSession: async (role: string) => role === "viewer", getSessionContext: async () => ({ role: "viewer", session: { device_id: "candidate-viewer" } }) }));import { GET } from "@/app/api/v1/fs/read/route";import { READ_TOOLS } from "./tools-read";import { publicProjectMcpServers, readProjectMcpServers } from "@/lib/host/project-mcp-config";import { listDir } from "@/lib/host/fs-enumeration";+import { GET as candidateGet } from "@/app/api/v1/projects/candidates/route";+import { DISCOVERY_TOOLS } from "./tools-discovery";let home: string;beforeEach(async () => {home = await mkdtemp(path.join(os.tmpdir(), "mso-credential-read-"));vi.spyOn(os, "homedir").mockReturnValue(home);vi.stubEnv("OS_FS_READ_ROOTS", home);vi.stubEnv("OS_FS_ALLOW_SENSITIVE", undefined);+ vi.stubEnv("MSO_CANDIDATE_INDEX_DIR", path.join(home,"candidate-cache"));});afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); await rm(home, { recursive: true, force: true }); });const fsRead = READ_TOOLS.find(tool => tool.name === "fs_read")!;describe("Viewer HTTP and read-scope MCP credential boundary", () => {+ it("keeps credentials out of both candidate preview transports on fresh and cached requests", async () => {+ const project = path.join(home,"projects","candidate"); await mkdir(project,{recursive:true});+ for (const file of [".mcp.json",".netrc",".mcp.json.bak",".env.local","key.pem"]) await writeFile(path.join(project,file),"needle PRIVATE_CANDIDATE\n");+ await writeFile(path.join(project,"needle.txt"),"needle public source\n");+ const tool = DISCOVERY_TOOLS.find(row=>row.name==="project_candidate_search")!;+ for (let attempt=0; attempt<2; attempt++) {+ const response = await candidateGet(new Request("http://localhost/api/v1/projects/candidates?"+new URLSearchParams({project,q:"needle .mcp.json .netrc",limit:"40"})));+ expect(response.status).toBe(200);+ const http = await response.text(), mcp = JSON.stringify(await tool.run({project,query:"needle .mcp.json .netrc",limit:40},{scope:"read"}));+ for (const output of [http,mcp]) { expect(output).not.toContain("PRIVATE_CANDIDATE"); expect(output).toContain("needle public source"); }+ }+ });it("opens only an allowed root and omits the disallowed Home jump point", async () => {const project = path.join(home, "projects", "app");await mkdir(project, { recursive: true }); await writeFile(path.join(project, "README.md"), "public-project");diff --git a/lib/mcp/instructions.ts b/lib/mcp/instructions.tsindex 8a76aea1..9dfc1eb3 100644--- a/lib/mcp/instructions.ts+++ b/lib/mcp/instructions.ts@@ -68,5 +68,6 @@ export function mcpInstructions(scope: Scope, profile: McpToolProfile = "full",const projectBoundary = profile === "chatgpt"? " Project-owned MCP tools never join this catalog: use project_mcp_tools then project_mcp_call.": "";- return `${startup}${projectBoundary} Call agent_session_open for provider-neutral sessions, then send params._meta[mso/sessionId]. Use flow_catalog to inspect required inputs before flow_run; flow_status waits for completion. Session/workflow state is isolated per conversation. Prefer bounded tools and exec_job_start for long builds. Never expose hidden transcripts, credentials, or private chain-of-thought.`;+ const session = scope === "read" ? "Read agent_session_current for your conversation-bound session; agent_session_open and inbox acknowledgement require write scope." : "Call agent_session_open for provider-neutral sessions, then send params._meta[mso/sessionId]. Acknowledge inbox messages with local_agent_inbox_acknowledge.";+ return `${startup}${projectBoundary} ${session} Use flow_catalog to inspect required inputs before flow_run; flow_status waits for completion. Session/workflow state is isolated per conversation. Prefer bounded tools and exec_job_start for long builds. Never expose hidden transcripts, credentials, or private chain-of-thought.`;}diff --git a/lib/mcp/local-agent-two-way.test.ts b/lib/mcp/local-agent-two-way.test.tsindex 2da4e199..133da71f 100644--- a/lib/mcp/local-agent-two-way.test.ts+++ b/lib/mcp/local-agent-two-way.test.ts@@ -44,6 +44,36 @@ beforeAll(async () => {afterAll(() => rmSync(root, { recursive: true, force: true }));describe("two-way Local Agent MCP receive", () => {+ it("keeps read tokens from acknowledging messages or changing session metadata", async () => {+ const c = await store.createAgentSession(principal, "mcp", { title: "Read boundary", titleSource: "manual" });+ const inboxContext = { principal, sessionId: c.id };+ const receive = dispatch(call("local_agent_inbox", { wait_ms: 10000 }), "read", "mcp:c", inboxContext);+ await waitForSubscriber(c.id);+ await dispatch(call("local_agent_message_send", { target: c.name, message: "ACK_BOUNDARY" }), "write", "mcp:a", { principal, sessionId: a.id });+ const inbox = textResult<Array<{id:string}>>(await receive);+ expect(inbox).toHaveLength(1);+ const legacy = await dispatch(call("local_agent_inbox", { acknowledge: true }), "read", "mcp:c", inboxContext);+ expect(JSON.stringify(legacy)).toContain("local_agent_inbox_acknowledge");+ const denied = await dispatch(call("local_agent_inbox_acknowledge", { message_ids: [inbox[0].id] }), "read", "mcp:c", inboxContext);+ expect(denied.result).toMatchObject({isError:true});+ expect(textResult<unknown[]>(await dispatch(call("local_agent_inbox"), "read", "mcp:c", inboxContext))).toHaveLength(1);+ const opened = await dispatch(call("agent_session_open", { conversation_key: "read-boundary", title: "Changed" }), "read", "mcp:c", inboxContext);+ expect(opened.result).toMatchObject({isError:true});+ const acknowledged = await dispatch(call("local_agent_inbox_acknowledge", { message_ids: [inbox[0].id] }), "write", "mcp:c", inboxContext);+ expect(acknowledged.error).toBeUndefined();+ expect(textResult<unknown[]>(await dispatch(call("local_agent_inbox"), "read", "mcp:c", inboxContext))).toEqual([]);+ });+ it.each(["revoked", "disconnected"])("closes a %s inbox wait before serializing later private messages", async kind => {+ const c = await store.createAgentSession(principal, "mcp", { title: "Revocation boundary", titleSource: "manual" });+ const controller = new AbortController(); let authorized = true;+ const liveAuthorization = async () => { if (!authorized) throw new Error("authorization revoked"); };+ const receive = dispatch(call("local_agent_inbox", { wait_ms: 10000 }), "read", "mcp:c", { principal, sessionId: c.id, signal: controller.signal, liveAuthorization });+ await waitForSubscriber(c.id);+ if (kind === "revoked") authorized = false; else controller.abort(new Error("disconnected"));+ await dispatch(call("local_agent_message_send", { target: c.name, message: "PRIVATE_AFTER_REVOCATION" }), "write", "mcp:a", { principal, sessionId: a.id });+ expect(JSON.stringify(await receive)).not.toContain("PRIVATE_AFTER_REVOCATION");+ expect(events.localAgentSubscriberCount(c.id)).toBe(0);+ });it("keeps each foreground inbox receivable and wakes both ChatGPT-style sessions without spawning a worker", async () => {const contextA = { principal, sessionId: a.id };const contextB = { principal, sessionId: b.id };@@ -91,4 +121,20 @@ describe("two-way Local Agent MCP receive", () => {subscribe.mockRestore();expect(Array.isArray(textResult<unknown[]>(response))).toBe(true);});+ it("discards a correlated private reply after wait authorization expires", async () => {+ const sender = await store.createAgentSession(principal,"mcp",{title:"Wait sender",titleSource:"manual"});+ const receiver = await store.createAgentSession(principal,"mcp",{title:"Wait receiver",titleSource:"manual"});+ const receiverContext = {principal,sessionId:receiver.id}, senderContext = {principal,sessionId:sender.id};+ const inbox = dispatch(call("local_agent_inbox",{wait_ms:10000}),"read","mcp:receiver",receiverContext);+ await waitForSubscriber(receiver.id);+ await dispatch(call("local_agent_message_send",{target:receiver.name,message:"REQUEST",intent:"request"}),"write","mcp:sender",senderContext);+ const message = textResult<Array<{id:string}>>(await inbox)[0];+ let live=true, entered=false;+ const waiting = dispatch(call("local_agent_request_wait",{request_message_id:message.id,timeout_ms:10000}),"read","mcp:sender",{...senderContext,liveAuthorization:async()=>{entered=true;if(!live)throw new Error("expired");}});+ while (!entered) await new Promise(resolve=>setTimeout(resolve,1));+ live=false;+ await dispatch(call("local_agent_reply",{reply_to_message_id:message.id,message:"PRIVATE_EXPIRED_REPLY"}),"write","mcp:receiver",receiverContext);+ const result = await waiting;+ expect(result.result).toMatchObject({isError:true}); expect(JSON.stringify(result)).not.toContain("PRIVATE_EXPIRED_REPLY");+ });});diff --git a/lib/mcp/store-token-admin.ts b/lib/mcp/store-token-admin.tsindex 9bafb71a..67a4abce 100644--- a/lib/mcp/store-token-admin.ts+++ b/lib/mcp/store-token-admin.ts@@ -3,6 +3,7 @@ import { sha256hex } from "./pkce";import type { Scope } from "./scope";import { commitMcpStore as write, mutateMcpStore as mutate, readMcpStore as read, sweepMcpStore as sweep } from "./store-state";import type { McpToken, TokenView } from "./store-types";+import { abortMcpTokenWaits } from "./token-waits";export async function listTokens(): Promise<TokenView[]> {const store = await read();@@ -36,6 +37,7 @@ export function revokeToken(id: string): Promise<boolean> {}}await write(store);+ for (const [hash,token] of Object.entries(store.tokens)) if (token.revokedAt) abortMcpTokenWaits(hash);return true;});}@@ -55,6 +57,7 @@ export function revokeAllTokens(): Promise<number> {if (!token.revokedAt) token.revokedAt = now;}if (count || Object.keys(store.refreshTokens).length) await write(store);+ for (const [hash,token] of Object.entries(store.tokens)) if (token.revokedAt) abortMcpTokenWaits(hash);return count;});}diff --git a/lib/mcp/store.test.ts b/lib/mcp/store.test.tsindex c72ae6e9..91d8088c 100644--- a/lib/mcp/store.test.ts+++ b/lib/mcp/store.test.ts@@ -8,6 +8,7 @@ process.env.OS_MCP_STORE = path.join(DIR, "mcp.json");const store = await import("./store");const { sha256hex } = await import("./pkce");+const { registerMcpTokenWait } = await import("./token-waits");beforeEach(async () => {await fs.rm(DIR, { recursive: true, force: true });@@ -69,7 +70,9 @@ describe("tokens", () => {it("stops validating the instant a token is revoked — this IS the kill switch", async () => {await mint("tok-revoke");const listed = (await store.listTokens())[0];+ const wait = registerMcpTokenWait(sha256hex("tok-revoke"));expect(await store.revokeToken(listed.id)).toBe(true);+ expect(wait.signal.aborted).toBe(true); wait.release();expect(await store.validateToken("tok-revoke")).toBeNull();expect(await store.revokeToken(listed.id)).toBe(false); // already dead});@@ -78,7 +81,9 @@ describe("tokens", () => {await mint("a");await mint("b");await mint("c");+ const waits = ["a","b","c"].map(raw => registerMcpTokenWait(sha256hex(raw)));expect(await store.revokeAllTokens()).toBe(3);+ for (const wait of waits) { expect(wait.signal.aborted).toBe(true); wait.release(); }expect(await store.validateToken("b")).toBeNull();expect(await store.revokeAllTokens()).toBe(0);});diff --git a/lib/mcp/token-waits.test.ts b/lib/mcp/token-waits.test.tsnew file mode 100644index 00000000..c0d5e0e9--- /dev/null+++ b/lib/mcp/token-waits.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from "vitest";+import { abortMcpTokenWaits, registerMcpTokenWait } from "./token-waits";+describe("MCP wait cancellation", () => {+ it("isolates tokens, cleans released waits, and propagates disconnects", () => {+ const parent = new AbortController(), a = registerMcpTokenWait("a",parent.signal), b = registerMcpTokenWait("b");+ parent.abort(); expect(a.signal.aborted).toBe(true); expect(b.signal.aborted).toBe(false); a.release();+ abortMcpTokenWaits("b"); expect(b.signal.aborted).toBe(true);+ const next = registerMcpTokenWait("b"); b.release();+ abortMcpTokenWaits("b"); expect(next.signal.aborted).toBe(true); next.release();+ const released = registerMcpTokenWait("c"); released.release(); abortMcpTokenWaits("c"); expect(released.signal.aborted).toBe(false);+ });+});diff --git a/lib/mcp/token-waits.ts b/lib/mcp/token-waits.tsnew file mode 100644index 00000000..6ca9eb24--- /dev/null+++ b/lib/mcp/token-waits.ts@@ -0,0 +1,19 @@+const waits = new Map<string, Set<AbortController>>();++export function registerMcpTokenWait(hash:string, parent?:AbortSignal) {+ const controller = new AbortController();+ const abort = () => controller.abort(parent?.reason);+ const set = waits.get(hash) ?? new Set<AbortController>();+ set.add(controller); waits.set(hash,set);+ parent?.addEventListener("abort",abort,{once:true});+ if (parent?.aborted) abort();+ return {signal:controller.signal, release:()=> {+ parent?.removeEventListener("abort",abort);+ set.delete(controller); if (!set.size && waits.get(hash) === set) waits.delete(hash);+ }};+}++export function abortMcpTokenWaits(hash:string): void {+ for (const controller of waits.get(hash) ?? []) controller.abort(new Error("MCP authorization revoked"));+ waits.delete(hash);+}diff --git a/lib/mcp/tools-agent-open.ts b/lib/mcp/tools-agent-open.tsindex d626c15d..c5995a96 100644--- a/lib/mcp/tools-agent-open.ts+++ b/lib/mcp/tools-agent-open.ts@@ -5,10 +5,11 @@ import { resolveProjectHint } from "@/lib/host/projects-api";import { type McpTool, S, str } from "./tool-kit";export const AGENT_OPEN_TOOLS: McpTool[] = [{- name: "agent_session_open", title: "Open Agent Session", scope: "read",+ name: "agent_session_open", title: "Open Agent Session", scope: "write",description: "Bootstrap an MSO application session for any AI provider. Reuse a unique conversation_key per conversation; this is metadata, never a secret. Send returned session.id as params._meta[mso/sessionId] or Mso-Session-Id on later calls. Optional exact project binds its working directory. The session is isolated to the authenticated principal.",chatgptDescription: "Open/resume a provider-neutral session using a stable conversation_key. Send session.id as _meta[mso/sessionId] on later calls.",- annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false, idempotentHint: true },+ audit: {action:"agent.session"},limit: { key: "agent.session.open", max: 20, windowMs: 60_000 },inputSchema: S({conversation_key: { type: "string", minLength: 1, maxLength: 256, description: "Optional stable identifier for this conversation. If omitted, a fresh session key is generated." },diff --git a/lib/mcp/tools-local-agents.ts b/lib/mcp/tools-local-agents.tsindex cd9d596f..c6273e9d 100644--- a/lib/mcp/tools-local-agents.ts+++ b/lib/mcp/tools-local-agents.ts@@ -9,6 +9,7 @@ import {} from "@/lib/agent/local-agent-standby";import { handoffOwnerLocalSession } from "@/lib/a2a/local-session";import { type McpRunContext, type McpTool, S, str } from "./tool-kit";+import { liveCapabilityContext } from "@/lib/capabilities/live-authority";function sessionContext(context: McpRunContext): { principal: string; sessionId: string } {if (!context.principal || !context.sessionId)@@ -16,6 +17,12 @@ function sessionContext(context: McpRunContext): { principal: string; sessionId:return { principal: context.principal, sessionId: context.sessionId };}+const waitAuthority = (context:McpRunContext,name:string,args:Record<string,unknown>) => async () => {+ context.signal?.throwIfAborted();+ if (context.liveAuthorization) await context.liveAuthorization();+ else if (context.authorizationGrant) await liveCapabilityContext(context,name,args);+};+export const LOCAL_AGENT_TOOLS: McpTool[] = [{name: "local_agents_list",@@ -141,6 +148,8 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [senderSessionId: current.sessionId,requestMessageId: str(a, "request_message_id"),timeoutMs: a.timeout_ms === undefined ? undefined : Number(a.timeout_ms),+ signal:context.signal,+ authorize:waitAuthority(context,"local_agent_request_wait",a),});},},@@ -175,21 +184,36 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [inputSchema: S({include_read: { type: "boolean" },limit: { type: "number", description: "1-200, default 100." },- acknowledge: { type: "boolean", description: "When true, mark returned messages read after retrieval." },+ acknowledge: { type: "boolean", description: "Deprecated. true is rejected; use local_agent_inbox_acknowledge with write scope." },wait_ms: { type: "number", minimum: 0, maximum: 20000, description: "Optional foreground receive wait in milliseconds. Default 0 preserves immediate inbox reads; max 20000." },}),run: async (a, context) => {const current = sessionContext(context);+ if (a.acknowledge === true) throw new Error("Use local_agent_inbox_acknowledge with write scope");const messages = await waitForLocalAgentInbox({principal: current.principal,sessionId: current.sessionId,includeRead: a.include_read === true,limit: Number(a.limit) || 100,waitMs: a.wait_ms === undefined ? 0 : Number(a.wait_ms),+ signal:context.signal,+ authorize:waitAuthority(context,"local_agent_inbox",a),});- if (a.acknowledge === true && messages.length)- await updateLocalAgentMessageState(current.principal, current.sessionId, messages.map((row) => row.id), "read");return messages;},},+ {+ name:"local_agent_inbox_acknowledge",+ description:"Mark exact messages in this conversation's inbox read. Requires write scope; read local_agent_inbox first and pass its exact message ids.",+ scope:"write",+ annotations:{readOnlyHint:false,idempotentHint:true,destructiveHint:false},+ audit:{action:"agent.message"},+ limit:{key:"local-agent.read",max:120,windowMs:60_000},+ inputSchema:S({message_ids:{type:"array",minItems:1,maxItems:200,items:{type:"string",pattern:"^localmsg_"}}},["message_ids"]),+ run:async (a,context) => {+ const current=sessionContext(context);+ if (!Array.isArray(a.message_ids) || !a.message_ids.length || a.message_ids.length>200 || a.message_ids.some(id=>typeof id!=="string" || !/^localmsg_[a-zA-Z0-9_-]+$/.test(id))) throw new Error("Exact local message ids required");+ return updateLocalAgentMessageState(current.principal,current.sessionId,a.message_ids,"read");+ },+ },];diff --git a/lib/mcp/tools-project-experience.test.ts b/lib/mcp/tools-project-experience.test.tsindex 77a5830d..e65ce1a7 100644--- a/lib/mcp/tools-project-experience.test.ts+++ b/lib/mcp/tools-project-experience.test.ts@@ -38,6 +38,21 @@ const tool = (name: string) => {};describe("Lovable-inspired MSO project surfaces", () => {+ it("redacts credential diffs in MCP text and structured output while preserving ordinary source", async () => {+ await writeFile(path.join(project,".mcp.json"), "PRIVATE_PATCH_MCP");+ await writeFile(path.join(project,".netrc"), "PRIVATE_PATCH_NETRC");+ await writeFile(path.join(project,"normal.txt"), "ordinary source\nAuthorization: Basic cHJpdmF0ZTpwYXNz\n");+ execFileSync("git",["add",".mcp.json",".netrc","normal.txt"],{cwd:project});+ const { dispatch } = await import("./dispatch");+ const output = await dispatch({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"project_diff",arguments:{project,staged:true}}},"read");+ const serialized = JSON.stringify(output);+ expect(serialized).not.toMatch(/PRIVATE_PATCH_MCP|PRIVATE_PATCH_NETRC|cHJpdmF0ZTpwYXNz/);+ expect(serialized).toContain("ordinary source"); expect(serialized).toContain('redacted');+ const result = output.result as {structuredContent:Record<string,unknown>};+ expect(result.structuredContent).not.toHaveProperty("unifiedDiff");+ execFileSync("git",["reset","--quiet"],{cwd:project});+ for (const name of [".mcp.json",".netrc","normal.txt"]) await rm(path.join(project,name));+ });it("project_get returns a canonical safe snapshot and project_diff keeps raw diff out of widget structured content", async () => {const got = await tool("project_get").run({ project }, { scope: "read" }) as Record<string, unknown>;expect(got).toMatchObject({ project: { name: "widget" }, package: { name: "widget", version: "2.0.0" }, database: { detected: false } });diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.tsindex 225bf33b..c9de40e2 100644--- a/lib/mcp/toolset.ts+++ b/lib/mcp/toolset.ts@@ -3,9 +3,9 @@ import type { Scope } from "./scope";import type { McpTool } from "./tool-kit";import { toolDescriptor, type McpToolProfile } from "./tool-contract";-export const MCP_SERVER_VERSION = "1.16.0";-export const MCP_TOOLSET_VERSION = "2026.10.09.1";-export const MCP_TOOLSET_CHANGED_AT = "2026-10-09T14:00:00+00:00";+export const MCP_SERVER_VERSION = "1.17.0";+export const MCP_TOOLSET_VERSION = "2026.10.10.1";+export const MCP_TOOLSET_CHANGED_AT = "2026-10-10T07:40:00+00:00";export type McpToolsetInfo = {serverVersion: string;diff --git a/lib/security/redact-text.test.ts b/lib/security/redact-text.test.tsnew file mode 100644index 00000000..c036e23b--- /dev/null+++ b/lib/security/redact-text.test.ts@@ -0,0 +1,9 @@+import { describe, expect, it } from "vitest";+import { redactText } from "./redact-text";+describe("complete authorization redaction", () => {+ it.each(["Authorization: Basic cHJpdmF0ZTpwYXNz", '"Authorization": "Digest username=private, response=secret"', "AUTHORIZATION=Custom private credential"])("scrubs the full header %s", input => {+ const output = redactText(input + "\nordinary source code");+ expect(output).not.toMatch(/cHJpdmF0ZTpwYXNz|username=private|response=secret|private credential/);+ expect(output).toContain("ordinary source code"); expect(redactText(output)).toBe(output);+ });+});diff --git a/lib/security/redact-text.ts b/lib/security/redact-text.tsindex 8abc0a10..998ce7f6 100644--- a/lib/security/redact-text.ts+++ b/lib/security/redact-text.ts@@ -8,9 +8,10 @@ const URL_CREDENTIALS = /\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s/@]+)@/gi;export function redactText(value: string, max = Number.POSITIVE_INFINITY): string {return value+ .replace(/\b(authorization["']?\s*[:=]\s*)("(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\r\n;\]}]+)/gi, (match, prefix: string, credential: string) => credential === "[redacted" ? match : `${prefix}${credential.startsWith('"') || credential.startsWith("'") ? credential[0] + "[redacted]" + credential[0] : "[redacted]"}`).replace(/\bbearer\s+[^\s,;]+/gi, "Bearer [redacted]").replace(URL_CREDENTIALS, "$1$2:[redacted]@")- .replace(SECRET, "$1$2[redacted]")+ .replace(SECRET, (match, key: string, separator: string, credential: string) => credential === "[redacted" ? match : `${key}${separator}[redacted]`).replace(SECRET_VALUE, "[redacted]").slice(0, max);}