Open History to see the last commit
1import * as NodeVM from "node:vm";
2import { describe, expect, it } from "vite-plus/test";
3
4import {
5 injectMcpAppCsp,
6 injectMcpAppThemeBootstrap,
7 injectMcpAppCookieBootstrap,
8 mcpAppContentSecurityPolicy,
9 mcpAppToolCallableByApp,
10 mcpAppToolResourceUri,
11 readMcpAppCsp,
12 readMcpAppReference,
13} from "./mcpApp.ts";
14
15describe("mcpAppContentSecurityPolicy", () => {
16 it("blocks the network and T3's own origin when the app declares nothing", () => {
17 const policy = mcpAppContentSecurityPolicy(undefined);
18 expect(policy).toContain("default-src 'none'");
19 expect(policy).toContain("connect-src 'none'");
20 expect(policy).toContain("frame-src 'none'");
21 expect(policy).not.toContain("'self'");
22 });
23
24 it("allows exactly the declared origins", () => {
25 const policy = mcpAppContentSecurityPolicy({
26 connectDomains: ["https://api.weather.test"],
27 resourceDomains: ["https://*.cdn.test"],
28 });
29 expect(policy).toContain("connect-src https://api.weather.test");
30 expect(policy).toContain("script-src 'unsafe-inline' https://*.cdn.test");
31 expect(policy).toContain("img-src data: blob: https://*.cdn.test");
32 });
33});
34
35describe("injectMcpAppCsp", () => {
36 it("puts the policy after the doctype and ahead of every script", () => {
37 const html = "<!DOCTYPE html><html><head><script>x()</script></head></html>";
38 const injected = injectMcpAppCsp(html, undefined);
39 expect(injected.startsWith('<!DOCTYPE html><meta http-equiv="Content-Security-Policy"')).toBe(
40 true,
41 );
42 expect(injected.indexOf("connect-src 'none'")).toBeLessThan(injected.indexOf("<script>"));
43 expect(injectMcpAppCsp("<p>hi</p>", undefined).startsWith("<!doctype html><meta")).toBe(true);
44 });
45});
46
47describe("injectMcpAppThemeBootstrap", () => {
48 it("keeps stored CSP before the bootstrap and vendor scripts after it", () => {
49 const snapshot = injectMcpAppCsp(
50 "<html><head><script>vendor()</script></head></html>",
51 undefined,
52 );
53 const html = injectMcpAppThemeBootstrap(snapshot);
54 expect(html.indexOf("Content-Security-Policy")).toBeLessThan(html.indexOf("<script>"));
55 expect(html.indexOf("window.addEventListener")).toBeLessThan(html.indexOf("vendor()"));
56 expect(html.endsWith(snapshot.slice(snapshot.indexOf("<html>")))).toBe(true);
57 });
58
59 it("applies parent initialize and theme changes while ignoring unrelated or invalid messages", () => {
60 const html = injectMcpAppThemeBootstrap(injectMcpAppCsp("<p>app</p>", undefined));
61 const script = html.slice(html.indexOf("<script>") + 8, html.indexOf("</script>"));
62 const parent = {};
63 const style = { colorScheme: "normal" };
64 let receive: ((event: { source: object; data: unknown }) => void) | undefined;
65 NodeVM.runInNewContext(script, {
66 window: {
67 parent,
68 addEventListener: (_type: string, callback: typeof receive) => {
69 receive = callback;
70 },
71 },
72 document: { documentElement: { style } },
73 });
74 const send = (data: unknown, source = parent) => receive?.({ source, data });
75 const initialized = { jsonrpc: "2.0", id: 1, result: { hostContext: { theme: "dark" } } };
76 send(initialized, {});
77 expect(style.colorScheme).toBe("normal");
78 send(initialized);
79 expect(style.colorScheme).toBe("dark");
80 for (const data of [
81 null,
82 "bad",
83 {},
84 { ...initialized, jsonrpc: "1.0" },
85 { jsonrpc: "2.0", method: "other", params: { theme: "light" } },
86 {
87 jsonrpc: "2.0",
88 method: "ui/notifications/host-context-changed",
89 params: { theme: "normal" },
90 },
91 { jsonrpc: "2.0", result: { hostContext: { theme: "light" } } },
92 ])
93 send(data);
94 expect(style.colorScheme).toBe("dark");
95 send({
96 jsonrpc: "2.0",
97 method: "ui/notifications/host-context-changed",
98 params: { theme: "light" },
99 });
100 expect(style.colorScheme).toBe("light");
101 send(initialized);
102 expect(style.colorScheme).toBe("dark");
103 });
104});
105
106describe("readMcpAppCsp", () => {
107 it("drops entries that could widen or break the policy", () => {
108 expect(
109 readMcpAppCsp({
110 connectDomains: [
111 "https://ok.test",
112 "*",
113 "'self'",
114 "https://evil.test; script-src *",
115 "http://localhost:3000",
116 "javascript:alert(1)",
117 ],
118 resourceDomains: "https://not-an-array.test",
119 }),
120 ).toEqual({ connectDomains: ["https://ok.test", "http://localhost:3000"] });
121 expect(readMcpAppCsp({ connectDomains: ["*"] })).toBeUndefined();
122 });
123});
124
125describe("readMcpAppReference", () => {
126 it("requires a ui:// resource and the owning server and tool", () => {
127 const reference = {
128 attachmentId: "thread-1-abc-html",
129 server: "weather",
130 tool: "get_weather",
131 resourceUri: "ui://weather/dashboard",
132 };
133 expect(readMcpAppReference(reference)).toEqual(reference);
134 expect(readMcpAppReference({ ...reference, resourceUri: "https://x.test" })).toBeUndefined();
135 expect(readMcpAppReference({ ...reference, server: "" })).toBeUndefined();
136 });
137});
138
139describe("tool metadata", () => {
140 it("reads the resource URI from either spelling and honors app visibility", () => {
141 const uri = "ui://weather/card.html";
142 expect(mcpAppToolResourceUri({ ui: { resourceUri: uri } })).toBe(uri);
143 expect(
144 mcpAppToolResourceUri({ ui: { visibility: ["model", "app"] }, "ui/resourceUri": uri }),
145 ).toBe(uri);
146 expect(
147 mcpAppToolResourceUri({ ui: { resourceUri: "https://weather/card.html" } }),
148 ).toBeUndefined();
149 expect(mcpAppToolCallableByApp(undefined)).toBe(true);
150 expect(mcpAppToolCallableByApp({ ui: { visibility: ["model"] } })).toBe(false);
151 expect(mcpAppToolCallableByApp({ ui: { visibility: ["model", "app"] } })).toBe(true);
152 });
153});
154
155describe("mcpAppFromToolItem", () => {
156 it("reads the app from both the stored output and its compact wire form", async () => {
157 const { compactDynamicToolOutput, mcpAppFromToolItem } = await import("./toolOutput.ts");
158 const app = {
159 attachmentId: "thread-1-abc-html",
160 server: "weather",
161 tool: "get_weather",
162 resourceUri: "ui://weather/dashboard",
163 };
164 const stored = { t3McpApp: app, result: { content: [] } };
165 const toolName = "weather.get_weather";
166 expect(mcpAppFromToolItem({ toolName, output: stored })).toEqual(app);
167 expect(mcpAppFromToolItem({ toolName, output: compactDynamicToolOutput(stored) })).toEqual(app);
168 });
169
170 it("ignores a reference naming a server or tool other than the item's own", async () => {
171 const { mcpAppFromToolItem } = await import("./toolOutput.ts");
172 const forged = {
173 t3McpApp: {
174 attachmentId: "thread-1-abc-html",
175 server: "bank",
176 tool: "transfer",
177 resourceUri: "ui://bank/app",
178 },
179 };
180 expect(mcpAppFromToolItem({ toolName: "evil.lookup", output: forged })).toBeUndefined();
181 expect(mcpAppFromToolItem({ toolName: "bank.transfer", output: forged })).toBeDefined();
182 // Claude Code names the same tool `mcp__<server>__<tool>`.
183 expect(mcpAppFromToolItem({ toolName: "mcp__bank__transfer", output: forged })).toBeDefined();
184 expect(mcpAppFromToolItem({ toolName: "mcp__evil__transfer", output: forged })).toBeUndefined();
185 const connector = { t3McpApp: { ...forged.t3McpApp, server: "claude.ai Asana (Beta)" } };
186 expect(
187 mcpAppFromToolItem({ toolName: "mcp__claude_ai_Asana_Beta__transfer", output: connector }),
188 ).toBeDefined();
189 });
190
191 it("keeps an app whose resource URI is longer than a name", async () => {
192 const { compactDynamicToolOutput } = await import("./toolOutput.ts");
193 const resourceUri = `ui://weather/${"segment/".repeat(60)}dashboard`;
194 const output = compactDynamicToolOutput({
195 t3McpApp: {
196 attachmentId: "thread-1-abc-html",
197 server: "weather",
198 tool: "get_weather",
199 resourceUri,
200 },
201 });
202 expect(output?.t3McpApp?.resourceUri).toBe(resourceUri);
203 });
204
205 it("keeps the compact app reference within the wire budget", async () => {
206 const { compactDynamicToolOutput } = await import("./toolOutput.ts");
207 const domains = Array.from(
208 { length: 32 },
209 (_, index) => `https://${"a".repeat(200)}${index}.test`,
210 );
211 const output = compactDynamicToolOutput({
212 t3McpApp: {
213 attachmentId: "thread-1-abc-html",
214 server: "weather",
215 tool: "get_weather",
216 resourceUri: "ui://weather/dashboard",
217 csp: { connectDomains: domains, resourceDomains: domains },
218 },
219 });
220 expect(new TextEncoder().encode(JSON.stringify(output)).byteLength).toBeLessThanOrEqual(8_192);
221 expect(output?.t3McpApp?.server).toBe("weather");
222 });
223});
224
225describe("MCP App cookie bootstrap", () => {
226 const vendor = `<script>document.cookie.split(";");document.cookie="analytics=1";document.root="rendered";</script>`;
227 const execute = (html: string, document: object) => {
228 for (const script of html.matchAll(/<script>([\s\S]*?)<\/script>/g)) {
229 NodeVM.runInNewContext(script[1]!, { document });
230 }
231 };
232
233 it("lets cookie-reading startup code render in an opaque document without granting storage", () => {
234 const blocked = new DOMException("Opaque origin", "SecurityError");
235 const prototype = Object.defineProperty({}, "cookie", {
236 get() {
237 throw blocked;
238 },
239 set() {
240 throw blocked;
241 },
242 });
243 const document = Object.assign(
244 Object.create(prototype) as { cookie: string; root: string; indexedDB: unknown },
245 { root: "" },
246 );
247 Object.defineProperty(document, "indexedDB", {
248 get() {
249 throw blocked;
250 },
251 });
252 const saved = injectMcpAppCsp(vendor, { connectDomains: ["https://analytics.example"] });
253 const html = injectMcpAppCookieBootstrap(saved);
254 expect(html.indexOf("Content-Security-Policy")).toBeLessThan(html.indexOf("<script>"));
255 expect(html).toContain("connect-src https://analytics.example");
256 execute(html, document);
257 expect(document.root).toBe("rendered");
258 expect(document.cookie).toBe("");
259 document.cookie = "session=secret";
260 expect(document.cookie).toBe("");
261 expect(() => document.indexedDB).toThrow(blocked);
262 expect(() => Reflect.get(prototype, "cookie")).toThrow(blocked);
263 });
264
265 it("leaves other cookie failures unchanged", () => {
266 const failure = new TypeError("Unexpected cookie failure");
267 const document = Object.defineProperty({}, "cookie", {
268 get() {
269 throw failure;
270 },
271 });
272 expect(() => execute(injectMcpAppCookieBootstrap(vendor), document)).toThrow(failure);
273 expect(() => Reflect.get(document, "cookie")).toThrow(failure);
274 });
275});