Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): stop MCP apps rendering blank under their own CSP (#82409)

Paul D'Ambra1d8c65d1901e
diff --git a/products/desktop/apps/mobile/src/features/mcp/sandbox/mcpAppCsp.ts b/products/desktop/apps/mobile/src/features/mcp/sandbox/mcpAppCsp.ts
deleted file mode 100644
index a29089aa4ec2..000000000000
--- a/products/desktop/apps/mobile/src/features/mcp/sandbox/mcpAppCsp.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import type { McpUiResourceCsp } from "@modelcontextprotocol/ext-apps/app-bridge";
-
-const DEFAULT_CSP =
- "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; connect-src 'none'; object-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'";
-
-export function sanitizeDomain(domain: string): string {
- return domain.replace(/[^a-zA-Z0-9.*:-]/g, "");
-}
-
-export function buildCspString(csp?: McpUiResourceCsp): string {
- if (!csp) return DEFAULT_CSP;
-
- const resourceDomains = csp.resourceDomains?.length
- ? csp.resourceDomains.map(sanitizeDomain).join(" ")
- : "";
- const resourceSuffix = resourceDomains ? ` ${resourceDomains}` : "";
-
- const directives: string[] = [
- "default-src 'none'",
- `script-src 'self' 'unsafe-inline'${resourceSuffix}`,
- `style-src 'self' 'unsafe-inline'${resourceSuffix}`,
- "object-src 'none'",
- "form-action 'none'",
- ];
-
- if (csp.connectDomains?.length) {
- directives.push(
- `connect-src ${csp.connectDomains.map(sanitizeDomain).join(" ")}`,
- );
- } else {
- directives.push("connect-src 'none'");
- }
-
- if (resourceDomains) {
- directives.push(`img-src 'self' data: ${resourceDomains}`);
- directives.push(`media-src 'self' data: ${resourceDomains}`);
- directives.push(`font-src ${resourceDomains}`);
- } else {
- directives.push("img-src 'self' data:");
- directives.push("media-src 'self' data:");
- }
-
- if (csp.frameDomains?.length) {
- directives.push(
- `frame-src ${csp.frameDomains.map(sanitizeDomain).join(" ")}`,
- );
- } else {
- directives.push("frame-src 'none'");
- }
-
- if (csp.baseUriDomains?.length) {
- directives.push(
- `base-uri ${csp.baseUriDomains.map(sanitizeDomain).join(" ")}`,
- );
- } else {
- directives.push("base-uri 'none'");
- }
-
- return directives.join("; ");
-}
-
-export function escapeAttr(str: string): string {
- return str
- .replace(/&/g, "&")
- .replace(/"/g, """)
- .replace(/'/g, "'")
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;");
-}
-
-export function buildCspMetaTag(csp?: McpUiResourceCsp): string {
- return `<meta http-equiv="Content-Security-Policy" content="${escapeAttr(buildCspString(csp))}">`;
-}
-
-export function applyCspToHtml(html: string, csp?: McpUiResourceCsp): string {
- const meta = buildCspMetaTag(csp);
- // The doctype must stay first, or the frame drops into quirks mode.
- const doctype = html.match(/^\s*<!doctype[^>]*>/i);
- if (doctype) {
- return (
- html.slice(0, doctype[0].length) + meta + html.slice(doctype[0].length)
- );
- }
- return meta + html;
-}
diff --git a/products/desktop/apps/mobile/src/features/mcp/sandbox/useMobileAppBridge.ts b/products/desktop/apps/mobile/src/features/mcp/sandbox/useMobileAppBridge.ts
index 943af839b354..6744f828dbeb 100644
--- a/products/desktop/apps/mobile/src/features/mcp/sandbox/useMobileAppBridge.ts
+++ b/products/desktop/apps/mobile/src/features/mcp/sandbox/useMobileAppBridge.ts
@@ -10,13 +10,13 @@ import type {
ReadResourceResult,
Tool,
} from "@modelcontextprotocol/sdk/types.js";
+import { applyCspToHtml } from "@posthog/core/mcp-apps/csp";
import { useCallback, useEffect, useRef } from "react";
import { Platform } from "react-native";
import type { EdgeInsets } from "react-native-safe-area-context";
import type WebView from "react-native-webview";
import { logger } from "@/lib/logger";
import type { ThemeColors } from "@/lib/theme";
-import { applyCspToHtml } from "./mcpAppCsp";
import { buildMcpHostStyles } from "./mcpAppTheme";
import { WebViewTransport } from "./webViewTransport";
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.test.tsx b/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.test.tsx
index 74b909f31fd9..075a6f50a3a8 100644
--- a/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.test.tsx
+++ b/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.test.tsx
@@ -21,7 +21,7 @@ vi.mock("react-native-webview", () => ({
default: (props: Record<string, unknown>) => createElement("WebView", props),
}));
-vi.mock("@/features/mcp/sandbox/mcpAppCsp", () => ({
+vi.mock("@posthog/core/mcp-apps/csp", () => ({
applyCspToHtml: (html: string) => `csp:${html}`,
}));
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.tsx b/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.tsx
index 82d98f1bac99..9a88401ebcf8 100644
--- a/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.tsx
+++ b/products/desktop/apps/mobile/src/features/tasks/components/ArtifactPreview.tsx
@@ -1,3 +1,4 @@
+import { applyCspToHtml } from "@posthog/core/mcp-apps/csp";
import type { TaskRunArtifact } from "@posthog/shared";
import { useQuery } from "@tanstack/react-query";
import {
@@ -20,7 +21,6 @@ import {
import { useSafeAreaInsets } from "react-native-safe-area-context";
import WebView from "react-native-webview";
import { MarkdownText } from "@/features/chat";
-import { applyCspToHtml } from "@/features/mcp/sandbox/mcpAppCsp";
import { openExternalUrl } from "@/lib/openExternalUrl";
import { useThemeColors } from "@/lib/theme";
import { useCloudAttachmentPreview } from "../hooks/useCloudAttachmentPreview";
diff --git a/products/desktop/apps/mobile/src/features/mcp/sandbox/mcpAppCsp.test.ts b/products/desktop/packages/core/src/mcp-apps/csp.test.ts
similarity index 75%
rename from products/desktop/apps/mobile/src/features/mcp/sandbox/mcpAppCsp.test.ts
rename to products/desktop/packages/core/src/mcp-apps/csp.test.ts
index dd399a674992..ed0fa0873968 100644
--- a/products/desktop/apps/mobile/src/features/mcp/sandbox/mcpAppCsp.test.ts
+++ b/products/desktop/packages/core/src/mcp-apps/csp.test.ts
@@ -4,20 +4,47 @@ import {
buildCspMetaTag,
buildCspString,
escapeAttr,
- sanitizeDomain,
-} from "./mcpAppCsp";
+} from "./csp";
-describe("sanitizeDomain", () => {
+describe("declared origins", () => {
it.each([
- ["example.com", "example.com"],
- ["*.example.com", "*.example.com"],
- ["example.com:8080", "example.com:8080"],
- ["' unsafe-eval; script-src *;", "unsafe-evalscript-src*"],
- ['" onload=alert(1)', "onloadalert1"],
- ["example.com; frame-ancestors *", "example.comframe-ancestors*"],
- ["example .com", "example.com"],
- ])("sanitizes %j", (input, expected) => {
- expect(sanitizeDomain(input)).toBe(expected);
+ "example.com",
+ "*.example.com",
+ "example.com:8080",
+ "https://cdn.example.com",
+ "https://*.cloudflare.com",
+ "wss://api.example.com",
+ "http://localhost:8787",
+ // A fully qualified name keeps its root dot under the host-source grammar.
+ "cdn.example.com.",
+ "https://cdn.example.com.",
+ ])("reaches the policy intact: %j", (source) => {
+ expect(buildCspString({ resourceDomains: [source] })).toContain(
+ `script-src 'self' 'unsafe-inline' ${source}`,
+ );
+ });
+
+ it.each([
+ "' unsafe-eval; script-src *;",
+ '" onload=alert(1)',
+ "example .com",
+ "'self'",
+ "https:",
+ // One root dot is allowed, so guard against loosening that to any number.
+ "example.com..",
+ ])("is dropped rather than edited to fit: %j", (source) => {
+ // Editing it down to fit would grant an origin nobody declared.
+ expect(buildCspString({ resourceDomains: [source] })).toContain(
+ "script-src 'self' 'unsafe-inline';",
+ );
+ });
+
+ it("keeps the origins declared beside an invalid one", () => {
+ expect(
+ buildCspString({
+ resourceDomains: ["https://cdn.example.com", "example .com"],
+ }),
+ ).toContain("script-src 'self' 'unsafe-inline' https://cdn.example.com;");
});
});
@@ -92,11 +119,11 @@ describe("buildCspString", () => {
);
});
- it("sanitizes injection attempts in domains", () => {
+ it("drops a domain that tries to inject a directive", () => {
const result = buildCspString({
connectDomains: ["example.com; script-src 'unsafe-eval'"],
});
- expect(result).toContain("connect-src example.comscript-srcunsafe-eval");
+ expect(result).toContain("connect-src 'none'");
expect(result).not.toMatch(/;\s*script-src\s+'unsafe-eval'/);
});
});
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-csp.ts b/products/desktop/packages/core/src/mcp-apps/csp.ts
similarity index 60%
rename from products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-csp.ts
rename to products/desktop/packages/core/src/mcp-apps/csp.ts
index 758e5672afdd..dad3a22b35a3 100644
--- a/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-csp.ts
+++ b/products/desktop/packages/core/src/mcp-apps/csp.ts
@@ -17,8 +17,25 @@ import type { McpUiResourceCsp } from "@modelcontextprotocol/ext-apps/app-bridge
const DEFAULT_CSP =
"default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; connect-src 'none'; object-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'";
-export function sanitizeDomain(domain: string): string {
- return domain.replace(/[^a-zA-Z0-9.*:-]/g, "");
+// The `ui.csp` fields are named `*Domains`, but what a server puts in them is a
+// CSP source expression: an origin carrying a scheme, like
+// `https://cdn.jsdelivr.net` or `wss://api.example.com`, optionally with a
+// wildcard subdomain, a port, or a path. The `\.?` after the host labels is the
+// root dot of a fully qualified name, which the grammar permits. The path stops
+// at `;` and `,` because the grammar excludes both, and they are what a source
+// would need to escape its directive.
+//
+// @see https://www.w3.org/TR/CSP3/#grammardef-host-source
+const CSP_SOURCE =
+ /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:\/\/)?(?:\*|(?:\*\.)?[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.?)(?::(?:\d+|\*))?(?:\/[^\s"';,]*)?$/;
+
+// A declaration that is not a source expression is dropped whole, rather than
+// having its offending characters removed so that it fits. Editing it down can
+// produce a valid origin the server never declared (`example .com` becomes
+// `example.com`), and the spec lets a host restrict what was declared but not
+// widen it. Dropping keeps that decision visible instead of guessing at intent.
+function cspSources(declared: string[] | undefined): string[] {
+ return declared?.filter((source) => CSP_SOURCE.test(source)) ?? [];
}
export function buildCspString(
@@ -27,8 +44,13 @@ export function buildCspString(
): string {
if (!csp && scriptNonce === undefined) return DEFAULT_CSP;
- const resourceDomainsSuffix = csp?.resourceDomains?.length
- ? ` ${csp.resourceDomains.map(sanitizeDomain).join(" ")}`
+ const resourceSources = cspSources(csp?.resourceDomains);
+ const connectSources = cspSources(csp?.connectDomains);
+ const frameSources = cspSources(csp?.frameDomains);
+ const baseUriSources = cspSources(csp?.baseUriDomains);
+
+ const resourceDomainsSuffix = resourceSources.length
+ ? ` ${resourceSources.join(" ")}`
: "";
const directives: string[] = [
@@ -43,15 +65,14 @@ export function buildCspString(
"form-action 'none'",
];
- if (csp?.connectDomains?.length) {
- const domains = csp.connectDomains.map(sanitizeDomain).join(" ");
- directives.push(`connect-src ${domains}`);
+ if (connectSources.length) {
+ directives.push(`connect-src ${connectSources.join(" ")}`);
} else {
directives.push("connect-src 'none'");
}
- if (csp?.resourceDomains?.length) {
- const domains = csp.resourceDomains.map(sanitizeDomain).join(" ");
+ if (resourceSources.length) {
+ const domains = resourceSources.join(" ");
directives.push(`img-src 'self' data: ${domains}`);
directives.push(`media-src 'self' data: ${domains}`);
directives.push(`font-src ${domains}`);
@@ -60,16 +81,14 @@ export function buildCspString(
directives.push("media-src 'self' data:");
}
- if (csp?.frameDomains?.length) {
- const domains = csp.frameDomains.map(sanitizeDomain).join(" ");
- directives.push(`frame-src ${domains}`);
+ if (frameSources.length) {
+ directives.push(`frame-src ${frameSources.join(" ")}`);
} else {
directives.push("frame-src 'none'");
}
- if (csp?.baseUriDomains?.length) {
- const domains = csp.baseUriDomains.map(sanitizeDomain).join(" ");
- directives.push(`base-uri ${domains}`);
+ if (baseUriSources.length) {
+ directives.push(`base-uri ${baseUriSources.join(" ")}`);
} else {
directives.push("base-uri 'none'");
}
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.ts b/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.ts
index aa07669c53e8..2e2dae18d907 100644
--- a/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.ts
+++ b/products/desktop/packages/ui/src/features/mcp-apps/hooks/useAppBridge.ts
@@ -11,13 +11,13 @@ import type {
ReadResourceResult,
Tool,
} from "@modelcontextprotocol/sdk/types.js";
+import { applyCspToHtml } from "@posthog/core/mcp-apps/csp";
import type { McpUiResource } from "@posthog/core/mcp-apps/schemas";
import { getAppViewSnapshot } from "@posthog/ui/router/useAppView";
import { useCallback, useEffect, useRef } from "react";
import { logger } from "../../../shell/logger";
import { useDraftStore } from "../../message-editor/draftStore";
import type { ToolCall } from "../../sessions/types";
-import { applyCspToHtml } from "../utils/mcp-app-csp";
import {
computeContainerDimensions,
INLINE_MAX_HEIGHT,
diff --git a/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-csp.test.ts b/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-csp.test.ts
deleted file mode 100644
index 4d7f80af3130..000000000000
--- a/products/desktop/packages/ui/src/features/mcp-apps/utils/mcp-app-csp.test.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- applyCspToHtml,
- buildCspMetaTag,
- buildCspString,
- escapeAttr,
- sanitizeDomain,
-} from "./mcp-app-csp";
-
-describe("sanitizeDomain", () => {
- it("passes through valid domains", () => {
- expect(sanitizeDomain("example.com")).toBe("example.com");
- expect(sanitizeDomain("*.example.com")).toBe("*.example.com");
- // CSP domains don't include protocol slashes - slashes are stripped
- expect(sanitizeDomain("example.com:8080")).toBe("example.com:8080");
- });
-
- it("strips injection characters", () => {
- // Semicolons, quotes, and spaces are stripped; * is allowed (CSP wildcard)
- expect(sanitizeDomain("' unsafe-eval; script-src *;")).toBe(
- "unsafe-evalscript-src*",
- );
- expect(sanitizeDomain('" onload=alert(1)')).toBe("onloadalert1");
- expect(sanitizeDomain("example.com; frame-ancestors *")).toBe(
- "example.comframe-ancestors*",
- );
- });
-
- it("strips whitespace", () => {
- expect(sanitizeDomain("example .com")).toBe("example.com");
- });
-});
-
-describe("buildCspString", () => {
- it("returns default CSP when no metadata provided", () => {
- const result = buildCspString();
- expect(result).toContain("default-src 'none'");
- expect(result).toContain("script-src 'self' 'unsafe-inline'");
- expect(result).toContain("style-src 'self' 'unsafe-inline'");
- expect(result).toContain("img-src 'self' data:");
- expect(result).toContain("media-src 'self' data:");
- expect(result).toContain("connect-src 'none'");
- expect(result).toContain("frame-src 'none'");
- expect(result).toContain("form-action 'none'");
- expect(result).toContain("base-uri 'none'");
- });
-
- it("returns default CSP for empty metadata", () => {
- const result = buildCspString({});
- expect(result).toContain("connect-src 'none'");
- expect(result).toContain("frame-src 'none'");
- expect(result).toContain("form-action 'none'");
- });
-
- it("always includes form-action 'none'", () => {
- const result = buildCspString({
- connectDomains: ["api.example.com"],
- });
- expect(result).toContain("form-action 'none'");
- });
-
- it("maps connectDomains to connect-src", () => {
- const result = buildCspString({
- connectDomains: ["api.example.com", "*.cdn.example.com"],
- });
- expect(result).toContain("connect-src api.example.com *.cdn.example.com");
- });
-
- it("maps resourceDomains to img/media/font/script/style-src", () => {
- const result = buildCspString({
- resourceDomains: ["cdn.example.com"],
- });
- expect(result).toContain("img-src 'self' data: cdn.example.com");
- expect(result).toContain("media-src 'self' data: cdn.example.com");
- expect(result).toContain("font-src cdn.example.com");
- expect(result).toContain(
- "script-src 'self' 'unsafe-inline' cdn.example.com",
- );
- expect(result).toContain(
- "style-src 'self' 'unsafe-inline' cdn.example.com",
- );
- });
-
- it("does not include resourceDomains in script/style-src when not declared", () => {
- const result = buildCspString({});
- expect(result).toContain("script-src 'self' 'unsafe-inline'");
- expect(result).toContain("style-src 'self' 'unsafe-inline'");
- // Should NOT have trailing space after 'unsafe-inline'
- expect(result).not.toMatch(/script-src 'self' 'unsafe-inline' ;/);
- });
-
- it("maps frameDomains to frame-src", () => {
- const result = buildCspString({
- frameDomains: ["embed.example.com"],
- });
- expect(result).toContain("frame-src embed.example.com");
- });
-
- it("maps baseUriDomains to base-uri", () => {
- const result = buildCspString({
- baseUriDomains: ["example.com"],
- });
- expect(result).toContain("base-uri example.com");
- });
-
- it("sanitizes domains with injection attempts", () => {
- const result = buildCspString({
- connectDomains: ["example.com; script-src 'unsafe-eval'"],
- });
- // After sanitization, the semicolons, quotes, and spaces are stripped
- // so the domain can't inject new CSP directives
- expect(result).toContain("connect-src example.comscript-srcunsafe-eval");
- // The injected directive should not appear as a separate CSP directive
- expect(result).not.toMatch(/;\s*script-src\s+'unsafe-eval'/);
- });
-});
-
-describe("escapeAttr", () => {
- it("escapes double quotes", () => {
- expect(escapeAttr('hello "world"')).toBe("hello &quot;world&quot;");
- });
-
- it("escapes single quotes", () => {
- expect(escapeAttr("hello 'world'")).toBe("hello &#39;world&#39;");
- });
-
- it("escapes ampersands", () => {
- expect(escapeAttr("a & b")).toBe("a &amp; b");
- });
-
- it("escapes angle brackets", () => {
- expect(escapeAttr("<script>alert(1)</script>")).toBe(
- "&lt;script&gt;alert(1)&lt;/script&gt;",
- );
- });
-
- it("handles combination", () => {
- expect(escapeAttr(`"foo" & 'bar' <baz>`)).toBe(
- "&quot;foo&quot; &amp; &#39;bar&#39; &lt;baz&gt;",
- );
- });
-
- it("passes through safe strings", () => {
- expect(escapeAttr("default-src none")).toBe("default-src none");
- });
-});
-
-describe("buildCspMetaTag", () => {
- it("returns a valid meta tag", () => {
- const tag = buildCspMetaTag();
- expect(tag).toMatch(
- /^<meta http-equiv="Content-Security-Policy" content=".*">$/,
- );
- expect(tag).toContain("default-src");
- });
-
- it("escapes CSP content in the attribute", () => {
- const tag = buildCspMetaTag({
- connectDomains: ["example.com"],
- });
- expect(tag).toContain("connect-src example.com");
- // Verify it's inside a proper attribute
- expect(tag).toMatch(/content="[^"]+"/);
- });
-});
-
-describe("applyCspToHtml", () => {
- it("prepends the CSP meta when there is no doctype", () => {
- const out = applyCspToHtml("<html><body>hi</body></html>");
- expect(out.startsWith(buildCspMetaTag())).toBe(true);
- });
-
- it("inserts the CSP meta after a leading doctype (no quirks mode)", () => {
- const out = applyCspToHtml("<!doctype html><html><head></head></html>");
- expect(out.startsWith("<!doctype html>")).toBe(true);
- expect(out).toBe(
- `<!doctype html>${buildCspMetaTag()}<html><head></head></html>`,
- );
- });
-
- it("handles a doctype with leading whitespace and mixed case", () => {
- const out = applyCspToHtml(" <!DOCTYPE html>\n<html></html>");
- expect(out.startsWith(" <!DOCTYPE html>")).toBe(true);
- expect(out.indexOf("<!DOCTYPE html>")).toBeLessThan(
- out.indexOf(buildCspMetaTag()),
- );
- });
-});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts
index dd222c26f5b9..5c9f96645a2c 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts
@@ -1,5 +1,5 @@
+import { applyCspToHtml } from "@posthog/core/mcp-apps/csp";
import { getImageMimeType, isAllowedImageMimeType } from "@posthog/shared";
-import { applyCspToHtml } from "../../mcp-apps/utils/mcp-app-csp";
import { injectArtifactHtmlCommentBridge } from "./artifactHtmlCommentBridge";
import type { CommentSurfaceTheme } from "./selectionCommentAction";