From 7a0d9f6da16b01e5060bdb572933c1b181d52ada Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:54:27 +0300 Subject: [PATCH 01/76] chore(lint): make clippy pass on main MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI's dtolnay/rust-toolchain@stable now installs Rust 1.100.0, whose clippy extends needless_bool to an `if` guard that returns a bool literal and is followed by the opposite literal. The retain closure in purge_legacy_builtin_seeds hit it and failed the -D warnings gate. Return the negated condition instead: same result, same short-circuit order. Cargo 1.100 also reports two dependencies nothing uses (cargo::unused_dependencies): fleetify-app's dotenvy build-dependency, a leftover of compile-time PostHog key loading that runtime resolution replaced (build.rs only calls tauri_build::build()), and serde in fleetify-core. Drop both so the gate output is clean. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- Cargo.lock | 2 -- crates/fleetify-backend/src/services/mcp_registry.rs | 5 +---- crates/fleetify-core/Cargo.toml | 1 - src-tauri/Cargo.toml | 3 --- 4 files changed, 1 insertion(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ab4ce39..bcdc800 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1381,7 +1381,6 @@ dependencies = [ "base64 0.22.1", "chrono", "cpal", - "dotenvy", "fleetify-backend", "fleetify-core", "hound", @@ -1461,7 +1460,6 @@ dependencies = [ name = "fleetify-core" version = "0.1.0" dependencies = [ - "serde", "thiserror 2.0.18", ] diff --git a/crates/fleetify-backend/src/services/mcp_registry.rs b/crates/fleetify-backend/src/services/mcp_registry.rs index 9b62beb..7d5ffde 100644 --- a/crates/fleetify-backend/src/services/mcp_registry.rs +++ b/crates/fleetify-backend/src/services/mcp_registry.rs @@ -162,10 +162,7 @@ pub fn purge_legacy_builtin_seeds() { .get("builtin") .and_then(|v| v.as_bool()) .unwrap_or(false); - if is_builtin_seed && FLEET_BUILTIN_NAMES.contains(&name.as_str()) { - return false; - } - true + !(is_builtin_seed && FLEET_BUILTIN_NAMES.contains(&name.as_str())) }); if doc.mcp_servers.len() != before { tracing::info!( diff --git a/crates/fleetify-core/Cargo.toml b/crates/fleetify-core/Cargo.toml index 464dc47..dfa0f4c 100644 --- a/crates/fleetify-core/Cargo.toml +++ b/crates/fleetify-core/Cargo.toml @@ -5,5 +5,4 @@ edition.workspace = true license.workspace = true [dependencies] -serde.workspace = true thiserror.workspace = true diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 2abf046..1959c94 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -14,9 +14,6 @@ crate-type = ["cdylib", "rlib"] [build-dependencies] tauri-build = { version = "2", features = [] } -# Read POSTHOG_* keys from `.env` at compile time so the renderer never -# sees the API key and the literal string doesn't sit in tracked source. -dotenvy = "0.15" [dependencies] fleetify-core.workspace = true From e32761a55b454b207f41a937ef8eb77d840cfbeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:15:51 +0300 Subject: [PATCH 02/76] fix(auth): pin production issuer and audience in release builds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A release build signs in against production fleetify.dev, but the embedded backend validated the resulting tokens against a local identity provider (http://localhost:3001) and audience (http://127.0.0.1:8765) unless FLEETIFY_ISSUER and FLEETIFY_AUDIENCE happened to be set. The shell and the backend each resolved these values on their own and only the shell pinned production, so the backend would reject the tokens from every real sign-in. Resolve the issuer origin and the API resource (the token audience) once, in fleetify_core::endpoints, and use it from the shell's OAuth client, the backend's AuthConfig and the telemetry WebSocket client. Release builds return the production values and ignore the environment. Debug builds keep reading FLEETIFY_ISSUER and FLEETIFY_RESOURCE, then FLEETIFY_AUDIENCE, with the same local defaults; the dev scripts set both of the latter to the same value. In debug builds the telemetry WebSocket client now falls back to the local IdP origin instead of production when FLEETIFY_ISSUER is unset, matching the shell it takes its token from. Its URL test now passes base URLs directly instead of setting FLEETIFY_ISSUER, which release builds ignore. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- crates/fleetify-backend/src/auth.rs | 38 +++++-- .../src/services/telemetry/ws_client.rs | 28 +++-- crates/fleetify-core/src/endpoints.rs | 100 ++++++++++++++++++ crates/fleetify-core/src/lib.rs | 2 + src-tauri/src/shell/auth.rs | 31 ++++-- 5 files changed, 173 insertions(+), 26 deletions(-) create mode 100644 crates/fleetify-core/src/endpoints.rs diff --git a/crates/fleetify-backend/src/auth.rs b/crates/fleetify-backend/src/auth.rs index 1a7a135..c1c1f8f 100644 --- a/crates/fleetify-backend/src/auth.rs +++ b/crates/fleetify-backend/src/auth.rs @@ -11,6 +11,7 @@ use axum::extract::{FromRef, FromRequestParts}; use axum::http::request::Parts; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; +use fleetify_core::endpoints; use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation}; use serde::Deserialize; use sha2::{Digest, Sha256}; @@ -61,20 +62,27 @@ pub struct AuthConfig { } impl AuthConfig { - pub fn from_env() -> Self { - let origin = std::env::var("FLEETIFY_ISSUER") - .unwrap_or_else(|_| "http://localhost:3001".to_string()); - let auth_base = format!("{origin}/api/auth"); + /// Derives the better-auth base (`{origin}/api/auth`, also the expected + /// `iss`) and its JWKS URL from the identity-provider origin. + pub fn new(issuer_origin: String, expected_audience: String) -> Self { + let auth_base = format!("{issuer_origin}/api/auth"); let jwks_url = format!("{auth_base}/jwks"); - let expected_audience = std::env::var("FLEETIFY_AUDIENCE") - .unwrap_or_else(|_| "http://127.0.0.1:8765".to_string()); Self { - issuer_origin: origin, + issuer_origin, auth_base, jwks_url, expected_audience, } } + + /// Production `fleetify.dev` values in release builds, whatever the + /// environment says; debug builds read `FLEETIFY_ISSUER` and + /// `FLEETIFY_RESOURCE` / `FLEETIFY_AUDIENCE` (see + /// [`fleetify_core::endpoints`]). The shell's OAuth client resolves the + /// same values, so the tokens it obtains are the ones validated here. + pub fn from_env() -> Self { + Self::new(endpoints::issuer_origin(), endpoints::api_resource()) + } } // ── Principal ─────────────────────────────────────────────────────── @@ -530,3 +538,19 @@ where Ok(AuthUser(user)) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn auth_config_new_derives_prod_urls() { + let c = AuthConfig::new( + "https://fleetify.dev".into(), + "https://fleetify.dev/api".into(), + ); + assert_eq!(c.auth_base, "https://fleetify.dev/api/auth"); + assert_eq!(c.jwks_url, "https://fleetify.dev/api/auth/jwks"); + assert_eq!(c.expected_audience, "https://fleetify.dev/api"); + } +} diff --git a/crates/fleetify-backend/src/services/telemetry/ws_client.rs b/crates/fleetify-backend/src/services/telemetry/ws_client.rs index 809dcb2..1624d46 100644 --- a/crates/fleetify-backend/src/services/telemetry/ws_client.rs +++ b/crates/fleetify-backend/src/services/telemetry/ws_client.rs @@ -31,14 +31,19 @@ const BACKOFF_INITIAL_S: u64 = 1; const BACKOFF_MAX_S: u64 = 30; const MAX_EVENTS_PER_FLUSH: i64 = 200; +/// The realtime endpoints live on the identity provider's origin: +/// production in release builds, `FLEETIFY_ISSUER` (default: the local +/// IdP) in debug builds — the same origin the shell signs in against. fn issuer() -> String { - std::env::var("FLEETIFY_ISSUER").unwrap_or_else(|_| "https://fleetify.dev".to_string()) + fleetify_core::endpoints::issuer_origin() } fn ticket_url() -> String { format!("{}/api/realtime/ticket", issuer().trim_end_matches('/')) } fn ws_url() -> String { - let base = issuer(); + ws_url_for(&issuer()) +} +fn ws_url_for(base: &str) -> String { let trimmed = base.trim_end_matches('/'); let url = if let Some(rest) = trimmed.strip_prefix("https://") { format!("wss://{rest}") @@ -418,14 +423,19 @@ mod tests { #[test] fn ws_url_translates_http_to_ws_and_https_to_wss() { - std::env::set_var("FLEETIFY_ISSUER", "https://fleetify.dev"); - assert_eq!(ws_url(), "wss://fleetify.dev/api/realtime/connect"); - std::env::set_var("FLEETIFY_ISSUER", "http://localhost:3001"); - assert_eq!(ws_url(), "ws://localhost:3001/api/realtime/connect"); + assert_eq!( + ws_url_for("https://fleetify.dev"), + "wss://fleetify.dev/api/realtime/connect" + ); + assert_eq!( + ws_url_for("http://localhost:3001"), + "ws://localhost:3001/api/realtime/connect" + ); // Trailing slash + no scheme = ws://. - std::env::set_var("FLEETIFY_ISSUER", "127.0.0.1:3001/"); - assert_eq!(ws_url(), "ws://127.0.0.1:3001/api/realtime/connect"); - std::env::remove_var("FLEETIFY_ISSUER"); + assert_eq!( + ws_url_for("127.0.0.1:3001/"), + "ws://127.0.0.1:3001/api/realtime/connect" + ); } #[test] diff --git a/crates/fleetify-core/src/endpoints.rs b/crates/fleetify-core/src/endpoints.rs new file mode 100644 index 0000000..7d00352 --- /dev/null +++ b/crates/fleetify-core/src/endpoints.rs @@ -0,0 +1,100 @@ +//! Auth endpoints shared by the desktop shell and the embedded backend. +//! +//! The shell's OAuth client and the backend's token validator must agree: +//! the shell asks the identity provider for an access token whose `aud` is +//! the API resource it names, and the backend accepts only tokens whose +//! `iss` is `{issuer}/api/auth` and whose `aud` is that same resource. +//! Both sides resolve the values here so they cannot drift apart. +//! +//! Release builds pin production `fleetify.dev` and ignore the environment, +//! so a variable left in a user's shell can neither break sign-in nor point +//! the app at another identity provider. Debug builds read the environment +//! (`npm run dev:tauri` sets it) so development can use a local IdP. + +/// Production identity-provider origin. better-auth serves under +/// `{origin}/api/auth` and stamps that base into every token's `iss`. +pub const PROD_ISSUER: &str = "https://fleetify.dev"; + +/// Production API resource indicator (RFC 8707): the `aud` of every access +/// token the shell requests and the embedded backend accepts. +pub const PROD_API_RESOURCE: &str = "https://fleetify.dev/api"; + +/// Debug default issuer: a local identity provider. +const DEV_ISSUER: &str = "http://localhost:3001"; + +/// Debug default resource: the embedded backend's loopback origin. +const DEV_API_RESOURCE: &str = "http://127.0.0.1:8765"; + +/// Identity-provider origin, without the `/api/auth` suffix. Release builds +/// return [`PROD_ISSUER`]; debug builds read `FLEETIFY_ISSUER` through `env` +/// and fall back to a local IdP. +pub fn issuer_origin_for(release: bool, env: &dyn Fn(&str) -> Option) -> String { + if release { + return PROD_ISSUER.to_string(); + } + env("FLEETIFY_ISSUER").unwrap_or_else(|| DEV_ISSUER.to_string()) +} + +/// API resource indicator, which is also the expected token audience. +/// Release builds return [`PROD_API_RESOURCE`]; debug builds read +/// `FLEETIFY_RESOURCE`, then `FLEETIFY_AUDIENCE`, through `env` and fall +/// back to the embedded backend's loopback origin. +pub fn api_resource_for(release: bool, env: &dyn Fn(&str) -> Option) -> String { + if release { + return PROD_API_RESOURCE.to_string(); + } + env("FLEETIFY_RESOURCE") + .or_else(|| env("FLEETIFY_AUDIENCE")) + .unwrap_or_else(|| DEV_API_RESOURCE.to_string()) +} + +/// [`issuer_origin_for`] for this build profile and the process environment. +pub fn issuer_origin() -> String { + issuer_origin_for(!cfg!(debug_assertions), &|k| std::env::var(k).ok()) +} + +/// [`api_resource_for`] for this build profile and the process environment. +pub fn api_resource() -> String { + api_resource_for(!cfg!(debug_assertions), &|k| std::env::var(k).ok()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn release_pins_prod_issuer_even_when_env_is_set() { + let env = |k: &str| (k == "FLEETIFY_ISSUER").then(|| "http://evil.test".to_string()); + assert_eq!(issuer_origin_for(true, &env), "https://fleetify.dev"); + } + + #[test] + fn debug_issuer_defaults_to_local_idp_and_honours_env() { + assert_eq!(issuer_origin_for(false, &|_| None), "http://localhost:3001"); + assert_eq!( + issuer_origin_for(false, &|_| Some("http://idp.test".into())), + "http://idp.test" + ); + } + + #[test] + fn release_pins_prod_resource() { + assert_eq!( + api_resource_for(true, &|_| Some("http://evil.test".into())), + "https://fleetify.dev/api" + ); + } + + #[test] + fn debug_resource_prefers_resource_then_audience_then_default() { + let both = |k: &str| match k { + "FLEETIFY_RESOURCE" => Some("a".into()), + "FLEETIFY_AUDIENCE" => Some("b".into()), + _ => None, + }; + let aud = |k: &str| (k == "FLEETIFY_AUDIENCE").then(|| "b".to_string()); + assert_eq!(api_resource_for(false, &both), "a"); + assert_eq!(api_resource_for(false, &aud), "b"); + assert_eq!(api_resource_for(false, &|_| None), "http://127.0.0.1:8765"); + } +} diff --git a/crates/fleetify-core/src/lib.rs b/crates/fleetify-core/src/lib.rs index b80eddd..1a368bb 100644 --- a/crates/fleetify-core/src/lib.rs +++ b/crates/fleetify-core/src/lib.rs @@ -2,6 +2,8 @@ use std::path::{Path, PathBuf}; +pub mod endpoints; + /// Backend wire-protocol version. Bumped only on breaking WS/REST changes. pub const PROTOCOL_VERSION: u32 = 1; diff --git a/src-tauri/src/shell/auth.rs b/src-tauri/src/shell/auth.rs index 164074c..718d20f 100644 --- a/src-tauri/src/shell/auth.rs +++ b/src-tauri/src/shell/auth.rs @@ -61,12 +61,10 @@ fn noauth_tokens() -> Tokens { scope: DEFAULT_SCOPES.into(), } } +/// Identity-provider origin; production in release builds. Shared with the +/// embedded backend's token validation via `fleetify_core::endpoints`. pub fn issuer() -> String { - if is_prod() { - "https://fleetify.dev".into() - } else { - env_or("FLEETIFY_ISSUER", "http://localhost:3001") - } + fleetify_core::endpoints::issuer_origin() } pub fn auth_base() -> String { format!("{}/api/auth", issuer()) @@ -78,12 +76,10 @@ fn dashboard_url() -> String { env_or("FLEETIFY_DASHBOARD_URL", "http://localhost:5174") } } +/// RFC 8707 resource indicator: the audience the embedded backend expects +/// (`fleetify_core::endpoints`); production in release builds. fn resource() -> String { - if is_prod() { - "https://fleetify.dev/api".into() - } else { - env_or("FLEETIFY_RESOURCE", "http://127.0.0.1:8765") - } + fleetify_core::endpoints::api_resource() } #[derive(Clone, Serialize)] @@ -516,3 +512,18 @@ pub async fn get_access_token(force: bool) -> Option { Err(_) => None, } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Tokens the shell requests must pass the embedded backend's checks: + /// the backend expects `iss` = the shell's auth base and `aud` = the + /// `resource` the shell names. Both read the same environment here. + #[test] + fn shell_requests_tokens_the_embedded_backend_accepts() { + let backend = fleetify_backend::auth::AuthConfig::from_env(); + assert_eq!(auth_base(), backend.auth_base); + assert_eq!(resource(), backend.expected_audience); + } +} From 5699555337bf0bc80e6fb9fc48d2414508d5d7bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:35:29 +0300 Subject: [PATCH 03/76] fix(backend): release builds ignore .env files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The embedded backend called dotenvy::dotenv() on every start, and dotenvy takes the first .env it finds in the working directory or any of its ancestors. Launching a release build from a terminal inside some project therefore let that project's .env configure Fleetify: the sessions database (FLEET_DB_URL), the data directory (FLEETIFY_HOME), the PostHog and Not Diamond keys, and anything else read from the process environment after startup. Only debug builds load .env now. The call site asks should_load_dotenv(!cfg!(debug_assertions)), the same release check the auth endpoints use, and a unit test pins the rule. Debug builds keep today's behaviour, so the single-file dev config under npm run dev:tauri still works. .env.example now states that only debug builds read the file and marks NOTDIAMOND_API_KEY as development-only. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- .env.example | 16 +++++++++----- crates/fleetify-backend/src/lib.rs | 35 +++++++++++++++++++++++++----- 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/.env.example b/.env.example index edc02e8..26b2738 100644 --- a/.env.example +++ b/.env.example @@ -1,9 +1,14 @@ # Fleetify local dev secrets. Copy to `.env` (gitignored) and fill in. # -# `dotenvy` loads this into the backend's process env at the top of -# `serve_with_routing_setup` so the Rust side picks it up via -# `std::env::var`. Vite reads `.env`/`.env.local` natively for the -# renderer. Existing shell env wins — set values here are a fallback. +# Only debug builds read `.env` at runtime. In a debug build +# (`npm run dev:tauri`), `dotenvy` loads it into the backend's process env +# at the top of `serve_with_routing_setup` so the Rust side picks it up via +# `std::env::var`. Release builds never read it: a project's `.env` in the +# directory Fleetify is launched from must not configure the app. Existing +# shell env wins — set values here are a fallback. +# +# Vite reads `.env`/`.env.local` natively for the renderer: the dev server +# exposes the `VITE_*` values, and `vite build` inlines them into the bundle. # PostHog product analytics. Both halves should match so backend + frontend # events flow into the same PostHog project. Keys are `phc_*` public keys @@ -17,7 +22,8 @@ VITE_POSTHOG_HOST=https://us.i.posthog.com # Not Diamond — Fleet-owned routing key for the "Auto" model picker. Read at # runtime by the backend (std::env::var). Fleet's own key, independent of any # Not Diamond a user connects in Settings → Routers. Unset ⇒ Auto falls back to -# the offline built-in router. +# the offline built-in router. Development only: never set it in CI or in +# release builds. NOTDIAMOND_API_KEY= # Model catalog API — the published provider/model catalog the picker fetches at diff --git a/crates/fleetify-backend/src/lib.rs b/crates/fleetify-backend/src/lib.rs index 5cfaa46..dca4409 100644 --- a/crates/fleetify-backend/src/lib.rs +++ b/crates/fleetify-backend/src/lib.rs @@ -154,6 +154,14 @@ fn resolve_db_path_in(configured: &str, home: PathBuf, isolate: bool) -> PathBuf } } +/// Whether startup loads a `.env` file into the process environment. Only +/// debug builds do. `dotenvy` searches the working directory and its +/// ancestors, so a release build launched from a terminal inside some +/// project would otherwise pick up that project's `.env`. +pub(crate) fn should_load_dotenv(release_build: bool) -> bool { + !release_build +} + /// Bind `addr` and start serving, hydrating the routing orchestrator with /// the supplied `routing_setup`. The Tauri shell composes the setup from /// `fleet.config.json` + the per-user keychain before invoking this so @@ -163,12 +171,16 @@ pub async fn serve_with_routing_setup( static_dir: Option, routing_setup: services::routing::setup::RoutingSetup, ) -> anyhow::Result { - // Load `.env` from the workspace root (if present) into the process - // environment. Existing env vars are NOT overridden — a real shell-set - // value wins over the file. No-op when `.env` is absent, which is the - // production case. Powers single-source dev config for POSTHOG_API_KEY - // and similar without forcing a wrapper shell script. - let _ = dotenvy::dotenv(); + // Debug builds load the first `.env` found walking up from the working + // directory (the workspace root's under `npm run dev:tauri`) into the + // process environment. Existing env vars are NOT overridden — a real + // shell-set value wins over the file. Powers single-source dev config + // for POSTHOG_API_KEY and similar without forcing a wrapper shell + // script. Release builds never read `.env`: a project's `.env` in the + // launch directory must not configure Fleetify. + if should_load_dotenv(!cfg!(debug_assertions)) { + let _ = dotenvy::dotenv(); + } // Lifespan parity: one-shot ~/.fleet → ~/.fleetify migration. services::migration::migrate_fleet_to_fleetify(); @@ -558,3 +570,14 @@ mod db_path_tests { ); } } + +#[cfg(test)] +mod dotenv_tests { + use super::should_load_dotenv; + + #[test] + fn dotenv_is_read_only_by_debug_builds() { + assert!(!should_load_dotenv(true)); + assert!(should_load_dotenv(false)); + } +} From a95c55926729677b86346308361a82b85fb7715f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:58:58 +0300 Subject: [PATCH 04/76] fix(keychain): keep Linux sign-in and API keys across reboots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every crate built keyring with its linux-native store, the kernel keyutils keyring, which keyring's own documentation describes as in-memory and not persistent across reboots. On Linux the OIDC refresh token, provider API keys and the other stored secrets were gone after every restart of the machine, so the user had to sign in and re-enter their keys. Build keyring with linux-native-sync-persistent and crypto-rust. That makes the Secret Service (GNOME Keyring, KWallet, ...) the default Linux store and encrypts secrets on the D-Bus wire. fleetify-backend, src-tauri and fleet-wipe now declare the same feature set. keyring scopes its Linux dependencies to Linux targets, so Windows and macOS builds resolve exactly as before, except that fleet-wipe built on its own on macOS now gets the Keychain store instead of the mock one. Building on Linux needs libdbus-1-dev and pkg-config, which the Tauri shell already required through tao. A fleetify-backend test fails to compile on Linux if the persistent store is dropped from the feature set again. Entries written by earlier builds exist only in the kernel keyring and are not migrated; they have to be entered once more. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- Cargo.lock | 473 ++++++++++++++++++ crates/fleet-wipe/Cargo.toml | 9 +- crates/fleetify-backend/Cargo.toml | 9 +- .../src/bridges/antigravity_sdk.rs | 9 + src-tauri/Cargo.toml | 6 +- 5 files changed, 496 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bcdc800..49c59d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -120,6 +131,106 @@ dependencies = [ "serde_json", ] +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.4", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.4", +] + +[[package]] +name = "async-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.4", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + [[package]] name = "async-stream" version = "0.3.6" @@ -142,6 +253,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + [[package]] name = "async-trait" version = "0.1.89" @@ -346,6 +463,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.6.2" @@ -355,6 +481,19 @@ dependencies = [ "objc2", ] +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "brotli" version = "8.0.2" @@ -496,6 +635,15 @@ dependencies = [ "toml 0.9.12+spec-1.1.0", ] +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.2.62" @@ -647,6 +795,16 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + [[package]] name = "clang-sys" version = "1.8.1" @@ -973,6 +1131,24 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "dbus-secret-service" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" +dependencies = [ + "aes", + "block-padding", + "cbc", + "dbus", + "fastrand", + "hkdf", + "num", + "once_cell", + "sha2", + "zeroize", +] + [[package]] name = "deadpool" version = "0.12.3" @@ -1241,6 +1417,33 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -1296,6 +1499,16 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + [[package]] name = "fastrand" version = "2.4.1" @@ -1602,6 +1815,19 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.32" @@ -2411,6 +2637,16 @@ dependencies = [ "libc", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + [[package]] name = "ioctl-rs" version = "0.1.6" @@ -2604,8 +2840,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" dependencies = [ "byteorder", + "dbus-secret-service", "linux-keyutils", "log", + "secret-service", "security-framework 2.11.1", "security-framework 3.7.0", "windows-sys 0.60.2", @@ -3035,6 +3273,19 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.11.1", + "cfg-if", + "cfg_aliases 0.2.1", + "libc", + "memoffset 0.9.1", +] + [[package]] name = "nom" version = "7.1.3" @@ -3084,6 +3335,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + [[package]] name = "num-bigint" version = "0.4.6" @@ -3110,6 +3375,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -3147,6 +3421,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -3432,6 +3717,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + [[package]] name = "pango" version = "0.18.3" @@ -3582,6 +3877,17 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkcs1" version = "0.7.5" @@ -3654,6 +3960,20 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + [[package]] name = "portable-pty" version = "0.8.1" @@ -4338,6 +4658,25 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "secret-service" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4" +dependencies = [ + "aes", + "cbc", + "futures-util", + "generic-array", + "hkdf", + "num", + "once_cell", + "rand 0.8.6", + "serde", + "sha2", + "zbus", +] + [[package]] name = "security-framework" version = "2.11.1" @@ -5024,6 +5363,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "string_cache" version = "0.9.0" @@ -6092,6 +6437,17 @@ version = "1.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset 0.9.1", + "tempfile", + "windows-sys 0.60.2", +] + [[package]] name = "unic-char-property" version = "0.9.0" @@ -7434,6 +7790,16 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "xdg-home" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + [[package]] name = "yoke" version = "0.8.2" @@ -7457,6 +7823,62 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725" +dependencies = [ + "async-broadcast", + "async-process", + "async-recursion", + "async-trait", + "enumflags2", + "event-listener", + "futures-core", + "futures-sink", + "futures-util", + "hex", + "nix 0.29.0", + "ordered-stream", + "rand 0.8.6", + "serde", + "serde_repr", + "sha1", + "static_assertions", + "tracing", + "uds_windows", + "windows-sys 0.52.0", + "xdg-home", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.117", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c" +dependencies = [ + "serde", + "static_assertions", + "zvariant", +] + [[package]] name = "zerocopy" version = "0.8.48" @@ -7503,6 +7925,20 @@ name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] name = "zerotrie" @@ -7586,3 +8022,40 @@ checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ "zune-core", ] + +[[package]] +name = "zvariant" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe" +dependencies = [ + "endi", + "enumflags2", + "serde", + "static_assertions", + "zvariant_derive", +] + +[[package]] +name = "zvariant_derive" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.117", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] diff --git a/crates/fleet-wipe/Cargo.toml b/crates/fleet-wipe/Cargo.toml index ae2e305..b107eca 100644 --- a/crates/fleet-wipe/Cargo.toml +++ b/crates/fleet-wipe/Cargo.toml @@ -5,9 +5,10 @@ edition.workspace = true license.workspace = true publish = false -# Linux: the app stores credentials in the KERNEL keyring (keyring crate's -# linux-keyutils backend), NOT the Secret Service — so `secret-tool` can't see -# them. We enumerate the kernel keyring directly and invalidate Fleetify keys. +# Linux: builds before the Secret Service store kept credentials in the +# KERNEL keyring (keyring crate's linux-keyutils backend), which `secret-tool` +# can't see. We enumerate it directly and invalidate leftover Fleetify keys. +# Secret Service items are not cleared here. [target.'cfg(target_os = "linux")'.dependencies] linux-keyutils = "0.2" @@ -16,4 +17,4 @@ linux-keyutils = "0.2" # wipe.mjs's `security` / `cmdkey` enumeration. Feature set mirrors src-tauri # so the backend resolves identically. [target.'cfg(not(target_os = "linux"))'.dependencies] -keyring = { version = "3", features = ["windows-native"] } +keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] } diff --git a/crates/fleetify-backend/Cargo.toml b/crates/fleetify-backend/Cargo.toml index a83fc95..f22a169 100644 --- a/crates/fleetify-backend/Cargo.toml +++ b/crates/fleetify-backend/Cargo.toml @@ -43,9 +43,12 @@ glob = "0.3" # Antigravity SDK bridge reads `GEMINI_API_KEY` from the OS keyring under # `Fleetify-Provider-antigravity-sdk` — same store the Tauri shell writes # to via providers_link, so a single source of truth flows through. -# `windows-native` keeps the credential in the Windows Credential Manager -# (Tauri shell uses the same feature set). -keyring = { version = "3", features = ["windows-native", "apple-native", "linux-native"] } +# One feature set for every crate (src-tauri, fleet-wipe): Keychain on macOS, +# Credential Manager on Windows, Secret Service on Linux. Plain `linux-native` +# (the kernel keyring) is in-memory and loses every credential on reboot. The +# Secret Service store needs libdbus-1-dev + pkg-config to build on Linux; +# `crypto-rust` encrypts secrets on the D-Bus wire. +keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] } # Loads `.env` (workspace root) into the process environment at server # startup so single-source dev config (POSTHOG_API_KEY, POSTHOG_HOST, …) # works without a wrapper shell script. No-op when `.env` is absent — diff --git a/crates/fleetify-backend/src/bridges/antigravity_sdk.rs b/crates/fleetify-backend/src/bridges/antigravity_sdk.rs index 62ba5b8..fa25b72 100644 --- a/crates/fleetify-backend/src/bridges/antigravity_sdk.rs +++ b/crates/fleetify-backend/src/bridges/antigravity_sdk.rs @@ -730,4 +730,13 @@ mod tests { assert_eq!(b.autonomy_mode, "chat"); assert_eq!(b.model, "gemini-3.5-flash"); } + + // Fails to compile unless keyring's persistent Linux store is enabled: + // plain `linux-native` (keyutils) is in-memory and loses every credential on reboot. + #[cfg(target_os = "linux")] + #[test] + fn linux_keyring_store_survives_reboot() { + #[allow(unused_imports)] + use keyring::keyutils_persistent as _; + } } diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 1959c94..88d0b43 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -32,9 +32,9 @@ zip = { version = "2", default-features = false, features = ["deflate"] } serde.workspace = true serde_json.workspace = true anyhow.workspace = true -# Windows is the current build/dev target; per-OS backends (apple-native / -# sync-secret-service) get added behind cfg in Phase 5 packaging. -keyring = { version = "3", features = ["windows-native"] } +# Same feature set as fleetify-backend (rationale there): the Secret Service +# store keeps Linux sign-in and provider keys across reboots. +keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "multipart"] } sha2 = "0.10" base64 = "0.22" From 213426d95c8b12c10db88af0e01cff3c91c647c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:50:36 +0300 Subject: [PATCH 05/76] fix(wipe): clear Linux credentials from the Secret Service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The app now keeps its Linux credentials (OIDC refresh token, GitHub link, voice, provider and router keys) in the Secret Service, but the reset helper still swept only the kernel keyring. wipe.mjs's secret-tool pass could not help either: `secret-tool search --all` without an attribute pair is malformed, and secret-tool is often not installed. After `npm run wipe` on Linux the app stayed signed in and kept its API keys. fleet-wipe now deletes every Secret Service item keyring created whose service is Fleetify or Fleetify-*. It searches for application = rust-keyring, the value keyring's code sets (its 3.6.3 module docs say rust-keyring-client, which matches nothing). It prints only service and username, never reads a secret, and still sweeps the kernel keyring for entries that older builds left there. A real run first unlocks a locked default collection. GNOME Keyring shows a locked item only with hashed attributes and refuses to delete it, so after an auto-login boot the sweep would otherwise remove nothing. When the sweep fails, fleet-wipe exits 1, so wipe.mjs reports the failure instead of printing "cleared". wipe.mjs drops the secret-tool pass, and its header now says where Linux credentials live. The new Linux-only test stores throwaway items through keyring, as the app does, and fails when no Secret Service is reachable. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- Cargo.lock | 1 + crates/fleet-wipe/Cargo.toml | 17 ++- crates/fleet-wipe/src/main.rs | 248 +++++++++++++++++++++++++++++++--- scripts/wipe.mjs | 67 +++------ 4 files changed, 261 insertions(+), 72 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 49c59d8..8b4d26f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1581,6 +1581,7 @@ dependencies = [ name = "fleet-wipe" version = "0.1.0" dependencies = [ + "dbus-secret-service", "keyring", "linux-keyutils", ] diff --git a/crates/fleet-wipe/Cargo.toml b/crates/fleet-wipe/Cargo.toml index b107eca..ab22782 100644 --- a/crates/fleet-wipe/Cargo.toml +++ b/crates/fleet-wipe/Cargo.toml @@ -5,13 +5,22 @@ edition.workspace = true license.workspace = true publish = false -# Linux: builds before the Secret Service store kept credentials in the -# KERNEL keyring (keyring crate's linux-keyutils backend), which `secret-tool` -# can't see. We enumerate it directly and invalidate leftover Fleetify keys. -# Secret Service items are not cleared here. +# Linux: the app keeps credentials in the Secret Service (keyring crate's +# linux-native-sync-persistent store). We search it with dbus-secret-service, +# the crate and version keyring itself uses, and delete Fleetify items. Builds +# before that store kept credentials in the KERNEL keyring (keyring crate's +# linux-keyutils backend), which `secret-tool` can't see; we still enumerate it +# and invalidate leftover Fleetify keys. [target.'cfg(target_os = "linux")'.dependencies] +dbus-secret-service = { version = "4.1", features = ["crypto-rust"] } linux-keyutils = "0.2" +# The Secret Service test stores its throwaway item through keyring, the way +# the app does, so a keyring upgrade that changes item attributes fails it. +# Keep version and features in step with src-tauri and fleetify-backend. +[target.'cfg(target_os = "linux")'.dev-dependencies] +keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] } + # macOS (Keychain) / Windows (Credential Manager): delete the fixed login # entry via the same `keyring` crate the app uses, as a belt-and-suspenders to # wipe.mjs's `security` / `cmdkey` enumeration. Feature set mirrors src-tauri diff --git a/crates/fleet-wipe/src/main.rs b/crates/fleet-wipe/src/main.rs index e3a69a0..194fba0 100644 --- a/crates/fleet-wipe/src/main.rs +++ b/crates/fleet-wipe/src/main.rs @@ -2,39 +2,57 @@ //! credential half of `npm run wipe` (the file half lives in `scripts/wipe.mjs`). //! //! Why a Rust helper instead of a CLI inside wipe.mjs? The app stores secrets -//! through the `keyring` crate, whose backend differs per OS — and on Linux -//! that backend is the **kernel keyring** (`linux-keyutils`), *not* the Secret -//! Service. So `secret-tool` (what wipe.mjs used) targets the wrong store and -//! the OIDC refresh token survives a wipe → the app silently re-logs-in on the -//! next launch. This helper clears creds the SAME way the app wrote them. +//! through the `keyring` crate, whose backend differs per OS. If the OIDC +//! refresh token survives a wipe, the app silently re-logs-in on the next +//! launch. This helper finds credentials in the store the app wrote them to, +//! by the attributes keyring gives them, with no `secret-tool` install needed. //! -//! - Linux: enumerate the session + persistent kernel keyrings and invalidate -//! every `keyring-rs:*@Fleetify*` key (OIDC refresh token, GitHub link, -//! per-provider keys, per-router keys). +//! - Linux: the app's store is the **Secret Service** (GNOME Keyring, +//! KWallet, ...). Delete every item keyring created whose `service` is +//! `Fleetify` / `Fleetify-*` (OIDC refresh token, GitHub link, voice, +//! per-provider and per-router keys). Builds before that store used the +//! in-memory **kernel keyring** (`linux-keyutils`), so also invalidate any +//! leftover `keyring-rs:*@Fleetify*` key there. //! - macOS: wipe.mjs's `security delete-generic-password` already clears the //! login Keychain; here we also delete the refresh-token entry via the //! keyring crate as a backstop. //! - Windows: same backstop, behind wipe.mjs's `cmdkey`. //! -//! Reads only key *descriptions* (never secret values) and only ever touches -//! keys whose service is `Fleetify` / `Fleetify-*`. Pass `--dry-run` (or -//! `--check`) to list what WOULD be removed without changing anything. +//! Reads only item attributes and key *descriptions* (never secret values) +//! and only ever touches entries whose service is `Fleetify` / `Fleetify-*`. +//! Pass `--dry-run` (or `--check`) to list what WOULD be removed without +//! changing anything. Exits with status 1 when the Linux Secret Service sweep +//! fails (unreachable, left locked, or an item can't be deleted), so wipe.mjs +//! reports the failure. fn main() { let dry = std::env::args() .skip(1) .any(|a| a == "--dry-run" || a == "--check"); - let removed = wipe(dry); let verb = if dry { "would remove" } else { "removed" }; - println!("fleet-wipe: {verb} {removed} Fleetify credential(s)"); + match wipe(dry) { + Ok(removed) => println!("fleet-wipe: {verb} {removed} Fleetify credential(s)"), + Err(e) => { + eprintln!("fleet-wipe: {e}"); + std::process::exit(1); + } + } +} + +/// True for the keyring service names Fleetify uses: exactly `Fleetify` (the +/// OIDC refresh token) or `Fleetify-*` (`Fleetify-GitHub`, `Fleetify-Voice`, +/// `Fleetify-Provider-`, `Fleetify-Router-`). `FleetifyX`, `fleetify` +/// and another app's services never match. +// Only the Linux sweeps match service names; on Windows/macOS these helpers +// are unused, so silence dead-code there (keeps `clippy -D warnings` green). +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn is_fleetify_service(service: &str) -> bool { + service == "Fleetify" || service.starts_with("Fleetify-") } /// True for `keyring`-crate key descriptions that belong to Fleetify. The /// linux-keyutils backend names keys `keyring-rs:@`; we match -/// on the `` half being `Fleetify` or `Fleetify-*` so a stray -/// `NotFleetify` or another app's key is never touched. -// Only the Linux `wipe` enumerates key descriptions; on Windows/macOS this -// helper is unused, so silence dead-code there (keeps `clippy -D warnings` green). +/// on the `` half with [`is_fleetify_service`]. #[cfg_attr(not(target_os = "linux"), allow(dead_code))] fn is_fleetify_desc(desc: &str) -> bool { let Some(rest) = desc.strip_prefix("keyring-rs:") else { @@ -43,12 +61,99 @@ fn is_fleetify_desc(desc: &str) -> bool { let Some(at) = rest.rfind('@') else { return false; }; - let service = &rest[at + 1..]; - service == "Fleetify" || service.starts_with("Fleetify-") + is_fleetify_service(&rest[at + 1..]) } +/// The `application` attribute keyring puts on every Secret Service item it +/// creates. keyring 3.6.3's module docs say `rust-keyring-client`, but its code +/// (`SsCredential::new_with_target`) and its own tests use `rust-keyring`, as +/// keyring 1.x and 2.x did. The Secret Service test fails if this drifts. #[cfg(target_os = "linux")] -fn wipe(dry: bool) -> usize { +const KEYRING_APPLICATION: &str = "rust-keyring"; + +/// Deletes the Secret Service items keyring created whose `service` attribute +/// satisfies `matches`, or with `dry_run` only lists them. Prints one line per +/// item with its service and username; secrets are never read. Returns how +/// many items it removed (or would remove). +#[cfg(target_os = "linux")] +fn wipe_secret_service(matches: &dyn Fn(&str) -> bool, dry_run: bool) -> Result { + use dbus_secret_service::{EncryptionType, SecretService}; + use std::collections::HashMap; + + let ss = SecretService::connect(EncryptionType::Dh) + .map_err(|e| format!("cannot reach the Secret Service: {e}"))?; + + // keyring creates its items in the default collection. While that + // collection is locked (e.g. after an auto-login boot), its items come + // back locked: GNOME Keyring then shows only hashed attributes, so their + // `service` can't be matched, and refuses to delete them. So a real run + // unlocks it first, which shows the same prompt the app shows on its + // first keyring access. A dry run changes nothing and only says so. + if let Ok(collection) = ss.get_default_collection() { + if collection.is_locked().unwrap_or(false) { + if dry_run { + println!( + " ! Secret Service: the default collection is locked, so its items \ + are not listed (a real run asks to unlock it)" + ); + } else { + collection.unlock().map_err(|e| { + format!("cannot unlock the Secret Service default collection: {e}") + })?; + } + } + } + + let found = ss + .search_items(HashMap::from([("application", KEYRING_APPLICATION)])) + .map_err(|e| format!("Secret Service search failed: {e}"))?; + let mut count = 0; + let mut failed = 0; + // Items that are still locked sit in another locked collection (or the + // default one, in a dry run). They are skipped: Fleetify writes only to + // the default collection. + for item in &found.unlocked { + let Ok(attributes) = item.get_attributes() else { + continue; + }; + let Some(service) = attributes.get("service").filter(|s| matches(s.as_str())) else { + continue; + }; + let username = attributes.get("username").map_or("", String::as_str); + let what = format!("service={service} username={username}"); + if dry_run { + println!(" · Secret Service: {what}"); + count += 1; + } else if let Err(e) = item.delete() { + eprintln!(" ! failed to delete Secret Service item {what}: {e}"); + failed += 1; + } else { + println!(" ✓ Secret Service: {what}"); + count += 1; + } + } + if failed > 0 { + return Err(format!( + "{failed} Secret Service item(s) could not be deleted" + )); + } + Ok(count) +} + +/// Linux: the app keeps credentials in the Secret Service; builds before that +/// store kept them in the kernel keyring. Sweep both, even when the Secret +/// Service fails, and report that failure afterwards. +#[cfg(target_os = "linux")] +fn wipe(dry: bool) -> Result { + let secret_service = wipe_secret_service(&is_fleetify_service, dry); + let kernel = wipe_kernel_keyring(dry); + Ok(secret_service? + kernel) +} + +/// Invalidates the `keyring-rs:*@Fleetify*` keys that builds before the Secret +/// Service store left in the kernel keyring. +#[cfg(target_os = "linux")] +fn wipe_kernel_keyring(dry: bool) -> usize { use linux_keyutils::{KeyRing, KeyRingIdentifier}; use std::collections::HashSet; @@ -104,7 +209,12 @@ fn wipe(dry: bool) -> usize { } #[cfg(not(target_os = "linux"))] -fn wipe(dry: bool) -> usize { +fn wipe(dry: bool) -> Result { + Ok(wipe_keychain(dry)) +} + +#[cfg(not(target_os = "linux"))] +fn wipe_keychain(dry: bool) -> usize { // macOS Keychain / Windows Credential Manager. wipe.mjs's `security` / // `cmdkey` enumeration clears every `Fleetify*` service by name; this is a // backstop that removes the fixed login refresh-token entry directly via the @@ -139,3 +249,99 @@ fn wipe(dry: bool) -> usize { } } } + +#[cfg(test)] +mod tests { + use super::{is_fleetify_desc, is_fleetify_service}; + + #[test] + fn fleetify_services_match() { + for service in [ + "Fleetify", + "Fleetify-GitHub", + "Fleetify-Voice", + "Fleetify-Provider-x", + "Fleetify-Router-y", + ] { + assert!(is_fleetify_service(service), "{service:?} should match"); + } + } + + #[test] + fn other_services_do_not_match() { + for service in ["FleetifyX", "fleetify", "Other-Fleetify", ""] { + assert!( + !is_fleetify_service(service), + "{service:?} should not match" + ); + } + } + + #[test] + fn kernel_key_descriptions_match_on_their_service_half() { + assert!(is_fleetify_desc("keyring-rs:refresh_token@Fleetify")); + assert!(is_fleetify_desc("keyring-rs:sub@tenant@Fleetify-GitHub")); + assert!(is_fleetify_desc("keyring-rs:default@Fleetify-Provider-x")); + assert!(!is_fleetify_desc("keyring-rs:refresh_token@FleetifyX")); + assert!(!is_fleetify_desc("keyring-rs:Fleetify@Other-Fleetify")); + assert!(!is_fleetify_desc("refresh_token@Fleetify")); + assert!(!is_fleetify_desc("keyring-rs:no-service")); + } +} + +/// Runs against the real Secret Service on the session bus and fails, rather +/// than skips, when there is none. It creates, matches and deletes only its own +/// uniquely named items: the matcher accepts exactly one test service name, so +/// real Fleetify items are never printed or deleted. +#[cfg(all(test, target_os = "linux"))] +mod secret_service_tests { + use super::wipe_secret_service; + use std::time::{SystemTime, UNIX_EPOCH}; + + /// Deletes its test item when dropped, so a failed assertion leaves + /// nothing behind in the keyring. + struct Cleanup(keyring::Entry); + + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = self.0.delete_credential(); + } + } + + /// Stores a throwaway item the way the app stores its credentials. + fn store(service: &str) -> Cleanup { + let entry = keyring::Entry::new(service, "wipe-test").expect("keyring entry"); + if let Err(e) = entry.set_password("not-a-real-secret") { + panic!( + "this test needs a Secret Service provider (e.g. an unlocked \ + gnome-keyring-daemon) on the session bus; storing a test item failed: {e}" + ); + } + Cleanup(entry) + } + + #[test] + fn deletes_only_the_matching_item_keyring_created() { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock after 1970") + .as_nanos(); + let service = format!("Fleetify-WipeTest-{}-{nanos}", std::process::id()); + let target = store(&service); + let other = store(&format!("{service}-keep")); + let only_target = |s: &str| s == service; + + assert_eq!(wipe_secret_service(&only_target, true), Ok(1), "dry run"); + assert!(target.0.get_password().is_ok(), "a dry run must not delete"); + + assert_eq!(wipe_secret_service(&only_target, false), Ok(1), "real run"); + assert!( + matches!(target.0.get_password(), Err(keyring::Error::NoEntry)), + "the matching item should be gone" + ); + assert!( + other.0.get_password().is_ok(), + "a non-matching item must stay" + ); + } +} diff --git a/scripts/wipe.mjs b/scripts/wipe.mjs index 90837be..d970716 100644 --- a/scripts/wipe.mjs +++ b/scripts/wipe.mjs @@ -19,18 +19,20 @@ * ~/.cache, which is just cache). * 3. OS credential store — every entry whose service is `Fleetify` * or `Fleetify-*` (OIDC refresh token, - * `Fleetify-GitHub`, `Fleetify-Provider-`, + * `Fleetify-GitHub`, `Fleetify-Voice`, + * `Fleetify-Provider-`, * `Fleetify-Router-`). Backend differs by * OS: macOS Keychain (`security`), Windows * Credential Manager (`cmdkey`), and on Linux - * the KERNEL keyring (linux-keyutils) cleared - * via the `fleet-wipe` helper — secret-tool - * targets the Secret Service, the wrong store. + * the Secret Service (GNOME Keyring, KWallet, + * ...) cleared via the `fleet-wipe` helper, + * which also sweeps the kernel keyring that + * builds before the Secret Service used. * * Idempotent: missing paths are skipped silently. Logs every action so * you can audit what was touched. * - * Pass `--keep-keychain` to skip step 4 (useful when you want to reset + * Pass `--keep-keychain` to skip step 3 (useful when you want to reset * onboarding state without re-running OAuth). */ @@ -46,7 +48,6 @@ import { fileURLToPath } from "node:url"; import { isFleetifyKeychainTarget, parseMacKeychainDump, - parseSecretToolDump, } from "./wipe/keychain-filter.mjs"; const ARGS = new Set(process.argv.slice(2)); @@ -249,43 +250,18 @@ function wipeKeychainMac() { } } +// Linux — the app's `keyring` crate keeps credentials in the Secret Service +// (GNOME Keyring, KWallet, ...). We shell out to the `fleet-wipe` Rust helper: +// it deletes every Secret Service item keyring created whose service is +// `Fleetify` / `Fleetify-*` (the OIDC refresh token plus GitHub / voice / +// provider / router keys), and invalidates the `keyring-rs:*@Fleetify*` keys +// that builds before the Secret Service store left in the kernel keyring. No +// secret-tool needed. fleet-wipe exits non-zero when its Secret Service sweep +// fails (unreachable, left locked, or an item can't be deleted). function wipeKeychainLinux() { - // `secret-tool search --all` lists every secret with attributes; - // we never look at the secret value, only `attribute.service`. - const dump = spawnSync("secret-tool", ["search", "--all"], { encoding: "utf8" }); - if (dump.status !== 0) { - // Missing secret-tool is the common fresh-install case — log, - // don't error. - console.log(" · keychain skip secret-tool unavailable (status", dump.status, ")"); - return; - } - const services = parseSecretToolDump(dump.stdout); - if (services.length === 0) { - console.log(" · keychain skip no Fleetify* services found"); - return; - } - for (const service of services) { - const r = spawnSync("secret-tool", ["clear", "service", service], { encoding: "utf8" }); - if (r.status === 0) { - console.log(` ✓ keychain cleared service=${service}`); - } else { - console.log(` ✗ keychain FAILED service=${service}`); - if (r.stderr) console.log(` ${r.stderr.trim()}`); - } - } -} - -// Linux kernel keyring (linux-keyutils) — the store the app's `keyring` crate -// ACTUALLY uses on Linux (verified: `/proc/keys` holds -// `keyring-rs:refresh_token@Fleetify`). secret-tool / the Secret Service never -// see these keys, which is why a wipe left the user signed in. We shell out to -// the `fleet-wipe` Rust helper — it links the same backend the app does and -// invalidates every `keyring-rs:*@Fleetify*` key (the OIDC refresh token plus -// provider / github / router keys). -function wipeKeychainLinuxKernel() { const run = spawnSync("cargo", ["run", "-q", "-p", "fleet-wipe"], { encoding: "utf8" }); if (run.error) { - console.log(" ✗ keychain (kernel) FAILED could not run fleet-wipe via cargo"); + console.log(" ✗ keychain FAILED could not run fleet-wipe via cargo"); console.log(` ${run.error.message}`); console.log(" The OIDC refresh token may persist — install Rust/cargo, then re-run `npm run wipe`."); return; @@ -294,9 +270,9 @@ function wipeKeychainLinuxKernel() { if (line.trim()) console.log(` ${line.trimEnd()}`); } if (run.status === 0) { - console.log(" ✓ keychain (kernel) cleared via fleet-wipe (linux-keyutils)"); + console.log(" ✓ keychain cleared via fleet-wipe (Secret Service + kernel keyring)"); } else { - console.log(" ✗ keychain (kernel) FAILED fleet-wipe exited", run.status); + console.log(" ✗ keychain FAILED fleet-wipe exited", run.status); if (run.stderr) console.log(` ${run.stderr.trim()}`); } } @@ -320,11 +296,8 @@ if (KEEP_KEYCHAIN) { } else if (plat === "darwin") { wipeKeychainMac(); } else { - // Linux: the app's keyring backend is the KERNEL keyring (linux-keyutils), - // which secret-tool can't reach — clear it via the fleet-wipe helper. Still - // run secret-tool too (harmless) in case an older build wrote to the Secret - // Service. - wipeKeychainLinuxKernel(); + // Linux: fleet-wipe clears the Secret Service (the app's keyring store) and + // the kernel keyring older builds used. wipeKeychainLinux(); } From 514b847e3ec441300f621c350c6783713a93b7fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:21:19 +0300 Subject: [PATCH 06/76] fix(auth): warn when the sign-in cannot be saved to the keychain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Linux now keeps the refresh token in the Secret Service. When there is none (no GNOME Keyring or KWallet) or the user dismisses the unlock prompt, the save fails, and the shell discarded that error: the user looked signed in but started signed out after every restart, with nothing saying why. The shell now logs the failure and sends the renderer a keychain-unavailable auth event, after sign-in and after each token refresh. Sign-in itself still succeeds, because the access token is cached in the process and the current session keeps working. The renderer shows a dismissible banner at the top of the main shell that says the next launch will ask for sign-in again and how to fix it on Linux. A sign-out drops the banner, since it was about that sign-in. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- src-tauri/src/shell/auth.rs | 36 ++++++-- src/App.tsx | 15 ++-- .../keychain-warning-banner.test.tsx | 61 ++++++++++++++ src/components/layout/app-shell.tsx | 5 ++ .../layout/keychain-warning-banner.tsx | 83 +++++++++++++++++++ src/lib/__tests__/auth-events.test.ts | 37 +++++++++ src/lib/auth-events.ts | 33 ++++++++ src/stores/app-store.ts | 7 ++ 8 files changed, 266 insertions(+), 11 deletions(-) create mode 100644 src/components/layout/__tests__/keychain-warning-banner.test.tsx create mode 100644 src/components/layout/keychain-warning-banner.tsx create mode 100644 src/lib/__tests__/auth-events.test.ts create mode 100644 src/lib/auth-events.ts diff --git a/src-tauri/src/shell/auth.rs b/src-tauri/src/shell/auth.rs index 718d20f..2e1578d 100644 --- a/src-tauri/src/shell/auth.rs +++ b/src-tauri/src/shell/auth.rs @@ -159,9 +159,25 @@ fn keyring_entry() -> keyring::Result { fn keyring_get() -> Option { keyring_entry().ok().and_then(|e| e.get_password().ok()) } -fn keyring_set(v: &str) { - if let Ok(e) = keyring_entry() { - let _ = e.set_password(v); +fn keyring_set(v: &str) -> keyring::Result<()> { + keyring_entry()?.set_password(v) +} + +/// Auth event for a refresh token that could not be saved; the renderer +/// shows a warning banner on it. +fn keychain_failure_event() -> serde_json::Value { + serde_json::json!({"kind": "keychain-unavailable"}) +} + +/// Saves the refresh token so the next launch starts signed in. When the +/// keychain refuses it (Linux without an unlocked Secret Service, a +/// dismissed unlock prompt), sign-in still succeeds for this session (the +/// access token is cached in-process), but the next launch would silently +/// start signed out: log it and tell the renderer. +fn save_refresh_token(token: &str) { + if let Err(e) = keyring_set(token) { + tracing::warn!(error = %e, "could not save the refresh token to the system keychain"); + emit_event(keychain_failure_event()); } } fn keyring_del() { @@ -344,7 +360,7 @@ pub async fn sign_in() -> Result { .map_err(|e| AuthError::new(e.to_string(), "auth"))?; let tokens = decode_token_response(r).await?; *cached().lock().unwrap() = Some(tokens.clone()); - keyring_set(&tokens.refresh_token); + save_refresh_token(&tokens.refresh_token); Ok(tokens) } @@ -390,7 +406,7 @@ pub async fn refresh_if_needed(force: bool) -> Result { .map_err(|e| AuthError::new(e.to_string(), "auth"))?; let tokens = decode_token_response(r).await?; *cached().lock().unwrap() = Some(tokens.clone()); - keyring_set(&tokens.refresh_token); + save_refresh_token(&tokens.refresh_token); emit_event(serde_json::json!({"kind":"refreshed","expiresAt":tokens.expires_at})); Ok(tokens) } @@ -526,4 +542,14 @@ mod tests { assert_eq!(auth_base(), backend.auth_base); assert_eq!(resource(), backend.expected_audience); } + + /// The renderer raises its keychain warning banner on exactly this + /// payload (`src/lib/auth-events.ts`). + #[test] + fn keychain_failure_event_is_the_payload_the_renderer_handles() { + assert_eq!( + keychain_failure_event(), + serde_json::json!({"kind": "keychain-unavailable"}) + ); + } } diff --git a/src/App.tsx b/src/App.tsx index e472a27..278cab8 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -7,6 +7,7 @@ import { SetupScreen } from "@/components/onboarding/setup-screen"; import { useAppStore } from "@/stores/app-store"; import { usePluginStore } from "@/stores/plugin-store"; import { clearToken, type AuthUser } from "@/lib/api"; +import { handleAuthEvent } from "@/lib/auth-events"; import { identifyUser, initPostHog, pageview } from "@/lib/posthog"; import { isIntroComplete } from "@/lib/onboarding-gate"; @@ -223,12 +224,14 @@ export function App() { setScreen("splash"); }); - const off = window.fleetify.onAuthEvent((event) => { - if (event.kind === "signed-out") { - clearToken(); - setScreen("welcome"); - } - }); + const off = window.fleetify.onAuthEvent((event) => + handleAuthEvent(event, { + onSignedOut: () => { + clearToken(); + setScreen("welcome"); + }, + }), + ); return off; }, []); diff --git a/src/components/layout/__tests__/keychain-warning-banner.test.tsx b/src/components/layout/__tests__/keychain-warning-banner.test.tsx new file mode 100644 index 0000000..9eff9f6 --- /dev/null +++ b/src/components/layout/__tests__/keychain-warning-banner.test.tsx @@ -0,0 +1,61 @@ +/** + * The keychain warning banner: the shell emits `{ kind: "keychain-unavailable" }` + * when it cannot save the refresh token to the OS keychain, so the user is + * told now instead of finding themselves signed out at the next launch. + */ +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { render, screen, fireEvent, act } from "@testing-library/react"; +import { KeychainWarningBanner } from "../keychain-warning-banner"; +import { useAppStore } from "@/stores/app-store"; +import { handleAuthEvent } from "@/lib/auth-events"; + +const MESSAGE = + "Fleetify couldn't save your sign-in to the system keychain, so you'll need to sign in again next time. On Linux, install or unlock GNOME Keyring or KWallet to stay signed in."; + +describe("KeychainWarningBanner", () => { + beforeEach(() => { + useAppStore.setState({ keychainWarning: false }); + }); + + it("renders nothing while the flag is false", () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it("shows the exact warning and a Dismiss button when the flag is set", () => { + useAppStore.setState({ keychainWarning: true }); + render(); + const status = screen.getByRole("status"); + expect(status).toContainElement(screen.getByText(MESSAGE)); + expect(status).toContainElement(screen.getByRole("button", { name: "Dismiss" })); + }); + + it("Dismiss clears the flag and hides the banner", () => { + useAppStore.setState({ keychainWarning: true }); + const { container } = render(); + fireEvent.click(screen.getByRole("button", { name: "Dismiss" })); + expect(useAppStore.getState().keychainWarning).toBe(false); + expect(container).toBeEmptyDOMElement(); + }); + + it("appears when the shell reports keychain-unavailable through the auth-event handler", () => { + // Stand-in for window.fleetify.onAuthEvent: keeps the listener so the + // test can fire a shell event at it, the way App subscribes. + let emit: ((event: { kind: string }) => void) | undefined; + const onAuthEvent = vi.fn((cb: (event: { kind: string }) => void) => { + emit = cb; + return () => {}; + }); + const onSignedOut = vi.fn(); + onAuthEvent((event) => handleAuthEvent(event, { onSignedOut })); + + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + + act(() => emit?.({ kind: "keychain-unavailable" })); + + expect(useAppStore.getState().keychainWarning).toBe(true); + expect(screen.getByText(MESSAGE)).toBeInTheDocument(); + expect(onSignedOut).not.toHaveBeenCalled(); + }); +}); diff --git a/src/components/layout/app-shell.tsx b/src/components/layout/app-shell.tsx index cbeea4e..77c2468 100644 --- a/src/components/layout/app-shell.tsx +++ b/src/components/layout/app-shell.tsx @@ -6,6 +6,7 @@ import { RightPanelWrapper } from "./right-panel-wrapper"; import { NewAgentView } from "@/components/agent/new-agent-dialog"; import { FirstLaunchTour } from "@/components/onboarding/first-launch-tour"; import { WindowsTitleBar } from "./windows-title-bar"; +import { KeychainWarningBanner } from "./keychain-warning-banner"; import { StudioSession } from "@/components/studio/StudioSession"; import { StudioComposer } from "@/components/studio/StudioComposer"; import { isStudioTool } from "@/lib/studio-tools"; @@ -438,6 +439,10 @@ export function AppShell({ introReveal = false }: { introReveal?: boolean }) { sidebar/chat/right-panel grid. macOS renders nothing here. */} + {/* Full-width warning when the sign-in could not be saved to the OS + keychain; renders nothing otherwise. */} + +
, the only red is the icon. On macOS there + * is no in-app title bar, so the card starts right of the traffic lights + * (the same 84px inset the page top bars use). + */ +export function KeychainWarningBanner(): JSX.Element | null { + const show = useAppStore(s => s.keychainWarning); + const setKeychainWarning = useAppStore(s => s.setKeychainWarning); + + if (!show) return null; + + return ( +
+ + + {MESSAGE} + + +
+ ); +} + +/** Secondary button, as in . */ +const dismissStyle: CSSProperties = { + flexShrink: 0, + display: "inline-flex", + alignItems: "center", + padding: "5px 10px", + height: 26, + background: "transparent", + border: "1px solid var(--sidebar-border)", + borderRadius: 7, + color: "var(--c-med)", + fontSize: 11.5, + fontWeight: 500, + fontFamily: "inherit", + lineHeight: 1, + cursor: "pointer", + transition: "background 0.08s, color 0.08s", +}; diff --git a/src/lib/__tests__/auth-events.test.ts b/src/lib/__tests__/auth-events.test.ts new file mode 100644 index 0000000..a0ebf85 --- /dev/null +++ b/src/lib/__tests__/auth-events.test.ts @@ -0,0 +1,37 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { handleAuthEvent } from "@/lib/auth-events"; +import { useAppStore } from "@/stores/app-store"; + +describe("handleAuthEvent", () => { + beforeEach(() => { + useAppStore.setState({ keychainWarning: false }); + }); + + it("raises the keychain warning on keychain-unavailable", () => { + const onSignedOut = vi.fn(); + handleAuthEvent({ kind: "keychain-unavailable" }, { onSignedOut }); + expect(useAppStore.getState().keychainWarning).toBe(true); + expect(onSignedOut).not.toHaveBeenCalled(); + }); + + it("hands signed-out to the sign-out handler", () => { + const onSignedOut = vi.fn(); + handleAuthEvent({ kind: "signed-out", reason: "refresh-failed" }, { onSignedOut }); + expect(onSignedOut).toHaveBeenCalledTimes(1); + }); + + it("drops a pending keychain warning on signed-out, since it was about that sign-in", () => { + // Otherwise a later sign-in whose token DID save would reach the main + // screen still showing the old warning. + useAppStore.setState({ keychainWarning: true }); + handleAuthEvent({ kind: "signed-out", reason: "user" }, { onSignedOut: () => {} }); + expect(useAppStore.getState().keychainWarning).toBe(false); + }); + + it("ignores other events such as refreshed", () => { + const onSignedOut = vi.fn(); + handleAuthEvent({ kind: "refreshed", expiresAt: 1_700_000_000 }, { onSignedOut }); + expect(onSignedOut).not.toHaveBeenCalled(); + expect(useAppStore.getState().keychainWarning).toBe(false); + }); +}); diff --git a/src/lib/auth-events.ts b/src/lib/auth-events.ts new file mode 100644 index 0000000..5791690 --- /dev/null +++ b/src/lib/auth-events.ts @@ -0,0 +1,33 @@ +import { useAppStore } from "@/stores/app-store"; + +/** Payload of the shell's `fleet:auth-event` (src-tauri/src/shell/auth.rs). */ +export interface AuthEvent { + kind: string; + [k: string]: unknown; +} + +export interface AuthEventHandlers { + /** The shell ended the session: the user signed out, or a refresh failed. */ + onSignedOut: () => void; +} + +/** + * Routes one shell auth event from `window.fleetify.onAuthEvent`. Lives + * outside App.tsx so it can be tested without mounting the whole app. + * + * - `signed-out`: hands off to `onSignedOut` and drops the keychain warning, + * which was about the sign-in that just ended. + * - `keychain-unavailable`: the shell could not save the sign-in to the OS + * keychain, so the next launch starts signed out. Raises the warning + * banner (). + * + * Other kinds (`refreshed`, ...) need nothing here. + */ +export function handleAuthEvent(event: AuthEvent, { onSignedOut }: AuthEventHandlers): void { + if (event.kind === "signed-out") { + onSignedOut(); + useAppStore.getState().setKeychainWarning(false); + } else if (event.kind === "keychain-unavailable") { + useAppStore.getState().setKeychainWarning(true); + } +} diff --git a/src/stores/app-store.ts b/src/stores/app-store.ts index 14b2ca0..665f80e 100644 --- a/src/stores/app-store.ts +++ b/src/stores/app-store.ts @@ -281,6 +281,10 @@ interface AppState { pendingGeneration: PendingGeneration | null; newAgentDialogOpen: boolean; fleetAutoMode: boolean; + /** The shell could not save the sign-in to the OS keychain (shell auth + * event `keychain-unavailable`): this session works, but the next launch + * starts signed out. Drives . In memory only. */ + keychainWarning: boolean; _removedIds: Set; /** Compose surface state — see ComposerState docs. `open: false` means * the user is either on the Control Center (`activeSessionId === null`) @@ -347,6 +351,7 @@ interface AppState { setMainView: (view: MainView) => void; setAppMode: (mode: AppMode) => void; setNewAgentDialogOpen: (open: boolean) => void; + setKeychainWarning: (v: boolean) => void; /** Open the compose surface — pure client-side, no DB write, no * Session entry in `sessions[]`. Sets `composer.open = true` and * `activeSessionId = null`; chat-view detects the combination and @@ -455,6 +460,7 @@ export const useAppStore = create((set, get) => ({ pendingGeneration: null, newAgentDialogOpen: false, fleetAutoMode: localStorage.getItem("fleet:autoMode") === "true", + keychainWarning: false, composer: { open: false, projectPath: "", @@ -886,6 +892,7 @@ export const useAppStore = create((set, get) => ({ setPendingGeneration: (p) => set({ pendingGeneration: p }), clearPendingGeneration: () => set({ pendingGeneration: null }), setNewAgentDialogOpen: (open) => set({ newAgentDialogOpen: open }), + setKeychainWarning: (v) => set({ keychainWarning: v }), // ── Composer state (new) ── // The compose surface is NOT a session. Opening it sets composer.open // and clears activeSessionId; chat-view renders the welcome / folder From fae2d8e884aa2acad69b1ab4dcf63cbf110b88f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:50:07 +0300 Subject: [PATCH 07/76] ci(release): add a secret scanner for build artefacts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The release build job will run it over dist/ and the bundle outputs so that no private API key or token can ship inside an installer. It prints `: ` for each finding and never the matched value, so the CI log cannot become the leak. Exit 0 means clean and 1 means findings. Exit 2 means the scan could not be completed (no path, a missing or empty path, a read error), so a job pointed at the wrong directory fails instead of passing as clean. The test fixtures are assembled at runtime from runs of "x", so no token-shaped literal lands in the public repository. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- scripts/release/scan-secrets.mjs | 154 +++++++++++++++++++++ scripts/release/scan-secrets.test.mjs | 188 ++++++++++++++++++++++++++ 2 files changed, 342 insertions(+) create mode 100644 scripts/release/scan-secrets.mjs create mode 100644 scripts/release/scan-secrets.test.mjs diff --git a/scripts/release/scan-secrets.mjs b/scripts/release/scan-secrets.mjs new file mode 100644 index 0000000..39ab35b --- /dev/null +++ b/scripts/release/scan-secrets.mjs @@ -0,0 +1,154 @@ +#!/usr/bin/env node +/** + * scan-secrets.mjs — fail the release build when a private API key or + * token has made it into a build artefact (the frontend bundle in dist/, + * the app and sidecar binaries, the bundle outputs). + * + * node scripts/release/scan-secrets.mjs ... + * + * Each path is scanned recursively. Every rule that matches in a file is + * printed once to stdout as `: `. The matched value is never + * printed, so the CI log cannot become the leak. + * + * Exit codes: + * 0 clean + * 1 at least one finding + * 2 the scan could not be completed: no path given, a path that does not + * exist or holds no files, or a read error. A release job pointed at + * the wrong directory must fail rather than pass as "clean". + * + * Files are read as latin1 (one byte per character), so binaries scan + * safely: decoding never fails and no byte is replaced or shifted. + * Symlinks found while walking a directory are not followed, because an + * archive stores the link and not its target. Compressed payloads (.deb, + * the AppImage's squashfs, .dmg, the NSIS installer) are opaque to a text + * scan, so point the scanner at the uncompressed files too. + * + * Public-by-design values match no rule: the PostHog `phc_` project key + * and the OIDC client id `fleetify-desktop`. + */ +import { lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +/** + * Rules in report order. The regexes have no `g` flag, which keeps + * `test()` stateless between calls. + */ +export const RULES = Object.freeze([ + { name: "anthropic", pattern: /sk-ant-[A-Za-z0-9_-]{20,}/ }, + { name: "openai-project", pattern: /sk-proj-[A-Za-z0-9_-]{20,}/ }, + { name: "openai-legacy", pattern: /\bsk-[A-Za-z0-9]{40,}\b/ }, + { name: "github-token", pattern: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/ }, + { name: "aws-access-key", pattern: /\bAKIA[0-9A-Z]{16}\b/ }, + { name: "slack", pattern: /\bxox[abprs]-[A-Za-z0-9-]{10,}/ }, + { name: "private-key", pattern: /-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/ }, + { name: "notdiamond-assignment", pattern: /NOTDIAMOND_API_KEY\s*[=:]\s*["']?[A-Za-z0-9_-]{16,}/ }, +]); + +/** + * The rules that match `text`, each reported once, in RULES order. A + * finding names the file and the rule, never the matched value. + * + * @param {string} text + * @param {string} file + * @returns {Array<{ file: string, rule: string }>} + */ +export function scanText(text, file) { + return RULES.filter(({ pattern }) => pattern.test(text)).map(({ name }) => ({ + file, + rule: name, + })); +} + +/** + * Regular files at or under `path`, depth first in sorted order. The root + * may be a symlink (it was named explicitly). Inside a directory, symlinks + * and special files are skipped. Problems are appended to `errors`. + */ +function listFiles(path, errors, isRoot = false) { + let stats; + try { + stats = isRoot ? statSync(path) : lstatSync(path); + } catch (err) { + errors.push(`${path}: ${err.message}`); + return []; + } + if (stats.isFile()) return [path]; + if (!stats.isDirectory()) return []; + let names; + try { + names = readdirSync(path).sort(); + } catch (err) { + errors.push(`${path}: ${err.message}`); + return []; + } + return names.flatMap((name) => listFiles(join(path, name), errors)); +} + +/** + * Scan every regular file at or under each of `paths`. A path that yields + * no file to scan counts as an error. + * + * @param {string[]} paths + * @returns {{ findings: Array<{ file: string, rule: string }>, errors: string[], files: number }} + */ +export function scanPaths(paths) { + const findings = []; + const errors = []; + let files = 0; + for (const path of paths) { + const errorsBefore = errors.length; + const list = listFiles(path, errors, true); + if (list.length === 0 && errors.length === errorsBefore) { + errors.push(`${path}: no files to scan`); + } + for (const file of list) { + let text; + try { + text = readFileSync(file, "latin1"); + } catch (err) { + errors.push(`${file}: ${err.message}`); + continue; + } + files += 1; + findings.push(...scanText(text, file)); + } + } + return { findings, errors, files }; +} + +function main(args) { + if (args.length === 0) { + process.stderr.write("usage: node scripts/release/scan-secrets.mjs ...\n"); + return 2; + } + const { findings, errors, files } = scanPaths(args); + for (const { file, rule } of findings) process.stdout.write(`${file}: ${rule}\n`); + for (const message of errors) process.stderr.write(`scan-secrets: ${message}\n`); + if (errors.length > 0) { + process.stderr.write(`scan-secrets: ${errors.length} error(s), so the scan is incomplete\n`); + return 2; + } + if (findings.length > 0) { + process.stderr.write( + `scan-secrets: ${findings.length} finding(s) in ${files} scanned file(s); values are not printed\n`, + ); + return 1; + } + process.stderr.write(`scan-secrets: ${files} file(s) scanned, no secrets found\n`); + return 0; +} + +function invokedDirectly() { + try { + return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); + } catch { + return false; + } +} + +// exitCode instead of process.exit(): writes to a piped stdout can be +// asynchronous on some platforms, and exiting early could cut the +// findings short. +if (invokedDirectly()) process.exitCode = main(process.argv.slice(2)); diff --git a/scripts/release/scan-secrets.test.mjs b/scripts/release/scan-secrets.test.mjs new file mode 100644 index 0000000..8b39928 --- /dev/null +++ b/scripts/release/scan-secrets.test.mjs @@ -0,0 +1,188 @@ +/** + * Tests for scan-secrets.mjs, the secret scanner the release build runs + * over its artefacts. + * + * node --test scripts/release/scan-secrets.test.mjs + * + * Every fake credential below is assembled at runtime from short pieces + * and runs of "x"/"X", so no complete token-shaped string appears in this + * file: GitHub push protection (the repo is public), gitleaks and + * scan-secrets.mjs itself have nothing to match here. + */ +import { after, describe, test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { RULES, scanPaths, scanText } from "./scan-secrets.mjs"; + +const SCRIPT = fileURLToPath(new URL("./scan-secrets.mjs", import.meta.url)); + +const x = (n, ch = "x") => ch.repeat(n); + +// One fake value per rule. `hit` is the shortest string the rule flags; +// `miss` falls one character short of it (for private-key: a public key +// header) and must not be flagged. +const CASES = [ + { rule: "anthropic", hit: "sk-" + "ant-" + x(20), miss: "sk-" + "ant-" + x(19) }, + { rule: "openai-project", hit: "sk-" + "proj-" + x(20), miss: "sk-" + "proj-" + x(19) }, + { rule: "openai-legacy", hit: "sk-" + x(40), miss: "sk-" + x(39) }, + { rule: "github-token", hit: "gh" + "p_" + x(36), miss: "gh" + "p_" + x(35) }, + { rule: "aws-access-key", hit: "AKIA" + x(16, "X"), miss: "AKIA" + x(15, "X") }, + { rule: "slack", hit: "xo" + "xb-" + x(10), miss: "xo" + "xb-" + x(9) }, + { + rule: "private-key", + hit: "-----BEGIN " + "PRIVATE KEY-----", + miss: "-----BEGIN " + "PUBLIC KEY-----", + }, + { + rule: "notdiamond-assignment", + hit: "NOTDIAMOND_API_KEY" + "=" + x(16), + miss: "NOTDIAMOND_API_KEY" + "=" + x(15), + }, +]; + +const fake = (rule) => CASES.find((c) => c.rule === rule).hit; + +/** How a value sits in a minified bundle: a quoted string literal. */ +const line = (value) => `export const VALUE = "${value}";\n`; + +const ROOT = mkdtempSync(join(tmpdir(), "scan-secrets-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +/** Create ROOT/ holding `files` (relative path → content). */ +function tree(name, files) { + const dir = join(ROOT, name); + mkdirSync(dir, { recursive: true }); + for (const [rel, content] of Object.entries(files)) { + const file = join(dir, rel); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, content); + } + return dir; +} + +const runCli = (...args) => + spawnSync(process.execPath, [SCRIPT, ...args], { encoding: "utf8" }); + +describe("scanText", () => { + for (const { rule, hit } of CASES) { + test(`flags a fake ${rule} value as "${rule}"`, () => { + assert.deepEqual(scanText(line(hit), "assets/index.js"), [ + { file: "assets/index.js", rule }, + ]); + }); + } + + for (const { rule, miss } of CASES) { + test(`does not flag the ${rule} near miss`, () => { + assert.deepEqual(scanText(line(miss), "assets/index.js"), []); + }); + } + + test("does not flag the public-by-design PostHog key or OIDC client id", () => { + const text = + `posthog.init("phc_${x(43)}", { api_host: "https://us.i.posthog.com" });\n` + + `const clientId = "fleetify-desktop";\n`; + assert.deepEqual(scanText(text, "assets/index.js"), []); + }); + + test("reports a rule once per file, however often it matches", () => { + const text = line(fake("slack")).repeat(3); + assert.deepEqual(scanText(text, "app.js"), [{ file: "app.js", rule: "slack" }]); + }); + + test("every rule has a fixture above, in report order", () => { + assert.deepEqual( + RULES.map((r) => r.name), + CASES.map((c) => c.rule), + ); + }); +}); + +describe("scanPaths", () => { + test("walks a directory recursively, dotfiles included", () => { + const dir = tree("recursive", { + "index.html": "Fleetify\n", + "assets/deep/chunk.js": line(fake("anthropic")), + "config/.env": `${fake("notdiamond-assignment")}\n`, + }); + assert.deepEqual(scanPaths([dir]), { + findings: [ + { file: join(dir, "assets", "deep", "chunk.js"), rule: "anthropic" }, + { file: join(dir, "config", ".env"), rule: "notdiamond-assignment" }, + ], + errors: [], + files: 3, + }); + }); + + test("scans a binary file byte for byte", () => { + const file = join(tree("binary", {}), "fleetify-app"); + writeFileSync( + file, + Buffer.concat([ + // ELF magic, NUL bytes and a truncated UTF-8 sequence right before the value. + Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x00, 0x00, 0xff, 0xfe, 0xc3]), + Buffer.from(fake("github-token"), "latin1"), + Buffer.from([0x00, 0x80, 0xff]), + ]), + ); + assert.deepEqual(scanPaths([file]), { + findings: [{ file, rule: "github-token" }], + errors: [], + files: 1, + }); + }); +}); + +describe("CLI", () => { + test("exits 1 on a dirty directory, printing : and never the value", () => { + const dir = tree("cli-dirty", { + "README.txt": "nothing to see here\n", + "src/app.js": line(fake("aws-access-key")) + line(fake("slack")), + }); + const result = runCli(dir); + assert.equal(result.status, 1, result.stderr); + const file = join(dir, "src", "app.js"); + assert.equal(result.stdout, `${file}: aws-access-key\n${file}: slack\n`); + for (const value of [fake("aws-access-key"), fake("slack")]) { + assert.ok(!result.stdout.includes(value), "value leaked to stdout"); + assert.ok(!result.stderr.includes(value), "value leaked to stderr"); + } + }); + + test("exits 0 on a clean directory and prints no findings", () => { + const dir = tree("cli-clean", { + "index.html": `\n`, + "assets/auth.js": `const clientId = "fleetify-desktop";\n`, + }); + const result = runCli(dir); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout, ""); + }); + + test("exits 2 with a usage line when given no path", () => { + const result = runCli(); + assert.equal(result.status, 2); + assert.match(result.stderr, /usage/i); + }); + + test("exits 2 when a path does not exist, even if the others are clean", () => { + const clean = tree("cli-missing", { "index.html": "ok\n" }); + const missing = join(ROOT, "no-such-dir"); + const result = runCli(clean, missing); + assert.equal(result.status, 2); + assert.ok(result.stderr.includes(missing), result.stderr); + }); + + test("exits 2 when a path holds no files to scan", () => { + const empty = tree("cli-empty", {}); + const result = runCli(empty); + assert.equal(result.status, 2); + assert.match(result.stderr, /no files/); + }); +}); From e7c34939a51a2f98e0c871bf27d84733ba006342 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:12:07 +0300 Subject: [PATCH 08/76] feat(git): let users turn off Fleetify attribution in commits and PRs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commits the app makes carry a Fleetify co-author trailer, and PRs it opens through gh carry a "Created with Fleetify" footer, with no way to opt out. Settings > General > Attribution now has a switch, on by default, that saves gitAttribution to fleet.config.json. The Create PR command reads it on every call; when it is off, neither path adds the trailer and the gh path adds no footer. An existing Fleetify co-author line, whatever its casing or address, is never doubled. The General cards now merge each change into the config as it is when they save. config_set replaces the whole file, so a card that merged into the copy it read at mount undid whatever another card had saved since: turning attribution off and then flipping any other General switch silently turned attribution back on. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- src-tauri/src/shell/config.rs | 38 +++++ src-tauri/src/shell/git.rs | 158 ++++++++++++++++-- src-tauri/src/shell/ipc/mod.rs | 11 +- .../__tests__/attribution-card.test.tsx | 43 +++++ .../__tests__/general-section.test.tsx | 50 +++++- src/components/settings/general/_config.ts | 19 +++ .../settings/general/_primitives.tsx | 16 +- .../settings/general/attribution-card.tsx | 62 +++++++ .../settings/general/general-section.tsx | 10 +- .../settings/general/notifications-card.tsx | 7 +- .../settings/general/privacy-card.tsx | 7 +- .../settings/general/startup-card.tsx | 7 +- .../settings/general/updates-card.tsx | 7 +- src/vite-env.d.ts | 5 + 14 files changed, 394 insertions(+), 46 deletions(-) create mode 100644 src/components/settings/general/__tests__/attribution-card.test.tsx create mode 100644 src/components/settings/general/_config.ts create mode 100644 src/components/settings/general/attribution-card.tsx diff --git a/src-tauri/src/shell/config.rs b/src-tauri/src/shell/config.rs index e6282ef..f5ebec2 100644 --- a/src-tauri/src/shell/config.rs +++ b/src-tauri/src/shell/config.rs @@ -154,6 +154,16 @@ pub fn providers_set(cfg: &mut Value, providers: &ProvidersConfig) { } } +/// Whether the commits and pull requests the app makes credit Fleetify (a +/// `Co-Authored-By` trailer and a PR footer). Settings → General → +/// Attribution writes the flat `gitAttribution` key; absent or non-boolean +/// means on, the default. +pub fn git_attribution_from(cfg: &Value) -> bool { + cfg.get("gitAttribution") + .and_then(Value::as_bool) + .unwrap_or(true) +} + /// PostHog product-analytics opt-in. Default `posthog_enabled` is `false` — /// flipped only by explicit user consent in the onboarding step or in /// Settings → Privacy. `posthog_enabled_at` records the first opt-in @@ -396,6 +406,34 @@ mod tests { assert!(ProvidersConfig::default().cloudflare_account_id.is_none()); } + #[test] + fn attribution_defaults_on() { + assert!(git_attribution_from(&json!({}))); + } + + #[test] + fn attribution_respects_false() { + assert!(!git_attribution_from(&json!({"gitAttribution": false}))); + } + + #[test] + fn attribution_ignores_non_boolean_values() { + assert!(git_attribution_from(&json!({"gitAttribution": "false"}))); + assert!(git_attribution_from(&json!({"gitAttribution": 0}))); + assert!(git_attribution_from(&json!({"gitAttribution": null}))); + } + + #[test] + fn attribution_opt_out_survives_save_and_reload() { + let tmp = tempfile::tempdir().unwrap(); + save_config_to( + tmp.path(), + &json!({"theme": "dark", "gitAttribution": false}), + ) + .unwrap(); + assert!(!git_attribution_from(&load_config_from(tmp.path()))); + } + #[test] fn providers_and_routing_coexist_in_same_config() { // Sanity check that the two sections don't clobber each other — diff --git a/src-tauri/src/shell/git.rs b/src-tauri/src/shell/git.rs index eec76e6..cb107c8 100644 --- a/src-tauri/src/shell/git.rs +++ b/src-tauri/src/shell/git.rs @@ -776,20 +776,35 @@ pub async fn open_pr(folder: &Path, pr_number: Option) -> Value { } // ── Fleetify attribution helpers ───────────────────────────────── +// `enabled` is the user's Settings → General → Attribution choice (config +// key `gitAttribution`, on by default), read once per IPC command. When it is +// off, both helpers return the trimmed input unchanged. const FLEETIFY_CO_AUTHOR: &str = "Co-Authored-By: Fleetify "; const FLEETIFY_PR_FOOTER: &str = "\n\n---\nCreated with [Fleetify](https://fleetify.dev)"; -fn with_fleetify_trailer(message: &str) -> String { +/// True when `message` already has a `Co-Authored-By: Fleetify <…>` trailer, +/// matched case-insensitively on the key and name whatever the address, so a +/// commit never credits Fleetify twice. +fn has_fleetify_co_author(message: &str) -> bool { + message.lines().any(|line| { + line.trim_start() + .to_ascii_lowercase() + .strip_prefix("co-authored-by:") + .is_some_and(|rest| rest.trim_start().starts_with("fleetify <")) + }) +} + +fn with_fleetify_trailer(message: &str, enabled: bool) -> String { let trimmed = message.trim_end(); - if trimmed.contains("Fleetify ") { + if !enabled || has_fleetify_co_author(trimmed) { return trimmed.to_string(); } format!("{trimmed}\n\n{FLEETIFY_CO_AUTHOR}") } -fn with_fleetify_footer(body: &str) -> String { +fn with_fleetify_footer(body: &str, enabled: bool) -> String { let trimmed = body.trim_end(); - if trimmed.contains("fleetify.dev") || trimmed.contains("github.com/fleetifyai") { + if !enabled || trimmed.contains("fleetify.dev") || trimmed.contains("github.com/fleetifyai") { return trimmed.to_string(); } format!("{trimmed}{FLEETIFY_PR_FOOTER}") @@ -870,7 +885,9 @@ fn write_gitignore_if_missing(folder: &Path) -> bool { // `localStorage["fleet:github-auth-method"]` so the onboarding choice is // honoured exactly — picking "Use GitHub CLI" never silently routes // through OAuth, and vice versa. -// 8 args is one over the default 7; refactor to a struct is out of scope for this cleanup. +// `attribution` is the user's `gitAttribution` setting: whether the commits +// this flow makes (both paths) and the PR footer (gh path) credit Fleetify. +// 9 args is two over the default 7; refactor to a struct is out of scope for this cleanup. #[allow(clippy::too_many_arguments)] pub async fn create_pr( folder: &Path, @@ -881,6 +898,7 @@ pub async fn create_pr( feature_branch: Option<&str>, tool: Option<&str>, method: Option<&str>, + attribution: bool, ) -> Value { let want_gh = matches!(method, Some("gh") | Some("cli")); let want_oauth = matches!(method, Some("oauth") | Some("link")); @@ -914,7 +932,17 @@ pub async fn create_pr( }); } tracing::info!(target: "createPR", "dispatch-gh (requested)"); - return create_pr_via_gh(folder, title, body, base, draft, feature_branch, tool).await; + return create_pr_via_gh( + folder, + title, + body, + base, + draft, + feature_branch, + tool, + attribution, + ) + .await; } if want_oauth { let Some(token) = oauth_token else { @@ -925,7 +953,8 @@ pub async fn create_pr( }); }; tracing::info!(target: "createPR", "dispatch-link (requested)"); - let preflight = ensure_repo_for_link(folder, title, base, feature_branch, tool).await; + let preflight = + ensure_repo_for_link(folder, title, base, feature_branch, tool, attribution).await; if let Some(err) = preflight { return err; } @@ -943,11 +972,22 @@ pub async fn create_pr( // No preference — legacy gh-first then link fallback. if gh_authed { tracing::info!(target: "createPR", "dispatch-gh (fallback)"); - return create_pr_via_gh(folder, title, body, base, draft, feature_branch, tool).await; + return create_pr_via_gh( + folder, + title, + body, + base, + draft, + feature_branch, + tool, + attribution, + ) + .await; } if let Some(token) = oauth_token { tracing::info!(target: "createPR", "dispatch-link (fallback)"); - let preflight = ensure_repo_for_link(folder, title, base, feature_branch, tool).await; + let preflight = + ensure_repo_for_link(folder, title, base, feature_branch, tool, attribution).await; if let Some(err) = preflight { return err; } @@ -980,6 +1020,7 @@ async fn ensure_repo_for_link( base: Option<&str>, feature_branch: Option<&str>, tool: Option<&str>, + attribution: bool, ) -> Option { let _ = (title, base); if !folder.exists() { @@ -1084,7 +1125,7 @@ async fn ensure_repo_for_link( Duration::from_secs(10), ) .await; - let baseline_msg = with_fleetify_trailer("chore: initialize repository"); + let baseline_msg = with_fleetify_trailer("chore: initialize repository", attribution); let (rc, _, err) = run( "git", &["commit", "--allow-empty", "-m", &baseline_msg], @@ -1125,7 +1166,7 @@ async fn ensure_repo_for_link( Duration::from_secs(10), ) .await; - let baseline_msg = with_fleetify_trailer("chore: initialize repository"); + let baseline_msg = with_fleetify_trailer("chore: initialize repository", attribution); let (rc, _, err) = run( "git", &["commit", "--allow-empty", "-m", &baseline_msg], @@ -1192,7 +1233,7 @@ async fn ensure_repo_for_link( .and_then(|v| v.as_str()) .map(str::to_string) .unwrap_or_else(|| "Working session updates".to_string()); - let commit_msg = with_fleetify_trailer(&msg); + let commit_msg = with_fleetify_trailer(&msg, attribution); let (rc, _, err) = run( "git", &["commit", "-m", &commit_msg], @@ -1217,7 +1258,9 @@ async fn ensure_repo_for_link( /// PR-summary fallback when body is empty, and finally invokes /// `gh pr create`. Every step gets a trace line in the error message /// and a tracing breadcrumb so the user can diagnose without log -/// spelunking. +/// spelunking. `attribution` gates the Fleetify commit trailer and PR footer. +// 8 args is one over the default 7; refactor to a struct is out of scope for this cleanup. +#[allow(clippy::too_many_arguments)] pub async fn create_pr_via_gh( folder: &Path, title: &str, @@ -1226,6 +1269,7 @@ pub async fn create_pr_via_gh( draft: bool, feature_branch: Option<&str>, tool: Option<&str>, + attribution: bool, ) -> Value { const HANDLER_VERSION: &str = "rust-v1-2026-05-20"; if title.trim().is_empty() { @@ -1412,7 +1456,7 @@ pub async fn create_pr_via_gh( Duration::from_secs(10), ) .await; - let baseline_msg = with_fleetify_trailer("chore: initialize repository"); + let baseline_msg = with_fleetify_trailer("chore: initialize repository", attribution); let (rc, _, err) = run( "git", &["commit", "--allow-empty", "-m", &baseline_msg], @@ -1441,7 +1485,7 @@ pub async fn create_pr_via_gh( // static "Initial commit"). } else { let (_, _, _) = run("git", &["add", "-A"], folder, Duration::from_secs(120)).await; - let init_msg = with_fleetify_trailer("Initial commit"); + let init_msg = with_fleetify_trailer("Initial commit", attribution); let (rc, _, err) = run( "git", &["commit", "--allow-empty", "-m", &init_msg], @@ -1499,7 +1543,7 @@ pub async fn create_pr_via_gh( Duration::from_secs(10), ) .await; - let baseline_msg = with_fleetify_trailer("chore: initialize repository"); + let baseline_msg = with_fleetify_trailer("chore: initialize repository", attribution); let (rc, _, err) = run( "git", &["commit", "--allow-empty", "-m", &baseline_msg], @@ -1608,7 +1652,7 @@ pub async fn create_pr_via_gh( _ => "Working session updates".to_string(), }; note("commit message", true, &msg); - let commit_msg = with_fleetify_trailer(&msg); + let commit_msg = with_fleetify_trailer(&msg, attribution); let (rc, _, err) = run( "git", &["commit", "-m", &commit_msg], @@ -1849,7 +1893,7 @@ pub async fn create_pr_via_gh( } } - let body_with_footer = with_fleetify_footer(&final_body); + let body_with_footer = with_fleetify_footer(&final_body, attribution); // 7. gh pr create. let mut args: Vec = vec![ @@ -2687,6 +2731,48 @@ mod tests { assert_eq!(parse_actions_run_job("garbage"), (None, None)); } + #[test] + fn trailer_added_when_enabled() { + assert_eq!( + with_fleetify_trailer("feat: x", true), + "feat: x\n\nCo-Authored-By: Fleetify " + ); + } + + #[test] + fn trailer_skipped_when_disabled() { + assert_eq!(with_fleetify_trailer("feat: x\n", false), "feat: x"); + } + + #[test] + fn trailer_not_duplicated_when_any_fleetify_coauthor_is_present() { + let m = "feat: x\n\nCo-authored-by: Fleetify "; + assert_eq!(with_fleetify_trailer(m, true), m); + } + + #[test] + fn trailer_dedupe_ignores_case_and_address() { + // Any existing Fleetify co-author line counts, whatever its casing or + // address, so a commit never ends up crediting Fleetify twice. + let lower = "feat: x\n\nco-authored-by: fleetify "; + assert_eq!(with_fleetify_trailer(lower, true), lower); + let other = "feat: x\n\nCo-Authored-By: Fleetify "; + assert_eq!(with_fleetify_trailer(other, true), other); + } + + #[test] + fn footer_skipped_when_disabled() { + assert_eq!(with_fleetify_footer("body", false), "body"); + } + + #[test] + fn footer_added_when_enabled() { + assert_eq!( + with_fleetify_footer("body\n", true), + "body\n\n---\nCreated with [Fleetify](https://fleetify.dev)" + ); + } + #[test] fn dedupe_ids_keeps_first_order() { assert_eq!(dedupe_ids(&[3, 1, 3, 2, 1]), vec![3, 1, 2]); @@ -3185,6 +3271,7 @@ mod tests { Some("main"), Some("fleet/x-ab12"), None, + true, ) .await; assert!(res.is_none(), "bootstrap should succeed: {res:?}"); @@ -3211,6 +3298,41 @@ mod tests { ); } + /// The link-path bootstrap commits honour the attribution setting: the + /// baseline commit credits Fleetify only while attribution is on. + #[tokio::test] + async fn link_bootstrap_trailer_follows_attribution_setting() { + if !git_available() { + return; + } + for attribution in [true, false] { + let tmp = tempfile::tempdir().unwrap(); + // Skip if an ancestor repo would mask our fresh-init state. + if fleetify_backend::services::worktree::is_git_repo(&tmp.path().to_string_lossy()) + .await + { + return; + } + let res = ensure_repo_for_link( + tmp.path(), + "My Feature", + Some("main"), + Some("fleet/x-ab12"), + None, + attribution, + ) + .await; + assert!(res.is_none(), "bootstrap should succeed: {res:?}"); + let (_, log, _) = git(&["log", "--all", "--format=%B"], tmp.path()).await; + assert_eq!( + log.to_ascii_lowercase() + .contains("co-authored-by: fleetify <"), + attribution, + "attribution={attribution}, commit messages: {log:?}" + ); + } + } + #[tokio::test] async fn ensure_repo_on_empty_dir_creates_repo() { if !git_available() { diff --git a/src-tauri/src/shell/ipc/mod.rs b/src-tauri/src/shell/ipc/mod.rs index b8535d2..0d918b6 100644 --- a/src-tauri/src/shell/ipc/mod.rs +++ b/src-tauri/src/shell/ipc/mod.rs @@ -1557,10 +1557,11 @@ pub async fn git_open_pr(folder: String, pr_number: Option) -> serde_json:: /// link only, omitted → legacy gh-first / link-fallback. Renderer /// pulls the value from `localStorage["fleet:github-auth-method"]` /// so the onboarding choice is honoured exactly. -// 8 args is one over the default 7; refactor to a struct is out of scope for this cleanup. +// 9 args is two over the default 7; refactor to a struct is out of scope for this cleanup. #[allow(clippy::too_many_arguments)] #[tauri::command] pub async fn git_create_pr( + app: tauri::AppHandle, folder: String, title: String, body: Option, @@ -1570,6 +1571,13 @@ pub async fn git_create_pr( tool: Option, method: Option, ) -> serde_json::Value { + // Settings → General → Attribution, read fresh for every PR so a change + // applies without a restart. No data dir → the default (on). + let attribution = app + .path() + .app_data_dir() + .map(|dir| config::git_attribution_from(&config::load_config_from(&dir))) + .unwrap_or(true); git::create_pr( &PathBuf::from(folder), &title, @@ -1579,6 +1587,7 @@ pub async fn git_create_pr( featureBranch.as_deref(), tool.as_deref(), method.as_deref(), + attribution, ) .await } diff --git a/src/components/settings/general/__tests__/attribution-card.test.tsx b/src/components/settings/general/__tests__/attribution-card.test.tsx new file mode 100644 index 0000000..108e388 --- /dev/null +++ b/src/components/settings/general/__tests__/attribution-card.test.tsx @@ -0,0 +1,43 @@ +import { describe, it, expect, vi } from "vitest"; +import { render, screen, fireEvent, waitFor } from "@testing-library/react"; +import { AttributionCard } from "../attribution-card"; + +describe("AttributionCard", () => { + it("is on by default and saves gitAttribution=false when switched off", async () => { + const setConfig = vi.fn().mockResolvedValue(undefined); + window.electronAPI = { + getConfig: vi.fn().mockResolvedValue({ onboardingComplete: true, apiKeys: {} }), + setConfig, + } as never; + render(); + const toggle = await screen.findByRole("switch", { + name: /credit fleetify in commits and pull requests/i, + }); + expect(toggle).toHaveAttribute("aria-checked", "true"); + expect( + screen.getByText( + 'Adds a "Co-Authored-By: Fleetify" line to commits Fleetify makes and a short footer to pull requests it opens.', + ), + ).toBeInTheDocument(); + fireEvent.click(toggle); + // Read-merge-write: the rest of the config is written back untouched. + await waitFor(() => + expect(setConfig).toHaveBeenCalledWith( + expect.objectContaining({ onboardingComplete: true, apiKeys: {}, gitAttribution: false }), + ), + ); + expect(toggle).toHaveAttribute("aria-checked", "false"); + }); + + it("shows a saved opt-out as off", async () => { + window.electronAPI = { + getConfig: vi.fn().mockResolvedValue({ onboardingComplete: true, apiKeys: {}, gitAttribution: false }), + setConfig: vi.fn().mockResolvedValue(undefined), + } as never; + render(); + const toggle = await screen.findByRole("switch", { + name: /credit fleetify in commits and pull requests/i, + }); + expect(toggle).toHaveAttribute("aria-checked", "false"); + }); +}); diff --git a/src/components/settings/general/__tests__/general-section.test.tsx b/src/components/settings/general/__tests__/general-section.test.tsx index 05cf8ce..bc6ec98 100644 --- a/src/components/settings/general/__tests__/general-section.test.tsx +++ b/src/components/settings/general/__tests__/general-section.test.tsx @@ -13,7 +13,7 @@ beforeEach(() => { }); describe("GeneralSection (composed)", () => { - it("renders all four section headers", async () => { + it("renders all five section headers", async () => { render(); await waitFor(() => { expect(screen.getByText(/^Startup$/i)).toBeInTheDocument(); @@ -21,9 +21,10 @@ describe("GeneralSection (composed)", () => { expect(screen.getByText(/^Notifications$/i)).toBeInTheDocument(); expect(screen.getByText(/^Updates$/i)).toBeInTheDocument(); expect(screen.getByText(/^Privacy$/i)).toBeInTheDocument(); + expect(screen.getByText(/^Attribution$/i)).toBeInTheDocument(); }); - it("renders the four signature rows", async () => { + it("renders the five signature rows", async () => { render(); await waitFor(() => { expect(screen.getByText(/Launch on system startup/i)).toBeInTheDocument(); @@ -31,6 +32,51 @@ describe("GeneralSection (composed)", () => { expect(screen.getByText(/Desktop notifications/i)).toBeInTheDocument(); expect(screen.getByText(/Automatic updates/i)).toBeInTheDocument(); expect(screen.getByText(/Anonymous usage analytics/i)).toBeInTheDocument(); + expect( + await screen.findByText(/Credit Fleetify in commits and pull requests/i), + ).toBeInTheDocument(); + }); +}); + +describe("GeneralSection — cards share one config file", () => { + // config_set replaces the whole fleet.config.json, so each card has to merge + // its change into the config as it is when it saves. Merging into the copy + // it read at mount would quietly undo what another card saved meanwhile. + it("a later change in another card keeps the attribution opt-out", async () => { + let stored: Record = { + onboardingComplete: true, + apiKeys: {}, + defaultFolder: "/Users/me/code", + }; + (window as unknown as { electronAPI: unknown }).electronAPI = { + getConfig: vi.fn(async () => ({ ...stored })), + setConfig: vi.fn(async (next: Record) => { + stored = next; + return true; + }), + openFolderDialog: vi.fn(async () => null), + }; + render(); + + const attribution = await screen.findByRole("switch", { + name: /credit fleetify in commits and pull requests/i, + }); + fireEvent.click(attribution); + await waitFor(() => expect(stored.gitAttribution).toBe(false)); + + // Startup card mounted before the opt-out; clearing its folder must not + // write the old config (without gitAttribution) back. + fireEvent.mouseEnter(screen.getByText("/Users/me/code").closest("div")!); + fireEvent.click(screen.getByLabelText(/clear default folder/i)); + await waitFor(() => expect(stored.defaultFolder).toBe("")); + expect(stored.gitAttribution).toBe(false); + + // And the other way round: switching attribution back on keeps the + // Startup card's change. + fireEvent.click(attribution); + await waitFor(() => expect(stored.gitAttribution).toBe(true)); + expect(stored.defaultFolder).toBe(""); + expect(stored.onboardingComplete).toBe(true); }); }); diff --git a/src/components/settings/general/_config.ts b/src/components/settings/general/_config.ts new file mode 100644 index 0000000..f15ce47 --- /dev/null +++ b/src/components/settings/general/_config.ts @@ -0,0 +1,19 @@ +/** + * Read-merge-write for the General settings cards. + * + * `config_set` replaces the whole `fleet.config.json`, so a card has to merge + * its change into the config as it is when it saves — not into the copy it + * read when it mounted. Merging into the mount-time copy silently undid + * whatever another card had saved since (turning attribution off, then + * toggling crash reports, turned attribution back on). + */ +type ConfigShim = { + getConfig?: () => Promise; + setConfig?: (cfg: object) => Promise; +}; + +export async function saveConfigPatch(patch: object): Promise { + const api = (window as unknown as { electronAPI?: ConfigShim }).electronAPI; + const latest = (await api?.getConfig?.()) ?? {}; + await api?.setConfig?.({ ...latest, ...patch }); +} diff --git a/src/components/settings/general/_primitives.tsx b/src/components/settings/general/_primitives.tsx index 67725df..a99e334 100644 --- a/src/components/settings/general/_primitives.tsx +++ b/src/components/settings/general/_primitives.tsx @@ -1,10 +1,10 @@ /** * Shared visual primitives for the General settings cards. * - * Each card (startup, notifications, updates, privacy) renders a - * `CardShell` wrapping one or more `Row`s with a `Toggle` (or other - * control) on the right. Keeping the primitives co-located here means - * adding a new General card stays a one-import affair and the four + * Each card (startup, notifications, updates, privacy, attribution) + * renders a `CardShell` wrapping one or more `Row`s with a `Toggle` (or + * other control) on the right. Keeping the primitives co-located here + * means adding a new General card stays a one-import affair and the * cards stay visually identical without copy/paste drift. */ @@ -43,11 +43,15 @@ export function Row({ title, desc, children, last, disabled }: { ); } -export function Toggle({ on, onChange }: { on: boolean; onChange: () => void }) { +export function Toggle({ on, onChange, label }: { + on: boolean; onChange: () => void; + /** Accessible name — usually the row title, so screen readers announce what the switch controls. */ + label?: string; +}) { return (