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