Files
lune/cli/src/team.rs
Adnan Zahir 4025726083 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 <noreply@anthropic.com>
2026-10-29 06:14:28 +07:00

222 lines
8.9 KiB
Rust

//! Hub commands: joining, pairing devices, vaults on the hub, invites, grants, members and the access log.
use anyhow::{Context, Result, bail};
use chrono::{Local, TimeZone};
use lune_core::config::{Config, VaultConfig};
use lune_core::hub::{self, HubLink};
use lune_core::remote;
use lune_core::state;
use lune_core::vault::Vault;
use std::path::PathBuf;
pub fn link(config: &Config) -> Result<&HubLink> {
config.hub.as_ref().context("this device isn't on a hub yet — `lunesync join <invite link>` or `lunesync login`")
}
fn connect(config: &mut Config, url: String, w: hub::Welcome, label: &str, vaults_dir: Option<PathBuf>) -> Result<()> {
config.hub = Some(HubLink { url, device_id: w.device_id, key: w.key });
config.device_name = Some(label.to_string());
if vaults_dir.is_some() {
config.vaults_dir = vaults_dir;
}
config.save()?;
config.use_hub_credentials();
println!("Welcome, {}. This device is \"{label}\".", w.person);
for msg in arrive(config)? {
println!("{msg}");
}
println!("Keep it in sync with `lunesync run` (or `lunesync service install`).");
Ok(())
}
pub fn join(config: &mut Config, invite: &str, label: &str, vaults_dir: Option<PathBuf>) -> Result<()> {
if let Some(h) = &config.hub {
bail!("this device is already on the hub at {}", h.url);
}
let (url, w) = hub::join(invite, label)?;
connect(config, url, w, label, vaults_dir)
}
pub fn login(config: &mut Config, url: &str, code: &str, label: &str, vaults_dir: Option<PathBuf>) -> Result<()> {
if let Some(h) = &config.hub {
bail!("this device is already on the hub at {}", h.url);
}
let w = hub::login(url, code, label)?;
connect(config, url.trim_end_matches('/').to_string(), w, label, vaults_dir)
}
pub fn pair(config: &Config) -> Result<()> {
let h = link(config)?;
let code = h.pair()?;
println!("On the new device (code works once, for 10 minutes):\n");
println!(" lunesync login --hub {} --code {code} --name <its label>", h.url);
Ok(())
}
pub use lune_core::membership::arrive;
pub fn vault_new(config: &mut Config, name: &str) -> Result<()> {
let hv = link(config)?.create_vault(name)?;
println!("Created {} on the hub.", hv.name);
for msg in arrive(config)? {
println!("{msg}");
}
Ok(())
}
/// Moves a vault that syncs through a plain Git remote onto the hub.
pub fn vault_upload(config: &mut Config, name: &str, fresh: bool) -> Result<()> {
let h = link(config)?.clone();
let label = config.device_label();
let cfg: VaultConfig = config.find(name).with_context(|| format!("no vault named \"{name}\" on this device"))?.clone();
if cfg.hub_vault.is_some() {
bail!("{} already syncs through the hub", cfg.name);
}
let hv = match h.create_vault(&cfg.name) {
Ok(hv) => hv,
Err(e) if format!("{e}").contains("already a vault") => h
.me()?
.vaults
.into_iter()
.find(|v| v.name.eq_ignore_ascii_case(&cfg.name))
.context("the hub has a vault with that name that you're not a member of")?,
Err(e) => return Err(e),
};
let v = Vault::open(&cfg, &label)?;
let _op = state::op_lock(&v.git_dir)?;
v.save_changes(None, &Default::default())?;
let before = if fresh { Some(v.fresh_start(&format!("Fresh start on the hub (earlier history stays on {label})"))?) } else { None };
v.relink(&hv.git_url)?;
state::write_role(&v.git_dir, &hv.role)?;
let joined = v.join_unrelated();
match joined.and_then(|_| v.sync()) {
Ok(_) => {
let vc = config.vaults.iter_mut().find(|x| x.path == cfg.path).unwrap();
vc.remote = hv.git_url.clone();
vc.hub_vault = Some(hv.id);
config.save()?;
println!("{} now syncs through the hub{}.", cfg.name, if fresh { ", starting fresh" } else { ", history included" });
println!("Other devices with this vault: `lunesync pair` here, then `lunesync login …` there — it moves over on its own.");
Ok(())
}
Err(e) => {
v.relink(&cfg.remote)?;
if let Some(id) = before {
v.reset_history(id)?;
}
let why = remote::describe_error(&e);
if why.contains("possible") && !fresh {
bail!("{why}\nThe old history has a secret in it. `lunesync vault upload {name} --fresh` uploads just the current notes.");
}
bail!("{why}\n{} keeps syncing where it did before.", cfg.name)
}
}
}
pub fn invite(config: &Config, person: &str, vaults: &[String]) -> Result<()> {
let grants: Vec<(String, String)> = vaults
.iter()
.map(|v| match v.rsplit_once(':') {
Some((name, role)) => (name.to_string(), role.to_string()),
None => (v.clone(), "edit".to_string()),
})
.collect();
let link = link(config)?.invite(person, &grants)?;
println!("Send this to {person}. It works once, for 7 days:\n");
println!(" lunesync join {link} --name <their device>");
Ok(())
}
pub fn grant(config: &Config, person: &str, vault: &str, role: &str) -> Result<()> {
link(config)?.grant(person, vault, role)?;
println!("{person} has {role} access to {vault}. It arrives on their devices within a minute.");
Ok(())
}
pub fn members(config: &Config, vault: &str) -> Result<()> {
for m in link(config)?.members(vault)? {
let devices = if m.devices.is_empty() { "no devices".to_string() } else { m.devices.join(", ") };
println!(" {:<16} {:<7} {devices}", m.person, m.role);
}
Ok(())
}
pub fn log(config: &Config, count: usize) -> Result<()> {
for e in link(config)?.log(count)?.into_iter().rev() {
let at = Local.timestamp_opt(e.at, 0).single().map(|t| t.format("%Y-%m-%d %H:%M").to_string()).unwrap_or_default();
println!("{at} {:<22} {:<15} {}", e.actor, e.action, e.detail);
}
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 <their device>");
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(())
}