From 40257260832b9249f3d24eb7c051085dc9fa25c7 Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Thu, 29 Oct 2026 06:14:28 +0700 Subject: [PATCH] Milestone 4: taking access back Removing someone from a vault, a device, or the team opens departures on the hub. Each device stops syncing, saves, goes read-only, hands unshared work over (secrets redacted), and deletes the folder only if the app created it. Managers review handovers (show/keep/discard/skip); removed devices may only hand over, then their key is retired. Adds the delete-from-devices vault setting and team restore. Co-Authored-By: Claude Opus 5.5 --- cli/src/main.rs | 91 +++++++++ cli/src/team.rs | 117 +++++++----- core/src/hub.rs | 75 ++++++++ core/src/lib.rs | 1 + core/src/membership.rs | 177 ++++++++++++++++++ core/src/remote.rs | 3 + core/src/runner.rs | 5 + core/src/vault.rs | 81 ++++++--- docs/SPEC.md | 63 +++---- hub/src/api.rs | 79 ++++++-- hub/src/db.rs | 70 ++++++- hub/src/git.rs | 22 ++- hub/src/hook.rs | 8 +- hub/src/leave.rs | 405 +++++++++++++++++++++++++++++++++++++++++ hub/src/main.rs | 10 + hub/tests/hub.rs | 148 +++++++++++++++ 16 files changed, 1222 insertions(+), 133 deletions(-) create mode 100644 core/src/membership.rs create mode 100644 hub/src/leave.rs diff --git a/cli/src/main.rs b/cli/src/main.rs index af72815..f65cecb 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -110,6 +110,27 @@ enum Command { }, /// Who has access to a vault, and their devices Members { vault: String }, + /// Take someone's access to one vault away; their unshared work comes back as a handover + Remove { + person: String, + #[arg(long)] + vault: String, + /// Delete their copy without sending anything back + #[arg(long)] + without_saving: bool, + }, + /// Remove someone from the team, or bring them back (team owner) + Team { + #[command(subcommand)] + action: TeamCmd, + }, + /// Unshared work that came back from people and devices leaving vaults + Handovers, + /// Look at a handover and decide about it + Handover { + #[command(subcommand)] + action: HandoverCmd, + }, /// The hub's access log (team owner) Hub { #[command(subcommand)] @@ -124,10 +145,42 @@ enum Command { }, } +#[derive(Subcommand)] +enum TeamCmd { + /// Ends every vault and device of theirs; the account is disabled (restorable) + Remove { + person: String, + /// Don't ask for confirmation + #[arg(long)] + yes: bool, + }, + /// Re-enable a removed person (no vaults); prints a one-time sign-in link + Restore { person: String }, +} + +#[derive(Subcommand)] +enum HandoverCmd { + /// Which notes it changes + Show { id: i64 }, + /// Bring it into the vault (same-lines clashes keep both) + Keep { id: i64 }, + /// Drop it + Discard { id: i64 }, + /// For a device that hasn't reported in: delete its copy without saving + Skip { id: i64 }, +} + #[derive(Subcommand)] enum VaultCmd { /// Create an empty vault on the hub New { name: String }, + /// Change a vault's settings + Set { + name: String, + /// Delete a person's copy from their devices when they're removed: on or off + #[arg(long)] + delete_from_devices: OnOff, + }, /// Move a vault from its plain Git remote onto the hub Upload { name: String, @@ -150,6 +203,13 @@ enum HubCmd { enum DeviceCmd { /// Set the label shown on everything this device shares Name { label: String }, + /// Remove a device (e.g. a lost laptop): it hands over and leaves every vault, then its key stops working + Remove { + label: String, + /// Someone else's device (team owner) + #[arg(long)] + person: Option, + }, } #[derive(Subcommand)] @@ -194,6 +254,12 @@ enum HeldCmd { }, } +#[derive(Clone, Copy, ValueEnum)] +enum OnOff { + On, + Off, +} + #[derive(Clone, Copy, ValueEnum)] enum KeepArg { Mine, @@ -236,6 +302,29 @@ fn run_cli(cli: Cli) -> Result<()> { Command::Invite { person, vaults } => team::invite(&config, &person, &vaults)?, Command::Grant { person, vault, role } => team::grant(&config, &person, &vault, &role)?, Command::Members { vault } => team::members(&config, &vault)?, + Command::Remove { person, vault, without_saving } => team::remove(&config, &person, &vault, without_saving)?, + Command::Team { action: TeamCmd::Remove { person, yes } } => team::team_remove(&config, &person, yes)?, + Command::Team { action: TeamCmd::Restore { person } } => team::team_restore(&config, &person)?, + Command::Handovers => team::handovers(&config)?, + Command::Handover { action } => match action { + HandoverCmd::Show { id } => team::handover_show(&config, id)?, + HandoverCmd::Keep { id } => team::handover_decide(&config, id, "keep")?, + HandoverCmd::Discard { id } => team::handover_decide(&config, id, "discard")?, + HandoverCmd::Skip { id } => team::handover_decide(&config, id, "skip")?, + }, + Command::Vault { action: VaultCmd::Set { name, delete_from_devices } } => { + team::link(&config)?.vault_setting(&name, matches!(delete_from_devices, OnOff::On))?; + let what = match delete_from_devices { + OnOff::On => "deleted from their devices", + OnOff::Off => "left on their devices, read-only", + }; + println!("When someone is removed from {name}, their copy is {what}."); + } + Command::Device { action: Some(DeviceCmd::Remove { label, person }) } => { + team::link(&config)?.remove_device(&label, person.as_deref())?; + println!("\"{label}\" is removed. Next time it's online it hands over anything unshared and leaves every vault;"); + println!("after that its key stops working. If it never comes back: `lunesync handovers`, then `handover skip `."); + } Command::Hub { action: HubCmd::Log { count } } => team::log(&config, count)?, Command::Service { action: ServiceCmd::Install { print } } => service::install(print)?, Command::Service { action: ServiceCmd::Uninstall } => service::uninstall()?, @@ -496,6 +585,8 @@ fn run() -> Result<()> { } } } + // A vault that left (access ended) can come back later at the same place. + started.retain(|p| config.vaults.iter().any(|v| &v.path == p)); for cfg in &config.vaults { if !started.insert(cfg.path.clone()) { continue; diff --git a/cli/src/team.rs b/cli/src/team.rs index 4c0a3ef..5ac7c98 100644 --- a/cli/src/team.rs +++ b/cli/src/team.rs @@ -6,7 +6,7 @@ use lune_core::config::{Config, VaultConfig}; use lune_core::hub::{self, HubLink}; use lune_core::remote; use lune_core::state; -use lune_core::vault::{self, Vault}; +use lune_core::vault::Vault; use std::path::PathBuf; pub fn link(config: &Config) -> Result<&HubLink> { @@ -53,49 +53,7 @@ pub fn pair(config: &Config) -> Result<()> { Ok(()) } -/// Brings this device in line with its hub memberships: new vaults arrive, same-named local vaults -/// move onto the hub, roles are refreshed. Returns what happened, in plain words. -pub fn arrive(config: &mut Config) -> Result> { - let Some(h) = config.hub.clone() else { return Ok(vec![]) }; - let me = h.me()?; - let label = config.device_label(); - let mut said = vec![]; - for hv in me.vaults { - if let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(hv.id)) { - let v = Vault::open(vc, &label)?; - state::write_role(&v.git_dir, &hv.role)?; - continue; - } - if let Some(vc) = config.vaults.iter_mut().find(|v| v.hub_vault.is_none() && v.name.eq_ignore_ascii_case(&hv.name)) { - let v = Vault::open(vc, &label)?; - let _op = state::op_lock(&v.git_dir)?; - v.relink(&hv.git_url)?; - state::write_role(&v.git_dir, &hv.role)?; - v.join_unrelated()?; - vc.remote = hv.git_url.clone(); - vc.hub_vault = Some(hv.id); - config.save()?; - said.push(format!("{} now syncs through the hub", hv.name)); - continue; - } - let path = config.vaults_dir().join(&hv.name); - if path.exists() && std::fs::read_dir(&path)?.next().is_some() && !path.join(".git").exists() { - said.push(format!("{} can't arrive: {} already has other files in it", hv.name, path.display())); - continue; - } - let (mut cfg, _, err) = vault::add(&hv.name, &path, &hv.git_url, &label)?; - cfg.hub_vault = Some(hv.id); - state::write_role(&path.join(".git"), &hv.role)?; - config.vaults.push(cfg); - config.save()?; - let note = if hub::can_edit(&hv.role) { String::new() } else { " (read access)".into() }; - said.push(format!("{} arrived in {}{note}", hv.name, path.display())); - if let Some(e) = err { - said.push(format!(" not synced yet: {e}")); - } - } - Ok(said) -} +pub use lune_core::membership::arrive; pub fn vault_new(config: &mut Config, name: &str) -> Result<()> { let hv = link(config)?.create_vault(name)?; @@ -190,3 +148,74 @@ pub fn log(config: &Config, count: usize) -> Result<()> { } Ok(()) } + +pub fn remove(config: &Config, person: &str, vault: &str, without_saving: bool) -> Result<()> { + let n = link(config)?.remove(person, vault, without_saving)?; + println!("{person} no longer has access to {vault}. Their other vaults are untouched."); + match (n, without_saving) { + (0, _) => println!("They had no devices to clean up."), + (n, false) => println!( + "{n} device(s) will hand over anything unshared (see `lunesync handovers`), then delete their copy." + ), + (n, true) => println!("{n} device(s) will delete their copy without sending anything."), + } + println!("Copies made elsewhere, or already given to other tools, can't be recalled."); + Ok(()) +} + +pub fn team_remove(config: &Config, person: &str, yes: bool) -> Result<()> { + if !yes { + println!("This ends every vault and device {person} has, and disables their account (it can be restored)."); + print!("Type their name to confirm: "); + std::io::Write::flush(&mut std::io::stdout())?; + let mut answer = String::new(); + std::io::stdin().read_line(&mut answer)?; + if !answer.trim().eq_ignore_ascii_case(person) { + bail!("not confirmed — nothing changed"); + } + } + link(config)?.team_remove(person)?; + println!("{person} is removed from the team. Their devices hand over anything unshared, delete their copies, and stop working."); + println!("History keeps their name. Copies made elsewhere can't be recalled."); + Ok(()) +} + +pub fn team_restore(config: &Config, person: &str) -> Result<()> { + let link = link(config)?.team_restore(person)?; + println!("{person} is back on the team, with no vaults yet (`lunesync grant`). Send them this one-time link:\n"); + println!(" lunesync join {link} --name "); + Ok(()) +} + +pub fn handovers(config: &Config) -> Result<()> { + let list = link(config)?.handovers()?; + if list.is_empty() { + println!("No handovers."); + } + for h in list { + let at = Local.timestamp_opt(h.at, 0).single().map(|t| t.format("%Y-%m-%d %H:%M").to_string()).unwrap_or_default(); + let state = match h.state.as_str() { + "waiting" => "waiting for the device to come online", + "received" => "TO REVIEW — `lunesync handover show|keep|discard`", + "kept" => "kept", + "discarded" => "discarded", + "skipped" => "deleted without saving", + _ => "nothing was unshared", + }; + println!("{:>4} {at} {:<10} {} ({}) {state}", h.id, h.vault, h.person, h.device); + } + Ok(()) +} + +pub fn handover_show(config: &Config, id: i64) -> Result<()> { + for line in link(config)?.handover_show(id)? { + println!(" {line}"); + } + println!("Bring it in with `lunesync handover keep {id}`, or drop it with `lunesync handover discard {id}`."); + Ok(()) +} + +pub fn handover_decide(config: &Config, id: i64, decision: &str) -> Result<()> { + println!("{}", link(config)?.handover_decide(id, decision)?); + Ok(()) +} diff --git a/core/src/hub.rs b/core/src/hub.rs index 0e22a8b..1a63369 100644 --- a/core/src/hub.rs +++ b/core/src/hub.rs @@ -29,6 +29,32 @@ pub struct Me { pub owner: bool, pub device_label: String, pub vaults: Vec, + /// Vaults this device must leave (access ended). + #[serde(default)] + pub leaving: Vec, +} + +/// A vault this device has to hand over and leave (A6). +#[derive(Debug, Clone, Deserialize)] +pub struct Departure { + pub id: i64, + pub vault_id: i64, + pub vault: String, + pub delete_files: bool, + /// A manager chose "delete without saving". + pub without_saving: bool, +} + +/// A departure as a manager sees it. +#[derive(Debug, Deserialize)] +pub struct Handover { + pub id: i64, + pub vault: String, + pub person: String, + pub device: String, + /// waiting (device hasn't reported in), received (to review), kept, discarded, done, skipped + pub state: String, + pub at: i64, } #[derive(Debug, Clone, Deserialize)] @@ -153,6 +179,55 @@ impl HubLink { } } +impl HubLink { + pub fn remove(&self, person: &str, vault: &str, without_saving: bool) -> Result { + let v: Value = self.post("/api/remove", json!({"person": person, "vault": vault, "without_saving": without_saving}))?; + Ok(v["devices"].as_u64().unwrap_or(0) as usize) + } + + pub fn remove_device(&self, label: &str, person: Option<&str>) -> Result<()> { + let _: Value = self.post("/api/device/remove", json!({"label": label, "person": person}))?; + Ok(()) + } + + pub fn team_remove(&self, person: &str) -> Result<()> { + let _: Value = self.post("/api/team/remove", json!({ "person": person }))?; + Ok(()) + } + + /// Re-enables a removed person; returns a one-time sign-in link. + pub fn team_restore(&self, person: &str) -> Result { + let v: Value = self.post("/api/team/restore", json!({ "person": person }))?; + Ok(v["link"].as_str().unwrap_or_default().to_string()) + } + + pub fn handovers(&self) -> Result> { + self.get("/api/handovers") + } + + /// Changed files in a received handover, as "added/changed/removed path". + pub fn handover_show(&self, id: i64) -> Result> { + self.post("/api/handovers/show", json!({ "id": id })) + } + + /// keep, discard or skip. + pub fn handover_decide(&self, id: i64, decision: &str) -> Result { + let v: Value = self.post("/api/handovers/decide", json!({"id": id, "decision": decision}))?; + Ok(v["message"].as_str().unwrap_or_default().to_string()) + } + + pub fn vault_setting(&self, vault: &str, delete_from_devices: bool) -> Result<()> { + let _: Value = self.post("/api/vaults/settings", json!({"vault": vault, "delete_from_devices": delete_from_devices}))?; + Ok(()) + } + + /// Tells the hub this device has handed over (`head`, if anything) and is leaving. + pub fn departure_done(&self, id: i64, head: Option) -> Result<()> { + let _: Value = self.post("/api/departures/done", json!({"id": id, "head": head}))?; + Ok(()) + } +} + /// Is `role` allowed to share changes? pub fn can_edit(role: &str) -> bool { role == "edit" || role == "manage" diff --git a/core/src/lib.rs b/core/src/lib.rs index a5d10e7..70c0e75 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -5,6 +5,7 @@ pub use git2; pub mod config; pub mod guard; pub mod hub; +pub mod membership; pub mod names; pub mod remote; pub mod runner; diff --git a/core/src/membership.rs b/core/src/membership.rs new file mode 100644 index 0000000..ff7b242 --- /dev/null +++ b/core/src/membership.rs @@ -0,0 +1,177 @@ +//! Keeping this device in line with its hub memberships: vaults arrive, and vaults whose access ended +//! are handed over and leave (A6). + +use crate::config::Config; +use crate::hub::{self, Departure, HubLink}; +use crate::secrets; +use crate::state; +use crate::vault::{self, Vault}; +use anyhow::{Result, bail}; +use std::path::Path; +use std::time::{Duration, Instant}; + +/// What a leaving note gets instead of a secret: the secret itself is never sent or kept (P1). +const REDACTED: &str = "[secret removed when leaving]"; + +/// New vaults arrive, same-named local vaults move onto the hub, roles refresh, and vaults whose access +/// ended are handed over and leave. Returns what happened, in plain words. +pub fn arrive(config: &mut Config) -> Result> { + let Some(h) = config.hub.clone() else { return Ok(vec![]) }; + let me = match h.me() { + Ok(me) => me, + Err(e) if format!("{e}").contains("isn't signed in") => { + // The hub no longer knows this device: it was removed and has nothing left to hand over. + config.hub = None; + config.vaults.retain(|v| v.hub_vault.is_none()); + config.save()?; + return Ok(vec!["This device was removed from the hub. Vaults on other remotes keep syncing.".into()]); + } + Err(e) => return Err(e), + }; + let label = config.device_label(); + let mut said = vec![]; + + for d in &me.leaving { + said.push(leave(config, &h, d)?); + } + + for hv in me.vaults { + if let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(hv.id)) { + let v = Vault::open(vc, &label)?; + state::write_role(&v.git_dir, &hv.role)?; + continue; + } + if let Some(vc) = config.vaults.iter_mut().find(|v| v.hub_vault.is_none() && v.name.eq_ignore_ascii_case(&hv.name)) { + let v = Vault::open(vc, &label)?; + let _op = state::op_lock(&v.git_dir)?; + v.relink(&hv.git_url)?; + state::write_role(&v.git_dir, &hv.role)?; + v.join_unrelated()?; + vc.remote = hv.git_url.clone(); + vc.hub_vault = Some(hv.id); + config.save()?; + said.push(format!("{} now syncs through the hub", hv.name)); + continue; + } + let path = config.vaults_dir().join(&hv.name); + if path.exists() && std::fs::read_dir(&path)?.next().is_some() && !path.join(".git").exists() { + said.push(format!("{} can't arrive: {} already has other files in it", hv.name, path.display())); + continue; + } + let (mut cfg, _, err) = vault::add(&hv.name, &path, &hv.git_url, &label)?; + cfg.hub_vault = Some(hv.id); + state::write_role(&path.join(".git"), &hv.role)?; + config.vaults.push(cfg); + config.save()?; + let note = if hub::can_edit(&hv.role) { String::new() } else { " (read access)".into() }; + said.push(format!("{} arrived in {}{note}", hv.name, path.display())); + if let Some(e) = err { + said.push(format!(" not synced yet: {e}")); + } + } + Ok(said) +} + +/// Leaves one vault: stop syncing, save, make read-only, hand over what wasn't shared, and once the +/// hub has it, delete the folder if the app created it. +pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result { + let label = config.device_label(); + let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(d.vault_id)).cloned() else { + link.departure_done(d.id, None)?; + return Ok(format!("Access to {} ended (it wasn't on this device)", d.vault)); + }; + let v = Vault::open(&vc, &label)?; + let lune = state::lune_dir(&v.git_dir); + std::fs::create_dir_all(&lune)?; + std::fs::write(lune.join("leaving"), d.id.to_string())?; + + // Wait for this vault's runner to notice and stop. + let deadline = Instant::now() + Duration::from_secs(60); + let _running = loop { + if let Some(lock) = state::try_run_lock(&v.git_dir)? { + break lock; + } + if Instant::now() > deadline { + bail!("{} is still busy syncing; will try leaving again shortly", d.vault); + } + std::thread::sleep(Duration::from_millis(250)); + }; + let _op = state::op_lock(&v.git_dir)?; + + let mut head = None; + if !d.without_saving { + for note in v.secret_holds()? { + let path = v.root.join(¬e.path); + if let Ok(text) = std::fs::read_to_string(&path) { + std::fs::write(&path, secrets::replace_with_pointer(&text, ¬e.hits, None, REDACTED))?; + } + } + v.save_unguarded(Some(&format!("Saved on {label} before leaving")))?; + } + set_read_only(&v.root, true)?; + if !d.without_saving + && let Some(h) = v.head_commit()? + { + v.hand_over(&format!("refs/handover/{}", d.id))?; + head = Some(h.id().to_string()); + } + link.departure_done(d.id, head)?; + + let created = state::read_marker(&v.git_dir).is_some_and(|m| m.created_folder && m.managed_by == "lune"); + config.vaults.retain(|x| x.path != vc.path); + config.save()?; + let sent = if d.without_saving { "nothing was sent" } else { "anything unshared was handed over" }; + if d.delete_files && created { + set_read_only(&v.root, false)?; + drop(v); + // remove_dir_all removes links themselves, never what they point to (A9). + std::fs::remove_dir_all(&vc.path)?; + Ok(format!("Access to {} ended: {sent}, and the folder was deleted", d.vault)) + } else { + let _ = std::fs::remove_file(lune.join("leaving")); + let why = if created { "this vault keeps copies on devices" } else { "you added this folder yourself" }; + Ok(format!("Access to {} ended: {sent}. The folder stays at {}, read-only and no longer synced ({why})", d.vault, vc.path.display())) + } +} + +/// Adds or removes write permission on everything in the vault folder except `.git`. +fn set_read_only(root: &Path, read_only: bool) -> Result<()> { + fn walk(dir: &Path, read_only: bool, top: bool) -> Result<()> { + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + if top && entry.file_name() == ".git" { + continue; + } + let meta = entry.path().symlink_metadata()?; + if meta.file_type().is_symlink() { + continue; + } + if meta.is_dir() { + walk(&entry.path(), read_only, false)?; + } + let mut perms = meta.permissions(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = perms.mode(); + perms.set_mode(if read_only { mode & !0o222 } else { mode | 0o200 }); + } + #[cfg(not(unix))] + perms.set_readonly(read_only); + std::fs::set_permissions(entry.path(), perms)?; + } + Ok(()) + } + walk(root, read_only, true)?; + let mut perms = std::fs::metadata(root)?.permissions(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = perms.mode(); + perms.set_mode(if read_only { mode & !0o222 } else { mode | 0o200 }); + } + #[cfg(not(unix))] + perms.set_readonly(read_only); + std::fs::set_permissions(root, perms)?; + Ok(()) +} diff --git a/core/src/remote.rs b/core/src/remote.rs index 18b8dce..be8c814 100644 --- a/core/src/remote.rs +++ b/core/src/remote.rs @@ -67,6 +67,9 @@ fn default_key_files() -> Vec { /// Turns a remote failure into plain words for `status` and the run log. pub fn describe_error(e: &anyhow::Error) -> String { if let Some(g) = e.downcast_ref::() { + if g.message().contains("status code: 403") { + return "the hub says this device has no access to this vault (if access ended, it will leave shortly)".into(); + } if g.code() == ErrorCode::Auth { return "the remote didn't accept our sign-in (check your SSH key or Git credentials)".into(); } diff --git a/core/src/runner.rs b/core/src/runner.rs index 5ce6c5a..1d8d13a 100644 --- a/core/src/runner.rs +++ b/core/src/runner.rs @@ -94,7 +94,12 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log: let mut was_holding = false; let mut was_read_only = false; let mut announced: HashSet = HashSet::new(); + let leaving = state::lune_dir(&vault.git_dir).join("leaving"); loop { + if leaving.exists() { + say("access to this vault ended — stopped syncing it"); + return Ok(()); + } let first = rx.recv_timeout(Duration::from_millis(250)); for ev in first.into_iter().chain(rx.try_iter()) { match ev { diff --git a/core/src/vault.rs b/core/src/vault.rs index d1502bb..fe05ce2 100644 --- a/core/src/vault.rs +++ b/core/src/vault.rs @@ -381,6 +381,27 @@ impl Vault { Ok(true) } + /// Sends this device's whole history to `dst` on the remote (the hub's handover area for this device). + pub fn hand_over(&self, dst: &str) -> Result<()> { + let mut remote = self.repo.find_remote("origin")?; + let rejected = RefCell::new(None::); + let mut cb = remote::callbacks(); + cb.push_update_reference(|_, status| { + if let Some(s) = status { + *rejected.borrow_mut() = Some(s.to_string()); + } + Ok(()) + }); + let mut opts = PushOptions::new(); + opts.remote_callbacks(cb); + remote.push(&[format!("+{}:{dst}", self.branch_ref())], Some(&mut opts))?; + drop(opts); + if let Some(why) = rejected.into_inner() { + bail!("the hub didn't take the handover: {why}"); + } + Ok(()) + } + /// One sync round: fetch, combine, write the result to disk, share local history. pub fn sync(&self) -> Result { let mut report = SyncReport::default(); @@ -467,33 +488,7 @@ impl Vault { /// Resolves every clash in `index` without markers: "their" version in place, ours beside it (S4). fn keep_both(&self, index: &mut git2::Index, kept_both: &mut Vec<(String, String)>) -> Result<()> { - if index.has_conflicts() { - let conflicts: Vec<_> = index.conflicts()?.collect::>()?; - for c in conflicts { - for e in [&c.ancestor, &c.our, &c.their].into_iter().flatten() { - let _ = index.conflict_remove(&names::bytes_path(&e.path)); - } - match (c.our, c.their) { - (Some(ours), Some(theirs)) if ours.path == theirs.path && ours.id != theirs.id => { - let note = String::from_utf8_lossy(&theirs.path).into_owned(); - let copy = (1..) - .map(|n| names::copy_name(¬e, &self.label, n)) - .find(|p| index.get_path(Path::new(p), 0).is_none()) - .unwrap(); - index.add(&stage0(&theirs, None))?; - index.add(&stage0(&ours, Some(copy.as_bytes())))?; - kept_both.push((note, copy)); - } - // Different paths, or one side removed the note: keep whatever still exists. - (ours, theirs) => { - for e in [ours, theirs].into_iter().flatten() { - index.add(&stage0(&e, None))?; - } - } - } - } - } - Ok(()) + keep_both(index, &self.label, kept_both) } /// Paths that differ only by letter case can't coexist on macOS/Windows. There, rename the extras so @@ -641,6 +636,38 @@ impl Vault { } } +/// Resolves every clash in `index` without markers: "their" version in place, ours beside it labeled +/// with `label` (S4). Used for syncing, undo, and keeping handovers on the hub. +pub fn keep_both(index: &mut git2::Index, label: &str, kept_both: &mut Vec<(String, String)>) -> Result<()> { + if index.has_conflicts() { + let conflicts: Vec<_> = index.conflicts()?.collect::>()?; + for c in conflicts { + for e in [&c.ancestor, &c.our, &c.their].into_iter().flatten() { + let _ = index.conflict_remove(&names::bytes_path(&e.path)); + } + match (c.our, c.their) { + (Some(ours), Some(theirs)) if ours.path == theirs.path && ours.id != theirs.id => { + let note = String::from_utf8_lossy(&theirs.path).into_owned(); + let copy = (1..) + .map(|n| names::copy_name(¬e, label, n)) + .find(|p| index.get_path(Path::new(p), 0).is_none()) + .unwrap(); + index.add(&stage0(&theirs, None))?; + index.add(&stage0(&ours, Some(copy.as_bytes())))?; + kept_both.push((note, copy)); + } + // Different paths, or one side removed the note: keep whatever still exists. + (ours, theirs) => { + for e in [ours, theirs].into_iter().flatten() { + index.add(&stage0(&e, None))?; + } + } + } + } + } + Ok(()) +} + fn blob_ids(tree: Option<&git2::Tree>) -> HashSet { let mut ids = HashSet::new(); if let Some(t) = tree { diff --git a/docs/SPEC.md b/docs/SPEC.md index b1abca5..03039df 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -153,52 +153,47 @@ Only the current milestone gets detailed below. The next one is detailed when th --- -## 6. Milestone 3 — Shared with my team +## 6. Milestone 4 — Access I can take back -Milestones 1–2 (sync over a Git remote, secret check, runaway guard) are built; their detail lives in the code and tests now. +Milestones 1–3 (sync, safety checks, the hub with invites, pairing and roles) are built; their detail lives in the code and tests now. ### Goal -A hub Sen runs in Docker replaces the plain Git remote. People get in by invite, add their own devices by pairing code, and every vault they're a member of arrives on its own. Roles are enforced by the hub, not by trust. +Taking access back is as clean as giving it. Removing someone from a vault collects their unshared work for a manager to review, then their copy disappears; their other vaults keep working. Removing someone from the team stops everything. A lost laptop can be removed on its own. All from the CLI. ### What Sen does ```bash -# on the VM -docker compose up -d # hub; first start prints the owner invite link in the log -# on the laptop -lunesync join https://hub.example/join/… --name Codex -lunesync vault upload DevOps # the M1 vault moves onto the hub, history kept -lunesync invite Alice --vault DevOps:edit # one-time link for Alice -lunesync pair # prints a ready-to-paste login line with a short code -# on the VPS -lunesync login --hub https://hub.example --code K7QD-4MXA --name Hermes -lunesync run # DevOps arrives in ~/Vaults/DevOps -# anytime -lunesync vault new Notes | grant Alice Notes --role read | members DevOps | hub log +lunesync remove Alice --vault DevOps # Alice loses DevOps only (A5) +lunesync remove Alice --vault DevOps --without-saving +lunesync device remove "Old laptop" # one device, e.g. lost; --person for someone else's (owner) +lunesync team remove Bob # owner only; asks to type the name (A8) +lunesync team restore Bob # re-enables the account; prints a one-time sign-in link +lunesync handovers # unshared work that came back, and devices still to report in +lunesync handover show|keep|discard 7 +lunesync handover skip 7 # a device that will never come back: delete without saving +lunesync vault set DevOps --delete-from-devices off # A7, on by default ``` -Alice runs `lunesync join --name "Alice laptop"`, then `lunesync run`: DevOps arrives. ### Behavior -- **Hub** = one container: an HTTP API plus Git over HTTPS for vaults, SQLite and bare repos on one volume (`/data`). It listens on plain HTTP; TLS comes from Sen's reverse proxy. `LUNE_HUB_URL` is the public address used in links. -- **Accounts, memberships, devices (A1)**. The hub has one team; the first account is its **owner**. Owners create vaults; owners and a vault's **Manage** members invite and grant for that vault. -- **Invites (A4)**: one per person, a one-time link that names the person and the vaults + roles they get, valid 7 days. Accepting it creates the account and its first device. -- **Pairing**: a signed-in device asks for a code (8 characters, 10 minutes, single use); a new device logs in with it and gets its own key. Devices never share keys. A device key is shown once and stored in the device's config file (owner-only permissions); the hub stores only its hash. -- **Vaults arrive**: while `run` is going, the device checks the hub every 30 s and adds any vault it's now a member of, under `~/Vaults/` (`--vaults-dir` to change). Vaults from M1 with a plain Git remote keep working. -- **Roles (A3)** are enforced by the hub on every Git request: Read can only receive changes. A Read member's own edits stay local; `status` says "not shared — you have read access". -- **Device labels (S7)**: chosen at join/login, renamed with `lunesync device name` (updates the hub too). History entries carry the label. -- **Hub secret check (P3)**: every incoming change is scanned with the same rules, commit by commit, before the hub accepts it. A hit is refused with the note, line and rule. "Not a secret" on a device is also sent to the hub for that vault. -- **Upload** keeps history. If old history contains a secret the hub refuses it; `vault upload --fresh` uploads only the current notes as a fresh start (the old history stays on that device only). -- **Access log (A10)**: the hub records invites created and accepted, devices paired and renamed, vaults created, memberships granted, and refused changes. `lunesync hub log` (owner). +- **Removing from a vault (A5, A6)**: the membership ends at once and the hub opens a *departure* for each of that person's devices. A device learns about it the next time it checks in (within ~30 s while running; offline devices on reconnect), then: + 1. stops syncing that vault and saves anything unsaved; + 2. makes the folder read-only; + 3. sends everything not yet shared to the hub's **handover area** for that vault. Notes held by the secret check go along with the secret replaced by `[secret removed when leaving]` (P1: the secret itself is never sent or kept); + 4. after the hub confirms receipt, deletes the folder — only if the app created it (marker in `.git/`, A9), never following links out. A folder the app adopted, or a vault with "delete from devices" off (A7), is left in place, read-only and no longer synced. +- A device that was removed can still do exactly one thing until its departures are done: hand over. It can't read or change the vault. +- **Handovers** are reviewed by a manager: **keep** combines them into the vault (same-lines clashes keep both, labeled with the leaving device), **discard** drops them. If nothing was unshared, the departure just completes. `skip` = "Delete without saving" for a pending departure. +- **Removing a device (A1)**: same flow for every vault on that device; afterwards its key stops working. +- **Remove from team (A8)**: owner only, asks for confirmation. Ends every membership (departures as above), removes every device, disables the account (restorable, keeps its name in history). Restore re-enables it with no vaults and a one-time sign-in link for a new device. +- Everything is in the access log (A10). Messages say plainly what can't be recalled (A11): copies made elsewhere stay where they are. ### Acceptance — Sen acts this out -1. `docker compose up -d` on a fresh VM; the owner link from the log works once and only once. -2. Upload the real DevOps vault; history and every file survive (checksums). -3. Pair the VPS with a code as "Hermes"; DevOps arrives; its edits show up labeled Hermes. -4. Invite a teammate with Edit on DevOps; they join, the vault arrives, their edits reach Sen. -5. Grant someone Read: the vault arrives, their edits stay local with the note, the hub refuses them even if pushed by hand. -6. Edit a note with a fake key directly in a hub vault from outside the app (plain `git push` with a device key): refused. +1. Alice has DevOps and Notes and edits DevOps while offline. Remove her from DevOps; when she reconnects her edit arrives as a handover, her DevOps folder disappears, Notes keeps syncing. +2. `handover show` lists her changes; `keep` brings them into DevOps on every device; another handover is discarded. +3. Remove Bob from the team: all his vaults leave his devices, his device can't do anything after, the access log shows each step. `team restore Bob` lets him back in with no vaults. +4. Remove a device that's switched off: `handover skip`; when it's switched on later, its copy is deleted without anything being sent. +5. A vault with "delete from devices" off: the person's copy stays, read-only, no longer synced. -### Out of scope for M3 -Removing people or devices, handovers (M4). Any web UI (M5). Client updates from the hub (M7). +### Out of scope for M4 +Undo window and gestures (M5, X2). Permanent account deletion (later admin action). Verifying removal in external tools (non-goal for v1). ## 7. Open questions None open. diff --git a/hub/src/api.rs b/hub/src/api.rs index fa94fd2..101912a 100644 --- a/hub/src/api.rs +++ b/hub/src/api.rs @@ -52,13 +52,13 @@ impl From for ApiError { } } -type ApiResult = Result, ApiError>; +pub type ApiResult = Result, ApiError>; -fn bad(msg: impl Into) -> ApiError { +pub fn bad(msg: impl Into) -> ApiError { ApiError(StatusCode::BAD_REQUEST, msg.into()) } -fn denied(msg: impl Into) -> ApiError { +pub fn denied(msg: impl Into) -> ApiError { ApiError(StatusCode::FORBIDDEN, msg.into()) } @@ -71,13 +71,23 @@ pub fn credentials(headers: &HeaderMap) -> Option<(String, String)> { Some((id.to_string(), key.to_string())) } -pub fn authenticate(hub: &Hub, headers: &HeaderMap) -> Result { +/// The signed-in device, including one that was removed and may only hand over. +pub fn authenticate_any(hub: &Hub, headers: &HeaderMap) -> Result { let unknown = || ApiError(StatusCode::UNAUTHORIZED, "this device isn't signed in to the hub".into()); let (id, key) = credentials(headers).ok_or_else(unknown)?; let conn = hub.db.lock().unwrap(); db::caller(&conn, &id, &key)?.ok_or_else(unknown) } +/// The signed-in device, if it still has normal access. +pub fn authenticate(hub: &Hub, headers: &HeaderMap) -> Result { + let caller = authenticate_any(hub, headers)?; + if !caller.active { + return Err(denied("this device was removed from the hub")); + } + Ok(caller) +} + const ROLES: [&str; 3] = ["read", "edit", "manage"]; fn check_label(label: &str) -> Result { @@ -89,7 +99,7 @@ fn check_label(label: &str) -> Result { } /// Owners can manage every vault; others need the Manage role on it. -fn can_manage(conn: &Connection, caller: &Caller, vault_id: i64) -> Result { +pub fn can_manage(conn: &Connection, caller: &Caller, vault_id: i64) -> Result { Ok(caller.owner || db::role(conn, caller.account_id, vault_id)?.as_deref() == Some("manage")) } @@ -97,6 +107,9 @@ fn welcome(person: &str, device_id: String, key: String) -> ApiResult { Ok(Json(json!({ "person": person, "device_id": device_id, "key": key }))) } +/// person, owner, grants (JSON), expires, used, account to restore +type InviteRow = (String, bool, String, i64, Option, Option); + #[derive(Deserialize)] pub struct JoinReq { token: String, @@ -107,14 +120,14 @@ pub async fn join(State(hub): State, Json(req): Json) -> ApiRes let label = check_label(&req.device_label)?; let mut conn = hub.db.lock().unwrap(); let tx = conn.transaction()?; - let invite: Option<(String, bool, String, i64, Option)> = tx + let invite: Option = tx .query_row( - "SELECT person, owner, grants, expires, used FROM invites WHERE token_hash = ?1", + "SELECT person, owner, grants, expires, used, account_id FROM invites WHERE token_hash = ?1", [db::hash(&req.token)], - |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)), + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)), ) .optional()?; - let Some((person, owner, grants, expires, used)) = invite else { + let Some((person, owner, grants, expires, used, restored)) = invite else { return Err(denied("that invite link isn't valid")); }; if used.is_some() { @@ -123,12 +136,18 @@ pub async fn join(State(hub): State, Json(req): Json) -> ApiRes if expires < db::now() { return Err(denied("that invite link has expired — ask for a new one")); } - let taken: bool = tx.query_row("SELECT COUNT(*) > 0 FROM accounts WHERE name = ?1", [&person], |r| r.get(0))?; - if taken { - return Err(denied(format!("{person} already has an account — pair a device instead"))); - } - tx.execute("INSERT INTO accounts (name, owner, created) VALUES (?1, ?2, ?3)", params![person, owner, db::now()])?; - let account_id = tx.last_insert_rowid(); + let account_id = match restored { + // A sign-in link for a restored account adds a device to it. + Some(id) => id, + None => { + let taken: bool = tx.query_row("SELECT COUNT(*) > 0 FROM accounts WHERE name = ?1", [&person], |r| r.get(0))?; + if taken { + return Err(denied(format!("{person} already has an account — pair a device instead"))); + } + tx.execute("INSERT INTO accounts (name, owner, created) VALUES (?1, ?2, ?3)", params![person, owner, db::now()])?; + tx.last_insert_rowid() + } + }; let grants: Vec<(i64, String)> = serde_json::from_str(&grants).map_err(anyhow::Error::from)?; let mut granted = vec![]; for (vault_id, role) in &grants { @@ -139,7 +158,7 @@ pub async fn join(State(hub): State, Json(req): Json) -> ApiRes tx.execute("UPDATE invites SET used = ?1 WHERE token_hash = ?2", params![db::now(), db::hash(&req.token)])?; let (device_id, key) = db::new_device(&tx, account_id, &label)?; let who = format!("{person} ({label})"); - let what = if owner { "as team owner".to_string() } else if granted.is_empty() { "with no vaults".into() } else { granted.join(", ") }; + let what = if restored.is_some() { "to come back after being restored".to_string() } else if owner { "as team owner".to_string() } else if granted.is_empty() { "with no vaults".into() } else { granted.join(", ") }; db::log(&tx, &who, "joined", &format!("accepted the invite {what}"))?; db::log(&tx, &who, "device added", &format!("{label} (first device)"))?; tx.commit()?; @@ -189,8 +208,25 @@ pub async fn pair(State(hub): State, headers: HeaderMap) -> ApiResult { } pub async fn me(State(hub): State, headers: HeaderMap) -> ApiResult { - let caller = authenticate(&hub, &headers)?; + let caller = authenticate_any(&hub, &headers)?; let conn = hub.db.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT d.id, d.vault_id, v.name, d.delete_files, d.without_saving FROM departures d JOIN vaults v ON v.id = d.vault_id + WHERE d.device_id = ?1 AND d.state = 'waiting'", + )?; + let leaving: Vec = stmt + .query_map([&caller.device_id], |r| { + Ok(json!({ + "id": r.get::<_, i64>(0)?, "vault_id": r.get::<_, i64>(1)?, "vault": r.get::<_, String>(2)?, + "delete_files": r.get::<_, bool>(3)?, "without_saving": r.get::<_, bool>(4)? + })) + })? + .collect::>()?; + if !caller.active { + return Ok(Json(json!({ + "person": caller.person, "owner": false, "device_label": caller.device_label, "vaults": [], "leaving": leaving + }))); + } let mut stmt = conn.prepare( "SELECT v.id, v.name, m.role FROM memberships m JOIN vaults v ON v.id = m.vault_id WHERE m.account_id = ?1 ORDER BY v.name", )?; @@ -201,7 +237,8 @@ pub async fn me(State(hub): State, headers: HeaderMap) -> ApiResult { .map(|(id, name, role)| json!({ "id": id, "name": name, "role": role, "git_url": hub.git_url(id) })) .collect(); Ok(Json(json!({ - "person": caller.person, "owner": caller.owner, "device_label": caller.device_label, "vaults": vaults + "person": caller.person, "owner": caller.owner, "device_label": caller.device_label, "vaults": vaults, + "leaving": leaving }))) } @@ -321,6 +358,10 @@ pub async fn grant(State(hub): State, headers: HeaderMap, Json(req): Jso .query_row("SELECT id, name FROM accounts WHERE name = ?1", [req.person.trim()], |r| Ok((r.get(0)?, r.get(1)?))) .optional()? .ok_or_else(|| bad(format!("nobody named {} has joined yet — invite them first", req.person.trim())))?; + let disabled: bool = conn.query_row("SELECT disabled FROM accounts WHERE id = ?1", [account_id], |r| r.get(0))?; + if disabled { + return Err(bad(format!("{person} was removed from the team — `lunesync team restore {person}` first"))); + } let before = db::role(&conn, account_id, g.0)?; db::grant(&conn, account_id, g.0, &g.2)?; let detail = match before { @@ -350,7 +391,7 @@ pub async fn members(State(hub): State, headers: HeaderMap, Json(req): J stmt.query_map([id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.collect::>()?; let mut out = vec![]; for (account_id, person, role) in rows { - let mut d = conn.prepare("SELECT label FROM devices WHERE account_id = ?1 ORDER BY created")?; + let mut d = conn.prepare("SELECT label FROM devices WHERE account_id = ?1 AND removed = 0 ORDER BY created")?; let devices: Vec = d.query_map([account_id], |r| r.get(0))?.collect::>()?; out.push(json!({ "person": person, "role": role, "devices": devices })); } diff --git a/hub/src/db.rs b/hub/src/db.rs index 1125534..0ec7820 100644 --- a/hub/src/db.rs +++ b/hub/src/db.rs @@ -51,6 +51,17 @@ CREATE TABLE IF NOT EXISTS not_secrets ( fingerprint TEXT NOT NULL, PRIMARY KEY (vault_id, fingerprint) ); +CREATE TABLE IF NOT EXISTS departures ( + id INTEGER PRIMARY KEY, + vault_id INTEGER NOT NULL, + account_id INTEGER NOT NULL, + device_id TEXT NOT NULL, + delete_files INTEGER NOT NULL, + without_saving INTEGER NOT NULL DEFAULT 0, + state TEXT NOT NULL, + created INTEGER NOT NULL, + updated INTEGER NOT NULL +); CREATE TABLE IF NOT EXISTS log ( id INTEGER PRIMARY KEY, at INTEGER NOT NULL, @@ -64,6 +75,15 @@ pub fn open(data: &Path) -> Result { let conn = Connection::open(data.join("hub.sqlite"))?; conn.busy_timeout(std::time::Duration::from_secs(5))?; conn.execute_batch(SCHEMA)?; + // Columns added after Milestone 3; adding one that exists fails harmlessly. + for (table, column) in [ + ("accounts", "disabled INTEGER NOT NULL DEFAULT 0"), + ("devices", "removed INTEGER NOT NULL DEFAULT 0"), + ("vaults", "delete_from_devices INTEGER NOT NULL DEFAULT 1"), + ("invites", "account_id INTEGER"), + ] { + let _ = conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column}"), []); + } Ok(conn) } @@ -99,6 +119,8 @@ pub struct Caller { pub account_id: i64, pub person: String, pub owner: bool, + /// False once the device was removed or the person removed from the team: it may only hand over. + pub active: bool, } impl Caller { @@ -111,11 +133,19 @@ impl Caller { pub fn caller(conn: &Connection, device_id: &str, key: &str) -> Result> { Ok(conn .query_row( - "SELECT d.id, d.label, a.id, a.name, a.owner FROM devices d JOIN accounts a ON a.id = d.account_id - WHERE d.id = ?1 AND d.key_hash = ?2", + "SELECT d.id, d.label, a.id, a.name, a.owner, d.removed = 0 AND a.disabled = 0 + FROM devices d JOIN accounts a ON a.id = d.account_id + WHERE d.id = ?1 AND d.key_hash = ?2 AND d.key_hash != ''", params![device_id, hash(key)], |r| { - Ok(Caller { device_id: r.get(0)?, device_label: r.get(1)?, account_id: r.get(2)?, person: r.get(3)?, owner: r.get(4)? }) + Ok(Caller { + device_id: r.get(0)?, + device_label: r.get(1)?, + account_id: r.get(2)?, + person: r.get(3)?, + owner: r.get(4)?, + active: r.get(5)?, + }) }, ) .optional()?) @@ -171,3 +201,37 @@ pub fn owner_invite(conn: &Connection, person: &str) -> Result> { )?; Ok(Some(token)) } + +/// Opens a departure (A6) for each of the person's devices (or just `device`) for one vault. +/// Returns how many devices will hand over and leave. +pub fn depart(conn: &Connection, account_id: i64, vault_id: i64, device: Option<&str>, without_saving: bool) -> Result { + let delete_files: bool = conn.query_row("SELECT delete_from_devices FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0))?; + let mut stmt = conn.prepare("SELECT id FROM devices WHERE account_id = ?1 AND key_hash != ''")?; + let devices: Vec = stmt.query_map([account_id], |r| r.get(0))?.collect::>()?; + let mut n = 0; + for d in devices.iter().filter(|d| device.is_none_or(|x| x == d.as_str())) { + conn.execute( + "INSERT INTO departures (vault_id, account_id, device_id, delete_files, without_saving, state, created, updated) + VALUES (?1, ?2, ?3, ?4, ?5, 'waiting', ?6, ?6)", + params![vault_id, account_id, d, delete_files, without_saving, now()], + )?; + n += 1; + } + Ok(n) +} + +/// A removed device whose departures are all done can't do anything any more: its key stops working. +pub fn retire_if_finished(conn: &Connection, device_id: &str) -> Result { + let inactive: bool = conn.query_row( + "SELECT d.removed = 1 OR a.disabled = 1 FROM devices d JOIN accounts a ON a.id = d.account_id WHERE d.id = ?1", + [device_id], + |r| r.get(0), + )?; + let pending: i64 = + conn.query_row("SELECT COUNT(*) FROM departures WHERE device_id = ?1 AND state = 'waiting'", [device_id], |r| r.get(0))?; + if inactive && pending == 0 { + conn.execute("UPDATE devices SET key_hash = '', removed = 1 WHERE id = ?1", [device_id])?; + return Ok(true); + } + Ok(false) +} diff --git a/hub/src/git.rs b/hub/src/git.rs index 1c9d6d0..65f1d8b 100644 --- a/hub/src/git.rs +++ b/hub/src/git.rs @@ -73,17 +73,28 @@ async fn handle( }; let Some((id, key)) = credentials(&headers) else { return Ok(ask_for_key()) }; - let (caller, role, vault_name) = { + let (caller, role, handover, vault_name) = { let conn = hub.db.lock().unwrap(); let Some(caller) = db::caller(&conn, &id, &key)? else { return Ok(ask_for_key()) }; - let role = db::role(&conn, caller.account_id, vault_id)?; + let role = if caller.active { db::role(&conn, caller.account_id, vault_id)? } else { None }; + // A device whose access ended may still send its handover, and nothing else (A6). + let handover: Option = conn + .query_row( + "SELECT id FROM departures WHERE device_id = ?1 AND vault_id = ?2 AND state = 'waiting' AND without_saving = 0 + ORDER BY id DESC LIMIT 1", + rusqlite::params![caller.device_id, vault_id], + |r| r.get(0), + ) + .ok(); let name: Option = conn.query_row("SELECT name FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0)).ok(); - (caller, role, name) + (caller, role, handover, name) }; let vault_name = vault_name.ok_or_else(not_found)?; - let Some(role) = role else { - return Err(ApiError(StatusCode::FORBIDDEN, format!("{} isn't a member of {vault_name}", caller.person))); + let role = match (role, handover) { + (Some(role), _) => role, + (None, Some(_)) if writing => "handover".to_string(), + _ => return Err(ApiError(StatusCode::FORBIDDEN, format!("{} has no access to {vault_name}", caller.person))), }; if writing && role == "read" { let conn = hub.db.lock().unwrap(); @@ -105,6 +116,7 @@ async fn handle( .env("REMOTE_ADDR", "127.0.0.1") .env("LUNE_HUB_DATA", &hub.data) .env("LUNE_ACTOR", caller.who()) + .env("LUNE_HANDOVER_REF", if role == "handover" { format!("refs/handover/{}", handover.unwrap_or(0)) } else { String::new() }) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::inherit()); diff --git a/hub/src/hook.rs b/hub/src/hook.rs index fe9f806..f245d95 100644 --- a/hub/src/hook.rs +++ b/hub/src/hook.rs @@ -22,11 +22,17 @@ pub fn pre_receive() -> Result { let conn = db::open(&data)?; let allowed = db::not_secrets(&conn, vault_id)?; + let handover = std::env::var("LUNE_HANDOVER_REF").unwrap_or_default(); let mut found = vec![]; for line in std::io::stdin().lock().lines() { let line = line?; let mut parts = line.split_whitespace(); - let (Some(_old), Some(new), Some(_name)) = (parts.next(), parts.next(), parts.next()) else { continue }; + let (Some(_old), Some(new), Some(name)) = (parts.next(), parts.next(), parts.next()) else { continue }; + // Leaving devices may only fill their own handover; nobody else writes to the handover area. + if (!handover.is_empty() && name != handover) || (handover.is_empty() && name.starts_with("refs/handover/")) { + eprintln!("lune: that place isn't open to this device"); + return Ok(false); + } let new = Oid::from_str(new)?; if new.is_zero() { continue; diff --git a/hub/src/leave.rs b/hub/src/leave.rs new file mode 100644 index 0000000..91e9c5e --- /dev/null +++ b/hub/src/leave.rs @@ -0,0 +1,405 @@ +//! Taking access back (M4): removing people from vaults, devices, and the team; handovers and their review. + +use crate::api::{ApiResult, Shared, authenticate, authenticate_any, bad, can_manage, denied}; +use crate::db; +use anyhow::{Context, Result}; +use axum::Json; +use axum::extract::State; +use axum::http::HeaderMap; +use lune_core::git2::{Oid, Repository, Signature}; +use rusqlite::{Connection, OptionalExtension, params}; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::path::Path; + +fn account(conn: &Connection, person: &str) -> Result> { + Ok(conn + .query_row("SELECT id, name, owner, disabled FROM accounts WHERE name = ?1", [person.trim()], |r| { + Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)) + }) + .optional()?) +} + +fn devices_phrase(n: usize) -> String { + match n { + 0 => "no devices to clean up".into(), + 1 => "1 device will hand over and leave".into(), + n => format!("{n} devices will hand over and leave"), + } +} + +#[derive(Deserialize)] +pub struct RemoveReq { + person: String, + vault: String, + #[serde(default)] + without_saving: bool, +} + +/// Removes a person from one vault (A5). Their other vaults are untouched. +pub async fn remove(State(hub): State, headers: HeaderMap, Json(req): Json) -> ApiResult { + let caller = authenticate(&hub, &headers)?; + let conn = hub.db.lock().unwrap(); + let (vault_id, vault) = db::vault_id(&conn, &req.vault)?.ok_or_else(|| bad(format!("no vault named {}", req.vault)))?; + if !can_manage(&conn, &caller, vault_id)? { + return Err(denied(format!("you need Manage on {vault} to remove people from it"))); + } + let (account_id, person, owner, _) = account(&conn, &req.person)?.ok_or_else(|| bad(format!("nobody named {}", req.person)))?; + if owner && account_id != caller.account_id { + return Err(denied("the team owner can't be removed from a vault by someone else")); + } + if db::role(&conn, account_id, vault_id)?.is_none() { + return Err(bad(format!("{person} isn't a member of {vault}"))); + } + conn.execute("DELETE FROM memberships WHERE account_id = ?1 AND vault_id = ?2", [account_id, vault_id])?; + let n = db::depart(&conn, account_id, vault_id, None, req.without_saving)?; + let how = if req.without_saving { " without saving" } else { "" }; + db::log(&conn, &caller.who(), "access removed", &format!("{person} from {vault}{how} ({})", devices_phrase(n)))?; + Ok(Json(json!({ "devices": n }))) +} + +#[derive(Deserialize)] +pub struct DeviceRemoveReq { + label: String, + person: Option, +} + +/// Removes one device (A1): it hands over and leaves every vault, then its key stops working. +pub async fn remove_device(State(hub): State, headers: HeaderMap, Json(req): Json) -> ApiResult { + let caller = authenticate(&hub, &headers)?; + let conn = hub.db.lock().unwrap(); + let (account_id, person) = match &req.person { + Some(p) if !p.eq_ignore_ascii_case(&caller.person) => { + if !caller.owner { + return Err(denied("only the team owner can remove someone else's device")); + } + let (id, name, _, _) = account(&conn, p)?.ok_or_else(|| bad(format!("nobody named {p}")))?; + (id, name) + } + _ => (caller.account_id, caller.person.clone()), + }; + let device: String = conn + .query_row( + "SELECT id FROM devices WHERE account_id = ?1 AND label = ?2 COLLATE NOCASE AND removed = 0", + params![account_id, req.label.trim()], + |r| r.get(0), + ) + .optional()? + .ok_or_else(|| bad(format!("{person} has no device called \"{}\"", req.label.trim())))?; + conn.execute("UPDATE devices SET removed = 1 WHERE id = ?1", [&device])?; + let mut stmt = conn.prepare("SELECT vault_id FROM memberships WHERE account_id = ?1")?; + let vaults: Vec = stmt.query_map([account_id], |r| r.get(0))?.collect::>()?; + for v in &vaults { + db::depart(&conn, account_id, *v, Some(&device), false)?; + } + db::retire_if_finished(&conn, &device)?; + db::log( + &conn, + &caller.who(), + "device removed", + &format!("{person}'s \"{}\" (hands over and leaves {} vault{})", req.label.trim(), vaults.len(), if vaults.len() == 1 { "" } else { "s" }), + )?; + Ok(Json(json!({}))) +} + +#[derive(Deserialize)] +pub struct PersonReq { + person: String, +} + +/// Remove from team (A8): every membership and device ends, the account is disabled (restorable). +pub async fn team_remove(State(hub): State, headers: HeaderMap, Json(req): Json) -> ApiResult { + let caller = authenticate(&hub, &headers)?; + if !caller.owner { + return Err(denied("only the team owner can remove someone from the team")); + } + let mut conn = hub.db.lock().unwrap(); + let tx = conn.transaction()?; + let (account_id, person, _, disabled) = account(&tx, &req.person)?.ok_or_else(|| bad(format!("nobody named {}", req.person)))?; + if account_id == caller.account_id { + return Err(bad("the team owner can't remove themselves")); + } + if disabled { + return Err(bad(format!("{person} was already removed from the team"))); + } + let vaults: Vec<(i64, String)> = { + let mut stmt = tx.prepare("SELECT v.id, v.name FROM memberships m JOIN vaults v ON v.id = m.vault_id WHERE m.account_id = ?1")?; + stmt.query_map([account_id], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::>()? + }; + for (id, _) in &vaults { + db::depart(&tx, account_id, *id, None, false)?; + } + tx.execute("DELETE FROM memberships WHERE account_id = ?1", [account_id])?; + tx.execute("UPDATE devices SET removed = 1 WHERE account_id = ?1", [account_id])?; + tx.execute("UPDATE accounts SET disabled = 1 WHERE id = ?1", [account_id])?; + tx.execute("DELETE FROM invites WHERE person = ?1 AND used IS NULL", [&person])?; + let devices: Vec = { + let mut stmt = tx.prepare("SELECT id FROM devices WHERE account_id = ?1")?; + stmt.query_map([account_id], |r| r.get(0))?.collect::>()? + }; + for d in &devices { + db::retire_if_finished(&tx, d)?; + } + let names: Vec<&str> = vaults.iter().map(|(_, n)| n.as_str()).collect(); + let from = if names.is_empty() { "no vaults".to_string() } else { names.join(", ") }; + db::log(&tx, &caller.who(), "removed from team", &format!("{person}: {from}; account disabled, devices will hand over and leave"))?; + tx.commit()?; + Ok(Json(json!({}))) +} + +/// Re-enables a removed account with no vaults; returns a one-time link to sign in a new device. +pub async fn team_restore(State(hub): State, headers: HeaderMap, Json(req): Json) -> ApiResult { + let caller = authenticate(&hub, &headers)?; + if !caller.owner { + return Err(denied("only the team owner can restore someone")); + } + let conn = hub.db.lock().unwrap(); + let (account_id, person, _, disabled) = account(&conn, &req.person)?.ok_or_else(|| bad(format!("nobody named {}", req.person)))?; + if !disabled { + return Err(bad(format!("{person} wasn't removed from the team"))); + } + conn.execute("UPDATE accounts SET disabled = 0 WHERE id = ?1", [account_id])?; + conn.execute("DELETE FROM invites WHERE person = ?1 AND used IS NULL", [&person])?; + let token = db::token(32); + conn.execute( + "INSERT INTO invites (token_hash, person, owner, grants, created_by, expires, account_id) VALUES (?1, ?2, 0, '[]', ?3, ?4, ?5)", + params![db::hash(&token), person, caller.who(), db::now() + 7 * 86400, account_id], + )?; + db::log(&conn, &caller.who(), "restored to team", &format!("{person} (no vaults yet)"))?; + Ok(Json(json!({ "link": format!("{}/join/{token}", hub.url) }))) +} + +#[derive(Deserialize)] +pub struct SettingsReq { + vault: String, + delete_from_devices: bool, +} + +/// "Delete from their devices" (A7), on by default. +pub async fn vault_settings(State(hub): State, headers: HeaderMap, Json(req): Json) -> ApiResult { + let caller = authenticate(&hub, &headers)?; + let conn = hub.db.lock().unwrap(); + let (id, name) = db::vault_id(&conn, &req.vault)?.ok_or_else(|| bad(format!("no vault named {}", req.vault)))?; + if !can_manage(&conn, &caller, id)? { + return Err(denied(format!("you need Manage on {name}"))); + } + conn.execute("UPDATE vaults SET delete_from_devices = ?1 WHERE id = ?2", params![req.delete_from_devices, id])?; + let what = if req.delete_from_devices { "on" } else { "off" }; + db::log(&conn, &caller.who(), "vault setting", &format!("{name}: delete from devices on removal {what}"))?; + Ok(Json(json!({}))) +} + +#[derive(Deserialize)] +pub struct DoneReq { + id: i64, + head: Option, +} + +/// A leaving device reports in: it has handed over (or had nothing to), and will now delete its copy. +pub async fn departure_done(State(hub): State, headers: HeaderMap, Json(req): Json) -> ApiResult { + let caller = authenticate_any(&hub, &headers)?; + let conn = hub.db.lock().unwrap(); + let found: Option<(i64, String, bool)> = conn + .query_row( + "SELECT d.vault_id, v.name, d.without_saving FROM departures d JOIN vaults v ON v.id = d.vault_id + WHERE d.id = ?1 AND d.device_id = ?2 AND d.state = 'waiting'", + params![req.id, caller.device_id], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .optional()?; + let Some((vault_id, vault, without_saving)) = found else { + return Err(bad("there's no open departure like that for this device")); + }; + let repo = Repository::open_bare(hub.repo_path(vault_id)).map_err(anyhow::Error::from)?; + let handover = format!("refs/handover/{}", req.id); + let state = match (&req.head, without_saving) { + (_, true) | (None, false) => if without_saving { "skipped" } else { "done" }, + (Some(head), false) => { + let got = repo.find_reference(&handover).ok().and_then(|r| r.target()); + if got.map(|o| o.to_string()).as_deref() != Some(head.as_str()) { + return Err(bad("the hub hasn't received that handover")); + } + let head = Oid::from_str(head).map_err(anyhow::Error::from)?; + if already_shared(&repo, head)? { + repo.find_reference(&handover).and_then(|mut r| r.delete()).map_err(anyhow::Error::from)?; + "done" + } else { + "received" + } + } + }; + conn.execute("UPDATE departures SET state = ?1, updated = ?2 WHERE id = ?3", params![state, db::now(), req.id])?; + let detail = match state { + "received" => format!("{vault}: unshared work handed over, waiting for review (handover {})", req.id), + "skipped" => format!("{vault}: copy deleted without saving"), + _ => format!("{vault}: nothing unshared; copy removed"), + }; + db::log(&conn, &caller.who(), "left vault", &detail)?; + db::retire_if_finished(&conn, &caller.device_id)?; + Ok(Json(json!({ "state": state }))) +} + +/// The vault's main line: whatever HEAD points to, or the only branch there is. +fn main_ref(repo: &Repository) -> Result> { + if let Ok(head) = repo.find_reference("HEAD") + && let Some(target) = head.symbolic_target().ok().flatten() + && repo.find_reference(target).is_ok() + { + return Ok(Some(target.to_string())); + } + for r in repo.references_glob("refs/heads/*")? { + if let Ok(name) = r?.name() { + return Ok(Some(name.to_string())); + } + } + Ok(None) +} + +fn already_shared(repo: &Repository, head: Oid) -> Result { + let Some(main) = main_ref(repo)? else { return Ok(false) }; + let tip = repo.find_reference(&main)?.peel_to_commit()?.id(); + Ok(tip == head || repo.graph_descendant_of(tip, head)?) +} + +/// Combines a handover into the vault's main line; same-lines clashes keep both, labeled with `label`. +fn keep_handover(repo_path: &Path, id: i64, label: &str) -> Result { + let repo = Repository::open_bare(repo_path)?; + let mut handover_ref = repo.find_reference(&format!("refs/handover/{id}"))?; + let handover = handover_ref.peel_to_commit()?; + let Some(main) = main_ref(&repo)? else { + repo.reference("refs/heads/main", handover.id(), false, "lune: kept handover")?; + handover_ref.delete()?; + return Ok(0); + }; + let tip = repo.find_reference(&main)?.peel_to_commit()?; + let mut kept = vec![]; + if repo.graph_descendant_of(handover.id(), tip.id())? { + repo.reference_matching(&main, handover.id(), true, tip.id(), "lune: kept handover")?; + } else if !repo.graph_descendant_of(tip.id(), handover.id())? { + let mut index = repo.merge_commits(&tip, &handover, None)?; + lune_core::vault::keep_both(&mut index, label, &mut kept)?; + let tree = repo.find_tree(index.write_tree_to(&repo)?)?; + let sig = Signature::now(label, "handover@lune.device")?; + let msg = format!("Kept the handover from {label}"); + let id = repo.commit(None, &sig, &sig, &msg, &tree, &[&tip, &handover])?; + repo.reference_matching(&main, id, true, tip.id(), "lune: kept handover")?; + } + handover_ref.delete()?; + Ok(kept.len()) +} + +/// Departures in vaults the caller manages (all of them for the owner), newest first. +pub async fn handovers(State(hub): State, headers: HeaderMap) -> ApiResult { + let caller = authenticate(&hub, &headers)?; + let conn = hub.db.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT d.id, d.vault_id, v.name, a.name, dev.label, d.state, d.updated + FROM departures d JOIN vaults v ON v.id = d.vault_id JOIN accounts a ON a.id = d.account_id + JOIN devices dev ON dev.id = d.device_id ORDER BY d.id DESC LIMIT 100", + )?; + let rows: Vec<(i64, i64, String, String, String, String, i64)> = stmt + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?)))? + .collect::>()?; + let mut out = vec![]; + for (id, vault_id, vault, person, device, state, at) in rows { + if can_manage(&conn, &caller, vault_id)? { + out.push(json!({ "id": id, "vault": vault, "person": person, "device": device, "state": state, "at": at })); + } + } + Ok(Json(Value::Array(out))) +} + +#[derive(Deserialize)] +pub struct IdReq { + id: i64, +} + +/// (vault id, vault name, device label, state) of a departure the caller may decide about. +fn departure_for(conn: &Connection, caller: &db::Caller, id: i64) -> Result<(i64, String, String, String), crate::api::ApiError> { + let found: Option<(i64, String, String, String)> = conn + .query_row( + "SELECT d.vault_id, v.name, dev.label, d.state FROM departures d JOIN vaults v ON v.id = d.vault_id + JOIN devices dev ON dev.id = d.device_id WHERE d.id = ?1", + [id], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + ) + .optional()?; + let found = found.ok_or_else(|| bad(format!("no handover {id}")))?; + if !can_manage(conn, caller, found.0)? { + return Err(denied(format!("you need Manage on {} to decide about its handovers", found.1))); + } + Ok(found) +} + +pub async fn handover_show(State(hub): State, headers: HeaderMap, Json(req): Json) -> ApiResult { + let caller = authenticate(&hub, &headers)?; + let conn = hub.db.lock().unwrap(); + let (vault_id, _, _, state) = departure_for(&conn, &caller, req.id)?; + if state != "received" { + return Err(bad(format!("handover {} has nothing to review ({state})", req.id))); + } + let lines = (|| -> Result> { + let repo = Repository::open_bare(hub.repo_path(vault_id))?; + let handover = repo.find_reference(&format!("refs/handover/{}", req.id))?.peel_to_commit()?; + let base = match main_ref(&repo)? { + Some(m) => { + let tip = repo.find_reference(&m)?.peel_to_commit()?; + repo.merge_base(tip.id(), handover.id()).ok().map(|b| repo.find_commit(b)).transpose()?.map(|c| c.tree()).transpose()? + } + None => None, + }; + let diff = repo.diff_tree_to_tree(base.as_ref(), Some(&handover.tree()?), None)?; + Ok(diff + .deltas() + .map(|d| { + let what = match d.status() { + lune_core::git2::Delta::Added => "added", + lune_core::git2::Delta::Deleted => "removed", + _ => "changed", + }; + let path = d.new_file().path().or(d.old_file().path()).map(|p| p.display().to_string()).unwrap_or_default(); + format!("{what:<8} {path}") + }) + .collect()) + })() + .context("can't read the handover")?; + Ok(Json(json!(lines))) +} + +#[derive(Deserialize)] +pub struct DecideReq { + id: i64, + decision: String, +} + +/// keep / discard a received handover, or skip (delete without saving) a device that hasn't reported in. +pub async fn handover_decide(State(hub): State, headers: HeaderMap, Json(req): Json) -> ApiResult { + let caller = authenticate(&hub, &headers)?; + let conn = hub.db.lock().unwrap(); + let (vault_id, vault, device, state) = departure_for(&conn, &caller, req.id)?; + let (new_state, message) = match (req.decision.as_str(), state.as_str()) { + ("keep", "received") => { + let clashes = keep_handover(&hub.repo_path(vault_id), req.id, &device)?; + let extra = if clashes > 0 { format!(" ({clashes} note(s) changed in two places: both versions kept)") } else { String::new() }; + ("kept", format!("Kept {device}'s handover in {vault}{extra}. It reaches every device on its next sync.")) + } + ("discard", "received") => { + let repo = Repository::open_bare(hub.repo_path(vault_id)).map_err(anyhow::Error::from)?; + repo.find_reference(&format!("refs/handover/{}", req.id)).and_then(|mut r| r.delete()).map_err(anyhow::Error::from)?; + ("discarded", format!("Discarded {device}'s handover for {vault}.")) + } + ("skip", "waiting") => { + conn.execute("UPDATE departures SET without_saving = 1 WHERE id = ?1", [req.id])?; + return { + db::log(&conn, &caller.who(), "handover skipped", &format!("{device} in {vault}: delete without saving"))?; + Ok(Json(json!({ "message": format!("{device} will delete its copy of {vault} without sending anything, the next time it's online.") }))) + }; + } + ("keep" | "discard", _) => return Err(bad(format!("handover {} has nothing to review ({state})", req.id))), + ("skip", _) => return Err(bad(format!("{device} has already reported in ({state})"))), + _ => return Err(bad("decide keep, discard or skip")), + }; + conn.execute("UPDATE departures SET state = ?1, updated = ?2 WHERE id = ?3", params![new_state, db::now(), req.id])?; + db::log(&conn, &caller.who(), &format!("handover {new_state}"), &format!("{device} in {vault}"))?; + Ok(Json(json!({ "message": message }))) +} diff --git a/hub/src/main.rs b/hub/src/main.rs index 401bca6..caad264 100644 --- a/hub/src/main.rs +++ b/hub/src/main.rs @@ -4,6 +4,7 @@ mod api; mod db; mod git; mod hook; +mod leave; use anyhow::Result; use axum::Router; @@ -74,6 +75,15 @@ async fn serve() -> Result<()> { .route("/api/members", post(api::members)) .route("/api/log", get(api::log)) .route("/api/not-secrets", post(api::not_secret)) + .route("/api/remove", post(leave::remove)) + .route("/api/device/remove", post(leave::remove_device)) + .route("/api/team/remove", post(leave::team_remove)) + .route("/api/team/restore", post(leave::team_restore)) + .route("/api/vaults/settings", post(leave::vault_settings)) + .route("/api/departures/done", post(leave::departure_done)) + .route("/api/handovers", get(leave::handovers)) + .route("/api/handovers/show", post(leave::handover_show)) + .route("/api/handovers/decide", post(leave::handover_decide)) .route("/git/{repo}/{*rest}", any(git::serve)) .route("/health", get(|| async { "ok" })) .layer(DefaultBodyLimit::disable()) diff --git a/hub/tests/hub.rs b/hub/tests/hub.rs index a36df62..54ebfe1 100644 --- a/hub/tests/hub.rs +++ b/hub/tests/hub.rs @@ -7,6 +7,9 @@ use std::collections::HashSet; use std::io::{BufRead, BufReader}; use std::process::{Child, Command, Stdio}; +/// Hub credentials are process-wide (as in the app), so these tests take turns. +static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + struct HubProcess(Child); impl Drop for HubProcess { @@ -47,6 +50,7 @@ fn as_device(url: &str, w: &hub::Welcome) -> HubLink { #[test] fn hub_lifecycle() { + let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); let tmp = tempfile::TempDir::new().unwrap(); let (_hub, url, owner_link) = start_hub(&tmp.path().join("data")); @@ -106,3 +110,147 @@ fn hub_lifecycle() { assert!(log.iter().any(|a| a == action), "missing {action} in {log:?}"); } } + +// ---- Milestone 4: taking access back ---- + +use lune_core::config::Config; +use lune_core::membership::arrive; + +fn device(url: &str, w: &hub::Welcome, label: &str, dir: &std::path::Path) -> Config { + Config { + device_name: Some(label.into()), + vaults_dir: Some(dir.to_path_buf()), + hub: Some(HubLink { url: url.into(), device_id: w.device_id.clone(), key: w.key.clone() }), + ..Default::default() + } +} + +/// Runs one check-in for a device, as `lunesync run` does every 30 s. +fn check_in(cfg: &mut Config) -> Vec { + cfg.use_hub_credentials(); + arrive(cfg).unwrap() +} + +fn open(cfg: &Config, name: &str) -> Vault { + let vc = cfg.find(name).unwrap_or_else(|| panic!("{name} missing")); + cfg.use_hub_credentials(); + Vault::open(vc, &cfg.device_label()).unwrap() +} + +fn write_and_save(v: &Vault, file: &str, text: &str) { + std::fs::write(v.root.join(file), text).unwrap(); + v.save_changes(None, &HashSet::new()).unwrap(); +} + +#[test] +fn taking_access_back() { + let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let tmp = tempfile::TempDir::new().unwrap(); + // Config::save writes here; each device's config lives in memory in this test. + unsafe { std::env::set_var("LUNE_HOME", tmp.path().join("cfg")) }; + let (_hub, url, owner_link) = start_hub(&tmp.path().join("data")); + let (_, sen_w) = hub::join(&owner_link, "Codex").unwrap(); + let mut sen = device(&url, &sen_w, "Codex", &tmp.path().join("sen")); + let sen_hub = sen.hub.clone().unwrap(); + sen.use_hub_credentials(); + sen_hub.create_vault("DevOps").unwrap(); + sen_hub.create_vault("Notes").unwrap(); + check_in(&mut sen); + write_and_save(&open(&sen, "DevOps"), "runbook.md", "restart\n"); + open(&sen, "DevOps").sync().unwrap(); + + // 1. Alice edits DevOps while offline, then loses DevOps only. + let link = sen_hub.invite("Alice", &[("DevOps".into(), "edit".into()), ("Notes".into(), "edit".into())]).unwrap(); + let (_, alice_w) = hub::join(&link, "Alice laptop").unwrap(); + let mut alice = device(&url, &alice_w, "Alice laptop", &tmp.path().join("alice")); + assert_eq!(check_in(&mut alice).len(), 2); + let a = open(&alice, "DevOps"); + write_and_save(&a, "alice.md", "alice's unshared work\n"); + std::fs::write(a.root.join("keys.md"), "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n").unwrap(); + let alice_devops = a.root.clone(); + drop(a); + sen.use_hub_credentials(); + assert_eq!(sen_hub.remove("Alice", "DevOps", false).unwrap(), 1); + + let said = check_in(&mut alice); + assert!(said[0].contains("folder was deleted"), "{said:?}"); + assert!(!alice_devops.exists()); + assert!(alice.find("DevOps").is_none()); + let n = open(&alice, "Notes"); + write_and_save(&n, "still.md", "notes keep syncing\n"); + n.sync().unwrap(); + + // 2. Sen reviews and keeps the handover; the secret never arrives, the work does. + sen.use_hub_credentials(); + let h = sen_hub.handovers().unwrap(); + assert_eq!((h[0].person.as_str(), h[0].state.as_str()), ("Alice", "received")); + let files = sen_hub.handover_show(h[0].id).unwrap(); + assert!(files.iter().any(|f| f.ends_with("alice.md")) && files.iter().any(|f| f.ends_with("keys.md")), "{files:?}"); + sen_hub.handover_decide(h[0].id, "keep").unwrap(); + let s = open(&sen, "DevOps"); + s.sync().unwrap(); + assert_eq!(std::fs::read(s.root.join("alice.md")).unwrap(), b"alice's unshared work\n"); + assert_eq!(std::fs::read(s.root.join("keys.md")).unwrap(), b"aws_access_key_id = [secret removed when leaving]\n"); + + // 3. Bob is removed from the team: everything stops; restored, he comes back with nothing. + let link = sen_hub.invite("Bob", &[("DevOps".into(), "edit".into()), ("Notes".into(), "read".into())]).unwrap(); + let (_, bob_w) = hub::join(&link, "Bob pc").unwrap(); + let mut bob = device(&url, &bob_w, "Bob pc", &tmp.path().join("bob")); + check_in(&mut bob); + write_and_save(&open(&bob, "DevOps"), "bob.md", "bob was here\n"); + sen.use_hub_credentials(); + sen_hub.team_remove("Bob").unwrap(); + let said = check_in(&mut bob); + assert_eq!(said.len(), 2, "{said:?}"); + assert!(bob.vaults.is_empty()); + assert!(!tmp.path().join("bob/DevOps").exists() && !tmp.path().join("bob/Notes").exists()); + let said = check_in(&mut bob); + assert!(said[0].contains("removed from the hub"), "{said:?}"); + assert!(bob.hub.is_none()); + sen.use_hub_credentials(); + let bob_handover = sen_hub.handovers().unwrap().into_iter().find(|h| h.person == "Bob" && h.state == "received").unwrap(); + sen_hub.handover_decide(bob_handover.id, "discard").unwrap(); + open(&sen, "DevOps").sync().unwrap(); + assert!(!open(&sen, "DevOps").root.join("bob.md").exists()); + assert!(sen_hub.grant("Bob", "Notes", "read").is_err(), "a removed person can't be granted access"); + let back = sen_hub.team_restore("Bob").unwrap(); + let (_, bob2) = hub::join(&back, "Bob new pc").unwrap(); + let bob2 = HubLink { url: url.clone(), device_id: bob2.device_id, key: bob2.key }; + assert!(bob2.me().unwrap().vaults.is_empty()); + + // 4. A switched-off device is removed and skipped: later it deletes its copy and sends nothing. + sen.use_hub_credentials(); + let code = sen_hub.pair().unwrap(); + let old_w = hub::login(&url, &code, "Old laptop").unwrap(); + let mut old = device(&url, &old_w, "Old laptop", &tmp.path().join("old")); + check_in(&mut old); + write_and_save(&open(&old, "DevOps"), "old.md", "never sent\n"); + sen.use_hub_credentials(); + sen_hub.remove_device("Old laptop", None).unwrap(); + for h in sen_hub.handovers().unwrap().into_iter().filter(|h| h.device == "Old laptop") { + assert_eq!(h.state, "waiting"); + sen_hub.handover_decide(h.id, "skip").unwrap(); + } + check_in(&mut old); + assert!(!tmp.path().join("old/DevOps").exists()); + sen.use_hub_credentials(); + assert!(sen_hub.handovers().unwrap().iter().filter(|h| h.device == "Old laptop").all(|h| h.state == "skipped")); + assert!(check_in(&mut old)[0].contains("removed from the hub")); + + // 5. With "delete from devices" off, the copy stays, read-only and no longer synced. + sen.use_hub_credentials(); + sen_hub.vault_setting("Notes", false).unwrap(); + sen_hub.remove("Alice", "Notes", false).unwrap(); + let said = check_in(&mut alice); + assert!(said[0].contains("read-only"), "{said:?}"); + let kept = tmp.path().join("alice/Notes"); + assert!(kept.join("still.md").exists()); + assert!(std::fs::write(kept.join("new.md"), "x").is_err(), "folder should be read-only"); + assert!(alice.vaults.is_empty()); + + sen.use_hub_credentials(); + let log: Vec = sen_hub.log(200).unwrap().into_iter().map(|e| e.action).collect(); + for action in ["access removed", "left vault", "handover kept", "removed from team", "handover discarded", "restored to team", "device removed", "handover skipped", "vault setting"] { + assert!(log.iter().any(|a| a == action), "missing {action} in {log:?}"); + } +}