second-brain-cli 0.13.4

Memory layer for AI coding agents: ingest, recall, and sync across machines
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail, ensure};
use second_brain_core::keys::{
    BackupKeys, BackupRestore, DeviceKeys, HeldEpoch, KeyStorage, RecoveryPhrase, check_backup,
    every_held_epoch_in, open_handed, restore_backup_with,
};
use second_brain_core::machine;
use second_brain_sync::pairing::{JoinCode, KeyPurpose, KeyRequest, fetch_keys};

use zeroize::{Zeroize, Zeroizing};

use crate::api;
use crate::commands::recovery::show_phrase;
use crate::daemon;

const USAGE: &str = "usage: sb restore <backup-dir> [--code <code> [--host <host>] | --own-keys]\n\
    Restores a copy of a data dir as a new device of a new identity, opening it with its \
    recovery phrase (read from stdin), with keys a surviving device hands over through \
    `sb pair --restore-keys` (--code), or with this device's own past keys (--own-keys).";
const STOP_LIMIT: Duration = Duration::from_secs(30);

#[derive(PartialEq, Eq)]
pub(crate) enum KeySource {
    Phrase,
    Handed { code: String, host: Option<String> },
    Own,
}

impl std::fmt::Debug for KeySource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Phrase => f.write_str("Phrase"),
            Self::Handed { host, .. } => write!(f, "Handed {{ host: {host:?}, .. }}"),
            Self::Own => f.write_str("Own"),
        }
    }
}

impl Drop for KeySource {
    fn drop(&mut self) {
        if let Self::Handed { code, .. } = self {
            code.zeroize();
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) struct RestoreArgs {
    pub(crate) backup: PathBuf,
    pub(crate) keys: KeySource,
}

/// `args` are the words after `restore`.
pub(crate) fn parse(args: &[String]) -> Result<RestoreArgs> {
    let mut backup = None;
    let mut code = None;
    let mut host = None;
    let mut own = false;
    let mut rest = args.iter();
    while let Some(arg) = rest.next() {
        match arg.as_str() {
            "--code" => code = Some(rest.next().context(USAGE)?.clone()),
            "--host" => host = Some(rest.next().context(USAGE)?.clone()),
            "--own-keys" => own = true,
            flag if flag.starts_with("--") => bail!("{USAGE}"),
            path if backup.is_none() => backup = Some(PathBuf::from(path)),
            _ => bail!("{USAGE}"),
        }
    }
    let backup = backup.context(USAGE)?;
    let keys = match (code, host, own) {
        (None, None, false) => KeySource::Phrase,
        (Some(code), host, false) => KeySource::Handed { code, host },
        (None, None, true) => KeySource::Own,
        (None, Some(_), _) => bail!("--host goes with --code; {USAGE}"),
        (Some(mut code), _, true) => {
            code.zeroize();
            bail!("--code and --own-keys are two ways to open the backup; pick one. {USAGE}")
        }
    };
    Ok(RestoreArgs { backup, keys })
}

enum Keys {
    Phrase(RecoveryPhrase),
    Epochs(Vec<HeldEpoch>),
    Own,
}

pub(crate) fn cmd_restore(args: &[String]) -> Result<()> {
    let args = parse(args)?;
    check_backup(&args.backup)?;
    let data_dir = machine::data_dir()?;
    let keys = match &args.keys {
        KeySource::Phrase => Keys::Phrase(read_phrase()?),
        KeySource::Handed { code, host } => {
            Keys::Epochs(fetch_handed_keys(code, host.as_deref(), &data_dir)?)
        }
        KeySource::Own => Keys::Own,
    };
    let was_running = daemon_answers();
    if was_running {
        eprintln!("stopping the daemon so the data dir can be replaced");
        daemon::control(daemon::Action::Stop)
            .context("stopping the daemon; stop it with `sb stop` and run the restore again")?;
        wait_until_down()?;
    }
    let result = restore(&args.backup, &data_dir, &keys);
    if was_running {
        restart_daemon();
    }
    let message = result?;
    print!("{}", *message);
    if !was_running {
        eprintln!("start the daemon with `sb start`");
    }
    Ok(())
}

/// Takes every key epoch the device showing `code` holds, through a
/// channel only this run can open.
fn fetch_handed_keys(code: &str, host: Option<&str>, data_dir: &Path) -> Result<Vec<HeldEpoch>> {
    let code = JoinCode::parse(code)?;
    let addresses = code.addresses(host)?;
    ensure!(
        !addresses.is_empty(),
        "name the device showing the code with --host, as `sb pair --restore-keys` shows there"
    );
    let transit = DeviceKeys::generate()?;
    let request = KeyRequest {
        purpose: KeyPurpose::RestoreKeys,
        name: match machine::MachineIdentity::load(data_dir) {
            Ok(Some(machine)) => machine.name,
            Ok(None) => "a device restoring a backup".to_string(),
            Err(e) => {
                tracing::warn!("cannot read this device's name: {e:#}");
                "a device restoring a backup".to_string()
            }
        },
        age_recipient: transit.age_recipient().to_string(),
    };
    let (held, unacked) = fetch_keys(&addresses, &code, &request, |handover| {
        eprintln!(
            "{} handed over {} key epochs",
            handover.name,
            handover.envelopes.len()
        );
        open_handed(&handover.envelopes, &transit)
    })?;
    if let Some(reason) = unacked {
        eprintln!("warning: the other device was not told the keys arrived: {reason}");
    }
    Ok(held)
}

fn restore(backup: &Path, data_dir: &Path, keys: &Keys) -> Result<Zeroizing<String>> {
    let storage = KeyStorage::detect();
    let own;
    let keys = match keys {
        Keys::Phrase(phrase) => BackupKeys::Phrase(phrase),
        Keys::Epochs(held) => BackupKeys::Epochs(held),
        Keys::Own => {
            own = every_held_epoch_in(data_dir, &storage)?;
            BackupKeys::Epochs(&own)
        }
    };
    let restored = restore_backup_with(&BackupRestore {
        backup,
        data_dir,
        keys,
        storage: &storage,
        now_micros: chrono::Utc::now().timestamp_micros(),
    })?;
    let mut out = Zeroizing::new(format!(
        "restored {} into {} as device {} ({}) of a new sync identity {}\n",
        backup.display(),
        data_dir.display(),
        restored.machine.name,
        restored.machine.id,
        restored.identity.as_str()
    ));
    if let Some(aside) = &restored.moved_aside {
        out.push_str(&format!(
            "the data dir it replaced was moved to {}; it is deleted after 90 days, and until \
             then POST /v1/maintenance/plaintext-copy with {{\"aside\": \"{}\"}} writes a \
             readable copy\n",
            aside.display(),
            aside.file_name().unwrap_or_default().to_string_lossy()
        ));
    }
    out.push_str(
        "other devices still belong to the old identity; pair each of them with this one again, \
         with `sb pair <code> --discard-local` where what it holds should not be merged in\n",
    );
    out.push_str(&show_phrase(
        &restored.phrase.expose_text(),
        &restored.phrase.fingerprint()?,
    ));
    Ok(out)
}

fn read_phrase() -> Result<RecoveryPhrase> {
    eprint!("recovery phrase of the backup: ");
    let mut line = Zeroizing::new(String::new());
    std::io::stdin()
        .read_line(&mut line)
        .context("reading the recovery phrase from stdin")?;
    RecoveryPhrase::parse(&line)
}

pub(crate) fn daemon_answers() -> bool {
    let Ok(client) = api::open_client(Duration::from_secs(2)) else {
        return false;
    };
    client
        .get(format!("{}/health", api::base_url()))
        .send()
        .is_ok()
}

pub(crate) fn restart_daemon() {
    match daemon::control(daemon::Action::Start) {
        Ok(()) => eprintln!("daemon started"),
        Err(e) => eprintln!("warning: starting the daemon failed: {e:#}; run `sb start`"),
    }
}

pub(crate) fn wait_until_down() -> Result<()> {
    let started = Instant::now();
    while daemon_answers() {
        if started.elapsed() > STOP_LIMIT {
            bail!(
                "the daemon still answers {}s after it was stopped; stop it and run the command again",
                STOP_LIMIT.as_secs()
            );
        }
        std::thread::sleep(Duration::from_millis(250));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn words(args: &[&str]) -> Vec<String> {
        args.iter().map(|a| a.to_string()).collect()
    }

    #[test]
    fn restore_takes_one_backup_dir_and_one_way_to_open_it() {
        let parsed = |args: &[&str]| parse(&words(args)).unwrap();
        assert_eq!(
            parsed(&["/backups/laptop"]),
            RestoreArgs {
                backup: PathBuf::from("/backups/laptop"),
                keys: KeySource::Phrase
            }
        );
        assert_eq!(
            parsed(&["/backups/laptop", "--code", "a-b-c-d", "--host", "desk"]).keys,
            KeySource::Handed {
                code: "a-b-c-d".into(),
                host: Some("desk".into())
            }
        );
        assert_eq!(
            parsed(&["--code", "a-b-c-d", "/backups/laptop"]).keys,
            KeySource::Handed {
                code: "a-b-c-d".into(),
                host: None
            }
        );
        assert_eq!(
            parsed(&["/backups/laptop", "--own-keys"]).keys,
            KeySource::Own
        );
        for bad in [
            &[][..],
            &["a", "b"],
            &["--yes"],
            &["a", "--code"],
            &["a", "--host", "desk"],
            &["a", "--code", "x", "--own-keys"],
        ] {
            let err = format!("{:#}", parse(&words(bad)).unwrap_err());
            assert!(err.contains("sb restore <backup-dir>"), "{bad:?}: {err}");
        }
    }
}