From 3b02e707943c6f0fa3111461c7e9357741e30b37 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:18:18 -0700 Subject: [PATCH 01/11] feat(app): the Windows program opens no console window; the window is named Wanderbooks (P15 C1) The installed program is one executable that is the window, the books server's child and the assistants' bridge. Built for the Windows GUI subsystem, a Start Menu launch shows no console; console.rs gives a command run in a terminal its words back and never replaces a pipe an assistant handed the bridge. The two console programs the window starts (the agent's own list, the system's opener) get CREATE_NO_WINDOW. The window title is the product name; the storage id and the Linux app id stay lowercase so nothing already kept moves. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 1 + crates/ledger-cli/Cargo.toml | 5 ++ crates/ledger-cli/src/console.rs | 85 ++++++++++++++++++++++++++++++ crates/ledger-cli/src/main.rs | 12 +++++ crates/ledger-gui/src/app.rs | 2 +- crates/ledger-gui/src/export.rs | 15 ++++-- crates/ledger-gui/src/lib.rs | 2 +- crates/ledger-gui/tests/tabs.rs | 14 ++--- crates/ledger-host/src/commands.rs | 13 ++++- 9 files changed, 134 insertions(+), 15 deletions(-) create mode 100644 crates/ledger-cli/src/console.rs diff --git a/Cargo.lock b/Cargo.lock index 4508742f..9d337a8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4039,6 +4039,7 @@ dependencies = [ "time", "tokio", "tokio-rustls", + "windows-sys 0.61.2", "zeroize", "zip", ] diff --git a/crates/ledger-cli/Cargo.toml b/crates/ledger-cli/Cargo.toml index a99d2b3c..7d8e19cd 100644 --- a/crates/ledger-cli/Cargo.toml +++ b/crates/ledger-cli/Cargo.toml @@ -24,6 +24,11 @@ ledger-mcp = { path = "../ledger-mcp" } ledger-store = { path = "../ledger-store" } ledger-gui = { path = "../ledger-gui", optional = true } +# The parent's console for a command run in a terminal (console.rs): the +# raw bindings, already in the lockfile through ledger-store. +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console"] } + [dev-dependencies] base64 = "0.22" chrono = "0.4" diff --git a/crates/ledger-cli/src/console.rs b/crates/ledger-cli/src/console.rs new file mode 100644 index 00000000..f7ee1d9d --- /dev/null +++ b/crates/ledger-cli/src/console.rs @@ -0,0 +1,85 @@ +//! The program's console on Windows (plan P15 unit C1, WB-pkg-2). +//! +//! The installed program is one executable that is the window, the books +//! server child and the assistants' bridge. Built for the Windows GUI +//! subsystem (`windows_subsystem = "windows"` in `main.rs`), a double-click +//! or a Start Menu entry opens no console window. The same file still has +//! to be a command line: a person who types `wanderbooks books list` in a +//! terminal needs the words printed there, and an assistant that starts +//! `wanderbooks mcp --book X` hands it pipes, which a GUI-subsystem +//! program receives as they are. +//! +//! ```text +//! GOAL: no console window when the program starts as an app; its words +//! reach the terminal that started it as a command; a pipe handed to +//! it is never replaced. +//! SOURCE: WB-pkg-2 (one executable); Microsoft's documentation of +//! AttachConsole(ATTACH_PARENT_PROCESS) and SetStdHandle. +//! INVARIANTS: +//! 1. A standard handle the parent gave (a pipe, a file) is left as it +//! is; only a missing one (null or invalid) is pointed at the +//! parent's console (CONIN$ for input, CONOUT$ for output and +//! errors). +//! 2. With no parent console (a Start Menu launch, an assistant that +//! gave pipes and has no console) nothing is attached and nothing is +//! opened: the program never makes a console window of its own. +//! SCENARIOS: +//! 1. IF an assistant starts `mcp` with three pipes: SHOULD speak over +//! them, unchanged. +//! 2. IF a terminal starts `books list`: SHOULD print into the terminal. +//! 3. IF the Start Menu starts it with no words: SHOULD open the window +//! and no console. +//! ``` +//! +//! Not run on Windows by the author (the unit was written on Linux); the +//! `release` workflow's Windows job builds it, and the first install is +//! the evidence for the scenarios. + +/// Point the missing standard handles at the parent's console, if there +/// is one (INVARIANTS 1 and 2). A no-op everywhere but Windows. +#[cfg(windows)] +pub fn attach_parent_console() { + use std::os::windows::io::IntoRawHandle; + use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + use windows_sys::Win32::System::Console::{ + ATTACH_PARENT_PROCESS, AttachConsole, GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, + STD_OUTPUT_HANDLE, SetStdHandle, + }; + + // SAFETY: plain Win32 calls with no pointers of ours; a failure is a + // value, and the handles opened below are given to the process, which + // keeps them open for its life. + unsafe { + let missing = |id| { + let handle = GetStdHandle(id); + handle.is_null() || handle == INVALID_HANDLE_VALUE + }; + let wanted = [ + (STD_INPUT_HANDLE, "CONIN$", true), + (STD_OUTPUT_HANDLE, "CONOUT$", false), + (STD_ERROR_HANDLE, "CONOUT$", false), + ]; + if !wanted.iter().any(|(id, _, _)| missing(*id)) { + return; + } + if AttachConsole(ATTACH_PARENT_PROCESS) == 0 { + return; + } + for (id, device, input) in wanted { + if !missing(id) { + continue; + } + let opened = std::fs::OpenOptions::new() + .read(input) + .write(!input) + .open(device); + if let Ok(file) = opened { + SetStdHandle(id, file.into_raw_handle()); + } + } + } +} + +/// Nothing to do where a program is a console program already. +#[cfg(not(windows))] +pub fn attach_parent_console() {} diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 69e68251..406c17f6 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -9,6 +9,13 @@ //! From nothing to the first post: `wanderbooks setup`, `wanderbooks books //! create ID`, `wanderbooks connect claude --book ID` (then talk to the //! agent). +//! +//! On Windows the executable is built for the GUI subsystem, so starting +//! it from the Start Menu opens no console window; `console` gives a +//! command run in a terminal its words back (WB-pkg-2). +#![cfg_attr(all(windows, feature = "gui"), windows_subsystem = "windows")] + +mod console; use std::env; use std::io::Write; @@ -700,6 +707,11 @@ fn main() { eprintln!("error: an argument isn't UTF-8 text"); std::process::exit(2); }; + // A command run in a terminal prints there; the app (no words) opens + // no console at all (console.rs). + if !words.is_empty() { + console::attach_parent_console(); + } // A bare launch is the viewer. if is_bare_launch(&words, std::io::IsTerminal::is_terminal(&std::io::stdin())) { std::process::exit(run_gui(Vec::new())); diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 211c5fb5..f2e16b50 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -214,7 +214,7 @@ const WARN_AGE: std::time::Duration = std::time::Duration::from_secs(60); const FIRST_CONNECT_KEY: &str = "first_connect_done"; /// What a window is called when no company is in front. -const TITLE: &str = "wanderbooks"; +const TITLE: &str = "Wanderbooks"; impl App { /// The live app over one company's books directory. diff --git a/crates/ledger-gui/src/export.rs b/crates/ledger-gui/src/export.rs index 167225d7..c5739b14 100644 --- a/crates/ledger-gui/src/export.rs +++ b/crates/ledger-gui/src/export.rs @@ -141,10 +141,17 @@ pub fn open(path: &Path) { #[cfg(target_os = "macos")] let cmd = std::process::Command::new("open").arg(path).spawn(); #[cfg(target_os = "windows")] - let cmd = std::process::Command::new("cmd") - .args(["/C", "start", ""]) - .arg(path) - .spawn(); + let cmd = { + // The window has no console (WB-pkg-2): a console program it + // starts would open one for a moment, so it is told not to + // (CREATE_NO_WINDOW). + use std::os::windows::process::CommandExt; + std::process::Command::new("cmd") + .args(["/C", "start", ""]) + .arg(path) + .creation_flags(0x0800_0000) + .spawn() + }; #[cfg(not(any(target_os = "macos", target_os = "windows")))] let cmd = std::process::Command::new("xdg-open").arg(path).spawn(); let _ = cmd; diff --git a/crates/ledger-gui/src/lib.rs b/crates/ledger-gui/src/lib.rs index eb4a4f9d..d02612d2 100644 --- a/crates/ledger-gui/src/lib.rs +++ b/crates/ledger-gui/src/lib.rs @@ -140,7 +140,7 @@ pub fn run( }; let options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() - .with_title("wanderbooks") + .with_title("Wanderbooks") .with_app_id("wanderbooks") .with_inner_size([1440.0, 920.0]) // Small on purpose: tiling window managers hand out small slots diff --git a/crates/ledger-gui/tests/tabs.rs b/crates/ledger-gui/tests/tabs.rs index d2e6f193..9da8baef 100644 --- a/crates/ledger-gui/tests/tabs.rs +++ b/crates/ledger-gui/tests/tabs.rs @@ -336,7 +336,7 @@ fn each_tab_shows_its_own_company_and_figures() { loaded(&mut h); assert_eq!(titles(&h), ["Alpha Co", "Beta Co"]); assert_eq!(h.state().active(), Some(0)); - assert_eq!(h.state().window_title(), "Alpha Co · wanderbooks"); + assert_eq!(h.state().window_title(), "Alpha Co · Wanderbooks"); // Alpha: cash 10,000.00 less 1,234.56 rent is 8,765.44. assert!(shows(&h, "8,765.44"), "alpha's cash: {:?}", texts(&h)); @@ -354,7 +354,7 @@ fn each_tab_shows_its_own_company_and_figures() { // Beta: cash 25,000.00 less 777.77 is 24,222.23. show_tab(&mut h, "Beta Co"); assert_eq!(h.state().active(), Some(1)); - assert_eq!(h.state().window_title(), "Beta Co · wanderbooks"); + assert_eq!(h.state().window_title(), "Beta Co · Wanderbooks"); assert!( matches!(h.state().route(), Route::Overview), "a tab opens on its overview, not on the page the other was on" @@ -768,7 +768,7 @@ fn start_up_restores_the_open_tabs_their_order_and_the_one_in_front() { assert_eq!(titles(&h), ["Gamma Co", "Alpha Co", "Beta Co"]); assert_eq!(h.state().active(), Some(1), "the same one in front"); assert!(h.state().views().iter().all(|v| v.error().is_none())); - assert_eq!(h.state().window_title(), "Alpha Co · wanderbooks"); + assert_eq!(h.state().window_title(), "Alpha Co · Wanderbooks"); // No record: the data root's first, alone. let h2 = start_with_prefs(&w, &[]); @@ -894,15 +894,15 @@ fn closing_the_front_tab_shows_a_neighbour_and_the_last_leaves_an_empty_window() show_tab(&mut h, "Beta Co"); close_tab(&mut h, "Beta Co"); assert_eq!(titles(&h), ["Alpha Co", "Gamma Co"]); - assert_eq!(h.state().window_title(), "Gamma Co · wanderbooks"); + assert_eq!(h.state().window_title(), "Gamma Co · Wanderbooks"); // A tab behind the front one closing leaves the front one in front. close_tab(&mut h, "Alpha Co"); assert_eq!(titles(&h), ["Gamma Co"]); - assert_eq!(h.state().window_title(), "Gamma Co · wanderbooks"); + assert_eq!(h.state().window_title(), "Gamma Co · Wanderbooks"); // The last one. close_tab(&mut h, "Gamma Co"); assert!(h.state().views().is_empty()); - assert_eq!(h.state().window_title(), "wanderbooks"); + assert_eq!(h.state().window_title(), "Wanderbooks"); assert!(shows(&h, "No company is open"), "{:?}", texts(&h)); assert!( shows(&h, "Open a company with the + at the top of the window."), @@ -1737,7 +1737,7 @@ fn the_status_card_shows_the_company_in_front_and_follows_the_tab() { "alpha's hue left the card" ); // The window's title still names the company. - assert_eq!(h.state().window_title(), "Beta Co · wanderbooks"); + assert_eq!(h.state().window_title(), "Beta Co · Wanderbooks"); } } diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 4ebe37c4..6564ef85 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -1967,11 +1967,20 @@ pub fn connect_agent(common: &Common, agent: &str, book: &str) -> Result| -> Result { - let mut child = std::process::Command::new(&program) + let mut command = std::process::Command::new(&program); + command .args(args) .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()); + // The window has no console (WB-pkg-2): this one is not to open + // a console of its own for a moment (CREATE_NO_WINDOW). + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x0800_0000); + } + let mut child = command .spawn() .map_err(|e| format!("{label} couldn't be run: {}", e.kind()))?; let deadline = std::time::Instant::now() + CONNECT_WAIT; From 479d3a5c5e69a59bc54f5f9add4a47f61772d838 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:19:35 -0700 Subject: [PATCH 02/11] feat(store): a missing git says how to get it, for this system; a Mac's git stub is not a git (P15 C1) Backups run the system's git, which the program does not carry (it is a separate GPL program: bundling it is the owner's decision). The error a backup reports with no git now says so in plain words and how to get one on Windows (Git for Windows, winget), macOS (the command line tools, or Homebrew) and Linux (the package manager); backups stay off until then and nothing else changes. On a Mac without the developer tools, /usr/bin/git is a stub that opens Apple's installer and fails: it no longer counts as found. Git for Windows' per-user folder is searched too. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-store/src/backup.rs | 96 ++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 2 deletions(-) diff --git a/crates/ledger-store/src/backup.rs b/crates/ledger-store/src/backup.rs index 4dbf74a1..90977be2 100644 --- a/crates/ledger-store/src/backup.rs +++ b/crates/ledger-store/src/backup.rs @@ -156,12 +156,48 @@ pub const TERM_GRACE: Duration = Duration::from_secs(5); /// younger one is left, and the next backup tries again. pub const ARCHIVE_STALE: Duration = Duration::from_secs(600); +/// How to get git on this system, in plain words (P15 C1, WB-pkg-4). The +/// program does not carry a git of its own: git is a separate program under +/// the GPL, and shipping one is the owner's decision (`docs/install.md`). +/// Until a person installs it, backups are off and the books work as ever. +pub fn how_to_get_git() -> &'static str { + if cfg!(windows) { + "Install Git for Windows from https://git-scm.com/download/win (or, in a terminal, run: winget install --id Git.Git -e), then try again." + } else if cfg!(target_os = "macos") { + "Open Terminal and run: xcode-select --install (a window asks to install Apple's command line tools, which include git; or run: brew install git), then try again." + } else { + "Install git with your system's package manager (for example: sudo apt install git, or sudo dnf install git, or sudo pacman -S git), then try again." + } +} + +/// Where Apple's developer tools keep a real git on a Mac: the command +/// line tools' folder and Xcode's. +const MAC_DEVELOPER_DIRS: [&str; 2] = [ + "/Library/Developer/CommandLineTools", + "/Applications/Xcode.app/Contents/Developer", +]; + +/// Whether `exe` is the stub macOS ships at `/usr/bin/git`: with no +/// developer tools installed (none of `developer_dirs` holds a +/// `usr/bin/git`) it is not git but a program that opens Apple's installer +/// dialog and fails, so it is not a git to run (a backup would otherwise +/// pop that dialog and report a failure with a stranger's words). +fn macos_git_stub(exe: &Path, developer_dirs: &[&Path]) -> bool { + exe == Path::new("/usr/bin/git") + && !developer_dirs + .iter() + .any(|dir| dir.join("usr/bin/git").is_file()) +} + /// Why a backup couldn't be made, pushed or trusted. Never names a path of /// the data root (INVARIANT 4). #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum BackupError { /// git isn't installed. - #[error("git isn't installed: backups need it (install git, then try again)")] + #[error( + "git isn't installed, so backups are off until it is. {}", + how_to_get_git() + )] NoGit, /// A git command failed; what it said, in whole lines (paths in it are /// the caller's to hide, INVARIANT 4). @@ -247,6 +283,17 @@ impl std::fmt::Debug for Watch { } } +/// Git for Windows' per-user install (no administrator needed): under the +/// account's local application data. +fn per_user_git_dirs() -> Vec { + if cfg!(windows) + && let Some(local) = std::env::var_os("LOCALAPPDATA") + { + return vec![Path::new(&local).join(r"Programs\Git\cmd")]; + } + Vec::new() +} + /// The git program, found once. #[derive(Debug, Clone)] pub struct Git { @@ -285,9 +332,14 @@ impl Git { .collect::>() .iter(), ) + .chain(per_user_git_dirs().iter()) .filter(|d| d.is_absolute()) .map(|d| d.join(if cfg!(windows) { "git.exe" } else { "git" })) - .find(|p| p.is_file()) + .find(|p| { + p.is_file() + && !(cfg!(target_os = "macos") + && macos_git_stub(p, &MAC_DEVELOPER_DIRS.map(Path::new))) + }) .map(|exe| Git { exe, quiet: GIT_TIMEOUT, @@ -1844,6 +1896,46 @@ mod tests { Money::new(s.parse().unwrap(), Currency::USD) } + /// WB-pkg-4: with no git a backup says how to get one, in words for + /// this system, and names no path of the data root. + #[test] + fn a_missing_git_says_how_to_get_it() { + let said = BackupError::NoGit.to_string(); + assert!(said.contains("git isn't installed"), "{said}"); + assert!(said.contains("backups are off until it is"), "{said}"); + assert!(said.ends_with(how_to_get_git()), "{said}"); + let how = how_to_get_git(); + if cfg!(windows) { + assert!( + how.contains("git-scm.com") && how.contains("winget"), + "{how}" + ); + } else if cfg!(target_os = "macos") { + assert!(how.contains("xcode-select --install"), "{how}"); + } else { + assert!(how.contains("package manager"), "{how}"); + } + assert!(how.ends_with("try again."), "{how}"); + } + + /// macOS's `/usr/bin/git` is a stub until the developer tools are + /// installed: it is no git, and nothing else is taken for one. + #[test] + fn the_mac_stub_is_not_a_git_until_the_developer_tools_are_there() { + let dir = tempfile::tempdir().unwrap(); + let tools = dir.path().join("CommandLineTools"); + let stub = Path::new("/usr/bin/git"); + assert!(macos_git_stub(stub, &[tools.as_path()]), "no tools yet"); + std::fs::create_dir_all(tools.join("usr/bin")).unwrap(); + std::fs::write(tools.join("usr/bin/git"), b"").unwrap(); + assert!(!macos_git_stub(stub, &[tools.as_path()]), "tools installed"); + // Any other git is never the stub. + assert!(!macos_git_stub( + Path::new("/opt/homebrew/bin/git"), + &[dir.path()] + )); + } + /// A book with a few entries and a stored file. fn book(dir: &Path) -> Store { let mut s = Store::create(dir, Currency::USD).unwrap(); From 2bc442f795c61a89f8951b2e527bae21175da0a1 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:31:21 -0700 Subject: [PATCH 03/11] feat(app): the Connect page's Claude desktop app row writes a one-click extension (P15 C1) Claude's desktop extension format is the MCP Bundle: a .mcpb zip with a manifest.json (manifest 0.3, github.com/anthropics/mcpb). The row's button makes the company's agent key if there is none and writes Documents/Wanderbooks/Extensions/wanderbooks-.mcpb: a manifest whose server is a binary running this program's own stable path as mcp --book , the 512 px icon and a short README as the entry point. The package carries no program (the one executable is the installed one), no key and no path of the data root. The page then says in plain words where in Claude to pick the file and to keep Wanderbooks open, and offers to show the file. The manifest is checked against Anthropic's published schema (a test fixture) and its required fields. The blessed Connect page pictures change by exactly the new row. The program's version is now one value set by main for every platform, not only Unix. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 1 + crates/ledger-cli/src/main.rs | 15 +- crates/ledger-cli/tests/extension.rs | 142 +++++++ .../ledger-cli/tests/fixtures/mcpb/SOURCE.txt | 10 + .../mcpb/mcpb-manifest-v0.3.schema.json | 376 ++++++++++++++++++ crates/ledger-gui/src/connect.rs | 81 ++++ crates/ledger-gui/src/owner.rs | 19 + crates/ledger-gui/tests/assistants.rs | 55 +++ .../snapshots/assist_connect_page_dark.shapes | 2 +- .../assist_connect_page_light.shapes | 2 +- crates/ledger-host/Cargo.toml | 2 + crates/ledger-host/src/commands.rs | 2 +- crates/ledger-host/src/extension.rs | 317 +++++++++++++++ crates/ledger-host/src/lib.rs | 19 + crates/ledger-host/src/update.rs | 17 +- 15 files changed, 1039 insertions(+), 21 deletions(-) create mode 100644 crates/ledger-cli/tests/extension.rs create mode 100644 crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt create mode 100644 crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json create mode 100644 crates/ledger-host/src/extension.rs diff --git a/Cargo.lock b/Cargo.lock index 9d337a8d..7e52588d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4133,6 +4133,7 @@ dependencies = [ "tokio", "tokio-util", "zeroize", + "zip", ] [[package]] diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 406c17f6..a4940241 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -282,6 +282,18 @@ impl ledger_gui::owner::Owner for ViewerOwner { ) } + fn claude_desktop_extension( + &self, + book: &str, + company: &str, + ) -> Result { + let made = ledger_host::extension::claude_desktop_extension(&self.common, book, company)?; + Ok(ledger_gui::owner::ExtensionMade { + file: made.path.display().to_string(), + folder: made.folder.display().to_string(), + }) + } + fn new_books(&self, id: &str, currency: &str) -> Result { ledger_host::commands::new_books_and_home(&self.common, id, currency) } @@ -690,8 +702,7 @@ fn is_bare_launch(words: &[String], stdin_is_terminal: bool) -> bool { } fn main() { - #[cfg(unix)] - ledger_host::update::set_program_version(env!("CARGO_PKG_VERSION")); + ledger_host::set_program_version(env!("CARGO_PKG_VERSION")); // A file's path may be any name the system takes: the file commands // get the words as given. Everything else is text. let given: Vec = env::args_os().skip(1).collect(); diff --git a/crates/ledger-cli/tests/extension.rs b/crates/ledger-cli/tests/extension.rs new file mode 100644 index 00000000..da9a213a --- /dev/null +++ b/crates/ledger-cli/tests/extension.rs @@ -0,0 +1,142 @@ +//! The Claude desktop extension the Connect page writes (plan P15 unit C1, +//! WB-pkg-5): its package is Anthropic's MCP Bundle, and its manifest is +//! checked against Anthropic's published schema for manifest version 0.3 +//! (`tests/fixtures/mcpb/`, with where it came from). +//! +//! ```text +//! GOAL: a package the Claude desktop app can install, naming this +//! program's bridge for one company, with nothing secret in it. +//! SOURCE: WB-pkg-5; github.com/anthropics/mcpb (MANIFEST.md, the 0.3 +//! schema); ledger-host extension.rs. +//! INVARIANTS: +//! 1. The package is a zip whose root holds `manifest.json`; every file +//! the manifest names (`icon`, `server.entry_point`) is in the zip. +//! 2. The manifest validates against the 0.3 schema, which refuses any +//! field the specification does not define. +//! 3. The server is a `binary` whose command is the program's path and +//! whose arguments are `mcp --book `. +//! SCENARIOS: +//! 1. A package made for a company with an awkward name validates. +//! 2. Every required field of the schema is present. +//! ``` + +use serde_json::Value; +use std::io::Read; + +fn schema() -> jsonschema::Validator { + let text = include_str!("fixtures/mcpb/mcpb-manifest-v0.3.schema.json"); + jsonschema::validator_for(&serde_json::from_str::(text).unwrap()).unwrap() +} + +fn made(company: &str) -> (tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let bridge: Vec = [ + "/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks", + "mcp", + "--book", + "acme", + ] + .map(Into::into) + .to_vec(); + let made = ledger_host::extension::write_in(dir.path(), "acme", company, "0.1.0", &bridge) + .expect("the package is written"); + (dir, made.path) +} + +fn read(path: &std::path::Path) -> (Value, Vec) { + let mut zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap(); + let names: Vec = (0..zip.len()) + .map(|i| zip.by_index(i).unwrap().name().unwrap().to_string()) + .collect(); + let mut text = String::new(); + zip.by_name("manifest.json") + .expect("manifest.json is at the root of the package") + .read_to_string(&mut text) + .unwrap(); + (serde_json::from_str(&text).unwrap(), names) +} + +#[test] +fn the_manifest_is_one_the_published_schema_accepts() { + for company in [ + "Wanderland Labs LLC", + "Quote \" and & \u{e9}\u{4e2d}", + &"long ".repeat(100), + "", + ] { + let (_dir, path) = made(company); + let (manifest, _) = read(&path); + let errors: Vec = schema() + .iter_errors(&manifest) + .map(|e| format!("{e} at {}", e.instance_path())) + .collect(); + assert!(errors.is_empty(), "{company:?}: {errors:?}\n{manifest:#}"); + // The check is not vacuous: a field the specification lacks, or a + // missing required one, is refused. + let mut extra = manifest.clone(); + extra["no_such_field"] = Value::Bool(true); + assert!(!schema().is_valid(&extra)); + let mut short = manifest.clone(); + short.as_object_mut().unwrap().remove("author"); + assert!(!schema().is_valid(&short)); + } +} + +#[test] +fn every_file_the_manifest_names_is_in_the_package() { + let (_dir, path) = made("Acme"); + let (manifest, names) = read(&path); + assert_eq!(manifest["manifest_version"], "0.3"); + for named in [ + manifest["icon"].as_str().unwrap(), + manifest["server"]["entry_point"].as_str().unwrap(), + ] { + assert!(names.iter().any(|n| n == named), "{named} in {names:?}"); + } + // The schema's required fields, by the schema's own list. + let schema: Value = + serde_json::from_str(include_str!("fixtures/mcpb/mcpb-manifest-v0.3.schema.json")).unwrap(); + for field in schema["required"].as_array().unwrap() { + assert!(manifest.get(field.as_str().unwrap()).is_some(), "{field}"); + } + for field in schema["properties"]["server"]["required"] + .as_array() + .unwrap() + { + assert!(manifest["server"].get(field.as_str().unwrap()).is_some()); + } +} + +#[test] +fn the_server_runs_this_programs_bridge_for_the_company() { + let (_dir, path) = made("Acme"); + let (manifest, _) = read(&path); + let server = &manifest["server"]; + assert_eq!(server["type"], "binary"); + assert_eq!( + server["mcp_config"]["command"], + "/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks" + ); + assert_eq!( + server["mcp_config"]["args"], + serde_json::json!(["mcp", "--book", "acme"]) + ); + // The package carries no program (the one executable is the installed + // one) and no key. + let (_, names) = read(&path); + assert_eq!(names.len(), 3, "{names:?}"); + assert_eq!(manifest["name"], "wanderbooks-acme"); +} + +/// The 512 px icon is a PNG (the manifest's `icon` is "a png icon file"). +#[test] +fn the_icon_is_a_png() { + let (_dir, path) = made("Acme"); + let mut zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap(); + let mut head = [0u8; 8]; + zip.by_name("icon.png") + .unwrap() + .read_exact(&mut head) + .unwrap(); + assert_eq!(&head, b"\x89PNG\r\n\x1a\n"); +} diff --git a/crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt b/crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt new file mode 100644 index 00000000..e87a8ce4 --- /dev/null +++ b/crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt @@ -0,0 +1,10 @@ +mcpb-manifest-v0.3.schema.json is Anthropic's published JSON Schema for the +manifest.json of an MCP Bundle (.mcpb, formerly the Desktop Extension .dxt), +manifest_version 0.3, copied verbatim on 2026-11-21 from +https://github.com/anthropics/mcpb (schemas/mcpb-manifest-v0.3.schema.json, +main branch). The specification's prose is MANIFEST.md in the same +repository; the install steps are Claude's help article "Getting started +with Local MCP servers on Claude Desktop" (support.claude.com). +The repository's licence: Apache-2.0 for new contributions, MIT for older +ones (its LICENSE file); both fit this project's MIT OR Apache-2.0. It is +a test fixture only and is not shipped. diff --git a/crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json b/crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json new file mode 100644 index 00000000..64471c54 --- /dev/null +++ b/crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json @@ -0,0 +1,376 @@ +{ + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "dxt_version": { + "type": "string", + "const": "0.3", + "description": "@deprecated Use manifest_version instead" + }, + "manifest_version": { + "type": "string", + "const": "0.3" + }, + "name": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "description": { + "type": "string" + }, + "long_description": { + "type": "string" + }, + "author": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "email": { + "type": "string", + "format": "email" + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + }, + "repository": { + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": [ + "type", + "url" + ], + "additionalProperties": false + }, + "homepage": { + "type": "string", + "format": "uri" + }, + "documentation": { + "type": "string", + "format": "uri" + }, + "support": { + "type": "string", + "format": "uri" + }, + "icon": { + "type": "string" + }, + "icons": { + "type": "array", + "items": { + "type": "object", + "properties": { + "src": { + "type": "string" + }, + "size": { + "type": "string", + "pattern": "^\\d+x\\d+$" + }, + "theme": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "src", + "size" + ], + "additionalProperties": false + } + }, + "screenshots": { + "type": "array", + "items": { + "type": "string" + } + }, + "localization": { + "type": "object", + "properties": { + "resources": { + "type": "string", + "pattern": "\\$\\{locale\\}" + }, + "default_locale": { + "type": "string", + "pattern": "^[A-Za-z0-9]{2,8}(?:-[A-Za-z0-9]{1,8})*$" + } + }, + "required": [ + "resources", + "default_locale" + ], + "additionalProperties": false + }, + "server": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "python", + "node", + "binary" + ] + }, + "entry_point": { + "type": "string" + }, + "mcp_config": { + "type": "object", + "properties": { + "command": { + "type": "string" + }, + "args": { + "type": "array", + "items": { + "type": "string" + } + }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "platform_overrides": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "command": { + "$ref": "#/properties/server/properties/mcp_config/properties/command" + }, + "args": { + "$ref": "#/properties/server/properties/mcp_config/properties/args" + }, + "env": { + "$ref": "#/properties/server/properties/mcp_config/properties/env" + } + }, + "additionalProperties": false + } + } + }, + "required": [ + "command" + ], + "additionalProperties": false + } + }, + "required": [ + "type", + "entry_point", + "mcp_config" + ], + "additionalProperties": false + }, + "tools": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + } + }, + "tools_generated": { + "type": "boolean" + }, + "prompts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "arguments": { + "type": "array", + "items": { + "type": "string" + } + }, + "text": { + "type": "string" + } + }, + "required": [ + "name", + "text" + ], + "additionalProperties": false + } + }, + "prompts_generated": { + "type": "boolean" + }, + "keywords": { + "type": "array", + "items": { + "type": "string" + } + }, + "license": { + "type": "string" + }, + "privacy_policies": { + "type": "array", + "items": { + "type": "string", + "format": "uri" + } + }, + "compatibility": { + "type": "object", + "properties": { + "claude_desktop": { + "type": "string" + }, + "platforms": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "darwin", + "win32", + "linux" + ] + } + }, + "runtimes": { + "type": "object", + "properties": { + "python": { + "type": "string" + }, + "node": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "user_config": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "directory", + "file" + ] + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "default": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "multiple": { + "type": "boolean" + }, + "sensitive": { + "type": "boolean" + }, + "min": { + "type": "number" + }, + "max": { + "type": "number" + } + }, + "required": [ + "type", + "title", + "description" + ], + "additionalProperties": false + } + }, + "_meta": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": {} + } + } + }, + "required": [ + "name", + "version", + "description", + "author", + "server" + ], + "additionalProperties": false, + "$schema": "http://json-schema.org/draft-07/schema#" +} \ No newline at end of file diff --git a/crates/ledger-gui/src/connect.rs b/crates/ledger-gui/src/connect.rs index 7ae8d23e..75f8fb38 100644 --- a/crates/ledger-gui/src/connect.rs +++ b/crates/ledger-gui/src/connect.rs @@ -424,6 +424,9 @@ pub struct State { new_address_asked: bool, /// The address was just copied (the time, for the word "Copied"). copied_at: Option, + /// The folder the Claude desktop extension was written in, once it + /// was (set by the job that made it). + extension_folder: Arc>>, } /// The two lines an assistant set up by hand needs. @@ -807,6 +810,7 @@ impl State { want = Some(w); } } + self.desktop_row(ui, status, book, &owner, busy, &mut want); another_row(ui, status, book, &owner, &commands, busy, &mut want); if let Some((what, keep, work)) = want { self.start(ui, jobs, what, &keep, work); @@ -842,6 +846,83 @@ impl State { }); } + /// The "Claude desktop app" row (WB-pkg-5): one button that writes the + /// one-click extension, and the steps that follow, in plain words. + fn desktop_row( + &mut self, + ui: &mut Ui, + status: &Status, + book: &str, + owner: &Option>, + busy: bool, + want: &mut Want, + ) { + let p = pal(ui.ctx()); + let made = self + .extension_folder + .lock() + .map(|f| f.clone()) + .unwrap_or_default(); + Frame::new() + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(8)) + .inner_margin(Margin::symmetric(12, 10)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label(RichText::new("Claude desktop app").font(theme::semibold(14.5))); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if let Some(owner) = owner + && ui + .add_enabled(!busy, egui::Button::new("Make the Claude extension")) + .on_hover_text( + "Writes one file you open in the Claude desktop app to add these books", + ) + .clicked() + { + let (o, b, company) = + (owner.clone(), book.to_string(), status.company.clone()); + let folder = self.extension_folder.clone(); + *want = Some(( + "Claude desktop extension".to_string(), + "Making the Claude desktop extension".to_string(), + Box::new(move || { + o.claude_desktop_extension(&b, &company).map(|made| { + if let Ok(mut f) = folder.lock() { + *f = Some(made.folder.clone()); + } + format!( + "made {}. Next: open the Claude desktop app, go to Settings, then Extensions, then Advanced settings, choose Install Extension, and pick that file (or just open the file). Keep Wanderbooks open while you use Claude.", + made.file + ) + }) + }), + )); + } + }); + }); + ui.add_space(4.0); + ui.label( + RichText::new( + "Adds these books to the Claude app on this computer with one file, so you type nothing.", + ) + .font(theme::regular(13.0)) + .color(p.muted), + ); + if let Some(folder) = made { + ui.add_space(4.0); + if ui + .button(format!("{} Show the file", icon::FOLDER_OPEN)) + .clicked() + { + crate::export::open(std::path::Path::new(&folder)); + } + } + }); + ui.add_space(6.0); + } + /// "Connections": every key to these books, who is connected on it, /// what it may do, when it last did anything, and Revoke. fn connections( diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index a10aaa4f..c9289be6 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -412,6 +412,16 @@ pub trait Owner: Send + Sync { fn command_line(&self, _words: &[&str]) -> Result { Err("not here".into()) } + /// The Claude desktop extension for the company `book` (shown as + /// `company`): the one-click package written where a person can open it, + /// the key made first if there was none. Blocks. + fn claude_desktop_extension( + &self, + _book: &str, + _company: &str, + ) -> Result { + Err("not here".into()) + } /// The key an assistant needs to reach the company `book` exists (made /// now if it did not), able to read, draft and post but not to see the /// access record: `Ok(true)` when it was made now. It never replaces a @@ -476,6 +486,15 @@ pub trait Owner: Send + Sync { } } +/// The Claude desktop extension the Connect page made (WB-pkg-5). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExtensionMade { + /// The package file, in full. + pub file: String, + /// The folder it is in. + pub folder: String, +} + /// The owner the program gave the viewer, for every company's view that /// isn't given one of its own. It is the program's (one per process, as /// the program is one), not a company's: each view takes a handle to it diff --git a/crates/ledger-gui/tests/assistants.rs b/crates/ledger-gui/tests/assistants.rs index 0e14ef99..3d14f3ca 100644 --- a/crates/ledger-gui/tests/assistants.rs +++ b/crates/ledger-gui/tests/assistants.rs @@ -247,6 +247,17 @@ impl Owner for Fake { self.note(format!("connect {} {book}", agent.key())); Ok(vec![format!("{} reaches the books.", agent.label())]) } + fn claude_desktop_extension( + &self, + book: &str, + company: &str, + ) -> Result { + self.note(format!("extension {book} {company}")); + Ok(ledger_gui::owner::ExtensionMade { + file: "/docs/Wanderbooks/Extensions/wanderbooks-alpha.mcpb".into(), + folder: "/docs/Wanderbooks/Extensions".into(), + }) + } fn new_books(&self, _: &str, _: &str) -> Result { Err("not here".into()) } @@ -731,6 +742,50 @@ fn the_connect_buttons_do_what_connect_does() { drop(h); } +/// WB-pkg-5: the "Claude desktop app" row makes the extension for this +/// company through the owner, then says in words what to do with the file. +#[test] +fn the_claude_desktop_row_makes_the_extension_and_says_what_to_do_next() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Fake::new(); + owner.answer(roster(vec![], vec![])); + let mut h = start(&w, &["alpha"], &owner); + refresh(&mut h); + h.state_mut().goto(Route::Connect); + h.run_steps(3); + assert!(h.query_by_label_contains("Claude desktop app").is_some()); + assert!( + h.query_by_label_contains("Show the file").is_none(), + "nothing is made yet" + ); + h.get_by_role_and_label(Role::Button, "Make the Claude extension") + .click(); + h.run_steps(2); + wait_for("the extension was made", || { + owner + .said() + .contains(&"extension alpha Wanderland Labs".to_string()) + }); + until(&mut h, "it said what came of it", |a| { + a.views()[0].connect_state().said().is_some() + }); + h.run_steps(2); + for words in [ + "wanderbooks-alpha.mcpb", + "Settings", + "Extensions", + "Install Extension", + "Keep Wanderbooks open", + ] { + assert!( + h.query_by_label_contains(words).is_some(), + "{words} is said on the page" + ); + } + assert!(h.query_by_label_contains("Show the file").is_some()); + drop(h); +} + // ---- 5: the warning before a close --------------------------------------------- fn connected_alpha(owner: &Fake) { diff --git a/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes b/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes index e58c6ce9..6a892c47 100644 --- a/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_connect_page_dark.shapes @@ -1 +1 @@ -2abd53e6457106f8 +de92373f318d6a38 diff --git a/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes b/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes index 26abeaee..e95e67d0 100644 --- a/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes +++ b/crates/ledger-gui/tests/snapshots/assist_connect_page_light.shapes @@ -1 +1 @@ -b990ac9586df492a +d163fd8e3925b936 diff --git a/crates/ledger-host/Cargo.toml b/crates/ledger-host/Cargo.toml index b3eedc39..c507be73 100644 --- a/crates/ledger-host/Cargo.toml +++ b/crates/ledger-host/Cargo.toml @@ -25,6 +25,8 @@ rpassword = "7" # Token texts and passphrases are wiped from memory when dropped. zeroize = "1" minisign-verify = "0.3.0" +# The Claude desktop extension is a zip file (extension.rs). +zip = { version = "9.0.1", default-features = false, features = ["deflate"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 6564ef85..73797754 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -1893,7 +1893,7 @@ pub fn ensure_key( /// What `connect` does first: the default key's copy is in the token file, /// or the key is made again with every scope (replacing a live key whose /// copy is missing: the owner asked to connect an agent here). -fn ensure_agent_key(common: &Common, book: &str) -> Result { +pub(crate) fn ensure_agent_key(common: &Common, book: &str) -> Result { let book = ledger_store::root::BookId::parse(book) .map_err(|e| e.to_string())? .to_string(); diff --git a/crates/ledger-host/src/extension.rs b/crates/ledger-host/src/extension.rs new file mode 100644 index 00000000..546142be --- /dev/null +++ b/crates/ledger-host/src/extension.rs @@ -0,0 +1,317 @@ +//! The Claude desktop extension for a company (plan P15 unit C1, 3.3). +//! +//! The Connect page's "Claude desktop app" row writes a one-click +//! extension package that makes the Claude desktop app run this program's +//! bridge (`wanderbooks mcp --book X`) for one company. The format is +//! Anthropic's MCP Bundle ("MCPB"): a zip archive, extension `.mcpb`, +//! holding a `manifest.json`. (The format was called "Desktop Extension", +//! `.dxt`, until it was renamed; the manifest spec's page says so.) +//! +//! ```text +//! GOAL: a person double-clicks one file, or picks it under Claude +//! desktop's Settings > Extensions > Advanced settings > Install +//! Extension, and Claude can keep that company's books, with no +//! command typed and no file edited. +//! SOURCE: WB-pkg-5; Anthropic's MCPB manifest specification, version +//! 0.3 (github.com/anthropics/mcpb, MANIFEST.md and +//! schemas/mcpb-manifest-v0.3.schema.json, read 2026-11-21) and +//! Claude's help article "Getting started with Local MCP servers +//! on Claude Desktop" (the install steps). +//! INVARIANTS: +//! 1. The manifest holds only fields the specification defines, with +//! `manifest_version` "0.3", a `server` of type `binary` whose +//! `mcp_config.command` is this program's own stable path (the one a +//! terminal agent is registered with: `commands::bridge_serve_args`, +//! which refuses a translocated app) and whose arguments are `mcp +//! --book ` (and `--root` when the root was named). The package +//! carries no program: the one executable is the installed one, so +//! an update of the app is an update of the extension. +//! 2. No key, token, passphrase or path of the data root is in the +//! package: the bridge reads its key from the token file the app +//! keeps, as it does for a terminal agent (`ensure_agent_key` makes +//! it, once). +//! 3. The package is written under `/Wanderbooks/Extensions/` +//! (a folder a person can open; not a book's home, which holds four +//! files and nothing else), by a temporary file and a rename. +//! 4. The package is for the system it was made on (`platforms`). +//! SCENARIOS: +//! 1. IF the program is installed at a stable path: SHOULD write +//! `wanderbooks-.mcpb` that validates against the 0.3 schema. +//! 2. IF the program runs from a translocated macOS copy: SHOULD write +//! nothing and say to move it first. +//! 3. IF the company's name holds quotes, markup or a very long text: +//! SHOULD appear as text in the manifest, bounded. +//! ``` +//! +//! Not run against a real Claude desktop app by the author (written on +//! Linux, with no Claude desktop at hand): the manifest is checked +//! against the published schema in `crates/ledger-cli/tests/extension.rs`; +//! that Claude accepts a `binary` extension whose command is an absolute +//! path to a program outside the package is the part to try first on a +//! real install. + +use crate::commands::Common; +use serde_json::{Value, json}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// The manifest specification this package follows. +pub const MANIFEST_VERSION: &str = "0.3"; + +/// The icon the package carries (the app's own, 512 px). +const ICON: &[u8] = include_bytes!("../../../deploy/packaging/icons/512x512.png"); + +/// The longest company name or description put in a manifest, in +/// characters. +const LONGEST: usize = 120; + +/// What was written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Made { + /// The package. + pub path: PathBuf, + /// The folder it is in, for the person to open. + pub folder: PathBuf, +} + +/// `/Wanderbooks/Extensions`: where the packages go. A book's id +/// is lower case, so no company's books home can have this name. +pub fn extensions_dir_in(documents: &Path) -> PathBuf { + documents.join("Wanderbooks").join("Extensions") +} + +/// The file's name for a book: `wanderbooks-.mcpb`. +pub fn file_name(book: &str) -> String { + format!("wanderbooks-{book}.mcpb") +} + +/// `process.platform`'s name for this system, as the manifest's +/// `compatibility.platforms` spells it. +pub fn platform_name() -> &'static str { + match std::env::consts::OS { + "macos" => "darwin", + "windows" => "win32", + other => other, + } +} + +/// `text` cut to [`LONGEST`] characters, with control characters turned +/// into spaces: a name is text in the manifest and nothing else. +fn tidy(text: &str) -> String { + text.chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .take(LONGEST) + .collect::() + .trim() + .to_string() +} + +/// The manifest (INVARIANT 1) for `book`, kept by `company`, run by +/// `command` with `args`, made for `platform`. +pub fn manifest( + book: &str, + company: &str, + version: &str, + command: &str, + args: &[String], + platform: &str, +) -> Value { + let company = match tidy(company) { + name if name.is_empty() => book.to_string(), + name => name, + }; + json!({ + "manifest_version": MANIFEST_VERSION, + "name": format!("wanderbooks-{book}"), + "display_name": format!("Wanderbooks: {company}"), + "version": version, + "description": format!("Lets Claude keep the books of {company} in Wanderbooks."), + "long_description": format!( + "Connects the Claude desktop app to the books of {company}, which Wanderbooks keeps on this computer. Claude reads them, drafts entries and, when you let it, posts them. Wanderbooks must be open, with these books open in a tab, for Claude to reach them." + ), + "author": { "name": "Wanderbooks", "url": "https://wanderbooks.ai" }, + "homepage": "https://wanderbooks.ai", + "icon": "icon.png", + "license": "MIT OR Apache-2.0", + "keywords": ["bookkeeping", "accounting", "wanderbooks"], + "server": { + "type": "binary", + "entry_point": "server/README.txt", + "mcp_config": { "command": command, "args": args } + }, + "tools_generated": true, + "compatibility": { "platforms": [platform] } + }) +} + +/// What `server/README.txt` says (the manifest's entry point is a file in +/// the package; the program it names is the installed one). +const README: &str = "This extension carries no program of its own.\n\ +It runs the Wanderbooks app you installed, as `wanderbooks mcp --book `,\n\ +so Claude can keep one company's books. Open Wanderbooks first, with those\n\ +books open in a tab. If you move or reinstall Wanderbooks somewhere else,\n\ +make this extension again from the app's Assistants page.\n"; + +/// The package's bytes: a zip of `manifest.json`, `icon.png` and +/// `server/README.txt` (INVARIANT 1). +pub fn package_bytes(manifest: &Value) -> Result, String> { + use zip::write::SimpleFileOptions; + let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + let text = serde_json::to_vec_pretty(manifest).map_err(|e| e.to_string())?; + let mut out = std::io::Cursor::new(Vec::new()); + let mut zip = zip::ZipWriter::new(&mut out); + let mut add = |name: &str, bytes: &[u8]| -> Result<(), String> { + zip.start_file(name, options) + .map_err(|e| format!("can't make the package: {e}"))?; + zip.write_all(bytes) + .map_err(|e| format!("can't make the package: {e}")) + }; + add("manifest.json", &text)?; + add("icon.png", ICON)?; + add("server/README.txt", README.as_bytes())?; + zip.finish() + .map_err(|e| format!("can't make the package: {e}"))?; + Ok(out.into_inner()) +} + +/// Write the extension for `book` (company `company`) under `documents`, +/// for the program and arguments `bridge` (`program, args…`). The key is +/// the caller's to have made (INVARIANT 2). +pub fn write_in( + documents: &Path, + book: &str, + company: &str, + version: &str, + bridge: &[std::ffi::OsString], +) -> Result { + let book = ledger_store::root::BookId::parse(book) + .map_err(|e| e.to_string())? + .to_string(); + if !documents.is_absolute() { + return Err("there is no documents folder to put the extension in".into()); + } + let (command, args) = bridge + .split_first() + .ok_or("the bridge's command could not be worked out")?; + let as_text = |part: &std::ffi::OsStr| { + part.to_str() + .map(str::to_string) + .ok_or_else(|| "the program's path is not text Claude can be given".to_string()) + }; + let command = as_text(command)?; + let args = args + .iter() + .map(|a| as_text(a)) + .collect::, _>>()?; + let bytes = package_bytes(&manifest( + &book, + company, + version, + &command, + &args, + platform_name(), + ))?; + let folder = extensions_dir_in(documents); + std::fs::create_dir_all(&folder) + .map_err(|e| format!("can't make {}: {}", folder.display(), e.kind()))?; + let path = folder.join(file_name(&book)); + let tmp = folder.join(format!(".{}.tmp{}", file_name(&book), std::process::id())); + std::fs::write(&tmp, &bytes).map_err(|e| format!("can't write the package: {}", e.kind()))?; + std::fs::rename(&tmp, &path).map_err(|e| { + let _ = std::fs::remove_file(&tmp); + format!("can't write the package: {}", e.kind()) + })?; + Ok(Made { path, folder }) +} + +/// The Claude desktop extension for `book`, in the person's Documents: +/// the agent key made if there is none, then the package (the words +/// above). What was made. +pub fn claude_desktop_extension( + common: &Common, + book: &str, + company: &str, +) -> Result { + let documents = crate::commands::documents_dir() + .ok_or("there is no documents folder to put the extension in")?; + // The stable path first: a translocated copy refuses here, before a + // key is made or a file written. + let bridge = crate::commands::bridge_serve_args(common, book)?; + crate::commands::ensure_agent_key(common, book)?; + write_in(&documents, book, company, crate::program_version(), &bridge) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bridge() -> Vec { + ["/opt/Wanderbooks/wanderbooks", "mcp", "--book", "acme"] + .map(Into::into) + .to_vec() + } + + #[test] + fn the_package_is_written_where_a_person_can_open_it() { + let dir = tempfile::tempdir().unwrap(); + let made = write_in(dir.path(), "acme", "Acme LLC", "0.1.0", &bridge()).unwrap(); + assert_eq!( + made.path, + dir.path() + .join("Wanderbooks/Extensions/wanderbooks-acme.mcpb") + ); + assert_eq!(made.folder, dir.path().join("Wanderbooks/Extensions")); + let file = std::fs::File::open(&made.path).unwrap(); + let mut zip = zip::ZipArchive::new(file).unwrap(); + let mut names: Vec = (0..zip.len()) + .map(|i| zip.by_index(i).unwrap().name().unwrap().to_string()) + .collect(); + names.sort(); + assert_eq!(names, ["icon.png", "manifest.json", "server/README.txt"]); + // Written again, it replaces itself; nothing is left beside it. + write_in(dir.path(), "acme", "Acme LLC", "0.1.0", &bridge()).unwrap(); + let left: Vec<_> = std::fs::read_dir(&made.folder).unwrap().collect(); + assert_eq!(left.len(), 1); + } + + #[test] + fn a_name_is_text_and_bounded() { + let long = "x".repeat(500); + let m = manifest( + "acme", + &format!("A\"\n{long}"), + "1.0.0", + "/p", + &[], + "linux", + ); + let shown = m["display_name"].as_str().unwrap(); + assert!( + shown.chars().count() <= "Wanderbooks: ".len() + LONGEST, + "{shown}" + ); + assert!(!shown.contains('\n')); + let none = manifest("acme", " ", "1.0.0", "/p", &[], "linux"); + assert_eq!(none["display_name"], "Wanderbooks: acme"); + } + + #[test] + fn no_secret_and_no_data_root_is_in_the_package() { + let dir = tempfile::tempdir().unwrap(); + let made = write_in(dir.path(), "acme", "Acme", "0.1.0", &bridge()).unwrap(); + let mut zip = zip::ZipArchive::new(std::fs::File::open(&made.path).unwrap()).unwrap(); + let mut text = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("manifest.json").unwrap(), &mut text) + .unwrap(); + for word in ["token", "passphrase", "secret", "password", "bearer"] { + assert!(!text.to_lowercase().contains(word), "{word} in {text}"); + } + assert!(text.contains("\"mcp\""), "{text}"); + } + + #[test] + fn a_relative_documents_folder_is_refused() { + let err = write_in(Path::new("Documents"), "acme", "Acme", "0.1.0", &bridge()).unwrap_err(); + assert!(err.contains("documents folder"), "{err}"); + } +} diff --git a/crates/ledger-host/src/lib.rs b/crates/ledger-host/src/lib.rs index 43d4cad2..119e700d 100644 --- a/crates/ledger-host/src/lib.rs +++ b/crates/ledger-host/src/lib.rs @@ -20,6 +20,7 @@ pub mod app_server; pub mod bridge; pub mod channel; pub mod commands; +pub mod extension; pub mod host; pub mod knobs; pub mod lease; @@ -30,6 +31,24 @@ pub mod tokens; pub mod update; pub mod web; +/// The version of the program being run, set by its `main` (this crate's +/// own is the fallback: the packages rewrite only the program's, whose +/// `Cargo.toml` is the one source of the version, WB-pkg-6). +static PROGRAM_VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new(); + +/// Say which version this program is. +pub fn set_program_version(version: &'static str) { + let _ = PROGRAM_VERSION.set(version); +} + +/// This program's version. +pub fn program_version() -> &'static str { + PROGRAM_VERSION + .get() + .copied() + .unwrap_or(env!("CARGO_PKG_VERSION")) +} + /// How a mode stops when it can't go on: the reason is already printed, /// and the number is the process's exit code. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/ledger-host/src/update.rs b/crates/ledger-host/src/update.rs index 4c519f40..dea7e848 100644 --- a/crates/ledger-host/src/update.rs +++ b/crates/ledger-host/src/update.rs @@ -90,22 +90,7 @@ const STAGED: &str = "staged"; const FEED_FILE: &str = "feed"; const CHECKED: &str = "checked"; -/// The version of the program being run, set by its `main` (this crate's -/// own is the fallback: the packages rewrite only the program's). -static PROGRAM_VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new(); - -/// Say which version this program is. -pub fn set_program_version(version: &'static str) { - let _ = PROGRAM_VERSION.set(version); -} - -/// This program's version. -pub fn program_version() -> &'static str { - PROGRAM_VERSION - .get() - .copied() - .unwrap_or(env!("CARGO_PKG_VERSION")) -} +pub use crate::{program_version, set_program_version}; const MAX_MANIFEST: usize = 1 << 20; const MAX_PROGRAM: u64 = 1 << 30; From 90f663ed5431f5ad6fda16fe5f68e45aa5cf4754 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:35:17 -0700 Subject: [PATCH 04/11] feat(app): the window tells when a newer version exists and where to get it (P15 C1) Update is an ordinary app update: the newer package installed over the old one. The program's part is to say one exists. Once a day, on a thread of its own, it reads one small file a release publishes (latest.json: only a version number is taken from it; where to get the update is a fixed address in the program) and notes the answer in the data root's updates folder. A higher x.y.z shows a standing notice with a button that opens the download page and the words that books, keys and connections stay. Check for updates does the same look at once on every platform; where a program may replace itself with a signed release it also stages one as before. A macOS app is never replaced one file at a time (that breaks its signature): it is treated as managed, and says to drag the new app over the old. Window prose names the product Wanderbooks. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/src/main.rs | 9 + crates/ledger-gui/src/owner.rs | 82 ++++++- crates/ledger-gui/src/welcome.rs | 2 +- crates/ledger-gui/tests/update_notice.rs | 59 ++++- crates/ledger-host/src/commands.rs | 60 ++--- crates/ledger-host/src/lib.rs | 1 + crates/ledger-host/src/newer.rs | 289 +++++++++++++++++++++++ crates/ledger-host/src/update.rs | 57 ++++- 8 files changed, 510 insertions(+), 49 deletions(-) create mode 100644 crates/ledger-host/src/newer.rs diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index a4940241..3bc9c36b 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -409,6 +409,15 @@ impl ledger_gui::owner::Owner for ViewerOwner { }) } + fn newer_version(&self) -> Option { + ledger_host::commands::newer_version(&self.common).map(|(version, page)| { + ledger_gui::owner::NewerVersion { + version, + page: page.to_string(), + } + }) + } + fn check_for_updates(&self) -> Result, String> { ledger_host::commands::check_for_updates(&self.common).map(|l| vec![l]) } diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index c9289be6..0f459d62 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -474,6 +474,11 @@ pub trait Owner: Send + Sync { fn check_for_updates(&self) -> Result, String> { Err("not here".into()) } + /// A newer version exists, and where to get it (WB-pkg-3): what the + /// program's daily look found. Cheap: called every few seconds. + fn newer_version(&self) -> Option { + None + } /// Accept the waiting update: the books' host installs it and restarts /// onto it when no call is running, the books staying open. fn apply_update(&self) -> Result, String> { @@ -486,6 +491,16 @@ pub trait Owner: Send + Sync { } } +/// A newer version of the program that the person may get and install over +/// this one (WB-pkg-3). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NewerVersion { + /// Its version. + pub version: String, + /// The page to get it from: the program's own, never a feed's. + pub page: String, +} + /// The Claude desktop extension the Connect page made (WB-pkg-5). #[derive(Clone, Debug, PartialEq, Eq)] pub struct ExtensionMade { @@ -642,6 +657,8 @@ pub struct OwnerMenu { /// The update waiting, as last read, and when (re-read every few /// seconds and after any job). update: Option<(std::time::Instant, Option)>, + /// A newer version the person may get, as last read, and when. + newer: Option<(std::time::Instant, Option)>, /// The tab's threads: every job is one of them (INVARIANT 6). jobs: crate::jobs::Spawner, } @@ -687,6 +704,23 @@ impl OwnerMenu { self.update.as_ref().and_then(|(_, u)| u.clone()) } + /// A newer version to get, if any (read now and then, not every frame). + fn newer_version( + &mut self, + ctx: &egui::Context, + owner: &Arc, + ) -> Option { + if self + .newer + .as_ref() + .is_none_or(|(at, _)| at.elapsed() > UPDATE_LOOK) + { + self.newer = Some((std::time::Instant::now(), owner.newer_version())); + } + ctx.request_repaint_after(UPDATE_LOOK); + self.newer.as_ref().and_then(|(_, n)| n.clone()) + } + /// The standing notices above the page: an update waiting for the /// owner's accept, and a format upgrade the books wait for, whose /// go-ahead is asked for once each open (INVARIANT 5). @@ -708,7 +742,7 @@ impl OwnerMenu { ui.horizontal_wrapped(|ui| { ui.label( RichText::new(format!( - "{} Version {} of wanderbooks is ready.", + "{} Version {} of Wanderbooks is ready.", icon::ARROW_FAT_UP, update.version )) @@ -738,12 +772,48 @@ impl OwnerMenu { ui.ctx(), ( "Update".into(), - Effect::Changes("Updating wanderbooks"), + Effect::Changes("Updating Wanderbooks"), work, ), ); } } + // No update of the program's own is waiting: is a newer version + // out for the person to get and install over this one? + else if let Some(newer) = self.newer_version(ui.ctx(), &owner) { + let p = crate::theme::pal(ui.ctx()); + egui::Frame::new() + .fill(p.warning_soft) + .inner_margin(egui::Margin::symmetric(20, 10)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new(format!( + "{} Version {} of Wanderbooks is available.", + icon::ARROW_FAT_UP, + newer.version + )) + .font(crate::theme::semibold(13.0)) + .color(p.warning), + ); + ui.label( + RichText::new( + "Download it and install it over this one. Your books, keys and connections stay as they are.", + ) + .font(crate::theme::regular(13.0)) + .color(p.text), + ); + if ui + .button("Open the download page") + .on_hover_text(newer.page.clone()) + .clicked() + { + ui.ctx().open_url(egui::OpenUrl::new_tab(newer.page.clone())); + } + }); + }); + } let Some(upgrade) = books.format_upgrade.clone() else { return; }; @@ -771,7 +841,7 @@ impl OwnerMenu { ); ui.label( RichText::new( - "An older version of wanderbooks wrote them. They work on their old format until you agree; what needs the new one is refused.", + "An older version of Wanderbooks wrote them. They work on their old format until you agree; what needs the new one is refused.", ) .font(crate::theme::regular(13.0)) .color(p.text), @@ -886,7 +956,7 @@ impl OwnerMenu { ui.separator(); if ui .button(format!("{} Check for updates", icon::ARROWS_CLOCKWISE)) - .on_hover_text("Look for a newer version of wanderbooks now") + .on_hover_text("Look for a newer version of Wanderbooks now") .clicked() { let o = owner.clone(); @@ -905,7 +975,7 @@ impl OwnerMenu { let o = owner.clone(); start = Some(( "Update".into(), - Effect::Changes("Updating wanderbooks"), + Effect::Changes("Updating Wanderbooks"), Box::new(move || o.apply_update()), )); } @@ -1167,7 +1237,7 @@ fn upgrade_dialog( ui.heading("Upgrade these books' format?"); ui.add_space(4.0); ui.label(format!( - "An older version of wanderbooks wrote these books, in journal format {}. The upgrade adds {}.", + "An older version of Wanderbooks wrote these books, in journal format {}. The upgrade adds {}.", form.upgrade.from.format, form.upgrade.adds().join(", ") )); diff --git a/crates/ledger-gui/src/welcome.rs b/crates/ledger-gui/src/welcome.rs index a03e5954..e8a123eb 100644 --- a/crates/ledger-gui/src/welcome.rs +++ b/crates/ledger-gui/src/welcome.rs @@ -158,7 +158,7 @@ impl Welcome { ui.vertical_centered(|ui| { ui.set_max_width(640.0); ui.add_space(36.0); - ui.label(RichText::new("Welcome to wanderbooks").font(crate::theme::bold(28.0))); + ui.label(RichText::new("Welcome to Wanderbooks").font(crate::theme::bold(28.0))); ui.label( RichText::new( "Your company's books, kept by an assistant and checked by you. A few short steps; nothing here needs a terminal.", diff --git a/crates/ledger-gui/tests/update_notice.rs b/crates/ledger-gui/tests/update_notice.rs index 91d3be45..8375bd14 100644 --- a/crates/ledger-gui/tests/update_notice.rs +++ b/crates/ledger-gui/tests/update_notice.rs @@ -21,6 +21,7 @@ use std::sync::{Arc, Mutex, OnceLock}; struct Fake { asked: Mutex>, staged: Mutex, + newer: Mutex, } impl Fake { @@ -57,6 +58,12 @@ impl Owner for Fake { staged_at: "2026-10-30T08:00:00Z".into(), }) } + fn newer_version(&self) -> Option { + (*self.newer.lock().unwrap()).then(|| ledger_gui::owner::NewerVersion { + version: "9.2.0".into(), + page: "https://example.test/releases/latest".into(), + }) + } fn check_for_updates(&self) -> Result, String> { self.said("check"); *self.staged.lock().unwrap() = true; @@ -159,7 +166,7 @@ fn the_menu_checks_for_updates_and_a_waiting_update_shows_a_notice_that_accepts( // owner, and the notice goes once it is installed. for _ in 0..60 { h.run_steps(2); - if h.query_by_label_contains("Version 9.1.0 of wanderbooks is ready") + if h.query_by_label_contains("Version 9.1.0 of Wanderbooks is ready") .is_some() { break; @@ -167,7 +174,7 @@ fn the_menu_checks_for_updates_and_a_waiting_update_shows_a_notice_that_accepts( std::thread::sleep(std::time::Duration::from_millis(100)); } assert!( - h.query_by_label_contains("Version 9.1.0 of wanderbooks is ready") + h.query_by_label_contains("Version 9.1.0 of Wanderbooks is ready") .is_some(), "no notice" ); @@ -194,3 +201,51 @@ fn books_outside_a_data_root_have_no_update_notice() { assert!(h.query_by_label_contains("is ready.").is_none()); *f.staged.lock().unwrap() = false; } + +/// WB-pkg-3: with no update of the program's own waiting, a newer version +/// the daily look found is told in a standing notice that says where to +/// get it and that books, keys and connections stay; an update that is +/// waiting is the only notice shown (one at a time). +#[test] +fn a_newer_version_is_told_with_where_to_get_it() { + let _alone = alone(); + let f = fake(); + *f.newer.lock().unwrap() = true; + let (_dir, _book, b) = books(true); + let mut h = harness(b); + for _ in 0..60 { + h.run_steps(2); + if h.query_by_label_contains("Version 9.2.0 of Wanderbooks is available") + .is_some() + { + break; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + assert!( + h.query_by_label_contains("Version 9.2.0 of Wanderbooks is available") + .is_some(), + "no notice" + ); + assert!( + h.query_by_label_contains("Your books, keys and connections stay as they are") + .is_some() + ); + assert!(h.query_by_label("Open the download page").is_some()); + // One notice at a time: a staged update wins. + *f.staged.lock().unwrap() = true; + for _ in 0..60 { + h.run_steps(2); + if h.query_by_label_contains("is ready.").is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + assert!(h.query_by_label_contains("is ready.").is_some()); + assert!( + h.query_by_label_contains("Version 9.2.0 of Wanderbooks is available") + .is_none() + ); + *f.staged.lock().unwrap() = false; + *f.newer.lock().unwrap() = false; +} diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 73797754..be17a3d0 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -1525,39 +1525,45 @@ pub fn update_waiting(_common: &Common) -> Option { None } -/// "Check for updates": look at the feed now, whatever the daily look -/// last did, and stage a newer release if there is one (it never swaps -/// the program: accepting is [`apply_update`]). What came of it. -#[cfg(unix)] +/// "Check for updates": say whether a newer version exists and where to +/// get it (the note of [`crate::newer`], looked at now whatever the last +/// look was). Where a program may replace itself (an AppImage, a program +/// put somewhere by hand, with a release key) a newer release is also +/// downloaded and checked, for [`apply_update`] (it never swaps the +/// program: accepting is). What came of it. pub fn check_for_updates(common: &Common) -> Result { let found = ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; - let mine = crate::update::program_version(); - if let crate::update::Install::PackageManaged(manager) = crate::update::this_install()? { - return Err(format!( - "this install is updated by {manager}, not here: use the package manager" - )); - } - match crate::update::stage_if_due(&found, mine, Duration::ZERO) { - Ok(Some(version)) => Ok(format!( - "Version {version} is downloaded and checked. Accept it to start using it." - )), - Ok(None) => Ok(match update_waiting(common) { - Some(u) => format!( - "Version {} is downloaded and checked. Accept it to start using it.", - u.version - ), - None => format!("You have the newest version ({mine})."), - }), - Err(why) => Err(why.to_string()), + let mine = crate::program_version(); + #[cfg(unix)] + if let Ok(crate::update::Install::SelfUpdating(_)) = crate::update::this_install() { + match crate::update::stage_if_due(&found, mine, Duration::ZERO) { + Ok(Some(version)) => { + return Ok(format!( + "Version {version} is downloaded and checked. Accept it to start using it." + )); + } + Ok(None) => { + if let Some(u) = update_waiting(common) { + return Ok(format!( + "Version {} is downloaded and checked. Accept it to start using it.", + u.version + )); + } + } + // No release key or local feed: the look below still tells. + Err(_) => {} + } } + crate::newer::check_now(found.path(), mine) } -/// Checking for updates isn't built for this platform: say so, and -/// change nothing. -#[cfg(not(unix))] -pub fn check_for_updates(_common: &Common) -> Result { - Err(NO_SELF_UPDATE.into()) +/// The newer version the window may tell the person of, with where to get +/// it: what the last (daily) look found, a look begun when one is due. +pub fn newer_version(common: &Common) -> Option<(String, &'static str)> { + let found = ledger_store::root::Root::find(common.root.as_deref()).ok()?; + let version = crate::newer::found_and_refresh(found.path(), crate::program_version())?; + Some((version, crate::newer::DOWNLOAD_PAGE)) } /// Accept the staged update: the books' host installs it and restarts diff --git a/crates/ledger-host/src/lib.rs b/crates/ledger-host/src/lib.rs index 119e700d..67380eaa 100644 --- a/crates/ledger-host/src/lib.rs +++ b/crates/ledger-host/src/lib.rs @@ -24,6 +24,7 @@ pub mod extension; pub mod host; pub mod knobs; pub mod lease; +pub mod newer; pub mod opener; mod start; pub mod tokens; diff --git a/crates/ledger-host/src/newer.rs b/crates/ledger-host/src/newer.rs new file mode 100644 index 00000000..6c55c2d1 --- /dev/null +++ b/crates/ledger-host/src/newer.rs @@ -0,0 +1,289 @@ +//! "A newer version exists, and where to get it" (plan P15 unit C1, 3.1: +//! update is an ordinary app update). +//! +//! The installed program is replaced by installing the newer package over +//! it (the installer on Windows, the `.dmg` on macOS, the package manager +//! or a new AppImage on Linux). The program's part is to tell the person +//! that one exists. This module is that part, on every platform: a look at +//! one small file a release publishes, at most once a day, and a note of +//! what it found in the data root. +//! +//! ```text +//! GOAL: a person who installed Wanderbooks is told, in the window, when a +//! newer version is out, and where to get it; nothing is downloaded +//! or installed by the program. +//! SOURCE: WB-pkg-3; plan/p15-app-and-relay.md 3.1 ("Update becomes an +//! ordinary app update"), D-24 (anything the program installs by +//! itself must be verified against our own release keys: this +//! installs nothing, so it needs none). +//! INVARIANTS: +//! 1. Only a version number is read from the feed: the place to get the +//! update is a fixed address in this program ([`DOWNLOAD_PAGE`]), +//! never one the feed names. A feed that lies can at most say a +//! number. +//! 2. The feed is looked at at most once a day ([`EVERY`]); a failed look +//! counts as a look (no hammering) and is never an error the person +//! sees. The look is never in the window's own thread. +//! 3. A version is "newer" only when it is a higher `x.y.z` than this +//! program's; anything else is no version of ours. +//! 4. The note is a small file in the data root's `updates/` folder, +//! private to the account; the books are not read or changed. +//! 5. The look sends no version, company, key or identifier of the +//! person: a plain request for a public file. +//! SCENARIOS: +//! 1. IF the feed says 0.2.0 and this is 0.1.0: SHOULD say 0.2.0 is +//! newer, for a day. +//! 2. IF the feed says the same, an older, or a word: SHOULD say nothing. +//! 3. IF the feed can't be reached: SHOULD say nothing and look again +//! tomorrow. +//! ``` + +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +/// The small file a release publishes: `{"version": "x.y.z"}`. +pub const FEED: &str = "https://github.com/swaits/wanderbooks/releases/latest/download/latest.json"; + +/// Where a person gets the newest version (INVARIANT 1). +pub const DOWNLOAD_PAGE: &str = "https://github.com/swaits/wanderbooks/releases/latest"; + +/// How often the feed is looked at (INVARIANT 2). +pub const EVERY: Duration = Duration::from_secs(24 * 60 * 60); + +/// The note's name in `/updates/`. +const NOTE: &str = "newer.json"; + +/// The longest feed read, in bytes. +const MAX_FEED: usize = 4096; + +/// `1.2.3` as numbers; anything else (a pre-release, a `v`) is no version +/// of ours. +pub fn parse_version(text: &str) -> Option<(u64, u64, u64)> { + let mut parts = text.split('.'); + let mut next = || -> Option { + let p = parts.next()?; + (!p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) + .then(|| p.parse().ok()) + .flatten() + }; + let v = (next()?, next()?, next()?); + parts.next().is_none().then_some(v) +} + +/// Whether `theirs` is a version higher than `mine` (INVARIANT 3). +pub fn is_newer(mine: &str, theirs: &str) -> bool { + parse_version(theirs) + .zip(parse_version(mine)) + .is_some_and(|(theirs, mine)| theirs > mine) +} + +/// The version the feed's text names (INVARIANT 1): nothing else of it is +/// read. +pub fn version_in_feed(text: &str) -> Option { + #[derive(Deserialize)] + struct Feed { + version: String, + } + let feed: Feed = serde_json::from_str(text).ok()?; + parse_version(&feed.version).map(|_| feed.version) +} + +/// What the last look found. +#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +struct Note { + /// Seconds since 1970 when the look was made. + looked: u64, + /// The version the feed named, when it named one. + version: Option, +} + +fn note_path(root: &Path) -> PathBuf { + root.join("updates").join(NOTE) +} + +fn read_note(root: &Path) -> Option { + let bytes = std::fs::read(note_path(root)).ok()?; + serde_json::from_slice(&bytes).ok() +} + +fn now_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +/// The newer version the last look found, if it found one newer than +/// `mine` (a note about a version this program already is, or is past, is +/// nothing). +pub fn found(root: &Path, mine: &str) -> Option { + read_note(root)? + .version + .filter(|theirs| is_newer(mine, theirs)) +} + +/// Whether the feed is due to be looked at at `now` (INVARIANT 2). +pub fn due(root: &Path, now: u64) -> bool { + read_note(root) + .is_none_or(|n| now.saturating_sub(n.looked) >= EVERY.as_secs() || n.looked > now) +} + +/// Look at the feed through `fetch` (its text) and note what it said, at +/// `now`. A feed that can't be read is noted as a look with nothing found +/// (INVARIANT 2). The newer version, if there is one. +pub fn look( + root: &Path, + mine: &str, + now: u64, + fetch: impl FnOnce() -> Result, +) -> Result, String> { + let said = fetch(); + let version = said.as_deref().ok().and_then(version_in_feed); + let note = Note { + looked: now, + version: version.clone(), + }; + let dir = root.join("updates"); + ledger_link::private::make_dir(&dir).map_err(|e| e.kind().to_string())?; + let bytes = serde_json::to_vec(¬e).map_err(|e| e.to_string())?; + ledger_link::private::write(¬e_path(root), &bytes).map_err(|e| e.kind().to_string())?; + match said { + Ok(_) => Ok(version.filter(|theirs| is_newer(mine, theirs))), + Err(why) => Err(why), + } +} + +/// The feed, over https: a plain request for a public file (INVARIANT 5). +pub fn fetch_feed() -> Result { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|e| e.to_string())?; + rt.block_on(async { + let mut response = reqwest::Client::new() + .get(FEED) + .timeout(Duration::from_secs(20)) + .send() + .await + .and_then(|r| r.error_for_status()) + .map_err(|e| format!("can't look for a newer version: {}", e.without_url()))?; + let mut bytes = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .map_err(|e| format!("can't look for a newer version: {}", e.without_url()))? + { + bytes.extend_from_slice(&chunk); + if bytes.len() > MAX_FEED { + return Err("the release note is larger than it can be".to_string()); + } + } + String::from_utf8(bytes).map_err(|_| "the release note is not text".to_string()) + }) +} + +/// "Check for updates", now: look whatever the last look was, and say +/// what came of it in plain words. +pub fn check_now(root: &Path, mine: &str) -> Result { + match look(root, mine, now_secs(), fetch_feed)? { + Some(version) => Ok(format!( + "Version {version} of Wanderbooks is available (this is {mine}). Get it at {DOWNLOAD_PAGE} and install it over this one: your books, keys and connections stay as they are." + )), + None => Ok(format!("You have the newest version ({mine}).")), + } +} + +/// Whether a background look is under way. +static LOOKING: AtomicBool = AtomicBool::new(false); + +/// The newer version known, and, when a look is due, one begun on a thread +/// of its own (INVARIANT 2): cheap, for the window to call every few +/// seconds. +pub fn found_and_refresh(root: &Path, mine: &'static str) -> Option { + if due(root, now_secs()) + && LOOKING + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) + .is_ok() + { + let root = root.to_path_buf(); + let started = std::thread::Builder::new() + .name("wanderbooks-newer".into()) + .spawn(move || { + // Whatever it came to, it was a look (noted), and the next + // is a day away. + let _ = look(&root, mine, now_secs(), fetch_feed); + LOOKING.store(false, Ordering::SeqCst); + }); + if started.is_err() { + LOOKING.store(false, Ordering::SeqCst); + } + } + found(root, mine) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_a_higher_plain_version_is_newer() { + assert!(is_newer("0.1.0", "0.2.0")); + assert!(is_newer("0.1.9", "0.1.10")); + assert!(!is_newer("0.2.0", "0.2.0")); + assert!(!is_newer("0.2.0", "0.1.9")); + for odd in ["v0.3.0", "0.3", "0.3.0-rc1", "", "latest", "1.2.3.4"] { + assert!(!is_newer("0.1.0", odd), "{odd}"); + } + } + + #[test] + fn the_feed_gives_a_version_and_nothing_else() { + assert_eq!( + version_in_feed(r#"{"version":"0.2.0","url":"https://evil.example/x"}"#), + Some("0.2.0".into()) + ); + assert_eq!(version_in_feed(r#"{"version":"soon"}"#), None); + assert_eq!(version_in_feed("not json"), None); + // Where to get it is this program's, never the feed's. + assert!(DOWNLOAD_PAGE.starts_with("https://github.com/swaits/wanderbooks/")); + } + + #[test] + fn a_look_is_noted_and_the_next_is_a_day_away() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + assert!(due(root, 1_000)); + let said = look(root, "0.1.0", 1_000, || Ok(r#"{"version":"0.2.0"}"#.into())).unwrap(); + assert_eq!(said, Some("0.2.0".into())); + assert_eq!(found(root, "0.1.0"), Some("0.2.0".into())); + assert!(!due(root, 1_000 + EVERY.as_secs() - 1)); + assert!(due(root, 1_000 + EVERY.as_secs())); + // A clock that went backwards is due, not stuck for years. + assert!(due(root, 10)); + // Once this program is that version, nothing is newer. + assert_eq!(found(root, "0.2.0"), None); + } + + #[test] + fn a_failed_look_says_nothing_and_still_counts() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + look(root, "0.1.0", 1_000, || Ok(r#"{"version":"0.2.0"}"#.into())).unwrap(); + let err = look(root, "0.1.0", 2_000, || Err("offline".into())).unwrap_err(); + assert_eq!(err, "offline"); + assert_eq!(found(root, "0.1.0"), None, "what was found is forgotten"); + assert!(!due(root, 2_001), "the failed look counts"); + } + + #[cfg(unix)] + #[test] + fn the_note_is_private() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + look(dir.path(), "0.1.0", 1, || Ok("{}".into())).unwrap(); + let mode = |p: PathBuf| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(dir.path().join("updates")), 0o700); + assert_eq!(mode(note_path(dir.path())), 0o600); + } +} diff --git a/crates/ledger-host/src/update.rs b/crates/ledger-host/src/update.rs index dea7e848..15d2d8f4 100644 --- a/crates/ledger-host/src/update.rs +++ b/crates/ledger-host/src/update.rs @@ -136,6 +136,17 @@ pub fn install_kind(exe: &Path, appimage: Option<&Path>) -> Install { if let Some(image) = appimage.filter(|p| p.is_file()) { return Install::SelfUpdating(image.to_path_buf()); } + // A macOS app is signed whole: one file replaced inside it breaks the + // signature, so it is only ever replaced whole, by the person (the + // newer .dmg), never by this program (WB-pkg-3). + if exe + .ancestors() + .skip(1) + .take(3) + .any(|dir| dir.extension().is_some_and(|e| e == "app") && dir.join("Contents").is_dir()) + { + return Install::PackageManaged("app".to_string()); + } if let Some(prefix) = exe.parent().and_then(Path::parent) && let Ok(text) = std::fs::read_to_string(prefix.join("share/wanderbooks/install-method")) { @@ -153,25 +164,20 @@ pub fn this_install() -> Result { } fn refuse_package_managed(manager: &str, what: &str) -> Failure { + if manager == "app" { + return format!( + "this is the macOS app, which is replaced whole and never one file at a time: get the newer Wanderbooks at {} and drag it over this one", + crate::newer::DOWNLOAD_PAGE + ) + .into(); + } format!( "this install is managed by {manager}, which also {what} it: use the package manager (our apt and dnf repositories keep every release, and the AUR keeps old PKGBUILDs)" ) .into() } -/// `1.2.3` as numbers; anything else (a pre-release, a `v`) is no version -/// of ours. -pub fn parse_version(text: &str) -> Option<(u64, u64, u64)> { - let mut parts = text.split('.'); - let mut next = || -> Option { - let p = parts.next()?; - (!p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) - .then(|| p.parse().ok()) - .flatten() - }; - let v = (next()?, next()?, next()?); - parts.next().is_none().then_some(v) -} +pub use crate::newer::parse_version; fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() @@ -966,6 +972,31 @@ mod tests { ); } + /// WB-pkg-3: a macOS app is signed whole, so this program never + /// replaces a file inside one; the person replaces the whole app. + #[test] + fn a_macos_app_is_never_updated_in_place() { + let dir = tempfile::tempdir().unwrap(); + let macos = dir.path().join("Wanderbooks.app/Contents/MacOS"); + std::fs::create_dir_all(&macos).unwrap(); + let exe = macos.join("wanderbooks"); + std::fs::write(&exe, b"x").unwrap(); + assert_eq!( + install_kind(&exe, None), + Install::PackageManaged("app".into()) + ); + let said = refuse_package_managed("app", "updates").to_string(); + assert!(said.contains("replaced whole"), "{said}"); + assert!(said.contains(crate::newer::DOWNLOAD_PAGE), "{said}"); + // A folder that only happens to be called .app, with no bundle in + // it, is not one. + let plain = dir.path().join("tools.app/bin"); + std::fs::create_dir_all(&plain).unwrap(); + let exe = plain.join("wanderbooks"); + std::fs::write(&exe, b"x").unwrap(); + assert_eq!(install_kind(&exe, None), Install::SelfUpdating(exe)); + } + #[test] fn a_public_key_is_read_in_every_form_minisign_and_the_packager_write_it() { let bare = "RWQdrs7W5/jf6drdD0G/ymxFmRWYAIOyggYlubz4NQzdQm5e/Fj0nrb0"; From 8e3db472fa9ff1ee3bfbafe60a6661142d933a24 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:41:22 -0700 Subject: [PATCH 05/11] feat(packaging): a per-user Windows installer, a universal macOS app and dmg, desktop entries with the icon (P15 C1) Windows: a hand-written NSIS script (per user, no administrator prompt, installs under the profile's Programs folder; one program file; a Start Menu entry named Wanderbooks with the icon; an uninstaller listed in Settings > Apps that removes only what the installer put in its own folder and never names the data folder). The installer asks the person to quit the app fully before it replaces or removes the program. An optional Authenticode signing step runs only when its secrets exist. macOS: the .app is assembled by a script (Info.plist with the bundle identifier, version, name, Documents-folder purpose string; the one program at Contents/MacOS/wanderbooks; the licences), signed with the hardened runtime and an empty entitlements file that says why, put in a dmg with an Applications shortcut, notarized and stapled when the owner's Apple identity is given and skipped with a notice when not. The program is one universal binary (lipo of the two release builds). Linux: both desktop entries name the window's app id and the icon; the rpm now installs the icon; the deb, the pacman tarball and the rpm all carry LICENSE-MIT and LICENSE-APACHE beside the notices. One version: deploy/packaging/version.sh reads crates/ledger-cli's Cargo.toml; every script takes it from there. Tests read the scripts and build a bundle with a stand-in program. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/Cargo.toml | 3 + crates/ledger-cli/tests/packaging.rs | 570 +++++++++++++++++++ deploy/packaging/Info.plist | 12 - deploy/packaging/build-linux.sh | 4 + deploy/packaging/build-macos.sh | 33 -- deploy/packaging/icons/wanderbooks.ico | Bin 0 -> 370070 bytes deploy/packaging/macos/Info.plist.in | 48 ++ deploy/packaging/macos/build-macos.sh | 143 +++++ deploy/packaging/macos/entitlements.plist | 29 + deploy/packaging/macos/import-certificate.sh | 24 + deploy/packaging/packager-macos.toml | 36 -- deploy/packaging/packager.toml | 4 + deploy/packaging/version.sh | 21 + deploy/packaging/wanderbooks-static.desktop | 8 +- deploy/packaging/wanderbooks.desktop | 1 + deploy/packaging/windows/build-windows.sh | 63 ++ deploy/packaging/windows/sign-windows.ps1 | 36 ++ deploy/packaging/windows/wanderbooks.nsi | 144 +++++ justfile | 17 +- 19 files changed, 1110 insertions(+), 86 deletions(-) create mode 100644 crates/ledger-cli/tests/packaging.rs delete mode 100644 deploy/packaging/Info.plist delete mode 100755 deploy/packaging/build-macos.sh create mode 100644 deploy/packaging/icons/wanderbooks.ico create mode 100644 deploy/packaging/macos/Info.plist.in create mode 100755 deploy/packaging/macos/build-macos.sh create mode 100644 deploy/packaging/macos/entitlements.plist create mode 100755 deploy/packaging/macos/import-certificate.sh delete mode 100644 deploy/packaging/packager-macos.toml create mode 100755 deploy/packaging/version.sh create mode 100755 deploy/packaging/windows/build-windows.sh create mode 100644 deploy/packaging/windows/sign-windows.ps1 create mode 100644 deploy/packaging/windows/wanderbooks.nsi diff --git a/crates/ledger-cli/Cargo.toml b/crates/ledger-cli/Cargo.toml index 7d8e19cd..ff19b180 100644 --- a/crates/ledger-cli/Cargo.toml +++ b/crates/ledger-cli/Cargo.toml @@ -82,5 +82,8 @@ assets = [ { source = "target/release/wanderbooks", dest = "/usr/bin/wanderbooks", mode = "0755" }, { source = "deploy/packaging/install-method-rpm", dest = "/usr/share/wanderbooks/install-method", mode = "0644" }, { source = "deploy/packaging/wanderbooks-static.desktop", dest = "/usr/share/applications/wanderbooks.desktop", mode = "0644" }, + { source = "deploy/packaging/icons/512x512.png", dest = "/usr/share/icons/hicolor/512x512/apps/wanderbooks.png", mode = "0644" }, + { source = "LICENSE-MIT", dest = "/usr/share/doc/wanderbooks/LICENSE-MIT", mode = "0644" }, + { source = "LICENSE-APACHE", dest = "/usr/share/doc/wanderbooks/LICENSE-APACHE", mode = "0644" }, { source = "THIRD-PARTY-NOTICES.txt", dest = "/usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt", mode = "0644" }, ] diff --git a/crates/ledger-cli/tests/packaging.rs b/crates/ledger-cli/tests/packaging.rs new file mode 100644 index 00000000..ad61926e --- /dev/null +++ b/crates/ledger-cli/tests/packaging.rs @@ -0,0 +1,570 @@ +//! The packages (plan P15 unit C1; WB-pkg-1 to WB-pkg-7): what can be checked +//! on Linux about the Windows installer, the macOS app, the Linux entries and +//! the one source of the version. For Windows and macOS the release workflow +//! is the real test (each packaging step fails loudly); these tests keep the +//! files it builds from true to the rules. +//! +//! ```text +//! GOAL: an installed Wanderbooks is one executable at a stable path, named +//! Wanderbooks everywhere a person sees it, with the licences beside +//! it; installing a newer one over it, or uninstalling it, never +//! touches the person's books. +//! SOURCE: WB-pkg-1 (installs like a normal program), WB-pkg-2 (one +//! executable, a stable bridge path), WB-pkg-6 (one version, one +//! name), WB-pkg-7 (the release carries the licences); D-77. +//! INVARIANTS: +//! 1. The version is written once (ledger-cli's Cargo.toml); the packaging +//! scripts read it through deploy/packaging/version.sh. +//! 2. The Windows installer is per user (no administrator), installs one +//! program, and its uninstaller names nothing but what the installer +//! put in its own folder: no recursive removal, no wildcard, no data +//! folder. +//! 3. The macOS bundle holds one program at Contents/MacOS/wanderbooks, an +//! Info.plist whose identifier, name, version and executable agree with +//! the scripts, and the licences. +//! 4. The Linux desktop entries launch plain `wanderbooks` (an AppImage's +//! launcher appends what it is given) with the icon, the name, and the +//! window's app id. +//! 5. Every package carries LICENSE-MIT, LICENSE-APACHE and +//! THIRD-PARTY-NOTICES.txt. +//! SCENARIOS: +//! 1. The bundle script run on Linux with a stand-in program makes a +//! bundle whose plist and files match the rules above. +//! ``` + +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +fn read(path: &str) -> String { + std::fs::read_to_string(root().join(path)).unwrap_or_else(|e| panic!("{path}: {e}")) +} + +/// The lines of `text` that are not comments (`;` for NSIS, `#` for shell +/// and TOML). +fn code(text: &str) -> Vec<&str> { + text.lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with(';') && !l.starts_with('#')) + .collect() +} + +const LICENCE_FILES: [&str; 3] = ["LICENSE-MIT", "LICENSE-APACHE", "THIRD-PARTY-NOTICES.txt"]; + +// ---- the version, written once --------------------------------------------------- + +#[cfg(unix)] +#[test] +fn the_version_is_written_once_and_every_script_reads_it_from_there() { + let out = Command::new("sh") + .arg(root().join("deploy/packaging/version.sh")) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + let said = String::from_utf8(out.stdout).unwrap(); + assert_eq!(said.trim(), env!("CARGO_PKG_VERSION")); + + // The Linux packager's own file carries a version the build script + // overwrites; it must not drift from the source. + let packager = read("deploy/packaging/packager.toml"); + let line = code(&packager) + .into_iter() + .find(|l| l.starts_with("version = ")) + .unwrap(); + assert_eq!(line, format!("version = \"{}\"", env!("CARGO_PKG_VERSION"))); + + // No packaging script or workflow assigns a literal version. + for file in [ + "deploy/packaging/windows/build-windows.sh", + "deploy/packaging/macos/build-macos.sh", + ".github/workflows/release.yml", + ] { + for line in code(&read(file)) { + let assigns = line.starts_with("version=") || line.starts_with("version:"); + let literal = line.split(['=', ':']).nth(1).is_some_and(|v| { + v.trim() + .trim_matches('"') + .chars() + .next() + .is_some_and(|c| c.is_ascii_digit()) + }); + assert!(!(assigns && literal), "{file}: a literal version: {line}"); + } + } + for file in [ + "deploy/packaging/windows/build-windows.sh", + "deploy/packaging/macos/build-macos.sh", + "deploy/packaging/build-linux.sh", + ] { + let text = read(file); + assert!( + text.contains("version.sh") || text.contains("ledger-cli/Cargo.toml"), + "{file} does not read the version from its one source" + ); + } +} + +#[cfg(unix)] +#[test] +fn a_version_that_is_not_three_numbers_is_refused() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(dir.path().join("deploy/packaging")).unwrap(); + std::fs::create_dir_all(dir.path().join("crates/ledger-cli")).unwrap(); + std::fs::copy( + root().join("deploy/packaging/version.sh"), + dir.path().join("deploy/packaging/version.sh"), + ) + .unwrap(); + for (toml, ok) in [ + ("version = \"0.2.0\"\n", true), + ("version = \"0.2.0-rc1\"\n", false), + ("version = \"two\"\n", false), + ("", false), + ] { + std::fs::write(dir.path().join("crates/ledger-cli/Cargo.toml"), toml).unwrap(); + let out = Command::new("sh") + .arg(dir.path().join("deploy/packaging/version.sh")) + .output() + .unwrap(); + assert_eq!(out.status.success(), ok, "{toml:?}: {out:?}"); + } +} + +// ---- Windows -------------------------------------------------------------------- + +#[test] +fn the_windows_installer_is_per_user_and_installs_one_program() { + let nsi = read("deploy/packaging/windows/wanderbooks.nsi"); + let lines = code(&nsi); + let has = |needle: &str| lines.iter().any(|l| l.contains(needle)); + // No administrator prompt; everything in the person's own profile. + assert!(has("RequestExecutionLevel user")); + assert!(has(r#"InstallDir "$LOCALAPPDATA\Programs\Wanderbooks""#)); + assert!( + !lines.iter().any(|l| l.contains("HKLM")), + "per-machine registry" + ); + assert!(!has("SetShellVarContext all"), "all users' Start Menu"); + // A Start Menu entry named Wanderbooks, with the icon. + assert!(has( + r#"CreateShortCut "$SMPROGRAMS\${NAME}.lnk" "$INSTDIR\wanderbooks.exe""# + )); + assert!(has(r#"!define NAME "Wanderbooks""#)); + assert!(has("wanderbooks.ico")); + // An uninstaller, listed in Settings > Apps, whose name is the product's. + assert!(has("WriteUninstaller")); + assert!(has(r#""DisplayName" "${NAME}""#)); + assert!(has("UninstallString")); + // One program: the only .exe installed besides the uninstaller. + let programs: Vec<&&str> = lines + .iter() + .filter(|l| l.starts_with("File ") && l.contains(".exe")) + .collect(); + assert_eq!(programs.len(), 1, "{programs:?}"); + assert!(programs[0].contains("/oname=wanderbooks.exe")); + // The licences travel with it. + for file in LICENCE_FILES { + assert!(has(&format!("/oname={file}")), "{file} is not installed"); + } +} + +/// WB-pkg-1: the uninstaller removes what the installer put in its own +/// folder and nothing else; the books are in the data folder, which it never +/// names. +#[test] +fn the_uninstaller_never_removes_the_books() { + let nsi = read("deploy/packaging/windows/wanderbooks.nsi"); + let lines = code(&nsi); + let start = lines + .iter() + .position(|l| l.starts_with(r#"Section "Uninstall""#)) + .expect("an uninstall section"); + let section = &lines[start..]; + let mut removals = 0; + for line in section { + let word = line.split_whitespace().next().unwrap_or(""); + if matches!(word, "Delete" | "RMDir" | "DeleteRegKey" | "DeleteRegValue") { + removals += 1; + assert!(!line.contains("/r"), "a recursive removal: {line}"); + assert!( + !line.contains('*') && !line.contains('?'), + "a wildcard: {line}" + ); + let ok = line.contains("$INSTDIR") + || line.contains("$SMPROGRAMS") + || line.contains("${UNINSTALL_KEY}") + || line.contains("${APP_KEY}"); + assert!( + ok, + "removes something that is not the program's own: {line}" + ); + } + } + assert!(removals >= 6, "the uninstaller removes the installed files"); + // The data folder, the roaming settings and the keys are named nowhere + // in the script's code (the comments say where the books are). + for line in &lines { + for data in [ + "$LOCALAPPDATA\\wanderbooks", + "$APPDATA", + "\\link", + "legacy", + "books\\", + ] { + assert!(!line.contains(data), "{data} named: {line}"); + } + } + // Only the registry keys of its own. + let keys: Vec<&&str> = lines + .iter() + .filter(|l| l.starts_with("!define") && l.contains("_KEY")) + .collect(); + assert_eq!(keys.len(), 2, "{keys:?}"); + assert!(keys[0].contains(r"Software\Microsoft\Windows\CurrentVersion\Uninstall\Wanderbooks")); + assert!(keys[1].contains(r"Software\Wanderbooks")); +} + +/// If NSIS is installed here, the script compiles with stand-in files +/// (the release workflow compiles it for real on Windows). +#[test] +fn the_installer_script_compiles_when_nsis_is_here() { + let Some(makensis) = std::env::var_os("PATH").and_then(|p| { + std::env::split_paths(&p) + .map(|d| d.join("makensis")) + .find(|f| f.is_file()) + }) else { + eprintln!( + "makensis is not installed here: the Windows job of the release workflow compiles the installer" + ); + return; + }; + let dir = tempfile::tempdir().unwrap(); + let p = dir.path(); + std::fs::write(p.join("wanderbooks.exe"), b"MZ").unwrap(); + for f in LICENCE_FILES { + std::fs::write(p.join(f), b"x").unwrap(); + } + std::fs::copy( + root().join("deploy/packaging/icons/wanderbooks.ico"), + p.join("wanderbooks.ico"), + ) + .unwrap(); + let out = Command::new(makensis) + .arg("-V2") + .arg(format!("-DVERSION={}", env!("CARGO_PKG_VERSION"))) + .arg(format!("-DPROGRAM={}", p.join("wanderbooks.exe").display())) + .arg(format!("-DICON={}", p.join("wanderbooks.ico").display())) + .arg(format!("-DLICENSES={}", p.display())) + .arg(format!("-DOUTFILE={}", p.join("setup.exe").display())) + .arg(root().join("deploy/packaging/windows/wanderbooks.nsi")) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stdout) + ); + assert!(p.join("setup.exe").metadata().unwrap().len() > 0); +} + +/// WB-pkg-2: on Windows the one executable is built for the GUI subsystem +/// (no console window for the app), and gives a terminal its words back. +#[test] +fn the_windows_program_opens_no_console_window_and_still_speaks_in_a_terminal() { + let main = read("crates/ledger-cli/src/main.rs"); + assert!( + main.contains( + r#"#![cfg_attr(all(windows, feature = "gui"), windows_subsystem = "windows")]"# + ) + ); + assert!(main.contains("console::attach_parent_console()")); + let console = read("crates/ledger-cli/src/console.rs"); + assert!(console.contains("AttachConsole(ATTACH_PARENT_PROCESS)")); + // The server child the app starts has no console window of its own. + assert!(read("crates/ledger-host/src/app_server.rs").contains("NO_WINDOW")); +} + +// ---- macOS ---------------------------------------------------------------------- + +/// The ``/value pairs of a plist's top-level dict, as text. Good enough +/// for the plain plists here (no nesting). +fn plist(text: &str) -> Vec<(String, String)> { + let mut pairs = Vec::new(); + let mut key: Option = None; + for line in text.lines().map(str::trim) { + if let Some(k) = line + .strip_prefix("") + .and_then(|l| l.strip_suffix("")) + { + assert!(key.is_none(), "a key with no value: {k}"); + key = Some(k.to_string()); + } else if let Some(k) = key.take_if(|_| line.starts_with('<') && !line.starts_with(" - - - LSMultipleInstancesProhibited - - NSSupportsAutomaticGraphicsSwitching - - - diff --git a/deploy/packaging/build-linux.sh b/deploy/packaging/build-linux.sh index ea84b556..88bad803 100755 --- a/deploy/packaging/build-linux.sh +++ b/deploy/packaging/build-linux.sh @@ -37,6 +37,7 @@ sed "s/^version = \".*\"/version = \"$version\"/ s#\"target/release\"#\"$PWD/$stage\"# s#\"deploy/packaging/#\"$PWD/deploy/packaging/# s#\"LICENSE-MIT\"#\"$PWD/LICENSE-MIT\"# + s#^\"LICENSE-APACHE\"#\"$PWD/LICENSE-APACHE\"# s#^\"THIRD-PARTY-NOTICES.txt\"#\"$PWD/THIRD-PARTY-NOTICES.txt\"#" \ deploy/packaging/packager.toml >"$config" # The AppImage tools are themselves AppImages; run them without FUSE. @@ -46,6 +47,9 @@ assets='assets = [ { source = "'$PWD/$stage'/wanderbooks", dest = "/usr/bin/wanderbooks", mode = "0755" }, { source = "deploy/packaging/install-method-rpm", dest = "/usr/share/wanderbooks/install-method", mode = "0644" }, { source = "deploy/packaging/wanderbooks-static.desktop", dest = "/usr/share/applications/wanderbooks.desktop", mode = "0644" }, + { source = "deploy/packaging/icons/512x512.png", dest = "/usr/share/icons/hicolor/512x512/apps/wanderbooks.png", mode = "0644" }, + { source = "LICENSE-MIT", dest = "/usr/share/doc/wanderbooks/LICENSE-MIT", mode = "0644" }, + { source = "LICENSE-APACHE", dest = "/usr/share/doc/wanderbooks/LICENSE-APACHE", mode = "0644" }, { source = "THIRD-PARTY-NOTICES.txt", dest = "/usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt", mode = "0644" }, ]' cargo generate-rpm -p crates/ledger-cli --set-metadata "version=\"$version\"" --set-metadata "$assets" -o "$out/" diff --git a/deploy/packaging/build-macos.sh b/deploy/packaging/build-macos.sh deleted file mode 100755 index f9e809f3..00000000 --- a/deploy/packaging/build-macos.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash -# The macOS bundle (P11a step 6), UNSIGNED, from the release program -# already built at target/release/wanderbooks (`cargo build --release -p -# ledger-cli`). Run on a Mac from the repository root: -# -# build-macos.sh [VERSION] -# -# Puts Wanderbooks_VERSION_.dmg into target/packages/VERSION/. It -# is not signed or notarized (step 5): Gatekeeper refuses it on a Mac -# that downloaded it, and the owner opens it with right-click > Open. -# Portable shell: macOS has BSD sed and no GNU mktemp options. -set -euo pipefail -own=$(sed -n 's/^version = "\(.*\)"/\1/p' crates/ledger-cli/Cargo.toml | head -n1) -version=${1:-$own} -out="target/packages/$version" -program=${WB_PROGRAM:-target/release/wanderbooks} -test -x "$program" || { echo "build the release program first: cargo build --release -p ledger-cli" >&2; exit 1; } -rm -rf "$out"; mkdir -p "$out" -stage="target/packages/.stage-$version" -rm -rf "$stage"; mkdir -p "$stage" -cp "$program" "$stage/wanderbooks" -config="$stage/packager.toml" -# cargo-packager reads paths relative to the config file, which is in the -# stage folder here, so they are made absolute. -sed -e "s/^version = \".*\"/version = \"$version\"/" \ - -e "s#^out-dir = .*#out-dir = \"$PWD/$out\"#" \ - -e "s#\"target/release\"#\"$PWD/$stage\"#" \ - -e "s#\"deploy/packaging/#\"$PWD/deploy/packaging/#" \ - -e "s#\"LICENSE-MIT\"#\"$PWD/LICENSE-MIT\"#" \ - deploy/packaging/packager-macos.toml >"$config" -cargo packager --config "$config" --formats dmg --release -rm -rf "$stage" -ls -l "$out" diff --git a/deploy/packaging/icons/wanderbooks.ico b/deploy/packaging/icons/wanderbooks.ico new file mode 100644 index 0000000000000000000000000000000000000000..a2c72ed54f43cdd285a7cf6717c282051ae0b9a9 GIT binary patch literal 370070 zcmeHQX|xs9mA=H#wmb6?$hx8}OHrtd8_ zRduTB410gy-lyuEI=56BQ2Lt^{sxo=mrfk~&eEl_-`w1L{I>&2(9^89;OsVvv83Rkl$QJos_Rdo2V{-B<(nnNg`847K&^W=@xlgggmDXihu!N9he99!2xgqoB%g6?+a?Q z!EpY1Ik#ElkVp~i%r?@_elY+}fE(aQOu+yziaM@^0dNl-Y={rAmLvP07TGOQt6of_UWkFl zU;rEh7whT+Ecs(Bzggr}5!#qKAO@1h0JsQFf}7e81b(P@xxwTq+hau*h|uQL0Wpw1 z41k;9Xly>ffNhvR z>;1Bi_X~X9Pp7TPLE6QR0dO_aJ3$NoF}|={#9juEsS{!#y%+#zD`SH}`T!R0V}1e0 z_tR@*@{hK0!vMHjnIq)K2Uxg&lBay!3@+>U0bV}9Tqj%1G42te zeW?RtAiEd&$g|}Roc&v0dU%}4`AUxV?VKD#}1G4fr*-Z01NjS`}1LE@|AY1 zg@KxV01N*a`-z)cxM5m;aM7<1(93^(Gk`TmX>00$7|1UMz;XS35XJ#|xsNT@96uyN z+fxU`Kz=a*j)Ut~?qeUnJ3zZr2gE@BF#xVx`Om(8{%uZP)5Zn^m1lrnKft~}v0<>m zZT_)fe+HP!zCWLRh=D?30G!7&z|kW34O04j>VOz14hFz^aDR{peutR0rw)jL;$Q%r z2lr1B!Ece%_S69}P#g?^^WgrqB5#xb^nb)ap)df>gZndR_d?m7F}^r4-pkhD{*B~6 z`A-ZK5(D5q`OkRZ6(@K;pBMr6r_=Wr()W|o`Q&sEyMp_7kpJXAF;GYhfcpn&`$F12 zNSxrc`Rpr@`}wph`AWMI1H=F^KnxHA!~iis3=jjv05L!e5Cg;jF+dCu1H=F^KnxHA z!~iis3=jjv05L!e5Cg;jF+dCu1H=F^KnxHA!~iis3=jjv05L!e5Cg;jF+dCu1H=F^ zKnxHA!~iis3=jjv05L!e5Cg;jF+dD71OvmHj#tB*j-v$B!3fctRj9)-7!njThVMZAI? zx(~dmw(aYo_|QT3{vP$xt^?})`R%G{_9iXZM;gvikN$K3%mI7AAh1aOC&PclD`0l( z-a`~0I@q@FkXpNAzwp0RHQl{Y3-*zQbJU|h9RPE{9{Jx`-Wxw_;y?NC53h#TXGCBN&1g4{O@{wzj|rQ%ekB5iZ-Ebe)=DA@Sl1-q+9^|KWp@7V9@B9Pz)X zy0f;M@Bgy({?BT=BJY#`<^FqA43Piie^d-5aX-RU zdb9g>#(&0tJ0`MlO#YMqamV5$@(UaPId6^g{}8)tOOSb#od1^u?@gIu_|N(Ood1vS zq@5(#Ix6J9;bIcop#0}|Yvq1#)c!y9X!J<_C&7DDW^n$O?Zx#!qV@mHdoSvd{5M=o zVoUy)*S!e7ZUy-d?ARr^9?AbCcyG!K&VR1|hw%ya|A*FG`w{(_VCyK7|Avc6Y=iP2 z*ysDd==`T1`TU;*-|c0F;eR>)as7|AJNB#d=eMe+yEkgVKGM)PfR6kK$59#o?VN1n zaajKQ!FHaniQ50qvu=X4&AbO4KY6Hrm(WP;v#j9je+RK`p06eU{q=9WFhKru{;wBC z(s-WyC;#)%e_;PV9FEEVaC)=*a>jqge>*0!a7_M_|BV0fU?2;8x7U&UkH_|m|BU~3 zZe`(^{3rhz|Kq_x7Wi(jBl#bX?HT_W|Lxq$!ZGN zI|j0NO#YMq_E?(5sCbj{?GV4>XG07CFwW9@SpSlIsc#Qf26A)AJ&Hiwm<_#U%0y z%YXQQB1_cwe?``vwe6h$pX@UL`5(@Yk^kZJX5~Ki$$#?Sj)^QBlmFy@68-hK%Vhiy zhhy?ToZjrdo$;UX-;Rka9Fza#f84P+iToJ7|G53c{g@xLhCOT)ck`41mZWQqFzugJQyww>eu$vy*+|Ka=?`5#ViR_e1+t z-~apJX}zuq&VR03f%g;9`ApdPfA!{Pz4H&tfB1kROVsy& zMb@3Q?VSIY>@xuQAI^`F|Kapz-RUdb9g> z#(&0tJ0`MlO#YMqjfl_nE`#wu9FEEVaC)=*cE*3ke>*0!aGX{Cqux;@ZrhOmen9FEEVaC#&EljXa;k3#;3!!h|EPH*IY zI{Cl0vr}~+cvFu7qEAL~*FpFG9`(|$12QMJT{X?#qy_s(!@0ESudlw*=KsdsK41>m z8$Wrdo{MUaPdu)#zZl+hyc#>{6!px?<=PHzzw5|z9m?onZAXV%yuMYP_seB!)XXJX zu#YsHGuNeMtLwX=U43#Md{wZy|Ck?ydvNb!$s^A8f&0K7FbFJ?@Ac(-E&ZN$_6b`5 z@WB-SIv9JwP<8r*Q`E@uWx+nuQmMlWhNy8Do~zE9wM>nkvnlZRKez|?B9HNsSDbAG z_kqD$*koE``~iF~-UU#C>0kt6mPJylzftd1BgUPinxwB1mjAdHc?_4l;%z76KK)!{ z{9Ix6EItbTl&Jhi9@^i@x1)vCCEHHhXAJ}7KQWs%%(A}mVV3-lPnX0cb(u8`kpIMN z)-cQZ#)nz*KR#U&m(*p}FhKqjvsuF|>l+_t4gYUlD&v2x}Z&2>#`+tsm zaNH+@7y$pr{j(Z1?Lp0Bi~|M|;Xdv~9vuJ6p#2$3!uE{s`H$~jHU`(N+{Zqj0f-AP z-0*z%F;dm{FUeo8FW@sk_H9dk(uQ6bsPz58ef(Ma0?o4TbwAHjN5nvOF#wKh&X?I= z#s3eM`vBxVV|^ho;28UB_yG8c zdifycOWhI!jmLmv?61LpJR@wO51|y{M2A4Ij4bPpn<~rFPB{ENhwxVOzXKL)^6aJJHy zH*r14)_T9}H;d5r)B!P&ehh%Ck+^UCge4z*AGClzfIg5INHqq)QE*lB-|#rf*5oDI zV@2o#((nHnql;-Ha1$Jjjr+!Lm^@_*--7-H-v<;EWArWQvpcv5PR1Jd4foAf^4ET) zcZ>H6yG4ix>VOzX4g=s|!0$#~fq!1?q2m@~hZ72FJiPaIV6^ z3NahJW37Yi;~S%95w0OrY>d)J#czLb3f!uE$0z#@W_#`8P!F5X55#YOa;lg*t;zee zaNp_?Y(4-!!T15JIeJKh7^V)00dEX|E8tAOcrR&I%B6B2b+ie_CGq zH~=ox6t$mJP0f zabO*o2ll~%e%xpjvz1aUPGub-CzX2J>2#?y73be_K0gTOyPVG-iSy0Q=Lg`t^XXDa zPXER2{5h`GE0qQ*wa@MTcez%-RFVd?xZN)rY<4>@4Rkv#4Rp~y?wsn{{8H&0uk$X} zL;izY)l(|H%ja&i7Uvdj4#&K%j|e*Orr^Udz}4~Tl+J$s&|2B-mQfEu6%r~zt# z8lVQK0cwC6pa!S`YJeJ`2B-mQfEu6%r~zt#8VIU^X7?K+kMFd&=kGcG)a8EvkzVJ$ z#@D>gdyVgTjSqUA_Zpw{8sGFBA8m0{pp37&Dp1B}T@@tbyRHh7@nKg5$oR5r1Ld?^ z1NHc}O9S-yxJv~GA%7POOvQQU5o(O@pD5~W7AXzDzrom(KRF2TS7RQ-KuJ4UL_)K^3t*4lMT#ko_?t zi$!SnblSWY7hx;d47P&}H4Z$?u1}k5W%~}1%SHBx)GC8%>DLQv2OGkco)|FK$QE-~ zr->XAp`Ej>1K1F@tjtHQBjbm74R42eZFiDF2km< zZNL72q#65|)CFu@^=v4|zyY2a`HYuO zn_IaI8^hLC?jI}1D@3fuUAal0}r%)acy7AA25x0AO?s5Vt^PR28aP-fEXYKh=I@; z7~XWe8s2nVDrJP!4U*RSL3i?uo>@8V>=V?u3x=qP|8}aHkRm~S#!VikPMiqewTCk6_bk(s(>kc}k{o}O_?O*>sr5FFV?K|8ce|xweul?FT**fNz z|6Q-|S8F>u)r)oRb0L3}gYvAt-H-i~uVX&#kG=qGa?yW`SL4nfqQ*}iS~o%dC!-2e-nq3?OS=5Qdqq+(5M>!}Df@h0 zS)DTS7&YYdch^mjKgvOQLErx*U&p-KpZvG_JZB%3Px~7moNR3M_xzu19rJB}gM%ct zUhzMPI@!zQ^MCx${YJ;MfAY_N#uiCzY5(NypX|GJfAK%rI_5Y2CqK64ZU5x!m{0qs zV{V1J{nJrL+Mn}3@;UyOyl-{qKl-G}*D;^`H~sx&`&QoeM?I6RW4`TgaFE27&wt53 z|0Q8}Qzq?C`}6y+`eMLq{!g-FEB@ktvUSX7{70XP^FR9LycBKx7w=Y*pIhP1|8&%m z{I|}N2($0ZEie10!AIrO{-zI}Y;1M6e>&=zZ~Ge^C$Z)8Uw!-j_$JV+|DS~2O_{Vm z?a$}``eML~|H-~v_ZR<@tz&-UfAV8%-u6$vj`_5II_6fm+dmz3r2RSngY!S4tjWps zpX%Gkb6Wew&+}iheJgkW-}juDF`ncw7-dSjQ_=q|Hl4FZrT4&zW-1AyFc6Jwf~=_-A&o`=Kps2Eun4)!8ub8w=M1O zPfu<-bUIfr`)`wPMmN89K;6D-r<%UJTiy74wIB`Wa1E|?svpv6e|P=3>CWq1-Rv*i z#=Npg_qD1s?%JTvynADnAPwjI{N5PtpI!S;p5LaL#P*|SR}0c`j`pvgZN0c(_O0&E z|9L^o>E4a1$=3HnUl3_H_mo`Y^?T#6eU^X!8*>2h+x7VUa`*xKj!{|!^%*yLm^yvp z5G~k`qmC0LpYa!uRcFmwsz%S*)UW@KG@QdVxYkV{x{jhd=+JGRW!lf-x9iatNTZC9 zx&c?$cFJ6VnT+5Oti@B>vMw#PYK zL;mN?_68$oouKUtjw2RSi=@H!at*nkQ~Lu4;s;#CV1--qfEXYKhyh}N7$63S0b+m{ zAO?s5VxVyt_!Hkn2^8NY`uV3WXhSIt%c3{Y=d4@;$~f2lq`=dJ4FLHnwY-_=!pd}K@Y@e$3{ z#{=xg)u(wx4NwEr05w1jH)v`HvB4 z78y_)EdR^j82x|E|7?AXcgyjGBKL~4i{O33UqrID*Y&{5-jO> zpE610X^|e0thCpwo@fi>k?^Gm>MYlcQw+Dv<*sUioG9JlcjfqOGRg*g_{r&l1MN z+5l}tTPrw_ec&R`cDL&aZAF`5d-w%#!+uTPkI`o1=kw(2{Mrp|HZjicJ$bv%#P__l z%Wr$y1q0|O_`N=F*JZ6=7q|Y45bxvGS)uduUfVa>HIeJ-%T7P1cirz#4cF^xV=e2@ z@~KnRIg^HInJD|A^D%XhI$=$6)Uh5qfZdV*lgpn~tJ~Yvi*0R@WKDaUx@OTTE!dBm zAL@j6Gg`;2ftykeSeSMVn2xB_hIoHSUV2%s2i5=(1LxWh5hYVQy0_? zb*x+a1#7Sq%6oaweyxjDn>Q=J@`7BuY5NZS`*8TZz#IP1t;PIyAkN_$zxm-hv>A0l zolrOMsQ&GLQ>}ZsOMUZuUsnHq>3QmlU!CMjzHrGW)a(VbbzSZ4NBwaQ*Z9p3Wup$L z3$W9;_7~g!;A;8zw!qn7g5TiAy>|PT^E(_OzrMOO%Kqi{A5>d*?-SV@NV;C%@7R8v z3z{G5uyyZ2?LQmUesFDl*H-oYYrd&2|MutA*Z%7ZzT~niFIMv&y3djSIEQQe=7+LT z2h^p}{O@>mk9uVB6Y7D-A5srI;Zq)8sGeW{N3oUQ+~)t0hI0?dHU9H^NY?>%X{7%* z{NJu)|63CO{Y&LuTl^ML)oYU>e5*L7rXrx3>Ost zmG&3Z{~^{CIsO&B|5L_)ar?i9|JWAs`3G(0`wzbVz`Lg)@2c|h{;TNxFS`FPdi*bX z|IhFr&)-4cS5)q`J^z|#c&Ge!9DGadvIvfoe*b|whZXz#FSmTQNjWRG?^6$N-dzzK zBi-Bwy*B#&k10FMHc0z%?M=^jtFz{8RAc7KZw<>9$4ED2=e_+mF7H-n-n~)(_A<6O zZg~4;Y;jFThuU%QPrl#zIlUX)Dg2%O{7x;{ce)PgI6q^>PBp5x{n+BzdLQb9y47#| z^LTak_>Zcqr~N=(f9sFcv|E1^Nv@asr(FF*E!cO<@A{e7ssFs=xAHsd<=@`M7RN|8 z_n}Ux8|sMPrjC33+vInu{J!(4XGWJ{l864SXvq)zZg~znkx0`JG`oPHkQ5 zfh5P>5d#$-M^l9lA3e>T=me?i`2rW9`!8`KmDk>X5Ir@ zupi`Jl!Y=;c9bzg^KI(xM$rSE!anzuX`nbT#GWJj`^1B zU;efg-;&+?@O*W{Z9i2v-agG$o?ZQd{*HIf+Fc5Q?|6~sbszFZ87NE7*^uwQqkOYk zUH?Ps=@rlE@3MaT#KX!>R?GLYJ7g|vrT(&yG`D+j4&QvC49vZVwf?PbYMazSi@B&&!}H7oTtC_!#90SvU1bLe)>n6 z)Ac4Dd83Tj^)I$Zp7%fYpqe@RW_9bFpS#Mkm)7*dKhnJJL*6JO_WD=w^Oi3kf_Z%X z@zdk$Ud%tM2Y$?VkWW3oOmhr8a}s>_xnuv~3jVQ=G^guLI`TH(VaCc|!Otsi98`DB zzf0z#{I|OHhN~Rq8aaph?3DREhQHWH8qT@hi@Z?=%8IrAz>mzMgAM!$@Y^ldn)+iO zX@2f4UlX(c(e*#9Hf-IlPH`{mZR^1l-U>|9SsgCy{PdSe=(1y7ECu}-v z?o9Q)tG}UsaP1Y&a?KU$iRW7S;Rk6ykaKSLB5#yYAN(BF--fmBcvZD|$jf{7_0vDn zyzWEZ`2H+*{rBP@b?AKU4NvKM{XjqbBhAmfC_~TLlrrOtzp&|T_sr7vzv{YgD`&Y< z{r(S2`r!v@S6z3d%YEP0d83Tj@gx2dHhpQ!%WCDujS77MH)-wO)ek>NbGt{Mle|%e z#*dU4oBn(8qvNWc8}7a~4$8O3U!CUTUX)QU{LFpe9`)m!u2w&h@46jDzP(=j!t>Jq z>5E_3M;gA%cDzsWMBXT)9{550d3N60Qwoi~Z z%BV~Kt@oQkKWi%a#n0A#^1b?QiHoltQmuQi#!7kprr7b*i+||Fuhi;4SntIg@8w(f zsxK|5T2`&_EziEVLS6s6 z#agg$zZYrqmabACzh{Grp1kj^o`jbPz_$b6Oqll{wub zC!VU#oH|R5`ro+{vO{+S(jhy~ZZy3O(! z0P3Fg@gt0Z#c9t*=7qXr3^I!tLY>Wgf-H|;V;%v<;xQ)QNZUs#3w1T~2h2PO9K#N2 z#uDm=I@;@Q+F<4rJSNwqWo#IAMqN-RgLhM3+iV~nHd+Iir!`n)j7Vjk)-iHm`xD#2 zX86s(i$#`+;I}T`7Ky^cTK6JPH??!L`)otn*zrMXn?!5O7wN}=Ef2{otE!anz z{W{!>Ji@jgV-7XPWyGdi-`HPiKlWi~`#22lMIK?>|IEtedfe%@dv296iaz;;v}=vn z$Fv{&NV8speT-QlkF2&oY5OOQ|D^ffx?@*Op9VZ{dF}NI{;`j=TK-SxA?JenANW(u zIrz<^52)WP`fZh9F39?>F75l^1F?@Z`*pY%c_6PaxFZ@wuAv)o*=HU3B?pv|!&{cgeRdRugV{MArS-tS0ylmpwJV1AUyb0R_3 z-@vuF$J`qh=T+s}ePb;@h%_nJNTtqY-+n>GU&C)t`MUUM5#z&k+T|B0yU#Yy28gpy zEnlkVb3H9{6Q6C{rUm<$&xLci#vb!=|0iTkvL!O-`bo?E&voup5OY7y;Tl|PjailZ zU#z}=S?3M~sk&dTN$>qD^;{;*34Tg`18Z4_)L#VqPb@2^VXWGz{+JVld86yLbg2!p zePR1vEgN6is(!z&O)XsArsov(zyEmkFB4BxH{Us3o=xYdyXE;5&!{)ubElTM3+`6m zpZBP`5}TpE1#Z6%Ky>tq=o^ + + + + + CFBundleName + Wanderbooks + CFBundleDisplayName + Wanderbooks + CFBundleIdentifier + @BUNDLE_ID@ + CFBundleExecutable + wanderbooks + CFBundleIconFile + wanderbooks + CFBundlePackageType + APPL + CFBundleInfoDictionaryVersion + 6.0 + CFBundleShortVersionString + @VERSION@ + CFBundleVersion + @VERSION@ + LSMinimumSystemVersion + 11.0 + LSApplicationCategoryType + public.app-category.finance + NSHighResolutionCapable + + + LSMultipleInstancesProhibited + + + NSSupportsAutomaticGraphicsSwitching + + NSHumanReadableCopyright + MIT OR Apache-2.0 + + NSDocumentsFolderUsageDescription + Wanderbooks keeps a small folder in Documents for each company, where an assistant such as Claude Code works, and the extension file for the Claude app. + + diff --git a/deploy/packaging/macos/build-macos.sh b/deploy/packaging/macos/build-macos.sh new file mode 100755 index 00000000..fc7e7f0b --- /dev/null +++ b/deploy/packaging/macos/build-macos.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +# The macOS app and its .dmg (plan P15 unit C1; WB-pkg-1). Run on a Mac from +# the repository root (CI: the `macos` job of .github/workflows/release.yml): +# +# build-macos.sh [VERSION] +# +# Puts Wanderbooks-VERSION-macos-universal.dmg into target/packages/VERSION/. +# +# One UNIVERSAL program (Apple silicon and Intel in one file, `lipo`ed from +# the two release builds): one download for everyone. The program is +# WB_PROGRAM if set (any program file), else the lipo of +# target/aarch64-apple-darwin/release/wanderbooks and +# target/x86_64-apple-darwin/release/wanderbooks. +# +# Signing and notarization need the owner's Apple Developer identity and run +# only when it is given, in the environment (the release workflow sets these +# from secrets; nothing here is a secret and nothing prints one): +# WB_SIGN_IDENTITY the signing identity, e.g. +# "Developer ID Application: Name (TEAMID)", already in +# the keychain (import-certificate.sh does that in CI) +# WB_NOTARY_APPLE_ID, WB_NOTARY_TEAM_ID, WB_NOTARY_PASSWORD +# for `xcrun notarytool` (an app-specific password) +# Without WB_SIGN_IDENTITY the app is signed ad hoc ("-"): Apple silicon +# will not start an unsigned program at all, so it runs, but Gatekeeper +# still refuses a download of it (right-click > Open once, docs/install.md). +# Without the notarization variables the .dmg is signed but not notarized. +# +# WB_NO_ICNS=1 skips the icon (no `iconutil` off a Mac): the structure +# tests build the bundle that way on Linux; a release never does. +# WB_BUNDLE_ONLY=1 stops after the .app (the structure tests). +set -euo pipefail + +here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +root=$(CDPATH='' cd -- "$here/../../.." && pwd) +cd "$root" +fail() { echo "build-macos: $*" >&2; exit 1; } +notice() { echo "::notice title=$1::$2"; echo "build-macos: $2"; } + +own=$(sh deploy/packaging/version.sh) +version=${1:-$own} +case "$version" in + [0-9]*.[0-9]*.[0-9]*) ;; + *) fail "'$version' is not an x.y.z version" ;; +esac +bundle_id=${WB_BUNDLE_ID:-ai.wanderbooks.app} +out="target/packages/$version" +stage="target/packages/.stage-macos-$version" +app="$stage/Wanderbooks.app" +dmg="Wanderbooks-$version-macos-universal.dmg" + +for f in LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt deploy/packaging/icons/512x512.png \ + deploy/packaging/macos/Info.plist.in deploy/packaging/macos/entitlements.plist; do + test -f "$f" || fail "$f is missing from the repository" +done + +# 1. The program: universal, or the one given. +rm -rf "${stage:?}" +mkdir -p "$stage" "$out" +program=${WB_PROGRAM:-} +if [ -z "$program" ]; then + arm=target/aarch64-apple-darwin/release/wanderbooks + intel=target/x86_64-apple-darwin/release/wanderbooks + test -f "$arm" || fail "$arm is missing: cargo build --release -p ledger-cli --target aarch64-apple-darwin" + test -f "$intel" || fail "$intel is missing: cargo build --release -p ledger-cli --target x86_64-apple-darwin" + lipo -create -output "$stage/wanderbooks-universal" "$arm" "$intel" + archs=$(lipo -archs "$stage/wanderbooks-universal") + case "$archs" in + *arm64*x86_64*|*x86_64*arm64*) ;; + *) fail "the universal program holds '$archs', not both arm64 and x86_64" ;; + esac + program="$stage/wanderbooks-universal" +fi +test -f "$program" || fail "the program is not at $program" + +# 2. The bundle. The program's path inside it, +# /Applications/Wanderbooks.app/Contents/MacOS/wanderbooks, is the one an +# assistant is registered with: it does not change when the app is +# replaced by a newer one dragged over it. +mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" +cp "$program" "$app/Contents/MacOS/wanderbooks" +chmod 755 "$app/Contents/MacOS/wanderbooks" +sed -e "s/@VERSION@/$version/g" -e "s/@BUNDLE_ID@/$bundle_id/g" \ + deploy/packaging/macos/Info.plist.in > "$app/Contents/Info.plist" +printf 'APPL????' > "$app/Contents/PkgInfo" +cp LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt "$app/Contents/Resources/" +if [ "${WB_NO_ICNS:-}" = 1 ]; then + notice "no icon" "WB_NO_ICNS=1: the bundle has no icon (a test build, never a release)" +else + command -v iconutil >/dev/null || fail "iconutil is not here: build the icon on a Mac, or set WB_NO_ICNS=1 for a test bundle" + iconset="$stage/wanderbooks.iconset" + mkdir -p "$iconset" + src=deploy/packaging/icons/512x512.png + for size in 16 32 128 256 512; do + sips -z "$size" "$size" "$src" --out "$iconset/icon_${size}x${size}.png" >/dev/null + done + for size in 16 32 128 256; do + double=$((size * 2)) + sips -z "$double" "$double" "$src" --out "$iconset/icon_${size}x${size}@2x.png" >/dev/null + done + iconutil -c icns "$iconset" -o "$app/Contents/Resources/wanderbooks.icns" +fi +if [ "${WB_BUNDLE_ONLY:-}" = 1 ]; then + echo "build-macos: bundle at $app (WB_BUNDLE_ONLY=1)" + exit 0 +fi + +# 3. Sign: hardened runtime, the entitlements, a secure timestamp. +identity=${WB_SIGN_IDENTITY:-} +if [ -z "$identity" ]; then + notice "macOS signing skipped" "no WB_SIGN_IDENTITY: the app is signed ad hoc, so it runs here, but macOS Gatekeeper will refuse a download of it until it is signed with a Developer ID and notarized" + identity=- + timestamp=--timestamp=none +else + timestamp=--timestamp +fi +codesign --force --options runtime "$timestamp" \ + --entitlements deploy/packaging/macos/entitlements.plist \ + --sign "$identity" "$app" +codesign --verify --deep --strict --verbose=2 "$app" + +# 4. The .dmg: the app and a shortcut to Applications (drag to install). +mkdir -p "$stage/dmg" +cp -R "$app" "$stage/dmg/" +ln -s /Applications "$stage/dmg/Applications" +rm -f "${out:?}/${dmg:?}" +hdiutil create -volname "Wanderbooks" -srcfolder "$stage/dmg" -ov -format UDZO "$out/$dmg" +if [ "$identity" != "-" ]; then + codesign --force --timestamp --sign "$identity" "$out/$dmg" +fi + +# 5. Notarize and staple (the Developer ID signature and Apple's ticket). +if [ "$identity" != "-" ] && [ -n "${WB_NOTARY_APPLE_ID:-}" ] && [ -n "${WB_NOTARY_TEAM_ID:-}" ] && [ -n "${WB_NOTARY_PASSWORD:-}" ]; then + xcrun notarytool submit "$out/$dmg" \ + --apple-id "$WB_NOTARY_APPLE_ID" --team-id "$WB_NOTARY_TEAM_ID" \ + --password "$WB_NOTARY_PASSWORD" --wait + xcrun stapler staple "$out/$dmg" + xcrun stapler validate "$out/$dmg" + spctl --assess --type open --context context:primary-signature --verbose=2 "$out/$dmg" +else + notice "macOS notarization skipped" "no signing identity or no WB_NOTARY_APPLE_ID / WB_NOTARY_TEAM_ID / WB_NOTARY_PASSWORD: the .dmg is not notarized, and macOS will warn on the first open" +fi +rm -rf "${stage:?}" +ls -l "$out" diff --git a/deploy/packaging/macos/entitlements.plist b/deploy/packaging/macos/entitlements.plist new file mode 100644 index 00000000..30dd36ee --- /dev/null +++ b/deploy/packaging/macos/entitlements.plist @@ -0,0 +1,29 @@ + + + + + + diff --git a/deploy/packaging/macos/import-certificate.sh b/deploy/packaging/macos/import-certificate.sh new file mode 100755 index 00000000..25bcecf0 --- /dev/null +++ b/deploy/packaging/macos/import-certificate.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Put the owner's Developer ID certificate into a temporary keychain on a CI +# macOS runner, so `codesign` can use it (plan P15 unit C1). Run by the +# release workflow only when the secrets exist. Takes the certificate (a .p12, +# base64) and its password from the environment, never the command line: +# APPLE_CERTIFICATE_P12_BASE64, APPLE_CERTIFICATE_PASSWORD +# Prints no secret. The keychain lives in RUNNER_TEMP and goes with the +# runner. +set -euo pipefail +: "${APPLE_CERTIFICATE_P12_BASE64:?the certificate secret is empty}" +: "${APPLE_CERTIFICATE_PASSWORD:?the certificate password secret is empty}" +: "${RUNNER_TEMP:?not on a GitHub runner}" +keychain="$RUNNER_TEMP/wanderbooks-signing.keychain-db" +password=$(uuidgen) +p12="$RUNNER_TEMP/wanderbooks-signing.p12" +printf '%s' "$APPLE_CERTIFICATE_P12_BASE64" | base64 --decode > "$p12" +security create-keychain -p "$password" "$keychain" +security set-keychain-settings -lut 21600 "$keychain" +security unlock-keychain -p "$password" "$keychain" +security import "$p12" -k "$keychain" -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign +security set-key-partition-list -S apple-tool:,apple: -s -k "$password" "$keychain" >/dev/null +security list-keychains -d user -s "$keychain" login.keychain +rm -f "$p12" +security find-identity -v -p codesigning "$keychain" diff --git a/deploy/packaging/packager-macos.toml b/deploy/packaging/packager-macos.toml deleted file mode 100644 index 64ef6c00..00000000 --- a/deploy/packaging/packager-macos.toml +++ /dev/null @@ -1,36 +0,0 @@ -# cargo-packager's description of the macOS bundle (P11a step 6; D-24, -# D-25): the .app and its .dmg, UNSIGNED. `deploy/packaging/build-macos.sh` -# runs it on a Mac (CI: the `macos` job of .github/workflows/release.yml). -# Developer ID signing and notarization are step 5 (the owner's Apple -# certificate, Q-4): they add `signing-identity` under [macos] and the -# certificate and notarization credentials as CI secrets. -# Paths are relative to this file's copy that build-macos.sh writes. -name = "wanderbooks" -product-name = "Wanderbooks" -version = "0.1.0" -identifier = "ai.wanderbooks.app" -description = "Double-entry bookkeeping your agent keeps and you can read." -homepage = "https://wanderbooks.ai" -authors = ["Stephen Waits"] -license-file = "LICENSE-MIT" -category = "Finance" -binaries-dir = "target/release" -out-dir = "target/packages" -# A png is made into the .icns (cargo-packager does it); the 512 px -# placeholder is the owner's to replace. -icons = ["deploy/packaging/icons/512x512.png"] -formats = ["dmg"] -binaries = [{ path = "wanderbooks", main = true }] - -[macos] -# The oldest macOS Rust's tier-1 aarch64-apple-darwin and x86-64 targets -# run on; eframe's wgpu/Metal path needs 10.15 at least. -minimum-system-version = "11.0" -# Keys merged into the generated Info.plist: one viewer at a time, and the -# discrete GPU is not woken for a ledger. -info-plist-path = "deploy/packaging/Info.plist" - -[dmg] -window-size = { width = 540, height = 380 } -app-position = { x = 140, y = 180 } -application-folder-position = { x = 400, y = 180 } diff --git a/deploy/packaging/packager.toml b/deploy/packaging/packager.toml index 0974f661..b0307d5a 100644 --- a/deploy/packaging/packager.toml +++ b/deploy/packaging/packager.toml @@ -31,6 +31,8 @@ depends = ["libc6", "libgcc-s1"] # The notices the third-party licences ask to travel with the program # (`just notices`); `wanderbooks licenses` prints the same text. "THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt" +"LICENSE-MIT" = "usr/share/doc/wanderbooks/LICENSE-MIT" +"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE" [pacman] depends = ["gcc-libs", "glibc"] @@ -38,3 +40,5 @@ depends = ["gcc-libs", "glibc"] [pacman.files] "deploy/packaging/install-method-aur" = "usr/share/wanderbooks/install-method" "THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt" +"LICENSE-MIT" = "usr/share/doc/wanderbooks/LICENSE-MIT" +"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE" diff --git a/deploy/packaging/version.sh b/deploy/packaging/version.sh new file mode 100755 index 00000000..99304cd3 --- /dev/null +++ b/deploy/packaging/version.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# The program's version: the one place it is written is `version = "..."` +# in crates/ledger-cli/Cargo.toml (plan P15 C1, WB-pkg-6). Every package, the +# release workflow and the installer take it from here; the program itself +# reports the same file's version through `CARGO_PKG_VERSION`. +# +# deploy/packaging/version.sh prints 0.1.0 +# +# A version that is not three plain numbers is refused: the Windows +# installer's file-version fields and the macOS bundle's both need them. +set -eu +here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +version=$(sed -n 's/^version = "\(.*\)"/\1/p' "$here/../../crates/ledger-cli/Cargo.toml" | head -n1) +case "$version" in + [0-9]*.[0-9]*.[0-9]*) ;; + *) echo "version.sh: no x.y.z version in crates/ledger-cli/Cargo.toml (found: '$version')" >&2; exit 1 ;; +esac +case "$version" in + *[!0-9.]*) echo "version.sh: '$version' is not three plain numbers" >&2; exit 1 ;; +esac +printf '%s\n' "$version" diff --git a/deploy/packaging/wanderbooks-static.desktop b/deploy/packaging/wanderbooks-static.desktop index ffa4bbe2..c6a9391a 100644 --- a/deploy/packaging/wanderbooks-static.desktop +++ b/deploy/packaging/wanderbooks-static.desktop @@ -1,7 +1,9 @@ [Desktop Entry] -Categories=Office;Finance; +Type=Application +Name=Wanderbooks Comment=Double-entry bookkeeping your agent keeps and you can read. Exec=wanderbooks -Name=Wanderbooks +Icon=wanderbooks Terminal=false -Type=Application +Categories=Office;Finance; +StartupWMClass=wanderbooks diff --git a/deploy/packaging/wanderbooks.desktop b/deploy/packaging/wanderbooks.desktop index 574cd598..5e3f2a8a 100644 --- a/deploy/packaging/wanderbooks.desktop +++ b/deploy/packaging/wanderbooks.desktop @@ -8,3 +8,4 @@ Icon={{icon}} Name={{name}} Terminal=false Type=Application +StartupWMClass=wanderbooks diff --git a/deploy/packaging/windows/build-windows.sh b/deploy/packaging/windows/build-windows.sh new file mode 100755 index 00000000..68ea948f --- /dev/null +++ b/deploy/packaging/windows/build-windows.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# The Windows installer (plan P15 unit C1), from the release program already +# built at target/release/wanderbooks.exe (`cargo build --release -p +# ledger-cli`). Run from the repository root, in Git Bash on Windows (CI: +# the `windows` job of .github/workflows/release.yml) or anywhere makensis +# is: +# +# build-windows.sh [VERSION] +# +# Puts Wanderbooks-VERSION-windows-x64-setup.exe into target/packages/VERSION/. +# VERSION defaults to the program's own (deploy/packaging/version.sh). +# WB_PROGRAM names another program file; WB_MAKENSIS another makensis. +# +# Unsigned: signing is a separate, optional step (sign-windows.ps1) that +# runs when the release workflow has the certificate's secrets. +set -euo pipefail + +here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +root=$(CDPATH='' cd -- "$here/../../.." && pwd) +cd "$root" +own=$(sh deploy/packaging/version.sh) +version=${1:-$own} +case "$version" in + [0-9]*.[0-9]*.[0-9]*) ;; + *) echo "build-windows: '$version' is not an x.y.z version" >&2; exit 1 ;; +esac +program=${WB_PROGRAM:-target/release/wanderbooks.exe} +out="target/packages/$version" +installer="Wanderbooks-$version-windows-x64-setup.exe" + +fail() { echo "build-windows: $*" >&2; exit 1; } +test -f "$program" || fail "the release program is not at $program: run cargo build --release -p ledger-cli first" +for f in LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt deploy/packaging/icons/wanderbooks.ico deploy/packaging/windows/wanderbooks.nsi; do + test -f "$f" || fail "$f is missing from the repository" +done + +makensis=${WB_MAKENSIS:-} +if [ -z "$makensis" ]; then + if command -v makensis >/dev/null 2>&1; then + makensis=makensis + elif [ -x "/c/Program Files (x86)/NSIS/makensis.exe" ]; then + makensis="/c/Program Files (x86)/NSIS/makensis.exe" + else + fail "makensis (NSIS) is not installed: choco install nsis, or apt install nsis" + fi +fi + +# NSIS is a Windows program; Git Bash must neither rewrite its options +# (-D...) nor hand it a Unix path, so paths are made native here. +export MSYS2_ARG_CONV_EXCL='*' +native() { if command -v cygpath >/dev/null 2>&1; then cygpath -w "$1"; else printf '%s\n' "$1"; fi; } + +rm -rf "${out:?}" +mkdir -p "$out" +"$makensis" -V2 \ + "-DVERSION=$version" \ + "-DPROGRAM=$(native "$program")" \ + "-DICON=$(native deploy/packaging/icons/wanderbooks.ico)" \ + "-DLICENSES=$(native "$root")" \ + "-DOUTFILE=$(native "$out/$installer")" \ + "$(native deploy/packaging/windows/wanderbooks.nsi)" +test -s "$out/$installer" || fail "makensis finished but $out/$installer is missing or empty" +ls -l "$out" diff --git a/deploy/packaging/windows/sign-windows.ps1 b/deploy/packaging/windows/sign-windows.ps1 new file mode 100644 index 00000000..6fce5ba0 --- /dev/null +++ b/deploy/packaging/windows/sign-windows.ps1 @@ -0,0 +1,36 @@ +# Sign Windows files with an Authenticode code-signing certificate (plan P15 +# unit C1). The release workflow runs this only when its secrets exist +# (WINDOWS_CERTIFICATE_PFX_BASE64 and WINDOWS_CERTIFICATE_PASSWORD); with none +# it prints a notice and the installer stays unsigned (SmartScreen warns). +# +# sign-windows.ps1 FILE [FILE...] +# +# The certificate is written to a temporary file for the signing and +# removed. Nothing here prints a secret. A failure is loud: a signature that +# was asked for and did not happen stops the release. +param([Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)][string[]]$Files) +$ErrorActionPreference = 'Stop' + +if (-not $env:WINDOWS_CERTIFICATE_PFX_BASE64 -or -not $env:WINDOWS_CERTIFICATE_PASSWORD) { + Write-Host "::notice title=Windows signing skipped::no WINDOWS_CERTIFICATE_PFX_BASE64 / WINDOWS_CERTIFICATE_PASSWORD secret: the installer is unsigned and Windows SmartScreen will warn on the first run." + exit 0 +} + +$signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin" -Recurse -Filter signtool.exe -ErrorAction SilentlyContinue | + Where-Object { $_.FullName -match '\\x64\\' } | + Sort-Object FullName -Descending | Select-Object -First 1 +if (-not $signtool) { throw "signtool.exe was not found in the Windows SDK on this runner" } + +$pfx = Join-Path $env:RUNNER_TEMP 'wanderbooks-codesign.pfx' +[IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:WINDOWS_CERTIFICATE_PFX_BASE64)) +try { + foreach ($file in $Files) { + & $signtool.FullName sign /fd sha256 /f $pfx /p $env:WINDOWS_CERTIFICATE_PASSWORD /tr http://timestamp.digicert.com /td sha256 $file + if ($LASTEXITCODE -ne 0) { throw "signtool failed on $file" } + & $signtool.FullName verify /pa $file + if ($LASTEXITCODE -ne 0) { throw "the signature on $file does not verify" } + Write-Host "signed $file" + } +} finally { + Remove-Item $pfx -Force -ErrorAction SilentlyContinue +} diff --git a/deploy/packaging/windows/wanderbooks.nsi b/deploy/packaging/windows/wanderbooks.nsi new file mode 100644 index 00000000..9d332144 --- /dev/null +++ b/deploy/packaging/windows/wanderbooks.nsi @@ -0,0 +1,144 @@ +; The Wanderbooks installer for Windows (plan P15 unit C1; WB-pkg-1, WB-pkg-2, +; WB-pkg-7). Built by deploy/packaging/windows/build-windows.sh with NSIS +; (https://nsis.sourceforge.io, free software, zlib licence). +; +; makensis -DVERSION=0.1.0 -DPROGRAM=...\wanderbooks.exe -DICON=...\wanderbooks.ico ^ +; -DLICENSES= -DOUTFILE=...\Wanderbooks-0.1.0-windows-x64-setup.exe wanderbooks.nsi +; +; What it does, and the rules it keeps: +; * Per user: RequestExecutionLevel user, so double-clicking it shows no +; administrator prompt. Everything goes under the person's own profile +; and HKEY_CURRENT_USER. +; * One program file, wanderbooks.exe. It is the window, the books +; server's child and the assistants' bridge; an assistant is registered +; with this installed path, which an update keeps (the same folder, the +; same file name, replaced in place). +; * A Start Menu entry named Wanderbooks, with the icon, and an entry in +; Settings > Apps (the uninstaller). +; * The uninstaller removes the files this installer put in the install +; folder, the Start Menu entry and its two registry keys. It NEVER +; removes the person's books, keys, backups or settings: they live in +; the data folder (%LOCALAPPDATA%\wanderbooks), which this script +; names nowhere, and no command below deletes a folder's contents or +; uses a wildcard (a test, crates/ledger-cli/tests/packaging.rs, reads +; this file and fails if one appears). +; * It asks the person to quit Wanderbooks fully before it replaces or +; removes the program (a running program cannot be replaced). +; * Unsigned until the owner has a code-signing certificate: Windows +; SmartScreen says so on the first run (docs/install.md). + +Unicode true +SetCompressor /SOLID lzma +!include "MUI2.nsh" +!include "LogicLib.nsh" + +!ifndef VERSION + !error "pass -DVERSION=x.y.z (deploy/packaging/version.sh)" +!endif +!ifndef PROGRAM + !error "pass -DPROGRAM=" +!endif +!ifndef ICON + !error "pass -DICON=" +!endif +!ifndef LICENSES + !error "pass -DLICENSES=" +!endif +!ifndef OUTFILE + !error "pass -DOUTFILE=" +!endif + +!define NAME "Wanderbooks" +!define PUBLISHER "Wanderbooks" +!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\Wanderbooks" +!define APP_KEY "Software\Wanderbooks" + +Name "${NAME}" +OutFile "${OUTFILE}" +RequestExecutionLevel user +InstallDir "$LOCALAPPDATA\Programs\Wanderbooks" +InstallDirRegKey HKCU "${APP_KEY}" "InstallDir" +BrandingText "${NAME} ${VERSION}" +ShowInstDetails nevershow +ShowUninstDetails nevershow + +VIProductVersion "${VERSION}.0" +VIAddVersionKey "ProductName" "${NAME}" +VIAddVersionKey "FileDescription" "${NAME} installer" +VIAddVersionKey "FileVersion" "${VERSION}" +VIAddVersionKey "ProductVersion" "${VERSION}" +VIAddVersionKey "LegalCopyright" "MIT OR Apache-2.0" + +!define MUI_ICON "${ICON}" +!define MUI_UNICON "${ICON}" +!define MUI_ABORTWARNING +!define MUI_FINISHPAGE_RUN "$INSTDIR\wanderbooks.exe" +!define MUI_FINISHPAGE_RUN_TEXT "Start ${NAME}" + +!insertmacro MUI_PAGE_INSTFILES +!insertmacro MUI_PAGE_FINISH +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES +!insertmacro MUI_LANGUAGE "English" + +; A program that is running cannot be replaced or removed. Try to open the +; installed file for writing; if it is in use, ask the person to quit +; Wanderbooks (its window, which closes the books and the server) and retry. +!macro WaitUntilNotRunning + ${Do} + ClearErrors + ${If} ${FileExists} "$INSTDIR\wanderbooks.exe" + FileOpen $0 "$INSTDIR\wanderbooks.exe" a + ${IfNot} ${Errors} + FileClose $0 + ${Break} + ${EndIf} + MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "${NAME} is open. Quit it fully (close its window), then choose Retry." IDRETRY +2 + Abort "${NAME} is still open." + ${Else} + ${Break} + ${EndIf} + ${Loop} +!macroend + +Section "Install" + SetOutPath "$INSTDIR" + !insertmacro WaitUntilNotRunning + File "/oname=wanderbooks.exe" "${PROGRAM}" + File "/oname=wanderbooks.ico" "${ICON}" + File "/oname=LICENSE-MIT" "${LICENSES}\LICENSE-MIT" + File "/oname=LICENSE-APACHE" "${LICENSES}\LICENSE-APACHE" + File "/oname=THIRD-PARTY-NOTICES.txt" "${LICENSES}\THIRD-PARTY-NOTICES.txt" + WriteUninstaller "$INSTDIR\Uninstall Wanderbooks.exe" + + CreateShortCut "$SMPROGRAMS\${NAME}.lnk" "$INSTDIR\wanderbooks.exe" "" "$INSTDIR\wanderbooks.ico" 0 + + WriteRegStr HKCU "${APP_KEY}" "InstallDir" "$INSTDIR" + WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "${NAME}" + WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}" + WriteRegStr HKCU "${UNINSTALL_KEY}" "Publisher" "${PUBLISHER}" + WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\wanderbooks.ico" + WriteRegStr HKCU "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR" + WriteRegStr HKCU "${UNINSTALL_KEY}" "URLInfoAbout" "https://wanderbooks.ai" + WriteRegStr HKCU "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\Uninstall Wanderbooks.exe"' + WriteRegStr HKCU "${UNINSTALL_KEY}" "QuietUninstallString" '"$INSTDIR\Uninstall Wanderbooks.exe" /S' + WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1 + WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1 +SectionEnd + +Section "Uninstall" + !insertmacro WaitUntilNotRunning + Delete "$INSTDIR\wanderbooks.exe" + Delete "$INSTDIR\wanderbooks.ico" + Delete "$INSTDIR\LICENSE-MIT" + Delete "$INSTDIR\LICENSE-APACHE" + Delete "$INSTDIR\THIRD-PARTY-NOTICES.txt" + Delete "$INSTDIR\Uninstall Wanderbooks.exe" + ; Only if empty: a folder the person put something in stays. + RMDir "$INSTDIR" + Delete "$SMPROGRAMS\${NAME}.lnk" + DeleteRegKey HKCU "${UNINSTALL_KEY}" + DeleteRegKey HKCU "${APP_KEY}" + ; The person's books, keys, backups and settings are not here: they are + ; in the data folder, which an uninstall leaves exactly as it is. +SectionEnd diff --git a/justfile b/justfile index 8db57ebf..e524faad 100644 --- a/justfile +++ b/justfile @@ -591,10 +591,23 @@ package-linux version="" formats="deb,appimage,pacman": cargo build --release -p ledger-cli deploy/packaging/build-linux.sh {{version}} {{formats}} -# Build the unsigned macOS .dmg (on a Mac; CI does it on a tag or dispatch) +# The macOS app and its universal .dmg (on a Mac; CI does it on a tag or +# dispatch). Signs and notarizes only with WB_SIGN_IDENTITY and WB_NOTARY_* +# in the environment (deploy/packaging/macos/build-macos.sh says which). +# Build the universal macOS .dmg package-macos version="": + rustup target add aarch64-apple-darwin x86_64-apple-darwin + cargo build --release -p ledger-cli --target aarch64-apple-darwin + cargo build --release -p ledger-cli --target x86_64-apple-darwin + deploy/packaging/macos/build-macos.sh {{version}} + +# The per-user Windows installer (in Git Bash on Windows, with NSIS: choco +# install nsis; CI does it on a tag or dispatch). Unsigned unless the +# release workflow signs it. +# Build the Windows installer +package-windows version="": cargo build --release -p ledger-cli - deploy/packaging/build-macos.sh {{version}} + deploy/packaging/windows/build-windows.sh {{version}} # A release folder on this machine signed with a throwaway key; then # `wanderbooks update --feed file://DIR/manifest.json --trusted-key DIR/release.pub` From 2d4c482abf6724f2d685c1bd4db6b251320b9651 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:41:48 -0700 Subject: [PATCH 06/11] fix(packaging): the AppImage carries the licences too (P15 C1) Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/packaging.rs | 4 ++-- deploy/packaging/packager.toml | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ledger-cli/tests/packaging.rs b/crates/ledger-cli/tests/packaging.rs index ad61926e..a1c6bed3 100644 --- a/crates/ledger-cli/tests/packaging.rs +++ b/crates/ledger-cli/tests/packaging.rs @@ -517,8 +517,8 @@ fn every_package_carries_the_licences_and_the_icon() { ); assert_eq!( deb_pacman.matches(&format!("\"{file}\" = ")).count(), - 2, - "both the deb and the pacman package carry {file}" + 3, + "the deb, the AppImage and the pacman package each carry {file}" ); assert!( rpm.contains(&format!("source = \"{file}\"")), diff --git a/deploy/packaging/packager.toml b/deploy/packaging/packager.toml index b0307d5a..4f5d917c 100644 --- a/deploy/packaging/packager.toml +++ b/deploy/packaging/packager.toml @@ -34,6 +34,11 @@ depends = ["libc6", "libgcc-s1"] "LICENSE-MIT" = "usr/share/doc/wanderbooks/LICENSE-MIT" "LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE" +[appimage.files] +"THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt" +"LICENSE-MIT" = "usr/share/doc/wanderbooks/LICENSE-MIT" +"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE" + [pacman] depends = ["gcc-libs", "glibc"] From 26311f8b521b11df3537c8ad241378ffca225d51 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:42:45 -0700 Subject: [PATCH 07/11] test(store): where each system keeps the books, and that no install folder holds them (P15 C1) Co-Authored-By: Claude Fable 5.2 --- crates/ledger-store/src/root.rs | 20 +++-- crates/ledger-store/tests/data_locations.rs | 84 +++++++++++++++++++++ 2 files changed, 98 insertions(+), 6 deletions(-) create mode 100644 crates/ledger-store/tests/data_locations.rs diff --git a/crates/ledger-store/src/root.rs b/crates/ledger-store/src/root.rs index 0353b74c..8c0bc6cb 100644 --- a/crates/ledger-store/src/root.rs +++ b/crates/ledger-store/src/root.rs @@ -357,12 +357,20 @@ pub fn platform_data_dir(home: &Path) -> PathBuf { { return local; } - if cfg!(target_os = "macos") { - home.join("Library").join("Application Support") - } else if cfg!(windows) { - home.join("AppData").join("Local") - } else { - home.join(".local").join("share") + data_dir_for(std::env::consts::OS, home) +} + +/// The data folder under `home` on the system called `os` (a +/// `std::env::consts::OS` name), as each system's conventions put an +/// installed app's own data (P15 C1, WB-pkg-8): `Library/Application +/// Support` on macOS, `AppData\Local` (not the roaming folder: the books +/// are big, hold locks and belong to this machine) on Windows, the XDG +/// default `.local/share` anywhere else. An uninstall never touches it. +pub fn data_dir_for(os: &str, home: &Path) -> PathBuf { + match os { + "macos" => home.join("Library").join("Application Support"), + "windows" => home.join("AppData").join("Local"), + _ => home.join(".local").join("share"), } } diff --git a/crates/ledger-store/tests/data_locations.rs b/crates/ledger-store/tests/data_locations.rs new file mode 100644 index 00000000..34d90567 --- /dev/null +++ b/crates/ledger-store/tests/data_locations.rs @@ -0,0 +1,84 @@ +//! Where an installed app's books live on each system (plan P15 unit C1, +//! WB-pkg-8). +//! +//! ```text +//! GOAL: the books, keys and settings sit where each system keeps an app's +//! own data, apart from the program, so installing a newer program +//! over the old one, or uninstalling it, leaves them as they are. +//! SOURCE: WB-pkg-8; each system's convention for per-user application data +//! (Apple's File System Programming Guide: Library/Application +//! Support; Microsoft's known folders: LocalAppData; the XDG base +//! directory specification: $XDG_DATA_HOME, default ~/.local/share). +//! INVARIANTS: +//! 1. macOS: /Library/Application Support/wanderbooks. +//! 2. Windows: \AppData\Local\wanderbooks (LocalAppData, the local +//! folder, never the roaming one). +//! 3. Anywhere else: /.local/share/wanderbooks, where books have +//! always lived on Linux. +//! 4. No system's data folder is inside the folder its program installs +//! to (the install folders are in docs/install.md and the packaging +//! scripts), so removing the program cannot remove the books. +//! SCENARIOS: +//! 1. The three systems' folders, from one home. +//! ``` + +use ledger_store::root::{ROOT_NAME, data_dir_for, default_root}; +use std::path::Path; + +#[test] +fn each_system_keeps_its_data_where_it_keeps_an_apps_data() { + let home = Path::new("/home/someone"); + assert_eq!( + data_dir_for("macos", home), + home.join("Library/Application Support") + ); + assert_eq!( + data_dir_for("windows", home), + home.join("AppData").join("Local") + ); + for other in ["linux", "freebsd", "openbsd"] { + assert_eq!( + data_dir_for(other, home), + home.join(".local/share"), + "{other}" + ); + } + assert_eq!(ROOT_NAME, "wanderbooks"); +} + +#[test] +fn this_systems_default_root_is_its_data_folder_and_the_name() { + let home = Path::new("/home/someone"); + assert_eq!( + default_root(home), + data_dir_for(std::env::consts::OS, home).join(ROOT_NAME) + ); +} + +/// The program's install folders (the Windows installer's, the macOS +/// bundle's, the Linux packages') are never above or below a data folder. +#[test] +fn no_data_folder_is_inside_an_install_folder() { + let home = Path::new("/home/someone"); + let installs = [ + // Windows: the installer's InstallDir (deploy/packaging/windows). + home.join("AppData/Local/Programs/Wanderbooks"), + // macOS: the app (drag-to-Applications), and the per-user folder. + Path::new("/Applications/Wanderbooks.app").to_path_buf(), + home.join("Applications/Wanderbooks.app"), + // Linux packages. + Path::new("/usr/bin").to_path_buf(), + Path::new("/usr/share/wanderbooks").to_path_buf(), + ]; + for os in ["macos", "windows", "linux"] { + let data = data_dir_for(os, home).join(ROOT_NAME); + for install in &installs { + assert!( + !data.starts_with(install) && !install.starts_with(&data), + "{os}: {} and {} overlap", + data.display(), + install.display() + ); + } + } +} From b88331d44c07581c8a89b6a98cfdbc2585aaad53 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:44:30 -0700 Subject: [PATCH 08/11] ci(release): all three packages, tested on their own system, in a draft release with SHA-256 sums (P15 C1) The release workflow runs on a version tag (which must equal the program's version) or by hand, never on an ordinary push. Each system runs the workspace's whole tests, builds its package, signs it only when the owner's secrets exist (and says so in the run's notices when not), and checks it: the .deb and .rpm file lists; the Windows program's PE subsystem is the GUI one, and the installer is run silently, installed over itself, uninstalled, with a sentinel in the data folder that must survive; the dmg is opened (never run) and its app checked for both architectures, the plist, the licences and the signature. A last job gathers the packages, the licences, a latest.json with the version number the app's daily look reads, and SHA256SUMS.txt, into a DRAFT release; a release that is already published is never touched. The apt and dnf repositories are no longer pushed to by a tag: that is the manual publish-repos workflow, from a published release. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/publish-repos.yml | 55 ++++ .github/workflows/release.yml | 375 +++++++++++++++++++++------ crates/ledger-cli/tests/packaging.rs | 118 +++++++++ 3 files changed, 463 insertions(+), 85 deletions(-) create mode 100644 .github/workflows/publish-repos.yml diff --git a/.github/workflows/publish-repos.yml b/.github/workflows/publish-repos.yml new file mode 100644 index 00000000..76134b78 --- /dev/null +++ b/.github/workflows/publish-repos.yml @@ -0,0 +1,55 @@ +# Add a PUBLISHED release's .deb and .rpm to the apt and dnf repositories on +# the gh-pages branch (plan P11a step 3, D-26; GitHub Pages serves them). By +# hand only, after the release was tried and published: the release workflow +# never touches these repositories (plan P15 unit C1). Unsigned until the +# owner's release key signs the indexes (Q-4). +name: publish-repos + +on: + workflow_dispatch: + inputs: + tag: + description: "The published release's tag, e.g. v0.1.0" + required: true + +permissions: + contents: write + +jobs: + repos: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Repository tools + run: sudo apt-get update && sudo apt-get install -y apt-utils createrepo-c + - name: The release's .deb and .rpm (it must be published, not a draft) + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ inputs.tag }} + run: | + draft=$(gh release view "$TAG" --json isDraft --jq .isDraft) + [ "$draft" = false ] || { echo "$TAG is a draft: publish the release first" >&2; exit 1; } + mkdir assets + gh release download "$TAG" --dir assets --pattern '*.deb' --pattern '*.rpm' + ls -l assets + - name: Add them to the apt and dnf repositories (gh-pages) + env: + TAG: ${{ inputs.tag }} + run: | + git fetch origin gh-pages || true + if git rev-parse --verify origin/gh-pages >/dev/null 2>&1; then + git worktree add repo origin/gh-pages + else + git worktree add --detach repo && git -C repo checkout --orphan gh-pages && git -C repo rm -rfq . || true + fi + mkdir -p repo/apt/pool repo/dnf + cp assets/*.deb repo/apt/pool/ + cp assets/*.rpm repo/dnf/ + deploy/packaging/repo-indexes.sh apt repo/apt + deploy/packaging/repo-indexes.sh dnf repo/dnf + cd repo || exit 1 + git config user.name "wanderbooks release" + git config user.email "release@wanderbooks.ai" + git add -A + git commit -m "wanderbooks $TAG" + git push origin HEAD:gh-pages diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0094a6b6..e807c738 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,29 +1,67 @@ -# Releases (plan P11a, D-24, D-26): on a version tag, build the Linux -# packages on the oldest system they claim (ubuntu-24.04, glibc 2.39; a -# program linked on a newer one does not start on an older one), attach -# them to the GitHub release, and add them to the apt and dnf repositories -# on the gh-pages branch (GitHub Pages serves them). Unsigned: step 5 of -# the unit (the release key, Q-4) signs the manifest and the indexes. The -# macOS job builds the .dmg UNSIGNED (no Developer ID, no notarization: -# step 5); the Windows job is unit P11c. The release holds no key today. -# To see the artifacts without a tag: Actions > release > Run workflow, -# pick the branch; each job uploads its files as a run artifact. +# The release (plan P15 unit C1; WB-pkg-7): packages for Linux, Windows and +# macOS, built from one version, tested on their own system, and attached with +# their SHA-256 sums to a DRAFT GitHub release. Nothing here publishes: the +# release stays a draft until the owner has tried the packages and presses +# Publish, and nothing here touches the apt or dnf repositories (that is +# publish-repos.yml, by hand, from a published release). +# +# Runs on a version tag (v0.1.0: the tag must equal the program's version) or +# by hand (Actions > release > Run workflow, on a branch: a draft for +# v is made, nothing is tagged). It never runs on an ordinary push: +# the tests below take hours (the same ones the portable workflows run). +# +# Unsigned by default. With the owner's secrets it signs; without them each +# signing step says so in the run's notices and the package is unsigned: +# Windows: WINDOWS_CERTIFICATE_PFX_BASE64, WINDOWS_CERTIFICATE_PASSWORD +# macOS: APPLE_CERTIFICATE_P12_BASE64, APPLE_CERTIFICATE_PASSWORD, +# APPLE_SIGNING_IDENTITY, and to notarize APPLE_ID, APPLE_TEAM_ID, +# APPLE_APP_SPECIFIC_PASSWORD +# (docs/install.md, "Signing", says how each is made.) name: release on: push: tags: ["v*"] workflow_dispatch: + inputs: + run_tests: + description: "Run each system's whole test suite before packaging (hours). Turn off only when this commit's tests already passed." + type: boolean + default: true permissions: - contents: write + contents: read + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +env: + # Same disk discipline as check.yml: no incremental caches. + CARGO_INCREMENTAL: "0" jobs: + version: + name: The version (one source) + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + - name: Read the version from crates/ledger-cli/Cargo.toml and check the tag against it + id: version + run: | + own=$(sh deploy/packaging/version.sh) + if [ "${GITHUB_REF_TYPE}" = tag ] && [ "${GITHUB_REF_NAME#v}" != "$own" ]; then + echo "the tag $GITHUB_REF_NAME is not the program's version $own (crates/ledger-cli/Cargo.toml)" >&2 + exit 1 + fi + echo "version=$own" >> "$GITHUB_OUTPUT" + linux: + name: Linux (AppImage, .deb, .rpm, pacman) + needs: version runs-on: ubuntu-24.04 - # Same disk discipline as check.yml: no incremental caches. - env: - CARGO_INCREMENTAL: "0" steps: - uses: actions/checkout@v4 - name: Room for the build (the image ships toolchains we never use) @@ -34,90 +72,257 @@ jobs: - uses: jdx/mise-action@v2 with: # Only what packaging needs, not the proof and fuzz tools. - install_args: "rust just cargo:cargo-packager cargo:cargo-generate-rpm" + install_args: "rust just cargo:cargo-packager cargo:cargo-generate-rpm cargo:cargo-about" - name: GUI build dependencies - run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libgtk-3-dev apt-utils createrepo-c - - name: The tag is the program's version - id: version + run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libgtk-3-dev + - name: THIRD-PARTY-NOTICES.txt is up to date with what the program links + run: scripts/notices.sh --check + - name: Tests (the workspace's whole suite on Linux) + if: ${{ github.event_name != 'workflow_dispatch' || inputs.run_tests }} + run: cargo test --workspace --no-fail-fast + - name: Build the release program and the four packages (on the oldest system they claim, glibc 2.39) + run: just package-linux ${{ needs.version.outputs.version }} + - name: Check each package holds the program, the entry, the icon and the licences run: | - own=$(sed -n 's/^version = "\(.*\)"/\1/p' crates/ledger-cli/Cargo.toml | head -n1) - tag="${GITHUB_REF_NAME#v}" - if [ "${GITHUB_REF_TYPE}" = tag ] && [ "$tag" != "$own" ]; then - echo "tag $GITHUB_REF_NAME is not version $own" >&2 - exit 1 - fi - echo "version=$own" >> "$GITHUB_OUTPUT" - - name: Build the packages - run: just package-linux ${{ steps.version.outputs.version }} - - name: Attach them to the release - if: github.ref_type == 'tag' - env: - GH_TOKEN: ${{ github.token }} - run: | - v=${{ steps.version.outputs.version }} - gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 || gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes "wanderbooks $v" - gh release upload "$GITHUB_REF_NAME" --clobber target/packages/$v/*.AppImage target/packages/$v/*.deb target/packages/$v/*.rpm target/packages/$v/*.tar.gz - - name: Add them to the apt and dnf repositories (gh-pages) - if: github.ref_type == 'tag' - run: | - v=${{ steps.version.outputs.version }} - git fetch origin gh-pages || true - if git rev-parse --verify origin/gh-pages >/dev/null 2>&1; then - git worktree add repo origin/gh-pages + v=${{ needs.version.outputs.version }} + cd target/packages/$v || exit 1 + ls -l + for need in *.AppImage *.deb *.rpm *.tar.gz; do + test -s "$need" || { echo "no $need was built" >&2; exit 1; } + done + mkdir deb && (cd deb && ar x ../*.deb && tar -xf data.tar.* && ls -R . | head -50) + for f in usr/bin/wanderbooks usr/share/applications/wanderbooks.desktop \ + usr/share/icons/hicolor/512x512/apps/wanderbooks.png \ + usr/share/doc/wanderbooks/LICENSE-MIT usr/share/doc/wanderbooks/LICENSE-APACHE \ + usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt; do + test -e "deb/$f" || { echo "the .deb lacks $f" >&2; exit 1; } + done + rpm -qlp *.rpm > rpm.list 2>/dev/null || true + if [ -s rpm.list ]; then + for f in /usr/bin/wanderbooks /usr/share/applications/wanderbooks.desktop \ + /usr/share/doc/wanderbooks/LICENSE-MIT /usr/share/doc/wanderbooks/LICENSE-APACHE \ + /usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt; do + grep -qx "$f" rpm.list || { echo "the .rpm lacks $f" >&2; exit 1; } + done else - git worktree add --detach repo && git -C repo checkout --orphan gh-pages && git -C repo rm -rfq . || true + echo "::notice title=rpm not listed::rpm is not on this runner; the .rpm's files were not listed" fi - mkdir -p repo/apt/pool repo/dnf - cp target/packages/$v/*.deb repo/apt/pool/ - cp target/packages/$v/*.rpm repo/dnf/ - deploy/packaging/repo-indexes.sh apt repo/apt - deploy/packaging/repo-indexes.sh dnf repo/dnf - cd repo - git config user.name "wanderbooks release" - git config user.email "release@wanderbooks.ai" - git add -A - git commit -m "wanderbooks $v" - git push origin HEAD:gh-pages - - name: Keep them with the run (a dispatch has no release) + rm -rf deb rpm.list + - name: Keep the packages with the run uses: actions/upload-artifact@v4 with: name: linux-packages - path: target/packages/${{ steps.version.outputs.version }}/ + path: | + target/packages/${{ needs.version.outputs.version }}/*.AppImage + target/packages/${{ needs.version.outputs.version }}/*.deb + target/packages/${{ needs.version.outputs.version }}/*.rpm + target/packages/${{ needs.version.outputs.version }}/*.tar.gz + target/packages/${{ needs.version.outputs.version }}/PKGBUILD + if-no-files-found: error - macos: - # UNSIGNED: a .dmg that Gatekeeper refuses until step 5 signs and - # notarizes it. Apple silicon (macos-latest); an Intel build is not - # made yet. - runs-on: macos-latest + windows: + name: Windows (per-user installer) + needs: version + runs-on: windows-latest + defaults: + run: + shell: bash env: - CARGO_INCREMENTAL: "0" + WINDOWS_CERTIFICATE_PFX_BASE64: ${{ secrets.WINDOWS_CERTIFICATE_PFX_BASE64 }} + WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }} + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_PROFILE_TEST_DEBUG: line-tables-only steps: - uses: actions/checkout@v4 - - uses: jdx/mise-action@v2 - with: - install_args: "rust just cargo:cargo-packager" - - name: The tag is the program's version - id: version + - name: Rust (the version mise.toml pins) + run: rustup toolchain install 1.99 --profile minimal && rustup default 1.99 + - name: Tests (the same ones the portable-windows workflow runs) + if: ${{ github.event_name != 'workflow_dispatch' || inputs.run_tests }} run: | - own=$(sed -n 's/^version = "\(.*\)"/\1/p' crates/ledger-cli/Cargo.toml | head -n1) - tag="${GITHUB_REF_NAME#v}" - if [ "${GITHUB_REF_TYPE}" = tag ] && [ "$tag" != "$own" ]; then - echo "tag $GITHUB_REF_NAME is not version $own" >&2 - exit 1 + cargo build --workspace --all-targets + cargo test --workspace --no-fail-fast + - name: Build the release program + run: cargo build --release -p ledger-cli + - name: Check the program is a Windows GUI program (no console window) and still prints in a terminal + shell: pwsh + run: | + $exe = "target\release\wanderbooks.exe" + $bytes = [IO.File]::ReadAllBytes($exe) + $pe = [BitConverter]::ToInt32($bytes, 0x3C) + $subsystem = [BitConverter]::ToUInt16($bytes, $pe + 24 + 68) + if ($subsystem -ne 2) { throw "wanderbooks.exe has Windows subsystem $subsystem, not 2 (GUI): the app would open a console window" } + Write-Host "subsystem $subsystem (GUI)" + $said = (& $exe --help 2>&1 | Out-String) + if ($said -notmatch "usage") { throw "wanderbooks.exe --help printed no usage through a pipe: $said" } + - name: Sign the program (only when the certificate secrets exist; says so when not) + shell: pwsh + run: deploy\packaging\windows\sign-windows.ps1 target\release\wanderbooks.exe + - name: NSIS (the installer's compiler; free) + shell: pwsh + run: | + if (-not (Get-Command makensis -ErrorAction SilentlyContinue) -and -not (Test-Path "${env:ProgramFiles(x86)}\NSIS\makensis.exe")) { + choco install nsis -y --no-progress + } + if (-not (Test-Path "${env:ProgramFiles(x86)}\NSIS\makensis.exe") -and -not (Get-Command makensis -ErrorAction SilentlyContinue)) { throw "NSIS did not install" } + - name: Build the installer + run: deploy/packaging/windows/build-windows.sh ${{ needs.version.outputs.version }} + - name: Sign the installer (only when the certificate secrets exist; says so when not) + shell: pwsh + run: deploy\packaging\windows\sign-windows.ps1 (Get-ChildItem target\packages\${{ needs.version.outputs.version }}\*-setup.exe) + - name: Install it silently, check what it put where, then uninstall it and check the books are still there + shell: pwsh + run: | + $v = "${{ needs.version.outputs.version }}" + $setup = (Get-ChildItem "target\packages\$v\Wanderbooks-$v-windows-x64-setup.exe").FullName + $dir = Join-Path $env:LOCALAPPDATA "Programs\Wanderbooks" + $data = Join-Path $env:LOCALAPPDATA "wanderbooks" + New-Item -ItemType Directory -Force $data | Out-Null + Set-Content (Join-Path $data "sentinel.txt") "the person's books" + $p = Start-Process $setup -ArgumentList "/S" -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "the installer exited $($p.ExitCode)" } + foreach ($f in "wanderbooks.exe", "wanderbooks.ico", "LICENSE-MIT", "LICENSE-APACHE", "THIRD-PARTY-NOTICES.txt", "Uninstall Wanderbooks.exe") { + if (-not (Test-Path (Join-Path $dir $f))) { throw "the installer did not put $f in $dir" } + } + $lnk = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\Wanderbooks.lnk" + if (-not (Test-Path $lnk)) { throw "no Start Menu entry at $lnk" } + $shell = New-Object -ComObject WScript.Shell + $target = $shell.CreateShortcut($lnk).TargetPath + if ($target -ne (Join-Path $dir "wanderbooks.exe")) { throw "the Start Menu entry points at $target" } + $key = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Wanderbooks" + $entry = Get-ItemProperty $key + if ($entry.DisplayName -ne "Wanderbooks" -or $entry.DisplayVersion -ne $v) { throw "the Settings > Apps entry is wrong: $($entry | Out-String)" } + # Installing a newer one over it keeps the same path (the bridge's). + $p = Start-Process $setup -ArgumentList "/S" -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "installing over itself exited $($p.ExitCode)" } + if (-not (Test-Path (Join-Path $dir "wanderbooks.exe"))) { throw "the program is gone after installing over it" } + # Uninstall (in place, so this waits for it). + $p = Start-Process (Join-Path $dir "Uninstall Wanderbooks.exe") -ArgumentList "/S", "_?=$dir" -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "the uninstaller exited $($p.ExitCode)" } + if (Test-Path (Join-Path $dir "wanderbooks.exe")) { throw "the uninstaller left the program" } + if (Test-Path $lnk) { throw "the uninstaller left the Start Menu entry" } + if (Test-Path $key) { throw "the uninstaller left its Settings > Apps entry" } + if (-not (Test-Path (Join-Path $data "sentinel.txt"))) { throw "THE UNINSTALLER REMOVED THE BOOKS' FOLDER" } + Write-Host "installed, installed over itself, uninstalled; the books' folder was left alone" + - name: Keep the installer with the run + uses: actions/upload-artifact@v4 + with: + name: windows-installer + path: target/packages/${{ needs.version.outputs.version }}/Wanderbooks-*-windows-x64-setup.exe + if-no-files-found: error + + macos: + name: macOS (universal .app in a .dmg) + needs: version + runs-on: macos-latest + env: + # A Unix socket path holds 104 bytes on macOS, and the runner's default + # temp folder is longer than the tests' homes can afford (the same + # reason as in portable-macos.yml). + TMPDIR: /tmp + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_PROFILE_TEST_DEBUG: line-tables-only + APPLE_CERTIFICATE_P12_BASE64: ${{ secrets.APPLE_CERTIFICATE_P12_BASE64 }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }} + steps: + - uses: actions/checkout@v4 + - name: Rust (the version mise.toml pins), for both Macs + run: | + rustup toolchain install 1.99 --profile minimal && rustup default 1.99 + rustup target add aarch64-apple-darwin x86_64-apple-darwin + - name: Tests (the same ones the portable-macos workflow runs) + if: ${{ github.event_name != 'workflow_dispatch' || inputs.run_tests }} + run: | + cargo build --workspace --all-targets + cargo test --workspace --no-fail-fast + - name: Build the release program for Apple silicon + run: cargo build --release -p ledger-cli --target aarch64-apple-darwin + - name: Build the release program for Intel + run: cargo build --release -p ledger-cli --target x86_64-apple-darwin + - name: Put the Developer ID certificate in a temporary keychain (only when the secrets exist) + run: | + if [ -n "$APPLE_CERTIFICATE_P12_BASE64" ] && [ -n "$APPLE_CERTIFICATE_PASSWORD" ] && [ -n "$APPLE_SIGNING_IDENTITY" ]; then + deploy/packaging/macos/import-certificate.sh + else + echo "::notice title=macOS signing skipped::no APPLE_CERTIFICATE_P12_BASE64, APPLE_CERTIFICATE_PASSWORD and APPLE_SIGNING_IDENTITY secrets: the app is signed ad hoc and macOS Gatekeeper will refuse a download of it" fi - echo "version=$own" >> "$GITHUB_OUTPUT" - - name: Build the unsigned .dmg - run: just package-macos ${{ steps.version.outputs.version }} - - name: Attach it to the release - if: github.ref_type == 'tag' + - name: Build, sign, notarize (each only when its secrets exist) and staple the .dmg + env: + WB_SIGN_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + WB_NOTARY_APPLE_ID: ${{ secrets.APPLE_ID }} + WB_NOTARY_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + WB_NOTARY_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }} + run: deploy/packaging/macos/build-macos.sh ${{ needs.version.outputs.version }} + - name: Check the .dmg holds a universal, hardened, well-formed app (opened, not run) + run: | + v=${{ needs.version.outputs.version }} + dmg=$(ls target/packages/$v/Wanderbooks-$v-macos-universal.dmg) + mnt=$(mktemp -d /tmp/wbdmg.XXXXXX) + hdiutil attach "$dmg" -mountpoint "$mnt" -nobrowse -readonly + trap 'hdiutil detach "$mnt" -quiet || true' EXIT + app="$mnt/Wanderbooks.app" + test -d "$app" || { echo "no Wanderbooks.app in the .dmg" >&2; exit 1; } + test -L "$mnt/Applications" || { echo "no Applications shortcut in the .dmg" >&2; exit 1; } + lipo -archs "$app/Contents/MacOS/wanderbooks" + lipo -archs "$app/Contents/MacOS/wanderbooks" | grep -q arm64 + lipo -archs "$app/Contents/MacOS/wanderbooks" | grep -q x86_64 + plutil -lint "$app/Contents/Info.plist" + test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Contents/Info.plist")" = ai.wanderbooks.app + test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app/Contents/Info.plist")" = "$v" + test -f "$app/Contents/Resources/wanderbooks.icns" + for f in LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt; do test -f "$app/Contents/Resources/$f"; done + codesign --verify --deep --strict --verbose=2 "$app" + codesign -dv --verbose=4 "$app" 2>&1 | grep -E "flags=|Authority|Signature|TeamIdentifier" || true + - name: Keep the .dmg with the run + uses: actions/upload-artifact@v4 + with: + name: macos-dmg + path: target/packages/${{ needs.version.outputs.version }}/Wanderbooks-*-macos-universal.dmg + if-no-files-found: error + + draft-release: + name: A draft release with the packages and their SHA-256 sums + needs: [version, linux, windows, macos] + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + - name: Fetch the three platforms' packages + uses: actions/download-artifact@v4 + with: + path: dist-parts + - name: Gather the files, the licences, the update note and the SHA-256 sums + run: | + v=${{ needs.version.outputs.version }} + mkdir dist + find dist-parts -type f -exec cp {} dist/ \; + cp LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt dist/ + # The note the app's daily look reads (crates/ledger-host/src/newer.rs): + # a version number and nothing else it uses. + printf '{"version":"%s"}\n' "$v" > dist/latest.json + (cd dist && sha256sum -- * > SHA256SUMS.txt && cat SHA256SUMS.txt) + ls -l dist + - name: Make or refresh the DRAFT release (a published release is never touched) env: GH_TOKEN: ${{ github.token }} run: | - v=${{ steps.version.outputs.version }} - gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 || gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes "wanderbooks $v" - gh release upload "$GITHUB_REF_NAME" --clobber target/packages/$v/*.dmg - - name: Keep it with the run (a dispatch has no release) - uses: actions/upload-artifact@v4 - with: - name: macos-dmg-unsigned - path: target/packages/${{ steps.version.outputs.version }}/*.dmg + v=${{ needs.version.outputs.version }} + tag="v$v" + if gh release view "$tag" >/dev/null 2>&1; then + draft=$(gh release view "$tag" --json isDraft --jq .isDraft) + if [ "$draft" != true ]; then + echo "$tag is already published: this workflow never changes a published release" >&2 + exit 1 + fi + gh release upload "$tag" --clobber dist/* + else + gh release create "$tag" --draft --target "$GITHUB_SHA" \ + --title "Wanderbooks $v" \ + --notes "Wanderbooks $v. Unsigned builds warn on first run: see docs/install.md. Check the SHA-256 sums in SHA256SUMS.txt." \ + dist/* + fi + echo "A draft release $tag holds the packages. Try them, then publish it by hand." diff --git a/crates/ledger-cli/tests/packaging.rs b/crates/ledger-cli/tests/packaging.rs index a1c6bed3..f8c19580 100644 --- a/crates/ledger-cli/tests/packaging.rs +++ b/crates/ledger-cli/tests/packaging.rs @@ -568,3 +568,121 @@ fn no_package_runs_a_script_that_could_touch_the_books() { assert!(!rpm.contains(key), "{key} in Cargo.toml"); } } + +// ---- the release workflow ------------------------------------------------------- + +/// WB-pkg-7: the release builds all three packages, ends in a DRAFT with the +/// SHA-256 sums, runs only on a version tag or by hand, and publishes +/// nothing by itself. +#[test] +fn the_release_workflow_makes_a_draft_of_all_three_packages_and_publishes_nothing() { + let text = read(".github/workflows/release.yml"); + let lines = code(&text); + let has = |needle: &str| lines.iter().any(|l| l.contains(needle)); + + // Triggers: a tag or by hand; never an ordinary push or a pull request. + let on = lines + .iter() + .position(|l| *l == "on:") + .expect("an `on:` block"); + let jobs = lines.iter().position(|l| *l == "jobs:").expect("jobs"); + let triggers: Vec<&&str> = lines[on + 1..jobs].iter().collect(); + assert!( + triggers.iter().any(|l| l.starts_with("tags:")), + "{triggers:?}" + ); + assert!(triggers.iter().any(|l| l.starts_with("workflow_dispatch:"))); + assert!( + !triggers + .iter() + .any(|l| l.starts_with("pull_request") || l.starts_with("schedule")) + ); + let push = triggers + .iter() + .position(|l| l.starts_with("push:")) + .unwrap(); + assert!( + triggers[push + 1].starts_with("tags:"), + "a push trigger without tags" + ); + + // All three systems, each tested on its own system before packaging. + for runner in ["ubuntu-24.04", "windows-latest", "macos-latest"] { + assert!(has(&format!("runs-on: {runner}")), "{runner}"); + } + assert_eq!( + lines + .iter() + .filter(|l| l.contains("cargo test --workspace --no-fail-fast")) + .count(), + 3, + "each system runs the workspace's tests" + ); + // The three packages, the sums, the licences and the update note. + for needle in [ + "just package-linux", + "build-windows.sh", + "build-macos.sh", + "sha256sum", + "SHA256SUMS.txt", + "THIRD-PARTY-NOTICES.txt", + "LICENSE-MIT", + "LICENSE-APACHE", + "latest.json", + "scripts/notices.sh --check", + ] { + assert!(has(needle), "{needle} is not in the release workflow"); + } + // A draft, never published, never a published release touched. + assert!(has("gh release create")); + assert!(has("--draft")); + for never in [ + "--draft=false", + "gh release edit", + "gh-pages", + "prerelease=false", + "make_latest", + ] { + assert!(!has(never), "{never} would publish"); + } + assert!(has("never changes a published release")); + // Secrets are read by name from the secrets store, never written here. + for secret in [ + "WINDOWS_CERTIFICATE_PFX_BASE64", + "APPLE_CERTIFICATE_P12_BASE64", + "APPLE_SIGNING_IDENTITY", + "APPLE_APP_SPECIFIC_PASSWORD", + ] { + assert!(has(&format!("${{{{ secrets.{secret} }}}}")), "{secret}"); + } + // Signing steps say so when they are skipped. + assert!(has("macOS signing skipped")); + assert!(read("deploy/packaging/windows/sign-windows.ps1").contains("Windows signing skipped")); + assert!(read("deploy/packaging/macos/build-macos.sh").contains("macOS notarization skipped")); + // The Windows job installs and uninstalls the installer, and checks the + // books' folder survives. + assert!(has("THE UNINSTALLER REMOVED THE BOOKS' FOLDER")); + assert!(has("subsystem -ne 2")); +} + +#[test] +fn only_a_person_runs_the_workflow_that_publishes_the_repositories() { + let text = read(".github/workflows/publish-repos.yml"); + let lines = code(&text); + let on = lines.iter().position(|l| *l == "on:").unwrap(); + let jobs = lines.iter().position(|l| *l == "jobs:").unwrap(); + assert_eq!( + lines[on + 1..jobs] + .iter() + .filter(|l| l.ends_with(':') && !l.starts_with("tag")) + .count(), + 2 + 1, + "workflow_dispatch and its inputs, nothing else: {:?}", + &lines[on + 1..jobs] + ); + assert!(lines.iter().any(|l| l.starts_with("workflow_dispatch:"))); + assert!( + lines.iter().any(|l| l.contains("isDraft")), + "it refuses a draft" + ); +} From 2c9aea08836b930d6857b5b5ff1901e704b2e054 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:44:38 -0700 Subject: [PATCH 09/11] test(packaging): the publish workflow's trigger is checked by what it must not have (P15 C1) Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/packaging.rs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/crates/ledger-cli/tests/packaging.rs b/crates/ledger-cli/tests/packaging.rs index f8c19580..5e5f0e57 100644 --- a/crates/ledger-cli/tests/packaging.rs +++ b/crates/ledger-cli/tests/packaging.rs @@ -671,15 +671,12 @@ fn only_a_person_runs_the_workflow_that_publishes_the_repositories() { let lines = code(&text); let on = lines.iter().position(|l| *l == "on:").unwrap(); let jobs = lines.iter().position(|l| *l == "jobs:").unwrap(); - assert_eq!( - lines[on + 1..jobs] - .iter() - .filter(|l| l.ends_with(':') && !l.starts_with("tag")) - .count(), - 2 + 1, - "workflow_dispatch and its inputs, nothing else: {:?}", - &lines[on + 1..jobs] - ); + for l in &lines[on + 1..jobs] { + assert!( + !(l.starts_with("push:") || l.starts_with("pull_request") || l.starts_with("schedule")), + "{l}: only workflow_dispatch may start it" + ); + } assert!(lines.iter().any(|l| l.starts_with("workflow_dispatch:"))); assert!( lines.iter().any(|l| l.contains("isDraft")), From 27f960743495c8deb9e7227465506021a489102d Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:48:26 -0700 Subject: [PATCH 10/11] docs(packaging): installing, the unit's claims, status, and the git decision; the Linux packages depend on git (P15 C1) docs/install.md is three short sections for a person installing. docs/packaging.md records what the installed app is on each system, why NSIS and the macOS bundle are scripts of our own, how signing is wired with the owner's secrets, what was left out, and what bundling git would require (GPL-2.0, separate program, unmodified: notices, source offer), which stays the owner's decision. WB-pkg-1 to WB-pkg-8 are the product rules. The Linux packages, the AUR file and the rpm now depend on git, so the package manager fetches it and a Linux person never meets the missing-git words. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/Cargo.toml | 2 + crates/ledger-cli/tests/extension.rs | 6 +- crates/ledger-cli/tests/packaging.rs | 24 ++++ crates/ledger-host/src/extension.rs | 10 +- deploy/README.md | 3 + deploy/packaging/aur/PKGBUILD | 2 +- deploy/packaging/packager.toml | 6 +- docs/install.md | 63 ++++++++++ docs/packaging.md | 92 +++++++++++++- docs/spec/claims/packaging.md | 175 +++++++++++++++++++++++++++ plan/STATUS.md | 29 +++++ 11 files changed, 399 insertions(+), 13 deletions(-) create mode 100644 docs/install.md create mode 100644 docs/spec/claims/packaging.md diff --git a/crates/ledger-cli/Cargo.toml b/crates/ledger-cli/Cargo.toml index ff19b180..a992303d 100644 --- a/crates/ledger-cli/Cargo.toml +++ b/crates/ledger-cli/Cargo.toml @@ -75,6 +75,8 @@ workspace = true # program: `just package-linux`. Paths are relative to the workspace root. [package.metadata.generate-rpm] name = "wanderbooks" +# Backups run the system's git (WB-pkg-4): dnf fetches it. +requires = { git = "*" } summary = "Double-entry bookkeeping your agent keeps and you can read" license = "MIT OR Apache-2.0" url = "https://wanderbooks.ai" diff --git a/crates/ledger-cli/tests/extension.rs b/crates/ledger-cli/tests/extension.rs index da9a213a..1c0bda51 100644 --- a/crates/ledger-cli/tests/extension.rs +++ b/crates/ledger-cli/tests/extension.rs @@ -6,8 +6,10 @@ //! ```text //! GOAL: a package the Claude desktop app can install, naming this //! program's bridge for one company, with nothing secret in it. -//! SOURCE: WB-pkg-5; github.com/anthropics/mcpb (MANIFEST.md, the 0.3 -//! schema); ledger-host extension.rs. +//! SOURCE: WB-pkg-5; Anthropic's MCP Bundle manifest specification +//! (the manifest page and the version 0.3 JSON schema of its +//! mcpb repository on GitHub); the writer's own spec block in +//! the host crate. //! INVARIANTS: //! 1. The package is a zip whose root holds `manifest.json`; every file //! the manifest names (`icon`, `server.entry_point`) is in the zip. diff --git a/crates/ledger-cli/tests/packaging.rs b/crates/ledger-cli/tests/packaging.rs index 5e5f0e57..b54eaca4 100644 --- a/crates/ledger-cli/tests/packaging.rs +++ b/crates/ledger-cli/tests/packaging.rs @@ -683,3 +683,27 @@ fn only_a_person_runs_the_workflow_that_publishes_the_repositories() { "it refuses a draft" ); } + +/// WB-pkg-4: on Linux git is a dependency of every package, so the package +/// manager fetches it; nothing carries a git of its own. +#[test] +fn the_linux_packages_depend_on_git_and_none_carries_one() { + let packager = read("deploy/packaging/packager.toml"); + assert_eq!( + packager.matches("\"git\"").count(), + 2, + "the deb and the pacman package depend on git" + ); + assert!(read("crates/ledger-cli/Cargo.toml").contains("requires = { git = \"*\" }")); + assert!(read("deploy/packaging/aur/PKGBUILD").contains("'git'")); + for file in [ + "deploy/packaging/windows/wanderbooks.nsi", + "deploy/packaging/macos/build-macos.sh", + ] { + let text = read(file).to_lowercase(); + assert!( + !text.contains("mingit") && !text.contains("git.exe"), + "{file} bundles a git" + ); + } +} diff --git a/crates/ledger-host/src/extension.rs b/crates/ledger-host/src/extension.rs index 546142be..8be6a727 100644 --- a/crates/ledger-host/src/extension.rs +++ b/crates/ledger-host/src/extension.rs @@ -12,11 +12,11 @@ //! desktop's Settings > Extensions > Advanced settings > Install //! Extension, and Claude can keep that company's books, with no //! command typed and no file edited. -//! SOURCE: WB-pkg-5; Anthropic's MCPB manifest specification, version -//! 0.3 (github.com/anthropics/mcpb, MANIFEST.md and -//! schemas/mcpb-manifest-v0.3.schema.json, read 2026-11-21) and -//! Claude's help article "Getting started with Local MCP servers -//! on Claude Desktop" (the install steps). +//! SOURCE: WB-pkg-5; Anthropic's MCP Bundle manifest specification, +//! version 0.3 (the manifest page and the version 0.3 JSON +//! schema of Anthropic's mcpb repository on GitHub, read +//! 2026-11-21) and Claude's help article "Getting started with +//! Local MCP servers on Claude Desktop" (the install steps). //! INVARIANTS: //! 1. The manifest holds only fields the specification defines, with //! `manifest_version` "0.3", a `server` of type `binary` whose diff --git a/deploy/README.md b/deploy/README.md index 8f5641d5..6d0630c8 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -6,6 +6,9 @@ account can read, and agents reach them through the server with a token. Locally the books are `same_user (advisory)` — hidden from the agent, not locked against it; here they are behind an account and a machine boundary. +This is the recipe for a machine with no window. To install the app on a +computer you sit at (Windows, macOS, Linux), see `docs/install.md`. + Nothing here needs the owner's books: every step works on a copy. The pieces: diff --git a/deploy/packaging/aur/PKGBUILD b/deploy/packaging/aur/PKGBUILD index 020b382c..77d469f9 100644 --- a/deploy/packaging/aur/PKGBUILD +++ b/deploy/packaging/aur/PKGBUILD @@ -9,7 +9,7 @@ pkgdesc="Double-entry bookkeeping your agent keeps and you can read" arch=('x86_64') url="https://wanderbooks.ai" license=('MIT' 'Apache-2.0') -depends=('gcc-libs' 'glibc') +depends=('gcc-libs' 'glibc' 'git') provides=('wanderbooks') conflicts=('wanderbooks') options=('!lto' '!strip') diff --git a/deploy/packaging/packager.toml b/deploy/packaging/packager.toml index 4f5d917c..7a0b9791 100644 --- a/deploy/packaging/packager.toml +++ b/deploy/packaging/packager.toml @@ -24,7 +24,9 @@ section = "utils" # A deb marks itself package-managed: `wanderbooks update` refuses on it # and says to use apt (plan 3.9). desktop-template = "deploy/packaging/wanderbooks.desktop" -depends = ["libc6", "libgcc-s1"] +# git: the backups run the system's git (WB-pkg-4); the package manager +# fetches it, so a Linux person never sees the missing-git words. +depends = ["libc6", "libgcc-s1", "git"] [deb.files] "deploy/packaging/install-method-deb" = "usr/share/wanderbooks/install-method" @@ -40,7 +42,7 @@ depends = ["libc6", "libgcc-s1"] "LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE" [pacman] -depends = ["gcc-libs", "glibc"] +depends = ["gcc-libs", "glibc", "git"] [pacman.files] "deploy/packaging/install-method-aur" = "usr/share/wanderbooks/install-method" diff --git a/docs/install.md b/docs/install.md new file mode 100644 index 00000000..3fbf7944 --- /dev/null +++ b/docs/install.md @@ -0,0 +1,63 @@ +# Installing Wanderbooks + +For a person who wants to use it. Three short sections, one per system, then +what to do after. The release page has the files: +https://github.com/swaits/wanderbooks/releases/latest + +Wanderbooks keeps your books on your own computer. An assistant (Claude, +ChatGPT, Codex and others) can reach them **only while Wanderbooks is open**, +and only the companies you have open in its tabs. When you are finished, +close the window: that quits Wanderbooks fully and closes your books. + +## Windows + +1. Download `Wanderbooks-…-windows-x64-setup.exe` and double-click it. It asks + for no administrator password: it installs for you alone. +2. Until the installer is signed, Windows shows "Windows protected your PC". + Choose **More info**, then **Run anyway**. (Unsigned software always does + this the first time.) +3. Open **Wanderbooks** from the Start Menu. The first time, it makes your + books' folder and helps you connect your assistant. +4. To update, run the newer installer over the old one. To remove it, use + Settings, Apps, Wanderbooks. Neither touches your books. + +Where things are: the program is in `%LOCALAPPDATA%\Programs\Wanderbooks`; your +books, keys and backups are in `%LOCALAPPDATA%\wanderbooks`. +Backups need Git for Windows (https://git-scm.com/download/win, or `winget +install --id Git.Git -e`); without it Wanderbooks works and says so. + +## macOS + +1. Download `Wanderbooks-…-macos-universal.dmg` (one file for Apple silicon and + Intel), open it, and drag **Wanderbooks** onto **Applications**. +2. Open it from Applications, not from the disk image or your Downloads folder + (an assistant needs the program to stay in one place). Until the app is + notarized by Apple, the first time: right-click it, choose **Open**, then + **Open** again. +3. To update, quit Wanderbooks and drag the newer app over the old one. To + remove it, drag it to the Trash. Neither touches your books. + +Your books, keys and backups are in `~/Library/Application Support/wanderbooks`. +Backups need git: run `xcode-select --install` in Terminal (or `brew install +git`). + +## Linux + +Use the package for your system from the release page: the `.deb` (Debian, +Ubuntu), the `.rpm` (Fedora), the Arch package, or the AppImage (one file: mark +it executable, keep it where you put it, and run it). Open **Wanderbooks** from +the menu. To update, install the newer package, or replace the AppImage. Your +books are in `~/.local/share/wanderbooks` and are never touched by a package. +Backups need git (`sudo apt install git`, `sudo dnf install git`, +`sudo pacman -S git`). + +## After it is installed + +Open the **Assistants** page of a company. Pick the assistant you use: Claude +Code and Codex have a button; **Claude desktop app** has a button that makes one +extension file to open in Claude (Settings, Extensions, Advanced settings, +Install Extension); web assistants have an address and the steps. Wanderbooks +tells you in the window when a newer version is out. + +`wanderbooks serve` (a server with no window, for another computer) is for +people who run it themselves: see `deploy/README.md`. diff --git a/docs/packaging.md b/docs/packaging.md index 5d221ade..730c9a6f 100644 --- a/docs/packaging.md +++ b/docs/packaging.md @@ -16,8 +16,8 @@ not a tool, so there is nothing for a recipe to call. | `.rpm` | `cargo-generate-rpm` (table in `crates/ledger-cli/Cargo.toml`) | same paths, marker `rpm`; 36 MB | dnf repository (`repo-indexes.sh dnf`) | unsigned until step 5 (`--signing-key` takes the PGP key then) | | AUR `PKGBUILD` | `cargo packager` makes the tarball (`pacman` format) and a PKGBUILD for it; ours is `deploy/packaging/aur/PKGBUILD`, which repacks the release's tarball (package `wanderbooks-bin`) | same paths, marker `aur`; built with `makepkg` | pacman (the AUR keeps old PKGBUILDs) | n/a (pacman trusts the AUR's checksums) | | AppImage | `cargo packager` (`appimage`); 44 MB | one file the owner puts anywhere and runs; needs no admin password | `wanderbooks update` (`$APPIMAGE` is the file replaced) against the manifest; minisign | minisign by the release key (step 5) | -| `.dmg` | `cargo packager` (`dmg`), `deploy/packaging/build-macos.sh`; **built in CI, unsigned; the trial on a Mac is the owner's** | `Wanderbooks.app` dragged to Applications; no admin password (the trial will say) | `wanderbooks update` (it replaces the program inside the `.app`: see the note below) | **unsigned**; Developer ID and notarization are step 5 | -| NSIS `.exe` | `cargo packager` (`nsis`) | **not built**: native Windows is unit P11c (D-62) | `wanderbooks update` | the Windows identity (step 5) | +| `.dmg` | `deploy/packaging/macos/build-macos.sh` (P15 C1; it replaced the cargo-packager `dmg` config, unrun) | `Wanderbooks.app` dragged to Applications; one universal program at `Contents/MacOS/wanderbooks`; no admin password | the newer app dragged over the old (the program tells the person one exists) | hardened runtime; Developer ID and notarization when the owner's secrets are in the release workflow, else ad hoc | +| Windows `.exe` | `deploy/packaging/windows/build-windows.sh` with NSIS (P15 C1; not cargo-packager's `nsis`) | `%LOCALAPPDATA%\Programs\Wanderbooks\wanderbooks.exe`, Start Menu entry, Settings > Apps uninstaller; per user, no admin | the newer installer run over the old one (the program tells the person one exists) | Authenticode when the owner's certificate secrets are in the release workflow, else unsigned | `just package-linux` builds the first four (`deploy/packaging/build-linux.sh`, about a minute after the release build, itself 8 to 12 minutes on a @@ -130,7 +130,7 @@ package manager. Not tested: Ubuntu, openSUSE, a package-manager *downgrade* (the repositories keep every release by construction), and the `.rpm` and `.deb` under their real signatures (step 5). -## The macOS bundle (step 6, built in CI, unsigned) +## The macOS bundle (step 6; REPLACED by P15 unit C1, see "P15 unit C1" below) `deploy/packaging/packager-macos.toml` (cargo-packager: the `dmg` format, which makes the `.app` first; the icon is the 512 px PNG, made into an @@ -260,3 +260,89 @@ not a `cfg` gap. Today Unix-only, found by grep (2026-10-29): file with read, write and delete sharing, so a rename never meets an open handle of ours. - The `portable` job runs Windows as a gate (`experimental: false`), since the port landed (P11c). + + +## P15 unit C1: the installed app on the new shape (2026-11-21) + +Written on Linux. **Nothing here has been run on Windows or macOS**: the +`release` workflow's first run on GitHub is the evidence, and it is built to +fail loudly at each step. What Linux checked: `crates/ledger-cli/tests/packaging.rs` +reads the installer script, the plist, the entitlements, the desktop entries and +the workflow; builds the macOS bundle with a stand-in program; compiles the +installer with `makensis` when it is installed; and a real `.deb` and `.rpm` +were built with a stand-in program and their file lists read (program, desktop +entry, icon, licences). + +| | Windows | macOS | Linux | +|---|---|---|---| +| Package | NSIS installer, per user | `.app` in a `.dmg`, one universal program | `.deb`, `.rpm`, pacman tarball, AppImage (unchanged tools) | +| Program path (the bridge's) | `%LOCALAPPDATA%\Programs\Wanderbooks\wanderbooks.exe` | `/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks` | `/usr/bin/wanderbooks`; the AppImage's own file | +| Books | `%LOCALAPPDATA%\wanderbooks` | `~/Library/Application Support/wanderbooks` | `~/.local/share/wanderbooks` (unchanged) | +| Removal leaves the books | the uninstaller names no data folder | dragging to Trash runs nothing | no package script runs | +| No console window | built for the GUI subsystem; attaches to a terminal for commands | n/a | n/a | +| Without git | says how to get Git for Windows | says `xcode-select --install`; the system's stub is not taken for git | says the package manager's command | + +**Why NSIS written by hand, not cargo-packager's.** The installer's rules +(per user, one program, an uninstaller that can never reach the books) are +short and exact; a script of our own states them in a file a test can read, and +needs only `makensis` (free, zlib-licensed, `choco install nsis`). cargo-packager's +NSIS template downloads helper plugins at build time and ships an uninstaller +option that removes application data. **Why the macOS bundle is assembled by a +script:** signing order (inside out, hardened runtime, then the disk image, then +notarization) and the entitlements are exact, and the secrets contract is ours. +cargo-packager stays for Linux. + +**Updating** is installing the newer package over the old one; the program says +when one exists (`ledger_host::newer`: a version number from `latest.json`, +once a day, a fixed download address) and never installs anything. The earlier +staged self-update (`update`, `update.lock`, the daily staged download) still +exists for an AppImage or a program put somewhere by hand and needs a release +key that does not exist yet; on the desktop the detached host it restarted +through is gone (P15 A5). A macOS `.app` is never updated one file at a time. + +**Signing.** Windows (secrets `WINDOWS_CERTIFICATE_PFX_BASE64`, +`WINDOWS_CERTIFICATE_PASSWORD`): `sign-windows.ps1` signs the program, then the +installer. macOS (`APPLE_CERTIFICATE_P12_BASE64`, `APPLE_CERTIFICATE_PASSWORD`, +`APPLE_SIGNING_IDENTITY`; to notarize `APPLE_ID`, `APPLE_TEAM_ID`, +`APPLE_APP_SPECIFIC_PASSWORD`): `import-certificate.sh` puts the certificate in +a temporary keychain, `build-macos.sh` signs with the hardened runtime, +notarizes and staples. With none, each step prints a notice and the package is +unsigned (macOS: ad hoc, so it runs, but Gatekeeper refuses a download). + +**The Claude desktop extension** (`ledger_host::extension`): an MCP Bundle +(`.mcpb`, the renamed `.dxt`; manifest version 0.3), one per company, made by the +Connect page's button; it runs the installed program as `mcp --book `. + +**Left out, on purpose:** an auto-installer; a Windows executable icon resource +(the shortcut and the uninstaller entry carry the icon; the running window uses +the system's default) and the window's own icon on Windows and Linux X11; +`wanderbooks.cmd`/PATH setup so a terminal waits for a command on Windows (a +GUI-subsystem program returns the prompt at once); a macOS refusal for a program +run from a mounted disk image (a path under `/Volumes` may be a real install on +another disk); bundling git on Windows and macOS (the owner's decision, below); the signed `manifest.json` of the earlier self-update +(needs the release key, Q-4). + +### Bundling git (an owner decision, not made here) + +Backups run the system's git. **Linux:** the packages now depend on git, so the +package manager fetches it (nothing is bundled). **Windows and macOS:** the app +detects a missing git and says how to get it (WB-pkg-4); nothing is bundled. + +What bundling would mean. Git is GPL-2.0-only free software. Shipping an +unmodified git as a separate file that our program starts as its own process +(never linked) is what the GPL calls aggregation: our MIT OR Apache-2.0 code is +unaffected, and AGENTS.md's clean-room rule (never copy GnuCash's code) is not +touched, since nothing of git is copied into ours; `deny.toml` governs Rust +crates only and does not see it. It still requires, for each release that +carries git: git's GPL text and copyright notices beside it (Git for Windows' +MinGit adds the notices of the components it carries: OpenSSL/curl, the MSYS2 +runtime); the corresponding source of exactly that git, or a written offer for it +valid three years (GPLv2 section 3), most simply the git version's source +archive attached to the same release; no term of ours that forbids the +recipient what the GPL permits; and a note of any change if git were modified. +`THIRD-PARTY-NOTICES.txt` (cargo-about) covers Rust crates only, so it would +need an addition. On Windows the candidate is MinGit from Git for Windows +(about 40 MB, unpacked beside the program; `Git::find` would look there first); +on macOS Apple's command line tools' git is Apple's and cannot be bundled, so +it would be a build of our own (Homebrew's, or from source), universal, signed +inside the app, with the same obligations. diff --git a/docs/spec/claims/packaging.md b/docs/spec/claims/packaging.md new file mode 100644 index 00000000..d6fd5c05 --- /dev/null +++ b/docs/spec/claims/packaging.md @@ -0,0 +1,175 @@ +# Claims: packaging + +Wanderbooks' own product rules for how the program is installed, named, +updated and removed on Windows, macOS and Linux (plan P15 unit C1, +`plan/p15-app-and-relay.md`). No authority outside this product states them. +They are `WB-pkg-`. + +Rules: none from bookspec's list; these are product rules only. + +--- + +### Product rules + +**WB-pkg-1 It installs like a normal program, and taking it away never takes +the books.** A person downloads one file and opens it. On Windows that is an +installer that asks for no administrator password, installs under their own +profile, adds a Start Menu entry named Wanderbooks with the icon, and lists +an uninstaller in Settings. On macOS it is a disk image holding the app and a +shortcut to Applications to drag it onto. On Linux it is the package manager's +package, or one AppImage file. The Windows uninstaller removes exactly the +files the installer put in its own folder, the Start Menu entry and two +registry keys of its own: it uses no recursive removal and no wildcard and +names the data folder nowhere, and it asks the person to quit the app first +rather than fail on a program that is running. Moving the macOS app to the +Trash, or removing a Linux package, never runs a script. Each leaves the +person's books, keys, backups and settings where they are (WB-pkg-8). +*Enforced:* `deploy/packaging/windows/wanderbooks.nsi`, +`deploy/packaging/macos/build-macos.sh`, `deploy/packaging/packager.toml`. +*Checked:* `ledger-cli` `tests/packaging.rs` +(`the_windows_installer_is_per_user_and_installs_one_program`, +`the_uninstaller_never_removes_the_books`, +`no_package_runs_a_script_that_could_touch_the_books`, +`the_installer_script_compiles_when_nsis_is_here`, +`the_macos_bundle_has_one_program_and_a_plist_that_agrees_with_the_scripts`); +the release workflow's Windows job installs the installer, installs it over +itself and uninstalls it with a marker in the data folder that must survive. + +**WB-pkg-2 One executable is the window, the books server and the +assistants' bridge, and the path an assistant is given does not change.** The +installed program is one file, `wanderbooks`, started three ways: with +nothing to say, as the window; by the window with `server`, as its child; and +by an assistant with `mcp --book`, as the bridge. No second program is +installed. The path an assistant is registered with is the installed file's own: +`%LOCALAPPDATA%\Programs\Wanderbooks\wanderbooks.exe` on Windows, which the +installer replaces in place; `/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks` +on macOS, which dragging a newer app over the old one replaces; `/usr/bin/wanderbooks` +for a Linux package, replaced by the package manager; and the AppImage's own +file, which the person keeps where they put it. On macOS a program running from +the temporary copy the system makes of a quarantined download still refuses to +register an assistant, in words, since that path goes away. On Windows the file +is built for the GUI subsystem, so starting it from the Start Menu opens no +console window; run from a terminal it attaches to that terminal so a +command's words appear there, and it never replaces a pipe an assistant gave +it. The two console programs the window starts (the assistant's own list and +the system's opener) are started without a console window. +*Enforced:* `ledger_host::start::translocation_refusal`, +`ledger_host::start::this_executable`, `crates/ledger-cli/src/console.rs` (the Windows +console), `ledger_host::app_server` (the server child). +*Checked:* `ledger-cli` `tests/one_executable.rs` +(`each_mode_names_itself_in_its_usage`), `tests/translocation.rs` +(`translocated_app_refuses_to_connect`), +`tests/packaging.rs` (`the_windows_program_opens_no_console_window_and_still_speaks_in_a_terminal`, +`the_macos_bundle_has_one_program_and_a_plist_that_agrees_with_the_scripts`); +the release workflow's Windows job checks the built file's subsystem is the GUI one +and that it still prints through a pipe. + +**WB-pkg-3 An update is the newer package installed over the old one, and the +app says when one exists.** The program installs nothing by itself. Once a day +at most, on a thread of its own, it reads one small public file a release +publishes and takes the version number from it and nothing else: where to get +the update is an address fixed in the program, never one the file names. A +higher version shows a notice in the window with a button to the download page, +and says the books, keys and connections stay as they are, because they live in +the data folder and the bridge's path is the same (WB-pkg-2). "Check for +updates" looks at once. The look sends no version, company or identifier and +a failed look is silent. A macOS app is never updated one file at a time +(that would break its signature): the program treats it as managed and says to +drag the newer app over the old one. Where the program may replace itself with +a release signed by our key (an AppImage, a program put somewhere by hand), the +earlier staged update still works; no release key exists yet, so today none does. +*Enforced:* `ledger_host::newer`, `ledger_host::update::install_kind`, +`ledger_host::commands::check_for_updates`, `ledger_gui::owner::NewerVersion`. +*Checked:* `ledger-host` unit tests in `newer.rs` +(`only_a_higher_plain_version_is_newer`, +`the_feed_gives_a_version_and_nothing_else`, +`a_look_is_noted_and_the_next_is_a_day_away`, +`a_failed_look_says_nothing_and_still_counts`, `the_note_is_private`) and +`update.rs` (`a_macos_app_is_never_updated_in_place`); `ledger-gui` +`tests/update_notice.rs` (`a_newer_version_is_told_with_where_to_get_it`). + +**WB-pkg-4 Without git, backups are off and the person is told how to get +it.** Backups run the system's git; the program carries none. With no git found, a +backup says so in plain words for the system it runs on (Git for Windows or winget; Apple's +command line tools or Homebrew; the package manager) and the books work as +ever; the next backup looks again, so installing git needs no restart. On a Mac +without the developer tools, the stub at the system's git path is not taken for a +git. Whether to ship a git with the app is the owner's decision, since git is +GPL-2.0-only free software and shipping it carries a source offer and notices. +*Enforced:* `ledger_store::backup::how_to_get_git`, +`ledger_store::backup::Git::find`. +*Checked:* `ledger-store` unit tests in `backup.rs` +(`a_missing_git_says_how_to_get_it`, +`the_mac_stub_is_not_a_git_until_the_developer_tools_are_there`); +`ledger-cli` `tests/packaging.rs` +(`the_linux_packages_depend_on_git_and_none_carries_one`). + +**WB-pkg-5 The Connect page can write a one-click Claude desktop extension +for a company.** The "Claude desktop app" row has one button. It makes the +company's assistant key if there is none and writes +`wanderbooks-.mcpb` in a folder named Extensions in Documents/Wanderbooks: an +MCP Bundle (Anthropic's extension format, a zip file with a manifest, manifest +version 0.3) whose server is a binary that runs this program's installed path +as `mcp --book ` (WB-pkg-2). The package carries no program, no key, no +passphrase and no path of the data root. The page then says in words where in Claude's +settings to pick the file (Settings, Extensions, Advanced settings, Install +Extension), to keep Wanderbooks open, and offers to show the file. A program +running from a translocated copy writes nothing and says to move it first. +*Enforced:* `ledger_host::extension::claude_desktop_extension`, +`ledger_host::extension::manifest`. +*Checked:* `ledger-cli` `tests/extension.rs` +(`the_manifest_is_one_the_published_schema_accepts`, +`every_file_the_manifest_names_is_in_the_package`, +`the_server_runs_this_programs_bridge_for_the_company`); `ledger-host` unit +tests in `extension.rs` +(`no_secret_and_no_data_root_is_in_the_package`); `ledger-gui` +`tests/assistants.rs` +(`the_claude_desktop_row_makes_the_extension_and_says_what_to_do_next`). + +**WB-pkg-6 One version, and the product is named Wanderbooks wherever a +person sees it.** The version is written once, in the program's own manifest +(`crates/ledger-cli/Cargo.toml`); every package script and the release workflow read it +through `deploy/packaging/version.sh`, which refuses anything that is not three +numbers, and the program reports it to the window, the update look and the +extension. The window's title, the Start Menu entry, the app bundle's name, +the uninstaller's entry and the installer are all "Wanderbooks". The +lower-case `wanderbooks` stays where it is an identifier a person does not +read: the program's file name, the window's app id, the data folder. +*Enforced:* `deploy/packaging/version.sh`, `ledger_host::program_version`. +*Checked:* `ledger-cli` `tests/packaging.rs` +(`the_version_is_written_once_and_every_script_reads_it_from_there`, +`a_version_that_is_not_three_numbers_is_refused`, +`the_desktop_entries_launch_plain_wanderbooks_with_the_icon_and_the_window_id`); +`ledger-gui` `tests/tabs.rs` (the window title tests). + +**WB-pkg-7 A release is a draft that carries the licences and the sums.** +The release workflow runs on a version tag or by hand and never on an +ordinary push. It builds all three packages, runs each system's tests on that +system, and attaches the packages, the licence files, the third-party +notices (every package also carries them), the update note and a file of +SHA-256 sums to a draft release. It never publishes a release, never changes +one already published, and never pushes the apt or dnf repositories (a +separate workflow, by hand, from a published release does). Signing runs only +when the owner's secrets are present and says so in the run's notices when not. +*Enforced:* `.github/workflows/release.yml`, +`.github/workflows/publish-repos.yml`. +*Checked:* `ledger-cli` `tests/packaging.rs` +(`the_release_workflow_makes_a_draft_of_all_three_packages_and_publishes_nothing`, +`only_a_person_runs_the_workflow_that_publishes_the_repositories`, +`every_package_carries_the_licences_and_the_icon`). + +**WB-pkg-8 The books live where each system keeps an app's own data, apart +from the program.** macOS: Library/Application Support/wanderbooks in the person's +home. Windows: the local application data folder, `wanderbooks` (never the +roaming one: the books are large, hold locks and belong to one machine). +Linux: the XDG data folder, `wanderbooks`, where the books have always been +(unchanged). The folder with the private keys and certificate for the web +address is owner-only on each system, as the data root is. No data folder is +inside any folder a program is installed to. +*Enforced:* `ledger_store::root::data_dir_for`, +`ledger_store::root::default_root`, `ledger_link::private::make_dir`. +*Checked:* `ledger-store` `tests/data_locations.rs` +(`each_system_keeps_its_data_where_it_keeps_an_apps_data`, +`no_data_folder_is_inside_an_install_folder`); `ledger-link` unit tests in +`private.rs` (`a_private_file_reads_back_and_is_mode_0600`, +`a_private_file_and_its_folder_are_owner_only_on_windows`). diff --git a/plan/STATUS.md b/plan/STATUS.md index d864f980..5e86bfdb 100644 --- a/plan/STATUS.md +++ b/plan/STATUS.md @@ -1,5 +1,34 @@ # STATUS — 2026-11-10: the evaluation batch: no money arithmetic outside the kernel in any crate, exact Decimal sums, four gates the build did not have +## 2026-11-21: P15 unit C1, the installed app (branch `t3/p15-c1-desktop-packages`) + +Written on Linux; **nothing of it has run on Windows or macOS**, and no +package has been installed anywhere. The `release` workflow's first run is the +evidence. What is there (`docs/packaging.md`, "P15 unit C1"; `docs/install.md`; +claims `WB-pkg-1` to `WB-pkg-8` in `docs/spec/claims/packaging.md`): + +- **Windows**: a per-user NSIS installer (no administrator prompt), one + program, a Start Menu entry named Wanderbooks, a Settings > Apps + uninstaller that cannot reach the books. The program is built for the GUI + subsystem, so no console window; a terminal still gets a command's words. +- **macOS**: a universal `.app` in a `.dmg` (hardened runtime, an empty + entitlements file with the reasons, a Documents-folder purpose string); + signing and notarization run only with the owner's Apple secrets. +- **Linux**: the tools are unchanged; the desktop entries carry the icon and + the window's app id, every package carries the licences, and the packages + depend on git. +- **The Claude desktop extension**: the Connect page's last row writes a + `.mcpb` (Anthropic's MCP Bundle, manifest 0.3) per company. +- **Update**: the window says when a newer version exists and where to get it + (a daily look at one small file; only a version number is read); the update + is the newer package installed over the old. +- **Release**: a draft only, tests on each system, SHA-256 sums, licences; + the apt/dnf publish moved to a by-hand workflow. +- **Owner's, open**: signing identities and their secrets; whether to bundle + git on Windows and macOS (a GPL-2.0 consequence, `docs/packaging.md`); + the first run of the release workflow on GitHub and the first install on a + clean Windows and macOS machine. + ## 2026-11-10: the evaluation batch (plan/2026-11-09_TRIAGE.md) A full evaluation of the project on 2026-11-09 found nothing wrong in the From 2b946405cf2dc4198e204288d508f4c7ed66a5be Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:55:10 -0700 Subject: [PATCH 11/11] feat(gui): the window carries the package icon (P15 C1) The taskbar on Windows and X11 shows the same icon the packages carry; macOS takes it from the bundle and Wayland from the desktop entry. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-gui/src/lib.rs | 40 +++++++++++++++++++++++++++++------- docs/packaging.md | 5 +++-- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/crates/ledger-gui/src/lib.rs b/crates/ledger-gui/src/lib.rs index d02612d2..b9c1eec9 100644 --- a/crates/ledger-gui/src/lib.rs +++ b/crates/ledger-gui/src/lib.rs @@ -138,14 +138,21 @@ pub fn run( }, }, }; + let mut viewport = egui::ViewportBuilder::default() + .with_title("Wanderbooks") + .with_app_id("wanderbooks") + .with_inner_size([1440.0, 920.0]) + // Small on purpose: tiling window managers hand out small slots + // regardless, and every screen lays itself out to fit. + .with_min_inner_size([360.0, 400.0]); + // The window's own icon (the taskbar on Windows, X11): the packages' + // icon. macOS takes its icon from the app bundle, Wayland from the + // desktop entry; a failure to decode leaves the system's default. + if let Some(icon) = window_icon() { + viewport = viewport.with_icon(std::sync::Arc::new(icon)); + } let options = eframe::NativeOptions { - viewport: egui::ViewportBuilder::default() - .with_title("Wanderbooks") - .with_app_id("wanderbooks") - .with_inner_size([1440.0, 920.0]) - // Small on purpose: tiling window managers hand out small slots - // regardless, and every screen lays itself out to fit. - .with_min_inner_size([360.0, 400.0]), + viewport, // The platform's place for app settings, never the books' folder // (prefs.rs). persistence_path: prefs::prepare(), @@ -201,3 +208,22 @@ mod exit_tests { assert_eq!(Exit(1).to_string(), "exit code 1"); } } + +/// The icon every package carries (`deploy/packaging/icons`), as the window's +/// own (WB-pkg-6). +fn window_icon() -> Option { + eframe::icon_data::from_png_bytes(include_bytes!( + "../../../deploy/packaging/icons/512x512.png" + )) + .ok() +} + +#[cfg(test)] +mod window_icon_tests { + #[test] + fn the_windows_icon_is_the_packages_icon() { + let icon = super::window_icon().expect("the icon decodes"); + assert_eq!((icon.width, icon.height), (512, 512)); + assert_eq!(icon.rgba.len(), 512 * 512 * 4); + } +} diff --git a/docs/packaging.md b/docs/packaging.md index 730c9a6f..3cfb437c 100644 --- a/docs/packaging.md +++ b/docs/packaging.md @@ -314,8 +314,9 @@ unsigned (macOS: ad hoc, so it runs, but Gatekeeper refuses a download). Connect page's button; it runs the installed program as `mcp --book `. **Left out, on purpose:** an auto-installer; a Windows executable icon resource -(the shortcut and the uninstaller entry carry the icon; the running window uses -the system's default) and the window's own icon on Windows and Linux X11; +(the shortcut and the uninstaller entry carry the icon, and the running window +sets its own from the 512 px PNG; Explorer shows the `.exe` with the default +icon); `wanderbooks.cmd`/PATH setup so a terminal waits for a command on Windows (a GUI-subsystem program returns the prompt at once); a macOS refusal for a program run from a mounted disk image (a path under `/Volumes` may be a real install on