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

HtmlRender.test.ts

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