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

browser.ts

266 lines10.6 KB

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 }
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/** Under sudo, an unspecified home uses the invoking user's ~/.t3. */
43const setupBaseDir = Effect.fn("browserSetup.baseDir")(function* (explicit: Option.Option<string>) {
44 const env = yield* HostProcess.Environment;
45 const raw = Option.getOrUndefined(explicit) ?? env.T3CODE_HOME;
46 if (raw !== undefined || env.SUDO_USER === undefined) return yield* resolveBaseDir(raw);
47 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
48 const entry = yield* spawner
49 .string(
50 ChildProcess.make("getent", ["passwd", env.SUDO_USER], { stdin: "ignore", stderr: "ignore" }),
51 )
52 .pipe(Effect.orElseSucceed(() => ""));
53 const home = entry.trim().split(":")[5];
54 const path = yield* Path.Path;
55 return home ? path.join(home, ".t3") : yield* resolveBaseDir(undefined);
56});
57​
58const aptOffers = Effect.fn("browserSetup.aptOffers")(function* (name: string) {
59 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
60 const policy = yield* spawner
61 .string(
62 ChildProcess.make("apt-cache", ["policy", name], {
63 stdin: "ignore",
64 stderr: "ignore",
65 env: { LC_ALL: "C" },
66 extendEnv: true,
67 }),
68 )
69 .pipe(Effect.orElseSucceed(() => ""));
70 const candidate = /Candidate:\s*(\S+)/.exec(policy)?.[1];
71 return candidate !== undefined && candidate !== "(none)";
72});
73​
74const installedBrowser = Effect.fn("browserSetup.installedBrowser")(function* (baseDir: string) {
75 const fs = yield* FileSystem.FileSystem;
76 const path = yield* Path.Path;
77 const root = path.join(baseDir, "tools", "chrome-headless-shell");
78 for (const platform of yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []))) {
79 for (const version of yield* fs
80 .readDirectory(path.join(root, platform))
81 .pipe(Effect.orElseSucceed(() => []))) {
82 const executable = path.join(root, platform, version, "chrome-headless-shell");
83 if (yield* fs.exists(executable).pipe(Effect.orElseSucceed(() => false))) {
84 return Option.some(executable);
85 }
86 }
87 }
88 return Option.none<string>();
89});
90​
91/**
92 * Chrome starts without fonts, but pages then render no text. Without
93 * fontconfig there is no `fc-match` at all, which counts as no font.
94 */
95const fontAvailable = Effect.gen(function* () {
96 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
97 const font = yield* spawner
98 .string(
99 ChildProcess.make("fc-match", ["--format=%{file}", "sans-serif"], {
100 stdin: "ignore",
101 stderr: "ignore",
102 }),
103 )
104 .pipe(
105 Effect.timeout("5 seconds"),
106 Effect.orElseSucceed(() => ""),
107 );
108 return font.trim() !== "";
109}).pipe(Effect.withSpan("browserSetup.fontAvailable"));
110​
111const FONT_PACKAGES = ["fontconfig", "fonts-liberation"];
112​
113const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe(
114 Command.withDescription(
115 "Set up this Linux host for T3's browser: allow Chrome's sandbox and install its libraries and fonts.",
116 ),
117 Command.withHandler(({ baseDir }) =>
118 Effect.gen(function* () {
119 if ((yield* HostProcess.Platform) !== "linux") {
120 return yield* Console.log("Nothing to set up: T3's browser runs as is on this system.");
121 }
122 const fs = yield* FileSystem.FileSystem;
123 const isRoot = (yield* HostProcess.UserId) === 0;
124 const env = yield* HostProcess.Environment;
125 const baseDirPath = yield* setupBaseDir(baseDir);
126 // sudo resets the environment, so a chosen home has to be on the command line.
127 const setupCommand = yield* resolveRootCliCommand(
128 PreviewBrowserHost.SETUP_SUBCOMMAND,
129 Option.isSome(baseDir) || env.T3CODE_HOME !== undefined ? ["--base-dir", baseDirPath] : [],
130 );
131 // Root, unless sudo came from another user, is likely the server's own account.
132 const rootWarning =
133 isRoot && (env.SUDO_USER ?? "root") === "root" && !PreviewBrowserHost.sandboxDisabled(env)
134 ? new PreviewBrowserHost.PreviewBrowserRootError().message
135 : undefined;
136​
137 const restricted = yield* PreviewBrowserHost.usernsRestricted;
138 // The kernel can lack a profile that is on disk, as on a host restored from an image,
139 // and only root can read the loaded list, so root reloads it on every run.
140 const needsProfile = isRoot ? restricted : yield* PreviewBrowserHost.sandboxBlocked;
141 const reloadHint =
142 restricted && !isRoot
143 ? `\nIf the browser still reports a blocked sandbox, the AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} is not loaded. To load it, run:\n\n ${setupCommand}\n`
144 : "";
145 const browser = yield* installedBrowser(baseDirPath);
146 const missing = Option.isSome(browser)
147 ? yield* PreviewBrowserHost.missingLibraries(browser.value)
148 : [];
149 const needsFonts = !(yield* fontAvailable);
150 const hasApt = yield* fs.exists("/usr/bin/apt-get").pipe(Effect.orElseSucceed(() => false));
151​
152 if (!needsProfile && missing.length === 0 && !needsFonts) {
153 return yield* Console.log(
154 rootWarning ??
155 (Option.isSome(browser)
156 ? "This host is ready for T3's browser."
157 : "Chrome's sandbox is allowed here. T3's browser installs on first use; if it then reports missing libraries, run this again.") +
158 reloadHint,
159 );
160 }
161​
162 if (!isRoot) {
163 if (needsProfile) {
164 yield* Console.log(
165 `This host blocks the sandbox T3's browser runs in. Setup installs an AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} that allows it.`,
166 );
167 }
168 if (missing.length > 0) {
169 yield* Console.log(`T3's browser is missing ${missing.join(", ")}; setup installs them.`);
170 }
171 if (needsFonts) {
172 yield* Console.log(
173 "T3's browser needs fontconfig and system fonts; setup installs them.",
174 );
175 }
176 return yield* Console.log(`\nThis needs root. Run:\n\n ${setupCommand}\n`);
177 }
178​
179 if (needsProfile) {
180 // An existing profile may carry an administrator's edits, so it is reloaded as is.
181 const profileOnDisk = yield* fs
182 .exists(PreviewBrowserHost.APPARMOR_PROFILE_PATH)
183 .pipe(Effect.orElseSucceed(() => false));
184 if (!profileOnDisk) {
185 yield* fs
186 .writeFileString(
187 PreviewBrowserHost.APPARMOR_PROFILE_PATH,
188 PreviewBrowserHost.APPARMOR_PROFILE,
189 )
190 .pipe(
191 Effect.mapError(
192 (cause) =>
193 new BrowserSetupStepError({
194 step: `write ${PreviewBrowserHost.APPARMOR_PROFILE_PATH}`,
195 detail: cause.message,
196 }),
197 ),
198 );
199 }
200 yield* runStep("load the AppArmor profile", "apparmor_parser", [
201 "-r",
202 PreviewBrowserHost.APPARMOR_PROFILE_PATH,
203 ]);
204 yield* Console.log(
205 profileOnDisk
206 ? `Reloaded the AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} that allows Chrome's sandbox for T3's browser.`
207 : `Wrote and loaded the AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} that allows Chrome's sandbox for T3's browser.`,
208 );
209 }
210​
211 if ((missing.length > 0 || needsFonts) && !hasApt) {
212 if (missing.length > 0) {
213 yield* Console.log(
214 `T3's browser is missing ${missing.join(", ")}. Install them with your package manager, then run this again.`,
215 );
216 }
217 if (needsFonts) {
218 yield* Console.log(
219 "T3's browser needs fontconfig and system fonts. Install them with your package manager, then run this again.",
220 );
221 }
222 return;
223 }
224 if (missing.length > 0 || needsFonts) {
225 yield* runStep("refresh the package lists", "apt-get", ["update"]);
226 }
227​
228 if (missing.length > 0) {
229 const packages = yield* Effect.forEach(PreviewBrowserHost.DEBIAN_PACKAGES, (names) =>
230 Effect.findFirst(names, aptOffers).pipe(Effect.map(Option.getOrElse(() => names[0]!))),
231 );
232 yield* runStep("install the browser's libraries", "apt-get", [
233 "install",
234 "-y",
235 "--no-install-recommends",
236 ...packages,
237 ]);
238 yield* Console.log("Installed the browser's libraries.");
239 }
240​
241 if (needsFonts) {
242 yield* runStep("install the browser's fonts", "apt-get", [
243 "install",
244 "-y",
245 "--no-install-recommends",
246 ...FONT_PACKAGES,
247 ]);
248 if (!(yield* fontAvailable)) {
249 return yield* Console.log(
250 "Font packages are installed, but Fontconfig still finds no system font. Check its configuration and run setup again.",
251 );
252 }
253 yield* Console.log(
254 "Installed the browser's fonts. Restart the T3 server if browser tabs were already open.",
255 );
256 }
257​
258 yield* Console.log(rootWarning ?? "This host is ready for T3's browser.");
259 }),
260 ),
261);
262​
263export const browserCommand = Command.make("browser").pipe(
264 Command.withDescription("Manage T3's headless browser on this host."),
265 Command.withSubcommands([browserSetupCommand]),
266);