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

View File

@@ -1,4 +1,5 @@
mod service;
mod team;
use anyhow::{Context, Result, bail};
use chrono::{Local, TimeZone};
@@ -11,7 +12,9 @@ use lune_core::state::{self, SyncState};
use lune_core::tidy::{self, Keep};
use lune_core::vault::{self, Added, Vault};
use lune_core::remote;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
#[derive(Parser)]
#[command(name = "lunesync", version, about = "Keeps every copy of your vaults in sync.")]
@@ -63,6 +66,55 @@ enum Command {
#[arg(long, global = true)]
vault: Option<String>,
},
/// Join a team's hub with an invite link (creates your account and this device)
Join {
link: String,
/// Label for this device, e.g. Codex
#[arg(long)]
name: String,
/// Where vaults from the hub go (default ~/Vaults)
#[arg(long)]
vaults_dir: Option<PathBuf>,
},
/// Add this device to your hub account with a code from `lunesync pair`
Login {
#[arg(long)]
hub: String,
#[arg(long)]
code: String,
/// Label for this device, e.g. Hermes
#[arg(long)]
name: String,
#[arg(long)]
vaults_dir: Option<PathBuf>,
},
/// Make a one-time code to add another of your devices
Pair,
/// Vaults on the hub
Vault {
#[command(subcommand)]
action: VaultCmd,
},
/// Invite a person to the team: --vault DevOps:edit (read, edit or manage), repeatable
Invite {
person: String,
#[arg(long = "vault")]
vaults: Vec<String>,
},
/// Give someone on the team access to a vault, or change their role
Grant {
person: String,
vault: String,
#[arg(long, default_value = "edit")]
role: String,
},
/// Who has access to a vault, and their devices
Members { vault: String },
/// The hub's access log (team owner)
Hub {
#[command(subcommand)]
action: HubCmd,
},
/// Recent history entries and which device made them
History {
#[arg(long)]
@@ -72,6 +124,28 @@ enum Command {
},
}
#[derive(Subcommand)]
enum VaultCmd {
/// Create an empty vault on the hub
New { name: String },
/// Move a vault from its plain Git remote onto the hub
Upload {
name: String,
/// Upload only the current notes, not the earlier history
#[arg(long)]
fresh: bool,
},
}
#[derive(Subcommand)]
enum HubCmd {
/// Recent access changes
Log {
#[arg(short = 'n', default_value_t = 30)]
count: usize,
},
}
#[derive(Subcommand)]
enum DeviceCmd {
/// Set the label shown on everything this device shares
@@ -136,6 +210,7 @@ fn main() {
fn run_cli(cli: Cli) -> Result<()> {
let mut config = Config::load()?;
config.use_hub_credentials();
let cwd = std::env::current_dir()?;
match cli.command {
Command::Device { action: None } => println!("This device is \"{}\".", config.device_label()),
@@ -144,12 +219,24 @@ fn run_cli(cli: Cli) -> Result<()> {
if label.is_empty() {
bail!("the label can't be empty");
}
if let Some(h) = &config.hub {
h.set_label(&label)?;
}
config.device_name = Some(label.clone());
config.save()?;
println!("This device is now \"{label}\". Everything it shares will carry that name.");
}
Command::Add { name, folder, remote } => add(&mut config, &name, &folder, &remote)?,
Command::Run => run(&config)?,
Command::Run => run()?,
Command::Join { link, name, vaults_dir } => team::join(&mut config, &link, &name, vaults_dir)?,
Command::Login { hub, code, name, vaults_dir } => team::login(&mut config, &hub, &code, &name, vaults_dir)?,
Command::Pair => team::pair(&config)?,
Command::Vault { action: VaultCmd::New { name } } => team::vault_new(&mut config, &name)?,
Command::Vault { action: VaultCmd::Upload { name, fresh } } => team::vault_upload(&mut config, &name, fresh)?,
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::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()?,
Command::Status { vault } => {
@@ -161,6 +248,12 @@ fn run_cli(cli: Cli) -> Result<()> {
println!("No vaults yet. Add one with `lunesync add <name> <folder> --remote <url>`.");
}
println!("Device: {}", config.device_label());
if let Some(h) = &config.hub {
match h.me() {
Ok(me) => println!("Hub: {} as {}{}", h.url, me.person, if me.owner { " (team owner)" } else { "" }),
Err(e) => println!("Hub: {} — can't reach it right now ({e})", h.url),
}
}
for v in vaults {
print_status(v, &config.device_label());
}
@@ -315,6 +408,9 @@ fn held(config: &Config, cwd: &Path, vault: Option<&str>, cmd: HeldCmd) -> Resul
let _op = state::op_lock(&v.git_dir)?;
for h in held_hits(&v, &rel, line)? {
secrets::allow(&v.git_dir, &h, &rel)?;
if let (Some(hub), Some(id)) = (&config.hub, cfg.hub_vault) {
hub.not_a_secret(id, &h.line_hash)?;
}
println!("OK — line {} of {rel} won't be held again on this device.", h.line);
}
save_and_share(&v)?;
@@ -369,34 +465,60 @@ fn add(config: &mut Config, name: &str, folder: &Path, remote: &str) -> Result<(
Ok(())
}
fn run(config: &Config) -> Result<()> {
if config.vaults.is_empty() {
bail!("no vaults yet — add one with `lunesync add <name> <folder> --remote <url>`");
}
let label = config.device_label();
let poll = config.poll_interval();
let log = |vault: &str, msg: &str| println!("{} {vault:<10} {msg}", Local::now().format("%H:%M:%S"));
std::thread::scope(|s| {
fn log_line(vault: &str, msg: &str) {
println!("{} {vault:<10} {msg}", Local::now().format("%H:%M:%S"));
}
/// Syncs every vault, picks up vaults added meanwhile, and checks the hub for new memberships.
fn run() -> Result<()> {
let mut started: HashSet<PathBuf> = HashSet::new();
let mut hub_check = Instant::now();
let mut hub_said = String::new();
loop {
let mut config = Config::load()?;
config.use_hub_credentials();
if config.vaults.is_empty() && config.hub.is_none() {
bail!("no vaults yet — add one with `lunesync add <name> <folder> --remote <url>` or join a hub");
}
if config.hub.is_some() && Instant::now() >= hub_check {
hub_check = Instant::now() + Duration::from_secs(30);
match team::arrive(&mut config) {
Ok(msgs) => {
hub_said.clear();
msgs.iter().for_each(|m| log_line("hub", m));
}
Err(e) => {
let msg = format!("can't check the hub: {e:#}");
if msg != hub_said {
log_line("hub", &msg);
hub_said = msg;
}
}
}
}
for cfg in &config.vaults {
let label = &label;
s.spawn(move || {
if !started.insert(cfg.path.clone()) {
continue;
}
let (cfg, label, poll) = (cfg.clone(), config.device_label(), config.poll_interval());
std::thread::spawn(move || {
loop {
match runner::run(cfg, label, poll, Timing::default(), &log) {
match runner::run(&cfg, &label, poll, Timing::default(), &log_line) {
Ok(()) => return,
Err(e) if format!("{e}").contains("already being synced") => {
log(&cfg.name, &format!("{e:#}"));
log_line(&cfg.name, &format!("{e:#}"));
return;
}
Err(e) => {
log(&cfg.name, &format!("stopped: {e:#} — retrying in 30 s"));
std::thread::sleep(std::time::Duration::from_secs(30));
log_line(&cfg.name, &format!("stopped: {e:#} — retrying in 30 s"));
std::thread::sleep(Duration::from_secs(30));
}
}
}
});
}
});
Ok(())
std::thread::sleep(Duration::from_secs(2));
}
}
/// After a one-off command, try to share right away; the runner picks it up otherwise.
@@ -411,7 +533,10 @@ fn share_now(v: &Vault) {
st.last_error = None;
let _ = st.save(&v.git_dir);
}
Err(e) => println!("Not shared yet ({}); it will go out when the remote is reachable.", remote::describe_error(&e)),
Err(e) if remote::is_offline(&e) => {
println!("Not shared yet ({}); it will go out when the remote is reachable.", remote::describe_error(&e))
}
Err(e) => println!("Not shared: {}", remote::describe_error(&e)),
}
}
@@ -425,9 +550,12 @@ fn print_status(cfg: &VaultConfig, label: &str) {
}
};
let st = SyncState::load(&v.git_dir);
let read_only = v.role().is_some_and(|r| !lune_core::hub::can_edit(&r));
let waiting = v.waiting_files().unwrap_or(0);
let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" });
let headline = match &st.last_error {
None if read_only && waiting > 0 => format!("Up to date · {changes} kept here, not shared (you have read access)"),
None if read_only => "Up to date (read access)".to_string(),
Some(e) if e.starts_with("offline") => format!("Offline · waiting to sync · {changes}"),
Some(e) => format!("Can't sync: {e}{}", if waiting > 0 { format!(" · {changes} waiting") } else { String::new() }),
None if waiting > 0 => format!("Waiting to sync · {changes}"),

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(())
}