@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, 04:45 UTC

main
ts 632 lines 28.7 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - plain local servers stand in for LAN services.
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, describe, expect, it } from "@effect/vitest";
4 import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
5 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
6 import * as HostProcess from "@t3tools/shared/HostProcess";
7 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
8 import * as Deferred from "effect/Deferred";
9 import * as Effect from "effect/Effect";
10 import * as Exit from "effect/Exit";
11 import * as Base64 from "effect/encoding/Base64";
12 import * as Fiber from "effect/Fiber";
13 import * as FileSystem from "effect/FileSystem";
14 import * as Layer from "effect/Layer";
15 import * as Option from "effect/Option";
16 import * as Path from "effect/Path";
17 import * as NodeDgram from "node:dgram";
18 import * as NodeHttp from "node:http";
19 import * as NodeURL from "node:url";
20
21 import { resolveAttachmentPathById } from "../attachmentStore.ts";
22 import * as ServerConfig from "../config.ts";
23 import * as HtmlRender from "./HtmlRender.ts";
24 import { HtmlRenderBrowserError } from "./headlessChrome.ts";
25 import * as PreviewBrowser from "../preview/PreviewBrowser.ts";
26 import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts";
27
28 const TEST_BROWSER_ENV = "T3CODE_TEST_HEADLESS_SHELL";
29
30 const layerHtmlRender = (
31 executable?: string,
32 installed: Effect.Effect<Option.Option<string>> = Effect.succeed(
33 Option.fromUndefinedOr(executable),
34 ),
35 ) =>
36 HtmlRender.layer.pipe(
37 Layer.provide(
38 Layer.succeed(
39 PreviewBrowser.PreviewBrowser,
40 PreviewBrowser.PreviewBrowser.of({
41 executable:
42 executable === undefined
43 ? Effect.die("This test has no preview browser.")
44 : Effect.succeed(executable),
45 installed,
46 }),
47 ),
48 ),
49 Layer.provideMerge(McpProviderSessions.layer),
50 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-html-render-" })),
51 Layer.provideMerge(NodeServices.layer),
52 );
53 const layerTest = layerHtmlRender();
54
55 const PNG_BYTES = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
56
57 describe("HtmlRender", () => {
58 it.effect("inlines local images by absolute path and leaves URLs and relative paths alone", () =>
59 Effect.gen(function* () {
60 const fileSystem = yield* FileSystem.FileSystem;
61 const path = yield* Path.Path;
62 const htmlRender = yield* HtmlRender.HtmlRender;
63 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
64 const png = path.join(directory, "shot.png");
65 const svg = path.join(directory, "logo.svg");
66 yield* fileSystem.writeFile(png, PNG_BYTES);
67 yield* fileSystem.writeFileString(svg, "<svg/>");
68 const kept = [
69 "https://example.com/a.png",
70 "//cdn.example.com/b.png",
71 "./c.png",
72 "data:image/png;base64,AAAA",
73 ];
74
75 const prepared = yield* htmlRender.prepare(
76 [
77 "<!doctype html><html><head><title>Shots</title></head><body>",
78 `<img src="${png}"><div style="background:url(${svg})"></div>`,
79 `<script>const shots = ['${png}', \`${svg}\`];</script>`,
80 ...kept.map((src) => `<img src="${src}">`),
81 "</body></html>",
82 ].join(""),
83 );
84
85 const pngUri = `data:image/png;base64,${Base64.encode(PNG_BYTES)}`;
86 const svgUri = `data:image/svg+xml;base64,${Base64.encode("<svg/>")}`;
87 expect(prepared).toContain(`<img src="${pngUri}">`);
88 expect(prepared).toContain(`url(${svgUri})`);
89 expect(prepared).toContain(`['${pngUri}', \`${svgUri}\`]`);
90 expect(prepared).not.toContain(directory);
91 for (const src of kept) expect(prepared).toContain(`<img src="${src}">`);
92 expect(prepared.indexOf("<head>")).toBeLessThan(prepared.indexOf('<style id="t3-theme">'));
93 expect(prepared.indexOf('<style id="t3-theme">')).toBeLessThan(prepared.indexOf("<title>"));
94 }).pipe(Effect.provide(layerTest)),
95 );
96
97 it.effect("rejects viewport height units, which make the fitted frame grow without end", () =>
98 Effect.gen(function* () {
99 const htmlRender = yield* HtmlRender.HtmlRender;
100 for (const page of [
101 "<style>main{min-height:100vh}</style>",
102 "<style media=screen>main{height: calc(100dvh - 2rem)}",
103 "<div style='top:.5svh'></div>",
104 "<div style=height:100vh></div>",
105 ]) {
106 const error = yield* htmlRender.prepare(page).pipe(Effect.flip);
107 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderViewportHeightError);
108 }
109 yield* htmlRender.prepare(
110 '<style>main{width:100vw;height:320px}</style><img src="data:image/png;base64,AB1vh+2vh/3vhC">',
111 );
112 yield* htmlRender.prepare(
113 "<p>Avoid 100vh here.</p><!-- <div style=\"height:100vh\"></div> --><script>const unit = '100vh';</script>",
114 );
115 yield* htmlRender.prepare(`<style>${"1".repeat(200_000)}vx</style>`);
116 }).pipe(Effect.provide(layerTest)),
117 );
118
119 it.effect("inlines an SVG behind processing instructions and a doctype subset", () =>
120 Effect.gen(function* () {
121 const fileSystem = yield* FileSystem.FileSystem;
122 const path = yield* Path.Path;
123 const htmlRender = yield* HtmlRender.HtmlRender;
124 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
125 const svg = path.join(directory, "styled.svg");
126 const source = [
127 '<?xml version="1.0"?>',
128 '<?xml-stylesheet href="theme.css"?>',
129 '<!DOCTYPE svg [ <!ENTITY fill "red"> ]>',
130 '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>',
131 ].join("\n");
132 yield* fileSystem.writeFileString(svg, source);
133
134 const prepared = yield* htmlRender.prepare(`<img src="${svg}">`);
135
136 expect(prepared).toContain(`data:image/svg+xml;base64,${Base64.encode(source)}`);
137 }).pipe(Effect.provide(layerTest)),
138 );
139
140 it.effect("lists every local image it cannot read", () =>
141 Effect.gen(function* () {
142 const fileSystem = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const htmlRender = yield* HtmlRender.HtmlRender;
145 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
146 const folder = path.join(directory, "folder.png");
147 yield* fileSystem.makeDirectory(folder);
148 const missing = path.join(directory, "missing.jpg");
149 const secret = path.join(directory, "secret.png");
150 yield* fileSystem.writeFileString(secret, "API_KEY=abc123");
151 const report = path.join(directory, "report.svg");
152 yield* fileSystem.writeFileString(report, "<!doctype html><body><svg></svg>API_KEY=abc123");
153 const config = path.join(directory, "config.svg");
154 yield* fileSystem.writeFileString(
155 config,
156 '<!DOCTYPE config [<!ENTITY a "a"><!ENTITY b "]><svg/>">]><config>API_KEY=abc123</config>',
157 );
158 const stalling = path.join(directory, "stalling.svg");
159 yield* fileSystem.writeFileString(stalling, `${"<?p?>".repeat(40)}<config><svg/></config>`);
160 const unclosed = path.join(directory, "unclosed.svg");
161 yield* fileSystem.writeFileString(unclosed, '<!DOCTYPE svg [<!ENTITY a "x><svg/>');
162 const upper = path.join(directory, "upper.svg");
163 yield* fileSystem.writeFileString(upper, "<SVG/>API_KEY=abc123");
164 const longer = path.join(directory, "longer.svg");
165 yield* fileSystem.writeFileString(longer, "<svg\u00e9/>API_KEY=abc123");
166
167 const error = yield* htmlRender
168 .prepare(
169 `<img src="${missing}"><img src='${folder}'><img src="C:\\nope\\shot.webp"><img src="${secret}"><img src="${report}"><img src="${config}"><img src="${stalling}"><img src="${unclosed}"><img src="${upper}"><img src="${longer}">`,
170 )
171 .pipe(Effect.flip);
172
173 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderImagesNotFoundError);
174 expect(error._tag === "HtmlRenderImagesNotFoundError" && error.paths).toEqual([
175 missing,
176 folder,
177 "C:\\nope\\shot.webp",
178 secret,
179 report,
180 config,
181 stalling,
182 unclosed,
183 upper,
184 longer,
185 ]);
186 }).pipe(Effect.provide(layerTest)),
187 );
188
189 it.effect("publishes the prepared page as an html thread attachment", () =>
190 Effect.gen(function* () {
191 const fileSystem = yield* FileSystem.FileSystem;
192 const config = yield* ServerConfig.ServerConfig;
193 const htmlRender = yield* HtmlRender.HtmlRender;
194 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
195 const threadId = ThreadId.make("thread-html-render");
196 const session = {
197 environmentId: EnvironmentId.make("html-render-environment"),
198 threadId,
199 providerSessionId: "first-credential",
200 providerInstanceId: ProviderInstanceId.make("claude"),
201 endpoint: "http://localhost:8311/mcp",
202 authorizationHeader: "Bearer first-token",
203 browserToolsAvailable: false,
204 };
205 yield* mcpSessions.set(session);
206
207 const reference = yield* htmlRender.publish({
208 threadId,
209 html: `<p>Quarterly revenue</p>${" ".repeat(8_000)}`,
210 title: " Revenue ",
211 height: 9_000,
212 });
213
214 expect(reference).toEqual({
215 attachmentId: expect.any(String),
216 title: "Revenue",
217 height: 2_000,
218 });
219 const stored = resolveAttachmentPathById({
220 attachmentsDir: config.attachmentsDir,
221 attachmentId: reference.attachmentId,
222 });
223 expect(stored?.endsWith(".html")).toBe(true);
224 const html = yield* fileSystem.readFileString(stored ?? "");
225 expect(html).toContain('<style id="t3-theme">');
226 expect(html).toContain("<p>Quarterly revenue</p>");
227 // Antigravity reports the call without its result, so the thread's
228 // provider session keeps the page for one call with these arguments.
229 const page = {
230 html: `<p>Quarterly revenue</p>${" ".repeat(8_000)}`,
231 title: " Revenue ",
232 height: 9_000,
233 };
234 expect(
235 yield* mcpSessions.takeHtmlRender(threadId, {
236 ...page,
237 html: page.html.replace("revenue", "expense"),
238 }),
239 ).toBe(undefined);
240 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(reference);
241 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
242 const reused = yield* htmlRender.publish({ threadId, ...page });
243 yield* mcpSessions.set({ ...session, browserToolsAvailable: true });
244 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(reused);
245 const first = yield* htmlRender.publish({ threadId, ...page });
246 const second = yield* htmlRender.publish({ threadId, ...page });
247 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(first);
248 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(second);
249 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
250
251 yield* htmlRender.publish({ threadId, ...page });
252 yield* mcpSessions.set({
253 ...session,
254 providerSessionId: "replacement-credential",
255 providerInstanceId: ProviderInstanceId.make("antigravity"),
256 authorizationHeader: "Bearer replacement-token",
257 });
258 const replacement = yield* htmlRender.publish({ threadId, ...page });
259 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(replacement);
260 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
261 // Clearing the thread's MCP session drops the pages it kept.
262 yield* htmlRender.publish({ threadId, ...page });
263 yield* mcpSessions.clear(threadId);
264 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
265 }).pipe(Effect.provide(layerTest)),
266 );
267
268 it.effect("publishes a page from an .html file as a snapshot that path calls recover", () =>
269 Effect.gen(function* () {
270 const fileSystem = yield* FileSystem.FileSystem;
271 const path = yield* Path.Path;
272 const config = yield* ServerConfig.ServerConfig;
273 const htmlRender = yield* HtmlRender.HtmlRender;
274 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
275 const threadId = ThreadId.make("thread-html-path");
276 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-page-" });
277 const file = path.join(directory, "report.html");
278 yield* fileSystem.writeFileString(file, "<!doctype html><p>First draft</p>");
279 const page = { path: file, title: "Report", height: 300 };
280
281 const first = yield* htmlRender.publish({ threadId, ...page });
282 yield* fileSystem.writeFileString(file, "<!doctype html><p>Second draft</p>");
283 const second = yield* htmlRender.publish({ threadId, ...page });
284 const inline = { html: "<!doctype html><p>First draft</p>", title: "Report", height: 300 };
285 const inlineReference = yield* htmlRender.publish({ threadId, ...inline });
286
287 const stored = yield* fileSystem.readFileString(
288 resolveAttachmentPathById({
289 attachmentsDir: config.attachmentsDir,
290 attachmentId: first.attachmentId,
291 }) ?? "",
292 );
293 expect(stored).toContain("<p>First draft</p>");
294 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...page, path: `${file}x` })).toBe(
295 undefined,
296 );
297 for (const html of [inline.html, false]) {
298 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...page, html })).toBe(undefined);
299 }
300 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...inline, path: null })).toEqual(
301 inlineReference,
302 );
303 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...page, html: null })).toEqual(first);
304 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(second);
305 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
306 }).pipe(Effect.provide(layerTest)),
307 );
308
309 it.effect("refuses anything but a regular, singly linked .html file of at most 25 MiB", () =>
310 Effect.gen(function* () {
311 const fileSystem = yield* FileSystem.FileSystem;
312 const path = yield* Path.Path;
313 const config = yield* ServerConfig.ServerConfig;
314 const htmlRender = yield* HtmlRender.HtmlRender;
315 const threadId = ThreadId.make("thread-html-path-guard");
316 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-page-" });
317 const secret = path.join(directory, "id_rsa");
318 yield* fileSystem.writeFileString(secret, "PRIVATE KEY");
319 const page = path.join(directory, "page.html");
320 yield* fileSystem.writeFileString(page, "<!doctype html><p>linked</p>");
321 const hardLinked = path.join(directory, "linked.html");
322 yield* fileSystem.link(page, hardLinked);
323 // `mv .env renamed.html` keeps one link and an .html name; only its bytes give it away.
324 const renamed = path.join(directory, "renamed.html");
325 yield* fileSystem.writeFileString(renamed, "API_KEY=abc123\n");
326 const folder = path.join(directory, "folder.html");
327 yield* fileSystem.makeDirectory(folder);
328 const internal = path.join(config.secretsDir, "page.html");
329 yield* fileSystem.makeDirectory(config.secretsDir, { recursive: true });
330 yield* fileSystem.writeFileString(internal, "<!doctype html><p>internal</p>");
331
332 for (const file of [
333 "page.html",
334 "//attacker/share/page.html",
335 path.join(directory, "missing.html"),
336 secret,
337 hardLinked,
338 renamed,
339 folder,
340 internal,
341 ]) {
342 const error = yield* htmlRender
343 .publish({ threadId, path: file, title: "X", height: 200 })
344 .pipe(Effect.flip);
345 expect(error, file).toBeInstanceOf(HtmlRender.HtmlRenderFileError);
346 }
347 const huge = path.join(directory, "huge.html");
348 yield* fileSystem.writeFileString(huge, "");
349 yield* fileSystem.truncate(huge, 25 * 1024 * 1024 + 1);
350 const tooLarge = yield* htmlRender
351 .publish({ threadId, path: huge, title: "X", height: 200 })
352 .pipe(Effect.flip);
353 expect(tooLarge).toBeInstanceOf(HtmlRender.HtmlRenderFileTooLargeError);
354 }).pipe(Effect.provide(layerTest)),
355 );
356
357 it.effect.skipIf(!symlinksSupported)("refuses an .html symlink to another file", () =>
358 Effect.gen(function* () {
359 const fileSystem = yield* FileSystem.FileSystem;
360 const path = yield* Path.Path;
361 const htmlRender = yield* HtmlRender.HtmlRender;
362 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-page-" });
363 const secret = path.join(directory, "id_rsa");
364 yield* fileSystem.writeFileString(secret, "PRIVATE KEY");
365 const symlinked = path.join(directory, "symlinked.html");
366 yield* fileSystem.symlink(secret, symlinked);
367
368 const error = yield* htmlRender
369 .publish({
370 threadId: ThreadId.make("thread-html-path-link"),
371 path: symlinked,
372 title: "X",
373 height: 200,
374 })
375 .pipe(Effect.flip);
376
377 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderFileError);
378 }).pipe(Effect.provide(layerTest)),
379 );
380
381 it.effect("removes the page when publishing is interrupted", () =>
382 Effect.gen(function* () {
383 const threadId = ThreadId.make("thread-html-cancel");
384 const page = { html: "<p>x</p>", title: "X", height: 200 };
385 const measuring = yield* Deferred.make<void>();
386 yield* Effect.gen(function* () {
387 const fileSystem = yield* FileSystem.FileSystem;
388 const config = yield* ServerConfig.ServerConfig;
389 const htmlRender = yield* HtmlRender.HtmlRender;
390 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
391 const storedPages = fileSystem
392 .readDirectory(config.attachmentsDir, { recursive: true })
393 .pipe(Effect.map((names) => names.filter((name) => name.endsWith(".html"))));
394
395 const publishing = yield* htmlRender.publish({ threadId, ...page }).pipe(Effect.forkChild);
396 yield* Deferred.await(measuring);
397 expect(yield* storedPages).toHaveLength(1);
398 yield* Fiber.interrupt(publishing);
399 expect(yield* storedPages).toEqual([]);
400 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
401 }).pipe(
402 Effect.provide(
403 layerHtmlRender(
404 undefined,
405 Deferred.succeed(measuring, undefined).pipe(Effect.andThen(Effect.never)),
406 ),
407 ),
408 );
409 }),
410 );
411
412 // Windows reports ENOENT asynchronously for this path instead of throwing ENOTDIR.
413 describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
414 "when the browser spawn throws synchronously",
415 () => {
416 it.live("reports a typed preview error", () =>
417 Effect.gen(function* () {
418 const fileSystem = yield* FileSystem.FileSystem;
419 const path = yield* Path.Path;
420 const file = yield* fileSystem.makeTempFileScoped({ prefix: "t3-browser-spawn-" });
421 const outcome = yield* HtmlRender.HtmlRender.use((htmlRender) =>
422 htmlRender.preview({ html: "<p>x</p>" }).pipe(Effect.flip),
423 ).pipe(
424 Effect.provide(layerHtmlRender(path.join(file, "chrome-headless-shell"))),
425 Effect.exit,
426 );
427 assert(Exit.isSuccess(outcome), "Expected a typed preview error.");
428 const error = outcome.value;
429 expect(error).toBeInstanceOf(HtmlRenderBrowserError);
430 expect(error.message).toBe(
431 "Headless Chrome could not render the page: the browser could not be started.",
432 );
433 expect(error).toMatchObject({ cause: { code: "ENOTDIR" } });
434 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
435 );
436 },
437 );
438
439 // The fake browser is a shebang script, which Windows cannot execute.
440 describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
441 "when the browser cannot be signalled",
442 () => {
443 // A browser T3 cannot signal, as under AppArmor in an LXC container, must still exit.
444 it.live("asks the browser to close when the preview finishes instead of signalling it", () =>
445 Effect.gen(function* () {
446 const fileSystem = yield* FileSystem.FileSystem;
447 const path = yield* Path.Path;
448 const directory = yield* fileSystem.makeTempDirectoryScoped({
449 prefix: "t3-fake-browser-",
450 });
451 const executable = path.join(directory, "chrome-headless-shell");
452 const exitRecord = path.join(directory, "exited");
453 yield* fileSystem.writeFileString(
454 executable,
455 `#!${process.execPath}
456 const fs = require("node:fs");
457 process.on("SIGTERM", () => {});
458 const quit = () => { fs.writeFileSync(${JSON.stringify(exitRecord)}, "asked to close"); process.exit(0); };
459 const reply = (message) => fs.writeSync(4, JSON.stringify(message) + "\\0");
460 const results = {
461 "Target.createBrowserContext": { browserContextId: "context" },
462 "Target.createTarget": { targetId: "page" },
463 "Target.attachToTarget": { sessionId: "session" },
464 "Runtime.evaluate": { result: { value: 100 } },
465 "Page.captureScreenshot": { data: "iVBORw0KGgo=" },
466 };
467 let buffered = "";
468 fs.createReadStream(null, { fd: 3 }).on("end", quit).on("data", (chunk) => {
469 const messages = (buffered + chunk).split("\\0");
470 buffered = messages.pop();
471 for (const { id, method, sessionId } of messages.map((raw) => JSON.parse(raw))) {
472 if (method === "Browser.close") quit();
473 reply({ id, sessionId, result: results[method] ?? {} });
474 if (method === "Page.navigate") {
475 const value = "x" + "\u{1F600}".repeat(300);
476 const params = { type: "log", args: [{ type: "string", value }] };
477 reply({ sessionId, method: "Runtime.consoleAPICalled", params });
478 reply({ sessionId, method: "Page.loadEventFired", params: {} });
479 }
480 }
481 });
482 `,
483 { mode: 0o755 },
484 );
485
486 const preview = yield* HtmlRender.HtmlRender.use((htmlRender) =>
487 htmlRender.preview({ html: "<p>x</p>" }),
488 ).pipe(Effect.provide(layerHtmlRender(executable)));
489 const logged = preview.consoleMessages[0]?.text ?? "";
490 expect(logged.isWellFormed()).toBe(true);
491 expect(logged).toHaveLength(500);
492
493 const exitedBy = yield* fileSystem.readFileString(exitRecord).pipe(Effect.option);
494 expect(Option.getOrElse(exitedBy, () => "killed by a signal")).toBe("asked to close");
495 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
496 );
497
498 it.live("names this server's home in the browser setup command", () =>
499 Effect.gen(function* () {
500 const fileSystem = yield* FileSystem.FileSystem;
501 const path = yield* Path.Path;
502 const directory = yield* fileSystem.makeTempDirectoryScoped({
503 prefix: "t3-fake-browser-",
504 });
505 const executable = path.join(directory, "chrome-headless-shell");
506 yield* fileSystem.writeFileString(
507 executable,
508 `#!${process.execPath}\nprocess.stderr.write(${JSON.stringify(PreviewBrowserHost.NO_SANDBOX_SIGNATURE)});\nprocess.exit(1);\n`,
509 { mode: 0o755 },
510 );
511
512 const { error, baseDir } = yield* Effect.gen(function* () {
513 const { baseDir } = yield* ServerConfig.ServerConfig;
514 const htmlRender = yield* HtmlRender.HtmlRender;
515 const error = yield* htmlRender.preview({ html: "<p>x</p>" }).pipe(Effect.flip);
516 return { error, baseDir };
517 }).pipe(
518 Effect.provide(layerHtmlRender(executable)),
519 Effect.provideService(HostProcess.UserId, 1000),
520 );
521 expect(error).toBeInstanceOf(PreviewBrowserHost.PreviewBrowserSandboxError);
522 expect(error.message).toContain(`browser setup --base-dir ${baseDir}`);
523 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
524 );
525 },
526 );
527
528 it.live("matches preview media queries and text colors to the requested appearance", (ctx) =>
529 Effect.gen(function* () {
530 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
531 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
532 yield* Effect.gen(function* () {
533 const htmlRender = yield* HtmlRender.HtmlRender;
534 for (const appearance of [undefined, "dark", "light"] as const) {
535 const preview = yield* htmlRender.preview({
536 appearance,
537 html: [
538 "<style>h1{color:#18181b}@media(prefers-color-scheme:dark){h1{color:#fafafa}}</style>",
539 "<h1>The moon garden opens at dusk</h1>",
540 '<script>console.log(matchMedia("(prefers-color-scheme:dark)").matches,',
541 'getComputedStyle(document.querySelector("h1")).color);</script>',
542 ].join(""),
543 });
544 expect(preview.consoleMessages).toContainEqual({
545 level: "log",
546 text: appearance === "light" ? "false rgb(24, 24, 27)" : "true rgb(250, 250, 250)",
547 });
548 }
549 }).pipe(Effect.provide(layerHtmlRender(executable)));
550 }),
551 );
552
553 it.live("keeps every local file but the page itself out of the browser", (ctx) =>
554 Effect.gen(function* () {
555 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
556 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
557 yield* Effect.gen(function* () {
558 const fileSystem = yield* FileSystem.FileSystem;
559 const path = yield* Path.Path;
560 const htmlRender = yield* HtmlRender.HtmlRender;
561 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-files-" });
562 const secret = path.join(directory, "secret.js");
563 yield* fileSystem.writeFileString(secret, 'window.secret = "abc123";');
564 const secretUrl = NodeURL.pathToFileURL(secret).href;
565
566 const preview = yield* htmlRender.preview({
567 html: [
568 `<script src="${secretUrl}"></script>`,
569 `<iframe src="${secretUrl}" onload="console.log('frame loaded')"></iframe>`,
570 '<script>addEventListener("load", () => console.log("secret:", window.secret ?? "none"));</script>',
571 ].join(""),
572 });
573
574 const texts = preview.consoleMessages.map((message) => message.text);
575 expect(texts).toContain("secret: none");
576 expect(texts.join(" ")).not.toContain("abc123");
577 }).pipe(Effect.scoped, Effect.provide(layerHtmlRender(executable)));
578 }),
579 );
580
581 it.live("keeps the page off this machine's local network", (ctx) =>
582 Effect.gen(function* () {
583 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
584 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
585 const requests: Array<string> = [];
586 const server = yield* Effect.acquireRelease(
587 Effect.callback<NodeHttp.Server>((resume) => {
588 const listening = NodeHttp.createServer((request, response) => {
589 requests.push(`${request.url} ${request.headers["sec-purpose"] ?? ""}`);
590 response.end("<p>LOCAL</p>");
591 });
592 listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening)));
593 }),
594 (listening) =>
595 Effect.callback<void>((resume) => {
596 listening.close(() => resume(Effect.void));
597 }),
598 );
599 const datagrams: Array<string> = [];
600 const udp = yield* Effect.acquireRelease(
601 Effect.callback<NodeDgram.Socket>((resume) => {
602 const socket = NodeDgram.createSocket("udp4");
603 socket.on("message", (message) => datagrams.push(message.toString("hex")));
604 socket.bind(0, "127.0.0.1", () => resume(Effect.succeed(socket)));
605 }),
606 (socket) =>
607 Effect.callback<void>((resume) => {
608 socket.close(() => resume(Effect.void));
609 }),
610 );
611 const address = server.address();
612 const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`;
613 const stun = `stun:127.0.0.1:${udp.address().port}`;
614 yield* Effect.gen(function* () {
615 const htmlRender = yield* HtmlRender.HtmlRender;
616 yield* htmlRender.preview({
617 html: [
618 `<img src="${origin}/x.png"><iframe src="${origin}/"></iframe>`,
619 `<script type="speculationrules">{"prefetch":[{"source":"list","urls":["${origin}/prefetch"]}]}</script>`,
620 `<script>fetch("${origin}/").catch(() => {}); new WebSocket("ws${origin.slice(4)}/socket");`,
621 `try { const peer = new RTCPeerConnection({ iceServers: [{ urls: "${stun}" }] });`,
622 `peer.createDataChannel("x"); peer.createOffer().then((offer) => peer.setLocalDescription(offer));`,
623 `} catch {}`,
624 `window.open("${origin}/popup"); location.href = "${origin}/navigate";</script>`,
625 ].join(""),
626 });
627 }).pipe(Effect.provide(layerHtmlRender(executable)));
628 expect(requests).toEqual([]);
629 expect(datagrams).toEqual([]);
630 }),
631 );
632 });