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

@@ -12,6 +12,12 @@ pub struct Config {
/// How often to check the remote for new changes, in seconds.
#[serde(default)]
pub poll_seconds: Option<u64>,
/// Where vaults from the hub are placed (default ~/Vaults).
#[serde(default)]
pub vaults_dir: Option<PathBuf>,
/// This device's hub sign-in, once it has joined or logged in.
#[serde(default)]
pub hub: Option<crate::hub::HubLink>,
#[serde(default, rename = "vault")]
pub vaults: Vec<VaultConfig>,
}
@@ -22,6 +28,9 @@ pub struct VaultConfig {
pub path: PathBuf,
pub remote: String,
pub branch: String,
/// The hub's id for this vault, when it syncs through the hub.
#[serde(default)]
pub hub_vault: Option<i64>,
}
/// Directory holding `config.toml`. `LUNE_HOME` overrides it (handy for running two devices on one machine).
@@ -52,10 +61,29 @@ impl Config {
std::fs::create_dir_all(path.parent().unwrap())?;
let tmp = path.with_extension("toml.tmp");
std::fs::write(&tmp, toml::to_string_pretty(self)?)?;
// Holds the device key: owner-only.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))?;
}
std::fs::rename(&tmp, &path)?;
Ok(())
}
pub fn vaults_dir(&self) -> PathBuf {
self.vaults_dir
.clone()
.unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join("Vaults"))
}
/// Makes the hub's device key available to Git requests in this process.
pub fn use_hub_credentials(&self) {
if let Some(h) = &self.hub {
crate::remote::set_hub(h.clone());
}
}
pub fn device_label(&self) -> String {
self.device_name.clone().unwrap_or_else(default_device_name)
}

159
core/src/hub.rs Normal file
View File

@@ -0,0 +1,159 @@
//! Talking to the hub's API: joining, pairing, and finding out which vaults this device should have.
use anyhow::{Context, Result, bail};
use base64::Engine;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::time::Duration;
/// This device's link to a hub, stored in the config file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HubLink {
pub url: String,
pub device_id: String,
pub key: String,
}
/// What `join` and `login` hand back.
#[derive(Debug, Deserialize)]
pub struct Welcome {
pub person: String,
pub device_id: String,
pub key: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Me {
pub person: String,
pub owner: bool,
pub device_label: String,
pub vaults: Vec<HubVault>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct HubVault {
pub id: i64,
pub name: String,
pub role: String,
pub git_url: String,
}
#[derive(Debug, Deserialize)]
pub struct Member {
pub person: String,
pub role: String,
pub devices: Vec<String>,
}
#[derive(Debug, Deserialize)]
pub struct LogEntry {
pub at: i64,
pub actor: String,
pub action: String,
pub detail: String,
}
fn agent() -> ureq::Agent {
ureq::Agent::config_builder()
.http_status_as_error(false)
.timeout_global(Some(Duration::from_secs(30)))
.build()
.into()
}
fn base(url: &str) -> String {
url.trim_end_matches('/').to_string()
}
fn finish<T: DeserializeOwned>(res: Result<ureq::http::Response<ureq::Body>, ureq::Error>, url: &str) -> Result<T> {
let mut res = res.map_err(|e| anyhow::anyhow!("can't reach the hub at {url}: {e}"))?;
let status = res.status();
let body: Value = res.body_mut().read_json().unwrap_or(Value::Null);
if !status.is_success() {
let msg = body.get("error").and_then(Value::as_str).unwrap_or("unexpected answer");
bail!("the hub said: {msg}");
}
serde_json::from_value(body).context("the hub's answer didn't make sense")
}
/// Accepts an invite link (`https://hub/join/<token>`), creating the person's account and this device.
pub fn join(link: &str, label: &str) -> Result<(String, Welcome)> {
let (url, token) = link.rsplit_once("/join/").context("that doesn't look like an invite link")?;
let url = base(url);
let res = agent().post(format!("{url}/api/join")).send_json(json!({"token": token, "device_label": label}));
Ok((url.clone(), finish(res, &url)?))
}
/// Signs this device in with a pairing code from another of the person's devices.
pub fn login(url: &str, code: &str, label: &str) -> Result<Welcome> {
let url = base(url);
let res = agent().post(format!("{url}/api/login")).send_json(json!({"code": code, "device_label": label}));
finish(res, &url)
}
impl HubLink {
fn auth(&self) -> String {
let raw = format!("{}:{}", self.device_id, self.key);
format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(raw))
}
fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
let res = agent().get(format!("{}{path}", self.url)).header("Authorization", self.auth()).call();
finish(res, &self.url)
}
fn post<T: DeserializeOwned>(&self, path: &str, body: Value) -> Result<T> {
let res = agent().post(format!("{}{path}", self.url)).header("Authorization", self.auth()).send_json(body);
finish(res, &self.url)
}
pub fn me(&self) -> Result<Me> {
self.get("/api/me")
}
/// A short code another of this person's devices can log in with.
pub fn pair(&self) -> Result<String> {
let v: Value = self.post("/api/pair", json!({}))?;
Ok(v["code"].as_str().unwrap_or_default().to_string())
}
pub fn set_label(&self, label: &str) -> Result<()> {
let _: Value = self.post("/api/device/label", json!({ "label": label }))?;
Ok(())
}
pub fn create_vault(&self, name: &str) -> Result<HubVault> {
self.post("/api/vaults", json!({ "name": name }))
}
/// One-time link for `person` with the given (vault, role) grants.
pub fn invite(&self, person: &str, grants: &[(String, String)]) -> Result<String> {
let grants: Vec<Value> = grants.iter().map(|(v, r)| json!({"vault": v, "role": r})).collect();
let v: Value = self.post("/api/invites", json!({"person": person, "grants": grants}))?;
Ok(v["link"].as_str().unwrap_or_default().to_string())
}
pub fn grant(&self, person: &str, vault: &str, role: &str) -> Result<()> {
let _: Value = self.post("/api/grants", json!({"person": person, "vault": vault, "role": role}))?;
Ok(())
}
pub fn members(&self, vault: &str) -> Result<Vec<Member>> {
self.post("/api/members", json!({ "vault": vault }))
}
pub fn log(&self, count: usize) -> Result<Vec<LogEntry>> {
self.get(&format!("/api/log?count={count}"))
}
pub fn not_a_secret(&self, vault_id: i64, fingerprint: &str) -> Result<()> {
let _: Value = self.post("/api/not-secrets", json!({"vault_id": vault_id, "fingerprint": fingerprint}))?;
Ok(())
}
}
/// Is `role` allowed to share changes?
pub fn can_edit(role: &str) -> bool {
role == "edit" || role == "manage"
}

View File

@@ -4,6 +4,7 @@ pub use git2;
pub mod config;
pub mod guard;
pub mod hub;
pub mod names;
pub mod remote;
pub mod runner;

View File

@@ -2,6 +2,20 @@
use git2::{Cred, CredentialType, ErrorClass, ErrorCode, RemoteCallbacks};
use std::path::PathBuf;
use std::sync::RwLock;
static HUB: RwLock<Option<crate::hub::HubLink>> = RwLock::new(None);
/// Git requests to this hub sign in with the device key.
pub fn set_hub(link: crate::hub::HubLink) {
*HUB.write().unwrap() = Some(link);
}
fn hub_credentials(url: &str) -> Option<(String, String)> {
let hub = HUB.read().unwrap();
let h = hub.as_ref()?;
url.starts_with(&h.url).then(|| (h.device_id.clone(), h.key.clone()))
}
pub fn callbacks<'a>() -> RemoteCallbacks<'a> {
let mut tried_agent = false;
@@ -26,6 +40,9 @@ pub fn callbacks<'a>() -> RemoteCallbacks<'a> {
}
if allowed.contains(CredentialType::USER_PASS_PLAINTEXT) && !tried_helper {
tried_helper = true;
if let Some((user, key)) = hub_credentials(url) {
return Cred::userpass_plaintext(&user, &key);
}
if let Ok(config) = git2::Config::open_default() {
return Cred::credential_helper(&config, url, username);
}

View File

@@ -92,6 +92,7 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
let mut backoff = poll;
let mut was_waiting = false;
let mut was_holding = false;
let mut was_read_only = false;
let mut announced: HashSet<String> = HashSet::new();
loop {
let first = rx.recv_timeout(Duration::from_millis(250));
@@ -168,6 +169,10 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
say("not sharing anything from this device while a big change is held");
}
was_holding = report.holding;
if report.read_only && !was_read_only {
say("your changes here aren't shared — you have read access to this vault");
}
was_read_only = report.read_only;
if report.waiting_for_local_edits && !was_waiting {
say("new changes are waiting until your current edits settle");
}

View File

@@ -37,6 +37,14 @@ pub fn read_marker(git_dir: &Path) -> Option<Marker> {
toml::from_str(&text).ok()
}
/// This device's role in a hub vault, refreshed from the hub by the runner.
pub fn write_role(git_dir: &Path, role: &str) -> Result<()> {
let dir = lune_dir(git_dir);
std::fs::create_dir_all(&dir)?;
std::fs::write(dir.join("role"), role)?;
Ok(())
}
/// Outcome of the last sync attempt, written by whoever ran it and read by `status`.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SyncState {

View File

@@ -37,6 +37,7 @@ pub struct Vault {
pub branch: String,
pub label: String,
repo: Repository,
last_refusal: RefCell<Option<String>>,
}
/// A burst of edits saved as one history entry.
@@ -75,6 +76,8 @@ pub struct SyncReport {
pub set_aside: Vec<(String, String)>,
/// A big change is held here, so nothing from this device was shared.
pub holding: bool,
/// Local changes not shared because this device's person only has read access.
pub read_only: bool,
}
impl Vault {
@@ -90,6 +93,7 @@ impl Vault {
branch: cfg.branch.clone(),
label: label.to_string(),
repo,
last_refusal: RefCell::new(None),
})
}
@@ -273,6 +277,48 @@ impl Vault {
Ok(kept_both)
}
/// Points the vault at a new remote (e.g. moving onto the hub). Its next sync shares everything there.
pub fn relink(&self, url: &str) -> Result<()> {
self.repo.remote_set_url("origin", url)?;
if let Ok(mut r) = self.repo.find_reference(&self.remote_ref()) {
r.delete()?;
}
Ok(())
}
/// Starts history over with just the current notes (the old history stays only on this device).
/// Returns where history was, to go back if needed.
pub fn fresh_start(&self, message: &str) -> Result<Oid> {
let head = self.head_commit()?.context("the vault is empty")?;
let sig = self.signature()?;
let id = self.repo.commit(None, &sig, &sig, message, &head.tree()?, &[])?;
self.repo.reference(&self.branch_ref(), id, true, "lune: fresh start")?;
Ok(head.id())
}
pub fn reset_history(&self, id: Oid) -> Result<()> {
self.repo.reference(&self.branch_ref(), id, true, "lune: put back")?;
Ok(())
}
/// After moving onto a remote whose history is unrelated (e.g. a fresh start on the hub), combine the
/// notes as one new entry on top of the remote's history, so this device's old history stays here.
pub fn join_unrelated(&self) -> Result<bool> {
self.fetch()?;
let (Some(local), Some(remote)) = (self.head_commit()?, self.remote_commit()?) else { return Ok(false) };
if self.repo.merge_base(local.id(), remote.id()).is_ok() {
return Ok(false);
}
let mut index = self.repo.merge_commits(&local, &remote, None)?;
let mut kept = vec![];
self.keep_both(&mut index, &mut kept)?;
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
let sig = self.signature()?;
let id = self.repo.commit(None, &sig, &sig, &format!("Joined the shared copy from {}", self.label), &tree, &[&remote])?;
self.move_to(id)?;
Ok(true)
}
/// A named checkpoint (S3). If everything is already saved, records the name on its own.
pub fn checkpoint(&self, message: &str) -> Result<Oid> {
if let Some(saved) = self.save_changes(Some(message), &HashSet::new())? {
@@ -293,10 +339,16 @@ impl Vault {
Ok(())
}
/// Pushes local history. Returns false if the remote moved on meanwhile (fetch and try again).
/// This device's role in the vault, as last told by the hub. None for plain Git remotes.
pub fn role(&self) -> Option<String> {
std::fs::read_to_string(state::lune_dir(&self.git_dir).join("role")).ok().map(|s| s.trim().to_string())
}
/// Pushes local history. Returns false if it was refused (the remote moved on, or said no).
fn push(&self) -> Result<bool> {
let mut remote = self.repo.find_remote("origin")?;
let rejected = RefCell::new(None::<String>);
let said = RefCell::new(String::new());
let mut cb = remote::callbacks();
cb.push_update_reference(|_, status| {
if let Some(s) = status {
@@ -304,6 +356,10 @@ impl Vault {
}
Ok(())
});
cb.sideband_progress(|text| {
said.borrow_mut().push_str(&String::from_utf8_lossy(text));
true
});
let mut opts = PushOptions::new();
opts.remote_callbacks(cb);
let spec = format!("{0}:{0}", self.branch_ref());
@@ -314,7 +370,9 @@ impl Vault {
return Err(e.into());
}
drop(opts);
if rejected.borrow().is_some() {
if let Some(status) = rejected.borrow().clone() {
let said: Vec<String> = said.borrow().lines().filter(|l| l.contains("lune:")).map(|l| l.replace("lune:", "").trim().to_string()).collect();
*self.last_refusal.borrow_mut() = Some(if said.is_empty() { status } else { said.join("; ") });
return Ok(false);
}
if let Some(head) = self.head_commit()? {
@@ -373,10 +431,21 @@ impl Vault {
report.holding = true;
return Ok(report);
}
if self.role().is_some_and(|r| !crate::hub::can_edit(&r)) {
report.read_only = true;
return Ok(report);
}
if self.push()? {
report.shared += ahead;
return Ok(report);
}
// Refused without the remote having moved on: the remote said no, so say why.
let before = self.remote_commit()?.map(|c| c.id());
self.fetch()?;
if self.remote_commit()?.map(|c| c.id()) == before {
let why = self.last_refusal.borrow().clone().unwrap_or_else(|| "no reason given".into());
bail!("the hub refused these changes: {why}");
}
}
bail!("the remote kept changing while sharing; will try again shortly")
}
@@ -672,7 +741,7 @@ pub fn add(name: &str, path: &Path, remote_url: &str, label: &str) -> Result<(Va
state::write_marker(&git_dir, name, !existed)?;
drop(repo);
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch };
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch, hub_vault: None };
let vault = Vault::open(&cfg, label)?;
let _op = state::op_lock(&git_dir)?;
vault.save_changes(Some(&format!("Added the vault on {label}")), &HashSet::new())?;