Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

build: strip the Tauri webview stack from GPUI Linux packages

Cursor Agent5824644f6381
diff --git a/scripts/finalize-linux-appimage.mjs b/scripts/finalize-linux-appimage.mjs
index b796b1cbb..b3e503e79 100644
--- a/scripts/finalize-linux-appimage.mjs
+++ b/scripts/finalize-linux-appimage.mjs
@@ -5,12 +5,18 @@ import {
access,
chmod,
copyFile,
+ lstat,
mkdtemp,
+ open,
readdir,
readFile,
+ readlink,
+ realpath,
rename,
rm,
+ rmdir,
stat,
+ symlink,
writeFile,
} from "node:fs/promises";
import { homedir } from "node:os";
@@ -243,10 +249,190 @@ export async function findConflictingLibraries(appDir, directory = appDir) {
return libraries;
}
+const elfMagic = Buffer.from([0x7f, 0x45, 0x4c, 0x46]);
+
+async function isElf(filename) {
+ const handle = await open(filename, "r");
+ try {
+ const { buffer, bytesRead } = await handle.read(Buffer.alloc(4), 0, 4, 0);
+ return bytesRead === 4 && buffer.equals(elfMagic);
+ } finally {
+ await handle.close();
+ }
+}
+
+async function neededLibraries(filename, env, run) {
+ const result = await run("readelf", ["--wide", "--dynamic", filename], {
+ env: { ...env, LC_ALL: "C" },
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "inherit"],
+ });
+ if (typeof result.stdout !== "string") {
+ throw new Error(`Could not read the dynamic section of ${filename}`);
+ }
+ return [
+ ...result.stdout.matchAll(/\(NEEDED\)\s+Shared library: \[([^\]]+)\]/g),
+ ].map((match) => match[1]);
+}
+
+async function elfFiles(directory, libraryDirectory) {
+ const files = [];
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ const filename = path.join(directory, entry.name);
+ if (entry.isDirectory()) {
+ files.push(...(await elfFiles(filename, libraryDirectory)));
+ } else if (
+ entry.isFile() &&
+ directory !== libraryDirectory &&
+ (await isElf(filename))
+ ) {
+ files.push(filename);
+ }
+ }
+ return files;
+}
+
+const gtkLauncherSource =
+ /^\s*source\s+"\$this_dir"\/apprun-hooks\/"linuxdeploy-plugin-gtk\.sh"\s*$/;
+const gtkLauncherExec = /^\s*exec\s+"\$this_dir"\/AppRun\.wrapped\s+"\$@"\s*$/;
+
+async function removeGtkLauncher(appDir) {
+ const hooks = path.join(appDir, "apprun-hooks");
+ const launcher = path.join(appDir, "AppRun");
+ const wrapped = path.join(appDir, "AppRun.wrapped");
+ const commands = (await readFile(launcher, "utf8"))
+ .split("\n")
+ .filter((line) => line.trim() && !line.trimStart().startsWith("#"));
+ const sources = commands.filter((line) => /^\s*source\b/.test(line));
+ if (
+ (await readdir(hooks)).join() !== "linuxdeploy-plugin-gtk.sh" ||
+ sources.length !== 1 ||
+ !gtkLauncherSource.test(sources[0]) ||
+ !gtkLauncherExec.test(commands.at(-1) ?? "")
+ ) {
+ throw new Error(
+ "Unrecognized AppImage launcher; refusing to remove the GTK runtime",
+ );
+ }
+ await access(wrapped, constants.X_OK);
+ await rm(hooks, { recursive: true });
+ await rename(wrapped, launcher);
+}
+
+async function webviewRuntimeDirectories(appDir) {
+ const libraryDirectory = path.join(appDir, "usr/lib");
+ const multiarch = (await readdir(libraryDirectory, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory() && /-linux-gnu/.test(entry.name))
+ .map((entry) => path.join(libraryDirectory, entry.name));
+ return {
+ multiarch,
+ directories: [
+ "usr/lib/gtk-3.0",
+ "usr/lib/gdk-pixbuf-2.0",
+ "usr/lib/girepository-1.0",
+ "usr/lib/webkit2gtk-4.1",
+ "usr/lib64/webkit2gtk-4.1",
+ "usr/libexec/webkit2gtk-4.1",
+ "usr/share/glib-2.0",
+ ]
+ .map((directory) => path.join(appDir, directory))
+ .concat(
+ multiarch.flatMap((directory) => [
+ path.join(directory, "webkit2gtk-4.1"),
+ path.join(directory, "gio"),
+ ]),
+ ),
+ };
+}
+
+export async function removeWebviewRuntime(
+ appDir,
+ { env = process.env, run = runCommand } = {},
+) {
+ await removeGtkLauncher(appDir);
+ const removed = [];
+ const { directories, multiarch } = await webviewRuntimeDirectories(appDir);
+ for (const directory of directories) {
+ const entry = await lstat(directory).catch(() => null);
+ if (!entry) continue;
+ await rm(directory, { recursive: true });
+ removed.push(directory);
+ }
+ for (const directory of multiarch) {
+ if ((await readdir(directory)).length === 0) await rmdir(directory);
+ }
+
+ const libraryDirectory = path.join(appDir, "usr/lib");
+ const libraryRoot = await realpath(libraryDirectory);
+ const candidates = new Set(
+ (await readdir(libraryDirectory, { withFileTypes: true }))
+ .filter(
+ (entry) =>
+ (entry.isFile() || entry.isSymbolicLink()) &&
+ /\.so(?:\.|$)/.test(entry.name),
+ )
+ .map((entry) => entry.name),
+ );
+ const pending = [];
+ for (const file of await elfFiles(appDir, libraryDirectory)) {
+ pending.push(...(await neededLibraries(file, env, run)));
+ }
+ const kept = new Set();
+ while (pending.length > 0) {
+ const name = pending.pop();
+ if (kept.has(name) || !candidates.has(name)) continue;
+ kept.add(name);
+ const filename = path.join(libraryDirectory, name);
+ if ((await lstat(filename)).isSymbolicLink()) {
+ const target = await realpath(filename).catch(() => null);
+ if (target && path.dirname(target) === libraryRoot) {
+ pending.push(path.basename(target));
+ }
+ } else if (await isElf(filename)) {
+ pending.push(...(await neededLibraries(filename, env, run)));
+ }
+ }
+ for (const name of candidates) {
+ if (kept.has(name)) continue;
+ const filename = path.join(libraryDirectory, name);
+ await rm(filename);
+ removed.push(filename);
+ }
+ return removed;
+}
+
+export async function relativizeDirIcon(appDir) {
+ const icon = path.join(appDir, ".DirIcon");
+ const target = await readlink(icon).catch(() => null);
+ if (!target || !path.isAbsolute(target)) return;
+ const name = path.basename(target);
+ await access(path.join(appDir, name));
+ await rm(icon);
+ await symlink(name, icon);
+}
+
+export async function signUpdaterArtifact(
+ filename,
+ { env = process.env, run = runCommand } = {},
+) {
+ await run("bun", ["run", "tauri", "signer", "sign", filename], {
+ cwd: desktopDirectory,
+ env: {
+ ...env,
+ TAURI_PRIVATE_KEY: env.TAURI_SIGNING_PRIVATE_KEY,
+ TAURI_PRIVATE_KEY_PASSWORD: env.TAURI_SIGNING_PRIVATE_KEY_PASSWORD ?? "",
+ },
+ });
+ if (!(await stat(`${filename}.sig`)).size) {
+ throw new Error(`Updater signature for ${filename} is empty`);
+ }
+}
+
export async function finalizeLinuxAppImage(
filename,
{
unsigned = false,
+ webview = true,
env = process.env,
run = runCommand,
replace = rename,
@@ -285,7 +471,12 @@ export async function finalizeLinuxAppImage(
const excluded = await findConflictingLibraries(appDir);
// Host Mesa and ALSA plugins require their matching Wayland and PipeWire ABIs.
for (const library of excluded) await rm(library);
- await selectAppImageGtkBackend(appDir);
+ if (webview) {
+ await selectAppImageGtkBackend(appDir);
+ } else {
+ excluded.push(...(await removeWebviewRuntime(appDir, { env, run })));
+ }
+ await relativizeDirIcon(appDir);
await preserveAppImageWorkingDirectory(appDir);
const output = path.join(work, path.basename(image));
await run(
@@ -309,20 +500,7 @@ export async function finalizeLinuxAppImage(
throw new Error("Final AppImage did not preserve its runtime");
}
await chmod(output, 0o755);
- if (!unsigned) {
- await run("bun", ["run", "tauri", "signer", "sign", output], {
- cwd: desktopDirectory,
- env: {
- ...env,
- TAURI_PRIVATE_KEY: env.TAURI_SIGNING_PRIVATE_KEY,
- TAURI_PRIVATE_KEY_PASSWORD:
- env.TAURI_SIGNING_PRIVATE_KEY_PASSWORD ?? "",
- },
- });
- if (!(await stat(`${output}.sig`)).size) {
- throw new Error("Final AppImage updater signature is empty");
- }
- }
+ if (!unsigned) await signUpdaterArtifact(output, { env, run });
const originalImage = path.join(work, "original-image");
const originalImageStat = await stat(image);
await copyFile(image, originalImage, constants.COPYFILE_FICLONE);
@@ -356,16 +534,19 @@ if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
) {
+ const flags = new Set(["--unsigned", "--without-webview"]);
const args = process.argv.slice(2);
- const unsigned = args[0] === "--unsigned";
- if (unsigned) args.shift();
- if (process.platform !== "linux" || args.length !== 1) {
+ const files = args.filter((arg) => !flags.has(arg));
+ if (process.platform !== "linux" || files.length !== 1) {
throw new Error(
- "Run on Linux: node scripts/finalize-linux-appimage.mjs [--unsigned] <Cap.AppImage>",
+ "Run on Linux: node scripts/finalize-linux-appimage.mjs [--unsigned] [--without-webview] <Cap.AppImage>",
);
}
- const excluded = await finalizeLinuxAppImage(args[0], { unsigned });
+ const excluded = await finalizeLinuxAppImage(files[0], {
+ unsigned: args.includes("--unsigned"),
+ webview: !args.includes("--without-webview"),
+ });
console.log(
- `Finalized ${args[0]}; excluded ${excluded.join(", ") || "none"}`,
+ `Finalized ${files[0]}; excluded ${excluded.join(", ") || "none"}`,
);
}
diff --git a/scripts/finalize-linux-appimage.test.mjs b/scripts/finalize-linux-appimage.test.mjs
index c53697eab..38f0bd30c 100644
--- a/scripts/finalize-linux-appimage.test.mjs
+++ b/scripts/finalize-linux-appimage.test.mjs
@@ -7,6 +7,7 @@ import {
mkdtemp,
readdir,
readFile,
+ readlink,
realpath,
rename,
rm,
@@ -22,6 +23,8 @@ import {
finalizeLinuxAppImage,
findConflictingLibraries,
preserveAppImageWorkingDirectory,
+ relativizeDirIcon,
+ removeWebviewRuntime,
selectAppImageGtkBackend,
} from "./finalize-linux-appimage.mjs";
@@ -644,3 +647,213 @@ exit 23
assert.match(result.stdout.toString(), /^GUI launched:/);
assert.ok(!result.stdout.toString().includes("/stale/caller"));
});
+
+const linuxdeployLauncher = `#! /usr/bin/env bash
+
+# autogenerated by linuxdeploy
+
+# make sure errors in sourced scripts will cause this script to stop
+set -e
+
+this_dir="$(readlink -f "$(dirname "$0")")"
+
+source "$this_dir"/apprun-hooks/"linuxdeploy-plugin-gtk.sh"
+
+exec "$this_dir"/AppRun.wrapped "$@"
+`;
+
+const elf = (name) =>
+ Buffer.concat([Buffer.from([0x7f, 0x45, 0x4c, 0x46]), Buffer.from(name)]);
+
+const webviewFixtureFiles = {
+ "usr/bin/Cap": ["libssl.so.3", "libavcodec.so.61", "libc.so.6"],
+ "usr/bin/pactl": ["libpulse.so.0"],
+ "usr/lib/cap/libavcodec.so.61": ["libva.so.2"],
+ "usr/lib/libssl.so.3": ["libcrypto.so.3"],
+ "usr/lib/libcrypto.so.3": [],
+ "usr/lib/libavcodec.so.61": ["libva.so.2"],
+ "usr/lib/libva.so.2.2100.0": [],
+ "usr/lib/libpulse.so.0": [],
+ "usr/lib/libwebkit2gtk-4.1.so.0": ["libgtk-3.so.0"],
+ "usr/lib/libgtk-3.so.0": [],
+ "usr/lib/im-xim.so": ["libgtk-3.so.0"],
+ "usr/lib/gtk-3.0/3.0.0/immodules.cache": null,
+ "usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache": null,
+ "usr/lib/girepository-1.0/Gtk-3.0.typelib": null,
+ "usr/lib/x86_64-linux-gnu/webkit2gtk-4.1/WebKitWebProcess": [
+ "libwebkit2gtk-4.1.so.0",
+ ],
+ "usr/lib/x86_64-linux-gnu/gio/modules/libgiognutls.so": ["libgtk-3.so.0"],
+ "usr/share/glib-2.0/schemas/gschemas.compiled": null,
+ "usr/lib/notes.txt": null,
+ "usr/lib/Cap/assets/music/track.mp3": null,
+ "AppRun.wrapped": ["libc.so.6"],
+};
+
+async function webviewAppDir(parent, name = "AppDir") {
+ const appDir = path.join(parent, name);
+ for (const [file, libraries] of Object.entries(webviewFixtureFiles)) {
+ const filename = path.join(appDir, file);
+ await mkdir(path.dirname(filename), { recursive: true });
+ await writeFile(filename, libraries ? elf(file) : "data", {
+ mode: 0o755,
+ });
+ }
+ await symlink("libva.so.2.2100.0", path.join(appDir, "usr/lib/libva.so.2"));
+ await symlink("libgtk-3.so.0", path.join(appDir, "usr/lib/libgtk-3.so"));
+ await gtkHook(appDir);
+ await writeFile(path.join(appDir, "AppRun"), linuxdeployLauncher, {
+ mode: 0o755,
+ });
+ const readelf = [];
+ const run = async (command, args, options) => {
+ assert.equal(command, "readelf");
+ assert.deepEqual(args.slice(0, 2), ["--wide", "--dynamic"]);
+ assert.equal(options.env.LC_ALL, "C");
+ const file = path.relative(appDir, args[2]);
+ readelf.push(file);
+ const libraries =
+ webviewFixtureFiles[file === "AppRun" ? "AppRun.wrapped" : file];
+ assert.ok(libraries, `unexpected readelf of ${file}`);
+ return {
+ stdout: libraries
+ .map(
+ (library) =>
+ ` 0x0000000000000001 (NEEDED) Shared library: [${library}]`,
+ )
+ .join("\n"),
+ };
+ };
+ return { appDir, run, readelf };
+}
+
+test("webview runtime removal keeps only libraries the shipped binaries load", async (t) => {
+ const { root } = await fixture(t);
+ const { appDir, run, readelf } = await webviewAppDir(root);
+ const removed = await removeWebviewRuntime(appDir, { env: {}, run });
+ assert.deepEqual(removed.map((file) => path.relative(appDir, file)).sort(), [
+ "usr/lib/gdk-pixbuf-2.0",
+ "usr/lib/girepository-1.0",
+ "usr/lib/gtk-3.0",
+ "usr/lib/im-xim.so",
+ "usr/lib/libgtk-3.so",
+ "usr/lib/libgtk-3.so.0",
+ "usr/lib/libwebkit2gtk-4.1.so.0",
+ "usr/lib/x86_64-linux-gnu/gio",
+ "usr/lib/x86_64-linux-gnu/webkit2gtk-4.1",
+ "usr/share/glib-2.0",
+ ]);
+ assert.deepEqual((await readdir(path.join(appDir, "usr/lib"))).sort(), [
+ "Cap",
+ "cap",
+ "libavcodec.so.61",
+ "libcrypto.so.3",
+ "libpulse.so.0",
+ "libssl.so.3",
+ "libva.so.2",
+ "libva.so.2.2100.0",
+ "notes.txt",
+ ]);
+ assert.deepEqual((await readdir(appDir)).sort(), ["AppRun", "usr"]);
+ assert.deepEqual(
+ await readFile(path.join(appDir, "AppRun")),
+ elf("AppRun.wrapped"),
+ );
+ assert.ok(!readelf.some((file) => file.includes("webkit2gtk-4.1/")));
+ assert.ok(!readelf.includes("usr/lib/libgtk-3.so.0"));
+});
+
+for (const [name, launcher, hooks] of [
+ [
+ "an extra hook",
+ linuxdeployLauncher.replace(
+ "\nexec",
+ '\nsource "$this_dir"/apprun-hooks/"other.sh"\n\nexec',
+ ),
+ ["other.sh"],
+ ],
+ [
+ "a different launcher target",
+ linuxdeployLauncher.replace("AppRun.wrapped", "usr/bin/Cap"),
+ [],
+ ],
+]) {
+ test(`webview runtime removal refuses ${name} without changing the AppDir`, async (t) => {
+ const { root } = await fixture(t);
+ const { appDir, run } = await webviewAppDir(root);
+ await writeFile(path.join(appDir, "AppRun"), launcher);
+ for (const hook of hooks) {
+ await writeFile(path.join(appDir, "apprun-hooks", hook), "");
+ }
+ const before = (await readdir(path.join(appDir, "usr/lib"))).sort();
+ await assert.rejects(
+ removeWebviewRuntime(appDir, { env: {}, run }),
+ /Unrecognized AppImage launcher/,
+ );
+ assert.deepEqual(
+ (await readdir(path.join(appDir, "usr/lib"))).sort(),
+ before,
+ );
+ assert.equal(await readFile(path.join(appDir, "AppRun"), "utf8"), launcher);
+ await stat(path.join(appDir, "AppRun.wrapped"));
+ await stat(path.join(appDir, "apprun-hooks/linuxdeploy-plugin-gtk.sh"));
+ });
+}
+
+test(".DirIcon is rewritten to a relative link inside the AppDir", async (t) => {
+ const { root } = await fixture(t);
+ const appDir = path.join(root, "AppDir");
+ await mkdir(appDir);
+ await writeFile(path.join(appDir, "Cap.png"), "icon");
+ await symlink("/build/Cap.AppDir/Cap.png", path.join(appDir, ".DirIcon"));
+ await relativizeDirIcon(appDir);
+ assert.equal(await readlink(path.join(appDir, ".DirIcon")), "Cap.png");
+ await relativizeDirIcon(appDir);
+ assert.equal(await readFile(path.join(appDir, ".DirIcon"), "utf8"), "icon");
+});
+
+test("webview-free finalization hands the pruned AppDir to the output plugin", async (t) => {
+ const { image, plugin } = await fixture(t);
+ let extracted;
+ const run = async (command, args, options) => {
+ if (command === image) {
+ if (args[0] === "--appimage-signature") return { stdout: "" };
+ if (args[0] === "--appimage-offset") {
+ return { stdout: `${runtimeSize}` };
+ }
+ extracted = await webviewAppDir(options.cwd, "squashfs-root");
+ return {};
+ }
+ if (command === "readelf" && args[1] === "--section-headers") {
+ return { stdout: digestSectionHeaders };
+ }
+ if (command === "readelf") return extracted.run(command, args, options);
+ assert.equal(command, plugin);
+ const appDir = args[2];
+ assert.deepEqual((await readdir(appDir)).sort(), [
+ "AppRun",
+ "AppRun.cap-original",
+ "usr",
+ ]);
+ assert.deepEqual(
+ await readFile(path.join(appDir, "AppRun.cap-original")),
+ elf("AppRun.wrapped"),
+ );
+ await assert.rejects(
+ stat(path.join(appDir, "usr/lib/libwebkit2gtk-4.1.so.0")),
+ );
+ await stat(path.join(appDir, "usr/lib/libssl.so.3"));
+ await writeFile(options.env.OUTPUT, finalImage());
+ return {};
+ };
+ const excluded = await finalizeLinuxAppImage(image, {
+ outputPlugin: plugin,
+ unsigned: true,
+ webview: false,
+ env: {},
+ run,
+ });
+ assert.ok(excluded.includes("usr/lib/libwebkit2gtk-4.1.so.0"));
+ assert.ok(excluded.includes("usr/share/glib-2.0"));
+ assert.deepEqual(await readFile(image), finalImage());
+});
diff --git a/scripts/finalize-linux-gpui-packages.mjs b/scripts/finalize-linux-gpui-packages.mjs
new file mode 100644
index 000000000..43536598f
--- /dev/null
+++ b/scripts/finalize-linux-gpui-packages.mjs
@@ -0,0 +1,339 @@
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ rename,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+import { runCommand, signUpdaterArtifact } from "./finalize-linux-appimage.mjs";
+
+export const webviewDebPackages = new Set([
+ "libwebkit2gtk-4.1-0",
+ "libgtk-3-0",
+]);
+export const webviewRpmRequirements = new Set([
+ "libwebkit2gtk-4.1.so.0",
+ "libgtk-3.so.0",
+ "webkit2gtk4.1",
+ "gtk3",
+]);
+
+const payloadCodecs = {
+ gzip: "gzdio",
+ bzip2: "bzdio",
+ xz: "xzdio",
+ lzma: "lzdio",
+ zstd: "zstdio",
+};
+
+export function withoutWebviewDebDependencies(control) {
+ const fields = [];
+ for (const line of control.split("\n")) {
+ if (/^[ \t]/.test(line) && fields.length > 0) fields.at(-1).push(line);
+ else if (line) fields.push([line]);
+ }
+ const lines = fields.flatMap(([first, ...continuation]) => {
+ const match = /^Depends:(.*)$/.exec(first);
+ if (!match) return [first, ...continuation];
+ const depends = [match[1], ...continuation]
+ .join(" ")
+ .split(",")
+ .map((dependency) => dependency.trim())
+ .filter(
+ (dependency) =>
+ dependency &&
+ (dependency.includes("|") ||
+ !webviewDebPackages.has(dependency.split(/[\s(]/, 1)[0])),
+ );
+ return depends.length > 0 ? [`Depends: ${depends.join(", ")}`] : [];
+ });
+ return `${lines.join("\n")}\n`;
+}
+
+export function withoutWebviewRpmRequirements(requirements) {
+ return requirements.filter((requirement) => {
+ const name = requirement.split(/\s/, 1)[0];
+ return (
+ name &&
+ !name.startsWith("rpmlib(") &&
+ !webviewRpmRequirements.has(name.replace(/\(\)\(64bit\)$/, ""))
+ );
+ });
+}
+
+const escapeMacros = (value) => value.replaceAll("%", "%%");
+const permissions = (mode) => (mode & 0o7777).toString(8).padStart(4, "0");
+
+export function rpmFileEntry({ mode, user, group, name }) {
+ if (!name.startsWith("/") || /["\n*?[\]{}\\]/.test(name)) {
+ throw new Error(`Unsupported RPM file name: ${JSON.stringify(name)}`);
+ }
+ const target = `"${escapeMacros(name)}"`;
+ const owner = `${user},${group}`;
+ switch (mode & 0o170000) {
+ case 0o040000:
+ return `%dir %attr(${permissions(mode)},${owner}) ${target}`;
+ case 0o100000:
+ return `%attr(${permissions(mode)},${owner}) ${target}`;
+ case 0o120000:
+ return `%attr(-,${owner}) ${target}`;
+ default:
+ throw new Error(`Unsupported RPM file type for ${name}`);
+ }
+}
+
+export function parseRpmFiles(listing) {
+ return listing
+ .split("\n")
+ .filter(Boolean)
+ .map((line) => {
+ const match = /^(\d+) (\d+) (\S+) (\S+) (\/.*)$/.exec(line);
+ if (!match) throw new Error(`Unrecognized RPM file entry: ${line}`);
+ if (match[2] !== "0") {
+ throw new Error(`Unsupported RPM file attributes for ${match[5]}`);
+ }
+ return {
+ mode: Number(match[1]),
+ user: match[3],
+ group: match[4],
+ name: match[5],
+ };
+ });
+}
+
+const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
+
+export function rpmSpec({
+ name,
+ version,
+ release,
+ summary,
+ license,
+ url,
+ description,
+ requires,
+ files,
+ staging,
+}) {
+ const summaryLine = escapeMacros(summary || name);
+ return [
+ `Name: ${name}`,
+ `Version: ${version}`,
+ `Release: ${release}`,
+ `Summary: ${summaryLine}`,
+ `License: ${escapeMacros(license)}`,
+ ...(url ? [`URL: ${escapeMacros(url)}`] : []),
+ "AutoReqProv: no",
+ ...requires.map((requirement) => `Requires: ${requirement}`),
+ "",
+ "%description",
+ description ? escapeMacros(description) : summaryLine,
+ "",
+ "%install",
+ `cp -a ${escapeMacros(shellQuote(staging))}/. "%{buildroot}/"`,
+ "",
+ "%files",
+ ...files.map(rpmFileEntry),
+ "",
+ ].join("\n");
+}
+
+function requireSigningKey(unsigned, env) {
+ if (!unsigned && !env.TAURI_SIGNING_PRIVATE_KEY) {
+ throw new Error(
+ "TAURI_SIGNING_PRIVATE_KEY is required to sign the final Linux package",
+ );
+ }
+}
+
+async function replaceArtifact(output, destination, { unsigned, env, run }) {
+ if (!unsigned) await signUpdaterArtifact(output, { env, run });
+ await rename(output, destination);
+ if (unsigned) await rm(`${destination}.sig`, { force: true });
+ else await rename(`${output}.sig`, `${destination}.sig`);
+}
+
+export async function finalizeGpuiDeb(
+ filename,
+ { unsigned = false, env = process.env, run = runCommand } = {},
+) {
+ const deb = path.resolve(filename);
+ if (!deb.endsWith(".deb")) throw new Error("Expected a .deb artifact");
+ requireSigningKey(unsigned, env);
+ const work = await mkdtemp(path.join(path.dirname(deb), ".cap-deb-"));
+ try {
+ const root = path.join(work, "root");
+ await run("dpkg-deb", ["--raw-extract", deb, root], { env });
+ const control = path.join(root, "DEBIAN", "control");
+ await writeFile(
+ control,
+ withoutWebviewDebDependencies(await readFile(control, "utf8")),
+ );
+ const output = path.join(work, path.basename(deb));
+ await run(
+ "dpkg-deb",
+ ["--root-owner-group", "-Zxz", "--build", root, output],
+ { env },
+ );
+ await replaceArtifact(output, deb, { unsigned, env, run });
+ } finally {
+ await rm(work, { recursive: true, force: true });
+ }
+}
+
+async function queryRpm(rpm, args, env, run) {
+ const result = await run("rpm", ["--query", "--package", ...args, rpm], {
+ env: { ...env, LC_ALL: "C" },
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "inherit"],
+ });
+ if (typeof result.stdout !== "string") {
+ throw new Error(`Could not query ${rpm}`);
+ }
+ return result.stdout;
+}
+
+const queryTag = async (rpm, tag, env, run) => {
+ const value = (
+ await queryRpm(rpm, ["--queryformat", `%{${tag}}`], env, run)
+ ).trim();
+ return value === "(none)" ? "" : value;
+};
+
+export async function finalizeGpuiRpm(
+ filename,
+ { unsigned = false, env = process.env, run = runCommand } = {},
+) {
+ const rpm = path.resolve(filename);
+ if (!rpm.endsWith(".rpm")) throw new Error("Expected an .rpm artifact");
+ requireSigningKey(unsigned, env);
+ if ((await queryRpm(rpm, ["--scripts"], env, run)).trim()) {
+ throw new Error(`${rpm} has install scripts that cannot be carried over`);
+ }
+ const tags = {};
+ for (const tag of [
+ "NAME",
+ "VERSION",
+ "RELEASE",
+ "ARCH",
+ "SUMMARY",
+ "LICENSE",
+ "URL",
+ "DESCRIPTION",
+ "PAYLOADCOMPRESSOR",
+ "PAYLOADFLAGS",
+ ]) {
+ tags[tag] = await queryTag(rpm, tag, env, run);
+ }
+ const codec = payloadCodecs[tags.PAYLOADCOMPRESSOR];
+ if (!codec) {
+ throw new Error(
+ `Unsupported RPM payload compressor: ${tags.PAYLOADCOMPRESSOR}`,
+ );
+ }
+ const requires = withoutWebviewRpmRequirements(
+ (await queryRpm(rpm, ["--requires"], env, run))
+ .split("\n")
+ .map((line) => line.trim()),
+ );
+ const files = parseRpmFiles(
+ await queryRpm(
+ rpm,
+ [
+ "--queryformat",
+ "[%{FILEMODES} %{FILEFLAGS} %{FILEUSERNAME} %{FILEGROUPNAME} %{FILENAMES}\\n]",
+ ],
+ env,
+ run,
+ ),
+ );
+
+ const work = await mkdtemp(path.join(path.dirname(rpm), ".cap-rpm-"));
+ try {
+ const staging = path.join(work, "staging");
+ const top = path.join(work, "rpmbuild");
+ const output = path.join(work, "output");
+ await mkdir(staging);
+ for (const directory of [
+ "BUILD",
+ "BUILDROOT",
+ "RPMS",
+ "SOURCES",
+ "SPECS",
+ ]) {
+ await mkdir(path.join(top, directory), { recursive: true });
+ }
+ await run("bsdtar", ["-xf", rpm, "-C", staging], { env });
+ const spec = path.join(top, "SPECS", `${tags.NAME}.spec`);
+ await writeFile(
+ spec,
+ rpmSpec({
+ name: tags.NAME,
+ version: tags.VERSION,
+ release: tags.RELEASE,
+ summary: tags.SUMMARY,
+ license: tags.LICENSE,
+ url: tags.URL,
+ description: tags.DESCRIPTION,
+ requires,
+ files,
+ staging,
+ }),
+ );
+ await run(
+ "rpmbuild",
+ [
+ "-bb",
+ spec,
+ "--target",
+ tags.ARCH,
+ "--define",
+ `_topdir ${top}`,
+ "--define",
+ `_rpmdir ${output}`,
+ "--define",
+ `_rpmfilename ${escapeMacros(path.basename(rpm))}`,
+ "--define",
+ `_binary_payload w${tags.PAYLOADFLAGS || "9"}.${codec}`,
+ "--define",
+ "_build_id_links none",
+ "--define",
+ "debug_package %{nil}",
+ "--define",
+ "__arch_install_post %{nil}",
+ "--define",
+ "__os_install_post %{nil}",
+ ],
+ { env: { ...env, LC_ALL: "C" } },
+ );
+ await replaceArtifact(path.join(output, path.basename(rpm)), rpm, {
+ unsigned,
+ env,
+ run,
+ });
+ } finally {
+ await rm(work, { recursive: true, force: true });
+ }
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ const args = process.argv.slice(2);
+ const unsigned = args.includes("--unsigned");
+ const files = args.filter((arg) => arg !== "--unsigned");
+ if (process.platform !== "linux" || files.length === 0) {
+ throw new Error(
+ "Run on Linux: node scripts/finalize-linux-gpui-packages.mjs [--unsigned] <Cap.deb|Cap.rpm>...",
+ );
+ }
+ for (const file of files) {
+ if (file.endsWith(".deb")) await finalizeGpuiDeb(file, { unsigned });
+ else await finalizeGpuiRpm(file, { unsigned });
+ console.log(`Finalized ${file}`);
+ }
+}
diff --git a/scripts/finalize-linux-gpui-packages.test.mjs b/scripts/finalize-linux-gpui-packages.test.mjs
new file mode 100644
index 000000000..cf6f0ee78
--- /dev/null
+++ b/scripts/finalize-linux-gpui-packages.test.mjs
@@ -0,0 +1,347 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { test } from "node:test";
+import {
+ finalizeGpuiDeb,
+ finalizeGpuiRpm,
+ parseRpmFiles,
+ rpmFileEntry,
+ rpmSpec,
+ withoutWebviewDebDependencies,
+ withoutWebviewRpmRequirements,
+} from "./finalize-linux-gpui-packages.mjs";
+
+const available = (command) =>
+ spawnSync("sh", ["-c", `command -v ${command}`]).status === 0;
+
+async function workspace(t) {
+ const root = await mkdtemp(path.join(tmpdir(), "cap-linux-packages-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ return root;
+}
+
+const capture = (command, args) => {
+ const result = spawnSync(command, args, { encoding: "utf8" });
+ assert.equal(result.status, 0, result.stderr);
+ return result.stdout;
+};
+
+test("deb control keeps every dependency except the injected webview stack", () => {
+ const control = [
+ "Package: cap",
+ "Version: 0.6.1",
+ "Depends: libva2, libasound2t64 | libasound2, libwebkit2gtk-4.1-0,",
+ " libgtk-3-0 (>= 3.24), libwebkit2gtk-4.1-0 | libwebkit2gtk-4.0-37, libx11-6",
+ "Description: Cap",
+ " Beautiful screen recordings.",
+ "",
+ ].join("\n");
+ assert.equal(
+ withoutWebviewDebDependencies(control),
+ [
+ "Package: cap",
+ "Version: 0.6.1",
+ "Depends: libva2, libasound2t64 | libasound2, libwebkit2gtk-4.1-0 | libwebkit2gtk-4.0-37, libx11-6",
+ "Description: Cap",
+ " Beautiful screen recordings.",
+ "",
+ ].join("\n"),
+ );
+ assert.equal(
+ withoutWebviewDebDependencies(
+ "Package: cap\nDepends: libgtk-3-0, libwebkit2gtk-4.1-0\n",
+ ),
+ "Package: cap\n",
+ );
+});
+
+test("rpm requirements drop rpmlib markers and the injected webview libraries", () => {
+ assert.deepEqual(
+ withoutWebviewRpmRequirements([
+ "libva",
+ "libwebkit2gtk-4.1.so.0()(64bit)",
+ "libgtk-3.so.0()(64bit)",
+ "libgtk-3.so.0",
+ "webkit2gtk4.1",
+ "openssl-libs >= 3.0",
+ "rpmlib(CompressedFileNames) <= 3.0.4-1",
+ "",
+ ]),
+ ["libva", "openssl-libs >= 3.0"],
+ );
+});
+
+test("rpm file entries preserve type, permissions and ownership", () => {
+ const files = parseRpmFiles(
+ [
+ "33261 0 root root /usr/bin/Cap",
+ "33188 0 root root /usr/lib/Cap/assets/music/lofi 100%.mp3",
+ "16877 0 root root /usr/lib/Cap",
+ "41471 0 root root /usr/lib/cap/libonnxruntime.so",
+ "",
+ ].join("\n"),
+ );
+ assert.deepEqual(files.map(rpmFileEntry), [
+ '%attr(0755,root,root) "/usr/bin/Cap"',
+ '%attr(0644,root,root) "/usr/lib/Cap/assets/music/lofi 100%%.mp3"',
+ '%dir %attr(0755,root,root) "/usr/lib/Cap"',
+ '%attr(-,root,root) "/usr/lib/cap/libonnxruntime.so"',
+ ]);
+ assert.throws(
+ () => parseRpmFiles("33188 1 root root /etc/cap.conf\n"),
+ /Unsupported RPM file attributes/,
+ );
+ for (const name of ["/usr/lib/Cap/*.mp3", '/usr/lib/"quoted"', "relative"]) {
+ assert.throws(
+ () => rpmFileEntry({ mode: 0o100644, user: "root", group: "root", name }),
+ /Unsupported RPM file name/,
+ );
+ }
+ assert.throws(
+ () =>
+ rpmFileEntry({
+ mode: 0o060644,
+ user: "root",
+ group: "root",
+ name: "/dev/cap",
+ }),
+ /Unsupported RPM file type/,
+ );
+});
+
+test("rpm spec disables automatic dependencies and escapes macros", () => {
+ const spec = rpmSpec({
+ name: "cap",
+ version: "0.6.1",
+ release: "1",
+ summary: "100% yours",
+ license: "AGPL-3.0",
+ url: "",
+ description: "",
+ requires: ["libva"],
+ files: [
+ { mode: 0o100755, user: "root", group: "root", name: "/usr/bin/Cap" },
+ ],
+ staging: "/tmp/it's %{here}",
+ });
+ assert.match(spec, /^AutoReqProv: no$/m);
+ assert.match(spec, /^Summary: 100%% yours$/m);
+ assert.match(spec, /^Requires: libva$/m);
+ assert.doesNotMatch(spec, /^URL:/m);
+ assert.match(spec, /%description\n100%% yours\n/);
+ assert.match(
+ spec,
+ /^cp -a '\/tmp\/it'\\''s %%\{here\}'\/\. "%\{buildroot\}\/"$/m,
+ );
+ assert.match(spec, /%files\n%attr\(0755,root,root\) "\/usr\/bin\/Cap"\n$/);
+});
+
+test("deb finalization signs the rebuilt package before replacing it", async (t) => {
+ const root = await workspace(t);
+ const deb = path.join(root, "Cap_0.6.1_amd64.deb");
+ await writeFile(deb, "original");
+ await writeFile(`${deb}.sig`, "original signature");
+ const calls = [];
+ const env = { TAURI_SIGNING_PRIVATE_KEY: "key" };
+ await finalizeGpuiDeb(deb, {
+ env,
+ run: async (command, args, options) => {
+ calls.push([command, ...args.slice(0, 4)]);
+ if (command === "dpkg-deb" && args[0] === "--raw-extract") {
+ await mkdir(path.join(args[2], "DEBIAN"), { recursive: true });
+ await writeFile(
+ path.join(args[2], "DEBIAN/control"),
+ "Package: cap\nDepends: libva2, libwebkit2gtk-4.1-0, libgtk-3-0\n",
+ );
+ } else if (command === "dpkg-deb") {
+ assert.deepEqual(args.slice(0, 3), [
+ "--root-owner-group",
+ "-Zxz",
+ "--build",
+ ]);
+ assert.equal(
+ await readFile(path.join(args[3], "DEBIAN/control"), "utf8"),
+ "Package: cap\nDepends: libva2\n",
+ );
+ await writeFile(args[4], "rebuilt");
+ } else {
+ assert.deepEqual(args.slice(0, 4), ["run", "tauri", "signer", "sign"]);
+ assert.equal(options.env.TAURI_PRIVATE_KEY, "key");
+ assert.equal(await readFile(args[4], "utf8"), "rebuilt");
+ await writeFile(`${args[4]}.sig`, "rebuilt signature");
+ }
+ return {};
+ },
+ });
+ assert.deepEqual(
+ calls.map(([command]) => command),
+ ["dpkg-deb", "dpkg-deb", "bun"],
+ );
+ assert.equal(await readFile(deb, "utf8"), "rebuilt");
+ assert.equal(await readFile(`${deb}.sig`, "utf8"), "rebuilt signature");
+});
+
+test("package finalization requires a signing key unless unsigned", async (t) => {
+ const root = await workspace(t);
+ const deb = path.join(root, "Cap.deb");
+ const rpm = path.join(root, "Cap.rpm");
+ await writeFile(deb, "original");
+ await writeFile(rpm, "original");
+ const run = () => assert.fail("no command should run");
+ await assert.rejects(
+ finalizeGpuiDeb(deb, { env: {}, run }),
+ /TAURI_SIGNING_PRIVATE_KEY/,
+ );
+ await assert.rejects(
+ finalizeGpuiRpm(rpm, { env: {}, run }),
+ /TAURI_SIGNING_PRIVATE_KEY/,
+ );
+ assert.equal(await readFile(deb, "utf8"), "original");
+ assert.equal(await readFile(rpm, "utf8"), "original");
+});
+
+test(
+ "a real deb loses only the webview dependencies",
+ { skip: !available("dpkg-deb") },
+ async (t) => {
+ const root = await workspace(t);
+ const tree = path.join(root, "tree");
+ await mkdir(path.join(tree, "DEBIAN"), { recursive: true });
+ await mkdir(path.join(tree, "usr/bin"), { recursive: true });
+ await writeFile(path.join(tree, "usr/bin/Cap"), "#!/bin/sh\n", {
+ mode: 0o755,
+ });
+ await writeFile(
+ path.join(tree, "DEBIAN/control"),
+ [
+ "Package: cap",
+ "Version: 0.6.1",
+ "Architecture: amd64",
+ "Maintainer: cap",
+ "Depends: libva2, libasound2t64 | libasound2, libwebkit2gtk-4.1-0, libgtk-3-0",
+ "Description: Beautiful screen recordings, owned by you.",
+ "",
+ ].join("\n"),
+ );
+ const deb = path.join(root, "Cap_0.6.1_amd64.deb");
+ capture("dpkg-deb", ["--root-owner-group", "-Zgzip", "--build", tree, deb]);
+ await writeFile(`${deb}.sig`, "stale");
+ await finalizeGpuiDeb(deb, { unsigned: true });
+ assert.equal(
+ capture("dpkg-deb", ["--field", deb, "Depends"]).trim(),
+ "libva2, libasound2t64 | libasound2",
+ );
+ assert.equal(
+ capture("dpkg-deb", ["--field", deb, "Package"]).trim(),
+ "cap",
+ );
+ assert.match(
+ capture("dpkg-deb", ["--contents", deb]),
+ /-rwxr-xr-x root\/root .* \.\/usr\/bin\/Cap/,
+ );
+ assert.match(capture("ar", ["t", deb]), /data\.tar\.xz/);
+ await assert.rejects(readFile(`${deb}.sig`));
+ },
+);
+
+test(
+ "a real rpm keeps its files and metadata without the webview requirements",
+ { skip: !available("rpmbuild") || !available("bsdtar") },
+ async (t) => {
+ const root = await workspace(t);
+ const top = path.join(root, "rpmbuild");
+ for (const directory of [
+ "BUILD",
+ "BUILDROOT",
+ "RPMS",
+ "SOURCES",
+ "SPECS",
+ ]) {
+ await mkdir(path.join(top, directory), { recursive: true });
+ }
+ const spec = path.join(top, "SPECS/cap.spec");
+ await writeFile(
+ spec,
+ [
+ "Name: cap",
+ "Version: 0.6.1",
+ "Release: 1",
+ "Summary: Beautiful screen recordings, owned by you.",
+ "License: AGPL-3.0",
+ "AutoReqProv: no",
+ "Requires: libva",
+ "Requires: libwebkit2gtk-4.1.so.0()(64bit)",
+ "Requires: libgtk-3.so.0()(64bit)",
+ "",
+ "%description",
+ "Beautiful screen recordings, owned by you.",
+ "",
+ "%install",
+ 'mkdir -p "%{buildroot}/usr/bin" "%{buildroot}/usr/lib/Cap"',
+ "printf 'cap' > \"%{buildroot}/usr/bin/Cap\"",
+ "printf 'music' > \"%{buildroot}/usr/lib/Cap/track one.mp3\"",
+ 'ln -s Cap "%{buildroot}/usr/bin/cap"',
+ "",
+ "%files",
+ '%attr(0755,root,root) "/usr/bin/Cap"',
+ '%attr(-,root,root) "/usr/bin/cap"',
+ '%dir %attr(0755,root,root) "/usr/lib/Cap"',
+ '%attr(0644,root,root) "/usr/lib/Cap/track one.mp3"',
+ "",
+ ].join("\n"),
+ );
+ const output = path.join(root, "out");
+ capture("rpmbuild", [
+ "-bb",
+ spec,
+ "--define",
+ `_topdir ${top}`,
+ "--define",
+ `_rpmdir ${output}`,
+ "--define",
+ "_rpmfilename Cap-0.6.1-1.x86_64.rpm",
+ "--define",
+ "_binary_payload w9.zstdio",
+ "--define",
+ "_build_id_links none",
+ "--define",
+ "debug_package %{nil}",
+ "--define",
+ "__arch_install_post %{nil}",
+ "--define",
+ "__os_install_post %{nil}",
+ "--target",
+ "x86_64",
+ ]);
+ const rpm = path.join(output, "Cap-0.6.1-1.x86_64.rpm");
+ const files = (file) =>
+ capture("rpm", [
+ "-qp",
+ "--queryformat",
+ "[%{FILEMODES:octal} %{FILEUSERNAME}:%{FILEGROUPNAME} %{FILENAMES}\\n]",
+ file,
+ ]);
+ const before = files(rpm);
+ await finalizeGpuiRpm(rpm, { unsigned: true });
+ assert.deepEqual(
+ capture("rpm", ["-qpR", rpm])
+ .split("\n")
+ .filter((line) => line && !line.startsWith("rpmlib(")),
+ ["libva"],
+ );
+ assert.equal(files(rpm), before);
+ assert.equal(
+ capture("rpm", [
+ "-qp",
+ "--queryformat",
+ "%{NAME} %{VERSION}-%{RELEASE} %{ARCH} %{PAYLOADCOMPRESSOR} %{SUMMARY}",
+ rpm,
+ ]),
+ "cap 0.6.1-1 x86_64 zstd Beautiful screen recordings, owned by you.",
+ );
+ assert.match(capture("rpm", ["-Kv", rpm]), /Payload SHA256 digest: OK/);
+ },
+);