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

PreviewBrowserHost.ts

146 lines6.2 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/** What chrome-headless-shell prints itself when started sandboxed as root. */
12const ROOT_SANDBOX_SIGNATURE = "Running as root without --no-sandbox";
13​
14export const sandboxDisabled = (env: Readonly<Record<string, string | undefined>>) =>
15 env.T3CODE_SERVER_BROWSER_SANDBOX === "0";
16​
17/** Set on Ubuntu 23.10+: unprivileged user namespaces need an AppArmor profile. */
18const USERNS_RESTRICTION = "/proc/sys/kernel/apparmor_restrict_unprivileged_userns";
19export const APPARMOR_PROFILE_PATH = "/etc/apparmor.d/t3-chrome-headless-shell";
20​
21/** Match Ubuntu's Chrome profile; unconfined adds nothing beyond userns. */
22export const APPARMOR_PROFILE = `# Written by \`t3 browser setup\`: lets T3 Code's headless browser use Chrome's sandbox.
23abi <abi/4.0>,
24include <tunables/global>
25​
26profile t3-chrome-headless-shell /**/tools/chrome-headless-shell/*/*/chrome-headless-shell flags=(unconfined) {
27 userns,
28​
29 include if exists <local/t3-chrome-headless-shell>
31`;
32​
33/** Ubuntu 24.04 and Debian 13 use some t64 library names; choose names available through apt. */
34export const DEBIAN_PACKAGES: ReadonlyArray<ReadonlyArray<string>> = [
35 ["libnss3"],
36 ["libglib2.0-0t64", "libglib2.0-0"],
37 ["libatk1.0-0t64", "libatk1.0-0"],
38 ["libatk-bridge2.0-0t64", "libatk-bridge2.0-0"],
39 ["libatspi2.0-0t64", "libatspi2.0-0"],
40 ["libdbus-1-3"],
41 ["libx11-6"],
42 ["libxcb1"],
43 ["libxcomposite1"],
44 ["libxdamage1"],
45 ["libxext6"],
46 ["libxfixes3"],
47 ["libxrandr2"],
48 ["libxkbcommon0"],
49 ["libgbm1"],
50 ["libasound2t64", "libasound2"],
51 ["libexpat1"],
52];
53​
54export class PreviewBrowserSandboxError extends Schema.TaggedError<PreviewBrowserSandboxError>()(
55 "PreviewBrowserSandboxError",
56 { setupCommand: Schema.String },
57) {
58 override get message(): string {
59 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.`;
60 }
62​
63export class PreviewBrowserLibrariesError extends Schema.TaggedError<PreviewBrowserLibrariesError>()(
64 "PreviewBrowserLibrariesError",
65 { setupCommand: Schema.String, libraries: Schema.Array(Schema.String) },
66) {
67 override get message(): string {
68 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.`;
69 }
71​
72/** Chrome will not start its sandbox as root (crbug.com/638180), which no host setup fixes. */
73export class PreviewBrowserRootError extends Schema.TaggedError<PreviewBrowserRootError>()(
74 "PreviewBrowserRootError",
75 {},
76) {
77 override get message(): string {
78 return "T3 server is running as root; Chrome's sandbox cannot start. Run T3 as a nonroot user. Otherwise set `T3CODE_SERVER_BROWSER_SANDBOX=0` in the T3 server's environment and restart the server; this disables Chrome's sandbox. Manual: `T3CODE_SERVER_BROWSER_SANDBOX=0 t3 serve`. Systemd: add `Environment=T3CODE_SERVER_BROWSER_SANDBOX=0` under `[Service]`, reload systemd, then restart the service. `t3 browser setup` cannot fix root sandboxing.";
79 }
81​
82export type PreviewBrowserHostError =
83 | PreviewBrowserSandboxError
84 | PreviewBrowserLibrariesError
85 | PreviewBrowserRootError;
86​
87const MISSING_LIBRARY = /^\s*(\S+) => not found$/gm;
88const LOADER_ERROR = /error while loading shared libraries: ([^:\s]+)/;
89​
90export const diagnoseLaunchFailure = Effect.fn("PreviewBrowserHost.diagnoseLaunchFailure")(
91 function* (input: {
92 readonly executable: string;
93 readonly output: string;
94 readonly setupCommand: string;
95 }) {
96 const { setupCommand } = input;
97 if (input.output.includes(ROOT_SANDBOX_SIGNATURE)) return new PreviewBrowserRootError();
98 if (input.output.includes(NO_SANDBOX_SIGNATURE)) {
99 // Playwright reports Chrome's refusal to sandbox as root as a sandbox failure too.
100 return (yield* HostProcess.UserId) === 0
101 ? new PreviewBrowserRootError()
102 : new PreviewBrowserSandboxError({ setupCommand });
103 }
104 if ((yield* HostProcess.Platform) !== "linux") return undefined;
105 const libraries = yield* missingLibraries(input.executable);
106 return libraries.length === 0
107 ? undefined
108 : new PreviewBrowserLibrariesError({ setupCommand, libraries });
109 },
110);
111​
112/** Detect missing libraries with --version; ldd can report misses that NixOS nix-ld provides. */
113export const missingLibraries = Effect.fn("PreviewBrowserHost.missingLibraries")(function* (
114 executable: string,
115) {
116 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
117 const run = (command: string, args: ReadonlyArray<string>) =>
118 spawner
119 .string(ChildProcess.make(command, args, { stdin: "ignore" }), { includeStderr: true })
120 .pipe(
121 Effect.timeout("5 seconds"),
122 Effect.orElseSucceed(() => ""),
123 );
124 const loaderError = LOADER_ERROR.exec(yield* run(executable, ["--version"]))?.[1];
125 if (loaderError === undefined) return [];
126 const listed = [...(yield* run("ldd", [executable])).matchAll(MISSING_LIBRARY)].map(
127 (match) => match[1]!,
128 );
129 return listed.length > 0 ? listed : [loaderError];
130});
131​
132export const usernsRestricted = Effect.gen(function* () {
133 if ((yield* HostProcess.Platform) !== "linux") return false;
134 const fs = yield* FileSystem.FileSystem;
135 return yield* fs.readFileString(USERNS_RESTRICTION).pipe(
136 Effect.map((value) => value.trim() === "1"),
137 Effect.orElseSucceed(() => false),
138 );
139}).pipe(Effect.withSpan("PreviewBrowserHost.usernsRestricted"));
140​
141/** A profile on disk can still be unloaded; only a failed launch shows that without root. */
142export const sandboxBlocked = Effect.gen(function* () {
143 if (!(yield* usernsRestricted)) return false;
144 const fs = yield* FileSystem.FileSystem;
145 return !(yield* fs.exists(APPARMOR_PROFILE_PATH).pipe(Effect.orElseSucceed(() => false)));
146}).pipe(Effect.withSpan("PreviewBrowserHost.sandboxBlocked"));