diff --git a/Cargo.lock b/Cargo.lock index 7fff05de..dbb4ebc8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1732,6 +1732,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", + "libc", "objc2 0.6.5", ] @@ -1831,7 +1833,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "pollster", + "pollster 1.0.1", "profiling", "raw-window-handle", "ron", @@ -1987,7 +1989,7 @@ dependencies = [ "kittest", "log", "open", - "pollster", + "pollster 1.0.1", "serde", "tempfile", "toml 1.1.8+spec-1.1.0", @@ -4105,6 +4107,7 @@ dependencies = [ "libc", "notify", "proptest", + "rfd", "rust_decimal", "serde", "serde_json", @@ -4858,6 +4861,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "objc2 0.6.5", "objc2-core-foundation", "objc2-core-graphics", @@ -5597,6 +5601,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + [[package]] name = "pollster" version = "1.0.1" @@ -6261,6 +6271,30 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "percent-encoding", + "pollster 0.4.0", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rgb" version = "0.8.53" diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index 20f44d12..eccb1df1 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -8020,6 +8020,7 @@ MIT License ================================================================================ Used by: + pollster 0.4.0 pollster 1.0.1 Copyright (c) 2020-2021 Joshua Barretto @@ -10049,6 +10050,36 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +MIT License +================================================================================ + +Used by: + rfd 0.17.2 + +MIT License + +Copyright (c) 2020 Bilal Elmoussaoui + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + ================================================================================ MIT License ================================================================================ @@ -10109,6 +10140,36 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +MIT License +================================================================================ + +Used by: + rfd 0.17.2 + +MIT License + +Copyright (c) 2022 Bartłomiej Maryńczak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + ================================================================================ MIT License ================================================================================ @@ -10429,6 +10490,7 @@ Used by: brotli-decompressor 5.0.3 chrono 0.4.45 comemo-macros 0.5.1 + dispatch2 0.3.1 dispatch 0.2.0 dpi 0.1.2 ecolor 0.36.2 @@ -15973,6 +16035,7 @@ Their copyright notices are in their source repositories: block2 0.6.2 https://github.com/madsmtm/objc2 comemo-macros 0.5.1 https://github.com/typst/comemo dispatch 0.2.0 http://github.com/SSheldon/rust-dispatch + dispatch2 0.3.1 https://github.com/madsmtm/objc2 ecolor 0.36.2 https://github.com/emilk/egui eframe 0.36.2 https://github.com/emilk/egui/tree/main/crates/eframe egui 0.36.2 https://github.com/emilk/egui diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 1026a006..5a497892 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -302,6 +302,35 @@ impl ledger_gui::owner::Owner for ViewerOwner { ledger_host::commands::back_up_now(&self.common, book, false) } + fn backup_state(&self, book: &str) -> Result { + let s = ledger_host::commands::backup_standing(&self.common, book)?; + Ok(ledger_gui::owner::BackupState { + lines: ledger_host::commands::backup_words(&s), + folder: s.folder.clone(), + sealed: s.sealed, + }) + } + + fn set_up_backups( + &self, + book: &str, + folder: Option, + passphrase: Option, + remove_passphrase: bool, + ) -> Result, String> { + ledger_host::commands::backup_setup( + &self.common, + book, + folder, + passphrase.map(|p| p.0.clone()), + remove_passphrase, + ) + } + + fn save_backup(&self, book: &str, file: &str) -> Result, String> { + ledger_host::commands::backup_save(&self.common, book, file) + } + fn plan_restore( &self, source: &str, diff --git a/crates/ledger-cli/tests/backups.rs b/crates/ledger-cli/tests/backups.rs index 5394e907..8604852d 100644 --- a/crates/ledger-cli/tests/backups.rs +++ b/crates/ledger-cli/tests/backups.rs @@ -1351,3 +1351,154 @@ async fn a_clone_of_an_old_git_backup_is_adopted_as_a_plain_folder() { assert!(server.close().success()); let _ = folder; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_passphrase_seals_the_backups_and_a_restore_asks_for_it() { + // D-92 from the window's side: set up through the admin socket, a backup + // made sealed, the status said, a restore on another computer asking for + // the passphrase, a wrong one refused, a saved file sealed too, and the + // passphrase taken off. + const PASS: &str = "correct horse battery staple"; + let home = Home::new("sealed"); + let server = Server::start(&home, Duration::from_secs(3600)); + home.create("acme"); + let folder = home.outside("disk"); + std::fs::create_dir_all(&folder).unwrap(); + let said = |r: Response| match r { + Response::Said { lines } => lines.join(" "), + other => panic!("{other:?}"), + }; + // A folder that isn't there, or is inside the books, is refused in words. + match home.admin(Request::BackupSetup { + id: "acme".into(), + folder: Some(home.outside("nowhere").display().to_string()), + passphrase: None, + remove_passphrase: false, + }) { + Response::Refused(why) => assert!(why.contains("isn't there"), "{why}"), + other => panic!("{other:?}"), + } + let words = said(home.admin(Request::BackupSetup { + id: "acme".into(), + folder: Some(folder.display().to_string()), + passphrase: Some(admin::Passphrase(PASS.into())), + remove_passphrase: false, + })); + assert!(words.contains("cannot be recovered"), "{words}"); + assert!(!words.contains(PASS)); + let c = connect(&home, "acme", home.token("acme", &ALL)).await; + post_one(&c, 3).await; + let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); + assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); + assert_eq!(s["targets"][0]["sealed"], true, "{s}"); + match home.admin(Request::BackupStatus { id: "acme".into() }) { + Response::BackupStatus(st) => { + assert!(st.sealed && st.last_ok_at.is_some(), "{st:?}"); + assert_eq!( + st.folder.as_deref(), + Some(folder.display().to_string().as_str()) + ); + } + other => panic!("{other:?}"), + } + // What is in the folder says nothing of the books. + let names: Vec = files_below(&folder, "") + .into_iter() + .map(|p| { + p.strip_prefix(&folder) + .unwrap() + .to_string_lossy() + .into_owned() + }) + .collect(); + assert!( + !names + .iter() + .any(|n| n.contains("acme") || n.contains("journal")), + "{names:?}" + ); + // Nothing of the passphrase or its key is in the backup record, the + // access log or the journal. + let book = home.book_dir("acme"); + for file in ["ops/backup.jsonl", "access.jsonl", "journal.jsonl"] { + let text = std::fs::read_to_string(book.join(file)).unwrap_or_default(); + assert!(!text.contains(PASS), "{file}"); + } + let key = std::fs::read_to_string(book.join("local").join("backup-key.json")).unwrap(); + let master = key + .split('"') + .nth(key.split('"').position(|p| p == "master").unwrap() + 2) + .unwrap() + .to_string(); + for file in ["ops/backup.jsonl", "access.jsonl", "journal.jsonl"] { + let text = std::fs::read_to_string(book.join(file)).unwrap_or_default(); + assert!(!text.contains(&master), "{file}"); + } + drop(c); + assert!(server.close().success()); + // Another computer: the passphrase is asked for, and a wrong one refused. + let other = Home::new("sealed-new"); + let server = Server::start(&other, Duration::from_secs(3600)); + let why = restore(&other, "acme", &folder, false).unwrap_err(); + assert!(why.contains("passphrase"), "{why}"); + let why = restore_with( + &other, + "acme", + &folder, + false, + Some("not the right words at all"), + ) + .unwrap_err(); + assert!(why.contains("isn't the passphrase"), "{why}"); + assert_eq!(books_held(&other), Vec::::new()); + let r = restore_with(&other, "acme", &folder, false, Some(PASS)).unwrap(); + assert_eq!(r.head, live_head(&home, "acme")); + // The restored books keep backing up sealed, with no question asked. + assert!( + other + .book_dir("acme") + .join("local") + .join("backup-key.json") + .is_file() + ); + // Saved as one file: sealed too, and restorable from. + let file = other.outside("acme.wbbackup"); + let words = said(other.admin(Request::BackupSave { + id: "acme".into(), + path: file.display().to_string(), + })); + assert!(words.contains("protected by the passphrase"), "{words}"); + assert!(server.close().success()); + let third = Home::new("sealed-file"); + let server = Server::start(&third, Duration::from_secs(3600)); + assert!(restore(&third, "acme", &file, false).is_err()); + let r = restore_with(&third, "acme", &file, false, Some(PASS)).unwrap(); + assert_eq!(r.head, live_head(&home, "acme")); + assert!(server.close().success()); + // The passphrase taken off: the next backup is plain, in the old plain + // folder, and the sealed one is untouched. + let server = Server::start(&home, Duration::from_secs(3600)); + let sealed_before: Vec<_> = files_below(&folder, "sealed-"); + let bytes_before: Vec> = sealed_before + .iter() + .map(|p| std::fs::read(p).unwrap()) + .collect(); + said(home.admin(Request::BackupSetup { + id: "acme".into(), + folder: None, + passphrase: None, + remove_passphrase: true, + })); + let c = connect(&home, "acme", home.token("acme", &ALL)).await; + let s = call(&c, "books.back_up_now", json!({})).await.unwrap(); + assert_eq!(s["targets"][0]["sealed"], false, "{s}"); + assert_eq!(s["targets"][0]["last_error"], Value::Null, "{s}"); + assert!(folder.join("acme").join("manifests").is_dir()); + let bytes_after: Vec> = sealed_before + .iter() + .map(|p| std::fs::read(p).unwrap()) + .collect(); + assert_eq!(bytes_before, bytes_after); + drop(c); + assert!(server.close().success()); +} diff --git a/crates/ledger-gui/Cargo.toml b/crates/ledger-gui/Cargo.toml index 1b95eec0..951b98f2 100644 --- a/crates/ledger-gui/Cargo.toml +++ b/crates/ledger-gui/Cargo.toml @@ -37,6 +37,10 @@ rust_decimal = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" zeroize = "1" +# The system's own folder and file dialogs for "Back up to..." and "Save a +# backup...": the portal on Linux, the native ones on Windows and macOS. The +# window shows nothing but what the system's dialog gives back, a path. +rfd = { version = "0.17", default-features = false, features = ["xdg-portal"] } # The dock: a terminal emulator over a PTY (ConPTY on Windows), P11b alacritty_terminal = "0.26" diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index edb204c6..e95f64f0 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -147,6 +147,18 @@ impl Drop for Secret { } } +/// How the books' backups stand, in words, for the Backups window. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BackupState { + /// What to tell the person, a line each (when it last backed up, whether + /// it was proven restorable, a disk that isn't connected). + pub lines: Vec, + /// The backup folder chosen, if one is. + pub folder: Option, + /// Protected by a passphrase. + pub sealed: bool, +} + /// A restore previewed: what it would do, and what it is of (INVARIANT 3). #[derive(Clone, Debug, PartialEq, Eq)] pub struct RestorePlan { @@ -453,6 +465,25 @@ pub trait Owner: Send + Sync { fn new_books(&self, id: &str, currency: &str) -> Result; /// Back the books `book` up now. fn back_up_now(&self, book: &str) -> Result, String>; + /// How the books `book`'s backups stand. Blocks. + fn backup_state(&self, _book: &str) -> Result { + Err("not here".into()) + } + /// Set the books' backups up: the backup folder, and the passphrase + /// (set, or taken off). What was done, a line each. Blocks. + fn set_up_backups( + &self, + _book: &str, + _folder: Option, + _passphrase: Option, + _remove_passphrase: bool, + ) -> Result, String> { + Err("not here".into()) + } + /// Save a backup of the books as one file at `file`. Blocks. + fn save_backup(&self, _book: &str, _file: &str) -> Result, String> { + Err("not here".into()) + } /// Preview restoring the backup at `source` (as `id`, else its own /// books' id), replacing the books of that id or not. fn plan_restore( @@ -594,12 +625,60 @@ enum Dialog { None, /// "New books…": their id and currency. NewBooks { id: String, currency: String }, + /// "Backups…": the folder, the passphrase, and how they stand. + Backups(Box), /// "Restore…": the backup, then its preview. Restore(Box), /// The format upgrade: the go-ahead, with the owner passphrase. Upgrade(Box), } +/// The Backups window: how they stand, the folder to choose, the passphrase +/// to offer. +struct BackupForm { + /// What the server said of them, once it has. + state: Option>, + /// The reading under way. + loading: Option>>, + /// The folder, as typed or chosen. + folder: String, + /// Whether a passphrase is being set (or changed). + protect: bool, + /// The passphrase, twice (wiped when the form is dropped). + pass: String, + again: String, + /// Why the last try was refused, or what it did. + problem: Option, + said: Vec, +} + +impl BackupForm { + fn new() -> Self { + Self { + state: None, + loading: None, + folder: String::new(), + protect: false, + pass: String::new(), + again: String::new(), + problem: None, + said: Vec::new(), + } + } +} + +impl Drop for BackupForm { + /// What was typed and not handed over is wiped from memory. + fn drop(&mut self) { + zeroize::Zeroize::zeroize(&mut self.pass); + zeroize::Zeroize::zeroize(&mut self.again); + } +} + +/// The words a person is told when setting a passphrase: what it does, and +/// that it cannot be recovered (D-92). +pub const PASSPHRASE_WARNING: &str = "Every file in the backup folder is sealed: only this passphrase opens it, and the files say nothing about your books but how many and how big. Your computer keeps the key so backups stay automatic. A forgotten passphrase cannot be recovered, by anyone, and backups made without it before this stay as they were. Write it down somewhere safe."; + /// The format upgrade's dialog (INVARIANT 5). struct UpgradeForm { /// What the books wait for. @@ -937,7 +1016,7 @@ impl OwnerMenu { ui.set_min_width(240.0); if ui .button(format!("{} Back up now", icon::CLOUD_ARROW_UP)) - .on_hover_text("Back these books up now, to every backup their settings name") + .on_hover_text("Back these books up now, to the backup folder") .clicked() { let (o, b) = (owner.clone(), book.clone()); @@ -947,6 +1026,39 @@ impl OwnerMenu { Box::new(move || o.back_up_now(&b)), )); } + if ui + .button(format!("{} Backups…", icon::CLOUD_ARROW_UP)) + .on_hover_text("Choose where these books back up to, protect the backups with a passphrase, and see how they stand") + .clicked() + { + self.dialog = Dialog::Backups(Box::new(BackupForm::new())); + } + if ui + .button(format!("{} Save a backup…", icon::CLOUD_ARROW_UP)) + .on_hover_text("Save these books as one backup file to keep or carry") + .clicked() + { + let name = format!( + "{}-{}.wbbackup", + book, + chrono::Local::now().format("%Y-%m-%d") + ); + if let Some(file) = rfd::FileDialog::new() + .set_title("Save a backup") + .set_file_name(name) + .add_filter("Wanderbooks backup", &[backup_extension()]) + .save_file() + { + let (o, b) = (owner.clone(), book.clone()); + let file = file.display().to_string(); + start = Some(( + "Save a backup".into(), + Effect::Reads, + Box::new(move || o.save_backup(&b, &file)), + )); + } + ui.close(); + } if ui .button(format!("{} Restore…", icon::CLOCK_COUNTER_CLOCKWISE)) .on_hover_text("Bring back books from a backup, proven whole first") @@ -1123,6 +1235,18 @@ impl OwnerMenu { }); }); } + Dialog::Backups(form) => { + backups_dialog( + ctx, + self.scope.unwrap_or(egui::Id::NULL), + form, + owner, + book, + &jobs, + &mut close, + &mut run, + ); + } Dialog::Restore(form) => { if let Some((rx, asked)) = &form.planning && let Ok(planned) = rx.try_recv() @@ -1155,6 +1279,31 @@ impl OwnerMenu { .hint_text("/media/backup, or /home/you/acme.wbbackup"), ) .changed(); + ui.horizontal(|ui| { + if ui + .add_enabled(open, egui::Button::new("Choose a folder…")) + .clicked() + && let Some(p) = rfd::FileDialog::new() + .set_title("Choose the backup folder") + .pick_folder() + { + form.source = p.display().to_string(); + form.plan = None; + form.problem = None; + } + if ui + .add_enabled(open, egui::Button::new("Choose a file…")) + .clicked() + && let Some(p) = rfd::FileDialog::new() + .set_title("Choose a backup file") + .add_filter("Wanderbooks backup", &[backup_extension()]) + .pick_file() + { + form.source = p.display().to_string(); + form.plan = None; + form.problem = None; + } + }); ui.horizontal(|ui| { ui.label("Passphrase, if the backup has one"); if ui @@ -1264,6 +1413,170 @@ impl OwnerMenu { } } +/// The extension of a backup file, without the dot. +fn backup_extension() -> &'static str { + ledger_store::backup::FILE_EXTENSION +} + +/// The Backups window: how the books' backups stand, the folder (chosen with +/// the system's folder dialog, or typed), the passphrase offer (off unless +/// asked for, with its warning), and a go. +#[allow(clippy::too_many_arguments)] +fn backups_dialog( + ctx: &egui::Context, + scope: egui::Id, + form: &mut BackupForm, + owner: &Arc, + book: &str, + jobs: &crate::jobs::Spawner, + close: &mut bool, + run: &mut Option, +) { + let p = crate::theme::pal(ctx); + // Read how they stand, once, and again after a change. + if form.state.is_none() && form.loading.is_none() { + let (tx, rx) = channel(); + let (o, b, c) = (owner.clone(), book.to_string(), ctx.clone()); + let started = jobs.spawn("backup state", crate::jobs::Hold::Free, move |stop| { + if stop.requested() { + return; + } + let _ = tx.send(o.backup_state(&b)); + c.request_repaint(); + }); + if started { + form.loading = Some(rx); + } else { + form.state = Some(Err("the system gave no thread for it".into())); + } + } + if let Some(rx) = &form.loading + && let Ok(state) = rx.try_recv() + { + form.loading = None; + if let Ok(s) = &state + && form.folder.is_empty() + { + form.folder = s.folder.clone().unwrap_or_default(); + } + form.state = Some(state); + } + egui::Modal::new(scope.with("owner-backups")).show(ctx, |ui| { + ui.set_max_width(540.0); + ui.heading("Backups"); + ui.add_space(4.0); + match &form.state { + None => { + ui.label("Reading how the backups stand…"); + } + Some(Err(why)) => { + ui.colored_label(p.warning, why); + } + Some(Ok(state)) => { + for line in &state.lines { + ui.label(line); + } + } + } + let sealed = matches!(&form.state, Some(Ok(s)) if s.sealed); + ui.separator(); + ui.label("Back up to this folder: another disk, or one your cloud drive (Dropbox, iCloud, OneDrive, Google Drive) keeps in sync."); + ui.horizontal(|ui| { + ui.add( + egui::TextEdit::singleline(&mut form.folder) + .desired_width(330.0) + .hint_text("choose a folder"), + ); + if ui.button("Choose a folder…").clicked() + && let Some(folder) = rfd::FileDialog::new() + .set_title("Choose the backup folder") + .pick_folder() + { + form.folder = folder.display().to_string(); + } + }); + ui.add_space(4.0); + if sealed { + ui.label("These backups are protected by a passphrase."); + } + ui.checkbox( + &mut form.protect, + if sealed { + "Change the passphrase" + } else { + "Protect the backups with a passphrase (optional)" + }, + ); + if form.protect { + ui.label(PASSPHRASE_WARNING); + ui.add( + egui::TextEdit::singleline(&mut form.pass) + .password(true) + .hint_text("passphrase (at least 12 characters)") + .desired_width(f32::INFINITY), + ); + ui.add( + egui::TextEdit::singleline(&mut form.again) + .password(true) + .hint_text("the same passphrase again") + .desired_width(f32::INFINITY), + ); + } + if let Some(why) = &form.problem { + ui.colored_label(p.warning, why); + } + for line in &form.said { + ui.label(line); + } + ui.horizontal(|ui| { + let folder = form.folder.trim().to_string(); + let known = matches!(&form.state, Some(Ok(s)) if s.folder.as_deref() == Some(folder.as_str())); + let pass_ready = !form.protect + || (form.pass.chars().count() >= 12 && form.pass == form.again); + let wants = (!folder.is_empty() && !known) || form.protect; + if ui + .add_enabled(wants && pass_ready, egui::Button::new("Save these choices")) + .on_disabled_hover_text( + "Choose a folder, or set a passphrase of at least 12 characters, typed twice the same", + ) + .clicked() + { + let (o, b) = (owner.clone(), book.to_string()); + let pass = form + .protect + .then(|| Secret(std::mem::take(&mut form.pass))) + .filter(|s| !s.0.is_empty()); + zeroize::Zeroize::zeroize(&mut form.again); + form.protect = false; + let folder = Some(folder).filter(|f| !f.is_empty() && !known); + *run = Some(( + "Backups".into(), + Effect::Changes("Setting up the backups"), + Box::new(move || o.set_up_backups(&b, folder, pass, false)), + )); + *close = true; + } + if sealed + && ui + .button("Take the passphrase off") + .on_hover_text("Later backups are written without protection; earlier sealed ones stay sealed") + .clicked() + { + let (o, b) = (owner.clone(), book.to_string()); + *run = Some(( + "Backups".into(), + Effect::Changes("Setting up the backups"), + Box::new(move || o.set_up_backups(&b, None, None, true)), + )); + *close = true; + } + if ui.button("Close").clicked() { + *close = true; + } + }); + }); +} + /// The format upgrade's dialog (INVARIANT 5): what it is, the owner /// passphrase, and the go-ahead or not now. fn upgrade_dialog( diff --git a/crates/ledger-gui/tests/owner_menu.rs b/crates/ledger-gui/tests/owner_menu.rs index eea4fdb6..bf91e17d 100644 --- a/crates/ledger-gui/tests/owner_menu.rs +++ b/crates/ledger-gui/tests/owner_menu.rs @@ -68,6 +68,34 @@ impl Owner for Fake { )); Ok(vec![format!("Restored as \"{}\".", plan.id)]) } + fn backup_state(&self, book: &str) -> Result { + self.said(format!("state {book}")); + Ok(ledger_gui::owner::BackupState { + lines: vec![ + "Not backed up: no backup folder is chosen yet.".into(), + "Not protected by a passphrase.".into(), + ], + folder: None, + sealed: false, + }) + } + fn set_up_backups( + &self, + book: &str, + folder: Option, + passphrase: Option, + remove: bool, + ) -> Result, String> { + self.said(format!( + "set up {book} {folder:?} {} {remove}", + if passphrase.is_some() { + "sealed" + } else { + "plain" + } + )); + Ok(vec!["The backup folder is chosen.".into()]) + } fn connect(&self, agent: Agent, book: &str) -> Result, String> { self.said(format!("connect {agent:?} {book}")); Ok(vec!["Claude Code reaches the books.".into()]) @@ -400,3 +428,67 @@ fn screenshots() { shot(&mut h, "restore-plan"); h.get_by_label("Cancel").click(); } + +/// The Backups window (D-91, D-92): how they stand in words, the folder, a +/// passphrase offered and off unless asked for, with its warning that a +/// forgotten one cannot be recovered; the owner is asked to set up only for +/// a folder, or a passphrase of 12 characters typed twice the same. +#[test] +fn the_backups_window_says_how_they_stand_and_offers_a_passphrase_plainly() { + let _alone = alone(); + let f = fake(); + let (_dir, _book, b) = books(true); + let mut h = harness(b); + let start = f.asked.lock().unwrap().len(); + let page_fields = h + .query_all_by_role(egui::accesskit::Role::TextInput) + .count(); + open_menu(&mut h); + h.get_by_label_contains("Backups…").click(); + settle(&mut h, &f, start + 1); + assert_eq!(f.asked.lock().unwrap()[start], "state acme"); + assert!( + h.query_by_label_contains("no backup folder is chosen yet") + .is_some() + ); + // The passphrase is off, and its offer says what it means only when + // asked for. + assert!(h.query_by_label_contains("cannot be recovered").is_none()); + h.get_by_label_contains("Protect the backups with a passphrase") + .click(); + h.run_steps(3); + assert!(h.query_by_label_contains("cannot be recovered").is_some()); + assert!(h.query_by_label_contains("git").is_none()); + // Nothing is done without a folder or a good passphrase. + h.get_all_by_role(egui::accesskit::Role::TextInput) + .nth(page_fields) + .unwrap() + .focus(); + h.run_steps(2); + h.get_all_by_role(egui::accesskit::Role::TextInput) + .nth(page_fields) + .unwrap() + .type_text("/media/disk"); + h.run_steps(2); + for (n, text) in [ + (0usize, "correct horse battery"), + (1, "correct horse battery"), + ] { + h.get_all_by_role(egui::accesskit::Role::PasswordInput) + .nth(n) + .unwrap() + .focus(); + h.run_steps(2); + h.get_all_by_role(egui::accesskit::Role::PasswordInput) + .nth(n) + .unwrap() + .type_text(text); + h.run_steps(2); + } + h.get_by_label("Save these choices").click(); + settle(&mut h, &f, start + 2); + assert_eq!( + f.asked.lock().unwrap()[start + 1], + "set up acme Some(\"/media/disk\") sealed false" + ); +} diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index fe687429..9ec39bc4 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -750,6 +750,11 @@ fn books_usage(prog: &str) { ); eprintln!(" {prog} restore BACKUP [--id ID] [--replace] [--yes]"); eprintln!(" {prog} back-up ID [--new-disk]"); + eprintln!(" {prog} backup-status ID"); + eprintln!( + " {prog} backup-setup ID [--folder FOLDER] [--passphrase | --remove-passphrase]" + ); + eprintln!(" {prog} backup-save ID FILE"); eprintln!(" {prog} upgrade ID"); eprintln!(" {prog} extract BOOK ATTACHMENT"); eprintln!(" {prog} open ID"); @@ -801,6 +806,9 @@ pub fn books( let mut yes = false; let mut replace = false; let mut new_disk = false; + let mut folder: Option = None; + let mut ask_passphrase = false; + let mut remove_passphrase = false; let mut args = args.into_iter(); while let Some(arg) = args.next() { if common.take(&arg, &mut args)? { @@ -808,6 +816,9 @@ pub fn books( } let mut value = |what: &str| args.next().ok_or_else(|| format!("{arg} needs {what}")); match arg.as_str() { + "--folder" => folder = Some(value("a folder")?), + "--passphrase" => ask_passphrase = true, + "--remove-passphrase" => remove_passphrase = true, "--currency" => currency = value("a currency code")?, "--id" => id = Some(value("an id")?), "--toml" => toml = Some(PathBuf::from(value("a file")?)), @@ -916,6 +927,61 @@ pub fn books( id: (*book).to_string(), }, ), + ["backup-status", book] => { + return match backup_status(&common, book) { + Ok(lines) => { + for line in lines { + println!("{line}"); + } + Ok(()) + } + Err(why) => { + eprintln!("error: {why}"); + Err(exit(1)) + } + }; + } + ["backup-setup", book] => { + // A passphrase is typed by a person, at a terminal, twice and + // unechoed: never on the command line, where a shell keeps it. + let passphrase = if ask_passphrase { + match ask_backup_passphrase() { + Ok(p) => Some(p), + Err(why) => { + eprintln!("error: {why}"); + return Err(exit(1)); + } + } + } else { + None + }; + return match backup_setup(&common, book, folder, passphrase, remove_passphrase) { + Ok(lines) => { + for line in lines { + println!("{line}"); + } + Ok(()) + } + Err(why) => { + eprintln!("error: {why}"); + Err(exit(1)) + } + }; + } + ["backup-save", book, file] => { + return match backup_save(&common, book, file) { + Ok(lines) => { + for line in lines { + println!("{line}"); + } + Ok(()) + } + Err(why) => { + eprintln!("error: {why}"); + Err(exit(1)) + } + }; + } ["back-up", book] => { return match back_up_now(&common, book, new_disk) { Ok(lines) => { @@ -1180,6 +1246,142 @@ pub fn back_up_now(common: &Common, book: &str, new_disk: bool) -> Result Result { + if !at_a_terminal() { + return Err( + "the backup passphrase is typed by a person, at a terminal (or set up in the window)" + .into(), + ); + } + println!( + "Backups protected by a passphrase are sealed: only this passphrase opens them. A forgotten passphrase cannot be recovered by anyone." + ); + let first = rpassword::prompt_password("Backup passphrase: ").map_err(|e| e.to_string())?; + let again = rpassword::prompt_password("Again: ").map_err(|e| e.to_string())?; + if first != again { + return Err("the two passphrases differ: nothing was changed".into()); + } + Ok(first) +} + +/// How the books' backups stand, as the server says it. +pub fn backup_standing(common: &Common, book: &str) -> Result { + match with_server( + common, + Request::BackupStatus { + id: book.to_string(), + }, + )? { + Response::BackupStatus(s) => Ok(s), + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } +} + +/// How the books' backups stand, in words, a line each. +pub fn backup_status(common: &Common, book: &str) -> Result, String> { + backup_standing(common, book).map(|s| backup_words(&s)) +} + +/// The words for a backup standing, as an ordinary person reads them. +pub fn backup_words(s: &admin::BackupStanding) -> Vec { + let mut lines = Vec::new(); + match &s.folder { + None => lines.push("Not backed up: no backup folder is chosen yet.".to_string()), + Some(folder) => { + lines.push(format!("Backing up to {folder}.")); + if s.disconnected { + lines.push("The disk with the backup is not connected: connect it, and the next backup goes there. If it is a new disk, say so when you back up now.".into()); + } else if let Some(why) = &s.last_error { + lines.push(format!("The last backup didn't work: {why}")); + } + match (&s.last_ok_at, s.through_seq) { + (Some(at), Some(seq)) => lines.push(format!( + "Last backed up {at}, through event {seq} of {}.{}", + s.head_seq, + if s.through_seq == Some(s.head_seq) { + " Up to date." + } else if s.stale { + " More than a day behind." + } else { + " Behind, and catching up." + } + )), + _ => lines.push("No backup has been made there yet.".into()), + } + match (&s.last_drill_at, &s.drill_error) { + (_, Some(why)) => lines.push(format!( + "The weekly check that the backup can be restored failed: {why}" + )), + (Some(at), None) => lines.push(format!("Proven restorable {at} (checked weekly).")), + (None, None) if s.through_seq.is_some() => { + lines.push("Not yet proven restorable: it is checked weekly.".into()) + } + _ => {} + } + lines.push(if s.sealed { + "Protected by a passphrase. A forgotten passphrase cannot be recovered.".into() + } else { + "Not protected by a passphrase.".into() + }); + } + } + if let Some(note) = &s.note { + lines.push(note.clone()); + } + lines +} + +/// Set up the books' backups: the folder, and the passphrase (D-92). +pub fn backup_setup( + common: &Common, + book: &str, + folder: Option, + passphrase: Option, + remove_passphrase: bool, +) -> Result, String> { + let folder = folder.map(|f| { + std::path::absolute(&f) + .unwrap_or_else(|_| PathBuf::from(&f)) + .display() + .to_string() + }); + match with_server( + common, + Request::BackupSetup { + id: book.to_string(), + folder, + passphrase: passphrase.map(ledger_mcp::admin::Passphrase), + remove_passphrase, + }, + )? { + Response::Said { lines } => Ok(lines), + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } +} + +/// Save a backup of the books as one file. +pub fn backup_save(common: &Common, book: &str, file: &str) -> Result, String> { + let file = std::path::absolute(file) + .unwrap_or_else(|_| PathBuf::from(file)) + .display() + .to_string(); + match with_server( + common, + Request::BackupSave { + id: book.to_string(), + path: file, + }, + )? { + Response::Said { lines } => Ok(lines), + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } +} + /// What a format upgrade the books `book` wait for means, a line each /// (plan 3.9, D-39): said before the owner is asked. pub fn upgrade_explained(book: &str, waiting: &admin::FormatWaiting) -> Vec { diff --git a/crates/ledger-mcp/src/admin.rs b/crates/ledger-mcp/src/admin.rs index a480c3f5..07f8c761 100644 --- a/crates/ledger-mcp/src/admin.rs +++ b/crates/ledger-mcp/src/admin.rs @@ -147,6 +147,35 @@ pub enum Request { #[serde(default)] new_disk: bool, }, + /// Set up a book's backups (D-91, D-92): the folder, and the + /// passphrase. + BackupSetup { + /// The books. + id: String, + /// The backup folder, by its whole path: set as the books' + /// `backup.folder`, the owner the one who decided. + #[serde(default, skip_serializing_if = "Option::is_none")] + folder: Option, + /// Protect the backups with this passphrase (never shown, never + /// kept: the key it makes is kept on this computer). + #[serde(default, skip_serializing_if = "Option::is_none")] + passphrase: Option, + /// Take the passphrase off. + #[serde(default)] + remove_passphrase: bool, + }, + /// How a book's backups stand. + BackupStatus { + /// The books. + id: String, + }, + /// Save a backup of a book as one file. + BackupSave { + /// The books. + id: String, + /// The file, by its whole path (.wbbackup is added if missing). + path: String, + }, /// Make a token for an agent (plan 3.3). TokenCreate { /// The books it opens. @@ -709,6 +738,40 @@ pub struct BackedUpTarget { pub problem: Option, } +/// How a book's backups stand, for the window and the command line. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct BackupStanding { + /// The books' head seq now. + pub head_seq: u64, + /// The backup folder chosen, if one is. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub folder: Option, + /// Protected by a passphrase. + pub sealed: bool, + /// When it last took the books (UTC), if ever. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_ok_at: Option, + /// The journal seq it holds, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub through_seq: Option, + /// More than a day behind. + pub stale: bool, + /// Why its last backup failed, if it did. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_error: Option, + /// When it was last proven restorable (UTC), if ever. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_drill_at: Option, + /// Why that check failed, if it did. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub drill_error: Option, + /// Its disk isn't connected. + pub disconnected: bool, + /// What to know or do: none set up, an older kind no longer used. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, +} + /// The server's answer. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case", deny_unknown_fields)] @@ -739,6 +802,13 @@ pub enum Response { /// Each target. targets: Vec, }, + /// What was done, in words (a backup set up or saved). + Said { + /// A line each. + lines: Vec, + }, + /// How a book's backups stand. + BackupStatus(BackupStanding), /// A token made: its text, shown this once (INVARIANT 6). TokenCreated { /// The token. @@ -857,7 +927,11 @@ pub fn call_within( | Request::Sessions | Request::RemoteStatus | Request::RemotePending + | Request::BackupStatus { .. } | Request::RemoteApprovals { .. } => None, + Request::BackupSetup { .. } | Request::BackupSave { .. } => { + Some("`wanderbooks books backup-status BOOK` says how the backups stand") + } Request::RemoteStart { .. } | Request::RemoteStop | Request::RemoteAllow { .. } diff --git a/crates/ledger-mcp/src/backup.rs b/crates/ledger-mcp/src/backup.rs index dd38d4bc..98682f7d 100644 --- a/crates/ledger-mcp/src/backup.rs +++ b/crates/ledger-mcp/src/backup.rs @@ -922,6 +922,192 @@ impl Backups { } } +/// What the window shows of a book's backups: the status, the folder the +/// person chose (their own path, never one of the data root's), and whether +/// the backups are protected by a passphrase. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Standing { + /// How the folder stands. + pub status: Status, + /// The backup folder, if one is chosen. + pub folder: Option, + /// Protected by a passphrase now. + pub sealed: bool, +} + +impl Backups { + /// What the window shows (read under the store's lock). + pub async fn window_standing(&self) -> Standing { + let store = self.store.clone(); + let (book, dir) = (self.book.clone(), self.dir.clone()); + let found = tokio::task::spawn_blocking(move || { + store + .with_store(|s| Standing { + status: standing(s, &book, &dir), + folder: s.ledger().settings().backup_folder().map(str::to_string), + sealed: matches!(BackupKey::load(&dir), Ok(Some(_))), + }) + .ok() + }) + .await + .ok() + .flatten(); + found.unwrap_or_else(|| Standing { + status: standing_of(&[], &[], 0, chrono::Utc::now(), None), + folder: None, + sealed: false, + }) + } + + /// Set up the backups (D-91, D-92), as the owner does it in the window: + /// the folder (`folder`, journaled as the books' `backup.folder` setting, + /// the owner the one who decided), and the passphrase (`passphrase` + /// makes a new key, kept on this computer only: backups from the next on + /// are sealed, in a set of their own beside any earlier one, which is + /// untouched; `remove_passphrase` forgets the key: the next backup is + /// plain). What was done, in words. + pub async fn set_up( + &self, + folder: Option, + passphrase: Option, + remove_passphrase: bool, + ) -> Result, String> { + let _one = self.running.lock().await; + if self.is_shut() { + return Err(SHUT.to_string()); + } + let step = self.begin()?; + let (store, dir) = (self.store.clone(), self.dir.clone()); + let done = tokio::task::spawn_blocking(move || -> Result, String> { + let _step = step; + let mut lines = Vec::new(); + if let Some(folder) = folder.filter(|f| !f.trim().is_empty()) { + let path = PathBuf::from(folder.trim()); + if !path.is_absolute() { + return Err("the backup folder is named by its whole path".into()); + } + if !path.is_dir() { + return Err("that folder isn't there: choose a folder that exists".into()); + } + if ledger_store::root::inside_a_root(&path) { + return Err(format!( + "that folder is inside {}: choose a folder somewhere else, on another disk if you can", + ledger_store::root::THE_ROOT + )); + } + let change = ledger_core::settings::Change { + key: "backup.folder".into(), + value: Some(Value::String(path.display().to_string())), + }; + let source = ledger_core::settings::Source { + decided_by: "the owner, in the window".into(), + decided_on: chrono::Utc::now().date_naive(), + citation: None, + note: Some("The backup folder.".into()), + }; + let made = store + .with_store_mut(|s| s.change_settings(&[change], &source)) + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + lines.push(if made.is_empty() { + "The backup folder is the one chosen already.".to_string() + } else { + "The backup folder is chosen: the books back themselves up there a little after each change, when they open and before they close.".to_string() + }); + } + if remove_passphrase && passphrase.is_some() { + return Err("choose a passphrase or remove it, not both".into()); + } + if let Some(p) = passphrase { + let key = BackupKey::generate(&p).map_err(|e| e.to_string())?; + key.store(&dir).map_err(|e| hide(&e.to_string(), &dir))?; + lines.push("Backups are now protected by the passphrase: from the next backup on, every file in the backup folder is sealed. Backups made before stay as they were, unprotected, and are never deleted: delete their folder yourself if you want them gone. A forgotten passphrase cannot be recovered by anyone.".to_string()); + } else if remove_passphrase { + BackupKey::forget(&dir).map_err(|e| hide(&e.to_string(), &dir))?; + lines.push("The passphrase is taken off: from the next backup on, files are written without protection. Backups sealed before stay sealed with the passphrase they were made with.".to_string()); + } + if lines.is_empty() { + lines.push("Nothing was changed.".to_string()); + } + Ok(lines) + }) + .await + .unwrap_or_else(|_| Err("the set-up stopped".into())); + if let Ok(lines) = &done { + self.record(json!({"kind": "setup", "lines": lines.len()})); + } + done + } + + /// Save a backup as one file at `path` ("Save a backup..."): the same + /// contents as the backup folder's, sealed when the backups are. + pub async fn save_file(&self, path: &str) -> Result, String> { + let _one = self.running.lock().await; + if self.is_shut() { + return Err(SHUT.to_string()); + } + if self.hurried() { + return Err(self.stopped_words()); + } + let mut file = PathBuf::from(path.trim()); + if !file.is_absolute() { + return Err("the file is named by its whole path".into()); + } + if file.extension().is_none_or(|e| e != backup::FILE_EXTENSION) { + let mut name = file.file_name().unwrap_or_default().to_os_string(); + name.push(format!(".{}", backup::FILE_EXTENSION)); + file.set_file_name(name); + } + if file.parent().is_none_or(|p| !p.is_dir()) { + return Err("the folder to save it in isn't there".into()); + } + if ledger_store::root::inside_a_root(&file) { + return Err(format!( + "that is inside {}: save it somewhere else", + ledger_store::root::THE_ROOT + )); + } + let step = self.begin()?; + let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone()); + let ctx = self.ctx_for("asked"); + let sealed_to = file.clone(); + let saved = tokio::task::spawn_blocking(move || { + let _step = step; + let key = BackupKey::load(&dir).map_err(|e| e.to_string())?; + let cut = store + .with_store(|s| Cut::take(&book, &dir, s.head())) + .map_err(|e| e)? + .map_err(|e| e.to_string())?; + backup::save_file(&sealed_to, &cut, key.as_ref(), &ctx) + .map(|w| (w, key.is_some())) + .map_err(|e| e.to_string()) + }) + .await + .unwrap_or_else(|_| Err("the backup stopped".into())); + match saved { + Ok((w, sealed)) => { + self.record(json!({"kind": "saved", "ok": true, "sealed": sealed, + "head": {"seq": w.head.0, "hash": w.head.1}})); + Ok(vec![format!( + "Saved a backup of the books through event {} as {}{}.", + w.head.0, + file.display(), + if sealed { + ", protected by the passphrase" + } else { + "" + } + )]) + } + Err(why) => { + let why = hide(&why, &self.dir); + self.record(json!({"kind": "saved", "ok": false, "error": why})); + Err(why) + } + } + } +} + /// The old backup history's folder in a book's folder: left alone. const OLD_ARCHIVE_DIR: &str = "archive.git"; diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 3642cb3f..359e62ab 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -1656,6 +1656,53 @@ impl Books { Err(why) => Response::Refused(self.hide(why)), } } + Request::BackupSetup { + id, + folder, + passphrase, + remove_passphrase, + } => match self.backups_of(&id) { + Ok(backups) => { + let rt = tokio::runtime::Handle::current(); + let pass = passphrase.as_ref().map(|p| p.0.clone()); + match rt.block_on(backups.set_up(folder, pass, remove_passphrase)) { + Ok(lines) => Response::Said { lines }, + Err(why) => Response::Refused(self.hide(why)), + } + } + Err(r) => r, + }, + Request::BackupStatus { id } => match self.backups_of(&id) { + Ok(backups) => { + let rt = tokio::runtime::Handle::current(); + let s = rt.block_on(backups.window_standing()); + let t = s.status.targets.first(); + Response::BackupStatus(admin::BackupStanding { + head_seq: s.status.head_seq, + folder: s.folder, + sealed: s.sealed, + last_ok_at: t.and_then(|t| t.last_ok_at.clone()), + through_seq: t.and_then(|t| t.through_seq), + stale: t.is_some_and(|t| t.stale), + last_error: t.and_then(|t| t.last_error.clone()), + last_drill_at: t.and_then(|t| t.last_drill_at.clone()), + drill_error: t.and_then(|t| t.drill_error.clone()), + disconnected: t.is_some_and(|t| t.disconnected), + note: s.status.note, + }) + } + Err(r) => r, + }, + Request::BackupSave { id, path } => match self.backups_of(&id) { + Ok(backups) => { + let rt = tokio::runtime::Handle::current(); + match rt.block_on(backups.save_file(&path)) { + Ok(lines) => Response::Said { lines }, + Err(why) => Response::Refused(self.hide(why)), + } + } + Err(r) => r, + }, Request::Adopt { id, source, @@ -2180,6 +2227,22 @@ impl Books { ) } + /// The backups of the open book `id`, or the refusal to give a request + /// that needs them. + fn backups_of(&self, id: &str) -> Result, Response> { + let refused = |text: String| Response::Refused(self.hide(text)); + let id = BookId::parse(id).map_err(|e| refused(e.to_string()))?; + match self.held().get(id.as_str()) { + Some(Book::Open { backups, .. }) => Ok(backups.clone()), + Some(Book::Failed(why)) => Err(refused(format!("those books didn't open: {why}"))), + Some(Book::Closed) => Err(refused(self.not_open(&id))), + None => Err(refused(format!( + "there are no books called {:?}", + id.as_str() + ))), + } + } + /// What is said of a book that exists but isn't open, to an admin /// request that needs it open. fn not_open(&self, id: &BookId) -> String {