0.1.3: upload a vault to a team from the app, detach first; AGPL-3.0

- The Lune window shows Upload on a vault that isn't on a team, for the team
  owner and anyone who manages a vault there. The hub now lets those people
  create vaults too (was owner only); /api/me and the canvas say can_create.
- A vault on its own remote (GitHub, GitLab, Gitea…) must be detached first
  (`lunesync vault detach`, or the Upload sheet's Detach): it shares what's
  waiting one last time, then lives on this device only. Upload refuses
  anything else, and a check-in no longer silently moves a same-named vault
  off its own remote onto the hub.
- Upload logic moved from the CLI into core (lune_core::upload).
- Canvas: "1 person loses access".
- License: AGPL-3.0-only. README and SPEC §8 updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 16:44:36 +07:00
parent 584b279496
commit 4ab9d580b8
26 changed files with 1082 additions and 70 deletions

View File

@@ -1,6 +1,7 @@
[package]
name = "lune-core"
version.workspace = true
license.workspace = true
edition = "2024"
[dependencies]

View File

@@ -35,6 +35,9 @@ 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).
#[serde(default)]
pub can_create: bool,
}
/// One vault's health, as a device reports it to the hub: counts only, never content.

View File

@@ -14,4 +14,5 @@ pub mod state;
pub mod status;
pub mod supervisor;
pub mod tidy;
pub mod upload;
pub mod vault;

View File

@@ -8,8 +8,9 @@ use crate::state;
use crate::vault::{self, Vault};
use anyhow::{Result, bail};
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// What a leaving note gets instead of a secret: the secret itself is never sent or kept (P1).
@@ -48,6 +49,13 @@ pub fn arrive_each(config: &mut Config) -> Vec<(String, Result<Vec<String>>)> {
out
}
/// The hubs where this device's person may create vaults, as of the last check-in.
static CAN_CREATE: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());
pub fn can_create_on() -> Vec<String> {
CAN_CREATE.lock().unwrap().iter().cloned().collect()
}
fn arrive_from(config: &mut Config, h: &HubLink) -> Result<Vec<String>> {
let me = match h.me() {
Ok(me) => me,
@@ -60,6 +68,10 @@ fn arrive_from(config: &mut Config, h: &HubLink) -> Result<Vec<String>> {
}
Err(e) => return Err(e),
};
{
let mut can = CAN_CREATE.lock().unwrap();
if me.owner || me.can_create { can.insert(h.url.clone()) } else { can.remove(&h.url) };
}
let label = config.device_label();
let mine = |v: &crate::config::VaultConfig, id: i64| v.hub_vault == Some(id) && v.hub_url.as_deref() == Some(&h.url);
let mut said = vec![];
@@ -84,6 +96,11 @@ fn arrive_from(config: &mut Config, h: &HubLink) -> Result<Vec<String>> {
state::write_role(&v.git_dir, &hv.role)?;
continue;
}
// A same-named vault that still syncs somewhere else stays put: it has to be detached from there first,
// or its notes would live in two places. Once it's only on this device, it joins this one.
if config.vaults.iter().any(|v| v.hub_vault.is_none() && !v.remote.is_empty() && v.name.eq_ignore_ascii_case(&hv.name)) {
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)?;

View File

@@ -12,6 +12,8 @@ pub struct VaultStatus {
pub path: String,
/// The hub's address, for vaults that sync through one.
pub team: Option<String>,
/// Where it syncs instead, for a vault on its own remote (GitHub, GitLab…): that remote's host.
pub elsewhere: Option<String>,
/// current, behind, offline or secret: the status colours (X6).
pub level: &'static str,
pub headline: String,
@@ -68,6 +70,7 @@ pub fn of(cfg: &VaultConfig, label: &str) -> VaultStatus {
name: cfg.name.clone(),
path: cfg.path.display().to_string(),
team: cfg.hub_url.clone(),
elsewhere: (cfg.hub_vault.is_none() && !cfg.remote.is_empty()).then(|| crate::upload::remote_host(&cfg.remote).to_string()),
level: "behind",
headline: String::new(),
last_synced: None,
@@ -114,6 +117,7 @@ pub fn of(cfg: &VaultConfig, label: &str) -> VaultStatus {
let waiting = out.waiting;
let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" });
let (level, headline) = match &st.last_error {
_ if v.is_local() => ("current", "Only on this device · not shared".to_string()),
None if out.read_only && waiting > 0 => ("current", format!("Up to date · {changes} kept here, not shared (you have read access)")),
None if out.read_only => ("current", "Up to date (read access)".to_string()),
Some(e) if e == remote::TOO_OLD => ("behind", format!("Update Lune to keep syncing · {changes} saved here")),

125
core/src/upload.rs Normal file
View File

@@ -0,0 +1,125 @@
//! Moving a vault onto a hub. Only a vault that is on this device alone can go up: one that still syncs somewhere
//! else (GitHub, GitLab, Gitea…) is detached from there first, so its notes don't end up living in two places.
use crate::config::{Config, VaultConfig};
use crate::hub::HubLink;
use crate::vault::Vault;
use crate::{remote, state};
use anyhow::{Context, Result, bail};
/// Where a remote lives, for people: `ssh://git@gitlab.com:22/x.git` → `gitlab.com`; a folder stays a path.
pub fn remote_host(url: &str) -> &str {
let rest = url.split_once("://").map_or(url, |(_, r)| r);
let rest = match rest.split_once('@') {
Some((user, r)) if !user.contains('/') => r,
_ => rest,
};
match rest.split(['/', ':']).next() {
Some(host) if !host.is_empty() => host,
_ => rest,
}
}
#[cfg(test)]
mod tests {
#[test]
fn remote_hosts_read_plainly() {
for (url, host) in [
("ssh://git@git.senkensha.space:2222/senkensha/agentic-vault.git", "git.senkensha.space"),
("git@github.com:you/notes.git", "github.com"),
("https://user:pw@gitlab.com/team/kb.git", "gitlab.com"),
("file:///srv/notes.git", "/srv/notes.git"),
] {
assert_eq!(super::remote_host(url), host);
}
}
}
/// Why this vault can't go onto a hub as it is, if it can't.
pub fn blocked(cfg: &VaultConfig) -> Option<String> {
if cfg.hub_vault.is_some() {
return Some(format!("{} already syncs through a team", cfg.name));
}
if !cfg.remote.is_empty() {
return Some(format!(
"{} still syncs with {}. Detach it from there first, so its notes don't end up in two places",
cfg.name,
remote_host(&cfg.remote)
));
}
None
}
/// Stops syncing a vault with its own remote. It stays on this device, history and all, shared nowhere until it's
/// uploaded. What's waiting is shared there one last time first, when it can be.
pub fn detach(config: &mut Config, name: &str) -> Result<String> {
let cfg = config.find(name).with_context(|| format!("no vault named \"{name}\" on this device"))?.clone();
if cfg.hub_vault.is_some() {
bail!("{} syncs through a team; leave it there instead", cfg.name);
}
if cfg.remote.is_empty() {
bail!("{} is already only on this device", cfg.name);
}
let v = Vault::open(&cfg, &config.device_label())?;
let _op = state::op_lock(&v.git_dir)?;
v.save_changes(None, &Default::default())?;
let missed = v.sync().err().map(|e| remote::describe_error(&e));
v.unlink()?;
let mut st = state::SyncState::load(&v.git_dir);
st.last_error = None;
st.save(&v.git_dir)?;
config.vaults.iter_mut().find(|x| x.path == cfg.path).unwrap().remote.clear();
config.save()?;
let host = remote_host(&cfg.remote);
Ok(match missed {
None => format!("{} is detached from {host}: it's only on this device now, history included", cfg.name),
Some(why) => format!("{} is detached from {host}, but its latest changes couldn't reach it first ({why}). They're safe here", cfg.name),
})
}
/// Puts a vault that's only on this device onto `hub`, history included, or just its current notes with `fresh`.
/// If anything goes wrong it stays only on this device, as it was.
pub fn upload(config: &mut Config, hub: &HubLink, name: &str, fresh: bool) -> Result<String> {
let label = config.device_label();
let cfg = config.find(name).with_context(|| format!("no vault named \"{name}\" on this device"))?.clone();
if let Some(why) = blocked(&cfg) {
bail!(why);
}
let hv = match hub.create_vault(&cfg.name) {
Ok(hv) => hv,
Err(e) if format!("{e}").contains("already a vault") => hub
.me()?
.vaults
.into_iter()
.find(|v| v.name.eq_ignore_ascii_case(&cfg.name))
.context("the team already has a vault with that name, and you're not in it")?,
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)?;
match v.join_unrelated().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);
vc.hub_url = Some(hub.url.clone());
config.save()?;
Ok(format!("{} now syncs through the team{}", cfg.name, if fresh { ", starting fresh" } else { ", history included" }))
}
Err(e) => {
v.unlink()?;
if let Some(id) = before {
v.reset_history(id)?;
}
let why = remote::describe_error(&e);
if why.contains("possible") && !fresh {
bail!("{why}\nThe earlier history has a possible secret in it. A fresh start uploads just the current notes.");
}
bail!("{why}\n{} stays only on this device.", cfg.name)
}
}
}

View File

@@ -279,6 +279,10 @@ impl Vault {
/// 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<()> {
if self.is_local() {
self.repo.remote("origin", url)?;
return Ok(());
}
self.repo.remote_set_url("origin", url)?;
if let Ok(mut r) = self.repo.find_reference(&self.remote_ref()) {
r.delete()?;
@@ -286,6 +290,19 @@ impl Vault {
Ok(())
}
/// A vault with no remote lives on this device only: it keeps saving history, and shares nowhere.
pub fn is_local(&self) -> bool {
self.repo.find_remote("origin").is_err()
}
/// Stops sharing with the remote; the notes and their history stay here.
pub fn unlink(&self) -> Result<()> {
if !self.is_local() {
self.repo.remote_delete("origin")?;
}
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> {
@@ -405,6 +422,9 @@ impl Vault {
/// One sync round: fetch, combine, write the result to disk, share local history.
pub fn sync(&self) -> Result<SyncReport> {
let mut report = SyncReport::default();
if self.is_local() {
return Ok(report);
}
for _ in 0..3 {
self.fetch()?;
let local = self.head_commit()?;