Milestone 7: the app normal people install (macOS)

A Tauri menu-bar app runs the same sync engine as `lunesync run`. It
connects from the website with no code typed (lune://join and
lune://pair links), shows status in the menu bar, and lets a person
resolve held secrets, held big changes and kept-both notes side by
side. Uninstall shares and hands over first, then removes only what
Lune created.

Releases are signed on the hub that holds the key (`lunehub release
keygen/publish`); other hubs `release import` them. Apps verify the
signature and the signed version. Clients older than the previous
release are asked to update and keep saving locally.

A device can now be on several hubs at once (own and workplace), each
with its own key; the CLI takes --team when it matters. The supervisor
and status summary moved into core, shared by the CLI and the app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 11:47:35 +07:00
parent 8be559817c
commit 6cb85004fb
59 changed files with 6871 additions and 210 deletions

View File

@@ -1,6 +1,6 @@
[package]
name = "lunehub"
version = "0.1.0"
version.workspace = true
edition = "2024"
[dependencies]
@@ -10,6 +10,7 @@ base64 = "0.23.1"
chrono = "0.4.45"
getrandom = "0.4.3"
lune-core = { version = "0.1.0", path = "../core" }
minisign = "0.10.0"
rusqlite = { version = "0.41.0", features = ["bundled"] }
rust-embed = { version = "8.13.0", features = ["mime-guess"] }
serde = { version = "1.0.229", features = ["derive"] }

View File

@@ -96,6 +96,7 @@ pub fn authenticate(hub: &Hub, headers: &HeaderMap) -> Result<Caller, ApiError>
if !caller.active {
return Err(denied("this device was removed from the hub"));
}
crate::release::check_client(&hub.data, headers)?;
Ok(caller)
}
@@ -220,6 +221,9 @@ pub async fn pair(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
pub async fn me(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
let caller = authenticate_any(&hub, &headers)?;
if caller.active {
crate::release::check_client(&hub.data, &headers)?;
}
let conn = hub.db.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT d.id, d.vault_id, v.name, d.delete_files, d.without_saving FROM departures d JOIN vaults v ON v.id = d.vault_id

View File

@@ -76,6 +76,10 @@ async fn handle(
let (caller, role, handover, vault_name) = {
let conn = hub.db.lock().unwrap();
let Some(caller) = db::caller(&conn, &id, &key)? else { return Ok(ask_for_key()) };
if caller.active {
// A device that's leaving may still hand over, whatever its version.
crate::release::check_client(&hub.data, &headers)?;
}
let role = if caller.active { db::role(&conn, caller.account_id, vault_id)? } else { None };
// A device whose access ended may still send its handover, and nothing else (A6).
let handover: Option<i64> = conn

View File

@@ -6,6 +6,7 @@ mod git;
mod health;
mod hook;
mod leave;
mod release;
mod web;
use anyhow::Result;
@@ -36,17 +37,31 @@ fn main() -> Result<()> {
s.read_to_string(&mut answer)?;
std::process::exit(if answer.ends_with("ok") { 0 } else { 1 });
}
["release", "keygen"] => release::keygen(&data_dir()),
["release", "list"] => {
release::list(&data_dir());
Ok(())
}
["release", "import", folder] => release::import(&data_dir(), folder.as_ref()),
["release", "publish", version, update, dmg, notes @ ..] => {
release::publish(&data_dir(), version, update.as_ref(), dmg.as_ref(), &notes.join(" "))
}
[] | ["serve"] => serve(),
_ => {
eprintln!("usage: lunehub [serve] | lunehub health | lunehub hook pre-receive");
eprintln!(" lunehub release keygen | list | publish <version> <Lune.app.tar.gz> <Lune.dmg> [notes] | import <folder>");
std::process::exit(2);
}
}
}
fn data_dir() -> PathBuf {
PathBuf::from(env("LUNE_HUB_DATA", "/data"))
}
#[tokio::main]
async fn serve() -> Result<()> {
let data = PathBuf::from(env("LUNE_HUB_DATA", "/data"));
let data = data_dir();
let url = env("LUNE_HUB_URL", "http://localhost:8080").trim_end_matches('/').to_string();
let listen = env("LUNE_HUB_LISTEN", "0.0.0.0:8080");
std::fs::create_dir_all(data.join("repos"))?;
@@ -109,6 +124,10 @@ async fn serve() -> Result<()> {
.route("/api/tidy/resolve", post(health::resolve))
.route("/api/invites/grant", post(web::invite_grant))
.route("/api/devices/rename", post(web::rename_device))
.route("/api/update/{target}/{arch}/{current}", get(release::check))
.route("/api/release", get(release::latest))
.route("/download/mac", get(release::download_mac))
.route("/releases/{version}/{file}", get(release::file))
.route("/signin/{token}", get(web::signin_link))
.route("/git/{repo}/{*rest}", any(git::serve))
.route("/health", get(|| async { "ok" }))

259
hub/src/release.rs Normal file
View File

@@ -0,0 +1,259 @@
//! Desktop releases (M7, D3): the update-signing key lives here on the hub's server, `lunehub release publish`
//! signs a build, and the hub offers the newest version for download and update. Clients older than the
//! version before it are asked to update.
use crate::api::{ApiError, Shared};
use anyhow::{Context, Result, bail};
use axum::Json;
use axum::extract::{Path, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Redirect, Response};
use base64::Engine;
use minisign::{KeyPair, PublicKeyBox, SecretKey, SecretKeyBox};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::path::{Path as FsPath, PathBuf};
/// What a published version holds; written next to its files as `release.json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Release {
pub version: String,
pub notes: String,
pub pub_date: String,
/// The installer people download.
pub dmg: String,
/// The app bundle the updater installs, and its signature (base64 minisign, as Tauri expects).
pub update: String,
pub signature: String,
}
pub fn parse_version(v: &str) -> Option<(u64, u64, u64)> {
let mut parts = v.trim().trim_start_matches('v').split('.').map(|p| p.parse::<u64>().ok());
let version = (parts.next()??, parts.next()??, parts.next()??);
parts.next().is_none().then_some(version)
}
fn key_dir(data: &FsPath) -> PathBuf {
data.join("release")
}
fn releases_dir(data: &FsPath) -> PathBuf {
data.join("releases")
}
/// Published releases, newest first.
pub fn published(data: &FsPath) -> Vec<Release> {
let Ok(dirs) = std::fs::read_dir(releases_dir(data)) else { return vec![] };
let mut out: Vec<Release> = dirs
.flatten()
.filter_map(|d| std::fs::read_to_string(d.path().join("release.json")).ok())
.filter_map(|s| serde_json::from_str::<Release>(&s).ok())
.filter(|r| parse_version(&r.version).is_some())
.collect();
out.sort_by_key(|r| std::cmp::Reverse(parse_version(&r.version)));
out
}
/// The oldest client version still served: the one before the newest release (D3). None until there are two.
pub fn oldest_supported(data: &FsPath) -> Option<(u64, u64, u64)> {
published(data).get(1).and_then(|r| parse_version(&r.version))
}
/// The client version a request carries in its User-Agent (`lune/<version>`), if it says one.
pub fn client_version(headers: &HeaderMap) -> Option<(u64, u64, u64)> {
let ua = headers.get(header::USER_AGENT)?.to_str().ok()?;
let rest = &ua[ua.find("lune/")? + 5..];
parse_version(rest.split(|c: char| c.is_whitespace() || c == ')' || c == ';').next()?)
}
/// Refuses clients older than the hub supports. Clients that don't say a version are let through.
pub fn check_client(data: &FsPath, headers: &HeaderMap) -> Result<(), ApiError> {
match (client_version(headers), oldest_supported(data)) {
(Some(v), Some(oldest)) if v < oldest => {
Err(ApiError(StatusCode::UPGRADE_REQUIRED, lune_core::remote::TOO_OLD.into()))
}
_ => Ok(()),
}
}
fn password() -> Option<String> {
// Unset: minisign asks on the terminal.
std::env::var("LUNE_RELEASE_PASSWORD").ok()
}
/// What Tauri's updater config wants as `pubkey`: the minisign public key file, base64-encoded.
fn tauri_pubkey(pk_box: &str) -> String {
base64::engine::general_purpose::STANDARD.encode(pk_box)
}
pub fn keygen(data: &FsPath) -> Result<()> {
let dir = key_dir(data);
let sk_path = dir.join("update.key");
if sk_path.exists() {
bail!("an update-signing key already exists at {} — keep using it (apps only trust that key)", sk_path.display());
}
std::fs::create_dir_all(&dir)?;
let KeyPair { pk, sk } = KeyPair::generate_encrypted_keypair(password()).context("couldn't create the key")?;
let sk_box = sk.to_box(Some("Lune update-signing key"))?.into_string();
let pk_box = pk.to_box()?.into_string();
write_private(&sk_path, &sk_box)?;
std::fs::write(dir.join("update.pub"), &pk_box)?;
println!("Created the update-signing key at {} (password-protected; back it up with the hub's data).", sk_path.display());
println!("Put this public key in desktop/tauri.conf.json → plugins.updater.pubkey, then build the app:");
println!("{}", tauri_pubkey(&pk_box));
Ok(())
}
fn write_private(path: &FsPath, text: &str) -> Result<()> {
use std::io::Write;
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
opts.open(path)?.write_all(text.as_bytes())?;
Ok(())
}
/// `lunehub release publish <version> <Lune.app.tar.gz> <Lune.dmg> [notes]`: signs the update here and makes it
/// the version the hub offers.
pub fn publish(data: &FsPath, version: &str, update: &FsPath, dmg: &FsPath, notes: &str) -> Result<()> {
let v = parse_version(version).context("the version should look like 1.2.3")?;
if let Some(newest) = published(data).first()
&& parse_version(&newest.version).is_some_and(|n| n >= v)
{
bail!("{} is already published; a new release needs a higher version", newest.version);
}
let dir = key_dir(data);
let sk_box = std::fs::read_to_string(dir.join("update.key"))
.context("no update-signing key yet — run `lunehub release keygen` first")?;
let pk_box = std::fs::read_to_string(dir.join("update.pub"))?;
let sk = SecretKey::from_box(SecretKeyBox::from_string(&sk_box)?, password()).context("couldn't unlock the key")?;
let pk = PublicKeyBox::from_string(&pk_box)?.into_public_key()?;
let version = format!("{}.{}.{}", v.0, v.1, v.2);
let out = releases_dir(data).join(&version);
std::fs::create_dir_all(&out)?;
let update_name = format!("Lune_{version}_aarch64.app.tar.gz");
let dmg_name = format!("Lune_{version}_aarch64.dmg");
std::fs::copy(update, out.join(&update_name)).with_context(|| format!("can't read {}", update.display()))?;
std::fs::copy(dmg, out.join(&dmg_name)).with_context(|| format!("can't read {}", dmg.display()))?;
// The trusted comment is signed too; the app checks the version in it against the one offered.
let now = chrono::Utc::now();
let trusted = format!("timestamp:{}\tfile:{update_name}\tversion:{version}", now.timestamp());
let file = std::fs::File::open(out.join(&update_name))?;
let sig = minisign::sign(Some(&pk), &sk, file, Some(&trusted), Some("signature from the Lune hub"))?;
let release = Release {
version: version.clone(),
notes: notes.to_string(),
pub_date: now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
dmg: dmg_name,
update: update_name,
signature: base64::engine::general_purpose::STANDARD.encode(sig.into_string()),
};
std::fs::write(out.join("release.json"), serde_json::to_string_pretty(&release)?)?;
println!("Published Lune {version}. Apps pick it up within a few hours, or at their next start.");
Ok(())
}
/// `lunehub release import <folder>`: offers a release signed on another hub (one key signs for every hub).
/// The folder is what `publish` made there: `releases/<version>/` with release.json and both files.
pub fn import(data: &FsPath, from: &FsPath) -> Result<()> {
let r: Release = serde_json::from_str(&std::fs::read_to_string(from.join("release.json")).context("that folder has no release.json")?)
.context("that release.json doesn't make sense")?;
let v = parse_version(&r.version).context("that release has no proper version")?;
if let Some(newest) = published(data).first()
&& parse_version(&newest.version).is_some_and(|n| n >= v)
{
bail!("{} is already offered here; only newer releases can be added", newest.version);
}
// If this hub knows the public key, check the signature now rather than letting every app refuse it later.
if let Ok(pk_box) = std::fs::read_to_string(key_dir(data).join("update.pub")) {
let pk = PublicKeyBox::from_string(&pk_box)?.into_public_key()?;
let sig_box = String::from_utf8(base64::engine::general_purpose::STANDARD.decode(&r.signature)?)?;
let sig = minisign::SignatureBox::from_string(&sig_box)?;
let file = std::fs::File::open(from.join(&r.update))?;
minisign::verify(&pk, &sig, file, true, false, false).context("the signature doesn't match this hub's key")?;
}
let out = releases_dir(data).join(&r.version);
std::fs::create_dir_all(&out)?;
for name in [&r.dmg, &r.update] {
std::fs::copy(from.join(name), out.join(name)).with_context(|| format!("can't read {name}"))?;
}
std::fs::write(out.join("release.json"), serde_json::to_string_pretty(&r)?)?;
println!("Now offering Lune {} (signed elsewhere).", r.version);
Ok(())
}
pub fn list(data: &FsPath) {
let all = published(data);
if all.is_empty() {
println!("Nothing published yet.");
}
for (i, r) in all.iter().enumerate() {
let note = match i {
0 => " (offered)",
1 => " (oldest still syncing)",
_ => "",
};
println!("{} {}{note}", r.version, r.pub_date);
}
}
/// Tauri's updater asks here: `/api/update/{target}/{arch}/{current_version}`. 204 means up to date.
pub async fn check(State(hub): State<Shared>, Path((target, arch, current)): Path<(String, String, String)>) -> Response {
let Some(newest) = published(&hub.data).into_iter().next() else { return StatusCode::NO_CONTENT.into_response() };
let newer = match (parse_version(&newest.version), parse_version(&current)) {
(Some(n), Some(c)) => n > c,
_ => false,
};
if target != "darwin" || arch != "aarch64" || !newer {
return StatusCode::NO_CONTENT.into_response();
}
Json(json!({
"version": newest.version,
"notes": newest.notes,
"pub_date": newest.pub_date,
"url": format!("{}/releases/{}/{}", hub.url, newest.version, newest.update),
"signature": newest.signature,
}))
.into_response()
}
/// What the download page offers.
pub async fn latest(State(hub): State<Shared>) -> Json<serde_json::Value> {
match published(&hub.data).into_iter().next() {
Some(r) => Json(json!({ "version": r.version, "mac": "/download/mac" })),
None => Json(json!({ "version": null, "mac": null })),
}
}
pub async fn download_mac(State(hub): State<Shared>) -> Response {
match published(&hub.data).into_iter().next() {
Some(r) => Redirect::to(&format!("/releases/{}/{}", r.version, r.dmg)).into_response(),
None => (StatusCode::NOT_FOUND, "no Mac app published yet").into_response(),
}
}
pub async fn file(State(hub): State<Shared>, Path((version, name)): Path<(String, String)>) -> Response {
let not_found = || (StatusCode::NOT_FOUND, "no such file").into_response();
let Some(r) = published(&hub.data).into_iter().find(|r| r.version == version) else { return not_found() };
if name != r.dmg && name != r.update {
return not_found();
}
let kind = if name.ends_with(".dmg") { "application/x-apple-diskimage" } else { "application/gzip" };
match tokio::fs::read(releases_dir(&hub.data).join(&r.version).join(&name)).await {
Ok(bytes) => (
[
(header::CONTENT_TYPE, kind.to_string()),
(header::CONTENT_DISPOSITION, format!("attachment; filename=\"{name}\"")),
],
bytes,
)
.into_response(),
Err(_) => not_found(),
}
}

View File

@@ -120,7 +120,7 @@ fn device(url: &str, w: &hub::Welcome, label: &str, dir: &std::path::Path) -> Co
Config {
device_name: Some(label.into()),
vaults_dir: Some(dir.to_path_buf()),
hub: Some(HubLink { url: url.into(), device_id: w.device_id.clone(), key: w.key.clone() }),
hubs: vec![HubLink { url: url.into(), device_id: w.device_id.clone(), key: w.key.clone() }],
..Default::default()
}
}
@@ -151,7 +151,7 @@ fn taking_access_back() {
let (_hub, url, owner_link) = start_hub(&tmp.path().join("data"));
let (_, sen_w) = hub::join(&owner_link, "Codex").unwrap();
let mut sen = device(&url, &sen_w, "Codex", &tmp.path().join("sen"));
let sen_hub = sen.hub.clone().unwrap();
let sen_hub = sen.hubs[0].clone();
sen.use_hub_credentials();
sen_hub.create_vault("DevOps").unwrap();
sen_hub.create_vault("Notes").unwrap();
@@ -206,7 +206,7 @@ fn taking_access_back() {
assert!(!tmp.path().join("bob/DevOps").exists() && !tmp.path().join("bob/Notes").exists());
let said = check_in(&mut bob);
assert!(said[0].contains("removed from the hub"), "{said:?}");
assert!(bob.hub.is_none());
assert!(bob.hubs.is_empty());
sen.use_hub_credentials();
let bob_handover = sen_hub.handovers().unwrap().into_iter().find(|h| h.person == "Bob" && h.state == "received").unwrap();
sen_hub.handover_decide(bob_handover.id, "discard").unwrap();
@@ -389,3 +389,160 @@ fn health_nudge_and_tidy() {
assert!(!a.root.join(&copy).exists());
assert!(get("/api/canvas")["vaults"][0]["tidy"].as_array().unwrap().is_empty());
}
fn lunehub(data: &std::path::Path, args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_lunehub"))
.args(args)
.env("LUNE_HUB_DATA", data)
.env("LUNE_RELEASE_PASSWORD", "test only")
.output()
.unwrap()
}
#[test]
fn releases_are_signed_on_the_hub_and_old_clients_are_asked_to_update() {
use base64::Engine;
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::TempDir::new().unwrap();
let data = tmp.path().join("data");
let (_hub, url, owner_link) = start_hub(&data);
// The key is made on the hub; only the public half leaves it.
let made = lunehub(&data, &["release", "keygen"]);
assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
let pubkey = String::from_utf8(made.stdout).unwrap().lines().last().unwrap().trim().to_string();
assert!(!lunehub(&data, &["release", "keygen"]).status.success(), "a second key would orphan every app");
let update = tmp.path().join("Lune.app.tar.gz");
let dmg = tmp.path().join("Lune.dmg");
for v in ["0.1.0", "0.2.0", "0.3.0"] {
std::fs::write(&update, format!("app {v}")).unwrap();
std::fs::write(&dmg, format!("dmg {v}")).unwrap();
let out = lunehub(&data, &["release", "publish", v, update.to_str().unwrap(), dmg.to_str().unwrap(), "Notes"]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
let again = lunehub(&data, &["release", "publish", "0.2.5", update.to_str().unwrap(), dmg.to_str().unwrap()]);
assert!(!again.status.success(), "versions only go up");
// The updater's question: 0.2.0 gets 0.3.0, signed with the hub's key, version bound in the signature.
let agent = ureq::Agent::config_builder().http_status_as_error(false).build().new_agent();
let mut res = agent.get(format!("{url}/api/update/darwin/aarch64/0.2.0")).call().unwrap();
assert_eq!(res.status(), 200);
let offer: serde_json::Value = res.body_mut().read_json().unwrap();
assert_eq!(offer["version"], "0.3.0");
let bytes = agent.get(offer["url"].as_str().unwrap()).call().unwrap().body_mut().read_to_vec().unwrap();
assert_eq!(bytes, b"app 0.3.0");
let b64 = |s: &str| String::from_utf8(base64::engine::general_purpose::STANDARD.decode(s).unwrap()).unwrap();
let pk = minisign::PublicKeyBox::from_string(&b64(&pubkey)).unwrap().into_public_key().unwrap();
let sig = minisign::SignatureBox::from_string(&b64(offer["signature"].as_str().unwrap())).unwrap();
assert!(sig.trusted_comment().unwrap().contains("\tversion:0.3.0"));
minisign::verify(&pk, &sig, std::io::Cursor::new(&bytes), true, false, false).unwrap();
assert_eq!(agent.get(format!("{url}/api/update/darwin/aarch64/0.3.0")).call().unwrap().status(), 204);
let mut dl = agent.get(format!("{url}/download/mac")).call().unwrap();
assert_eq!(dl.body_mut().read_to_vec().unwrap(), b"dmg 0.3.0");
// A second hub (a workplace) offers the same signed release without ever holding the key.
let work = tmp.path().join("work");
std::fs::create_dir_all(&work).unwrap();
let imported = lunehub(&work, &["release", "import", data.join("releases/0.3.0").to_str().unwrap()]);
assert!(imported.status.success(), "{}", String::from_utf8_lossy(&imported.stderr));
assert!(!work.join("release/update.key").exists());
assert_eq!(std::fs::read(work.join("releases/0.3.0/release.json")).unwrap(), std::fs::read(data.join("releases/0.3.0/release.json")).unwrap());
// 0.1.0 is two releases behind: it keeps its place on the team but can't sync until it updates.
remote::set_client_version("0.3.0");
let (_, sen) = hub::join(&owner_link, "Codex").unwrap();
let codex = as_device(&url, &sen);
let devops = codex.create_vault("DevOps").unwrap();
let (cfg, _, _) = vault::add("DevOps", &tmp.path().join("codex"), &devops.git_url, "Codex").unwrap();
let v = Vault::open(&cfg, "Codex").unwrap();
remote::set_client_version("0.1.0");
assert!(format!("{:#}", codex.me().unwrap_err()).contains(remote::TOO_OLD));
std::fs::write(v.root.join("note.md"), "kept while outdated\n").unwrap();
assert!(v.save_changes(None, &HashSet::new()).unwrap().is_some(), "saving locally goes on");
assert_eq!(remote::describe_error(&v.sync().unwrap_err()), remote::TOO_OLD);
// One release behind still syncs.
remote::set_client_version("0.2.0");
assert_eq!(codex.me().unwrap().vaults.len(), 1);
v.sync().unwrap();
assert_eq!(v.waiting_files().unwrap(), 0);
remote::set_client_version(env!("CARGO_PKG_VERSION"));
}
#[test]
fn one_device_on_two_hubs_keeps_the_teams_apart() {
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::TempDir::new().unwrap();
let (_own, own_url, own_link) = start_hub(&tmp.path().join("own"));
let (_work, work_url, work_link) = start_hub(&tmp.path().join("work"));
// Sen's own hub, with a Notes vault and a second device to read it from.
let (_, sen_w) = hub::join(&own_link, "Mac").unwrap();
let mut mac = device(&own_url, &sen_w, "Mac", &tmp.path().join("mac"));
mac.use_hub_credentials();
mac.hubs[0].create_vault("Notes").unwrap();
let code = mac.hubs[0].pair().unwrap();
let hermes_w = hub::login(&own_url, &code, "Hermes").unwrap();
let mut hermes = device(&own_url, &hermes_w, "Hermes", &tmp.path().join("hermes"));
// The workplace hub (its owner is also called Sen by the test hub) has a Notes too; it invites Mov Sen.
let (_, boss_w) = hub::join(&work_link, "Boss pc").unwrap();
let mut boss = device(&work_url, &boss_w, "Boss pc", &tmp.path().join("boss"));
boss.use_hub_credentials();
boss.hubs[0].create_vault("Notes").unwrap();
let invite = boss.hubs[0].invite("Mov Sen", &[("Notes".into(), "edit".into())]).unwrap();
let (url, w) = hub::join(&invite, "Mac").unwrap();
mac.hubs.push(HubLink { url, device_id: w.device_id, key: w.key });
// Both arrive, in separate folders, each tied to its own hub.
let said = check_in(&mut mac);
assert_eq!(mac.vaults.len(), 2, "{said:?}");
let own_notes = mac.vaults.iter().find(|v| v.hub_url.as_deref() == Some(own_url.as_str())).unwrap().clone();
let work_notes = mac.vaults.iter().find(|v| v.hub_url.as_deref() == Some(work_url.as_str())).unwrap().clone();
assert_ne!(own_notes.path, work_notes.path);
mac.use_hub_credentials();
let label = mac.device_label();
let (a, b) = (Vault::open(&own_notes, &label).unwrap(), Vault::open(&work_notes, &label).unwrap());
write_and_save(&a, "home.md", "mine\n");
write_and_save(&b, "work.md", "the company's\n");
a.sync().unwrap();
b.sync().unwrap();
check_in(&mut hermes);
let h = open(&hermes, "Notes");
h.sync().unwrap();
assert!(h.root.join("home.md").exists() && !h.root.join("work.md").exists());
check_in(&mut boss);
let bn = open(&boss, "Notes");
bn.sync().unwrap();
assert!(bn.root.join("work.md").exists() && !bn.root.join("home.md").exists());
// The workplace takes Sen's access back: only that folder leaves.
boss.use_hub_credentials();
boss.hubs[0].remove("Mov Sen", "Notes", false).unwrap();
check_in(&mut mac);
assert!(!work_notes.path.exists());
assert_eq!(std::fs::read(own_notes.path.join("home.md")).unwrap(), b"mine\n");
assert_eq!(mac.vaults.len(), 1);
let a = open(&mac, "Notes");
write_and_save(&a, "home.md", "still mine\n");
a.sync().unwrap();
}
#[test]
fn a_single_hub_config_from_before_moves_into_the_list() {
let tmp = tempfile::TempDir::new().unwrap();
std::fs::write(
tmp.path().join("config.toml"),
"device_name = \"Mac\"\n\n[hub]\nurl = \"https://hub.example\"\ndevice_id = \"dev_1\"\nkey = \"k\"\n\n\
[[vault]]\nname = \"Notes\"\npath = \"/tmp/notes\"\nremote = \"https://hub.example/git/1.git\"\nbranch = \"main\"\nhub_vault = 1\n",
)
.unwrap();
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
unsafe { std::env::set_var("LUNE_HOME", tmp.path()) };
let c = Config::load().unwrap();
unsafe { std::env::remove_var("LUNE_HOME") };
assert_eq!(c.hubs.len(), 1);
assert_eq!(c.vaults[0].hub_url.as_deref(), Some("https://hub.example"));
assert_eq!(c.hub_of(&c.vaults[0]).unwrap().device_id, "dev_1");
}