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): enforce live delegated grants and bound provider and OAuth state
Abdurrahman Fakhrul75ce43f8f9d9
diff --git a/app/api/models/test/route.test.ts b/app/api/models/test/route.test.tsindex bfcd00ed..3a39497c 100644--- a/app/api/models/test/route.test.ts+++ b/app/api/models/test/route.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const resolveModelRef = vi.fn();const readOAuthBundle = vi.fn();@@ -6,6 +6,7 @@ const writeOAuthBundle = vi.fn();const codexModels = vi.fn();const ensureFreshCodex = vi.fn();const streamCodex = vi.fn();+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });vi.mock("@/lib/auth/require-session", () => ({ requireSession: vi.fn(async () => true) }));vi.mock("@/lib/config/store", () => ({@@ -24,6 +25,29 @@ vi.mock("@/lib/models", () => ({ resolveModel: vi.fn() }));vi.mock("@/lib/host/ssrf", () => ({ safeProviderFetch: vi.fn() }));describe("/api/models/test OpenAI Codex OAuth", () => {+ it("bounds custom-provider error bodies and applies a deadline before fetching", async () => {+ resolveModelRef.mockResolvedValue("fixture/model");+ const { resolveModel } = await import("@/lib/models");+ vi.mocked(resolveModel).mockResolvedValue({ protocol: "openai", baseUrl: "https://fixture.invalid/v1", apiKey: "synthetic", provider: "fixture", model: "model" } as never);+ const cancel = vi.fn();+ const fetch = vi.fn(async (_url, init) => {+ expect(init.signal).toBeInstanceOf(AbortSignal);+ return new Response(new ReadableStream({ pull(controller) { controller.enqueue(new TextEncoder().encode("denied ".repeat(1000))); }, cancel }), { status: 401 });+ });+ vi.stubGlobal("fetch", fetch);+ const { POST } = await import("./route");+ const response = await (await POST()).json();+ expect(response.ok).toBe(false); expect(response.error.length).toBeLessThan(160); expect(cancel).toHaveBeenCalled();+ });+ it("releases an unused successful connection-test response body", async () => {+ resolveModelRef.mockResolvedValue("fixture/model");+ const { resolveModel } = await import("@/lib/models");+ vi.mocked(resolveModel).mockResolvedValue({ protocol: "openai", baseUrl: "https://fixture.invalid/v1", apiKey: "synthetic", provider: "fixture", model: "model" } as never);+ const cancel = vi.fn();+ vi.stubGlobal("fetch", vi.fn(async () => new Response(new ReadableStream({ cancel }))));+ const { POST } = await import("./route");+ expect((await (await POST()).json()).ok).toBe(true); expect(cancel).toHaveBeenCalled();+ });beforeEach(() => {resolveModelRef.mockReset().mockResolvedValue("openai-codex/gpt-5.6-sol");const bundle = { kind: "oauth", access: "x", expires: Date.now() + 999999 };diff --git a/app/api/models/test/route.ts b/app/api/models/test/route.tsindex a2c44afa..fb1a1037 100644--- a/app/api/models/test/route.ts+++ b/app/api/models/test/route.ts@@ -6,6 +6,7 @@ import { resolveModel } from "@/lib/models";import { safeProviderFetch } from "@/lib/host/ssrf";import { codexModels, ensureFreshCodex } from "@/lib/ai/oauth/codex";import { streamCodex } from "@/lib/ai/codex-stream";+import { boundedProviderFetch, providerErrorText } from "@/lib/ai/provider-response";export const runtime = "nodejs";export const dynamic = "force-dynamic";@@ -60,22 +61,25 @@ export async function POST() {}try {+ const signal = AbortSignal.timeout(30_000);if (resolved.protocol === "anthropic") {const a = new Anthropic({apiKey: resolved.apiKey, baseURL: resolved.baseUrl,- ...(customProvider ? { fetch: safeProviderFetch } : {}),+ fetch: boundedProviderFetch(customProvider ? safeProviderFetch : fetch),});- await a.messages.create({ model: resolved.model, max_tokens: 1, messages: [{ role: "user", content: "ping" }] });+ await a.messages.create({ model: resolved.model, max_tokens: 1, messages: [{ role: "user", content: "ping" }] }, { signal });} else {const r = await (customProvider ? safeProviderFetch : fetch)(`${resolved.baseUrl}/chat/completions`, {method: "POST",headers: { "content-type": "application/json", authorization: `Bearer ${resolved.apiKey}` },body: JSON.stringify({ model: resolved.model, max_tokens: 1, messages: [{ role: "user", content: "ping" }] }),+ signal,});if (!r.ok) {- const t = await r.text().catch(() => "");+ const t = await providerErrorText(r, signal, 140).catch(() => "");return NextResponse.json({ ok: false, error: `HTTP ${r.status}${t ? `: ${t.slice(0, 140)}` : ""}` });}+ await r.body?.cancel();}return NextResponse.json({ ok: true, provider: resolved.provider, model: resolved.model });} catch (e) {diff --git a/app/api/v1/flows/route.ts b/app/api/v1/flows/route.tsindex 1ddad603..c07dd425 100644--- a/app/api/v1/flows/route.ts+++ b/app/api/v1/flows/route.ts@@ -7,6 +7,7 @@ import { flowStatus } from "@/lib/workflow/automation-engine";import { executeCapabilityCall } from "@/lib/capabilities/execute";import { maxScope } from "@/lib/mcp/scope";import { TOOLS_BY_NAME } from "@/lib/mcp/tools";+import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";export const runtime = "nodejs";export const dynamic = "force-dynamic";const headers = { "Cache-Control": "no-store, private" };@@ -31,7 +32,7 @@ export async function POST(req: NextRequest) {const principal = "cli:" + auth.session.device_id;const session = await createAgentSession(principal, "cli", { title: "Automation: " + String(args.flow ?? ""), titleSource: "auto" });const outcome = await executeCapabilityCall({ tool: TOOLS_BY_NAME.get(name)!, args: { ...args, ...(action === "run" ? {} : { action }) },- actor: principal, scope: maxScope(), context: { principal, sessionId: session.id } });+ actor: principal, scope: maxScope(), context: { principal, sessionId: session.id, authorizationGrant: { kind: "device", session: auth.session }, capabilities: msoCapabilityRuntime } });if (outcome.kind !== "success") throw new Error(outcome.message);return NextResponse.json(outcome.result, { headers });} catch (e) { return fail(e); }diff --git a/app/oauth/authorize/actions.test.ts b/app/oauth/authorize/actions.test.tsindex d512854f..cbcf9559 100644--- a/app/oauth/authorize/actions.test.ts+++ b/app/oauth/authorize/actions.test.ts@@ -77,4 +77,16 @@ describe("OAuth consent approval", () => {await expect(approve(form())).resolves.toEqual({ ok: false, error: "Not signed in." });expect(mocks.storeCode).not.toHaveBeenCalled();});++ it.each(["chatgpt-mso", "mcpc_pruned", "manual:pat:another-owner"])("rejects unregistered principal %s even with an HTTPS callback", async (id) => {+ mocks.getClient.mockResolvedValue(null);+ const data = form("https://attacker.example/callback"); data.set("client_id", id);+ expect(await approve(data)).toMatchObject({ ok: false, error: expect.stringContaining("register") });+ expect(mocks.storeCode).not.toHaveBeenCalled();+ });++ it("does not authorize a registered client at another callback", async () => {+ expect(await approve(form("https://attacker.example/callback"))).toMatchObject({ ok: false });+ expect(mocks.storeCode).not.toHaveBeenCalled();+ });});diff --git a/app/oauth/authorize/actions.ts b/app/oauth/authorize/actions.tsindex bd6e25b0..a3dbf485 100644--- a/app/oauth/authorize/actions.ts+++ b/app/oauth/authorize/actions.ts@@ -5,7 +5,6 @@ import { headers } from "next/headers";import { getClient, storeCode, CODE_TTL_MS } from "@/lib/mcp/store";import { randomToken, isAllowedRedirect } from "@/lib/mcp/pkce";import { parseScope, clampScope, mcpEnabled, type Scope } from "@/lib/mcp/scope";-import { detectMcpToolProfile } from "@/lib/mcp/client-profile";export type ApprovalResult =| { ok: false; error: string }@@ -49,11 +48,9 @@ export async function approve(form: FormData): Promise<ApprovalResult> {if (!expectedIssuer || issuer !== expectedIssuer || resource !== `${expectedIssuer}/mcp`) return { ok: false, error: "OAuth resource/issuer mismatch." };const client = await getClient(clientId);- // A manually configured client may not have a DCR record. That compatibility path- // is allowed — the redirect_uri is still https-checked above and the- // code is still bound to this exact client_id + redirect_uri at exchange. What- // is NOT allowed is a REGISTERED client redirecting somewhere it never declared.- if (client && !client.redirectUris.includes(redirectUri)) {+ // Only server-generated registrations own durable client principals.+ if (!client) return { ok: false, error: "This client must register before requesting authorization." };+ if (!client.redirectUris.includes(redirectUri)) {return { ok: false, error: "That redirect target is not registered for this client." };}@@ -64,7 +61,7 @@ export async function approve(form: FormData): Promise<ApprovalResult> {codeChallenge: challenge,scope,resource,- profile: client?.profile ?? detectMcpToolProfile({ clientId, name: client?.name, redirectUris: client?.redirectUris ?? [redirectUri] }),+ profile: client.profile,offlineAccess,expiresAt: Date.now() + CODE_TTL_MS,});diff --git a/app/oauth/authorize/page.tsx b/app/oauth/authorize/page.tsxindex a7f9d7b9..7d0b9183 100644--- a/app/oauth/authorize/page.tsx+++ b/app/oauth/authorize/page.tsx@@ -79,8 +79,11 @@ export default async function AuthorizePage({// Fail loudly and specifically BEFORE showing an Allow button — a consent screen// that approves a malformed request is worse than one that refuses to render.+ const client = await getClient(clientId);const problem =!clientId ? "The client did not send a client_id."+ : !client ? "This client must register before requesting authorization."+ : !client.redirectUris.includes(redirectUri) ? "That redirect target is not registered for this client.": !isAllowedRedirect(redirectUri) ? "The client's redirect target is missing, or is not https (or localhost).": method !== "S256" || !challenge ? "The client did not use PKCE with S256, which mso requires.": !issuer || resource !== expectedResource ? "The OAuth resource does not match this MSO MCP endpoint."@@ -95,8 +98,6 @@ export default async function AuthorizePage({);}- const client = await getClient(clientId);-// Where Cancel goes. Built HERE, from the redirect target this page already// validated, rather than in the browser — the deny path must not be the one// place a URL gets assembled from unchecked input.diff --git a/app/oauth/token/route.test.ts b/app/oauth/token/route.test.tsindex e7981322..e514ddb5 100644--- a/app/oauth/token/route.test.ts+++ b/app/oauth/token/route.test.ts@@ -1,7 +1,7 @@import { TenantDenied } from "@/lib/tenancy/authority";import { beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({ consumeCode: vi.fn(), storeGrant: vi.fn(), rotate: vi.fn(), random: vi.fn(), verify: vi.fn(() => true), limited: vi.fn(() => false) }));-vi.mock("@/lib/mcp/store", () => ({ consumeCode: mocks.consumeCode, storeOAuthGrant: mocks.storeGrant, rotateOAuthGrant: mocks.rotate, OAUTH_ACCESS_TOKEN_TTL_MS: 3_600_000 }));+vi.mock("@/lib/mcp/store", () => ({ consumeCode: mocks.consumeCode, storeOAuthGrant: mocks.storeGrant, rotateOAuthGrant: mocks.rotate, OAUTH_ACCESS_TOKEN_TTL_MS: 3_600_000, OAuthRefreshRateLimit: class extends Error {} }));vi.mock("@/lib/mcp/pkce", () => ({ verifyPkce: mocks.verify, randomToken: mocks.random }));vi.mock("@/lib/mcp/scope", () => ({ mcpEnabled: () => true, oauthScopeString: (scope: string, offline = false) => `${scope}${offline ? " offline_access" : ""}` }));vi.mock("@/lib/mcp/origin", () => ({ clientIp: () => "127.0.0.1", publicOrigin: () => "https://mso.example.test" }));@@ -11,6 +11,14 @@ const post = (body: Record<string, string>) => new Request("https://mso.example.describe("OAuth token endpoint", () => {beforeEach(() => { vi.clearAllMocks(); mocks.random.mockImplementation((prefix: string) => `${prefix}${mocks.random.mock.calls.length}`); mocks.verify.mockReturnValue(true); mocks.storeGrant.mockReset(); });+ it("returns 429 for family rotation limits regardless of forwarded IPs", async () => {+ const { OAuthRefreshRateLimit } = await import("@/lib/mcp/store");+ mocks.rotate.mockRejectedValueOnce(new OAuthRefreshRateLimit("limited"));+ const request = post({ grant_type: "refresh_token", refresh_token: "fixture", client_id: "fixture" });+ request.headers.set("x-forwarded-for", "203.0.113.45");+ const response = await POST(request);+ expect(response.status).toBe(429); expect(await response.json()).toEqual({ error: "rate_limited" });+ });it("exchanges an authorization code into resource-bound access + refresh credentials", async () => {mocks.consumeCode.mockResolvedValue({ clientId: "chatgpt", redirectUri: "https://chatgpt.com/cb", codeChallenge: "challenge", scope: "exec", resource: "https://mso.example.test/mcp", profile: "chatgpt", offlineAccess: true });diff --git a/app/oauth/token/route.ts b/app/oauth/token/route.tsindex 9bad2a94..357a125c 100644--- a/app/oauth/token/route.ts+++ b/app/oauth/token/route.ts@@ -1,6 +1,6 @@import { readRequestJson, readRequestText, RequestBodyError } from "@/lib/security/request-body";import { TenantDenied } from "@/lib/tenancy/authority";-import { consumeCode, OAUTH_ACCESS_TOKEN_TTL_MS, rotateOAuthGrant, storeOAuthGrant } from "@/lib/mcp/store";+import { consumeCode, OAUTH_ACCESS_TOKEN_TTL_MS, rotateOAuthGrant, storeOAuthGrant, OAuthRefreshRateLimit } from "@/lib/mcp/store";import { verifyPkce, randomToken } from "@/lib/mcp/pkce";import { mcpEnabled, oauthScopeString } from "@/lib/mcp/scope";import { clientIp, publicOrigin } from "@/lib/mcp/origin";@@ -33,7 +33,9 @@ export async function POST(req: Request) {const resource = p.resource || expectedResource;if (resource !== expectedResource) return json({ error: "invalid_target" }, 400);const access = randomToken("mso_mcp_"), refresh = randomToken("mso_refresh_");- const rec = await rotateOAuthGrant({ oldRefreshToken: p.refresh_token, accessToken: access, refreshToken: refresh, label: `oauth · ${p.client_id.slice(0, 14)}`, clientId: p.client_id, resource });+ let rec;+ try { rec = await rotateOAuthGrant({ oldRefreshToken: p.refresh_token, accessToken: access, refreshToken: refresh, label: `oauth · ${p.client_id.slice(0, 14)}`, clientId: p.client_id, resource }); }+ catch (error) { if (error instanceof OAuthRefreshRateLimit) return json({ error: "rate_limited" }, 429); throw error; }if (!rec) return json({ error: "invalid_grant" }, 400);return json({ access_token: access, token_type: "Bearer", refresh_token: refresh, expires_in: Math.floor(OAUTH_ACCESS_TOKEN_TTL_MS / 1000), scope: oauthScopeString(rec.scope, rec.offlineAccess === true) });}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 3d58ab39..05ae95a2 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` enforce live delegated grants and bound provider and OAuth state- `security` close remaining repository scan trust boundaries**Tests**diff --git a/docs/MCP-HOW-TO.md b/docs/MCP-HOW-TO.mdindex 3db5180b..1fc1b563 100644--- a/docs/MCP-HOW-TO.md+++ b/docs/MCP-HOW-TO.md@@ -56,7 +56,8 @@ Pilih scope sesuai tugas: jangan menyebut seluruh MSO read-only hanya karena sat3. Buat app MCP dengan URL **`https://mso.example.com/mcp`**, transport **Streamable HTTP**,dan autentikasi **OAuth**. Gunakan domain instalasi sendiri, bukan `/api/mcp` atau `/sse`.4. Selesaikan login/consent pada domain MSO dan pilih scope minimum. Gunakan discovery/DCR- bila tersedia; untuk form Client ID manual, MSO mendukung `chatgpt-mso` tanpa client secret.+ untuk mendaftarkan callback URL dan mendapatkan Client ID unik tanpa client secret.+ Client ID manual lama `chatgpt-mso` perlu didaftarkan dan disambungkan ulang.Jangan memasukkan password MSO sebagai client secret dan jangan memilih No Authentication.5. Scan/refresh tools, simpan/publikasikan sesuai UI workspace, lalu aktifkan MSO pada percakapan.6. Uji dengan `@MSO tolong cek status VPS tanpa mengubah apa pun`.diff --git a/docs/MCP.md b/docs/MCP.mdindex bd911acc..aa3918de 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -89,9 +89,15 @@ label. Settings → MCP renders the live server URL, probes MCP/OAuth discovery,client-specific numbered steps. Use [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) forthe current field mapping, OAuth sequence, tool-snapshot refresh and troubleshooting.-Clients that support RFC 7591 Dynamic Client Registration can register through-`/oauth/register`. ChatGPT can also use the predefined public `chatgpt-mso` client without a-secret.+OAuth clients register their exact callback URLs through `/oauth/register` (RFC 7591).+Use the returned unique Client ID without a client secret. Unregistered/manual IDs,+including the former `chatgpt-mso` fallback and pruned registrations, cannot authorize;+register and reconnect instead. Client IDs are generated by the server and never reused.++Refresh grants have an absolute 90-day lifetime from consent. Rotation is limited to one+per 30 seconds per authenticated family, independent of proxy/IP headers. Expired access+tokens are pruned; recent replay detection retains at most 256 hashes per family. All+credential maps and the serialized private store have finite admission limits (4 MiB).A 404 from either well-known discovery document normally means `OS_MCP_ENABLED=1` is notactive in the **running** process (demo mode also forces MCP off).diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex b798f7fb..1b74cc8e 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,11 @@+## 2026-10-09: Close the eight findings from the independent security rescan++The completed rescan of `dac56bdf` found six Medium and two Low issues, with no High findings. Named MCP integrations now reuse the private endpoint-bound transport and recursive credential redaction rather than embedding bearer headers in an unbound server. OAuth consent accepts only server-generated registered client identities and their exact callbacks, preventing manual/pruned client IDs from aliasing another principal. The obsolete manual Client ID guidance is removed; clients must register and reconnect for new consent.++Async subagents, on-demand local workers and flows retain the initiating durable grant, profile, tool allowlist and argument constraints. Shared execution authority revalidates that grant and the deployment ceiling before every model round/action; browser flows retain their signed device session so revocation, demotion, logout, expiry and cookie-epoch changes stop later steps. External A2A workers reload their durable profile, intersect live scope and abort active profile tasks on token removal. Fixed-workflow lifecycle controls use one filter for both model advertisement and invocation.++OAuth rotation now has a persisted 30-second family limit, absolute 90-day grant expiry, expired-access pruning, bounded revoked/replay history and count/byte admission limits. Provider responses have server deadlines plus byte, SSE record/event, text, tool-count and aggregate-argument budgets; errors read only a bounded prefix and unused bodies are canceled. Regression tests exercise actual credential/device stores and mid-execution changes, reflected schema/result/error credentials, hostile provider streams, and registered/manual/pruned OAuth consent in the real browser release lane. Historical cloud findings remain scan evidence; closure requires independent reassessment of the new release.+## 2026-10-09: Keep the cookie browser proof in the mandatory browser release laneThe GitHub Verify job found that the new cookie proof needed Chromium before the unit/coverage lane installed a browser. The same unskipped proof now runs through the mandatory release browser configuration, after the existing Playwright preparation step. It still tests sibling Domain/path cookie injection in both insertion orders using the production helpers. Core verification remains usable on a fresh host; no runtime authorization, scanner gate, dependency or test assertion was relaxed.@@ -8,7 +16,7 @@ The October 8 scan at `fe9d66ed` identified seven separate gaps. Workflow OperatFilesystem reads inspect opened handles and streams retain those handles. Writes, mkdir, copy, move, recursive delete, enumeration and uploads hold directory descriptors; ZIP reads create a bounded credential-filtered private snapshot. Canonical configured roots do not gain authority when replaced with symlinks. Official Linux/WSL and macOS/Termux Linux guests provide the required descriptor primitives; unsupported native hosts fail closed. Managed-app cookies are HTTPS host-only `__Host-` cookies; legacy/duplicate names are refused and existing app sessions may need a new login. OAuth discovery ignores untrusted forwarded authority and is not cacheable. Local-agent SSE retains signed-session authority, checks before delivery and during idle periods, bounds its queue and releases subscriptions/timers on closure.-Regression tests exercise real ancestor exchanges, protected credential exchanges, pinned downloads/uploads, exact tag/raw-commit and missing-ref installations, both A2A transports and in-flight ceiling changes, Operator capability denial, cookie shadowing and signed-session revocation/demotion/logout/expiry/epoch rotation. Cloud reassessment is unavailable while the service reports exhausted credits; historical findings are not marked closed by local evidence. Runtime deployment requires the repository release path and a matching live build identity.+Regression tests exercise real ancestor exchanges, protected credential exchanges, pinned downloads/uploads, exact tag/raw-commit and missing-ref installations, both A2A transports and in-flight ceiling changes, Operator capability denial, cookie shadowing and signed-session revocation/demotion/logout/expiry/epoch rotation. Cloud reassessment subsequently launched and completed despite inconsistent quota availability metadata; historical findings are not marked closed by local evidence. Runtime deployment requires the repository release path and a matching live build identity.## 2026-10-08: Remove duplicate macOS chrome values from componentsdiff --git a/frontend/slices/os-settings/components/mcp-connection-section.tsx b/frontend/slices/os-settings/components/mcp-connection-section.tsxindex 3c1471c0..6ae5160e 100644--- a/frontend/slices/os-settings/components/mcp-connection-section.tsx+++ b/frontend/slices/os-settings/components/mcp-connection-section.tsx@@ -41,9 +41,8 @@ export function McpConnectionSection({ origin }: { origin: string }) {<McpCopyField label="Dynamic registration" value={endpoints.register} /><McpCopyField label="Protected-resource metadata" value={endpoints.protectedResource} /><McpCopyField label="Authorization-server metadata" value={endpoints.authorizationServer} />- <McpCopyField label="Public client ID (manual fallback)" value="chatgpt-mso" /></div>- <p className="mt-3 text-sm text-muted-foreground">OAuth authorization code with PKCE S256. No client secret. OAuth access tokens last one hour and renew through rotating refresh tokens, which expire after 90 days. Reconnect if renewal fails or access is revoked.</p>+ <p className="mt-3 text-sm text-muted-foreground">Register your app and its callback URL at the dynamic registration endpoint to obtain a unique Client ID. OAuth uses PKCE S256 without a client secret. Access tokens last one hour; refresh grants expire 90 days after authorization. Reconnect if renewal fails or access is revoked.</p></details></SettingsBlock></div>;diff --git a/lib/a2a/credentials-inbound.ts b/lib/a2a/credentials-inbound.tsindex 689c109a..e19bce60 100644--- a/lib/a2a/credentials-inbound.ts+++ b/lib/a2a/credentials-inbound.ts@@ -1,4 +1,5 @@import { expandOwnerStorePath } from "@/lib/owner-store-path.js";+import { abortA2AProfileTasks } from "./task-active";import {createHash,randomBytes,@@ -47,6 +48,11 @@ export async function listA2AInboundTokens(): Promise<.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));}+export async function getA2AInboundProfile(id: string): Promise<A2AInboundTokenSummary | null> {+ const row = (await readStore()).tokens.find((token) => token.id === id);+ return row ? summary(row) : null;+}+export async function createA2AInboundToken(label: string,scope: Scope | string = "read",@@ -87,8 +93,10 @@ export async function removeA2AInboundToken(id: string): Promise<boolean> {const store = await readStore();const before = store.tokens.length;store.tokens = store.tokens.filter((row) => row.id !== query);- if (store.tokens.length !== before)+ if (store.tokens.length !== before) {await writeA2APrivateStore(A2A_INBOUND_TOKEN_STORE_PATH, store);+ abortA2AProfileTasks(query);+ }return store.tokens.length !== before;});}diff --git a/lib/a2a/inbound-agent.test.ts b/lib/a2a/inbound-agent.test.tsindex ea8782a5..fa3832ca 100644--- a/lib/a2a/inbound-agent.test.ts+++ b/lib/a2a/inbound-agent.test.ts@@ -27,6 +27,16 @@ const { runInboundA2AAgent } = await import("./inbound-agent");afterEach(() => { vi.unstubAllEnvs(); vi.clearAllMocks(); });describe("inbound A2A model boundary", () => {+ it.each(["workflow_start", "workflow_finish", "workflow_cancel", "local_agent_standby"])("denies direct model emission of hidden fixed-workflow tool %s", async (name) => {+ const runtime = { ...capabilities, list: () => [{ name, description: "hidden", scope: "write" as const, inputSchema: { type: "object" as const, properties: {} } }] };+ let turn = 0;+ mocks.stream.mockImplementation(async ({ tools, emit }) => {+ expect(tools).toEqual([]);+ if (!turn++) emit("tool_use", { id: "attack", name, input: {} }); else emit("delta", "done");+ });+ const result = await runInboundA2AAgent({ prompt: "run", scope: "exec", principal: "standby", taskId: "fixed", signal: new AbortController().signal, capabilities: runtime, executionContext: { fixedWorkflow: true, workflowId: "fixed" } });+ expect(result.toolCalls).toEqual([{ name, ok: false }]); expect(mocks.invoke).not.toHaveBeenCalled();+ });it("rechecks a lowered deployment ceiling after the model selects an exec tool", async () => {vi.stubEnv("OS_MCP_MAX_SCOPE", "exec");let turn = 0;diff --git a/lib/a2a/inbound-agent.ts b/lib/a2a/inbound-agent.tsindex b208b612..f88d2b3d 100644--- a/lib/a2a/inbound-agent.ts+++ b/lib/a2a/inbound-agent.ts@@ -1,6 +1,7 @@import { allows, type Scope } from "@/lib/capabilities/scope";-import { clampScope } from "@/lib/capabilities/scope-policy";import type { CapabilityRuntime } from "@/lib/capabilities/runtime";+import type { CapabilityRunContext } from "@/lib/capabilities/tool";+import { liveCapabilityContext } from "@/lib/capabilities/live-authority";import {prepareSelectedModel,streamPreparedSelectedModel,@@ -90,15 +91,12 @@ function sessionHistory(session?: AgentSession): OaMsg[] {return out;}-function modelTools(runtime: CapabilityRuntime, scope: Scope, fixedWorkflow = false): OaTool[] {- return runtime.list(scope).filter(+function effectiveTools(runtime: CapabilityRuntime, context: CapabilityRunContext, fixedWorkflow = false) {+ const scope = context.scope;+ return runtime.list(scope, context).filter((tool) => allows(scope, tool.scope) && !EXTERNAL_TOOL_DENY.has(tool.name) &&- !(fixedWorkflow && FIXED_WORKFLOW_DENY.has(tool.name)),- ).map((tool) => ({- name: tool.name,- description: tool.description,- input_schema: tool.inputSchema,- }));+ !(fixedWorkflow && FIXED_WORKFLOW_DENY.has(tool.name)) && (!context.allowedTools || context.allowedTools.includes(tool.name)),+ );}function bounded(value: string, max = MAX_RESULT_BYTES): string {@@ -132,7 +130,8 @@ export async function runInboundA2AAgent(input: {signal: AbortSignal;onDelta?: (text: string) => void | Promise<void>;capabilities: CapabilityRuntime;- executionContext?: { workflowId?: string; workflowActor?: string; fixedWorkflow?: boolean };+ liveScope?: () => Promise<Scope>;+ executionContext?: { authority?: CapabilityRunContext; workflowId?: string; workflowActor?: string; fixedWorkflow?: boolean };}): Promise<{text: string;rounds: number;@@ -145,14 +144,17 @@ export async function runInboundA2AAgent(input: {];const toolCalls: Array<{ name: string; ok: boolean }> = [];let output = "";+ const live = async (name?: string, args?: Record<string, unknown>) => liveCapabilityContext({+ ...input.executionContext?.authority,+ principal: input.executionContext?.authority?.principal ?? input.principal,+ scope: await input.liveScope?.() ?? input.scope,+ capabilities: input.capabilities,+ }, name, args);for (let round = 1; round <= MAX_ROUNDS; round += 1) {- const scope = clampScope(input.scope);- const tools = modelTools(input.capabilities, scope, input.executionContext?.fixedWorkflow === true);- if (input.signal.aborted)- throw input.signal.reason instanceof Error- ? input.signal.reason- : new Error("A2A task canceled");+ const context = await live(), scope = context.scope;+ const tools: OaTool[] = effectiveTools(input.capabilities, context, input.executionContext?.fixedWorkflow === true).map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.inputSchema }));+ if (input.signal.aborted) throw input.signal.reason ?? new Error("A2A task canceled");let text = "";const uses: OaToolUse[] = [];await streamPreparedSelectedModel({@@ -170,39 +172,35 @@ export async function runInboundA2AAgent(input: {} else if (event === "tool_use") uses.push(data as OaToolUse);},});+ await live();+ if (input.signal.aborted) throw input.signal.reason ?? new Error("A2A task canceled");output = bounded(output + text, MAX_OUTPUT_BYTES);messages.push({ role: "assistant", text, toolUses: uses });if (!uses.length) return { text: output.trim(), rounds: round, toolCalls };const results: { id: string; content: string; isError?: boolean }[] = [];for (const call of uses) {- const effectiveScope = clampScope(input.scope);- const tool = input.capabilities.list(effectiveScope).find((entry) => entry.name === call.name);- if (!tool || EXTERNAL_TOOL_DENY.has(call.name) || !allows(effectiveScope, tool.scope)) {- results.push({- id: call.id,- content: "error: tool is unavailable to this A2A credential",- isError: true,- });+ const current = await live(call.name, call.input ?? {}), effectiveScope = current.scope;+ if (input.signal.aborted) throw input.signal.reason ?? new Error("A2A task canceled");+ const tool = effectiveTools(input.capabilities, current, input.executionContext?.fixedWorkflow === true).find((entry) => entry.name === call.name);+ if (!tool) {+ results.push({ id: call.id, content: "error: tool is unavailable to this A2A credential", isError: true });toolCalls.push({ name: call.name, ok: false });continue;}const invoked = await input.capabilities.invoke({+ ...(input.executionContext?.authority ? { ...current } : {}),name: call.name,args: call.input ?? {},scope: effectiveScope,actor: input.principal,- principal: input.principal,+ principal: current.principal,sessionId: input.taskId,...(input.executionContext?.workflowId ? { workflowId: input.executionContext.workflowId } : {}),...(input.executionContext?.workflowActor ? { workflowActor: input.executionContext.workflowActor } : {}),});const result = toolResultText(invoked);- results.push({- id: call.id,- content: result.content,- ...(result.isError ? { isError: true } : {}),- });+ results.push({ id: call.id, content: result.content, ...(result.isError ? { isError: true } : {}) });toolCalls.push({ name: call.name, ok: !result.isError });}messages.push({ role: "tool", results });diff --git a/lib/a2a/live-profile.test.ts b/lib/a2a/live-profile.test.tsnew file mode 100644index 00000000..e11b6685--- /dev/null+++ b/lib/a2a/live-profile.test.ts@@ -0,0 +1,52 @@+import { afterAll, beforeEach, expect, it, vi } from "vitest";+import { mkdtemp, readFile, writeFile, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+const stream = vi.hoisted(() => vi.fn());+vi.mock("@/lib/ai/selected-model-stream", () => ({ prepareSelectedModel: async () => ({}), streamPreparedSelectedModel: stream }));+const root = await mkdtemp(path.join(os.tmpdir(), "mso-a2a-live-profile-"));+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_MCP_MAX_SCOPE = "exec";+const creds = await import("./credentials-inbound");+const tasks = await import("./tasks");+const { executeInboundA2ATask } = await import("./server-execution");+const invoke = vi.fn(async () => ({ content: [{ type: "text" as const, text: "ok" }] }));+const capabilities = { invoke, list: () => [+ { name: "sys_stats", description: "read", scope: "read" as const, inputSchema: { type: "object" as const, properties: {} } },+ { name: "exec_run", description: "exec", scope: "exec" as const, inputSchema: { type: "object" as const, properties: {} } },+] };+beforeEach(() => { stream.mockReset(); invoke.mockClear(); });+afterAll(async () => { delete process.env.OS_A2A_INBOUND_TOKEN_STORE; delete process.env.OS_A2A_TASK_STORE; delete process.env.OS_MCP_MAX_SCOPE; await rm(root, { recursive: true, force: true }); });+async function start(label: string) {+ const { profile } = await creds.createA2AInboundToken(label, "exec");+ const task = await tasks.createA2ATask(`a2a:${profile.id}`, "exec", { messageId: label, role: "ROLE_USER", parts: [{ text: "inspect", mediaType: "text/plain" }] });+ return { profile, task };+}+it("revoking a bearer aborts its in-flight worker before the next action and preserves other tasks", async () => {+ const { profile, task } = await start("revoked");+ const other = new AbortController(); tasks.registerA2AActiveTask("other", other, "other-profile");+ stream.mockImplementationOnce(async ({ signal, emit }) => {+ await creds.removeA2AInboundToken(profile.id);+ expect(signal.aborted).toBe(true);+ emit("tool_use", { id: "denied", name: "exec_run", input: {} });+ });+ const result = await executeInboundA2ATask(task, profile, "inspect", undefined, capabilities);+ expect(result.status.state).toBe("TASK_STATE_CANCELED"); expect(invoke).not.toHaveBeenCalled();+ expect(other.signal.aborted).toBe(false); expect(tasks.isA2ATaskActive(task.id)).toBe(false);+ tasks.releaseA2AActiveTask("other");+});+it("intersects current profile scope before invocation and on the next catalog", async () => {+ const { profile, task } = await start("lowered");+ stream.mockImplementationOnce(async ({ emit }) => {+ const data = JSON.parse(await readFile(process.env.OS_A2A_INBOUND_TOKEN_STORE!, "utf8"));+ data.tokens.find((row: { id: string }) => row.id === profile.id).scope = "read";+ await writeFile(process.env.OS_A2A_INBOUND_TOKEN_STORE!, JSON.stringify(data));+ emit("tool_use", { id: "denied", name: "exec_run", input: {} });+ }).mockImplementationOnce(async ({ tools, emit }) => {+ expect(tools.map((tool: { name: string }) => tool.name)).toEqual(["sys_stats"]);+ emit("delta", "safe");+ });+ const result = await executeInboundA2ATask(task, profile, "inspect", undefined, capabilities);+ expect(result.status.state).toBe("TASK_STATE_COMPLETED"); expect(invoke).not.toHaveBeenCalled();+});diff --git a/lib/a2a/server-execution.ts b/lib/a2a/server-execution.tsindex d7f9248d..1564b554 100644--- a/lib/a2a/server-execution.ts+++ b/lib/a2a/server-execution.ts@@ -1,6 +1,9 @@import { audit } from "@/lib/host/audit-api";import type { AgentSession } from "@/lib/agent/session-types";import type { CapabilityRuntime } from "@/lib/capabilities/runtime";+import type { CapabilityRunContext } from "@/lib/capabilities/tool";+import { scopeRank } from "@/lib/capabilities/scope";+import { getA2AInboundProfile } from "./credentials-inbound";import type { A2AAuthenticatedProfile } from "./server-protocol";import { runInboundA2AAgent } from "./inbound-agent";import {@@ -20,6 +23,7 @@ import {import { a2aRpcOk, type A2ARpcId } from "./server-protocol";export interface A2AExecutionContext {+ authority?: CapabilityRunContext;workflowId?: string;workflowActor?: string;fixedWorkflow?: boolean;@@ -35,7 +39,7 @@ export async function executeInboundA2ATask(): Promise<A2ATaskRecord> {const principal = task.principal;const controller = new AbortController();- registerA2AActiveTask(task.id, controller);+ registerA2AActiveTask(task.id, controller, profile.local ? undefined : profile.id);let pendingDelta = "";let sentArtifact = false;try {@@ -59,7 +63,14 @@ export async function executeInboundA2ATask(signal: controller.signal,capabilities,executionContext,+ async liveScope() {+ if (profile.local) return profile.scope;+ const current = await getA2AInboundProfile(profile.id);+ if (!current) throw new Error("A2A authorization revoked");+ return scopeRank(current.scope) < scopeRank(profile.scope) ? current.scope : profile.scope;+ },onDelta(chunk) {+ if (controller.signal.aborted) return;if (pendingDelta) {publishA2AEvent(task.id,diff --git a/lib/a2a/task-active.ts b/lib/a2a/task-active.tsindex 45f9f1e5..9667203f 100644--- a/lib/a2a/task-active.ts+++ b/lib/a2a/task-active.ts@@ -1,14 +1,18 @@const active = new Map<string, AbortController>();+const profiles = new Map<string, string>();export function registerA2AActiveTask(id: string,controller: AbortController,+ profileId?: string,): void {active.set(id, controller);+ if (profileId) profiles.set(id, profileId);}export function releaseA2AActiveTask(id: string): void {active.delete(id);+ profiles.delete(id);}export function isA2ATaskActive(id: string): boolean {@@ -18,3 +22,7 @@ export function isA2ATaskActive(id: string): boolean {export function abortA2AActiveTask(id: string): void {active.get(id)?.abort(new Error("A2A task canceled"));}++export function abortA2AProfileTasks(profileId: string): void {+ for (const [id, owner] of profiles) if (owner === profileId) active.get(id)?.abort(new Error("A2A authorization revoked"));+}diff --git a/lib/agent/delegated-authority.test.ts b/lib/agent/delegated-authority.test.tsnew file mode 100644index 00000000..e95b97cb--- /dev/null+++ b/lib/agent/delegated-authority.test.ts@@ -0,0 +1,62 @@+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";+const stream = vi.hoisted(() => vi.fn());+vi.mock("./session-store", () => ({ getAgentSession: async () => ({ id: "parent", cwd: "/fixture" }) }));+vi.mock("@/lib/ai/selected-model-stream", () => ({ prepareSelectedModel: async () => ({}), streamPreparedSelectedModel: stream }));+const root = await mkdtemp(path.join(os.tmpdir(), "mso-worker-grant-"));+process.env.OS_MCP_STORE = path.join(root, "mcp.json");+const store = await import("@/lib/mcp/store");+const state = await import("@/lib/mcp/store-state");+const { mcpAuthorizationGrant, authorizeDurableGrant } = await import("@/lib/mcp/durable-grant");+const { runSessionSubagent } = await import("./subagent-runner");+const { runInboundA2AAgent } = await import("@/lib/a2a/inbound-agent");+const invoke = vi.fn(async () => ({ content: [{ type: "text" as const, text: "ok" }] }));+const capabilities: CapabilityRuntime = { authorize: authorizeDurableGrant, invoke, list: () => [+ { name: "project_get", scope: "read", description: "read", inputSchema: { type: "object", properties: {} } },+ { name: "exec_run", scope: "exec", description: "exec", inputSchema: { type: "object", properties: {} } },+] };+beforeEach(() => { stream.mockReset(); invoke.mockClear(); vi.stubEnv("OS_MCP_MAX_SCOPE", "exec"); });+afterEach(() => vi.unstubAllEnvs());+afterAll(async () => { delete process.env.OS_MCP_STORE; await rm(root, { recursive: true, force: true }); });+async function authority() {+ await store.storeToken("worker", { label: "fixture", clientId: "worker", scope: "exec", allowedTools: ["project_get"], toolArgumentConstraints: { project_get: { project: ["approved"] } } });+ const token = (await store.validateToken("worker"))!;+ return { principal: "mcp-client:worker", scope: "exec" as const, authorizationGrant: mcpAuthorizationGrant(token, "https://fixture.invalid/mcp"), allowedTools: token.allowedTools, toolArgumentConstraints: token.toolArgumentConstraints, toolProfile: "chatgpt" as const, capabilities };+}+const workers = {+ subagent: async (context: Awaited<ReturnType<typeof authority>>) => runSessionSubagent({ principal: context.principal, parentSessionId: "parent", objective: "inspect", maxScope: "exec", capabilities, authority: context }),+ local: async (context: Awaited<ReturnType<typeof authority>>) => runInboundA2AAgent({ prompt: "inspect", principal: "a2a:local:target", scope: "exec", taskId: "task", signal: new AbortController().signal, capabilities, executionContext: { authority: context } }),+};+describe.each(Object.entries(workers))("%s live initiating authority", (_name, run) => {+ it("intersects the catalog and preserves the exact grant and argument restrictions", async () => {+ const context = await authority();+ stream.mockImplementationOnce(async ({ tools, emit }) => {+ expect(tools.map((tool: { name: string }) => tool.name)).toEqual(["project_get"]);+ emit("tool_use", { id: "one", name: "project_get", input: { project: "approved" } });+ }).mockImplementationOnce(async ({ emit }) => emit("delta", "done"));+ await run(context);+ expect(invoke).toHaveBeenCalledWith(expect.objectContaining({ principal: context.principal, authorizationGrant: context.authorizationGrant, allowedTools: ["project_get"], toolArgumentConstraints: context.toolArgumentConstraints, toolProfile: "chatgpt" }));+ });+ it.each(["revoked", "expired", "argument"])("stops a %s grant before the selected action", async (reason) => {+ const context = await authority();+ stream.mockImplementationOnce(async ({ emit }) => {+ if (reason === "revoked") await store.revokeToken((await store.validateToken("worker"))!.hash);+ if (reason === "expired") await state.mutateMcpStore(async () => { const data = await state.readMcpStore(); data.tokens[context.authorizationGrant.kind === "mcp" ? context.authorizationGrant.id : ""].expiresAt = Date.now() - 1; await state.commitMcpStore(data); });+ emit("tool_use", { id: "one", name: "project_get", input: { project: reason === "argument" ? "unapproved" : "approved" } });+ });+ await expect(run(context)).rejects.toThrow(/authorization/);+ expect(invoke).not.toHaveBeenCalled();+ });+ it("rechecks the deployment ceiling after model selection", async () => {+ const context = await authority(); context.allowedTools = undefined;+ // Remove the credential allowlist too, so only the changed ceiling can deny exec.+ await store.storeToken("worker", { label: "unrestricted", clientId: "worker", scope: "exec" });+ context.authorizationGrant = mcpAuthorizationGrant((await store.validateToken("worker"))!, "https://fixture.invalid/mcp");+ stream.mockImplementationOnce(async ({ emit }) => { vi.stubEnv("OS_MCP_MAX_SCOPE", "read"); emit("tool_use", { id: "one", name: "exec_run", input: {} }); });+ await expect(run(context)).rejects.toThrow(/authorization/);+ expect(invoke).not.toHaveBeenCalled();+ });+});diff --git a/lib/agent/subagent-runner.ts b/lib/agent/subagent-runner.tsindex 086a1e18..8b9fbdc4 100644--- a/lib/agent/subagent-runner.ts+++ b/lib/agent/subagent-runner.ts@@ -4,6 +4,8 @@ import { prepareSelectedModel, streamPreparedSelectedModel } from "@/lib/ai/seleimport type { OaMsg, OaTool, OaToolUse } from "@/lib/ai/openai-stream";import { allows, parseScope, type Scope } from "@/lib/capabilities/scope";import type { CapabilityRuntime } from "@/lib/capabilities/runtime";+import type { CapabilityRunContext } from "@/lib/capabilities/tool";+import { liveCapabilityContext } from "@/lib/capabilities/live-authority";const MAX_RESULT_BYTES = 64 * 1024;const DEFAULT_TURNS = 6;@@ -60,6 +62,7 @@ export async function runSessionSubagent(input: {timeoutMs?: number;explicitContext?: string;capabilities: CapabilityRuntime;+ authority?: CapabilityRunContext;}) {const parent = await getAgentSession(input.principal, input.parentSessionId);if (!parent) throw new Error("parent MSO Agent session not found");@@ -71,8 +74,8 @@ export async function runSessionSubagent(input: {const maxTurns = Math.max(1, Math.min(maxTurnsLimit(), Math.trunc(input.maxTurns || DEFAULT_TURNS)));const timeoutMs = Math.max(1_000, Math.min(MAX_TIMEOUT_MS, Math.trunc(input.timeoutMs || DEFAULT_TIMEOUT_MS)));const subagentId = `subagent_${randomUUID()}`;- const toolDefs = input.capabilities.list(maxScope).filter((tool) => allows(maxScope, tool.scope) && allowedTool(tool.name));- const tools: OaTool[] = toolDefs.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.inputSchema }));+ const authority = { ...input.authority, principal: input.principal, scope: maxScope, capabilities: input.capabilities };+ const toolDefs = (context: CapabilityRunContext) => input.capabilities.list(context.scope, context).filter((tool) => allows(context.scope, tool.scope) && allowedTool(tool.name) && (!context.allowedTools || context.allowedTools.includes(tool.name)));const prepared = await prepareSelectedModel();const messages: OaMsg[] = [{ role: "user", text: objective }];const toolCalls: Array<{ name: string; ok: boolean }> = [];@@ -81,6 +84,8 @@ export async function runSessionSubagent(input: {let finalText = "";try {for (let round = 1; round <= maxTurns; round += 1) {+ const live = await liveCapabilityContext(authority);+ const tools: OaTool[] = toolDefs(live).map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.inputSchema }));let text = "";const uses: OaToolUse[] = [];await streamPreparedSelectedModel({@@ -92,19 +97,22 @@ export async function runSessionSubagent(input: {else if (event === "tool_use") uses.push(data as OaToolUse);},});+ await liveCapabilityContext(authority);+ if (controller.signal.aborted) throw controller.signal.reason;if (text) finalText = bounded(text);messages.push({ role: "assistant", text, toolUses: uses });if (!uses.length) return { subagentId, name, status: "completed" as const, text: finalText.trim(), rounds: round, toolCalls, maxScope };const results: { id: string; content: string; isError?: boolean }[] = [];for (const call of uses) {- const tool = toolDefs.find((entry) => entry.name === call.name);+ const current = await liveCapabilityContext(authority, call.name, call.input ?? {});+ const tool = toolDefs(current).find((entry) => entry.name === call.name);if (!tool) {results.push({ id: call.id, content: "error: tool unavailable to this subagent", isError: true });toolCalls.push({ name: call.name, ok: false });continue;}const invoked = await input.capabilities.invoke({- name: call.name, args: call.input ?? {}, scope: maxScope,+ ...current, name: call.name, args: call.input ?? {},actor: `${input.principal}#${subagentId}`, principal: input.principal,});const outcome = resultText({ result: invoked });diff --git a/lib/ai/openai-stream.ts b/lib/ai/openai-stream.tsindex 29b6f8ef..24e0cc65 100644--- a/lib/ai/openai-stream.ts+++ b/lib/ai/openai-stream.ts@@ -1,4 +1,5 @@import { chatCompletionsProviderUsage } from "./provider-usage.mjs";+import { providerErrorText, PROVIDER_MAX_BYTES, PROVIDER_TIMEOUT_MS } from "./provider-response";// OpenAI-protocol streaming adapter for /api/assistant. Every provider in the// @rahmanef/models registry except Anthropic speaks the OpenAI Chat Completions// wire (POST {baseUrl}/chat/completions, `data: {choices:[{delta}]}` SSE lines@@ -88,7 +89,8 @@ export async function streamOpenAI(opts: {emit: (event: "delta" | "tool_use" | "done", data: unknown) => void;fetchImpl?: typeof fetch;}): Promise<void> {- const { resolved, messages, tools, system, signal, emit } = opts;+ const { resolved, messages, tools, system, emit } = opts;+ const signal = AbortSignal.any([opts.signal, AbortSignal.timeout(PROVIDER_TIMEOUT_MS)]);const fetchImpl = opts.fetchImpl ?? fetch;if (signal.aborted) return;@@ -104,7 +106,7 @@ export async function streamOpenAI(opts: {signal,});if (!res.ok || !res.body) {- const detail = await res.text().catch(() => "");+ const detail = await providerErrorText(res, signal).catch(() => "");throw new Error(`${resolved.provider} HTTP ${res.status}${detail ? `: ${detail.slice(0, 300)}` : ""}`);}@@ -115,15 +117,24 @@ export async function streamOpenAI(opts: {const calls = new Map<number, { id: string; name: string; args: string }>();let finish: string | null = null;let usage: ReturnType<typeof chatCompletionsProviderUsage> = null;+ let bytes = 0, events = 0, textBytes = 0, argumentBytes = 0;+ const abort = () => { void reader.cancel(signal.reason).catch(() => undefined); };+ signal.addEventListener("abort", abort, { once: true });+ try {reading: while (true) {- if (signal.aborted) { await reader.cancel().catch(() => {}); return; }+ if (signal.aborted) { if (opts.signal.aborted) return; throw signal.reason; }const { done, value } = await reader.read();+ if (signal.aborted) { if (opts.signal.aborted) return; throw signal.reason; }if (done) break;+ bytes += value.byteLength;+ if (bytes > PROVIDER_MAX_BYTES) throw new Error("provider response exceeds byte budget");buf += dec.decode(value, { stream: true });const lines = buf.split("\n");buf = lines.pop() ?? ""; // keep the trailing partial line+ if (Buffer.byteLength(buf) > 256 * 1024) throw new Error("provider SSE record exceeds budget");for (const raw of lines) {+ if (++events > 16_384 || Buffer.byteLength(raw) > 256 * 1024) throw new Error("provider SSE event budget exceeded");const line = raw.trim();if (!line.startsWith("data:")) continue; // skip blank lines / SSE commentsconst data = line.slice(5).trim();@@ -134,13 +145,24 @@ export async function streamOpenAI(opts: {if (chunk.usage) usage = chatCompletionsProviderUsage(chunk.usage);const choice = chunk.choices?.[0];if (!choice) continue;- if (choice.delta?.content) emit("delta", choice.delta.content);+ if (choice.delta?.content) {+ if (typeof choice.delta.content !== "string") throw new Error("invalid provider content");+ textBytes += Buffer.byteLength(choice.delta.content);+ if (textBytes > 1024 * 1024) throw new Error("provider text budget exceeded");+ emit("delta", choice.delta.content);+ }for (const tc of choice.delta?.tool_calls ?? []) {const idx = tc.index ?? 0;const cur = calls.get(idx) ?? { id: "", name: "", args: "" };if (tc.id) cur.id = tc.id;if (tc.function?.name) cur.name = tc.function.name;- if (tc.function?.arguments) cur.args += tc.function.arguments;+ if (tc.function?.arguments) {+ if (typeof tc.function.arguments !== "string") throw new Error("invalid provider tool arguments");+ argumentBytes += Buffer.byteLength(tc.function.arguments);+ if (argumentBytes > 256 * 1024) throw new Error("provider tool argument budget exceeded");+ cur.args += tc.function.arguments;+ }+ if (!calls.has(idx) && calls.size >= 64) throw new Error("provider tool call budget exceeded");calls.set(idx, cur);}if (choice.finish_reason) finish = choice.finish_reason;@@ -153,4 +175,8 @@ export async function streamOpenAI(opts: {emit("tool_use", { id: c.id || `call_${c.name}`, name: c.name, input });}emit("done", { stopReason: toStopReason(finish), ...(usage ? { usage } : {}) });+ } finally {+ signal.removeEventListener("abort", abort);+ await reader.cancel().catch(() => undefined); reader.releaseLock();+ }}diff --git a/lib/ai/provider-budget.test.ts b/lib/ai/provider-budget.test.tsnew file mode 100644index 00000000..64f18cee--- /dev/null+++ b/lib/ai/provider-budget.test.ts@@ -0,0 +1,52 @@+import { afterEach, expect, it, vi } from "vitest";+import { streamOpenAI } from "./openai-stream";+import { boundedProviderFetch, providerErrorText, PROVIDER_MAX_BYTES, PROVIDER_TIMEOUT_MS } from "./provider-response";+const resolved = { baseUrl: "https://fixture.invalid/v1", apiKey: "synthetic", model: "fixture", provider: "fixture" };+afterEach(() => vi.restoreAllMocks());+function source(pieces: string[]) {+ const cancel = vi.fn(); let index = 0;+ const body = new ReadableStream<Uint8Array>({ pull(controller) { if (index < pieces.length) controller.enqueue(new TextEncoder().encode(pieces[index++])); else controller.close(); }, cancel });+ return { body, cancel };+}+const run = (body: ReadableStream<Uint8Array>, status = 200) => streamOpenAI({ resolved, messages: [], system: "fixture", signal: new AbortController().signal, emit: vi.fn(), fetchImpl: vi.fn(async () => new Response(body, { status })) });+it.each(["partial", "arguments", "text", "events", "calls", "bytes"])("cancels an excessive %s response before buffering more", async (kind) => {+ const sse = (delta: object) => `data: ${JSON.stringify({ choices: [{ delta }] })}\n\n`;+ const pieces = kind === "partial" ? ["data: " + "x".repeat(256 * 1024)]+ : kind === "arguments" ? Array.from({ length: 6 }, () => sse({ tool_calls: [{ index: 0, function: { arguments: "x".repeat(50 * 1024) } }] }))+ : kind === "text" ? Array.from({ length: 12 }, () => sse({ content: "x".repeat(100 * 1024) }))+ : kind === "events" ? ["\n".repeat(16_385)]+ : kind === "calls" ? Array.from({ length: 65 }, (_, index) => sse({ tool_calls: [{ index, id: String(index), function: { name: "fixture", arguments: "{}" } }] }))+ : Array.from({ length: 90 }, () => ":" + "x".repeat(100 * 1024) + "\n");+ const { body, cancel } = source([...pieces, "never consumed"]);+ await expect(run(body)).rejects.toThrow(/budget/);+ expect(cancel).toHaveBeenCalled();+});+it("reads only a bounded error prefix and cancels a never-ending error body", async () => {+ const cancel = vi.fn(), pull = vi.fn((controller: ReadableStreamDefaultController<Uint8Array>) => controller.enqueue(new TextEncoder().encode("denied ".repeat(100))));+ const body = new ReadableStream({ pull, cancel });+ await expect(run(body, 401)).rejects.toThrow(/fixture HTTP 401/);+ expect(cancel).toHaveBeenCalled(); expect(pull.mock.calls.length).toBeLessThan(4);+});+it("enforces a server deadline while headers are withheld", async () => {+ const deadline = new AbortController();+ vi.spyOn(AbortSignal, "timeout").mockImplementation((ms) => { expect(ms).toBe(PROVIDER_TIMEOUT_MS); return deadline.signal; });+ const fetchImpl: typeof fetch = vi.fn(async (_url, init) => new Promise<Response>((_resolve, reject) => { init!.signal!.addEventListener("abort", () => reject(init!.signal!.reason)); queueMicrotask(() => deadline.abort(new Error("provider deadline"))); }));+ await expect(streamOpenAI({ resolved, messages: [], system: "", signal: new AbortController().signal, emit: vi.fn(), fetchImpl })).rejects.toThrow("deadline");+});+it("cancels a stalled body when the server deadline elapses", async () => {+ const deadline = new AbortController(), cancel = vi.fn();+ vi.spyOn(AbortSignal, "timeout").mockReturnValue(deadline.signal);+ const body = new ReadableStream<Uint8Array>({ pull() { queueMicrotask(() => deadline.abort(new Error("provider deadline"))); }, cancel });+ await expect(run(body)).rejects.toThrow("deadline"); expect(cancel).toHaveBeenCalled();+});+it("bounds SDK response bodies and releases the upstream reader", async () => {+ const { body, cancel } = source(["x".repeat(PROVIDER_MAX_BYTES + 1), "unread"]);+ const response = await boundedProviderFetch(vi.fn(async () => new Response(body)))("https://fixture.invalid");+ await expect(response.text()).rejects.toThrow(/budget/);+ await new Promise(resolve => setTimeout(resolve, 0)); expect(cancel).toHaveBeenCalled();+});+it("connection-test error reads use the same bounded prefix", async () => {+ const { body, cancel } = source(["x".repeat(500), "unread"]);+ expect((await providerErrorText(new Response(body), new AbortController().signal, 140)).length).toBe(140);+ expect(cancel).toHaveBeenCalled();+});diff --git a/lib/ai/provider-response.ts b/lib/ai/provider-response.tsnew file mode 100644index 00000000..53785a84--- /dev/null+++ b/lib/ai/provider-response.ts@@ -0,0 +1,39 @@+export const PROVIDER_TIMEOUT_MS = 120_000;+export const PROVIDER_MAX_BYTES = 8 * 1024 * 1024;++/** Read only a small error prefix and release the provider connection. */+export async function providerErrorText(response: Response, signal: AbortSignal, limit = 300): Promise<string> {+ if (!response.body) return "";+ const reader = response.body.getReader(), chunks: Uint8Array[] = [];+ let size = 0;+ const abort = () => { void reader.cancel(signal.reason).catch(() => undefined); };+ signal.addEventListener("abort", abort, { once: true });+ try {+ while (size < limit && !signal.aborted) {+ const { done, value } = await reader.read();+ if (done) break;+ const part = value.subarray(0, limit - size); chunks.push(part); size += part.length;+ }+ return new TextDecoder().decode(Buffer.concat(chunks, size));+ } finally {+ signal.removeEventListener("abort", abort);+ await reader.cancel().catch(() => undefined); reader.releaseLock();+ }+}++/** SDKs may buffer tool arguments before emitting them; cap the wire too. */+export function boundedProviderFetch(fetchImpl: typeof fetch): typeof fetch {+ return async (input, init) => {+ const response = await fetchImpl(input, init);+ if (!response.body) return response;+ let bytes = 0;+ const body = response.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({+ transform(chunk, controller) {+ bytes += chunk.byteLength;+ if (bytes > PROVIDER_MAX_BYTES) throw new Error("provider response exceeds byte budget");+ controller.enqueue(chunk);+ },+ }));+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });+ };+}diff --git a/lib/ai/selected-model-stream.ts b/lib/ai/selected-model-stream.tsindex 0f95c1c5..e70bfab9 100644--- a/lib/ai/selected-model-stream.ts+++ b/lib/ai/selected-model-stream.ts@@ -15,6 +15,7 @@ import { ensureFreshCodex } from "@/lib/ai/oauth/codex";import { streamCodex } from "@/lib/ai/codex-stream";import { streamOpenAI, type OaMsg, type OaTool } from "@/lib/ai/openai-stream";import { anthropicDonePayload } from "@/lib/ai/usage";+import { boundedProviderFetch, PROVIDER_TIMEOUT_MS } from "./provider-response";export type SelectedModelEvent = "delta" | "tool_use" | "done";export type SelectedModelEmit = (@@ -132,7 +133,8 @@ export async function streamPreparedSelectedModel(opts: {signal: AbortSignal;emit: SelectedModelEmit;}): Promise<void> {- const { prepared, messages, tools, system, signal, emit } = opts;+ const { prepared, messages, tools, system, emit } = opts;+ const signal = AbortSignal.any([opts.signal, AbortSignal.timeout(PROVIDER_TIMEOUT_MS)]);if (prepared.kind === "codex") {await streamCodex({bundle: prepared.bundle,@@ -161,7 +163,7 @@ export async function streamPreparedSelectedModel(opts: {const anthropic = new Anthropic({apiKey: prepared.resolved.apiKey,baseURL: prepared.resolved.baseUrl,- ...(prepared.customProvider ? { fetch: safeProviderFetch } : {}),+ fetch: boundedProviderFetch(prepared.customProvider ? safeProviderFetch : fetch),});const ai = anthropic.messages.stream({diff --git a/lib/capabilities/live-authority.ts b/lib/capabilities/live-authority.tsnew file mode 100644index 00000000..49d93593--- /dev/null+++ b/lib/capabilities/live-authority.ts@@ -0,0 +1,10 @@+import type { CapabilityRunContext } from "./tool";+import { clampScope } from "./scope-policy";++/** Async workers retain the initiating grant, never a snapshot of its validity. */+export async function liveCapabilityContext(context: CapabilityRunContext, name?: string, args?: Record<string, unknown>): Promise<CapabilityRunContext> {+ if (context.authorizationGrant && (!context.principal || !await context.capabilities?.authorize?.(context.authorizationGrant, context.principal, name, args))) {+ throw new Error("execution authorization revoked, expired or changed");+ }+ return { ...context, scope: clampScope(context.scope) };+}diff --git a/lib/capabilities/runtime.ts b/lib/capabilities/runtime.tsindex 702efd89..b839b087 100644--- a/lib/capabilities/runtime.ts+++ b/lib/capabilities/runtime.ts@@ -13,6 +13,9 @@ export interface CapabilityDescriptor {}export interface CapabilityInvocation {+ allowedTools?: readonly string[];+ toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>;+ toolProfile?: "full" | "chatgpt";tenantContext?: TenantContext;name: string;args?: Record<string, unknown>;@@ -33,6 +36,6 @@ export interface CapabilityInvocationResult {export interface CapabilityRuntime {authorize?(grant: AuthorizationGrant, principal: string, name?: string, args?: Record<string, unknown>): Promise<boolean>;- list(scope: Scope): CapabilityDescriptor[];+ list(scope: Scope, context?: Pick<CapabilityInvocation, "allowedTools" | "toolProfile">): CapabilityDescriptor[];invoke(input: CapabilityInvocation): Promise<CapabilityInvocationResult>;}diff --git a/lib/host/project-mcp-auth.test.ts b/lib/host/project-mcp-auth.test.tsindex 7db6a5d8..24c7524d 100644--- a/lib/host/project-mcp-auth.test.ts+++ b/lib/host/project-mcp-auth.test.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";const state = vi.hoisted(() => ({ values: { endpoint: "https://app.example/mcp", accessToken: "private-downstream-token", allowedTools: "read_project" } as Record<string, string>, calls: [] as Record<string, unknown>[], paging: "", discoverStatus: 400 }));-vi.mock("@/lib/infra/connection-service", () => ({ directConnectionValues: vi.fn(async () => state.values) }));+vi.mock("@/lib/infra/connection-service", () => ({ directConnectionValues: vi.fn(async () => state.values), resolveIntegration: async () => ({ user: "owner", id: "assistant" }) }));vi.mock("./ssrf", () => ({ safeProviderFetch: vi.fn(async (_url, init) => {const payload = JSON.parse(init.body);state.calls.push({ ...payload, auth: new Headers(init.headers).get("authorization") });@@ -14,18 +14,37 @@ vi.mock("./ssrf", () => ({ safeProviderFetch: vi.fn(async (_url, init) => {}if (state.values.accessToken === "revoked-token-value") return new Response("private error", { status: 401 });const result = payload.method === "initialize" ? { protocolVersion: "2025-11-25", capabilities: { tools: {} } }- : payload.method === "tools/list" ? { tools: [{ name: "read_project", inputSchema: { type: "object" } }, { name: "delete_project", inputSchema: { type: "object" } }] }- : { content: [{ type: "text", text: "echo private-downstream-token" }], structuredContent: { "private-downstream-token": "echoed key" } };+ : payload.method === "tools/list" ? { tools: [{ name: "read_project", description: "private-downstream-token", inputSchema: { type: "object", properties: { "private-downstream-token": { description: "private-downstream-token" } } }, _meta: { "private-downstream-token": "private-downstream-token" } }, { name: "delete_project", inputSchema: { type: "object" } }] }+ : { content: [{ type: "text", text: "echo private-downstream-token" }], structuredContent: { "private-downstream-token": "echoed key" }, _meta: { nested: ["private-downstream-token"] } };return new Response(JSON.stringify({ jsonrpc: "2.0", id: payload.id, result }), { headers: { "content-type": "application/json" } });}) }));import { callMcpServerTool, listMcpServerTools } from "./project-mcp-client";import { normalizeMcpEndpoint, parseMcpToolAllowlist } from "@/lib/infra/mcp-policy";import type { ProjectMcpServer } from "./project-mcp-config";+import { callNamedMcpConnectionTool, listNamedMcpConnectionTools } from "@/lib/infra/mcp-connection";const server: ProjectMcpServer = { name: "app", transport: "http", url: "https://app.example/mcp", headers: {}, oauthConfigured: false, integration: { user: "owner", connection: "assistant" } };beforeEach(() => { state.calls = []; state.paging = ""; state.discoverStatus = 400; state.values = { endpoint: "https://app.example/mcp", accessToken: "private-downstream-token", allowedTools: "read_project" }; });describe("private modular MCP connection", () => {+ it("uses the same private binding and recursive redaction for named integrations", async () => {+ const tools = await listNamedMcpConnectionTools({ user: "owner", connection: "assistant" });+ const result = await callNamedMcpConnectionTool({ user: "owner", connection: "assistant" }, "read_project", {});+ expect(JSON.stringify({ tools, result })).not.toContain("private-downstream-token");+ expect(JSON.stringify({ tools, result })).toContain("[redacted]");+ expect(state.calls.filter((row) => row.method === "tools/call")).toHaveLength(1);+ expect(state.calls.every((row) => row.auth === "Bearer private-downstream-token")).toBe(true);+ });+ it("redacts reflected RPC errors from the named integration path", async () => {+ const { safeProviderFetch } = await import("./ssrf");+ vi.mocked(safeProviderFetch).mockImplementationOnce(async (_url, init) => {+ const payload = JSON.parse(String(init?.body));+ return Response.json({ jsonrpc: "2.0", id: payload.id, error: { code: -1, message: "private-downstream-token" } });+ });+ const request = callNamedMcpConnectionTool({ user: "owner", connection: "assistant" }, "read_project", {});+ await expect(request).rejects.toThrow(/redacted/);+ await expect(request).rejects.not.toThrow(/private-downstream-token/);+ });it("falls back from HTTP 200 method-not-found when the private token is verified", async () => {state.discoverStatus = 200;const url = "https://app.example/mcp/http200";diff --git a/lib/infra/mcp-connection.test.ts b/lib/infra/mcp-connection.test.tsindex 788cc4d4..f36dd42b 100644--- a/lib/infra/mcp-connection.test.ts+++ b/lib/infra/mcp-connection.test.ts@@ -50,7 +50,9 @@ describe("named MCP integration execution", () => {const [server, name] = call.mock.calls[0]!;expect(name).toBe("jev_decide");expect(server.url).toBe("https://www.jevai.org/api/mcp");- expect(server.headers.Authorization).toBe("Bearer opaque-private-token-123456");+ expect(server.headers).toEqual({});+ expect(server.integration).toEqual({ user: "owner", connection: "jev" });+ expect(JSON.stringify(server)).not.toContain("opaque-private-token-123456");await expect(callNamedMcpConnectionTool({ user: "owner", connection: "jev" }, "other", {})).rejects.toMatchObject({ code: "mcp_tool_not_allowed" });});diff --git a/lib/infra/mcp-connection.ts b/lib/infra/mcp-connection.tsindex aac5b778..8be11e3c 100644--- a/lib/infra/mcp-connection.ts+++ b/lib/infra/mcp-connection.ts@@ -2,15 +2,16 @@ import { callMcpServerTool, listMcpServerTools } from "@/lib/host/project-mcp-climport type { ProjectMcpServer } from "@/lib/host/project-mcp-config";import { IntegrationError, type ConnectionSelector } from "./identity";import { normalizeMcpEndpoint, parseMcpToolAllowlist } from "./mcp-policy";-import { directConnectionValues } from "./connection-service";+import { directConnectionValues, resolveIntegration } from "./connection-service";-function serverFrom(values: Record<string, string>): ProjectMcpServer {+function serverFrom(values: Record<string, string>, integration: { user: string; connection: string }): ProjectMcpServer {if (!values.endpoint || !values.accessToken) throw new IntegrationError("required_fields_missing");return {name: "integration-mcp",transport: "http",url: normalizeMcpEndpoint(values.endpoint),- headers: { Authorization: `Bearer ${values.accessToken}` },+ headers: {},+ integration,oauthConfigured: false,};}@@ -22,14 +23,18 @@ function allowedTool(values: Record<string, string>, tool: string): void {}export async function listNamedMcpConnectionTools(selector: ConnectionSelector) {+ const selected = await resolveIntegration("mcp", selector);+ selector = { user: selected.user, connection: selected.id };const values = await directConnectionValues("mcp", selector);- const tools = await listMcpServerTools(serverFrom(values));+ const tools = await listMcpServerTools(serverFrom(values, { user: selected.user, connection: selected.id }));const allowed = parseMcpToolAllowlist(values.allowedTools);return allowed ? tools.filter((tool) => allowed.includes(tool.name)) : tools;}export async function callNamedMcpConnectionTool(selector: ConnectionSelector, tool: string, args: Record<string, unknown>) {+ const selected = await resolveIntegration("mcp", selector);+ selector = { user: selected.user, connection: selected.id };const values = await directConnectionValues("mcp", selector);allowedTool(values, tool);- return callMcpServerTool(serverFrom(values), tool, args);+ return callMcpServerTool(serverFrom(values, { user: selected.user, connection: selected.id }), tool, args);}diff --git a/lib/mcp/capability-runtime.ts b/lib/mcp/capability-runtime.tsindex 8d89e596..c8284e6a 100644--- a/lib/mcp/capability-runtime.ts+++ b/lib/mcp/capability-runtime.ts@@ -5,6 +5,7 @@ import { boundedResultText } from "@/lib/capabilities/result-budget";import { isCapabilityDirectResult } from "@/lib/capabilities/tool";import type { CapabilityInvocationResult, CapabilityRuntime } from "@/lib/capabilities/runtime";import { TOOLS, TOOLS_BY_NAME } from "./tools";+import { toolAllowedForProfile } from "./tool-contract";function successResult(toolName: string, result: unknown): CapabilityInvocationResult {if (isCapabilityDirectResult(result))@@ -16,8 +17,8 @@ function successResult(toolName: string, result: unknown): CapabilityInvocationR/** Concrete MSO catalog composed once; MCP/A2A/subagents are adapters over it. */export const msoCapabilityRuntime: CapabilityRuntime = {authorize: authorizeDurableGrant,- list(scope) {- return TOOLS.filter((tool) => allows(scope, tool.scope)).map((tool) => ({+ list(scope, context) {+ return TOOLS.filter((tool) => allows(scope, tool.scope) && (!context?.allowedTools || context.allowedTools.includes(tool.name)) && toolAllowedForProfile(tool.name, context?.toolProfile ?? "full")).map((tool) => ({name: tool.name,description: tool.description,scope: tool.scope,@@ -39,6 +40,9 @@ export const msoCapabilityRuntime: CapabilityRuntime = {tenantContext: input.tenantContext,principal: input.principal,authorizationGrant: input.authorizationGrant,+ allowedTools: input.allowedTools,+ toolArgumentConstraints: input.toolArgumentConstraints,+ toolProfile: input.toolProfile,sessionId: input.sessionId,...(input.workflowActor ? { workflowActorOverride: input.workflowActor } : {}),capabilities: msoCapabilityRuntime,diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.tsindex f8983d41..72c0ebcc 100644--- a/lib/mcp/dispatch.test.ts+++ b/lib/mcp/dispatch.test.ts@@ -164,7 +164,7 @@ describe("local agent request dispatch", () => {const r = await dispatch(call("local_agent_request", { target: "milo", objective: "inspect this" }), "exec", "tester", context);expect(r.error).toBeUndefined();expect(localSessionMock.handoffOwnerLocalSession).toHaveBeenCalledWith(- context.principal, "milo", "inspect this", capabilities, context.sessionId,+ context.principal, "milo", "inspect this", capabilities, context.sessionId, { authority: expect.objectContaining({ principal: context.principal, sessionId: context.sessionId, scope: "exec" }) },);expect(JSON.stringify(r.result)).toContain("worker result");});diff --git a/lib/mcp/store-security.test.ts b/lib/mcp/store-security.test.tsindex 8e2180b6..1d758ce0 100644--- a/lib/mcp/store-security.test.ts+++ b/lib/mcp/store-security.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, beforeEach, afterAll } from "vitest";+import { describe, it, expect, beforeEach, afterAll, afterEach, vi } from "vitest";import { promises as fs } from "node:fs";import os from "node:os";import path from "node:path";@@ -14,9 +14,37 @@ beforeEach(async () => {afterAll(async () => {await fs.rm(DIR, { recursive: true, force: true });});+afterEach(() => vi.restoreAllMocks());describe("durable MCP credential isolation", () => {+ it("bounds many rotations, prunes expired access, preserves absolute expiry and rate limits the authenticated family", async () => {+ const clock = vi.spyOn(Date, "now").mockReturnValue(1_800_000_000_000);+ await store.storeOAuthGrant({ accessToken: "a0", refreshToken: "r0", clientId: "bounded", label: "fixture", scope: "exec", resource: "https://fixture.invalid/mcp", grantId: "bounded" });+ for (let index = 1; index <= 300; index++) {+ clock.mockReturnValue(1_800_000_000_000 + index * 30_001);+ await store.rotateOAuthGrant({ oldRefreshToken: `r${index - 1}`, accessToken: `a${index}`, refreshToken: `r${index}`, clientId: "bounded", label: "fixture", resource: "https://fixture.invalid/mcp" });+ }+ await expect(store.rotateOAuthGrant({ oldRefreshToken: "r300", accessToken: "denied", refreshToken: "denied-r", clientId: "bounded", label: "fixture", resource: "https://fixture.invalid/mcp" })).rejects.toBeInstanceOf(store.OAuthRefreshRateLimit);+ const serialized = await fs.readFile(process.env.OS_MCP_STORE!, "utf8"), data = JSON.parse(serialized);+ expect(Object.keys(data.tokens).length).toBeLessThanOrEqual(121);+ expect(Object.keys(data.spentRefreshTokens)).toHaveLength(256);+ expect(Object.values(data.refreshTokens)).toHaveLength(1);+ expect((Object.values(data.refreshTokens)[0] as { expiresAt: number }).expiresAt).toBe(1_800_000_000_000 + store.REFRESH_TOKEN_TTL_MS);+ expect(Buffer.byteLength(serialized)).toBeLessThan(200_000);+ clock.mockReturnValue(1_800_000_000_000 + store.REFRESH_TOKEN_TTL_MS + 1);+ expect(await store.rotateOAuthGrant({ oldRefreshToken: "r300", accessToken: "expired", refreshToken: "expired-r", clientId: "bounded", label: "fixture", resource: "https://fixture.invalid/mcp" })).toBeNull();+ });+ it("refuses count and byte admission without overwriting the private store", async () => {+ const state = await import("./store-state");+ const data = await state.readMcpStore();+ for (let i = 0; i < 65; i++) data.clients["fixture-" + i] = { name: "fixture", redirectUris: [], createdAt: Date.now() };+ await expect(state.commitMcpStore(data)).rejects.toThrow(/capacity/);+ expect(await state.readMcpStore()).toMatchObject({ clients: {} });+ data.clients = { huge: { name: "x".repeat(4 * 1024 * 1024), redirectUris: [], createdAt: Date.now() } };+ await expect(state.commitMcpStore(data)).rejects.toThrow(/size limit/);+ expect(await state.readMcpStore()).toMatchObject({ clients: {} });+ });it("assigns every PAT a distinct durable client principal", async () => {const first = await store.mintPatToken({ label: "client one", scope: "read", ttlDays: 1 });const second = await store.mintPatToken({ label: "client two", scope: "read", ttlDays: 1 });diff --git a/lib/mcp/store-state.ts b/lib/mcp/store-state.tsindex 0ee54222..6c9490ba 100644--- a/lib/mcp/store-state.ts+++ b/lib/mcp/store-state.ts@@ -7,11 +7,13 @@ import type { McpStore } from "./store-types";const STORE_PATH = expandOwnerStorePath(process.env.OS_MCP_STORE ?? path.join(os.homedir(), ".mso", "mcp.json"));const MAX_CLIENTS = 64;+const MAX_STORE_BYTES = 4 * 1024 * 1024;const empty = (): McpStore => ({ clients: {}, codes: {}, tokens: {}, refreshTokens: {}, spentRefreshTokens: {} });export async function readMcpStore(): Promise<McpStore> {let raw: string;try {+ if ((await fs.stat(STORE_PATH)).size > MAX_STORE_BYTES) throw new Error("MCP credential store size limit reached");raw = await fs.readFile(STORE_PATH, "utf8");} catch (error) {if ((error as NodeJS.ErrnoException).code === "ENOENT") return empty();@@ -28,9 +30,17 @@ export async function readMcpStore(): Promise<McpStore> {}async function writeMcpStore(store: McpStore): Promise<void> {+ sweepMcpStore(store);+ const limits = { clients: MAX_CLIENTS, codes: 256, tokens: 2048, refreshTokens: 256, spentRefreshTokens: 4096 };+ for (const [key, limit] of Object.entries(limits)) if (Object.keys(store[key as keyof McpStore]).length > limit) throw new Error("MCP credential store capacity reached");+ for (const clientId of new Set(Object.values(store.tokens).map((token) => token.clientId))) {+ if (Object.values(store.tokens).filter((token) => token.clientId === clientId).length > 256 || Object.values(store.refreshTokens).filter((token) => token.clientId === clientId).length > 16) throw new Error("MCP client credential capacity reached");+ }+ const serialized = JSON.stringify(store, null, 2);+ if (Buffer.byteLength(serialized) > MAX_STORE_BYTES) throw new Error("MCP credential store size limit reached");await fs.mkdir(path.dirname(STORE_PATH), { recursive: true, mode: 0o700 });const tmp = `${STORE_PATH}.${process.pid}.tmp`;- await fs.writeFile(tmp, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });+ await fs.writeFile(tmp, serialized, { encoding: "utf8", mode: 0o600 });await fs.rename(tmp, STORE_PATH);}@@ -48,12 +58,23 @@ export function sweepMcpStore(store: McpStore): McpStore {for (const [key, value] of Object.entries(store.codes)) {if (value.expiresAt < now) delete store.codes[key];}+ for (const [key, value] of Object.entries(store.tokens)) {+ if (value.expiresAt > 0 && value.expiresAt < now) delete store.tokens[key];+ }+ const revoked = Object.entries(store.tokens).filter(([, token]) => token.revokedAt).sort((a, b) => (b[1].revokedAt ?? 0) - (a[1].revokedAt ?? 0));+ for (const [key] of revoked.slice(256)) delete store.tokens[key];for (const [key, value] of Object.entries(store.refreshTokens)) {if (value.expiresAt < now || value.revokedAt) delete store.refreshTokens[key];}for (const [key, value] of Object.entries(store.spentRefreshTokens)) {if (value.expiresAt < now) delete store.spentRefreshTokens[key];}+ // Recent replay detection is retained; older hashes still cannot mint tokens.+ const families = new Map<string, string[]>();+ for (const [key, token] of Object.entries(store.spentRefreshTokens)) {+ const keys = families.get(token.grantId) ?? []; keys.push(key); families.set(token.grantId, keys);+ if (keys.length > 256) delete store.spentRefreshTokens[keys.shift()!];+ }return store;}diff --git a/lib/mcp/store-types.ts b/lib/mcp/store-types.tsindex c44b7e22..33c02f07 100644--- a/lib/mcp/store-types.ts+++ b/lib/mcp/store-types.ts@@ -40,6 +40,7 @@ export interface McpToken {}export interface McpRefreshToken {+ lastRotatedAt?: number;tenantBinding?: Readonly<TenantCredentialBinding>;grantId: string;clientId: string;diff --git a/lib/mcp/store.ts b/lib/mcp/store.tsindex 97d4a59d..8d33057c 100644--- a/lib/mcp/store.ts+++ b/lib/mcp/store.ts@@ -22,6 +22,7 @@ export const CODE_TTL_MS = 60_000;export const TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;export const OAUTH_ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000;export const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;+export class OAuthRefreshRateLimit extends Error {}export function registerClient(name: string, redirectUris: string[]): Promise<string> {return mutate(async () => {@@ -41,7 +42,8 @@ export function registerClient(name: string, redirectUris: string[]): Promise<st}export async function getClient(clientId: string): Promise<McpClient | null> {- return (await read()).clients[clientId] ?? null;+ const clients = (await read()).clients;+ return Object.hasOwn(clients, clientId) ? clients[clientId] : null;}export function storeCode(code: string, rec: McpCode): Promise<void> {@@ -148,6 +150,8 @@ export function rotateOAuthGrant(input: {const rec = store.refreshTokens[oldHash];if (!rec || rec.revokedAt || rec.expiresAt < Date.now() || rec.clientId !== captured.clientId || rec.resource !== captured.resource) return null;try { await authorizeMcpTenantGrant(rec); } catch (error) { if (error instanceof TenantDenied) return null; throw error; }+ const now = Date.now();+ if (rec.lastRotatedAt !== undefined && now - rec.lastRotatedAt < 30_000) throw new OAuthRefreshRateLimit("refresh grant rate limited");const tenant = tenantCredentialFields(rec);delete store.refreshTokens[oldHash];store.spentRefreshTokens[oldHash] = {@@ -156,7 +160,6 @@ export function rotateOAuthGrant(input: {resource: rec.resource,expiresAt: rec.expiresAt,};- const now = Date.now();store.tokens[sha256hex(captured.accessToken)] = {...tenant,label: captured.label,@@ -171,7 +174,8 @@ export function rotateOAuthGrant(input: {store.refreshTokens[sha256hex(captured.refreshToken)] = {...rec, ...tenant,createdAt: now,- expiresAt: now + REFRESH_TOKEN_TTL_MS,+ lastRotatedAt: now,+ expiresAt: rec.expiresAt,};await write(store);return rec;diff --git a/lib/mcp/tenant-grant-lifecycle.test.ts b/lib/mcp/tenant-grant-lifecycle.test.tsindex fcd42123..c0619334 100644--- a/lib/mcp/tenant-grant-lifecycle.test.ts+++ b/lib/mcp/tenant-grant-lifecycle.test.ts@@ -50,7 +50,9 @@ describe("actual OAuth store with synthetic tenant grants", () => {expect((await store.validateToken("fixture-access"))?.tenantBinding).toEqual(stamp);expect((await rotate())?.tenantBinding).toEqual(stamp);expect((await store.validateToken("fixture-access-two"))?.tenantBinding).toEqual(stamp);+ const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 30_001);expect((await rotate("fixture-refresh-two", "three"))?.tenantBinding).toEqual(stamp);+ clock.mockRestore();const disk = JSON.parse(await fs.readFile(root + "/synthetic-mcp.json", "utf8"));expect(disk.refreshTokens[sha256hex("fixture-refresh-three")].tenantBinding).toEqual(stamp);expect(await fs.readFile(root + "/synthetic-mcp.json", "utf8")).not.toContain("fixture-access-three");diff --git a/lib/mcp/tools-local-agents.test.ts b/lib/mcp/tools-local-agents.test.tsindex 12b6c389..050edb11 100644--- a/lib/mcp/tools-local-agents.test.ts+++ b/lib/mcp/tools-local-agents.test.ts@@ -8,6 +8,12 @@ const { LOCAL_AGENT_TOOLS } = await import("./tools-local-agents");const local = new Map(LOCAL_AGENT_TOOLS.map((tool) => [tool.name, tool]));describe("native local session agent MCP tools", () => {+ it("carries the initiating grant and restrictions into on-demand workers", async () => {+ const { handoffOwnerLocalSession } = await import("@/lib/a2a/local-session");+ const context = { principal: "mcp-client:fixture", sessionId: "parent", scope: "exec" as const, authorizationGrant: { kind: "mcp" as const, id: "a".repeat(64), resource: "https://fixture.invalid/mcp", fingerprint: "fixture" }, allowedTools: ["local_agent_request", "project_get"], toolArgumentConstraints: { project_get: { project: ["reviewed"] } }, capabilities: { list: () => [], invoke: vi.fn() } };+ await local.get("local_agent_request")!.run({ target: "target", objective: "inspect" }, context);+ expect(handoffOwnerLocalSession).toHaveBeenCalledWith(context.principal, "target", "inspect", context.capabilities, "parent", { authority: context });+ });it("keeps discovery/wait/inbox read-only, mailbox delivery below exec, and fresh-worker request explicit exec", () => {expect(local.get("local_agents_list")?.scope).toBe("read");expect(local.get("local_agent_inbox")?.scope).toBe("read");diff --git a/lib/mcp/tools-local-agents.ts b/lib/mcp/tools-local-agents.tsindex f8e0b92e..bb8c358d 100644--- a/lib/mcp/tools-local-agents.ts+++ b/lib/mcp/tools-local-agents.ts@@ -119,7 +119,7 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [run: async (a, context) => {const current = sessionContext(context);if (!context.capabilities) throw new Error("capability runtime unavailable for local-agent delegation");- const result = await handoffOwnerLocalSession(current.principal, str(a, "target"), str(a, "objective"), context.capabilities, current.sessionId);+ const result = await handoffOwnerLocalSession(current.principal, str(a, "target"), str(a, "objective"), context.capabilities, current.sessionId, { authority: context });return { mode: "durable_session_worker", ...result };},},diff --git a/lib/mcp/tools-subagents.ts b/lib/mcp/tools-subagents.tsindex be5f0954..9c4aa13d 100644--- a/lib/mcp/tools-subagents.ts+++ b/lib/mcp/tools-subagents.ts@@ -31,6 +31,7 @@ export const SUBAGENT_TOOLS: McpTool[] = [{timeoutMs: Number(a.timeout_ms) || undefined,explicitContext: typeof a.context === "string" ? a.context : undefined,capabilities: context.capabilities,+ authority: context,});},}];diff --git a/lib/workflow/automation-engine.ts b/lib/workflow/automation-engine.tsindex 819603e4..85444510 100644--- a/lib/workflow/automation-engine.ts+++ b/lib/workflow/automation-engine.ts@@ -1,4 +1,5 @@import { capabilityReportedFailure } from "@/lib/capabilities/result-outcome";+import { liveCapabilityContext } from "@/lib/capabilities/live-authority";import { randomUUID } from "node:crypto";import { executeCapabilityCall } from "@/lib/capabilities/execute";import { isCapabilityDirectResult, type CapabilityRunContext, type CapabilityTool } from "@/lib/capabilities/tool";@@ -40,7 +41,8 @@ async function execute(run: FlowRun, flow: AutomationFlow, input: Record<string,run.steps.push(row); run.updatedAt = new Date().toISOString(); await writeFlowRun(run);const started = Date.now();try {- const outcome = await executeCapabilityCall({ tool, args, scope: context.scope, actor: context.actor, context });+ const live = await liveCapabilityContext(context, tool.name, args);+ const outcome = await executeCapabilityCall({ tool, args, scope: live.scope, actor: live.actor, context: live });if (outcome.kind !== "success") throw new Error(outcome.message);const data = resultData(outcome.result);if (step.expect && canonical(flowValue(data, step.expect.path)) !== canonical(step.expect.equals)) throw new Error("flow expectation failed: " + step.expect.path);diff --git a/lib/workflow/automation-live-grant.test.ts b/lib/workflow/automation-live-grant.test.tsnew file mode 100644index 00000000..47213c96--- /dev/null+++ b/lib/workflow/automation-live-grant.test.ts@@ -0,0 +1,62 @@+import { afterAll, afterEach, beforeEach, expect, it, vi } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import path from "node:path";+import os from "node:os";+import type { CapabilityTool } from "@/lib/capabilities/tool";+const root = await mkdtemp(path.join(os.tmpdir(), "mso-flow-live-grant-"));+process.env.OS_DEVICE_STORE = path.join(root, "devices.json");+process.env.OS_AGENT_SESSIONS_DIR = path.join(root, "sessions");+process.env.OS_MCP_STORE = path.join(root, "mcp.json");+const devices = await import("@/lib/auth/device-store");+const { configuredSessionCookieScope } = await import("@/lib/auth/session-cookie");+const { authorizeDurableGrant, mcpAuthorizationGrant } = await import("@/lib/mcp/durable-grant");+const store = await import("@/lib/mcp/store");+const { parseFlow } = await import("./automation-schema");+const { startFlow, flowStatus } = await import("./automation-engine");+const { executeNode } = await import("./graph-runtime");+const id = "a".repeat(32);+const flow = parseFlow({ id: "fixture", description: "fixture", inputs: {}, steps: [+ { id: "first", tool: "project_mcp_call", arguments: { server: "fixture", tool: "fixture" } },+ { id: "second", tool: "project_mcp_call", arguments: { server: "fixture", tool: "fixture" } },+] });+beforeEach(async () => {+ await rm(root, { recursive: true, force: true });+ vi.stubEnv("OS_MCP_MAX_SCOPE", "exec"); vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", "");+ await devices.approveDevice(id); await devices.approveDevice("b".repeat(32));+});+afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); });+afterAll(async () => { delete process.env.OS_DEVICE_STORE; delete process.env.OS_AGENT_SESSIONS_DIR; delete process.env.OS_MCP_STORE; await rm(root, { recursive: true, force: true }); });+it.each(["revocation", "demotion", "logout", "epoch", "expiry"])("stops browser flow actions after actual device %s", async (reason) => {+ const policy = await devices.currentSessionPolicy(configuredSessionCookieScope());+ const context = { principal: "cli:" + id, sessionId: "fixture-session", scope: "exec" as const,+ authorizationGrant: { kind: "device" as const, session: { device_id: id, issued_at: Date.now(), expires_at: Date.now() + 1000, cookie_scope: policy.scope, cookie_epoch: policy.epoch } },+ capabilities: { authorize: authorizeDurableGrant, list: () => [], invoke: vi.fn() } };+ let calls = 0;+ const tool: CapabilityTool = { name: "project_mcp_call", scope: "exec", description: "fixture", inputSchema: { type: "object", properties: {} }, run: async () => {+ calls++;+ if (reason === "revocation") await devices.revokeDevice(id);+ if (reason === "demotion") await devices.setDeviceRole(id, "viewer");+ if (reason === "logout") await devices.invalidateDeviceSessions(id);+ if (reason === "epoch") { await devices.currentSessionPolicy("domain:fixture.invalid"); await devices.currentSessionPolicy("host"); }+ if (reason === "expiry") vi.spyOn(Date, "now").mockReturnValue(Date.now() + 1001);+ return { ok: true };+ } };+ const started = await startFlow(flow, "fixture", {}, "browser-" + reason, context, () => tool);+ const result = await flowStatus(started.id, context, 5000);+ expect(result.state).toBe("failed"); expect(result.error).toMatch(/authorization/); expect(calls).toBe(1);+});+it("checks a graph node's actual token constraints and revocation before invoking", async () => {+ await store.storeToken("fixture-token", { label: "fixture", clientId: "fixture", scope: "exec", allowedTools: ["project_get"], toolArgumentConstraints: { project_get: { project: ["approved"] } } });+ const token = (await store.validateToken("fixture-token"))!;+ const context = { principal: "mcp-client:fixture", sessionId: "fixture-session", scope: "exec" as const, authorizationGrant: mcpAuthorizationGrant(token, "https://fixture.invalid/mcp"), allowedTools: token.allowedTools, toolArgumentConstraints: token.toolArgumentConstraints,+ capabilities: { authorize: authorizeDurableGrant, list: () => [], invoke: vi.fn() } };+ const run = vi.fn(async () => ({ ok: true }));+ const tool: CapabilityTool = { name: "project_get", scope: "read", description: "fixture", inputSchema: { type: "object", properties: {} }, run };+ const graph = { id: "fixture", name: "fixture", metadata: {} } as never;+ const node = (project: string) => ({ id: "fixture", name: "fixture", type: "tool", config: { tool: "project_get", arguments: { project } } }) as never;+ await executeNode(node("approved"), {} as never, graph, {}, {}, context, () => tool);+ await expect(executeNode(node("other"), {} as never, graph, {}, {}, context, () => tool)).rejects.toThrow(/authorization/);+ await store.revokeToken(token.hash);+ await expect(executeNode(node("approved"), {} as never, graph, {}, {}, context, () => tool)).rejects.toThrow(/authorization/);+ expect(run).toHaveBeenCalledTimes(1);+});diff --git a/lib/workflow/automation.test.ts b/lib/workflow/automation.test.tsindex d21ef8cb..87de27fc 100644--- a/lib/workflow/automation.test.ts+++ b/lib/workflow/automation.test.ts@@ -1,4 +1,4 @@-import { afterAll, describe, expect, it, vi } from "vitest";+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";import { mkdtemp, rm } from "node:fs/promises";import path from "node:path";import os from "node:os";@@ -17,8 +17,25 @@ const flow = parseFlow({ id: "echo", description: "Echo two steps", inputs: { na{ id: "second", tool: "project_mcp_call", arguments: { server: "fixture", tool: "echo", arguments: { previous: { $ref: "steps.first.echo" } } }, expect: { path: "ok", equals: true } },] });afterAll(() => rm(directory, { recursive: true, force: true }));+afterEach(() => vi.unstubAllEnvs());describe("reusable project flows", () => {+ it.each(["revocation", "constraint", "ceiling"])("stops later steps after live %s changes", async (reason) => {+ let valid = true, calls = 0;+ const authorize = vi.fn(async (_grant, _principal, _name, args) => valid && (reason !== "constraint" || !args.arguments?.previous));+ const capabilities = { authorize, list: () => [], invoke: vi.fn() };+ const authority = { ...context, principal: "mcp-client:flow", capabilities,+ authorizationGrant: { kind: "mcp" as const, id: "a".repeat(64), fingerprint: "fixture", resource: "https://fixture.invalid/mcp" } };+ const tool: CapabilityTool = { name: "project_mcp_call", scope: "exec", description: "fixture", inputSchema: { type: "object", properties: {} }, run: async () => {+ calls++; if (reason === "ceiling") vi.stubEnv("OS_MCP_MAX_SCOPE", "read"); else if (reason !== "constraint") valid = false;+ return { ok: true, echo: "hello" };+ } };+ // The fixture adapter enforces the effective scope returned by the real engine.+ if (reason === "ceiling") capabilities.authorize = vi.fn(async () => process.env.OS_MCP_MAX_SCOPE !== "read");+ const started = await startFlow(flow, "project-a", { name: "hello" }, "live-" + reason, authority, () => tool);+ const done = await flowStatus(started.id, authority, 5000);+ expect(done.state).toBe("failed"); expect(calls).toBe(1);+ });it("runs ordered references once, binds project, rejects replay changes and isolates owners", async () => {const calls: Record<string, unknown>[] = [];const tool: CapabilityTool = { name: "project_mcp_call", scope: "exec", description: "fixture", inputSchema: { type: "object", properties: {} },diff --git a/lib/workflow/graph-authority.test.ts b/lib/workflow/graph-authority.test.tsindex 46035a64..fa9e14e0 100644--- a/lib/workflow/graph-authority.test.ts+++ b/lib/workflow/graph-authority.test.ts@@ -57,4 +57,12 @@ describe("live workflow execution authority", () => {it("never synthesizes unattended authority from an MCP client name", async () => {await expect(workflowExecutionContext({...context, principal: "mcp:client"}, {type: "schedule", receivedAt: "now"})).rejects.toThrow(/not execution grants/);});+ it("requires the initiating signed grant while a device remains approved", async () => {+ mocks.device.mockResolvedValue({ role: "owner" });+ const authorize = vi.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(false);+ const signed = { ...context, authorizationGrant: { kind: "device" as const, session: { device_id: "aaaaaaaaaaaaaaaa" } as never }, capabilities: { authorize, list: () => [], invoke: vi.fn() } };+ expect((await workflowExecutionContext(signed)).scope).toBe("exec");+ await expect(workflowExecutionContext(signed)).rejects.toThrow(/authorization/);+ expect(authorize).toHaveBeenCalledWith(signed.authorizationGrant, context.principal, undefined, undefined);+ });});diff --git a/lib/workflow/graph-authority.ts b/lib/workflow/graph-authority.tsindex fd228277..39d01414 100644--- a/lib/workflow/graph-authority.ts+++ b/lib/workflow/graph-authority.ts@@ -1,4 +1,5 @@import { getApprovedDevice } from "@/lib/auth/device-store";+import { liveCapabilityContext } from "@/lib/capabilities/live-authority";import { allows, scopeRank, type Scope } from "@/lib/capabilities/scope";import type { CapabilityRunContext } from "@/lib/capabilities/tool";import { configuredCapabilityCeiling } from "@/lib/capabilities/scope-policy";@@ -9,6 +10,7 @@ export async function workflowExecutionContext(context: CapabilityRunContext,trigger?: WorkflowGraphRun["trigger"],): Promise<CapabilityRunContext> {+ context = await liveCapabilityContext(context);const principal = context.principal ?? context.actor;if (!principal) throw new Error("workflow requires an authenticated principal");const unattended = trigger && ["schedule", "webhook", "channel"].includes(trigger.type);diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.tsindex c4dcdc66..9ec13689 100644--- a/lib/workflow/graph-runtime.ts+++ b/lib/workflow/graph-runtime.ts@@ -1,4 +1,5 @@import { requireWorkflowScope, workflowExecutionContext } from "./graph-authority";+import { liveCapabilityContext } from "@/lib/capabilities/live-authority";import path from "node:path";import { promises as fs } from "node:fs";import { capabilityReportedFailure } from "@/lib/capabilities/result-outcome";@@ -35,6 +36,7 @@ function resultData(result: unknown): unknown {async function callTool(name: string, args: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<unknown> {context = await workflowExecutionContext(context);const tool = resolve(name); if (!tool) throw new Error(`workflow tool unavailable: ${name}`);+ context = await liveCapabilityContext(context, name, args);const outcome = await executeCapabilityCall({ tool, args, scope: context.scope, actor: context.actor, context });if (outcome.kind !== "success") throw new Error(outcome.message); return resultData(outcome.result);}diff --git a/scripts/e2e/mcp-settings.mjs b/scripts/e2e/mcp-settings.mjsindex 04d66844..ed7f9bf3 100644--- a/scripts/e2e/mcp-settings.mjs+++ b/scripts/e2e/mcp-settings.mjs@@ -4,6 +4,7 @@ import path from "node:path";import { chmod } from "node:fs/promises";import { expect } from "@playwright/test";import AxeBuilder from "@axe-core/playwright";+import { createHash } from "node:crypto";async function capture(page, name) {if (!process.env.MSO_SCREENSHOT_DIR) return;@@ -136,3 +137,37 @@ export async function settingsAccessibilityJourney(page, base) {await expect(page.getByRole("switch", { name: "High contrast", exact: true })).toBeVisible();await expect(page.getByRole("group", { name: "Text size", exact: true }).getByRole("button", { pressed: true })).toHaveCount(1);}++export async function oauthRegistrationJourney(page, fixture) {+ const callback = fixture.base + "/oauth-fixture-callback", verifier = "v".repeat(43);+ const challenge = createHash("sha256").update(verifier).digest("base64url");+ const consent = (clientId, redirectUri = callback) => fixture.base + "/oauth/authorize?" + new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri, code_challenge: challenge, code_challenge_method: "S256", resource: fixture.base + "/mcp", state: "fixture-state", scope: "read" });+ for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }]) {+ await page.setViewportSize(viewport);+ await page.goto(consent("chatgpt-mso", "https://attacker.invalid/callback"));+ await expect(page.getByRole("heading", { name: "Cannot connect this client" })).toBeVisible();+ await expect(page.getByText("This client must register before requesting authorization.")).toBeVisible();+ await expect(page.getByRole("button", { name: "Allow", exact: true })).toHaveCount(0);+ const registration = await page.request.post(fixture.base + "/oauth/register", { data: { client_name: "Security fixture", redirect_uris: [callback] } });+ expect(registration.status()).toBe(201);+ const { client_id: clientId } = await registration.json(); expect(clientId).toMatch(/^mcpc_/);+ await page.goto(consent(clientId, "https://attacker.invalid/callback"));+ await expect(page.getByText("That redirect target is not registered for this client.")).toBeVisible();+ await expect(page.getByRole("button", { name: "Allow", exact: true })).toHaveCount(0);+ await page.goto(consent(clientId));+ await expect(page.getByRole("heading", { name: "Connect Security fixture to your VPS" })).toBeVisible();+ await page.getByRole("radio", { name: /^Read only/ }).check();+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);+ await page.getByRole("button", { name: "Allow", exact: true }).click();+ await expect(page).toHaveURL(new RegExp("/oauth-fixture-callback\\?code="));+ const url = new URL(page.url()); expect(url.searchParams.get("state")).toBe("fixture-state");+ const exchanged = await page.request.post(fixture.base + "/oauth/token", { form: { grant_type: "authorization_code", code: url.searchParams.get("code"), code_verifier: verifier, client_id: clientId, redirect_uri: callback, resource: fixture.base + "/mcp" } });+ expect(exchanged.status()).toBe(200); expect((await exchanged.json()).token_type).toBe("Bearer");+ // Replacing the isolated test store simulates a pruned registration, never owner data.+ await fixture.seedMcp();+ await page.goto(consent(clientId));+ await expect(page.getByText("This client must register before requesting authorization.")).toBeVisible();+ await expect(page.getByRole("button", { name: "Allow", exact: true })).toHaveCount(0);+ }+ console.log("PASS actual OAuth registered consent/exchange and manual/pruned callback denial on desktop/mobile");+}diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjsindex 695f118f..444c88d4 100644--- a/scripts/e2e/release.mjs+++ b/scripts/e2e/release.mjs@@ -3,7 +3,7 @@import { execFileSync } from "node:child_process";import { chromium, expect } from "@playwright/test";import AxeBuilder from "@axe-core/playwright";-import { mcpOwnerJourneys, mcpPublicJourney, settingsAccessibilityJourney } from "./mcp-settings.mjs";+import { mcpOwnerJourneys, mcpPublicJourney, oauthRegistrationJourney, settingsAccessibilityJourney } from "./mcp-settings.mjs";import { automationJourney } from "./automation.mjs";import { organizationJourney } from "./organization.mjs";import { workflowCanvasJourney } from "./workflow-canvas.mjs";@@ -141,6 +141,7 @@ try {expect((await call("/api/v1/fs/list?path=" + encodeURIComponent(fixture.dir))).status).toBe(200);await camoufoxConnectionJourney(page, fixture);await mcpOwnerJourneys(page, fixture);+ await oauthRegistrationJourney(page, fixture);await automationJourney(page, fixture);await organizationJourney(page, fixture);await workflowCanvasJourney(page, fixture);