diff --git a/.forgejo/workflows/desktop.yml b/.forgejo/workflows/desktop.yml new file mode 100644 index 00000000..ae3e049d --- /dev/null +++ b/.forgejo/workflows/desktop.yml @@ -0,0 +1,114 @@ +# storebound desktop: Linux (AppImage + deb) and Windows (NSIS, per user, unsigned) installers. +# macOS is built, signed and notarized on the owner's Mac (tools/desktop-release.ts mac); the updater signing key +# never reaches a runner: the Mac signs these installers after downloading them (tools/desktop-release.ts add). +# Runner setup (act_runner on the VDS for Linux in Docker, a Windows runner later): docs/desktop-release.md. +name: desktop + +on: + workflow_dispatch: + inputs: + windows: + description: Build Windows too (needs a runner with the "windows" label) + type: boolean + default: false + push: + tags: ['desktop-v*'] + +env: + BUN_VERSION: '1.4.0' + # the path-free build keeps the target folder outside every home folder + CARGO_TARGET_DIR: /tmp/storebound-target + CARGO_TERM_COLOR: never + +jobs: + linux: + # act_runner label: ubuntu-22.04:docker://ghcr.io/catthehacker/ubuntu:act-22.04 (glibc 2.35: the AppImage and the + # deb then run on Ubuntu 22.04 and newer, Debian 12) + runs-on: ubuntu-22.04 + timeout-minutes: 90 + env: + # linuxdeploy (AppImage) runs without FUSE inside the container + APPIMAGE_EXTRACT_AND_RUN: '1' + # WebKitGTK's DMABUF renderer leaves the window blank on some GPU / VM setups; the app sets this itself at + # start (src-tauri/src/lib.rs linux_webkit_env) unless the user did; set here too for anything run in CI + WEBKIT_DISABLE_DMABUF_RENDERER: '1' + steps: + - uses: actions/checkout@v4 + - name: System packages + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \ + librsvg2-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev libssl-dev libxdo-dev patchelf file build-essential \ + curl unzip squashfs-tools p7zip-full xz-utils + - name: Bun and Rust + run: | + curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" + echo "$HOME/.bun/bin" >> "$GITHUB_PATH" + command -v rustup || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + - name: Install and check + run: | + bun install --frozen-lockfile + bun tools/desktop-version.ts + bun tools/build-sidecars.ts --target bun-linux-x64 + - name: Build AppImage and deb (path-free) + working-directory: apps/desktop + run: bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles appimage,deb --ci + - name: Self-test the exact artifacts + run: | + V=$(bun tools/desktop-version.ts --print) + B="$CARGO_TARGET_DIR/release/bundle" + mkdir -p out && cp "$B/appimage/storebound_${V}_amd64.AppImage" "$B/deb/storebound_${V}_amd64.deb" out/ + chmod +x out/*.AppImage + (cd /tmp && rm -rf squashfs-root && "$GITHUB_WORKSPACE/out/storebound_${V}_amd64.AppImage" --appimage-extract >/dev/null && squashfs-root/usr/bin/storebound-desktop --self-test) + rm -rf /tmp/deb && dpkg-deb -x "out/storebound_${V}_amd64.deb" /tmp/deb && /tmp/deb/usr/bin/storebound-desktop --self-test + dpkg-deb -I "out/storebound_${V}_amd64.deb" | sed -n '1,20p' + - name: Privacy scan + run: bun tools/privacy-scan.ts out/ + - name: Checksums + run: (cd out && sha256sum * | tee SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: storebound-desktop-linux + path: out/ + retention-days: 14 + + windows: + if: ${{ inputs.windows }} + # a Windows runner registered with the "windows" label (host mode): Rust (MSVC), Bun, 7-Zip + runs-on: windows + timeout-minutes: 90 + env: + CARGO_TARGET_DIR: C:\storebound-target + steps: + - uses: actions/checkout@v4 + - name: Install and check + shell: pwsh + run: | + bun install --frozen-lockfile + bun tools/desktop-version.ts + bun tools/build-sidecars.ts --target bun-windows-x64 + - name: Build NSIS installer (per user, WebView2 bootstrapper, path-free) + shell: pwsh + working-directory: apps/desktop + run: bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles nsis --ci + - name: Install per user, self-test, uninstall + shell: pwsh + run: | + $V = bun tools/desktop-version.ts --print + New-Item -ItemType Directory -Force out | Out-Null + Copy-Item "$env:CARGO_TARGET_DIR\release\bundle\nsis\storebound_${V}_x64-setup.exe" out\ + Start-Process -Wait -FilePath "out\storebound_${V}_x64-setup.exe" -ArgumentList '/S' + $exe = "$env:LOCALAPPDATA\storebound\storebound-desktop.exe" + if (-not (Test-Path $exe)) { throw "not installed per user at $exe" } + & $exe --self-test | Tee-Object -Variable st + if ($LASTEXITCODE -ne 0) { throw "self-test failed" } + Start-Process -Wait -FilePath "$env:LOCALAPPDATA\storebound\uninstall.exe" -ArgumentList '/S' + - name: Privacy scan (no .pdb, no paths) + shell: pwsh + run: bun tools/privacy-scan.ts out + - uses: actions/upload-artifact@v3 + with: + name: storebound-desktop-windows + path: out/ + retention-days: 14 diff --git a/CHANGELOG.md b/CHANGELOG.md index 426a69ec..7c4ed21f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,17 @@ subscription price diffs; `health` treats App Store Connect's 404 for builds without field data as no diagnostics; `validate` no longer blocks on age rating fields accepted submissions leave empty (`gracRatingClassificationNumber`, `socialMediaAgeRestricted` unless social media is yes; `socialMedia` is a warning). +- **Desktop D5: release pipeline.** The desktop app is a separate signed download from storebound.dev/desktop/ (DMG, + Windows installer, AppImage / deb) that updates itself; the npm package stays the CLI, MCP server and skills. + `storebound desktop` opens the app (in an app folder it adds or selects that folder through + `storebound://open?path=`, after the app's own dialog) or prints the download for this system; `--download` saves + it to ~/Downloads after checking its SHA-256 and minisign signature, and never installs. One desktop version + (`desktopVersion` in package.json, checked in CI), a privacy scan of every artifact (`tools/privacy-scan.ts`), + path-free builds, `tools/desktop-release.ts` (universal macOS app + DMG, Developer ID + notarization when the + certificate exists, otherwise an ad-hoc `-unsigned` preview; self-test of the exact artifacts; signed latest.json), + a Forgejo workflow for Linux and Windows, the root-owned publish step on the server and a downloads page + (`site/desktop/`). Settings > Updates checks and installs signed updates on request. See `docs/desktop-release.md`. + - **Desktop machine interface** (`serve --stdio`): JSON-RPC session for the coming desktop app, built on the MCP core. Typed methods with argument schemas, structured results, progress notifications, cancellation, `project.inspect` and `portfolio.status`: apps across iOS and Android with identity, config check, release trains (current and next diff --git a/README.md b/README.md index 0974cb17..adc8e5b4 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,7 @@ run in the background with a log (`storebound shots render > .storebound/render. | `validate [--apple] [--play]` | API, read-only | readiness report with ordered blockers plus the local renders checks (`--no-local` skips); exit 1 while any blocker is left | | `whats-new [--since ]` | local | draft player-facing release notes from git log into both listing files | | `privacy-manifest --ios ` | local | PrivacyInfo.xcprivacy, required-reason APIs, SDKs without manifests | +| `desktop [--download]` | local | open the storebound desktop app (in an app folder: add or select it there); not installed: the download for this system, `--download` saves it to ~/Downloads after checking its signature (never installs) | | `doctor [--json]` | local | which local tools are here (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install the missing ones | | `icons` | local | App Store 1024 (no alpha), Play 512, web, Capacitor sources, Android legacy launcher icons | 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/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index aaf78590..e673cbd1 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "../package.json", + "version": "0.1.0", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", @@ -69,6 +69,13 @@ ], "macOS": { "minimumSystemVersion": "11.0" + }, + "windows": { + "webviewInstallMode": { "type": "embedBootstrapper" }, + "nsis": { "installMode": "currentUser" } + }, + "linux": { + "deb": { "section": "devel" } } }, "plugins": { @@ -79,7 +86,7 @@ }, "updater": { "endpoints": ["https://storebound.dev/desktop/latest.json"], - "pubkey": "PLACEHOLDER-minisign-public-key-set-in-D5" + "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ0Rjc4QTc4RDlFRjM4MkEKUldRcU9PL1plSXIzUkJtb2x0L2Z4MTA4bTg5UU5FVW5kUlRGcnVjangwQ0JNb2VGYjcveGhydlcK" } } } 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 && } +
+
+ ); +} diff --git a/cli/desktop.ts b/cli/desktop.ts new file mode 100644 index 00000000..1a11e0ac --- /dev/null +++ b/cli/desktop.ts @@ -0,0 +1,107 @@ +// `storebound desktop`: the bridge from the terminal to the desktop app. The app is a separate signed download from +// storebound.dev (it updates itself and brings its own copy of this CLI); the npm package never contains it. +// storebound desktop open the app; in an app folder (storebound.config.*) it adds or selects that +// folder (storebound://open?path=..., the app asks before adding) +// storebound desktop --dir the same for another folder; --no-folder: just open the app +// storebound desktop --download not installed: download the installer for this system into ~/Downloads, +// check its SHA-256 and signature, and print where it is. It never installs. +// --channel beta, --format deb (Linux), --json (print what it would do, change nothing) +import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { join, resolve } from 'node:path'; +import type { Args } from './lib/args'; +import { CONFIG_NAMES } from './lib/config'; +import { BUNDLE_ID, DOWNLOAD_LABEL, type Download, type DownloadKey, downloadsDir, downloadsFor, findInstalled, MANIFEST, type Manifest, manifestProblems, openCommand, openFolderLink, PAGE, PUBLIC_KEY } from './lib/desktop-dist'; +import { verify } from './lib/minisign'; + +type Fetch = (url: string) => Promise; + +export async function fetchManifest(channel: 'stable' | 'beta', get: Fetch = fetch): Promise { + const r = await get(MANIFEST[channel]); + if (!r.ok) throw new Error(`${MANIFEST[channel]}: HTTP ${r.status}`); + const m = await r.json() as unknown; + const problems = manifestProblems(m); + if (problems.length) throw new Error(`latest.json: ${problems.join('; ')}`); + return m as Manifest; +} + +/** Picks the installer for this system: the first of downloadsFor() the release has (or the asked format). */ +export function pick(m: Manifest, keys: DownloadKey[], format?: string): [DownloadKey, Download] | null { + const want = format ? keys.filter(k => k.endsWith(`-${format}`)) : keys; + for (const k of want) { const d = m.downloads?.[k]; if (d) return [k, d]; } + return null; +} + +/** Downloads one installer and keeps it only when its size, SHA-256 and minisign signature are right. */ +export async function download(d: Download, dir: string, get: Fetch = fetch, publicKey = PUBLIC_KEY): Promise { + const r = await get(d.url); + if (!r.ok) throw new Error(`${d.url}: HTTP ${r.status}`); + const data = new Uint8Array(await r.arrayBuffer()); + if (data.length !== d.size) throw new Error(`${d.file}: ${data.length} bytes, latest.json says ${d.size}; not kept`); + const sha = createHash('sha256').update(data).digest('hex'); + if (sha !== d.sha256) throw new Error(`${d.file}: SHA-256 ${sha} does not match latest.json; not kept`); + const v = verify(data, d.signature, publicKey); + if (!v.ok) throw new Error(`${d.file}: signature check failed (${v.reason}); not kept`); + mkdirSync(dir, { recursive: true }); + const out = join(dir, d.file); + const tmp = `${out}.part`; + writeFileSync(tmp, data); + renameSync(tmp, out); + return out; +} + +export async function run(args: Args): Promise { + const platform = process.platform; + const channel = args.get('channel') === 'beta' ? 'beta' : 'stable'; + const dir = resolve(args.str('dir', '.')); + const isApp = !args.has('no-folder') && CONFIG_NAMES.some(n => existsSync(join(dir, n))); + const installed = findInstalled(platform); + + if (installed && !args.has('download')) { + const link = isApp ? openFolderLink(dir) : null; + const cmd = openCommand(platform, installed, link); + if (args.has('json')) { console.log(JSON.stringify({ installed, link, command: cmd }, null, 2)); return; } + const p = Bun.spawn(cmd, { stdio: ['ignore', 'ignore', 'pipe'] }); + if (platform === 'darwin') { + const code = await p.exited; + if (code !== 0) throw new Error(`open -b ${BUNDLE_ID} failed: ${(await new Response(p.stderr).text()).trim()}`); + } else p.unref(); + console.log(link ? `storebound desktop: opening ${dir} (the app asks before it adds a new folder)` : 'storebound desktop: opened'); + return; + } + + const keys = downloadsFor(platform, process.arch); + let manifest: Manifest | null = null; + let error = ''; + try { manifest = await fetchManifest(channel); } catch (e) { error = (e as Error).message; } + const chosen = manifest ? pick(manifest, keys, args.get('format')) : null; + + if (args.has('json')) { + console.log(JSON.stringify({ installed, page: PAGE, version: manifest?.version ?? null, download: chosen ? { kind: chosen[0], ...chosen[1] } : null, error: error || null }, null, 2)); + return; + } + if (!args.has('download')) { + console.log(installed ? 'storebound desktop is installed.' : 'storebound desktop is not installed on this machine.'); + if (chosen) { + console.log(`\n ${DOWNLOAD_LABEL[chosen[0]]}, version ${manifest!.version}${chosen[1].codeSigned ? '' : ' (unsigned preview)'}:\n ${chosen[1].url}\n SHA-256 ${chosen[1].sha256}`); + } else if (!keys.length) { + console.log(`\n There is no desktop build for ${platform} ${process.arch} yet.`); + } else if (error) { + console.log(/HTTP 404/.test(error) ? '\n No desktop release is published yet.' : `\n (could not read the release list: ${error})`); + } + console.log(`\n Every download and its checksum: ${PAGE}`); + if (chosen) console.log(' Or: storebound desktop --download (saves the installer in ~/Downloads after checking its signature; it does not install it)'); + return; + } + if (!manifest) throw new Error(`could not read the release list: ${error}`); + if (!chosen) throw new Error(keys.length ? `version ${manifest.version} has no ${args.get('format') ?? 'installer'} for ${platform} ${process.arch} yet; see ${PAGE}` : `no desktop build for ${platform} ${process.arch}; see ${PAGE}`); + const [kind, d] = chosen; + console.log(`downloading ${d.file} (${(d.size / 1e6).toFixed(1)} MB, ${DOWNLOAD_LABEL[kind]})`); + const target = downloadsDir(); + let out: string; + try { out = await download(d, target); } catch (e) { rmSync(join(target, `${d.file}.part`), { force: true }); throw e; } + console.log(`saved ${out}\n SHA-256 and signature checked (key of storebound desktop). Not installed: open it yourself to install.`); + if (!d.codeSigned) console.log(platform === 'darwin' + ? ' This preview is not signed by Apple yet: after copying storebound to Applications, open it once, then System Settings > Privacy & Security > Open Anyway.' + : platform === 'win32' ? ' This preview is not code signed yet: Windows SmartScreen may ask; choose More info > Run anyway.' : ''); +} diff --git a/cli/index.ts b/cli/index.ts index 58aaba93..fed2ff2d 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -15,6 +15,7 @@ const PLAIN: Record Promise, string]> = { 'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'], 'serve': [() => import('./serve'), '--stdio: JSON-RPC session for the storebound desktop app (dry runs; writes need a host confirm token)'], 'apps': [() => import('./apps'), 'list (every app the store keys can see: App Store Connect team, Play developer accounts; --icons) | check (key works / permission missing / revoked, with the fix); --store apple|play, --json; read-only'], + 'desktop': [() => import('./desktop'), 'open the storebound desktop app (in an app folder: add or select it there); not installed: the download for this system, --download saves it to ~/Downloads after checking its signature (never installs)'], 'doctor': [() => import('./doctor'), 'local tools for screenshots, previews, icons and captures (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install what is missing; --json'], 'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios )'], }; diff --git a/cli/lib/desktop-dist.ts b/cli/lib/desktop-dist.ts new file mode 100644 index 00000000..e8d4ee93 --- /dev/null +++ b/cli/lib/desktop-dist.ts @@ -0,0 +1,129 @@ +// Where the storebound desktop app comes from and where it lives once installed. The app is a separate signed +// download from storebound.dev (DMG, Windows installer, AppImage / deb) that updates itself; the npm package stays +// the CLI, MCP server and skills and carries no app binaries. `storebound desktop` (cli/desktop.ts) uses this. +// +// storebound.dev/desktop/latest.json is Tauri's updater manifest (version, notes, pub_date, platforms: the update +// bundles with their minisign signatures) plus a `downloads` map of the installers people download by hand, each +// with its URL, SHA-256, size and minisign signature (the same key as the updater). Pure functions, tested in +// tests/desktop-dist.test.ts. +import { existsSync, readdirSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +export const BUNDLE_ID = 'dev.storebound.desktop'; +export const PAGE = 'https://storebound.dev/desktop/'; +export const MANIFEST: Record<'stable' | 'beta', string> = { + stable: 'https://storebound.dev/desktop/latest.json', + beta: 'https://storebound.dev/desktop/beta/latest.json', +}; +/** The updater public key of the desktop app (tauri.conf.json plugins.updater.pubkey; a test keeps them equal). */ +export const PUBLIC_KEY = 'dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDQ0Rjc4QTc4RDlFRjM4MkEKUldRcU9PL1plSXIzUkJtb2x0L2Z4MTA4bTg5UU5FVW5kUlRGcnVjangwQ0JNb2VGYjcveGhydlcK'; + +export type DownloadKey = 'macos-universal-dmg' | 'windows-x86_64-nsis' | 'linux-x86_64-appimage' | 'linux-x86_64-deb'; +export interface Download { + file: string; + url: string; + sha256: string; + size: number; + /** Tauri's form of the minisign signature (base64 of the .sig file). */ + signature: string; + /** Code signing by the OS vendor's scheme (Developer ID + notarization, Authenticode); false = an unsigned preview. */ + codeSigned: boolean; +} +export interface Manifest { + version: string; + notes?: string; + pub_date?: string; + platforms: Record; + downloads?: Partial>; +} + +export const DOWNLOAD_LABEL: Record = { + 'macos-universal-dmg': 'macOS 11+ (Apple silicon and Intel), .dmg', + 'windows-x86_64-nsis': 'Windows 10/11 x64, installer (.exe, per user)', + 'linux-x86_64-appimage': 'Linux x64, AppImage', + 'linux-x86_64-deb': 'Linux x64 (Debian, Ubuntu), .deb', +}; + +/** The installers for this OS and CPU, best first; [] when there is no build for it yet. */ +export function downloadsFor(platform: NodeJS.Platform, arch: string): DownloadKey[] { + if (platform === 'darwin' && (arch === 'arm64' || arch === 'x64')) return ['macos-universal-dmg']; + if (platform === 'win32' && arch === 'x64') return ['windows-x86_64-nsis']; + if (platform === 'linux' && arch === 'x64') return ['linux-x86_64-appimage', 'linux-x86_64-deb']; + return []; +} + +const SHA256 = /^[0-9a-f]{64}$/; +const SAFE_FILE = /^[A-Za-z0-9._-]+$/; + +/** Checks the shape of latest.json and that every URL is on storebound.dev over HTTPS. Returns the problems. */ +export function manifestProblems(m: unknown): string[] { + const out: string[] = []; + const isObj = (x: unknown): x is Record => !!x && typeof x === 'object' && !Array.isArray(x); + if (!isObj(m)) return ['latest.json is not an object']; + if (typeof m.version !== 'string' || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(m.version)) out.push('version is not a version number'); + const ours = (u: unknown) => { try { const x = new URL(String(u)); return x.protocol === 'https:' && x.host === 'storebound.dev' && x.pathname.startsWith('/desktop/'); } catch { return false; } }; + if (!isObj(m.platforms)) out.push('platforms is missing'); + else for (const [k, p] of Object.entries(m.platforms)) { + if (!isObj(p) || typeof p.signature !== 'string' || !p.signature || !ours(p.url)) out.push(`platforms.${k}: needs a signature and a storebound.dev URL`); + } + if (m.downloads !== undefined) { + if (!isObj(m.downloads)) out.push('downloads is not an object'); + else for (const [k, d] of Object.entries(m.downloads)) { + if (!(k in DOWNLOAD_LABEL)) { out.push(`downloads.${k}: unknown kind`); continue; } + if (!isObj(d)) { out.push(`downloads.${k}: not an object`); continue; } + if (typeof d.file !== 'string' || !SAFE_FILE.test(d.file)) out.push(`downloads.${k}: bad file name`); + if (!ours(d.url) || typeof d.file !== 'string' || !String(d.url).endsWith(`/${d.file}`)) out.push(`downloads.${k}: URL must be storebound.dev/desktop/.../`); + if (typeof d.sha256 !== 'string' || !SHA256.test(d.sha256)) out.push(`downloads.${k}: sha256`); + if (typeof d.size !== 'number' || !(d.size > 0)) out.push(`downloads.${k}: size`); + if (typeof d.signature !== 'string' || !d.signature) out.push(`downloads.${k}: signature`); + if (typeof d.codeSigned !== 'boolean') out.push(`downloads.${k}: codeSigned`); + } + } + return out; +} + +/** The deep link that makes the app add (after its own dialog) or select an app folder. */ +export function openFolderLink(dir: string): string { + return `storebound://open?path=${encodeURIComponent(dir)}`; +} + +export interface Installed { path: string; how: 'bundle' | 'exe' | 'appimage' | 'deb' } + +/** Where the app is installed on this machine, or null. `exists` and `home` are injectable for tests. */ +export function findInstalled(platform: NodeJS.Platform, env: Record = process.env, + exists: (p: string) => boolean = existsSync, home = homedir(), + list: (dir: string) => string[] = d => { try { return readdirSync(d); } catch { return []; } }): Installed | null { + if (platform === 'darwin') { + for (const dir of ['/Applications', join(home, 'Applications')]) { + const app = join(dir, 'storebound.app'); + if (exists(join(app, 'Contents/MacOS/storebound-desktop'))) return { path: app, how: 'bundle' }; + } + return null; + } + if (platform === 'win32') { + // NSIS per-user install: %LOCALAPPDATA%\storebound\storebound-desktop.exe (all-users: %ProgramFiles%\storebound) + for (const base of [env.LOCALAPPDATA, env.ProgramFiles]) { + if (!base) continue; + const exe = `${base}\\storebound\\storebound-desktop.exe`; + if (exists(exe)) return { path: exe, how: 'exe' }; + } + return null; + } + if (exists('/usr/bin/storebound-desktop')) return { path: '/usr/bin/storebound-desktop', how: 'deb' }; + // an AppImage is wherever its owner put it: look in the usual folders (storebound_0.1.0_amd64.AppImage, renamed ones) + for (const dir of [join(home, 'Applications'), join(home, '.local/bin'), join(home, 'Downloads')]) { + const name = list(dir).filter(n => /^storebound(?:[-_][A-Za-z0-9._-]*)?\.AppImage$/i.test(n)).sort().at(-1); + if (name) return { path: join(dir, name), how: 'appimage' }; + } + return null; +} + +/** The command that opens the installed app (with a deep link, or plain). Never through a shell. */ +export function openCommand(platform: NodeJS.Platform, installed: Installed, link: string | null): string[] { + if (platform === 'darwin') return link ? ['open', '-b', BUNDLE_ID, link] : ['open', '-b', BUNDLE_ID]; + // Windows and Linux: the app takes the link as its argument; a running app gets it through single-instance + return link ? [installed.path, link] : [installed.path]; +} + +export const downloadsDir = (home = homedir()): string => join(home, 'Downloads'); diff --git a/cli/lib/minisign.ts b/cli/lib/minisign.ts new file mode 100644 index 00000000..3296dd28 --- /dev/null +++ b/cli/lib/minisign.ts @@ -0,0 +1,63 @@ +// Minisign signature checks (the format of Tauri's updater signatures, `tauri signer sign`), with node:crypto only. +// A Tauri public key or `.sig` file is the base64 of the minisign text file: +// public key: "untrusted comment: ...\n" + base64("Ed" | key id (8) | Ed25519 public key (32)) +// signature: "untrusted comment: ...\n" + base64(alg (2) | key id (8) | signature (64)) + "\n" +// "trusted comment: ...\n" + base64(global signature (64)) +// alg "ED" signs the BLAKE2b-512 hash of the file (what Tauri writes), "Ed" the file itself. The global signature +// covers the signature and the trusted comment, so the comment (timestamp, file name) cannot be swapped either. +import { createHash, createPublicKey, verify as edVerify } from 'node:crypto'; + +export interface PublicKey { keyId: string; key: Buffer } +export interface Signature { alg: 'Ed' | 'ED'; keyId: string; sig: Buffer; trustedComment: string; globalSig: Buffer } + +const b64 = (s: string): Buffer => { + const t = s.trim(); + if (!/^[A-Za-z0-9+/]+={0,2}$/.test(t)) throw new Error('not base64'); + return Buffer.from(t, 'base64'); +}; + +/** The text of a minisign file, from the file itself or from Tauri's base64 wrapping of it. */ +function text(input: string): string { + const t = input.trim(); + if (t.startsWith('untrusted comment:')) return t; + return b64(t).toString('utf8'); +} + +export function parsePublicKey(input: string): PublicKey { + const lines = text(input).split(/\r?\n/); + if (!lines[0]?.startsWith('untrusted comment:') || !lines[1]) throw new Error('minisign public key: unexpected format'); + const raw = b64(lines[1]); + if (raw.length !== 42 || raw.subarray(0, 2).toString('latin1') !== 'Ed') throw new Error('minisign public key: not an Ed25519 key'); + return { keyId: Buffer.from(raw.subarray(2, 10)).reverse().toString('hex').toUpperCase(), key: raw.subarray(10) }; +} + +export function parseSignature(input: string): Signature { + const lines = text(input).split(/\r?\n/); + if (!lines[0]?.startsWith('untrusted comment:') || !lines[1] || !lines[2]?.startsWith('trusted comment: ') || !lines[3]) { + throw new Error('minisign signature: unexpected format'); + } + const raw = b64(lines[1]); + const alg = raw.subarray(0, 2).toString('latin1'); + if (raw.length !== 74 || (alg !== 'Ed' && alg !== 'ED')) throw new Error('minisign signature: unknown algorithm'); + const globalSig = b64(lines[3]); + if (globalSig.length !== 64) throw new Error('minisign signature: bad global signature'); + return { alg, keyId: Buffer.from(raw.subarray(2, 10)).reverse().toString('hex').toUpperCase(), sig: raw.subarray(10), trustedComment: lines[2].slice('trusted comment: '.length), globalSig }; +} + +function ed25519(key: Buffer) { + return createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: key.toString('base64url') }, format: 'jwk' }); +} + +export type VerifyResult = { ok: true; trustedComment: string } | { ok: false; reason: string }; + +/** Checks `data` against a minisign signature and public key (either may be Tauri's base64 form). */ +export function verify(data: Uint8Array, signature: string, publicKey: string): VerifyResult { + let pk: PublicKey; let s: Signature; + try { pk = parsePublicKey(publicKey); s = parseSignature(signature); } catch (e) { return { ok: false, reason: (e as Error).message }; } + if (pk.keyId !== s.keyId) return { ok: false, reason: `signed with key ${s.keyId}, expected ${pk.keyId}` }; + const key = ed25519(pk.key); + const msg = s.alg === 'ED' ? createHash('blake2b512').update(data).digest() : Buffer.from(data); + if (!edVerify(null, msg, key, s.sig)) return { ok: false, reason: 'the signature does not match the file' }; + if (!edVerify(null, Buffer.concat([s.sig, Buffer.from(s.trustedComment, 'utf8')]), key, s.globalSig)) return { ok: false, reason: 'the trusted comment was changed' }; + return { ok: true, trustedComment: s.trustedComment }; +} diff --git a/docs/desktop-release.md b/docs/desktop-release.md new file mode 100644 index 00000000..ec3df9e9 --- /dev/null +++ b/docs/desktop-release.md @@ -0,0 +1,267 @@ +# Releasing storebound desktop + +How the desktop app (`apps/desktop`) is built, signed, checked and published. For what the app does, see +[desktop.md](desktop.md). + +## Distribution + +- **The desktop app is its own download.** A signed app from storebound.dev/desktop/: + - macOS: a DMG with a universal app (Apple silicon and Intel), macOS 11 or later; + - Windows: an NSIS installer that installs for the current user and brings the WebView2 bootstrapper; + - Linux: an AppImage and a .deb, built on Ubuntu 22.04. +- **It updates itself** with Tauri's updater: storebound.dev/desktop/latest.json, every bundle signed with the + updater key. The app checks the signature before it replaces anything and installs only after the owner clicks + Install in a native dialog (Settings > Updates). +- **It brings its own CLI.** The app bundles the storebound CLI as a sidecar, so it never depends on an npm install. +- **The npm package stays the CLI, the MCP server and the skills.** It contains no Tauri binaries. +- **Bridge: `storebound desktop`.** + - Installed: it opens the app. In an app folder it sends `storebound://open?path=`, and the app selects + that folder, or adds it after a native dialog. + - Not installed: it prints the download for this OS and CPU. + - `--download` saves the installer to ~/Downloads after checking its size, SHA-256 and minisign signature. It never + installs anything. + +## One version + +`desktopVersion` in the root `package.json` is the desktop app's version. The npm package's own `version` belongs +to the CLI and moves on its own. + +- `bun tools/desktop-version.ts` checks the copies: `apps/desktop/package.json`, `tauri.conf.json`, `Cargo.toml` + and the app's entry in `Cargo.lock`. CI runs this check. +- `bun tools/desktop-version.ts --set 0.1.1` writes a new version into all of them. +- `src-tauri/tests/d5.rs` checks the same thing again from the Rust side. + +## Keys and private files (outside every repository) + +`~/.storebound-keys/` (mode 700) on the release Mac holds: + +| file | what | made by | +|---|---|---| +| `updater.key` | minisign private key of the updater (no password; mode 600) | `bunx tauri signer generate -w ~/.storebound-keys/updater.key -p "" --ci` (done once, D5) | +| `updater.key.pub` | its public key; the same text is `plugins.updater.pubkey` in tauri.conf.json and `PUBLIC_KEY` in cli/lib/desktop-dist.ts | the same command | +| `forbidden-terms.txt` | names the privacy scan must never find: one per line (people, accounts, emails, machine names) | the owner | +| `notary.json` | optional: `{"keyId", "issuerId", "keyPath"}` of the App Store Connect API key for notarytool (or the `ASC_*` / `APPLE_API_*` variables) | the owner | + +**Back up `updater.key`** (password manager or an offline copy). If it is lost, installed apps can never update +again: they only accept bundles signed with this key, so everyone would have to reinstall by hand. Never commit +it, never copy it to a runner. The Forgejo workflow builds unsigned installers, and the Mac signs them. + +## Privacy gate + +`bun tools/privacy-scan.ts ` runs on every artifact before it can ship. + +- **Terms it looks for:** + - the terms file; + - this machine's account name, home folder, full name, host and computer names, and git's global identity; + - the private-name rule of tools/scrub.ts; + - any `/Users/`, `/home/` or `C:\Users\` that is not a generic account. +- **How it reads files:** as bytes, in UTF-8 and UTF-16LE. +- **Archives it opens:** DMG (mounted read-only, never shown in Finder), .tar.gz, .deb, .zip, AppImage (unsquashfs + or 7-Zip) and NSIS (7-Zip). +- **Debug files:** .dSYM, .pdb and source maps fail the scan. +- **Exit codes:** 1 when it finds something, 2 when it cannot open an archive. A term is never printed in full. + +**Path-free builds.** `tools/desktop-release.ts` builds with `--remap-path-prefix` and `-ffile-prefix-map`, which +turn home into `~`, the checkout into `/src`, the cargo and rustup homes into `/cargo` and `/rustup`, and +`CARGO_TARGET_DIR` into `/target`. On Windows it also uses `/PDBALTPATH` and `/d1trimfile`. The target folder must +be outside the home folder. Release profile: `strip = true`, LTO, `panic = "abort"`. + +## macOS (on the owner's Mac) + +```sh +bun tools/desktop-release.ts mac --out ~/.storebound-releases/desktop/0.1.0 # from a clean commit +``` + +**Runs in the owner's logged-in macOS session.** It refuses SSH and background sessions: over SSH `codesign` +cannot use the login keychain (errSecInternalComponent). + +What it does, in order: + +1. Checks the session, the version, a clean checkout, the updater key and that the rustup targets are installed. +2. Picks the signing identity: + - **Developer ID Application found** (`security find-identity -v -p codesigning`): hardened runtime with + `src-tauri/entitlements.plist` (JIT for the Bun sidecar), notarization and stapling. Tauri notarizes the app, + the script notarizes the DMG. + - **None found**: an ad-hoc signed build whose files end in `-unsigned`. +3. Builds the sidecars for arm64 and x64, merges them into one universal file with `lipo`, then runs + `tauri build --target universal-apple-darwin --bundles app` with the path-free environment. +4. Makes the updater bundle (`.app.tar.gz`, root-owned entries, no macOS metadata) and the DMG. The DMG is made with + `hdiutil` only (no Finder scripting, nothing comes to the front). +5. **Checks the exact artifacts:** + - `codesign --verify --deep --strict`; + - the Gatekeeper expectation (signed: `spctl` accepts it as Notarized Developer ID and `stapler validate` passes; + unsigned: ad-hoc, and `spctl` rejects it); + - the self-test, run from the mounted DMG and from the unpacked updater bundle, for both CPU types (x86_64 through + Rosetta). `storebound-desktop --self-test` starts the bundled sidecar, sends `session.hello`, prints one JSON + line and exits, before Tauri starts, so no window opens; + - the privacy scan of the app, the DMG and the updater bundle. +6. Writes minisign `.sig` files with the updater key and checks them right away against tauri.conf.json's key. +7. Writes `latest.json`, `SHA256SUMS` and `evidence-macos-.json`. The evidence file (tool versions, checks, + hashes) stays local. + +### Signing identity and notarization key + +1. **Developer ID certificate.** A **Developer ID Application** certificate of your Apple developer team in the login + keychain (the Account Holder creates it at developer.apple.com > Certificates > +, with a CSR from Keychain + Access). It is installed on the release Mac since October 2026. A machine without it still builds, but only the + ad-hoc `-unsigned` preview. +2. **Notarization key.** An App Store Connect API key, found in this order: + - `APPLE_API_KEY`, `APPLE_API_ISSUER` and `APPLE_API_KEY_PATH`; + - storebound's own `ASC_KEY_ID`, `ASC_ISSUER_ID` and `ASC_P8` (a path or the PEM; by default + `~/.appstoreconnect/private_keys/AuthKey_.p8`, where Xcode keeps it); + - `~/.storebound-keys/notary.json`. + + The key ids are never written into the repository. +3. **Build.** Run the command above in Terminal on the Mac. + +**Gates on the exact artifacts.** A signed release stops unless all of these pass: + +- every executable in `Contents/MacOS` (the app and the CLI sidecar, signed inside out by Tauri), and the bundle, is + signed with Developer ID, with the hardened runtime and a secure timestamp; +- no executable carries the App Sandbox entitlement (Mac App Store) or `get-task-allow`; +- `spctl -a -vvv -t exec ` says Notarized Developer ID, and `xcrun stapler validate ` passes for the + built app, the app inside the mounted DMG and the app inside the updater bundle; +- `spctl -a -vvv -t open --context context:primary-signature ` accepts the DMG, and + `xcrun stapler validate ` passes. + +### Opening an unsigned preview (what the downloads page says) + +macOS: copy storebound to Applications and open it. When macOS refuses, open System Settings > Privacy & Security +and choose Open Anyway (once). + +## Windows and Linux (Forgejo Actions) + +`.forgejo/workflows/desktop.yml` runs on a `desktop-v*` tag or by hand (workflow_dispatch; tick "windows" only when +a Windows runner exists). + +- **Linux** (`runs-on: ubuntu-22.04`, a container): AppImage and .deb built with the path-free environment, then: + - self-tests of the extracted AppImage and the unpacked .deb; + - the privacy scan and SHA256SUMS; + - an artifact `storebound-desktop-linux`. + + `WEBKIT_DISABLE_DMABUF_RENDERER=1`: the app sets it itself at start on Linux unless the user set it (some GPU / VM + setups leave the window blank with DMABUF), and the workflow sets it too. +- **Windows** (`runs-on: windows`): an NSIS installer (`installMode: currentUser`, WebView2 `embedBootstrapper`, + unsigned), then: + - a silent per-user install (`/S`), the self-test of the installed exe, a silent uninstall; + - the privacy scan; + - an artifact `storebound-desktop-windows`. + +Then on the Mac: + +```sh +bun tools/desktop-release.ts add --out ~/.storebound-releases/desktop/0.1.0 \ + storebound_0.1.0_amd64.AppImage storebound_0.1.0_amd64.deb storebound_0.1.0_x64-setup.exe +``` + +It scans and signs each file, renames the unsigned Windows installer to `-unsigned`, and updates latest.json +(`windows-x86_64`, `linux-x86_64`) and SHA256SUMS. For the scan, install `squashfs` and `sevenzip` from Homebrew. + +### Runner setup (not done yet) + +Forgejo runs in Docker on the VDS; Actions is off (`[actions] ENABLED = false` in its app.ini). + +1. **Enable Actions in Forgejo.** In `app.ini`, set `[actions] ENABLED = true` and + `DEFAULT_ACTIONS_URL = https://data.forgejo.org`. Restart the forgejo container, then enable Actions in the + repository settings. +2. **Linux runner on the VDS, in Docker.** + - Get a registration token: Site administration > Actions > Runners > Create new runner. + - Register and run: + + ```sh + mkdir -p /srv/forgejo-runner && cd /srv/forgejo-runner + docker run --rm -v $PWD:/data code.forgejo.org/forgejo/runner:6 forgejo-runner generate-config > config.yml + # in config.yml: runner.labels: ["ubuntu-22.04:docker://ghcr.io/catthehacker/ubuntu:act-22.04"], + # runner.capacity: 1, container.network: bridge, no privileged mode, no docker socket in jobs + docker run --rm -it -v $PWD:/data code.forgejo.org/forgejo/runner:6 forgejo-runner register \ + --no-interactive --instance https://git.crt.fyi --token --name vds-linux --labels ubuntu-22.04 + ``` + + - Run it as a service: the `forgejo-runner daemon` container with `/data` and the Docker socket, restart + unless-stopped. + - Jobs run in throwaway containers. The runner never sees a signing key. +3. **Windows runner (later).** The owner has no Windows machine yet. On one (Windows 10/11 x64): + - install Rust (MSVC, with the Visual Studio Build Tools), Bun and 7-Zip; + - run `forgejo-runner register --labels windows:host`, then `forgejo-runner daemon` as a service. + + Until then, Windows waits; the workflow's Windows job only runs when "windows" is ticked. +4. **Windows code signing (later).** Buy a code-signing certificate, then sign the installer before `add` and pass + `--code-signed`. + +## Hosting on storebound.dev + +| URL | served from | how it gets there | +|---|---|---| +| /desktop/ (downloads page) | /var/www/storebound.dev/desktop/index.html | `site/desktop/index.html`, with the site (Jenkins + /usr/local/sbin/storebound-publish) | +| /desktop/latest.json, /desktop/beta/latest.json | /var/www/storebound-desktop/ | storebound-desktop-publish | +| /desktop/dl// | /var/www/storebound-desktop/dl/ | storebound-desktop-publish | + +**Why the binaries live outside the site's document root.** The site's publish script rsyncs `site/` with +`--delete-after`, so anything not in git would vanish on the next site deploy. Binaries are never committed. +Apache maps the three paths with `Include /etc/apache2/storebound-desktop.conf` in the :443 vhost +(`tools/vds/apache-storebound-desktop.conf`): + +- latest.json is sent `no-cache`; +- version folders are sent `immutable`; +- no directory listings. + +**`/usr/local/sbin/storebound-desktop-publish [stable|beta]`** (`tools/vds/storebound-desktop-publish`, +root:root 755) takes `/var/lib/storebound-desktop/incoming//` (root only, mode 700) and checks it: + +- only plain files with plain names; +- SHA256SUMS matches; +- latest.json is that version, and every URL in it names an uploaded file under /desktop/dl//. + +Then it publishes: + +- a new version folder appears at once (temp folder, then rename); +- a later `add` to the same version only adds files, and a published file is never replaced by other bytes; +- latest.json goes in last (temp file, then rename), so apps see a version only when all its files are there. + +It runs nothing from the upload. + +**No sudoers entry is needed today.** The owner's Mac uploads and runs the script as root over SSH. If a CI job +should publish one day, give its user exactly this script, as the existing Jenkins entries do: +` ALL=(root) NOPASSWD: /usr/local/sbin/storebound-desktop-publish`. + +Both files are installed on the VDS (D5). The Apache vhost was backed up to `/root/storebound.dev.conf.bak-*` first. +To reinstall after a change: + +```sh +scp tools/vds/storebound-desktop-publish root@:/usr/local/sbin/storebound-desktop-publish +scp tools/vds/apache-storebound-desktop.conf root@:/etc/apache2/storebound-desktop.conf +ssh root@ 'chmod 755 /usr/local/sbin/storebound-desktop-publish && apache2ctl configtest && systemctl reload apache2' +``` + +## Publish + +Publishing is the owner's call. Every installed app on the channel offers the update as soon as latest.json is +live. + +```sh +export STOREBOUND_PUBLISH_HOST=root@ # the VDS (not the Cloudflare name) +bun tools/desktop-release.ts verify --out ~/.storebound-releases/desktop/0.1.0 +bun tools/desktop-release.ts publish --out ~/.storebound-releases/desktop/0.1.0 # dry run: the plan +bun tools/desktop-release.ts publish --out ~/.storebound-releases/desktop/0.1.0 --yes # upload + publish +``` + +1. **Checks again:** sums, signatures against tauri.conf.json's key, latest.json and the privacy scan. +2. **Uploads:** rsync into the incoming folder (evidence stays local). +3. **Publishes:** runs the publish script. +4. **Confirms:** reads the live latest.json back. + +`--channel beta` publishes to /desktop/beta/latest.json, which apps on the Beta channel read. + +**Rollback.** Tauri updates only to a higher version, so a bad release is replaced by a fixed higher version. Its +files stay where they are, because links and checksums must not change. + +## Going public: checklist + +1. A signed, notarized macOS build from the release commit (the Developer ID certificate is on the Mac). The gates + above must pass. +2. Forgejo Actions enabled, the Linux runner registered, a `desktop-v0.1.0` tag built, `add` of the AppImage and + deb. +3. Windows: a runner, or ship macOS + Linux first. The page and latest.json list only what exists. +4. `publish --yes` to stable. Then open storebound.dev/desktop/ on each OS and run `storebound desktop --download`. +5. An updater round trip: publish 0.1.1 to beta, switch a 0.1.0 install to Beta, Check for updates, Install. +6. Link /desktop/ from the main page, and update README and CHANGELOG. diff --git a/docs/desktop.md b/docs/desktop.md index 98a2bf75..3e486f37 100644 --- a/docs/desktop.md +++ b/docs/desktop.md @@ -129,7 +129,7 @@ host state file (`overrides_set`, every key checked in `workspace.rs`). - Dependencies and the CLI sidecar. - Privacy, with a button that reveals the data folder. - Shortcuts. -- Update channel (placeholder until the updater ships). +- Updates: channel (stable / beta), check and install (D5). - Reset: native confirmation, then the keychain entries and every saved state are removed. ### Writes in the window @@ -189,6 +189,20 @@ Download sources (one click on the Dependencies screen or in the first-run guide - **Progress and cancel** go through the same progress events as sidecar jobs; a cancelled download removes its temporary file. +## Release, updates and the terminal bridge (D5) + +- Releases: [desktop-release.md](desktop-release.md) (version authority, privacy gate, macOS signing and + notarization, Forgejo builds for Linux and Windows, storebound.dev hosting, publish). +- **Updates**: Settings > Updates checks storebound.dev (stable `/desktop/latest.json` or beta + `/desktop/beta/latest.json`) only when asked; Install shows a native dialog, then the updater downloads the bundle, + checks its minisign signature against `plugins.updater.pubkey` and restarts (`update_check`, `update_install`). +- **`storebound://open?path=`** (sent by `storebound desktop` in an app folder): the host accepts + one plain absolute path (`policy::deep_link_open_path`), selects that app folder when it is in the list, otherwise + asks in a native dialog and adds it (`deep-link-folder` event). A folder without a storebound config gets a message, + nothing else. +- **`storebound-desktop --self-test`**: starts the bundled sidecar, checks the `session.hello` handshake, prints one + JSON line and exits, before Tauri starts (no window). The release runs it on the exact artifacts. + ## Develop ```sh diff --git a/package.json b/package.json index 98f1e88b..ab5c831d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "name": "storebound", "version": "0.5.0", + "desktopVersion": "0.1.0", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a Bun CLI, an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", diff --git a/site/desktop/index.html b/site/desktop/index.html new file mode 100644 index 00000000..687abaf4 --- /dev/null +++ b/site/desktop/index.html @@ -0,0 +1,210 @@ + + + + + +storebound desktop · download + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+

Desktop app · preview

+

storebound desktop

+

Every app and game you ship, on Google Play and the App Store, in one window: releases on both stores, catalog parity, listings, crash health, reviews and TestFlight. It drives the same open source storebound CLI, keeps store keys in the system keychain, shows a dry run before every change, and never presses Submit.

+ +
+

Looking up the latest release…

+
+ +
+

Already use the CLI? storebound desktop opens the app in your app folder, or prints the download for your system; storebound desktop --download saves the installer to ~/Downloads after checking its signature (it never installs anything).

+
+
+ +
+
+

All downloads

+

Every system, with checksums

+

The app updates itself from this site: each update is signed, and the app checks the signature before it replaces anything. It asks before installing.

+ + + + +
+
+ +
+
+

Verify

+

Check a download yourself

+
    +
  1. Checksum: shasum -a 256 <file> (macOS, Linux) or Get-FileHash <file> (Windows) must print the SHA-256 above.
  2. +
  3. Signature: every file has a .sig next to it (the app's update key, minisign). With minisign: base64 -d <file>.sig > f.minisig && minisign -Vm <file> -x f.minisig -P <key>, with the public key + RWQqOO/ZeIr3RBmolt/fx108m89QNEUndRTFrucjx0CBMoeFb7/xhrvW
  4. +
  5. Or let the CLI do both: storebound desktop --download.
  6. +
+

The npm package storebound stays the CLI, MCP server and agent skills; it does not contain this app. The app brings its own copy of the CLI.

+
+
+
+ + + + + + diff --git a/tests/desktop-dist.test.ts b/tests/desktop-dist.test.ts new file mode 100644 index 00000000..d228a779 --- /dev/null +++ b/tests/desktop-dist.test.ts @@ -0,0 +1,136 @@ +// `storebound desktop`: minisign checks (Tauri's updater signatures), latest.json, the installer for each system, +// finding the installed app and the deep link it opens. +import { describe, expect, test } from 'bun:test'; +import { createHash, generateKeyPairSync, sign } from 'node:crypto'; +import { mkdtempSync, readFileSync, existsSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { download, pick } from '../cli/desktop'; +import { downloadsFor, findInstalled, type Manifest, manifestProblems, openCommand, openFolderLink, PUBLIC_KEY } from '../cli/lib/desktop-dist'; +import { parsePublicKey, parseSignature, verify } from '../cli/lib/minisign'; + +/** A throwaway minisign key pair in Tauri's base64 form, and a signer like `tauri signer sign`. */ +function keyPair() { + const { publicKey, privateKey } = generateKeyPairSync('ed25519'); + const raw = Buffer.from(publicKey.export({ format: 'jwk' }).x!, 'base64url'); + const id = Buffer.from('0102030405060708', 'hex'); + const pubText = `untrusted comment: minisign public key: ${Buffer.from(id).reverse().toString('hex').toUpperCase()}\n${Buffer.concat([Buffer.from('Ed'), id, raw]).toString('base64')}\n`; + const signer = (data: Uint8Array, alg: 'Ed' | 'ED' = 'ED', comment = 'timestamp:1\tfile:x') => { + const msg = alg === 'ED' ? createHash('blake2b512').update(data).digest() : Buffer.from(data); + const sig = sign(null, msg, privateKey); + const global = sign(null, Buffer.concat([sig, Buffer.from(comment)]), privateKey); + const text = `untrusted comment: signature from tauri secret key\n${Buffer.concat([Buffer.from(alg), id, sig]).toString('base64')}\ntrusted comment: ${comment}\n${global.toString('base64')}\n`; + return Buffer.from(text).toString('base64'); + }; + return { pub: Buffer.from(pubText).toString('base64'), pubText, signer }; +} + +describe('minisign', () => { + const k = keyPair(); + const data = new Uint8Array(Buffer.from('storebound installer bytes')); + test('prehashed (Tauri) and plain signatures verify, in both wrappings', () => { + expect(verify(data, k.signer(data, 'ED'), k.pub)).toEqual({ ok: true, trustedComment: 'timestamp:1\tfile:x' }); + expect(verify(data, k.signer(data, 'Ed'), k.pubText).ok).toBe(true); + expect(parsePublicKey(k.pub).keyId).toBe('0807060504030201'); + expect(parseSignature(k.signer(data)).alg).toBe('ED'); + }); + test('a changed file, comment, key or garbage fails', () => { + const changed = new Uint8Array(data); changed[0] = changed[0]! ^ 1; + expect(verify(changed, k.signer(data), k.pub)).toEqual({ ok: false, reason: 'the signature does not match the file' }); + const sig = Buffer.from(k.signer(data), 'base64').toString().replace('file:x', 'file:y'); + expect(verify(data, Buffer.from(sig).toString('base64'), k.pub)).toEqual({ ok: false, reason: 'the trusted comment was changed' }); + const other = keyPair(); + expect(verify(data, k.signer(data), other.pub).ok).toBe(false); + expect(verify(data, 'not a signature', k.pub).ok).toBe(false); + expect(verify(data, k.signer(data), 'AAAA').ok).toBe(false); + }); + test('the CLI carries the desktop app\'s updater key', () => { + const conf = JSON.parse(readFileSync(join(import.meta.dir, '../apps/desktop/src-tauri/tauri.conf.json'), 'utf8')); + expect(PUBLIC_KEY).toBe(conf.plugins.updater.pubkey); + expect(parsePublicKey(PUBLIC_KEY).keyId).toMatch(/^[0-9A-F]{16}$/); + // the downloads page prints the minisign key line for people who verify by hand + const line = Buffer.from(PUBLIC_KEY, 'base64').toString().split('\n')[1]!; + expect(readFileSync(join(import.meta.dir, '../site/desktop/index.html'), 'utf8')).toContain(`${line}`); + }); +}); + +function manifest(k: ReturnType, data: Uint8Array): Manifest { + const sha256 = createHash('sha256').update(data).digest('hex'); + const file = 'storebound_0.1.0_universal.dmg'; + return { + version: '0.1.0', pub_date: '2026-10-11T00:00:00Z', + platforms: { 'darwin-aarch64': { signature: k.signer(data), url: 'https://storebound.dev/desktop/dl/0.1.0/storebound_0.1.0_universal.app.tar.gz' } }, + downloads: { + 'macos-universal-dmg': { file, url: `https://storebound.dev/desktop/dl/0.1.0/${file}`, sha256, size: data.length, signature: k.signer(data), codeSigned: false }, + 'linux-x86_64-deb': { file: 'storebound_0.1.0_amd64.deb', url: 'https://storebound.dev/desktop/dl/0.1.0/storebound_0.1.0_amd64.deb', sha256, size: data.length, signature: k.signer(data), codeSigned: false }, + }, + }; +} + +describe('latest.json and downloads', () => { + const k = keyPair(); + const data = new Uint8Array(Buffer.from('a'.repeat(1000))); + test('installers per system', () => { + expect(downloadsFor('darwin', 'arm64')).toEqual(['macos-universal-dmg']); + expect(downloadsFor('darwin', 'x64')).toEqual(['macos-universal-dmg']); + expect(downloadsFor('win32', 'x64')).toEqual(['windows-x86_64-nsis']); + expect(downloadsFor('linux', 'x64')).toEqual(['linux-x86_64-appimage', 'linux-x86_64-deb']); + expect(downloadsFor('linux', 'arm64')).toEqual([]); + const m = manifest(k, data); + expect(pick(m, downloadsFor('darwin', 'arm64'))?.[0]).toBe('macos-universal-dmg'); + expect(pick(m, downloadsFor('linux', 'x64'))?.[0]).toBe('linux-x86_64-deb'); + expect(pick(m, downloadsFor('linux', 'x64'), 'appimage')).toBeNull(); + expect(pick(m, downloadsFor('win32', 'x64'))).toBeNull(); + }); + test('only storebound.dev URLs, hashes and signatures pass', () => { + const m = manifest(k, data); + expect(manifestProblems(m)).toEqual([]); + const bad = structuredClone(m) as Manifest; + bad.downloads!['macos-universal-dmg']!.url = 'https://evil.test/desktop/storebound_0.1.0_universal.dmg'; + bad.platforms['darwin-aarch64']!.url = 'http://storebound.dev/desktop/x.tar.gz'; + bad.downloads!['linux-x86_64-deb']!.sha256 = 'abc'; + expect(manifestProblems(bad)).toHaveLength(3); + expect(manifestProblems({ version: 'latest', platforms: {} })).toEqual(['version is not a version number']); + expect(manifestProblems([])).toEqual(['latest.json is not an object']); + }); + test('download keeps the file only when size, SHA-256 and signature match', async () => { + const m = manifest(k, data); + const d = m.downloads!['macos-universal-dmg']!; + const dir = mkdtempSync(join(tmpdir(), 'sb-dl-')); + const serve = (body: Uint8Array) => async () => new Response(Buffer.from(body)); + const out = await download(d, dir, serve(data), k.pub); + expect(readFileSync(out)).toEqual(Buffer.from(data)); + const evil = new Uint8Array(data); evil[3] = evil[3]! ^ 1; + await expect(download({ ...d, file: 'b.dmg' }, dir, serve(evil), k.pub)).rejects.toThrow(/SHA-256/); + const sha = createHash('sha256').update(evil).digest('hex'); + await expect(download({ ...d, file: 'c.dmg', sha256: sha }, dir, serve(evil), k.pub)).rejects.toThrow(/signature/); + await expect(download({ ...d, file: 'e.dmg' }, dir, serve(data.subarray(1)), k.pub)).rejects.toThrow(/bytes/); + await expect(download({ ...d, file: 'f.dmg' }, dir, async () => new Response('', { status: 404 }), k.pub)).rejects.toThrow(/404/); + for (const f of ['b.dmg', 'c.dmg', 'e.dmg', 'f.dmg']) expect(existsSync(join(dir, f))).toBe(false); + }); +}); + +describe('the installed app', () => { + const at = (paths: string[]) => (p: string) => paths.includes(p); + test('found per system', () => { + expect(findInstalled('darwin', {}, at(['/Applications/storebound.app/Contents/MacOS/storebound-desktop']), '/Users/you')) + .toEqual({ path: '/Applications/storebound.app', how: 'bundle' }); + expect(findInstalled('darwin', {}, at(['/Users/you/Applications/storebound.app/Contents/MacOS/storebound-desktop']), '/Users/you')?.path) + .toBe('/Users/you/Applications/storebound.app'); + expect(findInstalled('darwin', {}, at([]), '/Users/you')).toBeNull(); + expect(findInstalled('win32', { LOCALAPPDATA: 'C:\\Users\\you\\AppData\\Local' }, at(['C:\\Users\\you\\AppData\\Local\\storebound\\storebound-desktop.exe']), 'C:\\Users\\you')) + .toEqual({ path: 'C:\\Users\\you\\AppData\\Local\\storebound\\storebound-desktop.exe', how: 'exe' }); + expect(findInstalled('linux', {}, at(['/usr/bin/storebound-desktop']), '/home/you')).toEqual({ path: '/usr/bin/storebound-desktop', how: 'deb' }); + const list = (d: string) => (d === '/home/you/Applications' ? ['notes.txt', 'storebound_0.1.0_amd64.AppImage', 'storebound_0.2.0_amd64.AppImage'] : []); + expect(findInstalled('linux', {}, at([]), '/home/you', list)).toEqual({ path: '/home/you/Applications/storebound_0.2.0_amd64.AppImage', how: 'appimage' }); + expect(findInstalled('linux', {}, at([]), '/home/you', () => ['storeboundish.AppImage'])).toBeNull(); + }); + test('opened with the folder as a deep link, never through a shell', () => { + const link = openFolderLink('/Users/you/games/Demo App & co'); + expect(link).toBe('storebound://open?path=%2FUsers%2Fyou%2Fgames%2FDemo App%20%26%20co'); + expect(new URL(link).searchParams.get('path')).toBe('/Users/you/games/Demo App & co'); + expect(openCommand('darwin', { path: '/Applications/storebound.app', how: 'bundle' }, link)).toEqual(['open', '-b', 'dev.storebound.desktop', link]); + expect(openCommand('darwin', { path: '/Applications/storebound.app', how: 'bundle' }, null)).toEqual(['open', '-b', 'dev.storebound.desktop']); + expect(openCommand('win32', { path: 'C:\\x\\storebound-desktop.exe', how: 'exe' }, link)).toEqual(['C:\\x\\storebound-desktop.exe', link]); + }); +}); diff --git a/tests/desktop-release.test.ts b/tests/desktop-release.test.ts new file mode 100644 index 00000000..4f664e74 --- /dev/null +++ b/tests/desktop-release.test.ts @@ -0,0 +1,88 @@ +// tools/desktop-release.ts and tools/desktop-version.ts: the pure parts of the desktop release pipeline. +import { describe, expect, test } from 'bun:test'; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { artifactName, developerIdIdentity, mergeManifest, pathFreeEnv, releaseUrl, remoteSessionReason, sumsText, uploadable } from '../tools/desktop-release'; +import { COPIES, setVersion, versions } from '../tools/desktop-version'; + +describe('desktop version authority', () => { + test('the repository has one desktop version', () => { + const { version, drift } = versions(); + expect(version).toMatch(/^\d+\.\d+\.\d+$/); + expect(drift).toEqual([]); + }); + test('drift is found and --set fixes every copy', () => { + const root = mkdtempSync(join(tmpdir(), 'sb-ver-')); + for (const c of COPIES) { mkdirSync(join(root, c.file, '..'), { recursive: true }); cpSync(join(import.meta.dir, '..', c.file), join(root, c.file)); } + const conf = join(root, 'apps/desktop/src-tauri/tauri.conf.json'); + writeFileSync(conf, readFileSync(conf, 'utf8').replace(/"version": "[^"]+"/, '"version": "9.9.9"')); + expect(versions(root).drift.map(d => d.file)).toEqual(['apps/desktop/src-tauri/tauri.conf.json']); + setVersion('0.2.0-beta.1', root); + expect(versions(root)).toEqual({ version: '0.2.0-beta.1', drift: [] }); + // only the package's own version line of Cargo.toml / Cargo.lock changes + expect(readFileSync(join(root, 'apps/desktop/src-tauri/Cargo.toml'), 'utf8')).toContain('tauri = { version = "2.12"'); + expect(() => setVersion('latest', root)).toThrow(); + }); +}); + +describe('desktop release', () => { + test('signing refuses SSH and non-GUI sessions', () => { + expect(remoteSessionReason({}, 'Aqua')).toBeNull(); + expect(remoteSessionReason({ SSH_CONNECTION: '1 2 3 4' }, 'Aqua')).toMatch(/SSH/); + expect(remoteSessionReason({ SSH_TTY: '/dev/ttys001' }, 'Aqua')).toMatch(/SSH/); + expect(remoteSessionReason({}, 'Background')).toMatch(/GUI session/); + }); + test('only a Developer ID Application identity signs a release', () => { + const out = ` 1) ${'A'.repeat(40)} "Apple Distribution: Example Studio (TEAM000001)" + 2) ${'B'.repeat(40)} "Apple Development: Example Person (TEAM000002)" + 2 valid identities found`; + expect(developerIdIdentity(out)).toBeNull(); + expect(developerIdIdentity(`${out}\n 3) ${'C'.repeat(40)} "Developer ID Application: Example Studio (TEAM000001)"`)).toBe('Developer ID Application: Example Studio (TEAM000001)'); + }); + test('artifact names say when a build is unsigned', () => { + expect(artifactName('0.1.0', 'dmg', false)).toBe('storebound_0.1.0_universal-unsigned.dmg'); + expect(artifactName('0.1.0', 'updater', true)).toBe('storebound_0.1.0_universal.app.tar.gz'); + expect(artifactName('0.1.0', 'nsis', false)).toBe('storebound_0.1.0_x64-setup-unsigned.exe'); + expect(artifactName('0.1.0', 'appimage', false)).toBe('storebound_0.1.0_amd64.AppImage'); + expect(releaseUrl('0.1.0', 'a.dmg')).toBe('https://storebound.dev/desktop/dl/0.1.0/a.dmg'); + }); + test('path-free build: home, checkout, cargo, rustup and target dir are remapped, general first', () => { + const env = pathFreeEnv('/Users/you/src/storebound', { CARGO_TARGET_DIR: '/tmp/t', RUSTFLAGS: '-Cforce-frame-pointers=yes', CFLAGS: '-O2' }, '/Users/you'); + const flags = env.CARGO_ENCODED_RUSTFLAGS!.split('\x1f'); + expect(flags).toEqual([ + '-Cforce-frame-pointers=yes', + '--remap-path-prefix=/Users/you=~', + '--remap-path-prefix=/Users/you/src/storebound=/src', + '--remap-path-prefix=/tmp/t=/target', + '--remap-path-prefix=/Users/you/.cargo=/cargo', + '--remap-path-prefix=/Users/you/.rustup=/rustup', + ]); + expect(env.CFLAGS).toStartWith('-O2 -ffile-prefix-map=/Users/you=~'); + expect(env.CXXFLAGS).toContain('-ffile-prefix-map=/Users/you/.rustup=/rustup'); + const w = pathFreeEnv('C:\\src\\storebound', { CARGO_TARGET_DIR: 'C:\\t' }, 'C:\\Users\\you', 'win32'); + const wf = w.CARGO_ENCODED_RUSTFLAGS!.split('\x1f'); + expect(wf).toContain('--remap-path-prefix=C:\\Users\\you=~'); + expect(wf).toContain('--remap-path-prefix=\\\\?\\C:\\Users\\you=~'); + expect(wf).toContain('-Clink-arg=/PDBALTPATH:%_PDB%'); + expect(w.CL).toContain('"/d1trimfile:C:\\Users\\you\\.rustup/"'); + expect(w.LINK).toBe('/PDBALTPATH:%_PDB%'); + expect(w.CFLAGS).toBeUndefined(); + }); + test('latest.json keeps the other platforms of the same version, a new version starts fresh', () => { + const mac = { platforms: { 'darwin-aarch64': { signature: 's', url: 'https://storebound.dev/desktop/dl/0.1.0/m.app.tar.gz' } } }; + const win = { platforms: { 'windows-x86_64': { signature: 'w', url: 'https://storebound.dev/desktop/dl/0.1.0/w.exe' } } }; + const one = mergeManifest(null, '0.1.0', 'first', '2026-10-11T00:00:00Z', mac); + const two = mergeManifest(one, '0.1.0', 'other notes', '2026-10-12T00:00:00Z', win); + expect(Object.keys(two.platforms)).toEqual(['darwin-aarch64', 'windows-x86_64']); + expect(two.notes).toBe('first'); + expect(two.pub_date).toBe('2026-10-12T00:00:00Z'); + expect(Object.keys(mergeManifest(two, '0.1.1', 'n', 'x', win).platforms)).toEqual(['windows-x86_64']); + }); + test('SHA256SUMS and what is uploaded', () => { + expect(sumsText([{ file: 'b', sha256: '2' }, { file: 'a', sha256: '1' }])).toBe('1 a\n2 b\n'); + expect(uploadable('storebound_0.1.0_universal-unsigned.dmg')).toBe(true); + expect(uploadable('latest.json')).toBe(true); + for (const n of ['evidence-macos-0.1.0.json', '.DS_Store', 'latest.json.part', 'a b.dmg']) expect(uploadable(n)).toBe(false); + }); +}); diff --git a/tests/privacy-scan.test.ts b/tests/privacy-scan.test.ts new file mode 100644 index 00000000..5611df52 --- /dev/null +++ b/tests/privacy-scan.test.ts @@ -0,0 +1,67 @@ +// tools/privacy-scan.ts: the release gate over every desktop artifact. Made-up terms only (the real ones live in a +// file outside the repository). +import { describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { collectTerms, kindOf, mask, parseTerms, scan, scanBuffer, type Term } from '../tools/privacy-scan'; + +const T: Term[] = [{ text: 'Quillfeather', short: false }, { text: 'qz', short: true }]; +// home folders are put together at run time, so tools/scrub.ts (which forbids them in the repository) passes +const home = (root: string, name: string): string => `${root}${name}`; + +describe('privacy scan', () => { + test('terms: comments and blanks skipped, never printed in full', () => { + expect(parseTerms('# names\nQuillfeather\n\n qz \n')).toEqual(['Quillfeather', 'qz']); + expect(mask('Quillfeather')).toBe('Q***'); + const dir = mkdtempSync(join(tmpdir(), 'sb-terms-')); + writeFileSync(join(dir, 't.txt'), `Quillfeather\nCRT\n${['hi', 'crt.fyi'].join('@')}\n`); + // the release identity is never a forbidden term + expect(collectTerms(join(dir, 't.txt'), false).map(t => t.text)).toEqual(['Quillfeather']); + }); + + test('finds a term in any case, in UTF-8 and UTF-16LE', () => { + const hits = scanBuffer('bin', Buffer.concat([Buffer.from('xx QUILLFEATHER yy'), Buffer.from('built by quillFeather', 'utf16le')]), T); + expect(hits.map(h => h.encoding)).toEqual(['utf8', 'utf16le']); + expect(hits.every(h => h.what === 'term Q***')).toBe(true); + expect(scanBuffer('bin', Buffer.from('nothing to see'), T)).toEqual([]); + }); + + test('a short term counts only in a path', () => { + expect(scanBuffer('bin', Buffer.from('jazz quiz qz-mode'), T)).toEqual([]); + expect(scanBuffer('bin', Buffer.from('/opt/qz/src'), T).some(h => h.what === 'term q***')).toBe(true); + }); + + test('home folders of any account, generic ones allowed', () => { + const hits = scanBuffer('bin', Buffer.from(`${home('/Users/', 'someone')}/work /home/runner/work ${home('C:\\Users\\', 'other')}\\x /Users/you/app /home/$USER`), []); + expect(hits.map(h => h.what)).toEqual(['home folder of an account (s***)', 'home folder of an account (o***)']); + }); + + test('folders, archives and debug files', () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-scan-')); + mkdirSync(join(dir, 'pkg/My.app/Contents'), { recursive: true }); + writeFileSync(join(dir, 'pkg/My.app/Contents/clean.txt'), 'all good'); + writeFileSync(join(dir, 'pkg/My.app/Contents/leak.bin'), Buffer.from(`panic at ${home('/Users/', 'quillfeather')}/src/main.rs`, 'utf8')); + mkdirSync(join(dir, 'pkg/My.app.dSYM')); + expect(spawnSync('tar', ['-czf', join(dir, 'bundle.tar.gz'), '-C', join(dir, 'pkg'), '.']).status).toBe(0); + const r = scan([join(dir, 'bundle.tar.gz')], null, false); + expect(r.errors).toEqual([]); + const shown = r.hits.map(h => `${h.file}: ${h.what}`); + expect(shown.some(s => s.startsWith('bundle.tar.gz!/') && s.includes('leak.bin') && s.includes('home folder'))).toBe(true); + expect(shown.some(s => s.includes('My.app.dSYM: debug file'))).toBe(true); + expect(r.files).toBeGreaterThanOrEqual(3); + const clean = scan([join(dir, 'pkg/My.app/Contents/clean.txt')], null, false); + expect(clean.hits).toEqual([]); + expect(scan([join(dir, 'missing.dmg')], null, false).errors).toHaveLength(1); + }); + + test('container kinds', () => { + expect(kindOf('a/storebound_0.1.0_universal.dmg', new Uint8Array())).toBe('dmg'); + expect(kindOf('storebound_0.1.0_universal.app.tar.gz', new Uint8Array())).toBe('tar'); + expect(kindOf('storebound_0.1.0_amd64.deb', new Uint8Array())).toBe('deb'); + expect(kindOf('storebound_0.1.0_amd64.AppImage', new Uint8Array())).toBe('appimage'); + expect(kindOf('storebound_0.1.0_x64-setup.exe', Buffer.from('MZ....Nullsoft Install System'))).toBe('nsis'); + expect(kindOf('storebound-desktop.exe', Buffer.from('MZ'))).toBe('file'); + }); +}); diff --git a/tools/ci.ts b/tools/ci.ts index b7052900..44da2693 100644 --- a/tools/ci.ts +++ b/tools/ci.ts @@ -10,6 +10,8 @@ const tauri = join(root, 'apps/desktop/src-tauri'); const cargo = process.env.STOREBOUND_CI_RUST === '0' ? null : Bun.which('cargo'); const steps: [string, string[], string?][] = [ ['adapters', ['bun', 'tools/gen-adapters.ts', '--check']], + // one desktop version: package.json desktopVersion = apps/desktop/package.json = tauri.conf.json = Cargo.toml / .lock + ['desktop version', ['bun', 'tools/desktop-version.ts']], ['tests', ['bun', 'test']], ['typecheck', ['bunx', 'tsc', '--noEmit']], ['desktop i18n', ['bun', 'tools/i18n-check.ts']], diff --git a/tools/desktop-release.ts b/tools/desktop-release.ts new file mode 100644 index 00000000..962cee41 --- /dev/null +++ b/tools/desktop-release.ts @@ -0,0 +1,585 @@ +#!/usr/bin/env bun +// Release pipeline of the storebound desktop app. Builds, signs, checks and lays out one version for +// storebound.dev/desktop/; nothing here installs anything, and publishing is a separate, explicit step. +// +// bun tools/desktop-release.ts mac [--out ] [--target-dir ] [--identity ""] +// [--no-notarize] [--notes "..."] [--allow-dirty] +// Universal (Apple silicon + Intel) app, updater bundle (.app.tar.gz) and DMG. With a "Developer ID Application" +// identity in the keychain: hardened runtime, notarization (notarytool, App Store Connect API key) and stapling. +// Without one: an ad-hoc signed build named `-unsigned`, and what the owner has to do. Must run in the owner's +// local GUI session: codesign over SSH fails (the keychain is locked there), so SSH sessions are refused. +// Then, on the exact artifacts: codesign / Gatekeeper expectations, the self-test (sidecar handshake, both CPU +// types) from the mounted DMG and from the unpacked updater bundle, the privacy scan, minisign signatures with +// the updater key (~/.storebound-keys/updater.key), SHA256SUMS, latest.json and evidence.json. +// bun tools/desktop-release.ts add --out [--code-signed] +// Adds Windows / Linux installers built by the Forgejo workflow (.forgejo/workflows/desktop.yml) to the version +// folder: privacy scan, minisign signature here (the key never goes to a runner), latest.json, SHA256SUMS. +// bun tools/desktop-release.ts publish --out --host [--channel stable|beta] [--yes] +// Checks the folder again, uploads it to the server's incoming folder (rsync) and runs the root-owned publish +// script there (tmp -> mv, latest.json last). Without --yes it only prints the plan (dry run). +// bun tools/desktop-release.ts verify --out +// The checks of publish without uploading. +// bun tools/desktop-release.ts exec -- +// Runs a build command (tauri build on a runner) with the path-free environment described at pathFreeEnv. +// +// Version: package.json "desktopVersion" (bun tools/desktop-version.ts). Docs: docs/desktop-release.md. +import { spawnSync, type SpawnSyncOptions } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; +import { homedir, release as osRelease, tmpdir } from 'node:os'; +import { basename, join, resolve } from 'node:path'; +import { type Download, type DownloadKey, type Manifest, manifestProblems } from '../cli/lib/desktop-dist'; +import { verify as verifySig } from '../cli/lib/minisign'; +import { buildOne, OUT_DIR as SIDECAR_DIR } from './build-sidecars'; +import { versions } from './desktop-version'; +import { scan } from './privacy-scan'; + +export const ROOT = resolve(import.meta.dir, '..'); +const APP_DIR = join(ROOT, 'apps/desktop'); +const TAURI_DIR = join(APP_DIR, 'src-tauri'); +export const BASE_URL = 'https://storebound.dev/desktop'; +export const KEYS_DIR = process.env.STOREBOUND_KEYS_DIR ?? join(homedir(), '.storebound-keys'); +const PRODUCT = 'storebound'; +const APP_NAME = 'storebound.app'; +const MAIN_BIN = 'storebound-desktop'; +/** Where the server takes uploads and the root-owned script that publishes them (tools/vds/). */ +export const REMOTE_INCOMING = '/var/lib/storebound-desktop/incoming'; +export const REMOTE_PUBLISH = '/usr/local/sbin/storebound-desktop-publish'; + +// --------------------------------------------------------------------------------------------------------------------- +// Pure parts (tests/desktop-release.test.ts) + +/** Why this session cannot sign (null = a local session). codesign needs the unlocked login keychain of the GUI + * session; over SSH it stops at errSecInternalComponent. */ +export function remoteSessionReason(env: Record, managerName: string): string | null { + if (env.SSH_CONNECTION || env.SSH_CLIENT || env.SSH_TTY) return 'this is an SSH session'; + if (managerName && managerName !== 'Aqua') return `this is not the logged-in GUI session (launchctl manager: ${managerName})`; + return null; +} + +/** The first "Developer ID Application" identity of `security find-identity -v -p codesigning`. */ +export function developerIdIdentity(securityOutput: string): string | null { + const m = /^\s*\d+\)\s+[0-9A-F]{40}\s+"(Developer ID Application: [^"]+)"/m.exec(securityOutput); + return m?.[1] ?? null; +} + +/** File names of a version. Unsigned (no Developer ID / Authenticode) builds say so in the name. */ +export function artifactName(version: string, kind: 'dmg' | 'updater' | 'nsis' | 'appimage' | 'deb', codeSigned: boolean): string { + const u = codeSigned ? '' : '-unsigned'; + switch (kind) { + case 'dmg': return `${PRODUCT}_${version}_universal${u}.dmg`; + case 'updater': return `${PRODUCT}_${version}_universal${u}.app.tar.gz`; + case 'nsis': return `${PRODUCT}_${version}_x64-setup${u}.exe`; + case 'appimage': return `${PRODUCT}_${version}_amd64.AppImage`; + case 'deb': return `${PRODUCT}_${version}_amd64.deb`; + } +} + +export const releaseUrl = (version: string, file: string): string => `${BASE_URL}/dl/${version}/${file}`; + +/** + * Environment of a build whose binaries hold no build-machine path: rustc's --remap-path-prefix (and + * -ffile-prefix-map for C compiled by build scripts) turn the home folder, the checkout, CARGO_HOME, RUSTUP_HOME and + * CARGO_TARGET_DIR into ~, /src, /cargo, /rustup and /target. General roots first: rustc applies the last match. + */ +export function pathFreeEnv(root: string, env: Record, home = homedir(), platform: NodeJS.Platform = process.platform): Record { + const win = platform === 'win32'; + const sep = win ? '\\' : '/'; + const trim = (p: string) => (win ? p.replace(/[\\/]+$/, '') : p.replace(/\/+$/, '') || '/'); + const at = (...parts: string[]) => parts.join(sep); + const roots: [string | undefined, string][] = [ + [home, '~'], + [root, '/src'], + [env.CARGO_TARGET_DIR && (win ? env.CARGO_TARGET_DIR : resolve(env.CARGO_TARGET_DIR)), '/target'], + [env.CARGO_HOME ?? at(home, '.cargo'), '/cargo'], + [env.RUSTUP_HOME ?? at(home, '.rustup'), '/rustup'], + ]; + const maps: [string, string][] = []; + for (const [f, t] of roots) { + if (!f) continue; + maps.push([trim(f), t]); + // Windows hands some paths out in verbatim form (canonicalized by build scripts and cargo) + if (win && /^[A-Za-z]:/.test(f)) maps.push([`\\\\?\\${trim(f)}`, t]); + } + const SEP = '\x1f'; + const flags = env.CARGO_ENCODED_RUSTFLAGS ? env.CARGO_ENCODED_RUSTFLAGS.split(SEP) : (env.RUSTFLAGS ?? '').split(/\s+/).filter(Boolean); + const add = (fl: string) => { if (!flags.includes(fl)) flags.push(fl); }; + for (const [f, t] of maps) add(`--remap-path-prefix=${f}=${t}`); + const out: Record = {}; + if (win) { + // MSVC: the PDB is named without its folder, and cl.exe cuts the roots off __FILE__ (longest root first) + add('-Clink-arg=/PDBALTPATH:%_PDB%'); + const trims = roots.map(r => r[0]).filter((f): f is string => !!f && !f.includes('"')).map(trim).sort((a, b) => b.length - a.length).map(f => `"/d1trimfile:${f}/"`); + out.CL = [...new Set([env.CL, ...trims].filter(Boolean))].join(' '); + out.LINK = [...new Set([env.LINK, '/PDBALTPATH:%_PDB%'].filter(Boolean))].join(' '); + } else { + const prefix = maps.filter(([f]) => !/\s/.test(f)).map(([f, t]) => `-ffile-prefix-map=${f}=${t}`); + for (const n of ['CFLAGS', 'CXXFLAGS']) out[n] = [...(env[n] ?? '').split(/\s+/).filter(Boolean), ...prefix].join(' '); + } + out.CARGO_ENCODED_RUSTFLAGS = flags.join(SEP); + return out; +} + +/** latest.json of a version: an existing one of the same version keeps its other platforms. */ +export function mergeManifest(existing: Manifest | null, version: string, notes: string, now: string, + add: { platforms?: Manifest['platforms']; downloads?: Partial> }): Manifest { + const base: Manifest = existing && existing.version === version ? existing : { version, notes, pub_date: now, platforms: {}, downloads: {} }; + return { + version, + notes: base.notes || notes, + pub_date: now, + platforms: { ...base.platforms, ...add.platforms }, + downloads: { ...base.downloads, ...add.downloads }, + }; +} + +/** `sha256sum -c` format, sorted. */ +export function sumsText(entries: { file: string; sha256: string }[]): string { + return [...entries].sort((a, b) => a.file.localeCompare(b.file)).map(e => `${e.sha256} ${e.file}`).join('\n') + '\n'; +} + +/** Files of a version folder that are uploaded (evidence and temp files stay local). */ +export const uploadable = (name: string): boolean => /^[A-Za-z0-9._-]+$/.test(name) && !name.startsWith('.') && !/^evidence/.test(name) && !name.endsWith('.part'); + +// --------------------------------------------------------------------------------------------------------------------- +// Helpers with side effects + +const t0 = Date.now(); +const say = (msg: string) => console.log(`[${((Date.now() - t0) / 1000).toFixed(0).padStart(4)}s] ${msg}`); +function fail(msg: string): never { console.error(`\ndesktop-release: ${msg}`); process.exit(1); } + +function run(cmd: string[], opts: SpawnSyncOptions & { quiet?: boolean; allowFail?: boolean } = {}): { code: number; out: string; err: string } { + const r = spawnSync(cmd[0]!, cmd.slice(1), { encoding: 'utf8', maxBuffer: 256 << 20, ...opts, stdio: opts.stdio ?? ['ignore', 'pipe', 'pipe'] }); + const res = { code: r.status ?? 1, out: String(r.stdout ?? ''), err: String(r.stderr ?? '') }; + if (res.code !== 0 && !opts.allowFail) fail(`${basename(cmd[0]!)} ${cmd.slice(1, 3).join(' ')} failed (exit ${res.code})\n${res.err.trim().split('\n').slice(-15).join('\n')}`); + return res; +} + +const sha256 = (file: string) => createHash('sha256').update(readFileSync(file)).digest('hex'); +const mb = (n: number) => `${(n / 1e6).toFixed(1)} MB`; +const confPubkey = (): string => JSON.parse(readFileSync(join(TAURI_DIR, 'tauri.conf.json'), 'utf8')).plugins.updater.pubkey; + +function updaterKey(): string { + const key = process.env.STOREBOUND_UPDATER_KEY ?? join(KEYS_DIR, 'updater.key'); + if (!existsSync(key)) fail(`no updater signing key at ${key.replace(homedir(), '~')}: see docs/desktop-release.md (bunx tauri signer generate)`); + const pub = `${key}.pub`; + if (existsSync(pub) && readFileSync(pub, 'utf8').trim() !== confPubkey()) fail(`${basename(pub)} is not the public key in tauri.conf.json: the app would refuse these updates`); + return key; +} + +/** minisign signature with the updater key (tauri signer), checked right away against tauri.conf.json's key. */ +function signFile(file: string): string { + const key = updaterKey(); + rmSync(`${file}.sig`, { force: true }); + run(['bunx', 'tauri', 'signer', 'sign', '-f', key, '-p', '', file], { cwd: APP_DIR, env: { ...process.env, TAURI_SIGNING_PRIVATE_KEY_PASSWORD: '' } }); + const sig = readFileSync(`${file}.sig`, 'utf8').trim(); + const v = verifySig(readFileSync(file), sig, confPubkey()); + if (!v.ok) fail(`${basename(file)}: fresh signature does not verify (${v.reason})`); + return sig; +} + +function privacyGate(paths: string[]): { files: number; bytes: number; hits: number } { + const r = scan(paths); + for (const h of r.hits) console.error(`privacy: ${h.file} @${h.offset}${h.encoding ? ` (${h.encoding})` : ''}: ${h.what}`); + for (const e of r.errors) console.error(`privacy: could not open ${e}`); + if (r.hits.length || r.errors.length) fail(`privacy scan failed (${r.hits.length} hits, ${r.errors.length} errors): nothing may ship`); + say(`privacy scan clean: ${r.files} files, ${mb(r.bytes)}, ${r.terms} terms${r.termsFile ? '' : ' (no forbidden-terms file: only this machine\'s names)'}`); + return { files: r.files, bytes: r.bytes, hits: 0 }; +} + +function readManifest(out: string): Manifest | null { + const p = join(out, 'latest.json'); + return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) as Manifest : null; +} + +function writeVersionFiles(out: string, manifest: Manifest): void { + const problems = manifestProblems(manifest); + if (problems.length) fail(`latest.json: ${problems.join('; ')}`); + writeFileSync(join(out, 'latest.json.part'), `${JSON.stringify(manifest, null, 2)}\n`); + renameSync(join(out, 'latest.json.part'), join(out, 'latest.json')); + const files = readdirSync(out).filter(n => uploadable(n) && n !== 'SHA256SUMS'); + writeFileSync(join(out, 'SHA256SUMS'), sumsText(files.map(file => ({ file, sha256: sha256(join(out, file)) })))); +} + +function gitState(): { commit: string; dirty: boolean } { + const commit = run(['git', 'rev-parse', 'HEAD'], { cwd: ROOT }).out.trim(); + const dirty = run(['git', 'status', '--porcelain'], { cwd: ROOT }).out.trim().length > 0; + return { commit, dirty }; +} + +function args(argv: string[]) { + const get = (n: string) => { const i = argv.indexOf(`--${n}`); return i >= 0 ? argv[i + 1] : undefined; }; + return { get, has: (n: string) => argv.includes(`--${n}`), rest: argv.filter((a, i) => !a.startsWith('--') && !(i > 0 && argv[i - 1]!.startsWith('--') && !['--allow-dirty', '--no-notarize', '--yes', '--code-signed'].includes(argv[i - 1]!))) }; +} + +// --------------------------------------------------------------------------------------------------------------------- +// mac + +interface SelfTest { arch: string; result: Record } + +function selfTest(appPath: string, label: string): SelfTest[] { + const bin = join(appPath, 'Contents/MacOS', MAIN_BIN); + const out: SelfTest[] = []; + const arches = run(['lipo', '-archs', bin]).out.trim().split(/\s+/).sort(); + const sideArches = run(['lipo', '-archs', join(appPath, 'Contents/MacOS', PRODUCT)]).out.trim().split(/\s+/).sort(); + if (arches.join(' ') !== 'arm64 x86_64' || sideArches.join(' ') !== 'arm64 x86_64') fail(`${label}: not universal (app ${arches}, sidecar ${sideArches})`); + const rosetta = run(['arch', '-x86_64', '/usr/bin/true'], { allowFail: true }).code === 0; + for (const arch of rosetta ? ['arm64', 'x86_64'] : [process.arch === 'arm64' ? 'arm64' : 'x86_64']) { + const r = run(['arch', `-${arch}`, bin, '--self-test'], { allowFail: true, timeout: 90_000 }); + if (r.code !== 0) fail(`${label}: self-test (${arch}) failed: ${r.err.trim() || r.out.trim()}`); + const result = JSON.parse(r.out.trim().split('\n').at(-1)!) as Record; + if (result.ok !== true || result.protocol !== 'storebound-desktop/1') fail(`${label}: self-test (${arch}) answered ${r.out}`); + say(`self-test ${label} (${arch}): sidecar ${result.sidecar}, ${result.methods} methods, ${result.ms} ms`); + out.push({ arch, result }); + } + if (!rosetta) say('self-test: Rosetta is not installed, x86_64 slice not run (softwareupdate --install-rosetta to cover it)'); + return out; +} + +export interface Gate { codesign: string; spctl: string; stapler: string; binaries: string[] } + +/** Signature checks of one app, inside out: every executable in Contents/MacOS (the app and the CLI sidecar), then the + * bundle. Signed: Developer ID, hardened runtime, a secure timestamp, no sandbox entitlement (Developer ID, not the + * Mac App Store), Gatekeeper accepts it as notarized and the ticket is stapled. Unsigned: ad-hoc, Gatekeeper rejects. */ +function gatekeeper(appPath: string, signed: boolean, notarized: boolean, label: string): Gate { + run(['codesign', '--verify', '--deep', '--strict', '--verbose=2', appPath]); + const binaries: string[] = []; + const macos = join(appPath, 'Contents/MacOS'); + for (const name of [...readdirSync(macos).sort(), '']) { + const target = name ? join(macos, name) : appPath; + const info = run(['codesign', '-dvv', '--verbose=4', target]).err; + const flags = /flags=0x[0-9a-f]+\(([^)]*)\)/.exec(info)?.[1] ?? ''; + const authority = /Authority=(Developer ID Application[^\n]*)/.exec(info)?.[1]; + const ents = run(['codesign', '-d', '--entitlements', '-', '--xml', target], { allowFail: true }).out; + const what = name || APP_NAME; + if (signed) { + if (!authority) fail(`${label}: ${what} is not signed with Developer ID`); + if (!/runtime/.test(flags)) fail(`${label}: ${what} has no hardened runtime`); + if (!/Timestamp=/.test(info)) fail(`${label}: ${what} has no secure timestamp`); + if (/com\.apple\.security\.app-sandbox/.test(ents)) fail(`${label}: ${what} carries the App Sandbox entitlement (Mac App Store), not for Developer ID`); + if (/get-task-allow/.test(ents)) fail(`${label}: ${what} is debuggable (get-task-allow)`); + } else if (!/Signature=adhoc/.test(info)) fail(`${label}: unsigned build should be ad-hoc signed (${what})`); + binaries.push(`${what}: ${signed ? 'Developer ID' : 'ad-hoc'}, flags ${flags || 'none'}${/Timestamp=/.test(info) ? ', timestamped' : ''}${/allow-jit/.test(ents) ? ', JIT entitlement' : ''}`); + } + const sp = run(['spctl', '-a', '-vvv', '-t', 'exec', appPath], { allowFail: true }); + const spOut = (sp.err || sp.out).trim(); + const spctl = `${sp.code === 0 ? 'accepted' : 'rejected'}: ${spOut.split('\n').slice(1, 3).join(' / ')}`; + let stapler = 'not stapled (unsigned)'; + if (notarized) { + if (sp.code !== 0 || !/source=Notarized Developer ID/.test(spOut)) fail(`${label}: Gatekeeper does not accept the app as notarized: ${spctl}`); + const st = run(['xcrun', 'stapler', 'validate', appPath], { allowFail: true }); + if (st.code !== 0) fail(`${label}: stapler validate failed: ${(st.out + st.err).trim()}`); + stapler = 'ticket stapled, validated'; + } else if (signed) { + stapler = 'signed, not notarized (--no-notarize)'; + } else if (sp.code === 0) { + fail(`${label}: Gatekeeper accepted an ad-hoc build: unexpected`); + } + const codesign = signed ? 'Developer ID Application, hardened runtime, timestamped' : 'ad-hoc'; + say(`${label}: codesign ${codesign}; spctl -t exec ${spctl}; ${stapler}`); + return { codesign, spctl, stapler, binaries }; +} + +/** notarytool / Tauri credentials: APPLE_API_KEY + APPLE_API_ISSUER + APPLE_API_KEY_PATH, or storebound's own + * ASC_KEY_ID + ASC_ISSUER_ID + ASC_P8 (path or PEM; default ~/.appstoreconnect/private_keys/AuthKey_.p8), or + * ~/.storebound-keys/notary.json {keyId, issuerId, keyPath}. Nothing of it is printed. */ +function notaryEnv(): Record | null { + const env = process.env; + const fromJson = (() => { + const f = join(KEYS_DIR, 'notary.json'); + if (!existsSync(f)) return {} as { keyId?: string; issuerId?: string; keyPath?: string }; + return JSON.parse(readFileSync(f, 'utf8')) as { keyId?: string; issuerId?: string; keyPath?: string }; + })(); + const id = env.APPLE_API_KEY ?? env.ASC_KEY_ID ?? fromJson.keyId; + const issuer = env.APPLE_API_ISSUER ?? env.ASC_ISSUER_ID ?? fromJson.issuerId; + if (!id || !issuer) return null; + let path = env.APPLE_API_KEY_PATH ?? env.ASC_P8 ?? fromJson.keyPath ?? join(homedir(), '.appstoreconnect/private_keys', `AuthKey_${id}.p8`); + if (/BEGIN PRIVATE KEY/.test(path)) { + const dir = mkdtempSync(join(tmpdir(), 'sb-notary-')); + writeFileSync(join(dir, `AuthKey_${id}.p8`), path, { mode: 0o600 }); + path = join(dir, `AuthKey_${id}.p8`); + } + path = path.replace(/^~(?=\/)/, homedir()); + if (!existsSync(path)) fail(`notarization key file not found (${basename(path)}): set ASC_P8 or APPLE_API_KEY_PATH`); + return { APPLE_API_KEY: id, APPLE_API_ISSUER: issuer, APPLE_API_KEY_PATH: path }; +} + +async function mac(argv: string[]): Promise { + const a = args(argv); + if (process.platform !== 'darwin') fail('the macOS build runs on a Mac'); + const remote = remoteSessionReason(process.env, run(['launchctl', 'managername'], { allowFail: true }).out.trim()); + if (remote) fail(`${remote}. Signing and notarization must run in the owner's logged-in macOS session (Terminal on the Mac itself): codesign over SSH fails with errSecInternalComponent.`); + const { version, drift } = versions(); + if (!version || drift.length) fail(`desktop version drift: ${drift.map(d => d.file).join(', ')} (bun tools/desktop-version.ts)`); + const git = gitState(); + if (git.dirty && !a.has('allow-dirty')) fail('the checkout has uncommitted changes: a release is built from a commit (--allow-dirty for a test build)'); + updaterKey(); + + const securityOut = run(['security', 'find-identity', '-v', '-p', 'codesigning']).out; + const identity = a.get('identity') ?? developerIdIdentity(securityOut); + if (a.get('identity') && !securityOut.includes(`"${a.get('identity')}"`)) fail(`identity not in the keychain: ${a.get('identity')}`); + const signed = !!identity; + const notary = signed && !a.has('no-notarize') ? notaryEnv() : null; + if (signed && !a.has('no-notarize') && !notary) fail('Developer ID found but no notarization key: set ASC_KEY_ID + ASC_ISSUER_ID (+ ASC_P8), APPLE_API_KEY + APPLE_API_ISSUER + APPLE_API_KEY_PATH, or ~/.storebound-keys/notary.json (docs/desktop-release.md), or pass --no-notarize for a local test'); + const notarized = signed && !!notary; + say(`storebound desktop ${version} for macOS (universal), commit ${git.commit.slice(0, 10)}${git.dirty ? ' + uncommitted changes' : ''}: ${signed ? `signing as Developer ID${notarized ? ', notarized' : ' (not notarized)'}` : 'NO Developer ID Application identity in the keychain: ad-hoc signed preview, named -unsigned'}`); + + const out = resolve(a.get('out') ?? join(homedir(), '.storebound-releases', 'desktop', version)); + mkdirSync(resolve(a.get('target-dir') ?? '/tmp/storebound-desktop-target'), { recursive: true }); + const targetDir = realpathSync(resolve(a.get('target-dir') ?? '/tmp/storebound-desktop-target')); + if (targetDir.startsWith(homedir())) fail('--target-dir must be outside the home folder (build paths end up in binaries)'); + mkdirSync(out, { recursive: true }); + + // toolchain: rustup's (Homebrew's Rust has no x86_64 standard library for the universal build) + const cargoBin = join(homedir(), '.cargo/bin'); + const PATH = `${cargoBin}:${process.env.PATH}`; + const installed = run(['rustup', 'target', 'list', '--installed'], { env: { ...process.env, PATH } }).out; + for (const t of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) if (!installed.includes(t)) fail(`rustup target ${t} missing: rustup target add ${t}`); + + // sidecars: both CPU types, then one universal file (Tauri looks for binaries/storebound-universal-apple-darwin) + say('sidecars: bun build --compile for darwin-arm64 and darwin-x64'); + const arm = await buildOne('bun-darwin-arm64'); + const x64 = await buildOne('bun-darwin-x64'); + const uni = join(SIDECAR_DIR, 'storebound-universal-apple-darwin'); + rmSync(uni, { force: true }); + run(['lipo', '-create', '-output', uni, arm, x64]); + run(['codesign', '--force', '--sign', '-', uni]); + for (const f of [arm, x64, uni]) { + const v = run([f, 'version'], { allowFail: true, timeout: 60_000 }); + if (f !== x64 && v.code !== 0) fail(`${basename(f)} does not run: ${v.err}`); + } + + // the app: tauri build with the path-free environment, CARGO_TARGET_DIR outside home + const env: Record = { ...process.env, PATH, CARGO_TARGET_DIR: targetDir, CI: 'true' }; + delete env.APPLE_API_KEY; delete env.APPLE_API_ISSUER; delete env.APPLE_API_KEY_PATH; delete env.APPLE_SIGNING_IDENTITY; + delete env.APPLE_CERTIFICATE; delete env.APPLE_ID; delete env.APPLE_PASSWORD; delete env.TAURI_SIGNING_PRIVATE_KEY; + Object.assign(env, pathFreeEnv(ROOT, env), notary ?? {}); + const override = { bundle: { macOS: signed ? { signingIdentity: identity, hardenedRuntime: true, entitlements: './entitlements.plist' } : { signingIdentity: '-' } } }; + const overrideFile = join(mkdtempSync(join(tmpdir(), 'sb-release-')), 'override.json'); + writeFileSync(overrideFile, JSON.stringify(override)); + say(`tauri build --target universal-apple-darwin --bundles app (target dir ${targetDir}; this takes a while)`); + const tb = spawnSync('bunx', ['tauri', 'build', '--target', 'universal-apple-darwin', '--bundles', 'app', '--ci', '--config', overrideFile], + { cwd: APP_DIR, env: env as Record, stdio: ['ignore', 'inherit', 'inherit'] }); + if (tb.status !== 0) fail(`tauri build failed (exit ${tb.status})`); + const bundleDir = join(targetDir, 'universal-apple-darwin/release/bundle/macos'); + const app = join(bundleDir, APP_NAME); + if (!existsSync(app)) fail(`no ${APP_NAME} in ${bundleDir}`); + const dsyms = readdirSync(bundleDir).filter(n => n.endsWith('.dSYM')); + if (dsyms.length) fail(`debug symbols next to the app: ${dsyms.join(', ')}`); + + const checks: Record = { app: gatekeeper(app, signed, notarized, 'built app') }; + const tests: Record = { app: selfTest(app, 'built app') }; + + // updater bundle: the app as Tauri's updater expects it (tar.gz, no macOS metadata, root-owned entries) + const updaterName = artifactName(version, 'updater', signed); + const updater = join(out, updaterName); + rmSync(updater, { force: true }); + run(['tar', '--uid', '0', '--gid', '0', '--uname', 'root', '--gname', 'wheel', '--no-mac-metadata', '-czf', updater, '-C', bundleDir, APP_NAME], { env: { ...process.env, COPYFILE_DISABLE: '1' } }); + + // DMG: the app and an Applications link, made with hdiutil only (no Finder scripting, nothing comes to the front) + const dmgName = artifactName(version, 'dmg', signed); + const dmg = join(out, dmgName); + const stage = mkdtempSync(join(tmpdir(), 'sb-dmg-')); + run(['ditto', app, join(stage, APP_NAME)]); + symlinkSync('/Applications', join(stage, 'Applications')); + rmSync(dmg, { force: true }); + say(`DMG ${dmgName}`); + run(['hdiutil', 'create', '-volname', PRODUCT, '-srcfolder', stage, '-fs', 'HFS+', '-format', 'UDZO', '-imagekey', 'zlib-level=9', '-ov', dmg]); + rmSync(stage, { recursive: true, force: true }); + if (signed) { + run(['codesign', '--force', '--sign', identity!, '--timestamp', dmg]); + if (notarized) { + say('notarytool submit (DMG), waiting for Apple'); + const n = run(['xcrun', 'notarytool', 'submit', dmg, '--key', notary!.APPLE_API_KEY_PATH!, '--key-id', notary!.APPLE_API_KEY!, '--issuer', notary!.APPLE_API_ISSUER!, '--wait', '--output-format', 'json'], { allowFail: true, timeout: 3_600_000 }); + const status = (() => { try { return (JSON.parse(n.out) as { status?: string }).status; } catch { return undefined; } })(); + if (status !== 'Accepted') fail(`notarization of the DMG: ${status ?? n.err.trim()}`); + run(['xcrun', 'stapler', 'staple', dmg]); + run(['xcrun', 'stapler', 'validate', dmg]); + } + } + + // the exact artifacts: mount the DMG and unpack the updater bundle, then self-test what is inside + const mnt = mkdtempSync(join(tmpdir(), 'sb-mnt-')); + run(['hdiutil', 'attach', '-readonly', '-nobrowse', '-noautoopen', '-mountpoint', mnt, dmg]); + try { + checks.dmgApp = gatekeeper(join(mnt, APP_NAME), signed, notarized, 'app in the DMG'); + tests.dmg = selfTest(join(mnt, APP_NAME), 'DMG'); + } finally { + run(['hdiutil', 'detach', mnt, '-force'], { allowFail: true }); + } + // the DMG itself, as Gatekeeper sees a downloaded disk image + const dsp = run(['spctl', '-a', '-vvv', '-t', 'open', '--context', 'context:primary-signature', dmg], { allowFail: true }); + const dmgSpctl = `${dsp.code === 0 ? 'accepted' : 'rejected'}: ${(dsp.err || dsp.out).trim().split('\n').slice(1, 3).join(' / ')}`; + let dmgStapler = 'not stapled (unsigned)'; + if (notarized) { + if (dsp.code !== 0 || !/Notarized Developer ID/.test(dsp.err + dsp.out)) fail(`Gatekeeper does not accept the DMG: ${dmgSpctl}`); + const st = run(['xcrun', 'stapler', 'validate', dmg], { allowFail: true }); + if (st.code !== 0) fail(`DMG: stapler validate failed: ${(st.out + st.err).trim()}`); + dmgStapler = 'ticket stapled, validated'; + } + say(`DMG: spctl -t open ${dmgSpctl}; ${dmgStapler}`); + const unpacked = mkdtempSync(join(tmpdir(), 'sb-upd-')); + run(['tar', '-xzf', updater, '-C', unpacked]); + checks.updaterApp = gatekeeper(join(unpacked, APP_NAME), signed, notarized, 'app in the updater bundle'); + tests.updater = selfTest(join(unpacked, APP_NAME), 'updater bundle'); + rmSync(unpacked, { recursive: true, force: true }); + + // privacy: the app folder, the DMG (mounted) and the updater bundle (unpacked) + const privacy = privacyGate([app, dmg, updater]); + + // signatures with the updater key, latest.json, SHA256SUMS + const updaterSig = signFile(updater); + const dmgSig = signFile(dmg); + const notes = a.get('notes') ?? `storebound desktop ${version}`; + const now = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'); + const manifest = mergeManifest(readManifest(out), version, notes, now, { + platforms: { + 'darwin-aarch64': { signature: updaterSig, url: releaseUrl(version, updaterName) }, + 'darwin-x86_64': { signature: updaterSig, url: releaseUrl(version, updaterName) }, + }, + downloads: { 'macos-universal-dmg': { file: dmgName, url: releaseUrl(version, dmgName), sha256: sha256(dmg), size: statSync(dmg).size, signature: dmgSig, codeSigned: notarized } }, + }); + writeVersionFiles(out, manifest); + + const artifacts = [dmg, updater].map(f => ({ file: basename(f), size: statSync(f).size, sha256: sha256(f) })); + const evidence = { + product: 'storebound desktop', version, platform: 'macos-universal', builtAt: now, commit: git.commit, dirty: git.dirty, + signing: signed ? { identity: 'Developer ID Application', notarized, hardenedRuntime: true } : { identity: 'ad-hoc', notarized: false, note: 'no Developer ID Application certificate in the keychain' }, + tools: { + rustc: run(['rustc', '--version'], { env: { ...process.env, PATH } }).out.trim(), bun: Bun.version, + tauri: run(['bunx', 'tauri', '--version'], { cwd: APP_DIR }).out.trim(), macos: run(['sw_vers', '-productVersion']).out.trim(), darwin: osRelease(), + }, + checks: { ...checks, dmg: { spctl: dmgSpctl, stapler: dmgStapler }, selfTest: tests, privacy }, + artifacts, + }; + writeFileSync(join(out, `evidence-macos-${version}.json`), `${JSON.stringify(evidence, null, 2)}\n`); + + console.log(`\nstorebound desktop ${version} for macOS: ${out.replace(homedir(), '~')}`); + for (const x of artifacts) console.log(` ${x.file.padEnd(48)} ${mb(x.size).padStart(9)} ${x.sha256}`); + console.log(' latest.json, SHA256SUMS, *.sig, evidence-macos-*.json (evidence stays local)'); + if (!signed) { + console.log(` +Unsigned preview (ad-hoc). To ship a signed, notarized build: + 1. The Account Holder of the Apple Developer team creates a "Developer ID Application" certificate + (developer.apple.com > Certificates > +; a CSR from Keychain Access on this Mac) and installs it here. + 2. App Store Connect API key for notarytool (Users and Access > Integrations, role Developer): + ~/.storebound-keys/notary.json {"keyId": "...", "issuerId": "...", "keyPath": "~/.storebound-keys/AuthKey_.p8"} + 3. Run this again in Terminal on the Mac (not over SSH).`); + } + console.log(`\nnext: add Windows / Linux (bun tools/desktop-release.ts add --out ${out.replace(homedir(), '~')} ), then publish (docs/desktop-release.md).`); +} + +// --------------------------------------------------------------------------------------------------------------------- +// add (Windows / Linux installers from the Forgejo workflow) + +function add(argv: string[]): void { + const a = args(argv); + const { version, drift } = versions(); + if (!version || drift.length) fail('desktop version drift (bun tools/desktop-version.ts)'); + const out = resolve(a.get('out') ?? join(homedir(), '.storebound-releases', 'desktop', version)); + const files = a.rest.slice(1); + if (!files.length) fail('usage: add --out '); + mkdirSync(out, { recursive: true }); + const codeSigned = a.has('code-signed'); + const platforms: Manifest['platforms'] = {}; + const downloads: Partial> = {}; + const added: string[] = []; + for (const f of files.map(x => resolve(x))) { + const n = basename(f); + if (!n.includes(`_${version}_`)) fail(`${n} is not version ${version}`); + const kind = /-setup\.exe$/i.test(n) ? 'nsis' : /\.AppImage$/.test(n) ? 'appimage' : /\.deb$/.test(n) ? 'deb' : null; + if (!kind) fail(`${n}: expected an NSIS setup .exe, an .AppImage or a .deb`); + const name = artifactName(version, kind, kind === 'nsis' ? codeSigned : true); + const dest = join(out, name); + copyFileSync(f, dest); + added.push(dest); + } + privacyGate(added); + for (const dest of added) { + const name = basename(dest); + const sig = signFile(dest); + const d: Download = { file: name, url: releaseUrl(version, name), sha256: sha256(dest), size: statSync(dest).size, signature: sig, codeSigned: name.endsWith('.exe') ? codeSigned : false }; + if (name.endsWith('.exe')) { downloads['windows-x86_64-nsis'] = d; platforms['windows-x86_64'] = { signature: sig, url: d.url }; } + else if (name.endsWith('.AppImage')) { downloads['linux-x86_64-appimage'] = d; platforms['linux-x86_64'] = { signature: sig, url: d.url }; } + else downloads['linux-x86_64-deb'] = d; + say(`added ${name} (${mb(d.size)})`); + } + const existing = readManifest(out); + writeVersionFiles(out, mergeManifest(existing, version, a.get('notes') ?? existing?.notes ?? `storebound desktop ${version}`, new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'), { platforms, downloads })); + say(`latest.json now has ${Object.keys(readManifest(out)!.platforms).join(', ')}`); +} + +// --------------------------------------------------------------------------------------------------------------------- +// verify / publish + +function verifyFolder(out: string): { manifest: Manifest; files: string[] } { + if (!existsSync(join(out, 'latest.json')) || !existsSync(join(out, 'SHA256SUMS'))) fail(`${out}: no latest.json / SHA256SUMS`); + const manifest = readManifest(out)!; + const problems = manifestProblems(manifest); + if (problems.length) fail(`latest.json: ${problems.join('; ')}`); + const sums = readFileSync(join(out, 'SHA256SUMS'), 'utf8').trim().split('\n').map(l => { const [h, f] = l.split(/\s+/); return { h: h!, f: f! }; }); + for (const { h, f } of sums) if (!existsSync(join(out, f)) || sha256(join(out, f)) !== h) fail(`SHA256SUMS: ${f} does not match`); + const files = readdirSync(out).filter(uploadable); + for (const f of files) if (f !== 'SHA256SUMS' && !sums.some(s => s.f === f)) fail(`${f} is not in SHA256SUMS`); + const pub = confPubkey(); + const check = (url: string, signature: string, what: string) => { + const file = url.split('/').pop()!; + if (!url.startsWith(releaseUrl(manifest.version, ''))) fail(`${what}: ${url} is not in /desktop/dl/${manifest.version}/`); + if (!files.includes(file)) fail(`${what}: ${file} is not in the folder`); + const v = verifySig(readFileSync(join(out, file)), signature, pub); + if (!v.ok) fail(`${what}: ${file}: ${v.reason}`); + }; + for (const [k, p] of Object.entries(manifest.platforms)) check(p.url, p.signature, `platforms.${k}`); + for (const [k, d] of Object.entries(manifest.downloads ?? {})) { + check(d!.url, d!.signature, `downloads.${k}`); + if (sha256(join(out, d!.file)) !== d!.sha256 || statSync(join(out, d!.file)).size !== d!.size) fail(`downloads.${k}: size or SHA-256 differ from the file`); + } + privacyGate(files.filter(f => !/\.(sig|json)$|^SHA256SUMS$/.test(f)).map(f => join(out, f))); + say(`verified ${manifest.version}: ${files.length} files, platforms ${Object.keys(manifest.platforms).join(', ')}, downloads ${Object.keys(manifest.downloads ?? {}).join(', ')}`); + return { manifest, files }; +} + +function publish(argv: string[]): void { + const a = args(argv); + const out = resolve(a.get('out') ?? fail('--out is required')); + const host = a.get('host') ?? process.env.STOREBOUND_PUBLISH_HOST ?? fail('--host (or STOREBOUND_PUBLISH_HOST) is required'); + if (!/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+$/.test(host)) fail(`--host: user@host, got ${host}`); + const channel = a.get('channel') ?? 'stable'; + if (!['stable', 'beta'].includes(channel)) fail('--channel stable or beta'); + const { manifest, files } = verifyFolder(out); + const v = manifest.version; + const unsigned = Object.values(manifest.downloads ?? {}).filter(d => !d!.codeSigned && /\.(dmg|exe)$/.test(d!.file)).map(d => d!.file); + const steps = [ + ['ssh', host, `mkdir -p ${REMOTE_INCOMING}/${v} && chmod 700 ${REMOTE_INCOMING}`], + ['rsync', '-a', '--chmod=F644,D755', '--delete', ...files.map(f => join(out, f)), `${host}:${REMOTE_INCOMING}/${v}/`], + ['ssh', host, `${REMOTE_PUBLISH} ${v} ${channel}`], + ]; + console.log(`\npublish storebound desktop ${v} to the ${channel} channel (${channel === 'stable' ? `${BASE_URL}/latest.json` : `${BASE_URL}/beta/latest.json`}):`); + for (const f of files) console.log(` ${f}`); + if (unsigned.length) console.log(` note: unsigned preview builds (${unsigned.join(', ')}); the downloads page says so.`); + console.log('\nsteps:'); + for (const s of steps) console.log(` ${s[0]} ${s.slice(1).map(x => (x.includes(' ') ? `"${x}"` : x.replace(out, ''))).join(' ')}`); + if (!a.has('yes')) { console.log('\ndry run: nothing uploaded. Every installed app on this channel offers the update once latest.json is live; run again with --yes to publish.'); return; } + for (const s of steps) { say(`${s[0]} ...`); run(s, { stdio: ['ignore', 'inherit', 'inherit'] }); } + const live = spawnSync('curl', ['-fsS', channel === 'stable' ? `${BASE_URL}/latest.json` : `${BASE_URL}/beta/latest.json`], { encoding: 'utf8' }); + if (live.status !== 0 || (JSON.parse(live.stdout) as Manifest).version !== v) fail('latest.json on storebound.dev is not the new version yet'); + say(`live: ${BASE_URL}/ serves ${v}`); +} + +if (import.meta.main) { + const argv = process.argv.slice(2); + const cmd = argv[0]; + if (cmd === 'mac') await mac(argv.slice(1)); + else if (cmd === 'add') add(argv); + else if (cmd === 'verify') verifyFolder(resolve(args(argv).get('out') ?? fail('--out '))); + else if (cmd === 'publish') publish(argv.slice(1)); + else if (cmd === 'exec') { + // `exec -- `: runs a build command with the path-free environment (the Forgejo workflow uses it) + const cmdline = argv.slice(argv.indexOf('--') + 1); + if (argv.indexOf('--') < 0 || !cmdline.length) fail('usage: exec -- '); + const r = spawnSync(cmdline[0]!, cmdline.slice(1), { stdio: 'inherit', env: { ...process.env, ...pathFreeEnv(ROOT, process.env) }, shell: process.platform === 'win32' }); + process.exit(r.status ?? 1); + } + else { console.log(readFileSync(import.meta.path, 'utf8').split('\n').filter(l => l.startsWith('//')).slice(0, 26).map(l => l.slice(3)).join('\n')); process.exit(cmd ? 2 : 0); } +} + diff --git a/tools/desktop-version.ts b/tools/desktop-version.ts new file mode 100644 index 00000000..7513c7af --- /dev/null +++ b/tools/desktop-version.ts @@ -0,0 +1,73 @@ +#!/usr/bin/env bun +// One version for the desktop app. The authority is `desktopVersion` in the root package.json (the npm package's +// own `version` is the CLI's and moves on its own); it is copied into apps/desktop/package.json, +// src-tauri/tauri.conf.json, src-tauri/Cargo.toml and the app's entry in src-tauri/Cargo.lock. +// bun tools/desktop-version.ts check: exit 1 when any copy drifted (CI runs this) +// bun tools/desktop-version.ts --set 0.1.1 write the new version into the authority and every copy +// bun tools/desktop-version.ts --print print the version +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +export const ROOT = join(import.meta.dir, '..'); +const TAURI = 'apps/desktop/src-tauri'; +export const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; + +export interface Copy { file: string; read(text: string): string | null; write(text: string, v: string): string } + +const jsonVersion = (key: string): Pick => ({ + read: t => { const v = (JSON.parse(t) as Record)[key]; return typeof v === 'string' ? v : null; }, + write: (t, v) => t.replace(new RegExp(`("${key}"\\s*:\\s*)"[^"]*"`), `$1"${v}"`), +}); + +/** The authority first, then every copy. */ +export const COPIES: Copy[] = [ + { file: 'package.json', ...jsonVersion('desktopVersion') }, + { file: 'apps/desktop/package.json', ...jsonVersion('version') }, + { file: `${TAURI}/tauri.conf.json`, ...jsonVersion('version') }, + { + file: `${TAURI}/Cargo.toml`, + // the [package] table's version (the first `version =` line of the file, before any dependency table) + read: t => /^\[package\][^[]*?^version\s*=\s*"([^"]+)"/ms.exec(t)?.[1] ?? null, + write: (t, v) => t.replace(/^(\[package\][^[]*?^version\s*=\s*)"[^"]+"/ms, `$1"${v}"`), + }, + { + file: `${TAURI}/Cargo.lock`, + read: t => /^name = "storebound-desktop"\nversion = "([^"]+)"/m.exec(t)?.[1] ?? null, + write: (t, v) => t.replace(/^(name = "storebound-desktop"\nversion = )"[^"]+"/m, `$1"${v}"`), + }, +]; + +export interface Drift { file: string; found: string | null } + +export function versions(root = ROOT): { version: string | null; drift: Drift[] } { + const [authority, ...copies] = COPIES.map(c => ({ file: c.file, found: c.read(readFileSync(join(root, c.file), 'utf8')) })); + const version = authority!.found; + return { version, drift: copies.filter(c => c.found !== version) }; +} + +export function setVersion(v: string, root = ROOT): void { + if (!SEMVER.test(v)) throw new Error(`not a version: ${v}`); + for (const c of COPIES) { + const p = join(root, c.file); + const before = readFileSync(p, 'utf8'); + const after = c.write(before, v); + if (c.read(after) !== v) throw new Error(`could not set the version in ${c.file}`); + if (after !== before) writeFileSync(p, after); + } +} + +if (import.meta.main) { + const argv = process.argv.slice(2); + const i = argv.indexOf('--set'); + if (i >= 0) { + setVersion(argv[i + 1] ?? ''); + console.log(`desktop version ${argv[i + 1]} written to ${COPIES.map(c => c.file).join(', ')}`); + process.exit(0); + } + const { version, drift } = versions(); + if (argv.includes('--print')) { console.log(version ?? ''); process.exit(version ? 0 : 1); } + if (!version || !SEMVER.test(version)) { console.error('desktop version: package.json has no valid "desktopVersion"'); process.exit(1); } + for (const d of drift) console.error(`desktop version drift: ${d.file} has ${d.found ?? 'no version'}, package.json desktopVersion is ${version}`); + if (drift.length) { console.error('fix: bun tools/desktop-version.ts --set ' + version); process.exit(1); } + console.log(`desktop version ${version}: ${COPIES.length - 1} copies match`); +} diff --git a/tools/privacy-scan.ts b/tools/privacy-scan.ts new file mode 100644 index 00000000..c369420f --- /dev/null +++ b/tools/privacy-scan.ts @@ -0,0 +1,246 @@ +#!/usr/bin/env bun +// Release gate: nothing storebound ships may name a person, an account or a machine. Scans files, folders (an .app +// bundle) and archives (DMG, .tar.gz, .deb, .zip, AppImage, NSIS installer) for +// +// - forbidden terms: a file kept OUTSIDE every repository (STOREBOUND_FORBIDDEN_TERMS, else +// ~/.storebound-keys/forbidden-terms.txt; one term per line, # comments), plus what this machine says about its +// owner: account name, home folder, full name (macOS), host and computer names, git's global identity (unless it +// is the release identity), and the private-name rule of tools/scrub.ts; +// - home folders of any account (/Users/, /home/, C:\Users\), generic accounts excepted +// (runner, you, ...), in case a build machine other than this one made a file; +// - debug files that must not ship: .dSYM bundles, .pdb, source maps. +// +// Every file is searched as bytes in UTF-8 and UTF-16LE, ASCII case-insensitively. A term is never printed: a hit +// shows the file (inside its archive), the byte offset and the term as its first letter plus ***. A container that +// cannot be opened is an error, not a pass. +// +// bun tools/privacy-scan.ts [--terms ] [--json] exit 0 clean, 1 hits, 2 could not open +import { spawnSync } from 'node:child_process'; +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'; +import { homedir, hostname, tmpdir, userInfo } from 'node:os'; +import { basename, join, relative } from 'node:path'; +import { RULES } from './scrub'; + +export const TERMS_ENV = 'STOREBOUND_FORBIDDEN_TERMS'; +export const DEFAULT_TERMS = join(homedir(), '.storebound-keys', 'forbidden-terms.txt'); +/** The identity every release commit uses: not personal (the address is put together so scrub's email rule passes). */ +const RELEASE_IDENTITY = new Set(['crt', ['hi', 'crt.fyi'].join('@'), 'crtkafa']); +/** Account names that say nothing about a person (never added automatically, allowed after /Users/ or /home/). */ +export const GENERIC = new Set(['root', 'user', 'users', 'admin', 'administrator', 'runner', 'runneradmin', 'ubuntu', 'build', 'builder', 'ci', + 'docker', 'node', 'vagrant', 'default', 'nobody', 'home', 'dev', 'developer', 'owner', 'guest', 'test', 'app', 'work', 'shared', 'public', + 'you', 'me', 'name', 'example', 'username', 'yourname', 'travis', 'circleci', 'jenkins', 'buildkite', 'vsts', 'cloudtest', 'appveyor', + 'pi', 'ec2-user', 'azureuser', 'vscode', 'codespace', 'gitpod', 'linuxbrew', 'abuild', 'buildbot', 'mockbuild', 'pbuilder', 'portage']); + +export interface Term { text: string; short: boolean } +export interface Hit { file: string; offset: number; what: string; encoding?: string } +export interface Report { files: number; bytes: number; hits: Hit[]; errors: string[] } + +const sh = (cmd: string[]): string => { + const r = spawnSync(cmd[0]!, cmd.slice(1), { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); + return r.status === 0 ? r.stdout.trim() : ''; +}; + +export function parseTerms(text: string): string[] { + return text.split(/\r?\n/).map(l => l.trim()).filter(l => l && !l.startsWith('#')); +} + +/** The terms of the file (if any) plus what this machine says about its owner. */ +export function collectTerms(file: string | null, auto = true): Term[] { + const seen = new Map(); + const add = (t: string, automatic: boolean) => { + const v = t.trim(); + const k = v.toLowerCase(); + if (v.length < 2 || seen.has(k) || RELEASE_IDENTITY.has(k) || (automatic && GENERIC.has(k))) return; + seen.set(k, { text: v, short: v.length <= 3 }); + }; + if (file && existsSync(file)) for (const t of parseTerms(readFileSync(file, 'utf8'))) add(t, false); + if (auto) { + let user = ''; + try { user = userInfo().username; } catch { /* no passwd entry */ } + add(user, true); + add(basename(homedir()), true); + if (homedir().length > 4) add(homedir(), true); + const host = hostname().replace(/\.local$/i, ''); + add(host, true); + if (process.platform === 'darwin') { + add(sh(['scutil', '--get', 'ComputerName']), true); + add(sh(['scutil', '--get', 'LocalHostName']), true); + const real = sh(['id', '-F']); + add(real, true); + for (const part of real.split(/\s+/)) if (part.length >= 4) add(part, true); + } + for (const k of ['user.name', 'user.email']) add(sh(['git', 'config', '--global', k]), true); + } + return [...seen.values()]; +} + +/** The private-name rule of tools/scrub.ts as a plain term (scrub keeps it in parts so no file spells it). */ +function scrubTerms(): Term[] { + const r = RULES.find(x => x.id === 'private-name'); + const src = r?.re.source ?? ''; + return /^[A-Za-z]+$/.test(src) ? [{ text: src, short: false }] : []; +} + +export const mask = (t: string): string => `${t[0]}***`; + +/** ASCII lower-casing on bytes, so one native indexOf finds every case. */ +function lowerAscii(b: Uint8Array): Buffer { + const out = Buffer.from(b); + for (let i = 0; i < out.length; i++) { const c = out[i]!; if (c >= 0x41 && c <= 0x5a) out[i] = c | 0x20; } + return out; +} + +const PATH_BEFORE = /(?:\/users\/|\/home\/|\\users\\|[\\/])$/; +const HOME_RE = /(?:\/Users\/|\/home\/|[A-Za-z]:\\Users\\)([A-Za-z0-9._-]{2,40})/g; + +/** Searches one buffer. `name` is the shown file name. */ +export function scanBuffer(name: string, data: Uint8Array, terms: Term[]): Hit[] { + const hits: Hit[] = []; + const low = lowerAscii(data); + for (const t of terms) { + for (const enc of ['utf8', 'utf16le'] as const) { + const needle = lowerAscii(Buffer.from(t.text, enc)); + let at = low.indexOf(needle); + let n = 0; + while (at >= 0 && n < 5) { + if (!t.short || PATH_BEFORE.test(low.subarray(Math.max(0, at - 8 * (enc === 'utf8' ? 1 : 2)), at).toString('latin1').replace(/\0/g, ''))) { + hits.push({ file: name, offset: at, what: `term ${mask(t.text)}`, encoding: enc }); + n++; + } + at = low.indexOf(needle, at + 1); + } + } + } + // home folders of other accounts (UTF-8 and UTF-16LE read as one latin1 string each) + const views: [string, string][] = [['utf8', Buffer.from(data).toString('latin1')]]; + if (data.length > 1) views.push(['utf16le', Buffer.from(data.buffer, data.byteOffset, data.length - (data.length % 2)).toString('utf16le')]); + for (const [enc, s] of views) { + let n = 0; + for (const m of s.matchAll(HOME_RE)) { + if (GENERIC.has(m[1]!.toLowerCase()) || /^(?:\$|%|<|\{)/.test(m[1]!)) continue; + hits.push({ file: name, offset: enc === 'utf8' ? m.index! : m.index! * 2, what: `home folder of an account (${mask(m[1]!)})`, encoding: enc }); + if (++n >= 5) break; + } + } + return hits; +} + +const FORBIDDEN_FILE = /(?:\.dSYM$|\.pdb$|\.map$)/i; + +type Kind = 'dir' | 'dmg' | 'tar' | 'deb' | 'zip' | 'appimage' | 'nsis' | 'file'; + +export function kindOf(path: string, head: Uint8Array): Kind { + const n = path.toLowerCase(); + if (n.endsWith('.dmg')) return 'dmg'; + if (n.endsWith('.deb')) return 'deb'; + if (/\.(tar\.gz|tgz|tar|tar\.xz|tar\.zst)$/.test(n)) return 'tar'; + if (n.endsWith('.zip') || n.endsWith('.nupkg')) return 'zip'; + if (n.endsWith('.appimage')) return 'appimage'; + if (n.endsWith('.exe') && Buffer.from(head).includes(Buffer.from('Nullsoft'))) return 'nsis'; + return 'file'; +} + +function which(...names: string[]): string | null { + for (const n of names) { const p = Bun.which(n); if (p) return p; } + return null; +} + +/** Unpacks a container into a temp folder; returns the folder (caller removes it) or throws. */ +function unpack(path: string, kind: Kind): { dir: string; cleanup: () => void } { + const dir = mkdtempSync(join(tmpdir(), 'sb-privacy-')); + const cleanup = () => rmSync(dir, { recursive: true, force: true }); + const run = (cmd: string[]) => { + const r = spawnSync(cmd[0]!, cmd.slice(1), { stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' }); + if (r.status !== 0) { cleanup(); throw new Error(`${basename(path)}: ${basename(cmd[0]!)} failed: ${(r.stderr || '').trim().split('\n').at(-1)}`); } + }; + if (kind === 'dmg') { + if (process.platform !== 'darwin') { cleanup(); throw new Error(`${basename(path)}: DMG needs macOS (hdiutil)`); } + const mnt = join(dir, 'mnt'); + run(['hdiutil', 'attach', '-readonly', '-nobrowse', '-noverify', '-noautoopen', '-mountpoint', mnt, path]); + return { dir: mnt, cleanup: () => { spawnSync('hdiutil', ['detach', mnt, '-force'], { stdio: 'ignore' }); cleanup(); } }; + } + if (kind === 'tar' || kind === 'zip' || kind === 'deb') { + // bsdtar (macOS, Windows) reads tar, zip and ar; GNU tar on Linux reads tar, the others go through ar / unzip + if (kind === 'deb' && process.platform === 'linux') { + run(['ar', 'x', '--output', dir, path]); + for (const f of readdirSync(dir)) if (/^(data|control)\.tar/.test(f)) { const sub = join(dir, f.replace(/\..*$/, '')); mkdirSync(sub, { recursive: true }); run(['tar', '-xf', join(dir, f), '-C', sub]); } + return { dir, cleanup }; + } + if (kind === 'zip' && process.platform === 'linux') { run(['unzip', '-q', path, '-d', dir]); return { dir, cleanup }; } + run(['tar', '-xf', path, '-C', dir]); + if (kind === 'deb') for (const f of readdirSync(dir)) if (/^(data|control)\.tar/.test(f)) { const sub = join(dir, f.replace(/\..*$/, '')); mkdirSync(sub, { recursive: true }); run(['tar', '-xf', join(dir, f), '-C', sub]); } + return { dir, cleanup }; + } + if (kind === 'appimage') { + const unsq = which('unsquashfs'); + const data = readFileSync(path); + const off = data.indexOf(Buffer.from('hsqs'), 0x400); + if (unsq && off > 0) { run([unsq, '-q', '-n', '-d', join(dir, 'root'), '-o', String(off), path]); return { dir: join(dir, 'root'), cleanup }; } + const z = which('7zz', '7z'); + if (z) { run([z, 'x', '-y', `-o${dir}`, path]); return { dir, cleanup }; } + cleanup(); throw new Error(`${basename(path)}: AppImage needs unsquashfs (squashfs-tools) or 7-Zip`); + } + if (kind === 'nsis') { + const z = which('7zz', '7z'); + if (!z) { cleanup(); throw new Error(`${basename(path)}: NSIS installer needs 7-Zip (7z / 7zz)`); } + run([z, 'x', '-y', `-o${dir}`, path]); + return { dir, cleanup }; + } + cleanup(); + throw new Error(`${basename(path)}: not a container`); +} + +export function scanPath(path: string, terms: Term[], shown = basename(path), report: Report = { files: 0, bytes: 0, hits: [], errors: [] }): Report { + const st = lstatSync(path); + if (FORBIDDEN_FILE.test(path)) report.hits.push({ file: shown, offset: 0, what: 'debug file that must not ship (.dSYM / .pdb / source map)' }); + if (st.isSymbolicLink()) return report; + if (st.isDirectory()) { + for (const n of readdirSync(path).sort()) scanPath(join(path, n), terms, `${shown}/${n}`, report); + return report; + } + if (!st.isFile()) return report; + const data = readFileSync(path); + report.files++; + report.bytes += data.length; + // the file's own bytes (names, uncompressed parts), then what is inside a container + report.hits.push(...scanBuffer(shown, data, terms)); + const kind = kindOf(path, data.subarray(0, 1 << 20)); + if (kind !== 'file' && kind !== 'dir') { + let u: { dir: string; cleanup: () => void } | null = null; + try { + u = unpack(path, kind); + scanPath(u.dir, terms, `${shown}!`, report); + } catch (e) { + report.errors.push((e as Error).message); + } finally { + u?.cleanup(); + } + } + return report; +} + +export function scan(paths: string[], termsFile: string | null = process.env[TERMS_ENV] ?? DEFAULT_TERMS, auto = true): Report & { terms: number; termsFile: string | null } { + const terms = [...collectTerms(termsFile, auto), ...scrubTerms()]; + const report: Report = { files: 0, bytes: 0, hits: [], errors: [] }; + for (const p of paths) { + if (!existsSync(p)) { report.errors.push(`${p}: does not exist`); continue; } + scanPath(p, terms, basename(p), report); + } + return { ...report, terms: terms.length, termsFile: termsFile && existsSync(termsFile) ? termsFile : null }; +} + +if (import.meta.main) { + const argv = process.argv.slice(2); + const ti = argv.indexOf('--terms'); + const termsFile = ti >= 0 ? argv[ti + 1] ?? null : process.env[TERMS_ENV] ?? DEFAULT_TERMS; + const paths = argv.filter((a, i) => !a.startsWith('--') && !(ti >= 0 && i === ti + 1)); + if (!paths.length) { console.error('usage: bun tools/privacy-scan.ts [--terms ] [--json]'); process.exit(2); } + const r = scan(paths, termsFile); + if (argv.includes('--json')) console.log(JSON.stringify({ ...r, termsFile: r.termsFile ? relative(homedir(), r.termsFile).replace(/^/, '~/') : null }, null, 2)); + else { + for (const h of r.hits) console.error(`privacy: ${h.file} @${h.offset}${h.encoding ? ` (${h.encoding})` : ''}: ${h.what}`); + for (const e of r.errors) console.error(`privacy: could not open ${e}`); + console.log(`privacy-scan: ${r.files} files, ${(r.bytes / 1e6).toFixed(1)} MB, ${r.terms} terms${r.termsFile ? ' (with the terms file)' : ' (no terms file: only this machine\'s names)'}, ${r.hits.length} hits, ${r.errors.length} errors`); + } + process.exit(r.hits.length ? 1 : r.errors.length ? 2 : 0); +} diff --git a/tools/vds/apache-storebound-desktop.conf b/tools/vds/apache-storebound-desktop.conf new file mode 100644 index 00000000..50caf44f --- /dev/null +++ b/tools/vds/apache-storebound-desktop.conf @@ -0,0 +1,25 @@ +# storebound desktop downloads on storebound.dev (included in the :443 vhost of /etc/apache2/sites-available/storebound.dev.conf +# as Include /etc/apache2/storebound-desktop.conf ; see docs/desktop-release.md). +# The page itself (site/desktop/index.html) comes with the site; the binaries and latest.json live outside the site's +# document root, because the site's publish rsync deletes everything that is not in the repository. +Alias /desktop/latest.json /var/www/storebound-desktop/latest.json +Alias /desktop/beta/latest.json /var/www/storebound-desktop/beta/latest.json +Alias /desktop/dl/ /var/www/storebound-desktop/dl/ + + Options -Indexes -FollowSymLinks + AllowOverride None + Require all granted + + ForceType application/octet-stream + Header set Content-Disposition "attachment" + + + + Header set Cache-Control "no-cache" + Header set Access-Control-Allow-Origin "*" + + + # a published file never changes (a new version gets a new folder) + Header set Cache-Control "public, max-age=31536000, immutable" + Header set X-Content-Type-Options "nosniff" + diff --git a/tools/vds/storebound-desktop-publish b/tools/vds/storebound-desktop-publish new file mode 100755 index 00000000..e0a3a6a0 --- /dev/null +++ b/tools/vds/storebound-desktop-publish @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Root-owned publish step for storebound desktop releases (install as /usr/local/sbin/storebound-desktop-publish, +# root:root 755; see docs/desktop-release.md). tools/desktop-release.ts publish uploads one version folder to +# /var/lib/storebound-desktop/incoming// and then runs: storebound-desktop-publish [stable|beta] +# +# It checks the upload (regular files with plain names only, SHA256SUMS, latest.json of that version whose every URL +# points at an uploaded file of /desktop/dl//), copies the files into /var/www/storebound-desktop/dl// +# (a new version: a temp folder renamed into place; an existing version: only new files, a file already published is +# never replaced by different bytes), and only then swaps latest.json of the channel atomically (temp file + rename). +# Apache serves that folder under https://storebound.dev/desktop/ (tools/vds/apache-storebound-desktop.conf), apart +# from the site's own rsync, which deletes what is not in the repository. Nothing from the upload is executed. +set -euo pipefail +umask 022 + +VERSION="${1:-}" +CHANNEL="${2:-stable}" +INCOMING=/var/lib/storebound-desktop/incoming +ROOT=/var/www/storebound-desktop +SITE=https://storebound.dev/desktop + +die() { echo "storebound-desktop-publish: $*" >&2; exit 1; } +[[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || die "usage: storebound-desktop-publish [stable|beta]" +[[ "$CHANNEL" == stable || "$CHANNEL" == beta ]] || die "channel: stable or beta" +IN="$INCOMING/$VERSION" +DL="$ROOT/dl/$VERSION" +[ -d "$IN" ] && [ ! -L "$IN" ] || die "nothing uploaded at $IN" + +# only regular files with plain names, nothing hidden, no folders, no links +if find "$IN" -mindepth 1 \( ! -type f -o -name '.*' \) -print | grep -q .; then die "the upload holds something other than plain files"; fi +if find "$IN" -mindepth 1 -type f -printf '%f\n' | grep -Ev '^[A-Za-z0-9][A-Za-z0-9._-]*$' | grep -q .; then die "a file name has unexpected characters"; fi +[ -f "$IN/latest.json" ] && [ -f "$IN/SHA256SUMS" ] || die "latest.json and SHA256SUMS are required" +(cd "$IN" && sha256sum --quiet --strict -c SHA256SUMS) || die "SHA256SUMS does not match the files" + +python3 - "$IN" "$VERSION" "$SITE" <<'PY' || die "latest.json does not describe this upload" +import json, os, re, sys +src, version, site = sys.argv[1], sys.argv[2], sys.argv[3] +m = json.load(open(os.path.join(src, "latest.json"))) +assert m.get("version") == version, "version" +files = set(os.listdir(src)) +listed = {l.split()[1] for l in open(os.path.join(src, "SHA256SUMS")) if l.strip()} +assert files - {"SHA256SUMS"} <= listed, "files missing from SHA256SUMS" +prefix = f"{site}/dl/{version}/" +entries = list((m.get("platforms") or {}).values()) + list((m.get("downloads") or {}).values()) +assert entries, "no platforms" +for e in entries: + url = e.get("url", "") + assert url.startswith(prefix), url + name = url[len(prefix):] + assert re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", name) and name in files, url + assert e.get("signature"), url +PY + +install -d -m 755 "$ROOT" "$ROOT/dl" "$ROOT/beta" +if [ ! -e "$DL" ]; then + TMP="$(mktemp -d "$ROOT/dl/.tmp-$VERSION.XXXXXX")" + for f in "$IN"/*; do n="$(basename "$f")"; [ "$n" = latest.json ] || install -m 644 "$f" "$TMP/$n"; done + chmod 755 "$TMP" + mv -T "$TMP" "$DL" +else + for f in "$IN"/*; do + n="$(basename "$f")" + [ "$n" = latest.json ] && continue + if [ -e "$DL/$n" ]; then + [ "$n" = SHA256SUMS ] && continue + cmp -s "$f" "$DL/$n" || die "$n is already published with other bytes: a published file is never replaced (bump the version)" + else + install -m 644 "$f" "$DL/.$n.tmp" && mv -f "$DL/.$n.tmp" "$DL/$n" + fi + done + install -m 644 "$IN/SHA256SUMS" "$DL/.SHA256SUMS.tmp" && mv -f "$DL/.SHA256SUMS.tmp" "$DL/SHA256SUMS" +fi + +# latest.json last: installed apps see the new version only once every file it names is in place +if [ "$CHANNEL" = stable ]; then LJ="$ROOT/latest.json"; URL="$SITE/latest.json"; else LJ="$ROOT/beta/latest.json"; URL="$SITE/beta/latest.json"; fi +install -m 644 "$IN/latest.json" "$LJ.tmp" +mv -f "$LJ.tmp" "$LJ" +rm -rf "$IN" +curl -fsS -o /dev/null --resolve storebound.dev:443:127.0.0.1 "$URL" && echo "storebound desktop $VERSION published ($CHANNEL): $URL"