From c6496be2c1df812b5c55f5dea82965605900e065 Mon Sep 17 00:00:00 2001 From: CRT Date: Sat, 10 Oct 2026 21:16:59 +0000 Subject: [PATCH] Desktop D5 app: --self-test (sidecar handshake, no window) for release smoke tests; Settings > Updates checks and installs signed updates after a native dialog; storebound://open?path= adds or selects an app folder after asking --- apps/desktop/src-tauri/capabilities/main.json | 4 +- apps/desktop/src-tauri/entitlements.plist | 13 ++ .../autogenerated/update_check.toml | 11 ++ .../autogenerated/update_install.toml | 11 ++ apps/desktop/src-tauri/src/commands.rs | 130 ++++++++++++++++++ apps/desktop/src-tauri/src/commands_list.rs | 2 + apps/desktop/src-tauri/src/lib.rs | 11 +- apps/desktop/src-tauri/src/main.rs | 5 + apps/desktop/src-tauri/src/policy.rs | 23 ++++ apps/desktop/src-tauri/src/selftest.rs | 99 +++++++++++++ apps/desktop/src-tauri/src/updates.rs | 37 +++++ apps/desktop/src-tauri/tests/d5.rs | 104 ++++++++++++++ apps/desktop/src-tauri/tests/security.rs | 6 + apps/desktop/src/App.tsx | 8 +- apps/desktop/src/api.ts | 8 ++ apps/desktop/src/dev/fixtures.ts | 2 + apps/desktop/src/i18n/en.ts | 8 +- apps/desktop/src/i18n/tr.ts | 8 +- apps/desktop/src/screens/Settings.tsx | 33 ++++- 19 files changed, 514 insertions(+), 9 deletions(-) create mode 100644 apps/desktop/src-tauri/entitlements.plist create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/update_check.toml create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/update_install.toml create mode 100644 apps/desktop/src-tauri/src/selftest.rs create mode 100644 apps/desktop/src-tauri/src/updates.rs create mode 100644 apps/desktop/src-tauri/tests/d5.rs diff --git a/apps/desktop/src-tauri/capabilities/main.json b/apps/desktop/src-tauri/capabilities/main.json index 8936134f..83ad7618 100644 --- a/apps/desktop/src-tauri/capabilities/main.json +++ b/apps/desktop/src-tauri/capabilities/main.json @@ -43,6 +43,8 @@ "allow-cache-info", "allow-data-reveal", "allow-notify", - "allow-app-reset" + "allow-app-reset", + "allow-update-check", + "allow-update-install" ] } diff --git a/apps/desktop/src-tauri/entitlements.plist b/apps/desktop/src-tauri/entitlements.plist new file mode 100644 index 00000000..59263d21 --- /dev/null +++ b/apps/desktop/src-tauri/entitlements.plist @@ -0,0 +1,13 @@ + + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + + diff --git a/apps/desktop/src-tauri/permissions/autogenerated/update_check.toml b/apps/desktop/src-tauri/permissions/autogenerated/update_check.toml new file mode 100644 index 00000000..8a4fef9a --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/update_check.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-update-check" +description = "Enables the update_check command without any pre-configured scope." +commands.allow = ["update_check"] + +[[permission]] +identifier = "deny-update-check" +description = "Denies the update_check command without any pre-configured scope." +commands.deny = ["update_check"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/update_install.toml b/apps/desktop/src-tauri/permissions/autogenerated/update_install.toml new file mode 100644 index 00000000..eb584ac4 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/update_install.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-update-install" +description = "Enables the update_install command without any pre-configured scope." +commands.allow = ["update_install"] + +[[permission]] +identifier = "deny-update-install" +description = "Denies the update_install command without any pre-configured scope." +commands.deny = ["update_install"] diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index c53baa78..43a31b86 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -17,6 +17,7 @@ use crate::downloads; use crate::policy::{self, Kind}; use crate::sidecar::{valid_job, Fail, Progress, Sidecar}; use crate::store::{self, Project, State as Saved}; +use crate::updates; use crate::workspace::{self, Overrides, Settings, StoreTarget, Studio}; pub struct AppState { @@ -902,3 +903,132 @@ pub async fn app_reset(window: WebviewWindow, state: State<'_, AppState>) -> Res state.cache.clear().map_err(Fail::host)?; Ok(true) } + +// --------------------------------------------------------------------------------------------------------------------- +// Updates (Settings > Updates): signed bundles from storebound.dev, installed only after the owner's click. + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct UpdateInfo { + pub current: String, + pub channel: String, + /// The newer version on the channel, if any. + pub available: Option, + pub notes: Option, + pub date: Option, +} + +async fn find_update(app: &AppHandle, channel: &str) -> Res> { + use tauri_plugin_updater::UpdaterExt; + let url = url::Url::parse(updates::endpoint(channel)).map_err(|e| Fail::host(e.to_string()))?; + if !updates::endpoint_allowed(&url) { + return Err(Fail::host("update endpoint not allowed")); + } + let updater = app + .updater_builder() + .endpoints(vec![url]) + .map_err(|e| Fail::host(e.to_string()))? + .timeout(std::time::Duration::from_secs(30)) + .build() + .map_err(|e| Fail::host(updates::error_text(&e.to_string())))?; + updater.check().await.map_err(|e| Fail::host(updates::error_text(&e.to_string()))) +} + +/// Asks storebound.dev whether the chosen channel has a newer version. Reads only; installs nothing. +#[tauri::command] +pub async fn update_check(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>) -> Res { + guard(&window)?; + let channel = saved(&state)?.settings.channel.clone(); + let found = find_update(&app, &channel).await?; + Ok(UpdateInfo { + current: env!("CARGO_PKG_VERSION").into(), + channel, + available: found.as_ref().map(|u| u.version.clone()), + notes: found.as_ref().and_then(|u| u.body.clone()), + date: found.as_ref().and_then(|u| u.date).and_then(|d| u64::try_from(d.unix_timestamp()).ok()).map(store::iso_from_unix), + }) +} + +/// Installs `version` (the one the window showed) after a native dialog: download, signature check against the key +/// in tauri.conf.json, install, restart. False = the owner said no. Progress goes to the window as `update-progress`. +#[tauri::command] +pub async fn update_install(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, version: String) -> Res { + guard(&window)?; + let channel = saved(&state)?.settings.channel.clone(); + let Some(update) = find_update(&app, &channel).await? else { + return Err(Fail::host("no update available")); + }; + if update.version != version { + return Err(Fail::host(format!("storebound.dev now offers {} instead of {version}: check again", update.version))); + } + let text = format!( + "storebound {version} is ready (this is {}).\n\nThe update comes from storebound.dev; its signature is checked against this app's key before anything is replaced. Then storebound restarts.", + env!("CARGO_PKG_VERSION") + ); + if !confirm_dialog_with(&window, "Install the update?".into(), text, "Install and restart".into()).await? { + return Ok(false); + } + // the sidecar binary lives inside the app bundle that is about to be replaced + state.sidecar.shutdown().await; + let w = window.clone(); + let mut received: u64 = 0; + update + .download_and_install( + move |n, total| { + received += n as u64; + let _ = w.emit("update-progress", json!({ "received": received, "total": total })); + }, + || {}, + ) + .await + .map_err(|e| Fail::host(updates::error_text(&e.to_string())))?; + app.restart(); +} + +// --------------------------------------------------------------------------------------------------------------------- +// storebound://open?path= (`storebound desktop` in a terminal): select that app folder, or add it after a +// native dialog. Not a command: lib.rs calls it for a deep link. + +fn tell(app: &AppHandle, text: String) { + let mut d = app.dialog().message(text).title("storebound").kind(MessageDialogKind::Info); + if let Some(w) = app.get_webview_window(policy::MAIN) { + d = d.parent(&w); + } + d.show(|_| {}); +} + +pub async fn open_folder_link(app: AppHandle, dir: PathBuf) { + if let Err(e) = open_folder(&app, &dir).await { + tell(&app, e.message); + } +} + +async fn open_folder(app: &AppHandle, dir: &Path) -> Res<()> { + let state = app.state::(); + let window = app.get_webview_window(policy::MAIN).ok_or_else(|| Fail::host("no main window"))?; + let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string()); + let shown = tilde(&dir.to_string_lossy(), home.as_deref()); + let dir = std::fs::canonicalize(dir).map_err(|_| Fail::host(format!("{shown} does not exist")))?; + if !dir.is_dir() { + return Err(Fail::host(format!("{shown} is not a folder"))); + } + if !has_config(&dir) { + return Err(Fail::host(format!( + "{shown} has no storebound config.\n\nStart one with `storebound init` in that folder, or in storebound: App folders > Start an app folder." + ))); + } + let path = dir.to_string_lossy().to_string(); + let known = saved(&state)?.projects.iter().find(|p| p.path == path).map(|p| p.id.clone()); + let id = match known { + Some(id) => id, + None => { + let text = format!("{}\n\nAdd this app folder to storebound? Nothing in the folder changes.", tilde(&path, home.as_deref())); + if !confirm_dialog_with(&window, "Add an app folder".into(), text, "Add folder".into()).await? { + return Ok(()); + } + add_folder(app, &state, &dir).await?.id + } + }; + let _ = app.emit_to(policy::MAIN, "deep-link-folder", id); + Ok(()) +} diff --git a/apps/desktop/src-tauri/src/commands_list.rs b/apps/desktop/src-tauri/src/commands_list.rs index f6978ae9..e7fa104e 100644 --- a/apps/desktop/src-tauri/src/commands_list.rs +++ b/apps/desktop/src-tauri/src/commands_list.rs @@ -36,4 +36,6 @@ pub const COMMANDS: &[&str] = &[ "data_reveal", "notify", "app_reset", + "update_check", + "update_install", ]; diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 2c496974..c525d63f 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -6,6 +6,8 @@ pub mod commands; pub mod confirm; pub mod downloads; pub mod policy; +pub mod selftest; +pub mod updates; pub mod sidecar; pub mod store; pub mod workspace; @@ -87,8 +89,11 @@ fn menu(app: &AppHandle) -> tauri::Result> { Menu::with_items(app, &[&app_menu, &edit, &window]) } -fn handle_deep_link(app: &AppHandle, urls: &[url::Url]) { - if let Some(screen) = urls.iter().find_map(policy::deep_link_screen) { +fn handle_deep_link(app: &AppHandle, urls: &[url::Url]) { + if let Some(dir) = urls.iter().find_map(policy::deep_link_open_path) { + show_main(app); + tauri::async_runtime::spawn(commands::open_folder_link(app.clone(), dir)); + } else if let Some(screen) = urls.iter().find_map(policy::deep_link_screen) { show_main(app); let _ = app.emit_to(policy::MAIN, "deep-link", screen); } @@ -214,6 +219,8 @@ pub fn run() { commands::data_reveal, commands::notify, commands::app_reset, + commands::update_check, + commands::update_install, ]) .build(tauri::generate_context!()) .expect("storebound desktop failed to start"); diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index cdf49436..4ff89205 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -2,5 +2,10 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { + // Release smoke test of the exact artifact (tools/desktop-release.ts, the Forgejo workflow): sidecar handshake, + // one JSON line, exit. Runs before Tauri starts, so no window opens. + if std::env::args().skip(1).any(|a| a == storebound_desktop::selftest::FLAG) { + std::process::exit(storebound_desktop::selftest::run()); + } storebound_desktop::run(); } diff --git a/apps/desktop/src-tauri/src/policy.rs b/apps/desktop/src-tauri/src/policy.rs index a603df85..25b016ed 100644 --- a/apps/desktop/src-tauri/src/policy.rs +++ b/apps/desktop/src-tauri/src/policy.rs @@ -150,3 +150,26 @@ pub fn deep_link_screen(url: &Url) -> Option<&'static str> { let host = url.host_str().unwrap_or_default(); DEEP_LINK_SCREENS.iter().copied().find(|s| *s == host) } + +/// `storebound://open?path=` (what `storebound desktop` sends from a terminal): the folder to add or +/// select. Only an absolute, plain path: no `..`, no NUL or control characters, at most 4096 bytes, one `path` +/// parameter and nothing else. The host still checks that it is a folder with a storebound config and asks the owner +/// in a native dialog before adding it. +pub fn deep_link_open_path(url: &Url) -> Option { + if url.scheme() != "storebound" || url.host_str() != Some("open") || !url.username().is_empty() || url.password().is_some() || url.port().is_some() { + return None; + } + if !(url.path().is_empty() || url.path() == "/") || url.fragment().is_some() { + return None; + } + let pairs: Vec<(String, String)> = url.query_pairs().map(|(k, v)| (k.into_owned(), v.into_owned())).collect(); + let [(k, v)] = pairs.as_slice() else { return None }; + if k != "path" || v.is_empty() || v.len() > 4096 || v.chars().any(char::is_control) { + return None; + } + let p = std::path::PathBuf::from(v); + if !p.is_absolute() || p.components().any(|c| matches!(c, std::path::Component::ParentDir | std::path::Component::CurDir)) { + return None; + } + Some(p) +} diff --git a/apps/desktop/src-tauri/src/selftest.rs b/apps/desktop/src-tauri/src/selftest.rs new file mode 100644 index 00000000..cd9a3783 --- /dev/null +++ b/apps/desktop/src-tauri/src/selftest.rs @@ -0,0 +1,99 @@ +//! `storebound-desktop --self-test`: the release smoke test of the exact artifact. It starts the bundled sidecar the +//! same way the app does (next to the executable, policy::SIDECAR_ARGS), sends `session.hello` with a fresh secret, +//! checks the protocol, prints one JSON line and exits. No window, no webview, no Tauri runtime: it runs headless +//! (a CI runner, a mounted DMG, an SSH session) and never brings anything to the front. +use std::io::{BufRead, BufReader, Write}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use serde_json::{json, Value}; + +use crate::{confirm, policy}; + +pub const FLAG: &str = "--self-test"; +const PROTOCOL: &str = "storebound-desktop/1"; + +/// The bundled sidecar: Tauri puts `externalBin` next to the main executable without its target triple +/// (Contents/MacOS on macOS, the install folder on Windows, usr/bin in the AppImage and the deb). +pub fn sidecar_path() -> Result { + let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; + let dir = exe.parent().ok_or("the executable has no folder")?; + Ok(dir.join(format!("{}{}", policy::SIDECAR, std::env::consts::EXE_SUFFIX))) +} + +/// Exit code of the self-test (0 = the sidecar answered with the expected protocol). +pub fn run() -> i32 { + match check(Duration::from_secs(30)) { + Ok(v) => { + println!("{v}"); + 0 + } + Err(e) => { + eprintln!("self-test failed: {e}"); + 1 + } + } +} + +pub fn check(timeout: Duration) -> Result { + let bin = sidecar_path()?; + if !bin.is_file() { + return Err(format!("no sidecar next to the executable ({})", bin.file_name().unwrap_or_default().to_string_lossy())); + } + let started = Instant::now(); + let mut child = Command::new(&bin) + .args(policy::SIDECAR_ARGS) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .map_err(|e| format!("sidecar did not start: {e}"))?; + let secret = confirm::new_secret()?; + let hello = json!({ "jsonrpc": "2.0", "id": 1, "method": "session.hello", + "params": { "secret": confirm::hex(&secret), "client": { "name": "storebound-desktop-self-test", "version": env!("CARGO_PKG_VERSION") } } }); + let mut stdin = child.stdin.take().ok_or("no sidecar stdin")?; + let line = format!("{hello}\n"); + let stdout = child.stdout.take().ok_or("no sidecar stdout")?; + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + for l in BufReader::new(stdout).lines().map_while(Result::ok) { + if let Ok(v) = serde_json::from_str::(&l) { + if v.get("id").and_then(Value::as_u64) == Some(1) { + let _ = tx.send(v); + return; + } + } + } + }); + let wrote = stdin.write_all(line.as_bytes()).and_then(|_| stdin.flush()); + let answer = rx.recv_timeout(timeout); + drop(stdin); + let _ = child.kill(); + let _ = child.wait(); + wrote.map_err(|e| format!("sidecar stdin: {e}"))?; + let answer = answer.map_err(|_| format!("no answer to session.hello within {} s", timeout.as_secs()))?; + if let Some(e) = answer.get("error") { + return Err(format!("session.hello failed: {e}")); + } + let r = &answer["result"]; + let protocol = r["protocol"].as_str().unwrap_or_default(); + if protocol != PROTOCOL { + return Err(format!("unsupported sidecar protocol '{protocol}'")); + } + let methods = r["methods"].as_array().map(Vec::len).unwrap_or(0); + if methods == 0 { + return Err("the sidecar announced no methods".into()); + } + Ok(json!({ + "ok": true, + "app": env!("CARGO_PKG_VERSION"), + "sidecar": r["server"]["version"], + "protocol": protocol, + "methods": methods, + "ms": started.elapsed().as_millis() as u64, + "os": std::env::consts::OS, + "arch": std::env::consts::ARCH, + })) +} diff --git a/apps/desktop/src-tauri/src/updates.rs b/apps/desktop/src-tauri/src/updates.rs new file mode 100644 index 00000000..40c0ef51 --- /dev/null +++ b/apps/desktop/src-tauri/src/updates.rs @@ -0,0 +1,37 @@ +//! Signed updates from storebound.dev. The updater plugin checks `latest.json` of the chosen channel, downloads the +//! platform's bundle and refuses it unless its minisign signature matches the public key in tauri.conf.json (the +//! private key never leaves the release machine, ~/.storebound-keys). Nothing installs without the owner's click in +//! a native dialog (commands::update_install). Pure parts here so tests can pin them. +use url::Url; + +/// `latest.json` of each channel (static files on storebound.dev, published by tools/desktop-release.ts). +pub const STABLE: &str = "https://storebound.dev/desktop/latest.json"; +pub const BETA: &str = "https://storebound.dev/desktop/beta/latest.json"; + +/// The endpoint of a channel (Settings > Updates); anything unknown is the stable channel. +pub fn endpoint(channel: &str) -> &'static str { + if channel == "beta" { + BETA + } else { + STABLE + } +} + +/// Only storebound.dev over HTTPS, without port or user info, may serve updates. +pub fn endpoint_allowed(url: &Url) -> bool { + url.scheme() == "https" && url.host_str() == Some("storebound.dev") && url.port().is_none() && url.username().is_empty() && url.password().is_none() && url.path().starts_with("/desktop/") +} + +/// The updater's error in words the owner can act on. +pub fn error_text(e: &str) -> String { + let l = e.to_lowercase(); + if l.contains("signature") { + "the update's signature does not match this app's key: not installed".into() + } else if l.contains("404") || l.contains("not found") { + "no update information on storebound.dev yet".into() + } else if l.contains("platform") { + "no update for this system in the latest release yet".into() + } else { + format!("update check failed: {e}") + } +} diff --git a/apps/desktop/src-tauri/tests/d5.rs b/apps/desktop/src-tauri/tests/d5.rs new file mode 100644 index 00000000..df7c6d8b --- /dev/null +++ b/apps/desktop/src-tauri/tests/d5.rs @@ -0,0 +1,104 @@ +//! D5 release pipeline: one version everywhere, the updater's key and endpoints, the `storebound://open?path=` deep +//! link and the self-test the release runs on the exact artifact. +use std::fs; +use std::path::PathBuf; + +use base64::Engine; +use serde_json::Value; +use storebound_desktop::policy::deep_link_open_path; +use storebound_desktop::{selftest, updates}; +use url::Url; + +fn root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +fn conf() -> Value { + serde_json::from_str(&fs::read_to_string(root().join("tauri.conf.json")).unwrap()).unwrap() +} + +#[test] +fn one_version_from_the_root_package_json() { + let pkg: Value = serde_json::from_str(&fs::read_to_string(root().join("../../../package.json")).unwrap()).unwrap(); + let want = pkg["desktopVersion"].as_str().expect("package.json desktopVersion"); + assert_eq!(env!("CARGO_PKG_VERSION"), want, "Cargo.toml (bun tools/desktop-version.ts --set {want})"); + assert_eq!(conf()["version"], want, "tauri.conf.json"); + let app: Value = serde_json::from_str(&fs::read_to_string(root().join("../package.json")).unwrap()).unwrap(); + assert_eq!(app["version"], want, "apps/desktop/package.json"); +} + +#[test] +fn updater_has_a_real_minisign_key_and_only_storebound_dev() { + let c = conf(); + let key = c["plugins"]["updater"]["pubkey"].as_str().unwrap(); + let text = String::from_utf8(base64::engine::general_purpose::STANDARD.decode(key).expect("base64 pubkey")).unwrap(); + let mut lines = text.lines(); + assert!(lines.next().unwrap().starts_with("untrusted comment: minisign public key")); + let raw = base64::engine::general_purpose::STANDARD.decode(lines.next().unwrap()).unwrap(); + assert_eq!(raw.len(), 42, "Ed + key id + 32-byte key"); + assert_eq!(&raw[..2], b"Ed"); + assert_eq!(c["plugins"]["updater"]["endpoints"], serde_json::json!([updates::STABLE])); + // updater bundles are signed by tools/desktop-release.ts on the release Mac, never by a CI runner + assert_eq!(c["bundle"]["createUpdaterArtifacts"], false); + for ch in ["stable", "beta", "nightly", ""] { + assert!(updates::endpoint_allowed(&Url::parse(updates::endpoint(ch)).unwrap()), "{ch}"); + } + assert_eq!(updates::endpoint("beta"), updates::BETA); + assert_eq!(updates::endpoint("anything"), updates::STABLE); + for bad in ["http://storebound.dev/desktop/latest.json", "https://storebound.dev:8443/desktop/latest.json", "https://evil.test/desktop/latest.json", "https://storebound.dev/latest.json"] { + assert!(!updates::endpoint_allowed(&Url::parse(bad).unwrap()), "{bad}"); + } + assert!(updates::error_text("signature verification failed").contains("not installed")); +} + +#[test] +fn open_deep_link_takes_one_plain_absolute_path() { + let p = |s: &str| deep_link_open_path(&Url::parse(s).unwrap()); + let abs = if cfg!(windows) { "C:%5Cgames%5CDemo App" } else { "%2FUsers%2Fyou%2Fgames%2FDemo App" }; + let want = if cfg!(windows) { "C:\\games\\Demo App" } else { "/Users/you/games/Demo App" }; + assert_eq!(p(&format!("storebound://open?path={abs}")), Some(PathBuf::from(want))); + assert_eq!(p(&format!("storebound://open/?path={abs}")), Some(PathBuf::from(want))); + for bad in [ + "storebound://open?path=games%2FDemo App".to_string(), + "storebound://open?path=".to_string(), + "storebound://open".to_string(), + format!("storebound://open?path={abs}&path={abs}"), + format!("storebound://open?path={abs}&run=1"), + format!("storebound://open?path={abs}%2F..%2F..%2Fetc"), + format!("storebound://open?path={abs}%0A"), + format!("storebound://open/x?path={abs}"), + format!("storebound://open?path={abs}#f"), + format!("storebound://user@open?path={abs}"), + format!("storebound://apps?path={abs}"), + format!("https://open?path={abs}"), + format!("storebound://open?path={}", "a".repeat(5000)), + ] { + assert_eq!(p(&bad), None, "{bad}"); + } +} + +#[test] +fn self_test_looks_for_the_sidecar_next_to_the_executable() { + let p = selftest::sidecar_path().unwrap(); + let exe = std::env::current_exe().unwrap(); + assert_eq!(p.parent(), exe.parent()); + assert_eq!(p.file_name().unwrap().to_string_lossy(), format!("storebound{}", std::env::consts::EXE_SUFFIX)); + assert_eq!(selftest::FLAG, "--self-test"); + // the flag is handled in main before Tauri starts, so no window opens + let main = fs::read_to_string(root().join("src/main.rs")).unwrap(); + let flag = main.find("selftest::FLAG").unwrap(); + assert!(flag < main.find("storebound_desktop::run()").unwrap()); +} + +#[test] +fn deep_links_to_folders_ask_before_adding() { + let cmds = fs::read_to_string(root().join("src/commands.rs")).unwrap(); + let at = cmds.find("async fn open_folder(").unwrap(); + let body = &cmds[at..]; + let confirm = body.find("confirm_dialog_with(").unwrap(); + let add = body.find("add_folder(").unwrap(); + assert!(confirm < add, "the native dialog comes before add_folder"); + let at = cmds.find("pub async fn update_install(").unwrap(); + let body = &cmds[at..]; + assert!(body.find("confirm_dialog_with(").unwrap() < body.find("download_and_install(").unwrap()); +} diff --git a/apps/desktop/src-tauri/tests/security.rs b/apps/desktop/src-tauri/tests/security.rs index 7254c2d7..68697fe2 100644 --- a/apps/desktop/src-tauri/tests/security.rs +++ b/apps/desktop/src-tauri/tests/security.rs @@ -173,6 +173,12 @@ fn sidecar_starts_with_fixed_arguments_from_one_place() { assert!(src.contains(".args(policy::SIDECAR_ARGS)")); } assert!(!src.contains(".command("), "{}: no other programs are started", p.display()); + // the release self-test (--self-test) starts the bundled sidecar with the same fixed arguments, nothing else + if p.ends_with("selftest.rs") { + assert_eq!(src.matches("Command::new(").count(), 1); + assert!(src.contains("Command::new(&bin)\n .args(policy::SIDECAR_ARGS)")); + continue; + } // other programs: only the download checks (unpack, signature, version banner), with fixed program names if src.contains("Command::new(") { assert!(p.ends_with("downloads.rs"), "{} starts a program", p.display()); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index ac703b95..f0ecfa16 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -1,7 +1,7 @@ // Shell: sidebar (studios, collapsible, with their apps; the workspace), top bar (breadcrumbs, last read, refresh), // the screen, the command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide. import { useCallback, useEffect, useMemo, useState } from 'react'; -import { FIXTURES, onDeepLink } from './api'; +import { FIXTURES, onDeepLink, onDeepLinkFolder } from './api'; import { devSwitch } from './dev/switches'; import { type Key, t } from './i18n'; import { ago } from './lib/format'; @@ -61,8 +61,10 @@ export function App({ onTheme }: { onTheme: () => void }) { useEffect(() => { const un = onDeepLink(s => { const r = parseStart(s, []); if (r) go(r); }); - return () => { un.then(f => f()); }; - }, [go]); + // `storebound desktop` in an app folder: the host added (after its native dialog) or found that folder + const unFolder = onDeepLinkFolder(id => { d.reload().catch(() => {}).finally(() => go({ screen: 'app', appId: id, tab: 'releases' })); }); + return () => { un.then(f => f()); unFolder.then(f => f()); }; + }, [go, d.reload]); const app = route.screen === 'app' ? d.appByKey(route.appId) : undefined; const tabs = app ? tabsFor(!!app.project) : []; diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index e97a1e60..00c195d7 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -38,6 +38,7 @@ export interface CacheEntry { value: T; at: string } export interface DownloadInfo { tool: 'ffmpeg' | 'chrome'; available: boolean; version: string | null; size: number | null; license: string; licenseUrl: string; source: string; installed: boolean; folder: string } export interface DownloadEvent { job: string; tool: string; stage: 'resolve' | 'download' | 'verify' | 'unpack' | 'install' | 'done' | 'error' | 'cancelled'; received: number; total: number | null; message?: string } export type { IconResult as Icon }; +export interface UpdateInfo { current: string; channel: 'stable' | 'beta'; available: string | null; notes: string | null; date: string | null } /** What a failed command rejects with (sidecar.rs `Fail`). */ export interface Fail { code: number; message: string; data?: unknown } @@ -111,6 +112,10 @@ export const api = { toolsInfo: () => invoke('tools_info'), installTool: (tool: 'ffmpeg' | 'chrome', job: string) => invoke('tools_install', { tool, job }), uninstallTool: (tool: 'ffmpeg' | 'chrome') => invoke('tools_uninstall', { tool }), + /** Asks storebound.dev for a newer version on the chosen channel (installs nothing). */ + updateCheck: () => invoke('update_check'), + /** Native dialog, then download, signature check, install and restart. False = not installed. */ + updateInstall: (version: string) => invoke('update_install', { version }), }; /** Typed reads of the project files (offline) and the stores (network). */ @@ -125,3 +130,6 @@ export const onProgress = (cb: (p: ProgressEvent) => void): Promise listen<{ params: ProgressParams; job?: string }>('sidecar-progress', e => cb({ ...e.params, job: e.job })); export const onDownload = (cb: (e: DownloadEvent) => void): Promise => listen('tool-download', cb); export const onDeepLink = (cb: (screen: string) => void): Promise => listen('deep-link', cb); +/** storebound://open?path=... selected or added an app folder (its project id). */ +export const onDeepLinkFolder = (cb: (projectId: string) => void): Promise => listen('deep-link-folder', cb); +export const onUpdateProgress = (cb: (p: { received: number; total: number | null }) => void): Promise => listen('update-progress', cb); diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 8dfde395..9d265579 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -463,6 +463,8 @@ async function answer(cmd: string, a: Record): Promise case 'cache_info': return { rows: 214, bytes: 3_412_000, oldest: iso(60 * 24 * 26), file_bytes: 4_718_592 }; case 'data_reveal': case 'notify': return null; case 'app_reset': return false; + case 'update_check': await sleep(300); return { current: '0.1.0', channel: settings.channel, available: null, notes: null, date: null }; + case 'update_install': return false; case 'portfolio_status': { const stores = (a.stores as string[] | undefined) ?? []; if (a.live) { diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index f0fc17a9..2750f5b0 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -763,7 +763,13 @@ export const en = { 'set.channel': 'Channel', 'set.stable': 'Stable', 'set.beta': 'Beta', - 'set.updatesText': 'Signed updates from storebound.dev arrive with the first public desktop release; the channel is kept for then.', + 'set.updatesText': 'Updates come from storebound.dev and are signed; the app checks the signature before it replaces anything, and installs only when you press Install. Nothing is checked in the background.', + 'set.updateCheck': 'Check for updates', + 'set.updateChecking': 'Checking…', + 'set.updateNone': 'storebound {version} is the newest version on the {channel} channel.', + 'set.updateAvailable': 'storebound {version} is available.', + 'set.updateInstall': 'Install {version}…', + 'set.updateInstalling': 'Downloading the update… {done}', 'set.reset': 'Reset', 'set.resetText': 'Forgets {accounts} accounts (their keys are removed from the keychain), {studios} studios, {folders} app folders (the folders stay on disk), pairing, the ignore list, settings and saved reads. A system dialog asks first.', 'set.resetButton': 'Reset the app', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 688a0d93..d91d1ed7 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -765,7 +765,13 @@ export const tr: Record = { 'set.channel': 'Kanal', 'set.stable': 'Kararlı', 'set.beta': 'Beta', - 'set.updatesText': 'storebound.dev\'den imzalı güncellemeler ilk herkese açık masaüstü sürümüyle gelir; kanal o zaman için saklanır.', + 'set.updatesText': 'Güncellemeler storebound.dev\'den imzalı gelir; uygulama bir şeyi değiştirmeden önce imzayı denetler ve yalnızca siz Yükle\'ye bastığınızda yükler. Arka planda denetim yapılmaz.', + 'set.updateCheck': 'Güncellemeleri denetle', + 'set.updateChecking': 'Denetleniyor…', + 'set.updateNone': 'storebound {version}, {channel} kanalındaki en yeni sürüm.', + 'set.updateAvailable': 'storebound {version} çıktı.', + 'set.updateInstall': '{version} sürümünü yükle…', + 'set.updateInstalling': 'Güncelleme indiriliyor… {done}', 'set.reset': 'Sıfırla', 'set.resetText': '{accounts} hesabı (anahtarları anahtar zincirinden silinir), {studios} stüdyoyu, {folders} uygulama klasörünü (klasörler diskte kalır), eşleştirmeyi, yok sayılanları, ayarları ve kayıtlı okumaları unutur. Önce bir sistem penceresi sorar.', 'set.resetButton': 'Uygulamayı sıfırla', diff --git a/apps/desktop/src/screens/Settings.tsx b/apps/desktop/src/screens/Settings.tsx index 8f131961..8301db44 100644 --- a/apps/desktop/src/screens/Settings.tsx +++ b/apps/desktop/src/screens/Settings.tsx @@ -2,7 +2,7 @@ // (on launch, every N minutes, how many apps at once, icons), the offline cache, language and theme, notifications, // local tools, the CLI sidecar, privacy, keyboard shortcuts, updates and reset. A section list on the left jumps. import { useEffect, useState } from 'react'; -import { api, type CacheInfo, errorText, type Settings as S } from '../api'; +import { api, type CacheInfo, errorText, onUpdateProgress, type Settings as S, type UpdateInfo } from '../api'; import { type Key, t } from '../i18n'; import { ago, bytes, date, num } from '../lib/format'; import { pairCandidates, type UnifiedApp, withPair, withUnpair } from '../lib/identity'; @@ -221,6 +221,7 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
{t('set.channel')} set(x => ({ ...x, channel }))} options={[['stable', t('set.stable')], ['beta', t('set.beta')]]} />
+

{t('set.updatesText')}

@@ -240,3 +241,33 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void; ); } + +/** Settings > Updates: checks on click only; installs after the host's native dialog (the signature is checked there). */ +function Updates() { + const [info, setInfo] = useState(null); + const [busy, setBusy] = useState<'check' | 'install' | null>(null); + const [error, setError] = useState(null); + const [got, setGot] = useState<{ received: number; total: number | null } | null>(null); + useEffect(() => { const un = onUpdateProgress(setGot); return () => { un.then(f => f()); }; }, []); + const check = async () => { + setBusy('check'); setError(null); + try { setInfo(await api.updateCheck()); } catch (e) { setError(errorText(e)); } finally { setBusy(null); } + }; + const install = async (version: string) => { + setBusy('install'); setError(null); + try { await api.updateInstall(version); } catch (e) { setError(errorText(e)); } finally { setBusy(null); setGot(null); } + }; + const channel = info ? t(info.channel === 'beta' ? 'set.beta' : 'set.stable') : ''; + return ( +
+ {error && {error}} + {info && !info.available &&

{t('set.updateNone', { version: info.current, channel })}

} + {info?.available &&

{t('set.updateAvailable', { version: info.available })}{info.notes ? ` ${info.notes}` : ''}

} + {busy === 'install' && got &&

{t('set.updateInstalling', { done: got.total ? `${Math.round((got.received / got.total) * 100)}%` : bytes(got.received) })}

} +
+ + {info?.available && } +
+
+ ); +}