TypeScript
fix(client): tolerate blocked cookies in MCP app sandboxes (#17027)
Alexac2cc78d4a4a
diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.tsindex 0ee1ca9c186..9d3686a4669 100644--- a/apps/server/src/http.test.ts+++ b/apps/server/src/http.test.ts@@ -18,6 +18,7 @@ import { openMediaFile } from "./assets/MediaFile.ts";import {injectMcpAppCsp,+ injectMcpAppCookieBootstrap,injectMcpAppThemeBootstrap,MCP_APP_MAX_HTML_BYTES,} from "@t3tools/shared/mcpApp";@@ -58,7 +59,7 @@ describe("MCP app asset responses", () => {method,),);- const expected = injectMcpAppThemeBootstrap(html);+ const expected = injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html));expect(response.status).toBe(200);expect(response.headers.get("content-length")).toBe(String(new TextEncoder().encode(expected).byteLength),diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex 1e9c3d714d1..13f54ef3529 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -5,7 +5,7 @@ import {EnvironmentHttpApi,} from "@t3tools/contracts";import { isDevProxiedPath } from "@t3tools/shared/devProxy";-import { injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp";+import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp";import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";import * as Data from "effect/Data";import * as Effect from "effect/Effect";@@ -185,7 +185,7 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* (return HttpServerResponse.text("MCP app is too large to preview.", { status: 413 });}const body = new TextEncoder().encode(- injectMcpAppThemeBootstrap(new TextDecoder().decode(bytes)),+ injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(new TextDecoder().decode(bytes))),);headers["Content-Length"] = String(body.byteLength);return method === "HEAD"diff --git a/packages/shared/src/mcpApp.test.ts b/packages/shared/src/mcpApp.test.tsindex bca145a4fba..7dd50690adf 100644--- a/packages/shared/src/mcpApp.test.ts+++ b/packages/shared/src/mcpApp.test.ts@@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test";import {injectMcpAppCsp,injectMcpAppThemeBootstrap,+ injectMcpAppCookieBootstrap,mcpAppContentSecurityPolicy,mcpAppToolCallableByApp,readMcpAppCsp,@@ -209,3 +210,61 @@ describe("mcpAppFromToolItem", () => {expect(output?.t3McpApp?.server).toBe("weather");});});++describe("MCP App cookie bootstrap", () => {+ const vendor = `<script>document.cookie.split(";");document.cookie="analytics=1";document.root="rendered";</script>`;+ const execute = (html: string, document: object) => {+ for (const script of html.matchAll(/<script>([\s\S]*?)<\/script>/g)) {+ NodeVM.runInNewContext(script[1]!, { document });+ }+ };++ it("lets cookie-reading startup code render in an opaque document without granting storage", () => {+ const blocked = new DOMException("Opaque origin", "SecurityError");+ const prototype = Object.defineProperty({}, "cookie", {+ get() {+ throw blocked;+ },+ set() {+ throw blocked;+ },+ });+ const document = Object.assign(+ Object.create(prototype) as { cookie: string; root: string; indexedDB: unknown },+ { root: "" },+ );+ Object.defineProperty(document, "indexedDB", {+ get() {+ throw blocked;+ },+ });+ const saved = injectMcpAppCsp(vendor, { connectDomains: ["https://analytics.example"] });+ const html = injectMcpAppCookieBootstrap(saved);+ expect(html.indexOf("Content-Security-Policy")).toBeLessThan(html.indexOf("<script>"));+ expect(html).toContain("connect-src https://analytics.example");+ execute(html, document);+ expect(document.root).toBe("rendered");+ expect(document.cookie).toBe("");+ document.cookie = "session=secret";+ expect(document.cookie).toBe("");+ expect(() => document.indexedDB).toThrow(blocked);+ expect(() => Reflect.get(prototype, "cookie")).toThrow(blocked);+ });++ it("leaves functioning cookie reads and writes unchanged", () => {+ const document = { cookie: "existing=1", root: "" };+ execute(injectMcpAppCookieBootstrap(vendor), document);+ expect(document).toEqual({ cookie: "analytics=1", root: "rendered" });+ });++ it("leaves other cookie failures unchanged", () => {+ const failure = new TypeError("Unexpected cookie failure");+ const document = Object.defineProperty({}, "cookie", {+ get() {+ throw failure;+ },+ });+ expect(() => execute(injectMcpAppCookieBootstrap(vendor), document)).toThrow(failure);+ expect(() => Reflect.get(document, "cookie")).toThrow(failure);+ });+});diff --git a/packages/shared/src/mcpApp.ts b/packages/shared/src/mcpApp.tsindex b99defbb504..e525b1b68d0 100644--- a/packages/shared/src/mcpApp.ts+++ b/packages/shared/src/mcpApp.ts@@ -249,6 +249,22 @@ export function injectMcpAppThemeBootstrap(html: string): string {: `<!doctype html>${script}${html}`;}+/**+ * Analytics libraries often read cookies during startup. An opaque document+ * has none, but browsers throw instead of returning an empty cookie string.+ * Keep the sandbox and make that document-local case behave like no cookies.+ */+export function injectMcpAppCookieBootstrap(html: string): string {+ const bootstrap = `<script>(function(){try{void document.cookie;}catch(error){if(error&&error.name==="SecurityError"){Object.defineProperty(document,"cookie",{configurable:true,get:function(){return "";},set:function(){}});}}})();</script>`;+ // Saved captures begin with the CSP inserted by injectMcpAppCsp. Keep it+ // ahead of executable code, including this bootstrap, without rewriting it.+ const prefix =+ /^(?:\uFEFF?\s*<!doctype[^>]*>\s*)?(?:<meta http-equiv="Content-Security-Policy" content="[^"]*">)?/i.exec(+ html,+ )![0];+ return `${prefix}${bootstrap}${html.slice(prefix.length)}`;+}+/** The iframe `allow` attribute for the permissions an app declared. */export function mcpAppAllowAttribute(permissions: McpAppPermissions | undefined): string {const features: Array<string> = [];