//! 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 serde::Serialize; use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; 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]"; /// For every hub this device is on: 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. /// One hub failing doesn't stop the others; the first error comes back after the rest have run. pub fn arrive(config: &mut Config) -> Result> { let mut said = vec![]; let mut failed = None; for (_, result) in arrive_each(config) { match result { Ok(mut msgs) => said.append(&mut msgs), Err(e) => failed = failed.or(Some(e)), } } match failed { Some(e) if said.is_empty() => Err(e), Some(e) => { said.push(format!("can't check the hub: {e:#}")); Ok(said) } None => Ok(said), } } /// `arrive`, hub by hub: (hub address, what happened there). pub fn arrive_each(config: &mut Config) -> Vec<(String, Result>)> { let several = config.hubs.len() > 1; let mut out = vec![]; for h in config.hubs.clone() { let result = arrive_from(config, &h).map_err(|e| if several { e.context(h.url.clone()) } else { e }); out.push((h.url, result)); } out } fn arrive_from(config: &mut Config, h: &HubLink) -> Result> { 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.hubs.retain(|x| x.url != h.url); config.vaults.retain(|v| v.hub_url.as_deref() != Some(&h.url)); config.save()?; return Ok(vec![format!("This device was removed from the hub at {}. Other vaults keep syncing.", h.url)]); } Err(e) => return Err(e), }; let label = config.device_label(); let mine = |v: &crate::config::VaultConfig, id: i64| v.hub_vault == Some(id) && v.hub_url.as_deref() == Some(&h.url); let mut said = vec![]; for d in &me.leaving { said.push(leave(config, h, d)?); } if me.nudge { // Each of this hub's vault runners sees this and shares at once. for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some() && v.hub_url.as_deref() == Some(&h.url)) { let dir = state::lune_dir(&vc.path.join(".git")); if dir.exists() { std::fs::write(dir.join("nudge"), "")?; } } said.push("Someone asked this device to share now — sharing".into()); } for hv in me.vaults { if let Some(vc) = config.vaults.iter().find(|v| mine(v, 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); vc.hub_url = Some(h.url.clone()); config.save()?; said.push(format!("{} now syncs through the hub", hv.name)); continue; } // Two teams can each have a "Notes": the second one gets the team's address in its folder name. let mut path = config.vaults_dir().join(&hv.name); let real = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); if config.vaults.iter().any(|v| real(&v.path) == real(&path)) { let host = h.url.split("://").last().unwrap_or(&h.url).replace([':', '/'], "-"); path = config.vaults_dir().join(format!("{} ({host})", 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); cfg.hub_url = Some(h.url.clone()); 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) } /// Tells each hub how this device's vaults on it are doing (M6 freshness). pub fn report(config: &Config) -> Result<()> { let label = config.device_label(); let mut failed = None; for h in &config.hubs { let mut out = vec![]; for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some() && v.hub_url.as_deref() == Some(&h.url)) { let Ok(v) = Vault::open(vc, &label) else { continue }; out.push(hub::VaultHealth { vault_id: vc.hub_vault.unwrap(), last_synced: state::SyncState::load(&v.git_dir).last_synced, waiting: v.waiting_files().unwrap_or(0), held_secrets: v.secret_holds().map(|n| n.len()).unwrap_or(0), holding: !crate::guard::load(&v.git_dir).is_empty(), }); } if let Err(e) = h.report(&out) { failed = Some(e); } } failed.map_or(Ok(()), Err) } /// 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) && v.hub_url.as_deref() == Some(&link.url)).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())) } } /// Leaves one team's hub on this device. If the hub answers, this device removes itself there, which hands /// over anything unshared and leaves its vaults the usual way (A6). If the hub is gone or no longer knows this /// device, `forget` drops it from this device only: its folders stay where they are, no longer synced. pub fn leave_hub(config: &mut Config, url: &str, forget: bool) -> Result> { let Some(link) = config.hub(url).cloned() else { bail!("this device isn't on the hub at {url}") }; let label = config.device_label(); let reached = link.remove_device(&label, None).and_then(|_| link.me()); let mut said = vec![]; match reached { Ok(me) => { for d in &me.leaving { said.push(leave(config, &link, d)?); } } Err(e) if !forget => { bail!("can't reach the hub at {url} ({e:#}). If that team is gone for good, forget it on this device only") } Err(_) => said.push(format!("Couldn't reach {url}, so this device only forgot it; its folders stay, no longer synced")), } for vc in config.vaults.iter().filter(|v| v.hub_url.as_deref() == Some(url) && v.path.exists()) { let _ = set_read_only(&vc.path, false); said.push(format!("{} stays at {}, no longer synced", vc.name, vc.path.display())); } config.vaults.retain(|v| v.hub_url.as_deref() != Some(url)); config.hubs.retain(|h| h.url != url); config.save()?; said.push(format!("Left the team at {url}")); Ok(said) } /// What uninstalling did, in plain words. #[derive(Debug, Default, Serialize)] pub struct Uninstalled { /// Folders deleted. pub removed: Vec, /// Folders left in place, each with why ("path — reason"). pub kept: Vec, /// Set when the hub couldn't be told this device is gone. pub hub_problem: Option, } /// Uninstall (D5). Every runner must already be stopped (`runner::STOP`). Shares what it can, hands the rest /// over through the hub (A6) and signs this device out, then deletes the vault folders Lune created. A folder /// still holding work that is neither shared nor handed over stays, and so does one the person added (A9). pub fn uninstall(config: &mut Config) -> Result { let label = config.device_label(); let all = config.vaults.clone(); let mut out = Uninstalled::default(); let mut unshared: HashMap = HashMap::new(); for vc in &all { let Ok(v) = Vault::open(vc, &label) else { continue }; wait_for_runner(&v)?; let _op = state::op_lock(&v.git_dir)?; let _ = v.save_changes(None, &HashSet::new()); if v.role().is_none_or(|r| hub::can_edit(&r)) { let _ = v.sync(); } if let Some(why) = unshared_work(&v) { unshared.insert(vc.path.clone(), why); } } for link in config.hubs.clone() { let signed_out = link.remove_device(&label, None).and_then(|_| link.me()); match signed_out { Ok(me) => { for d in &me.leaving { match leave(config, &link, d) { // Whatever wasn't shared is with the vault's managers now. Ok(_) => { let left = all.iter().find(|v| v.hub_vault == Some(d.vault_id) && v.hub_url.as_deref() == Some(&link.url)); if let Some(vc) = left { unshared.remove(&vc.path); } } Err(e) => out.hub_problem = Some(format!("couldn't hand over {}: {e:#}", d.vault)), } } } Err(e) => { out.hub_problem = Some(format!( "couldn't reach the hub at {} ({e:#}) — this device still shows on its canvas; remove it there", link.url )) } } } for vc in &all { let shown = vc.path.display().to_string(); if !vc.path.exists() { out.removed.push(shown); continue; } let _ = set_read_only(&vc.path, false); let created = state::read_marker(&vc.path.join(".git")).is_some_and(|m| m.created_folder && m.managed_by == "lune"); if let Some(why) = unshared.get(&vc.path) { out.kept.push(format!("{shown} — {why}")); } else if !created { out.kept.push(format!("{shown} — you added this folder yourself")); } else { // remove_dir_all removes links themselves, never what they point to (A9). std::fs::remove_dir_all(&vc.path)?; out.removed.push(shown); } } config.vaults.clear(); config.hubs.clear(); config.save()?; Ok(out) } /// Waits until the vault's runner has let go of it. fn wait_for_runner(v: &Vault) -> Result<()> { let deadline = Instant::now() + Duration::from_secs(60); while state::try_run_lock(&v.git_dir)?.is_none() { if Instant::now() > deadline { bail!("{} is still busy syncing; try again in a moment", v.name); } std::thread::sleep(Duration::from_millis(250)); } Ok(()) } /// Why a vault still holds work nobody else has, if it does. fn unshared_work(v: &Vault) -> Option { if !v.secret_holds().unwrap_or_default().is_empty() { return Some("a note was held back as a possible secret".into()); } if !crate::guard::load(&v.git_dir).is_empty() { return Some("a big change is waiting for you to confirm it".into()); } match v.waiting_files().unwrap_or(0) { 0 => None, n if v.role().is_some_and(|r| !hub::can_edit(&r)) => Some(format!("{n} changed notes you can't share (read access)")), n => Some(format!("{n} changed notes couldn't be shared (offline?)")), } } /// 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(()) }