Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(linux): verify the Secret Service store and the app channel on Linux

Alan Buscaglia837a42d60fa2
diff --git a/README.md b/README.md
index 7aec5a2..c2669ac 100644
--- a/README.md
+++ b/README.md
@@ -151,7 +151,7 @@ A small Node daemon starts the agent engine (Gentle Shell, `gentle-shell --mode
What already holds: computer control's grant, panic stop, blocklist, rate limit, and risky-action confirmations are enforced by the desktop app, not the agent, and the agent's processes do not inherit the app's macOS permissions. Connectors are reached only through the assistant's own proxy, which hides what their mode does not allow, and that holds for its subagents too: they are back on, reach connectors through the same proxy and approvals, and run with the same file checks as the assistant (set `GENTLE_DOT_SUBAGENTS=off` to turn them off). Approving a connector's action and changing a connector (its mode, connecting, removing, importing) happen only in the desktop app that started the assistant, in native dialogs, over a private channel the agent cannot open; in the browser those controls are read-only. Credentials are typed in the app, never in the chat. On macOS, connector tokens, client secrets, and sign-ins live in the Keychain, in items the signed app creates, and reach the assistant only in memory over that private channel; they are never written to a file, and tokens from older versions move there once. Without the app, connectors that need a token stop working instead of falling back to a file. The connector settings file is signed with a key kept in the Keychain: if anything changes it while Gentle Dot is closed, the app sets it aside at the next start, starts with no connectors, and tells you.
-What does not yet: the agent has a shell, and its shell commands (and its subagents') are checked on a best-effort basis only. Started without the app (from a terminal, or in the browser-only setup), the assistant cannot check that signature and loads the settings as they are, with token-based connectors locked. The app cannot yet tell its own Keychain items from ones another program of yours planted. On Linux, tokens go to the system keyring, which any program of yours can read while it is unlocked, and that path is not yet verified on a Linux desktop.
+What does not yet: the agent has a shell, and its shell commands (and its subagents') are checked on a best-effort basis only. Started without the app (from a terminal, or in the browser-only setup), the assistant cannot check that signature and loads the settings as they are, with token-based connectors locked. The app cannot yet tell its own Keychain items from ones another program of yours planted. On Linux, connector secrets live in your desktop keyring (Secret Service); while it is unlocked, any program running as you, the assistant's shell included, can read them. See [docs/install.md](docs/install.md).
<div align="right"><a href="#top">Back to top</a></div>
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock
index 80086f8..af698da 100644
--- a/apps/desktop/src-tauri/Cargo.lock
+++ b/apps/desktop/src-tauri/Cargo.lock
@@ -1408,6 +1408,7 @@ dependencies = [
"block2",
"bzip2 0.6.1",
"core-foundation",
+ "dbus",
"dbus-secret-service",
"getrandom 0.3.4",
"image",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index c733b8c..dd21608 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -59,6 +59,10 @@ core-foundation = "0.10"
[target.'cfg(target_os = "linux")'.dependencies]
dbus-secret-service = "4.1"
+# The store's tests build D-Bus errors (the same `dbus` that dbus-secret-service uses).
+[target.'cfg(target_os = "linux")'.dev-dependencies]
+dbus = "0.9"
+
# Debug builds encode screenshots fast too (S24.8): `image` holds the JPEG encoder and `zune-*`
# decode JPEGs (tests). The encoder is generic, so most of its code is compiled in this crate,
# which gets opt-level 1 as well (measured on a 1280 × 800 encode: 200 ms unoptimized, 126 ms
diff --git a/apps/desktop/src-tauri/src/daemon.rs b/apps/desktop/src-tauri/src/daemon.rs
index 5e7a287..409bc04 100644
--- a/apps/desktop/src-tauri/src/daemon.rs
+++ b/apps/desktop/src-tauri/src/daemon.rs
@@ -316,6 +316,11 @@ fn spawn_daemon(spec: &LaunchSpec, log: File, channel: Option<BorrowedFd<'_>>) -
Ok(Box::new(child))
}
+/// As on macOS, the daemon gets stdio and `channel` on fd 3 and no other descriptor of the app:
+/// everything from fd 3 up (fd 4 up with a channel) is marked close-on-exec in the child, so a
+/// descriptor some library of the app opened without close-on-exec never reaches the daemon. Node
+/// then marks fd 3 close-on-exec at its own startup (libuv's `uv_disable_stdio_inheritance`), so
+/// the daemon's children never get it either (`app-channel.ts` `childInherits` checks that).
#[cfg(not(target_os = "macos"))]
fn spawn_daemon(spec: &LaunchSpec, log: File, channel: Option<BorrowedFd<'_>>) -> io::Result<Box<dyn ChildProcess>> {
use std::os::fd::AsRawFd;
@@ -328,22 +333,52 @@ fn spawn_daemon(spec: &LaunchSpec, log: File, channel: Option<BorrowedFd<'_>>) -
.stdin(Stdio::null())
.stdout(log.try_clone()?)
.stderr(log);
- if let Some(fd) = channel.map(|fd| fd.as_raw_fd()) {
- // SAFETY: runs in the child between fork and exec and only calls dup2, which is
- // async-signal-safe. `fd` is above APP_FD (channel_pair), so dup2 makes a new fd 3
- // without close-on-exec, while the original closes at exec.
- unsafe {
- command.pre_exec(move || {
+ let channel = channel.map(|fd| fd.as_raw_fd());
+ // SAFETY: runs in the child between fork and exec and only makes system calls (dup2, fcntl,
+ // close_range, getrlimit), which are async-signal-safe; nothing allocates. `fd` is above
+ // APP_FD (channel_pair), so dup2 makes a new fd 3 without close-on-exec, while the original
+ // closes at exec.
+ unsafe {
+ command.pre_exec(move || {
+ if let Some(fd) = channel {
if libc::dup2(fd, APP_FD) == -1 {
return Err(io::Error::last_os_error());
}
- Ok(())
- });
- }
+ }
+ let first = if channel.is_some() { APP_FD + 1 } else { APP_FD };
+ cloexec_from(first);
+ Ok(())
+ });
}
Ok(Box::new(command.spawn()?))
}
+/// Marks every descriptor from `first` up close-on-exec. Called between fork and exec: system
+/// calls only.
+#[cfg(not(target_os = "macos"))]
+fn cloexec_from(first: libc::c_int) {
+ #[cfg(target_os = "linux")]
+ if let Ok(low) = libc::c_uint::try_from(first) {
+ // SAFETY: close_range(2) with CLOSE_RANGE_CLOEXEC (Linux 5.11) only changes descriptor flags.
+ if unsafe { libc::syscall(libc::SYS_close_range, low, libc::c_uint::MAX, libc::CLOSE_RANGE_CLOEXEC) } == 0 {
+ return;
+ }
+ }
+ // An older kernel: every descriptor up to the limit, one by one.
+ // SAFETY: an all-zero rlimit is valid, and getrlimit writes only into it.
+ let mut limit: libc::rlimit = unsafe { std::mem::zeroed() };
+ // SAFETY: a valid out-pointer.
+ let top = if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } == 0 {
+ libc::c_int::try_from(limit.rlim_cur.min(1 << 20)).unwrap_or(1 << 20)
+ } else {
+ 1 << 16
+ };
+ for fd in first..top {
+ // SAFETY: F_SETFD on a descriptor number; one that is not open fails with EBADF, harmlessly.
+ unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) };
+ }
+}
+
/// Sends SIGTERM, waits up to `grace` for a clean exit, then kills.
pub fn stop_child(child: &mut dyn ChildProcess, grace: Duration) {
if !matches!(child.try_wait(), Ok(None)) {
@@ -787,7 +822,6 @@ IFS= read -r line <&3; printf '%s %s\\n' \"$kind\" \"$line\" >&3";
assert!(daemon_end.as_raw_fd() > APP_FD, "{}", daemon_end.as_raw_fd());
}
- #[cfg(target_os = "macos")]
#[test]
fn without_a_channel_fd_3_is_closed_in_the_daemon() {
let dir = scratch_dir("channel-none");
@@ -797,6 +831,65 @@ IFS= read -r line <&3; printf '%s %s\\n' \"$kind\" \"$line\" >&3";
assert_eq!(fs::read_to_string(dir.join("daemon.log")).unwrap(), "none\n");
}
+ #[test]
+ fn no_other_descriptor_of_the_app_reaches_the_daemon() {
+ let dir = scratch_dir("channel-only");
+ let log = open_private_log(&dir).unwrap();
+ // A descriptor some library opened without close-on-exec (F_DUPFD leaves the flag clear).
+ // SAFETY: duplicating a descriptor we own; the copy is owned by `stray`.
+ let stray = unsafe { OwnedFd::from_raw_fd(libc::fcntl(log.as_raw_fd(), libc::F_DUPFD, 60)) };
+ assert!(stray.as_raw_fd() >= 60);
+ let (_app, daemon_end) = channel_pair().unwrap();
+ let script = format!(
+ "if [ -S /dev/fd/3 ]; then echo channel; fi; if [ -e /dev/fd/{} ]; then echo leaked; else echo closed; fi",
+ stray.as_raw_fd()
+ );
+ let mut child = spawn_daemon(&sh_spec(&script), log, Some(daemon_end.as_fd())).unwrap();
+ assert!(child.wait().unwrap().success());
+ assert_eq!(fs::read_to_string(dir.join("daemon.log")).unwrap(), "channel\nclosed\n");
+ }
+
+ /// The real thing on this platform: the app's spawn hands fd 3 to Node running the daemon's
+ /// stand-in (packages/daemon/test/fixtures/app-channel-child.ts), which opens the channel the way
+ /// the daemon does and reports what the children it spawns see on fd 3. Needs Node 24 on PATH
+ /// (or `GENTLE_DOT_TEST_NODE`): `cargo test a_node_daemon -- --ignored`.
+ #[test]
+ #[ignore = "needs Node 24 and the repository's daemon sources"]
+ fn a_node_daemon_keeps_the_channel_from_its_children() {
+ use std::os::unix::fs::MetadataExt;
+ let dir = scratch_dir("channel-node");
+ let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../packages/daemon/test/fixtures/app-channel-child.ts");
+ let node = std::env::var("GENTLE_DOT_TEST_NODE").unwrap_or_else(|_| "node".into());
+ let path = std::env::var("PATH").unwrap_or_default();
+ let spec = LaunchSpec {
+ program: node,
+ args: vec![fixture.to_string_lossy().into_owned()],
+ envs: vec![("PATH".into(), path)],
+ };
+ let (app, daemon_end) = channel_pair().unwrap();
+ let own = File::from(daemon_end.try_clone().unwrap()).metadata().unwrap();
+ // Node shows `dev` signed (macOS's dev_t is an i32 and a socket's is -1).
+ let identity = format!("{}:{}", own.dev() as i64, own.ino());
+ let mut child = spawn_daemon(&spec, open_private_log(&dir).unwrap(), Some(daemon_end.as_fd())).unwrap();
+ drop(daemon_end);
+ app.set_read_timeout(Some(Duration::from_secs(30))).unwrap();
+ let mut line = String::new();
+ BufReader::new(&app).read_line(&mut line).unwrap();
+ let log = || fs::read_to_string(dir.join("daemon.log")).unwrap_or_default();
+ let frame: serde_json::Value = serde_json::from_str(&line).unwrap_or_else(|_| panic!("no report: {line:?} {}", log()));
+ assert_eq!(frame["method"], "report", "{frame} {}", log());
+ (&app).write_all(format!("{{\"kind\":\"response\",\"id\":{},\"result\":{{}}}}\n", frame["id"]).as_bytes()).unwrap();
+ assert!(child.wait().unwrap().success(), "{}", log());
+ let report = &frame["params"];
+ // The daemon holds the socket this app handed over; none of its children does.
+ assert_eq!(report["identity"], identity.as_str(), "{report}");
+ assert_ne!(report["fromSpawn"], identity.as_str(), "{report}");
+ assert_ne!(report["fromSpawnSync"], identity.as_str(), "{report}");
+ assert_eq!(report["fromShell"], "none", "{report}");
+ // And the daemon's startup probe would have seen a leak, had there been one.
+ assert_eq!(report["detectsALeak"], true, "{report}");
+ }
+
#[derive(Default)]
struct Opened(Mutex<usize>);
diff --git a/apps/desktop/src-tauri/src/secure_store/linux.rs b/apps/desktop/src-tauri/src/secure_store/linux.rs
index 9840552..3effc33 100644
--- a/apps/desktop/src-tauri/src/secure_store/linux.rs
+++ b/apps/desktop/src-tauri/src/secure_store/linux.rs
@@ -1,21 +1,28 @@
//! Connector secrets in the Secret Service (S25.7), over D-Bus: GNOME Keyring on Debian and
//! Ubuntu, KWallet or GNOME Keyring elsewhere. Items carry the attributes `service` =
-//! [`SERVICE`](super::SERVICE) and `account` = the secret id.
+//! [`SERVICE`](super::SERVICE) and `account` = the secret id, in the default collection (the login
+//! keyring).
//!
-//! Documented limit (S25.7): the Secret Service has no per-caller access list, so any process of
-//! the same user can read items while the collection is unlocked (usually the whole session).
-//! Items are encrypted at rest. The session uses the plain transfer (the secret crosses the
-//! local session bus unencrypted), since every same-user process can read it anyway.
+//! Documented limit (S25.7, docs/install.md): the Secret Service has no per-caller access list, so
+//! any process of the same user can read items while the collection is unlocked (usually the whole
+//! session). Items are encrypted at rest. The session uses the plain transfer (the secret crosses
+//! the local session bus unencrypted), since every same-user process can read it anyway.
//!
-//! Not compiled on the macOS development machine (no Linux target installed); T23g verifies it
-//! in a Linux container.
+//! Without a Secret Service (no session bus, or no provider on it) every call fails with
+//! [`StoreError::Unavailable`] naming what is missing, so connectors that need a secret fail closed.
+//! A locked collection asks the provider to show its unlock prompt and waits at most
+//! [`PROMPT_TIMEOUT_SECS`]; dismissed or unanswered, the call is [`StoreError::Denied`].
use super::{check_id, wipe, Secret, SecretStore, StoreError, SERVICE};
use dbus_secret_service::{EncryptionType, Error, Item, SecretService};
use std::collections::HashMap;
+/// How long a call waits on the provider's unlock prompt, below the daemon's wait for an answer.
+pub const PROMPT_TIMEOUT_SECS: u64 = 120;
+
pub struct SecretServiceStore {
service: String,
+ prompt_timeout: u64,
}
impl SecretServiceStore {
@@ -24,11 +31,15 @@ impl SecretServiceStore {
}
pub fn with_service(service: impl Into<String>) -> Self {
- SecretServiceStore { service: service.into() }
+ SecretServiceStore { service: service.into(), prompt_timeout: PROMPT_TIMEOUT_SECS }
}
- fn connect() -> Result<SecretService, StoreError> {
- SecretService::connect(EncryptionType::Plain).map_err(store_error)
+ fn connect(&self) -> Result<SecretService, StoreError> {
+ SecretService::connect_with_max_prompt_timeout(EncryptionType::Plain, self.prompt_timeout).map_err(|error| {
+ StoreError::Unavailable(format!(
+ "no Secret Service in this desktop session ({error}); install and unlock a keyring such as GNOME Keyring or KWallet"
+ ))
+ })
}
fn attributes<'a>(&'a self, id: &'a str) -> HashMap<&'a str, &'a str> {
@@ -48,10 +59,21 @@ impl std::fmt::Debug for SecretServiceStore {
}
}
+/// D-Bus errors that mean the provider went away or never was there.
+const GONE: [&str; 4] = [
+ "org.freedesktop.DBus.Error.ServiceUnknown",
+ "org.freedesktop.DBus.Error.NameHasNoOwner",
+ "org.freedesktop.DBus.Error.NoServer",
+ "org.freedesktop.DBus.Error.Disconnected",
+];
+
fn store_error(error: Error) -> StoreError {
match error {
Error::Locked | Error::Prompt => StoreError::Denied,
Error::Unavailable => StoreError::Unavailable("no Secret Service on the session bus".into()),
+ Error::Dbus(ref dbus) if dbus.name().is_some_and(|name| GONE.contains(&name)) => {
+ StoreError::Unavailable(format!("the Secret Service stopped answering ({error})"))
+ }
other => StoreError::Failed(other.to_string()),
}
}
@@ -65,8 +87,13 @@ fn matching<'a>(ss: &'a SecretService, attributes: HashMap<&str, &str>) -> Resul
impl SecretStore for SecretServiceStore {
fn put(&self, id: &str, secret: &Secret) -> Result<(), StoreError> {
check_id(id)?;
- let ss = Self::connect()?;
- let collection = ss.get_default_collection().map_err(store_error)?;
+ let ss = self.connect()?;
+ let collection = ss.get_default_collection().map_err(|error| match error {
+ Error::NoResult => StoreError::Unavailable(
+ "the Secret Service has no default keyring; create one (for example the login keyring in Passwords and Keys)".into(),
+ ),
+ other => store_error(other),
+ })?;
collection.ensure_unlocked().map_err(store_error)?;
let label = format!("Gentle Dot connector: {id}");
collection
@@ -77,7 +104,7 @@ impl SecretStore for SecretServiceStore {
fn get(&self, id: &str) -> Result<Option<Secret>, StoreError> {
check_id(id)?;
- let ss = Self::connect()?;
+ let ss = self.connect()?;
let Some(item) = matching(&ss, self.attributes(id))?.into_iter().next() else {
return Ok(None);
};
@@ -94,7 +121,7 @@ impl SecretStore for SecretServiceStore {
fn delete(&self, id: &str) -> Result<bool, StoreError> {
check_id(id)?;
- let ss = Self::connect()?;
+ let ss = self.connect()?;
let items = matching(&ss, self.attributes(id))?;
for item in &items {
item.delete().map_err(store_error)?;
@@ -103,7 +130,7 @@ impl SecretStore for SecretServiceStore {
}
fn list_ids(&self) -> Result<Vec<String>, StoreError> {
- let ss = Self::connect()?;
+ let ss = self.connect()?;
let items = matching(&ss, HashMap::from([("service", self.service.as_str())]))?;
let mut ids = Vec::new();
for item in &items {
@@ -116,3 +143,101 @@ impl SecretStore for SecretServiceStore {
Ok(ids)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::{Duration, Instant};
+
+ fn throwaway() -> SecretServiceStore {
+ let mut random = [0u8; 8];
+ getrandom::fill(&mut random).unwrap();
+ let suffix: String = random.iter().map(|b| format!("{b:02x}")).collect();
+ SecretServiceStore::with_service(format!("dev.gentleman.gentle-dot.test.{suffix}"))
+ }
+
+ #[test]
+ fn the_store_shows_its_service_only() {
+ assert_eq!(
+ format!("{:?}", SecretServiceStore::new()),
+ "SecretServiceStore { service: \"dev.gentleman.gentle-dot.connectors\" }"
+ );
+ }
+
+ #[test]
+ fn secret_service_errors_map_to_denied_unavailable_or_failed() {
+ assert_eq!(store_error(Error::Locked), StoreError::Denied);
+ assert_eq!(store_error(Error::Prompt), StoreError::Denied);
+ assert!(matches!(store_error(Error::Unavailable), StoreError::Unavailable(_)));
+ for gone in GONE {
+ let error = Error::Dbus(dbus::Error::new_custom(gone, "the provider quit"));
+ assert!(matches!(store_error(error), StoreError::Unavailable(_)), "{gone}");
+ }
+ let other = Error::Dbus(dbus::Error::new_custom("org.freedesktop.Secret.Error.NoSuchObject", "gone"));
+ assert!(matches!(store_error(other), StoreError::Failed(_)));
+ }
+
+ /// Run by `docker/linux-package/cargo-check.sh` with no session bus, and with a bus that has no
+ /// provider: every call fails closed, saying what is missing.
+ #[test]
+ #[ignore = "needs a session without a Secret Service"]
+ fn without_a_secret_service_the_store_is_unavailable() {
+ let store = throwaway();
+ let errors = [
+ store.put("connector/x/value/token", &Secret::new("s")).unwrap_err(),
+ store.get("connector/x/value/token").unwrap_err(),
+ store.delete("connector/x/value/token").unwrap_err(),
+ store.list_ids().unwrap_err(),
+ ];
+ for error in errors {
+ let StoreError::Unavailable(ref why) = error else { panic!("{error:?}") };
+ assert!(why.starts_with("no Secret Service in this desktop session ("), "{why}");
+ assert!(why.ends_with("install and unlock a keyring such as GNOME Keyring or KWallet"), "{why}");
+ }
+ // What the daemon gets back over the app channel when it asks for a connector's secret.
+ let answer = crate::app_channel::serve_secret(&store, "secret_get", &serde_json::json!({"id": "connector/x/value/token"}));
+ let refusal = answer.unwrap_err();
+ assert!(refusal.starts_with("the secret store is unavailable: no Secret Service in this desktop session ("), "{refusal}");
+ eprintln!("the app answers secret_get with: {refusal}");
+ }
+
+ /// Touches a real, unlocked Secret Service under a throwaway service and removes what it
+ /// created; also shows the documented limit: another same-user client (`secret-tool`) reads the
+ /// item with no prompt. Run by `docker/linux-package/cargo-check.sh` against GNOME Keyring.
+ #[test]
+ #[ignore = "uses the session's Secret Service"]
+ fn real_secret_service_keeps_the_contract_under_a_throwaway_service() {
+ let store = throwaway();
+ let outcome = std::panic::catch_unwind(|| {
+ super::super::check_contract(&store);
+ store.put("limit/demo", &Secret::new("readable-by-the-same-user")).unwrap();
+ match std::process::Command::new("secret-tool")
+ .args(["lookup", "service", &store.service, "account", "limit/demo"])
+ .output()
+ {
+ Ok(output) => assert_eq!(String::from_utf8_lossy(&output.stdout), "readable-by-the-same-user"),
+ Err(error) => eprintln!("secret-tool not run ({error}); the same-user read is not shown"),
+ }
+ });
+ // Leave nothing behind, whatever happened.
+ for id in store.list_ids().unwrap_or_default() {
+ let _ = store.delete(&id);
+ }
+ assert!(store.list_ids().unwrap().is_empty());
+ if let Err(panic) = outcome {
+ std::panic::resume_unwind(panic);
+ }
+ }
+
+ /// Run by `docker/linux-package/cargo-check.sh` against a locked GNOME Keyring with no way to
+ /// show its unlock prompt: refused, within the prompt timeout.
+ #[test]
+ #[ignore = "needs a locked Secret Service"]
+ fn a_locked_keyring_is_refused_without_waiting_on_a_prompt() {
+ let mut store = throwaway();
+ store.prompt_timeout = 3;
+ let started = Instant::now();
+ assert_eq!(store.put("connector/x/value/token", &Secret::new("s")).unwrap_err(), StoreError::Denied);
+ assert!(started.elapsed() < Duration::from_secs(10), "{:?}", started.elapsed());
+ }
+}
diff --git a/docker/linux-package/Dockerfile.check b/docker/linux-package/Dockerfile.check
new file mode 100644
index 0000000..4c41c44
--- /dev/null
+++ b/docker/linux-package/Dockerfile.check
@@ -0,0 +1,15 @@
+# The Linux checks of the desktop crate (S25.7): the package builder's toolchain plus a session
+# D-Bus and GNOME Keyring, so the Secret Service store runs against a real provider. The repository
+# is mounted read-only at /src and `cargo-check.sh` works on a copy. Driven by
+# scripts/package/linux-cargo-check.mjs:
+# docker build --platform linux/arm64 --build-arg BUILDER=gentle-dot-linux-builder:arm64 \
+# -f docker/linux-package/Dockerfile.check -t gentle-dot-linux-check:arm64 docker/linux-package
+ARG BUILDER=gentle-dot-linux-builder:arm64
+FROM ${BUILDER}
+
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends dbus dbus-bin gnome-keyring libsecret-tools \
+ && rm -rf /var/lib/apt/lists/*
+
+# The builder installs Rust with the minimal profile.
+RUN rustup component add clippy
diff --git a/docker/linux-package/cargo-check.sh b/docker/linux-package/cargo-check.sh
new file mode 100644
index 0000000..9d64e55
--- /dev/null
+++ b/docker/linux-package/cargo-check.sh
@@ -0,0 +1,94 @@
+#!/usr/bin/env bash
+# Runs inside gentle-dot-linux-check (see Dockerfile.check). Copies the working tree mounted at
+# /src and checks the desktop crate on Linux (S25.7):
+# 1. `cargo test` and `cargo clippy --all-targets -- -D warnings`;
+# 2. the Secret Service store against no session bus, a bus with no provider, GNOME Keyring
+# unlocked with a test password (the real put/get/delete contract under a throwaway service),
+# and the same keyring locked (refused, without waiting on a prompt nobody can answer);
+# 3. the app channel on Linux: the app's spawn hands fd 3 to a real Node daemon stand-in, whose
+# children never hold it (Rust test), and the daemon's own test of the same (vitest).
+set -euo pipefail
+
+step() { printf '\n==> %s (%s s)\n' "$1" "$SECONDS"; }
+
+step "Copying the working tree from /src (tracked and untracked files, minus .gitignore)"
+cd /src
+git ls-files -z --cached --others --exclude-standard -- . ':!:.codegraph' ':!:.atl' |
+ tar --null --files-from=- --ignore-failed-read -cf - 2>/dev/null | tar -xf - -C /work
+cd /work
+# tauri's generate_context! needs the frontend folder to exist; the tests never load it.
+mkdir -p packages/ui/dist/app
+[ -e packages/ui/dist/app/index.html ] || printf '<!doctype html>\n' >packages/ui/dist/app/index.html
+
+cd /work/apps/desktop/src-tauri
+step "cargo test"
+cargo test
+
+step "cargo clippy --all-targets -- -D warnings"
+cargo clippy --all-targets -- -D warnings
+
+# Each Secret Service case runs with a throwaway HOME and runtime folder, so no keyring outlives it.
+fresh_home() {
+ HOME=$(mktemp -d)
+ XDG_RUNTIME_DIR=$(mktemp -d)
+ chmod 700 "$XDG_RUNTIME_DIR"
+ export HOME XDG_RUNTIME_DIR
+ unset DISPLAY WAYLAND_DISPLAY
+}
+ignored() { cargo test --lib -- --ignored --nocapture --exact "$@"; }
+UNAVAILABLE=secure_store::linux::tests::without_a_secret_service_the_store_is_unavailable
+
+step "Secret Service: no session bus"
+(fresh_home && env -u DBUS_SESSION_BUS_ADDRESS cargo test --lib -- --ignored --nocapture --exact "$UNAVAILABLE")
+
+step "Secret Service: a session bus with no provider (no activatable services)"
+bus_config=$(mktemp)
+cat >"$bus_config" <<'EOF'
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+<busconfig>
+ <type>session</type>
+ <listen>unix:tmpdir=/tmp</listen>
+ <auth>EXTERNAL</auth>
+ <policy context="default">
+ <allow send_destination="*" eavesdrop="true"/>
+ <allow eavesdrop="true"/>
+ <allow own="*"/>
+ </policy>
+</busconfig>
+EOF
+(fresh_home && dbus-run-session --config-file="$bus_config" -- \
+ cargo test --lib -- --ignored --nocapture --exact "$UNAVAILABLE")
+
+step "Secret Service: GNOME Keyring unlocked with a test password, then locked"
+(
+ fresh_home
+ export -f ignored
+ dbus-run-session -- bash -euc '
+ printf "gentle-dot-test" | gnome-keyring-daemon --unlock --components=secrets >/dev/null
+ ignored secure_store::linux::tests::real_secret_service_keeps_the_contract_under_a_throwaway_service
+ # Encrypted at rest: a stored value never appears in the keyring files.
+ printf "at-rest-marker-7f3a" | secret-tool store --label=at-rest app gentle-dot-test
+ sleep 1
+ if grep -rq "at-rest-marker-7f3a" "$HOME/.local/share/keyrings"; then
+ echo "the keyring file holds the value in the clear" >&2
+ exit 1
+ fi
+ echo "at rest: $(ls "$HOME/.local/share/keyrings") hold no stored value in the clear"
+ secret-tool clear app gentle-dot-test
+ # The same keyring, locked: a put needs an unlock prompt that cannot be shown here.
+ gnome-keyring-daemon --replace --components=secrets >/dev/null 2>&1 </dev/null
+ sleep 1
+ ignored secure_store::linux::tests::a_locked_keyring_is_refused_without_waiting_on_a_prompt
+ '
+)
+
+step "App channel: a real Node daemon stand-in keeps fd 3 from its children (Rust spawn)"
+cargo test --lib -- --ignored --exact daemon::tests::a_node_daemon_keeps_the_channel_from_its_children
+
+step "App channel: the daemon's own fd 3 test (vitest)"
+cd /work
+pnpm install --frozen-lockfile --store-dir /pnpm-store >/dev/null
+pnpm exec vitest run packages/daemon/test/app-channel-fd.test.ts
+
+step "All Linux checks passed"
diff --git a/docs/design.md b/docs/design.md
index 5319333..d6f5b2c 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -148,12 +148,12 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete
- Integrity (S25.6, `packages/daemon/src/connector-integrity.ts`): every write of `connectors.json` (a change, a migration, a put-back) carries `mac`, the lowercase hex HMAC-SHA256 of the text `gentle-dot/connectors.json/v1\n` followed by the record without `mac` in canonical JSON (no whitespace; every object's keys sorted by UTF-16 code unit; arrays in order; strings, numbers, booleans, and null as `JSON.stringify` writes them). The key is 32 random bytes, kept as hex in the app's secure store under `integrity/connectors`, created on the first start with the app, and held only in memory; it is never written to a file or logged. At start the daemon listens (so the app's health check answers), then checks the file as it was read before anything rewrites it, watches it, migrates secrets, answers the app, or starts the engine. With the app: a file that was signed before (it has a `mac`, or the key already existed) whose `mac` is missing or wrong was changed while Gentle Dot was closed; it is moved to `<data>/connectors.rejected-<UTC time>.json` (0600; a planted link is moved as a link), the daemon starts with no connectors and a fresh signed record, the log says so once, and every window of that run gets the warning toast "Connectors were changed while Gentle Dot was closed, so they were set aside. Review them in Connectors." The Keychain items are not touched (a reference in the set-aside file is never read). The first start after T23e (an unsigned file and no key) creates the key and signs the file without refusing it. Without the app, the file cannot be checked: it is loaded as it is, the log says it was not verified, connectors that need a secret stay locked, and a signed file is put back byte for byte so its signature survives until a daemon the app launches checks it. With the app but a key that cannot be read or stored, the check fails closed: the file stays as it is, no secret is read, and every window gets "Gentle Dot could not check your connectors, so the ones that need a secret stay locked. Restart Gentle Dot to try again." A signed file deleted while Gentle Dot was closed (the key exists, the file is gone) starts with no connectors and every window gets "Your connectors file was removed while Gentle Dot was closed. Add your connectors again in Connectors." While running, a change is put back as before, signed. Limits: the signature has no counter, so putting back an older signed version of the file (for example one with a connector the user removed since) is accepted; sending actions still need the user's native approval. A same-user process that deletes the key's Keychain item and also removes `mac` makes the next start sign the file as a first start. A `connectors.json` written without the app (a migration rename of a `computer` entry) is unsigned and is refused at the next start with the app once the key exists; the key's Keychain item has the same limits as any other (§8).
- Sign-in (S25.5, `packages/daemon/src/connector-oauth.ts`) runs in the daemon with pi-mcp's OAuth, as the engine's `mcp login` did (the CLI is no longer run): a stored refresh token signs in again without the browser; otherwise the authorization code flow (PKCE, dynamic client registration or the user's own client) against a loopback callback (`127.0.0.1`, a random port, or the connector's fixed redirect such as Slack's `http://localhost:38417/callback`). The whole flow keeps its state in memory; only the result is stored, once, with `secret_put`, and a refresh after a 401 stores the new tokens the same way. The daemon relays the authorization URL to the window that started it (`auth_event` `auth_url`, which opens the browser) and offers a `manual_code` prompt: when the browser cannot reach the loopback callback, the user pastes the address it ended on, and the daemon takes the code from it only when it is this sign-in's loopback address (port and path) with its `state`; nothing is fetched. Cancel closes the callback. Flow ids start with `connector-`, so `auth_reply` reaches the right flow; typed text and codes are never logged (URLs are masked).
- Status: `needs_setup` while a typed value is missing; for servers that sign in with OAuth, `connected` when the connector refers to a stored sign-in with tokens and `needs_signin` otherwise; `connected` for servers with a token or none; `error` after a failed sign-in.
-- App channel (S25.1–S25.3, `packages/daemon/src/app-channel.ts`, `apps/desktop/src-tauri/src/app_channel.rs`): when the desktop app spawns the daemon it creates a connected pair of Unix sockets and puts one end on the daemon's fd 3 (posix_spawn `adddup2` on macOS, with `POSIX_SPAWN_CLOEXEC_DEFAULT` closing every other descriptor; a `pre_exec` `dup2` on Linux); it keeps the other. The connection is the authentication: nothing is written to a file or an environment variable, and nothing listens. The daemon (`cli.ts`) opens fd 3 before it spawns anything, only when it is a socket and not Node's own IPC channel, and first checks that a child spawned the daemon's way would not hold it (a probe child compares the socket's identity on its fd 3); if one would, it closes it and runs without a channel. On macOS, libuv spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so the engine, stdio servers, and sign-in commands never get it (`app-channel-fd.test.ts`); Node cannot mark an inherited descriptor close-on-exec, which is why the probe checks rather than assumes. Frames are line-delimited JSON (`{"kind":"request","id","method","params"}`, `{"kind":"response","id","result"|"error"}`), each side numbering its own requests. The app sends `command {clientId, message}`, `computer_register {url, token}`, and `computer_unregister`; the daemon sends `approve` with `{connector, action, preview: [{name, value}], title?, summary?}` and gets `{approved}`, and the secret requests `secret_get {id}` (`{secret}` or `null`), `secret_put {id, secret}`, `secret_delete {id}` (`{deleted}`), and `secret_list` (`{ids}`). The app answers on worker threads: approvals with T23b's `approvals` (one native dialog at a time, Decline the default, 120 s timeout), secrets from `secure_store` with ids checked (`check_id`), refusals that never repeat a value, and nothing logged; a malformed request, a dialog that fails, or the channel closing refuses. A frame longer than 1 MiB closes the channel on either side, and a closed channel stops the daemon (below), so neither side sends one: an oversized request fails before it is written (a daemon approval is then refused), and an oversized answer goes out as an error. Lifetime (S35.2): a daemon launched with a channel stops when it closes, as on SIGTERM (engine, memory, and the connectors' servers stopped, then the process exits), whether the app quit, crashed, or was killed, since the kernel closes the app's end in every case; it stops listening first, so a relaunched app starts a daemon of its own. A daemon started without a channel keeps running until it is stopped.
+- App channel (S25.1–S25.3, `packages/daemon/src/app-channel.ts`, `apps/desktop/src-tauri/src/app_channel.rs`): when the desktop app spawns the daemon it creates a connected pair of Unix sockets and puts one end on the daemon's fd 3 (posix_spawn `adddup2` on macOS, with `POSIX_SPAWN_CLOEXEC_DEFAULT` closing every other descriptor; on Linux a `pre_exec` `dup2` plus `close_range(CLOSE_RANGE_CLOEXEC)`, or an `fcntl` loop before kernel 5.11, marking every other descriptor close-on-exec); it keeps the other. The connection is the authentication: nothing is written to a file or an environment variable, and nothing listens. The daemon (`cli.ts`) opens fd 3 before it spawns anything, only when it is a socket and not Node's own IPC channel, and first checks that a child spawned the daemon's way would not hold it (a probe child compares the socket's identity on its fd 3); if one would, it closes it and runs without a channel. On macOS, libuv spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so the engine, stdio servers, and sign-in commands never get it (`app-channel-fd.test.ts`); on Linux, Node marks fds 0–15 close-on-exec at startup (libuv `uv_disable_stdio_inheritance`), fd 3 included, so no child of the daemon holds it either; Node cannot mark an inherited descriptor close-on-exec, which is why the probe checks rather than assumes. Frames are line-delimited JSON (`{"kind":"request","id","method","params"}`, `{"kind":"response","id","result"|"error"}`), each side numbering its own requests. The app sends `command {clientId, message}`, `computer_register {url, token}`, and `computer_unregister`; the daemon sends `approve` with `{connector, action, preview: [{name, value}], title?, summary?}` and gets `{approved}`, and the secret requests `secret_get {id}` (`{secret}` or `null`), `secret_put {id, secret}`, `secret_delete {id}` (`{deleted}`), and `secret_list` (`{ids}`). The app answers on worker threads: approvals with T23b's `approvals` (one native dialog at a time, Decline the default, 120 s timeout), secrets from `secure_store` with ids checked (`check_id`), refusals that never repeat a value, and nothing logged; a malformed request, a dialog that fails, or the channel closing refuses. A frame longer than 1 MiB closes the channel on either side, and a closed channel stops the daemon (below), so neither side sends one: an oversized request fails before it is written (a daemon approval is then refused), and an oversized answer goes out as an error. Lifetime (S35.2): a daemon launched with a channel stops when it closes, as on SIGTERM (engine, memory, and the connectors' servers stopped, then the process exits), whether the app quit, crashed, or was killed, since the kernel closes the app's end in every case; it stops listening first, so a relaunched app starts a daemon of its own. A daemon started without a channel keeps running until it is stopped.
- Privileged messages (S25.2, `APP_COMMANDS` in the protocol): `connector_connect`, `connector_signin`, `connector_setup`, `connector_disconnect`, `connector_remove`, `connector_mode`, `connector_draft_reply` approving, `connector_import`, `computer_register`, and `computer_unregister` are refused on the WebSocket (`error app_required`, "Open the Gentle Dot app to change connectors.") whoever sends them, the access key notwithstanding (L49). The desktop panel sends them with the `connector_command` Tauri command, which the app forwards over the channel with the panel's `clientId` (from `ready`; it only routes the sign-in steps and refusals to that window and authorizes nothing by itself). Every other message stays on the WebSocket: chat, history, accounts, profiles, models, uploads, `connectors_list`, `connectors_scan`, sign-in answers (`auth_reply`, owner-checked), and declining a draft. Changes that widen access are confirmed natively even though the app sent them: switching to "Read and send", connecting or setting up a connector that is off, approving a draft, and importing (each with what it adds); declining sends the window `error declined` and changes nothing. Narrowing (read only, disconnecting, removing) and signing in again need no dialog. Without a channel (a daemon started from a terminal such as `pnpm dev`, the web, a VPS until T23h) these messages and every approval fail closed. Approvals the daemon asks show in every window as an `ask` with `method: "app"` ("Waiting for your answer in the Gentle Dot app."); `ui_response` to it is refused.
- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): the tools of a connector the proxy fronts (`proxied` in the policy: turned on and set up) pass, since the proxy filters them and asks itself; a card here would ask twice. A turned-off connector is not in `proxied` or the approved list, so its tools stay blocked here as well. For any other connector tool: it runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm`: an ask card ("Allow Notion to create pages?") with every argument, key fields first, up to 8,000 characters (beyond that it says "(truncated, N more characters)"), shown in a scrollable block. It is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks.
- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json` (where it was before the proxy), `models.json` (it can hold API keys), `mcp.json`, the old sign-in home `<dataDir>/connector-signin` with its `mcp.json` and `mcp-auth.json` (gone after the migration, still protected in case they appear again), `<dataDir>/connectors.json`, `<dataDir>/token`, the guard itself, and the file that loads it into subagents (`<agentHome>/extensions/gentle-dot-child-guard.ts`, below). The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.
- Stage 2 integrity (S25.6, Integrity above) covers the user's own servers too: the signature is over the whole record, so a file edited while the daemon is not running cannot add a server that runs a command, turn it on, claim an `origin`, change its command, arguments, URL, env, headers, `enabled`, or `mode`, or plant a secret reference (L117 A1) without being set aside at the next start with the app. Without the app it is still loaded, but connectors that need a secret are locked there.
-- Subagents (S25.4, T23f; `packages/daemon/src/child-guard.ts`): they are on (`GENTLE_PI_AGENTS=1`, §3; `GENTLE_DOT_SUBAGENTS=off` turns them off). A subagent is a child engine that gentle-pi starts as `pi --mode rpc` (`lib/agents-runner.ts` `childArguments`) with the engine's environment (`PI_CODING_AGENT_DIR` is the assistant's engine home, plus the guard's policy) and without `--no-extensions`. So it reads the same `<agentHome>/mcp.json`: connectors only as proxy entries with the current launch's key, where the daemon filters by mode, refuses hidden tools, and asks in the app's native dialog before every sending action, whoever calls; and the computer helper at the app's address with its key, where the app's own session grant and confirmations apply. A child also loads gentle-pi's two child extensions (`child-context.ts`, `child-safety.ts`) and whatever it discovers in the engine home, never the engine's `-e`, and gentle-pi offers no setting for extra child extensions (its `GENTLE_PI_AGENTS_PI` override splits on spaces, and the app's paths have them). The daemon therefore keeps `<agentHome>/extensions/gentle-dot-child-guard.ts`, which imports the guard from the daemon's own install (a path fixed when the daemon writes it, never one from the environment) and runs it only when `GENTLE_PI_AGENTS_CHILD=1` and the daemon's policy variable are both set: inert in the main engine (which already has the guard) and in any engine Gentle Dot did not start that shares the home. It is written (0600) at every engine start, checked with the connector files (a change or removal is put back, logged, and reported like one to `mcp.json`; an `extensions` folder that became a link loses the link, never its target), and protected like the guard. If it cannot be put in place (the folder's place holds a file, or the file's place a folder), that is logged once and the engine starts with `GENTLE_PI_AGENTS=0`. In a child the guard blocks the credential and control files and the connector commands as in the engine; it registers no `propose_connector`, because a child's status updates go to its parent engine, never to the daemon, so a draft could not reach the user. The proxy and the native approvals stay the boundary; the guard in children is defense in depth, with the guard's own limits (the agent's shell can change files between the daemon's checks, add an `index.ts` or ignore file to that folder, or turn the file off in `settings.json`), the same reach the engine's shell already has (S25, refined in L109). `subagent-probe.test.ts` (opt-in, `GENTLE_DOT_SUBAGENT_PROBE=1`, offline) runs the real engine with gentle-pi's subagents: the child's read of `mcp.json` is refused by the guard, a read-only Notion search goes through the proxy without asking, creating a page waits for the app's answer, and the computer helper is reached with its key.
+- Subagents (S25.4, T23f; `packages/daemon/src/child-guard.ts`): they are on (`GENTLE_PI_AGENTS=1`, §3; `GENTLE_DOT_SUBAGENTS=off` turns them off). A subagent is a child engine that gentle-pi starts as `pi --mode rpc` (`lib/agents-runner.ts` `childArguments`) with the engine's environment (`PI_CODING_AGENT_DIR` is the assistant's engine home, plus the guard's policy) and without `--no-extensions`. So it reads the same `<agentHome>/mcp.json`: connectors only as proxy entries with the current launch's key, where the daemon filters by mode, refuses hidden tools, and asks in the app's native dialog before every sending action, whoever calls; and the computer helper at the app's address with its key, where the app's own session grant and confirmations apply. A child also loads gentle-pi's two child extensions (`child-context.ts`, `child-safety.ts`) and whatever it discovers in the engine home, never the engine's `-e`, and gentle-pi offers no setting for extra child extensions (its `GENTLE_PI_AGENTS_PI` override splits on spaces, and the app's paths have them). The daemon therefore keeps `<agentHome>/extensions/gentle-dot-child-guard.ts`, which imports the guard from the daemon's own install (a path fixed when the daemon writes it, never one from the environment) and runs it only when `GENTLE_PI_AGENTS_CHILD=1` and the daemon's policy variable are both set: inert in the main engine (which already has the guard) and in any engine Gentle Dot did not start that shares the home. It is written (0600) at every engine start, checked with the connector files (a change or removal is put back, logged, and reported like one to `mcp.json`; an `extensions` folder that became a link loses the link, never its target), and protected like the guard. If it cannot be put in place (the folder's place holds a file, the file's place a folder, or the folder cannot be written), that is logged once and the engine starts with `GENTLE_PI_AGENTS=0`. In a child the guard blocks the credential and control files and the connector commands as in the engine; it registers no `propose_connector`, because a child's status updates go to its parent engine, never to the daemon, so a draft could not reach the user. The proxy and the native approvals stay the boundary; the guard in children is defense in depth, with the guard's own limits (the agent's shell can change files between the daemon's checks, add an `index.ts` or ignore file to that folder, or turn the file off in `settings.json`), the same reach the engine's shell already has (S25, refined in L109). `subagent-probe.test.ts` (opt-in, `GENTLE_DOT_SUBAGENT_PROBE=1`, offline) runs the real engine with gentle-pi's subagents: the child's read of `mcp.json` is refused by the guard, a read-only Notion search goes through the proxy without asking, creating a page waits for the app's answer, and the computer helper is reached with its key.
### Switching and history races (S21)
@@ -288,7 +288,7 @@ The user changes the main assistant's model from the chat, in the panel and the
- The daemon binds `127.0.0.1` only. A random 256-bit token is stored in `~/.gentle-dot/token` (mode 0600). The desktop app reads it; the browser receives it once by URL fragment.
- WebSocket upgrades check `Origin` against an allowlist (`http://127.0.0.1:4317`, `tauri://localhost`).
- The VPS guide requires HTTPS, a reverse proxy with authentication, and a dedicated Docker container with no access to personal machines.
-- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon: the MCP proxy (S25.4, done) keeps every token, real address, and server environment out of the engine's `mcp.json`, and enforces mode, hidden tools, and approvals in the daemon. Connector changes and approvals come only from the desktop app that launched the daemon, over its private channel, and are answered in native dialogs (§4, App channel); the WebSocket's access key no longer reaches them. Connector secrets (tokens, client secrets, imported headers, sign-ins) are in Keychain items the signed app creates and reach the daemon only in memory over that channel (S25.5, §4 Secrets); without the app, connectors that need one fail closed. What the Keychain cannot check: `security-framework` exposes no item access list, so the app cannot tell an item it created from one a same-user process planted (before the first `put`, or after deleting the app's); the daemon only reads ids it recorded, and every `put` replaces the item. `connectors.json` is signed with a key in the Keychain, and a file changed while Gentle Dot was closed is set aside at the next start with the app (S25.6, §4 Integrity); without the app it is loaded unverified. Still open: Linux children could inherit the channel if libuv there does not close it (the daemon then refuses it; T23g), and the proxy key is in the engine's `mcp.json`, so the agent's shell could call the proxy directly; that reaches only what the proxy allows, and every sending action still needs the user's approval.
+- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon: the MCP proxy (S25.4, done) keeps every token, real address, and server environment out of the engine's `mcp.json`, and enforces mode, hidden tools, and approvals in the daemon. Connector changes and approvals come only from the desktop app that launched the daemon, over its private channel, and are answered in native dialogs (§4, App channel); the WebSocket's access key no longer reaches them. Connector secrets (tokens, client secrets, imported headers, sign-ins) are in Keychain items the signed app creates and reach the daemon only in memory over that channel (S25.5, §4 Secrets); without the app, connectors that need one fail closed. What the Keychain cannot check: `security-framework` exposes no item access list, so the app cannot tell an item it created from one a same-user process planted (before the first `put`, or after deleting the app's); the daemon only reads ids it recorded, and every `put` replaces the item. `connectors.json` is signed with a key in the Keychain, and a file changed while Gentle Dot was closed is set aside at the next start with the app (S25.6, §4 Integrity); without the app it is loaded unverified. On Linux the app keeps connector secrets in the Secret Service (GNOME Keyring or KWallet), encrypted at rest; the Secret Service has no per-caller access list, so any same-user process, the agent's shell included, can read the items while the keyring is unlocked (S25.7, documented limit). The app channel, the MCP proxy, and native approvals work as on macOS: no child of the daemon holds the channel (checked in containers by `scripts/package/linux-cargo-check.mjs` and the package smoke). Without a Secret Service, connectors that need a secret fail closed, and the assistant and `daemon.log` name the missing keyring. Still open: the proxy key is in the engine's `mcp.json`, so the agent's shell could call the proxy directly; that reaches only what the proxy allows, and every sending action still needs the user's approval.
## 9. Desktop shell contract (Tauri 2 <-> UI)
diff --git a/docs/install.md b/docs/install.md
index 922ed6d..b60c6e8 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -95,8 +95,11 @@ Keep the `./` with `apt`. The package manager adds WebKitGTK and tray support. T
- The app is `/usr/bin/gentle-dot`; its bundled runtime is in `/usr/lib/Gentle Dot/runtime`. Your data lives in `~/.gentle-dot`.
- First launch needs the network once: the engine installs its companion packages (about 20 seconds).
- Computer control is macOS only.
+- Connector secrets (tokens and sign-ins) are kept in your desktop keyring through the Secret Service (GNOME Keyring or KWallet), encrypted on disk, never in `~/.gentle-dot`. In Passwords and Keys (Seahorse) they show as "Gentle Dot connector: …" in the login keyring. Connector approvals and connector changes go through the app's own dialogs, which the assistant cannot answer.
+- **Limit on Linux:** while the keyring is unlocked (usually your whole session), any program running as your user can read those items, including commands the assistant runs in its shell (for example `secret-tool lookup service dev.gentleman.gentle-dot.connectors account <id>`). The Secret Service has no way to restrict which program reads an item. On macOS the Keychain lets only the signed app read them without asking; on Linux, protect the secrets by keeping the keyring locked when you are away and by connecting only the accounts you want the assistant to use.
+- Without a keyring (no Secret Service in the session, common on minimal window-manager setups), connectors that need a secret do not run, and nothing is written to disk instead. `~/.gentle-dot/daemon.log` then says `no Secret Service in this desktop session (…); install and unlock a keyring such as GNOME Keyring or KWallet`. Install `gnome-keyring` (or KWallet), and make sure it runs in your session; the app looks for it again on every request, so no restart is needed. A locked keyring shows its unlock prompt when a connector needs a secret; dismissing it, or no answer within two minutes, refuses.
- GNOME: add a custom shortcut that runs `/usr/bin/gentle-dot --toggle` (see docs/linux-testing.md, step 9). Debian needs the AppIndicator extension for the tray icon.
- Hyprland / Omarchy: paste `scripts/linux/hyprland/gentle-dot.lua` (or `.conf`) into your Hyprland config; it already calls `/usr/bin/gentle-dot --toggle`.
- Remove: `sudo apt remove gentle-dot` or `sudo pacman -R gentle-dot` (your data in `~/.gentle-dot` stays).
-- Build the packages (needs Docker): `pnpm package:linux --arch <arm64|amd64>` (amd64 also builds the Arch package); check them in clean containers with `pnpm package:linux:check --arch <arm64|amd64>`.
+- Build the packages (needs Docker): `pnpm package:linux --arch <arm64|amd64>` (amd64 also builds the Arch package); check them in clean containers with `pnpm package:linux:check --arch <arm64|amd64>`. `node scripts/package/linux-cargo-check.mjs --arch <arm64|amd64>` runs the desktop crate's tests and clippy on Linux, the keyring store against a real GNOME Keyring on a private session bus, and the app channel checks.
- Developers can still build from source with `scripts/linux/setup-debian.sh` or `scripts/linux/setup-arch.sh` (app at `~/.local/bin/gentle-dot`).
diff --git a/docs/linux-testing.md b/docs/linux-testing.md
index ca3598c..27ba794 100644
--- a/docs/linux-testing.md
+++ b/docs/linux-testing.md
@@ -211,6 +211,14 @@ Turn on **Launch at login** in the tray menu, log out, and log back in.
**Expected:** the rose appears after login. Turn the option off again afterwards.
+### 17. Connector secrets and approvals (optional, needs an account for one connector)
+
+Open **Connectors**, connect one that signs in with your account (for example Notion), and finish the sign-in. Then open **Passwords and Keys** (Seahorse; on KDE, KWalletManager) and look in the **Login** keyring.
+
+**Expected:** an item whose name starts with "Gentle Dot connector: connector/". Then ask the assistant to do something that sends, for example "create a Notion page called Gentle Dot test". A Gentle Dot dialog (not a card in the chat) asks "Allow Notion to …?" with the full action, and **Decline** is the default button. Choose **Decline**: nothing is created.
+
+The keyring keeps these items encrypted on disk, but while it is unlocked any program running as you can read them (see docs/install.md, Linux). If your session has no keyring, the connector does not run and `~/.gentle-dot/daemon.log` says `no Secret Service in this desktop session`; note that in the report.
+
## Reporting Wayland limitations
Some things Wayland does not allow at all, and we already work around them: apps cannot place their own windows, stay on top by themselves, or register global shortcuts. If you notice something else that does not work the same way as on other systems, write in the report:
@@ -227,6 +235,7 @@ For a quick comparison on GNOME, you can start the app as a native Wayland clien
| Symptom | Try |
|---|---|
| The panel or rose is blank, or the app prints `Failed to create GBM buffer` (often with NVIDIA) | Quit the app, then start it with `WEBKIT_DISABLE_DMABUF_RENDERER=1` before the app command, for example `WEBKIT_DISABLE_DMABUF_RENDERER=1 gentle-dot`. Note in the report whether it helped. |
+| A connector that needs a sign-in or token never runs, and `daemon.log` says `no Secret Service in this desktop session` | Your session has no keyring. Install `gnome-keyring` (or KWallet) and make sure it runs in your session, then try the connector again. |
| The rose stays dimmed | Look at `~/.gentle-dot/daemon.log` and attach it (see below). |
| No tray icon on GNOME | Check that the AppIndicator extension is on: `gnome-extensions list --enabled` |
| `gentle-dot: command not found` | Use the full path: `/usr/bin/gentle-dot` with the package, `~/.local/bin/gentle-dot` from source |
@@ -265,6 +274,7 @@ Source version: (from source: output of git rev-parse --short HEAD
| 14| Connectors | | |
| 15| Quit and relaunch | | |
| 16| Launch at login (optional) | | |
+| 17| Connector secrets | | |
Wayland limitations noticed:
diff --git a/packages/daemon/src/secret-source.ts b/packages/daemon/src/secret-source.ts
index 13cfb23..360767b 100644
--- a/packages/daemon/src/secret-source.ts
+++ b/packages/daemon/src/secret-source.ts
@@ -12,6 +12,9 @@ import { APPROVAL_WAIT_MS, type AppChannel } from "./app-channel.ts";
/** Why a connector that needs a secret cannot run: the secrets are only in the app's store. */
export const NO_APP = "Open the Gentle Dot app to use this connector.";
+/** How the app starts its answer when its secret store cannot be reached (`StoreError::Unavailable`). */
+const STORE_UNAVAILABLE = "the secret store is unavailable: ";
+
/** The secret store is not reachable; `message` is safe to show. */
export class SecretsUnavailableError extends Error {
constructor(message = NO_APP) {
@@ -81,7 +84,10 @@ export class AppSecretSource implements SecretSource {
return await channel.request(method, params, this.timeoutMs);
} catch (error) {
if (!channel.connected) throw new SecretsUnavailableError();
- throw new Error(`The app's secure store refused it: ${(error as Error).message}`);
+ const message = (error as Error).message;
+ // The app's own words for a store it cannot reach (no keyring on Linux), safe to show.
+ if (message.startsWith(STORE_UNAVAILABLE)) throw new SecretsUnavailableError(`T${message.slice(1)}`);
+ throw new Error(`The app's secure store refused it: ${message}`);
}
}
}
diff --git a/packages/daemon/test/connector-secrets.test.ts b/packages/daemon/test/connector-secrets.test.ts
index cef0586..b385a91 100644
--- a/packages/daemon/test/connector-secrets.test.ts
+++ b/packages/daemon/test/connector-secrets.test.ts
@@ -23,7 +23,12 @@ import WebSocket from "ws";
import { AppChannel } from "../src/app-channel.ts";
import { ConnectorManager, ConnectorStore, type CustomConnector } from "../src/connectors.ts";
import { type DotDaemon, startDaemon } from "../src/daemon.ts";
-import { AppSecretSource, MemorySecretSource, NO_APP } from "../src/secret-source.ts";
+import {
+ AppSecretSource,
+ MemorySecretSource,
+ NO_APP,
+ SecretsUnavailableError,
+} from "../src/secret-source.ts";
import { fakeApp, sendLikeThePanel } from "./fake-app.ts";
import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
import { fakeOAuth } from "./fake-oauth.ts";
@@ -130,6 +135,27 @@ describe("the app's secret store over its channel", () => {
await expect(new AppSecretSource(undefined).list()).rejects.toThrow(NO_APP);
expect(NO_APP).toBe("Open the Gentle Dot app to use this connector.");
});
+
+ it("passes on why the app's secret store is unavailable, so the assistant can say it (S25.7)", async () => {
+ const app = fakeApp();
+ const channel = new AppChannel(app.daemonEnd);
+ closers.push(async () => channel.close());
+ const source = new AppSecretSource(channel);
+ const why =
+ "the secret store is unavailable: no Secret Service in this desktop session (DBus error); install and unlock a keyring such as GNOME Keyring or KWallet";
+ app.failSecrets(why);
+ const unavailable = await source.get("connector/x").catch((error: unknown) => error);
+ expect(unavailable).toBeInstanceOf(SecretsUnavailableError);
+ expect((unavailable as Error).message).toBe(
+ "The secret store is unavailable: no Secret Service in this desktop session (DBus error); install and unlock a keyring such as GNOME Keyring or KWallet",
+ );
+ app.failSecrets("the user denied access to the secret store");
+ const refused = await source.get("connector/x").catch((error: unknown) => error);
+ expect(refused).not.toBeInstanceOf(SecretsUnavailableError);
+ expect((refused as Error).message).toBe(
+ "The app's secure store refused it: the user denied access to the secret store",
+ );
+ });
});
describe("typed connector secrets", () => {
diff --git a/packages/daemon/test/fake-app.ts b/packages/daemon/test/fake-app.ts
index 7b09dbe..e89dfbb 100644
--- a/packages/daemon/test/fake-app.ts
+++ b/packages/daemon/test/fake-app.ts
@@ -27,6 +27,8 @@ export function fakeApp(answers: Answer[] = [], otherwise: Answer = "decline") {
/** The app's Keychain, by secret id; `secretCalls` records the methods and ids only. */
const secrets = new Map<string, string>();
const secretCalls: string[] = [];
+ /** When set, every secret call is answered with this error, as the app's store would refuse it. */
+ let secretError: string | undefined;
const queue = [...answers];
const pending = new Map<number, { resolve(v: unknown): void; reject(e: Error): void }>();
const held: number[] = [];
@@ -50,6 +52,10 @@ export function fakeApp(answers: Answer[] = [], otherwise: Answer = "decline") {
const params = (frame.params ?? {}) as { id?: string; secret?: string };
secretCalls.push(params.id === undefined ? frame.method : `${frame.method} ${params.id}`);
const id = params.id ?? "";
+ if (secretError !== undefined) {
+ write({ kind: "response", id: frame.id, error: secretError });
+ continue;
+ }
let result: unknown = { ids: [...secrets.keys()].sort() };
if (frame.method === "secret_get") result = secrets.has(id) ? { secret: secrets.get(id) } : null;
else if (frame.method === "secret_put") {
@@ -81,6 +87,9 @@ export function fakeApp(answers: Answer[] = [], otherwise: Answer = "decline") {
asked,
secrets,
secretCalls,
+ failSecrets: (error: string | undefined) => {
+ secretError = error;
+ },
/** Answers the oldest held approval, as a user clicking in the dialog later. */
release: (approved: boolean) => {
const id = held.shift();
diff --git a/scripts/package/linux-app-smoke.mjs b/scripts/package/linux-app-smoke.mjs
index 2b3c28a..8d97aee 100755
--- a/scripts/package/linux-app-smoke.mjs
+++ b/scripts/package/linux-app-smoke.mjs
@@ -2,9 +2,19 @@
// Launches an installed Gentle Dot binary under Xvfb on a clean HOME, as a desktop session would,
// and waits until the daemon the app spawned reports idle on a free port:
// `node scripts/package/linux-app-smoke.mjs --binary /usr/bin/gentle-dot [--runtime <dir>] [--timeout <s>]`.
+// Also checks the app channel (S25.1, S25.7): the daemon holds the app's socket on fd 3, the log
+// shows no refusal, and no other process (the engine, Engram, their children) holds that socket.
// Runs inside a Linux container (docker/linux-package/check-package.sh); needs xvfb-run and lsof.
import { execFileSync, spawn } from "node:child_process";
-import { existsSync, mkdirSync, mkdtempSync, openSync, readFileSync } from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ openSync,
+ readdirSync,
+ readFileSync,
+ readlinkSync,
+} from "node:fs";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -26,21 +36,71 @@ function freePort() {
});
}
-/** The command line of the process listening on `port`, when `lsof` can tell. */
-function listener(port) {
+/** The pid of the process listening on `port`, when `lsof` can tell. */
+function listenerPid(port) {
try {
- const pid = execFileSync("lsof", ["-t", "-n", "-P", `-iTCP:${port}`, "-sTCP:LISTEN"], {
+ return execFileSync("lsof", ["-t", "-n", "-P", `-iTCP:${port}`, "-sTCP:LISTEN"], {
encoding: "utf8",
env: { PATH: SYSTEM_PATH },
})
.trim()
.split("\n")[0];
+ } catch {
+ return undefined;
+ }
+}
+
+/** The command line of the process listening on `port`, when `lsof` can tell. */
+function listener(port) {
+ const pid = listenerPid(port);
+ if (!pid) return undefined;
+ try {
return execFileSync("ps", ["-o", "command=", "-p", pid], { encoding: "utf8" }).trim();
} catch {
return undefined;
}
}
+const pids = () => readdirSync("/proc").filter((name) => /^\d+$/.test(name));
+const tryRead = (read) => {
+ try {
+ return read();
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * The app channel as the daemon `pid` holds it: fd 3 is a socket, and which other processes hold
+ * that same socket (none should), with the daemon's descendants for scale.
+ */
+function channelCheck(pid) {
+ const socket = tryRead(() => readlinkSync(`/proc/${pid}/fd/3`));
+ if (!socket?.startsWith("socket:"))
+ return { ok: false, detail: `the daemon's fd 3 is ${socket ?? "closed"}` };
+ const parents = new Map();
+ for (const other of pids()) {
+ const stat = tryRead(() => readFileSync(`/proc/${other}/stat`, "utf8"));
+ if (stat) parents.set(other, stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
+ }
+ const descends = (other) => {
+ for (let at = parents.get(other); at && at !== "0"; at = parents.get(at)) if (at === pid) return true;
+ return false;
+ };
+ const descendants = [...parents.keys()].filter(descends);
+ const holders = [];
+ for (const other of pids()) {
+ if (other === pid) continue;
+ for (const fd of tryRead(() => readdirSync(`/proc/${other}/fd`)) ?? [])
+ if (tryRead(() => readlinkSync(`/proc/${other}/fd/${fd}`)) === socket)
+ holders.push(`pid ${other} fd ${fd}`);
+ }
+ return {
+ ok: holders.length === 0,
+ detail: `daemon fd 3 is ${socket}; ${descendants.length} descendant processes; other holders: ${holders.join(", ") || "none"}`,
+ };
+}
+
async function health(port) {
try {
const response = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(2000) });
@@ -108,6 +168,9 @@ async function main() {
if (runtime) say(`daemon launched from the packaged runtime: ${fromRuntime}`);
const engram = listener(engramPort);
say(`engram on ${engramPort}: ${engram ?? "not listening"}`);
+ const daemonPid = listenerPid(port);
+ const channel = daemonPid ? channelCheck(daemonPid) : { ok: false, detail: "no daemon" };
+ say(`app channel: ${channel.detail}`);
if (!exited) {
process.kill(-app.pid, "SIGTERM");
@@ -120,15 +183,18 @@ async function main() {
`after stop: daemon ${daemonLeft ? "still listening" : "stopped"}, engram ${engramLeft ? "still listening" : "stopped"}`,
);
const daemonLog = join(dataDir, "daemon.log");
+ let refused = false;
if (existsSync(daemonLog)) {
const lines = readFileSync(daemonLog, "utf8").trim().split("\n");
say(`daemon.log: ${lines.length} lines, last: ${lines.at(-1)}`);
+ refused = lines.some((line) => line.includes("the app's channel was refused"));
+ say(`daemon.log: the app's channel was ${refused ? "REFUSED" : "not refused"}`);
}
const appLines = readFileSync(logFile, "utf8").trim().split("\n").filter(Boolean);
say(`app output: ${appLines.length} lines`);
for (const line of appLines.slice(-8)) say(` ${line}`);
- const ok = state === "idle" && fromRuntime && !daemonLeft && !engramLeft;
+ const ok = state === "idle" && fromRuntime && !daemonLeft && !engramLeft && channel.ok && !refused;
say(ok ? "app smoke: ok" : "app smoke: FAILED");
process.exit(ok ? 0 : 1);
}
diff --git a/scripts/package/linux-cargo-check.mjs b/scripts/package/linux-cargo-check.mjs
new file mode 100644
index 0000000..5428551
--- /dev/null
+++ b/scripts/package/linux-cargo-check.mjs
@@ -0,0 +1,75 @@
+#!/usr/bin/env node
+// Checks the desktop crate on Linux (S25.7) in a container of the given architecture, from any
+// machine with Docker: `node scripts/package/linux-cargo-check.mjs --arch <arm64|amd64>`. It runs
+// `cargo test`, `cargo clippy --all-targets -- -D warnings`, the Secret Service store against a real
+// GNOME Keyring on a private session bus, and the app channel's fd 3 checks
+// (docker/linux-package/cargo-check.sh). The image builds on the package builder
+// (`package-linux.mjs`), which it builds first; compiled crates stay in a volume of their own.
+import { spawnSync } from "node:child_process";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import {
+ ARCHES,
+ builderImage,
+ cargoCheckVolumes,
+ checkImage,
+ formatDuration,
+ parseCargoCheckArgs,
+} from "./linux-lib.mjs";
+
+const REPO = fileURLToPath(new URL("../..", import.meta.url));
+const say = (line) => process.stdout.write(`${line}\n`);
+
+function docker(args) {
+ const result = spawnSync("docker", args, { stdio: "inherit" });
+ if (result.status !== 0)
+ throw new Error(
+ `docker ${args.slice(0, 2).join(" ")} failed (${result.error?.message ?? `exit ${result.status}`}).`,
+ );
+}
+
+function main() {
+ const { arch } = parseCargoCheckArgs(process.argv.slice(2));
+ const { platform } = ARCHES[arch];
+ const context = join(REPO, "docker", "linux-package");
+ const started = Date.now();
+ say(`\n=== Builder image ${builderImage(arch)}`);
+ docker(["build", "--platform", platform, "-t", builderImage(arch), context]);
+ say(`\n=== Check image ${checkImage(arch)}`);
+ docker([
+ "build",
+ "--platform",
+ platform,
+ "--build-arg",
+ `BUILDER=${builderImage(arch)}`,
+ "-f",
+ join(context, "Dockerfile.check"),
+ "-t",
+ checkImage(arch),
+ context,
+ ]);
+ const volumes = cargoCheckVolumes(arch).flatMap(({ name, target }) => ["-v", `${name}:${target}`]);
+ say(`\n=== Linux checks of the desktop crate (linux/${arch})`);
+ docker([
+ "run",
+ "--rm",
+ "--name",
+ `gentle-dot-linux-cargo-check-${arch}`,
+ "--platform",
+ platform,
+ "-v",
+ `${REPO}:/src:ro`,
+ ...volumes,
+ checkImage(arch),
+ "bash",
+ "/src/docker/linux-package/cargo-check.sh",
+ ]);
+ say(`\nLinux checks passed in ${formatDuration(Date.now() - started)}.`);
+}
+
+try {
+ main();
+} catch (error) {
+ process.stderr.write(`linux-cargo-check: ${error.message}\n`);
+ process.exit(1);
+}
diff --git a/scripts/package/linux-lib.mjs b/scripts/package/linux-lib.mjs
index e126667..2c33dc6 100644
--- a/scripts/package/linux-lib.mjs
+++ b/scripts/package/linux-lib.mjs
@@ -23,6 +23,7 @@ export const PACKAGE_USAGE =
"usage: package-linux --arch <arm64|amd64> [--out <dir>] [--engram-version <x.y.z>] [--no-arch-package]";
export const CHECK_USAGE =
"usage: linux-check --arch <arm64|amd64> [--distro <debian|ubuntu|arch>[,…]] [--out <dir>]";
+export const CARGO_CHECK_USAGE = "usage: linux-cargo-check --arch <arm64|amd64>";
/** Reads `--name value` pairs and bare switches; throws with `usage` on anything unexpected. */
function readFlags(argv, valued, switches, usage) {
@@ -85,6 +86,13 @@ export function parseCheckArgs(argv) {
return { arch: options.arch, out: options.out, distros };
}
+/** `linux-cargo-check` options: the architecture. */
+export function parseCargoCheckArgs(argv) {
+ const options = readFlags(argv, { "--arch": "arch" }, {}, CARGO_CHECK_USAGE);
+ checkArch(options.arch, CARGO_CHECK_USAGE);
+ return options;
+}
+
export function debFileName(version, arch) {
return `gentle-dot_${version}_${ARCHES[arch].deb}.deb`;
}
@@ -104,6 +112,11 @@ export function builderImage(arch) {
export const ARCH_BUILDER_IMAGE = "gentle-dot-arch-builder:latest";
+/** The package builder plus a session D-Bus and GNOME Keyring, for `linux-cargo-check`. */
+export function checkImage(arch) {
+ return `gentle-dot-linux-check:${arch}`;
+}
+
/** Named volumes that keep downloads and compiled crates between builds, and where they mount. */
export function cacheVolumes(arch) {
return [
@@ -114,6 +127,18 @@ export function cacheVolumes(arch) {
];
}
+/**
+ * The volumes `linux-cargo-check` mounts: the package build's downloads, and compiled test crates in
+ * a target volume of their own (debug builds, kept apart from the release builds of the packages).
+ */
+export function cargoCheckVolumes(arch) {
+ const downloads = ["/usr/local/cargo/registry", "/pnpm-store"];
+ return [
+ ...cacheVolumes(arch).filter(({ target }) => downloads.includes(target)),
+ { name: `gentle-dot-linux-${arch}-check-target`, target: "/work/apps/desktop/src-tauri/target" },
+ ];
+}
+
/**
* The repository's PKGBUILD with this build's version, release, and the checksum of the
* .deb it repackages; throws when a field to fill is missing.
diff --git a/scripts/package/test-linux/linux-lib.test.ts b/scripts/package/test-linux/linux-lib.test.ts
index c71f9d0..6880074 100644
--- a/scripts/package/test-linux/linux-lib.test.ts
+++ b/scripts/package/test-linux/linux-lib.test.ts
@@ -4,10 +4,13 @@ import {
archPackageFileName,
builderImage,
cacheVolumes,
+ cargoCheckVolumes,
+ checkImage,
debFileName,
fillPkgbuild,
formatDuration,
packageFileFor,
+ parseCargoCheckArgs,
parseCheckArgs,
parsePackageArgs,
} from "../linux-lib.mjs";
@@ -80,6 +83,26 @@ describe("artifact names", () => {
]);
expect(volumes.every((volume) => volume.target.startsWith("/"))).toBe(true);
});
+
+ it("check the crate in an image and a target volume of their own, sharing the downloads", () => {
+ expect(checkImage("arm64")).toBe("gentle-dot-linux-check:arm64");
+ expect(cargoCheckVolumes("arm64")).toEqual([
+ { name: "gentle-dot-linux-arm64-cargo", target: "/usr/local/cargo/registry" },
+ { name: "gentle-dot-linux-arm64-pnpm", target: "/pnpm-store" },
+ { name: "gentle-dot-linux-arm64-check-target", target: "/work/apps/desktop/src-tauri/target" },
+ ]);
+ });
+});
+
+describe("parseCargoCheckArgs", () => {
+ it("takes an architecture and nothing else", () => {
+ expect(parseCargoCheckArgs(["--", "--arch", "arm64"])).toEqual({ arch: "arm64" });
+ expect(() => parseCargoCheckArgs([])).toThrow(/Missing --arch/);
+ expect(() => parseCargoCheckArgs(["--arch", "riscv"])).toThrow(/Unknown architecture/);
+ expect(() => parseCargoCheckArgs(["--arch", "arm64", "--distro", "debian"])).toThrow(
+ /Unexpected argument/,
+ );
+ });
});
describe("fillPkgbuild", () => {