Milestone 3: the hub
lunehub serves accounts, invites, pairing codes, memberships, devices and vaults as plain bare repos (SPEC §8), checks device key and role on every Git request, refuses secrets in a pre-receive hook (P3) and logs every access change. Ships as one container (Dockerfile, compose.yaml). lunesync gains join, login, pair, vault new/upload, invite, grant, members and hub log; `run` picks up new vaults and roles from the hub. Read members' edits stay local. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2
.dockerignore
Normal file
2
.dockerignore
Normal file
@@ -0,0 +1,2 @@
|
||||
target/
|
||||
.git/
|
||||
870
Cargo.lock
generated
870
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,3 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["core", "cli"]
|
||||
members = ["core", "cli", "hub"]
|
||||
|
||||
16
Dockerfile
Normal file
16
Dockerfile
Normal file
@@ -0,0 +1,16 @@
|
||||
# Lune hub: one container, data on /data.
|
||||
FROM rust:1.99-bookworm AS build
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN cargo build --release -p lunehub
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/* \
|
||||
&& useradd --system --uid 1000 --home /data lune && mkdir /data && chown lune /data
|
||||
COPY --from=build /src/target/release/lunehub /usr/local/bin/lunehub
|
||||
USER lune
|
||||
ENV LUNE_HUB_DATA=/data LUNE_HUB_LISTEN=0.0.0.0:8080
|
||||
VOLUME /data
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=30s --start-period=5s CMD ["lunehub", "health"]
|
||||
CMD ["lunehub", "serve"]
|
||||
164
cli/src/main.rs
164
cli/src/main.rs
@@ -1,4 +1,5 @@
|
||||
mod service;
|
||||
mod team;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use chrono::{Local, TimeZone};
|
||||
@@ -11,7 +12,9 @@ use lune_core::state::{self, SyncState};
|
||||
use lune_core::tidy::{self, Keep};
|
||||
use lune_core::vault::{self, Added, Vault};
|
||||
use lune_core::remote;
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "lunesync", version, about = "Keeps every copy of your vaults in sync.")]
|
||||
@@ -63,6 +66,55 @@ enum Command {
|
||||
#[arg(long, global = true)]
|
||||
vault: Option<String>,
|
||||
},
|
||||
/// Join a team's hub with an invite link (creates your account and this device)
|
||||
Join {
|
||||
link: String,
|
||||
/// Label for this device, e.g. Codex
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
/// Where vaults from the hub go (default ~/Vaults)
|
||||
#[arg(long)]
|
||||
vaults_dir: Option<PathBuf>,
|
||||
},
|
||||
/// Add this device to your hub account with a code from `lunesync pair`
|
||||
Login {
|
||||
#[arg(long)]
|
||||
hub: String,
|
||||
#[arg(long)]
|
||||
code: String,
|
||||
/// Label for this device, e.g. Hermes
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
#[arg(long)]
|
||||
vaults_dir: Option<PathBuf>,
|
||||
},
|
||||
/// Make a one-time code to add another of your devices
|
||||
Pair,
|
||||
/// Vaults on the hub
|
||||
Vault {
|
||||
#[command(subcommand)]
|
||||
action: VaultCmd,
|
||||
},
|
||||
/// Invite a person to the team: --vault DevOps:edit (read, edit or manage), repeatable
|
||||
Invite {
|
||||
person: String,
|
||||
#[arg(long = "vault")]
|
||||
vaults: Vec<String>,
|
||||
},
|
||||
/// Give someone on the team access to a vault, or change their role
|
||||
Grant {
|
||||
person: String,
|
||||
vault: String,
|
||||
#[arg(long, default_value = "edit")]
|
||||
role: String,
|
||||
},
|
||||
/// Who has access to a vault, and their devices
|
||||
Members { vault: String },
|
||||
/// The hub's access log (team owner)
|
||||
Hub {
|
||||
#[command(subcommand)]
|
||||
action: HubCmd,
|
||||
},
|
||||
/// Recent history entries and which device made them
|
||||
History {
|
||||
#[arg(long)]
|
||||
@@ -72,6 +124,28 @@ enum Command {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum VaultCmd {
|
||||
/// Create an empty vault on the hub
|
||||
New { name: String },
|
||||
/// Move a vault from its plain Git remote onto the hub
|
||||
Upload {
|
||||
name: String,
|
||||
/// Upload only the current notes, not the earlier history
|
||||
#[arg(long)]
|
||||
fresh: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum HubCmd {
|
||||
/// Recent access changes
|
||||
Log {
|
||||
#[arg(short = 'n', default_value_t = 30)]
|
||||
count: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum DeviceCmd {
|
||||
/// Set the label shown on everything this device shares
|
||||
@@ -136,6 +210,7 @@ fn main() {
|
||||
|
||||
fn run_cli(cli: Cli) -> Result<()> {
|
||||
let mut config = Config::load()?;
|
||||
config.use_hub_credentials();
|
||||
let cwd = std::env::current_dir()?;
|
||||
match cli.command {
|
||||
Command::Device { action: None } => println!("This device is \"{}\".", config.device_label()),
|
||||
@@ -144,12 +219,24 @@ fn run_cli(cli: Cli) -> Result<()> {
|
||||
if label.is_empty() {
|
||||
bail!("the label can't be empty");
|
||||
}
|
||||
if let Some(h) = &config.hub {
|
||||
h.set_label(&label)?;
|
||||
}
|
||||
config.device_name = Some(label.clone());
|
||||
config.save()?;
|
||||
println!("This device is now \"{label}\". Everything it shares will carry that name.");
|
||||
}
|
||||
Command::Add { name, folder, remote } => add(&mut config, &name, &folder, &remote)?,
|
||||
Command::Run => run(&config)?,
|
||||
Command::Run => run()?,
|
||||
Command::Join { link, name, vaults_dir } => team::join(&mut config, &link, &name, vaults_dir)?,
|
||||
Command::Login { hub, code, name, vaults_dir } => team::login(&mut config, &hub, &code, &name, vaults_dir)?,
|
||||
Command::Pair => team::pair(&config)?,
|
||||
Command::Vault { action: VaultCmd::New { name } } => team::vault_new(&mut config, &name)?,
|
||||
Command::Vault { action: VaultCmd::Upload { name, fresh } } => team::vault_upload(&mut config, &name, fresh)?,
|
||||
Command::Invite { person, vaults } => team::invite(&config, &person, &vaults)?,
|
||||
Command::Grant { person, vault, role } => team::grant(&config, &person, &vault, &role)?,
|
||||
Command::Members { vault } => team::members(&config, &vault)?,
|
||||
Command::Hub { action: HubCmd::Log { count } } => team::log(&config, count)?,
|
||||
Command::Service { action: ServiceCmd::Install { print } } => service::install(print)?,
|
||||
Command::Service { action: ServiceCmd::Uninstall } => service::uninstall()?,
|
||||
Command::Status { vault } => {
|
||||
@@ -161,6 +248,12 @@ fn run_cli(cli: Cli) -> Result<()> {
|
||||
println!("No vaults yet. Add one with `lunesync add <name> <folder> --remote <url>`.");
|
||||
}
|
||||
println!("Device: {}", config.device_label());
|
||||
if let Some(h) = &config.hub {
|
||||
match h.me() {
|
||||
Ok(me) => println!("Hub: {} as {}{}", h.url, me.person, if me.owner { " (team owner)" } else { "" }),
|
||||
Err(e) => println!("Hub: {} — can't reach it right now ({e})", h.url),
|
||||
}
|
||||
}
|
||||
for v in vaults {
|
||||
print_status(v, &config.device_label());
|
||||
}
|
||||
@@ -315,6 +408,9 @@ fn held(config: &Config, cwd: &Path, vault: Option<&str>, cmd: HeldCmd) -> Resul
|
||||
let _op = state::op_lock(&v.git_dir)?;
|
||||
for h in held_hits(&v, &rel, line)? {
|
||||
secrets::allow(&v.git_dir, &h, &rel)?;
|
||||
if let (Some(hub), Some(id)) = (&config.hub, cfg.hub_vault) {
|
||||
hub.not_a_secret(id, &h.line_hash)?;
|
||||
}
|
||||
println!("OK — line {} of {rel} won't be held again on this device.", h.line);
|
||||
}
|
||||
save_and_share(&v)?;
|
||||
@@ -369,34 +465,60 @@ fn add(config: &mut Config, name: &str, folder: &Path, remote: &str) -> Result<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run(config: &Config) -> Result<()> {
|
||||
if config.vaults.is_empty() {
|
||||
bail!("no vaults yet — add one with `lunesync add <name> <folder> --remote <url>`");
|
||||
fn log_line(vault: &str, msg: &str) {
|
||||
println!("{} {vault:<10} {msg}", Local::now().format("%H:%M:%S"));
|
||||
}
|
||||
let label = config.device_label();
|
||||
let poll = config.poll_interval();
|
||||
let log = |vault: &str, msg: &str| println!("{} {vault:<10} {msg}", Local::now().format("%H:%M:%S"));
|
||||
std::thread::scope(|s| {
|
||||
for cfg in &config.vaults {
|
||||
let label = &label;
|
||||
s.spawn(move || {
|
||||
|
||||
/// Syncs every vault, picks up vaults added meanwhile, and checks the hub for new memberships.
|
||||
fn run() -> Result<()> {
|
||||
let mut started: HashSet<PathBuf> = HashSet::new();
|
||||
let mut hub_check = Instant::now();
|
||||
let mut hub_said = String::new();
|
||||
loop {
|
||||
match runner::run(cfg, label, poll, Timing::default(), &log) {
|
||||
let mut config = Config::load()?;
|
||||
config.use_hub_credentials();
|
||||
if config.vaults.is_empty() && config.hub.is_none() {
|
||||
bail!("no vaults yet — add one with `lunesync add <name> <folder> --remote <url>` or join a hub");
|
||||
}
|
||||
if config.hub.is_some() && Instant::now() >= hub_check {
|
||||
hub_check = Instant::now() + Duration::from_secs(30);
|
||||
match team::arrive(&mut config) {
|
||||
Ok(msgs) => {
|
||||
hub_said.clear();
|
||||
msgs.iter().for_each(|m| log_line("hub", m));
|
||||
}
|
||||
Err(e) => {
|
||||
let msg = format!("can't check the hub: {e:#}");
|
||||
if msg != hub_said {
|
||||
log_line("hub", &msg);
|
||||
hub_said = msg;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for cfg in &config.vaults {
|
||||
if !started.insert(cfg.path.clone()) {
|
||||
continue;
|
||||
}
|
||||
let (cfg, label, poll) = (cfg.clone(), config.device_label(), config.poll_interval());
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
match runner::run(&cfg, &label, poll, Timing::default(), &log_line) {
|
||||
Ok(()) => return,
|
||||
Err(e) if format!("{e}").contains("already being synced") => {
|
||||
log(&cfg.name, &format!("{e:#}"));
|
||||
log_line(&cfg.name, &format!("{e:#}"));
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
log(&cfg.name, &format!("stopped: {e:#} — retrying in 30 s"));
|
||||
std::thread::sleep(std::time::Duration::from_secs(30));
|
||||
log_line(&cfg.name, &format!("stopped: {e:#} — retrying in 30 s"));
|
||||
std::thread::sleep(Duration::from_secs(30));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
|
||||
/// After a one-off command, try to share right away; the runner picks it up otherwise.
|
||||
@@ -411,7 +533,10 @@ fn share_now(v: &Vault) {
|
||||
st.last_error = None;
|
||||
let _ = st.save(&v.git_dir);
|
||||
}
|
||||
Err(e) => println!("Not shared yet ({}); it will go out when the remote is reachable.", remote::describe_error(&e)),
|
||||
Err(e) if remote::is_offline(&e) => {
|
||||
println!("Not shared yet ({}); it will go out when the remote is reachable.", remote::describe_error(&e))
|
||||
}
|
||||
Err(e) => println!("Not shared: {}", remote::describe_error(&e)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,9 +550,12 @@ fn print_status(cfg: &VaultConfig, label: &str) {
|
||||
}
|
||||
};
|
||||
let st = SyncState::load(&v.git_dir);
|
||||
let read_only = v.role().is_some_and(|r| !lune_core::hub::can_edit(&r));
|
||||
let waiting = v.waiting_files().unwrap_or(0);
|
||||
let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" });
|
||||
let headline = match &st.last_error {
|
||||
None if read_only && waiting > 0 => format!("Up to date · {changes} kept here, not shared (you have read access)"),
|
||||
None if read_only => "Up to date (read access)".to_string(),
|
||||
Some(e) if e.starts_with("offline") => format!("Offline · waiting to sync · {changes}"),
|
||||
Some(e) => format!("Can't sync: {e}{}", if waiting > 0 { format!(" · {changes} waiting") } else { String::new() }),
|
||||
None if waiting > 0 => format!("Waiting to sync · {changes}"),
|
||||
|
||||
192
cli/src/team.rs
Normal file
192
cli/src/team.rs
Normal file
@@ -0,0 +1,192 @@
|
||||
//! Hub commands: joining, pairing devices, vaults on the hub, invites, grants, members and the access log.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use chrono::{Local, TimeZone};
|
||||
use lune_core::config::{Config, VaultConfig};
|
||||
use lune_core::hub::{self, HubLink};
|
||||
use lune_core::remote;
|
||||
use lune_core::state;
|
||||
use lune_core::vault::{self, Vault};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn link(config: &Config) -> Result<&HubLink> {
|
||||
config.hub.as_ref().context("this device isn't on a hub yet — `lunesync join <invite link>` or `lunesync login`")
|
||||
}
|
||||
|
||||
fn connect(config: &mut Config, url: String, w: hub::Welcome, label: &str, vaults_dir: Option<PathBuf>) -> Result<()> {
|
||||
config.hub = Some(HubLink { url, device_id: w.device_id, key: w.key });
|
||||
config.device_name = Some(label.to_string());
|
||||
if vaults_dir.is_some() {
|
||||
config.vaults_dir = vaults_dir;
|
||||
}
|
||||
config.save()?;
|
||||
config.use_hub_credentials();
|
||||
println!("Welcome, {}. This device is \"{label}\".", w.person);
|
||||
for msg in arrive(config)? {
|
||||
println!("{msg}");
|
||||
}
|
||||
println!("Keep it in sync with `lunesync run` (or `lunesync service install`).");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn join(config: &mut Config, invite: &str, label: &str, vaults_dir: Option<PathBuf>) -> Result<()> {
|
||||
if let Some(h) = &config.hub {
|
||||
bail!("this device is already on the hub at {}", h.url);
|
||||
}
|
||||
let (url, w) = hub::join(invite, label)?;
|
||||
connect(config, url, w, label, vaults_dir)
|
||||
}
|
||||
|
||||
pub fn login(config: &mut Config, url: &str, code: &str, label: &str, vaults_dir: Option<PathBuf>) -> Result<()> {
|
||||
if let Some(h) = &config.hub {
|
||||
bail!("this device is already on the hub at {}", h.url);
|
||||
}
|
||||
let w = hub::login(url, code, label)?;
|
||||
connect(config, url.trim_end_matches('/').to_string(), w, label, vaults_dir)
|
||||
}
|
||||
|
||||
pub fn pair(config: &Config) -> Result<()> {
|
||||
let h = link(config)?;
|
||||
let code = h.pair()?;
|
||||
println!("On the new device (code works once, for 10 minutes):\n");
|
||||
println!(" lunesync login --hub {} --code {code} --name <its label>", h.url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Brings this device in line with its hub memberships: new vaults arrive, same-named local vaults
|
||||
/// move onto the hub, roles are refreshed. Returns what happened, in plain words.
|
||||
pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
|
||||
let Some(h) = config.hub.clone() else { return Ok(vec![]) };
|
||||
let me = h.me()?;
|
||||
let label = config.device_label();
|
||||
let mut said = vec![];
|
||||
for hv in me.vaults {
|
||||
if let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(hv.id)) {
|
||||
let v = Vault::open(vc, &label)?;
|
||||
state::write_role(&v.git_dir, &hv.role)?;
|
||||
continue;
|
||||
}
|
||||
if let Some(vc) = config.vaults.iter_mut().find(|v| v.hub_vault.is_none() && v.name.eq_ignore_ascii_case(&hv.name)) {
|
||||
let v = Vault::open(vc, &label)?;
|
||||
let _op = state::op_lock(&v.git_dir)?;
|
||||
v.relink(&hv.git_url)?;
|
||||
state::write_role(&v.git_dir, &hv.role)?;
|
||||
v.join_unrelated()?;
|
||||
vc.remote = hv.git_url.clone();
|
||||
vc.hub_vault = Some(hv.id);
|
||||
config.save()?;
|
||||
said.push(format!("{} now syncs through the hub", hv.name));
|
||||
continue;
|
||||
}
|
||||
let path = config.vaults_dir().join(&hv.name);
|
||||
if path.exists() && std::fs::read_dir(&path)?.next().is_some() && !path.join(".git").exists() {
|
||||
said.push(format!("{} can't arrive: {} already has other files in it", hv.name, path.display()));
|
||||
continue;
|
||||
}
|
||||
let (mut cfg, _, err) = vault::add(&hv.name, &path, &hv.git_url, &label)?;
|
||||
cfg.hub_vault = Some(hv.id);
|
||||
state::write_role(&path.join(".git"), &hv.role)?;
|
||||
config.vaults.push(cfg);
|
||||
config.save()?;
|
||||
let note = if hub::can_edit(&hv.role) { String::new() } else { " (read access)".into() };
|
||||
said.push(format!("{} arrived in {}{note}", hv.name, path.display()));
|
||||
if let Some(e) = err {
|
||||
said.push(format!(" not synced yet: {e}"));
|
||||
}
|
||||
}
|
||||
Ok(said)
|
||||
}
|
||||
|
||||
pub fn vault_new(config: &mut Config, name: &str) -> Result<()> {
|
||||
let hv = link(config)?.create_vault(name)?;
|
||||
println!("Created {} on the hub.", hv.name);
|
||||
for msg in arrive(config)? {
|
||||
println!("{msg}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Moves a vault that syncs through a plain Git remote onto the hub.
|
||||
pub fn vault_upload(config: &mut Config, name: &str, fresh: bool) -> Result<()> {
|
||||
let h = link(config)?.clone();
|
||||
let label = config.device_label();
|
||||
let cfg: VaultConfig = config.find(name).with_context(|| format!("no vault named \"{name}\" on this device"))?.clone();
|
||||
if cfg.hub_vault.is_some() {
|
||||
bail!("{} already syncs through the hub", cfg.name);
|
||||
}
|
||||
let hv = match h.create_vault(&cfg.name) {
|
||||
Ok(hv) => hv,
|
||||
Err(e) if format!("{e}").contains("already a vault") => h
|
||||
.me()?
|
||||
.vaults
|
||||
.into_iter()
|
||||
.find(|v| v.name.eq_ignore_ascii_case(&cfg.name))
|
||||
.context("the hub has a vault with that name that you're not a member of")?,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let v = Vault::open(&cfg, &label)?;
|
||||
let _op = state::op_lock(&v.git_dir)?;
|
||||
v.save_changes(None, &Default::default())?;
|
||||
let before = if fresh { Some(v.fresh_start(&format!("Fresh start on the hub (earlier history stays on {label})"))?) } else { None };
|
||||
v.relink(&hv.git_url)?;
|
||||
state::write_role(&v.git_dir, &hv.role)?;
|
||||
let joined = v.join_unrelated();
|
||||
match joined.and_then(|_| v.sync()) {
|
||||
Ok(_) => {
|
||||
let vc = config.vaults.iter_mut().find(|x| x.path == cfg.path).unwrap();
|
||||
vc.remote = hv.git_url.clone();
|
||||
vc.hub_vault = Some(hv.id);
|
||||
config.save()?;
|
||||
println!("{} now syncs through the hub{}.", cfg.name, if fresh { ", starting fresh" } else { ", history included" });
|
||||
println!("Other devices with this vault: `lunesync pair` here, then `lunesync login …` there — it moves over on its own.");
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
v.relink(&cfg.remote)?;
|
||||
if let Some(id) = before {
|
||||
v.reset_history(id)?;
|
||||
}
|
||||
let why = remote::describe_error(&e);
|
||||
if why.contains("possible") && !fresh {
|
||||
bail!("{why}\nThe old history has a secret in it. `lunesync vault upload {name} --fresh` uploads just the current notes.");
|
||||
}
|
||||
bail!("{why}\n{} keeps syncing where it did before.", cfg.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn invite(config: &Config, person: &str, vaults: &[String]) -> Result<()> {
|
||||
let grants: Vec<(String, String)> = vaults
|
||||
.iter()
|
||||
.map(|v| match v.rsplit_once(':') {
|
||||
Some((name, role)) => (name.to_string(), role.to_string()),
|
||||
None => (v.clone(), "edit".to_string()),
|
||||
})
|
||||
.collect();
|
||||
let link = link(config)?.invite(person, &grants)?;
|
||||
println!("Send this to {person}. It works once, for 7 days:\n");
|
||||
println!(" lunesync join {link} --name <their device>");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn grant(config: &Config, person: &str, vault: &str, role: &str) -> Result<()> {
|
||||
link(config)?.grant(person, vault, role)?;
|
||||
println!("{person} has {role} access to {vault}. It arrives on their devices within a minute.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn members(config: &Config, vault: &str) -> Result<()> {
|
||||
for m in link(config)?.members(vault)? {
|
||||
let devices = if m.devices.is_empty() { "no devices".to_string() } else { m.devices.join(", ") };
|
||||
println!(" {:<16} {:<7} {devices}", m.person, m.role);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn log(config: &Config, count: usize) -> Result<()> {
|
||||
for e in link(config)?.log(count)?.into_iter().rev() {
|
||||
let at = Local.timestamp_opt(e.at, 0).single().map(|t| t.format("%Y-%m-%d %H:%M").to_string()).unwrap_or_default();
|
||||
println!("{at} {:<22} {:<15} {}", e.actor, e.action, e.detail);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
16
compose.yaml
Normal file
16
compose.yaml
Normal file
@@ -0,0 +1,16 @@
|
||||
services:
|
||||
hub:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
# The address people and devices use to reach the hub (behind your TLS proxy).
|
||||
LUNE_HUB_URL: https://hub.example.com
|
||||
# Name of the team owner; their one-time join link is printed in the log on first start.
|
||||
LUNE_OWNER_NAME: Sen
|
||||
volumes:
|
||||
- hub-data:/data
|
||||
|
||||
volumes:
|
||||
hub-data:
|
||||
@@ -5,6 +5,7 @@ edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
base64 = "0.23.1"
|
||||
chrono = "0.4.45"
|
||||
dirs = "7.0.0"
|
||||
gethostname = "1.1.0"
|
||||
@@ -14,6 +15,7 @@ regex = "1.13.1"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
toml = "1.1.8"
|
||||
ureq = { version = "3.5.0", features = ["json"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.27.0"
|
||||
|
||||
@@ -12,6 +12,12 @@ pub struct Config {
|
||||
/// How often to check the remote for new changes, in seconds.
|
||||
#[serde(default)]
|
||||
pub poll_seconds: Option<u64>,
|
||||
/// Where vaults from the hub are placed (default ~/Vaults).
|
||||
#[serde(default)]
|
||||
pub vaults_dir: Option<PathBuf>,
|
||||
/// This device's hub sign-in, once it has joined or logged in.
|
||||
#[serde(default)]
|
||||
pub hub: Option<crate::hub::HubLink>,
|
||||
#[serde(default, rename = "vault")]
|
||||
pub vaults: Vec<VaultConfig>,
|
||||
}
|
||||
@@ -22,6 +28,9 @@ pub struct VaultConfig {
|
||||
pub path: PathBuf,
|
||||
pub remote: String,
|
||||
pub branch: String,
|
||||
/// The hub's id for this vault, when it syncs through the hub.
|
||||
#[serde(default)]
|
||||
pub hub_vault: Option<i64>,
|
||||
}
|
||||
|
||||
/// Directory holding `config.toml`. `LUNE_HOME` overrides it (handy for running two devices on one machine).
|
||||
@@ -52,10 +61,29 @@ impl Config {
|
||||
std::fs::create_dir_all(path.parent().unwrap())?;
|
||||
let tmp = path.with_extension("toml.tmp");
|
||||
std::fs::write(&tmp, toml::to_string_pretty(self)?)?;
|
||||
// Holds the device key: owner-only.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))?;
|
||||
}
|
||||
std::fs::rename(&tmp, &path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn vaults_dir(&self) -> PathBuf {
|
||||
self.vaults_dir
|
||||
.clone()
|
||||
.unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join("Vaults"))
|
||||
}
|
||||
|
||||
/// Makes the hub's device key available to Git requests in this process.
|
||||
pub fn use_hub_credentials(&self) {
|
||||
if let Some(h) = &self.hub {
|
||||
crate::remote::set_hub(h.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn device_label(&self) -> String {
|
||||
self.device_name.clone().unwrap_or_else(default_device_name)
|
||||
}
|
||||
|
||||
159
core/src/hub.rs
Normal file
159
core/src/hub.rs
Normal file
@@ -0,0 +1,159 @@
|
||||
//! Talking to the hub's API: joining, pairing, and finding out which vaults this device should have.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use base64::Engine;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::time::Duration;
|
||||
|
||||
/// This device's link to a hub, stored in the config file.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HubLink {
|
||||
pub url: String,
|
||||
pub device_id: String,
|
||||
pub key: String,
|
||||
}
|
||||
|
||||
/// What `join` and `login` hand back.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Welcome {
|
||||
pub person: String,
|
||||
pub device_id: String,
|
||||
pub key: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Me {
|
||||
pub person: String,
|
||||
pub owner: bool,
|
||||
pub device_label: String,
|
||||
pub vaults: Vec<HubVault>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct HubVault {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub role: String,
|
||||
pub git_url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Member {
|
||||
pub person: String,
|
||||
pub role: String,
|
||||
pub devices: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct LogEntry {
|
||||
pub at: i64,
|
||||
pub actor: String,
|
||||
pub action: String,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
fn agent() -> ureq::Agent {
|
||||
ureq::Agent::config_builder()
|
||||
.http_status_as_error(false)
|
||||
.timeout_global(Some(Duration::from_secs(30)))
|
||||
.build()
|
||||
.into()
|
||||
}
|
||||
|
||||
fn base(url: &str) -> String {
|
||||
url.trim_end_matches('/').to_string()
|
||||
}
|
||||
|
||||
fn finish<T: DeserializeOwned>(res: Result<ureq::http::Response<ureq::Body>, ureq::Error>, url: &str) -> Result<T> {
|
||||
let mut res = res.map_err(|e| anyhow::anyhow!("can't reach the hub at {url}: {e}"))?;
|
||||
let status = res.status();
|
||||
let body: Value = res.body_mut().read_json().unwrap_or(Value::Null);
|
||||
if !status.is_success() {
|
||||
let msg = body.get("error").and_then(Value::as_str).unwrap_or("unexpected answer");
|
||||
bail!("the hub said: {msg}");
|
||||
}
|
||||
serde_json::from_value(body).context("the hub's answer didn't make sense")
|
||||
}
|
||||
|
||||
/// Accepts an invite link (`https://hub/join/<token>`), creating the person's account and this device.
|
||||
pub fn join(link: &str, label: &str) -> Result<(String, Welcome)> {
|
||||
let (url, token) = link.rsplit_once("/join/").context("that doesn't look like an invite link")?;
|
||||
let url = base(url);
|
||||
let res = agent().post(format!("{url}/api/join")).send_json(json!({"token": token, "device_label": label}));
|
||||
Ok((url.clone(), finish(res, &url)?))
|
||||
}
|
||||
|
||||
/// Signs this device in with a pairing code from another of the person's devices.
|
||||
pub fn login(url: &str, code: &str, label: &str) -> Result<Welcome> {
|
||||
let url = base(url);
|
||||
let res = agent().post(format!("{url}/api/login")).send_json(json!({"code": code, "device_label": label}));
|
||||
finish(res, &url)
|
||||
}
|
||||
|
||||
impl HubLink {
|
||||
fn auth(&self) -> String {
|
||||
let raw = format!("{}:{}", self.device_id, self.key);
|
||||
format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(raw))
|
||||
}
|
||||
|
||||
fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
|
||||
let res = agent().get(format!("{}{path}", self.url)).header("Authorization", self.auth()).call();
|
||||
finish(res, &self.url)
|
||||
}
|
||||
|
||||
fn post<T: DeserializeOwned>(&self, path: &str, body: Value) -> Result<T> {
|
||||
let res = agent().post(format!("{}{path}", self.url)).header("Authorization", self.auth()).send_json(body);
|
||||
finish(res, &self.url)
|
||||
}
|
||||
|
||||
pub fn me(&self) -> Result<Me> {
|
||||
self.get("/api/me")
|
||||
}
|
||||
|
||||
/// A short code another of this person's devices can log in with.
|
||||
pub fn pair(&self) -> Result<String> {
|
||||
let v: Value = self.post("/api/pair", json!({}))?;
|
||||
Ok(v["code"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
pub fn set_label(&self, label: &str) -> Result<()> {
|
||||
let _: Value = self.post("/api/device/label", json!({ "label": label }))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_vault(&self, name: &str) -> Result<HubVault> {
|
||||
self.post("/api/vaults", json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// One-time link for `person` with the given (vault, role) grants.
|
||||
pub fn invite(&self, person: &str, grants: &[(String, String)]) -> Result<String> {
|
||||
let grants: Vec<Value> = grants.iter().map(|(v, r)| json!({"vault": v, "role": r})).collect();
|
||||
let v: Value = self.post("/api/invites", json!({"person": person, "grants": grants}))?;
|
||||
Ok(v["link"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
pub fn grant(&self, person: &str, vault: &str, role: &str) -> Result<()> {
|
||||
let _: Value = self.post("/api/grants", json!({"person": person, "vault": vault, "role": role}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn members(&self, vault: &str) -> Result<Vec<Member>> {
|
||||
self.post("/api/members", json!({ "vault": vault }))
|
||||
}
|
||||
|
||||
pub fn log(&self, count: usize) -> Result<Vec<LogEntry>> {
|
||||
self.get(&format!("/api/log?count={count}"))
|
||||
}
|
||||
|
||||
pub fn not_a_secret(&self, vault_id: i64, fingerprint: &str) -> Result<()> {
|
||||
let _: Value = self.post("/api/not-secrets", json!({"vault_id": vault_id, "fingerprint": fingerprint}))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `role` allowed to share changes?
|
||||
pub fn can_edit(role: &str) -> bool {
|
||||
role == "edit" || role == "manage"
|
||||
}
|
||||
@@ -4,6 +4,7 @@ pub use git2;
|
||||
|
||||
pub mod config;
|
||||
pub mod guard;
|
||||
pub mod hub;
|
||||
pub mod names;
|
||||
pub mod remote;
|
||||
pub mod runner;
|
||||
|
||||
@@ -2,6 +2,20 @@
|
||||
|
||||
use git2::{Cred, CredentialType, ErrorClass, ErrorCode, RemoteCallbacks};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::RwLock;
|
||||
|
||||
static HUB: RwLock<Option<crate::hub::HubLink>> = RwLock::new(None);
|
||||
|
||||
/// Git requests to this hub sign in with the device key.
|
||||
pub fn set_hub(link: crate::hub::HubLink) {
|
||||
*HUB.write().unwrap() = Some(link);
|
||||
}
|
||||
|
||||
fn hub_credentials(url: &str) -> Option<(String, String)> {
|
||||
let hub = HUB.read().unwrap();
|
||||
let h = hub.as_ref()?;
|
||||
url.starts_with(&h.url).then(|| (h.device_id.clone(), h.key.clone()))
|
||||
}
|
||||
|
||||
pub fn callbacks<'a>() -> RemoteCallbacks<'a> {
|
||||
let mut tried_agent = false;
|
||||
@@ -26,6 +40,9 @@ pub fn callbacks<'a>() -> RemoteCallbacks<'a> {
|
||||
}
|
||||
if allowed.contains(CredentialType::USER_PASS_PLAINTEXT) && !tried_helper {
|
||||
tried_helper = true;
|
||||
if let Some((user, key)) = hub_credentials(url) {
|
||||
return Cred::userpass_plaintext(&user, &key);
|
||||
}
|
||||
if let Ok(config) = git2::Config::open_default() {
|
||||
return Cred::credential_helper(&config, url, username);
|
||||
}
|
||||
|
||||
@@ -92,6 +92,7 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
|
||||
let mut backoff = poll;
|
||||
let mut was_waiting = false;
|
||||
let mut was_holding = false;
|
||||
let mut was_read_only = false;
|
||||
let mut announced: HashSet<String> = HashSet::new();
|
||||
loop {
|
||||
let first = rx.recv_timeout(Duration::from_millis(250));
|
||||
@@ -168,6 +169,10 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
|
||||
say("not sharing anything from this device while a big change is held");
|
||||
}
|
||||
was_holding = report.holding;
|
||||
if report.read_only && !was_read_only {
|
||||
say("your changes here aren't shared — you have read access to this vault");
|
||||
}
|
||||
was_read_only = report.read_only;
|
||||
if report.waiting_for_local_edits && !was_waiting {
|
||||
say("new changes are waiting until your current edits settle");
|
||||
}
|
||||
|
||||
@@ -37,6 +37,14 @@ pub fn read_marker(git_dir: &Path) -> Option<Marker> {
|
||||
toml::from_str(&text).ok()
|
||||
}
|
||||
|
||||
/// This device's role in a hub vault, refreshed from the hub by the runner.
|
||||
pub fn write_role(git_dir: &Path, role: &str) -> Result<()> {
|
||||
let dir = lune_dir(git_dir);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
std::fs::write(dir.join("role"), role)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Outcome of the last sync attempt, written by whoever ran it and read by `status`.
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
pub struct SyncState {
|
||||
|
||||
@@ -37,6 +37,7 @@ pub struct Vault {
|
||||
pub branch: String,
|
||||
pub label: String,
|
||||
repo: Repository,
|
||||
last_refusal: RefCell<Option<String>>,
|
||||
}
|
||||
|
||||
/// A burst of edits saved as one history entry.
|
||||
@@ -75,6 +76,8 @@ pub struct SyncReport {
|
||||
pub set_aside: Vec<(String, String)>,
|
||||
/// A big change is held here, so nothing from this device was shared.
|
||||
pub holding: bool,
|
||||
/// Local changes not shared because this device's person only has read access.
|
||||
pub read_only: bool,
|
||||
}
|
||||
|
||||
impl Vault {
|
||||
@@ -90,6 +93,7 @@ impl Vault {
|
||||
branch: cfg.branch.clone(),
|
||||
label: label.to_string(),
|
||||
repo,
|
||||
last_refusal: RefCell::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -273,6 +277,48 @@ impl Vault {
|
||||
Ok(kept_both)
|
||||
}
|
||||
|
||||
/// Points the vault at a new remote (e.g. moving onto the hub). Its next sync shares everything there.
|
||||
pub fn relink(&self, url: &str) -> Result<()> {
|
||||
self.repo.remote_set_url("origin", url)?;
|
||||
if let Ok(mut r) = self.repo.find_reference(&self.remote_ref()) {
|
||||
r.delete()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts history over with just the current notes (the old history stays only on this device).
|
||||
/// Returns where history was, to go back if needed.
|
||||
pub fn fresh_start(&self, message: &str) -> Result<Oid> {
|
||||
let head = self.head_commit()?.context("the vault is empty")?;
|
||||
let sig = self.signature()?;
|
||||
let id = self.repo.commit(None, &sig, &sig, message, &head.tree()?, &[])?;
|
||||
self.repo.reference(&self.branch_ref(), id, true, "lune: fresh start")?;
|
||||
Ok(head.id())
|
||||
}
|
||||
|
||||
pub fn reset_history(&self, id: Oid) -> Result<()> {
|
||||
self.repo.reference(&self.branch_ref(), id, true, "lune: put back")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// After moving onto a remote whose history is unrelated (e.g. a fresh start on the hub), combine the
|
||||
/// notes as one new entry on top of the remote's history, so this device's old history stays here.
|
||||
pub fn join_unrelated(&self) -> Result<bool> {
|
||||
self.fetch()?;
|
||||
let (Some(local), Some(remote)) = (self.head_commit()?, self.remote_commit()?) else { return Ok(false) };
|
||||
if self.repo.merge_base(local.id(), remote.id()).is_ok() {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut index = self.repo.merge_commits(&local, &remote, None)?;
|
||||
let mut kept = vec![];
|
||||
self.keep_both(&mut index, &mut kept)?;
|
||||
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
|
||||
let sig = self.signature()?;
|
||||
let id = self.repo.commit(None, &sig, &sig, &format!("Joined the shared copy from {}", self.label), &tree, &[&remote])?;
|
||||
self.move_to(id)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A named checkpoint (S3). If everything is already saved, records the name on its own.
|
||||
pub fn checkpoint(&self, message: &str) -> Result<Oid> {
|
||||
if let Some(saved) = self.save_changes(Some(message), &HashSet::new())? {
|
||||
@@ -293,10 +339,16 @@ impl Vault {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pushes local history. Returns false if the remote moved on meanwhile (fetch and try again).
|
||||
/// This device's role in the vault, as last told by the hub. None for plain Git remotes.
|
||||
pub fn role(&self) -> Option<String> {
|
||||
std::fs::read_to_string(state::lune_dir(&self.git_dir).join("role")).ok().map(|s| s.trim().to_string())
|
||||
}
|
||||
|
||||
/// Pushes local history. Returns false if it was refused (the remote moved on, or said no).
|
||||
fn push(&self) -> Result<bool> {
|
||||
let mut remote = self.repo.find_remote("origin")?;
|
||||
let rejected = RefCell::new(None::<String>);
|
||||
let said = RefCell::new(String::new());
|
||||
let mut cb = remote::callbacks();
|
||||
cb.push_update_reference(|_, status| {
|
||||
if let Some(s) = status {
|
||||
@@ -304,6 +356,10 @@ impl Vault {
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
cb.sideband_progress(|text| {
|
||||
said.borrow_mut().push_str(&String::from_utf8_lossy(text));
|
||||
true
|
||||
});
|
||||
let mut opts = PushOptions::new();
|
||||
opts.remote_callbacks(cb);
|
||||
let spec = format!("{0}:{0}", self.branch_ref());
|
||||
@@ -314,7 +370,9 @@ impl Vault {
|
||||
return Err(e.into());
|
||||
}
|
||||
drop(opts);
|
||||
if rejected.borrow().is_some() {
|
||||
if let Some(status) = rejected.borrow().clone() {
|
||||
let said: Vec<String> = said.borrow().lines().filter(|l| l.contains("lune:")).map(|l| l.replace("lune:", "").trim().to_string()).collect();
|
||||
*self.last_refusal.borrow_mut() = Some(if said.is_empty() { status } else { said.join("; ") });
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(head) = self.head_commit()? {
|
||||
@@ -373,10 +431,21 @@ impl Vault {
|
||||
report.holding = true;
|
||||
return Ok(report);
|
||||
}
|
||||
if self.role().is_some_and(|r| !crate::hub::can_edit(&r)) {
|
||||
report.read_only = true;
|
||||
return Ok(report);
|
||||
}
|
||||
if self.push()? {
|
||||
report.shared += ahead;
|
||||
return Ok(report);
|
||||
}
|
||||
// Refused without the remote having moved on: the remote said no, so say why.
|
||||
let before = self.remote_commit()?.map(|c| c.id());
|
||||
self.fetch()?;
|
||||
if self.remote_commit()?.map(|c| c.id()) == before {
|
||||
let why = self.last_refusal.borrow().clone().unwrap_or_else(|| "no reason given".into());
|
||||
bail!("the hub refused these changes: {why}");
|
||||
}
|
||||
}
|
||||
bail!("the remote kept changing while sharing; will try again shortly")
|
||||
}
|
||||
@@ -672,7 +741,7 @@ pub fn add(name: &str, path: &Path, remote_url: &str, label: &str) -> Result<(Va
|
||||
state::write_marker(&git_dir, name, !existed)?;
|
||||
drop(repo);
|
||||
|
||||
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch };
|
||||
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch, hub_vault: None };
|
||||
let vault = Vault::open(&cfg, label)?;
|
||||
let _op = state::op_lock(&git_dir)?;
|
||||
vault.save_changes(Some(&format!("Added the vault on {label}")), &HashSet::new())?;
|
||||
|
||||
61
docs/SPEC.md
61
docs/SPEC.md
@@ -153,48 +153,59 @@ Only the current milestone gets detailed below. The next one is detailed when th
|
||||
|
||||
---
|
||||
|
||||
## 6. Milestone 2 — It catches my mistakes
|
||||
## 6. Milestone 3 — Shared with my team
|
||||
|
||||
Milestone 1 (sync through a plain Git remote, `lunesync` CLI) is built; its detail lives in the code and tests now.
|
||||
Milestones 1–2 (sync over a Git remote, secret check, runaway guard) are built; their detail lives in the code and tests now.
|
||||
|
||||
### Goal
|
||||
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.
|
||||
A hub Sen runs in Docker replaces the plain Git remote. People get in by invite, add their own devices by pairing code, and every vault they're a member of arrives on its own. Roles are enforced by the hub, not by trust.
|
||||
|
||||
### What Sen does
|
||||
```bash
|
||||
lunesync held # what's held back and why
|
||||
lunesync held pointer <file> "search prod-deploy in Secrets Manager" # replace the secret with a pointer
|
||||
lunesync held not-secret <file> [--line N] # it isn't a secret; remembered for that exact line
|
||||
lunesync held share # the big change was intended: share it anyway
|
||||
lunesync held undo # it wasn't: bring everything back
|
||||
lunesync tidy show <file> # compare the two kept versions before picking one
|
||||
# on the VM
|
||||
docker compose up -d # hub; first start prints the owner invite link in the log
|
||||
# on the laptop
|
||||
lunesync join https://hub.example/join/… --name Codex
|
||||
lunesync vault upload DevOps # the M1 vault moves onto the hub, history kept
|
||||
lunesync invite Alice --vault DevOps:edit # one-time link for Alice
|
||||
lunesync pair # prints a ready-to-paste login line with a short code
|
||||
# on the VPS
|
||||
lunesync login --hub https://hub.example --code K7QD-4MXA --name Hermes
|
||||
lunesync run # DevOps arrives in ~/Vaults/DevOps
|
||||
# anytime
|
||||
lunesync vault new Notes | grant Alice Notes --role read | members DevOps | hub log
|
||||
```
|
||||
`status` and the `run` log say when something is held.
|
||||
Alice runs `lunesync join <link> --name "Alice laptop"`, then `lunesync run`: DevOps arrives.
|
||||
|
||||
### Behavior
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **Tidy** gets `show`: a line-by-line comparison of the note and its kept copy.
|
||||
- **Hub** = one container: an HTTP API plus Git over HTTPS for vaults, SQLite and bare repos on one volume (`/data`). It listens on plain HTTP; TLS comes from Sen's reverse proxy. `LUNE_HUB_URL` is the public address used in links.
|
||||
- **Accounts, memberships, devices (A1)**. The hub has one team; the first account is its **owner**. Owners create vaults; owners and a vault's **Manage** members invite and grant for that vault.
|
||||
- **Invites (A4)**: one per person, a one-time link that names the person and the vaults + roles they get, valid 7 days. Accepting it creates the account and its first device.
|
||||
- **Pairing**: a signed-in device asks for a code (8 characters, 10 minutes, single use); a new device logs in with it and gets its own key. Devices never share keys. A device key is shown once and stored in the device's config file (owner-only permissions); the hub stores only its hash.
|
||||
- **Vaults arrive**: while `run` is going, the device checks the hub every 30 s and adds any vault it's now a member of, under `~/Vaults/<name>` (`--vaults-dir` to change). Vaults from M1 with a plain Git remote keep working.
|
||||
- **Roles (A3)** are enforced by the hub on every Git request: Read can only receive changes. A Read member's own edits stay local; `status` says "not shared — you have read access".
|
||||
- **Device labels (S7)**: chosen at join/login, renamed with `lunesync device name` (updates the hub too). History entries carry the label.
|
||||
- **Hub secret check (P3)**: every incoming change is scanned with the same rules, commit by commit, before the hub accepts it. A hit is refused with the note, line and rule. "Not a secret" on a device is also sent to the hub for that vault.
|
||||
- **Upload** keeps history. If old history contains a secret the hub refuses it; `vault upload --fresh` uploads only the current notes as a fresh start (the old history stays on that device only).
|
||||
- **Access log (A10)**: the hub records invites created and accepted, devices paired and renamed, vaults created, memberships granted, and refused changes. `lunesync hub log` (owner).
|
||||
|
||||
### Acceptance — Sen acts this out
|
||||
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. A line that only looks like a secret: `held not-secret` releases it and it's never flagged again on that device.
|
||||
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. A deliberate big cleanup: `held share` sends it.
|
||||
5. Edit the same lines on both machines, `tidy show`, then `tidy keep`.
|
||||
1. `docker compose up -d` on a fresh VM; the owner link from the log works once and only once.
|
||||
2. Upload the real DevOps vault; history and every file survive (checksums).
|
||||
3. Pair the VPS with a code as "Hermes"; DevOps arrives; its edits show up labeled Hermes.
|
||||
4. Invite a teammate with Edit on DevOps; they join, the vault arrives, their edits reach Sen.
|
||||
5. Grant someone Read: the vault arrives, their edits stay local with the note, the hub refuses them even if pushed by hand.
|
||||
6. Edit a note with a fake key directly in a hub vault from outside the app (plain `git push` with a device key): refused.
|
||||
|
||||
### Out of scope for M2
|
||||
The hub-side check (P3) and anything with accounts: M3.
|
||||
### Out of scope for M3
|
||||
Removing people or devices, handovers (M4). Any web UI (M5). Client updates from the hub (M7).
|
||||
|
||||
## 7. Open questions
|
||||
- Hub storage for repos: plain bare repos on disk vs. something like Gitea underneath (decide at M3).
|
||||
None open.
|
||||
|
||||
## 8. Decision changes
|
||||
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-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)
|
||||
- 2026-10-29 — Hub storage (open question): plain bare repos on the hub's volume served by the hub itself (device key + role check, then Git's own HTTP backend); no Gitea underneath. (Sen)
|
||||
|
||||
20
hub/Cargo.toml
Normal file
20
hub/Cargo.toml
Normal file
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "lunehub"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
axum = "0.8.9"
|
||||
base64 = "0.23.1"
|
||||
chrono = "0.4.45"
|
||||
getrandom = "0.4.3"
|
||||
lune-core = { version = "0.1.0", path = "../core" }
|
||||
rusqlite = { version = "0.41.0", features = ["bundled"] }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
sha2 = "0.11.1"
|
||||
tokio = { version = "1.54.1", features = ["full"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.27.0"
|
||||
400
hub/src/api.rs
Normal file
400
hub/src/api.rs
Normal file
@@ -0,0 +1,400 @@
|
||||
//! The hub's JSON API: joining, pairing, vaults, invites, grants, members and the access log.
|
||||
|
||||
use crate::db::{self, Caller};
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use base64::Engine;
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub struct Hub {
|
||||
pub db: Mutex<Connection>,
|
||||
pub data: PathBuf,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
pub type Shared = Arc<Hub>;
|
||||
|
||||
impl Hub {
|
||||
pub fn repo_path(&self, vault_id: i64) -> PathBuf {
|
||||
self.data.join("repos").join(format!("{vault_id}.git"))
|
||||
}
|
||||
|
||||
pub fn git_url(&self, vault_id: i64) -> String {
|
||||
format!("{}/git/{vault_id}.git", self.url)
|
||||
}
|
||||
}
|
||||
|
||||
/// An error with the plain-words message the CLI shows.
|
||||
pub struct ApiError(pub StatusCode, pub String);
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
(self.0, Json(json!({ "error": self.1 }))).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<anyhow::Error> for ApiError {
|
||||
fn from(e: anyhow::Error) -> Self {
|
||||
eprintln!("hub error: {e:#}");
|
||||
ApiError(StatusCode::INTERNAL_SERVER_ERROR, "something went wrong on the hub".into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<rusqlite::Error> for ApiError {
|
||||
fn from(e: rusqlite::Error) -> Self {
|
||||
anyhow::Error::from(e).into()
|
||||
}
|
||||
}
|
||||
|
||||
type ApiResult = Result<Json<Value>, ApiError>;
|
||||
|
||||
fn bad(msg: impl Into<String>) -> ApiError {
|
||||
ApiError(StatusCode::BAD_REQUEST, msg.into())
|
||||
}
|
||||
|
||||
fn denied(msg: impl Into<String>) -> ApiError {
|
||||
ApiError(StatusCode::FORBIDDEN, msg.into())
|
||||
}
|
||||
|
||||
/// Device id and key from a Basic `Authorization` header.
|
||||
pub fn credentials(headers: &HeaderMap) -> Option<(String, String)> {
|
||||
let value = headers.get("authorization")?.to_str().ok()?;
|
||||
let encoded = value.strip_prefix("Basic ")?;
|
||||
let raw = base64::engine::general_purpose::STANDARD.decode(encoded).ok()?;
|
||||
let (id, key) = std::str::from_utf8(&raw).ok()?.split_once(':')?;
|
||||
Some((id.to_string(), key.to_string()))
|
||||
}
|
||||
|
||||
pub fn authenticate(hub: &Hub, headers: &HeaderMap) -> Result<Caller, ApiError> {
|
||||
let unknown = || ApiError(StatusCode::UNAUTHORIZED, "this device isn't signed in to the hub".into());
|
||||
let (id, key) = credentials(headers).ok_or_else(unknown)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
db::caller(&conn, &id, &key)?.ok_or_else(unknown)
|
||||
}
|
||||
|
||||
const ROLES: [&str; 3] = ["read", "edit", "manage"];
|
||||
|
||||
fn check_label(label: &str) -> Result<String, ApiError> {
|
||||
let label = label.trim();
|
||||
if label.is_empty() || label.len() > 40 {
|
||||
return Err(bad("a device label needs 1–40 characters"));
|
||||
}
|
||||
Ok(label.to_string())
|
||||
}
|
||||
|
||||
/// Owners can manage every vault; others need the Manage role on it.
|
||||
fn can_manage(conn: &Connection, caller: &Caller, vault_id: i64) -> Result<bool, ApiError> {
|
||||
Ok(caller.owner || db::role(conn, caller.account_id, vault_id)?.as_deref() == Some("manage"))
|
||||
}
|
||||
|
||||
fn welcome(person: &str, device_id: String, key: String) -> ApiResult {
|
||||
Ok(Json(json!({ "person": person, "device_id": device_id, "key": key })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct JoinReq {
|
||||
token: String,
|
||||
device_label: String,
|
||||
}
|
||||
|
||||
pub async fn join(State(hub): State<Shared>, Json(req): Json<JoinReq>) -> ApiResult {
|
||||
let label = check_label(&req.device_label)?;
|
||||
let mut conn = hub.db.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
let invite: Option<(String, bool, String, i64, Option<i64>)> = tx
|
||||
.query_row(
|
||||
"SELECT person, owner, grants, expires, used FROM invites WHERE token_hash = ?1",
|
||||
[db::hash(&req.token)],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((person, owner, grants, expires, used)) = invite else {
|
||||
return Err(denied("that invite link isn't valid"));
|
||||
};
|
||||
if used.is_some() {
|
||||
return Err(denied("that invite link was already used"));
|
||||
}
|
||||
if expires < db::now() {
|
||||
return Err(denied("that invite link has expired — ask for a new one"));
|
||||
}
|
||||
let taken: bool = tx.query_row("SELECT COUNT(*) > 0 FROM accounts WHERE name = ?1", [&person], |r| r.get(0))?;
|
||||
if taken {
|
||||
return Err(denied(format!("{person} already has an account — pair a device instead")));
|
||||
}
|
||||
tx.execute("INSERT INTO accounts (name, owner, created) VALUES (?1, ?2, ?3)", params![person, owner, db::now()])?;
|
||||
let account_id = tx.last_insert_rowid();
|
||||
let grants: Vec<(i64, String)> = serde_json::from_str(&grants).map_err(anyhow::Error::from)?;
|
||||
let mut granted = vec![];
|
||||
for (vault_id, role) in &grants {
|
||||
db::grant(&tx, account_id, *vault_id, role)?;
|
||||
let name: Option<String> = tx.query_row("SELECT name FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0)).optional()?;
|
||||
granted.push(format!("{}: {role}", name.unwrap_or_default()));
|
||||
}
|
||||
tx.execute("UPDATE invites SET used = ?1 WHERE token_hash = ?2", params![db::now(), db::hash(&req.token)])?;
|
||||
let (device_id, key) = db::new_device(&tx, account_id, &label)?;
|
||||
let who = format!("{person} ({label})");
|
||||
let what = if owner { "as team owner".to_string() } else if granted.is_empty() { "with no vaults".into() } else { granted.join(", ") };
|
||||
db::log(&tx, &who, "joined", &format!("accepted the invite {what}"))?;
|
||||
db::log(&tx, &who, "device added", &format!("{label} (first device)"))?;
|
||||
tx.commit()?;
|
||||
welcome(&person, device_id, key)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LoginReq {
|
||||
code: String,
|
||||
device_label: String,
|
||||
}
|
||||
|
||||
pub async fn login(State(hub): State<Shared>, Json(req): Json<LoginReq>) -> ApiResult {
|
||||
let label = check_label(&req.device_label)?;
|
||||
let code: String = req.code.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_uppercase();
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let found: Option<(i64, i64, Option<i64>)> = conn
|
||||
.query_row(
|
||||
"SELECT account_id, expires, used FROM pair_codes WHERE code_hash = ?1",
|
||||
[db::hash(&code)],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let account_id = match found {
|
||||
Some((a, expires, None)) if expires >= db::now() => a,
|
||||
Some((_, _, Some(_))) => return Err(denied("that code was already used — make a new one with `lunesync pair`")),
|
||||
Some(_) => return Err(denied("that code has expired — make a new one with `lunesync pair`")),
|
||||
None => return Err(denied("that code isn't valid")),
|
||||
};
|
||||
conn.execute("UPDATE pair_codes SET used = ?1 WHERE code_hash = ?2", params![db::now(), db::hash(&code)])?;
|
||||
let person: String = conn.query_row("SELECT name FROM accounts WHERE id = ?1", [account_id], |r| r.get(0))?;
|
||||
let (device_id, key) = db::new_device(&conn, account_id, &label)?;
|
||||
db::log(&conn, &format!("{person} ({label})"), "device added", &format!("{label} paired with a code"))?;
|
||||
welcome(&person, device_id, key)
|
||||
}
|
||||
|
||||
pub async fn pair(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let code = db::token(8);
|
||||
let conn = hub.db.lock().unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO pair_codes (code_hash, account_id, expires) VALUES (?1, ?2, ?3)",
|
||||
params![db::hash(&code), caller.account_id, db::now() + 600],
|
||||
)?;
|
||||
db::log(&conn, &caller.who(), "pairing code", "made a code to add a device")?;
|
||||
Ok(Json(json!({ "code": format!("{}-{}", &code[..4], &code[4..]) })))
|
||||
}
|
||||
|
||||
pub async fn me(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT v.id, v.name, m.role FROM memberships m JOIN vaults v ON v.id = m.vault_id WHERE m.account_id = ?1 ORDER BY v.name",
|
||||
)?;
|
||||
let vaults: Vec<Value> = stmt
|
||||
.query_map([caller.account_id], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.map(|(id, name, role)| json!({ "id": id, "name": name, "role": role, "git_url": hub.git_url(id) }))
|
||||
.collect();
|
||||
Ok(Json(json!({
|
||||
"person": caller.person, "owner": caller.owner, "device_label": caller.device_label, "vaults": vaults
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LabelReq {
|
||||
label: String,
|
||||
}
|
||||
|
||||
pub async fn label(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<LabelReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let label = check_label(&req.label)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
conn.execute("UPDATE devices SET label = ?1 WHERE id = ?2", params![label, caller.device_id])?;
|
||||
db::log(&conn, &caller.who(), "device renamed", &format!("{} → {label}", caller.device_label))?;
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct VaultReq {
|
||||
name: String,
|
||||
}
|
||||
|
||||
pub async fn create_vault(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<VaultReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
if !caller.owner {
|
||||
return Err(denied("only the team owner can create vaults"));
|
||||
}
|
||||
let name = req.name.trim();
|
||||
let ok = !name.is_empty()
|
||||
&& name.len() <= 60
|
||||
&& !name.starts_with('.')
|
||||
&& name.chars().all(|c| c.is_alphanumeric() || " _-.".contains(c));
|
||||
if !ok {
|
||||
return Err(bad("vault names use letters, numbers, spaces, - _ . (up to 60)"));
|
||||
}
|
||||
let conn = hub.db.lock().unwrap();
|
||||
if db::vault_id(&conn, name)?.is_some() {
|
||||
return Err(ApiError(StatusCode::CONFLICT, format!("there's already a vault named {name}")));
|
||||
}
|
||||
conn.execute("INSERT INTO vaults (name, created) VALUES (?1, ?2)", params![name, db::now()])?;
|
||||
let id = conn.last_insert_rowid();
|
||||
crate::git::create_repo(&hub.repo_path(id))?;
|
||||
db::grant(&conn, caller.account_id, id, "manage")?;
|
||||
db::log(&conn, &caller.who(), "vault created", name)?;
|
||||
Ok(Json(json!({ "id": id, "name": name, "role": "manage", "git_url": hub.git_url(id) })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Grant {
|
||||
vault: String,
|
||||
role: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct InviteReq {
|
||||
person: String,
|
||||
grants: Vec<Grant>,
|
||||
}
|
||||
|
||||
/// Resolves (vault name, role) pairs the caller may hand out.
|
||||
fn allowed_grants(conn: &Connection, caller: &Caller, grants: &[Grant]) -> Result<Vec<(i64, String, String)>, ApiError> {
|
||||
let mut out = vec![];
|
||||
for g in grants {
|
||||
let role = g.role.to_lowercase();
|
||||
if !ROLES.contains(&role.as_str()) {
|
||||
return Err(bad(format!("roles are read, edit or manage (not \"{}\")", g.role)));
|
||||
}
|
||||
let (id, name) = db::vault_id(conn, &g.vault)?.ok_or_else(|| bad(format!("no vault named {}", g.vault)))?;
|
||||
if !can_manage(conn, caller, id)? {
|
||||
return Err(denied(format!("you need Manage on {name} to give access to it")));
|
||||
}
|
||||
out.push((id, name, role));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub async fn invite(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<InviteReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let person = req.person.trim();
|
||||
if person.is_empty() || person.len() > 60 {
|
||||
return Err(bad("a person's name needs 1–60 characters"));
|
||||
}
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let grants = allowed_grants(&conn, &caller, &req.grants)?;
|
||||
if grants.is_empty() && !caller.owner {
|
||||
return Err(bad("say which vault to share, e.g. --vault DevOps:edit"));
|
||||
}
|
||||
let taken: bool = conn.query_row("SELECT COUNT(*) > 0 FROM accounts WHERE name = ?1", [person], |r| r.get(0))?;
|
||||
if taken {
|
||||
return Err(bad(format!("{person} already has an account — use `lunesync grant` instead")));
|
||||
}
|
||||
// One invite per person: a new one replaces any unused older one.
|
||||
conn.execute("DELETE FROM invites WHERE person = ?1 AND used IS NULL", [person])?;
|
||||
let token = db::token(32);
|
||||
let ids: Vec<(i64, &str)> = grants.iter().map(|(id, _, role)| (*id, role.as_str())).collect();
|
||||
conn.execute(
|
||||
"INSERT INTO invites (token_hash, person, owner, grants, created_by, expires) VALUES (?1, ?2, 0, ?3, ?4, ?5)",
|
||||
params![db::hash(&token), person, serde_json::to_string(&ids).unwrap(), caller.who(), db::now() + 7 * 86400],
|
||||
)?;
|
||||
let what: Vec<String> = grants.iter().map(|(_, n, r)| format!("{n}: {r}")).collect();
|
||||
db::log(&conn, &caller.who(), "invite created", &format!("for {person} ({})", what.join(", ")))?;
|
||||
Ok(Json(json!({ "link": format!("{}/join/{token}", hub.url) })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct GrantReq {
|
||||
person: String,
|
||||
vault: String,
|
||||
role: String,
|
||||
}
|
||||
|
||||
pub async fn grant(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<GrantReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let g = allowed_grants(&conn, &caller, &[Grant { vault: req.vault, role: req.role }])?.remove(0);
|
||||
let (account_id, person): (i64, String) = conn
|
||||
.query_row("SELECT id, name FROM accounts WHERE name = ?1", [req.person.trim()], |r| Ok((r.get(0)?, r.get(1)?)))
|
||||
.optional()?
|
||||
.ok_or_else(|| bad(format!("nobody named {} has joined yet — invite them first", req.person.trim())))?;
|
||||
let before = db::role(&conn, account_id, g.0)?;
|
||||
db::grant(&conn, account_id, g.0, &g.2)?;
|
||||
let detail = match before {
|
||||
Some(old) => format!("{person} on {}: {old} → {}", g.1, g.2),
|
||||
None => format!("{person} on {}: {}", g.1, g.2),
|
||||
};
|
||||
db::log(&conn, &caller.who(), "access granted", &detail)?;
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct MembersReq {
|
||||
vault: String,
|
||||
}
|
||||
|
||||
pub async fn members(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<MembersReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let (id, name) = db::vault_id(&conn, &req.vault)?.ok_or_else(|| bad(format!("no vault named {}", req.vault)))?;
|
||||
if !caller.owner && db::role(&conn, caller.account_id, id)?.is_none() {
|
||||
return Err(denied(format!("you're not a member of {name}")));
|
||||
}
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT a.id, a.name, m.role FROM memberships m JOIN accounts a ON a.id = m.account_id WHERE m.vault_id = ?1 ORDER BY a.name",
|
||||
)?;
|
||||
let rows: Vec<(i64, String, String)> =
|
||||
stmt.query_map([id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.collect::<Result<_, _>>()?;
|
||||
let mut out = vec![];
|
||||
for (account_id, person, role) in rows {
|
||||
let mut d = conn.prepare("SELECT label FROM devices WHERE account_id = ?1 ORDER BY created")?;
|
||||
let devices: Vec<String> = d.query_map([account_id], |r| r.get(0))?.collect::<Result<_, _>>()?;
|
||||
out.push(json!({ "person": person, "role": role, "devices": devices }));
|
||||
}
|
||||
Ok(Json(Value::Array(out)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LogQuery {
|
||||
count: Option<i64>,
|
||||
}
|
||||
|
||||
pub async fn log(State(hub): State<Shared>, headers: HeaderMap, Query(q): Query<LogQuery>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
if !caller.owner {
|
||||
return Err(denied("only the team owner can read the access log"));
|
||||
}
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let mut stmt = conn.prepare("SELECT at, actor, action, detail FROM log ORDER BY id DESC LIMIT ?1")?;
|
||||
let rows: Vec<Value> = stmt
|
||||
.query_map([q.count.unwrap_or(30)], |r| {
|
||||
Ok(json!({ "at": r.get::<_, i64>(0)?, "actor": r.get::<_, String>(1)?, "action": r.get::<_, String>(2)?, "detail": r.get::<_, String>(3)? }))
|
||||
})?
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(Json(Value::Array(rows)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NotSecretReq {
|
||||
vault_id: i64,
|
||||
fingerprint: String,
|
||||
}
|
||||
|
||||
pub async fn not_secret(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<NotSecretReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let role = db::role(&conn, caller.account_id, req.vault_id)?;
|
||||
if !role.as_deref().is_some_and(|r| r == "edit" || r == "manage") {
|
||||
return Err(denied("you need Edit on that vault"));
|
||||
}
|
||||
if req.fingerprint.len() != 40 || !req.fingerprint.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return Err(bad("that fingerprint doesn't look right"));
|
||||
}
|
||||
conn.execute("INSERT OR IGNORE INTO not_secrets (vault_id, fingerprint) VALUES (?1, ?2)", params![req.vault_id, req.fingerprint])?;
|
||||
let name: String = conn.query_row("SELECT name FROM vaults WHERE id = ?1", [req.vault_id], |r| r.get(0))?;
|
||||
db::log(&conn, &caller.who(), "not a secret", &format!("a line in {name} was marked as not a secret"))?;
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
173
hub/src/db.rs
Normal file
173
hub/src/db.rs
Normal file
@@ -0,0 +1,173 @@
|
||||
//! The hub's records: accounts, devices, vaults, memberships, invites, pairing codes and the access log.
|
||||
|
||||
use anyhow::Result;
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::Path;
|
||||
|
||||
const SCHEMA: &str = "
|
||||
PRAGMA journal_mode = WAL;
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
owner INTEGER NOT NULL DEFAULT 0,
|
||||
created INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id INTEGER NOT NULL REFERENCES accounts(id),
|
||||
label TEXT NOT NULL,
|
||||
key_hash TEXT NOT NULL,
|
||||
created INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS vaults (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
created INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS memberships (
|
||||
account_id INTEGER NOT NULL REFERENCES accounts(id),
|
||||
vault_id INTEGER NOT NULL REFERENCES vaults(id),
|
||||
role TEXT NOT NULL,
|
||||
PRIMARY KEY (account_id, vault_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS invites (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
person TEXT NOT NULL,
|
||||
owner INTEGER NOT NULL DEFAULT 0,
|
||||
grants TEXT NOT NULL,
|
||||
created_by TEXT NOT NULL,
|
||||
expires INTEGER NOT NULL,
|
||||
used INTEGER
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS pair_codes (
|
||||
code_hash TEXT PRIMARY KEY,
|
||||
account_id INTEGER NOT NULL,
|
||||
expires INTEGER NOT NULL,
|
||||
used INTEGER
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS not_secrets (
|
||||
vault_id INTEGER NOT NULL,
|
||||
fingerprint TEXT NOT NULL,
|
||||
PRIMARY KEY (vault_id, fingerprint)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS log (
|
||||
id INTEGER PRIMARY KEY,
|
||||
at INTEGER NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
detail TEXT NOT NULL
|
||||
);
|
||||
";
|
||||
|
||||
pub fn open(data: &Path) -> Result<Connection> {
|
||||
let conn = Connection::open(data.join("hub.sqlite"))?;
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
pub fn now() -> i64 {
|
||||
chrono::Utc::now().timestamp()
|
||||
}
|
||||
|
||||
pub fn hash(secret: &str) -> String {
|
||||
Sha256::digest(secret.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// Random token from an alphabet without look-alike characters.
|
||||
pub fn token(len: usize) -> String {
|
||||
const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
let mut bytes = vec![0u8; len];
|
||||
getrandom::fill(&mut bytes).expect("no randomness available");
|
||||
bytes.iter().map(|b| ALPHABET[*b as usize % ALPHABET.len()] as char).collect()
|
||||
}
|
||||
|
||||
pub fn log(conn: &Connection, actor: &str, action: &str, detail: &str) -> Result<()> {
|
||||
conn.execute(
|
||||
"INSERT INTO log (at, actor, action, detail) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![now(), actor, action, detail],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The device signing a request, with its person.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Caller {
|
||||
pub device_id: String,
|
||||
pub device_label: String,
|
||||
pub account_id: i64,
|
||||
pub person: String,
|
||||
pub owner: bool,
|
||||
}
|
||||
|
||||
impl Caller {
|
||||
/// "Sen (Codex)" — how the access log names whoever did something.
|
||||
pub fn who(&self) -> String {
|
||||
format!("{} ({})", self.person, self.device_label)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn caller(conn: &Connection, device_id: &str, key: &str) -> Result<Option<Caller>> {
|
||||
Ok(conn
|
||||
.query_row(
|
||||
"SELECT d.id, d.label, a.id, a.name, a.owner FROM devices d JOIN accounts a ON a.id = d.account_id
|
||||
WHERE d.id = ?1 AND d.key_hash = ?2",
|
||||
params![device_id, hash(key)],
|
||||
|r| {
|
||||
Ok(Caller { device_id: r.get(0)?, device_label: r.get(1)?, account_id: r.get(2)?, person: r.get(3)?, owner: r.get(4)? })
|
||||
},
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
/// Creates a device for `account_id`; returns (device id, key). Only the key's hash is kept.
|
||||
pub fn new_device(conn: &Connection, account_id: i64, label: &str) -> Result<(String, String)> {
|
||||
let id = format!("dev_{}", token(10).to_lowercase());
|
||||
let key = token(40);
|
||||
conn.execute(
|
||||
"INSERT INTO devices (id, account_id, label, key_hash, created) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![id, account_id, label, hash(&key), now()],
|
||||
)?;
|
||||
Ok((id, key))
|
||||
}
|
||||
|
||||
pub fn vault_id(conn: &Connection, name: &str) -> Result<Option<(i64, String)>> {
|
||||
Ok(conn.query_row("SELECT id, name FROM vaults WHERE name = ?1", [name], |r| Ok((r.get(0)?, r.get(1)?))).optional()?)
|
||||
}
|
||||
|
||||
pub fn role(conn: &Connection, account_id: i64, vault_id: i64) -> Result<Option<String>> {
|
||||
Ok(conn
|
||||
.query_row("SELECT role FROM memberships WHERE account_id = ?1 AND vault_id = ?2", [account_id, vault_id], |r| r.get(0))
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn grant(conn: &Connection, account_id: i64, vault_id: i64, role: &str) -> Result<()> {
|
||||
conn.execute(
|
||||
"INSERT INTO memberships (account_id, vault_id, role) VALUES (?1, ?2, ?3)
|
||||
ON CONFLICT (account_id, vault_id) DO UPDATE SET role = excluded.role",
|
||||
params![account_id, vault_id, role],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn not_secrets(conn: &Connection, vault_id: i64) -> Result<std::collections::HashSet<String>> {
|
||||
let mut stmt = conn.prepare("SELECT fingerprint FROM not_secrets WHERE vault_id = ?1")?;
|
||||
let rows = stmt.query_map([vault_id], |r| r.get(0))?;
|
||||
Ok(rows.collect::<Result<_, _>>()?)
|
||||
}
|
||||
|
||||
/// If nobody has an account yet, creates a fresh one-time owner invite (older unused ones stop working).
|
||||
pub fn owner_invite(conn: &Connection, person: &str) -> Result<Option<String>> {
|
||||
let accounts: i64 = conn.query_row("SELECT COUNT(*) FROM accounts", [], |r| r.get(0))?;
|
||||
if accounts > 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
conn.execute("DELETE FROM invites WHERE owner = 1 AND used IS NULL", [])?;
|
||||
let token = token(32);
|
||||
conn.execute(
|
||||
"INSERT INTO invites (token_hash, person, owner, grants, created_by, expires) VALUES (?1, ?2, 1, '[]', 'hub', ?3)",
|
||||
params![hash(&token), person, now() + 7 * 86400],
|
||||
)?;
|
||||
Ok(Some(token))
|
||||
}
|
||||
146
hub/src/git.rs
Normal file
146
hub/src/git.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
//! Vaults over Git's HTTP protocol: check the device key and role, then hand off to `git http-backend`.
|
||||
|
||||
use crate::api::{ApiError, Shared, credentials};
|
||||
use crate::db;
|
||||
use anyhow::{Context, Result};
|
||||
use axum::body::{Body, Bytes};
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::{HeaderMap, Method, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path as FsPath;
|
||||
use std::process::Stdio;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
pub fn create_repo(path: &FsPath) -> Result<()> {
|
||||
let repo = lune_core::git2::Repository::init_bare(path).with_context(|| format!("can't create {}", path.display()))?;
|
||||
repo.set_head("refs/heads/main")?;
|
||||
install_hook(path)
|
||||
}
|
||||
|
||||
/// Every incoming change goes through the hub's secret check before it's accepted (P3).
|
||||
pub fn install_hook(repo: &FsPath) -> Result<()> {
|
||||
let exe = std::env::current_exe()?;
|
||||
let hook = repo.join("hooks/pre-receive");
|
||||
std::fs::create_dir_all(hook.parent().unwrap())?;
|
||||
std::fs::write(&hook, format!("#!/bin/sh\nexec \"{}\" hook pre-receive\n", exe.display()))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ask_for_key() -> Response {
|
||||
(StatusCode::UNAUTHORIZED, [("WWW-Authenticate", "Basic realm=\"lune\"")], "sign in with a device key").into_response()
|
||||
}
|
||||
|
||||
pub async fn serve(
|
||||
State(hub): State<Shared>,
|
||||
Path((repo, rest)): Path<(String, String)>,
|
||||
Query(query): Query<HashMap<String, String>>,
|
||||
method: Method,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
match handle(hub, repo, rest, query, method, headers, body).await {
|
||||
Ok(r) => r,
|
||||
Err(e) => e.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle(
|
||||
hub: Shared,
|
||||
repo: String,
|
||||
rest: String,
|
||||
query: HashMap<String, String>,
|
||||
method: Method,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Result<Response, ApiError> {
|
||||
let not_found = || ApiError(StatusCode::NOT_FOUND, "no such vault".into());
|
||||
let vault_id: i64 = repo.strip_suffix(".git").and_then(|s| s.parse().ok()).ok_or_else(not_found)?;
|
||||
let service = match rest.as_str() {
|
||||
"info/refs" => query.get("service").cloned().unwrap_or_default(),
|
||||
"git-upload-pack" | "git-receive-pack" => rest.clone(),
|
||||
_ => return Err(not_found()),
|
||||
};
|
||||
let writing = match service.as_str() {
|
||||
"git-upload-pack" => false,
|
||||
"git-receive-pack" => true,
|
||||
_ => return Err(ApiError(StatusCode::FORBIDDEN, "only the smart Git protocol is served".into())),
|
||||
};
|
||||
|
||||
let Some((id, key)) = credentials(&headers) else { return Ok(ask_for_key()) };
|
||||
let (caller, role, vault_name) = {
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let Some(caller) = db::caller(&conn, &id, &key)? else { return Ok(ask_for_key()) };
|
||||
let role = db::role(&conn, caller.account_id, vault_id)?;
|
||||
let name: Option<String> =
|
||||
conn.query_row("SELECT name FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0)).ok();
|
||||
(caller, role, name)
|
||||
};
|
||||
let vault_name = vault_name.ok_or_else(not_found)?;
|
||||
let Some(role) = role else {
|
||||
return Err(ApiError(StatusCode::FORBIDDEN, format!("{} isn't a member of {vault_name}", caller.person)));
|
||||
};
|
||||
if writing && role == "read" {
|
||||
let conn = hub.db.lock().unwrap();
|
||||
db::log(&conn, &caller.who(), "change refused", &format!("{vault_name}: read access only"))?;
|
||||
return Err(ApiError(StatusCode::FORBIDDEN, format!("{} has read access to {vault_name}", caller.person)));
|
||||
}
|
||||
|
||||
let mut cmd = tokio::process::Command::new("git");
|
||||
cmd.arg("http-backend")
|
||||
.env_clear()
|
||||
.env("PATH", std::env::var("PATH").unwrap_or_default())
|
||||
.env("GIT_PROJECT_ROOT", hub.data.join("repos"))
|
||||
.env("GIT_HTTP_EXPORT_ALL", "1")
|
||||
.env("PATH_INFO", format!("/{repo}/{rest}"))
|
||||
.env("REQUEST_METHOD", method.as_str())
|
||||
.env("QUERY_STRING", query.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join("&"))
|
||||
.env("CONTENT_LENGTH", body.len().to_string())
|
||||
.env("REMOTE_USER", &caller.device_id)
|
||||
.env("REMOTE_ADDR", "127.0.0.1")
|
||||
.env("LUNE_HUB_DATA", &hub.data)
|
||||
.env("LUNE_ACTOR", caller.who())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit());
|
||||
for (header, var) in [("content-type", "CONTENT_TYPE"), ("content-encoding", "HTTP_CONTENT_ENCODING"), ("git-protocol", "GIT_PROTOCOL")] {
|
||||
if let Some(v) = headers.get(header).and_then(|v| v.to_str().ok()) {
|
||||
cmd.env(var, v);
|
||||
}
|
||||
}
|
||||
let mut child = cmd.spawn().map_err(|e| anyhow::anyhow!("can't start git http-backend: {e}"))?;
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
let writer = tokio::spawn(async move {
|
||||
let _ = stdin.write_all(&body).await;
|
||||
});
|
||||
let mut out = vec![];
|
||||
child.stdout.take().unwrap().read_to_end(&mut out).await.map_err(anyhow::Error::from)?;
|
||||
let _ = writer.await;
|
||||
let _ = child.wait().await;
|
||||
Ok(cgi_response(&out))
|
||||
}
|
||||
|
||||
/// Turns CGI output (headers, blank line, body) into an HTTP response.
|
||||
fn cgi_response(out: &[u8]) -> Response {
|
||||
let split = out.windows(4).position(|w| w == b"\r\n\r\n").map(|i| (i, 4)).or_else(|| out.windows(2).position(|w| w == b"\n\n").map(|i| (i, 2)));
|
||||
let Some((end, sep)) = split else {
|
||||
return (StatusCode::BAD_GATEWAY, "git gave no answer").into_response();
|
||||
};
|
||||
let mut status = StatusCode::OK;
|
||||
let mut builder = Response::builder();
|
||||
for line in String::from_utf8_lossy(&out[..end]).lines() {
|
||||
let Some((k, v)) = line.split_once(':') else { continue };
|
||||
let v = v.trim();
|
||||
if k.eq_ignore_ascii_case("status") {
|
||||
status = v.split_whitespace().next().and_then(|c| c.parse().ok()).and_then(|c| StatusCode::from_u16(c).ok()).unwrap_or(status);
|
||||
} else {
|
||||
builder = builder.header(k.trim(), v);
|
||||
}
|
||||
}
|
||||
builder.status(status).body(Body::from(out[end + sep..].to_vec())).unwrap_or_else(|_| StatusCode::BAD_GATEWAY.into_response())
|
||||
}
|
||||
86
hub/src/hook.rs
Normal file
86
hub/src/hook.rs
Normal file
@@ -0,0 +1,86 @@
|
||||
//! `lunehub hook pre-receive`: the hub's secret check (P3), run by Git before it accepts any change.
|
||||
|
||||
use crate::db;
|
||||
use anyhow::{Context, Result};
|
||||
use lune_core::git2::{self, Oid, Repository};
|
||||
use lune_core::secrets;
|
||||
use std::io::BufRead;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Returns false (refuse) if any new history entry adds a line that looks like a secret.
|
||||
pub fn pre_receive() -> Result<bool> {
|
||||
// Open with Git's environment so we can see the incoming (still quarantined) objects.
|
||||
let repo = Repository::open_from_env().context("can't open the vault")?;
|
||||
let data = PathBuf::from(std::env::var("LUNE_HUB_DATA").context("LUNE_HUB_DATA not set")?);
|
||||
let vault_id: i64 = repo
|
||||
.path()
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.and_then(|n| n.strip_suffix(".git"))
|
||||
.and_then(|n| n.parse().ok())
|
||||
.context("unexpected vault folder")?;
|
||||
let conn = db::open(&data)?;
|
||||
let allowed = db::not_secrets(&conn, vault_id)?;
|
||||
|
||||
let mut found = vec![];
|
||||
for line in std::io::stdin().lock().lines() {
|
||||
let line = line?;
|
||||
let mut parts = line.split_whitespace();
|
||||
let (Some(_old), Some(new), Some(_name)) = (parts.next(), parts.next(), parts.next()) else { continue };
|
||||
let new = Oid::from_str(new)?;
|
||||
if new.is_zero() {
|
||||
continue;
|
||||
}
|
||||
let mut walk = repo.revwalk()?;
|
||||
walk.push(new)?;
|
||||
for r in repo.references()? {
|
||||
if let Some(target) = r?.target() {
|
||||
walk.hide(target)?;
|
||||
}
|
||||
}
|
||||
for id in walk {
|
||||
found.extend(check_commit(&repo, &repo.find_commit(id?)?, &allowed)?);
|
||||
}
|
||||
}
|
||||
if found.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
for f in &found {
|
||||
eprintln!("lune: {f}");
|
||||
}
|
||||
let vault: String = conn.query_row("SELECT name FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0)).unwrap_or_default();
|
||||
let actor = std::env::var("LUNE_ACTOR").unwrap_or_else(|_| "unknown device".into());
|
||||
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)
|
||||
}
|
||||
85
hub/src/main.rs
Normal file
85
hub/src/main.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
//! lunehub: accounts, memberships, devices and vault repos for a team (Milestone 3).
|
||||
|
||||
mod api;
|
||||
mod db;
|
||||
mod git;
|
||||
mod hook;
|
||||
|
||||
use anyhow::Result;
|
||||
use axum::Router;
|
||||
use axum::extract::DefaultBodyLimit;
|
||||
use axum::routing::{any, get, post};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn env(name: &str, default: &str) -> String {
|
||||
std::env::var(name).unwrap_or_else(|_| default.to_string())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
|
||||
["hook", "pre-receive"] => {
|
||||
let ok = hook::pre_receive()?;
|
||||
std::process::exit(if ok { 0 } else { 1 });
|
||||
}
|
||||
["health"] => {
|
||||
// For the container healthcheck: is the hub answering?
|
||||
use std::io::{Read, Write};
|
||||
let port = env("LUNE_HUB_LISTEN", "0.0.0.0:8080").rsplit(':').next().unwrap_or("8080").to_string();
|
||||
let mut s = std::net::TcpStream::connect(format!("127.0.0.1:{port}"))?;
|
||||
s.write_all(b"GET /health HTTP/1.0\r\n\r\n")?;
|
||||
let mut answer = String::new();
|
||||
s.read_to_string(&mut answer)?;
|
||||
std::process::exit(if answer.ends_with("ok") { 0 } else { 1 });
|
||||
}
|
||||
[] | ["serve"] => serve(),
|
||||
_ => {
|
||||
eprintln!("usage: lunehub [serve] | lunehub health | lunehub hook pre-receive");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn serve() -> Result<()> {
|
||||
let data = PathBuf::from(env("LUNE_HUB_DATA", "/data"));
|
||||
let url = env("LUNE_HUB_URL", "http://localhost:8080").trim_end_matches('/').to_string();
|
||||
let listen = env("LUNE_HUB_LISTEN", "0.0.0.0:8080");
|
||||
std::fs::create_dir_all(data.join("repos"))?;
|
||||
let conn = db::open(&data)?;
|
||||
|
||||
// Keep every vault's hook pointing at this binary (it may have moved with an update).
|
||||
for entry in std::fs::read_dir(data.join("repos"))? {
|
||||
let path = entry?.path();
|
||||
if path.extension().is_some_and(|e| e == "git") {
|
||||
git::install_hook(&path)?;
|
||||
}
|
||||
}
|
||||
if let Some(token) = db::owner_invite(&conn, &env("LUNE_OWNER_NAME", "Owner"))? {
|
||||
println!("No team yet. The owner joins with this one-time link (valid 7 days):");
|
||||
println!(" lunesync join {url}/join/{token} --name <this device>");
|
||||
}
|
||||
|
||||
let hub = Arc::new(api::Hub { db: Mutex::new(conn), data, url: url.clone() });
|
||||
let app = Router::new()
|
||||
.route("/api/join", post(api::join))
|
||||
.route("/api/login", post(api::login))
|
||||
.route("/api/pair", post(api::pair))
|
||||
.route("/api/me", get(api::me))
|
||||
.route("/api/device/label", post(api::label))
|
||||
.route("/api/vaults", post(api::create_vault))
|
||||
.route("/api/invites", post(api::invite))
|
||||
.route("/api/grants", post(api::grant))
|
||||
.route("/api/members", post(api::members))
|
||||
.route("/api/log", get(api::log))
|
||||
.route("/api/not-secrets", post(api::not_secret))
|
||||
.route("/git/{repo}/{*rest}", any(git::serve))
|
||||
.route("/health", get(|| async { "ok" }))
|
||||
.layer(DefaultBodyLimit::disable())
|
||||
.with_state(hub);
|
||||
let listener = tokio::net::TcpListener::bind(&listen).await?;
|
||||
println!("Lune hub listening on {listen} (public address {url})");
|
||||
axum::serve(listener, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
108
hub/tests/hub.rs
Normal file
108
hub/tests/hub.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
//! The hub end to end: one-time links, pairing, roles enforced by the hub, secrets refused (P3).
|
||||
|
||||
use lune_core::hub::{self, HubLink};
|
||||
use lune_core::vault::{self, Vault};
|
||||
use lune_core::{remote, secrets, state};
|
||||
use std::collections::HashSet;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
|
||||
struct HubProcess(Child);
|
||||
|
||||
impl Drop for HubProcess {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
}
|
||||
}
|
||||
|
||||
fn start_hub(data: &std::path::Path) -> (HubProcess, String, String) {
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let url = format!("http://127.0.0.1:{port}");
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lunehub"))
|
||||
.env("LUNE_HUB_DATA", data)
|
||||
.env("LUNE_HUB_URL", &url)
|
||||
.env("LUNE_HUB_LISTEN", format!("127.0.0.1:{port}"))
|
||||
.env("LUNE_OWNER_NAME", "Sen")
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut link = String::new();
|
||||
for line in BufReader::new(child.stdout.take().unwrap()).lines() {
|
||||
let line = line.unwrap();
|
||||
if let Some(i) = line.find("http").filter(|_| line.contains("/join/")) {
|
||||
link = line[i..].split_whitespace().next().unwrap().to_string();
|
||||
}
|
||||
if line.contains("listening") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(HubProcess(child), url, link)
|
||||
}
|
||||
|
||||
fn as_device(url: &str, w: &hub::Welcome) -> HubLink {
|
||||
let link = HubLink { url: url.into(), device_id: w.device_id.clone(), key: w.key.clone() };
|
||||
remote::set_hub(link.clone());
|
||||
link
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hub_lifecycle() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let (_hub, url, owner_link) = start_hub(&tmp.path().join("data"));
|
||||
|
||||
// The owner link works once.
|
||||
let (_, sen) = hub::join(&owner_link, "Codex").unwrap();
|
||||
assert_eq!(sen.person, "Sen");
|
||||
assert!(hub::join(&owner_link, "Again").is_err());
|
||||
let codex = as_device(&url, &sen);
|
||||
let devops = codex.create_vault("DevOps").unwrap();
|
||||
|
||||
// Pairing: a code works once, and the new device has its own key.
|
||||
let code = codex.pair().unwrap();
|
||||
let hermes_w = hub::login(&url, &code, "Hermes").unwrap();
|
||||
assert!(hub::login(&url, &code, "Again").is_err());
|
||||
assert_ne!(hermes_w.key, sen.key);
|
||||
|
||||
// Codex shares a note; Hermes receives it labeled Codex.
|
||||
as_device(&url, &sen);
|
||||
let (cfg, _, err) = vault::add("DevOps", &tmp.path().join("codex"), &devops.git_url, "Codex").unwrap();
|
||||
assert_eq!(err, None);
|
||||
let a = Vault::open(&cfg, "Codex").unwrap();
|
||||
std::fs::write(a.root.join("vm-list.md"), "web-1\n").unwrap();
|
||||
a.save_changes(None, &HashSet::new()).unwrap();
|
||||
a.sync().unwrap();
|
||||
let hermes = as_device(&url, &hermes_w);
|
||||
assert_eq!(hermes.me().unwrap().vaults[0].role, "manage");
|
||||
let (cfg_h, _, _) = vault::add("DevOps", &tmp.path().join("hermes"), &devops.git_url, "Hermes").unwrap();
|
||||
let h = Vault::open(&cfg_h, "Hermes").unwrap();
|
||||
assert_eq!(std::fs::read(h.root.join("vm-list.md")).unwrap(), b"web-1\n");
|
||||
|
||||
// Bob has Read: the hub refuses his changes even from a client that ignores its role.
|
||||
as_device(&url, &sen);
|
||||
let bob_link = codex.invite("Bob", &[("DevOps".into(), "read".into())]).unwrap();
|
||||
let (_, bob_w) = hub::join(&bob_link, "Bob pc").unwrap();
|
||||
as_device(&url, &bob_w);
|
||||
let (cfg_b, _, _) = vault::add("DevOps", &tmp.path().join("bob"), &devops.git_url, "Bob pc").unwrap();
|
||||
let b = Vault::open(&cfg_b, "Bob pc").unwrap();
|
||||
std::fs::write(b.root.join("bob.md"), "bob\n").unwrap();
|
||||
b.save_changes(None, &HashSet::new()).unwrap();
|
||||
assert!(b.sync().is_err(), "read access must not share");
|
||||
state::write_role(&b.git_dir, "read").unwrap();
|
||||
assert!(b.sync().unwrap().read_only);
|
||||
|
||||
// A line this device calls "not a secret" is still refused by the hub until the hub hears it too.
|
||||
as_device(&url, &sen);
|
||||
std::fs::write(a.root.join("aws.md"), "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n").unwrap();
|
||||
let hit = a.secret_holds().unwrap()[0].hits[0].clone();
|
||||
secrets::allow(&a.git_dir, &hit, "aws.md").unwrap();
|
||||
a.save_changes(None, &HashSet::new()).unwrap();
|
||||
let err = format!("{:#}", a.sync().unwrap_err());
|
||||
assert!(err.contains("aws.md line 1: possible AWS access key"), "{err}");
|
||||
codex.not_a_secret(devops.id, &hit.line_hash).unwrap();
|
||||
a.sync().unwrap();
|
||||
|
||||
let log: Vec<String> = codex.log(50).unwrap().into_iter().map(|e| e.action).collect();
|
||||
for action in ["joined", "device added", "vault created", "invite created", "change refused", "not a secret"] {
|
||||
assert!(log.iter().any(|a| a == action), "missing {action} in {log:?}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user