Skip to content
TypeScript

fix(cli): browser setup installs missing fonts (#17570)

Adrian Las03a2b1acc673
diff --git a/apps/server/src/cli/browser.test.ts b/apps/server/src/cli/browser.test.ts
index ef775b9c184..0646ccfc773 100644
--- a/apps/server/src/cli/browser.test.ts
+++ b/apps/server/src/cli/browser.test.ts
@@ -4,11 +4,94 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as PlatformError from "effect/PlatformError";
+import * as Sink from "effect/Sink";
+import * as Stream from "effect/Stream";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/cli";
+import * as ChildProcess from "effect/process/ChildProcess";
+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { browserCommand } from "./browser.ts";
+const BROWSER = "/t3/tools/chrome-headless-shell/linux64/154/chrome-headless-shell";
+const FONT = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf";
+
+/**
+ * Records every command. `fc-match` is missing until fonts are installed, unless
+ * the host starts with a font; the browser fails to load libnss3 when asked to.
+ */
+const fakeSpawner = (host: { readonly font?: string; readonly missingLibrary?: boolean }) => {
+ const commands: Array<ReadonlyArray<string>> = [];
+ let font = host.font;
+ const spawner = ChildProcessSpawner.make((command) =>
+ Effect.gen(function* () {
+ if (!ChildProcess.isStandardCommand(command)) return yield* Effect.die("Unexpected pipeline");
+ commands.push([command.command, ...command.args]);
+ if (command.command === "apt-get" && command.args.includes("fonts-liberation")) font = FONT;
+ if (command.command === "fc-match" && font === undefined) {
+ return yield* PlatformError.systemError({
+ _tag: "NotFound",
+ module: "ChildProcess",
+ method: "spawn",
+ });
+ }
+ const output =
+ command.command === "fc-match"
+ ? font!
+ : command.command === BROWSER && host.missingLibrary
+ ? "error while loading shared libraries: libnss3.so: cannot open shared object file"
+ : command.command === "ldd"
+ ? "\tlibnss3.so => not found\n"
+ : "";
+ const bytes = Stream.make(new TextEncoder().encode(output));
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(1),
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
+ isRunning: Effect.succeed(false),
+ kill: () => Effect.void,
+ unref: Effect.succeed(Effect.void),
+ stdin: Sink.drain,
+ stdout: bytes,
+ stderr: Stream.empty,
+ all: bytes,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ });
+ }),
+ );
+ return { spawner, commands };
+};
+
+/** A Linux host with apt and T3's browser installed under `/t3`. */
+const runSetup = (host: {
+ readonly root: boolean;
+ readonly font?: string;
+ readonly missingLibrary?: boolean;
+}) => {
+ const { spawner, commands } = fakeSpawner(host);
+ const fs = FileSystem.makeNoop({
+ exists: (path) => Effect.succeed(path === "/usr/bin/apt-get" || path === BROWSER),
+ readDirectory: (path) =>
+ Effect.succeed(path.endsWith("chrome-headless-shell") ? ["linux64"] : ["154"]),
+ });
+ return Effect.gen(function* () {
+ yield* Command.runWith(browserCommand, { version: "0.0.0" })(["setup", "--base-dir", "/t3"]);
+ return { commands, output: (yield* TestConsole.logLines).join("\n") };
+ }).pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+ Effect.provideService(HostProcess.Platform, "linux"),
+ Effect.provideService(HostProcess.UserId, host.root ? 0 : 1000),
+ // Root through sudo from a regular user, so setup reports ready instead of the root warning.
+ Effect.provideService(HostProcess.Environment, host.root ? { SUDO_USER: "alice" } : {}),
+ Effect.provide(Layer.mergeAll(NodeServices.layer, TestConsole.layer)),
+ );
+};
+
+const aptGet = (commands: ReadonlyArray<ReadonlyArray<string>>) =>
+ commands.filter(([name]) => name === "apt-get");
+
it.effect("setup in a root shell warns that the server cannot run as root", () =>
Effect.gen(function* () {
// Every file read fails, so setup finds nothing to install and changes nothing.
@@ -18,6 +101,10 @@ it.effect("setup in a root shell warns that the server cannot run as root", () =
"/nonexistent",
]).pipe(
Effect.provide(FileSystem.layerNoop({})),
+ Effect.provideService(
+ ChildProcessSpawner.ChildProcessSpawner,
+ fakeSpawner({ font: FONT }).spawner,
+ ),
Effect.provideService(HostProcess.Platform, "linux"),
Effect.provideService(HostProcess.UserId, 0),
// A root user who follows the old advice runs setup through sudo.
@@ -28,3 +115,34 @@ it.effect("setup in a root shell warns that the server cannot run as root", () =
expect(output).not.toContain("ready");
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, TestConsole.layer))),
);
+
+it.effect("setup without root does not report a host without fonts as ready", () =>
+ Effect.gen(function* () {
+ const { commands, output } = yield* runSetup({ root: false });
+ expect(output).toContain(
+ "T3's browser needs fontconfig and system fonts; setup installs them.",
+ );
+ expect(output).toContain("This needs root. Run:");
+ expect(output).not.toContain("ready");
+ expect(aptGet(commands)).toEqual([]);
+ }),
+);
+
+it.effect("setup as root installs missing libraries and fonts after one package refresh", () =>
+ Effect.gen(function* () {
+ const { commands, output } = yield* runSetup({ root: true, missingLibrary: true });
+ const apt = aptGet(commands);
+ expect(apt.filter(([, action]) => action === "update")).toHaveLength(1);
+ expect(apt.find((args) => args.includes("libnss3"))).toBeDefined();
+ expect(apt).toContainEqual([
+ "apt-get",
+ "install",
+ "-y",
+ "--no-install-recommends",
+ "fontconfig",
+ "fonts-liberation",
+ ]);
+ expect(output).toContain("Installed the browser's fonts.");
+ expect(output).toContain("This host is ready for T3's browser.");
+ }),
+);
diff --git a/apps/server/src/cli/browser.ts b/apps/server/src/cli/browser.ts
index f741458241d..641c8978f19 100644
--- a/apps/server/src/cli/browser.ts
+++ b/apps/server/src/cli/browser.ts
@@ -84,9 +84,31 @@ const installedBrowser = Effect.fn("browserSetup.installedBrowser")(function* (b
return Option.none<string>();
});
+/**
+ * Chrome starts without fonts, but pages then render no text. Without
+ * fontconfig there is no `fc-match` at all, which counts as no font.
+ */
+const fontAvailable = Effect.gen(function* () {
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const font = yield* spawner
+ .string(
+ ChildProcess.make("fc-match", ["--format=%{file}", "sans-serif"], {
+ stdin: "ignore",
+ stderr: "ignore",
+ }),
+ )
+ .pipe(
+ Effect.timeout("5 seconds"),
+ Effect.orElseSucceed(() => ""),
+ );
+ return font.trim() !== "";
+}).pipe(Effect.withSpan("browserSetup.fontAvailable"));
+
+const FONT_PACKAGES = ["fontconfig", "fonts-liberation"];
+
const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe(
Command.withDescription(
- "Set up this Linux host for T3's browser: allow Chrome's sandbox and install its libraries.",
+ "Set up this Linux host for T3's browser: allow Chrome's sandbox and install its libraries and fonts.",
),
Command.withHandler(({ baseDir }) =>
Effect.gen(function* () {
@@ -108,9 +130,10 @@ const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe
const missing = Option.isSome(browser)
? yield* PreviewBrowserHost.missingLibraries(browser.value)
: [];
+ const needsFonts = !(yield* fontAvailable);
const hasApt = yield* fs.exists("/usr/bin/apt-get").pipe(Effect.orElseSucceed(() => false));
- if (!needsProfile && missing.length === 0) {
+ if (!needsProfile && missing.length === 0 && !needsFonts) {
return yield* Console.log(
rootWarning ??
(Option.isSome(browser)
@@ -128,6 +151,11 @@ const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe
if (missing.length > 0) {
yield* Console.log(`T3's browser is missing ${missing.join(", ")}; setup installs them.`);
}
+ if (needsFonts) {
+ yield* Console.log(
+ "T3's browser needs fontconfig and system fonts; setup installs them.",
+ );
+ }
return yield* Console.log(`\nThis needs root. Run:\n\n ${setupCommand}\n`);
}
@@ -153,13 +181,24 @@ const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe
yield* Console.log("Allowed Chrome's sandbox for T3's browser.");
}
- if (missing.length > 0) {
- if (!hasApt) {
- return yield* Console.log(
+ if ((missing.length > 0 || needsFonts) && !hasApt) {
+ if (missing.length > 0) {
+ yield* Console.log(
`T3's browser is missing ${missing.join(", ")}. Install them with your package manager, then run this again.`,
);
}
+ if (needsFonts) {
+ yield* Console.log(
+ "T3's browser needs fontconfig and system fonts. Install them with your package manager, then run this again.",
+ );
+ }
+ return;
+ }
+ if (missing.length > 0 || needsFonts) {
yield* runStep("refresh the package lists", "apt-get", ["update"]);
+ }
+
+ if (missing.length > 0) {
const packages = yield* Effect.forEach(PreviewBrowserHost.DEBIAN_PACKAGES, (names) =>
Effect.findFirst(names, aptOffers).pipe(Effect.map(Option.getOrElse(() => names[0]!))),
);
@@ -172,6 +211,23 @@ const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe
yield* Console.log("Installed the browser's libraries.");
}
+ if (needsFonts) {
+ yield* runStep("install the browser's fonts", "apt-get", [
+ "install",
+ "-y",
+ "--no-install-recommends",
+ ...FONT_PACKAGES,
+ ]);
+ if (!(yield* fontAvailable)) {
+ return yield* Console.log(
+ "Font packages are installed, but Fontconfig still finds no system font. Check its configuration and run setup again.",
+ );
+ }
+ yield* Console.log(
+ "Installed the browser's fonts. Restart the T3 server if browser tabs were already open.",
+ );
+ }
+
yield* Console.log(rootWarning ?? "This host is ready for T3's browser.");
}),
),
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index 6ba7a63ef27..aaa80e39ca9 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -231,8 +231,9 @@ The server shows the exact line for how you started it, such as
`sudo npx t3 browser setup`, and keeps your `PATH` when Node is installed only
for your user. Where `t3` is not on your `PATH`, such as with only the
desktop app installed, it names the full path of the app's own `t3` instead. It allows Chrome's sandbox with an AppArmor profile and installs
-any missing libraries with apt. It is safe to run again. Without `sudo`, it
-only reports what it would change.
+any missing libraries and system fonts with apt; pages that load without text
+can mean the host has no fonts. It is safe to run again. Without `sudo`, it only
+reports what it would change.
The browser always runs in Chrome's sandbox. Where you cannot change the host,
set `T3CODE_SERVER_BROWSER_SANDBOX=0` for the environment to run without it.