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:
8
Cargo.lock
generated
8
Cargo.lock
generated
@@ -2581,7 +2581,7 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
|
||||
[[package]]
|
||||
name = "lune-core"
|
||||
version = "0.1.4"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.23.1",
|
||||
@@ -2601,7 +2601,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lune-desktop"
|
||||
version = "0.1.4"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
@@ -2621,7 +2621,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lunehub"
|
||||
version = "0.1.4"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -2642,7 +2642,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lunesync"
|
||||
version = "0.1.4"
|
||||
version = "0.1.5"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
||||
@@ -4,5 +4,5 @@ members = ["core", "cli", "hub", "desktop"]
|
||||
|
||||
# One version for every part: the hub offers clients by it (D3).
|
||||
[workspace.package]
|
||||
version = "0.1.4"
|
||||
version = "0.1.5"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
@@ -125,7 +125,7 @@ Lists each vault with its status, and anything that needs you:
|
||||
- **A big change is waiting:** **Undo** brings back everything it removed or rewrote; **Share anyway** sends it.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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).
|
||||
- **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
|
||||
|
||||
@@ -76,10 +76,11 @@ pub fn vault_upload(config: &mut Config, name: &str, fresh: bool) -> Result<()>
|
||||
match lune_core::upload::upload(config, &h, name, fresh) {
|
||||
Ok(said) => {
|
||||
println!("{said}.");
|
||||
println!("Other devices with this vault: `lunesync pair` here, then `lunesync login …` there — it moves over on its own.");
|
||||
println!("Other devices with this vault: detach it there too, then connect them to the team (`lunesync pair` here, `lunesync login …` there); it joins on its own when it shares this history.");
|
||||
Ok(())
|
||||
}
|
||||
Err(e) if format!("{e}").contains("A fresh start") => bail!("{e}\n`lunesync vault upload {name} --fresh` does that."),
|
||||
Err(e) if format!("{e}").contains("A fresh start") => bail!("{e}.\n`lunesync vault upload {name} --fresh` does that."),
|
||||
Err(e) if format!("{e}").contains("Decide about each") => bail!("{e}: `lunesync held`."),
|
||||
Err(e) if format!("{e}").contains("Detach it") => bail!("{e}: `lunesync vault detach {name}`."),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -210,4 +210,5 @@ Record here: date, what changed, why, which decision number. Example:
|
||||
- 2026-10-29 — Deleting a vault (new, team owner): everyone is removed the usual way (handover, then copies removed), the history stays archived on the hub and the name is freed. Asks for confirmation, like Remove from team (X2). (Sen, after testing)
|
||||
- 2026-10-29 — Moving a vault onto a hub (new): the team owner and anyone with Manage on a vault may create vaults, so they may upload one too (the app's **Upload**, `lunesync vault upload`). Only a vault that's on that device alone goes up; one on its own remote (GitHub, GitLab…) is **detached** first, and a check-in no longer moves a same-named vault off its own remote silently. Avoids one vault's notes living in two places (A3). (Sen)
|
||||
- 2026-10-29 — A vault's settings decide where it shares: a folder found pointing elsewhere is set back. A leaving device whose older history has a possible secret hands over its current notes as one entry with those lines replaced, instead of never finishing (A6, P3). (Sen, after the Brain mix-up)
|
||||
- 2026-10-29 — Uploading checks everything first, the way the hub will: a vault on one device only holds every line that looks like a secret for a decision; "not a secret" marks travel to the team; history with one goes up as a fresh start. Nothing is made on the team until it passes. A vault on one device joins a same-named team vault only if they share history; otherwise the team's arrives beside it (P2, P3). (Sen, after the Brain upload)
|
||||
- 2026-10-29 — Community release without Apple signing, under AGPL-3.0-only; the public repo stays at git.senkensha.space. (Sen)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::db;
|
||||
use anyhow::{Context, Result};
|
||||
use lune_core::git2::{self, Oid, Repository};
|
||||
use lune_core::git2::{Oid, Repository};
|
||||
use lune_core::secrets;
|
||||
use std::io::BufRead;
|
||||
use std::path::PathBuf;
|
||||
@@ -45,7 +45,7 @@ pub fn pre_receive() -> Result<bool> {
|
||||
}
|
||||
}
|
||||
for id in walk {
|
||||
found.extend(check_commit(&repo, &repo.find_commit(id?)?, &allowed)?);
|
||||
found.extend(secrets::check_commit(&repo, &repo.find_commit(id?)?, &allowed)?);
|
||||
}
|
||||
}
|
||||
if found.is_empty() {
|
||||
@@ -59,34 +59,3 @@ pub fn pre_receive() -> Result<bool> {
|
||||
db::log(&conn, &actor, "change refused", &format!("{vault}: possible secret — {}", found.join("; ")))?;
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Lines this history entry adds (relative to all its parents) that look like secrets.
|
||||
fn check_commit(repo: &Repository, commit: &git2::Commit, allowed: &std::collections::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 secrets::scan_bytes(new.content(), old, allowed) {
|
||||
out.push(format!("{} line {}: possible {}", path.display(), hit.line, hit.rule));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -664,6 +664,8 @@ fn a_vault_moves_onto_the_hub_only_once_it_is_detached() {
|
||||
sen.create_vault("Brain").unwrap();
|
||||
check_in(&mut mac);
|
||||
assert!(mac.find("Brain").unwrap().hub_vault.is_none(), "a vault on its own remote stays put");
|
||||
let brains = |c: &Config| c.vaults.iter().filter(|v| v.name == "Brain").count();
|
||||
assert_eq!(brains(&mac), 1, "and the team's vault waits until it can arrive beside it");
|
||||
|
||||
// Detaching shares what was waiting there one last time, then it's only on this device.
|
||||
lune_core::upload::detach(&mut mac, "Brain").unwrap();
|
||||
@@ -677,10 +679,22 @@ fn a_vault_moves_onto_the_hub_only_once_it_is_detached() {
|
||||
assert_eq!(lune_core::status::of(mac.find("Brain").unwrap(), "Mac").headline, "Only on this device · not shared");
|
||||
drop(v);
|
||||
|
||||
// Uploading joins the same-named team vault, history included; another device gets every note.
|
||||
// The team's unrelated "Brain" doesn't swallow it: it arrives in its own folder, and the name is taken.
|
||||
check_in(&mut mac);
|
||||
assert!(mac.find("Brain").unwrap().hub_vault.is_none());
|
||||
assert_eq!(brains(&mac), 2, "{:?}", mac.vaults.iter().map(|v| &v.path).collect::<Vec<_>>());
|
||||
let err = lune_core::upload::upload(&mut mac, &sen, "Brain", false).unwrap_err().to_string();
|
||||
assert!(err.contains("already has a vault named Brain"), "{err}");
|
||||
mac.use_hub_credentials();
|
||||
sen.delete_vault("Brain").unwrap();
|
||||
check_in(&mut mac);
|
||||
let mac_brain = mac.find("Brain").unwrap().clone();
|
||||
assert!(mac_brain.hub_vault.is_none() && brains(&mac) == 1, "the deleted team vault left");
|
||||
|
||||
// Uploading, history included; another device gets every note.
|
||||
let said = lune_core::upload::upload(&mut mac, &sen, "Brain", false).unwrap();
|
||||
assert!(said.contains("history included"), "{said}");
|
||||
assert!(mac.find("Brain").unwrap().hub_vault.is_some());
|
||||
assert!(mac.find("Brain").unwrap().hub_vault.is_some() && mac.find("Brain").unwrap().path == mac_brain.path);
|
||||
let code = sen.pair().unwrap();
|
||||
let other_w = hub::login(&url, &code, "Air").unwrap();
|
||||
let mut other = device(&url, &other_w, "Air", &tmp.path().join("air"));
|
||||
@@ -690,6 +704,66 @@ fn a_vault_moves_onto_the_hub_only_once_it_is_detached() {
|
||||
assert_eq!(std::fs::read(o.root.join("later.md")).unwrap(), b"kept here\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn possible_secrets_are_decided_before_anything_goes_to_the_team() {
|
||||
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let (_hub, url, owner_link) = start_hub(&tmp.path().join("data"));
|
||||
let (_, sen_w) = hub::join(&owner_link, "Mac").unwrap();
|
||||
let mut mac = device(&url, &sen_w, "Mac", &tmp.path().join("mac"));
|
||||
let sen = as_device(&url, &sen_w);
|
||||
let elsewhere = tmp.path().join("gitlab.git");
|
||||
lune_core::git2::Repository::init_bare(&elsewhere).unwrap();
|
||||
let remote_url = format!("file://{}", elsewhere.display());
|
||||
|
||||
// Two vaults whose history already has a key line (it was shared elsewhere before Lune checked anything).
|
||||
for name in ["Kept", "Fresh"] {
|
||||
let dir = tmp.path().join(format!("src-{name}"));
|
||||
let repo = lune_core::git2::Repository::init(&dir).unwrap();
|
||||
std::fs::write(dir.join("aws.md"), "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n").unwrap();
|
||||
std::fs::write(dir.join("plan.md"), "plan\n").unwrap();
|
||||
let mut index = repo.index().unwrap();
|
||||
index.add_all(["*"], Default::default(), None).unwrap();
|
||||
let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
|
||||
let sig = lune_core::git2::Signature::now("x", "x@example.com").unwrap();
|
||||
repo.commit(Some("HEAD"), &sig, &sig, "old", &tree, &[]).unwrap();
|
||||
let (mut cfg, _, _) = vault::add(name, &dir, &remote_url, "Mac").unwrap();
|
||||
cfg.remote = remote_url.clone();
|
||||
mac.vaults.push(cfg);
|
||||
lune_core::upload::detach(&mut mac, name).unwrap();
|
||||
// Only on this device now: the key line is held, like any note that hasn't gone anywhere yet.
|
||||
let v = open(&mac, name);
|
||||
assert_eq!(v.secret_holds().unwrap().len(), 1);
|
||||
let err = lune_core::upload::upload(&mut mac, &sen, name, false).unwrap_err().to_string();
|
||||
assert!(err.contains("Decide about each first"), "{err}");
|
||||
}
|
||||
assert!(sen.me().unwrap().vaults.is_empty(), "nothing was made on the team");
|
||||
|
||||
// "Not a secret" here travels with the upload, so the history goes up whole.
|
||||
let v = open(&mac, "Kept");
|
||||
let hit = v.secret_holds().unwrap()[0].hits[0].clone();
|
||||
secrets::allow(&v.git_dir, &hit, "aws.md").unwrap();
|
||||
assert!(v.secret_holds().unwrap().is_empty());
|
||||
drop(v);
|
||||
let said = lune_core::upload::upload(&mut mac, &sen, "Kept", false).unwrap();
|
||||
assert!(said.contains("history included"), "{said}");
|
||||
|
||||
// Replaced with a pointer: the old entry still has it, so only a fresh start goes up.
|
||||
let v = open(&mac, "Fresh");
|
||||
let note = v.secret_holds().unwrap().remove(0);
|
||||
let text = std::fs::read_to_string(v.root.join("aws.md")).unwrap();
|
||||
std::fs::write(v.root.join("aws.md"), secrets::replace_with_pointer(&text, ¬e.hits, None, "in 1Password: AWS")).unwrap();
|
||||
v.save_changes(None, &HashSet::new()).unwrap();
|
||||
drop(v);
|
||||
let err = lune_core::upload::upload(&mut mac, &sen, "Fresh", false).unwrap_err().to_string();
|
||||
assert!(err.contains("A fresh start"), "{err}");
|
||||
assert_eq!(sen.me().unwrap().vaults.len(), 1, "still nothing made for it");
|
||||
let said = lune_core::upload::upload(&mut mac, &sen, "Fresh", true).unwrap();
|
||||
assert!(said.contains("starting fresh"), "{said}");
|
||||
let v = open(&mac, "Fresh");
|
||||
assert_eq!(std::fs::read_to_string(v.root.join("aws.md")).unwrap(), "aws_access_key_id = in 1Password: AWS\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_finishes_even_when_the_folder_points_elsewhere_and_history_has_a_secret() {
|
||||
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
|
||||
@@ -248,6 +248,7 @@ function UploadSheet({ v, teams, close, done }: { v: VaultStatus; teams: string[
|
||||
const [busy, setBusy] = useState('');
|
||||
const [detached, setDetached] = useState(false);
|
||||
const elsewhere = v.elsewhere && !detached ? v.elsewhere : null;
|
||||
const undecided = v.secrets.length;
|
||||
const run = async (what: string, f: () => Promise<string>) => {
|
||||
setBusy(what);
|
||||
setError('');
|
||||
@@ -280,6 +281,9 @@ function UploadSheet({ v, teams, close, done }: { v: VaultStatus; teams: string[
|
||||
) : (
|
||||
<>
|
||||
<p className="muted">{v.name} {detached ? 'is detached and ' : ''}is only on this Mac. Uploading puts it on the team with its history; you can then give people access on the team canvas.</p>
|
||||
{undecided > 0 && (
|
||||
<p className="error">{plural(undecided, 'note')} {undecided === 1 ? 'has' : 'have'} a line that looks like a secret, marked red in the list. Decide about each there first (replace it with where to find it, or mark it not a secret); a team never takes a secret.</p>
|
||||
)}
|
||||
{teams.length > 1 && (
|
||||
<>
|
||||
<label htmlFor="up-team">Team</label>
|
||||
@@ -296,9 +300,9 @@ function UploadSheet({ v, teams, close, done }: { v: VaultStatus; teams: string[
|
||||
{elsewhere ? (
|
||||
<button className="btn btn-primary" disabled={!!busy} onClick={detach}>{busy || `Detach from ${elsewhere}`}</button>
|
||||
) : secret ? (
|
||||
<button className="btn btn-primary" disabled={!!busy} onClick={() => upload(true)}>{busy || 'Upload current notes only'}</button>
|
||||
<button className="btn btn-primary" disabled={!!busy || undecided > 0} onClick={() => upload(true)}>{busy || 'Upload current notes only'}</button>
|
||||
) : (
|
||||
<button className="btn btn-primary" disabled={!!busy} onClick={() => upload(false)}>{busy || `Upload to ${host(team)}`}</button>
|
||||
<button className="btn btn-primary" disabled={!!busy || undecided > 0} onClick={() => upload(false)}>{busy || `Upload to ${host(team)}`}</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -347,7 +351,7 @@ function App() {
|
||||
const [comparing, setComparing] = useState<{ vault: string; copy: string } | null>(null);
|
||||
const [joining, setJoining] = useState(false);
|
||||
const [leaving, setLeaving] = useState<string | null>(null);
|
||||
const [uploading, setUploading] = useState<VaultStatus | null>(null);
|
||||
const [uploading, setUploading] = useState<string | null>(null);
|
||||
const [uploadTeams, setUploadTeams] = useState<string[]>([]);
|
||||
|
||||
const load = useCallback(() => invoke<Overview>('overview').then(setO).catch((e) => setError(String(e))), []);
|
||||
@@ -402,7 +406,7 @@ function App() {
|
||||
<section className="vaults">
|
||||
{o.vaults.length === 0 && <p className="muted center">Your vaults are on their way. They'll appear in {o.folder}.</p>}
|
||||
{o.vaults.map((v) => (
|
||||
<VaultCard key={v.path} v={v} several={o.teams.length > 1} canUpload={uploadTeams.length > 0} upload={setUploading} act={act} compare={(vault, copy) => setComparing({ vault, copy })} />
|
||||
<VaultCard key={v.path} v={v} several={o.teams.length > 1} canUpload={uploadTeams.length > 0} upload={(u) => setUploading(u.path)} act={act} compare={(vault, copy) => setComparing({ vault, copy })} />
|
||||
))}
|
||||
</section>
|
||||
<footer className="foot">
|
||||
@@ -432,7 +436,7 @@ function App() {
|
||||
</>
|
||||
)}
|
||||
{comparing && <CompareSheet {...comparing} close={() => setComparing(null)} done={(msg) => { setComparing(null); setToast(msg); load(); }} />}
|
||||
{uploading && <UploadSheet v={uploading} teams={uploadTeams} close={() => { setUploading(null); load(); }} done={(msg) => { setUploading(null); setToast(msg); load(); }} />}
|
||||
{uploading && o.vaults.some((x) => x.path === uploading) && <UploadSheet v={o.vaults.find((x) => x.path === uploading)!} teams={uploadTeams} close={() => { setUploading(null); load(); }} done={(msg) => { setUploading(null); setToast(msg); load(); }} />}
|
||||
{leaving && <LeaveSheet team={leaving} close={() => setLeaving(null)} done={(msg) => { setLeaving(null); setToast(msg); load(); }} />}
|
||||
{toast && <div className="toast-d" role="status">{toast}</div>}
|
||||
</main>
|
||||
|
||||
Reference in New Issue
Block a user