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

PreviewBrowserHost.ts

132 lines4.9 KB

1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Schema from "effect/Schema";
5import * as ChildProcess from "effect/process/ChildProcess";
6import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
7​
8export const SETUP_SUBCOMMAND = "browser setup";
9​
10export const NO_SANDBOX_SIGNATURE = "No usable sandbox";
11​
12export const sandboxDisabled = (env: Readonly<Record<string, string | undefined>>) =>
13 env.T3CODE_SERVER_BROWSER_SANDBOX === "0";
14​
15/** Set on Ubuntu 23.10+: unprivileged user namespaces need an AppArmor profile. */
16const USERNS_RESTRICTION = "/proc/sys/kernel/apparmor_restrict_unprivileged_userns";
17export const APPARMOR_PROFILE_PATH = "/etc/apparmor.d/t3-chrome-headless-shell";
18​
19/**
20 * Modelled on the profile Ubuntu ships for Google Chrome; `unconfined` adds
21 * nothing beyond `userns`.
22 */
23export const APPARMOR_PROFILE = `# Written by \`t3 browser setup\`: lets T3 Code's headless browser use Chrome's sandbox.
24abi <abi/4.0>,
25include <tunables/global>
26​
27profile t3-chrome-headless-shell /**/tools/chrome-headless-shell/*/*/chrome-headless-shell flags=(unconfined) {
28 userns,
29​
30 include if exists <local/t3-chrome-headless-shell>
32`;
33​
34/**
35 * Ubuntu 24.04 and Debian 13 renamed some with a `t64` suffix; setup installs
36 * whichever name the host's apt offers.
37 */
38export const DEBIAN_PACKAGES: ReadonlyArray<ReadonlyArray<string>> = [
39 ["libnss3"],
40 ["libglib2.0-0t64", "libglib2.0-0"],
41 ["libatk1.0-0t64", "libatk1.0-0"],
42 ["libatk-bridge2.0-0t64", "libatk-bridge2.0-0"],
43 ["libatspi2.0-0t64", "libatspi2.0-0"],
44 ["libdbus-1-3"],
45 ["libx11-6"],
46 ["libxcb1"],
47 ["libxcomposite1"],
48 ["libxdamage1"],
49 ["libxext6"],
50 ["libxfixes3"],
51 ["libxrandr2"],
52 ["libxkbcommon0"],
53 ["libgbm1"],
54 ["libasound2t64", "libasound2"],
55 ["libexpat1"],
56];
57​
58export class PreviewBrowserSandboxError extends Schema.TaggedError<PreviewBrowserSandboxError>()(
59 "PreviewBrowserSandboxError",
60 { setupCommand: Schema.String },
61) {
62 override get message(): string {
63 return `This host blocks the sandbox T3's browser runs in (AppArmor on Ubuntu 23.10+). Run \`${this.setupCommand}\` on the host once to allow it, then try again.`;
64 }
66​
67export class PreviewBrowserLibrariesError extends Schema.TaggedError<PreviewBrowserLibrariesError>()(
68 "PreviewBrowserLibrariesError",
69 { setupCommand: Schema.String, libraries: Schema.Array(Schema.String) },
70) {
71 override get message(): string {
72 return `This host is missing libraries T3's browser needs (${this.libraries.join(", ")}). Run \`${this.setupCommand}\` on the host to install them, then try again.`;
73 }
75​
76export type PreviewBrowserHostError = PreviewBrowserSandboxError | PreviewBrowserLibrariesError;
77​
78const MISSING_LIBRARY = /^\s*(\S+) => not found$/gm;
79const LOADER_ERROR = /error while loading shared libraries: ([^:\s]+)/;
80​
81export const diagnoseLaunchFailure = Effect.fn("PreviewBrowserHost.diagnoseLaunchFailure")(
82 function* (input: {
83 readonly executable: string;
84 readonly output: string;
85 readonly setupCommand: string;
86 }) {
87 const { setupCommand } = input;
88 if (input.output.includes(NO_SANDBOX_SIGNATURE)) {
89 return new PreviewBrowserSandboxError({ setupCommand });
90 }
91 if ((yield* HostProcess.Platform) !== "linux") return undefined;
92 const libraries = yield* missingLibraries(input.executable);
93 return libraries.length === 0
94 ? undefined
95 : new PreviewBrowserLibrariesError({ setupCommand, libraries });
96 },
97);
98​
99/**
100 * The browser's own `--version` decides whether any are missing; `ldd` only
101 * lists them after the real loader fails, because it can report libraries a
102 * host provides another way (NixOS's nix-ld).
103 */
104export const missingLibraries = Effect.fn("PreviewBrowserHost.missingLibraries")(function* (
105 executable: string,
106) {
107 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
108 const run = (command: string, args: ReadonlyArray<string>) =>
109 spawner
110 .string(ChildProcess.make(command, args, { stdin: "ignore" }), { includeStderr: true })
111 .pipe(
112 Effect.timeout("5 seconds"),
113 Effect.orElseSucceed(() => ""),
114 );
115 const loaderError = LOADER_ERROR.exec(yield* run(executable, ["--version"]))?.[1];
116 if (loaderError === undefined) return [];
117 const listed = [...(yield* run("ldd", [executable])).matchAll(MISSING_LIBRARY)].map(
118 (match) => match[1]!,
119 );
120 return listed.length > 0 ? listed : [loaderError];
121});
122​
123export const sandboxBlocked = Effect.gen(function* () {
124 if ((yield* HostProcess.Platform) !== "linux") return false;
125 const fs = yield* FileSystem.FileSystem;
126 const restricted = yield* fs.readFileString(USERNS_RESTRICTION).pipe(
127 Effect.map((value) => value.trim() === "1"),
128 Effect.orElseSucceed(() => false),
129 );
130 if (!restricted) return false;
131 return !(yield* fs.exists(APPARMOR_PROFILE_PATH).pipe(Effect.orElseSucceed(() => false)));
132}).pipe(Effect.withSpan("PreviewBrowserHost.sandboxBlocked"));