Milestone 2: secret check and runaway guard
Notes with a likely secret on a new line are held on the device (own short rule list, per SPEC §8); `lunesync held pointer|not-secret` resolves them. Bursts removing or rewriting a big part of the vault are saved but not shared until `lunesync held share|undo`. Incoming edits to a held note land in place with the held version kept beside it. Adds `tidy show` and SPEC §6 detail for M2. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
39
Cargo.lock
generated
39
Cargo.lock
generated
@@ -2,6 +2,15 @@
|
|||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 4
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "aho-corasick"
|
||||||
|
version = "1.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "android_system_properties"
|
name = "android_system_properties"
|
||||||
version = "0.1.6"
|
version = "0.1.6"
|
||||||
@@ -603,6 +612,7 @@ dependencies = [
|
|||||||
"gethostname",
|
"gethostname",
|
||||||
"git2",
|
"git2",
|
||||||
"notify",
|
"notify",
|
||||||
|
"regex",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
@@ -800,6 +810,35 @@ dependencies = [
|
|||||||
"thiserror",
|
"thiserror",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex"
|
||||||
|
version = "1.13.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
|
||||||
|
dependencies = [
|
||||||
|
"aho-corasick",
|
||||||
|
"memchr",
|
||||||
|
"regex-automata",
|
||||||
|
"regex-syntax",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-automata"
|
||||||
|
version = "0.4.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||||
|
dependencies = [
|
||||||
|
"aho-corasick",
|
||||||
|
"memchr",
|
||||||
|
"regex-syntax",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-syntax"
|
||||||
|
version = "0.8.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustix"
|
name = "rustix"
|
||||||
version = "1.1.6"
|
version = "1.1.6"
|
||||||
|
|||||||
157
cli/src/main.rs
157
cli/src/main.rs
@@ -4,6 +4,8 @@ use anyhow::{Context, Result, bail};
|
|||||||
use chrono::{Local, TimeZone};
|
use chrono::{Local, TimeZone};
|
||||||
use clap::{Parser, Subcommand, ValueEnum};
|
use clap::{Parser, Subcommand, ValueEnum};
|
||||||
use lune_core::config::{Config, VaultConfig};
|
use lune_core::config::{Config, VaultConfig};
|
||||||
|
use lune_core::guard;
|
||||||
|
use lune_core::secrets;
|
||||||
use lune_core::runner::{self, Timing};
|
use lune_core::runner::{self, Timing};
|
||||||
use lune_core::state::{self, SyncState};
|
use lune_core::state::{self, SyncState};
|
||||||
use lune_core::tidy::{self, Keep};
|
use lune_core::tidy::{self, Keep};
|
||||||
@@ -51,7 +53,14 @@ enum Command {
|
|||||||
Tidy {
|
Tidy {
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
action: Option<TidyCmd>,
|
action: Option<TidyCmd>,
|
||||||
#[arg(long)]
|
#[arg(long, global = true)]
|
||||||
|
vault: Option<String>,
|
||||||
|
},
|
||||||
|
/// What's held back on this device (secrets, big changes) and deciding about it
|
||||||
|
Held {
|
||||||
|
#[command(subcommand)]
|
||||||
|
action: Option<HeldCmd>,
|
||||||
|
#[arg(long, global = true)]
|
||||||
vault: Option<String>,
|
vault: Option<String>,
|
||||||
},
|
},
|
||||||
/// Recent history entries and which device made them
|
/// Recent history entries and which device made them
|
||||||
@@ -85,6 +94,30 @@ enum ServiceCmd {
|
|||||||
enum TidyCmd {
|
enum TidyCmd {
|
||||||
/// Keep one version (mine = this device's), or both as separate notes
|
/// Keep one version (mine = this device's), or both as separate notes
|
||||||
Keep { choice: KeepArg, file: PathBuf },
|
Keep { choice: KeepArg, file: PathBuf },
|
||||||
|
/// Compare the two kept versions line by line
|
||||||
|
Show { file: PathBuf },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum HeldCmd {
|
||||||
|
/// The big change was intended: share it anyway
|
||||||
|
Share,
|
||||||
|
/// The big change was a mistake: bring back everything it removed or rewrote
|
||||||
|
Undo,
|
||||||
|
/// Replace the secret in a note with a pointer to where it lives
|
||||||
|
Pointer {
|
||||||
|
file: PathBuf,
|
||||||
|
/// Where to get it, e.g. "search prod-deploy in Secrets Manager"
|
||||||
|
pointer: String,
|
||||||
|
#[arg(long)]
|
||||||
|
line: Option<usize>,
|
||||||
|
},
|
||||||
|
/// It isn't a secret; don't hold that exact line again on this device
|
||||||
|
NotSecret {
|
||||||
|
file: PathBuf,
|
||||||
|
#[arg(long)]
|
||||||
|
line: Option<usize>,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, ValueEnum)]
|
#[derive(Clone, Copy, ValueEnum)]
|
||||||
@@ -177,6 +210,44 @@ fn run_cli(cli: Cli) -> Result<()> {
|
|||||||
}
|
}
|
||||||
share_now(&v);
|
share_now(&v);
|
||||||
}
|
}
|
||||||
|
Command::Tidy { action: Some(TidyCmd::Show { file }), vault } => {
|
||||||
|
let (cfg, rel) = locate(&config, vault.as_deref(), &cwd, &file)?;
|
||||||
|
let v = Vault::open(cfg, &config.device_label())?;
|
||||||
|
print!("{}", tidy::show(&v, &rel)?);
|
||||||
|
println!("Pick one with `lunesync tidy keep mine|theirs|both {rel}`.");
|
||||||
|
}
|
||||||
|
Command::Held { action: None, vault } => {
|
||||||
|
let list: Vec<&VaultConfig> = match vault {
|
||||||
|
Some(n) => vec![config.pick(Some(&n), &cwd)?],
|
||||||
|
None => config.vaults.iter().collect(),
|
||||||
|
};
|
||||||
|
let mut any = false;
|
||||||
|
for cfg in list {
|
||||||
|
let v = Vault::open(cfg, &config.device_label())?;
|
||||||
|
for h in guard::load(&v.git_dir) {
|
||||||
|
any = true;
|
||||||
|
println!(
|
||||||
|
"{}: big change held — \"{}\" removes {} and rewrites {} of {} notes.",
|
||||||
|
v.name, h.message, h.removed, h.rewritten, h.total
|
||||||
|
);
|
||||||
|
println!(" Send it: `lunesync held share` Bring everything back: `lunesync held undo`");
|
||||||
|
}
|
||||||
|
for n in v.secret_holds()? {
|
||||||
|
any = true;
|
||||||
|
for h in &n.hits {
|
||||||
|
println!("{}: {} line {} has a possible {}: {}", v.name, n.path, h.line, h.rule, h.hint);
|
||||||
|
}
|
||||||
|
println!(
|
||||||
|
" Replace it: `lunesync held pointer {} \"where to get it\"` Not a secret: `lunesync held not-secret {}`",
|
||||||
|
n.path, n.path
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !any {
|
||||||
|
println!("Nothing held back.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Held { action: Some(cmd), vault } => held(&config, &cwd, vault.as_deref(), cmd)?,
|
||||||
Command::History { vault, count } => {
|
Command::History { vault, count } => {
|
||||||
let cfg = config.pick(vault.as_deref(), &cwd)?;
|
let cfg = config.pick(vault.as_deref(), &cwd)?;
|
||||||
let v = Vault::open(cfg, &config.device_label())?;
|
let v = Vault::open(cfg, &config.device_label())?;
|
||||||
@@ -203,6 +274,80 @@ fn run_cli(cli: Cli) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn held(config: &Config, cwd: &Path, vault: Option<&str>, cmd: HeldCmd) -> Result<()> {
|
||||||
|
let label = config.device_label();
|
||||||
|
match cmd {
|
||||||
|
HeldCmd::Share | HeldCmd::Undo => {
|
||||||
|
let cfg = config.pick(vault, cwd)?;
|
||||||
|
let v = Vault::open(cfg, &label)?;
|
||||||
|
let _op = state::op_lock(&v.git_dir)?;
|
||||||
|
if guard::load(&v.git_dir).is_empty() {
|
||||||
|
println!("No big change is held in {}.", v.name);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if matches!(cmd, HeldCmd::Share) {
|
||||||
|
for h in v.share_held()? {
|
||||||
|
println!("Sharing \"{}\".", h.message);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let kept = v.undo_held()?;
|
||||||
|
println!("Brought everything back in {}.", v.name);
|
||||||
|
for (note, copy) in kept {
|
||||||
|
println!(" {note} was edited elsewhere meanwhile — kept both, the other version is \"{copy}\".");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
share_now(&v);
|
||||||
|
}
|
||||||
|
HeldCmd::Pointer { file, pointer, line } => {
|
||||||
|
let (cfg, rel) = locate(config, vault, cwd, &file)?;
|
||||||
|
let v = Vault::open(cfg, &label)?;
|
||||||
|
let _op = state::op_lock(&v.git_dir)?;
|
||||||
|
let hits = held_hits(&v, &rel, line)?;
|
||||||
|
let path = v.root.join(&rel);
|
||||||
|
let text = std::fs::read_to_string(&path)?;
|
||||||
|
std::fs::write(&path, secrets::replace_with_pointer(&text, &hits, line, &pointer))?;
|
||||||
|
println!("Replaced {} secret{} in {rel} with \"{pointer}\".", hits.len(), if hits.len() == 1 { "" } else { "s" });
|
||||||
|
save_and_share(&v)?;
|
||||||
|
}
|
||||||
|
HeldCmd::NotSecret { file, line } => {
|
||||||
|
let (cfg, rel) = locate(config, vault, cwd, &file)?;
|
||||||
|
let v = Vault::open(cfg, &label)?;
|
||||||
|
let _op = state::op_lock(&v.git_dir)?;
|
||||||
|
for h in held_hits(&v, &rel, line)? {
|
||||||
|
secrets::allow(&v.git_dir, &h, &rel)?;
|
||||||
|
println!("OK — line {} of {rel} won't be held again on this device.", h.line);
|
||||||
|
}
|
||||||
|
save_and_share(&v)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn held_hits(v: &Vault, rel: &str, line: Option<usize>) -> Result<Vec<secrets::Hit>> {
|
||||||
|
let note = v.secret_holds()?.into_iter().find(|n| n.path == rel);
|
||||||
|
let hits: Vec<secrets::Hit> = note
|
||||||
|
.map(|n| n.hits)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|h| line.is_none_or(|l| h.line == l))
|
||||||
|
.collect();
|
||||||
|
if hits.is_empty() {
|
||||||
|
bail!("nothing is held in {rel}{}", line.map(|l| format!(" on line {l}")).unwrap_or_default());
|
||||||
|
}
|
||||||
|
Ok(hits)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_and_share(v: &Vault) -> Result<()> {
|
||||||
|
if v.save_changes(None, &Default::default())?.is_some_and(|s| s.held.is_some()) {
|
||||||
|
println!("That change is big enough to be held too — see `lunesync held`.");
|
||||||
|
}
|
||||||
|
if !v.secret_holds()?.is_empty() {
|
||||||
|
println!("Something else in this vault is still held — see `lunesync held`.");
|
||||||
|
}
|
||||||
|
share_now(v);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn add(config: &mut Config, name: &str, folder: &Path, remote: &str) -> Result<()> {
|
fn add(config: &mut Config, name: &str, folder: &Path, remote: &str) -> Result<()> {
|
||||||
if config.find(name).is_some() {
|
if config.find(name).is_some() {
|
||||||
bail!("there's already a vault named \"{name}\"");
|
bail!("there's already a vault named \"{name}\"");
|
||||||
@@ -293,6 +438,16 @@ fn print_status(cfg: &VaultConfig, label: &str) {
|
|||||||
if let Some(t) = st.last_synced {
|
if let Some(t) = st.last_synced {
|
||||||
println!(" Last sync: {} ({})", Local.timestamp_opt(t, 0).unwrap().format("%Y-%m-%d %H:%M:%S"), ago(t));
|
println!(" Last sync: {} ({})", Local.timestamp_opt(t, 0).unwrap().format("%Y-%m-%d %H:%M:%S"), ago(t));
|
||||||
}
|
}
|
||||||
|
for h in guard::load(&v.git_dir) {
|
||||||
|
println!(" Holding back a big change: \"{}\" — nothing from here is shared until you decide (`lunesync held`)", h.message);
|
||||||
|
}
|
||||||
|
let secret_notes = v.secret_holds().map(|l| l.len()).unwrap_or(0);
|
||||||
|
if secret_notes > 0 {
|
||||||
|
println!(
|
||||||
|
" {secret_notes} note{} not shared: looks like a secret (`lunesync held`)",
|
||||||
|
if secret_notes == 1 { "" } else { "s" }
|
||||||
|
);
|
||||||
|
}
|
||||||
let to_tidy = tidy::list(&v).map(|l| l.len()).unwrap_or(0);
|
let to_tidy = tidy::list(&v).map(|l| l.len()).unwrap_or(0);
|
||||||
if to_tidy > 0 {
|
if to_tidy > 0 {
|
||||||
println!(" {to_tidy} note{} to tidy — see `lunesync tidy`", if to_tidy == 1 { "" } else { "s" });
|
println!(" {to_tidy} note{} to tidy — see `lunesync tidy`", if to_tidy == 1 { "" } else { "s" });
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ dirs = "7.0.0"
|
|||||||
gethostname = "1.1.0"
|
gethostname = "1.1.0"
|
||||||
git2 = { version = "0.21.0", features = ["ssh", "https", "vendored-libgit2", "vendored-openssl"] }
|
git2 = { version = "0.21.0", features = ["ssh", "https", "vendored-libgit2", "vendored-openssl"] }
|
||||||
notify = "8.2.1"
|
notify = "8.2.1"
|
||||||
|
regex = "1.13.1"
|
||||||
serde = { version = "1.0.229", features = ["derive"] }
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
serde_json = "1.0.154"
|
serde_json = "1.0.154"
|
||||||
toml = "1.1.8"
|
toml = "1.1.8"
|
||||||
|
|||||||
98
core/src/guard.rs
Normal file
98
core/src/guard.rs
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
//! Runaway guard (S6): a burst that removes or rewrites a big part of the vault is held for the owner.
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use git2::{DiffFindOptions, Patch, Repository, Tree, TreeWalkMode, TreeWalkResult};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// A saved burst that isn't shared until the owner says so.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct HeldBurst {
|
||||||
|
pub id: String,
|
||||||
|
pub message: String,
|
||||||
|
pub removed: usize,
|
||||||
|
pub rewritten: usize,
|
||||||
|
pub total: usize,
|
||||||
|
pub at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default)]
|
||||||
|
pub struct Damage {
|
||||||
|
pub removed: usize,
|
||||||
|
pub rewritten: usize,
|
||||||
|
/// Notes in the vault before the burst.
|
||||||
|
pub total: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Damage {
|
||||||
|
pub fn is_runaway(&self) -> bool {
|
||||||
|
let n = self.removed + self.rewritten;
|
||||||
|
n >= 50 || (n >= 5 && n * 5 >= self.total)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Counts notes removed and heavily rewritten (more than half their lines gone). Renames don't count.
|
||||||
|
pub fn assess(repo: &Repository, old: &Tree, new: &Tree) -> Result<Damage> {
|
||||||
|
let mut diff = repo.diff_tree_to_tree(Some(old), Some(new), None)?;
|
||||||
|
diff.find_similar(Some(DiffFindOptions::new().renames(true)))?;
|
||||||
|
let mut d = Damage::default();
|
||||||
|
old.walk(TreeWalkMode::PreOrder, |_, e| {
|
||||||
|
if e.kind() == Some(git2::ObjectType::Blob) {
|
||||||
|
d.total += 1;
|
||||||
|
}
|
||||||
|
TreeWalkResult::Ok
|
||||||
|
})?;
|
||||||
|
for delta in diff.deltas() {
|
||||||
|
match delta.status() {
|
||||||
|
git2::Delta::Deleted => d.removed += 1,
|
||||||
|
git2::Delta::Modified => {
|
||||||
|
let before = repo.find_blob(delta.old_file().id())?;
|
||||||
|
let after = repo.find_blob(delta.new_file().id())?;
|
||||||
|
if before.is_binary() || after.is_binary() {
|
||||||
|
d.rewritten += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let lines = before.content().split(|&b| b == b'\n').filter(|l| !l.is_empty()).count();
|
||||||
|
let patch = Patch::from_blobs(&before, None, &after, None, None)?;
|
||||||
|
let (_, _, gone) = patch.line_stats()?;
|
||||||
|
if lines > 0 && gone * 2 > lines {
|
||||||
|
d.rewritten += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(d)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path(git_dir: &Path) -> std::path::PathBuf {
|
||||||
|
crate::state::lune_dir(git_dir).join("held.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load(git_dir: &Path) -> Vec<HeldBurst> {
|
||||||
|
std::fs::read_to_string(path(git_dir)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(git_dir: &Path, held: &[HeldBurst]) -> Result<()> {
|
||||||
|
let p = path(git_dir);
|
||||||
|
std::fs::create_dir_all(p.parent().unwrap())?;
|
||||||
|
let tmp = p.with_extension("json.tmp");
|
||||||
|
std::fs::write(&tmp, serde_json::to_vec_pretty(held)?)?;
|
||||||
|
std::fs::rename(tmp, p)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn thresholds() {
|
||||||
|
let d = |removed, rewritten, total| Damage { removed, rewritten, total };
|
||||||
|
assert!(d(50, 0, 10_000).is_runaway());
|
||||||
|
assert!(d(10, 10, 100).is_runaway());
|
||||||
|
assert!(!d(19, 0, 100).is_runaway());
|
||||||
|
assert!(!d(4, 0, 10).is_runaway(), "tiny vaults need at least 5 notes touched");
|
||||||
|
assert!(d(5, 0, 10).is_runaway());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,9 +3,11 @@
|
|||||||
pub use git2;
|
pub use git2;
|
||||||
|
|
||||||
pub mod config;
|
pub mod config;
|
||||||
|
pub mod guard;
|
||||||
pub mod names;
|
pub mod names;
|
||||||
pub mod remote;
|
pub mod remote;
|
||||||
pub mod runner;
|
pub mod runner;
|
||||||
|
pub mod secrets;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
pub mod tidy;
|
pub mod tidy;
|
||||||
pub mod vault;
|
pub mod vault;
|
||||||
|
|||||||
@@ -91,6 +91,8 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
|
|||||||
let mut sync_at = Instant::now();
|
let mut sync_at = Instant::now();
|
||||||
let mut backoff = poll;
|
let mut backoff = poll;
|
||||||
let mut was_waiting = false;
|
let mut was_waiting = false;
|
||||||
|
let mut was_holding = false;
|
||||||
|
let mut announced: HashSet<String> = HashSet::new();
|
||||||
loop {
|
loop {
|
||||||
let first = rx.recv_timeout(Duration::from_millis(250));
|
let first = rx.recv_timeout(Duration::from_millis(250));
|
||||||
for ev in first.into_iter().chain(rx.try_iter()) {
|
for ev in first.into_iter().chain(rx.try_iter()) {
|
||||||
@@ -116,11 +118,39 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
|
|||||||
match vault.save_changes(None, &skip) {
|
match vault.save_changes(None, &skip) {
|
||||||
Ok(Some(saved)) => {
|
Ok(Some(saved)) => {
|
||||||
say(&format!("saved: {}", saved.message));
|
say(&format!("saved: {}", saved.message));
|
||||||
|
if let Some(d) = saved.held {
|
||||||
|
say(&format!(
|
||||||
|
"HELD: this change removes or rewrites {} of {} notes, so it stays on this device. \
|
||||||
|
`lunesync held share` to send it anyway, `lunesync held undo` to bring everything back",
|
||||||
|
d.removed + d.rewritten,
|
||||||
|
d.total
|
||||||
|
));
|
||||||
|
}
|
||||||
sync_at = now;
|
sync_at = now;
|
||||||
}
|
}
|
||||||
Ok(None) => {}
|
Ok(None) => {}
|
||||||
Err(e) => say(&format!("couldn't save changes: {e:#}")),
|
Err(e) => say(&format!("couldn't save changes: {e:#}")),
|
||||||
}
|
}
|
||||||
|
match vault.secret_holds() {
|
||||||
|
Ok(notes) => {
|
||||||
|
let mut current = HashSet::new();
|
||||||
|
for n in notes {
|
||||||
|
for h in n.hits {
|
||||||
|
let key = format!("{}:{}", n.path, h.line_hash);
|
||||||
|
if !announced.contains(&key) {
|
||||||
|
say(&format!(
|
||||||
|
"HELD: {} line {} has a possible {} ({}), so this note isn't shared. \
|
||||||
|
`lunesync held` to replace it with a pointer or mark it not a secret",
|
||||||
|
n.path, h.line, h.rule, h.hint
|
||||||
|
));
|
||||||
|
}
|
||||||
|
current.insert(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
announced = current;
|
||||||
|
}
|
||||||
|
Err(e) => say(&format!("couldn't run the secret check: {e:#}")),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if Instant::now() >= sync_at {
|
if Instant::now() >= sync_at {
|
||||||
@@ -131,9 +161,13 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
|
|||||||
match result {
|
match result {
|
||||||
Ok(report) => {
|
Ok(report) => {
|
||||||
st.last_error = None;
|
st.last_error = None;
|
||||||
if !report.waiting_for_local_edits {
|
if !report.waiting_for_local_edits && !report.holding {
|
||||||
st.last_synced = st.last_attempt;
|
st.last_synced = st.last_attempt;
|
||||||
}
|
}
|
||||||
|
if report.holding && !was_holding {
|
||||||
|
say("not sharing anything from this device while a big change is held");
|
||||||
|
}
|
||||||
|
was_holding = report.holding;
|
||||||
if report.waiting_for_local_edits && !was_waiting {
|
if report.waiting_for_local_edits && !was_waiting {
|
||||||
say("new changes are waiting until your current edits settle");
|
say("new changes are waiting until your current edits settle");
|
||||||
}
|
}
|
||||||
@@ -180,6 +214,9 @@ fn print_report(r: &SyncReport, say: &dyn Fn(&str)) {
|
|||||||
for (note, copy) in &r.kept_both {
|
for (note, copy) in &r.kept_both {
|
||||||
say(&format!("{note} was changed in two places — kept both, yours is in \"{copy}\""));
|
say(&format!("{note} was changed in two places — kept both, yours is in \"{copy}\""));
|
||||||
}
|
}
|
||||||
|
for (note, copy) in &r.set_aside {
|
||||||
|
say(&format!("{note} changed elsewhere while held here — your held version is now \"{copy}\""));
|
||||||
|
}
|
||||||
for (old, new) in &r.case_renamed {
|
for (old, new) in &r.case_renamed {
|
||||||
say(&format!("{old} clashed with another name differing only by case — renamed to {new}"));
|
say(&format!("{old} clashed with another name differing only by case — renamed to {new}"));
|
||||||
}
|
}
|
||||||
|
|||||||
217
core/src/secrets.rs
Normal file
217
core/src/secrets.rs
Normal file
@@ -0,0 +1,217 @@
|
|||||||
|
//! The secret check (P2): our own short list of high-confidence rules, run before a change becomes history.
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use regex::Regex;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
|
struct Rule {
|
||||||
|
name: &'static str,
|
||||||
|
re: Regex,
|
||||||
|
/// Extra test on the matched secret, for rules that would otherwise catch ordinary words.
|
||||||
|
looks_random: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
static RULES: LazyLock<Vec<Rule>> = LazyLock::new(|| {
|
||||||
|
let r = |name, pattern: &str, looks_random| Rule { name, re: Regex::new(pattern).unwrap(), looks_random };
|
||||||
|
vec![
|
||||||
|
r("private key", r"(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----(?:.*?-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|.*)", false),
|
||||||
|
r("AWS access key", r"\b((?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16})\b", false),
|
||||||
|
r("AWS secret key", r#"(?i)aws.{0,20}(?:secret|key).{0,20}?[:=]\s*["']?([A-Za-z0-9/+=]{40})(?:[^A-Za-z0-9/+=]|$)"#, false),
|
||||||
|
r("GitHub token", r"\b((?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})", false),
|
||||||
|
r("GitLab token", r"\b(glpat-[A-Za-z0-9_\-]{20,})", false),
|
||||||
|
r("Slack token", r"\b(xox[baprs]-[A-Za-z0-9-]{10,})", false),
|
||||||
|
r("Slack webhook", r"(https://hooks\.slack\.com/services/[A-Za-z0-9/]{20,})", false),
|
||||||
|
r("Stripe key", r"\b((?:sk|rk)_live_[A-Za-z0-9]{20,})", false),
|
||||||
|
r("Google API key", r"\b(AIza[0-9A-Za-z_\-]{35})", false),
|
||||||
|
r("Google client secret", r"\b(GOCSPX-[A-Za-z0-9_\-]{28})", false),
|
||||||
|
r("Anthropic key", r"\b(sk-ant-[A-Za-z0-9_\-]{32,})", false),
|
||||||
|
r("OpenAI key", r"\b(sk-(?:proj-|svcacct-)?[A-Za-z0-9_\-]{32,})", false),
|
||||||
|
r("npm token", r"\b(npm_[A-Za-z0-9]{36})\b", false),
|
||||||
|
r("DigitalOcean token", r"\b(do[opr]_v1_[a-f0-9]{64})\b", false),
|
||||||
|
r("SendGrid key", r"\b(SG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43})", false),
|
||||||
|
r("Telegram bot token", r"\b(\d{8,10}:AA[A-Za-z0-9_\-]{33})", false),
|
||||||
|
r("Vault token", r"\b(hv[sb]\.[A-Za-z0-9_\-]{90,})", false),
|
||||||
|
r("JSON web token", r"\b(eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})", false),
|
||||||
|
r("password in a URL", r"\b[a-z][a-z0-9+.\-]*://[^\s:/@]+:([^\s@/]{3,})@", true),
|
||||||
|
r(
|
||||||
|
"password or token",
|
||||||
|
r#"(?i)(?:password|passwd|pwd|secret|token|api[_\-]?key|access[_\-]?key|client[_\-]?secret|private[_\-]?key)["']?\s*[:=]\s*["'`]?([^\s"'`,;]{12,})"#,
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
/// One suspected secret in a note.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Hit {
|
||||||
|
pub rule: &'static str,
|
||||||
|
/// Byte span of the secret itself.
|
||||||
|
pub start: usize,
|
||||||
|
pub end: usize,
|
||||||
|
/// 1-based line where it starts.
|
||||||
|
pub line: usize,
|
||||||
|
/// Fingerprint of the exact line(s) it sits on, for "not a secret".
|
||||||
|
pub line_hash: String,
|
||||||
|
/// Masked preview, never the full secret.
|
||||||
|
pub hint: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Secrets on lines of `text` that aren't in `old` (already shared) and aren't allowed.
|
||||||
|
pub fn scan(text: &str, old: Option<&str>, allowed: &HashSet<String>) -> Vec<Hit> {
|
||||||
|
let old_lines: HashSet<&str> = old.map(|o| o.lines().collect()).unwrap_or_default();
|
||||||
|
let mut hits: Vec<Hit> = vec![];
|
||||||
|
for rule in RULES.iter() {
|
||||||
|
for caps in rule.re.captures_iter(text) {
|
||||||
|
let m = caps.get(1).unwrap_or_else(|| caps.get(0).unwrap());
|
||||||
|
if hits.iter().any(|h| m.start() < h.end && h.start < m.end()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if rule.looks_random && !looks_random(m.as_str()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let ls = text[..m.start()].rfind('\n').map_or(0, |i| i + 1);
|
||||||
|
let le = text[m.end()..].find('\n').map_or(text.len(), |i| m.end() + i);
|
||||||
|
let lines = &text[ls..le];
|
||||||
|
if lines.lines().all(|l| old_lines.contains(l)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let line_hash = fingerprint(lines);
|
||||||
|
if allowed.contains(&line_hash) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
hits.push(Hit {
|
||||||
|
rule: rule.name,
|
||||||
|
start: m.start(),
|
||||||
|
end: m.end(),
|
||||||
|
line: text[..m.start()].matches('\n').count() + 1,
|
||||||
|
line_hash,
|
||||||
|
hint: mask(m.as_str()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hits.sort_by_key(|h| h.start);
|
||||||
|
hits
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Scans a file's bytes; binary files are skipped.
|
||||||
|
pub fn scan_bytes(new: &[u8], old: Option<&[u8]>, allowed: &HashSet<String>) -> Vec<Hit> {
|
||||||
|
if new.iter().take(8000).any(|&b| b == 0) {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
let Ok(text) = std::str::from_utf8(new) else { return vec![] };
|
||||||
|
let old = old.and_then(|o| std::str::from_utf8(o).ok());
|
||||||
|
scan(text, old, allowed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces every hit (or only the one on `line`) with `pointer`.
|
||||||
|
pub fn replace_with_pointer(text: &str, hits: &[Hit], line: Option<usize>, pointer: &str) -> String {
|
||||||
|
let mut out = text.to_string();
|
||||||
|
for h in hits.iter().rev().filter(|h| line.is_none_or(|l| h.line == l)) {
|
||||||
|
out.replace_range(h.start..h.end, pointer);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fingerprint(s: &str) -> String {
|
||||||
|
git2::Oid::hash_object(git2::ObjectType::Blob, s.as_bytes()).map(|o| o.to_string()).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mask(s: &str) -> String {
|
||||||
|
let first_line = s.lines().next().unwrap_or("");
|
||||||
|
let shown: String = first_line.chars().take(4).collect();
|
||||||
|
format!("{shown}… ({} characters)", s.chars().count())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Long, mixed and not a placeholder: what real generated secrets look like.
|
||||||
|
fn looks_random(s: &str) -> bool {
|
||||||
|
let lower = s.to_lowercase();
|
||||||
|
let placeholder = ["<", ">", "${", "{{", "xxx", "changeme", "example", "your", "redacted", "placeholder", "****"]
|
||||||
|
.iter()
|
||||||
|
.any(|p| lower.contains(p));
|
||||||
|
if placeholder || s.len() < 8 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let classes = [s.bytes().any(|b| b.is_ascii_lowercase()), s.bytes().any(|b| b.is_ascii_uppercase()), s.bytes().any(|b| b.is_ascii_digit()), s.bytes().any(|b| !b.is_ascii_alphanumeric())];
|
||||||
|
let mut counts = std::collections::HashMap::new();
|
||||||
|
for c in s.chars() {
|
||||||
|
*counts.entry(c).or_insert(0usize) += 1;
|
||||||
|
}
|
||||||
|
let n = s.chars().count() as f64;
|
||||||
|
let entropy: f64 = counts.values().map(|&c| { let p = c as f64 / n; -p * p.log2() }).sum();
|
||||||
|
classes.iter().filter(|&&c| c).count() >= 2 && entropy >= 3.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lines this device was told are not secrets, as fingerprints. Lives in `.git/lune/`.
|
||||||
|
pub fn load_allowed(git_dir: &Path) -> HashSet<String> {
|
||||||
|
std::fs::read_to_string(crate::state::lune_dir(git_dir).join("not-secrets"))
|
||||||
|
.unwrap_or_default()
|
||||||
|
.lines()
|
||||||
|
.filter_map(|l| l.split_whitespace().next().map(String::from))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn allow(git_dir: &Path, hit: &Hit, file: &str) -> Result<()> {
|
||||||
|
use std::io::Write;
|
||||||
|
let dir = crate::state::lune_dir(git_dir);
|
||||||
|
std::fs::create_dir_all(&dir)?;
|
||||||
|
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("not-secrets"))?;
|
||||||
|
writeln!(f, "{} {} line {} · {}", hit.line_hash, file, hit.line, hit.rule)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn rules_hit(text: &str) -> Vec<&'static str> {
|
||||||
|
scan(text, None, &HashSet::new()).into_iter().map(|h| h.rule).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn catches_real_looking_secrets() {
|
||||||
|
assert_eq!(rules_hit("key: AKIAIOSFODNN7EXAMPLE\n"), ["AWS access key"]);
|
||||||
|
assert_eq!(rules_hit("aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n"), ["AWS secret key"]);
|
||||||
|
assert_eq!(rules_hit("-----BEGIN OPENSSH PRIVATE KEY-----\nb3Blbn\n-----END OPENSSH PRIVATE KEY-----\n"), ["private key"]);
|
||||||
|
assert_eq!(rules_hit("token ghp_0123456789abcdefghijABCDEFGHIJ012345\n"), ["GitHub token"]);
|
||||||
|
assert_eq!(rules_hit("sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789\n"), ["Anthropic key"]);
|
||||||
|
assert_eq!(rules_hit("db: postgres://app:S3cr3t-Pa55w0rd@db.internal/app\n"), ["password in a URL"]);
|
||||||
|
assert_eq!(rules_hit("DB_PASSWORD=Xq7#pL9!vR2@mK4z\n"), ["password or token"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn leaves_pointers_and_prose_alone() {
|
||||||
|
for ok in [
|
||||||
|
"Get the DB password from 1Password: search prod-db\n",
|
||||||
|
"password: <ask Sen>\n",
|
||||||
|
"token = ${GITHUB_TOKEN}\n",
|
||||||
|
"secret: see Secrets Manager prod/deploy\n",
|
||||||
|
"use tsh login --proxy=teleport.internal\n",
|
||||||
|
"postgres://app@db.internal/app\n",
|
||||||
|
"api_key = changeme_changeme\n",
|
||||||
|
] {
|
||||||
|
assert!(rules_hit(ok).is_empty(), "{ok}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_new_lines_count_and_allowed_lines_are_remembered() {
|
||||||
|
let old = "AKIAIOSFODNN7EXAMPLE\n";
|
||||||
|
assert!(scan("AKIAIOSFODNN7EXAMPLE\nmore\n", Some(old), &HashSet::new()).is_empty());
|
||||||
|
let hits = scan("x\nkey AKIAIOSFODNN7EXAMPLE\n", None, &HashSet::new());
|
||||||
|
assert_eq!(hits[0].line, 2);
|
||||||
|
let allowed = HashSet::from([hits[0].line_hash.clone()]);
|
||||||
|
assert!(scan("x\nkey AKIAIOSFODNN7EXAMPLE\n", None, &allowed).is_empty());
|
||||||
|
assert!(!hits[0].hint.contains("IOSFODNN7EXAMPLE"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pointer_replaces_only_the_secret() {
|
||||||
|
let text = "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n";
|
||||||
|
let hits = scan(text, None, &HashSet::new());
|
||||||
|
let out = replace_with_pointer(text, &hits, None, "(search prod-deploy in Secrets Manager)");
|
||||||
|
assert_eq!(out, "aws_access_key_id = (search prod-deploy in Secrets Manager)\n");
|
||||||
|
assert!(scan(&out, None, &HashSet::new()).is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@
|
|||||||
use crate::names;
|
use crate::names;
|
||||||
use crate::vault::{Saved, Vault};
|
use crate::vault::{Saved, Vault};
|
||||||
use anyhow::{Result, bail};
|
use anyhow::{Result, bail};
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct KeptBoth {
|
pub struct KeptBoth {
|
||||||
@@ -65,5 +64,40 @@ pub fn keep(vault: &Vault, file: &str, choice: Keep) -> Result<Option<Saved>> {
|
|||||||
_ => std::fs::remove_file(©)?,
|
_ => std::fs::remove_file(©)?,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
vault.save_changes(Some(&format!("Tidied {note}")), &HashSet::new())
|
vault.save_unguarded(Some(&format!("Tidied {note}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Line-by-line comparison of a note and its kept copy: `-` only in the note, `+` only in the copy.
|
||||||
|
pub fn show(vault: &Vault, file: &str) -> Result<String> {
|
||||||
|
let all = list(vault)?;
|
||||||
|
let pairs: Vec<&KeptBoth> = all.iter().filter(|k| k.copy == file || k.note == file).collect();
|
||||||
|
let mut out = String::new();
|
||||||
|
if pairs.is_empty() {
|
||||||
|
bail!("{file} has no kept-both versions to compare");
|
||||||
|
}
|
||||||
|
for k in pairs {
|
||||||
|
let note = std::fs::read(vault.root.join(&k.note)).unwrap_or_default();
|
||||||
|
let copy = std::fs::read(vault.root.join(&k.copy))?;
|
||||||
|
let whose = |copy_side: bool| {
|
||||||
|
if k.label.eq_ignore_ascii_case(&vault.label) == copy_side { "yours" } else { "theirs" }
|
||||||
|
};
|
||||||
|
out.push_str(&format!("- {} ({})\n+ {} ({})\n", k.note, whose(false), k.copy, whose(true)));
|
||||||
|
let patch = git2::Patch::from_buffers(¬e, None, ©, None, None)?;
|
||||||
|
if patch.num_hunks() == 0 {
|
||||||
|
out.push_str(" (identical)\n");
|
||||||
|
}
|
||||||
|
for h in 0..patch.num_hunks() {
|
||||||
|
out.push_str(" ···\n");
|
||||||
|
for l in 0..patch.num_lines_in_hunk(h)? {
|
||||||
|
let line = patch.line_in_hunk(h, l)?;
|
||||||
|
let text = String::from_utf8_lossy(line.content());
|
||||||
|
out.push_str(&format!("{} {}", line.origin(), text));
|
||||||
|
if !text.ends_with('\n') {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
//! One vault on disk: setting it up, saving bursts of edits as history entries, and syncing with the remote.
|
//! One vault on disk: setting it up, saving bursts of edits as history entries, and syncing with the remote.
|
||||||
|
|
||||||
use crate::config::VaultConfig;
|
use crate::config::VaultConfig;
|
||||||
|
use crate::guard::{self, Damage, HeldBurst};
|
||||||
use crate::names;
|
use crate::names;
|
||||||
use crate::remote;
|
use crate::remote;
|
||||||
|
use crate::secrets::{self, Hit};
|
||||||
use crate::state;
|
use crate::state;
|
||||||
use anyhow::{Context, Result, bail};
|
use anyhow::{Context, Result, bail};
|
||||||
use git2::build::{CheckoutBuilder, TreeUpdateBuilder};
|
use git2::build::{CheckoutBuilder, TreeUpdateBuilder};
|
||||||
@@ -43,6 +45,15 @@ pub struct Saved {
|
|||||||
pub id: Oid,
|
pub id: Oid,
|
||||||
pub message: String,
|
pub message: String,
|
||||||
pub files: Vec<String>,
|
pub files: Vec<String>,
|
||||||
|
/// Set when the runaway guard held this burst back.
|
||||||
|
pub held: Option<Damage>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A note whose change is held back because it seems to contain a secret.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct SecretNote {
|
||||||
|
pub path: String,
|
||||||
|
pub hits: Vec<Hit>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What one sync round did, in terms the run log can print.
|
/// What one sync round did, in terms the run log can print.
|
||||||
@@ -60,6 +71,10 @@ pub struct SyncReport {
|
|||||||
pub shared: usize,
|
pub shared: usize,
|
||||||
/// Incoming changes touch a file that is still being edited here; they'll land after it settles.
|
/// Incoming changes touch a file that is still being edited here; they'll land after it settles.
|
||||||
pub waiting_for_local_edits: bool,
|
pub waiting_for_local_edits: bool,
|
||||||
|
/// (note, copy) for held notes moved aside so an incoming version could land.
|
||||||
|
pub set_aside: Vec<(String, String)>,
|
||||||
|
/// A big change is held here, so nothing from this device was shared.
|
||||||
|
pub holding: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Vault {
|
impl Vault {
|
||||||
@@ -119,8 +134,20 @@ impl Vault {
|
|||||||
self.repo.is_path_ignored(rel).unwrap_or(false)
|
self.repo.is_path_ignored(rel).unwrap_or(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Saves every changed file as one history entry, except paths in `skip` (still being written).
|
/// Saves every changed file as one history entry, except paths in `skip` (still being written)
|
||||||
|
/// and notes that seem to contain a secret. A runaway burst is saved but held (S6).
|
||||||
pub fn save_changes(&self, message: Option<&str>, skip: &HashSet<String>) -> Result<Option<Saved>> {
|
pub fn save_changes(&self, message: Option<&str>, skip: &HashSet<String>) -> Result<Option<Saved>> {
|
||||||
|
self.save(message, skip, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like `save_changes`, without the runaway guard: for changes the app makes on the owner's say-so.
|
||||||
|
pub fn save_unguarded(&self, message: Option<&str>) -> Result<Option<Saved>> {
|
||||||
|
self.save(message, &HashSet::new(), false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, message: Option<&str>, skip: &HashSet<String>, guarded: bool) -> Result<Option<Saved>> {
|
||||||
|
let mut skip = skip.clone();
|
||||||
|
skip.extend(self.secret_holds()?.into_iter().map(|n| n.path));
|
||||||
let mut index = self.repo.index()?;
|
let mut index = self.repo.index()?;
|
||||||
index.read(false)?;
|
index.read(false)?;
|
||||||
let mut filter = |p: &Path, _: &[u8]| -> i32 { if skip.contains(&names::slash_path(p)) { 1 } else { 0 } };
|
let mut filter = |p: &Path, _: &[u8]| -> i32 { if skip.contains(&names::slash_path(p)) { 1 } else { 0 } };
|
||||||
@@ -143,10 +170,107 @@ impl Vault {
|
|||||||
Some(m) => m.to_string(),
|
Some(m) => m.to_string(),
|
||||||
None => describe_files(&diff),
|
None => describe_files(&diff),
|
||||||
};
|
};
|
||||||
|
let damage = match &old_tree {
|
||||||
|
Some(old) if guarded => Some(guard::assess(&self.repo, old, &tree)?).filter(|d| d.is_runaway()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
let sig = self.signature()?;
|
let sig = self.signature()?;
|
||||||
let parents: Vec<&Commit> = parent.iter().collect();
|
let parents: Vec<&Commit> = parent.iter().collect();
|
||||||
let id = self.repo.commit(Some(&self.branch_ref()), &sig, &sig, &message, &tree, &parents)?;
|
let id = self.repo.commit(Some(&self.branch_ref()), &sig, &sig, &message, &tree, &parents)?;
|
||||||
Ok(Some(Saved { id, message, files }))
|
if let Some(d) = damage {
|
||||||
|
let mut held = guard::load(&self.git_dir);
|
||||||
|
held.push(HeldBurst {
|
||||||
|
id: id.to_string(),
|
||||||
|
message: message.clone(),
|
||||||
|
removed: d.removed,
|
||||||
|
rewritten: d.rewritten,
|
||||||
|
total: d.total,
|
||||||
|
at: chrono::Utc::now().timestamp(),
|
||||||
|
});
|
||||||
|
guard::save(&self.git_dir, &held)?;
|
||||||
|
}
|
||||||
|
Ok(Some(Saved { id, message, files, held: damage }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changed notes (not yet saved) that seem to contain a secret on a new line.
|
||||||
|
pub fn secret_holds(&self) -> Result<Vec<SecretNote>> {
|
||||||
|
let allowed = secrets::load_allowed(&self.git_dir);
|
||||||
|
let head_tree = 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);
|
||||||
|
let mut out = vec![];
|
||||||
|
for entry in self.repo.statuses(Some(&mut opts))?.iter() {
|
||||||
|
let st = entry.status();
|
||||||
|
if st.is_wt_deleted() || st.is_index_deleted() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Ok(path) = entry.path() else { continue };
|
||||||
|
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 => {
|
||||||
|
// 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()));
|
||||||
|
if known.contains(&Oid::hash_object(git2::ObjectType::Blob, &bytes)?) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let hits = secrets::scan_bytes(&bytes, old.as_deref(), &allowed);
|
||||||
|
if !hits.is_empty() {
|
||||||
|
out.push(SecretNote { path: path.to_string(), hits });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Owner says the held big change was intended: share it.
|
||||||
|
pub fn share_held(&self) -> Result<Vec<HeldBurst>> {
|
||||||
|
let held = guard::load(&self.git_dir);
|
||||||
|
guard::save(&self.git_dir, &[])?;
|
||||||
|
Ok(held)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Owner says the held big change was a mistake: bring back exactly what it removed or rewrote.
|
||||||
|
/// Notes edited elsewhere meanwhile keep both versions. The caller holds the op lock.
|
||||||
|
pub fn undo_held(&self) -> Result<Vec<(String, String)>> {
|
||||||
|
let held = guard::load(&self.git_dir);
|
||||||
|
let mut kept_both = vec![];
|
||||||
|
for h in held.iter().rev() {
|
||||||
|
let burst = self.repo.find_commit(Oid::from_str(&h.id)?)?;
|
||||||
|
let head = self.head_commit()?.context("nothing to undo")?;
|
||||||
|
let mut index = self.repo.revert_commit(&burst, &head, 0, None)?;
|
||||||
|
self.keep_both(&mut index, &mut kept_both)?;
|
||||||
|
let reverted = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
|
||||||
|
// Notes the burst added stay: undo only brings back what it removed or rewrote.
|
||||||
|
let added = self.repo.diff_tree_to_tree(Some(&burst.parent(0)?.tree()?), Some(&burst.tree()?), None)?;
|
||||||
|
let head_tree = head.tree()?;
|
||||||
|
let mut keep = TreeUpdateBuilder::new();
|
||||||
|
for d in added.deltas().filter(|d| d.status() == git2::Delta::Added) {
|
||||||
|
if let Some(p) = d.new_file().path()
|
||||||
|
&& let Ok(e) = head_tree.get_path(p)
|
||||||
|
{
|
||||||
|
keep.upsert(p, e.id(), file_mode(e.filemode()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let tree = self.repo.find_tree(keep.create_updated(&self.repo, &reverted)?)?;
|
||||||
|
if tree.id() == head.tree_id() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let sig = self.signature()?;
|
||||||
|
let id = self.repo.commit(None, &sig, &sig, &format!("Undid: {}", h.message), &tree, &[&head])?;
|
||||||
|
self.move_to(id).map_err(|e| {
|
||||||
|
if e.code() == ErrorCode::Conflict {
|
||||||
|
anyhow::anyhow!("some of those notes are being edited right now — try again in a few seconds")
|
||||||
|
} else {
|
||||||
|
e.into()
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
guard::save(&self.git_dir, &[])?;
|
||||||
|
Ok(kept_both)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A named checkpoint (S3). If everything is already saved, records the name on its own.
|
/// A named checkpoint (S3). If everything is already saved, records the name on its own.
|
||||||
@@ -225,6 +349,7 @@ impl Vault {
|
|||||||
let target = self.fix_case_clashes(target, &mut report)?;
|
let target = self.fix_case_clashes(target, &mut report)?;
|
||||||
let incoming = incoming.as_ref().unwrap();
|
let incoming = incoming.as_ref().unwrap();
|
||||||
self.note_incoming(local.as_ref(), incoming, target, &mut report)?;
|
self.note_incoming(local.as_ref(), incoming, target, &mut report)?;
|
||||||
|
self.set_aside_held_notes(target, &mut report)?;
|
||||||
match self.move_to(target) {
|
match self.move_to(target) {
|
||||||
Ok(()) => {}
|
Ok(()) => {}
|
||||||
Err(e) if e.code() == ErrorCode::Conflict => {
|
Err(e) if e.code() == ErrorCode::Conflict => {
|
||||||
@@ -244,6 +369,10 @@ impl Vault {
|
|||||||
if ahead == 0 {
|
if ahead == 0 {
|
||||||
return Ok(report);
|
return Ok(report);
|
||||||
}
|
}
|
||||||
|
if !guard::load(&self.git_dir).is_empty() {
|
||||||
|
report.holding = true;
|
||||||
|
return Ok(report);
|
||||||
|
}
|
||||||
if self.push()? {
|
if self.push()? {
|
||||||
report.shared += ahead;
|
report.shared += ahead;
|
||||||
return Ok(report);
|
return Ok(report);
|
||||||
@@ -255,6 +384,20 @@ impl Vault {
|
|||||||
/// Combines two lines of history. Same-lines clashes keep both: incoming in place, ours beside it (S4).
|
/// Combines two lines of history. Same-lines clashes keep both: incoming in place, ours beside it (S4).
|
||||||
fn combine(&self, local: &Commit, incoming: &Commit, report: &mut SyncReport) -> Result<Oid> {
|
fn combine(&self, local: &Commit, incoming: &Commit, report: &mut SyncReport) -> Result<Oid> {
|
||||||
let mut index = self.repo.merge_commits(local, incoming, None)?;
|
let mut index = self.repo.merge_commits(local, incoming, None)?;
|
||||||
|
self.keep_both(&mut index, &mut report.kept_both)?;
|
||||||
|
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
|
||||||
|
let from = incoming.author().name().unwrap_or("another device").to_string();
|
||||||
|
let mut message = format!("Combined changes from {from}");
|
||||||
|
if !report.kept_both.is_empty() {
|
||||||
|
let notes: Vec<&str> = report.kept_both.iter().map(|(n, _)| n.as_str()).collect();
|
||||||
|
message.push_str(&format!(" · kept both versions of {}", notes.join(", ")));
|
||||||
|
}
|
||||||
|
let sig = self.signature()?;
|
||||||
|
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[local, incoming])?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves every clash in `index` without markers: "their" version in place, ours beside it (S4).
|
||||||
|
fn keep_both(&self, index: &mut git2::Index, kept_both: &mut Vec<(String, String)>) -> Result<()> {
|
||||||
if index.has_conflicts() {
|
if index.has_conflicts() {
|
||||||
let conflicts: Vec<_> = index.conflicts()?.collect::<Result<_, _>>()?;
|
let conflicts: Vec<_> = index.conflicts()?.collect::<Result<_, _>>()?;
|
||||||
for c in conflicts {
|
for c in conflicts {
|
||||||
@@ -270,7 +413,7 @@ impl Vault {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
index.add(&stage0(&theirs, None))?;
|
index.add(&stage0(&theirs, None))?;
|
||||||
index.add(&stage0(&ours, Some(copy.as_bytes())))?;
|
index.add(&stage0(&ours, Some(copy.as_bytes())))?;
|
||||||
report.kept_both.push((note, copy));
|
kept_both.push((note, copy));
|
||||||
}
|
}
|
||||||
// Different paths, or one side removed the note: keep whatever still exists.
|
// Different paths, or one side removed the note: keep whatever still exists.
|
||||||
(ours, theirs) => {
|
(ours, theirs) => {
|
||||||
@@ -281,15 +424,7 @@ impl Vault {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
|
Ok(())
|
||||||
let from = incoming.author().name().unwrap_or("another device").to_string();
|
|
||||||
let mut message = format!("Combined changes from {from}");
|
|
||||||
if !report.kept_both.is_empty() {
|
|
||||||
let notes: Vec<&str> = report.kept_both.iter().map(|(n, _)| n.as_str()).collect();
|
|
||||||
message.push_str(&format!(" · kept both versions of {}", notes.join(", ")));
|
|
||||||
}
|
|
||||||
let sig = self.signature()?;
|
|
||||||
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[local, incoming])?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Paths that differ only by letter case can't coexist on macOS/Windows. There, rename the extras so
|
/// Paths that differ only by letter case can't coexist on macOS/Windows. There, rename the extras so
|
||||||
@@ -366,6 +501,35 @@ impl Vault {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A held note can't take an incoming version in place, and must not wait for it either:
|
||||||
|
/// move the local version beside it (still held) and put back the saved one so the update lands.
|
||||||
|
fn set_aside_held_notes(&self, target: Oid, report: &mut SyncReport) -> Result<()> {
|
||||||
|
let held = self.secret_holds()?;
|
||||||
|
if held.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let head_tree = self.head_commit()?.map(|c| c.tree()).transpose()?;
|
||||||
|
let target_tree = self.repo.find_commit(target)?.tree()?;
|
||||||
|
for note in held {
|
||||||
|
let p = Path::new(¬e.path);
|
||||||
|
let current = head_tree.as_ref().and_then(|t| t.get_path(p).ok()).map(|e| e.id());
|
||||||
|
let incoming = target_tree.get_path(p).ok().map(|e| e.id());
|
||||||
|
if current == incoming {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let copy = (1..)
|
||||||
|
.map(|n| names::copy_name(¬e.path, &self.label, n))
|
||||||
|
.find(|c| !self.root.join(c).exists() && target_tree.get_path(Path::new(c)).is_err())
|
||||||
|
.unwrap();
|
||||||
|
std::fs::rename(self.root.join(p), self.root.join(©))?;
|
||||||
|
if let Some(id) = current {
|
||||||
|
std::fs::write(self.root.join(p), self.repo.find_blob(id)?.content())?;
|
||||||
|
}
|
||||||
|
report.set_aside.push((note.path, copy));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Writes `target` to the folder without touching anything that's still being edited, then makes it current.
|
/// Writes `target` to the folder without touching anything that's still being edited, then makes it current.
|
||||||
fn move_to(&self, target: Oid) -> Result<(), git2::Error> {
|
fn move_to(&self, target: Oid) -> Result<(), git2::Error> {
|
||||||
let commit = self.repo.find_commit(target)?;
|
let commit = self.repo.find_commit(target)?;
|
||||||
@@ -408,6 +572,17 @@ impl Vault {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn blob_ids(tree: Option<&git2::Tree>) -> HashSet<Oid> {
|
||||||
|
let mut ids = HashSet::new();
|
||||||
|
if let Some(t) = tree {
|
||||||
|
let _ = t.walk(TreeWalkMode::PreOrder, |_, e| {
|
||||||
|
ids.insert(e.id());
|
||||||
|
TreeWalkResult::Ok
|
||||||
|
});
|
||||||
|
}
|
||||||
|
ids
|
||||||
|
}
|
||||||
|
|
||||||
fn stage0(e: &IndexEntry, path: Option<&[u8]>) -> IndexEntry {
|
fn stage0(e: &IndexEntry, path: Option<&[u8]>) -> IndexEntry {
|
||||||
let mut e = IndexEntry { path: e.path.clone(), ..*e };
|
let mut e = IndexEntry { path: e.path.clone(), ..*e };
|
||||||
e.flags = 0;
|
e.flags = 0;
|
||||||
@@ -438,7 +613,12 @@ fn describe_files(diff: &git2::Diff) -> String {
|
|||||||
};
|
};
|
||||||
return format!("{verb} {path}");
|
return format!("{verb} {path}");
|
||||||
}
|
}
|
||||||
format!("Updated {} notes", deltas.len())
|
let verb = match deltas.iter().map(|d| d.status()).collect::<Vec<_>>() {
|
||||||
|
s if s.iter().all(|&x| x == git2::Delta::Deleted) => "Removed",
|
||||||
|
s if s.iter().all(|&x| matches!(x, git2::Delta::Added | git2::Delta::Untracked)) => "Added",
|
||||||
|
_ => "Updated",
|
||||||
|
};
|
||||||
|
format!("{verb} {} notes", deltas.len())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What `add` did with the folder.
|
/// What `add` did with the folder.
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ fn a_burst_is_one_history_entry_labeled_with_the_device() {
|
|||||||
a.sync().unwrap();
|
a.sync().unwrap();
|
||||||
let head = a.head_commit().unwrap().unwrap();
|
let head = a.head_commit().unwrap().unwrap();
|
||||||
assert_eq!(head.author().name().unwrap(), "Hermes");
|
assert_eq!(head.author().name().unwrap(), "Hermes");
|
||||||
assert_eq!(head.summary().unwrap().unwrap(), "Updated 14 notes");
|
assert_eq!(head.summary().unwrap().unwrap(), "Added 14 notes");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -361,3 +361,157 @@ fn names_differing_only_by_case_are_renamed_not_overwritten() {
|
|||||||
assert_eq!(read(&a, "Notes.md"), b"upper\n");
|
assert_eq!(read(&a, "Notes.md"), b"upper\n");
|
||||||
assert_eq!(read(&a, "notes (name clash).md"), b"lower\n");
|
assert_eq!(read(&a, "notes (name clash).md"), b"lower\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Milestone 2: secrets and the runaway guard ----
|
||||||
|
|
||||||
|
use lune_core::secrets;
|
||||||
|
|
||||||
|
const FAKE_KEY: &str = "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_note_with_a_secret_stays_home_while_the_rest_is_shared() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
write(&a, "aws.md", format!("# AWS\n{FAKE_KEY}"));
|
||||||
|
write(&a, "other.md", "fine\n");
|
||||||
|
save_and_sync(&a);
|
||||||
|
b.sync().unwrap();
|
||||||
|
assert_eq!(read(&b, "other.md"), b"fine\n");
|
||||||
|
assert!(!b.root.join("aws.md").exists());
|
||||||
|
|
||||||
|
let held = a.secret_holds().unwrap();
|
||||||
|
assert_eq!(held.len(), 1);
|
||||||
|
assert_eq!((held[0].path.as_str(), held[0].hits[0].rule, held[0].hits[0].line), ("aws.md", "AWS access key", 2));
|
||||||
|
|
||||||
|
let text = String::from_utf8(read(&a, "aws.md")).unwrap();
|
||||||
|
write(&a, "aws.md", secrets::replace_with_pointer(&text, &held[0].hits, None, "(search prod-deploy in Secrets Manager)"));
|
||||||
|
save_and_sync(&a);
|
||||||
|
b.sync().unwrap();
|
||||||
|
assert_eq!(read(&b, "aws.md"), b"# AWS\naws_access_key_id = (search prod-deploy in Secrets Manager)\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn not_a_secret_is_remembered_for_that_line() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
write(&a, "example.md", "The docs use AKIAIOSFODNN7EXAMPLE as a sample.\n");
|
||||||
|
save_and_sync(&a);
|
||||||
|
let held = a.secret_holds().unwrap();
|
||||||
|
secrets::allow(&a.git_dir, &held[0].hits[0], "example.md").unwrap();
|
||||||
|
assert!(a.secret_holds().unwrap().is_empty());
|
||||||
|
save_and_sync(&a);
|
||||||
|
b.sync().unwrap();
|
||||||
|
assert!(b.root.join("example.md").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incoming_changes_to_a_held_note_land_and_the_held_version_moves_beside() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
write(&a, "ops.md", "ops\n");
|
||||||
|
save_and_sync(&a);
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
|
||||||
|
write(&a, "ops.md", format!("ops\n{FAKE_KEY}"));
|
||||||
|
save_and_sync(&a);
|
||||||
|
write(&b, "ops.md", "ops\nnew runbook link\n");
|
||||||
|
save_and_sync(&b);
|
||||||
|
|
||||||
|
let report = a.sync().unwrap();
|
||||||
|
assert!(!report.waiting_for_local_edits);
|
||||||
|
assert_eq!(report.set_aside, vec![("ops.md".into(), "ops (Codex's version).md".into())]);
|
||||||
|
assert_eq!(read(&a, "ops.md"), b"ops\nnew runbook link\n");
|
||||||
|
assert_eq!(read(&a, "ops (Codex's version).md"), format!("ops\n{FAKE_KEY}").as_bytes());
|
||||||
|
let held: Vec<String> = a.secret_holds().unwrap().into_iter().map(|n| n.path).collect();
|
||||||
|
assert_eq!(held, ["ops (Codex's version).md"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn vault_of_20(w: &World) -> (Vault, Vault) {
|
||||||
|
let a = w.device("Codex");
|
||||||
|
for i in 0..20 {
|
||||||
|
write(&a, &format!("notes/{i:02}.md"), format!("note {i}\nline two\n"));
|
||||||
|
}
|
||||||
|
save_and_sync(&a);
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
(a, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deleting_half_the_vault_is_held_and_undo_brings_back_every_byte() {
|
||||||
|
let w = World::new();
|
||||||
|
let (a, b) = vault_of_20(&w);
|
||||||
|
let before = snapshot(&a.root);
|
||||||
|
for i in 0..10 {
|
||||||
|
fs::remove_file(a.root.join(format!("notes/{i:02}.md"))).unwrap();
|
||||||
|
}
|
||||||
|
write(&a, "notes/03-new.md", "unrelated new note\n");
|
||||||
|
let saved = a.save_changes(None, &HashSet::new()).unwrap().unwrap();
|
||||||
|
let d = saved.held.expect("should be held");
|
||||||
|
assert_eq!((d.removed, d.total), (10, 20));
|
||||||
|
|
||||||
|
let report = a.sync().unwrap();
|
||||||
|
assert!(report.holding);
|
||||||
|
b.sync().unwrap();
|
||||||
|
assert_eq!(snapshot(&b.root), before, "nothing reached the other device");
|
||||||
|
|
||||||
|
a.undo_held().unwrap();
|
||||||
|
let mut expected = before.clone();
|
||||||
|
expected.insert("notes/03-new.md".into(), b"unrelated new note\n".to_vec());
|
||||||
|
assert_eq!(snapshot(&a.root), expected);
|
||||||
|
a.sync().unwrap();
|
||||||
|
b.sync().unwrap();
|
||||||
|
assert_eq!(snapshot(&b.root), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn share_anyway_sends_the_big_change() {
|
||||||
|
let w = World::new();
|
||||||
|
let (a, b) = vault_of_20(&w);
|
||||||
|
for i in 0..10 {
|
||||||
|
fs::remove_file(a.root.join(format!("notes/{i:02}.md"))).unwrap();
|
||||||
|
}
|
||||||
|
assert!(a.save_changes(None, &HashSet::new()).unwrap().unwrap().held.is_some());
|
||||||
|
a.sync().unwrap();
|
||||||
|
a.share_held().unwrap();
|
||||||
|
let report = a.sync().unwrap();
|
||||||
|
assert!(!report.holding);
|
||||||
|
b.sync().unwrap();
|
||||||
|
assert_eq!(snapshot(&b.root).len(), 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn undo_keeps_both_when_a_removed_note_was_edited_elsewhere() {
|
||||||
|
let w = World::new();
|
||||||
|
let (a, b) = vault_of_20(&w);
|
||||||
|
for i in 0..10 {
|
||||||
|
fs::remove_file(a.root.join(format!("notes/{i:02}.md"))).unwrap();
|
||||||
|
}
|
||||||
|
a.save_changes(None, &HashSet::new()).unwrap();
|
||||||
|
write(&b, "notes/03.md", "note 3\nline two\nedited on hermes\n");
|
||||||
|
save_and_sync(&b);
|
||||||
|
a.sync().unwrap();
|
||||||
|
a.undo_held().unwrap();
|
||||||
|
let all: Vec<Vec<u8>> = snapshot(&a.root).into_values().collect();
|
||||||
|
assert!(all.contains(&b"note 3\nline two\n".to_vec()));
|
||||||
|
assert!(all.contains(&b"note 3\nline two\nedited on hermes\n".to_vec()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn moves_and_appends_are_not_runaway() {
|
||||||
|
let w = World::new();
|
||||||
|
let (a, _b) = vault_of_20(&w);
|
||||||
|
for i in 0..20 {
|
||||||
|
fs::rename(a.root.join(format!("notes/{i:02}.md")), a.root.join(format!("{i:02}.md"))).unwrap();
|
||||||
|
}
|
||||||
|
assert!(a.save_changes(None, &HashSet::new()).unwrap().unwrap().held.is_none());
|
||||||
|
for i in 0..20 {
|
||||||
|
write(&a, &format!("{i:02}.md"), format!("note {i}\nline two\nappended\n"));
|
||||||
|
}
|
||||||
|
assert!(a.save_changes(None, &HashSet::new()).unwrap().unwrap().held.is_none());
|
||||||
|
for i in 0..20 {
|
||||||
|
write(&a, &format!("{i:02}.md"), "wiped\n");
|
||||||
|
}
|
||||||
|
assert!(a.save_changes(None, &HashSet::new()).unwrap().unwrap().held.is_some());
|
||||||
|
}
|
||||||
|
|||||||
65
docs/SPEC.md
65
docs/SPEC.md
@@ -153,57 +153,48 @@ Only the current milestone gets detailed below. The next one is detailed when th
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Milestone 1 — My machines share one vault
|
## 6. Milestone 2 — It catches my mistakes
|
||||||
|
|
||||||
|
Milestone 1 (sync through a plain Git remote, `lunesync` CLI) is built; its detail lives in the code and tests now.
|
||||||
|
|
||||||
### Goal
|
### Goal
|
||||||
Sen's laptop and VPS keep one vault in sync through an ordinary Git remote (e.g. a private GitHub repo or a bare repo on the VPS). No hub, no accounts yet. This alone fixes the Codex/Hermes drift and becomes a daily-use tool immediately.
|
The sync engine stops the two mistakes that hurt most before they reach anyone else: a secret pasted into a note, and a script that wipes or rewrites a big part of the vault. Both are held on the device where they happened; everything else keeps syncing.
|
||||||
|
|
||||||
### What Sen does
|
### What Sen does
|
||||||
```bash
|
```bash
|
||||||
# on each machine
|
lunesync held # what's held back and why
|
||||||
lunesync device name Codex # or Hermes on the VPS
|
lunesync held pointer <file> "search prod-deploy in Secrets Manager" # replace the secret with a pointer
|
||||||
lunesync add DevOps ~/Vaults/DevOps --remote git@github.com:sen/devops-vault.git
|
lunesync held not-secret <file> [--line N] # it isn't a secret; remembered for that exact line
|
||||||
lunesync run # foreground, to watch it work
|
lunesync held share # the big change was intended: share it anyway
|
||||||
lunesync service install # later: keep it running (launchd / systemd)
|
lunesync held undo # it wasn't: bring everything back
|
||||||
|
lunesync tidy show <file> # compare the two kept versions before picking one
|
||||||
# anytime
|
|
||||||
lunesync status
|
|
||||||
lunesync checkpoint "updated VM list"
|
|
||||||
lunesync tidy # list notes with kept-both versions
|
|
||||||
lunesync tidy keep mine|theirs|both <file>
|
|
||||||
```
|
```
|
||||||
`add` on an empty folder clones; on a folder that already holds a vault, it adopts it (initial commit, then sync). Existing vaults are never reorganized.
|
`status` and the `run` log say when something is held.
|
||||||
|
|
||||||
### Behavior
|
### Behavior
|
||||||
- **Watch → settle → commit → sync**: file watcher; a burst ends after ~5 s of quiet or at 60 s max; only settled files are included; one commit per burst, author = device label.
|
- **Secret check (P2)** runs on every saved burst, before a change becomes history, so a held change can never leave the device. Only lines new to the note are checked. A hit holds that whole note's change (it stays unsaved in the folder); the rest of the burst is shared as usual. Binary files are skipped.
|
||||||
- **Sync** = fetch, merge, push. Retries with backoff. Offline: commits pile up locally, `status` shows "Waiting to sync · N changes".
|
- **Rules**: our own short list of ~20 high-confidence patterns (AWS keys, private key blocks, GitHub/GitLab/Slack/Stripe/Google/OpenAI/Anthropic/npm/DigitalOcean/SendGrid/Telegram/Vault tokens, JWTs, passwords inside URLs, and `password|secret|token|api_key = <long random value>`). Output never prints a full secret, only a masked hint.
|
||||||
- **Conflicts** (S4): never leave conflict markers in files; never stop syncing. `tidy` resolves.
|
- **Pointer**: replaces just the secret text with the pointer text. **Not a secret**: remembered per device as a hash of that exact line (no secret text stored), in `.git/lune/`. The hub gets its own copy of this list in M3.
|
||||||
- **Ignore by default**: `.obsidian/workspace*.json`, `.obsidian/cache`, `.trash/`, OS junk (`.DS_Store`, `Thumbs.db`). Everything else, including binaries and other `.obsidian/` files, syncs byte-for-byte.
|
- **Incoming changes to a held note** don't wait: the held local version moves beside the note as `name (Label's version).md` (still held), the incoming version lands in place. Same rule as S4.
|
||||||
- **No line-ending or case rewriting.** Bytes in = bytes out. Two paths differing only by case are reported, not silently merged.
|
- **Runaway guard (S6)**: a burst is held if it deletes or heavily rewrites (more than half the lines gone) at least 50 notes, or at least 20% of the vault's notes and at least 5. Renames and moves don't count. The burst is saved locally as history (so Undo is exact), but nothing from this device is shared while it's held; incoming changes still arrive.
|
||||||
- **Marker** inside `.git/` identifies folders the app manages (needed later for safe deletion, A9).
|
- **Share anyway** releases it. **Undo** adds a history entry that brings back exactly what the burst removed or rewrote; if someone else edited one of those notes meanwhile, both versions are kept. Then both entries are shared, so other devices see no change.
|
||||||
- `status` per vault: Synced just now / Waiting N / Offline / N notes to tidy, plus last sync time.
|
- **Tidy** gets `show`: a line-by-line comparison of the note and its kept copy.
|
||||||
|
|
||||||
### Tech choices (implementation defaults — record changes)
|
|
||||||
- Rust. Git via `git2` with vendored libgit2 (mature merge support, no system Git needed). `notify` for file watching. TOML config in the OS config dir.
|
|
||||||
- Credentials for the Git remote in M1: whatever the user's SSH agent / Git credential setup already provides. The hub replaces this in M3.
|
|
||||||
|
|
||||||
### Acceptance — Sen acts this out
|
### Acceptance — Sen acts this out
|
||||||
1. Laptop edits `vm-list.md`; within ~10 s the VPS folder has it and Hermes can read it.
|
1. Paste `AKIAIOSFODNN7EXAMPLE` into `aws.md` while other notes are being edited: the other notes reach the VPS, `aws.md` doesn't; `status` and the log say why; `held pointer aws.md "…"` replaces it and the note is shared.
|
||||||
2. Hermes (or a script) rewrites 14 notes in a burst; history shows one entry labeled Hermes.
|
2. A line that only looks like a secret: `held not-secret` releases it and it's never flagged again on that device.
|
||||||
3. Laptop goes offline, 3 notes edited; `status` shows waiting; reconnect; VPS catches up with no action.
|
3. A script deletes half the vault: nothing reaches the VPS; `held undo` brings every file back byte-exact; the VPS never loses a note.
|
||||||
4. Both edit the same lines of `runbook.md` while one is offline; after sync both versions exist, nothing is lost, sync kept running; `tidy keep both|mine|theirs` cleans it up.
|
4. A deliberate big cleanup: `held share` sends it.
|
||||||
5. Adopting an existing Obsidian vault preserves every file and folder exactly (compare checksums before/after).
|
5. Edit the same lines on both machines, `tidy show`, then `tidy keep`.
|
||||||
6. Obsidian open on the vault the whole time: no churn from workspace files, no broken notes.
|
|
||||||
|
|
||||||
### Out of scope for M1
|
### Out of scope for M2
|
||||||
Secret check and runaway guard (M2), hub/accounts/devices (M3), any UI beyond the CLI.
|
The hub-side check (P3) and anything with accounts: M3.
|
||||||
|
|
||||||
---
|
## 7. Open questions
|
||||||
|
|
||||||
## 7. Open questions (not blocking M1)
|
|
||||||
- Hub storage for repos: plain bare repos on disk vs. something like Gitea underneath (decide at M3).
|
- Hub storage for repos: plain bare repos on disk vs. something like Gitea underneath (decide at M3).
|
||||||
- Secret detection rules: embed a known ruleset (gitleaks-style) vs. our own short list (decide at M2).
|
|
||||||
|
|
||||||
## 8. Decision changes
|
## 8. Decision changes
|
||||||
Record here: date, what changed, why, which decision number. Example:
|
Record here: date, what changed, why, which decision number. Example:
|
||||||
`2026-11-02 — S2 cap raised from 60 s to 90 s: VPS bursts too chatty. (Sen)`
|
`2026-11-02 — S2 cap raised from 60 s to 90 s: VPS bursts too chatty. (Sen)`
|
||||||
|
|
||||||
|
- 2026-10-28 — Secret detection (open question, P2): our own short list of ~20 high-confidence rules, not an embedded gitleaks-style set. Fewer false alarms, easy to read. (Sen)
|
||||||
|
|||||||
Reference in New Issue
Block a user