Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest.
2import * as EffectNodeStream from "@effect/platform-node/NodeStream";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Cause from "effect/Cause";
5import * as Clock from "effect/Clock";
6import * as Context from "effect/Context";
7import * as Deferred from "effect/Deferred";
8import type * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import * as Semaphore from "effect/Semaphore";
17import * as Stream from "effect/Stream";
18import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
19import * as NodeCrypto from "node:crypto";
20
21import * as ServerConfig from "../config.ts";
22import { openZipArchive } from "../zipArchive.ts";
23
24// To bump the pin, pick a version from
25// https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json,
26// download each platform's chrome-headless-shell zip, and replace the version and every byte count
27// and SHA-256 below.
28//
29// The headless shell never loads Chrome's CRLSet, so a certificate block reaches it only through
30// Chromium's compiled-in SPKI blocklist. Do not pin below 156.0.8078.70: earlier builds trust the
31// compromised eMudhra intermediates (crrev.com/c/8627687).
32const VERSION = "156.0.8078.70";
33const ARCHIVES = {
34 linux64: {
35 bytes: 126_646_931,
36 sha256: "a313da592261ff1e342c1e507d315f25b1809006c0508f77ce86151d464d4ccb",
37 },
38 "linux-arm64": {
39 bytes: 126_749_876,
40 sha256: "dca11213d2e0b1db52141edd9f92ec423fd52ca25715846790d84fa1d5d16e8a",
41 },
42 "mac-arm64": {
43 bytes: 103_901_293,
44 sha256: "1f848385611f2e58122e68969489712661880fc9a92c9dd20428099f9998ba7b",
45 },
46 "mac-x64": {
47 bytes: 109_387_968,
48 sha256: "ab4cc2949f88439e2241b2712c49268f24982f2d25af87960466cc22bdc2e6e1",
49 },
50 win32: {
51 bytes: 119_029_359,
52 sha256: "37dc9a03f37fd79637fec9f26042bf32f04cfe5b83749d980eb1e7d1a429d47c",
53 },
54 win64: {
55 bytes: 126_214_071,
56 sha256: "41c6aa97046d05d015b817a95f7b1512c3a1a41b18364f8da46478ae520400b1",
57 },
58} as const;
59
60const chromePlatform = (platform: NodeJS.Platform, arch: NodeJS.Architecture) => {
61 switch (platform) {
62 case "linux":
63 return arch === "x64" ? "linux64" : arch === "arm64" ? "linux-arm64" : null;
64 case "darwin":
65 return arch === "arm64" ? "mac-arm64" : arch === "x64" ? "mac-x64" : null;
66 case "win32":
67 // There is no Windows arm64 build; Windows on Arm runs the x64 one under emulation.
68 return arch === "ia32" ? "win32" : arch === "x64" || arch === "arm64" ? "win64" : null;
69 default:
70 return null;
71 }
72};
73
74export interface PreviewBrowserRelease {
75 readonly version: string;
76 readonly platform: string;
77 readonly url: string;
78 readonly bytes: number;
79 readonly sha256: string;
80}
81
82const previewBrowserRelease = (
83 platform: NodeJS.Platform,
84 arch: NodeJS.Architecture,
85): PreviewBrowserRelease | null => {
86 const chrome = chromePlatform(platform, arch);
87 return chrome === null
88 ? null
89 : {
90 version: VERSION,
91 platform: chrome,
92 url: `https://storage.googleapis.com/chrome-for-testing-public/${VERSION}/${chrome}/chrome-headless-shell-${chrome}.zip`,
93 ...ARCHIVES[chrome],
94 };
95};
96
97const megabytes = (bytes: number) => Math.round(bytes / 1_000_000);
98
99export class PreviewBrowserInstallError extends Schema.TaggedError<PreviewBrowserInstallError>()(
100 "PreviewBrowserInstallError",
101 { detail: Schema.String, cause: Schema.optional(Schema.Defect()) },
102) {
103 override get message(): string {
104 return `T3 could not install its headless browser: ${this.detail} Try again.`;
105 }
106}
107const isInstallError = Schema.is(PreviewBrowserInstallError);
108
109export class PreviewBrowserInstallingError extends Schema.TaggedError<PreviewBrowserInstallingError>()(
110 "PreviewBrowserInstallingError",
111 { downloadedBytes: Schema.Number, totalBytes: Schema.Number, unpacking: Schema.Boolean },
112) {
113 override get message(): string {
114 const progress = this.unpacking
115 ? "unpacking"
116 : `${megabytes(this.downloadedBytes)} of ${megabytes(this.totalBytes)} MB downloaded`;
117 return `T3 is installing its headless browser (${progress}). Try again in a minute.`;
118 }
119}
120
121export class PreviewBrowserUnsupportedError extends Schema.TaggedError<PreviewBrowserUnsupportedError>()(
122 "PreviewBrowserUnsupportedError",
123 { platform: Schema.String, arch: Schema.String },
124) {
125 override get message(): string {
126 return `T3's headless browser is not available on ${this.platform}-${this.arch}: Chrome for Testing has no headless shell for it.`;
127 }
128}
129
130export class PreviewBrowser extends Context.Service<
131 PreviewBrowser,
132 {
133 /**
134 * Path to the installed headless shell. The first call starts the
135 * install; callers wait for it up to a bound and then get its progress
136 * instead, while the install keeps running.
137 */
138 readonly executable: Effect.Effect<
139 string,
140 PreviewBrowserInstallError | PreviewBrowserInstallingError | PreviewBrowserUnsupportedError
141 >;
142 readonly installed: Effect.Effect<Option.Option<string>>;
143 }
144>()("t3/preview/PreviewBrowser") {}
145
146export interface PreviewBrowserOptions {
147 readonly baseDir: string;
148 readonly release?: PreviewBrowserRelease | null;
149 /** How long a caller waits on an install in progress. Provider tool calls time out near 60s. */
150 readonly wait?: Duration.Input;
151}
152
153const DOWNLOAD_TIMEOUT = "15 minutes";
154const STAGING_STALE_AFTER_MS = 60 * 60_000;
155
156const wrapFailure = (detail: string) => (cause: unknown) =>
157 isInstallError(cause) ? cause : new PreviewBrowserInstallError({ detail, cause });
158
159type InstallState =
160 | { readonly _tag: "idle" }
161 | {
162 readonly _tag: "installing";
163 readonly done: Deferred.Deferred<string, PreviewBrowserInstallError>;
164 }
165 | { readonly _tag: "installed"; readonly executable: string }
166 | { readonly _tag: "failed"; readonly error: PreviewBrowserInstallError };
167
168export const makePreviewBrowser = Effect.fn("PreviewBrowser.make")(function* (
169 options: PreviewBrowserOptions,
170) {
171 const fs = yield* FileSystem.FileSystem;
172 const path = yield* Path.Path;
173 const http = yield* HttpClient.HttpClient;
174 // Installs belong to the service, so they finish even when no caller is still waiting.
175 const serviceScope = yield* Effect.scope;
176 const platform = yield* HostProcess.Platform;
177 const arch = yield* HostProcess.Architecture;
178 const release =
179 options.release === undefined ? previewBrowserRelease(platform, arch) : options.release;
180 const wait = options.wait ?? "45 seconds";
181 const installRoot = path.join(
182 options.baseDir,
183 "tools",
184 "chrome-headless-shell",
185 release?.platform ?? `${platform}-${arch}`,
186 );
187 const executableName =
188 platform === "win32" ? "chrome-headless-shell.exe" : "chrome-headless-shell";
189 const gate = yield* Semaphore.make(1);
190 let state: InstallState = { _tag: "idle" };
191 const progress = { downloadedBytes: 0, unpacking: false };
192
193 const installedExecutable = (release: PreviewBrowserRelease) => {
194 const executable = path.join(installRoot, release.version, executableName);
195 return fs.stat(executable).pipe(
196 Effect.map((info) =>
197 info.type === "File" && (platform === "win32" || (info.mode & 0o111) !== 0)
198 ? Option.some(executable)
199 : Option.none<string>(),
200 ),
201 Effect.orElseSucceed(() => Option.none<string>()),
202 );
203 };
204
205 const download = Effect.fn("PreviewBrowser.download")(
206 function* (release: PreviewBrowserRelease, archivePath: string) {
207 const response = yield* http
208 .execute(HttpClientRequest.get(release.url))
209 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
210 const contentLength = response.headers["content-length"];
211 const contentEncoding = response.headers["content-encoding"]?.trim().toLowerCase();
212 if (
213 (contentEncoding === undefined || contentEncoding === "identity") &&
214 contentLength !== undefined &&
215 Number(contentLength) !== release.bytes
216 ) {
217 return yield* new PreviewBrowserInstallError({
218 detail: "The download size did not match the pinned release.",
219 });
220 }
221 const hash = NodeCrypto.createHash("sha256");
222 yield* response.stream.pipe(
223 Stream.tap((chunk) =>
224 Effect.suspend(() => {
225 progress.downloadedBytes += chunk.byteLength;
226 if (progress.downloadedBytes > release.bytes) {
227 return Effect.fail(
228 new PreviewBrowserInstallError({
229 detail: "The download was larger than the pinned release.",
230 }),
231 );
232 }
233 hash.update(chunk);
234 return Effect.void;
235 }),
236 ),
237 Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })),
238 );
239 if (progress.downloadedBytes !== release.bytes || hash.digest("hex") !== release.sha256) {
240 return yield* new PreviewBrowserInstallError({
241 detail: "The download failed its size or SHA-256 check. Nothing was installed.",
242 });
243 }
244 },
245 Effect.timeout(DOWNLOAD_TIMEOUT),
246 Effect.mapError(
247 wrapFailure(
248 "The download from storage.googleapis.com failed. Check this machine's network access.",
249 ),
250 ),
251 );
252
253 const extract = Effect.fn("PreviewBrowser.extract")(
254 function* (release: PreviewBrowserRelease, archivePath: string, destination: string) {
255 const archive = yield* openZipArchive(
256 archivePath,
257 (detail, cause) => new PreviewBrowserInstallError({ detail, cause }),
258 );
259 const unsafe = new PreviewBrowserInstallError({
260 detail: "The archive contains an unexpected or unsafe entry.",
261 });
262 const root = `chrome-headless-shell-${release.platform}/`;
263 yield* fs.makeDirectory(destination);
264 let foundExecutable = false;
265 for (;;) {
266 const entry = yield* archive.next;
267 if (!entry) break;
268 const unixMode = entry.externalFileAttributes >>> 16;
269 const unixType = unixMode & 0o170000;
270 const isDirectory = entry.fileName.endsWith("/");
271 const relative = entry.fileName.startsWith(root) ? entry.fileName.slice(root.length) : null;
272 const target = relative === null ? null : path.resolve(destination, relative);
273 if (
274 relative === null ||
275 target === null ||
276 (relative !== "" && !target.startsWith(`${destination}${path.sep}`)) ||
277 relative.split("/").includes("..") ||
278 (unixType !== 0 && unixType !== (isDirectory ? 0o040000 : 0o100000)) ||
279 (entry.generalPurposeBitFlag & 1) !== 0 ||
280 ![0, 8].includes(entry.compressionMethod)
281 ) {
282 return yield* unsafe;
283 }
284 if (isDirectory) {
285 yield* fs.makeDirectory(target, { recursive: true });
286 continue;
287 }
288 yield* fs.makeDirectory(path.dirname(target), { recursive: true });
289 yield* Effect.gen(function* () {
290 const readable = yield* archive.streamEntry(entry);
291 yield* EffectNodeStream.fromReadable<Uint8Array, PreviewBrowserInstallError>({
292 evaluate: () => readable,
293 onError: wrapFailure("Could not unpack the browser."),
294 }).pipe(Stream.run(fs.sink(target, { flag: "wx" })));
295 }).pipe(Effect.scoped);
296 // The binary and its shared libraries carry exec bits in the archive.
297 if (platform !== "win32" && (unixMode & 0o777) !== 0) {
298 yield* fs.chmod(target, unixMode & 0o777);
299 }
300 if (relative === executableName) foundExecutable = true;
301 }
302 if (!foundExecutable) {
303 return yield* new PreviewBrowserInstallError({
304 detail: "The archive does not contain chrome-headless-shell.",
305 });
306 }
307 },
308 Effect.scoped,
309 Effect.mapError(
310 wrapFailure("Could not unpack the browser. Check free disk space in T3's home directory."),
311 ),
312 );
313
314 const install = Effect.fn("PreviewBrowser.install")(
315 function* (release: PreviewBrowserRelease) {
316 yield* Effect.gen(function* () {
317 yield* fs.makeDirectory(installRoot, { recursive: true });
318 // Staging shares the install root's filesystem so publishing is one rename.
319 const staging = yield* fs.makeTempDirectoryScoped({
320 directory: installRoot,
321 prefix: ".install-",
322 });
323 const archivePath = path.join(staging, "download.zip");
324 const unpacked = path.join(staging, "browser");
325 yield* download(release, archivePath);
326 progress.unpacking = true;
327 yield* extract(release, archivePath, unpacked);
328 const destination = path.join(installRoot, release.version);
329 yield* fs.remove(destination, { recursive: true, force: true });
330 yield* fs.rename(unpacked, destination);
331 }).pipe(Effect.scoped);
332 // Two servers can share a home, so a staging directory touched within the
333 // last hour may be another server's install in progress and stays.
334 const entries = yield* fs.readDirectory(installRoot);
335 const now = yield* Clock.currentTimeMillis;
336 yield* Effect.forEach(
337 entries.filter((name) => name !== release.version),
338 (name) =>
339 Effect.gen(function* () {
340 const target = path.join(installRoot, name);
341 if (name.startsWith(".install-")) {
342 const info = yield* fs.stat(target);
343 const modifiedAt = Option.match(info.mtime, {
344 onNone: () => now,
345 onSome: (date) => date.getTime(),
346 });
347 if (now - modifiedAt < STAGING_STALE_AFTER_MS) return;
348 }
349 yield* fs.remove(target, { recursive: true, force: true });
350 }).pipe(
351 Effect.catch((cause) =>
352 Effect.logWarning("Could not remove an old preview browser.", { name, cause }),
353 ),
354 ),
355 { discard: true },
356 );
357 return path.join(installRoot, release.version, executableName);
358 },
359 Effect.mapError(wrapFailure("Could not save the browser in T3's home directory.")),
360 );
361
362 const join = (release: PreviewBrowserRelease) =>
363 gate.withPermit(
364 Effect.gen(function* () {
365 if (state._tag === "installing") return state;
366 if (state._tag === "failed") {
367 const failed = state;
368 state = { _tag: "idle" };
369 return failed;
370 }
371 const installed = yield* installedExecutable(release);
372 if (Option.isSome(installed)) {
373 state = { _tag: "installed", executable: installed.value };
374 return state;
375 }
376 const done = yield* Deferred.make<string, PreviewBrowserInstallError>();
377 progress.downloadedBytes = 0;
378 progress.unpacking = false;
379 const installing: InstallState = { _tag: "installing", done };
380 state = installing;
381 yield* install(release).pipe(
382 Effect.onExit((exit) =>
383 gate
384 .withPermit(
385 Effect.sync(() => {
386 state = Exit.isSuccess(exit)
387 ? { _tag: "installed", executable: exit.value }
388 : {
389 _tag: "failed",
390 error: Option.getOrElse(
391 Cause.findErrorOption(exit.cause),
392 () => new PreviewBrowserInstallError({ detail: "The install stopped." }),
393 ),
394 };
395 }),
396 )
397 .pipe(Effect.andThen(Deferred.done(done, exit))),
398 ),
399 Effect.ignoreCause,
400 Effect.interruptible,
401 Effect.forkIn(serviceScope),
402 );
403 return installing;
404 }),
405 );
406
407 const clearFailure = (error: PreviewBrowserInstallError) =>
408 gate.withPermit(
409 Effect.sync(() => {
410 if (state._tag === "failed" && state.error === error) state = { _tag: "idle" };
411 }),
412 );
413
414 const executable = Effect.gen(function* () {
415 if (release === null) {
416 return yield* new PreviewBrowserUnsupportedError({ platform, arch });
417 }
418 const current = yield* join(release);
419 switch (current._tag) {
420 case "installed":
421 return current.executable;
422 case "failed":
423 return yield* current.error;
424 case "installing":
425 return yield* Deferred.await(current.done).pipe(
426 Effect.tapError(clearFailure),
427 Effect.timeoutOrElse({
428 duration: wait,
429 orElse: () =>
430 Effect.fail(
431 new PreviewBrowserInstallingError({
432 downloadedBytes: progress.downloadedBytes,
433 totalBytes: release.bytes,
434 unpacking: progress.unpacking,
435 }),
436 ),
437 }),
438 );
439 }
440 }).pipe(Effect.withSpan("PreviewBrowser.executable"));
441
442 const installed = release === null ? Effect.succeedNone : installedExecutable(release);
443
444 return PreviewBrowser.of({ executable, installed });
445});
446
447export const layer = Layer.effect(
448 PreviewBrowser,
449 Effect.gen(function* () {
450 const config = yield* ServerConfig.ServerConfig;
451 return yield* makePreviewBrowser({ baseDir: config.baseDir });
452 }),
453);