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