Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop): support Linux packages and updater targets

Richie McIlroyd249b5290e13
diff --git a/.github/actions/install-desktop-deps/action.yml b/.github/actions/install-desktop-deps/action.yml
index 50f85262e..575f19750 100644
--- a/.github/actions/install-desktop-deps/action.yml
+++ b/.github/actions/install-desktop-deps/action.yml
@@ -34,6 +34,8 @@ runs:
libpipewire-0.3-dev \
libspa-0.2-dev \
libasound2-dev \
+ libasound2-plugins \
+ pulseaudio-utils \
libdbus-1-dev \
libudev-dev \
libx11-dev \
@@ -49,4 +51,8 @@ runs:
libva-dev \
xvfb \
xauth \
+ rpm \
+ cpio \
+ libarchive-tools \
+ zstd \
patchelf
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml
index 1445ee2e5..a26dcec2d 100644
--- a/.github/workflows/desktop-release.yml
+++ b/.github/workflows/desktop-release.yml
@@ -235,7 +235,7 @@ jobs:
console.error("package.version line not found in " + path);
process.exit(1);
}
- toml = toml.replace(re, `version = "${version}"`);
+ toml = toml.replace(re, "version = \"" + version + "\"");
fs.writeFileSync(path, toml);
console.log("Stamped " + path + " with " + version);
'
@@ -340,7 +340,7 @@ jobs:
- name: Build app
working-directory: apps/desktop
- run: ${{ runner.os == 'Linux' && 'CARGO_PROFILE_RELEASE_DEBUG=0 ' || '' }}pnpm build:tauri --target ${{ matrix.settings.target }} --config src-tauri/tauri.prod.conf.json ${{ runner.os == 'Windows' && '--bundles nsis' || runner.os == 'Linux' && '--bundles deb --verbose' || '' }}
+ run: ${{ runner.os == 'Linux' && 'CARGO_PROFILE_RELEASE_DEBUG=0 node ../../scripts/build-linux-packages.mjs' || 'pnpm build:tauri --target' }} ${{ matrix.settings.target }} --config src-tauri/tauri.prod.conf.json ${{ runner.os == 'Windows' && '--bundles nsis' || runner.os == 'Linux' && '--verbose' || '' }}
env:
# https://github.com/tauri-apps/tauri-action/issues/740
CI: false
@@ -426,12 +426,6 @@ jobs:
fi
echo "Frontend build output OK ($FE, $(wc -c < "$FE") bytes)"
- UNSUPPORTED_ARTIFACT="$(find target/${{ matrix.settings.target }}/release/bundle -type f \( -name '*.AppImage' -o -name '*.rpm' \) -print -quit)"
- if [[ -n "$UNSUPPORTED_ARTIFACT" ]]; then
- echo "::error::Unexpected Linux non-deb artifact produced: $UNSUPPORTED_ARTIFACT"
- exit 1
- fi
-
DEB="$(find target/${{ matrix.settings.target }}/release/bundle/deb -name '*.deb' | head -n1)"
if [[ -z "$DEB" ]]; then echo "::error::No .deb produced"; exit 1; fi
if [[ ! -s "$DEB.sig" ]]; then echo "::error::No .deb updater signature produced next to $DEB"; exit 1; fi
@@ -450,7 +444,7 @@ jobs:
done
GPUI_RPATH="$(objdump -p "$WORK/usr/bin/cap-gpui" | awk '/RPATH|RUNPATH/{print $2}')"
- if [[ "$GPUI_RPATH" != *'$ORIGIN/../lib/cap'* ]]; then
+ if [[ "$GPUI_RPATH" != *"\$ORIGIN/../lib/cap"* ]]; then
echo "::error::The bundled GPUI executable cannot resolve shared libraries from /usr/lib/cap"
exit 1
fi
@@ -464,7 +458,6 @@ jobs:
fi
# (2) every FFmpeg soname the binary NEEDs is bundled
- BIN="$WORK/usr/bin/Cap"
NEEDED="$(for executable in "${EXECUTABLES[@]}"; do objdump -p "$executable"; done | awk '/NEEDED/{print $2}' | grep -E '^lib(av|sw|postproc)' | sort -u || true)"
echo "Binary NEEDs FFmpeg sonames:"; echo "${NEEDED:-(none)}"
echo "Bundled FFmpeg libs:"; ls -1 "$WORK/usr/lib/cap" 2>/dev/null || true
@@ -519,6 +512,73 @@ jobs:
fi
echo "Runtime dependency declarations OK"
+ - name: Verify Linux RPM and AppImage contents
+ if: ${{ runner.os == 'Linux' }}
+ shell: bash
+ env:
+ CAP_RELEASE_VERSION: ${{ inputs.version }}
+ run: |
+ set -euo pipefail
+ BUNDLE="${{ github.workspace }}/target/${{ matrix.settings.target }}/release/bundle"
+ RPM="$BUNDLE/rpm/Cap-$CAP_RELEASE_VERSION-1.x86_64.rpm"
+ APPIMAGE="$BUNDLE/appimage/Cap_${CAP_RELEASE_VERSION}_amd64.AppImage"
+ test -s "$APPIMAGE.sig"
+ WORK="$(mktemp -d)"
+ trap 'rm -rf "$WORK"' EXIT
+ mkdir "$WORK/rpm" "$WORK/appimage"
+ (cd "$WORK/appimage" && "$APPIMAGE" --appimage-extract > /dev/null)
+ APPROOT="$WORK/appimage/squashfs-root"
+ ROOTS=("$APPROOT")
+ if [[ "$CAP_RELEASE_VERSION" != *-* ]]; then
+ test -s "$RPM"
+ test "$(rpm -qp --queryformat '%{VERSION}-%{RELEASE}' "$RPM")" = "$CAP_RELEASE_VERSION-1"
+ rpm -Kv "$RPM"
+ bsdtar -xf "$RPM" -C "$WORK/rpm"
+ test "$(cat "$WORK/rpm/usr/lib/cap/package-format")" = rpm
+ ROOTS+=("$WORK/rpm")
+ fi
+ for ROOT in "${ROOTS[@]}"; do
+ for binary in Cap cap-muxer cap-exporter cap-cli cap-gpui; do
+ test -x "$ROOT/usr/bin/$binary"
+ while read -r soname; do
+ test -f "$ROOT/usr/lib/cap/$soname"
+ done < <(objdump -p "$ROOT/usr/bin/$binary" | awk '/NEEDED/{print $2}' | grep -E '^lib(av|sw|postproc)' || true)
+ done
+ done
+ test "$(cat "$APPROOT/usr/lib/cap/package-format")" = appimage
+ test -x "$APPROOT/usr/bin/pactl"
+ test -s "$APPROOT/usr/lib/alsa-lib/libasound_module_pcm_pulse.so"
+ test -s "$APPROOT/usr/lib/cap/alsa-pulse.conf"
+ if [[ -n "$(find "$APPROOT" -name 'libwayland-client.so*' -print -quit)" ]]; then
+ echo "::error::AppImage bundles a Wayland client that can conflict with host Mesa drivers"
+ exit 1
+ fi
+ if [[ -n "$(find "$APPROOT/usr/lib" -maxdepth 1 -name 'libpipewire-0.3.so*' -print -quit)" ]]; then
+ echo "::error::AppImage bundles PipeWire that can conflict with host ALSA plugins"
+ exit 1
+ fi
+
+ - name: Build Arch Linux package
+ id: build_arch
+ if: ${{ runner.os == 'Linux' }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ BUNDLE="target/${{ matrix.settings.target }}/release/bundle"
+ mkdir -p "$BUNDLE/arch"
+ docker run --rm --network none \
+ --env CAP_PACKAGE_UID="$(id -u)" \
+ --volume "${{ github.workspace }}:/source:ro" \
+ --volume "${{ github.workspace }}/$BUNDLE/arch:/output" \
+ archlinux:base-devel@sha256:68bfc3b0d277b08a99101dc9b94aaa03e5ae70cf1b4fb965c03b2b87b915760d \
+ bash -c 'useradd --uid "$CAP_PACKAGE_UID" --create-home cap-package && runuser -u cap-package -- bash /source/scripts/build-linux-arch-package.sh "$1" /output' \
+ bash "/source/$BUNDLE/deb/Cap_${{ inputs.version }}_amd64.deb"
+ PACKAGES=("$BUNDLE/arch/"*.pkg.tar.zst)
+ test "${#PACKAGES[@]}" -eq 1
+ test -s "${PACKAGES[0]}"
+ test "$(bsdtar -xOf "${PACKAGES[0]}" usr/lib/cap/package-format)" = arch
+ echo "package=../../${PACKAGES[0]}" >> "$GITHUB_OUTPUT"
+
- name: Verify Windows installer contents
if: ${{ runner.os == 'Windows' }}
shell: pwsh
@@ -659,6 +719,30 @@ jobs:
command: release upload ${{ env.CN_APPLICATION }} "${{ inputs.version }}" --file "../../target/${{ matrix.settings.target }}/release/bundle/deb/Cap_${{ inputs.version }}_amd64.deb" --signature "../../target/${{ matrix.settings.target }}/release/bundle/deb/Cap_${{ inputs.version }}_amd64.deb.sig" --public-platform deb-x86_64 --update-platform linux-x86_64-deb ${{ env.CN_CHANNEL_FLAG }}
api-key: ${{ secrets.CN_API_KEY }}
+ - name: Upload Linux AppImage asset
+ if: ${{ runner.os == 'Linux' }}
+ uses: crabnebula-dev/cloud-release@v0
+ with:
+ working-directory: apps/desktop
+ command: release upload ${{ env.CN_APPLICATION }} "${{ inputs.version }}" --file "../../target/${{ matrix.settings.target }}/release/bundle/appimage/Cap_${{ inputs.version }}_amd64.AppImage" --signature "../../target/${{ matrix.settings.target }}/release/bundle/appimage/Cap_${{ inputs.version }}_amd64.AppImage.sig" --public-platform appimage-x86_64 --update-platform linux-x86_64-appimage ${{ env.CN_CHANNEL_FLAG }}
+ api-key: ${{ secrets.CN_API_KEY }}
+
+ - name: Upload Linux RPM asset
+ if: ${{ runner.os == 'Linux' && !contains(inputs.version, '-') }}
+ uses: crabnebula-dev/cloud-release@v0
+ with:
+ working-directory: apps/desktop
+ command: release upload ${{ env.CN_APPLICATION }} "${{ inputs.version }}" --file "../../target/${{ matrix.settings.target }}/release/bundle/rpm/Cap-${{ inputs.version }}-1.x86_64.rpm" --public-platform rpm-x86_64 ${{ env.CN_CHANNEL_FLAG }}
+ api-key: ${{ secrets.CN_API_KEY }}
+
+ - name: Upload Arch Linux asset
+ if: ${{ runner.os == 'Linux' }}
+ uses: crabnebula-dev/cloud-release@v0
+ with:
+ working-directory: apps/desktop
+ command: release upload ${{ env.CN_APPLICATION }} "${{ inputs.version }}" --file "${{ steps.build_arch.outputs.package }}" --public-platform pacman-x86_64 ${{ env.CN_CHANNEL_FLAG }}
+ api-key: ${{ secrets.CN_API_KEY }}
+
- uses: matbour/setup-sentry-cli@8ef22a4ff03bcd1ebbcaa3a36a81482ca8e3872e
- name: Upload debug symbols to Sentry
diff --git a/apps/desktop-gpui/src/updates.rs b/apps/desktop-gpui/src/updates.rs
index 69af5f491..d0a5434ce 100644
--- a/apps/desktop-gpui/src/updates.rs
+++ b/apps/desktop-gpui/src/updates.rs
@@ -57,30 +57,36 @@ struct UpdateScheduler {
impl Global for UpdateScheduler {}
-fn updater_target() -> String {
+fn updater_target() -> Result<String, String> {
let arch = if cfg!(target_arch = "aarch64") {
"aarch64"
} else {
"x86_64"
};
- if cfg!(target_os = "macos") {
- format!("darwin-{arch}")
- } else if cfg!(target_os = "linux") {
- format!("linux-{arch}-deb")
- } else {
- format!("windows-{arch}")
+ #[cfg(target_os = "linux")]
+ {
+ cap_utils::linux_package::updater_target(arch)
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ let platform = if cfg!(target_os = "macos") {
+ "darwin"
+ } else {
+ "windows"
+ };
+ Ok(format!("{platform}-{arch}"))
}
}
-fn endpoint(channel: UpdateChannel) -> String {
+fn endpoint(channel: UpdateChannel) -> Result<String, String> {
let url = UPDATE_ENDPOINT
- .replace("{target}", &updater_target())
+ .replace("{target}", &updater_target()?)
.replace("{current_version}", env!("CARGO_PKG_VERSION"));
- match channel {
+ Ok(match channel {
UpdateChannel::Stable => url,
UpdateChannel::Nightly => format!("{url}?channel=nightly"),
- }
+ })
}
async fn remote_version(channel: UpdateChannel) -> Result<Option<Version>, String> {
@@ -88,7 +94,7 @@ async fn remote_version(channel: UpdateChannel) -> Result<Option<Version>, Strin
.timeout(Duration::from_secs(15))
.build()
.map_err(|error| error.to_string())?
- .get(endpoint(channel))
+ .get(endpoint(channel)?)
.send()
.await
.map_err(|error| error.to_string())?;
diff --git a/apps/desktop/scripts/prepare.test.js b/apps/desktop/scripts/prepare.test.js
index 2ad7bfc58..e43e2816d 100644
--- a/apps/desktop/scripts/prepare.test.js
+++ b/apps/desktop/scripts/prepare.test.js
@@ -1,29 +1,21 @@
import { describe, expect, it } from "vitest";
+import { createLinuxBundleConfig } from "../../../scripts/linux-bundle-config.mjs";
import { deepMerge } from "./prepare.js";
describe("Tauri platform release configuration", () => {
it("preserves generated Linux shared-library mappings when adding GPUI", () => {
- const existing = {
- bundle: {
- linux: {
- deb: {
- files: {
- "/usr/lib/cap/libavcodec.so.61":
- "../../../target/native-deps/cap-deb-libs/libavcodec.so.61",
- },
- },
- },
- },
- };
+ const existing = createLinuxBundleConfig(["libavcodec.so.61"]);
const merged = deepMerge(existing, {
bundle: { externalBin: ["binaries/cap-gpui"] },
});
expect(merged.bundle.externalBin).toEqual(["binaries/cap-gpui"]);
- expect(merged.bundle.linux.deb.files).toEqual(
- existing.bundle.linux.deb.files,
- );
+ for (const format of ["deb", "rpm", "appimage"]) {
+ expect(merged.bundle.linux[format]).toEqual(
+ existing.bundle.linux[format],
+ );
+ }
});
it("preserves Windows resource mappings when platform overrides are applied", () => {
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index ab1dc76e7..84fe5ecc0 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -9,6 +9,20 @@ use tracing_subscriber::{Layer, layer::SubscriberExt, util::SubscriberInitExt};
const TOKIO_WORKER_THREAD_STACK_SIZE: usize = 16 * 1024 * 1024;
fn main() {
+ #[cfg(target_os = "linux")]
+ if let Some(config) = cap_utils::linux_package::appimage_alsa_config_path() {
+ // Configure ALSA before starting threads or handing off to a bundled child process.
+ unsafe {
+ std::env::set_var("ALSA_CONFIG_PATH", config);
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ if let Err(error) = cap_cli_install::appimage::dispatch_cli() {
+ eprintln!("{error}");
+ std::process::exit(1);
+ }
+
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
if std::env::var_os("ORT_DYLIB_PATH").is_none()
&& let Some(path) = cap_camera_effects::onnx_runtime_library_path()
diff --git a/apps/desktop/src-tauri/src/updates.rs b/apps/desktop/src-tauri/src/updates.rs
index 6934af905..d2491f8f6 100644
--- a/apps/desktop/src-tauri/src/updates.rs
+++ b/apps/desktop/src-tauri/src/updates.rs
@@ -69,22 +69,25 @@ fn current_channel(app: &AppHandle) -> UpdateChannel {
.unwrap_or_default()
}
-// Mirrors `updaterTarget()` in src/utils/updater.ts; the plugin's built-in
-// target reports "macos"/"linux" while CrabNebula releases are keyed on
-// "darwin-*" / "linux-*-deb".
-fn updater_target() -> String {
+fn updater_target() -> Result<String, String> {
let arch = if cfg!(target_arch = "aarch64") {
"aarch64"
} else {
"x86_64"
};
- if cfg!(target_os = "macos") {
- format!("darwin-{arch}")
- } else if cfg!(target_os = "linux") {
- format!("linux-{arch}-deb")
- } else {
- format!("windows-{arch}")
+ #[cfg(target_os = "linux")]
+ {
+ cap_utils::linux_package::updater_target(arch)
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ let platform = if cfg!(target_os = "macos") {
+ "darwin"
+ } else {
+ "windows"
+ };
+ Ok(format!("{platform}-{arch}"))
}
}
@@ -103,7 +106,7 @@ async fn check_channel(
) -> Result<Option<Update>, String> {
let builder = app
.updater_builder()
- .target(updater_target())
+ .target(updater_target()?)
.endpoints(vec![endpoint(channel)?])
.map_err(|e| e.to_string())?;
diff --git a/crates/cli-install/src/appimage.rs b/crates/cli-install/src/appimage.rs
new file mode 100644
index 000000000..72b230825
--- /dev/null
+++ b/crates/cli-install/src/appimage.rs
@@ -0,0 +1,222 @@
+use std::{
+ ffi::OsString,
+ fs,
+ io::Write,
+ os::unix::{
+ ffi::{OsStrExt, OsStringExt},
+ fs::OpenOptionsExt,
+ },
+ path::{Path, PathBuf},
+};
+
+const SHIM_PREFIX: &[u8] = b"#!/bin/sh\nexec '";
+const SHIM_SUFFIX: &[u8] = b"' --cap-cli \"$@\"\n";
+
+pub fn current_path() -> Option<PathBuf> {
+ #[cfg(target_os = "linux")]
+ {
+ appimage_path(
+ Path::new(&std::env::var_os("APPIMAGE")?),
+ Path::new(&std::env::var_os("APPDIR")?),
+ &std::env::current_exe().ok()?,
+ )
+ }
+ #[cfg(not(target_os = "linux"))]
+ None
+}
+
+#[cfg(any(target_os = "linux", test))]
+fn appimage_path(image: &Path, directory: &Path, executable: &Path) -> Option<PathBuf> {
+ (image.is_absolute() && directory.is_absolute() && executable.starts_with(directory))
+ .then(|| image.to_path_buf())
+}
+
+fn shim_contents(target: &Path) -> Result<Vec<u8>, String> {
+ if !target.is_absolute() {
+ return Err("The AppImage CLI launcher requires an absolute application path".into());
+ }
+
+ let mut contents = SHIM_PREFIX.to_vec();
+ for byte in target.as_os_str().as_bytes() {
+ if *byte == b'\'' {
+ contents.extend_from_slice(b"'\\''");
+ } else {
+ contents.push(*byte);
+ }
+ }
+ contents.extend_from_slice(SHIM_SUFFIX);
+ Ok(contents)
+}
+
+pub fn shim_target(contents: &[u8]) -> Option<PathBuf> {
+ let mut encoded = contents
+ .strip_prefix(SHIM_PREFIX)?
+ .strip_suffix(SHIM_SUFFIX)?;
+ let mut decoded = Vec::with_capacity(encoded.len());
+ while let Some((&byte, remaining)) = encoded.split_first() {
+ if byte == b'\'' {
+ encoded = encoded.strip_prefix(b"'\\''")?;
+ } else {
+ if byte == 0 {
+ return None;
+ }
+ encoded = remaining;
+ }
+ decoded.push(byte);
+ }
+ let target = PathBuf::from(OsString::from_vec(decoded));
+ target.is_absolute().then_some(target)
+}
+
+pub fn write_shim(shim: &Path, target: &Path) -> Result<(), String> {
+ let contents = shim_contents(target)?;
+ let mut file = fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o755)
+ .open(shim)
+ .map_err(|error| format!("Could not create AppImage CLI launcher: {error}"))?;
+ file.write_all(&contents)
+ .map_err(|error| format!("Could not write AppImage CLI launcher: {error}"))
+}
+
+#[cfg(any(target_os = "linux", test))]
+fn cli_command(
+ executable: &Path,
+ original_directory: Option<&Path>,
+) -> Result<std::process::Command, String> {
+ let directory = original_directory
+ .filter(|directory| directory.is_absolute() && directory.is_dir())
+ .ok_or_else(|| "The AppImage original working directory is unavailable".to_string())?;
+ let mut command = std::process::Command::new(executable);
+ command.current_dir(directory);
+ Ok(command)
+}
+
+#[cfg(target_os = "linux")]
+pub fn dispatch_cli() -> Result<(), String> {
+ use std::os::unix::process::CommandExt;
+
+ let mut arguments = std::env::args_os().skip(1);
+ if arguments.next().as_deref() != Some(std::ffi::OsStr::new("--cap-cli")) {
+ return Ok(());
+ }
+ if current_path().is_none() {
+ return Err("The --cap-cli launcher is only available inside a Cap AppImage".into());
+ }
+ let executable = std::env::current_exe().map_err(|error| error.to_string())?;
+ let directory = executable
+ .parent()
+ .ok_or_else(|| "Could not locate the AppImage executable directory".to_string())?;
+ let original_directory = std::env::var_os("OWD").map(PathBuf::from);
+ let error = cli_command(&directory.join("cap-cli"), original_directory.as_deref())?
+ .args(arguments)
+ .exec();
+ Err(format!("Could not launch the bundled Cap CLI: {error}"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn ignores_appimage_environment_from_unrelated_applications() {
+ assert_eq!(
+ appimage_path(
+ Path::new("/home/user/Cap.AppImage"),
+ Path::new("/tmp/.mount_cap"),
+ Path::new("/tmp/.mount_cap/usr/bin/Cap"),
+ ),
+ Some(PathBuf::from("/home/user/Cap.AppImage"))
+ );
+ assert!(
+ appimage_path(
+ Path::new("/home/user/Cap.AppImage"),
+ Path::new("/tmp/.mount_cap"),
+ Path::new("/usr/bin/Cap"),
+ )
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn launcher_round_trips_shell_metacharacters_and_non_unicode_paths() {
+ for raw in [
+ b"/home/user/Cap.AppImage".as_slice(),
+ b"/home/user/Cap's $(example) `command`.AppImage".as_slice(),
+ b"/home/user/Cap-\xff.AppImage".as_slice(),
+ ] {
+ let target = PathBuf::from(OsString::from_vec(raw.to_vec()));
+ assert_eq!(shim_target(&shim_contents(&target).unwrap()), Some(target));
+ }
+ assert!(shim_contents(Path::new("relative.AppImage")).is_err());
+ assert!(shim_target(b"#!/bin/sh\nexec '/tmp/Cap'bad' --cap-cli \"$@\"\n").is_none());
+ assert!(
+ shim_target(b"#!/bin/sh\nexec '/tmp/Cap' --cap-cli \"$@\"\necho extra\n").is_none()
+ );
+ }
+
+ #[test]
+ fn launcher_preserves_arguments_exit_status_and_in_place_updates() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let directory = tempfile::tempdir().unwrap();
+ let image = directory.path().join("Cap's portable.AppImage");
+ let shim = directory.path().join("cap");
+ fs::write(&image, b"#!/bin/sh\nprintf '%s\\n' \"$@\"\nexit 23\n").unwrap();
+ fs::set_permissions(&image, fs::Permissions::from_mode(0o755)).unwrap();
+ write_shim(&shim, &image).unwrap();
+ let output = std::process::Command::new(&shim)
+ .args(["--version", "two words", "$(literal)"])
+ .output()
+ .unwrap();
+ assert_eq!(output.status.code(), Some(23));
+ assert_eq!(
+ output.stdout,
+ b"--cap-cli\n--version\ntwo words\n$(literal)\n"
+ );
+ fs::write(&image, b"#!/bin/sh\nprintf replacement\n").unwrap();
+ let output = std::process::Command::new(&shim).output().unwrap();
+ assert!(output.status.success());
+ assert_eq!(output.stdout, b"replacement");
+ assert!(write_shim(&shim, &image).is_err());
+ }
+
+ #[test]
+ fn cli_launch_resolves_relative_paths_from_the_original_directory() {
+ let parent_directory = std::env::current_dir().unwrap();
+ let root = tempfile::tempdir().unwrap();
+ for name in [b"caller's directory".as_slice(), b"caller-\xff".as_slice()] {
+ let directory = root.path().join(OsString::from_vec(name.to_vec()));
+ fs::create_dir(&directory).unwrap();
+ fs::write(directory.join("relative-project.txt"), b"caller project").unwrap();
+ let mut command = cli_command(Path::new("/bin/sh"), Some(&directory)).unwrap();
+ assert_eq!(command.get_current_dir(), Some(directory.as_path()));
+ let output = command
+ .args(["-c", "cat relative-project.txt"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_eq!(output.stdout, b"caller project");
+ }
+ assert_eq!(std::env::current_dir().unwrap(), parent_directory);
+ }
+
+ #[test]
+ fn cli_launch_never_substitutes_a_different_directory_for_invalid_owd() {
+ let root = tempfile::tempdir().unwrap();
+ let executable = Path::new("/bin/sh");
+ assert!(cli_command(executable, Some(Path::new("relative"))).is_err());
+ assert!(cli_command(executable, Some(&root.path().join("missing"))).is_err());
+ let file = root.path().join("file");
+ fs::write(&file, b"not a directory").unwrap();
+ assert!(cli_command(executable, Some(&file)).is_err());
+ assert!(cli_command(executable, None).is_err());
+
+ let directory = root.path().join("removed-before-launch");
+ fs::create_dir(&directory).unwrap();
+ let mut command = cli_command(executable, Some(&directory)).unwrap();
+ fs::remove_dir(&directory).unwrap();
+ assert!(command.output().is_err());
+ }
+}
diff --git a/crates/cli-install/src/lib.rs b/crates/cli-install/src/lib.rs
index 3b86484c1..08a4ccce0 100644
--- a/crates/cli-install/src/lib.rs
+++ b/crates/cli-install/src/lib.rs
@@ -13,6 +13,9 @@ use std::{
path::{Path, PathBuf},
};
+#[cfg(unix)]
+pub mod appimage;
+
const CAP_DIR_NAME: &str = ".cap";
const BIN_DIR_NAME: &str = "bin";
const CLI_BINARY_STEM: &str = "cap-cli";
@@ -83,6 +86,11 @@ fn shim_path() -> Result<PathBuf, String> {
}
fn target_path() -> Result<PathBuf, String> {
+ #[cfg(target_os = "linux")]
+ if let Some(path) = appimage::current_path() {
+ return Ok(path);
+ }
+
let exe = env::current_exe().map_err(|e| format!("Could not locate Cap executable: {e}"))?;
// When `cap` runs through the installed shim (a symlink), macOS `current_exe()` returns the
// symlink path; resolve it to the real binary so the sibling `cap-cli` resolves to the bundled
@@ -215,14 +223,20 @@ fn shim_points_to(shim_path: &Path, target_path: &Path) -> Result<bool, String>
// current_exe spells differently; compare the resolved paths too so a Cap-managed shim is still
// recognized by status/install/uninstall.
Ok(link) => Ok(link == target_path || same_file(&link, target_path)),
- // A non-symlink regular file (read_link → InvalidInput) or a missing path is simply not a
- // Cap-managed shim — let the caller report that as a conflict rather than surfacing a raw error.
- Err(err)
- if matches!(
- err.kind(),
- std::io::ErrorKind::NotFound | std::io::ErrorKind::InvalidInput
- ) =>
- {
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
+ Err(err) if err.kind() == std::io::ErrorKind::InvalidInput => {
+ #[cfg(target_os = "linux")]
+ {
+ if !shim_path.is_file() {
+ return Ok(false);
+ }
+ let contents = fs::read(shim_path)
+ .map_err(|error| format!("Could not read AppImage CLI launcher: {error}"))?;
+ Ok(appimage::shim_target(&contents)
+ .is_some_and(|target| target == target_path || same_file(&target, target_path)))
+ }
+
+ #[cfg(not(target_os = "linux"))]
Ok(false)
}
Err(err) => Err(format!("Could not read CLI shim: {err}")),
@@ -257,6 +271,17 @@ fn shim_is_cap_managed(shim_path: &Path) -> bool {
Ok(link) => link
.file_name()
.is_some_and(cli_binary_file_name_is_cap_managed),
+ Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => {
+ #[cfg(target_os = "linux")]
+ return shim_path.is_file()
+ && fs::read(shim_path)
+ .ok()
+ .and_then(|contents| appimage::shim_target(&contents))
+ .is_some();
+
+ #[cfg(not(target_os = "linux"))]
+ false
+ }
Err(_) => false,
}
}
@@ -438,6 +463,11 @@ pub fn status() -> Result<CliInstallStatus, String> {
#[cfg(unix)]
fn write_shim(shim_path: &Path, target_path: &Path) -> Result<(), String> {
+ #[cfg(target_os = "linux")]
+ if appimage::current_path().as_deref() == Some(target_path) {
+ return appimage::write_shim(shim_path, target_path);
+ }
+
std::os::unix::fs::symlink(target_path, shim_path)
.map_err(|e| format!("Could not create CLI symlink: {e}"))
}
@@ -628,17 +658,53 @@ pub fn uninstall() -> Result<CliInstallStatus, String> {
let shim_path = shim_path()?;
let target_path = target_path()?;
- if shim_points_to(&shim_path, &target_path)? {
- fs::remove_file(&shim_path).map_err(|e| format!("Could not remove CLI shim: {e}"))?;
- }
-
+ uninstall_shim(&shim_path, &target_path)?;
status()
}
+fn uninstall_shim(shim: &Path, target: &Path) -> Result<(), String> {
+ let removable = shim_points_to(shim, target)?;
+ #[cfg(target_os = "linux")]
+ let removable = removable
+ || (fs::symlink_metadata(shim).is_ok_and(|metadata| metadata.is_file())
+ && fs::read(shim)
+ .ok()
+ .and_then(|contents| appimage::shim_target(&contents))
+ .is_some_and(|previous| !path_is_present(&previous)));
+
+ if removable {
+ fs::remove_file(shim).map_err(|error| format!("Could not remove CLI shim: {error}"))?;
+ }
+ Ok(())
+}
+
#[cfg(all(test, unix))]
mod tests {
use super::*;
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn uninstall_handles_moved_appimages_without_removing_other_installations() {
+ let directory = tempfile::tempdir().unwrap();
+ let shim = directory.path().join("cap");
+ let previous = directory.path().join("previous.AppImage");
+ let current = directory.path().join("current.AppImage");
+ appimage::write_shim(&shim, &previous).unwrap();
+ uninstall_shim(&shim, &current).unwrap();
+ assert!(!path_is_present(&shim));
+
+ fs::write(&previous, b"another installed AppImage").unwrap();
+ appimage::write_shim(&shim, &previous).unwrap();
+ uninstall_shim(&shim, &current).unwrap();
+ assert!(path_is_present(&shim));
+ uninstall_shim(&shim, &previous).unwrap();
+ assert!(!path_is_present(&shim));
+
+ fs::write(&shim, b"#!/bin/sh\necho user script\n").unwrap();
+ uninstall_shim(&shim, &current).unwrap();
+ assert_eq!(fs::read(&shim).unwrap(), b"#!/bin/sh\necho user script\n");
+ }
+
#[test]
fn shell_profile_selection() {
let home = Path::new("/home/u");
@@ -699,6 +765,25 @@ mod tests {
// A missing path is not Cap-managed.
fs::remove_file(&shim).unwrap();
assert!(!shim_is_cap_managed(&shim));
+
+ fs::create_dir(&shim).unwrap();
+ let target = Path::new("/home/u/Cap.AppImage");
+ assert!(!shim_is_cap_managed(&shim));
+ assert!(!shim_points_to(&shim, target).unwrap());
+ uninstall_shim(&shim, target).unwrap();
+ assert!(shim.is_dir());
+ }
+
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn appimage_shims_remain_managed_when_the_application_moves() {
+ let directory = tempfile::tempdir().unwrap();
+ let shim = directory.path().join(SHIM_NAME);
+ let target = Path::new("/home/u/Cap.AppImage");
+ appimage::write_shim(&shim, target).unwrap();
+ assert!(shim_is_cap_managed(&shim));
+ assert!(shim_points_to(&shim, target).unwrap());
+ assert!(!shim_points_to(&shim, Path::new("/home/u/New.Cap.AppImage")).unwrap());
}
#[test]
diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs
index c5210822b..7b428feea 100644
--- a/crates/utils/src/lib.rs
+++ b/crates/utils/src/lib.rs
@@ -10,6 +10,8 @@ use aho_corasick::{AhoCorasickBuilder, MatchKind};
use tracing::Instrument;
pub mod disk_space;
+#[cfg(any(target_os = "linux", test))]
+pub mod linux_package;
#[cfg(target_os = "macos")]
pub mod macos_qos;
@@ -45,10 +47,13 @@ pub fn ensure_dir(path: &PathBuf) -> Result<PathBuf, std::io::Error> {
/// # Example
///
/// ```rust
+/// use cap_utils::ensure_unique_filename;
+/// let recordings_dir = std::path::Path::new("recordings");
/// let unique_name = ensure_unique_filename("My Recording.cap", &recordings_dir,);
/// // If "My Recording.cap" exists, returns "My Recording (1).cap"
/// // If that exists too, returns "My Recording (2).cap", etc.
///
+/// let documents_dir = std::path::Path::new("documents");
/// let unique_name = ensure_unique_filename("document.pdf", &documents_dir);
/// // If "document.pdf" exists, returns "document (1).pdf"
/// ```
@@ -161,7 +166,7 @@ pub fn ensure_unique_filename_with_attempts(
///
/// ## Examples
///
-/// ```
+/// ```text
/// // Basic formats
/// YYYY-MM-DD HH:mm → %Y-%m-%d %H:%M
/// // Output: "2025-01-15 14:30"
diff --git a/crates/utils/src/linux_package.rs b/crates/utils/src/linux_package.rs
new file mode 100644
index 000000000..0a2acf4f0
--- /dev/null
+++ b/crates/utils/src/linux_package.rs
@@ -0,0 +1,210 @@
+use std::{
+ env,
+ ffi::{OsStr, OsString},
+ fs,
+ path::{Path, PathBuf},
+};
+
+fn append_alsa_config(config: &Path, existing: Option<&OsStr>) -> Option<OsString> {
+ let config_bytes = config.as_os_str().as_encoded_bytes();
+ if config_bytes.contains(&b':') {
+ return None;
+ }
+ let existing = existing
+ .filter(|value| !value.is_empty())
+ .unwrap_or(OsStr::new("/usr/share/alsa/alsa.conf"));
+ if existing
+ .as_encoded_bytes()
+ .split(|byte| *byte == b':')
+ .any(|path| path == config_bytes)
+ {
+ return None;
+ }
+ let mut paths = existing.to_os_string();
+ if !paths.is_empty() {
+ paths.push(":");
+ }
+ paths.push(config);
+ Some(paths)
+}
+
+pub fn appimage_alsa_config_path() -> Option<OsString> {
+ let executable = env::current_exe().ok()?;
+ let appimage = env::var_os("APPIMAGE").map(PathBuf::from);
+ let appdir = env::var_os("APPDIR").map(PathBuf::from)?;
+ if package_format(&executable, None, appimage.as_deref(), Some(&appdir), None)
+ != PackageFormat::AppImage
+ {
+ return None;
+ }
+ let config = appdir.join("usr/lib/cap/alsa-pulse.conf");
+ let plugin = appdir.join("usr/lib/alsa-lib/libasound_module_pcm_pulse.so");
+ if !config.is_file() || !plugin.is_file() {
+ return None;
+ }
+ append_alsa_config(&config, env::var_os("ALSA_CONFIG_PATH").as_deref())
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum PackageFormat {
+ Deb,
+ AppImage,
+ ExtractedAppImage,
+ Rpm,
+ Arch,
+ Unknown,
+}
+
+fn package_format(
+ executable: &Path,
+ marker: Option<&str>,
+ appimage: Option<&Path>,
+ appdir: Option<&Path>,
+ debian_files: Option<&str>,
+) -> PackageFormat {
+ if appimage.is_some_and(Path::is_absolute)
+ && appdir
+ .is_some_and(|directory| directory.is_absolute() && executable.starts_with(directory))
+ {
+ return PackageFormat::AppImage;
+ }
+
+ match marker.map(str::trim) {
+ Some("deb") => PackageFormat::Deb,
+ Some("rpm") => PackageFormat::Rpm,
+ Some("arch") => PackageFormat::Arch,
+ Some("appimage") => PackageFormat::ExtractedAppImage,
+ None if debian_files
+ .is_some_and(|files| files.lines().any(|file| Path::new(file) == executable)) =>
+ {
+ PackageFormat::Deb
+ }
+ _ => PackageFormat::Unknown,
+ }
+}
+
+fn target_for(format: PackageFormat, arch: &str) -> Result<String, String> {
+ let suffix = match format {
+ PackageFormat::Deb => "deb",
+ PackageFormat::AppImage => "appimage",
+ PackageFormat::Rpm => {
+ return Err("Update Cap through your RPM package manager or install the latest RPM from cap.so/download.".into());
+ }
+ PackageFormat::Arch => {
+ return Err("Update Cap through your Arch package manager or install the latest Arch package from cap.so/download.".into());
+ }
+ PackageFormat::ExtractedAppImage => {
+ return Err("Launch the original Cap AppImage to use automatic updates. An extracted AppImage cannot update itself.".into());
+ }
+ PackageFormat::Unknown => {
+ return Err("Automatic updates are unavailable for this Cap installation. Update it through your package manager or cap.so/download.".into());
+ }
+ };
+ Ok(format!("linux-{arch}-{suffix}"))
+}
+
+pub fn updater_target(arch: &str) -> Result<String, String> {
+ let executable = env::current_exe().map_err(|error| error.to_string())?;
+ let marker = executable
+ .parent()
+ .and_then(Path::parent)
+ .and_then(|directory| fs::read_to_string(directory.join("lib/cap/package-format")).ok());
+ let appimage = env::var_os("APPIMAGE").map(PathBuf::from);
+ let appdir = env::var_os("APPDIR").map(PathBuf::from);
+ let debian_files = fs::read_to_string("/var/lib/dpkg/info/cap.list").ok();
+ target_for(
+ package_format(
+ &executable,
+ marker.as_deref(),
+ appimage.as_deref(),
+ appdir.as_deref(),
+ debian_files.as_deref(),
+ ),
+ arch,
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn appimage_audio_preserves_host_and_custom_configuration() {
+ let config = Path::new("/tmp/.mount_cap/usr/lib/cap/alsa-pulse.conf");
+ for existing in [None, Some(OsStr::new(""))] {
+ assert_eq!(
+ append_alsa_config(config, existing).unwrap(),
+ OsString::from(
+ "/usr/share/alsa/alsa.conf:/tmp/.mount_cap/usr/lib/cap/alsa-pulse.conf"
+ )
+ );
+ }
+ let current = OsStr::new("/home/user/audio.conf:/home/user/devices.conf");
+ let combined = append_alsa_config(config, Some(current)).unwrap();
+ assert_eq!(
+ combined,
+ OsString::from(
+ "/home/user/audio.conf:/home/user/devices.conf:/tmp/.mount_cap/usr/lib/cap/alsa-pulse.conf"
+ )
+ );
+ assert!(append_alsa_config(config, Some(&combined)).is_none());
+ assert!(append_alsa_config(Path::new("/tmp/invalid:path/alsa.conf"), None).is_none());
+ }
+
+ #[test]
+ fn appimage_updates_require_the_current_executable_inside_its_appdir() {
+ let image = Some(Path::new("/home/user/Cap.AppImage"));
+ let directory = Some(Path::new("/tmp/.mount_cap"));
+ let format = package_format(
+ Path::new("/tmp/.mount_cap/usr/bin/Cap"),
+ Some("appimage\n"),
+ image,
+ directory,
+ None,
+ );
+ assert_eq!(
+ target_for(format, "x86_64").unwrap(),
+ "linux-x86_64-appimage"
+ );
+ let format = package_format(
+ Path::new("/usr/bin/Cap"),
+ Some("rpm\n"),
+ image,
+ directory,
+ None,
+ );
+ assert_eq!(format, PackageFormat::Rpm);
+ assert!(target_for(format, "x86_64").is_err());
+ }
+
+ #[test]
+ fn packages_never_select_an_incompatible_updater() {
+ for (marker, expected) in [
+ ("rpm", PackageFormat::Rpm),
+ ("arch", PackageFormat::Arch),
+ ("appimage", PackageFormat::ExtractedAppImage),
+ ("other", PackageFormat::Unknown),
+ ] {
+ let format = package_format(Path::new("/usr/bin/Cap"), Some(marker), None, None, None);
+ assert_eq!(format, expected);
+ assert!(target_for(format, "aarch64").is_err());
+ }
+ let format = package_format(Path::new("/usr/bin/Cap"), Some("deb\n"), None, None, None);
+ assert_eq!(target_for(format, "aarch64").unwrap(), "linux-aarch64-deb");
+ }
+
+ #[test]
+ fn legacy_debian_packages_require_executable_ownership() {
+ let files = Some("/usr/bin/Cap\n/usr/bin/cap-gpui\n");
+ for executable in ["/usr/bin/Cap", "/usr/bin/cap-gpui"] {
+ assert_eq!(
+ package_format(Path::new(executable), None, None, None, files),
+ PackageFormat::Deb
+ );
+ }
+ assert_eq!(
+ package_format(Path::new("/tmp/Cap"), None, None, None, files),
+ PackageFormat::Unknown
+ );
+ }
+}
diff --git a/packaging/linux/README.md b/packaging/linux/README.md
new file mode 100644
index 000000000..760188080
--- /dev/null
+++ b/packaging/linux/README.md
@@ -0,0 +1,54 @@
+# Linux packages
+
+Build release packages on Linux with the desktop dependencies installed:
+
+```sh
+pnpm with-env node scripts/build-linux-packages.mjs x86_64-unknown-linux-gnu --config src-tauri/tauri.prod.conf.json
+```
+
+The wrapper builds the CLI, GPUI, Tauri, DEB, RPM, and AppImage artifacts. It requires `TAURI_SIGNING_PRIVATE_KEY` and optionally `TAURI_SIGNING_PRIVATE_KEY_PASSWORD`. Release CI supplies these through secrets; use a disposable key and matching updater public-key configuration for sandbox tests.
+
+Prerelease versions containing a hyphen build DEB and AppImage but skip RPM, whose version format does not accept that character. Stable releases build all three formats. Arch packages can be built from either stable or prerelease DEBs.
+
+## AppImage finalization
+
+Use the Linux wrapper for distributable AppImages. The generic `build:tauri` command produces an intermediate AppImage that still needs finalization.
+
+Bundled Wayland and PipeWire libraries can conflict with newer host Mesa drivers and ALSA plugins. The finalizer extracts the produced AppImage, removes `libwayland-client.so*` and the `usr/lib/libpipewire-0.3.so*` copy, and rebuilds it with Tauri's cached `linuxdeploy-plugin-appimage.AppImage`. It preserves other libraries, the existing AppRun, and GTK/GStreamer hooks. It supplies the input image's runtime to the output plugin through `LDAI_RUNTIME_FILE`, avoiding a new runtime download during finalization. It checks every runtime byte except the 16-byte payload checksum that appimagetool regenerates, locating that section with `readelf` from binutils. It does not replace cached packaging tools and fails if the output plugin is unavailable. Inputs must use Tauri's external updater signature; embedded GPG signatures are not supported.
+
+The original launcher is retained as `AppRun.cap-original`. A small wrapper captures the caller's working directory before AppRun changes it, for both normal and `--appimage-extract-and-run` launches. CLI dispatch restores that directory so relative project and output paths work. An unavailable original directory produces an error instead of resolving paths inside the mounted image. GUI working-directory behavior is unchanged.
+
+The finalizer signs the rebuilt bytes and replaces the artifact and its adjacent `.sig` only after packaging and signing succeed. With `createUpdaterArtifacts: true`, the updater consumes this `.AppImage` and `.AppImage.sig` pair, not a tar archive. Do not upload the signature from the intermediate image.
+
+For an explicitly unsigned local test artifact:
+
+```sh
+node scripts/finalize-linux-appimage.mjs --unsigned target/x86_64-unknown-linux-gnu/release/bundle/appimage/Cap_0.6.0_amd64.AppImage
+```
+
+This removes any old signature. The host must provide its Wayland client and PipeWire libraries alongside its graphics drivers and audio plugins.
+
+## Arch Linux and Omarchy
+
+Run the package builder as an ordinary user in an Arch environment with `makepkg` and `bsdtar`:
+
+```sh
+bash scripts/build-linux-arch-package.sh Cap_0.6.0_amd64.deb ./arch-packages
+sudo pacman -U ./arch-packages/cap-bin-0.6.0-1-x86_64.pkg.tar.zst
+```
+
+The builder reuses the exact DEB payload, changes the package-format marker, and declares Arch dependencies. It does not strip or rebuild the executables. Release CI uses a pinned Arch container without network access during packaging.
+
+On Omarchy, screen capture uses the installed Hyprland desktop portal and PipeWire. Package installation alone does not verify recording, playback, export, or device access; these require tests in the target desktop session.
+
+## CLI camera in Instant mode
+
+On Linux, `cap record start --mode instant --camera DEVICE` composites the camera directly into the recorded screen or window. The CLI uses an unmirrored square at the bottom right, sized to 30% of the shorter screen edge with a 2% margin. Camera images are center-cropped without stretching. If camera frames stop arriving, screen recording continues without a stale camera image.
+
+This CLI default does not change desktop camera-window settings or Studio's separate, editable camera track.
+
+## Updates and verification
+
+DEB and AppImage installations use separate updater targets. RPM and Arch installations direct users to update through their package manager or install the latest package, avoiding an incompatible DEB update.
+
+The release workflow checks bundled executables, native FFmpeg libraries, package markers, AppImage audio configuration, RPM version metadata, and final updater signatures. Runtime validation must additionally cover GPUI/Tauri switching, capture permissions, screen/window/area selection, camera and audio, playback, export, and CLI behavior on each supported desktop.
diff --git a/packaging/linux/alsa-pulse.conf b/packaging/linux/alsa-pulse.conf
new file mode 100644
index 000000000..f458469a5
--- /dev/null
+++ b/packaging/linux/alsa-pulse.conf
@@ -0,0 +1,16 @@
+pcm_type.pulse {
+ lib {
+ @func concat
+ strings [
+ { @func getenv vars [ APPDIR ] default "" }
+ "/usr/lib/alsa-lib/libasound_module_pcm_pulse.so"
+ ]
+ }
+}
+
+pcm.pulse {
+ type pulse
+ hint {
+ description "PulseAudio Sound Server"
+ }
+}
diff --git a/packaging/linux/appimage b/packaging/linux/appimage
new file mode 100644
index 000000000..3bd8135f5
--- /dev/null
+++ b/packaging/linux/appimage
@@ -0,0 +1 @@
+appimage
diff --git a/packaging/linux/deb b/packaging/linux/deb
new file mode 100644
index 000000000..e619f9ccd
--- /dev/null
+++ b/packaging/linux/deb
@@ -0,0 +1 @@
+deb
diff --git a/packaging/linux/rpm b/packaging/linux/rpm
new file mode 100644
index 000000000..916f55df7
--- /dev/null
+++ b/packaging/linux/rpm
@@ -0,0 +1 @@
+rpm
diff --git a/scripts/build-linux-arch-package.sh b/scripts/build-linux-arch-package.sh
new file mode 100644
index 000000000..806c0df16
--- /dev/null
+++ b/scripts/build-linux-arch-package.sh
@@ -0,0 +1,71 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+if [[ $# -ne 2 ]]; then
+ printf 'Usage: %s <Cap.deb> <output-directory>\n' "$0" >&2
+ exit 1
+fi
+
+if [[ $(id -u) -eq 0 ]]; then
+ printf 'Build the Arch package as an ordinary user, as required by makepkg.\n' >&2
+ exit 1
+fi
+
+deb="$(realpath "$1")"
+mkdir -p "$2"
+output="$(realpath "$2")"
+work="$(mktemp -d)"
+trap 'rm -rf "$work"' EXIT
+
+control_member="$(bsdtar -tf "$deb" | awk '/^control\.tar(\.|$)/ { print; exit }')"
+data_member="$(bsdtar -tf "$deb" | awk '/^data\.tar(\.|$)/ { print; exit }')"
+if [[ ! "$control_member" =~ ^control\.tar(\.(gz|xz|zst|bz2|lzma))?$ || ! "$data_member" =~ ^data\.tar(\.(gz|xz|zst|bz2|lzma))?$ ]]; then
+ printf 'The input is not a Debian package with control and data archives.\n' >&2
+ exit 1
+fi
+
+mkdir "$work/control"
+bsdtar -xOf "$deb" "$control_member" | bsdtar -xf - -C "$work/control"
+version="$(awk '/^Version:/ { print $2 }' "$work/control/control")"
+architecture="$(awk '/^Architecture:/ { print $2 }' "$work/control/control")"
+if [[ ! "$version" =~ ^[0-9][0-9A-Za-z.+~_-]*$ ]]; then
+ printf 'Unsupported package version: %s\n' "$version" >&2
+ exit 1
+fi
+
+case "$architecture" in
+ amd64) architecture=x86_64 ;;
+ arm64) architecture=aarch64 ;;
+ *) printf 'Unsupported package architecture: %s\n' "$architecture" >&2; exit 1 ;;
+esac
+
+cp "$deb" "$work/Cap.deb"
+checksum="$(sha256sum "$work/Cap.deb" | cut -d ' ' -f 1)"
+cat > "$work/PKGBUILD" <<EOF
+pkgname=cap-bin
+pkgver=${version//-/_}
+pkgrel=1
+pkgdesc="Screen recording with Studio, Instant, and screenshot modes"
+arch=("$architecture")
+url="https://cap.so"
+license=("AGPL-3.0-only")
+depends=("webkit2gtk-4.1" "gtk3" "libappindicator-gtk3" "libva" "libpulse" "libpipewire" "alsa-lib" "alsa-plugins" "libxkbcommon" "libxkbcommon-x11" "openssl" "vulkan-icd-loader" "xdg-desktop-portal" "xdg-utils" "gst-plugins-good" "gst-libav")
+optdepends=("xdg-desktop-portal-hyprland: screen capture on Hyprland and Omarchy" "vulkan-driver: hardware accelerated recording and editing")
+provides=("cap=\$pkgver")
+conflicts=("cap")
+options=("!strip" "!debug")
+source=("Cap.deb")
+noextract=("Cap.deb")
+sha256sums=("$checksum")
+
+package() {
+ bsdtar -xOf "\$srcdir/Cap.deb" "$data_member" | bsdtar -xf - -C "\$pkgdir"
+ for binary in Cap cap-gpui cap-cli cap-exporter cap-muxer; do
+ test -x "\$pkgdir/usr/bin/\$binary"
+ done
+ printf 'arch\n' > "\$pkgdir/usr/lib/cap/package-format"
+}
+EOF
+
+cd "$work"
+PKGDEST="$output" makepkg --nodeps --noconfirm
diff --git a/scripts/build-linux-packages.mjs b/scripts/build-linux-packages.mjs
new file mode 100644
index 000000000..a841655fa
--- /dev/null
+++ b/scripts/build-linux-packages.mjs
@@ -0,0 +1,68 @@
+import { readdir } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import {
+ finalizeLinuxAppImage,
+ runCommand,
+} from "./finalize-linux-appimage.mjs";
+import { supportedLinuxBundles } from "./linux-bundle-config.mjs";
+
+const [target, ...args] = process.argv.slice(2);
+if (
+ process.platform !== "linux" ||
+ !/^\w+-unknown-linux-gnu$/.test(target ?? "") ||
+ args.some((arg) => /^--(?:target|bundles|debug|profile)(?:=|$)/.test(arg))
+) {
+ throw new Error(
+ "Run on Linux: node scripts/build-linux-packages.mjs <target> [tauri build options]",
+ );
+}
+if (!process.env.TAURI_SIGNING_PRIVATE_KEY) {
+ throw new Error(
+ "TAURI_SIGNING_PRIVATE_KEY is required for Linux release packages",
+ );
+}
+
+const desktopDirectory = fileURLToPath(
+ new URL("../apps/desktop/", import.meta.url),
+);
+const metadata = runCommand(
+ "cargo",
+ ["metadata", "--no-deps", "--format-version", "1"],
+ {
+ cwd: path.join(desktopDirectory, "src-tauri"),
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "inherit"],
+ },
+);
+const workspace = JSON.parse(metadata.stdout);
+const targetDirectory = workspace.target_directory;
+const version = workspace.packages.find(
+ (pkg) => pkg.name === "cap-desktop",
+)?.version;
+if (!version) throw new Error("Desktop version is missing from Cargo metadata");
+const bundles = supportedLinuxBundles(version).join(",");
+
+runCommand(
+ "pnpm",
+ ["build:tauri", "--target", target, "--bundles", bundles, ...args],
+ {
+ cwd: desktopDirectory,
+ env: { ...process.env, RUST_TARGET_TRIPLE: target },
+ },
+);
+
+const bundleDirectory = path.join(
+ targetDirectory,
+ target,
+ "release/bundle/appimage",
+);
+const images = (await readdir(bundleDirectory)).filter((file) =>
+ file.endsWith(".AppImage"),
+);
+if (images.length !== 1) {
+ throw new Error(
+ `Expected one AppImage in ${bundleDirectory}, found ${images.length}`,
+ );
+}
+await finalizeLinuxAppImage(path.join(bundleDirectory, images[0]));
diff --git a/scripts/finalize-linux-appimage.mjs b/scripts/finalize-linux-appimage.mjs
new file mode 100644
index 000000000..f0e3eabe0
--- /dev/null
+++ b/scripts/finalize-linux-appimage.mjs
@@ -0,0 +1,309 @@
+import { spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { constants, createReadStream, createWriteStream } from "node:fs";
+import {
+ access,
+ chmod,
+ copyFile,
+ mkdtemp,
+ readdir,
+ readFile,
+ rename,
+ rm,
+ stat,
+ writeFile,
+} from "node:fs/promises";
+import { homedir } from "node:os";
+import path from "node:path";
+import { pipeline } from "node:stream/promises";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const desktopDirectory = fileURLToPath(
+ new URL("../apps/desktop/", import.meta.url),
+);
+
+// The sentinel preserves directory names ending in newlines through shell substitution.
+const appRunWrapper = `#!/bin/sh
+unset OWD
+if cap_original_directory="$(pwd -P && printf '.')"; then
+ OWD="\${cap_original_directory%?}"
+ OWD="\${OWD%?}"
+ export OWD
+fi
+case "$0" in
+ */*) cap_appdir="\${0%/*}" ;;
+ *) cap_appdir=. ;;
+esac
+exec "$cap_appdir/AppRun.cap-original" "$@"
+`;
+
+export async function preserveAppImageWorkingDirectory(appDir) {
+ const launcher = path.join(appDir, "AppRun");
+ const original = path.join(appDir, "AppRun.cap-original");
+ if ((await readdir(appDir)).includes(path.basename(original))) {
+ if ((await readFile(launcher, "utf8")) !== appRunWrapper) {
+ throw new Error("AppImage already contains a different AppRun wrapper");
+ }
+ await access(original, constants.X_OK);
+ return;
+ }
+ await access(launcher, constants.X_OK);
+ await rename(launcher, original);
+ await writeFile(launcher, appRunWrapper, { mode: 0o755, flag: "wx" });
+}
+
+export function runCommand(command, args, options = {}) {
+ const result = spawnSync(command, args, { stdio: "inherit", ...options });
+ if (result.error) throw result.error;
+ if (result.status !== 0) {
+ throw new Error(`${command} failed with ${result.signal ?? result.status}`);
+ }
+ return result;
+}
+
+async function hashPrefix(filename, size, digestMd5Offset) {
+ const digestMd5End = digestMd5Offset + 16;
+ const hash = createHash("sha256");
+ let position = 0;
+ for await (const chunk of createReadStream(filename, { end: size - 1 })) {
+ if (
+ digestMd5Offset >= position + chunk.length ||
+ digestMd5End <= position
+ ) {
+ hash.update(chunk);
+ } else {
+ const start = Math.max(digestMd5Offset - position, 0);
+ const end = Math.min(digestMd5End - position, chunk.length);
+ if (start > 0) hash.update(chunk.subarray(0, start));
+ hash.update(Buffer.alloc(end - start));
+ if (end < chunk.length) hash.update(chunk.subarray(end));
+ }
+ position += chunk.length;
+ }
+ return hash.digest("hex");
+}
+
+function parseElfHex(value) {
+ if (!/^(?:0x)?[0-9a-f]+$/i.test(value)) return Number.NaN;
+ const parsed = Number.parseInt(value, 16);
+ return Number.isSafeInteger(parsed) ? parsed : Number.NaN;
+}
+
+async function readDigestMd5Section(runtime, env, run) {
+ const result = await run(
+ "readelf",
+ ["--wide", "--section-headers", runtime],
+ {
+ env: { ...env, LC_ALL: "C" },
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "inherit"],
+ },
+ );
+ const sections =
+ typeof result.stdout === "string"
+ ? result.stdout.split(/\r?\n/).flatMap((line) => {
+ const match =
+ /^\s*\[\s*\d+\]\s+(\S+)\s+\S+\s+\S+\s+(\S+)\s+(\S+)/.exec(line);
+ return match?.[1] === ".digest_md5"
+ ? [{ offset: parseElfHex(match[2]), length: parseElfHex(match[3]) }]
+ : [];
+ })
+ : [];
+ if (sections.length !== 1) {
+ throw new Error("Could not locate a single .digest_md5 section");
+ }
+ return sections[0];
+}
+
+async function copyRuntime(image, directory, env, run) {
+ const options = {
+ env,
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "inherit"],
+ };
+ const signature = (await run(image, ["--appimage-signature"], options))
+ .stdout;
+ if (typeof signature !== "string" || signature.trim()) {
+ throw new Error("Expected an AppImage without an embedded GPG signature");
+ }
+ const offset = (await run(image, ["--appimage-offset"], options)).stdout;
+ const size = typeof offset === "string" ? Number(offset.trim()) : Number.NaN;
+ if (
+ typeof offset !== "string" ||
+ !/^\d+$/.test(offset.trim()) ||
+ !Number.isSafeInteger(size) ||
+ size <= 0 ||
+ size >= (await stat(image)).size
+ ) {
+ throw new Error("Invalid AppImage runtime offset");
+ }
+ const filename = path.join(directory, "runtime");
+ await pipeline(
+ createReadStream(image, { end: size - 1 }),
+ createWriteStream(filename, { mode: 0o755, flags: "wx" }),
+ );
+ const runtime = await stat(filename);
+ if (!runtime.isFile() || runtime.size !== size) {
+ throw new Error("AppImage runtime copy is incomplete");
+ }
+ await access(filename, constants.X_OK);
+ const digestMd5 = await readDigestMd5Section(filename, env, run);
+ if (
+ !Number.isSafeInteger(digestMd5.offset) ||
+ digestMd5.offset <= 0 ||
+ !Number.isSafeInteger(digestMd5.length) ||
+ digestMd5.length < 16 ||
+ digestMd5.offset + digestMd5.length > size
+ ) {
+ throw new Error("Invalid .digest_md5 section in AppImage runtime");
+ }
+ return {
+ filename,
+ size,
+ digestMd5,
+ hash: await hashPrefix(filename, size, digestMd5.offset),
+ };
+}
+
+export async function findConflictingLibraries(appDir, directory = appDir) {
+ const libraries = [];
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ const filename = path.join(directory, entry.name);
+ if (entry.isDirectory()) {
+ libraries.push(...(await findConflictingLibraries(appDir, filename)));
+ } else if (
+ /^libwayland-client\.so(?:\..+)?$/.test(entry.name) ||
+ (directory === path.join(appDir, "usr/lib") &&
+ /^libpipewire-0\.3\.so(?:\..+)?$/.test(entry.name))
+ ) {
+ libraries.push(filename);
+ }
+ }
+ return libraries;
+}
+
+export async function finalizeLinuxAppImage(
+ filename,
+ {
+ unsigned = false,
+ env = process.env,
+ run = runCommand,
+ replace = rename,
+ outputPlugin = path.join(
+ env.XDG_CACHE_HOME || path.join(homedir(), ".cache"),
+ "tauri/linuxdeploy-plugin-appimage.AppImage",
+ ),
+ } = {},
+) {
+ const image = path.resolve(filename);
+ if (!image.endsWith(".AppImage")) {
+ throw new Error("Expected an .AppImage artifact");
+ }
+ if (!unsigned && !env.TAURI_SIGNING_PRIVATE_KEY) {
+ throw new Error(
+ "TAURI_SIGNING_PRIVATE_KEY is required to sign the final AppImage",
+ );
+ }
+ if (env.LDAI_SIGN !== undefined || env.SIGN !== undefined) {
+ throw new Error(
+ "Embedded GPG signing is unsupported; use the Tauri signer",
+ );
+ }
+ await access(outputPlugin, constants.X_OK);
+ await access(image, constants.X_OK);
+ const work = await mkdtemp(path.join(path.dirname(image), ".cap-appimage-"));
+ let retainWork = false;
+ try {
+ const runtime = await copyRuntime(image, work, env, run);
+ await run(image, ["--appimage-extract"], {
+ cwd: work,
+ env,
+ stdio: ["ignore", "ignore", "inherit"],
+ });
+ const appDir = path.join(work, "squashfs-root");
+ 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 preserveAppImageWorkingDirectory(appDir);
+ const output = path.join(work, path.basename(image));
+ await run(
+ outputPlugin,
+ ["--appimage-extract-and-run", "--appdir", appDir],
+ {
+ env: {
+ ...env,
+ APPIMAGE_EXTRACT_AND_RUN: "1",
+ OUTPUT: output,
+ LDAI_OUTPUT: output,
+ LDAI_RUNTIME_FILE: runtime.filename,
+ },
+ },
+ );
+ if (
+ (await stat(output)).size <= runtime.size ||
+ (await hashPrefix(output, runtime.size, runtime.digestMd5.offset)) !==
+ runtime.hash
+ ) {
+ throw new Error("Final AppImage did not preserve its runtime");
+ }
+ await chmod(output, 0o755);
+ if (!unsigned) {
+ await run("pnpm", ["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");
+ }
+ }
+ const originalImage = path.join(work, "original-image");
+ const originalImageStat = await stat(image);
+ await copyFile(image, originalImage, constants.COPYFILE_FICLONE);
+ await chmod(originalImage, originalImageStat.mode & 0o7777);
+ let imageReplaced = false;
+ try {
+ await replace(output, image);
+ imageReplaced = true;
+ if (!unsigned) await replace(`${output}.sig`, `${image}.sig`);
+ else await rm(`${image}.sig`, { force: true });
+ } catch (error) {
+ if (!imageReplaced) throw error;
+ try {
+ await rename(originalImage, image);
+ } catch (rollbackError) {
+ retainWork = true;
+ throw new Error(
+ `${error instanceof Error ? error.message : error}; ${rollbackError instanceof Error ? rollbackError.message : rollbackError}. Recovery backup retained at ${work}`,
+ { cause: rollbackError },
+ );
+ }
+ throw error;
+ }
+ return excluded.map((library) => path.relative(appDir, library));
+ } finally {
+ if (!retainWork) 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[0] === "--unsigned";
+ if (unsigned) args.shift();
+ if (process.platform !== "linux" || args.length !== 1) {
+ throw new Error(
+ "Run on Linux: node scripts/finalize-linux-appimage.mjs [--unsigned] <Cap.AppImage>",
+ );
+ }
+ const excluded = await finalizeLinuxAppImage(args[0], { unsigned });
+ console.log(
+ `Finalized ${args[0]}; excluded ${excluded.join(", ") || "none"}`,
+ );
+}
diff --git a/scripts/finalize-linux-appimage.test.mjs b/scripts/finalize-linux-appimage.test.mjs
new file mode 100644
index 000000000..e95509af4
--- /dev/null
+++ b/scripts/finalize-linux-appimage.test.mjs
@@ -0,0 +1,500 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import {
+ chmod,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ realpath,
+ rename,
+ rm,
+ stat,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { test } from "node:test";
+import {
+ finalizeLinuxAppImage,
+ findConflictingLibraries,
+ preserveAppImageWorkingDirectory,
+} from "./finalize-linux-appimage.mjs";
+
+const runtimeSize = 64;
+const digestMd5Offset = 16;
+const originalRuntime = Buffer.alloc(runtimeSize, 0x52);
+originalRuntime.write("cap runtime fixture");
+Buffer.from("0123456789abcdef").copy(originalRuntime, digestMd5Offset);
+const originalImage = Buffer.concat([
+ originalRuntime,
+ Buffer.from("original payload"),
+]);
+const digestSectionHeaders = `[ 1] .digest_md5 PROGBITS 0000000000000000 0000000000000010 0000000000000010 0000000000000000 A 0 0 1`;
+
+function finalImage(runtime = originalRuntime) {
+ return Buffer.concat([runtime, Buffer.from("final payload")]);
+}
+
+async function assertOriginalArtifact(image, signature) {
+ assert.deepEqual(await readFile(image), originalImage);
+ assert.equal(await readFile(`${image}.sig`, "utf8"), signature);
+}
+
+async function fixture(t) {
+ const root = await mkdtemp(path.join(tmpdir(), "cap-appimage-test-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const image = path.join(root, "Cap.AppImage");
+ const plugin = path.join(root, "output-plugin");
+ await writeFile(image, originalImage, { mode: 0o755 });
+ await writeFile(`${image}.sig`, "original signature");
+ await writeFile(plugin, "fixture", { mode: 0o755 });
+ return { root, image, plugin, originalRuntime };
+}
+
+for (const failureAt of [1, 2]) {
+ test(`replacement failure ${failureAt} preserves the original artifact`, async (t) => {
+ const { root, image, plugin } = await fixture(t);
+ const env = {
+ TAURI_SIGNING_PRIVATE_KEY: "test key",
+ };
+ let replacements = 0;
+ const originalInode = (await stat(image)).ino;
+ const run = async (command, args, options) => {
+ if (command === image) {
+ if (args[0] === "--appimage-signature") return { stdout: "" };
+ if (args[0] === "--appimage-offset") {
+ return { stdout: `${runtimeSize}` };
+ }
+ const appDir = path.join(options.cwd, "squashfs-root");
+ await mkdir(appDir);
+ await writeFile(path.join(appDir, "AppRun"), "launcher", {
+ mode: 0o755,
+ });
+ } else if (command === plugin) {
+ await writeFile(options.env.OUTPUT, finalImage());
+ } else if (command === "readelf") {
+ assert.deepEqual(args.slice(0, 2), ["--wide", "--section-headers"]);
+ assert.equal(options.env.LC_ALL, "C");
+ return { stdout: digestSectionHeaders };
+ } else {
+ assert.equal(command, "pnpm");
+ await writeFile(`${args[3]}.sig`, "new signature");
+ }
+ };
+ await assert.rejects(
+ finalizeLinuxAppImage(image, {
+ outputPlugin: plugin,
+ env,
+ run,
+ replace: async (from, to) => {
+ replacements += 1;
+ if (replacements === failureAt) {
+ throw new Error(`replacement ${failureAt} failed`);
+ }
+ await rename(from, to);
+ if (to === image) {
+ assert.notDeepEqual(await readFile(image), originalImage);
+ }
+ },
+ }),
+ new RegExp(`replacement ${failureAt} failed`),
+ );
+ await assertOriginalArtifact(image, "original signature");
+ assert.equal((await stat(image)).mode & 0o111, 0o111);
+ if (failureAt === 1) assert.equal((await stat(image)).ino, originalInode);
+ assert.ok(
+ !(await readdir(root)).some((file) => file.startsWith(".cap-appimage-")),
+ );
+ });
+}
+
+test("conflicting libraries are limited to Wayland clients and the root PipeWire copy without following directory symlinks", async (t) => {
+ const { root } = await fixture(t);
+ const appDir = path.join(root, "AppDir");
+ const libraryDirectory = path.join(appDir, "usr/lib");
+ await mkdir(libraryDirectory, { recursive: true });
+ await writeFile(
+ path.join(libraryDirectory, "libwayland-client.so.0.23.0"),
+ "client",
+ );
+ await symlink(
+ "libwayland-client.so.0.23.0",
+ path.join(libraryDirectory, "libwayland-client.so.0"),
+ );
+ await writeFile(path.join(libraryDirectory, "libwayland-egl.so.1"), "egl");
+ await writeFile(
+ path.join(libraryDirectory, "libpipewire-0.3.so.0"),
+ "pipewire",
+ );
+ await mkdir(path.join(libraryDirectory, "cap"));
+ await writeFile(
+ path.join(libraryDirectory, "cap/libpipewire-0.3.so.0"),
+ "private copy",
+ );
+ await writeFile(path.join(root, "libwayland-client.so.99"), "outside");
+ await symlink(root, path.join(appDir, "outside"));
+ const libraries = await findConflictingLibraries(appDir);
+ assert.deepEqual(libraries.map((file) => path.basename(file)).sort(), [
+ "libpipewire-0.3.so.0",
+ "libwayland-client.so.0",
+ "libwayland-client.so.0.23.0",
+ ]);
+});
+
+for (const failure of [false, true]) {
+ test(`signing ${failure ? "failure preserves the original artifact" : "uses the final bytes before replacing the artifact"}`, async (t) => {
+ const { root, image, plugin } = await fixture(t);
+ const calls = [];
+ const env = {
+ TAURI_SIGNING_PRIVATE_KEY: "test key",
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: "test password",
+ };
+ const run = async (command, args, options) => {
+ calls.push(command);
+ assert.deepEqual(await readFile(image), originalImage);
+ assert.equal(
+ await readFile(`${image}.sig`, "utf8"),
+ "original signature",
+ );
+ if (command === image) {
+ if (args[0] === "--appimage-signature") return { stdout: "\n" };
+ if (args[0] === "--appimage-offset") {
+ return { stdout: `${runtimeSize}\n` };
+ }
+ assert.deepEqual(args, ["--appimage-extract"]);
+ const libraries = path.join(options.cwd, "squashfs-root/usr/lib");
+ await mkdir(libraries, { recursive: true });
+ await writeFile(
+ path.join(libraries, "libwayland-client.so.0"),
+ "client",
+ );
+ await writeFile(
+ path.join(libraries, "libwayland-server.so.0"),
+ "server",
+ );
+ await writeFile(
+ path.join(libraries, "libpipewire-0.3.so.0"),
+ "pipewire",
+ );
+ await writeFile(
+ path.join(options.cwd, "squashfs-root/AppRun"),
+ "original launcher",
+ { mode: 0o755 },
+ );
+ } else if (command === "readelf") {
+ return { stdout: digestSectionHeaders };
+ } else if (command === plugin) {
+ assert.equal(
+ Buffer.compare(
+ await readFile(options.env.LDAI_RUNTIME_FILE),
+ originalRuntime,
+ ),
+ 0,
+ );
+ assert.notEqual(options.env.LDAI_RUNTIME_FILE, image);
+ assert.equal(options.env.OUTPUT, options.env.LDAI_OUTPUT);
+ assert.deepEqual(await readdir(path.join(args[2], "usr/lib")), [
+ "libwayland-server.so.0",
+ ]);
+ assert.equal(
+ await readFile(path.join(args[2], "AppRun.cap-original"), "utf8"),
+ "original launcher",
+ );
+ assert.match(
+ await readFile(path.join(args[2], "AppRun"), "utf8"),
+ /export OWD/,
+ );
+ const changedRuntime = Buffer.from(originalRuntime);
+ changedRuntime.fill(0xa5, digestMd5Offset, digestMd5Offset + 16);
+ await writeFile(options.env.OUTPUT, finalImage(changedRuntime));
+ } else {
+ assert.equal(command, "pnpm");
+ assert.deepEqual(args.slice(0, 3), ["tauri", "signer", "sign"]);
+ assert.equal(
+ options.env.TAURI_PRIVATE_KEY,
+ env.TAURI_SIGNING_PRIVATE_KEY,
+ );
+ assert.equal(
+ options.env.TAURI_PRIVATE_KEY_PASSWORD,
+ env.TAURI_SIGNING_PRIVATE_KEY_PASSWORD,
+ );
+ assert.ok(!args.includes(env.TAURI_SIGNING_PRIVATE_KEY));
+ if (failure) throw new Error("signer failed");
+ const hash = createHash("sha256")
+ .update(await readFile(args[3]))
+ .digest("hex");
+ await writeFile(`${args[3]}.sig`, hash);
+ }
+ };
+ const operation = finalizeLinuxAppImage(image, {
+ outputPlugin: plugin,
+ env,
+ run,
+ });
+ if (failure) {
+ await assert.rejects(operation, /signer failed/);
+ await assertOriginalArtifact(image, "original signature");
+ assert.equal(
+ await readFile(`${image}.sig`, "utf8"),
+ "original signature",
+ );
+ } else {
+ assert.deepEqual((await operation).sort(), [
+ "usr/lib/libpipewire-0.3.so.0",
+ "usr/lib/libwayland-client.so.0",
+ ]);
+ const expectedRuntime = Buffer.from(originalRuntime);
+ expectedRuntime.fill(0xa5, digestMd5Offset, digestMd5Offset + 16);
+ assert.deepEqual(await readFile(image), finalImage(expectedRuntime));
+ assert.equal(
+ await readFile(`${image}.sig`, "utf8"),
+ createHash("sha256").update(finalImage(expectedRuntime)).digest("hex"),
+ );
+ }
+ assert.deepEqual(calls, [image, image, "readelf", image, plugin, "pnpm"]);
+ assert.ok(
+ !(await readdir(root)).some((file) => file.startsWith(".cap-appimage-")),
+ );
+ });
+}
+
+test("missing signing key or output tool fails before changing the input", async (t) => {
+ const { image, plugin } = await fixture(t);
+ await assert.rejects(
+ finalizeLinuxAppImage(image, { outputPlugin: plugin, env: {} }),
+ /TAURI_SIGNING_PRIVATE_KEY/,
+ );
+ await chmod(plugin, 0o644);
+ await assert.rejects(
+ finalizeLinuxAppImage(image, { outputPlugin: plugin, unsigned: true }),
+ /EACCES/,
+ );
+ await assertOriginalArtifact(image, "original signature");
+});
+
+for (const invalidOffset of [
+ "",
+ "0",
+ "-1",
+ "80",
+ "99999999999999999999",
+ "9x",
+]) {
+ test(`invalid runtime offset ${JSON.stringify(invalidOffset)} preserves the input`, async (t) => {
+ const { root, image, plugin } = await fixture(t);
+ await assert.rejects(
+ finalizeLinuxAppImage(image, {
+ outputPlugin: plugin,
+ unsigned: true,
+ env: {},
+ run: async (command, args) => {
+ assert.equal(command, image);
+ return {
+ stdout: args[0] === "--appimage-signature" ? "" : invalidOffset,
+ };
+ },
+ }),
+ /Invalid AppImage runtime offset/,
+ );
+ await assertOriginalArtifact(image, "original signature");
+ assert.ok(
+ !(await readdir(root)).some((file) => file.startsWith(".cap-appimage-")),
+ );
+ });
+}
+
+for (const [name, sectionHeaders] of [
+ [
+ "missing",
+ "[ 1] .text PROGBITS 0000000000000000 0000000000000010 0000000000000010",
+ ],
+ [
+ "malformed",
+ "[ 1] .digest_md5 PROGBITS 0000000000000000 not-hex 0000000000000010",
+ ],
+ [
+ "short",
+ "[ 1] .digest_md5 PROGBITS 0000000000000000 0000000000000010 000000000000000f",
+ ],
+ [
+ "out of range",
+ "[ 1] .digest_md5 PROGBITS 0000000000000000 0000000000000038 0000000000000020",
+ ],
+]) {
+ test(`invalid digest section ${name} preserves the input`, async (t) => {
+ const { root, image, plugin } = await fixture(t);
+ await assert.rejects(
+ finalizeLinuxAppImage(image, {
+ outputPlugin: plugin,
+ unsigned: true,
+ env: {},
+ run: async (command, args) => {
+ if (command === image) {
+ return {
+ stdout:
+ args[0] === "--appimage-signature" ? "" : `${runtimeSize}`,
+ };
+ }
+ assert.equal(command, "readelf");
+ return { stdout: sectionHeaders };
+ },
+ }),
+ /digest_md5/,
+ );
+ await assertOriginalArtifact(image, "original signature");
+ assert.ok(
+ !(await readdir(root)).some((file) => file.startsWith(".cap-appimage-")),
+ );
+ });
+}
+
+test("runtime changes from the output plugin are rejected before signing", async (t) => {
+ const { root, image, plugin } = await fixture(t);
+ await assert.rejects(
+ finalizeLinuxAppImage(image, {
+ outputPlugin: plugin,
+ env: { TAURI_SIGNING_PRIVATE_KEY: "test key" },
+ run: async (command, args, options) => {
+ if (command === image) {
+ if (args[0] === "--appimage-signature") return { stdout: "" };
+ if (args[0] === "--appimage-offset") {
+ return { stdout: `${runtimeSize}` };
+ }
+ const appDir = path.join(options.cwd, "squashfs-root");
+ await mkdir(appDir);
+ await writeFile(path.join(appDir, "AppRun"), "launcher", {
+ mode: 0o755,
+ });
+ } else if (command === "readelf") {
+ return { stdout: digestSectionHeaders };
+ } else {
+ assert.equal(command, plugin);
+ const changedRuntime = Buffer.from(originalRuntime);
+ changedRuntime[0] ^= 0xff;
+ await writeFile(options.env.OUTPUT, finalImage(changedRuntime));
+ }
+ },
+ }),
+ /did not preserve its runtime/,
+ );
+ await assertOriginalArtifact(image, "original signature");
+ assert.ok(
+ !(await readdir(root)).some((file) => file.startsWith(".cap-appimage-")),
+ );
+});
+
+test("embedded GPG signatures and signing requests fail without changing the input", async (t) => {
+ const { image, plugin } = await fixture(t);
+ for (const env of [{ LDAI_SIGN: "1" }, { SIGN: "0" }]) {
+ await assert.rejects(
+ finalizeLinuxAppImage(image, {
+ outputPlugin: plugin,
+ unsigned: true,
+ env,
+ }),
+ /Embedded GPG signing is unsupported/,
+ );
+ }
+ await assert.rejects(
+ finalizeLinuxAppImage(image, {
+ outputPlugin: plugin,
+ unsigned: true,
+ env: {},
+ run: async () => ({ stdout: "-----BEGIN PGP SIGNATURE-----" }),
+ }),
+ /without an embedded GPG signature/,
+ );
+ await assertOriginalArtifact(image, "original signature");
+});
+
+test("AppRun preserves caller paths and arguments in mounted and extracted launches", async (t) => {
+ const { root } = await fixture(t);
+ const appDir = path.join(root, "Cap's AppDir");
+ await mkdir(path.join(appDir, "usr"), { recursive: true });
+ const launcher = path.join(appDir, "AppRun");
+ const original = `#!/bin/sh
+cd "\${0%/*}/usr" || exit
+printf '%s\\0' "$OWD" "$@"
+exit 23
+`;
+ await writeFile(launcher, original, { mode: 0o755 });
+ await preserveAppImageWorkingDirectory(appDir);
+ await preserveAppImageWorkingDirectory(appDir);
+ assert.equal(
+ await readFile(path.join(appDir, "AppRun.cap-original"), "utf8"),
+ original,
+ );
+ const direct = spawnSync("/bin/sh", ["AppRun", "--version"], {
+ cwd: appDir,
+ });
+ assert.equal(direct.status, 23, direct.stderr.toString());
+ assert.deepEqual(direct.stdout.toString().split("\0"), [
+ await realpath(appDir),
+ "--version",
+ "",
+ ]);
+ for (const name of ["caller's directory", "trailing-newline\n"]) {
+ const caller = path.join(root, name);
+ await mkdir(caller);
+ for (const runtimeOwd of [undefined, "/stale/caller"]) {
+ const env = { ...process.env };
+ if (runtimeOwd === undefined) delete env.OWD;
+ else env.OWD = runtimeOwd;
+ const args = ["--cap-cli", "two words", "$(literal)", "last\n"];
+ const result = spawnSync(launcher, args, { cwd: caller, env });
+ assert.equal(result.status, 23, result.stderr.toString());
+ assert.deepEqual(result.stdout.toString().split("\0"), [
+ await realpath(caller),
+ ...args,
+ "",
+ ]);
+ }
+ }
+});
+
+test("AppRun wrapping refuses an unrelated existing launcher backup", async (t) => {
+ const { root } = await fixture(t);
+ await writeFile(path.join(root, "AppRun"), "existing launcher");
+ await writeFile(path.join(root, "AppRun.cap-original"), "unrelated file");
+ await assert.rejects(
+ preserveAppImageWorkingDirectory(root),
+ /different AppRun wrapper/,
+ );
+ assert.equal(
+ await readFile(path.join(root, "AppRun"), "utf8"),
+ "existing launcher",
+ );
+ assert.equal(
+ await readFile(path.join(root, "AppRun.cap-original"), "utf8"),
+ "unrelated file",
+ );
+});
+
+test("AppRun still launches the GUI after the caller directory is removed", async (t) => {
+ const { root } = await fixture(t);
+ const appDir = path.join(root, "AppDir");
+ const caller = path.join(root, "removed-caller");
+ await mkdir(appDir);
+ await mkdir(caller);
+ const launcher = path.join(appDir, "AppRun");
+ await writeFile(
+ launcher,
+ `#!/bin/sh
+printf 'GUI launched:%s' "\${OWD-unset}"
+exit 23
+`,
+ { mode: 0o755 },
+ );
+ await preserveAppImageWorkingDirectory(appDir);
+ const result = spawnSync(
+ "/bin/sh",
+ ["-c", `cd "$1" && rmdir "$1" && exec "$2"`, "sh", caller, launcher],
+ { env: { ...process.env, OWD: "/stale/caller" } },
+ );
+ assert.equal(result.status, 23, result.stderr.toString());
+ assert.match(result.stdout.toString(), /^GUI launched:/);
+ assert.ok(!result.stdout.toString().includes("/stale/caller"));
+});
diff --git a/scripts/linux-bundle-config.mjs b/scripts/linux-bundle-config.mjs
new file mode 100644
index 000000000..1564f3628
--- /dev/null
+++ b/scripts/linux-bundle-config.mjs
@@ -0,0 +1,63 @@
+export function supportedLinuxBundles(version) {
+ return version.includes("-")
+ ? ["deb", "appimage"]
+ : ["deb", "rpm", "appimage"];
+}
+
+export function createLinuxBundleConfig(
+ libraryNames,
+ commonFiles = {},
+ debDependencies = [],
+) {
+ const files = { ...commonFiles };
+ for (const name of [...new Set(libraryNames)].toSorted()) {
+ files[`/usr/lib/cap/${name}`] =
+ `../../../target/native-deps/cap-deb-libs/${name}`;
+ }
+
+ return {
+ bundle: {
+ linux: {
+ deb: {
+ depends: [...new Set([...debDependencies, "libasound2-plugins"])],
+ files: {
+ ...files,
+ "/usr/lib/cap/package-format": "../../../packaging/linux/deb",
+ },
+ },
+ rpm: {
+ compression: { type: "zstd", level: 9 },
+ depends: [
+ "webkit2gtk4.1",
+ "gtk3",
+ "libayatana-appindicator-gtk3",
+ "libva",
+ "pulseaudio-utils",
+ "pipewire-libs",
+ "alsa-lib",
+ "alsa-plugins-pulseaudio",
+ "libxkbcommon",
+ "libxkbcommon-x11",
+ "openssl-libs",
+ ],
+ files: {
+ ...files,
+ "/usr/lib/cap/package-format": "../../../packaging/linux/rpm",
+ },
+ },
+ appimage: {
+ bundleMediaFramework: true,
+ files: {
+ ...files,
+ "/usr/bin/pactl": "/usr/bin/pactl",
+ "/usr/lib/alsa-lib/libasound_module_pcm_pulse.so":
+ "../../../target/native-deps/cap-appimage-libs/libasound_module_pcm_pulse.so",
+ "/usr/lib/cap/alsa-pulse.conf":
+ "../../../packaging/linux/alsa-pulse.conf",
+ "/usr/lib/cap/package-format": "../../../packaging/linux/appimage",
+ },
+ },
+ },
+ },
+ };
+}
diff --git a/scripts/linux-bundle-config.test.mjs b/scripts/linux-bundle-config.test.mjs
new file mode 100644
index 000000000..53f5c133d
--- /dev/null
+++ b/scripts/linux-bundle-config.test.mjs
@@ -0,0 +1,78 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ createLinuxBundleConfig,
+ supportedLinuxBundles,
+} from "./linux-bundle-config.mjs";
+
+test("nightly builds retain DEB and AppImage without passing invalid hyphenated versions to RPM", () => {
+ assert.deepEqual(supportedLinuxBundles("0.6.0"), ["deb", "rpm", "appimage"]);
+ assert.deepEqual(supportedLinuxBundles("0.6.0-nightly.202608261700"), [
+ "deb",
+ "appimage",
+ ]);
+ assert.deepEqual(supportedLinuxBundles("0.6.0-rc.1"), ["deb", "appimage"]);
+});
+
+test("all Linux formats retain the exact native library sonames and shared icons", () => {
+ const icon =
+ "/usr/share/icons/hicolor/scalable/status/so.cap.desktop-tray-studio-symbolic.svg";
+ const config = createLinuxBundleConfig(
+ ["libonnxruntime.so", "libavcodec.so.61", "libonnxruntime.so.1"],
+ { [icon]: "icons/linux/so.cap.desktop-tray-studio-symbolic.svg" },
+ );
+
+ for (const format of ["deb", "rpm", "appimage"]) {
+ assert.equal(
+ config.bundle.linux[format].files["/usr/lib/cap/libavcodec.so.61"],
+ "../../../target/native-deps/cap-deb-libs/libavcodec.so.61",
+ );
+ assert.equal(
+ config.bundle.linux[format].files["/usr/lib/cap/libonnxruntime.so.1"],
+ "../../../target/native-deps/cap-deb-libs/libonnxruntime.so.1",
+ );
+ assert.equal(
+ config.bundle.linux[format].files[icon],
+ "icons/linux/so.cap.desktop-tray-studio-symbolic.svg",
+ );
+ }
+});
+
+test("AppImage includes the system-audio control tool and webview media framework", () => {
+ const { appimage, deb, rpm } = createLinuxBundleConfig([]).bundle.linux;
+ assert.equal(appimage.files["/usr/bin/pactl"], "/usr/bin/pactl");
+ assert.equal(appimage.bundleMediaFramework, true);
+ assert.equal(
+ appimage.files["/usr/lib/alsa-lib/libasound_module_pcm_pulse.so"],
+ "../../../target/native-deps/cap-appimage-libs/libasound_module_pcm_pulse.so",
+ );
+ assert.equal(
+ appimage.files["/usr/lib/cap/alsa-pulse.conf"],
+ "../../../packaging/linux/alsa-pulse.conf",
+ );
+ for (const format of [deb, rpm]) {
+ assert.equal(format.files["/usr/lib/cap/alsa-pulse.conf"], undefined);
+ }
+});
+
+test("library mappings are deterministic and preserve the input mappings", () => {
+ const files = { "/usr/share/cap/example": "example" };
+ const first = createLinuxBundleConfig(["libz.so.1", "liba.so.2"], files);
+ const second = createLinuxBundleConfig(
+ ["liba.so.2", "libz.so.1", "liba.so.2"],
+ files,
+ );
+ assert.equal(JSON.stringify(first), JSON.stringify(second));
+ assert.deepEqual(files, { "/usr/share/cap/example": "example" });
+});
+
+test("Debian audio dependencies retain existing requirements without duplicates", () => {
+ const dependencies = ["libgtk-3-0", "libasound2-plugins"];
+ const config = createLinuxBundleConfig([], {}, dependencies);
+ assert.deepEqual(config.bundle.linux.deb.depends, dependencies);
+ assert.notEqual(config.bundle.linux.deb.depends, dependencies);
+ assert.deepEqual(
+ createLinuxBundleConfig([], {}, ["libgtk-3-0"]).bundle.linux.deb.depends,
+ ["libgtk-3-0", "libasound2-plugins"],
+ );
+});
diff --git a/scripts/setup.js b/scripts/setup.js
index 378944e94..1997c7478 100644
--- a/scripts/setup.js
+++ b/scripts/setup.js
@@ -7,6 +7,7 @@ import * as path from "node:path";
import { env } from "node:process";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
+import { createLinuxBundleConfig } from "./linux-bundle-config.mjs";
const exec = promisify(execCb);
const execFile = promisify(execFileCb);
@@ -710,6 +711,32 @@ async function fileExists(path) {
}
async function writeLinuxTauriConfig(sonameLibs) {
+ const pluginName = "libasound_module_pcm_pulse.so";
+ const pluginDirectories = [
+ `/usr/lib/${arch}-linux-gnu/alsa-lib`,
+ "/usr/lib64/alsa-lib",
+ "/usr/lib/alsa-lib",
+ ];
+ let pulsePlugin;
+ for (const directory of pluginDirectories) {
+ const candidate = path.join(directory, pluginName);
+ if (await fileExists(candidate)) {
+ pulsePlugin = candidate;
+ break;
+ }
+ }
+ if (!pulsePlugin) {
+ throw new Error(
+ "The ALSA PulseAudio plugin is required for Linux bundles. Install libasound2-plugins (Debian/Ubuntu), alsa-plugins-pulseaudio (Fedora), or alsa-plugins (Arch).",
+ );
+ }
+ const appimageLibDir = path.join(
+ __root,
+ "target/native-deps/cap-appimage-libs",
+ );
+ await fs.mkdir(appimageLibDir, { recursive: true });
+ await fs.copyFile(pulsePlugin, path.join(appimageLibDir, pluginName));
+
const configPath = path.join(
__root,
"apps",
@@ -717,19 +744,24 @@ async function writeLinuxTauriConfig(sonameLibs) {
"src-tauri",
"tauri.linux.conf.json",
);
- const files = {};
-
- for (const name of sonameLibs.toSorted()) {
- files[`/usr/lib/cap/${name}`] =
- `../../../target/native-deps/cap-deb-libs/${name}`;
- }
+ const baseConfig = JSON.parse(
+ await fs.readFile(
+ path.join(path.dirname(configPath), "tauri.conf.json"),
+ "utf8",
+ ),
+ );
+ const config = createLinuxBundleConfig(
+ sonameLibs,
+ baseConfig.bundle.linux.deb.files,
+ baseConfig.bundle.linux.deb.depends,
+ );
await writeFileIfChanged(
configPath,
- `${JSON.stringify({ bundle: { linux: { deb: { files } } } }, null, "\t")}\n`,
+ `${JSON.stringify(config, null, "\t")}\n`,
);
console.log(
- `Generated Linux Tauri deb config with ${sonameLibs.length} shared libraries`,
+ `Generated Linux Tauri package configs with ${sonameLibs.length} shared libraries`,
);
}