fix: proper CSP handling in basic-host sandboxing (HTTP headers, worker-src, document.write) (#234)
* fix: Move CSP to HTTP headers + add worker-src, frameDomains, baseUriDomains, permissions Security improvements: - CSP is now set via HTTP headers in serve.ts instead of meta tags (meta tag CSP can be tampered with by same-origin content) - CSP passed as query param to sandbox.html for header-based enforcement New CSP/permissions features (borrowed from PR #158): - frameDomains: control frame-src directive for nested iframes - baseUriDomains: control base-uri directive - permissions: camera, microphone, geolocation via iframe allow attribute WebGL fix: - Use document.write() instead of srcdoc for inner iframe content (srcdoc creates opaque origin that breaks WebGL canvas updates) - Add worker-src directive with blob: support (critical for WebGL apps like CesiumJS/Three.js that use workers for tile decoding, terrain processing, image processing) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: Remove permissions support (defer to PR #158) Keep this PR focused on CSP security fixes only. Permissions (camera, microphone, geolocation) will be handled in #158. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * cleanup McpUiResourceCsp type usage / duplicate defs * fix: guard against CSP injection in domain parameters Validate CSP domain entries to reject characters that could: - Break out of CSP directives (semicolons, newlines) - Inject CSP keywords like 'unsafe-eval' (quotes) - Inject multiple sources in one entry (spaces) This prevents injection attacks where malicious domains could override the security policy. --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
df49e88b2d
commit
8b09f4278c
4 changed files with 572 additions and 155 deletions
|
|
@ -1,10 +1,10 @@
|
|||
import { RESOURCE_MIME_TYPE, getToolUiResourceUri, type McpUiSandboxProxyReadyNotification, AppBridge, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge";
|
||||
import { RESOURCE_MIME_TYPE, getToolUiResourceUri, type McpUiSandboxProxyReadyNotification, AppBridge, PostMessageTransport, type McpUiResourceCsp } from "@modelcontextprotocol/ext-apps/app-bridge";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import type { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
|
||||
|
||||
|
||||
const SANDBOX_PROXY_URL = new URL("http://localhost:8081/sandbox.html");
|
||||
const SANDBOX_PROXY_BASE_URL = "http://localhost:8081/sandbox.html";
|
||||
const IMPLEMENTATION = { name: "MCP Apps Host", version: "1.0.0" };
|
||||
|
||||
|
||||
|
|
@ -42,10 +42,7 @@ export async function connectToServer(serverUrl: URL): Promise<ServerInfo> {
|
|||
|
||||
interface UiResourceData {
|
||||
html: string;
|
||||
csp?: {
|
||||
connectDomains?: string[];
|
||||
resourceDomains?: string[];
|
||||
};
|
||||
csp?: McpUiResourceCsp;
|
||||
}
|
||||
|
||||
export interface ToolCallInfo {
|
||||
|
|
@ -120,7 +117,10 @@ async function getUiResource(serverInfo: ServerInfo, uri: string): Promise<UiRes
|
|||
}
|
||||
|
||||
|
||||
export function loadSandboxProxy(iframe: HTMLIFrameElement): Promise<boolean> {
|
||||
export function loadSandboxProxy(
|
||||
iframe: HTMLIFrameElement,
|
||||
csp?: McpUiResourceCsp,
|
||||
): Promise<boolean> {
|
||||
// Prevent reload
|
||||
if (iframe.src) return Promise.resolve(false);
|
||||
|
||||
|
|
@ -140,8 +140,14 @@ export function loadSandboxProxy(iframe: HTMLIFrameElement): Promise<boolean> {
|
|||
window.addEventListener("message", listener);
|
||||
});
|
||||
|
||||
log.info("Loading sandbox proxy...");
|
||||
iframe.src = SANDBOX_PROXY_URL.href;
|
||||
// Build sandbox URL with CSP query param for HTTP header-based CSP
|
||||
const sandboxUrl = new URL(SANDBOX_PROXY_BASE_URL);
|
||||
if (csp) {
|
||||
sandboxUrl.searchParams.set("csp", JSON.stringify(csp));
|
||||
}
|
||||
|
||||
log.info("Loading sandbox proxy...", csp ? `(CSP: ${JSON.stringify(csp)})` : "");
|
||||
iframe.src = sandboxUrl.href;
|
||||
|
||||
return readyPromise;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -263,16 +263,21 @@ function AppIFramePanel({ toolCallInfo, isDestroying, onTeardownComplete }: AppI
|
|||
|
||||
useEffect(() => {
|
||||
const iframe = iframeRef.current!;
|
||||
loadSandboxProxy(iframe).then((firstTime) => {
|
||||
// The `firstTime` check guards against React Strict Mode's double
|
||||
// invocation (mount → unmount → remount simulation in development).
|
||||
// Outside of Strict Mode, this `useEffect` runs only once per
|
||||
// `toolCallInfo`.
|
||||
if (firstTime) {
|
||||
const appBridge = newAppBridge(toolCallInfo.serverInfo, iframe);
|
||||
appBridgeRef.current = appBridge;
|
||||
initializeApp(iframe, appBridge, toolCallInfo);
|
||||
}
|
||||
|
||||
// First get CSP from resource, then load sandbox with CSP in query param
|
||||
// This ensures CSP is set via HTTP headers (tamper-proof)
|
||||
toolCallInfo.appResourcePromise.then(({ csp }) => {
|
||||
loadSandboxProxy(iframe, csp).then((firstTime) => {
|
||||
// The `firstTime` check guards against React Strict Mode's double
|
||||
// invocation (mount → unmount → remount simulation in development).
|
||||
// Outside of Strict Mode, this `useEffect` runs only once per
|
||||
// `toolCallInfo`.
|
||||
if (firstTime) {
|
||||
const appBridge = newAppBridge(toolCallInfo.serverInfo, iframe);
|
||||
appBridgeRef.current = appBridge;
|
||||
initializeApp(iframe, appBridge, toolCallInfo);
|
||||
}
|
||||
});
|
||||
});
|
||||
}, [toolCallInfo]);
|
||||
|
||||
|
|
|
|||
|
|
@ -62,26 +62,9 @@ const PROXY_READY_NOTIFICATION: McpUiSandboxProxyReadyNotification["method"] =
|
|||
// Special case: The "ui/notifications/sandbox-proxy-ready" message is
|
||||
// intercepted here (not relayed) because the Sandbox uses it to configure and
|
||||
// load the inner iframe with the Guest UI HTML content.
|
||||
// Build CSP meta tag from domains
|
||||
function buildCspMetaTag(csp?: { connectDomains?: string[]; resourceDomains?: string[] }): string {
|
||||
const resourceDomains = csp?.resourceDomains?.join(" ") ?? "";
|
||||
const connectDomains = csp?.connectDomains?.join(" ") ?? "";
|
||||
|
||||
// Base CSP directives
|
||||
const directives = [
|
||||
"default-src 'self'",
|
||||
`script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: data: ${resourceDomains}`.trim(),
|
||||
`style-src 'self' 'unsafe-inline' blob: data: ${resourceDomains}`.trim(),
|
||||
`img-src 'self' data: blob: ${resourceDomains}`.trim(),
|
||||
`font-src 'self' data: blob: ${resourceDomains}`.trim(),
|
||||
`connect-src 'self' ${connectDomains}`.trim(),
|
||||
"frame-src 'none'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
];
|
||||
|
||||
return `<meta http-equiv="Content-Security-Policy" content="${directives.join("; ")}">`;
|
||||
}
|
||||
//
|
||||
// Security: CSP is enforced via HTTP headers on sandbox.html (set by serve.ts
|
||||
// based on ?csp= query param). This is tamper-proof unlike meta tags.
|
||||
|
||||
window.addEventListener("message", async (event) => {
|
||||
if (event.source === window.parent) {
|
||||
|
|
@ -98,29 +81,26 @@ window.addEventListener("message", async (event) => {
|
|||
}
|
||||
|
||||
if (event.data && event.data.method === RESOURCE_READY_NOTIFICATION) {
|
||||
const { html, sandbox, csp } = event.data.params;
|
||||
const { html, sandbox } = event.data.params;
|
||||
if (typeof sandbox === "string") {
|
||||
inner.setAttribute("sandbox", sandbox);
|
||||
}
|
||||
if (typeof html === "string") {
|
||||
// Inject CSP meta tag at the start of <head> if CSP is provided
|
||||
console.log("[Sandbox] Received CSP:", csp);
|
||||
let modifiedHtml = html;
|
||||
if (csp) {
|
||||
const cspMetaTag = buildCspMetaTag(csp);
|
||||
console.log("[Sandbox] Injecting CSP meta tag:", cspMetaTag);
|
||||
// Insert after <head> tag if present, otherwise prepend
|
||||
if (modifiedHtml.includes("<head>")) {
|
||||
modifiedHtml = modifiedHtml.replace("<head>", `<head>\n${cspMetaTag}`);
|
||||
} else if (modifiedHtml.includes("<head ")) {
|
||||
modifiedHtml = modifiedHtml.replace(/<head[^>]*>/, `$&\n${cspMetaTag}`);
|
||||
} else {
|
||||
modifiedHtml = cspMetaTag + modifiedHtml;
|
||||
}
|
||||
// Use document.write instead of srcdoc for WebGL compatibility.
|
||||
// srcdoc creates an opaque origin which prevents WebGL canvas updates
|
||||
// from being displayed properly. document.write preserves the sandbox
|
||||
// origin, allowing WebGL to work correctly.
|
||||
// CSP is enforced via HTTP headers on this page (sandbox.html).
|
||||
const doc = inner.contentDocument || inner.contentWindow?.document;
|
||||
if (doc) {
|
||||
doc.open();
|
||||
doc.write(html);
|
||||
doc.close();
|
||||
} else {
|
||||
console.log("[Sandbox] No CSP provided, using default");
|
||||
// Fallback to srcdoc if document is not accessible
|
||||
console.warn("[Sandbox] document.write not available, falling back to srcdoc");
|
||||
inner.srcdoc = html;
|
||||
}
|
||||
inner.srcdoc = modifiedHtml;
|
||||
}
|
||||
} else {
|
||||
if (inner && inner.contentWindow) {
|
||||
|
|
|
|||
325
examples/basic-host/src/tamper-detection.ts
Normal file
325
examples/basic-host/src/tamper-detection.ts
Normal file
|
|
@ -0,0 +1,325 @@
|
|||
/**
|
||||
* Tamper Detection Module for MCP-UI Sandbox
|
||||
*
|
||||
* Generates a script that monitors security-sensitive JavaScript APIs
|
||||
* and emits notifications when guest code accesses them.
|
||||
*/
|
||||
|
||||
export type TamperRuleTarget =
|
||||
| "window"
|
||||
| "Element.prototype"
|
||||
| "Document.prototype"
|
||||
| "Node.prototype"
|
||||
| "HTMLElement.prototype"
|
||||
| "EventTarget.prototype"
|
||||
| "History.prototype"
|
||||
| "Location.prototype";
|
||||
|
||||
export type TamperRuleType = "getter" | "method" | "both";
|
||||
export type TamperSeverity = "low" | "medium" | "high" | "critical";
|
||||
|
||||
export interface TamperRule {
|
||||
target: TamperRuleTarget;
|
||||
property: string;
|
||||
type: TamperRuleType;
|
||||
severity: TamperSeverity;
|
||||
}
|
||||
|
||||
export const TAMPER_DETECTED_NOTIFICATION =
|
||||
"ui/notifications/tamper-detected" as const;
|
||||
|
||||
/**
|
||||
* Default rules for security-sensitive APIs.
|
||||
* - critical: Access is blocked (returns undefined / throws)
|
||||
* - high/medium/low: Access is allowed but an alert is emitted
|
||||
*/
|
||||
export const DEFAULT_TAMPER_RULES: TamperRule[] = [
|
||||
// === CRITICAL (blocked) ===
|
||||
// Escape attempts
|
||||
{ target: "window", property: "top", type: "getter", severity: "critical" },
|
||||
{
|
||||
target: "window",
|
||||
property: "parent",
|
||||
type: "getter",
|
||||
severity: "critical",
|
||||
},
|
||||
{
|
||||
target: "window",
|
||||
property: "opener",
|
||||
type: "getter",
|
||||
severity: "critical",
|
||||
},
|
||||
{
|
||||
target: "window",
|
||||
property: "frameElement",
|
||||
type: "getter",
|
||||
severity: "critical",
|
||||
},
|
||||
// Code execution
|
||||
{ target: "window", property: "eval", type: "method", severity: "critical" },
|
||||
|
||||
// === HIGH (allowed with alert) ===
|
||||
{ target: "window", property: "Function", type: "getter", severity: "high" },
|
||||
// Network/data exfiltration
|
||||
{ target: "window", property: "fetch", type: "method", severity: "high" },
|
||||
{
|
||||
target: "window",
|
||||
property: "XMLHttpRequest",
|
||||
type: "getter",
|
||||
severity: "high",
|
||||
},
|
||||
{ target: "window", property: "WebSocket", type: "getter", severity: "high" },
|
||||
{
|
||||
target: "window",
|
||||
property: "EventSource",
|
||||
type: "getter",
|
||||
severity: "high",
|
||||
},
|
||||
// DOM injection (high-risk methods)
|
||||
{
|
||||
target: "Document.prototype",
|
||||
property: "write",
|
||||
type: "method",
|
||||
severity: "high",
|
||||
},
|
||||
{
|
||||
target: "Document.prototype",
|
||||
property: "writeln",
|
||||
type: "method",
|
||||
severity: "high",
|
||||
},
|
||||
{
|
||||
target: "Element.prototype",
|
||||
property: "insertAdjacentHTML",
|
||||
type: "method",
|
||||
severity: "high",
|
||||
},
|
||||
|
||||
// === MEDIUM (allowed with alert) ===
|
||||
// Storage access
|
||||
{
|
||||
target: "window",
|
||||
property: "localStorage",
|
||||
type: "getter",
|
||||
severity: "medium",
|
||||
},
|
||||
{
|
||||
target: "window",
|
||||
property: "sessionStorage",
|
||||
type: "getter",
|
||||
severity: "medium",
|
||||
},
|
||||
{
|
||||
target: "window",
|
||||
property: "indexedDB",
|
||||
type: "getter",
|
||||
severity: "medium",
|
||||
},
|
||||
{ target: "window", property: "caches", type: "getter", severity: "medium" },
|
||||
// DOM injection (property-based)
|
||||
{
|
||||
target: "Element.prototype",
|
||||
property: "innerHTML",
|
||||
type: "both",
|
||||
severity: "medium",
|
||||
},
|
||||
{
|
||||
target: "Element.prototype",
|
||||
property: "outerHTML",
|
||||
type: "both",
|
||||
severity: "medium",
|
||||
},
|
||||
// DOM traversal
|
||||
{
|
||||
target: "Node.prototype",
|
||||
property: "parentNode",
|
||||
type: "getter",
|
||||
severity: "medium",
|
||||
},
|
||||
{
|
||||
target: "Node.prototype",
|
||||
property: "parentElement",
|
||||
type: "getter",
|
||||
severity: "medium",
|
||||
},
|
||||
{
|
||||
target: "Element.prototype",
|
||||
property: "closest",
|
||||
type: "method",
|
||||
severity: "medium",
|
||||
},
|
||||
// History manipulation
|
||||
{ target: "window", property: "history", type: "getter", severity: "medium" },
|
||||
{
|
||||
target: "window",
|
||||
property: "location",
|
||||
type: "getter",
|
||||
severity: "medium",
|
||||
},
|
||||
|
||||
// === LOW (allowed with alert) ===
|
||||
// Message passing
|
||||
{
|
||||
target: "window",
|
||||
property: "postMessage",
|
||||
type: "method",
|
||||
severity: "low",
|
||||
},
|
||||
// DOM queries
|
||||
{
|
||||
target: "Document.prototype",
|
||||
property: "querySelector",
|
||||
type: "method",
|
||||
severity: "low",
|
||||
},
|
||||
{
|
||||
target: "Document.prototype",
|
||||
property: "querySelectorAll",
|
||||
type: "method",
|
||||
severity: "low",
|
||||
},
|
||||
{
|
||||
target: "Document.prototype",
|
||||
property: "getElementById",
|
||||
type: "method",
|
||||
severity: "low",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Generates the tamper detection script as a string.
|
||||
* This script should be injected into guest HTML before any other scripts run.
|
||||
*/
|
||||
export function generateTamperDetectionScript(
|
||||
rules: TamperRule[] = DEFAULT_TAMPER_RULES,
|
||||
): string {
|
||||
const rulesJson = JSON.stringify(rules);
|
||||
|
||||
return `(function() {
|
||||
'use strict';
|
||||
|
||||
var NOTIFICATION_METHOD = '${TAMPER_DETECTED_NOTIFICATION}';
|
||||
var rules = ${rulesJson};
|
||||
|
||||
function emitTamperAlert(rule, accessType, stackTrace) {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: '2.0',
|
||||
method: NOTIFICATION_METHOD,
|
||||
params: {
|
||||
property: rule.target + '.' + rule.property,
|
||||
accessType: accessType,
|
||||
severity: rule.severity,
|
||||
blocked: rule.severity === 'critical',
|
||||
timestamp: Date.now(),
|
||||
stack: stackTrace
|
||||
}
|
||||
}, '*');
|
||||
} catch (e) {
|
||||
// Silently fail if postMessage is unavailable
|
||||
}
|
||||
}
|
||||
|
||||
function shouldBlock(rule) {
|
||||
return rule.severity === 'critical';
|
||||
}
|
||||
|
||||
function wrapProperty(target, prop, rule) {
|
||||
var descriptor = Object.getOwnPropertyDescriptor(target, prop);
|
||||
if (!descriptor) return false;
|
||||
|
||||
var newDescriptor = {
|
||||
configurable: false,
|
||||
enumerable: descriptor.enumerable
|
||||
};
|
||||
|
||||
var wrapped = false;
|
||||
|
||||
if (rule.type === 'getter' || rule.type === 'both') {
|
||||
var originalGetter = descriptor.get || (function() { return descriptor.value; });
|
||||
newDescriptor.get = function() {
|
||||
emitTamperAlert(rule, 'read', new Error().stack);
|
||||
if (shouldBlock(rule)) {
|
||||
return undefined;
|
||||
}
|
||||
return originalGetter.call(this);
|
||||
};
|
||||
wrapped = true;
|
||||
}
|
||||
|
||||
if (rule.type === 'method' && typeof descriptor.value === 'function') {
|
||||
var originalMethod = descriptor.value;
|
||||
newDescriptor.value = function() {
|
||||
emitTamperAlert(rule, 'call', new Error().stack);
|
||||
if (shouldBlock(rule)) {
|
||||
throw new Error('Access to ' + rule.target + '.' + rule.property + ' is blocked');
|
||||
}
|
||||
return originalMethod.apply(this, arguments);
|
||||
};
|
||||
wrapped = true;
|
||||
}
|
||||
|
||||
if (rule.type === 'both' && descriptor.set) {
|
||||
var originalSetter = descriptor.set;
|
||||
newDescriptor.set = function(value) {
|
||||
emitTamperAlert(rule, 'write', new Error().stack);
|
||||
if (shouldBlock(rule)) {
|
||||
return;
|
||||
}
|
||||
return originalSetter.call(this, value);
|
||||
};
|
||||
}
|
||||
|
||||
if (wrapped) {
|
||||
try {
|
||||
Object.defineProperty(target, prop, newDescriptor);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function getTargetObject(targetName) {
|
||||
switch (targetName) {
|
||||
case 'window': return window;
|
||||
case 'Element.prototype': return Element.prototype;
|
||||
case 'Document.prototype': return Document.prototype;
|
||||
case 'Node.prototype': return Node.prototype;
|
||||
case 'HTMLElement.prototype': return HTMLElement.prototype;
|
||||
case 'EventTarget.prototype': return EventTarget.prototype;
|
||||
case 'History.prototype': return History.prototype;
|
||||
case 'Location.prototype': return Location.prototype;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Install monitoring
|
||||
for (var i = 0; i < rules.length; i++) {
|
||||
var rule = rules[i];
|
||||
var target = getTargetObject(rule.target);
|
||||
if (target) {
|
||||
wrapProperty(target, rule.property, rule);
|
||||
}
|
||||
}
|
||||
})();`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Injects a script into HTML content, ensuring it runs before any other scripts.
|
||||
*/
|
||||
export function injectScriptIntoHtml(html: string, script: string): string {
|
||||
const scriptTag = `<script>${script}</script>`;
|
||||
|
||||
// Try <head> first
|
||||
if (html.includes("<head>")) {
|
||||
return html.replace("<head>", `<head>${scriptTag}`);
|
||||
}
|
||||
// Try <body>
|
||||
if (html.includes("<body>")) {
|
||||
return html.replace("<body>", `<body>${scriptTag}`);
|
||||
}
|
||||
// Fallback: prepend
|
||||
return scriptTag + html;
|
||||
}
|
||||
Loading…
Reference in a new issue