Add mcp-apps module: Spring AI 2.1.0 MCP server with MCP Apps HTML views, app-only tool callbacks, CSP declarations, SDK client tests and a Chromium harness on the official AppBridge
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4RzcCS5JCAgcxLz7T
This commit is contained in:
@@ -0,0 +1 @@
|
||||
node_modules/
|
||||
@@ -0,0 +1,58 @@
|
||||
// Drives the official ext-apps basic-host (already running on :8080, see scripts/basic-host.sh) and writes output/08.
|
||||
import { chromium } from "playwright";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const outDir = join(here, "../output");
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined });
|
||||
const out = ["# The official ext-apps basic-host against the Spring AI server", ""];
|
||||
const consoleLines = [];
|
||||
const wire = [];
|
||||
|
||||
async function open(toolName) {
|
||||
const page = await browser.newPage({ viewport: { width: 900, height: 900 } });
|
||||
page.on("console", (m) => consoleLines.push(m.text()));
|
||||
page.on("request", (r) => { if (r.url().endsWith("/mcp") && r.postData()) wire.push(r.postData()); });
|
||||
await page.route("https://unpkg.com/**", (route) => route.fulfill({ status: 200, contentType: "text/javascript",
|
||||
headers: { "Access-Control-Allow-Origin": "*" },
|
||||
body: readFileSync(join(here, "node_modules/@modelcontextprotocol/ext-apps/dist/src/app-with-deps.js")) }));
|
||||
await page.goto("http://localhost:8080/");
|
||||
await page.locator("option[value=show_inventory]").waitFor({ state: "attached" });
|
||||
const tools = await page.locator("select").nth(1).locator("option").allTextContents();
|
||||
await page.locator("select").nth(1).selectOption(toolName);
|
||||
await page.getByRole("button", { name: "Call Tool" }).click();
|
||||
await page.waitForTimeout(5000);
|
||||
let view;
|
||||
for (const f of page.frames()) if (await f.locator("#rows").count().catch(() => 0)) view = f;
|
||||
assert.ok(view, "view frame not found");
|
||||
return { page, view, tools };
|
||||
}
|
||||
|
||||
const first = await open("show_inventory");
|
||||
out.push("tools offered in basic-host's tool list: " + JSON.stringify(first.tools));
|
||||
await first.view.locator("tr[data-sku=KB-01] button").click();
|
||||
await first.view.getByText("Restocked KB-01").waitFor();
|
||||
out.push("show_inventory, after clicking +10 on KB-01: " + await first.view.locator("#status").innerText());
|
||||
await first.view.evaluate((code) => { const s = document.createElement("script"); s.textContent = code; document.body.append(s); }, readFileSync(join(here, "probes.js"), "utf8"));
|
||||
await first.view.waitForFunction(() => window.__probes);
|
||||
out.push("", "probes in a view that declares no CSP domains:", ...await first.view.evaluate(() => window.__probes));
|
||||
await first.page.waitForTimeout(1000);
|
||||
await first.page.screenshot({ path: join(outDir, "basic-host.png"), fullPage: true });
|
||||
const body = await first.page.locator("body").innerText();
|
||||
out.push("", "basic-host Model Context panel shows: " + body.match(/The user restocked[^\n]*/)?.[0]);
|
||||
await first.page.close();
|
||||
|
||||
const second = await open("show_inventory_sdk");
|
||||
out.push("", "show_inventory_sdk renders: " + (await second.view.locator("#rows li").allInnerTexts()).join(" | "));
|
||||
await second.page.close();
|
||||
|
||||
const requests = wire.map((w) => JSON.parse(w));
|
||||
const init = requests.find((r) => r.method === "initialize");
|
||||
out.push("", "initialize sent by basic-host: " + JSON.stringify(init.params),
|
||||
"methods basic-host sent while loading and running the first tool: " + [...new Set(requests.map((r) => r.method))].join(", "));
|
||||
writeFileSync(join(outDir, "08-basic-host.txt"), out.join("\n") + "\n");
|
||||
console.log(out.join("\n"));
|
||||
await browser.close();
|
||||
@@ -0,0 +1,18 @@
|
||||
// The Content-Security-Policy a strict host builds, following "Restrictive Default" in the 2026-01-26 spec.
|
||||
const clean = (list) => (list ?? []).filter((d) => typeof d === "string" && !/[;\r\n'" ]/.test(d)).join(" ");
|
||||
|
||||
export function buildCsp(csp = {}) {
|
||||
const resources = clean(csp.resourceDomains);
|
||||
return [
|
||||
"default-src 'none'",
|
||||
`script-src 'self' 'unsafe-inline' ${resources}`,
|
||||
`style-src 'self' 'unsafe-inline' ${resources}`,
|
||||
`img-src 'self' data: ${resources}`,
|
||||
`media-src 'self' data: ${resources}`,
|
||||
`font-src ${resources || "'none'"}`,
|
||||
`connect-src ${clean(csp.connectDomains) || "'none'"}`,
|
||||
`frame-src ${clean(csp.frameDomains) || "'none'"}`,
|
||||
"object-src 'none'",
|
||||
`base-uri ${clean(csp.baseUriDomains) || "'self'"}`,
|
||||
].map((d) => d.trim().replace(/\s+/g, " ")).join("; ");
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<!DOCTYPE html><meta charset="utf-8"><title>harness host</title><body style="font:14px system-ui"><script src="/host.bundle.js"></script>
|
||||
@@ -0,0 +1,54 @@
|
||||
// A small web host built on the official AppBridge. It is a test harness, not a chat client: there is no model.
|
||||
import { AppBridge, PostMessageTransport, getToolUiResourceUri } from "@modelcontextprotocol/ext-apps/app-bridge";
|
||||
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
||||
|
||||
const MIME = "text/html;profile=mcp-app";
|
||||
window.hostLog = [];
|
||||
const log = (line) => window.hostLog.push(line);
|
||||
|
||||
window.runApp = async ({ mcpUrl, sandboxUrl, toolName, dropCsp }) => {
|
||||
const client = new Client({ name: "harness-host", version: "1.0.0" },
|
||||
{ capabilities: { extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [MIME] } } } });
|
||||
await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));
|
||||
|
||||
const tool = (await client.listTools()).tools.find((t) => t.name === toolName);
|
||||
const uri = getToolUiResourceUri(tool);
|
||||
const [content] = (await client.readResource({ uri })).contents;
|
||||
if (content.mimeType !== MIME) throw new Error("not an MCP App: " + content.mimeType);
|
||||
// dropCsp simulates a server that forgot to declare its domains.
|
||||
const csp = dropCsp ? undefined : content._meta?.ui?.csp;
|
||||
log(`host: tool ${toolName} -> ${uri}, declared csp ${JSON.stringify(csp) ?? "none"}`);
|
||||
|
||||
const frame = document.createElement("iframe");
|
||||
frame.id = "sandbox";
|
||||
frame.setAttribute("sandbox", "allow-scripts allow-same-origin");
|
||||
frame.style.cssText = "width:640px;height:260px;border:1px solid #ccc";
|
||||
document.body.append(frame);
|
||||
|
||||
const bridge = new AppBridge(client, { name: "harness-host", version: "1.0.0" },
|
||||
{ serverTools: {}, updateModelContext: { text: {} }, message: { text: {} } },
|
||||
{ hostContext: { theme: "light" } });
|
||||
|
||||
bridge.onsandboxready = () => bridge.sendSandboxResourceReady({ html: content.text, csp });
|
||||
bridge.oninitialized = async () => {
|
||||
await bridge.sendToolInput({ arguments: {} });
|
||||
await bridge.sendToolResult(await client.callTool({ name: toolName, arguments: {} }));
|
||||
log("host: tool-input and tool-result delivered");
|
||||
};
|
||||
bridge.onsizechange = ({ height }) => { if (height) frame.style.height = height + "px"; };
|
||||
bridge.onupdatemodelcontext = async (p) => { log("host: model context = " + p.content[0].text); return {}; };
|
||||
bridge.onmessage = async (p) => { log("host: chat message = " + p.content[0].text); return {}; };
|
||||
|
||||
// Wire log of what the view side sends, in order.
|
||||
window.addEventListener("message", (e) => {
|
||||
if (e.source !== frame.contentWindow) return;
|
||||
const m = e.data;
|
||||
if (m.method) {
|
||||
const detail = m.method === "tools/call" ? ` ${m.params.name} ${JSON.stringify(m.params.arguments)} (id ${m.id})` : "";
|
||||
log("view -> host: " + m.method + detail);
|
||||
}
|
||||
});
|
||||
|
||||
await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow));
|
||||
frame.src = sandboxUrl + "?csp=" + encodeURIComponent(JSON.stringify(csp ?? {}));
|
||||
};
|
||||
Generated
+252
@@ -0,0 +1,252 @@
|
||||
{
|
||||
"name": "mcp-apps-harness",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "mcp-apps-harness",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/client": "2.4.0",
|
||||
"@modelcontextprotocol/ext-apps": "2.0.4",
|
||||
"zod": "4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"esbuild": "0.28.2",
|
||||
"playwright": "1.65.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.28.2",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/client": {
|
||||
"version": "2.4.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/core": "2.4.0",
|
||||
"cross-spawn": "^7.0.5",
|
||||
"eventsource": "^3.0.2",
|
||||
"eventsource-parser": "^3.0.8",
|
||||
"jose": "^6.1.3",
|
||||
"pkce-challenge": "^5.0.0",
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/core": {
|
||||
"version": "2.4.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/ext-apps": {
|
||||
"version": "2.0.4",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"examples/*"
|
||||
],
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@modelcontextprotocol/client": "^2.0.0",
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@modelcontextprotocol/server": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
},
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@standard-schema/spec": {
|
||||
"version": "1.1.0",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.1.2",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"path-key": "^3.1.0",
|
||||
"shebang-command": "^2.0.0",
|
||||
"which": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.28.2",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"esbuild": "bin/esbuild"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@esbuild/aix-ppc64": "0.28.2",
|
||||
"@esbuild/android-arm": "0.28.2",
|
||||
"@esbuild/android-arm64": "0.28.2",
|
||||
"@esbuild/android-x64": "0.28.2",
|
||||
"@esbuild/darwin-arm64": "0.28.2",
|
||||
"@esbuild/darwin-x64": "0.28.2",
|
||||
"@esbuild/freebsd-arm64": "0.28.2",
|
||||
"@esbuild/freebsd-x64": "0.28.2",
|
||||
"@esbuild/linux-arm": "0.28.2",
|
||||
"@esbuild/linux-arm64": "0.28.2",
|
||||
"@esbuild/linux-ia32": "0.28.2",
|
||||
"@esbuild/linux-loong64": "0.28.2",
|
||||
"@esbuild/linux-mips64el": "0.28.2",
|
||||
"@esbuild/linux-ppc64": "0.28.2",
|
||||
"@esbuild/linux-riscv64": "0.28.2",
|
||||
"@esbuild/linux-s390x": "0.28.2",
|
||||
"@esbuild/linux-x64": "0.28.2",
|
||||
"@esbuild/netbsd-arm64": "0.28.2",
|
||||
"@esbuild/netbsd-x64": "0.28.2",
|
||||
"@esbuild/openbsd-arm64": "0.28.2",
|
||||
"@esbuild/openbsd-x64": "0.28.2",
|
||||
"@esbuild/openharmony-arm64": "0.28.2",
|
||||
"@esbuild/sunos-x64": "0.28.2",
|
||||
"@esbuild/win32-arm64": "0.28.2",
|
||||
"@esbuild/win32-ia32": "0.28.2",
|
||||
"@esbuild/win32-x64": "0.28.2"
|
||||
}
|
||||
},
|
||||
"node_modules/eventsource": {
|
||||
"version": "3.0.7",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"eventsource-parser": "^3.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eventsource-parser": {
|
||||
"version": "3.1.1",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/isexe": {
|
||||
"version": "2.0.0",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/jose": {
|
||||
"version": "6.3.0",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/path-key": {
|
||||
"version": "3.1.1",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/pkce-challenge": {
|
||||
"version": "5.0.2",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.65.2",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.65.2"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.65.2",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/shebang-command": {
|
||||
"version": "2.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"shebang-regex": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shebang-regex": {
|
||||
"version": "3.0.0",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"isexe": "^2.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"node-which": "bin/node-which"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "4.6.7",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "mcp-apps-harness",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": { "test": "node run.mjs" },
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/client": "2.4.0",
|
||||
"@modelcontextprotocol/ext-apps": "2.0.4",
|
||||
"zod": "4.6.7"
|
||||
},
|
||||
"devDependencies": { "esbuild": "0.28.2", "playwright": "1.65.2" }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Runs inside the view's frame as a real inline script, so the page's CSP applies to it (DevTools evaluate would not).
|
||||
(async () => {
|
||||
const r = [];
|
||||
// Wait for a new task: while a DevTools call is still on the stack, Chromium lets eval through whatever the CSP says.
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
try { eval("1"); r.push("eval(): ALLOWED"); } catch (e) { r.push("eval(): " + e.name); }
|
||||
try { await fetch(location.ancestorOrigins[0] + "/sandbox.html"); r.push("fetch from the sandbox origin ('self'): ALLOWED"); }
|
||||
catch (e) { r.push("fetch from the sandbox origin ('self'): " + e.name); }
|
||||
try { await fetch("https://api.example.com/stock"); r.push("fetch undeclared origin: ALLOWED"); }
|
||||
catch (e) { r.push("fetch undeclared origin: " + e.name); }
|
||||
window.__probes = r;
|
||||
})();
|
||||
@@ -0,0 +1,163 @@
|
||||
// Drives the Java server through the harness host in a real Chromium and writes output/05..07.
|
||||
// Usage: node run.mjs (the jar must already be built: mvn -pl mcp-apps package)
|
||||
import { build } from "esbuild";
|
||||
import { chromium } from "playwright";
|
||||
import { spawn } from "node:child_process";
|
||||
import { createServer } from "node:http";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildCsp } from "./csp.mjs";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const jar = join(here, "../target/mcp-apps.jar");
|
||||
const outDir = join(here, "../output");
|
||||
const MCP = "http://localhost:3001/mcp";
|
||||
const SANDBOX = "http://127.0.0.1:7002/sandbox.html";
|
||||
const SDK_FILE = join(here, "node_modules/@modelcontextprotocol/ext-apps/dist/src/app-with-deps.js");
|
||||
|
||||
const bundle = (await build({ entryPoints: [join(here, "host.js")], bundle: true, format: "iife", write: false,
|
||||
logLevel: "error", absWorkingDir: here })).outputFiles[0].text;
|
||||
|
||||
const hostServer = createServer((req, res) => {
|
||||
if (req.url === "/host.bundle.js") return res.writeHead(200, { "Content-Type": "text/javascript" }).end(bundle);
|
||||
res.writeHead(200, { "Content-Type": "text/html" }).end(readFileSync(join(here, "host.html")));
|
||||
}).listen(7001);
|
||||
const sandboxServer = createServer((req, res) => {
|
||||
const url = new URL(req.url, SANDBOX);
|
||||
res.writeHead(200, { "Content-Type": "text/html", "Content-Security-Policy": buildCsp(JSON.parse(url.searchParams.get("csp") ?? "{}")) })
|
||||
.end(readFileSync(join(here, "sandbox.html")));
|
||||
}).listen(7002, "127.0.0.1");
|
||||
|
||||
async function startJava(profiles) {
|
||||
const proc = spawn("java", ["-jar", jar, "--app.cors-origins=http://localhost:7001", "--logging.level.root=warn",
|
||||
...(profiles ? ["--spring.profiles.active=" + profiles] : [])], { stdio: "ignore" });
|
||||
for (let i = 0; i < 120; i++) {
|
||||
try { await fetch(MCP); return proc; } catch { await new Promise((r) => setTimeout(r, 500)); }
|
||||
}
|
||||
throw new Error("server did not start");
|
||||
}
|
||||
const stop = (proc) => new Promise((r) => { proc.once("exit", r); proc.kill(); });
|
||||
|
||||
const addInlineScript = (code) => { const s = document.createElement("script"); s.textContent = code; document.body.append(s); };
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined });
|
||||
async function open(toolName, extra = {}) {
|
||||
const page = await browser.newPage({ viewport: { width: 700, height: 420 } });
|
||||
const consoleLines = [];
|
||||
page.on("console", (m) => consoleLines.push(m.text()));
|
||||
page.on("pageerror", (e) => consoleLines.push("pageerror: " + e.message));
|
||||
// unpkg.com is answered from the pinned npm package, so the run does not depend on the CDN.
|
||||
// The browser still applies the CSP before the request is made.
|
||||
await page.route("https://unpkg.com/**", (route) => route.fulfill({ status: 200, body: readFileSync(SDK_FILE),
|
||||
contentType: "text/javascript", headers: { "Access-Control-Allow-Origin": "*" } }));
|
||||
await page.goto("http://localhost:7001/");
|
||||
await page.evaluate((a) => window.runApp(a), { mcpUrl: MCP, sandboxUrl: SANDBOX, toolName, ...extra });
|
||||
const view = page.frameLocator("#sandbox").frameLocator("#view");
|
||||
const log = () => page.evaluate(() => window.hostLog);
|
||||
return { page, view, log, consoleLines };
|
||||
}
|
||||
const inner = (page) => page.frames().find((f) => f.url() === "about:srcdoc");
|
||||
const pause = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const rowText = async (view) => (await view.locator("#rows tr").allInnerTexts()).map((t) => t.replace(/\s+/g, " ").trim());
|
||||
const violations = (lines) => lines.filter((l) => /Content Security Policy/i.test(l))
|
||||
.map((l) => l.replace(/\s+/g, " ").replace(/\. Note that .*$/, "."));
|
||||
const write = (name, lines) => { writeFileSync(join(outDir, name), lines.join("\n") + "\n"); console.log("wrote", name); };
|
||||
|
||||
let java;
|
||||
try {
|
||||
// ---------- 05: the hand-written view, end to end ----------
|
||||
java = await startJava();
|
||||
{
|
||||
const out = ["# Hand-written view (board.html) in Chromium, AppBridge as the host, strict CSP", ""];
|
||||
const { page, view, log } = await open("show_inventory");
|
||||
await view.locator("tr[data-sku=KB-01]").waitFor();
|
||||
out.push("## rows after the tool result", ...(await rowText(view)));
|
||||
await view.locator("tr[data-sku=KB-01] button").click();
|
||||
await view.getByText("Restocked KB-01").waitFor();
|
||||
await pause(500);
|
||||
out.push("", "## rows after clicking +10 on KB-01", ...(await rowText(view)), "", "status line: " + await view.locator("#status").innerText());
|
||||
const seen = (await log()).filter((l, i, a) => !(l.includes("size-changed") && a.indexOf(l) !== i));
|
||||
out.push("", "## host log (repeated size-changed lines removed)", ...seen);
|
||||
await page.screenshot({ path: join(outDir, "board.png") });
|
||||
|
||||
const frame = inner(page);
|
||||
const probes = await frame.evaluate(async () => {
|
||||
const r = [];
|
||||
try { window.top.document.title; r.push("read host page DOM: ALLOWED"); } catch (e) { r.push("read host page DOM: " + e.name); }
|
||||
try { await fetch("https://api.example.com/stock"); r.push("fetch undeclared origin: ALLOWED"); } catch (e) { r.push("fetch undeclared origin: " + e.name + ": " + e.message); }
|
||||
try { await fetch("http://localhost:3001/mcp"); r.push("fetch the MCP server directly: ALLOWED"); } catch (e) { r.push("fetch the MCP server directly: " + e.name + ": " + e.message); }
|
||||
const ask = (params) => new Promise((resolve) => {
|
||||
const id = Math.floor(Math.random() * 1e6) + 5000;
|
||||
addEventListener("message", function on(e) { if (e.data.id === id && !e.data.method) { removeEventListener("message", on); resolve(e.data); } });
|
||||
parent.postMessage({ jsonrpc: "2.0", id, method: "ui/message", params }, "*");
|
||||
});
|
||||
const text = { type: "text", text: "hi" };
|
||||
for (const [label, content] of [["ui/message, content as one object (spec text)", text], ["ui/message, content as an array (SDK types)", [text]]]) {
|
||||
const reply = await ask({ role: "user", content });
|
||||
r.push(label + ": " + (reply.error ? "error " + reply.error.code : "ok"));
|
||||
}
|
||||
return r;
|
||||
});
|
||||
await frame.evaluate(addInlineScript, readFileSync(join(here, "probes.js"), "utf8"));
|
||||
await frame.waitForFunction(() => window.__probes);
|
||||
out.push("", "## probes run inside the view's frame", ...probes, ...await frame.evaluate(() => window.__probes));
|
||||
assert.ok(probes[0].endsWith("SecurityError"));
|
||||
assert.ok(probes[1].includes("TypeError") && probes[2].includes("TypeError"));
|
||||
assert.ok((await rowText(view))[0].includes(" 14 "));
|
||||
write("05-browser-board.txt", out);
|
||||
await page.close();
|
||||
}
|
||||
await stop(java);
|
||||
|
||||
// ---------- 06: the SDK view and its CSP declaration ----------
|
||||
java = await startJava();
|
||||
{
|
||||
const out = ["# SDK view (board-sdk.html), strict CSP", ""];
|
||||
const good = await open("show_inventory_sdk");
|
||||
await good.view.locator("li", { hasText: "KB-01" }).waitFor();
|
||||
await good.view.locator("#ask").click();
|
||||
await good.view.getByText("Sent to the chat.").waitFor();
|
||||
out.push("## with _meta.ui.csp.resourceDomains = [https://unpkg.com]", ...(await good.view.locator("li").allInnerTexts()),
|
||||
...(await good.log()).filter((l) => l.startsWith("host:")));
|
||||
await good.page.screenshot({ path: join(outDir, "board-sdk.png") });
|
||||
await good.page.close();
|
||||
|
||||
const bad = await open("show_inventory_sdk", { dropCsp: true });
|
||||
await pause(4000);
|
||||
out.push("", "## the same view when no domains are declared, 4 seconds later",
|
||||
"view shows: " + (await bad.view.locator("#rows").innerText()).trim(),
|
||||
...(await bad.log()), "browser console:", ...violations(bad.consoleLines));
|
||||
assert.ok(violations(bad.consoleLines).length > 0);
|
||||
assert.ok(!(await bad.log()).some((l) => l.includes("ui/initialize")));
|
||||
write("06-browser-csp.txt", out);
|
||||
await bad.page.close();
|
||||
}
|
||||
await stop(java);
|
||||
|
||||
// ---------- 07: a poisoned product name ----------
|
||||
const out = ["# A product name carrying <img onerror=...>, rendered two ways", ""];
|
||||
for (const [profile, label] of [["poisoned", "textContent (the shipped view)"], ["unsafe", "innerHTML (app.unsafe-render=true)"]]) {
|
||||
java = await startJava(profile);
|
||||
const { page, view, log } = await open("show_inventory");
|
||||
await view.locator("tr[data-sku=CB-99]").waitFor();
|
||||
await pause(2500);
|
||||
const calls = (await log()).filter((l) => l.includes("tools/call"));
|
||||
const stock = await inner(page).evaluate(() => new Promise((resolve) => {
|
||||
addEventListener("message", function on(e) { if (e.data.id === 777) { removeEventListener("message", on); resolve(e.data.result.structuredContent.items[0].stock); } });
|
||||
parent.postMessage({ jsonrpc: "2.0", id: 777, method: "tools/call", params: { name: "show_inventory", arguments: {} } }, "*");
|
||||
}));
|
||||
out.push("## " + label, "CB-99 row text: " + (await view.locator("tr[data-sku=CB-99] td").nth(1).innerText()).slice(0, 60), "clicks by the user: 0",
|
||||
"tools/call sent by the view: " + (calls.length ? "" : "none"), ...calls, "KB-01 stock on the server afterwards: " + stock, "");
|
||||
assert.equal(stock, profile === "unsafe" ? 103 : 4);
|
||||
await page.close();
|
||||
await stop(java);
|
||||
}
|
||||
write("07-browser-injection.txt", out);
|
||||
java = undefined;
|
||||
} finally {
|
||||
java?.kill();
|
||||
await browser.close();
|
||||
hostServer.close();
|
||||
sandboxServer.close();
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<!DOCTYPE html>
|
||||
<meta charset="utf-8">
|
||||
<title>sandbox proxy</title>
|
||||
<style>html,body,iframe{margin:0;border:0;width:100%;height:100%}</style>
|
||||
<body>
|
||||
<script>
|
||||
// The proxy of the spec: a second origin between the host and the view. It loads the HTML and relays messages.
|
||||
const inner = document.createElement("iframe");
|
||||
inner.id = "view";
|
||||
inner.setAttribute("sandbox", "allow-scripts allow-same-origin");
|
||||
const HOST = "http://localhost:7001";
|
||||
window.addEventListener("message", (event) => {
|
||||
if (event.source === window.parent && event.origin === HOST) {
|
||||
if (event.data.method === "ui/notifications/sandbox-resource-ready") {
|
||||
inner.srcdoc = event.data.params.html; // srcdoc inherits this page's CSP header
|
||||
document.body.append(inner);
|
||||
} else {
|
||||
inner.contentWindow?.postMessage(event.data, "*");
|
||||
}
|
||||
} else if (event.source === inner.contentWindow) {
|
||||
window.parent.postMessage(event.data, HOST);
|
||||
}
|
||||
});
|
||||
window.parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/sandbox-proxy-ready", params: {} }, HOST);
|
||||
</script>
|
||||
Reference in New Issue
Block a user