From 2b25b6a858f65a71c8c68e970b9a0cc33550e48f Mon Sep 17 00:00:00 2001 From: broisnees Date: Tue, 24 Nov 2026 06:34:27 +0000 Subject: [PATCH] Share saved connections between Stroke and Stroke Nightly Stable and Nightly each kept connections.json in their own data folder but share one keychain vault. A connection added in Nightly was missing in Stable, and Stable then deleted Nightly's passwords twice over: at startup it pruned every vault id missing from its own list, and every save rewrote the whole vault from its own cache. - connections.json lives in Stable's folder for both apps. Nightly's own file is merged in once (newer lastConnectedAt wins per id) and renamed to connections.json.merged. - Every write merges with the file on disk: rows the other app added are kept, and a tombstone in `deleted` wins over a stale copy. `revived` lifts one for an explicit re-add. - Connection secrets are written with conn_secrets_merge, which reads the vault fresh and only touches this app's ids and deleted ids. Startup prunes only tombstoned ids. - On window focus the list and passwords are re-read, so what the other app saved shows up without a restart. --- .changeset/shared-connections.md | 2 + src-tauri/src/connection_store.rs | 230 +++++++++++++++++++++-- src-tauri/src/lib.rs | 2 + src-tauri/src/secrets.rs | 92 +++++++++ src/lib/components/SettingsDialog.svelte | 2 +- src/lib/components/StudioShell.svelte | 16 ++ src/lib/stores/connections.js | 92 ++++++++- src/lib/stores/connections.test.js | 56 +++++- 8 files changed, 467 insertions(+), 25 deletions(-) create mode 100644 .changeset/shared-connections.md diff --git a/.changeset/shared-connections.md b/.changeset/shared-connections.md new file mode 100644 index 00000000..75ba368f --- /dev/null +++ b/.changeset/shared-connections.md @@ -0,0 +1,2 @@ +### Bug Fixes +- **Connections are shared by Stroke and Stroke Nightly** - A connection added in one app was missing in the other, and opening Stable then dropped Nightly's saved passwords from the keychain the two share. Both apps now use one saved list, and each save merges with it, so both can stay open side by side: coming back to a window shows what the other one added, edited or deleted, with its password. Nightly's own list is merged in on first launch, and a copy of it is kept. diff --git a/src-tauri/src/connection_store.rs b/src-tauri/src/connection_store.rs index 51d44c99..5e7d8c82 100644 --- a/src-tauri/src/connection_store.rs +++ b/src-tauri/src/connection_store.rs @@ -6,35 +6,153 @@ //! came back on the next launch (and a freshly added one could vanish). This //! file is written synchronously and fsynced on every change, and the frontend //! loads it before anything reads the list. +//! +//! Stroke and Stroke Nightly share one file, in Stable's data folder +//! (`shared_dir`). They already share the keychain that holds the passwords, and +//! with a file each, a connection added in one track was missing in the other, +//! and the other track then dropped its password from the shared keychain. Both +//! can run at once, so a write merges with the file on disk instead of replacing +//! it: connections the other app added are kept, and a delete is a tombstone in +//! `deleted` that wins over a stale copy still held by the other app. +use serde_json::{json, Value}; +use std::collections::HashSet; use std::path::{Path, PathBuf}; +use std::sync::Mutex; const FILE_NAME: &str = "connections.json"; +/// The suffix Nightly's identifier adds to Stable's (tauri.nightly.conf.json). +const NIGHTLY_SUFFIX: &str = ".nightly"; +/// Matches MAX_DELETED_IDS in src/lib/stores/connections.js. +const MAX_DELETED: usize = 500; + +/// Serialises read-merge-write within this process. +static LOCK: Mutex<()> = Mutex::new(()); + +fn store_path(dir: &Path) -> PathBuf { + dir.join(FILE_NAME) +} -fn store_path(data_dir: &Path) -> PathBuf { - data_dir.join(FILE_NAME) +/// Stable's data folder, which both tracks use for this file. Nightly's own +/// folder is Stable's with `.nightly` on the end, beside it. +pub fn shared_dir(app_data_dir: &Path) -> PathBuf { + match app_data_dir.file_name().and_then(|n| n.to_str()) { + Some(name) if name.ends_with(NIGHTLY_SUFFIX) => { + app_data_dir.with_file_name(&name[..name.len() - NIGHTLY_SUFFIX.len()]) + } + _ => app_data_dir.to_path_buf(), + } } -/// The stored payload, or `None` before the first write. -pub fn read(data_dir: &Path) -> Result, String> { - match std::fs::read_to_string(store_path(data_dir)) { +fn read_file(path: &Path) -> Result, String> { + match std::fs::read_to_string(path) { Ok(s) => Ok(Some(s)), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(format!("Could not read saved connections: {e}")), } } -/// Replace the stored payload. Written to a sibling temp file, fsynced, then -/// renamed over the old one, so a crash mid-write leaves the previous list -/// intact instead of a truncated file. -pub fn write(data_dir: &Path, json: &str) -> Result<(), String> { - use std::io::Write; +/// The stored payload, or `None` before the first write. On Nightly, a list it +/// kept in its own folder before the file was shared is merged in once, then +/// renamed to `connections.json.merged` (kept, not deleted). +pub fn read(app_data_dir: &Path) -> Result, String> { + let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let shared = shared_dir(app_data_dir); + if shared != app_data_dir { + let own = store_path(app_data_dir); + if let Some(own_json) = read_file(&own)? { + let base = read_file(&store_path(&shared))?; + let merged = merge_newer(base.as_deref(), &own_json)?; + write_file(&shared, &merged)?; + let _ = std::fs::rename(&own, own.with_extension("json.merged")); + } + } + read_file(&store_path(&shared)) +} - serde_json::from_str::(json) +/// Save the payload, merged with what is on disk (see the module comment). +pub fn write(app_data_dir: &Path, json: &str) -> Result<(), String> { + let incoming: Value = serde_json::from_str(json) .map_err(|e| format!("Refusing to save connections: payload is not JSON ({e})"))?; - std::fs::create_dir_all(data_dir).map_err(|e| e.to_string())?; + let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = shared_dir(app_data_dir); + let disk = read_file(&store_path(&dir))?.and_then(|s| serde_json::from_str::(&s).ok()); + write_file(&dir, &merge(disk.as_ref(), &incoming).to_string()) +} + +fn ids(list: &Value) -> Vec { + list.as_array() + .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()) + .unwrap_or_default() +} + +fn conn_id(c: &Value) -> Option<&str> { + c.get("id").and_then(Value::as_str) +} + +/// `incoming` (this app's list) merged with `disk` (the file as it is now): +/// - tombstones are the union of both, less the ids `incoming` revived; +/// - every connection in `incoming` that has no tombstone, in its order; +/// - then every connection only on disk (the other app added it) without one. +pub fn merge(disk: Option<&Value>, incoming: &Value) -> Value { + let revived: HashSet = ids(&incoming["revived"]).into_iter().collect(); + let mut deleted: Vec = Vec::new(); + let mut seen = HashSet::new(); + for id in disk.map(|d| ids(&d["deleted"])).unwrap_or_default().into_iter().chain(ids(&incoming["deleted"])) { + if !revived.contains(&id) && seen.insert(id.clone()) { + deleted.push(id); + } + } + if deleted.len() > MAX_DELETED { + deleted.drain(..deleted.len() - MAX_DELETED); + } + let gone: HashSet<&str> = deleted.iter().map(String::as_str).collect(); + + let mut out: Vec = Vec::new(); + let mut have = HashSet::new(); + let lists = [incoming.get("connections"), disk.and_then(|d| d.get("connections"))]; + for c in lists.into_iter().flatten().filter_map(Value::as_array).flatten() { + match conn_id(c) { + Some(id) if gone.contains(id) => {} + Some(id) => { + if have.insert(id.to_string()) { + out.push(c.clone()); + } + } + // No id: keep it as it came (the frontend gives it one on load). + None => out.push(c.clone()), + } + } + json!({ "version": 1, "connections": out, "deleted": deleted }) +} + +/// One-time merge of Nightly's own list into the shared one. Neither side is +/// "this app's latest" here, so for an id in both, the copy connected to more +/// recently wins. +fn merge_newer(base: Option<&str>, own: &str) -> Result { + let own: Value = serde_json::from_str(own).map_err(|e| format!("Unreadable connections.json: {e}"))?; + let Some(base) = base.and_then(|s| serde_json::from_str::(s).ok()) else { + return Ok(merge(None, &own).to_string()); + }; + let stamp = |c: &Value| c.get("lastConnectedAt").and_then(Value::as_f64).unwrap_or(0.0); + let mut own = own; + if let (Some(mine), Some(theirs)) = (own["connections"].as_array_mut(), base["connections"].as_array()) { + for c in mine.iter_mut() { + if let Some(newer) = theirs.iter().find(|t| conn_id(t).is_some() && conn_id(t) == conn_id(c) && stamp(t) > stamp(c)) { + *c = newer.clone(); + } + } + } + Ok(merge(Some(&base), &own).to_string()) +} - let path = store_path(data_dir); +/// Written to a sibling temp file, fsynced, then renamed over the old one, so a +/// crash mid-write leaves the previous list intact instead of a truncated file. +fn write_file(dir: &Path, json: &str) -> Result<(), String> { + use std::io::Write; + + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + let path = store_path(dir); let tmp = path.with_extension("json.tmp"); let mut opts = std::fs::OpenOptions::new(); opts.write(true).create(true).truncate(true); @@ -51,3 +169,89 @@ pub fn write(data_dir: &Path, json: &str) -> Result<(), String> { drop(f); std::fs::rename(&tmp, &path).map_err(|e| format!("Could not save connections: {e}")) } + +#[cfg(test)] +mod tests { + use super::*; + + fn tmp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("stroke-conn-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d + } + + fn names(v: &Value) -> Vec<&str> { + v["connections"].as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap()).collect() + } + + #[test] + fn nightly_shares_stables_folder() { + let base = Path::new("/data/com.broisnischal.stroke"); + assert_eq!(shared_dir(&base.with_file_name("com.broisnischal.stroke.nightly")), base); + assert_eq!(shared_dir(base), base); + } + + #[test] + fn a_write_keeps_what_the_other_app_added() { + let disk = json!({ "connections": [{ "id": "a" }, { "id": "n" }], "deleted": [] }); + // Stable never saw "n" (Nightly added it); its write must not drop it. + let mine = json!({ "connections": [{ "id": "a", "name": "renamed" }, { "id": "s" }], "deleted": [] }); + let out = merge(Some(&disk), &mine); + assert_eq!(names(&out), ["a", "s", "n"]); + assert_eq!(out["connections"][0]["name"], "renamed"); + } + + #[test] + fn a_delete_wins_over_a_stale_copy() { + // Nightly deleted "x"; Stable still holds it and writes it back. + let disk = json!({ "connections": [{ "id": "a" }], "deleted": ["x"] }); + let stale = json!({ "connections": [{ "id": "a" }, { "id": "x" }], "deleted": [] }); + let out = merge(Some(&disk), &stale); + assert_eq!(names(&out), ["a"]); + assert_eq!(out["deleted"], json!(["x"])); + // An explicit re-add (the sample database) lifts the tombstone. + let revive = json!({ "connections": [{ "id": "x" }], "deleted": [], "revived": ["x"] }); + let out = merge(Some(&disk), &revive); + assert_eq!(names(&out), ["x", "a"]); + assert_eq!(out["deleted"], json!([])); + } + + #[test] + fn tombstones_are_capped() { + let many: Vec = (0..MAX_DELETED + 10).map(|i| i.to_string()).collect(); + let out = merge(None, &json!({ "connections": [], "deleted": many })); + assert_eq!(out["deleted"].as_array().unwrap().len(), MAX_DELETED); + assert_eq!(out["deleted"][0], "10"); + } + + #[test] + fn nightlys_own_file_is_merged_into_the_shared_one_once() { + let root = tmp("migrate"); + let stable = root.join("com.broisnischal.stroke"); + let nightly = root.join("com.broisnischal.stroke.nightly"); + write_file(&stable, r#"{"connections":[{"id":"a","lastConnectedAt":5},{"id":"s"}],"deleted":["gone"]}"#).unwrap(); + write_file(&nightly, r#"{"connections":[{"id":"a","lastConnectedAt":9,"name":"newer"},{"id":"n"},{"id":"gone"}],"deleted":[]}"#).unwrap(); + + let out: Value = serde_json::from_str(&read(&nightly).unwrap().unwrap()).unwrap(); + assert_eq!(names(&out), ["a", "n", "s"]); + assert_eq!(out["connections"][0]["name"], "newer"); + assert!(!store_path(&nightly).exists()); + assert!(nightly.join("connections.json.merged").exists()); + // Stable reads the same list from its own folder. + assert_eq!(read(&stable).unwrap(), read(&nightly).unwrap()); + + // Writes from either app land in the one file and keep each other's rows. + write(&nightly, r#"{"connections":[{"id":"a"},{"id":"n"},{"id":"n2"}],"deleted":[]}"#).unwrap(); + write(&stable, r#"{"connections":[{"id":"a"},{"id":"s"}],"deleted":["n"]}"#).unwrap(); + let out: Value = serde_json::from_str(&read(&stable).unwrap().unwrap()).unwrap(); + assert_eq!(names(&out), ["a", "s", "n2"]); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn refuses_a_payload_that_is_not_json() { + let root = tmp("bad"); + assert!(write(&root, "{not json").is_err()); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a797c5e3..b138e967 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -964,6 +964,8 @@ pub fn run() { commands::connections_store_write, secrets::conn_secrets_read, secrets::conn_secrets_write, + secrets::conn_secrets_read_fresh, + secrets::conn_secrets_merge, metrics::get_app_metrics, metrics::set_process_title, commands::enable_autostart, diff --git a/src-tauri/src/secrets.rs b/src-tauri/src/secrets.rs index d257990f..a2ddfc81 100644 --- a/src-tauri/src/secrets.rs +++ b/src-tauri/src/secrets.rs @@ -420,11 +420,103 @@ pub async fn conn_secrets_write(app: tauri::AppHandle, json: String) -> Result<( .await } +// Stroke and Stroke Nightly share this vault (same keychain service) and can +// run at once, but each process trusts its own session cache. A write built +// from that cache put back whatever the process read at launch, so one track +// silently dropped passwords the other had saved since. The connection +// secrets are therefore read fresh from the durable store before a merge, and +// written as a merge: ids this app sends are replaced, ids it names as deleted +// are removed, and every other id is left as the other app saved it. + +/// The connection secrets as the durable store holds them right now, or `None` +/// when it can't be read (then the session cache is the best answer). +fn fresh_conn_secrets(app: &tauri::AppHandle) -> Option> { + let path = legacy_path(app); + if let Some(map) = std::fs::read_to_string(&path).ok().and_then(|s| parse_map(&s)) { + return Some(map.get(CONN_SECRETS_KEY).cloned()); + } + match read_vault(&Keychain) { + Ok(map) => Some(map.and_then(|m| m.get(CONN_SECRETS_KEY).cloned())), + Err(_) => None, + } +} + +/// `base` (the stored `{ id: { field: secret } }`) with `set` applied (an empty +/// object clears that id) and `removed` ids dropped. `None` when nothing is left. +fn merge_conn_secrets(base: Option<&str>, set: &serde_json::Map, removed: &[String]) -> Option { + let mut map: serde_json::Map = base + .and_then(|s| serde_json::from_str::(s).ok()) + .and_then(|v| v.as_object().cloned()) + .unwrap_or_default(); + for (id, sec) in set { + if sec.as_object().is_some_and(|o| !o.is_empty()) { + map.insert(id.clone(), sec.clone()); + } else { + map.remove(id); + } + } + for id in removed { + map.remove(id); + } + (!map.is_empty()).then(|| serde_json::Value::Object(map).to_string()) +} + +/// Like `conn_secrets_read`, but from the durable store, so secrets the other +/// track saved after this one started are seen. Refreshes the session cache. +#[tauri::command] +pub async fn conn_secrets_read_fresh(app: tauri::AppHandle) -> Result, String> { + update_async(&app.clone(), move |map| { + if let Some(fresh) = fresh_conn_secrets(&app) { + match &fresh { + Some(v) => map.insert(CONN_SECRETS_KEY.to_string(), v.clone()), + None => map.remove(CONN_SECRETS_KEY), + }; + } + map.get(CONN_SECRETS_KEY).cloned() + }) + .await +} + +/// Merge this app's connection secrets into the vault: `set` is +/// `{ id: { field: secret } }` for every connection this app has (an empty +/// object clears that id), `removed` the ids it deleted. +#[tauri::command] +pub async fn conn_secrets_merge(app: tauri::AppHandle, set: String, removed: Vec) -> Result<(), String> { + let set: serde_json::Value = serde_json::from_str(&set).map_err(|e| format!("Not JSON: {e}"))?; + let set = set.as_object().cloned().ok_or("Expected an object of connection secrets")?; + update_async(&app.clone(), move |map| { + let base = match fresh_conn_secrets(&app) { + Some(fresh) => fresh, + None => map.get(CONN_SECRETS_KEY).cloned(), + }; + match merge_conn_secrets(base.as_deref(), &set, &removed) { + Some(v) => map.insert(CONN_SECRETS_KEY.to_string(), v), + None => map.remove(CONN_SECRETS_KEY), + }; + }) + .await +} + #[cfg(test)] mod tests { use super::*; use std::cell::RefCell; + #[test] + fn connection_secrets_merge_keeps_the_other_tracks_ids() { + let base = r#"{"stable":{"password":"s"},"nightly":{"password":"n"},"old":{"password":"o"}}"#; + let set: serde_json::Map = + serde_json::from_str(r#"{"stable":{"password":"s2"},"cleared":{},"new":{"apiKey":"k"}}"#).unwrap(); + let out: serde_json::Value = + serde_json::from_str(&merge_conn_secrets(Some(base), &set, &["old".into()]).unwrap()).unwrap(); + assert_eq!(out["stable"]["password"], "s2"); + assert_eq!(out["nightly"]["password"], "n", "an id this app never had is left alone"); + assert_eq!(out["new"]["apiKey"], "k"); + assert!(out.get("old").is_none() && out.get("cleared").is_none()); + let empty = serde_json::Map::new(); + assert_eq!(merge_conn_secrets(Some(r#"{"a":{"password":"x"}}"#), &empty, &["a".into()]), None); + } + /// In-memory keychain with Windows' per-credential limit, and switches to /// make it refuse writes. struct MemStore { diff --git a/src/lib/components/SettingsDialog.svelte b/src/lib/components/SettingsDialog.svelte index afe4ee04..29a52171 100644 --- a/src/lib/components/SettingsDialog.svelte +++ b/src/lib/components/SettingsDialog.svelte @@ -2187,7 +2187,7 @@

- Connections and settings stay with each app. Signed in, synced ones follow you. + Both apps share saved connections and their passwords. Settings stay with each app; signed in, synced ones follow you.

diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index 380bfe58..5585714b 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -310,6 +310,7 @@ setWasDisconnected, upsertConnection, engineFamily, + refreshConnectionsFromDisk, } from '$lib/stores/connections.js' import { workspaces, activeWorkspaceId, setActiveWorkspace, workspaceOf } from '$lib/stores/workspaces.js' import { hasPro, FREE_CONNECTION_LIMIT } from '$lib/stores/license.js' @@ -775,6 +776,21 @@ window.addEventListener('stroke:connections-synced', reload) return () => window.removeEventListener('stroke:connections-synced', reload) }) + // Stroke and Stroke Nightly share the saved list: coming back to this window, + // show what the other one added, edited or deleted in the meantime. + $effect(() => { + if (!('__TAURI_INTERNALS__' in window)) return + let busy = false + const onFocus = () => { + if (busy) return + busy = true + void refreshConnectionsFromDisk() + .then((changed) => { if (changed) savedConnections = loadSavedConnections() }) + .finally(() => { busy = false }) + } + window.addEventListener('focus', onFocus) + return () => window.removeEventListener('focus', onFocus) + }) let showSettingsModal = $state(false) /** Settings category to open on next (e.g. 'keybindings'); the dialog clears it. */ let settingsSection = $state('') diff --git a/src/lib/stores/connections.js b/src/lib/stores/connections.js index aea0b887..997c4daa 100644 --- a/src/lib/stores/connections.js +++ b/src/lib/stores/connections.js @@ -157,7 +157,7 @@ export function saveConnections(connections) { return pub }) _secretCache = next - queueSecretsWrite() + queueSecretsWrite(connections.map((c) => c.id)) } localStorage.setItem(STORAGE_KEY, JSON.stringify(stored)) mirrorToDisk() @@ -230,11 +230,22 @@ export function splitSecrets(c) { let _secretsChain = Promise.resolve() -/** Persist the cache; on failure, put the secrets back inline so none is lost. */ -function queueSecretsWrite() { - const json = JSON.stringify(Object.fromEntries(_secretCache)) +/** + * Merge this app's secrets into the keychain vault, which Stroke and Stroke + * Nightly share: every id of `ids` is written from the cache (an empty object + * clears it), deleted ids are removed, and ids this app doesn't have are left + * as the other app saved them. Writing the whole vault from this app's cache + * used to drop the other track's passwords. On failure the secrets go back + * inline so none is lost. + * @param {Iterable} ids + */ +function queueSecretsWrite(ids) { + /** @type {Record>} */ + const set = {} + for (const id of ids) if (typeof id === 'string') set[id] = _secretCache.get(id) ?? {} + const payload = { set: JSON.stringify(set), removed: [...loadDeletedIds()] } _secretsChain = _secretsChain - .then(() => invoke('conn_secrets_write', { json })) + .then(() => invoke('conn_secrets_merge', payload)) .catch((err) => { console.error('Keychain write failed; keeping connection secrets inline:', err) _vaultReady = false @@ -267,11 +278,18 @@ export async function hydrateConnectionSecrets() { inline = true } } - // Secrets of deleted connections don't come back. - const ids = new Set(list.map((c) => c?.id)) - for (const id of [...cache.keys()]) if (!ids.has(id)) cache.delete(id) - if (inline || cache.size !== Object.keys(stored ?? {}).length) { - await invoke('conn_secrets_write', { json: JSON.stringify(Object.fromEntries(cache)) }) + // Secrets of deleted connections don't come back. Only an id with a + // tombstone counts as deleted: one missing from this list may belong to + // the other track (Stroke and Stroke Nightly share the vault), and + // dropping those wiped its passwords every time the other app started. + const deleted = loadDeletedIds() + let pruned = false + for (const id of [...cache.keys()]) if (deleted.has(id)) { cache.delete(id); pruned = true } + if (inline || pruned) { + /** @type {Record>} */ + const set = {} + for (const c of list) if (c && typeof c.id === 'string') set[c.id] = cache.get(c.id) ?? {} + await invoke('conn_secrets_merge', { set: JSON.stringify(set), removed: [...deleted] }) } _secretCache = cache _vaultReady = true @@ -293,6 +311,9 @@ export async function hydrateConnectionSecrets() { // file is loaded into localStorage before anything reads the list. let _mirrorChain = Promise.resolve() +/** Ids re-added after a delete this session. The backend merges each write + * with the file, where a tombstone otherwise wins over a copy of the row. */ +const _revived = new Set() /** Queue a write of the current list and deleted ids. Writes run one at a time, * so an older payload can never land after a newer one. */ @@ -303,6 +324,7 @@ function mirrorToDisk() { version: 1, connections: JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]'), deleted: [...loadDeletedIds()], + revived: [..._revived], }) } catch { return @@ -380,6 +402,54 @@ export async function hydrateConnectionsFromDisk({ waitForSecrets = true } = {}) } } +/** JSON with object keys sorted, for comparing two payloads by value. @param {unknown} v @returns {string} */ +function canonical(v) { + if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]` + if (v && typeof v === 'object') { + return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(/** @type {Record} */ (v)[k])}`).join(',')}}` + } + return JSON.stringify(v) ?? 'null' +} + +/** + * Pick up what the other track saved. Stroke and Stroke Nightly share + * connections.json and the keychain vault, and both can be open: call this + * when the window comes back to the front. Returns true when the list changed, + * after reading the passwords fresh so a connection added over there connects + * here without asking again. + * @returns {Promise} + */ +export async function refreshConnectionsFromDisk() { + try { + // Let this app's own pending writes land first, so the file includes them. + await _mirrorChain + await _secretsChain + const json = /** @type {string | null} */ (await invoke('connections_store_read')) + if (json == null) return false + const data = JSON.parse(json) + if (!Array.isArray(data?.connections)) return false + const list = JSON.stringify(data.connections) + const deleted = JSON.stringify(Array.isArray(data.deleted) ? data.deleted : []) + // The backend may write keys in another order: compare values, not text. + const same = (/** @type {string} */ a, /** @type {string | null} */ b) => { + try { return canonical(JSON.parse(a)) === canonical(JSON.parse(b ?? '[]')) } catch { return false } + } + if (same(list, localStorage.getItem(STORAGE_KEY)) && same(deleted, localStorage.getItem(DELETED_KEY))) return false + if (_vaultReady) { + try { + const sec = /** @type {string | null} */ (await invoke('conn_secrets_read_fresh')) + const parsed = sec ? JSON.parse(sec) : {} + _secretCache = new Map(Object.entries(parsed ?? {})) + } catch { /* keep the cache: a connection without its password asks for it */ } + } + localStorage.setItem(STORAGE_KEY, list) + localStorage.setItem(DELETED_KEY, deleted) + return true + } catch { + return false + } +} + /** * Where a connection is filed and how it looks, set by the person rather than * by whatever dialled it. The one-click paths (a provider's database, a Docker @@ -417,6 +487,7 @@ export function upsertConnection(conn, { revive = false, exact = false } = {}) { } deleted.delete(conn.id) saveDeletedIds(deleted) + _revived.add(conn.id) } const list = loadSavedConnections() const idx = list.findIndex((c) => c.id === conn.id) @@ -482,6 +553,7 @@ export function removeConnection(id) { closeParkedFor(id) const deleted = loadDeletedIds() deleted.add(id) + _revived.delete(id) // Before saveConnections, so the disk copy it writes carries the id too. saveDeletedIds(deleted) // Sync carries the delete to other devices (a no-op while sync applies one). diff --git a/src/lib/stores/connections.test.js b/src/lib/stores/connections.test.js index 9c7d2bd3..f89a5d6d 100644 --- a/src/lib/stores/connections.test.js +++ b/src/lib/stores/connections.test.js @@ -15,7 +15,19 @@ vi.mock('@tauri-apps/api/core', () => ({ if (cmd === 'connections_store_read') return diskPayload if (cmd === 'close_parked') { closedParked.push(args.connection); return null } if (cmd === 'conn_secrets_read') { if (vaultBroken) throw new Error('no keychain'); return vault } - if (cmd === 'conn_secrets_write') { if (vaultBroken) throw new Error('no keychain'); vault = args.json; return null } + if (cmd === 'conn_secrets_read_fresh') { if (vaultBroken) throw new Error('no keychain'); return vault } + if (cmd === 'conn_secrets_merge') { + // Same rules as merge_conn_secrets in secrets.rs. + if (vaultBroken) throw new Error('no keychain') + const map = vault ? JSON.parse(vault) : {} + for (const [id, sec] of Object.entries(JSON.parse(args.set))) { + if (sec && Object.keys(sec).length) map[id] = sec + else delete map[id] + } + for (const id of args.removed) delete map[id] + vault = Object.keys(map).length ? JSON.stringify(map) : null + return null + } throw new Error(`unexpected command ${cmd}`) }), })) @@ -165,6 +177,48 @@ describe('connection secrets in the keychain', () => { expect(JSON.parse(vault ?? '{}').n).toBeUndefined() }) + it("leaves the other track's passwords in the shared keychain", async () => { + // Nightly saved "n" (with its password); this app (Stable) never had it. + vault = JSON.stringify({ n: { password: 'nightly' }, gone: { password: 'x' } }) + diskPayload = JSON.stringify({ connections: [{ id: 's', type: 'postgres', name: 's', host: 'h' }], deleted: ['gone'] }) + const store = await import('./connections.js') + await store.hydrateConnectionsFromDisk() + // Startup drops only a deleted id, not every id missing from this list. + expect(JSON.parse(vault ?? '{}')).toEqual({ n: { password: 'nightly' } }) + // A save here merges, so "n" survives this app's writes too. + store.upsertConnection({ id: 's', type: 'postgres', name: 's', host: 'h', password: 'stable' }) + await flush() + expect(JSON.parse(vault ?? '{}')).toEqual({ n: { password: 'nightly' }, s: { password: 'stable' } }) + }) + + it('picks up a connection the other track added, with its password', async () => { + diskPayload = JSON.stringify({ connections: [{ id: 's', type: 'postgres', name: 's' }], deleted: [] }) + const store = await import('./connections.js') + await store.hydrateConnectionsFromDisk() + expect(await store.refreshConnectionsFromDisk()).toBe(false) + // Meanwhile Nightly adds "n" to the shared file and keychain. + diskPayload = JSON.stringify({ connections: [{ id: 's', type: 'postgres', name: 's' }, { id: 'n', type: 'mysql', name: 'n' }], deleted: [] }) + vault = JSON.stringify({ n: { password: 'nightly' } }) + expect(await store.refreshConnectionsFromDisk()).toBe(true) + const n = store.loadSavedConnections().find((c) => c.id === 'n') + expect(n?.password).toBe('nightly') + // Same list with keys in another order is not a change. + diskPayload = JSON.stringify({ deleted: [], connections: [{ name: 's', type: 'postgres', id: 's' }, { name: 'n', id: 'n', type: 'mysql' }] }) + expect(await store.refreshConnectionsFromDisk()).toBe(false) + }) + + it('tells the disk copy about a revived connection', async () => { + const store = await import('./connections.js') + await store.hydrateConnectionsFromDisk() + store.upsertConnection({ id: 'sample', type: 'sqlite', name: 'Sample', filePath: '/s.db' }) + store.removeConnection('sample') + store.upsertConnection({ id: 'sample', type: 'sqlite', name: 'Sample', filePath: '/s.db' }, { revive: true }) + await flush() + const last = JSON.parse(writes.at(-1) ?? '{}') + expect(last.revived).toEqual(['sample']) + expect(last.deleted).toEqual([]) + }) + it('keeps secrets inline when the keychain is unavailable', async () => { vaultBroken = true localStorage.setItem('stroke:connections', JSON.stringify(legacy))