Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Linux: harden the relay socket, file permissions and release workflow

Louis Raillebef6558bc04c
diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml
index c12d6298..21d8cc95 100644
--- a/.github/workflows/linux.yml
+++ b/.github/workflows/linux.yml
@@ -1,8 +1,12 @@
name: Linux
# Builds the Linux app (AppImage, .deb, .rpm) from the same Tauri project as
-# Windows and publishes the packages. Triggered by tags like `linux-v0.1.0`;
-# the macOS and Windows workflows are untouched.
+# Windows. Triggered by tags like `linux-v0.1.0`, or by hand; the macOS and
+# Windows workflows are untouched.
+#
+# Two jobs on purpose. `build` runs npm, cargo and the AppImage tooling (which
+# downloads its own helpers) with a read-only token that is not even kept on
+# disk. Only `publish`, which runs none of that code, may write to the repo.
on:
push:
@@ -11,22 +15,30 @@ on:
workflow_dispatch:
permissions:
- contents: write
+ contents: read
+# Off until a first build has been checked by hand: run this workflow manually,
+# download the Coucou-Linux artifact, try it, then set this to 'true' and push a
+# linux-v* tag.
env:
- PUBLISH: 'true'
+ PUBLISH: 'false'
jobs:
build:
# The oldest supported Ubuntu: an AppImage only runs on systems whose glibc
# is at least as new as the one it was built against.
runs-on: ubuntu-22.04
+ outputs:
+ version: ${{ steps.pack.outputs.version }}
+ publish: ${{ steps.gate.outputs.publish }}
defaults:
run:
working-directory: windows
steps:
- uses: actions/checkout@v4
+ with:
+ persist-credentials: false
# webkit2gtk, gtk-layer-shell and appindicator to build against; patchelf
# and the GStreamer plugins for the AppImage, which carries its own
@@ -74,8 +86,12 @@ jobs:
[ "$tag" = "$cargo" ] || bad="$bad Cargo.toml says $cargo;"
if [ -n "$bad" ]; then echo "tag says $tag but$bad"; exit 1; fi
+ # The app bundles target/release/coucou-hook as a resource, and its build
+ # script refuses to run until that file exists.
- name: Test
- run: cargo test --workspace
+ run: |
+ cargo build --release -p coucou-hook
+ cargo test --workspace
# linuxdeploy is itself an AppImage; runners have no FUSE, so it unpacks
# itself instead of mounting.
@@ -86,26 +102,57 @@ jobs:
run: |
npm run pack
echo "version=$(node -p "require('./src-tauri/tauri.conf.json').version")" >> "$GITHUB_OUTPUT"
- ls -la release
-
+ cd release
+ sha256sum Coucou-Linux-* > SHA256SUMS
+ ls -la
+ cat SHA256SUMS
+
+ - name: Decide whether to publish
+ id: gate
+ run: echo "publish=${{ env.PUBLISH == 'true' && startsWith(github.ref, 'refs/tags/linux-v') }}" >> "$GITHUB_OUTPUT"
+
+ # Upload only on a manual run or when publishing a release, as on Windows.
+ # The repo is public, so artifacts are downloadable by any signed-in GitHub
+ # user; retention-days: 3 limits exposure.
- uses: actions/upload-artifact@v4
+ if: github.event_name == 'workflow_dispatch' || steps.gate.outputs.publish == 'true'
with:
name: Coucou-Linux
path: |
- windows/release/Coucou-Linux-${{ steps.pack.outputs.version }}-*
+ windows/release/Coucou-Linux-*
+ windows/release/SHA256SUMS
+ retention-days: 3
+
+ publish:
+ needs: build
+ if: needs.build.outputs.publish == 'true'
+ runs-on: ubuntu-22.04
+ permissions:
+ contents: write
+
+ steps:
+ # Only for the linux-latest tag below; nothing from the repo is run.
+ - uses: actions/checkout@v4
+
+ - uses: actions/download-artifact@v4
+ with:
+ name: Coucou-Linux
+ path: release
- name: Publish the release
- if: env.PUBLISH == 'true' && startsWith(github.ref, 'refs/tags/linux-v')
env:
GH_TOKEN: ${{ github.token }}
+ VERSION: ${{ needs.build.outputs.version }}
run: |
- v="${{ steps.pack.outputs.version }}"
+ v="$VERSION"
notes="Coucou for Linux $v — Mochi at the top of your screen.
- **AppImage** (any distribution): \`chmod +x Coucou-Linux-$v-x86_64.AppImage\` and run it.
- **Debian / Ubuntu**: \`sudo apt install ./Coucou-Linux-$v-amd64.deb\`
- **Fedora / openSUSE**: \`sudo dnf install ./Coucou-Linux-$v-x86_64.rpm\`
+ Check a download with \`sha256sum -c SHA256SUMS --ignore-missing\`.
+
The island sits on the top edge on compositors with layer-shell (COSMIC,
KDE Plasma, Hyprland, Sway…). On GNOME it opens as a regular window."
# --latest=false: the macOS \`v*\` releases own the Latest slot, which
@@ -114,16 +161,17 @@ jobs:
"release/Coucou-Linux-$v-x86_64.AppImage" \
"release/Coucou-Linux-$v-amd64.deb" \
"release/Coucou-Linux-$v-x86_64.rpm" \
+ "release/SHA256SUMS" \
--title "Coucou for Linux $v" \
--notes "$notes" \
--latest=false
- name: Update the rolling linux-latest release
- if: env.PUBLISH == 'true' && startsWith(github.ref, 'refs/tags/linux-v')
env:
GH_TOKEN: ${{ github.token }}
+ VERSION: ${{ needs.build.outputs.version }}
run: |
- v="${{ steps.pack.outputs.version }}"
+ v="$VERSION"
if gh release view linux-latest >/dev/null 2>&1; then
# The tag has to follow the release, as for windows-latest.
git tag -f linux-latest "$GITHUB_SHA"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3fffbc3..2ff63c0d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
- Declare the tools you use in Settings: Gemini CLI, Antigravity, Anthropic, Google AI and OpenAI pills join the existing ones (Cursor and Codex pills are coming soon), and you pick the main pill.
- Chat now supports Google AI (Gemini) and OpenAI in addition to Anthropic; switch provider and model by clicking the model name in the chat view, on macOS.
+- Linux version: the Tauri app now builds for Linux too (AppImage, .deb, .rpm), with the island as a layer-shell overlay on Wayland and Claude Code hooks over a private Unix socket (#21) — thanks @Davy133
- Compact island on screens without a notch (#22) — thanks @Kamasoutra
- Only web links (http/https) open from the notch; other kinds of links from Claude or integrations are ignored (#16) — thanks @Cris1670
- Hook socket limited to your own user account, with size and time limits; logs no longer keep commands, n8n data or full URLs, and stay under 1 MB (#16) — thanks @Cris1670 and @Vignesh-Thangamariappan
diff --git a/README.md b/README.md
index d5d9979e..1399c329 100644
--- a/README.md
+++ b/README.md
@@ -77,7 +77,9 @@ rest of the differences.
### Linux
-Grab a package from [Releases](https://github.com/Louis-CFM/coucou/releases):
+Linux packages are published in [Releases](https://github.com/Louis-CFM/coucou/releases)
+under `linux-v*` tags; the first one is on its way. Until it lands, [build from source](#build-from-source).
+Once it's there:
- **AppImage** (any distribution): `chmod +x Coucou-Linux-*.AppImage`, then run it.
- **Debian / Ubuntu**: `sudo apt install ./Coucou-Linux-*.deb`
diff --git a/windows/hook/src/unix.rs b/windows/hook/src/unix.rs
index 332e1faa..6a45aa81 100644
--- a/windows/hook/src/unix.rs
+++ b/windows/hook/src/unix.rs
@@ -15,17 +15,25 @@ use std::time::{Duration, Instant};
use crate::CONNECT_TIMEOUT;
/// `$XDG_RUNTIME_DIR/coucou.sock`, or `/run/user/<uid>/coucou.sock` when the
-/// variable is missing (a hook started from a stripped-down environment).
+/// variable is missing (a hook started from a stripped-down environment). The
+/// directory must be ours and closed to everyone else, or there is no relay.
/// Must match `platform::relay_socket_path()` in the app exactly.
fn socket_path() -> Option<PathBuf> {
let dir = std::env::var_os("XDG_RUNTIME_DIR")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
- .or_else(|| {
- let p = PathBuf::from(format!("/run/user/{}", unsafe { libc::getuid() }));
- p.is_dir().then_some(p)
- })?;
- Some(dir.join("coucou.sock"))
+ .unwrap_or_else(|| PathBuf::from(format!("/run/user/{}", unsafe { libc::getuid() })));
+ is_private_dir(&dir).then(|| dir.join("coucou.sock"))
+}
+
+/// A real directory (not a symlink), owned by us, no access for group or others.
+fn is_private_dir(dir: &Path) -> bool {
+ use std::os::unix::fs::MetadataExt;
+ std::fs::symlink_metadata(dir)
+ .map(|m| {
+ m.file_type().is_dir() && m.uid() == unsafe { libc::getuid() } && m.mode() & 0o077 == 0
+ })
+ .unwrap_or(false)
}
/// Opens the socket. Retries only while the app's backlog is full: any other
@@ -100,5 +108,7 @@ fn server_is_same_user(stream: &UnixStream) -> bool {
&mut len,
)
};
- rc == 0 && cred.uid == unsafe { libc::getuid() }
+ rc == 0
+ && len as usize == std::mem::size_of::<libc::ucred>()
+ && cred.uid == unsafe { libc::getuid() }
}
diff --git a/windows/src-tauri/src/files.rs b/windows/src-tauri/src/files.rs
index d43e5d4d..14490715 100644
--- a/windows/src-tauri/src/files.rs
+++ b/windows/src-tauri/src/files.rs
@@ -31,6 +31,7 @@ pub fn ingest(source: &str) -> Result<DroppedFile, String> {
}
let dir = inbox_dir();
+ crate::platform::ensure_private_dir(&settings::local_dir()).map_err(|e| e.to_string())?;
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let name = src
diff --git a/windows/src-tauri/src/hooks.rs b/windows/src-tauri/src/hooks.rs
index 85843306..3da1d0e5 100644
--- a/windows/src-tauri/src/hooks.rs
+++ b/windows/src-tauri/src/hooks.rs
@@ -103,11 +103,27 @@ fn read_settings_lossy() -> Value {
read_settings().unwrap_or_else(|_| json!({}))
}
+#[cfg(windows)]
fn hook_command(event: &str) -> String {
let exe = settings::hook_exe_path().to_string_lossy().replace('\\', "/");
format!("\"{exe}\" {event}")
}
+/// Claude Code runs the command through `sh`, which still reads `$`, `` ` ``
+/// and `\` inside double quotes. Single quotes keep the path a path, whatever
+/// the home directory is called.
+#[cfg(unix)]
+fn hook_command(event: &str) -> String {
+ format!("{} {event}", sh_quote(&settings::hook_exe_path().to_string_lossy()))
+}
+
+/// `s` as one single-quoted shell word: `'` becomes `'\''`, nothing else is
+/// special inside single quotes.
+#[cfg(unix)]
+fn sh_quote(s: &str) -> String {
+ format!("'{}'", s.replace('\'', r"'\''"))
+}
+
fn entry_is_ours(entry: &Value) -> bool {
entry
.get("hooks")
@@ -284,10 +300,18 @@ pub fn write(install: bool, fingerprint: &str) -> Result<String, String> {
let mut text = pretty(&next);
text.push('\n');
+ // A dotfiles setup often makes settings.json a symlink: write to the file it
+ // points at, so the link survives the rename below.
+ #[cfg(unix)]
+ let path = std::fs::canonicalize(&path).unwrap_or(path);
+
// Write beside the target and rename over it: a crash or a full disk leaves
// the original settings.json intact rather than half a file.
let temp = path.with_extension(format!("json.coucou-{}", std::process::id()));
- std::fs::write(&temp, text.as_bytes()).map_err(|e| format!("write failed: {e}"))?;
+ if let Err(err) = write_like(&temp, &path, text.as_bytes()) {
+ let _ = std::fs::remove_file(&temp);
+ return Err(format!("write failed: {err}"));
+ }
if let Err(err) = std::fs::rename(&temp, &path) {
let _ = std::fs::remove_file(&temp);
return Err(format!("write failed: {err}"));
@@ -295,6 +319,32 @@ pub fn write(install: bool, fingerprint: &str) -> Result<String, String> {
Ok(backup.to_string_lossy().to_string())
}
+/// Writes `bytes` to `temp`, which is about to replace `original`.
+///
+/// On Linux a fresh file would get the umask's 0644, and settings.json can hold
+/// API keys in its `env` block: the new file is created readable by us only,
+/// then given the original's permissions, so the rename never widens them.
+fn write_like(temp: &Path, original: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ use std::io::Write;
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
+ let mut file = options.open(temp)?;
+ file.write_all(bytes)?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = std::fs::metadata(original)
+ .map(|m| m.permissions().mode() & 0o777)
+ .unwrap_or(0o600);
+ file.set_permissions(std::fs::Permissions::from_mode(mode))?;
+ }
+ #[cfg(not(unix))]
+ let _ = original;
+ Ok(())
+}
+
/// Copies the relay (coucou-hook.exe / coucou-hook) into the local data dir's
/// bin/ on launch. In a bundled install it comes from the app resources; in
/// `tauri dev` it sits next to the app binary in the workspace target directory.
@@ -307,7 +357,10 @@ pub fn write(install: bool, fingerprint: &str) -> Result<String, String> {
pub fn ensure_hook_exe(app: &AppHandle) {
let dest = settings::hook_exe_path();
let Some(dir) = dest.parent() else { return };
- if std::fs::create_dir_all(dir).is_err() {
+ // Nobody else may swap the relay Claude Code runs: its folder is ours only.
+ if platform::ensure_private_dir(&settings::local_dir()).is_err()
+ || std::fs::create_dir_all(dir).is_err()
+ {
return;
}
@@ -335,8 +388,12 @@ pub fn ensure_hook_exe(app: &AppHandle) {
));
return;
};
+ install_relay(&src, &dest);
+}
- let same = match (std::fs::metadata(&src), std::fs::metadata(&dest)) {
+#[cfg(windows)]
+fn install_relay(src: &Path, dest: &Path) {
+ let same = match (std::fs::metadata(src), std::fs::metadata(dest)) {
(Ok(a), Ok(b)) => a.len() == b.len() && a.modified().ok() == b.modified().ok(),
_ => false,
};
@@ -345,13 +402,33 @@ pub fn ensure_hook_exe(app: &AppHandle) {
}
// A hook may be running right now and hold the file open; keeping the old
// copy is fine, it is the same relay.
- if let Err(err) = std::fs::copy(&src, &dest) {
+ if let Err(err) = std::fs::copy(src, dest) {
if !dest.exists() {
crate::log::line(format!("could not install {}: {err}", platform::HOOK_EXE));
}
}
}
+/// Linux does not keep the modification time on copy, so the contents decide.
+/// The new relay is written beside the old one and renamed over it: a hook
+/// starting at that moment runs either the old relay or the new one, never half
+/// of one, and a relay that is running right now does not block the update.
+#[cfg(unix)]
+fn install_relay(src: &Path, dest: &Path) {
+ use std::os::unix::fs::PermissionsExt;
+ if matches!((std::fs::read(src), std::fs::read(dest)), (Ok(a), Ok(b)) if a == b) {
+ return;
+ }
+ let temp = dest.with_extension(format!("new-{}", std::process::id()));
+ let result = std::fs::copy(src, &temp)
+ .and_then(|_| std::fs::set_permissions(&temp, std::fs::Permissions::from_mode(0o755)))
+ .and_then(|_| std::fs::rename(&temp, dest));
+ if let Err(err) = result {
+ let _ = std::fs::remove_file(&temp);
+ crate::log::line(format!("could not install {}: {err}", platform::HOOK_EXE));
+ }
+}
+
// ── Minimal unified diff (LCS) ────────────────────────────────────────────────
/// settings.json is short, so a plain O(n·m) LCS is the simplest honest diff.
@@ -504,6 +581,46 @@ mod tests {
assert_ne!(fingerprint(b""), fingerprint(b"{}"));
}
+ #[cfg(unix)]
+ #[test]
+ fn the_hook_path_is_one_shell_word_whatever_it_contains() {
+ assert_eq!(sh_quote("/home/a b/x"), "'/home/a b/x'");
+ // $, backticks, backslashes and double quotes stay literal in single quotes.
+ assert_eq!(sh_quote(r#"/h/$(id)`x`\"y"#), r#"'/h/$(id)`x`\"y'"#);
+ // A single quote closes, escapes and reopens.
+ assert_eq!(sh_quote("/h/it's"), r"'/h/it'\''s'");
+ }
+
+ /// settings.json can carry API keys in its `env` block: rewriting it must
+ /// never make it readable by more people than before.
+ #[cfg(unix)]
+ #[test]
+ fn rewriting_settings_never_widens_its_permissions() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = std::env::temp_dir().join(format!("coucou-perm-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let original = dir.join("settings.json");
+ let temp = dir.join("settings.json.new");
+ let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
+
+ for wanted in [0o600, 0o640, 0o644] {
+ std::fs::write(&original, b"{}").unwrap();
+ std::fs::set_permissions(&original, std::fs::Permissions::from_mode(wanted)).unwrap();
+ let _ = std::fs::remove_file(&temp);
+ write_like(&temp, &original, b"{\"a\":1}").unwrap();
+ assert_eq!(mode(&temp), wanted, "the rewrite must keep {wanted:o}");
+ }
+
+ // No original: ours only.
+ std::fs::remove_file(&original).unwrap();
+ let _ = std::fs::remove_file(&temp);
+ write_like(&temp, &original, b"{}").unwrap();
+ assert_eq!(mode(&temp), 0o600);
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
/// Everything filesystem-shaped lives in one test on purpose: it points
/// the home directory at a temp directory, and that is process-wide.
#[test]
diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs
index 2c1248e9..714103e5 100644
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@ -140,16 +140,26 @@ fn open_in_vscode(path: Option<String>) -> bool {
// whoever is using Claude Code, and a shell would happily read `&`, `^`, `%`
// or `$` in a folder name as syntax. Finding the launcher ourselves and
// handing the path over as a separate argument keeps it a path.
+ let path = path.filter(|p| !p.is_empty());
+ // It arrives in a hook payload: only an existing folder, given by its full
+ // path, goes any further. `code` would read `--something` as an option, and
+ // xdg-open would launch a file with whatever handles its type.
+ if let Some(p) = path.as_deref() {
+ let p = std::path::Path::new(p);
+ if !(p.is_absolute() && p.is_dir()) {
+ return false;
+ }
+ }
if let Some(code) = platform::find_on_path("code") {
let mut cmd = Command::new(code);
- if let Some(p) = path.as_deref().filter(|p| !p.is_empty()) {
+ if let Some(p) = path.as_deref() {
cmd.arg(p);
}
if platform::no_console(&mut cmd).spawn().is_ok() {
return true;
}
}
- if let Some(p) = path.as_deref().filter(|p| !p.is_empty()) {
+ if let Some(p) = path.as_deref() {
platform::reveal_folder(p);
}
false
diff --git a/windows/src-tauri/src/log.rs b/windows/src-tauri/src/log.rs
index d618165e..4fe787fd 100644
--- a/windows/src-tauri/src/log.rs
+++ b/windows/src-tauri/src/log.rs
@@ -13,7 +13,7 @@ pub fn line(message: impl AsRef<str>) {
t.year, t.month, t.day, t.hour, t.minute, t.second
);
let dir = settings::local_dir();
- if std::fs::create_dir_all(&dir).is_err() {
+ if platform::ensure_private_dir(&dir).is_err() {
return;
}
let path = dir.join("coucou.log");
@@ -21,7 +21,12 @@ pub fn line(message: impl AsRef<str>) {
if std::fs::metadata(&path).map(|m| m.len() > 1_000_000).unwrap_or(false) {
let _ = std::fs::remove_file(&path);
}
- if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
+ let mut options = std::fs::OpenOptions::new();
+ options.create(true).append(true);
+ // Readable by us only, like the macOS log.
+ #[cfg(unix)]
+ std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
+ if let Ok(mut file) = options.open(path) {
let _ = writeln!(file, "{stamp} {}", message.as_ref());
}
}
diff --git a/windows/src-tauri/src/pipe.rs b/windows/src-tauri/src/pipe.rs
index ab8480b0..36b6316c 100644
--- a/windows/src-tauri/src/pipe.rs
+++ b/windows/src-tauri/src/pipe.rs
@@ -106,7 +106,7 @@ pub fn start(app: AppHandle) {
tauri::async_runtime::spawn(async move {
let Some(path) = crate::platform::relay_socket_path() else {
- log::line("no runtime directory — Claude Code hooks are inactive");
+ log::line("no private runtime directory ($XDG_RUNTIME_DIR) — Claude Code hooks are inactive");
return;
};
// A socket file left behind by a crash answers nothing and can go. One
diff --git a/windows/src-tauri/src/platform/linux.rs b/windows/src-tauri/src/platform/linux.rs
index df43f47f..020d4214 100644
--- a/windows/src-tauri/src/platform/linux.rs
+++ b/windows/src-tauri/src/platform/linux.rs
@@ -11,7 +11,7 @@
// the island — Mochi's eyes follow the pointer there, not across the screen.
use std::os::unix::fs::PermissionsExt;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
@@ -85,18 +85,38 @@ pub fn local_time() -> LocalTime {
}
}
+/// Creates `dir` and closes it to other users. The log, the inbox of dropped
+/// files and the relay binary live under these directories; with the default
+/// umask they would come out 0755 and readable by anyone on the machine.
+pub fn ensure_private_dir(dir: &Path) -> std::io::Result<()> {
+ std::fs::create_dir_all(dir)?;
+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
+}
+
+/// True when `dir` is a real directory (not a symlink), owned by us, with no
+/// access for group or others: what `$XDG_RUNTIME_DIR` promises, checked
+/// rather than assumed, since the socket in it decides who can answer a
+/// permission request.
+fn is_private_dir(dir: &Path) -> bool {
+ use std::os::unix::fs::MetadataExt;
+ std::fs::symlink_metadata(dir)
+ .map(|m| {
+ m.file_type().is_dir() && m.uid() == unsafe { libc::getuid() } && m.mode() & 0o077 == 0
+ })
+ .unwrap_or(false)
+}
+
/// Where coucou-hook finds us: `$XDG_RUNTIME_DIR/coucou.sock`, or
-/// `/run/user/<uid>/coucou.sock` when the variable is missing. Must match
-/// `socket_path()` in hook/src/unix.rs exactly.
+/// `/run/user/<uid>/coucou.sock` when the variable is missing. A directory
+/// that is not ours and private means no relay at all — never a fallback to a
+/// shared place like /tmp. Must match `socket_path()` in hook/src/unix.rs
+/// exactly.
pub fn relay_socket_path() -> Option<PathBuf> {
let dir = std::env::var_os("XDG_RUNTIME_DIR")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
- .or_else(|| {
- let p = PathBuf::from(format!("/run/user/{}", unsafe { libc::getuid() }));
- p.is_dir().then_some(p)
- })?;
- Some(dir.join("coucou.sock"))
+ .unwrap_or_else(|| PathBuf::from(format!("/run/user/{}", unsafe { libc::getuid() })));
+ is_private_dir(&dir).then(|| dir.join("coucou.sock"))
}
// ── Processes ─────────────────────────────────────────────────────────────────
@@ -278,3 +298,49 @@ fn apply_input_region(gw: &impl IsA<gtk::Widget>, rect: Region) {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_a_private_directory_of_ours_can_hold_the_relay_socket() {
+ let base = std::env::temp_dir().join(format!("coucou-rt-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&base);
+ let dir = base.join("runtime");
+ std::fs::create_dir_all(&dir).unwrap();
+ let set = |mode| std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(mode)).unwrap();
+
+ set(0o700);
+ assert!(is_private_dir(&dir));
+
+ // Readable or reachable by group or others: no.
+ for open in [0o750, 0o705, 0o755, 0o777, 0o1777] {
+ set(open);
+ assert!(!is_private_dir(&dir), "{open:o} must be refused");
+ }
+
+ // A symlink to a private directory: no, the link itself is what we got.
+ set(0o700);
+ let link = base.join("link");
+ std::os::unix::fs::symlink(&dir, &link).unwrap();
+ assert!(!is_private_dir(&link));
+
+ // Missing: no.
+ assert!(!is_private_dir(&base.join("missing")));
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn private_dirs_are_closed_to_everyone_else() {
+ use std::os::unix::fs::MetadataExt;
+ let dir = std::env::temp_dir().join(format!("coucou-priv-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
+ ensure_private_dir(&dir).unwrap();
+ assert_eq!(std::fs::metadata(&dir).unwrap().mode() & 0o777, 0o700);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/windows/src-tauri/src/platform/windows.rs b/windows/src-tauri/src/platform/windows.rs
index ae2279d4..6e1200a8 100644
--- a/windows/src-tauri/src/platform/windows.rs
+++ b/windows/src-tauri/src/platform/windows.rs
@@ -49,6 +49,11 @@ pub fn local_dir() -> PathBuf {
base.join("Coucou")
}
+/// %APPDATA% and %LOCALAPPDATA% are already private to the user.
+pub fn ensure_private_dir(dir: &std::path::Path) -> std::io::Result<()> {
+ std::fs::create_dir_all(dir)
+}
+
/// Nothing to set up before the webview starts.
pub fn prepare_environment() {}
diff --git a/windows/src-tauri/src/settings.rs b/windows/src-tauri/src/settings.rs
index effac511..2a8d7d35 100644
--- a/windows/src-tauri/src/settings.rs
+++ b/windows/src-tauri/src/settings.rs
@@ -66,7 +66,7 @@ pub fn load() -> Settings {
pub fn save(settings: &Settings) -> std::io::Result<()> {
let dir = config_dir();
- std::fs::create_dir_all(&dir)?;
+ crate::platform::ensure_private_dir(&dir)?;
let json = serde_json::to_vec_pretty(settings)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
std::fs::write(settings_path(), json)
diff --git a/windows/src-tauri/tauri.linux.conf.json b/windows/src-tauri/tauri.linux.conf.json
index 8afd0ba7..d2b5531f 100644
--- a/windows/src-tauri/tauri.linux.conf.json
+++ b/windows/src-tauri/tauri.linux.conf.json
@@ -16,7 +16,7 @@
},
"deb": {
"depends": [
- "libgtk-layer-shell0"
+ "libgtk-layer-shell0 (>= 0.6)"
]
},
"rpm": {