Open History to see the last commit
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>
31}
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 }
65}
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 }
74}
75
76/** Chrome will not start its sandbox as root (crbug.com/638180), which no host setup fixes. */
77export class PreviewBrowserRootError extends Schema.TaggedError<PreviewBrowserRootError>()(
78 "PreviewBrowserRootError",
79 {},
80) {
81 override get message(): string {
82 return "Chrome will not start its sandbox as root, so T3's browser cannot run while the T3 server runs as root. Run the server as a nonroot user (for example `User=` in its systemd service), or set `T3CODE_SERVER_BROWSER_SANDBOX=0` to run the browser unsandboxed as root.";
83 }
84}
85
86export type PreviewBrowserHostError =
87 | PreviewBrowserSandboxError
88 | PreviewBrowserLibrariesError
89 | PreviewBrowserRootError;
90
91const MISSING_LIBRARY = /^\s*(\S+) => not found$/gm;
92const LOADER_ERROR = /error while loading shared libraries: ([^:\s]+)/;
93
94export const diagnoseLaunchFailure = Effect.fn("PreviewBrowserHost.diagnoseLaunchFailure")(
95 function* (input: {
96 readonly executable: string;
97 readonly output: string;
98 readonly setupCommand: string;
99 }) {
100 const { setupCommand } = input;
101 if (input.output.includes(NO_SANDBOX_SIGNATURE)) {
102 // Playwright reports Chrome's refusal to sandbox as root as a sandbox failure too.
103 return (yield* HostProcess.UserId) === 0
104 ? new PreviewBrowserRootError()
105 : new PreviewBrowserSandboxError({ setupCommand });
106 }
107 if ((yield* HostProcess.Platform) !== "linux") return undefined;
108 const libraries = yield* missingLibraries(input.executable);
109 return libraries.length === 0
110 ? undefined
111 : new PreviewBrowserLibrariesError({ setupCommand, libraries });
112 },
113);
114
115/**
116 * The browser's own `--version` decides whether any are missing; `ldd` only
117 * lists them after the real loader fails, because it can report libraries a
118 * host provides another way (NixOS's nix-ld).
119 */
120export const missingLibraries = Effect.fn("PreviewBrowserHost.missingLibraries")(function* (
121 executable: string,
122) {
123 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
124 const run = (command: string, args: ReadonlyArray<string>) =>
125 spawner
126 .string(ChildProcess.make(command, args, { stdin: "ignore" }), { includeStderr: true })
127 .pipe(
128 Effect.timeout("5 seconds"),
129 Effect.orElseSucceed(() => ""),
130 );
131 const loaderError = LOADER_ERROR.exec(yield* run(executable, ["--version"]))?.[1];
132 if (loaderError === undefined) return [];
133 const listed = [...(yield* run("ldd", [executable])).matchAll(MISSING_LIBRARY)].map(
134 (match) => match[1]!,
135 );
136 return listed.length > 0 ? listed : [loaderError];
137});
138
139export const sandboxBlocked = Effect.gen(function* () {
140 if ((yield* HostProcess.Platform) !== "linux") return false;
141 const fs = yield* FileSystem.FileSystem;
142 const restricted = yield* fs.readFileString(USERNS_RESTRICTION).pipe(
143 Effect.map((value) => value.trim() === "1"),
144 Effect.orElseSucceed(() => false),
145 );
146 if (!restricted) return false;
147 return !(yield* fs.exists(APPARMOR_PROFILE_PATH).pipe(Effect.orElseSucceed(() => false)));
148}).pipe(Effect.withSpan("PreviewBrowserHost.sandboxBlocked"));