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(mcp): validate browser origins
Rahman1ba50e1f4539
diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.tsindex 8a7e4c01..aaa95b30 100644--- a/app/mcp/route.test.ts+++ b/app/mcp/route.test.ts@@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({clampScope: vi.fn((scope: "read" | "write" | "exec") => scope),rateLimited: vi.fn(() => false),rateLimitedUntrusted: vi.fn(() => false),+ mcpRequestOriginAllowed: vi.fn(() => true),}));vi.mock("@/lib/mcp/store", () => ({@@ -30,6 +31,7 @@ vi.mock("@/lib/mcp/scope", () => ({vi.mock("@/lib/mcp/origin", () => ({publicOrigin: () => "https://mso.example.test",clientIp: () => "127.0.0.1",+ mcpRequestOriginAllowed: mocks.mcpRequestOriginAllowed,}));vi.mock("@/lib/host", () => ({rateLimited: mocks.rateLimited,@@ -56,9 +58,25 @@ describe("/mcp request boundary", () => {mocks.clampScope.mockClear();mocks.rateLimited.mockClear().mockReturnValue(false);mocks.rateLimitedUntrusted.mockClear().mockReturnValue(false);+ mocks.mcpRequestOriginAllowed.mockClear().mockReturnValue(true);});afterEach(() => vi.unstubAllEnvs());+ it("rejects a browser Origin that fails the Streamable HTTP boundary before auth", async () => {+ mocks.mcpRequestOriginAllowed.mockReturnValueOnce(false);+ const getReader = vi.fn(() => { throw new Error("body must not be read"); });+ const req = {+ headers: new Headers({ authorization: "Bearer live-token", origin: "https://evil.example" }),+ body: { getReader },+ } as unknown as Request;+ const { POST } = await import("./route");+ const res = await POST(req);+ expect(res.status).toBe(403);+ expect(getReader).not.toHaveBeenCalled();+ expect(mocks.validateToken).not.toHaveBeenCalled();+ expect(mocks.dispatch).not.toHaveBeenCalled();+ });+it("rejects an invalid bearer before opening the request body", async () => {mocks.validateToken.mockResolvedValueOnce(null);const getReader = vi.fn(() => { throw new Error("body must not be read"); });diff --git a/app/mcp/route.ts b/app/mcp/route.tsindex 278d0898..4b5a2c53 100644--- a/app/mcp/route.ts+++ b/app/mcp/route.ts@@ -1,7 +1,7 @@import { dispatch, isNotification, rpcError, UNAUTHORIZED, RATE_LIMITED } from "@/lib/mcp/dispatch";import { validateToken, touchToken } from "@/lib/mcp/store";import { clampScope, mcpEnabled } from "@/lib/mcp/scope";-import { publicOrigin, clientIp } from "@/lib/mcp/origin";+import { publicOrigin, clientIp, mcpRequestOriginAllowed } from "@/lib/mcp/origin";import { rateLimited, rateLimitedUntrusted } from "@/lib/host";import { TOOLS } from "@/lib/mcp/tools";import { toolsetInfo } from "@/lib/mcp/toolset";@@ -57,6 +57,9 @@ export async function POST(req: Request) {Response.json(rpcError(null, UNAUTHORIZED, msg), { status: 401, headers: { "WWW-Authenticate": challenge } });if (!mcpEnabled()) return new Response("Not Found", { status: 404 });+ if (!mcpRequestOriginAllowed(req)) {+ return Response.json({ error: "forbidden_origin" }, { status: 403, headers: { "Cache-Control": "no-store" } });+ }// Pre-auth flood guard: an invalid token still costs a sha256 + a file read.if (rateLimitedUntrusted(`mcp:ip:${clientIp(req)}`, PREAUTH_PER_MIN, 60_000)) {@@ -109,6 +112,9 @@ export async function POST(req: Request) {// with anything that needs the token.export async function GET(req: Request) {if (!mcpEnabled()) return new Response("Not Found", { status: 404 });+ if (!mcpRequestOriginAllowed(req)) {+ return Response.json({ error: "forbidden_origin" }, { status: 403, headers: { "Cache-Control": "no-store" } });+ }return Response.json({name: "mso MCP",transport: "streamable-http (JSON-RPC over POST)",diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 4b4e2d3c..00431f0e 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -12,6 +12,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Fixed**+- `mcp` validate browser origins- `settings` hide premature update warning- `update` enforce main and raise MCP daily limit- `mcp` raise daily token call limitdiff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.mdindex 99de7db1..2df424e5 100644--- a/docs/CHATGPT-PLUGIN.md+++ b/docs/CHATGPT-PLUGIN.md@@ -1,10 +1,10 @@# ChatGPT plugin / custom MCP app for MSO-> **Current reference.** OpenAI moved its app directory to the **Plugin directory** on-> 2026-07-09; plugins are now the discovery surface across ChatGPT/Codex, while the underlying-> MSO connection remains a custom MCP app created in Developer Mode. Depending on workspace-> controls, the UI can say **Plugins → New Plugin** or **Apps → Create**. This is not a legacy-> ChatGPT Plugin manifest, browser extension, or a plugin installed inside Hermes/OpenClaw.+> **Current reference.** OpenAI currently exposes custom MCP setup through more than one product+> surface: the official Developer Mode guide uses **Apps → Create**, while ChatGPT Work and some+> plugin surfaces expose **Plugins → MCP / New Plugin**. The underlying MSO connection is the same+> remote MCP app/server. This is not a legacy ChatGPT Plugin manifest, browser extension, or a+> plugin installed inside Hermes/OpenClaw.>> ChatGPT's Developer Mode UI and permissions are controlled by OpenAI and can change during> the MCP beta. Settings → MCP in MSO therefore shows the live endpoint, OAuth metadata and adiff --git a/docs/MCP.md b/docs/MCP.mdindex dd38e543..a1aede02 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -43,6 +43,11 @@ The stable server contract is the remote HTTPS endpoint plus OAuth discovery:| authorization metadata | `/.well-known/oauth-authorization-server` || protected-resource metadata | `/.well-known/oauth-protected-resource` |+The Streamable HTTP route validates any browser `Origin` header before bearer authentication, as+required by the MCP transport security guidance to prevent DNS rebinding. Server-to-server clients+normally omit `Origin`; browser-origin traffic is accepted only from the configured public origin or+from a loopback browser talking to the loopback cockpit.+MSO supports OAuth 2.1-style authorization-code flow with PKCE S256 and public clients(token endpoint auth `none`). The current authorization metadata advertises only`authorization_code`; there is no refresh-token grant. The authorization page is a normal@@ -50,11 +55,11 @@ signed-in MSO page: an approved human browser session converts into a scoped MCPconsent page is not a second login mechanism. Expired/revoked bearers therefore require anew authorization flow.-For ChatGPT, the connection is a **custom MCP app** created in Developer Mode and surfaced-through OpenAI's current Plugin/App experience. OpenAI moved the directory to Plugins in July-2026, while some workspace configuration pages still say Apps → Create; MSO therefore does not-freeze one menu label. Settings → MCP renders the live server URL, probes MCP/OAuth discovery,-and provides client-specific numbered steps. Use [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) for+For ChatGPT, the connection is a **custom MCP app** created in Developer Mode. OpenAI currently+shows more than one setup surface: its Developer Mode guide uses Apps → Create, while ChatGPT Work+and some plugin surfaces expose Plugins → MCP / New Plugin. MSO therefore does not freeze one menu+label. Settings → MCP renders the live server URL, probes MCP/OAuth discovery, and provides+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 throughdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex d3392558..2550e08b 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -20,7 +20,9 @@ starts at `read` and explicitly describes `write` and `exec` blast radius.The existing token revocation, audit trail and toolset-signature cards remain the operational truthafter connection. Current MCP/ChatGPT docs were refreshed at the same time, including the live-31-tool split (16 read / 10 write / 5 exec) and current Plugin/App terminology.+31-tool split (16 read / 10 write / 5 exec) and current Plugin/App terminology. The Streamable HTTP+route now also validates browser `Origin` before authentication, closing the DNS-rebinding gap called+out as a MUST in the MCP transport specification, while server-to-server clients remain unaffected.## 2026-08-31 — 10× MCP daily allowance + truthful Settings updater preflight (SHIPPED)diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 77bbbac1..a99fc98c 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -330,7 +330,9 @@ the client URL.The test is not a generic ping. All four public contracts must agree on the same deployment:`GET /mcp`, the unauthenticated Bearer/OAuth challenge from `POST /mcp`, RFC 9728 protected-resource metadata, and RFC 8414 authorization-server metadata. Expand **Advanced OAuth settings**+resource metadata, and RFC 8414 authorization-server metadata. Streamable HTTP browser requests+also have their `Origin` validated before authentication to block DNS-rebinding access to a local+listener. Expand **Advanced OAuth settings**and compare the URLs if one badge is red. A proxy/domain mismatch is more likely than a tokenproblem because this probe intentionally runs before OAuth authorization.diff --git a/frontend/slices/os-settings/components/mcp-connection-mode.tsx b/frontend/slices/os-settings/components/mcp-connection-mode.tsxindex c166fbb8..b8d469be 100644--- a/frontend/slices/os-settings/components/mcp-connection-mode.tsx+++ b/frontend/slices/os-settings/components/mcp-connection-mode.tsx@@ -52,6 +52,7 @@ export function McpConnectionMode({ endpoints, remote }: { endpoints: McpEndpoin<p className="mt-1.5 text-[11px] leading-relaxed text-muted-foreground">For a stable URL, route an HTTPS hostname to the loopback MSO runtime through your trusted tunnel or reverse proxy, then set that same origin in MSO.</p><p className="mt-3 text-[10px] leading-relaxed text-muted-foreground">Keep the raw Next listener loopback-only. OAuth discovery, redirect validation, cookies, and MCP resource metadata must agree on one public origin.</p></div>+</div>)}</div>diff --git a/frontend/slices/os-settings/components/mcp-setup-guide.tsx b/frontend/slices/os-settings/components/mcp-setup-guide.tsxindex 30cce6ba..7138ac5f 100644--- a/frontend/slices/os-settings/components/mcp-setup-guide.tsx+++ b/frontend/slices/os-settings/components/mcp-setup-guide.tsx@@ -81,7 +81,7 @@ export function McpSetupGuide({ origin, maxScope }: { origin: string; maxScope:<McpCopyField label="Public Client ID (manual fallback)" value="chatgpt-mso" /><McpCopyField label="Authentication" value="OAuth · authorization_code · PKCE S256" /></div>- <p className="mt-3 text-[11px] leading-relaxed text-muted-foreground">Client secret: none · token endpoint auth: none · refresh token: not issued · access tokens require authorization again after expiry/revocation.</p>+ <p className="mt-3 text-[11px] leading-relaxed text-muted-foreground">Client secret: none · token endpoint auth: none · access-token TTL: 90 days · refresh token: not issued · reconnect after expiry/revocation.</p></details><div className="flex gap-2 rounded-lg border border-warning/30 bg-warning/10 px-3 py-2.5"><ShieldCheck className="mt-0.5 size-4 shrink-0" />diff --git a/lib/mcp/origin.test.ts b/lib/mcp/origin.test.tsnew file mode 100644index 00000000..d88b977c--- /dev/null+++ b/lib/mcp/origin.test.ts@@ -0,0 +1,46 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { mcpRequestOriginAllowed, publicOrigin } from "./origin";++function req(url: string, headers: Record<string, string> = {}) {+ return new Request(url, { headers });+}++afterEach(() => vi.unstubAllEnvs());++describe("MCP public origin boundary", () => {+ it("prefers the deployment-owned origin", () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test/path");+ expect(publicOrigin(req("http://127.0.0.1:4005/mcp", { host: "127.0.0.1:4005" }))).toBe("https://mso.example.test");+ });++ it("allows server-to-server clients that omit Origin", () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");+ expect(mcpRequestOriginAllowed(req("https://mso.example.test/mcp"))).toBe(true);+ });++ it("allows the configured public browser origin", () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");+ expect(mcpRequestOriginAllowed(req("https://mso.example.test/mcp", { origin: "https://mso.example.test", host: "mso.example.test" }))).toBe(true);+ });++ it("keeps the Settings self-probe working on a loopback cockpit", () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");+ expect(mcpRequestOriginAllowed(req("http://127.0.0.1:4005/mcp", { origin: "http://127.0.0.1:4005", host: "127.0.0.1:4005" }))).toBe(true);+ });++ it("rejects a different loopback origin or port", () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");+ expect(mcpRequestOriginAllowed(req("http://127.0.0.1:4005/mcp", { origin: "http://localhost:4005", host: "127.0.0.1:4005" }))).toBe(false);+ expect(mcpRequestOriginAllowed(req("http://127.0.0.1:4005/mcp", { origin: "http://127.0.0.1:9999", host: "127.0.0.1:4005" }))).toBe(false);+ });++ it("rejects an arbitrary browser origin even when Host is attacker controlled", () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "");+ expect(mcpRequestOriginAllowed(req("http://attacker.example/mcp", { origin: "http://attacker.example", host: "attacker.example" }))).toBe(false);+ });++ it("rejects a foreign origin when a public origin is configured", () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");+ expect(mcpRequestOriginAllowed(req("https://mso.example.test/mcp", { origin: "https://evil.example", host: "mso.example.test" }))).toBe(false);+ });+});diff --git a/lib/mcp/origin.ts b/lib/mcp/origin.tsindex 8edc9961..02e5c462 100644--- a/lib/mcp/origin.ts+++ b/lib/mcp/origin.ts@@ -5,6 +5,65 @@// Precedence mirrors lib/managed-apps/proxy-headers: OS_PUBLIC_ORIGIN is// deployment-owned and wins; the real Host header comes next; X-Forwarded-Host is// client-settable and is consulted LAST.++function normalizedConfiguredOrigin(): string | null {+ const explicit = process.env.OS_PUBLIC_ORIGIN?.trim();+ if (!explicit) return null;+ try {+ return new URL(explicit).origin;+ } catch {+ return null;+ }+}++function isLoopbackHostname(hostname: string): boolean {+ const host = hostname.toLowerCase().replace(/^\[/, "").replace(/\]$/, "");+ return host === "localhost" || host === "::1" || host.startsWith("127.");+}++function requestHeaderOrigin(req: Request): string | null {+ const url = new URL(req.url);+ const proto = req.headers.get("x-forwarded-proto")?.split(",")[0].trim() || url.protocol.replace(":", "");+ const host = req.headers.get("host")?.trim() || url.host;+ try {+ return new URL(`${proto}://${host}`).origin;+ } catch {+ return null;+ }+}++/**+ * Streamable HTTP requires Origin validation to prevent a browser from using DNS+ * rebinding to reach a local MCP listener. Server-to-server MCP clients normally+ * omit Origin and remain unaffected. If OS_PUBLIC_ORIGIN is configured, browser+ * requests must match it; a browser opened directly on the loopback cockpit is+ * also allowed to probe the loopback route used by Settings → MCP.+ */+export function mcpRequestOriginAllowed(req: Request): boolean {+ const raw = req.headers.get("origin");+ if (!raw) return true;++ let supplied: URL;+ try {+ supplied = new URL(raw);+ } catch {+ return false;+ }++ const explicit = normalizedConfiguredOrigin();+ if (explicit && supplied.origin === explicit) return true;++ const requestOrigin = requestHeaderOrigin(req);+ if (requestOrigin) {+ const target = new URL(requestOrigin);+ if (isLoopbackHostname(target.hostname) && supplied.origin === requestOrigin) return true;+ }++ // Without an explicit public origin, never trust an arbitrary Host header merely+ // because a browser echoed it in Origin: that is the DNS-rebinding failure mode.+ return false;+}+export function publicOrigin(req: Request): string {const explicit = process.env.OS_PUBLIC_ORIGIN?.trim();if (explicit) {