@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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