0.1.5: uploading checks everything first; no silent joining

- Before anything is made on the team, upload checks the vault the way the
  hub will (the hub's per-entry check now lives in core): a vault on one
  device only holds every line that looks like a secret as a red card to
  decide; lines marked "not a secret" are told to the team's hub at upload;
  history with a flagged entry offers a fresh start. A refused upload no
  longer leaves an empty vault on the team.
- A vault on one device joins a same-named team vault only when they share
  history; otherwise the team's vault arrives beside it in its own folder.
  (A failed upload's empty vault had silently swallowed Brain.)
- The upload sheet follows the vault live and waits for those decisions.
- Full checks of such a vault are cached by content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 18:23:28 +07:00
parent fdcdecf0f1
commit ac5dba46df
12 changed files with 239 additions and 78 deletions

View File

@@ -96,12 +96,15 @@ 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)) {
// A same-named vault here joins this one only when it's on this device alone and shares its history (it was
// uploaded from another device). One that still syncs elsewhere has to be detached first, or its notes would
// live in two places; one with unrelated history is a different vault, so the team's arrives beside it.
let same_name = |v: &crate::config::VaultConfig| v.hub_vault.is_none() && v.name.eq_ignore_ascii_case(&hv.name);
if config.vaults.iter().any(|v| same_name(v) && !v.remote.is_empty()) {
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 joins = |vc: &crate::config::VaultConfig| Vault::open(vc, &label).and_then(|v| v.shares_history_with(&hv.git_url)).unwrap_or(false);
if let Some(vc) = config.vaults.iter_mut().find(|v| same_name(v) && joins(v)) {
let v = Vault::open(vc, &label)?;
let _op = state::op_lock(&v.git_dir)?;
v.relink(&hv.git_url)?;
@@ -117,7 +120,7 @@ fn arrive_from(config: &mut Config, h: &HubLink) -> Result<Vec<String>> {
// Two teams can each have a "Notes": the second one gets the team's address in its folder name.
let mut path = config.vaults_dir().join(&hv.name);
let real = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
if config.vaults.iter().any(|v| real(&v.path) == real(&path)) {
if config.vaults.iter().any(|v| real(&v.path) == real(&path) || v.name.eq_ignore_ascii_case(&hv.name)) {
let host = h.url.split("://").last().unwrap_or(&h.url).replace([':', '/'], "-");
path = config.vaults_dir().join(format!("{} ({host})", hv.name));
}

View File

@@ -161,6 +161,38 @@ pub fn allow(git_dir: &Path, hit: &Hit, file: &str) -> Result<()> {
Ok(())
}
/// Lines this history entry adds (relative to all its parents) that look like secrets. The hub refuses any
/// entry with one (P3); devices use it to know beforehand.
pub fn check_commit(repo: &git2::Repository, commit: &git2::Commit, allowed: &HashSet<String>) -> Result<Vec<String>> {
let parents: Vec<git2::Tree> = commit.parents().map(|p| p.tree()).collect::<Result<_, _>>()?;
let tree = commit.tree()?;
let first = parents.first();
let diff = repo.diff_tree_to_tree(first, Some(&tree), None)?;
let mut out = vec![];
for delta in diff.deltas() {
if !matches!(delta.status(), git2::Delta::Added | git2::Delta::Modified) {
continue;
}
let Some(path) = delta.new_file().path() else { continue };
let new = repo.find_blob(delta.new_file().id())?;
// A line already present in any parent isn't new here.
let mut old = Vec::new();
for p in &parents {
if let Ok(e) = p.get_path(path)
&& let Ok(b) = repo.find_blob(e.id())
{
old.extend_from_slice(b.content());
old.push(b'\n');
}
}
let old = if old.is_empty() { None } else { Some(old.as_slice()) };
for hit in scan_bytes(new.content(), old, allowed) {
out.push(format!("{} line {}: possible {}", path.display(), hit.line, hit.rule));
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;

View File

@@ -4,7 +4,7 @@
use crate::config::{Config, VaultConfig};
use crate::hub::HubLink;
use crate::vault::Vault;
use crate::{remote, state};
use crate::{remote, secrets, 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.
@@ -77,31 +77,79 @@ pub fn detach(config: &mut Config, name: &str) -> Result<String> {
})
}
/// Entries in a vault's history with a line that looks like a secret (and wasn't marked otherwise here). The hub
/// refuses those (P3), so such a vault goes up with its current notes only.
pub fn history_findings(v: &Vault) -> Result<usize> {
let Some(head) = v.head_commit()? else { return Ok(0) };
let allowed = secrets::load_allowed(&v.git_dir);
let repo = v.repo();
let mut walk = repo.revwalk()?;
walk.push(head.id())?;
let mut n = 0;
for id in walk {
if !secrets::check_commit(repo, &repo.find_commit(id?)?, &allowed)?.is_empty() {
n += 1;
}
}
Ok(n)
}
/// What stands between a vault and a team, checked before anything is made there: lines in the current notes
/// that look like secrets (decided one by one, like any held note), then older history the hub would refuse.
pub fn check(config: &Config, name: &str, fresh: bool) -> Result<()> {
let cfg = config.find(name).with_context(|| format!("no vault named \"{name}\" on this device"))?;
if let Some(why) = blocked(cfg) {
bail!(why);
}
let v = Vault::open(cfg, &config.device_label())?;
let held = v.secret_holds()?;
if !held.is_empty() {
let n = held.len();
bail!(
"{n} note{} in {} {} a line that looks like a secret. Decide about each first: replace it with where to find it, or mark it not a secret",
if n == 1 { "" } else { "s" },
cfg.name,
if n == 1 { "has" } else { "have" }
);
}
let old = history_findings(&v)?;
if old > 0 && !fresh {
bail!(
"{old} earlier entr{} in {}'s history {} a line that looks like a secret, which a team never takes. A fresh start uploads just the current notes; the full history stays on this device",
if old == 1 { "y" } else { "ies" },
cfg.name,
if old == 1 { "has" } else { "have" }
);
}
Ok(())
}
/// 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.
/// Everything is checked first, so a vault that can't go up leaves nothing behind on the team. If sending fails
/// after all, 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 };
check(config, name, fresh)?;
let hv = match hub.create_vault(&cfg.name) {
Ok(hv) => hv,
Err(e) if format!("{e}").contains("already a vault") => bail!(
"the team already has a vault named {}. Rename this one (or delete that one on the team canvas) and upload again",
cfg.name
),
Err(e) => return Err(e),
};
// Lines marked "not a secret" here are told to the team's hub, which would refuse them otherwise.
for line_hash in secrets::load_allowed(&v.git_dir) {
hub.not_a_secret(hv.id, &line_hash)?;
}
let before = if fresh { Some(v.fresh_start(&format!("Fresh start on the team (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()) {
match v.sync() {
Ok(_) => {
let vc = config.vaults.iter_mut().find(|x| x.path == cfg.path).unwrap();
vc.remote = hv.git_url.clone();
@@ -115,11 +163,7 @@ pub fn upload(config: &mut Config, hub: &HubLink, name: &str, fresh: bool) -> Re
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)
bail!("{}\n{} stays only on this device.", remote::describe_error(&e), cfg.name)
}
}
}

View File

@@ -198,11 +198,15 @@ impl Vault {
/// Changed notes (not yet saved) that seem to contain a secret on a new line.
pub fn secret_holds(&self) -> Result<Vec<SecretNote>> {
static SCANNED: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<Oid, Vec<Hit>>>> =
std::sync::LazyLock::new(Default::default);
let allowed = secrets::load_allowed(&self.git_dir);
let head_tree = self.head_commit()?.map(|c| c.tree()).transpose()?;
// A vault on this device only hasn't shared anything with where it may go next (a team), so every line counts.
let local = self.is_local();
let head_tree = if local { None } else { self.head_commit()?.map(|c| c.tree()).transpose()? };
let mut known_blobs: Option<HashSet<Oid>> = None;
let mut opts = StatusOptions::new();
opts.include_untracked(true).recurse_untracked_dirs(true).include_ignored(false);
opts.include_untracked(true).recurse_untracked_dirs(true).include_ignored(false).include_unmodified(local);
let mut out = vec![];
for entry in self.repo.statuses(Some(&mut opts))?.iter() {
let st = entry.status();
@@ -213,6 +217,7 @@ impl Vault {
let Ok(bytes) = std::fs::read(self.root.join(path)) else { continue };
let old = match head_tree.as_ref().and_then(|t| t.get_path(Path::new(path)).ok()) {
Some(e) => Some(self.repo.find_blob(e.id())?.content().to_vec()),
None if local => None,
None => {
// A new file whose exact bytes are already in the vault (a copy or a move) was already shared.
let known = known_blobs.get_or_insert_with(|| blob_ids(head_tree.as_ref()));
@@ -222,7 +227,15 @@ impl Vault {
None
}
};
let hits = secrets::scan_bytes(&bytes, old.as_deref(), &allowed);
let hits = if local {
// Every note is checked each time here, so results are kept by content: only edits cost a scan.
let id = Oid::hash_object(git2::ObjectType::Blob, &bytes)?;
let mut cache = SCANNED.lock().unwrap();
let all = cache.entry(id).or_insert_with(|| secrets::scan_bytes(&bytes, None, &HashSet::new()));
all.iter().filter(|h| !allowed.contains(&h.line_hash)).cloned().collect()
} else {
secrets::scan_bytes(&bytes, old.as_deref(), &allowed)
};
if !hits.is_empty() {
out.push(SecretNote { path: path.to_string(), hits });
}
@@ -319,6 +332,26 @@ impl Vault {
Ok(())
}
/// Whether this vault's history and the one at `url` share entries: the same vault, kept in two places.
pub fn shares_history_with(&self, url: &str) -> Result<bool> {
const PROBE: &str = "refs/lune/probe";
let mut remote = self.repo.remote_anonymous(url)?;
let mut opts = FetchOptions::new();
opts.remote_callbacks(remote::callbacks());
opts.download_tags(AutotagOption::None);
remote.fetch(&[format!("+{}:{PROBE}", self.branch_ref())], Some(&mut opts), None)?;
let theirs = self.repo.find_reference(PROBE).ok().and_then(|r| r.target());
let ours = self.head_commit()?.map(|c| c.id());
let shared = match (ours, theirs) {
(Some(a), Some(b)) => self.repo.merge_base(a, b).is_ok(),
_ => false,
};
if let Ok(mut r) = self.repo.find_reference(PROBE) {
r.delete()?;
}
Ok(shared)
}
/// 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> {