Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HtmlRender.test.ts

701 lines32.7 KB

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