From 0148f98cfe195b4d275ca10e48ef9cd57ae7430a Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Tue, 17 Nov 2026 12:49:40 +0700 Subject: [PATCH] Hub: LUNE_VAULT_CREATION=anyone lets every member create vaults By default only the team owner and people who manage a vault can create vaults, as before. A hub run with LUNE_VAULT_CREATION=anyone lets any active member create one (and upload one); the creator is Manage on that vault only. Sharing is unchanged: inviting or granting still needs Manage on the vault being shared, so nobody can connect others to a vault they do not manage. An unknown value stops the hub at startup, before any data is touched. All three places that report or enforce the rule (me, canvas, create_vault) read the same setting. No client change is needed. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 8 +-- compose.yaml | 2 + core/src/hub.rs | 3 +- docs/SPEC.md | 1 + hub/src/api.rs | 8 +-- hub/src/db.rs | 46 ++++++++++++++++-- hub/src/main.rs | 7 ++- hub/src/web.rs | 2 +- hub/tests/hub.rs | 124 ++++++++++++++++++++++++++++++++++++++++++++++- 9 files changed, 188 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 98181c4..50c8732 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ Lists each vault with its status, and anything that needs you: - **A note may contain a secret:** type where the secret really lives and click **Replace**, or click **Not a secret**. - **A note was changed in two places:** **Compare** shows both versions with the differences highlighted. Keep one, or keep both as separate notes. - **GBrain:** **Mark as GBrain** makes the vault a GBrain brain for the whole team (Lune suggests it when it sees `gbrain.yml`). Where `gbrain` is installed, Lune asks once whether to refresh GBrain after each sync; if a refresh fails, the vault turns amber with **Retry**. -- **Upload:** put a vault that's only on this Mac onto a team, history included. The button shows for the team owner and anyone who manages a vault there. A vault that syncs with its own remote (GitHub, GitLab, Gitea…) is **detached** from it first, so its notes don't end up in two places; that remote keeps its copy as it was. Before anything is made on the team, Lune checks the notes the way the team's hub will: a line that looks like a secret turns red to decide (replace it with where to find it, or mark it not a secret), and if older history has one, you can upload just the current notes (the full history stays on your Mac). +- **Upload:** put a vault that's only on this Mac onto a team, history included. The button shows for whoever may create vaults on that team: by default the team owner and anyone who manages a vault there, or every member if the hub allows it (`LUNE_VAULT_CREATION=anyone`). A vault that syncs with its own remote (GitHub, GitLab, Gitea…) is **detached** from it first, so its notes don't end up in two places; that remote keeps its copy as it was. Before anything is made on the team, Lune checks the notes the way the team's hub will: a line that looks like a secret turns red to decide (replace it with where to find it, or mark it not a secret), and if older history has one, you can upload just the current notes (the full history stays on your Mac). - **Join another team:** add a second hub, such as your workplace's. **Leave** next to a team removes this Mac from it (anything unshared is handed over first). ### The team canvas @@ -136,7 +136,7 @@ Open it from the menu (**Open team canvas**), or with `lunesync open`. Managers - **Grant:** drag a vault onto a person. - **Revoke:** pull the ribbon between them until it snaps. You get an **Undo** for about 8 seconds; nothing reaches their devices before that. -- **Invite person**, **New vault** (the team owner and anyone who manages a vault), **Delete vault…** (team owner; asks first, and the history stays archived on the hub), change roles, rename devices, **Nudge** a device that's behind, tidy notes changed in two places, review **handovers**, and (team owner only) **Remove from team** or **Restore**. +- **Invite person**, **New vault** (the team owner and anyone who manages a vault; every member if the hub sets `LUNE_VAULT_CREATION=anyone`), **Delete vault…** (team owner; asks first, and the history stays archived on the hub), change roles, rename devices, **Nudge** a device that's behind, tidy notes changed in two places, review **handovers**, and (team owner only) **Remove from team** or **Restore**. Every gesture also has a button in the side panel. Every access change is recorded in the hub's access log. @@ -157,7 +157,7 @@ lunesync pair # a one-time code to add another device Team management from the terminal: ```sh -lunesync vault new DevOps # the team owner, or anyone who manages a vault +lunesync vault new DevOps # the team owner, or anyone who manages a vault (any member with LUNE_VAULT_CREATION=anyone) lunesync vault kind Brain gbrain # a GBrain brain for the whole team (or: obsidian) lunesync vault detach Brain # stop syncing with its own remote (GitHub, GitLab…); stays on this device lunesync vault upload Brain # put a vault that's only on this device onto the team @@ -214,6 +214,7 @@ Such a vault still shows in the Lune app with its status, but not on a team canv | `LUNE_HUB_DATA` | `/data` | Where vault histories, the database and the update-signing key live. | | `LUNE_HUB_LISTEN` | `0.0.0.0:8080` | Address the hub listens on. | | `LUNE_RELEASE_PASSWORD` | (asks) | Password of the update-signing key, for `release keygen` / `publish`. | +| `LUNE_VAULT_CREATION` | `managers` | Who may create vaults (and upload one): `managers` is the team owner and anyone who manages a vault; `anyone` is every member. Creators manage only their own new vault, and sharing a vault still needs Manage on it. Any other value stops the hub at start. | --- @@ -230,6 +231,7 @@ services: environment: LUNE_HUB_URL: https://lune.example.com LUNE_OWNER_NAME: Sen + # LUNE_VAULT_CREATION: anyone # let every member create vaults (default: managers) volumes: - ./data:/data caddy: diff --git a/compose.yaml b/compose.yaml index 9375439..8a2ba1f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -9,6 +9,8 @@ services: LUNE_HUB_URL: https://hub.example.com # Name of the team owner; their one-time join link is printed in the log on first start. LUNE_OWNER_NAME: Sen + # Who may create vaults: managers (the default: the owner and anyone who manages a vault) or anyone (every member). + # LUNE_VAULT_CREATION: anyone volumes: - hub-data:/data diff --git a/core/src/hub.rs b/core/src/hub.rs index d0f80ad..8ad693b 100644 --- a/core/src/hub.rs +++ b/core/src/hub.rs @@ -35,7 +35,8 @@ pub struct Me { /// Someone asked this device to share now (Nudge). #[serde(default)] pub nudge: bool, - /// This person may create vaults here, and move vaults onto this hub (owner, or Manage on a vault). + /// This person may create vaults here, and move vaults onto this hub. The hub decides (by default the + /// owner, or Manage on a vault; every member when it runs with `LUNE_VAULT_CREATION=anyone`). #[serde(default)] pub can_create: bool, } diff --git a/docs/SPEC.md b/docs/SPEC.md index 235daca..c9dde54 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -250,3 +250,4 @@ Record here: date, what changed, why, which decision number. Example: - 2026-10-29 — Community release without Apple signing, under AGPL-3.0-only; the public repo stays at git.senkensha.space. (Sen) - 2026-11-16 — For GBrain vaults, S4 changes: the losing version of a same-lines clash is kept only on its own device under Notes to tidy, never written into the vault folder; lines both sides added are kept, incoming first (S4, M8). (Sen) - 2026-11-16 — A vault's kind (Obsidian / GBrain) is a hub setting, so a GBrain vault must be on a hub; Brain moves from Gitea to the hub before M8's acceptance (M8). (Sen) +- 2026-11-17 — Who may create vaults is a hub setting, `LUNE_VAULT_CREATION`: `managers` (the default, as decided 2026-10-29: the team owner and anyone with Manage on a vault) or `anyone`. Any member can create vaults when LUNE_VAULT_CREATION=anyone; creators are Manage on their own vault only; sharing still needs Manage on the vault being shared. The same rule covers uploading a vault, and an unknown value stops the hub at start. (Sen) diff --git a/hub/src/api.rs b/hub/src/api.rs index 515e5e2..fe144ec 100644 --- a/hub/src/api.rs +++ b/hub/src/api.rs @@ -16,6 +16,8 @@ pub struct Hub { pub db: Mutex, pub data: PathBuf, pub url: String, + /// Who may create vaults (`LUNE_VAULT_CREATION`), read once at start. + pub vault_creation: db::VaultCreation, } pub type Shared = Arc; @@ -263,7 +265,7 @@ pub async fn me(State(hub): State, headers: HeaderMap) -> ApiResult { if nudge { conn.execute("UPDATE devices SET nudge = 0 WHERE id = ?1", [&caller.device_id])?; } - let can_create = db::can_create_vaults(&conn, caller.account_id, caller.owner)?; + let can_create = db::can_create_vaults(&conn, hub.vault_creation, caller.account_id, caller.owner)?; Ok(Json(json!({ "person": caller.person, "owner": caller.owner, "device_label": caller.device_label, "vaults": vaults, "leaving": leaving, "nudge": nudge, "can_create": can_create @@ -300,8 +302,8 @@ pub async fn create_vault(State(hub): State, headers: HeaderMap, Json(re return Err(bad("vault names use letters, numbers, spaces, - _ . (up to 60)")); } let conn = hub.db.lock().unwrap(); - if !db::can_create_vaults(&conn, caller.account_id, caller.owner)? { - return Err(denied("only the team owner and people who manage a vault can create vaults")); + if !db::can_create_vaults(&conn, hub.vault_creation, caller.account_id, caller.owner)? { + return Err(denied("on this hub, only the team owner and people who manage a vault can create vaults")); } if db::vault_id(&conn, name)?.is_some() { return Err(ApiError(StatusCode::CONFLICT, format!("there's already a vault named {name}"))); diff --git a/hub/src/db.rs b/hub/src/db.rs index 4980fd4..66c6f3f 100644 --- a/hub/src/db.rs +++ b/hub/src/db.rs @@ -225,9 +225,30 @@ pub fn role(conn: &Connection, account_id: i64, vault_id: i64) -> Result Result { - if owner { +/// Who may create vaults on this hub (`LUNE_VAULT_CREATION`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VaultCreation { + /// The team owner, and anyone with Manage on a vault (the default). + Managers, + /// Any active member of the team. + Anyone, +} + +impl VaultCreation { + /// Reads the setting: `managers` or `anyone`, any case; empty means the default. + pub fn parse(value: &str) -> Result { + match value.trim().to_ascii_lowercase().as_str() { + "" | "managers" => Ok(Self::Managers), + "anyone" => Ok(Self::Anyone), + other => anyhow::bail!("LUNE_VAULT_CREATION is \"{other}\"; use \"managers\" (the default) or \"anyone\""), + } + } +} + +/// Who may create vaults (and move vaults onto the hub). With `Managers`: the team owner, and anyone with +/// Manage on a vault. With `Anyone`: every member. Callers are signed in with normal access (`authenticate`). +pub fn can_create_vaults(conn: &Connection, mode: VaultCreation, account_id: i64, owner: bool) -> Result { + if owner || mode == VaultCreation::Anyone { return Ok(true); } Ok(conn @@ -304,3 +325,22 @@ pub fn retire_if_finished(conn: &Connection, device_id: &str) -> Result { } Ok(false) } + +#[cfg(test)] +mod tests { + use super::VaultCreation; + + #[test] + fn vault_creation_setting_is_read_strictly() { + for v in ["", " ", "managers", "Managers", " MANAGERS\n"] { + assert_eq!(VaultCreation::parse(v).unwrap(), VaultCreation::Managers, "{v:?}"); + } + for v in ["anyone", "Anyone", " ANYONE "] { + assert_eq!(VaultCreation::parse(v).unwrap(), VaultCreation::Anyone, "{v:?}"); + } + for v in ["sometimes", "manager", "any one", "true"] { + let err = VaultCreation::parse(v).unwrap_err().to_string(); + assert!(err.contains("LUNE_VAULT_CREATION") && err.contains("managers") && err.contains("anyone"), "{err}"); + } + } +} diff --git a/hub/src/main.rs b/hub/src/main.rs index 6919464..42f3d72 100644 --- a/hub/src/main.rs +++ b/hub/src/main.rs @@ -64,6 +64,8 @@ async fn serve() -> Result<()> { 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"); + // A value the hub doesn't know stops it here, before any data is touched. + let vault_creation = db::VaultCreation::parse(&env("LUNE_VAULT_CREATION", "managers"))?; std::fs::create_dir_all(data.join("repos"))?; let conn = db::open(&data)?; @@ -79,7 +81,7 @@ async fn serve() -> Result<()> { println!(" lunesync join {url}/join/{token} --name "); } - let hub = Arc::new(api::Hub { db: Mutex::new(conn), data, url: url.clone() }); + let hub = Arc::new(api::Hub { db: Mutex::new(conn), data, url: url.clone(), vault_creation }); // Removals made on the canvas wait out their Undo window, then go through. let ticker = hub.clone(); tokio::spawn(async move { @@ -137,6 +139,9 @@ async fn serve() -> Result<()> { .layer(DefaultBodyLimit::disable()) .with_state(hub); let listener = tokio::net::TcpListener::bind(&listen).await?; + if vault_creation == db::VaultCreation::Anyone { + println!("Any team member may create vaults (LUNE_VAULT_CREATION=anyone)."); + } println!("Lune hub listening on {listen} (public address {url})"); axum::serve(listener, app).await?; Ok(()) diff --git a/hub/src/web.rs b/hub/src/web.rs index 7209232..4b762b4 100644 --- a/hub/src/web.rs +++ b/hub/src/web.rs @@ -231,7 +231,7 @@ pub async fn canvas(State(hub): State, headers: HeaderMap) -> ApiResult .collect() }; - let can_create = db::can_create_vaults(&conn, caller.account_id, caller.owner)?; + let can_create = db::can_create_vaults(&conn, hub.vault_creation, caller.account_id, caller.owner)?; Ok(Json(json!({ "me": { "id": format!("a{}", caller.account_id), "person": caller.person, "owner": caller.owner, "can_create": can_create }, "vaults": vaults, "people": people, "members": members, "pending": pending diff --git a/hub/tests/hub.rs b/hub/tests/hub.rs index 0ca91c3..4f2d6d8 100644 --- a/hub/tests/hub.rs +++ b/hub/tests/hub.rs @@ -24,6 +24,11 @@ impl Drop for HubProcess { static HOME: std::sync::OnceLock = std::sync::OnceLock::new(); fn start_hub(data: &std::path::Path) -> (HubProcess, String, String) { + start_hub_with(data, &[]) +} + +/// A hub with extra settings (`LUNE_VAULT_CREATION`…), given to its process only. +fn start_hub_with(data: &std::path::Path, settings: &[(&str, &str)]) -> (HubProcess, String, String) { if std::env::var_os("LUNE_HOME").is_none() { unsafe { std::env::set_var("LUNE_HOME", HOME.get_or_init(|| tempfile::TempDir::new().unwrap()).path()) }; } @@ -34,6 +39,8 @@ fn start_hub(data: &std::path::Path) -> (HubProcess, String, String) { .env("LUNE_HUB_URL", &url) .env("LUNE_HUB_LISTEN", format!("127.0.0.1:{port}")) .env("LUNE_OWNER_NAME", "Sen") + .env_remove("LUNE_VAULT_CREATION") + .envs(settings.iter().copied()) .stdout(Stdio::piped()) .spawn() .unwrap(); @@ -635,12 +642,18 @@ fn a_vault_moves_onto_the_hub_only_once_it_is_detached() { let sen = mac.hubs[0].clone(); sen.create_vault("Team").unwrap(); - // Creating vaults: the owner, and people who manage a vault; not people who only edit. + // Creating vaults: the owner, and people who manage a vault; not people who only edit or read. let (_, ed_w) = hub::join(&sen.invite("Ed", &[("Team".into(), "edit".into())]).unwrap(), "Ed pc").unwrap(); let ed = as_device(&url, &ed_w); assert!(!ed.me().unwrap().can_create); assert!(ed.create_vault("Eds").is_err()); as_device(&url, &sen_w); + let (_, rae_w) = hub::join(&sen.invite("Rae", &[("Team".into(), "read".into())]).unwrap(), "Rae pc").unwrap(); + let rae = as_device(&url, &rae_w); + assert!(!rae.me().unwrap().can_create); + let err = rae.create_vault("Raes").unwrap_err().to_string(); + assert!(err.contains("only the team owner and people who manage a vault"), "{err}"); + as_device(&url, &sen_w); sen.grant("Ed", "Team", "manage").unwrap(); let ed = as_device(&url, &ed_w); assert!(ed.me().unwrap().can_create); @@ -887,3 +900,112 @@ fn a_vaults_kind_is_set_on_the_hub_and_every_device_follows() { fn db_now() -> i64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as i64 } + +// ---- LUNE_VAULT_CREATION=anyone: every member creates vaults, but shares only what they manage ---- + +#[test] +fn with_vault_creation_anyone_every_member_creates_but_shares_only_what_they_manage() { + let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let tmp = tempfile::TempDir::new().unwrap(); + let (_hub, url, owner_link) = start_hub_with(&tmp.path().join("data"), &[("LUNE_VAULT_CREATION", " Anyone ")]); + let (_, sen_w) = hub::join(&owner_link, "Mac").unwrap(); + let sen = as_device(&url, &sen_w); + sen.create_vault("Team").unwrap(); + sen.create_vault("Private").unwrap(); + let (_, ed_w) = hub::join(&sen.invite("Ed", &[("Team".into(), "edit".into())]).unwrap(), "Ed pc").unwrap(); + as_device(&url, &sen_w); + let (_, rae_w) = hub::join(&sen.invite("Rae", &[("Team".into(), "read".into())]).unwrap(), "Rae pc").unwrap(); + + // An edit-only member and a read-only member may create vaults, and manage only their own. + let ed = as_device(&url, &ed_w); + assert!(ed.me().unwrap().can_create); + assert_eq!(ed.create_vault("Eds").unwrap().role, "manage"); + let rae = as_device(&url, &rae_w); + assert!(rae.me().unwrap().can_create); + assert_eq!(rae.create_vault("Raes").unwrap().role, "manage"); + let roles = |me: lune_core::hub::Me| me.vaults.into_iter().map(|v| format!("{}:{}", v.name, v.role)).collect::>(); + assert_eq!(roles(rae.me().unwrap()), ["Raes:manage", "Team:read"]); + let members: Vec = rae.members("Raes").unwrap().into_iter().map(|m| format!("{}:{}", m.person, m.role)).collect(); + assert_eq!(members, ["Rae:manage"]); + + // Vault names stay unique across the team, whoever asks. + let err = rae.create_vault("team").unwrap_err().to_string(); + assert!(err.contains("already a vault named"), "{err}"); + let ed = as_device(&url, &ed_w); + let err = ed.create_vault("Raes").unwrap_err().to_string(); + assert!(err.contains("already a vault named"), "{err}"); + + // Ed shares the vault he created: a new person by invite, an existing member by grant. + let nia_link = ed.invite("Nia", &[("Eds".into(), "edit".into())]).unwrap(); + ed.grant("Rae", "Eds", "read").unwrap(); + let (_, nia_w) = hub::join(&nia_link, "Nia pc").unwrap(); + let nia = as_device(&url, &nia_w); + assert_eq!(roles(nia.me().unwrap()), ["Eds:edit"]); + let ed = as_device(&url, &ed_w); + let mut members: Vec = ed.members("Eds").unwrap().into_iter().map(|m| format!("{}:{}", m.person, m.role)).collect(); + members.sort(); + assert_eq!(members, ["Ed:manage", "Nia:edit", "Rae:read"]); + + // But nobody connects others to a vault they don't manage, or raises themselves there. + for (vault, role) in [("Team", "read"), ("Private", "edit"), ("Raes", "read")] { + let err = ed.invite("Zed", &[(vault.into(), role.into())]).unwrap_err().to_string(); + assert!(err.contains(&format!("you need Manage on {vault} to give access to it")), "{err}"); + let err = ed.invite("Zed", &[("Eds".into(), "edit".into()), (vault.into(), role.into())]).unwrap_err().to_string(); + assert!(err.contains(&format!("you need Manage on {vault}")), "a mixed invite is refused whole: {err}"); + let err = ed.grant("Nia", vault, role).unwrap_err().to_string(); + assert!(err.contains(&format!("you need Manage on {vault}")), "{err}"); + } + for who in ["Ed", "Nia"] { + let err = ed.grant(who, "Team", "manage").unwrap_err().to_string(); + assert!(err.contains("you need Manage on Team"), "{err}"); + } + let rae = as_device(&url, &rae_w); + for (who, vault) in [("Rae", "Team"), ("Rae", "Eds"), ("Ed", "Team"), ("Nia", "Private")] { + let err = rae.grant(who, vault, "manage").unwrap_err().to_string(); + assert!(err.contains(&format!("you need Manage on {vault}")), "{err}"); + } + let err = rae.invite("Zed", &[("Team".into(), "read".into())]).unwrap_err().to_string(); + assert!(err.contains("you need Manage on Team"), "{err}"); + assert_eq!(roles(rae.me().unwrap()), ["Eds:read", "Raes:manage", "Team:read"]); + let ed = as_device(&url, &ed_w); + assert_eq!(roles(ed.me().unwrap()), ["Eds:manage", "Team:edit"]); + + // The owner still sees every vault, and Zed was never invited. + let sen = as_device(&url, &sen_w); + assert!(sen.members("Team").unwrap().iter().all(|m| m.person != "Zed" && m.person != "Nia")); + assert!(sen.members("Private").unwrap().iter().all(|m| m.person == "Sen")); + let log: Vec = sen.log(100).unwrap().into_iter().map(|e| e.detail).collect(); + assert!(!log.iter().any(|d| d.contains("Zed")), "{log:?}"); +} + +#[test] +fn an_unknown_vault_creation_setting_stops_the_hub() { + let tmp = tempfile::TempDir::new().unwrap(); + let data = tmp.path().join("data"); + let mut child = Command::new(env!("CARGO_BIN_EXE_lunehub")) + .env("LUNE_HUB_DATA", &data) + .env("LUNE_HUB_URL", "http://127.0.0.1:9") + .env("LUNE_HUB_LISTEN", "127.0.0.1:0") + .env("LUNE_OWNER_NAME", "Sen") + .env("LUNE_VAULT_CREATION", "sometimes") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let started = std::time::Instant::now(); + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break status; + } + if started.elapsed() > std::time::Duration::from_secs(10) { + let _ = child.kill(); + panic!("the hub kept running with LUNE_VAULT_CREATION=sometimes"); + } + std::thread::sleep(std::time::Duration::from_millis(50)); + }; + let mut stderr = String::new(); + std::io::Read::read_to_string(&mut child.stderr.take().unwrap(), &mut stderr).unwrap(); + assert!(!status.success()); + assert!(stderr.contains("LUNE_VAULT_CREATION") && stderr.contains("managers") && stderr.contains("anyone"), "{stderr}"); + assert!(!data.exists(), "nothing is written before the setting is checked"); +}