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): protect public admission and OAuth registration trust
Abdurrahman Fakhrulda7772c070f1
diff --git a/.env.example b/.env.exampleindex 872ec891..2e51fcf6 100644--- a/.env.example+++ b/.env.example@@ -60,12 +60,13 @@ OS_SESSION_SECRET=# unset. When unset, MSO update paths use `ssh -oBatchMode=yes` for non-interactive# custom SSH remotes; set only when your private/fork origin needs another SSH command.# GIT_SSH_COMMAND=-# Number of trusted reverse-proxy hops in front of the app. The login rate-# limiter keys on the (N-from-last) x-forwarded-for hop, so a wrong value+# Number of trusted reverse-proxy hops in front of the app. Public rate+# limiters key on the (N-from-last) x-forwarded-for hop, so a wrong value# collapses every client into one bucket (too small N) or trusts spoofed# client headers (too large N).-# 1 = direct proxy (default). 2 = Cloudflare → nginx → app, etc.-# OS_TRUSTED_PROXY_HOPS=1+# Default 0 ignores forwarding headers. Set 1 for a direct trusted proxy or 2+# for Cloudflare → nginx → app only when direct origin access is firewalled.+# OS_TRUSTED_PROXY_HOPS=0# --- System Monitor Service Center (optional) ---@@ -361,10 +362,9 @@ OS_MCP_MAX_SCOPE=exec# Origin and need no entry. Exact origins only; this never weakens loopback/DNS-# rebinding protection. Example: https://claude.example,https://cursor.example# OS_MCP_BROWSER_ORIGINS=-# Optional exact Azure Blob hostnames for generic MCP file imports. `*.oaiusercontent.com`-# is trusted directly. OAuth clients with a verified `chatgpt.com` callback may also use-# ChatGPT's rotating oaisdmntpr<region> Azure family; a client name alone is insufficient.-# Other Azure hosts remain exact-only here. Comma-separated; wildcards are rejected.+# Optional exact Azure Blob hostnames for all MCP file imports. `*.oaiusercontent.com`+# is trusted directly. DCR client names and callbacks never grant host trust.+# Comma-separated; wildcards are rejected, including rotating ChatGPT Azure hosts.# OS_MCP_OPENAI_FILE_HOSTS=oaisdmntprseasia.blob.core.windows.net# Persistent semantic skill/recipe memory. The default is ~/.mso/skill-memory.json# (0600). Embeddings are deterministic and local — no API key, model download ordiff --git a/app/api/auth/login/route.test.ts b/app/api/auth/login/route.test.tsindex 9d0904a1..d43631df 100644--- a/app/api/auth/login/route.test.ts+++ b/app/api/auth/login/route.test.ts@@ -22,10 +22,10 @@ afterEach(() => {});describe("clientIp — XFF trusted-proxy hops", () => {- it("1 hop (default) → last XFF entry", () => {+ it("ignores forwarding headers unless proxy trust is explicitly configured", () => {expect(clientIp(reqWith({ "x-forwarded-for": "1.1.1.1, 2.2.2.2, 3.3.3.3" })),- ).toBe("3.3.3.3");+ ).toBe("unknown");});it("OS_TRUSTED_PROXY_HOPS=2 → second from last", () => {@@ -42,29 +42,34 @@ describe("clientIp — XFF trusted-proxy hops", () => {).toBe("1.1.1.1");});- it("hops exceed chain length → clamps to leftmost", () => {+ it("rejects a chain shorter than the configured trusted hops", () => {vi.stubEnv("OS_TRUSTED_PROXY_HOPS", "9");expect(clientIp(reqWith({ "x-forwarded-for": "1.1.1.1, 2.2.2.2" }))).toBe(- "1.1.1.1",+ "unknown",);});- it("invalid env value falls back to 1", () => {+ it("invalid env value fails closed", () => {vi.stubEnv("OS_TRUSTED_PROXY_HOPS", "not-a-number");expect(clientIp(reqWith({ "x-forwarded-for": "1.1.1.1, 2.2.2.2" })),- ).toBe("2.2.2.2");+ ).toBe("unknown");});- it("no XFF → falls back to x-real-ip then loopback", () => {- expect(clientIp(reqWith({ "x-real-ip": "5.5.5.5" }))).toBe("5.5.5.5");- expect(clientIp(reqWith({}))).toBe("127.0.0.1");+ it("does not trust x-real-ip or invent a loopback identity", () => {+ expect(clientIp(reqWith({ "x-real-ip": "5.5.5.5" }))).toBe("unknown");+ expect(clientIp(reqWith({}))).toBe("unknown");});- it("ignores empty XFF entries from trailing commas", () => {+ it("rejects empty, non-IP, fractional or oversized proxy attribution", () => {+ vi.stubEnv("OS_TRUSTED_PROXY_HOPS", "1");expect(clientIp(reqWith({ "x-forwarded-for": "1.1.1.1,," }))).toBe(- "1.1.1.1",+ "unknown",);+ expect(clientIp(reqWith({ "x-forwarded-for": "attacker" }))).toBe("unknown");+ expect(clientIp(reqWith({ "x-forwarded-for": "1".repeat(4097) }))).toBe("unknown");+ vi.stubEnv("OS_TRUSTED_PROXY_HOPS", "1.5");+ expect(clientIp(reqWith({ "x-forwarded-for": "1.1.1.1, 2.2.2.2" }))).toBe("unknown");});});@@ -83,6 +88,7 @@ describe("login admission budgets", () => {vi.stubEnv("OS_SESSION_SECRET", SECRET);vi.stubEnv("OS_LOGIN_PASSWORD", PASSWORD);vi.stubEnv("NEXT_PUBLIC_OS_DEMO", "0");+ vi.stubEnv("OS_TRUSTED_PROXY_HOPS", "1");vi.doMock("@/lib/auth/device-store", async (orig) => ({...(await orig<Record<string, unknown>>()),currentSessionPolicy: async (scope: string) => ({ scope, epoch: "epoch-0000000000000000", changedAt: 1 }),diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.tsindex 7029c221..5db3ab3a 100644--- a/app/api/auth/login/route.ts+++ b/app/api/auth/login/route.ts@@ -6,6 +6,8 @@ import { configuredSessionCookieScope, sessionCookieAttrs } from "@/lib/auth/sesimport { currentSessionPolicy, isApproved, isValidDeviceId, recordPending, touchApproved } from "@/lib/auth/device-store";import { audit } from "@/lib/host/audit-api";import { IS_DEMO } from "@/lib/demo";+import { clientIp } from "@/lib/host/request-ip";+export { clientIp } from "@/lib/host/request-ip";export const runtime = "nodejs";export const dynamic = "force-dynamic";@@ -25,31 +27,6 @@ let globalWindowStart = Date.now();let globalAttempts = 0;// Exported for tests — module-private otherwise.-export function clientIp(req: NextRequest): string {- // x-forwarded-for is a comma-separated trail; the leftmost entries are- // client-supplied and spoofable. The first hop WE trust is N from the end,- // where N = number of reverse proxies in front of this app (Cloudflare →- // nginx → app = 2). Default 1 = direct proxy. Direct access with a forged- // header still spoofs this, so :4005 must stay firewalled behind the proxy;- // the global limiter caps brute force anyway.- const xff = req.headers.get("x-forwarded-for");- if (xff) {- const hops = xff- .split(",")- .map((s) => s.trim())- .filter(Boolean);- if (hops.length > 0) {- const parsed = Number(process.env.OS_TRUSTED_PROXY_HOPS ?? "1");- const trustedN = Number.isFinite(parsed) && parsed >= 1 ? parsed : 1;- // trustedN=1 → last hop (current behavior). trustedN=2 → second from last.- // Clamp to the start of the list if N exceeds the chain length.- const idx = Math.max(0, hops.length - trustedN);- const hop = hops[idx];- if (hop) return hop;- }- }- return req.headers.get("x-real-ip") ?? "127.0.0.1";-}// Per-IP rejection never charges the global budget. Admission is reserved before// body reads/password comparison so distributed requests cannot keep testing guesses.diff --git a/app/mcp/route-protocol.test.ts b/app/mcp/route-protocol.test.tsindex 55b04018..50c5e502 100644--- a/app/mcp/route-protocol.test.ts+++ b/app/mcp/route-protocol.test.ts@@ -27,7 +27,7 @@ vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rateLimited, rateLivi.mock("@/lib/mcp/capability-runtime", () => ({ msoCapabilityRuntime: { list: () => [], invoke: vi.fn(async () => ({ content: [] })) } }));vi.mock("@/lib/mcp/tools", () => ({ TOOLS: [] }));vi.mock("@/lib/mcp/toolset", () => ({ toolsetInfo: () => ({}), MCP_SERVER_VERSION: "1.15.4" }));-vi.mock("@/lib/mcp/client-profile", () => ({ detectMcpToolProfile: () => "full", isTrustedOpenAiFileParamsClient: () => false }));+vi.mock("@/lib/mcp/client-profile", () => ({ detectMcpToolProfile: () => "full" }));vi.mock("@/lib/mcp/tool-contract", () => ({ visibleToolsForProfile: () => [] }));vi.mock("@/lib/agent/session-store", () => ({ findOrCreateAgentSessionForConversation: vi.fn() }));diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.tsindex 26a3ba0d..8c7824c7 100644--- a/app/mcp/route.test.ts+++ b/app/mcp/route.test.ts@@ -50,8 +50,6 @@ vi.mock("@/lib/mcp/tools", () => ({ TOOLS: [] }));vi.mock("@/lib/mcp/toolset", () => ({ toolsetInfo: () => ({}) }));vi.mock("@/lib/mcp/client-profile", () => ({detectMcpToolProfile: ({ name }: { name?: string }) => name === "ChatGPT" ? "chatgpt" : "full",- isTrustedOpenAiFileParamsClient: ({ redirectUris }: { redirectUris?: string[] }) =>- (redirectUris ?? []).some((uri) => uri.startsWith("https://chatgpt.com/")),}));vi.mock("@/lib/mcp/tool-contract", () => ({ visibleToolsForProfile: () => [] }));@@ -152,7 +150,7 @@ describe("/mcp request boundary", () => {it("binds tools/call to a hashed ChatGPT conversation session without forwarding the raw conversation id", async () => {const token = { hash: "e".repeat(64), scope: "read" as const, clientId: "client-session", label: "Session test" };mocks.validateToken.mockResolvedValue(token);- mocks.getClient.mockResolvedValue({ name: "ChatGPT", redirectUris: ["https://chatgpt.com/connector/oauth/test"] });+ mocks.getClient.mockResolvedValue({ name: "ChatGPT", redirectUris: ["https://attacker.invalid/callback", "https://chatgpt.com/connector/oauth/test"] });const { POST } = await import("./route");const rawConversation = "chatgpt-conversation-raw-secret-id";const body = { jsonrpc: "2.0", id: 7, method: "tools/call", params: {@@ -170,7 +168,6 @@ describe("/mcp request boundary", () => {authorizationGrant: expect.objectContaining({ kind: "mcp", id: token.hash, fingerprint: expect.stringMatching(/^[a-f0-9]{64}$/) }),sessionId: "20260901_100000_aabbccdd",toolProfile: "chatgpt",- trustedOpenAiFileParams: true,capabilities: expect.objectContaining({ list: expect.any(Function), invoke: expect.any(Function) }),});});diff --git a/app/mcp/route.ts b/app/mcp/route.tsindex 73114879..282ffc65 100644--- a/app/mcp/route.ts+++ b/app/mcp/route.ts@@ -10,7 +10,7 @@ import { publicOrigin, clientIp, mcpCorsHeaders, mcpRequestOriginAllowed } fromimport { rateLimited, rateLimitedUntrusted } from "@/lib/host/limits-api";import { TOOLS } from "@/lib/mcp/tools";import { toolsetInfo } from "@/lib/mcp/toolset";-import { detectMcpToolProfile, isTrustedOpenAiFileParamsClient } from "@/lib/mcp/client-profile";+import { detectMcpToolProfile } from "@/lib/mcp/client-profile";import { validateMcpRequest, modernMcpResult } from "@/lib/mcp/modern-http";import { MCP_SERVER_VERSION } from "@/lib/mcp/toolset";import { visibleToolsForProfile } from "@/lib/mcp/tool-contract";@@ -101,7 +101,6 @@ export async function POST(req: Request) {}const client = token.clientId ? await getClient(token.clientId).catch(() => null) : null;const toolProfile = token.profile ?? client?.profile ?? detectMcpToolProfile({ clientId: token.clientId, name: client?.name, redirectUris: client?.redirectUris });- const trustedOpenAiFileParams = isTrustedOpenAiFileParamsClient({ clientId: token.clientId, redirectUris: client?.redirectUris });const resolved = await resolveMcpSession(req, rpc, principal, token.label);if ("response" in resolved) return resolved.response;const headers = responseHeaders(req, mcpSessionHeaders(wire.modern ? undefined : resolved.responseSessionId));@@ -114,7 +113,6 @@ export async function POST(req: Request) {principal,...(resolved.agentSessionId ? { sessionId: resolved.agentSessionId } : {}),toolProfile,- trustedOpenAiFileParams,...(token.allowedTools ? { allowedTools: token.allowedTools } : {}),...(token.toolArgumentConstraints ? { toolArgumentConstraints: token.toolArgumentConstraints } : {}),capabilities: msoCapabilityRuntime,diff --git a/app/oauth/register/route.test.ts b/app/oauth/register/route.test.tsnew file mode 100644index 00000000..9bc16b88--- /dev/null+++ b/app/oauth/register/route.test.ts@@ -0,0 +1,31 @@+import { afterEach, expect, it, vi } from "vitest";+const registerClient = vi.hoisted(() => vi.fn(async () => "fixture-client"));+vi.mock("@/lib/mcp/store", () => ({ registerClient }));+afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); });++it("limits rotating forwarding headers before body/store work and reports protected capacity", async () => {+ vi.stubEnv("OS_MCP_ENABLED", "1");+ vi.stubEnv("NEXT_PUBLIC_OS_DEMO", "0");+ vi.stubEnv("OS_TRUSTED_PROXY_HOPS", "0");+ const clock = vi.spyOn(Date, "now").mockReturnValue(1_910_000_000_000);+ const { POST } = await import("./route");+ const request = (index: number) => new Request("https://fixture.invalid/oauth/register", {+ method: "POST", headers: { "x-forwarded-for": `198.51.100.${index}`, "content-type": "application/json" },+ body: JSON.stringify({ client_name: "ChatGPT", redirect_uris: ["https://attacker.invalid/callback", "https://chatgpt.com/connector/oauth/example"] }),+ });+ for (let i = 0; i < 10; i++) expect((await POST(request(i))).status).toBe(201);+ expect((await POST(request(11))).status).toBe(429);+ expect(registerClient).toHaveBeenCalledTimes(10);+ clock.mockReturnValue(1_910_003_600_001);+ vi.stubEnv("OS_TRUSTED_PROXY_HOPS", "1");+ for (let i = 0; i < 40; i++) expect((await POST(request(i))).status).toBe(201);+ const next = request(41), reader = vi.spyOn(next.body!, "getReader");+ expect((await POST(next)).status).toBe(429);+ expect(registerClient).toHaveBeenCalledTimes(50);+ expect(reader).not.toHaveBeenCalled();+ clock.mockReturnValue(1_910_007_200_002);+ registerClient.mockRejectedValueOnce(new Error("MCP client registration capacity reached"));+ const response = await POST(request(0));+ expect(response.status).toBe(503);+ expect(await response.json()).toMatchObject({ error: "temporarily_unavailable" });+});diff --git a/app/oauth/register/route.ts b/app/oauth/register/route.tsindex 91c37141..4969908c 100644--- a/app/oauth/register/route.ts+++ b/app/oauth/register/route.ts@@ -3,7 +3,7 @@ import { registerClient } from "@/lib/mcp/store";import { isAllowedRedirect } from "@/lib/mcp/pkce";import { mcpEnabled } from "@/lib/mcp/scope";import { clientIp } from "@/lib/mcp/origin";-import { rateLimitedUntrusted } from "@/lib/host/limits-api";+import { rateLimited, rateLimitedUntrusted } from "@/lib/host/limits-api";// RFC 7591 Dynamic Client Registration. Open by design and safe to be: a// registered client is INERT until the owner approves it on the consent page and@@ -27,7 +27,7 @@ export async function OPTIONS() {export async function POST(req: Request) {if (!mcpEnabled()) return new Response("Not Found", { status: 404 });- if (rateLimitedUntrusted(`mcp:dcr:${clientIp(req)}`, 10, 3_600_000)) {+ if (rateLimitedUntrusted(`mcp:dcr:${clientIp(req)}`, 10, 3_600_000) || rateLimited("mcp:dcr:admission", 40, 3_600_000)) {return Response.json({ error: "rate_limited" }, { status: 429, headers: { ...DCR_CORS, "Retry-After": "3600" } });}@@ -48,7 +48,12 @@ export async function POST(req: Request) {if (uris.length > 8) return bad("invalid_client_metadata", "at most 8 redirect_uris");const name = typeof body.client_name === "string" ? body.client_name : "MCP Client";- const clientId = await registerClient(name, uris);+ let clientId: string;+ try { clientId = await registerClient(name, uris); }+ catch (error) {+ if (error instanceof Error && error.message === "MCP client registration capacity reached") return bad("temporarily_unavailable", "Pending registrations are protected; retry after capacity expires.", 503);+ throw error;+ }return Response.json({client_id: clientId,diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 8aa492ca..57e57b99 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -4,6 +4,12 @@Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;this is the *what*, and it is what Settings → Account → About shows as “What's new”.+## 2026-10-10++**Fixed**++- `security` protect public admission and OAuth registration trust+## 2026-10-09**Added**diff --git a/docs/MCP.md b/docs/MCP.mdindex aa3918de..57c0e5ed 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -596,11 +596,11 @@ body incrementally with a hard **20 MiB** ceiling even when `Content-Length` isThe declared/inferred MIME must be in that five-format matrix; generic octet-stream may be used onthe wire but cannot bypass the declared matrix. PNG/JPEG/WebP magic bytes, JSON UTF-8 + syntax,and ZIP signatures are validated before the normal credential/path jail writes into-`OS_FS_WRITE_ROOTS`. `*.oaiusercontent.com` is trusted directly. For an OAuth client whose-registered callback is owned by `chatgpt.com`, the `openai/fileParams` bridge may also follow the-rotating `oaisdmntpr<region>.blob.core.windows.net` family used by ChatGPT temporary downloads.-That family exception is never granted from a self-declared client name alone; generic MCP clients-still need exact Azure hosts in `OS_MCP_OPENAI_FILE_HOSTS`. Raster files must also fully decode through bounded Sharp validation; magic bytes alone are insufficient. ZIP input requires a valid end-of-central-directory structure. The final write uses exclusive temporary files and atomic filesystem operations and never executes transferred bytes. Same bytes are idempotent; different existing bytes fail by default. `conflict=rename` uses a deterministic content-hash filename, while `conflict=replace` requires the current `expected_sha256`, so stale overwrites fail.+`OS_FS_WRITE_ROOTS`. `*.oaiusercontent.com` is trusted directly. Every Azure hostname,+including rotating ChatGPT download hosts, requires an exact Owner entry in+`OS_MCP_OPENAI_FILE_HOSTS`. DCR client names and callbacks are self-declared and never+confer provider identity or download trust. Each redirect is checked against the same allowlist.+Raster files must also fully decode through bounded Sharp validation; magic bytes alone are insufficient. ZIP input requires a valid end-of-central-directory structure. The final write uses exclusive temporary files and atomic filesystem operations and never executes transferred bytes. Same bytes are idempotent; different existing bytes fail by default. `conflict=rename` uses a deterministic content-hash filename, while `conflict=replace` requires the current `expected_sha256`, so stale overwrites fail.**`fs_export_file`** is the read-side counterpart for one original file up to **10 MiB**. It usesthe same `OS_FS_READ_ROOTS`, realpath and credential denylist as other reads, reads withdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex f3075bcc..91772368 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -4,6 +4,12 @@ The Vault window previously used a separate Basic login even after the Owner sigEvery app HTTP request requires the current Owner role and durable device/session generation. WebSockets use the existing continuously authorized server relay, so demotion, logout, revocation and expiry stop both directions rather than authorizing only the initial upgrade. App cookies cannot authenticate cockpit APIs, upstream requests strip all MSO credentials, and duplicate hosts/off-box targets fail closed. The derived cookie retains the parent expiry independently of the one-minute ticket. Regression coverage checks purpose/origin separation, expiry, role changes, cookie stripping, proxy routing and production HTTP/socket handoff with synthetic stores. Instance ingress, domain and vault data remain outside source.+## 2026-10-09: Close the three findings from the 0af3e570 cloud scan++Public IP attribution ignores all forwarding headers by default. An explicit trusted proxy hop count selects a validated IP from the right only behind a firewalled origin; invalid or insufficient chains fail closed. Login shares the same helper. Fixed global admission budgets protect inbound A2A authentication and OAuth registration even when source keys rotate or the untrusted limiter pool churns.++Pending OAuth registrations remain intact at the 64-client capacity: excess admission fails rather than evicting consent state. Only unreferenced registrations older than one hour expire; live codes, access and refresh grants retain their clients. DCR metadata never establishes provider identity or file-host trust. All Azure downloads and redirects require an exact Owner allowlist entry, including rotating ChatGPT hosts; direct oaiusercontent downloads remain supported. Independent cloud verification remains required after release.+## 2026-10-09: Preserve security regressions without synthetic scanner noisePost-release GitHub checks found two test-only matches. The growing-file regression now changes bytes through the already-open descriptor, preserving the actual-byte limit assertion without introducing a pathname check/reopen race in its fixture. Agent Vault constructs its deterministic redaction fixture from pieces; the original historical Gitleaks fingerprint is narrowly recorded after verifying every reachable commit. No production credential, scanner rule or release gate is excluded.diff --git a/lib/a2a/server-admission.test.ts b/lib/a2a/server-admission.test.tsnew file mode 100644index 00000000..f7197128--- /dev/null+++ b/lib/a2a/server-admission.test.ts@@ -0,0 +1,28 @@+import { afterEach, expect, it, vi } from "vitest";+const authenticate = vi.hoisted(() => vi.fn(async () => null));+vi.mock("./credentials", () => ({ authenticateA2AInboundToken: authenticate }));+afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); });++it("bounds forged forwarding identities before authentication and caps trusted-proxy traffic globally", async () => {+ vi.stubEnv("OS_A2A_INBOUND_ENABLED", "1");+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://fixture.invalid");+ vi.stubEnv("NEXT_PUBLIC_OS_DEMO", "0");+ vi.stubEnv("OS_TRUSTED_PROXY_HOPS", "0");+ const clock = vi.spyOn(Date, "now").mockReturnValue(1_900_000_000_000);+ const { handleA2ARequest } = await import("./server");+ const capabilities = { list: () => [], invoke: vi.fn(async () => ({ content: [] })) };+ const request = (index: number) => new Request("https://fixture.invalid/a2a/v1", {+ method: "POST", headers: { "x-forwarded-for": `198.51.100.${index % 250}`, "x-real-ip": String(index), authorization: "Bearer invalid" }, body: "{}",+ });+ for (let i = 0; i < 120; i++) expect((await handleA2ARequest(request(i), capabilities)).status).toBe(401);+ expect((await handleA2ARequest(request(121), capabilities)).status).toBe(429);+ expect(authenticate).toHaveBeenCalledTimes(120);+ clock.mockReturnValue(1_900_000_060_001);+ vi.stubEnv("OS_TRUSTED_PROXY_HOPS", "1");+ for (let i = 0; i < 600; i++) expect((await handleA2ARequest(request(i), capabilities)).status).toBe(401);+ const next = request(601);+ const reader = vi.spyOn(next.body!, "getReader");+ expect((await handleA2ARequest(next, capabilities)).status).toBe(429);+ expect(authenticate).toHaveBeenCalledTimes(720);+ expect(reader).not.toHaveBeenCalled();+});diff --git a/lib/a2a/server.ts b/lib/a2a/server.tsindex ebcdb03f..3ae6ecdb 100644--- a/lib/a2a/server.ts+++ b/lib/a2a/server.ts@@ -34,7 +34,7 @@ export async function handleA2ARequest(req: Request, capabilities: CapabilityRunreturn a2aJson({ error: "not_found" }, 404);if (req.method !== "POST")return a2aJson({ error: "method_not_allowed" }, 405, { allow: "POST" });- if (rateLimitedUntrusted(`a2a.inbound.ip:${clientIp(req)}`, 120, 60_000))+ if (rateLimitedUntrusted(`a2a.inbound.ip:${clientIp(req)}`, 120, 60_000) || rateLimited("a2a.inbound.admission", 600, 60_000))return a2aJson({ error: "rate_limited" }, 429, { "retry-after": "60" });const profile = await authenticateA2ARequest(req);if (!profile) return a2aUnauthorized();diff --git a/lib/capabilities/actors.ts b/lib/capabilities/actors.tsindex 34f65248..715771c1 100644--- a/lib/capabilities/actors.ts+++ b/lib/capabilities/actors.ts@@ -2,7 +2,7 @@ import type { TenantContext } from "@/lib/tenancy/authority";import type { AuthorizationGrant } from "./authorization-grant";import type { CapabilityToolProfile } from "./tool";-export interface CapabilityAgentContext { authorizationGrant?: AuthorizationGrant; tenantContext?: TenantContext; principal?: string; sessionId?: string; workflowActorOverride?: string; toolProfile?: CapabilityToolProfile; trustedOpenAiFileParams?: boolean; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }+export interface CapabilityAgentContext { authorizationGrant?: AuthorizationGrant; tenantContext?: TenantContext; principal?: string; sessionId?: string; workflowActorOverride?: string; toolProfile?: CapabilityToolProfile; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }export function workflowActor(actor: string | undefined, context?: CapabilityAgentContext): string | undefined {if (context?.workflowActorOverride) return context.workflowActorOverride;return context?.principal && context.sessionId ? `${context.principal}#session:${context.sessionId}` : actor;diff --git a/lib/capabilities/execute.ts b/lib/capabilities/execute.tsindex 9a2a2f0b..5a939954 100644--- a/lib/capabilities/execute.ts+++ b/lib/capabilities/execute.ts@@ -139,7 +139,6 @@ export async function executeCapabilityCall(input: {capabilities: context?.capabilities,authorizationGrant: context?.authorizationGrant,toolProfile: context?.toolProfile,- trustedOpenAiFileParams: context?.trustedOpenAiFileParams,}));const reportedFailure = capabilityReportedFailure(result) || trail?.outcome?.(result)?.ok === false;const completedState = reportedFailure ? "failed" : "completed";diff --git a/lib/capabilities/tool.ts b/lib/capabilities/tool.tsindex 970c5a02..2f0cc6a2 100644--- a/lib/capabilities/tool.ts+++ b/lib/capabilities/tool.ts@@ -71,7 +71,6 @@ export interface CapabilityRunContext {toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>;capabilities?: CapabilityRuntime;toolProfile?: CapabilityToolProfile;- trustedOpenAiFileParams?: boolean;}/**diff --git a/lib/host/rate-limit.ts b/lib/host/rate-limit.tsindex 41fd71f3..bb71823a 100644--- a/lib/host/rate-limit.ts+++ b/lib/host/rate-limit.ts@@ -37,7 +37,7 @@ function limit(buckets: Map<string, Bucket>, key: string, max: number, windowMs:return false;}-// Authenticated/session/bearer/owner-action limits. Never call this with a raw+// Authenticated/session/bearer/owner-action and fixed global admission limits. Never call this with a raw// unauthenticated IP key; use rateLimitedUntrusted for those.export function rateLimited(key: string, max: number, windowMs: number): boolean {return limit(privilegedBuckets, key, max, windowMs);diff --git a/lib/host/request-ip.ts b/lib/host/request-ip.tsindex b50a0c04..07809825 100644--- a/lib/host/request-ip.ts+++ b/lib/host/request-ip.ts@@ -1,8 +1,11 @@-/** Best-effort client IP for pre-auth rate limiting only. Never authorization. */+import { isIP } from "node:net";++/** Forwarded attribution requires an explicit proxy count and a firewalled origin. Never authorization. */export function clientIp(req: Request): string {- return (- req.headers.get("x-forwarded-for")?.split(",")[0].trim() ||- req.headers.get("x-real-ip")?.trim() ||- "unknown"- );+ const trusted = Number(process.env.OS_TRUSTED_PROXY_HOPS ?? "0");+ const trail = req.headers.get("x-forwarded-for") ?? "";+ if (!Number.isInteger(trusted) || trusted < 1 || trusted > 16 || trail.length > 4096) return "unknown";+ const hops = trail.split(",").map(value => value.trim());+ const address = hops[hops.length - trusted];+ return hops.length <= 32 && address && isIP(address) ? address : "unknown";}diff --git a/lib/mcp/client-profile.test.ts b/lib/mcp/client-profile.test.tsindex 280f665b..68f61ec0 100644--- a/lib/mcp/client-profile.test.ts+++ b/lib/mcp/client-profile.test.ts@@ -1,22 +1,19 @@import { describe, expect, it } from "vitest";-import { detectMcpToolProfile, isTrustedOpenAiFileParamsClient } from "./client-profile";+import { detectMcpToolProfile } from "./client-profile";describe("MCP client profile detection", () => {- it("recognizes the current ChatGPT connector callback host and trusts fileParams provenance", () => {+ it("recognizes a ChatGPT callback as a catalog hint", () => {const input = { redirectUris: ["https://chatgpt.com/connector/oauth/callback-123"] };expect(detectMcpToolProfile(input)).toBe("chatgpt");- expect(isTrustedOpenAiFileParamsClient(input)).toBe(true);});it("keeps legacy name-only ChatGPT compatibility without using the self-declared name as a file trust signal", () => {const input = { clientId: "mcpc_legacy", name: "ChatGPT", redirectUris: ["https://example.com/oauth/callback"] };expect(detectMcpToolProfile(input)).toBe("chatgpt");- expect(isTrustedOpenAiFileParamsClient(input)).toBe(false);});it("keeps generic MCP clients on the full MSO catalog and outside ChatGPT file trust", () => {const input = { clientId: "mcpc_generic", name: "Cursor", redirectUris: ["https://example.com/oauth/callback"] };expect(detectMcpToolProfile(input)).toBe("full");- expect(isTrustedOpenAiFileParamsClient(input)).toBe(false);});});diff --git a/lib/mcp/client-profile.ts b/lib/mcp/client-profile.tsindex d278a5e1..650255f2 100644--- a/lib/mcp/client-profile.ts+++ b/lib/mcp/client-profile.ts@@ -8,14 +8,9 @@ function isChatGptHost(host: string): boolean {return host === "chatgpt.com" || host.endsWith(".chatgpt.com");}-export function isTrustedOpenAiFileParamsClient(input: { clientId?: string; redirectUris?: string[] }): boolean {- const clientHost = hostOf(input.clientId ?? "");- const redirectHosts = (input.redirectUris ?? []).map(hostOf);- return isChatGptHost(clientHost) || redirectHosts.some(isChatGptHost);-}-export function detectMcpToolProfile(input: { clientId?: string; name?: string; redirectUris?: string[] }): McpToolProfile {const name = (input.name ?? "").toLowerCase();- if (name.includes("chatgpt") || name === "openai" || isTrustedOpenAiFileParamsClient(input)) return "chatgpt";+ // Display/catalog hints never establish provider identity or download authority.+ if (name.includes("chatgpt") || name === "openai" || isChatGptHost(hostOf(input.clientId ?? "")) || (input.redirectUris ?? []).some(uri => isChatGptHost(hostOf(uri)))) return "chatgpt";return "full";}diff --git a/lib/mcp/dispatch-types.ts b/lib/mcp/dispatch-types.tsindex b88b4d71..c2b2e562 100644--- a/lib/mcp/dispatch-types.ts+++ b/lib/mcp/dispatch-types.ts@@ -26,7 +26,6 @@ export interface McpAgentContext {authorizationGrant?: AuthorizationGrant;sessionId?: string;toolProfile?: McpToolProfile;- trustedOpenAiFileParams?: boolean;allowedTools?: readonly string[];toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>;capabilities?: CapabilityRuntime;diff --git a/lib/mcp/openai-file-upload-regression.test.ts b/lib/mcp/openai-file-upload-regression.test.tsindex c440a151..652abbc6 100644--- a/lib/mcp/openai-file-upload-regression.test.ts+++ b/lib/mcp/openai-file-upload-regression.test.ts@@ -39,10 +39,12 @@ describe("ChatGPT transfer regression boundaries", () => {await expect(call({ download_url: "https://oaisdmntprseasia.blob.core.windows.net/file.png", mime_type: "image/png" })).rejects.toThrow(/invalid Azure Blob hostname/i);});- it("allows the rotating Azure family only when OAuth provenance marks ChatGPT fileParams", async () => {+ it("requires exact Azure host configuration regardless of self-declared provider metadata", async () => {const file = { download_url: "https://oaisdmntprindiasocentral.blob.core.windows.net/file.png", file_id: "file_test", file_name: "file.png", mime_type: "image/png" };await expect(importOpenAiProvidedFile({ file, dest: "/home/example/generated-files" })).rejects.toThrow(/host is not allowed/i);- await expect(importOpenAiProvidedFile({ file, dest: "/home/example/generated-files", allowChatGptAzureFamily: true })).resolves.toMatchObject({ mimeType: "image/png" });+ expect(fetch).not.toHaveBeenCalled();+ process.env.OS_MCP_OPENAI_FILE_HOSTS = "oaisdmntprindiasocentral.blob.core.windows.net";+ await expect(importOpenAiProvidedFile({ file, dest: "/home/example/generated-files" })).resolves.toMatchObject({ mimeType: "image/png" });});it("rejects redirects to untrusted hosts", async () => {diff --git a/lib/mcp/openai-file-upload.ts b/lib/mcp/openai-file-upload.tsindex 5b1d5cb7..1e64cd97 100644--- a/lib/mcp/openai-file-upload.ts+++ b/lib/mcp/openai-file-upload.ts@@ -34,7 +34,6 @@ async function acquireImageImportSlot(): Promise<() => void> {}const SUPPORTED_MIME = new Set(["image/png", "image/webp", "image/jpeg", "application/json", "application/zip"]);const WIRE_MIME = new Set([...SUPPORTED_MIME, "application/octet-stream"]);-const CHATGPT_AZURE_FILE_HOST = /^oaisdmntpr[a-z0-9]{2,40}\.blob\.core\.windows\.net$/;const MIME_ALIASES = new Map([["application/x-zip-compressed", "application/zip"]]);const EXTENSION_MIME = new Map([[".png", "image/png"], [".webp", "image/webp"], [".jpg", "image/jpeg"],@@ -62,17 +61,17 @@ function configuredAzureHosts(): Set<string> {}return hosts;}-function trustedDownloadUrl(raw: string, allowChatGptAzureFamily = false): URL {+function trustedDownloadUrl(raw: string): URL {let url: URL;try { url = new URL(raw); } catch { throw new HostError("file.download_url is invalid"); }if (url.protocol !== "https:") throw new HostError("file.download_url must use HTTPS");const host = url.hostname.toLowerCase();const openAiContentHost = host === "files.oaiusercontent.com" || host.endsWith(".oaiusercontent.com");- const trustedChatGptAzure = allowChatGptAzureFamily && CHATGPT_AZURE_FILE_HOST.test(host);- if (!openAiContentHost && !trustedChatGptAzure && !configuredAzureHosts().has(host)) throw new HostError(`file.download_url host is not allowed: ${host}`);+ // shortcut: rotating Azure hosts need exact Owner configuration until provider identity can be verified independently of DCR metadata.+ if (!openAiContentHost && !configuredAzureHosts().has(host)) throw new HostError(`file.download_url host is not allowed: ${host}`);return url;}-async function fetchTrustedFile(initialUrl: URL, allowChatGptAzureFamily = false): Promise<Response> {+async function fetchTrustedFile(initialUrl: URL): Promise<Response> {let url = initialUrl;for (let hop = 0; hop <= 3; hop += 1) {const response = await fetch(url, {@@ -82,7 +81,7 @@ async function fetchTrustedFile(initialUrl: URL, allowChatGptAzureFamily = falseif (![301, 302, 303, 307, 308].includes(response.status)) return response;const location = response.headers.get("location");if (!location) throw new HostError("OpenAI file redirect was missing a location");- url = trustedDownloadUrl(new URL(location, url).toString(), allowChatGptAzureFamily);+ url = trustedDownloadUrl(new URL(location, url).toString());}throw new HostError("OpenAI file download exceeded the redirect limit");}@@ -163,13 +162,13 @@ function safeFilename(input: string | undefined, fallback: string, mimeType: str}export async function importOpenAiProvidedFile(opts: {- file: unknown; dest: string; filename?: string; conflict?: UploadConflictPolicy; expectedSha256?: string; allowChatGptAzureFamily?: boolean;+ file: unknown; dest: string; filename?: string; conflict?: UploadConflictPolicy; expectedSha256?: string;}) {- const file = providedFile(opts.file), url = trustedDownloadUrl(file.download_url, opts.allowChatGptAzureFamily === true), mimeType = declaredMime(file);+ const file = providedFile(opts.file), url = trustedDownloadUrl(file.download_url), mimeType = declaredMime(file);if (typeof file.size === "number" && (!Number.isFinite(file.size) || file.size < 0 || file.size > MAX_FILE_BYTES)) throw new HostError("file exceeds the 20 MiB MCP import limit");const release = mimeType.startsWith("image/") ? await acquireImageImportSlot() : null;try {- const response = await fetchTrustedFile(url, opts.allowChatGptAzureFamily === true);+ const response = await fetchTrustedFile(url);if (!response.ok) throw new HostError(`OpenAI file download failed (${response.status})`);const wireMime = responseMime(response);if (wireMime && wireMime !== "application/octet-stream" && wireMime !== mimeType) throw new HostError(`response file type ${wireMime} does not match ${mimeType}`);diff --git a/lib/mcp/store-security.test.ts b/lib/mcp/store-security.test.tsindex 496b83e4..ed415376 100644--- a/lib/mcp/store-security.test.ts+++ b/lib/mcp/store-security.test.ts@@ -18,6 +18,19 @@ afterEach(() => vi.restoreAllMocks());describe("durable MCP credential isolation", () => {+ it("protects pending consent at capacity and expires only unreferenced registrations", async () => {+ const clock = vi.spyOn(Date, "now").mockReturnValue(1_920_000_000_000);+ const pending = await store.registerClient("pending", ["https://fixture.invalid/callback"]);+ for (let i = 1; i < 64; i++) await store.registerClient("other", ["https://fixture.invalid/callback"]);+ await expect(store.registerClient("overflow", ["https://fixture.invalid/callback"])).rejects.toThrow(/registration capacity/);+ expect(await store.getClient(pending)).toMatchObject({ name: "pending" });+ await store.storeCode("pending-code", { clientId: pending, redirectUri: "https://fixture.invalid/callback", codeChallenge: "fixture", scope: "read", expiresAt: Date.now() + 7_200_000 });+ clock.mockReturnValue(1_920_003_600_001);+ const replacement = await store.registerClient("new", ["https://fixture.invalid/callback"]);+ expect(await store.getClient(replacement)).not.toBeNull();+ expect(await store.getClient(pending)).not.toBeNull();+ expect(await store.consumeCode("pending-code")).toMatchObject({ clientId: pending });+ });it("reads the size-checked descriptor when the store pathname is replaced", async () => {const state = await import("./store-state");await state.commitMcpStore({ clients: { original: { name: "fixture", redirectUris: [], createdAt: Date.now() } }, codes: {}, tokens: {}, refreshTokens: {}, spentRefreshTokens: {} });diff --git a/lib/mcp/store-state.ts b/lib/mcp/store-state.tsindex 2ed302ca..d1e06e84 100644--- a/lib/mcp/store-state.ts+++ b/lib/mcp/store-state.ts@@ -87,6 +87,10 @@ export function sweepMcpStore(store: McpStore): McpStore {const keys = families.get(token.grantId) ?? []; keys.push(key); families.set(token.grantId, keys);if (keys.length > 256) delete store.spentRefreshTokens[keys.shift()!];}+ const referenced = referencedClientIds(store);+ for (const [id, client] of Object.entries(store.clients)) {+ if (!referenced.has(id) && client.createdAt + 3_600_000 < now) delete store.clients[id];+ }return store;}@@ -99,15 +103,8 @@ function referencedClientIds(store: McpStore): Set<string> {].filter(Boolean));}-export function pruneUnreferencedClients(store: McpStore): void {- const ids = Object.keys(store.clients);- if (ids.length < MAX_CLIENTS) return;- const referenced = referencedClientIds(store);- const removable = ids- .filter((id) => !referenced.has(id))- .sort((a, b) => store.clients[a].createdAt - store.clients[b].createdAt);- const removeCount = Math.min(removable.length, ids.length - MAX_CLIENTS + 1);- for (const id of removable.slice(0, removeCount)) delete store.clients[id];+export function assertMcpClientCapacity(store: McpStore): void {+ if (Object.keys(store.clients).length >= MAX_CLIENTS) throw new Error("MCP client registration capacity reached");}export async function commitMcpStore(store: McpStore): Promise<void> {diff --git a/lib/mcp/store.ts b/lib/mcp/store.tsindex 8d33057c..cfbd5d98 100644--- a/lib/mcp/store.ts+++ b/lib/mcp/store.ts@@ -10,7 +10,7 @@ import { detectMcpToolProfile } from "./client-profile";import {commitMcpStore as write,mutateMcpStore as mutate,- pruneUnreferencedClients,+ assertMcpClientCapacity,readMcpStore as read,sweepMcpStore as sweep,} from "./store-state";@@ -27,7 +27,7 @@ export class OAuthRefreshRateLimit extends Error {}export function registerClient(name: string, redirectUris: string[]): Promise<string> {return mutate(async () => {const store = sweep(await read());- pruneUnreferencedClients(store);+ assertMcpClientCapacity(store);const clientId = "mcpc_" + randomUUID().replaceAll("-", "").slice(0, 24);const cleanName = name.slice(0, 80) || "MCP Client";store.clients[clientId] = {@@ -42,7 +42,7 @@ export function registerClient(name: string, redirectUris: string[]): Promise<st}export async function getClient(clientId: string): Promise<McpClient | null> {- const clients = (await read()).clients;+ const clients = sweep(await read()).clients;return Object.hasOwn(clients, clientId) ? clients[clientId] : null;}diff --git a/lib/mcp/tools-mutate.ts b/lib/mcp/tools-mutate.tsindex 39d9b683..db65e744 100644--- a/lib/mcp/tools-mutate.ts+++ b/lib/mcp/tools-mutate.ts@@ -35,7 +35,7 @@ export const MUTATE_TOOLS: McpTool[] = [name: "fs_upload_file",limit: { key: "fs.upload", max: 20, windowMs: 60_000 },audit: { action: "fs.upload" as const, targetArg: "dest" },- description: "Import one ChatGPT conversation/generated PNG, WebP, JPEG, JSON or ZIP file through openai/fileParams. MSO validates OAuth-bound temporary URL provenance, type, size and content before writing inside OS_FS_WRITE_ROOTS. Verified ChatGPT callbacks may use rotating Azure file hosts; generic MCP clients require exact allowlisting. Same bytes are idempotent; different existing bytes fail by default. conflict=rename is deterministic; conflict=replace requires expected_sha256.",+ description: "Import one ChatGPT conversation/generated PNG, WebP, JPEG, JSON or ZIP file through openai/fileParams. MSO validates temporary URL host, type, size and content before writing inside OS_FS_WRITE_ROOTS. All Azure file hosts require exact Owner allowlisting; DCR metadata never grants host trust. Same bytes are idempotent; different existing bytes fail by default. conflict=rename is deterministic; conflict=replace requires expected_sha256.",scope: "write",annotations: { destructiveHint: true, openWorldHint: true, idempotentHint: true },actionContract: { phase: "mutate", target: "artifact-ingress", sourceOfTruth: "provider", validators: ["openai-file-provenance", "content-type", "content-size", "content-structure", "destination-policy"], verify: ["fs_read"], confirmation: "contextual", concurrency: "hash", presentation: "structured" },@@ -67,7 +67,7 @@ export const MUTATE_TOOLS: McpTool[] = [return importOpenAiProvidedFile({file: a.file, dest, filename: opt(a, "filename"),conflict: opt(a, "conflict") as "error" | "rename" | "replace" | undefined,- expectedSha256: opt(a, "expected_sha256"), allowChatGptAzureFamily: context.trustedOpenAiFileParams === true,+ expectedSha256: opt(a, "expected_sha256"),});},},