Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Console from "effect/Console";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8import { Command } from "effect/cli";
9import * as ChildProcess from "effect/process/ChildProcess";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11
12import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts";
13import { resolveBaseDir } from "../os-jank.ts";
14import { baseDirFlag } from "./config.ts";
15import { resolveRootCliCommand } from "./invocation.ts";
16
17export class BrowserSetupStepError extends Schema.TaggedError<BrowserSetupStepError>()(
18 "BrowserSetupStepError",
19 { step: Schema.String, detail: Schema.String },
20) {
21 override get message(): string {
22 return `Could not ${this.step}: ${this.detail}`;
23 }
24}
25
26const runStep = Effect.fn("browserSetup.runStep")(function* (
27 step: string,
28 command: string,
29 args: ReadonlyArray<string>,
30) {
31 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
32 const exitCode = yield* spawner
33 .exitCode(
34 ChildProcess.make(command, args, { stdin: "inherit", stdout: "inherit", stderr: "inherit" }),
35 )
36 .pipe(Effect.mapError((cause) => new BrowserSetupStepError({ step, detail: String(cause) })));
37 if (exitCode !== 0) {
38 return yield* new BrowserSetupStepError({ step, detail: `${command} exited with ${exitCode}` });
39 }
40});
41
42/**
43 * Under `sudo` the process home is root's, so an unspecified home falls back to
44 * the invoking user's `~/.t3`.
45 */
46const setupBaseDir = Effect.fn("browserSetup.baseDir")(function* (explicit: Option.Option<string>) {
47 const env = yield* HostProcess.Environment;
48 const raw = Option.getOrUndefined(explicit) ?? env.T3CODE_HOME;
49 if (raw !== undefined || env.SUDO_USER === undefined) return yield* resolveBaseDir(raw);
50 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
51 const entry = yield* spawner
52 .string(
53 ChildProcess.make("getent", ["passwd", env.SUDO_USER], { stdin: "ignore", stderr: "ignore" }),
54 )
55 .pipe(Effect.orElseSucceed(() => ""));
56 const home = entry.trim().split(":")[5];
57 const path = yield* Path.Path;
58 return home ? path.join(home, ".t3") : yield* resolveBaseDir(undefined);
59});
60
61const aptOffers = Effect.fn("browserSetup.aptOffers")(function* (name: string) {
62 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
63 const policy = yield* spawner
64 .string(ChildProcess.make("apt-cache", ["policy", name], { stdin: "ignore", stderr: "ignore" }))
65 .pipe(Effect.orElseSucceed(() => ""));
66 const candidate = /Candidate:\s*(\S+)/.exec(policy)?.[1];
67 return candidate !== undefined && candidate !== "(none)";
68});
69
70const installedBrowser = Effect.fn("browserSetup.installedBrowser")(function* (baseDir: string) {
71 const fs = yield* FileSystem.FileSystem;
72 const path = yield* Path.Path;
73 const root = path.join(baseDir, "tools", "chrome-headless-shell");
74 for (const platform of yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []))) {
75 for (const version of yield* fs
76 .readDirectory(path.join(root, platform))
77 .pipe(Effect.orElseSucceed(() => []))) {
78 const executable = path.join(root, platform, version, "chrome-headless-shell");
79 if (yield* fs.exists(executable).pipe(Effect.orElseSucceed(() => false))) {
80 return Option.some(executable);
81 }
82 }
83 }
84 return Option.none<string>();
85});
86
87/**
88 * Chrome starts without fonts, but pages then render no text. Without
89 * fontconfig there is no `fc-match` at all, which counts as no font.
90 */
91const fontAvailable = Effect.gen(function* () {
92 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
93 const font = yield* spawner
94 .string(
95 ChildProcess.make("fc-match", ["--format=%{file}", "sans-serif"], {
96 stdin: "ignore",
97 stderr: "ignore",
98 }),
99 )
100 .pipe(
101 Effect.timeout("5 seconds"),
102 Effect.orElseSucceed(() => ""),
103 );
104 return font.trim() !== "";
105}).pipe(Effect.withSpan("browserSetup.fontAvailable"));
106
107const FONT_PACKAGES = ["fontconfig", "fonts-liberation"];
108
109const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe(
110 Command.withDescription(
111 "Set up this Linux host for T3's browser: allow Chrome's sandbox and install its libraries and fonts.",
112 ),
113 Command.withHandler(({ baseDir }) =>
114 Effect.gen(function* () {
115 if ((yield* HostProcess.Platform) !== "linux") {
116 return yield* Console.log("Nothing to set up: T3's browser runs as is on this system.");
117 }
118 const fs = yield* FileSystem.FileSystem;
119 const isRoot = (yield* HostProcess.UserId) === 0;
120 const env = yield* HostProcess.Environment;
121 const baseDirPath = yield* setupBaseDir(baseDir);
122 // sudo resets the environment, so a chosen home has to be on the command line.
123 const setupCommand = yield* resolveRootCliCommand(
124 PreviewBrowserHost.SETUP_SUBCOMMAND,
125 Option.isSome(baseDir) || env.T3CODE_HOME !== undefined ? ["--base-dir", baseDirPath] : [],
126 );
127 // Root, unless sudo came from another user, is likely the server's own account.
128 const rootWarning =
129 isRoot && (env.SUDO_USER ?? "root") === "root" && !PreviewBrowserHost.sandboxDisabled(env)
130 ? new PreviewBrowserHost.PreviewBrowserRootError().message
131 : undefined;
132
133 const needsProfile = yield* PreviewBrowserHost.sandboxBlocked;
134 const browser = yield* installedBrowser(baseDirPath);
135 const missing = Option.isSome(browser)
136 ? yield* PreviewBrowserHost.missingLibraries(browser.value)
137 : [];
138 const needsFonts = !(yield* fontAvailable);
139 const hasApt = yield* fs.exists("/usr/bin/apt-get").pipe(Effect.orElseSucceed(() => false));
140
141 if (!needsProfile && missing.length === 0 && !needsFonts) {
142 return yield* Console.log(
143 rootWarning ??
144 (Option.isSome(browser)
145 ? "This host is ready for T3's browser."
146 : "Chrome's sandbox is allowed here. T3's browser installs on first use; if it then reports missing libraries, run this again."),
147 );
148 }
149
150 if (!isRoot) {
151 if (needsProfile) {
152 yield* Console.log(
153 `This host blocks the sandbox T3's browser runs in. Setup installs an AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} that allows it.`,
154 );
155 }
156 if (missing.length > 0) {
157 yield* Console.log(`T3's browser is missing ${missing.join(", ")}; setup installs them.`);
158 }
159 if (needsFonts) {
160 yield* Console.log(
161 "T3's browser needs fontconfig and system fonts; setup installs them.",
162 );
163 }
164 return yield* Console.log(`\nThis needs root. Run:\n\n ${setupCommand}\n`);
165 }
166
167 if (needsProfile) {
168 yield* fs
169 .writeFileString(
170 PreviewBrowserHost.APPARMOR_PROFILE_PATH,
171 PreviewBrowserHost.APPARMOR_PROFILE,
172 )
173 .pipe(
174 Effect.mapError(
175 (cause) =>
176 new BrowserSetupStepError({
177 step: `write ${PreviewBrowserHost.APPARMOR_PROFILE_PATH}`,
178 detail: cause.message,
179 }),
180 ),
181 );
182 yield* runStep("load the AppArmor profile", "apparmor_parser", [
183 "-r",
184 PreviewBrowserHost.APPARMOR_PROFILE_PATH,
185 ]);
186 yield* Console.log("Allowed Chrome's sandbox for T3's browser.");
187 }
188
189 if ((missing.length > 0 || needsFonts) && !hasApt) {
190 if (missing.length > 0) {
191 yield* Console.log(
192 `T3's browser is missing ${missing.join(", ")}. Install them with your package manager, then run this again.`,
193 );
194 }
195 if (needsFonts) {
196 yield* Console.log(
197 "T3's browser needs fontconfig and system fonts. Install them with your package manager, then run this again.",
198 );
199 }
200 return;
201 }
202 if (missing.length > 0 || needsFonts) {
203 yield* runStep("refresh the package lists", "apt-get", ["update"]);
204 }
205
206 if (missing.length > 0) {
207 const packages = yield* Effect.forEach(PreviewBrowserHost.DEBIAN_PACKAGES, (names) =>
208 Effect.findFirst(names, aptOffers).pipe(Effect.map(Option.getOrElse(() => names[0]!))),
209 );
210 yield* runStep("install the browser's libraries", "apt-get", [
211 "install",
212 "-y",
213 "--no-install-recommends",
214 ...packages,
215 ]);
216 yield* Console.log("Installed the browser's libraries.");
217 }
218
219 if (needsFonts) {
220 yield* runStep("install the browser's fonts", "apt-get", [
221 "install",
222 "-y",
223 "--no-install-recommends",
224 ...FONT_PACKAGES,
225 ]);
226 if (!(yield* fontAvailable)) {
227 return yield* Console.log(
228 "Font packages are installed, but Fontconfig still finds no system font. Check its configuration and run setup again.",
229 );
230 }
231 yield* Console.log(
232 "Installed the browser's fonts. Restart the T3 server if browser tabs were already open.",
233 );
234 }
235
236 yield* Console.log(rootWarning ?? "This host is ready for T3's browser.");
237 }),
238 ),
239);
240
241export const browserCommand = Command.make("browser").pipe(
242 Command.withDescription("Manage T3's headless browser on this host."),
243 Command.withSubcommands([browserSetupCommand]),
244);