Milestone 3: the hub

lunehub serves accounts, invites, pairing codes, memberships, devices
and vaults as plain bare repos (SPEC §8), checks device key and role on
every Git request, refuses secrets in a pre-receive hook (P3) and logs
every access change. Ships as one container (Dockerfile, compose.yaml).

lunesync gains join, login, pair, vault new/upload, invite, grant,
members and hub log; `run` picks up new vaults and roles from the hub.
Read members' edits stay local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 00:47:54 +07:00
parent 62bc3db416
commit 2b4ca84a6b
23 changed files with 2578 additions and 58 deletions

192
cli/src/team.rs Normal file
View File

@@ -0,0 +1,192 @@
//! 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::{self, 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(())
}
/// 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<Vec<String>> {
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 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(())
}