Milestone 7: the app normal people install (macOS)

A Tauri menu-bar app runs the same sync engine as `lunesync run`. It
connects from the website with no code typed (lune://join and
lune://pair links), shows status in the menu bar, and lets a person
resolve held secrets, held big changes and kept-both notes side by
side. Uninstall shares and hands over first, then removes only what
Lune created.

Releases are signed on the hub that holds the key (`lunehub release
keygen/publish`); other hubs `release import` them. Apps verify the
signature and the signed version. Clients older than the previous
release are asked to update and keep saving locally.

A device can now be on several hubs at once (own and workplace), each
with its own key; the CLI takes --team when it matters. The supervisor
and status summary moved into core, shared by the CLI and the app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 11:47:35 +07:00
parent 8be559817c
commit 6cb85004fb
59 changed files with 6871 additions and 210 deletions

View File

@@ -2,3 +2,5 @@ target/
.git/
web/node_modules/
web/dist/
web/dist-desktop/
desktop/node_modules/

4305
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,7 @@
[workspace]
resolver = "3"
members = ["core", "cli", "hub"]
members = ["core", "cli", "hub", "desktop"]
# One version for every part: the hub offers clients by it (D3).
[workspace.package]
version = "0.1.0"

View File

@@ -1,6 +1,6 @@
[package]
name = "lunesync"
version = "0.1.0"
version.workspace = true
edition = "2024"
[dependencies]

View File

@@ -7,20 +7,20 @@ use clap::{Parser, Subcommand, ValueEnum};
use lune_core::config::{Config, VaultConfig};
use lune_core::guard;
use lune_core::secrets;
use lune_core::runner::{self, Timing};
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.")]
struct Cli {
#[command(subcommand)]
command: Command,
/// Which team's hub, when this device is on more than one (part of its address, e.g. its host name)
#[arg(long, global = true)]
team: Option<String>,
}
#[derive(Subcommand)]
@@ -280,6 +280,7 @@ fn run_cli(cli: Cli) -> Result<()> {
let mut config = Config::load()?;
config.use_hub_credentials();
let cwd = std::env::current_dir()?;
team::choose(cli.team);
match cli.command {
Command::Device { action: None } => println!("This device is \"{}\".", config.device_label()),
Command::Device { action: Some(DeviceCmd::Name { label }) } => {
@@ -287,7 +288,7 @@ fn run_cli(cli: Cli) -> Result<()> {
if label.is_empty() {
bail!("the label can't be empty");
}
if let Some(h) = &config.hub {
for h in &config.hubs {
h.set_label(&label)?;
}
config.device_name = Some(label.clone());
@@ -346,7 +347,7 @@ 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 {
for h in &config.hubs {
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),
@@ -506,7 +507,7 @@ 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) {
if let (Some(hub), Some(id)) = (config.hub_of(cfg), 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);
@@ -569,59 +570,11 @@ fn log_line(vault: &str, msg: &str) {
/// 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 {
let mut config = Config::load()?;
config.use_hub_credentials();
if config.vaults.is_empty() && config.hub.is_none() {
let config = Config::load()?;
if config.vaults.is_empty() && config.hubs.is_empty() {
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));
if let Err(e) = lune_core::membership::report(&config) {
log_line("hub", &format!("couldn't report health: {e:#}"));
}
}
Err(e) => {
let msg = format!("can't check the hub: {e:#}");
if msg != hub_said {
log_line("hub", &msg);
hub_said = msg;
}
}
}
}
// A vault that left (access ended) can come back later at the same place.
started.retain(|p| config.vaults.iter().any(|v| &v.path == p));
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_line(&cfg.name, &format!("{e:#}"));
return;
}
Err(e) => {
log_line(&cfg.name, &format!("stopped: {e:#} — retrying in 30 s"));
std::thread::sleep(Duration::from_secs(30));
}
}
}
});
}
std::thread::sleep(Duration::from_secs(2));
}
lune_core::supervisor::supervise(log_line)
}
/// After a one-off command, try to share right away; the runner picks it up otherwise.
@@ -645,48 +598,32 @@ fn share_now(v: &Vault) {
fn print_status(cfg: &VaultConfig, label: &str) {
println!("\n{} — {}", cfg.name, cfg.path.display());
let v = match Vault::open(cfg, label) {
Ok(v) => v,
Err(e) => {
println!(" Can't open: {e:#}");
return;
let st = lune_core::status::of(cfg, label);
match st.last_synced {
Some(t) if st.headline == "Synced" => println!(" Synced {}", ago(t)),
_ => println!(" {}", st.headline),
}
};
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}"),
None if st.last_synced.is_some() => format!("Synced {}", ago(st.last_synced.unwrap())),
None => "Not synced yet".to_string(),
};
println!(" {headline}");
if let Some(t) = st.last_synced {
println!(" Last sync: {} ({})", Local.timestamp_opt(t, 0).unwrap().format("%Y-%m-%d %H:%M:%S"), ago(t));
}
for h in guard::load(&v.git_dir) {
for h in &st.held {
println!(" Holding back a big change: \"{}\" — nothing from here is shared until you decide (`lunesync held`)", h.message);
}
let secret_notes = v.secret_holds().map(|l| l.len()).unwrap_or(0);
let secret_notes = st.secrets.len();
if secret_notes > 0 {
println!(
" {secret_notes} note{} not shared: looks like a secret (`lunesync held`)",
if secret_notes == 1 { "" } else { "s" }
);
}
let to_tidy = tidy::list(&v).map(|l| l.len()).unwrap_or(0);
let to_tidy = st.tidy.len();
if to_tidy > 0 {
println!(" {to_tidy} note{} to tidy — see `lunesync tidy`", if to_tidy == 1 { "" } else { "s" });
}
if !st.case_clashes.is_empty() {
println!(" Names differing only by case: {}", st.case_clashes.join(", "));
}
if !state::is_running(&v.git_dir) {
if !st.running && !st.headline.starts_with("Can't open") {
println!(" Not running — start `lunesync run` or `lunesync service install`");
}
}

View File

@@ -9,12 +9,20 @@ use lune_core::state;
use lune_core::vault::Vault;
use std::path::PathBuf;
static TEAM: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
/// The `--team` choice for this command.
pub fn choose(team: Option<String>) {
let _ = TEAM.set(team);
}
/// The hub this command talks to: the one `--team` names, or the only one.
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`")
config.pick_hub(TEAM.get().cloned().flatten().as_deref())
}
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.hubs.push(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;
@@ -30,16 +38,17 @@ fn connect(config: &mut Config, url: String, w: hub::Welcome, label: &str, vault
}
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 = invite.split("/join/").next().unwrap_or_default().trim_end_matches('/');
if config.hub(url).is_some() {
bail!("this device is already on the hub at {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);
if config.hub(url.trim_end_matches('/')).is_some() {
bail!("this device is already on the hub at {url}");
}
let w = hub::login(url, code, label)?;
connect(config, url.trim_end_matches('/').to_string(), w, label, vaults_dir)
@@ -94,6 +103,7 @@ pub fn vault_upload(config: &mut Config, name: &str, fresh: bool) -> Result<()>
let vc = config.vaults.iter_mut().find(|x| x.path == cfg.path).unwrap();
vc.remote = hv.git_url.clone();
vc.hub_vault = Some(hv.id);
vc.hub_url = Some(h.url.clone());
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.");

View File

@@ -1,6 +1,6 @@
[package]
name = "lune-core"
version = "0.1.0"
version.workspace = true
edition = "2024"
[dependencies]
@@ -10,6 +10,7 @@ chrono = "0.4.45"
dirs = "7.0.0"
gethostname = "1.1.0"
git2 = { version = "0.21.0", features = ["ssh", "https", "vendored-libgit2", "vendored-openssl"] }
libgit2-sys = "0.18.8"
notify = "8.2.1"
regex = "1.13.1"
serde = { version = "1.0.229", features = ["derive"] }

View File

@@ -15,9 +15,13 @@ pub struct Config {
/// 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.
/// This device's hub sign-ins: one per team it belongs to (a person's own hub, a workplace hub).
#[serde(default)]
pub hub: Option<crate::hub::HubLink>,
pub hubs: Vec<crate::hub::HubLink>,
/// Before M7 a device had one hub, stored as `[hub]`; read once and moved into `hubs`.
#[serde(default, rename = "hub", skip_serializing)]
#[doc(hidden)]
pub legacy_hub: Option<crate::hub::HubLink>,
#[serde(default, rename = "vault")]
pub vaults: Vec<VaultConfig>,
}
@@ -28,9 +32,12 @@ 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.
/// The hub's id for this vault, when it syncs through a hub.
#[serde(default)]
pub hub_vault: Option<i64>,
/// Which hub that is (ids are per hub).
#[serde(default)]
pub hub_url: Option<String>,
}
/// Directory holding `config.toml`. `LUNE_HOME` overrides it (handy for running two devices on one machine).
@@ -50,7 +57,18 @@ impl Config {
pub fn load() -> Result<Config> {
let path = Self::path()?;
match std::fs::read_to_string(&path) {
Ok(text) => toml::from_str(&text).with_context(|| format!("can't read {}", path.display())),
Ok(text) => {
let mut c: Config = toml::from_str(&text).with_context(|| format!("can't read {}", path.display()))?;
if let Some(h) = c.legacy_hub.take() {
for v in c.vaults.iter_mut().filter(|v| v.hub_vault.is_some() && v.hub_url.is_none()) {
v.hub_url = Some(h.url.clone());
}
if !c.hubs.iter().any(|x| x.url == h.url) {
c.hubs.insert(0, h);
}
}
Ok(c)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
Err(e) => Err(e).with_context(|| format!("can't read {}", path.display())),
}
@@ -77,10 +95,34 @@ impl Config {
.unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join("Vaults"))
}
/// Makes the hub's device key available to Git requests in this process.
/// Makes each 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());
crate::remote::set_hubs(&self.hubs);
}
pub fn hub(&self, url: &str) -> Option<&crate::hub::HubLink> {
self.hubs.iter().find(|h| h.url == url)
}
/// The hub a vault syncs through, if any.
pub fn hub_of(&self, v: &VaultConfig) -> Option<&crate::hub::HubLink> {
v.hub_vault?;
self.hub(v.hub_url.as_deref()?)
}
/// Picks a hub: the one whose address contains `sel` (e.g. its host name), else the only one.
pub fn pick_hub(&self, sel: Option<&str>) -> Result<&crate::hub::HubLink> {
match (sel, self.hubs.as_slice()) {
(_, []) => bail!("this device isn't on a hub yet — `lunesync join <invite link>` or `lunesync login`"),
(Some(s), all) => all
.iter()
.find(|h| h.url.contains(s))
.with_context(|| format!("this device isn't on a hub matching \"{s}\"")),
(None, [only]) => Ok(only),
(None, all) => {
let names: Vec<&str> = all.iter().map(|h| h.url.as_str()).collect();
bail!("this device is on several hubs ({}) — say which with --team <host>", names.join(", "))
}
}
}

View File

@@ -97,6 +97,7 @@ fn agent() -> ureq::Agent {
ureq::Agent::config_builder()
.http_status_as_error(false)
.timeout_global(Some(Duration::from_secs(30)))
.user_agent(crate::remote::user_agent())
.build()
.into()
}

View File

@@ -11,5 +11,7 @@ pub mod remote;
pub mod runner;
pub mod secrets;
pub mod state;
pub mod status;
pub mod supervisor;
pub mod tidy;
pub mod vault;

View File

@@ -7,36 +7,69 @@ use crate::secrets;
use crate::state;
use crate::vault::{self, Vault};
use anyhow::{Result, bail};
use std::path::Path;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
/// What a leaving note gets instead of a secret: the secret itself is never sent or kept (P1).
const REDACTED: &str = "[secret removed when leaving]";
/// New vaults arrive, same-named local vaults move onto the hub, roles refresh, and vaults whose access
/// ended are handed over and leave. Returns what happened, in plain words.
/// For every hub this device is on: new vaults arrive, same-named local vaults move onto the hub, roles
/// refresh, and vaults whose access ended are handed over and leave. Returns what happened, in plain words.
/// One hub failing doesn't stop the others; the first error comes back after the rest have run.
pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
let Some(h) = config.hub.clone() else { return Ok(vec![]) };
let mut said = vec![];
let mut failed = None;
for (_, result) in arrive_each(config) {
match result {
Ok(mut msgs) => said.append(&mut msgs),
Err(e) => failed = failed.or(Some(e)),
}
}
match failed {
Some(e) if said.is_empty() => Err(e),
Some(e) => {
said.push(format!("can't check the hub: {e:#}"));
Ok(said)
}
None => Ok(said),
}
}
/// `arrive`, hub by hub: (hub address, what happened there).
pub fn arrive_each(config: &mut Config) -> Vec<(String, Result<Vec<String>>)> {
let several = config.hubs.len() > 1;
let mut out = vec![];
for h in config.hubs.clone() {
let result = arrive_from(config, &h).map_err(|e| if several { e.context(h.url.clone()) } else { e });
out.push((h.url, result));
}
out
}
fn arrive_from(config: &mut Config, h: &HubLink) -> Result<Vec<String>> {
let me = match h.me() {
Ok(me) => me,
Err(e) if format!("{e}").contains("isn't signed in") => {
// The hub no longer knows this device: it was removed and has nothing left to hand over.
config.hub = None;
config.vaults.retain(|v| v.hub_vault.is_none());
config.hubs.retain(|x| x.url != h.url);
config.vaults.retain(|v| v.hub_url.as_deref() != Some(&h.url));
config.save()?;
return Ok(vec!["This device was removed from the hub. Vaults on other remotes keep syncing.".into()]);
return Ok(vec![format!("This device was removed from the hub at {}. Other vaults keep syncing.", h.url)]);
}
Err(e) => return Err(e),
};
let label = config.device_label();
let mine = |v: &crate::config::VaultConfig, id: i64| v.hub_vault == Some(id) && v.hub_url.as_deref() == Some(&h.url);
let mut said = vec![];
for d in &me.leaving {
said.push(leave(config, &h, d)?);
said.push(leave(config, h, d)?);
}
if me.nudge {
// Each vault's runner sees this and shares at once.
for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some()) {
// Each of this hub's vault runners sees this and shares at once.
for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some() && v.hub_url.as_deref() == Some(&h.url)) {
let dir = state::lune_dir(&vc.path.join(".git"));
if dir.exists() {
std::fs::write(dir.join("nudge"), "")?;
@@ -46,7 +79,7 @@ pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
}
for hv in me.vaults {
if let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(hv.id)) {
if let Some(vc) = config.vaults.iter().find(|v| mine(v, hv.id)) {
let v = Vault::open(vc, &label)?;
state::write_role(&v.git_dir, &hv.role)?;
continue;
@@ -59,17 +92,25 @@ pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
v.join_unrelated()?;
vc.remote = hv.git_url.clone();
vc.hub_vault = Some(hv.id);
vc.hub_url = Some(h.url.clone());
config.save()?;
said.push(format!("{} now syncs through the hub", hv.name));
continue;
}
let path = config.vaults_dir().join(&hv.name);
// Two teams can each have a "Notes": the second one gets the team's address in its folder name.
let mut path = config.vaults_dir().join(&hv.name);
let real = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
if config.vaults.iter().any(|v| real(&v.path) == real(&path)) {
let host = h.url.split("://").last().unwrap_or(&h.url).replace([':', '/'], "-");
path = config.vaults_dir().join(format!("{} ({host})", 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);
cfg.hub_url = Some(h.url.clone());
state::write_role(&path.join(".git"), &hv.role)?;
config.vaults.push(cfg);
config.save()?;
@@ -82,12 +123,13 @@ pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
Ok(said)
}
/// Tells the hub how each of this device's hub vaults is doing (M6 freshness).
/// Tells each hub how this device's vaults on it are doing (M6 freshness).
pub fn report(config: &Config) -> Result<()> {
let Some(h) = &config.hub else { return Ok(()) };
let label = config.device_label();
let mut failed = None;
for h in &config.hubs {
let mut out = vec![];
for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some()) {
for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some() && v.hub_url.as_deref() == Some(&h.url)) {
let Ok(v) = Vault::open(vc, &label) else { continue };
out.push(hub::VaultHealth {
vault_id: vc.hub_vault.unwrap(),
@@ -97,14 +139,20 @@ pub fn report(config: &Config) -> Result<()> {
holding: !crate::guard::load(&v.git_dir).is_empty(),
});
}
h.report(&out)
if let Err(e) = h.report(&out) {
failed = Some(e);
}
}
failed.map_or(Ok(()), Err)
}
/// Leaves one vault: stop syncing, save, make read-only, hand over what wasn't shared, and once the
/// hub has it, delete the folder if the app created it.
pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<String> {
let label = config.device_label();
let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(d.vault_id)).cloned() else {
let Some(vc) =
config.vaults.iter().find(|v| v.hub_vault == Some(d.vault_id) && v.hub_url.as_deref() == Some(&link.url)).cloned()
else {
link.departure_done(d.id, None)?;
return Ok(format!("Access to {} ended (it wasn't on this device)", d.vault));
};
@@ -162,6 +210,117 @@ pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<Strin
}
}
/// What uninstalling did, in plain words.
#[derive(Debug, Default, Serialize)]
pub struct Uninstalled {
/// Folders deleted.
pub removed: Vec<String>,
/// Folders left in place, each with why ("path — reason").
pub kept: Vec<String>,
/// Set when the hub couldn't be told this device is gone.
pub hub_problem: Option<String>,
}
/// Uninstall (D5). Every runner must already be stopped (`runner::STOP`). Shares what it can, hands the rest
/// over through the hub (A6) and signs this device out, then deletes the vault folders Lune created. A folder
/// still holding work that is neither shared nor handed over stays, and so does one the person added (A9).
pub fn uninstall(config: &mut Config) -> Result<Uninstalled> {
let label = config.device_label();
let all = config.vaults.clone();
let mut out = Uninstalled::default();
let mut unshared: HashMap<PathBuf, String> = HashMap::new();
for vc in &all {
let Ok(v) = Vault::open(vc, &label) else { continue };
wait_for_runner(&v)?;
let _op = state::op_lock(&v.git_dir)?;
let _ = v.save_changes(None, &HashSet::new());
if v.role().is_none_or(|r| hub::can_edit(&r)) {
let _ = v.sync();
}
if let Some(why) = unshared_work(&v) {
unshared.insert(vc.path.clone(), why);
}
}
for link in config.hubs.clone() {
let signed_out = link.remove_device(&label, None).and_then(|_| link.me());
match signed_out {
Ok(me) => {
for d in &me.leaving {
match leave(config, &link, d) {
// Whatever wasn't shared is with the vault's managers now.
Ok(_) => {
let left = all.iter().find(|v| v.hub_vault == Some(d.vault_id) && v.hub_url.as_deref() == Some(&link.url));
if let Some(vc) = left {
unshared.remove(&vc.path);
}
}
Err(e) => out.hub_problem = Some(format!("couldn't hand over {}: {e:#}", d.vault)),
}
}
}
Err(e) => {
out.hub_problem = Some(format!(
"couldn't reach the hub at {} ({e:#}) — this device still shows on its canvas; remove it there",
link.url
))
}
}
}
for vc in &all {
let shown = vc.path.display().to_string();
if !vc.path.exists() {
out.removed.push(shown);
continue;
}
let _ = set_read_only(&vc.path, false);
let created =
state::read_marker(&vc.path.join(".git")).is_some_and(|m| m.created_folder && m.managed_by == "lune");
if let Some(why) = unshared.get(&vc.path) {
out.kept.push(format!("{shown} — {why}"));
} else if !created {
out.kept.push(format!("{shown} — you added this folder yourself"));
} else {
// remove_dir_all removes links themselves, never what they point to (A9).
std::fs::remove_dir_all(&vc.path)?;
out.removed.push(shown);
}
}
config.vaults.clear();
config.hubs.clear();
config.save()?;
Ok(out)
}
/// Waits until the vault's runner has let go of it.
fn wait_for_runner(v: &Vault) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(60);
while state::try_run_lock(&v.git_dir)?.is_none() {
if Instant::now() > deadline {
bail!("{} is still busy syncing; try again in a moment", v.name);
}
std::thread::sleep(Duration::from_millis(250));
}
Ok(())
}
/// Why a vault still holds work nobody else has, if it does.
fn unshared_work(v: &Vault) -> Option<String> {
if !v.secret_holds().unwrap_or_default().is_empty() {
return Some("a note was held back as a possible secret".into());
}
if !crate::guard::load(&v.git_dir).is_empty() {
return Some("a big change is waiting for you to confirm it".into());
}
match v.waiting_files().unwrap_or(0) {
0 => None,
n if v.role().is_some_and(|r| !hub::can_edit(&r)) => Some(format!("{n} changed notes you can't share (read access)")),
n => Some(format!("{n} changed notes couldn't be shared (offline?)")),
}
}
/// Adds or removes write permission on everything in the vault folder except `.git`.
fn set_read_only(root: &Path, read_only: bool) -> Result<()> {
fn walk(dir: &Path, read_only: bool, top: bool) -> Result<()> {

View File

@@ -4,17 +4,57 @@ 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);
static HUBS: RwLock<Vec<crate::hub::HubLink>> = RwLock::new(Vec::new());
static VERSION: RwLock<Option<String>> = RwLock::new(None);
/// Git requests to this hub sign in with the device key.
/// What the hub says to a client too old to sync (D3).
pub const TOO_OLD: &str = "update Lune to keep syncing";
/// Sets the version this client tells the hub (the desktop app's own version; the crate version otherwise).
pub fn set_client_version(version: &str) {
*VERSION.write().unwrap() = Some(version.to_string());
set_git_user_agent();
}
pub fn client_version() -> String {
VERSION.read().unwrap().clone().unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string())
}
/// `lune/<version>`: how every request says which client it is, so the hub can turn away versions it no
/// longer supports.
pub fn user_agent() -> String {
format!("lune/{}", client_version())
}
/// Git requests carry the same User-Agent (libgit2 can't add headers to every request, but it can name itself).
pub fn set_git_user_agent() {
let product = std::ffi::CString::new(user_agent()).unwrap();
// SAFETY: a documented libgit2 option; libgit2 copies the string.
unsafe {
libgit2_sys::init();
libgit2_sys::git_libgit2_opts(libgit2_sys::GIT_OPT_SET_USER_AGENT_PRODUCT as std::ffi::c_int, product.as_ptr());
}
}
/// Git requests to this hub sign in with this device key (replacing any earlier key for the same hub).
pub fn set_hub(link: crate::hub::HubLink) {
*HUB.write().unwrap() = Some(link);
set_git_user_agent();
let mut hubs = HUBS.write().unwrap();
hubs.retain(|h| h.url != link.url);
hubs.push(link);
}
/// Git requests to each of these hubs sign in with that hub's device key.
pub fn set_hubs(links: &[crate::hub::HubLink]) {
set_git_user_agent();
*HUBS.write().unwrap() = links.to_vec();
}
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()))
let hubs = HUBS.read().unwrap();
// The longest matching address wins (two hubs could share a host).
let h = hubs.iter().filter(|h| url.starts_with(&format!("{}/", h.url))).max_by_key(|h| h.url.len())?;
Some((h.device_id.clone(), h.key.clone()))
}
pub fn callbacks<'a>() -> RemoteCallbacks<'a> {
@@ -67,6 +107,9 @@ fn default_key_files() -> Vec<PathBuf> {
/// Turns a remote failure into plain words for `status` and the run log.
pub fn describe_error(e: &anyhow::Error) -> String {
if let Some(g) = e.downcast_ref::<git2::Error>() {
if g.message().contains("status code: 426") {
return TOO_OLD.into();
}
if g.message().contains("status code: 403") {
return "the hub says this device has no access to this vault (if access ended, it will leave shortly)".into();
}

View File

@@ -8,6 +8,7 @@ use anyhow::{Result, bail};
use notify::{EventKind, RecursiveMode, Watcher};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::{Duration, Instant};
@@ -71,6 +72,9 @@ impl Burst {
pub type Log<'a> = &'a (dyn Fn(&str, &str) + Sync);
/// Set to stop every runner in this process (the desktop app uninstalling); each lets go of its vault.
pub static STOP: AtomicBool = AtomicBool::new(false);
/// Runs forever for one vault. `log(vault, message)` prints progress.
pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log: Log) -> Result<()> {
let vault = Vault::open(cfg, label)?;
@@ -101,6 +105,9 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
say("access to this vault ended — stopped syncing it");
return Ok(());
}
if STOP.load(Ordering::Relaxed) {
return Ok(());
}
if nudge.exists() {
// Nudged from the canvas: save what has settled and share right away.
let _ = std::fs::remove_file(&nudge);

136
core/src/status.rs Normal file
View File

@@ -0,0 +1,136 @@
//! How a vault is doing on this device, in plain words: for `lunesync status` and the desktop app.
use crate::config::VaultConfig;
use crate::state::{self, SyncState};
use crate::vault::Vault;
use crate::{guard, hub, remote, tidy};
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub struct VaultStatus {
pub name: String,
pub path: String,
/// The hub's address, for vaults that sync through one.
pub team: Option<String>,
/// current, behind, offline or secret: the status colours (X6).
pub level: &'static str,
pub headline: String,
pub last_synced: Option<i64>,
pub waiting: usize,
pub read_only: bool,
pub running: bool,
pub held: Vec<HeldChange>,
pub secrets: Vec<HeldSecret>,
pub tidy: Vec<ToTidy>,
pub case_clashes: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct HeldChange {
pub message: String,
pub removed: usize,
pub rewritten: usize,
pub total: usize,
}
#[derive(Debug, Clone, Serialize)]
pub struct HeldSecret {
pub path: String,
/// "line 3: possible AWS access key (AKIA…7Q)"
pub found: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ToTidy {
pub note: String,
pub copy: String,
pub label: String,
}
/// The order status colours are worst-first in: one red dot outranks everything.
pub fn worst<'a>(levels: impl IntoIterator<Item = &'a str>) -> &'static str {
let rank = |l: &str| match l {
"secret" => 3,
"behind" => 2,
"offline" => 1,
_ => 0,
};
match levels.into_iter().map(rank).max().unwrap_or(0) {
3 => "secret",
2 => "behind",
1 => "offline",
_ => "current",
}
}
pub fn of(cfg: &VaultConfig, label: &str) -> VaultStatus {
let mut out = VaultStatus {
name: cfg.name.clone(),
path: cfg.path.display().to_string(),
team: cfg.hub_url.clone(),
level: "behind",
headline: String::new(),
last_synced: None,
waiting: 0,
read_only: false,
running: false,
held: vec![],
secrets: vec![],
tidy: vec![],
case_clashes: vec![],
};
let v = match Vault::open(cfg, label) {
Ok(v) => v,
Err(e) => {
out.headline = format!("Can't open: {e:#}");
return out;
}
};
let st = SyncState::load(&v.git_dir);
out.last_synced = st.last_synced;
out.read_only = v.role().is_some_and(|r| !hub::can_edit(&r));
out.running = state::is_running(&v.git_dir);
out.waiting = v.waiting_files().unwrap_or(0);
out.case_clashes = st.case_clashes.clone();
out.held = guard::load(&v.git_dir)
.into_iter()
.map(|h| HeldChange { message: h.message, removed: h.removed, rewritten: h.rewritten, total: h.total })
.collect();
out.secrets = v
.secret_holds()
.unwrap_or_default()
.into_iter()
.map(|n| HeldSecret {
found: n.hits.iter().map(|h| format!("line {}: possible {} ({})", h.line, h.rule, h.hint)).collect(),
path: n.path,
})
.collect();
out.tidy = tidy::list(&v)
.unwrap_or_default()
.into_iter()
.map(|k| ToTidy { note: k.note, copy: k.copy, label: k.label })
.collect();
let waiting = out.waiting;
let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" });
let (level, headline) = match &st.last_error {
None if out.read_only && waiting > 0 => ("current", format!("Up to date · {changes} kept here, not shared (you have read access)")),
None if out.read_only => ("current", "Up to date (read access)".to_string()),
Some(e) if e == remote::TOO_OLD => ("behind", format!("Update Lune to keep syncing · {changes} saved here")),
Some(e) if e.starts_with("offline") => ("offline", format!("Offline · waiting to sync · {changes}")),
Some(e) => ("behind", format!("Can't sync: {e}{}", if waiting > 0 { format!(" · {changes} waiting") } else { String::new() })),
None if waiting > 0 => ("behind", format!("Waiting to sync · {changes}")),
None if st.last_synced.is_some() => ("current", "Synced".to_string()),
None => ("behind", "Not synced yet".to_string()),
};
out.level = if !out.secrets.is_empty() {
"secret"
} else if (!out.held.is_empty() || !out.tidy.is_empty()) && level == "current" {
// Waiting for a decision is amber too (X6).
"behind"
} else {
level
};
out.headline = headline;
out
}

95
core/src/supervisor.rs Normal file
View File

@@ -0,0 +1,95 @@
//! Keeps every vault in the config syncing: one runner thread per vault, vaults added meanwhile picked up,
//! and the hub checked every 30 s (memberships, departures, nudges, health). Used by `lunesync run` and the
//! desktop app.
use crate::config::Config;
use crate::membership;
use crate::runner::{self, STOP, Timing};
use anyhow::Result;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
/// Set to check the hub on the next round instead of waiting up to 30 s (just connected).
pub static CHECK_HUB: AtomicBool = AtomicBool::new(false);
/// Runs until `runner::STOP` is set. `log(vault, message)` reports what happens; "hub" for hub messages.
pub fn supervise(log: fn(&str, &str)) -> Result<()> {
let mut started: HashSet<PathBuf> = HashSet::new();
let mut hub_check = Instant::now();
// Each hub's last complaint, so an unreachable hub isn't logged every 30 s.
let mut hub_said: HashMap<String, String> = HashMap::new();
while !STOP.load(Ordering::Relaxed) {
let mut config = Config::load()?;
config.use_hub_credentials();
if CHECK_HUB.swap(false, Ordering::Relaxed) {
hub_check = Instant::now();
}
if !config.hubs.is_empty() && Instant::now() >= hub_check {
hub_check = Instant::now() + Duration::from_secs(30);
for (url, result) in membership::arrive_each(&mut config) {
match result {
Ok(msgs) => {
hub_said.remove(&url);
msgs.iter().for_each(|m| log("hub", m));
}
Err(e) => {
let msg = format!("can't check the hub: {e:#}");
if hub_said.get(&url) != Some(&msg) {
log("hub", &msg);
hub_said.insert(url, msg);
}
}
}
}
match membership::report(&config) {
Ok(()) => {
hub_said.remove("report");
}
Err(e) => {
let msg = format!("couldn't report health: {e:#}");
if hub_said.get("report") != Some(&msg) {
log("hub", &msg);
hub_said.insert("report".into(), msg);
}
}
}
}
// A vault that left (access ended) can come back later at the same place.
started.retain(|p| config.vaults.iter().any(|v| &v.path == p));
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 || {
while !STOP.load(Ordering::Relaxed) {
match runner::run(&cfg, &label, poll, Timing::default(), &log) {
Ok(()) => return,
Err(e) if format!("{e}").contains("already being synced") => {
log(&cfg.name, &format!("{e:#}"));
return;
}
Err(e) => {
log(&cfg.name, &format!("stopped: {e:#} — retrying in 30 s"));
std::thread::sleep(Duration::from_secs(30));
}
}
}
});
}
std::thread::sleep(Duration::from_secs(2));
}
Ok(())
}
/// Asks every running vault to save what has settled and share now (the menu's "Share now").
pub fn share_now(config: &Config) {
for vc in &config.vaults {
let dir = crate::state::lune_dir(&vc.path.join(".git"));
if dir.exists() {
let _ = std::fs::write(dir.join("nudge"), "");
}
}
}

View File

@@ -768,7 +768,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, hub_vault: None };
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch, hub_vault: None, hub_url: 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())?;

View File

@@ -515,3 +515,54 @@ fn moves_and_appends_are_not_runaway() {
}
assert!(a.save_changes(None, &HashSet::new()).unwrap().unwrap().held.is_some());
}
#[test]
fn uninstall_deletes_only_folders_it_made_and_never_unshared_work() {
let w = World::new();
// Uninstall rewrites the config; keep it inside this test's folder.
unsafe { std::env::set_var("LUNE_HOME", w.folder("home")) };
let other = w.device("Hermes");
let made = w.device_at("Codex", &w.folder("made"));
write(&made, "note.md", "shared\n");
save_and_sync(&made);
// A folder the person already had: Lune adopted it, so it never deletes it.
let own = w.folder("own");
fs::create_dir_all(&own).unwrap();
fs::write(own.join("mine.md"), "mine\n").unwrap();
let remote2 = w.folder("remote2.git");
Repository::init_bare(&remote2).unwrap();
let (own_cfg, _, _) = vault::add("Own", &own, remote2.to_str().unwrap(), "Codex").unwrap();
// A folder Lune made that holds a note with a secret: it can't be shared, so it must stay.
let remote3 = w.folder("remote3.git");
Repository::init_bare(&remote3).unwrap();
let (held_cfg, _, _) = vault::add("Held", &w.folder("held"), remote3.to_str().unwrap(), "Codex").unwrap();
fs::write(w.folder("held").join("aws.md"), format!("# AWS\n{FAKE_KEY}")).unwrap();
let mut config = lune_core::config::Config {
device_name: Some("Codex".into()),
vaults: vec![made_cfg(&w), own_cfg, held_cfg],
..Default::default()
};
let done = lune_core::membership::uninstall(&mut config).unwrap();
assert!(!w.folder("made").exists(), "{done:?}");
assert_eq!(fs::read(own.join("mine.md")).unwrap(), b"mine\n");
assert!(w.folder("held").join("aws.md").exists());
assert_eq!(done.removed.len(), 1);
assert_eq!(done.kept.len(), 2, "{:?}", done.kept);
assert!(config.vaults.is_empty());
// What was shared before uninstalling is still with everyone else.
other.sync().unwrap();
assert_eq!(read(&other, "note.md"), b"shared\n");
}
fn made_cfg(w: &World) -> lune_core::config::VaultConfig {
lune_core::config::VaultConfig {
name: "Test".into(),
path: w.folder("made"),
remote: w.remote.to_str().unwrap().into(),
branch: "main".into(),
hub_vault: None,
hub_url: None,
}
}

2
desktop/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules/
gen/

27
desktop/Cargo.toml Normal file
View File

@@ -0,0 +1,27 @@
[package]
name = "lune-desktop"
version.workspace = true
edition = "2024"
description = "Lune: the menu-bar app"
[[bin]]
name = "lune"
path = "src/main.rs"
[build-dependencies]
tauri-build = { version = "2.7.4", features = [] }
[dependencies]
anyhow = "1.0.104"
chrono = "0.4.45"
lune-core = { version = "0.1.0", path = "../core" }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
tauri = { version = "2.12.5", features = ["tray-icon", "image-png"] }
tauri-plugin-autostart = "2.7.0"
tauri-plugin-deep-link = "2.6.3"
tauri-plugin-dialog = "2.8.4"
tauri-plugin-opener = "2.7.2"
tauri-plugin-updater = "2.14.1"
trash = "5.2.2"
url = "2.5.4"

3
desktop/build.rs Normal file
View File

@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

18
desktop/build.sh Executable file
View File

@@ -0,0 +1,18 @@
#!/bin/sh
# Builds Lune for the Mac: desktop/build.sh <version> [extra tauri --config ...]
# Makes the .dmg people download and the .app.tar.gz the updater installs; then publish both on the hub that holds
# the signing key: lunehub release publish <version> <app.tar.gz> <dmg>
set -eu
cd "$(dirname "$0")"
v=${1:?usage: desktop/build.sh <version>}
shift
if grep -q '"pubkey": ""' tauri.conf.json; then
echo "note: no update key in tauri.conf.json yet — this build won't accept updates (run lunehub release keygen)" >&2
fi
npx tauri build --bundles app,dmg --config "{\"version\":\"$v\"}" "$@"
b=../target/release/bundle
# macOS tar would add ._ resource-fork entries that the updater can't unpack.
COPYFILE_DISABLE=1 tar --no-mac-metadata -czf "$b/Lune_${v}_aarch64.app.tar.gz" -C "$b/macos" Lune.app
echo "Built:"
echo " $(cd "$b" && pwd)/dmg/Lune_${v}_aarch64.dmg"
echo " $(cd "$b" && pwd)/Lune_${v}_aarch64.app.tar.gz"

View File

@@ -0,0 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "The Lune window: its own commands and events only.",
"windows": ["main"],
"permissions": ["core:default"]
}

BIN
desktop/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
desktop/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

BIN
desktop/icons/icon.icns Normal file

Binary file not shown.

BIN
desktop/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

BIN
desktop/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

BIN
desktop/icons/tray-grey.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

BIN
desktop/icons/tray-red.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

230
desktop/package-lock.json generated Normal file
View File

@@ -0,0 +1,230 @@
{
"name": "lune-desktop",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "lune-desktop",
"devDependencies": {
"@tauri-apps/cli": "2.12.4"
}
},
"node_modules/@tauri-apps/cli": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.4.tgz",
"integrity": "sha512-JI9bHfudSRJikGOrjbXEm6RjzzvmKuLc+JixB1NE8hNzQkNlCCIC3pTES3uypkR9lxHrsbxzcnSwhI2IxBQphw==",
"dev": true,
"license": "Apache-2.0 OR MIT",
"bin": {
"tauri": "tauri.js"
},
"engines": {
"node": ">= 10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/tauri"
},
"optionalDependencies": {
"@tauri-apps/cli-darwin-arm64": "2.12.4",
"@tauri-apps/cli-darwin-x64": "2.12.4",
"@tauri-apps/cli-linux-arm-gnueabihf": "2.12.4",
"@tauri-apps/cli-linux-arm64-gnu": "2.12.4",
"@tauri-apps/cli-linux-arm64-musl": "2.12.4",
"@tauri-apps/cli-linux-riscv64-gnu": "2.12.4",
"@tauri-apps/cli-linux-x64-gnu": "2.12.4",
"@tauri-apps/cli-linux-x64-musl": "2.12.4",
"@tauri-apps/cli-win32-arm64-msvc": "2.12.4",
"@tauri-apps/cli-win32-ia32-msvc": "2.12.4",
"@tauri-apps/cli-win32-x64-msvc": "2.12.4"
}
},
"node_modules/@tauri-apps/cli-darwin-arm64": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.4.tgz",
"integrity": "sha512-OxqKSckIkoJ6vX2AjifIJpTasFC0Hbdoo7gEiCmAjauABO3U8m2MRsLWe+QTiBwDx1mIrvgA+rvI7tvDnbnHVg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-darwin-x64": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.4.tgz",
"integrity": "sha512-fz76/77wMMJOaaUN6n3CybRG0P/MTEjjqYk81mGPyhi9m6Ue5T+LWBnJP/AkPooNatBPI2vtulGqomyMJ44lCQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm-gnueabihf": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.4.tgz",
"integrity": "sha512-K0w8Bof6Lt8QKLAYhRy0yy36ZH5iA/35VuSOvnxyjvCUZ+A3JKsUTlALviH/sVgAlisaPzzmeJSH8XOn4Q2HBA==",
"cpu": [
"arm"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm64-gnu": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.4.tgz",
"integrity": "sha512-j5rOnjmRUwWrm1oosf0zBYl4D+fqydgUROFCk0hvKZxvbTT8SOERes0QB7rBV/XWNy+kM6pCKzb3oSm2sRglzg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm64-musl": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.4.tgz",
"integrity": "sha512-aOue3Fy6Jb7+oWcfAVUsVHfeTybSCt2CZoU06aO4jv4d2Ks/KnaTPwMAK3CLEduGOvBLY1lbBBrIyomqLLH5Sg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-riscv64-gnu": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.4.tgz",
"integrity": "sha512-Fx6GShY/RvST+t6LMlTHAwd66+1tEaAAGrnU7cysVfaiRP1BKng5Vl6rVmO6rSLOA1Sp1dRzNYM4f0OWQGb7qA==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-x64-gnu": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.4.tgz",
"integrity": "sha512-tNzZSa79Z1nRpHxEpQ38lsAFpKlFlYvoXzjTV+lRRn/zSf3wrdUC3wnLcq2XEadchPu4ttK0zivhYzr+XGD19Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-x64-musl": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.4.tgz",
"integrity": "sha512-jmZ1pr0xEqUhuEusWtt9Yt+GF6lCnGHUmIL+KIknpbjK/XQ2qkhDBhaxK/JMHM2A8dAacVXCxXJk2EXpwhQUfA==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-arm64-msvc": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.4.tgz",
"integrity": "sha512-fGo8pgEHZxdSYgZ/J98m1usJ7NHKmKbq7k6uT0x1rpOq6Bg2YVzzpaAblWk710f5LHYBJIL5QIFS5IrD+4gmTg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-ia32-msvc": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.4.tgz",
"integrity": "sha512-ezl8sQIcjYsye3TUnTH5VcWmWzccZASlQm7hlZt0dYyj1XD0qpVW47u2xYVrIKui0F8uQv/7QGZixdWiClBsbg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-x64-msvc": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.4.tgz",
"integrity": "sha512-DJhDeCqjLDNMWYFy7ZS8cfeAHX2RK0RbQMLiA3bMVVkXRDJ4NBYiHriGqsUhsr9iG41aTb+dJGkFPmPw1gWwVw==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
}
}
}

10
desktop/package.json Normal file
View File

@@ -0,0 +1,10 @@
{
"name": "lune-desktop",
"private": true,
"scripts": {
"tauri": "tauri"
},
"devDependencies": {
"@tauri-apps/cli": "2.12.4"
}
}

271
desktop/src/commands.rs Normal file
View File

@@ -0,0 +1,271 @@
//! What the Lune window can ask for: status, connecting, and the decisions only a person makes.
use crate::{AppState, Connect};
use lune_core::config::{Config, default_device_name};
use lune_core::hub::{self, HubLink};
use lune_core::state;
use lune_core::status::{self, VaultStatus};
use lune_core::tidy::{self, Keep};
use lune_core::vault::Vault;
use lune_core::{secrets, supervisor};
use serde::Serialize;
use std::sync::atomic::Ordering;
use tauri::{AppHandle, State};
use tauri_plugin_autostart::ManagerExt as _;
use tauri_plugin_dialog::DialogExt;
use tauri_plugin_opener::OpenerExt;
type Answer<T> = Result<T, String>;
fn plain(e: anyhow::Error) -> String {
format!("{e:#}").replace("the hub said: ", "")
}
#[derive(Serialize)]
pub struct Pending {
kind: &'static str,
hub: String,
}
#[derive(Serialize)]
pub struct Overview {
version: String,
connected: bool,
/// The hubs this Mac is on, by address.
teams: Vec<String>,
device: String,
folder: String,
level: String,
summary: String,
vaults: Vec<VaultStatus>,
pending: Option<Pending>,
update: Option<String>,
recent: Vec<String>,
}
/// The name people gave this Mac ("Sen's MacBook Air"), rather than its network host name.
fn mac_name() -> String {
std::process::Command::new("scutil")
.args(["--get", "ComputerName"])
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|n| n.trim().chars().take(40).collect::<String>())
.filter(|n| !n.is_empty())
.unwrap_or_else(default_device_name)
}
#[tauri::command(async)]
pub fn overview(app: AppHandle, state: State<AppState>) -> Answer<Overview> {
let config = Config::load().map_err(plain)?;
let label = config.device_label();
let (level, summary) = crate::summary(&config);
let pending = state.pending.lock().unwrap().as_ref().map(|c| Pending {
kind: if matches!(c, Connect::Join { .. }) { "join" } else { "pair" },
hub: c.hub(),
});
Ok(Overview {
version: app.package_info().version.to_string(),
connected: !config.hubs.is_empty(),
teams: config.hubs.iter().map(|h| h.url.clone()).collect(),
device: config.device_name.clone().unwrap_or_else(mac_name),
folder: config.vaults_dir().display().to_string(),
level,
summary,
vaults: config.vaults.iter().map(|v| status::of(v, &label)).collect(),
pending,
update: state.update_ready.lock().unwrap().clone(),
recent: crate::recent_log(),
})
}
/// Connects this Mac to a team: from the link the website opened, or from a hub address and pairing code typed
/// by hand. A Mac can be on several teams' hubs at once.
#[tauri::command(async)]
pub fn connect(
app: AppHandle,
state: State<AppState>,
name: String,
folder: String,
hub_url: Option<String>,
code: Option<String>,
) -> Answer<String> {
let label = name.trim();
if label.is_empty() {
return Err("give this Mac a name your team will see".into());
}
let mut config = Config::load().map_err(plain)?;
let request = match (hub_url, code) {
(Some(hub), Some(code)) if !hub.trim().is_empty() && !code.trim().is_empty() => {
let hub = hub.trim().trim_end_matches('/');
let hub = if hub.starts_with("http") { hub.to_string() } else { format!("https://{hub}") };
Connect::Pair { hub, code: code.trim().to_string() }
}
_ => state.pending.lock().unwrap().clone().ok_or("open the link from your team's website, or enter a code")?,
};
if config.hub(request.hub().trim_end_matches('/')).is_some() {
*state.pending.lock().unwrap() = None;
return Err(format!("this Mac is already connected to {}", request.hub()));
}
let (url, welcome) = match &request {
Connect::Join { link } => hub::join(link, label).map_err(plain)?,
Connect::Pair { hub, code } => (hub.clone(), hub::login(hub, code, label).map_err(plain)?),
};
*state.pending.lock().unwrap() = None;
config.device_name = Some(label.to_string());
config.vaults_dir = Some(folder.into());
config.hubs.push(HubLink { url, device_id: welcome.device_id, key: welcome.key });
config.save().map_err(plain)?;
supervisor::CHECK_HUB.store(true, Ordering::Relaxed);
// Start with the Mac from now on (not for test setups that point LUNE_HOME elsewhere).
if std::env::var_os("LUNE_HOME").is_none() {
let _ = app.autolaunch().enable();
}
Ok(format!("Connected as {} — your vaults are on their way", welcome.person))
}
#[tauri::command(async)]
pub fn choose_folder(app: AppHandle) -> Option<String> {
let start = Config::load().unwrap_or_default().vaults_dir();
let start = start.ancestors().find(|p| p.exists()).map(|p| p.to_path_buf()).unwrap_or_default();
app.dialog()
.file()
.set_title("Where should shared vaults live?")
.set_directory(start)
.blocking_pick_folder()
.and_then(|p| p.into_path().ok())
.map(|p| p.display().to_string())
}
#[tauri::command(async)]
pub fn share_now() {
supervisor::share_now(&Config::load().unwrap_or_default());
}
/// Opens a vault and holds its op lock for one decision; afterwards the runner shares at once.
fn with_vault<T>(name: &str, f: impl FnOnce(&Config, &Vault) -> anyhow::Result<T>) -> Answer<T> {
let config = Config::load().map_err(plain)?;
config.use_hub_credentials();
let cfg = config.find(name).ok_or(format!("no vault named {name}"))?;
let v = Vault::open(cfg, &config.device_label()).map_err(plain)?;
let out = {
let _op = state::op_lock(&v.git_dir).map_err(plain)?;
f(&config, &v).map_err(plain)?
};
let _ = std::fs::write(state::lune_dir(&v.git_dir).join("nudge"), "");
Ok(out)
}
#[tauri::command(async)]
pub fn held_share(vault: String) -> Answer<()> {
with_vault(&vault, |_, v| v.share_held().map(|_| ()))
}
#[tauri::command(async)]
pub fn held_undo(vault: String) -> Answer<usize> {
with_vault(&vault, |_, v| v.undo_held().map(|kept| kept.len()))
}
fn held_hits(v: &Vault, path: &str) -> anyhow::Result<Vec<secrets::Hit>> {
let note = v.secret_holds()?.into_iter().find(|n| n.path == path);
note.map(|n| n.hits).filter(|h| !h.is_empty()).ok_or_else(|| anyhow::anyhow!("nothing is held in {path} any more"))
}
/// Replace with a pointer (P2): the secret goes, a note on where to find it stays.
#[tauri::command(async)]
pub fn secret_pointer(vault: String, path: String, pointer: String) -> Answer<()> {
if pointer.trim().is_empty() {
return Err("say where to get it, e.g. \"search prod-deploy in Secrets Manager\"".into());
}
with_vault(&vault, |_, v| {
let hits = held_hits(v, &path)?;
let file = v.root.join(&path);
let text = std::fs::read_to_string(&file)?;
std::fs::write(&file, secrets::replace_with_pointer(&text, &hits, None, pointer.trim()))?;
Ok(())
})
}
#[tauri::command(async)]
pub fn not_a_secret(vault: String, path: String) -> Answer<()> {
with_vault(&vault, |config, v| {
let cfg = config.find(&vault).unwrap();
for h in held_hits(v, &path)? {
secrets::allow(&v.git_dir, &h, &path)?;
if let (Some(hub), Some(id)) = (config.hub_of(cfg), cfg.hub_vault) {
hub.not_a_secret(id, &h.line_hash)?;
}
}
Ok(())
})
}
#[derive(Serialize)]
pub struct Comparison {
note: String,
copy: String,
label: String,
/// The copy beside the note is this Mac's version (the usual case after a clash here).
copy_is_mine: bool,
note_text: Option<String>,
copy_text: Option<String>,
}
fn as_text(bytes: Option<Vec<u8>>) -> Option<String> {
bytes.filter(|b| b.len() <= 200_000 && !b.iter().take(8000).any(|&c| c == 0)).map(|b| String::from_utf8_lossy(&b).into_owned())
}
#[tauri::command(async)]
pub fn compare(vault: String, copy: String) -> Answer<Comparison> {
let config = Config::load().map_err(plain)?;
let cfg = config.find(&vault).ok_or(format!("no vault named {vault}"))?;
let v = Vault::open(cfg, &config.device_label()).map_err(plain)?;
let k = tidy::list(&v).map_err(plain)?.into_iter().find(|k| k.copy == copy).ok_or("that was tidied already")?;
Ok(Comparison {
note_text: as_text(std::fs::read(v.root.join(&k.note)).ok()),
copy_text: as_text(std::fs::read(v.root.join(&k.copy)).ok()),
copy_is_mine: k.label.eq_ignore_ascii_case(&v.label),
note: k.note,
copy: k.copy,
label: k.label,
})
}
/// Keeps the version in place ("note"), the one beside it ("copy"), or both as separate notes.
#[tauri::command(async)]
pub fn tidy(vault: String, copy: String, keep: String) -> Answer<()> {
with_vault(&vault, |_, v| {
let k = tidy::list(v)?.into_iter().find(|k| k.copy == copy).ok_or_else(|| anyhow::anyhow!("that was tidied already"))?;
let copy_is_mine = k.label.eq_ignore_ascii_case(&v.label);
let choice = match (keep.as_str(), copy_is_mine) {
("both", _) => Keep::Both,
("copy", true) | ("note", false) => Keep::Mine,
_ => Keep::Theirs,
};
tidy::keep(v, &copy, choice).map(|_| ())
})
}
pub fn open_canvas_now(app: &AppHandle, team: Option<&str>) -> Answer<()> {
let config = Config::load().map_err(plain)?;
let hub = config.pick_hub(team).map_err(plain)?;
let link = hub.web_link().map_err(plain)?;
app.opener().open_url(link, None::<&str>).map_err(|e| e.to_string())
}
#[tauri::command(async)]
pub fn open_canvas(app: AppHandle, team: Option<String>) -> Answer<()> {
open_canvas_now(&app, team.as_deref())
}
#[tauri::command(async)]
pub fn open_folder(app: AppHandle, vault: String) -> Answer<()> {
let config = Config::load().map_err(plain)?;
let cfg = config.find(&vault).ok_or(format!("no vault named {vault}"))?;
app.opener().open_path(cfg.path.display().to_string(), None::<&str>).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn restart(app: AppHandle) {
app.restart();
}

419
desktop/src/main.rs Normal file
View File

@@ -0,0 +1,419 @@
//! Lune for the Mac (M7): the sync engine in the menu bar, a small window for what needs a person, connecting
//! from a link, signed updates from the hub, and a clean uninstall.
mod commands;
use lune_core::config::{self, Config};
use lune_core::{membership, remote, runner, status, supervisor};
use std::collections::VecDeque;
use std::io::Write;
use std::sync::atomic::Ordering;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use tauri::image::Image;
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
use tauri::tray::{TrayIcon, TrayIconBuilder};
use tauri::{AppHandle, Manager, WindowEvent};
use tauri_plugin_autostart::{MacosLauncher, ManagerExt as _};
use tauri_plugin_deep_link::DeepLinkExt;
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
use tauri_plugin_updater::UpdaterExt;
/// A request to connect this Mac, from a `lune://` link the website opened.
#[derive(Clone)]
pub enum Connect {
/// An invite link: creates the person's account and this device.
Join { link: String },
/// A pairing code made for a signed-in person.
Pair { hub: String, code: String },
}
impl Connect {
pub fn hub(&self) -> String {
match self {
Connect::Join { link } => link.split("/join/").next().unwrap_or_default().to_string(),
Connect::Pair { hub, .. } => hub.clone(),
}
}
fn from_url(url: &url::Url) -> Option<Connect> {
let param = |name: &str| url.query_pairs().find(|(k, _)| k == name).map(|(_, v)| v.into_owned());
match url.host_str()? {
"join" => Some(Connect::Join { link: param("link")? }),
"pair" => Some(Connect::Pair { hub: param("hub")?, code: param("code")? }),
_ => None,
}
}
}
#[derive(Default)]
pub struct AppState {
pub pending: Mutex<Option<Connect>>,
/// A newer version, downloaded and installed; it runs after a restart.
pub update_ready: Mutex<Option<String>>,
tray: Mutex<Option<TrayParts>>,
}
struct TrayParts {
icon: TrayIcon,
status: MenuItem<tauri::Wry>,
canvas: MenuItem<tauri::Wry>,
update: MenuItem<tauri::Wry>,
level: String,
}
static APP: OnceLock<AppHandle> = OnceLock::new();
static RECENT: Mutex<VecDeque<String>> = Mutex::new(VecDeque::new());
/// The engine's log: kept briefly for the window and appended to `lune.log` next to the config.
fn log_line(vault: &str, msg: &str) {
let line = format!("{} {vault:<10} {msg}", chrono::Local::now().format("%H:%M:%S"));
{
let mut recent = RECENT.lock().unwrap();
recent.push_back(line.clone());
while recent.len() > 50 {
recent.pop_front();
}
}
if let Ok(dir) = config::config_dir() {
let path = dir.join("lune.log");
if std::fs::metadata(&path).is_ok_and(|m| m.len() > 2_000_000) {
let _ = std::fs::remove_file(&path);
}
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
let _ = writeln!(f, "{line}");
}
}
}
pub fn recent_log() -> Vec<String> {
RECENT.lock().unwrap().iter().rev().take(12).cloned().collect()
}
pub fn show_window(app: &AppHandle) {
if let Some(w) = app.get_webview_window("main") {
let _ = w.show();
let _ = w.unminimize();
let _ = w.set_focus();
}
// Opening the window is a good moment to look for an update.
let app = app.clone();
tauri::async_runtime::spawn(async move { check_for_update(&app).await });
}
fn tray_image(level: &str) -> Image<'static> {
let bytes: &[u8] = match level {
"secret" => include_bytes!("../icons/tray-red.png"),
"behind" => include_bytes!("../icons/tray-amber.png"),
"offline" => include_bytes!("../icons/tray-grey.png"),
_ => include_bytes!("../icons/tray-green.png"),
};
Image::from_bytes(bytes).expect("tray icons are valid PNGs")
}
/// One line for the menu bar: the worst thing going on, in plain words.
pub fn summary(config: &Config) -> (String, String) {
if config.hubs.is_empty() && config.vaults.is_empty() {
return ("offline".into(), "Not connected to a team yet".into());
}
let label = config.device_label();
let all: Vec<status::VaultStatus> = config.vaults.iter().map(|v| status::of(v, &label)).collect();
let level = status::worst(all.iter().map(|s| s.level)).to_string();
let text = match all.iter().find(|s| s.level == level && level != "current") {
Some(s) if !s.secrets.is_empty() => format!("{}: a note was held back (possible secret)", s.name),
Some(s) if !s.held.is_empty() => format!("{}: a big change is waiting for you", s.name),
Some(s) if !s.tidy.is_empty() && s.headline == "Synced" => {
format!("{}: {} to tidy", s.name, if s.tidy.len() == 1 { "1 note".to_string() } else { format!("{} notes", s.tidy.len()) })
}
Some(s) => format!("{}: {}", s.name, s.headline),
None if all.is_empty() => "Waiting for vaults to arrive".into(),
None => "All synced".into(),
};
(level, text)
}
fn refresh_tray(app: &AppHandle) {
let config = Config::load().unwrap_or_default();
let (level, text) = summary(&config);
let state = app.state::<AppState>();
let update = state.update_ready.lock().unwrap().clone();
let mut tray = state.tray.lock().unwrap();
let Some(t) = tray.as_mut() else { return };
if t.level != level {
let _ = t.icon.set_icon(Some(tray_image(&level)));
t.level = level;
}
let _ = t.status.set_text(&text);
let _ = t.icon.set_tooltip(Some(format!("Lune — {text}")));
let _ = t.canvas.set_enabled(!config.hubs.is_empty());
match update {
Some(v) => {
let _ = t.update.set_text(format!("Restart to update (Lune {v})"));
let _ = t.update.set_enabled(true);
}
None => {
let _ = t.update.set_text(format!("Lune {}", app.package_info().version));
let _ = t.update.set_enabled(false);
}
}
}
fn build_tray(app: &AppHandle) -> tauri::Result<()> {
let status = MenuItem::with_id(app, "status", "Starting…", false, None::<&str>)?;
let open = MenuItem::with_id(app, "open", "Open Lune", true, None::<&str>)?;
let canvas = MenuItem::with_id(app, "canvas", "Open team canvas", false, None::<&str>)?;
let share = MenuItem::with_id(app, "share", "Share now", true, None::<&str>)?;
let update = MenuItem::with_id(app, "update", "", false, None::<&str>)?;
let uninstall_item = MenuItem::with_id(app, "uninstall", "Uninstall Lune…", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Quit Lune", true, None::<&str>)?;
let sep = || PredefinedMenuItem::separator(app);
let menu = Menu::with_items(app, &[&status, &sep()?, &open, &canvas, &share, &sep()?, &update, &uninstall_item, &quit])?;
let icon = TrayIconBuilder::with_id("lune")
.icon(tray_image("offline"))
.icon_as_template(false)
.menu(&menu)
.show_menu_on_left_click(true)
.on_menu_event(|app, event| match event.id.as_ref() {
"open" => show_window(app),
"canvas" => {
// One team: straight to its canvas. Several: the window lists them.
if Config::load().unwrap_or_default().hubs.len() > 1 {
show_window(app);
} else {
let app = app.clone();
std::thread::spawn(move || {
if let Err(e) = commands::open_canvas_now(&app, None) {
log_line("hub", &format!("couldn't open the canvas: {e}"));
}
});
}
}
"share" => supervisor::share_now(&Config::load().unwrap_or_default()),
"update" => app.restart(),
"uninstall" => {
let app = app.clone();
std::thread::spawn(move || uninstall(&app));
}
"quit" => app.exit(0),
_ => {}
})
.build(app)?;
let state = app.state::<AppState>();
*state.tray.lock().unwrap() = Some(TrayParts { icon, status, canvas, update, level: "offline".into() });
Ok(())
}
/// Looks for a newer version on this Mac's hubs (they all serve releases signed with the one key); downloads and
/// installs it, ready for a restart (D3).
pub async fn check_for_update(app: &AppHandle) {
let hubs = Config::load().map(|c| c.hubs).unwrap_or_default();
if hubs.is_empty() {
return;
}
if app.state::<AppState>().update_ready.lock().unwrap().is_some() {
return;
}
let configured = app
.config()
.plugins
.0
.get("updater")
.and_then(|u| u.get("pubkey"))
.and_then(|k| k.as_str())
.is_some_and(|k| !k.is_empty());
if !configured {
return; // a build without the hub's public key can't verify updates, so it doesn't take any
}
let endpoints = hubs.iter().filter_map(|h| format!("{}/api/update/{{{{target}}}}/{{{{arch}}}}/{{{{current_version}}}}", h.url).parse().ok());
let result = async {
let updater = app
.updater_builder()
.endpoints(endpoints.collect())?
.header("User-Agent", remote::user_agent())?
.build()?;
if let Some(update) = updater.check().await? {
log_line("app", &format!("downloading Lune {}", update.version));
update.download_and_install(|_, _| {}, || {}).await?;
return Ok::<_, anyhow::Error>(Some(update.version));
}
Ok(None)
}
.await;
match result {
Ok(Some(version)) => {
log_line("app", &format!("Lune {version} is ready — restart to use it"));
*app.state::<AppState>().update_ready.lock().unwrap() = Some(version);
refresh_tray(app);
}
Ok(None) => {}
Err(e) => log_line("app", &format!("couldn't check for an update: {e:#}")),
}
}
/// Uninstall Lune… (D5): asks once, then shares, hands over, removes what Lune made, and moves itself to the Trash.
fn uninstall(app: &AppHandle) {
let ok = app
.dialog()
.message(
"Lune first shares anything not yet shared and hands the rest to your team, then removes:\n\n\
• the vault folders Lune created\n• this Mac from your team\n• Lune's settings and login item\n• the app itself\n\n\
Folders you added yourself stay, and so does any folder whose changes couldn't be shared.",
)
.title("Uninstall Lune from this Mac?")
.kind(MessageDialogKind::Warning)
.buttons(MessageDialogButtons::OkCancelCustom("Uninstall".into(), "Cancel".into()))
.blocking_show();
if !ok {
return;
}
runner::STOP.store(true, Ordering::Relaxed);
let mut config = Config::load().unwrap_or_default();
config.use_hub_credentials();
let done = membership::uninstall(&mut config);
let _ = app.autolaunch().disable();
let mut leftovers = vec![];
if let Ok(dir) = config::config_dir() {
leftovers.push(dir);
}
let paths = app.path();
leftovers.extend([paths.app_data_dir(), paths.app_cache_dir(), paths.app_log_dir(), paths.app_config_dir()].into_iter().flatten());
if let Some(home) = std::env::home_dir() {
let id = &app.config().identifier;
leftovers.push(home.join("Library/WebKit").join(id));
leftovers.push(home.join("Library/Caches").join(id));
}
let message = match done {
Ok(done) => {
for dir in leftovers.iter().filter(|d| d.exists()) {
let _ = std::fs::remove_dir_all(dir);
}
let bundle = std::env::current_exe()
.ok()
.and_then(|exe| exe.ancestors().find(|p| p.extension().is_some_and(|e| e == "app")).map(|p| p.to_path_buf()));
let mut text = String::from("Lune is uninstalled.");
if let Some(bundle) = bundle
&& let Err(e) = move_to_trash(&bundle)
{
log_line("app", &format!("couldn't move the app to the Trash: {e}"));
text = format!("Lune is uninstalled. Drag {} to the Trash to finish.", bundle.display());
}
if !done.removed.is_empty() {
text.push_str(&format!("\n\nRemoved:\n{}", done.removed.join("\n")));
}
if !done.kept.is_empty() {
text.push_str(&format!("\n\nKept:\n{}", done.kept.join("\n")));
}
if let Some(p) = done.hub_problem {
text.push_str(&format!("\n\nNote: {p}"));
}
text
}
Err(e) => format!("Uninstall stopped before removing anything else: {e:#}\n\nOpen Lune again to keep syncing."),
};
app.dialog().message(message).title("Lune").buttons(MessageDialogButtons::Ok).blocking_show();
app.exit(0);
}
/// The system's own "move to Trash" (Finder's way needs an extra permission and fails quietly without it).
fn move_to_trash(path: &std::path::Path) -> Result<(), trash::Error> {
let mut ctx = trash::TrashContext::default();
#[cfg(target_os = "macos")]
{
use trash::macos::{DeleteMethod, TrashContextExtMacos};
ctx.set_delete_method(DeleteMethod::NsFileManager);
}
ctx.delete(path)
}
fn handle_links(app: &AppHandle, urls: Vec<url::Url>) {
for url in urls {
if let Some(c) = Connect::from_url(&url) {
*app.state::<AppState>().pending.lock().unwrap() = Some(c);
show_window(app);
}
}
}
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, None))
.manage(AppState::default())
.invoke_handler(tauri::generate_handler![
commands::overview,
commands::connect,
commands::choose_folder,
commands::share_now,
commands::held_share,
commands::held_undo,
commands::secret_pointer,
commands::not_a_secret,
commands::compare,
commands::tidy,
commands::open_canvas,
commands::open_folder,
commands::restart,
])
.setup(|app| {
let handle = app.handle().clone();
let _ = APP.set(handle.clone());
remote::set_client_version(&app.package_info().version.to_string());
#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
build_tray(&handle)?;
// The engine: the same one `lunesync run` uses, in this process.
std::thread::spawn(|| {
loop {
if let Err(e) = supervisor::supervise(log_line) {
log_line("app", &format!("sync stopped: {e:#} — restarting in 10 s"));
}
if runner::STOP.load(Ordering::Relaxed) {
return;
}
std::thread::sleep(Duration::from_secs(10));
}
});
let tray_handle = handle.clone();
std::thread::spawn(move || {
loop {
refresh_tray(&tray_handle);
std::thread::sleep(Duration::from_secs(3));
}
});
let update_handle = handle.clone();
tauri::async_runtime::spawn(async move {
tokio_sleep(Duration::from_secs(15)).await;
loop {
check_for_update(&update_handle).await;
tokio_sleep(Duration::from_secs(6 * 3600)).await;
}
});
let link_handle = handle.clone();
app.deep_link().on_open_url(move |event| handle_links(&link_handle, event.urls()));
if let Ok(Some(urls)) = app.deep_link().get_current() {
handle_links(&handle, urls);
}
if Config::load().map(|c| c.hubs.is_empty() && c.vaults.is_empty()).unwrap_or(true) {
show_window(&handle);
}
Ok(())
})
.on_window_event(|window, event| {
// Closing the window keeps Lune running in the menu bar.
if let WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close();
let _ = window.hide();
}
})
.run(tauri::generate_context!())
.expect("Lune couldn't start");
}
async fn tokio_sleep(d: Duration) {
let _ = tauri::async_runtime::spawn_blocking(move || std::thread::sleep(d)).await;
}

39
desktop/tauri.conf.json Normal file
View File

@@ -0,0 +1,39 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Lune",
"mainBinaryName": "lune",
"identifier": "space.senkensha.lune",
"build": {
"frontendDist": "../web/dist-desktop",
"beforeBuildCommand": "npm --prefix ../web run build:desktop"
},
"app": {
"windows": [
{
"label": "main",
"title": "Lune",
"url": "desktop.html",
"width": 440,
"height": 620,
"minWidth": 360,
"minHeight": 420,
"visible": false
}
],
"security": {
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:"
}
},
"bundle": {
"active": true,
"targets": ["app", "dmg"],
"icon": ["icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.png"],
"category": "Productivity",
"shortDescription": "Keeps shared vaults in sync",
"macOS": { "minimumSystemVersion": "12.0", "signingIdentity": "-" }
},
"plugins": {
"deep-link": { "desktop": { "schemes": ["lune"] } },
"updater": { "pubkey": "", "requireSignedVersion": true }
}
}

View File

@@ -153,38 +153,44 @@ Only the current milestone gets detailed below. The next one is detailed when th
---
## 6. Milestone 6 — Canvas for health and leaving
## 6. Milestone 7 — The app normal people install
Milestones 1–5 (sync, safety checks, the hub, taking access back, the canvas for access) are built; their detail lives in the code and tests now.
Milestones 1–6 (sync, safety checks, the hub, taking access back, the canvas) are built; their detail lives in the code and tests now.
### Goal
Before you need someone's work, you can see whether it has reached the team, and ask for it. Everything that needs a human decision — a note changed in two places, a handover, removing someone from the team — can be done on the canvas, including from a phone.
Someone who has never opened a terminal installs Lune on a Mac from the team's website, connects without typing a code, and from then on only notices it in the menu bar. Updates arrive on their own, signed. Uninstalling leaves nothing behind except notes that never got shared.
### What Sen does (on the canvas)
- Sees each person ringed by freshness and each device dotted the same way: green current, amber behind, grey offline (X6). A red dot means a possible secret was held back on that device.
- Opens a behind device: "4 changes not shared · 2 days" → **Nudge**.
- A vault shows "1 note to tidy" → **Compare** shows both versions side by side → keep one, or keep both.
- A vault shows a handover → see which notes it changes → **Keep** / **Discard**. A device that never came back → **Delete without saving**.
- A person → **Remove from team** (owner, asks to confirm, says how much unshared work will come back first). A removed person stays visible to the owner, dimmed, with **Restore** (gives a one-time sign-in link).
This milestone ships **macOS (Apple silicon) only** (§8). The code stays portable; Windows, Linux and Intel Macs come after the pilot.
### What a person does
- Opens their invite link (or the team canvas → **Get the Mac app**) → downloads `Lune.dmg` → drags Lune to Applications → opens it.
- Back on the page, clicks **Open Lune to join** (invite) or **Connect this Mac** (already on the team). Lune opens, shows the device name it will use (editable) → **Join** / **Connect**. No code to copy.
- Picks where shared vaults live (default `~/Vaults`) → vaults arrive.
- The menu-bar icon shows the worst status: synced, waiting, offline, held secret (same colours as X6). Its menu: status line, **Open Lune**, **Open team canvas**, **Share now**, **Uninstall Lune…**, **Quit**.
- The Lune window lists vaults with plain status and anything that needs them: a held big change (**Share anyway** / **Undo**), a possible secret (**Replace with a pointer** / **Not a secret**), notes to tidy (**Compare** side by side → keep this Mac's, the other, or both).
- When a new version is published, Lune downloads it quietly and the menu says **Restart to update**.
- **Uninstall Lune…** asks once, then: shares what it can, removes the vault folders Lune created, signs this Mac out of the hub, removes its settings and login item, and moves the app to the Trash.
### Behavior
- **Health reports**: while `lunesync run` is going, each device tells the hub every ~30 s, per vault: when it last synced, how many changes are waiting, and whether something is held (a big change, or a possible secret — counts only, never content). The hub knows work exists, not what it is.
- **Freshness**: current = reported in the last 2 minutes with nothing waiting; behind = something waiting or held; offline = not heard from in 2 minutes (shown with when it was last seen). A person's ring shows their worst device.
- **Nudge** reaches the device on its next check-in (~30 s): it saves what has settled and syncs at once. If something is held, the panel says so instead of pretending a nudge will help.
- **Tidy on the canvas** reads the two versions from the hub's copy of the vault (members only; Edit to decide). Keeping one, or both as separate notes, is a normal change on the hub that every device receives — same outcome as `lunesync tidy keep`.
- **Handovers on the canvas** are the M4 review (show / keep / discard / delete without saving), shown in the vault and person panels.
- **Remove from team / Restore** are the M4 flows; this is the only gesture on the canvas that asks for confirmation (X2).
- Status colors are used only for status; red only for a held secret (X6).
- **One engine**: the app runs the same sync engine as `lunesync run`, in-process. Both share one config, so the CLI still works next to the app. Lune starts at login once connected.
- **Connecting without a code**: the web page asks the hub for a short-lived pairing code (signed-in person) or uses the invite token, and opens `lune://pair?…` / `lune://join?…`. Typing a hub address and code in the window stays as a fallback.
- **Releases** (D3): `lunehub release keygen` creates the update-signing key on the hub's server (password-protected, never leaves it). `lunehub release publish` takes a built app, signs it there, and makes it the version the hub offers for download and update. The app trusts only that public key.
- **Too-old clients** (D3): every client says its version in its User-Agent. The hub serves the newest published version and the one before it. Older clients are refused with "Update Lune to keep syncing" and keep saving locally. Clients that don't say a version (0.1.x CLI, plain Git) are let through.
- **Several hubs on one device**: a Mac (or server) can belong to more than one team, e.g. Sen's own hub and a workplace hub. Each connection has its own device key; vaults from all of them sync side by side, and leaving one team never touches another's vaults.
- **One signing key for every hub**: releases are signed once where the key lives; other hubs `lunehub release import` an already-signed release and never hold the key.
- **Uninstall** never loses work: a vault with changes that couldn't be shared (offline, held, read-only) keeps its folder, and the dialog says which. Folders Lune didn't create are never deleted (A9).
- **Unsigned pilot** (D4): the first open needs "Open Anyway" in System Settings; the download page says so. OS code signing comes before a wider rollout.
### Acceptance — Sen acts this out
1. Laptop offline with edits: its ring turns amber, then grey with "last seen"; back online it turns green on its own.
2. A behind laptop that's online but idle: **Nudge** → green within a minute.
3. Same lines edited on two devices: the vault shows 1 to tidy; compare side by side on the canvas; keep one; the copy disappears on every device.
4. Remove someone from a vault with unshared work: review and keep the handover on the canvas.
5. From a phone: remove someone from the team (confirm), see their devices leave; restore them.
1. From an invite link on a Mac that has never run Lune: download, install, **Open Lune to join**, pick a folder; the team's vaults arrive and the menu bar shows synced.
2. On the canvas of an existing member: **Connect this Mac** pairs it with no code typed.
3. A possible secret: the menu bar turns red; resolve it from the window.
4. Same lines edited on two devices: compare side by side in the window, keep one.
5. Publish a new version on the hub: the app picks it up, **Restart to update**, and comes back as the new version still synced.
6. **Uninstall Lune…**: vault folders it created and its settings are gone, the device disappears from the canvas, and a folder you added yourself is untouched.
### Out of scope for M6
Desktop app, tray, installers, updates (M7). Push notifications for Nudge (the next check-in is enough for now).
### Out of scope for M7
Windows and Linux installers, Intel Macs, server install script (D2), OS code signing (D4), security audit and release evidence (before a wider rollout, not the pilot).
## 7. Open questions
None open.
@@ -196,3 +202,7 @@ Record here: date, what changed, why, which decision number. Example:
- 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)
- 2026-10-29 — Web canvas sign-in (new): no passwords; a one-time link from `lunesync open` or a pairing code typed on the hub's sign-in page; 30-day session cookie. (Sen)
- 2026-10-29 — Milestone 7 ships macOS (Apple silicon) only; Windows, Linux and Intel Macs after the pilot (D1). (Sen)
- 2026-10-29 — The update-signing key lives on the hub's server and `lunehub` signs releases there, so losing a laptop doesn't lose the key (D3). (Sen)
- 2026-10-29 — A device can connect to several hubs at once (Sen's own and a workplace hub), each with its own device key (A1, new in M7). (Sen)
- 2026-10-29 — One update-signing key, on Sen's VPS, signs releases for every hub; other hubs import signed releases (D3). Accepted trade-off: that server is trusted by every hub's Macs. (Sen)

View File

@@ -1,6 +1,6 @@
[package]
name = "lunehub"
version = "0.1.0"
version.workspace = true
edition = "2024"
[dependencies]
@@ -10,6 +10,7 @@ base64 = "0.23.1"
chrono = "0.4.45"
getrandom = "0.4.3"
lune-core = { version = "0.1.0", path = "../core" }
minisign = "0.10.0"
rusqlite = { version = "0.41.0", features = ["bundled"] }
rust-embed = { version = "8.13.0", features = ["mime-guess"] }
serde = { version = "1.0.229", features = ["derive"] }

View File

@@ -96,6 +96,7 @@ pub fn authenticate(hub: &Hub, headers: &HeaderMap) -> Result<Caller, ApiError>
if !caller.active {
return Err(denied("this device was removed from the hub"));
}
crate::release::check_client(&hub.data, headers)?;
Ok(caller)
}
@@ -220,6 +221,9 @@ pub async fn pair(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
pub async fn me(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
let caller = authenticate_any(&hub, &headers)?;
if caller.active {
crate::release::check_client(&hub.data, &headers)?;
}
let conn = hub.db.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT d.id, d.vault_id, v.name, d.delete_files, d.without_saving FROM departures d JOIN vaults v ON v.id = d.vault_id

View File

@@ -76,6 +76,10 @@ async fn handle(
let (caller, role, handover, vault_name) = {
let conn = hub.db.lock().unwrap();
let Some(caller) = db::caller(&conn, &id, &key)? else { return Ok(ask_for_key()) };
if caller.active {
// A device that's leaving may still hand over, whatever its version.
crate::release::check_client(&hub.data, &headers)?;
}
let role = if caller.active { db::role(&conn, caller.account_id, vault_id)? } else { None };
// A device whose access ended may still send its handover, and nothing else (A6).
let handover: Option<i64> = conn

View File

@@ -6,6 +6,7 @@ mod git;
mod health;
mod hook;
mod leave;
mod release;
mod web;
use anyhow::Result;
@@ -36,17 +37,31 @@ fn main() -> Result<()> {
s.read_to_string(&mut answer)?;
std::process::exit(if answer.ends_with("ok") { 0 } else { 1 });
}
["release", "keygen"] => release::keygen(&data_dir()),
["release", "list"] => {
release::list(&data_dir());
Ok(())
}
["release", "import", folder] => release::import(&data_dir(), folder.as_ref()),
["release", "publish", version, update, dmg, notes @ ..] => {
release::publish(&data_dir(), version, update.as_ref(), dmg.as_ref(), &notes.join(" "))
}
[] | ["serve"] => serve(),
_ => {
eprintln!("usage: lunehub [serve] | lunehub health | lunehub hook pre-receive");
eprintln!(" lunehub release keygen | list | publish <version> <Lune.app.tar.gz> <Lune.dmg> [notes] | import <folder>");
std::process::exit(2);
}
}
}
fn data_dir() -> PathBuf {
PathBuf::from(env("LUNE_HUB_DATA", "/data"))
}
#[tokio::main]
async fn serve() -> Result<()> {
let data = PathBuf::from(env("LUNE_HUB_DATA", "/data"));
let data = data_dir();
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"))?;
@@ -109,6 +124,10 @@ async fn serve() -> Result<()> {
.route("/api/tidy/resolve", post(health::resolve))
.route("/api/invites/grant", post(web::invite_grant))
.route("/api/devices/rename", post(web::rename_device))
.route("/api/update/{target}/{arch}/{current}", get(release::check))
.route("/api/release", get(release::latest))
.route("/download/mac", get(release::download_mac))
.route("/releases/{version}/{file}", get(release::file))
.route("/signin/{token}", get(web::signin_link))
.route("/git/{repo}/{*rest}", any(git::serve))
.route("/health", get(|| async { "ok" }))

259
hub/src/release.rs Normal file
View File

@@ -0,0 +1,259 @@
//! Desktop releases (M7, D3): the update-signing key lives here on the hub's server, `lunehub release publish`
//! signs a build, and the hub offers the newest version for download and update. Clients older than the
//! version before it are asked to update.
use crate::api::{ApiError, Shared};
use anyhow::{Context, Result, bail};
use axum::Json;
use axum::extract::{Path, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Redirect, Response};
use base64::Engine;
use minisign::{KeyPair, PublicKeyBox, SecretKey, SecretKeyBox};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::path::{Path as FsPath, PathBuf};
/// What a published version holds; written next to its files as `release.json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Release {
pub version: String,
pub notes: String,
pub pub_date: String,
/// The installer people download.
pub dmg: String,
/// The app bundle the updater installs, and its signature (base64 minisign, as Tauri expects).
pub update: String,
pub signature: String,
}
pub fn parse_version(v: &str) -> Option<(u64, u64, u64)> {
let mut parts = v.trim().trim_start_matches('v').split('.').map(|p| p.parse::<u64>().ok());
let version = (parts.next()??, parts.next()??, parts.next()??);
parts.next().is_none().then_some(version)
}
fn key_dir(data: &FsPath) -> PathBuf {
data.join("release")
}
fn releases_dir(data: &FsPath) -> PathBuf {
data.join("releases")
}
/// Published releases, newest first.
pub fn published(data: &FsPath) -> Vec<Release> {
let Ok(dirs) = std::fs::read_dir(releases_dir(data)) else { return vec![] };
let mut out: Vec<Release> = dirs
.flatten()
.filter_map(|d| std::fs::read_to_string(d.path().join("release.json")).ok())
.filter_map(|s| serde_json::from_str::<Release>(&s).ok())
.filter(|r| parse_version(&r.version).is_some())
.collect();
out.sort_by_key(|r| std::cmp::Reverse(parse_version(&r.version)));
out
}
/// The oldest client version still served: the one before the newest release (D3). None until there are two.
pub fn oldest_supported(data: &FsPath) -> Option<(u64, u64, u64)> {
published(data).get(1).and_then(|r| parse_version(&r.version))
}
/// The client version a request carries in its User-Agent (`lune/<version>`), if it says one.
pub fn client_version(headers: &HeaderMap) -> Option<(u64, u64, u64)> {
let ua = headers.get(header::USER_AGENT)?.to_str().ok()?;
let rest = &ua[ua.find("lune/")? + 5..];
parse_version(rest.split(|c: char| c.is_whitespace() || c == ')' || c == ';').next()?)
}
/// Refuses clients older than the hub supports. Clients that don't say a version are let through.
pub fn check_client(data: &FsPath, headers: &HeaderMap) -> Result<(), ApiError> {
match (client_version(headers), oldest_supported(data)) {
(Some(v), Some(oldest)) if v < oldest => {
Err(ApiError(StatusCode::UPGRADE_REQUIRED, lune_core::remote::TOO_OLD.into()))
}
_ => Ok(()),
}
}
fn password() -> Option<String> {
// Unset: minisign asks on the terminal.
std::env::var("LUNE_RELEASE_PASSWORD").ok()
}
/// What Tauri's updater config wants as `pubkey`: the minisign public key file, base64-encoded.
fn tauri_pubkey(pk_box: &str) -> String {
base64::engine::general_purpose::STANDARD.encode(pk_box)
}
pub fn keygen(data: &FsPath) -> Result<()> {
let dir = key_dir(data);
let sk_path = dir.join("update.key");
if sk_path.exists() {
bail!("an update-signing key already exists at {} — keep using it (apps only trust that key)", sk_path.display());
}
std::fs::create_dir_all(&dir)?;
let KeyPair { pk, sk } = KeyPair::generate_encrypted_keypair(password()).context("couldn't create the key")?;
let sk_box = sk.to_box(Some("Lune update-signing key"))?.into_string();
let pk_box = pk.to_box()?.into_string();
write_private(&sk_path, &sk_box)?;
std::fs::write(dir.join("update.pub"), &pk_box)?;
println!("Created the update-signing key at {} (password-protected; back it up with the hub's data).", sk_path.display());
println!("Put this public key in desktop/tauri.conf.json → plugins.updater.pubkey, then build the app:");
println!("{}", tauri_pubkey(&pk_box));
Ok(())
}
fn write_private(path: &FsPath, text: &str) -> Result<()> {
use std::io::Write;
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
opts.open(path)?.write_all(text.as_bytes())?;
Ok(())
}
/// `lunehub release publish <version> <Lune.app.tar.gz> <Lune.dmg> [notes]`: signs the update here and makes it
/// the version the hub offers.
pub fn publish(data: &FsPath, version: &str, update: &FsPath, dmg: &FsPath, notes: &str) -> Result<()> {
let v = parse_version(version).context("the version should look like 1.2.3")?;
if let Some(newest) = published(data).first()
&& parse_version(&newest.version).is_some_and(|n| n >= v)
{
bail!("{} is already published; a new release needs a higher version", newest.version);
}
let dir = key_dir(data);
let sk_box = std::fs::read_to_string(dir.join("update.key"))
.context("no update-signing key yet — run `lunehub release keygen` first")?;
let pk_box = std::fs::read_to_string(dir.join("update.pub"))?;
let sk = SecretKey::from_box(SecretKeyBox::from_string(&sk_box)?, password()).context("couldn't unlock the key")?;
let pk = PublicKeyBox::from_string(&pk_box)?.into_public_key()?;
let version = format!("{}.{}.{}", v.0, v.1, v.2);
let out = releases_dir(data).join(&version);
std::fs::create_dir_all(&out)?;
let update_name = format!("Lune_{version}_aarch64.app.tar.gz");
let dmg_name = format!("Lune_{version}_aarch64.dmg");
std::fs::copy(update, out.join(&update_name)).with_context(|| format!("can't read {}", update.display()))?;
std::fs::copy(dmg, out.join(&dmg_name)).with_context(|| format!("can't read {}", dmg.display()))?;
// The trusted comment is signed too; the app checks the version in it against the one offered.
let now = chrono::Utc::now();
let trusted = format!("timestamp:{}\tfile:{update_name}\tversion:{version}", now.timestamp());
let file = std::fs::File::open(out.join(&update_name))?;
let sig = minisign::sign(Some(&pk), &sk, file, Some(&trusted), Some("signature from the Lune hub"))?;
let release = Release {
version: version.clone(),
notes: notes.to_string(),
pub_date: now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
dmg: dmg_name,
update: update_name,
signature: base64::engine::general_purpose::STANDARD.encode(sig.into_string()),
};
std::fs::write(out.join("release.json"), serde_json::to_string_pretty(&release)?)?;
println!("Published Lune {version}. Apps pick it up within a few hours, or at their next start.");
Ok(())
}
/// `lunehub release import <folder>`: offers a release signed on another hub (one key signs for every hub).
/// The folder is what `publish` made there: `releases/<version>/` with release.json and both files.
pub fn import(data: &FsPath, from: &FsPath) -> Result<()> {
let r: Release = serde_json::from_str(&std::fs::read_to_string(from.join("release.json")).context("that folder has no release.json")?)
.context("that release.json doesn't make sense")?;
let v = parse_version(&r.version).context("that release has no proper version")?;
if let Some(newest) = published(data).first()
&& parse_version(&newest.version).is_some_and(|n| n >= v)
{
bail!("{} is already offered here; only newer releases can be added", newest.version);
}
// If this hub knows the public key, check the signature now rather than letting every app refuse it later.
if let Ok(pk_box) = std::fs::read_to_string(key_dir(data).join("update.pub")) {
let pk = PublicKeyBox::from_string(&pk_box)?.into_public_key()?;
let sig_box = String::from_utf8(base64::engine::general_purpose::STANDARD.decode(&r.signature)?)?;
let sig = minisign::SignatureBox::from_string(&sig_box)?;
let file = std::fs::File::open(from.join(&r.update))?;
minisign::verify(&pk, &sig, file, true, false, false).context("the signature doesn't match this hub's key")?;
}
let out = releases_dir(data).join(&r.version);
std::fs::create_dir_all(&out)?;
for name in [&r.dmg, &r.update] {
std::fs::copy(from.join(name), out.join(name)).with_context(|| format!("can't read {name}"))?;
}
std::fs::write(out.join("release.json"), serde_json::to_string_pretty(&r)?)?;
println!("Now offering Lune {} (signed elsewhere).", r.version);
Ok(())
}
pub fn list(data: &FsPath) {
let all = published(data);
if all.is_empty() {
println!("Nothing published yet.");
}
for (i, r) in all.iter().enumerate() {
let note = match i {
0 => " (offered)",
1 => " (oldest still syncing)",
_ => "",
};
println!("{} {}{note}", r.version, r.pub_date);
}
}
/// Tauri's updater asks here: `/api/update/{target}/{arch}/{current_version}`. 204 means up to date.
pub async fn check(State(hub): State<Shared>, Path((target, arch, current)): Path<(String, String, String)>) -> Response {
let Some(newest) = published(&hub.data).into_iter().next() else { return StatusCode::NO_CONTENT.into_response() };
let newer = match (parse_version(&newest.version), parse_version(&current)) {
(Some(n), Some(c)) => n > c,
_ => false,
};
if target != "darwin" || arch != "aarch64" || !newer {
return StatusCode::NO_CONTENT.into_response();
}
Json(json!({
"version": newest.version,
"notes": newest.notes,
"pub_date": newest.pub_date,
"url": format!("{}/releases/{}/{}", hub.url, newest.version, newest.update),
"signature": newest.signature,
}))
.into_response()
}
/// What the download page offers.
pub async fn latest(State(hub): State<Shared>) -> Json<serde_json::Value> {
match published(&hub.data).into_iter().next() {
Some(r) => Json(json!({ "version": r.version, "mac": "/download/mac" })),
None => Json(json!({ "version": null, "mac": null })),
}
}
pub async fn download_mac(State(hub): State<Shared>) -> Response {
match published(&hub.data).into_iter().next() {
Some(r) => Redirect::to(&format!("/releases/{}/{}", r.version, r.dmg)).into_response(),
None => (StatusCode::NOT_FOUND, "no Mac app published yet").into_response(),
}
}
pub async fn file(State(hub): State<Shared>, Path((version, name)): Path<(String, String)>) -> Response {
let not_found = || (StatusCode::NOT_FOUND, "no such file").into_response();
let Some(r) = published(&hub.data).into_iter().find(|r| r.version == version) else { return not_found() };
if name != r.dmg && name != r.update {
return not_found();
}
let kind = if name.ends_with(".dmg") { "application/x-apple-diskimage" } else { "application/gzip" };
match tokio::fs::read(releases_dir(&hub.data).join(&r.version).join(&name)).await {
Ok(bytes) => (
[
(header::CONTENT_TYPE, kind.to_string()),
(header::CONTENT_DISPOSITION, format!("attachment; filename=\"{name}\"")),
],
bytes,
)
.into_response(),
Err(_) => not_found(),
}
}

View File

@@ -120,7 +120,7 @@ fn device(url: &str, w: &hub::Welcome, label: &str, dir: &std::path::Path) -> Co
Config {
device_name: Some(label.into()),
vaults_dir: Some(dir.to_path_buf()),
hub: Some(HubLink { url: url.into(), device_id: w.device_id.clone(), key: w.key.clone() }),
hubs: vec![HubLink { url: url.into(), device_id: w.device_id.clone(), key: w.key.clone() }],
..Default::default()
}
}
@@ -151,7 +151,7 @@ fn taking_access_back() {
let (_hub, url, owner_link) = start_hub(&tmp.path().join("data"));
let (_, sen_w) = hub::join(&owner_link, "Codex").unwrap();
let mut sen = device(&url, &sen_w, "Codex", &tmp.path().join("sen"));
let sen_hub = sen.hub.clone().unwrap();
let sen_hub = sen.hubs[0].clone();
sen.use_hub_credentials();
sen_hub.create_vault("DevOps").unwrap();
sen_hub.create_vault("Notes").unwrap();
@@ -206,7 +206,7 @@ fn taking_access_back() {
assert!(!tmp.path().join("bob/DevOps").exists() && !tmp.path().join("bob/Notes").exists());
let said = check_in(&mut bob);
assert!(said[0].contains("removed from the hub"), "{said:?}");
assert!(bob.hub.is_none());
assert!(bob.hubs.is_empty());
sen.use_hub_credentials();
let bob_handover = sen_hub.handovers().unwrap().into_iter().find(|h| h.person == "Bob" && h.state == "received").unwrap();
sen_hub.handover_decide(bob_handover.id, "discard").unwrap();
@@ -389,3 +389,160 @@ fn health_nudge_and_tidy() {
assert!(!a.root.join(&copy).exists());
assert!(get("/api/canvas")["vaults"][0]["tidy"].as_array().unwrap().is_empty());
}
fn lunehub(data: &std::path::Path, args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_lunehub"))
.args(args)
.env("LUNE_HUB_DATA", data)
.env("LUNE_RELEASE_PASSWORD", "test only")
.output()
.unwrap()
}
#[test]
fn releases_are_signed_on_the_hub_and_old_clients_are_asked_to_update() {
use base64::Engine;
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::TempDir::new().unwrap();
let data = tmp.path().join("data");
let (_hub, url, owner_link) = start_hub(&data);
// The key is made on the hub; only the public half leaves it.
let made = lunehub(&data, &["release", "keygen"]);
assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
let pubkey = String::from_utf8(made.stdout).unwrap().lines().last().unwrap().trim().to_string();
assert!(!lunehub(&data, &["release", "keygen"]).status.success(), "a second key would orphan every app");
let update = tmp.path().join("Lune.app.tar.gz");
let dmg = tmp.path().join("Lune.dmg");
for v in ["0.1.0", "0.2.0", "0.3.0"] {
std::fs::write(&update, format!("app {v}")).unwrap();
std::fs::write(&dmg, format!("dmg {v}")).unwrap();
let out = lunehub(&data, &["release", "publish", v, update.to_str().unwrap(), dmg.to_str().unwrap(), "Notes"]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
let again = lunehub(&data, &["release", "publish", "0.2.5", update.to_str().unwrap(), dmg.to_str().unwrap()]);
assert!(!again.status.success(), "versions only go up");
// The updater's question: 0.2.0 gets 0.3.0, signed with the hub's key, version bound in the signature.
let agent = ureq::Agent::config_builder().http_status_as_error(false).build().new_agent();
let mut res = agent.get(format!("{url}/api/update/darwin/aarch64/0.2.0")).call().unwrap();
assert_eq!(res.status(), 200);
let offer: serde_json::Value = res.body_mut().read_json().unwrap();
assert_eq!(offer["version"], "0.3.0");
let bytes = agent.get(offer["url"].as_str().unwrap()).call().unwrap().body_mut().read_to_vec().unwrap();
assert_eq!(bytes, b"app 0.3.0");
let b64 = |s: &str| String::from_utf8(base64::engine::general_purpose::STANDARD.decode(s).unwrap()).unwrap();
let pk = minisign::PublicKeyBox::from_string(&b64(&pubkey)).unwrap().into_public_key().unwrap();
let sig = minisign::SignatureBox::from_string(&b64(offer["signature"].as_str().unwrap())).unwrap();
assert!(sig.trusted_comment().unwrap().contains("\tversion:0.3.0"));
minisign::verify(&pk, &sig, std::io::Cursor::new(&bytes), true, false, false).unwrap();
assert_eq!(agent.get(format!("{url}/api/update/darwin/aarch64/0.3.0")).call().unwrap().status(), 204);
let mut dl = agent.get(format!("{url}/download/mac")).call().unwrap();
assert_eq!(dl.body_mut().read_to_vec().unwrap(), b"dmg 0.3.0");
// A second hub (a workplace) offers the same signed release without ever holding the key.
let work = tmp.path().join("work");
std::fs::create_dir_all(&work).unwrap();
let imported = lunehub(&work, &["release", "import", data.join("releases/0.3.0").to_str().unwrap()]);
assert!(imported.status.success(), "{}", String::from_utf8_lossy(&imported.stderr));
assert!(!work.join("release/update.key").exists());
assert_eq!(std::fs::read(work.join("releases/0.3.0/release.json")).unwrap(), std::fs::read(data.join("releases/0.3.0/release.json")).unwrap());
// 0.1.0 is two releases behind: it keeps its place on the team but can't sync until it updates.
remote::set_client_version("0.3.0");
let (_, sen) = hub::join(&owner_link, "Codex").unwrap();
let codex = as_device(&url, &sen);
let devops = codex.create_vault("DevOps").unwrap();
let (cfg, _, _) = vault::add("DevOps", &tmp.path().join("codex"), &devops.git_url, "Codex").unwrap();
let v = Vault::open(&cfg, "Codex").unwrap();
remote::set_client_version("0.1.0");
assert!(format!("{:#}", codex.me().unwrap_err()).contains(remote::TOO_OLD));
std::fs::write(v.root.join("note.md"), "kept while outdated\n").unwrap();
assert!(v.save_changes(None, &HashSet::new()).unwrap().is_some(), "saving locally goes on");
assert_eq!(remote::describe_error(&v.sync().unwrap_err()), remote::TOO_OLD);
// One release behind still syncs.
remote::set_client_version("0.2.0");
assert_eq!(codex.me().unwrap().vaults.len(), 1);
v.sync().unwrap();
assert_eq!(v.waiting_files().unwrap(), 0);
remote::set_client_version(env!("CARGO_PKG_VERSION"));
}
#[test]
fn one_device_on_two_hubs_keeps_the_teams_apart() {
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::TempDir::new().unwrap();
let (_own, own_url, own_link) = start_hub(&tmp.path().join("own"));
let (_work, work_url, work_link) = start_hub(&tmp.path().join("work"));
// Sen's own hub, with a Notes vault and a second device to read it from.
let (_, sen_w) = hub::join(&own_link, "Mac").unwrap();
let mut mac = device(&own_url, &sen_w, "Mac", &tmp.path().join("mac"));
mac.use_hub_credentials();
mac.hubs[0].create_vault("Notes").unwrap();
let code = mac.hubs[0].pair().unwrap();
let hermes_w = hub::login(&own_url, &code, "Hermes").unwrap();
let mut hermes = device(&own_url, &hermes_w, "Hermes", &tmp.path().join("hermes"));
// The workplace hub (its owner is also called Sen by the test hub) has a Notes too; it invites Mov Sen.
let (_, boss_w) = hub::join(&work_link, "Boss pc").unwrap();
let mut boss = device(&work_url, &boss_w, "Boss pc", &tmp.path().join("boss"));
boss.use_hub_credentials();
boss.hubs[0].create_vault("Notes").unwrap();
let invite = boss.hubs[0].invite("Mov Sen", &[("Notes".into(), "edit".into())]).unwrap();
let (url, w) = hub::join(&invite, "Mac").unwrap();
mac.hubs.push(HubLink { url, device_id: w.device_id, key: w.key });
// Both arrive, in separate folders, each tied to its own hub.
let said = check_in(&mut mac);
assert_eq!(mac.vaults.len(), 2, "{said:?}");
let own_notes = mac.vaults.iter().find(|v| v.hub_url.as_deref() == Some(own_url.as_str())).unwrap().clone();
let work_notes = mac.vaults.iter().find(|v| v.hub_url.as_deref() == Some(work_url.as_str())).unwrap().clone();
assert_ne!(own_notes.path, work_notes.path);
mac.use_hub_credentials();
let label = mac.device_label();
let (a, b) = (Vault::open(&own_notes, &label).unwrap(), Vault::open(&work_notes, &label).unwrap());
write_and_save(&a, "home.md", "mine\n");
write_and_save(&b, "work.md", "the company's\n");
a.sync().unwrap();
b.sync().unwrap();
check_in(&mut hermes);
let h = open(&hermes, "Notes");
h.sync().unwrap();
assert!(h.root.join("home.md").exists() && !h.root.join("work.md").exists());
check_in(&mut boss);
let bn = open(&boss, "Notes");
bn.sync().unwrap();
assert!(bn.root.join("work.md").exists() && !bn.root.join("home.md").exists());
// The workplace takes Sen's access back: only that folder leaves.
boss.use_hub_credentials();
boss.hubs[0].remove("Mov Sen", "Notes", false).unwrap();
check_in(&mut mac);
assert!(!work_notes.path.exists());
assert_eq!(std::fs::read(own_notes.path.join("home.md")).unwrap(), b"mine\n");
assert_eq!(mac.vaults.len(), 1);
let a = open(&mac, "Notes");
write_and_save(&a, "home.md", "still mine\n");
a.sync().unwrap();
}
#[test]
fn a_single_hub_config_from_before_moves_into_the_list() {
let tmp = tempfile::TempDir::new().unwrap();
std::fs::write(
tmp.path().join("config.toml"),
"device_name = \"Mac\"\n\n[hub]\nurl = \"https://hub.example\"\ndevice_id = \"dev_1\"\nkey = \"k\"\n\n\
[[vault]]\nname = \"Notes\"\npath = \"/tmp/notes\"\nremote = \"https://hub.example/git/1.git\"\nbranch = \"main\"\nhub_vault = 1\n",
)
.unwrap();
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
unsafe { std::env::set_var("LUNE_HOME", tmp.path()) };
let c = Config::load().unwrap();
unsafe { std::env::remove_var("LUNE_HOME") };
assert_eq!(c.hubs.len(), 1);
assert_eq!(c.vaults[0].hub_url.as_deref(), Some("https://hub.example"));
assert_eq!(c.hub_of(&c.vaults[0]).unwrap().device_id, "dev_1");
}

1
web/.gitignore vendored
View File

@@ -1,2 +1,3 @@
node_modules/
dist/
dist-desktop/

12
web/desktop.html Normal file
View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lune</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/desktop/main.tsx"></script>
</body>
</html>

11
web/package-lock.json generated
View File

@@ -8,6 +8,7 @@
"name": "lune-canvas",
"version": "0.1.0",
"dependencies": {
"@tauri-apps/api": "2.12.4",
"react": "18.3.1",
"react-dom": "18.3.1"
},
@@ -1109,6 +1110,16 @@
"win32"
]
},
"node_modules/@tauri-apps/api": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.4.tgz",
"integrity": "sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==",
"license": "Apache-2.0 OR MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/tauri"
}
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",

View File

@@ -6,9 +6,11 @@
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"check": "tsc -b"
"check": "tsc -b",
"build:desktop": "tsc -b && vite build --config vite.desktop.config.ts"
},
"dependencies": {
"@tauri-apps/api": "2.12.4",
"react": "18.3.1",
"react-dom": "18.3.1"
},

View File

@@ -3,6 +3,7 @@
// also has a button in the details panel (X3).
import { useEffect, useMemo, useRef, useState } from 'react';
import { MacSection } from './MacApp';
import { api, type CanvasData, type Comparison, type Health, type LogEntry, type Member, type Person, type Role, type Status, type Vault } from './api';
import {
HANDLE_T, W, boardHeight, circle, easeBack, lerp, personColor, positions, ribbon, roundRect, vaultColor,
@@ -668,6 +669,7 @@ function Overview({ data, members, log, open, close, newVault, signOut }: {
</ol>
</section>
)}
<MacSection />
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<span className="muted">Signed in as {data.me.person}</span>
<button className="btn btn-small" onClick={signOut}>Sign out</button>

58
web/src/MacApp.tsx Normal file
View File

@@ -0,0 +1,58 @@
// Getting the Mac app (M7): download it from this hub, then hand it the invite or a fresh pairing code through a
// lune:// link, so nobody copies a code by hand.
import { useEffect, useState } from 'react';
import { api } from './api';
interface Release { version: string | null; mac: string | null }
function useRelease() {
const [r, setR] = useState<Release | null>(null);
useEffect(() => { fetch('/api/release').then((x) => x.json()).then(setR).catch(() => setR({ version: null, mac: null })); }, []);
return r;
}
const FIRST_OPEN = 'This pilot build isn’t signed by Apple yet: the first time, macOS may say it can’t check Lune. Open System Settings → Privacy & Security and choose Open Anyway.';
/** On an invite page: download, then join from the app with this link. */
export function JoinWithApp({ link }: { link: string }) {
const r = useRelease();
return (
<>
<ol className="steps">
<li>
{r?.mac ? <a className="btn btn-primary" href={r.mac}>Download Lune for Mac</a> : <span className="muted">The Mac app isn't published on this hub yet.</span>}
{r?.mac && <span className="muted">Open the download and drag Lune to Applications, then open it. {FIRST_OPEN}</span>}
</li>
<li>
<a className="btn" href={`lune://join?link=${encodeURIComponent(link)}`}>Open Lune to join</a>
<span className="muted">Lune asks for a name for this Mac and where shared vaults should go. This link works once.</span>
</li>
</ol>
</>
);
}
/** On the canvas: get the app, or connect a Mac that has it, without typing a code. */
export function MacSection() {
const r = useRelease();
const [error, setError] = useState('');
const connect = async () => {
setError('');
try {
const { code } = await api.pair();
location.href = `lune://pair?hub=${encodeURIComponent(location.origin)}&code=${encodeURIComponent(code)}`;
} catch (e) {
setError((e as Error).message);
}
};
return (
<section className="ov-sec">
<div className="ov-head"><h3>Lune for Mac{r?.version ? ` · ${r.version}` : ''}</h3></div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, padding: '0 6px 4px' }}>
{r?.mac && <a className="btn btn-small" href={r.mac}>Get the Mac app</a>}
<button className="btn btn-small" onClick={connect}>Connect this Mac</button>
</div>
{error && <p className="error" style={{ padding: '0 6px' }}>{error}</p>}
</section>
);
}

View File

@@ -90,6 +90,7 @@ async function call<T>(method: string, path: string, body?: unknown): Promise<T>
export const api = {
canvas: () => call<CanvasData>('GET', '/api/canvas'),
log: (count = 8) => call<LogEntry[]>('GET', `/api/log?count=${count}`),
pair: () => call<{ code: string }>('POST', '/api/pair'),
signin: (code: string) => call<object>('POST', '/api/web/signin', { code }),
signout: () => call<object>('POST', '/api/web/signout'),
grant: (person: string, vault: string, role: Role) => call<object>('POST', '/api/grants', { person, vault, role }),

View File

@@ -0,0 +1,48 @@
/* The Lune window: same ink-on-lavender as the canvas, sized for a small menu-bar window. Status colours as X6. */
:root {
--current: #2E8B5F;
--behind: #E09A2B;
--offline: #A9A5B6;
--secret: #C8323B;
}
body { background: var(--paper); user-select: none; -webkit-user-select: none; }
input, pre { user-select: text; -webkit-user-select: text; }
.app { min-height: 100vh; display: flex; flex-direction: column; gap: 14px; padding: 16px; }
.top { display: flex; align-items: center; gap: 10px; }
.top-text { display: flex; flex-direction: column; min-width: 0; }
.top-text b { font-size: 18px; }
.moon-small { width: 32px; height: 32px; }
.moon { width: 64px; height: 64px; align-self: center; }
.dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; flex: none; vertical-align: baseline; }
.dot-current { background: var(--current); }
.dot-behind { background: var(--behind); }
.dot-offline { background: var(--offline); }
.dot-secret { background: var(--secret); }
.banner { display: flex; align-items: center; justify-content: space-between; gap: 10px; background: var(--accent-soft); border: 1px solid var(--accent-tint); border-radius: 14px; padding: 8px 8px 8px 14px; font-size: 14px; }
.welcome { background: var(--surface); border: 1px solid var(--line); border-radius: 20px; padding: 20px; display: flex; flex-direction: column; gap: 10px; }
.welcome h1 { margin: 0; font-size: 22px; line-height: 1.2; }
.welcome p { margin: 0; line-height: 1.5; }
.welcome label { font-weight: 700; font-size: 14px; margin-top: 4px; }
.folder-row { display: flex; align-items: center; gap: 8px; }
.folder { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; direction: rtl; text-align: left; font-size: 14px; background: #F8F6FC; border: 1px solid #ECE8F5; border-radius: 10px; padding: 7px 10px; }
.vaults { display: flex; flex-direction: column; gap: 10px; }
.vault { background: var(--surface); border: 1px solid var(--line); border-radius: 18px; padding: 12px; display: flex; flex-direction: column; gap: 10px; }
.vault-head { display: flex; align-items: center; gap: 10px; }
.vault-name { display: flex; flex-direction: column; flex: 1; min-width: 0; }
.vault-name .muted { overflow-wrap: anywhere; }
.need { background: #F8F6FC; border: 1px solid #ECE8F5; border-radius: 14px; padding: 10px 12px; display: flex; flex-direction: column; gap: 6px; font-size: 14px; }
.need-secret { background: #FBEDED; border-color: #F0CDCF; }
.need .lbl { font-size: 13px; font-weight: 700; margin-top: 4px; }
.need .field { font-size: 14px; padding: 8px 10px; }
.need .actions { margin-top: 2px; }
.center { text-align: center; padding: 24px 8px; }
.foot { margin-top: auto; display: flex; flex-direction: column; gap: 8px; }
.foot > .actions { justify-content: flex-start; }
.recent summary { cursor: pointer; font-size: 13px; color: var(--muted); }
.recent pre { font-size: 11px; line-height: 1.5; white-space: pre-wrap; color: var(--muted); max-height: 160px; overflow-y: auto; }
.cmp-body { max-height: 22vh; }
.dialog .actions { position: sticky; bottom: -24px; background: #FFFFFF; padding: 10px 0 2px; }
.team-tag { font-weight: 400; font-size: 12px; color: var(--muted); background: var(--accent-soft); border-radius: 999px; padding: 1px 8px; margin-left: 8px; }
.teams { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
.teams li { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 14px; background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 2px 4px 2px 12px; }
.toast-d { position: fixed; left: 16px; right: 16px; bottom: 16px; background: var(--ink); color: #FFFFFF; border-radius: 14px; padding: 10px 14px; font-size: 14px; box-shadow: 0 10px 30px rgba(34, 30, 51, 0.25); }

318
web/src/desktop/main.tsx Normal file
View File

@@ -0,0 +1,318 @@
// The Lune window in the Mac app: connect this Mac, see each vault plainly, and make the few decisions only a person
// can (a held big change, a possible secret, a note changed in two places). Talks to the app, not to the hub.
import { StrictMode, useCallback, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { invoke } from '@tauri-apps/api/core';
import '../styles.css';
import './desktop.css';
import moon from './moon.svg';
type Level = 'current' | 'behind' | 'offline' | 'secret';
interface VaultStatus {
name: string;
path: string;
team: string | null;
level: Level;
headline: string;
last_synced: number | null;
waiting: number;
read_only: boolean;
running: boolean;
held: { message: string; removed: number; rewritten: number; total: number }[];
secrets: { path: string; found: string[] }[];
tidy: { note: string; copy: string; label: string }[];
case_clashes: string[];
}
interface Overview {
version: string;
connected: boolean;
teams: string[];
device: string;
folder: string;
level: Level;
summary: string;
vaults: VaultStatus[];
pending: { kind: 'join' | 'pair'; hub: string } | null;
update: string | null;
recent: string[];
}
interface Comparison {
note: string;
copy: string;
label: string;
copy_is_mine: boolean;
note_text: string | null;
copy_text: string | null;
}
const host = (url: string | null) => (url ? url.replace(/^https?:\/\//, '') : '');
const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;
function Dot({ level }: { level: Level }) {
return <span className={`dot dot-${level}`} aria-hidden="true" />;
}
/** Connecting: from the link the website opened (no code), or a hub address and code typed by hand. */
function Connect({ o, done, cancel }: { o: Overview; done: (msg: string) => void; cancel?: () => void }) {
const [name, setName] = useState(o.device);
const [folder, setFolder] = useState(o.folder);
const [hubUrl, setHubUrl] = useState('');
const [code, setCode] = useState('');
const [manual, setManual] = useState(!!cancel && !o.pending);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const fromLink = o.pending && !manual;
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setError('');
try {
done(await invoke<string>('connect', { name, folder, hubUrl: fromLink ? null : hubUrl, code: fromLink ? null : code }));
} catch (err) {
setError(String(err));
} finally {
setBusy(false);
}
};
const pick = async () => {
const path = await invoke<string | null>('choose_folder');
if (path) setFolder(path);
};
if (!o.pending && !manual) {
return (
<section className="welcome">
<img className="moon" src={moon} alt="" />
<h1 className="disp">Connect this Mac to your team</h1>
<p>Open your invite link and choose <b>Open Lune to join</b>. Already on the team? Open the team canvas in your browser and choose <b>Connect this Mac</b>.</p>
<button className="btn btn-ghost" onClick={() => setManual(true)}>I have a pairing code instead</button>
</section>
);
}
return (
<form className="welcome" onSubmit={submit}>
<span className="eyebrow">{fromLink ? (o.pending!.kind === 'join' ? 'Invite' : 'Connect') : 'Pairing code'}</span>
<h1 className="disp">
{fromLink ? (o.pending!.kind === 'join' ? `Join the team at ${host(o.pending!.hub)}` : `Connect to ${host(o.pending!.hub)}`) : 'Connect with a code'}
</h1>
{!fromLink && (
<>
<label htmlFor="hub">Team address</label>
<input id="hub" className="field" value={hubUrl} onChange={(e) => setHubUrl(e.target.value)} placeholder="lune.example.com" autoFocus />
<label htmlFor="code">Code from one of your devices</label>
<input id="code" className="field code" value={code} onChange={(e) => setCode(e.target.value)} placeholder="K7QD-4MXA" />
</>
)}
<label htmlFor="name">This Mac's name</label>
<input id="name" className="field" value={name} onChange={(e) => setName(e.target.value)} maxLength={40} />
<p className="muted">Your team sees it next to your changes.</p>
<label>Shared vaults go in</label>
<div className="folder-row">
<span className="folder" title={folder}><bdi>{folder}</bdi></span>
<button type="button" className="btn btn-small" onClick={pick}>Change…</button>
</div>
{error && <p className="error" role="alert">{error}</p>}
<button className="btn btn-primary" type="submit" disabled={busy || !name.trim() || (!fromLink && (!hubUrl.trim() || !code.trim()))}>
{busy ? 'Connecting…' : fromLink && o.pending!.kind === 'join' ? 'Join' : 'Connect'}
</button>
{fromLink ? (
<button type="button" className="btn btn-ghost" onClick={() => setManual(true)}>Use a pairing code instead</button>
) : o.pending ? (
<button type="button" className="btn btn-ghost" onClick={() => setManual(false)}>Back to the link</button>
) : (
<button type="button" className="btn btn-ghost" onClick={() => (cancel ? cancel() : setManual(false))}>Back</button>
)}
</form>
);
}
function SecretCard({ vault, s, act }: { vault: string; s: VaultStatus['secrets'][number]; act: (cmd: string, args: Record<string, unknown>, msg: string) => void }) {
const [pointer, setPointer] = useState('');
return (
<div className="need need-secret">
<b>{s.path} wasn't shared: it may contain a secret</b>
{s.found.map((f) => <span key={f} className="muted">{f}</span>)}
<label className="lbl" htmlFor={`p-${s.path}`}>Replace it with where to find it</label>
<input id={`p-${s.path}`} className="field" value={pointer} onChange={(e) => setPointer(e.target.value)} placeholder='e.g. "search prod-deploy in Secrets Manager"' />
<div className="actions">
<button className="btn btn-small" onClick={() => act('not_a_secret', { vault, path: s.path }, `OK — ${s.path} will be shared`)}>Not a secret</button>
<button className="btn btn-small btn-primary" disabled={!pointer.trim()} onClick={() => act('secret_pointer', { vault, path: s.path, pointer }, 'Replaced — sharing now')}>Replace</button>
</div>
</div>
);
}
function VaultCard({ v, several, act, compare }: { v: VaultStatus; several: boolean; act: (cmd: string, args: Record<string, unknown>, msg: string) => void; compare: (vault: string, copy: string) => void }) {
return (
<article className="vault" data-vault={v.name}>
<div className="vault-head">
<Dot level={v.level} />
<div className="vault-name">
<b>{v.name}{several && v.team && <span className="team-tag">{host(v.team)}</span>}</b>
<span className="muted">{v.headline}</span>
</div>
<button className="btn btn-small btn-ghost" onClick={() => act('open_folder', { vault: v.name }, '')}>Open folder</button>
</div>
{v.held.map((h) => (
<div key={h.message} className="need">
<b>A big change is waiting for you</b>
<span className="muted">"{h.message}" removes {h.removed} and rewrites {h.rewritten} of {plural(h.total, 'note')}. Nothing from this Mac is shared until you decide.</span>
<div className="actions">
<button className="btn btn-small" onClick={() => act('held_undo', { vault: v.name }, 'Brought everything back')}>Undo</button>
<button className="btn btn-small btn-primary" onClick={() => act('held_share', { vault: v.name }, 'Sharing it')}>Share anyway</button>
</div>
</div>
))}
{v.secrets.map((s) => <SecretCard key={s.path} vault={v.name} s={s} act={act} />)}
{v.tidy.map((t) => (
<div key={t.copy} className="need">
<b>{t.note} was changed in two places</b>
<span className="muted">Both versions are kept; pick one when you have a moment.</span>
<div className="actions">
<button className="btn btn-small btn-primary" onClick={() => compare(v.name, t.copy)}>Compare</button>
</div>
</div>
))}
</article>
);
}
/** Side by side (stacked in this narrow window); differing lines tinted. */
function CompareSheet({ vault, copy, close, done }: { vault: string; copy: string; close: () => void; done: (msg: string) => void }) {
const [c, setC] = useState<Comparison | null>(null);
const [error, setError] = useState('');
useEffect(() => { invoke<Comparison>('compare', { vault, copy }).then(setC).catch((e) => setError(String(e))); }, [vault, copy]);
const keep = async (which: 'note' | 'copy' | 'both') => {
try {
await invoke('tidy', { vault, copy, keep: which });
done(which === 'both' ? 'Kept both as separate notes' : 'Tidied — every device gets it shortly');
} catch (e) {
setError(String(e));
}
};
const column = (title: string, text: string | null, other: string | null, tint: string) => {
const others = new Set((other ?? '').split('\n'));
return (
<div className="cmp-col">
<div className="cmp-head">{title}</div>
<div className="cmp-body">
{text === null ? <span className="muted">Not shown (not a text note, or very large).</span>
: text.split('\n').map((line, i) => <div key={i} style={others.has(line) ? undefined : { background: tint, margin: '0 -14px', padding: '0 14px' }}>{line || ' '}</div>)}
</div>
</div>
);
};
const mine = c?.copy_is_mine;
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label="Compare two versions">
<div><span className="eyebrow">{vault} · {c?.note ?? ''}</span><h2 className="disp">Two versions of the same lines</h2></div>
{error && <p className="error">{error}</p>}
{c && (
<div className="cmp">
{column(mine ? 'The other version (in place)' : 'In place', c.note_text, c.copy_text, '#FBEBD3')}
{column(mine ? "This Mac's version" : `${c.label}'s version`, c.copy_text, c.note_text, '#E8E1FB')}
</div>
)}
<div className="actions">
<button className="btn" onClick={close}>Not now</button>
{c && (
<>
<button className="btn" onClick={() => keep('both')}>Keep both</button>
<button className="btn" onClick={() => keep('note')}>{mine ? 'Keep the other' : 'Keep the one in place'}</button>
<button className="btn btn-primary" onClick={() => keep('copy')}>{mine ? "Keep this Mac's" : `Keep ${c.label}'s`}</button>
</>
)}
</div>
</div>
</div>
);
}
function App() {
const [o, setO] = useState<Overview | null>(null);
const [error, setError] = useState('');
const [toast, setToast] = useState('');
const [comparing, setComparing] = useState<{ vault: string; copy: string } | null>(null);
const [joining, setJoining] = useState(false);
const load = useCallback(() => invoke<Overview>('overview').then(setO).catch((e) => setError(String(e))), []);
useEffect(() => {
load();
const t = setInterval(load, 2000);
return () => clearInterval(t);
}, [load]);
useEffect(() => {
if (!toast) return;
const t = setTimeout(() => setToast(''), 4000);
return () => clearTimeout(t);
}, [toast]);
const act = async (cmd: string, args: Record<string, unknown>, msg: string) => {
try {
await invoke(cmd, args);
if (msg) setToast(msg);
load();
} catch (e) {
setToast(String(e));
}
};
if (!o) return <main className="app">{error && <p className="error">{error}</p>}</main>;
return (
<main className="app">
<header className="top">
<img className="moon-small" src={moon} alt="" />
<div className="top-text">
<b className="disp">Lune</b>
<span className="muted"><Dot level={o.level} /> {o.summary}</span>
</div>
</header>
{o.update && (
<div className="banner">
<span>Lune {o.update} is ready.</span>
<button className="btn btn-small btn-primary" onClick={() => invoke('restart')}>Restart to update</button>
</div>
)}
{!o.connected || o.pending || joining ? (
<Connect o={o} done={(msg) => { setJoining(false); setToast(msg); load(); }} cancel={o.connected ? () => setJoining(false) : undefined} />
) : (
<>
<section className="vaults">
{o.vaults.length === 0 && <p className="muted center">Your vaults are on their way. They'll appear in {o.folder}.</p>}
{o.vaults.map((v) => <VaultCard key={v.path} v={v} several={o.teams.length > 1} act={act} compare={(vault, copy) => setComparing({ vault, copy })} />)}
</section>
<footer className="foot">
<span className="muted">{o.device} · Lune {o.version}</span>
<ul className="teams">
{o.teams.map((t) => (
<li key={t}>
<span>{host(t)}</span>
<button className="btn btn-small btn-ghost" onClick={() => act('open_canvas', { team: t }, '')}>Open canvas</button>
</li>
))}
</ul>
<div className="actions">
<button className="btn btn-small" onClick={() => act('share_now', {}, 'Sharing now')}>Share now</button>
<button className="btn btn-small" onClick={() => setJoining(true)}>Join another team</button>
</div>
{o.recent.length > 0 && (
<details className="recent">
<summary>Recent activity</summary>
<pre>{o.recent.join('\n')}</pre>
</details>
)}
</footer>
</>
)}
{comparing && <CompareSheet {...comparing} close={() => setComparing(null)} done={(msg) => { setComparing(null); setToast(msg); load(); }} />}
{toast && <div className="toast-d" role="status">{toast}</div>}
</main>
);
}
createRoot(document.getElementById('root')!).render(<StrictMode><App /></StrictMode>);

1
web/src/desktop/moon.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><mask id="m"><rect width="64" height="64" fill="#fff"/><circle cx="38" cy="26" r="16" fill="#000"/></mask></defs><rect x="2" y="2" width="60" height="60" rx="14" fill="#1F2A4D"/><circle cx="30" cy="34" r="17" fill="#F1E6C8" mask="url(#m)"/></svg>

After

Width:  |  Height:  |  Size: 313 B

View File

@@ -2,6 +2,7 @@ import { StrictMode, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { api, SignedOut, type CanvasData } from './api';
import { Canvas } from './Canvas';
import { JoinWithApp } from './MacApp';
import './styles.css';
/** Sign in with a code from one of your devices (no passwords, §8). */
@@ -34,7 +35,7 @@ function SignIn({ onDone }: { onDone: () => void }) {
);
}
/** What an invite link shows in a browser: how to join with the app. */
/** What an invite link shows in a browser: get the Mac app and join from it, or join a server from the terminal. */
function Join() {
const link = location.href;
return (
@@ -42,9 +43,11 @@ function Join() {
<div className="card">
<span className="eyebrow">Lune · invite</span>
<h1 className="disp">You're invited to a team</h1>
<p>Install the sync app, then join from the device you'll use (this link works once):</p>
<pre className="cmd">lunesync join {link} --name "My laptop"</pre>
<p className="muted">Pick any name for the device; your team sees it next to your changes. Shared vaults arrive in <code>~/Vaults</code>.</p>
<JoinWithApp link={link} />
<details>
<summary className="muted">Joining from a server or the terminal instead</summary>
<pre className="cmd">lunesync join {link} --name "My server"</pre>
</details>
</div>
</main>
);

View File

@@ -141,3 +141,10 @@ button:focus-visible, input:focus-visible, a:focus-visible { outline: 3px solid
.panel { animation: none; }
.stage, .bottombar, .fade { transition: none; }
}
/* Getting the Mac app */
.steps { margin: 0; padding-left: 22px; display: flex; flex-direction: column; gap: 14px; }
.steps li { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; }
.steps a.btn { text-decoration: none; display: inline-flex; align-items: center; }
.ov-sec a.btn { text-decoration: none; display: inline-flex; align-items: center; }
details summary { cursor: pointer; }

1
web/src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -1 +1 @@
{"root":["./src/canvas.tsx","./src/api.ts","./src/geometry.ts","./src/main.tsx"],"version":"5.6.3"}
{"root":["./src/canvas.tsx","./src/macapp.tsx","./src/api.ts","./src/geometry.ts","./src/main.tsx","./src/vite-env.d.ts","./src/desktop/main.tsx"],"version":"5.6.3"}

View File

@@ -0,0 +1,9 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// The Lune window inside the Mac app (desktop/): its own page, built next to the canvas, never served by the hub.
export default defineConfig({
plugins: [react()],
base: './',
build: { outDir: 'dist-desktop', emptyOutDir: true, rollupOptions: { input: 'desktop.html' } },
});