use std::thread;
use std::time::Duration;
use anyhow::{Context, Result, bail, ensure};
use chrono::Utc;
use qrcode::QrCode;
use qrcode::render::unicode::Dense1x2;
use second_brain_core::keys::move_aside_for_pairing;
use second_brain_core::machine;
use second_brain_sync::pairing::{JOIN_PENDING_FILE, JoinCode, reachable};
use serde::Deserialize;
use zeroize::{Zeroize, Zeroizing};
use super::recovery::show_phrase;
use super::restore::{daemon_answers, restart_daemon, wait_until_down};
use super::setup::daemon_ready;
use crate::{api, daemon};
const USAGE: &str = "usage: sb pair [--port <port>] [--restore-keys] | sb pair <code> [--host <host>] \
[--discard-local] | sb pair --stop-waiting";
const POLL: Duration = Duration::from_secs(1);
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum PairArgs {
Host {
port: Option<u16>,
restore_keys: bool,
},
Join {
code: String,
host: Option<String>,
discard_local: bool,
},
StopWaiting,
}
impl PairArgs {
pub(crate) fn parse(args: &[String]) -> Result<Self> {
let mut words = Vec::new();
let mut host = None;
let mut port = None;
let mut restore_keys = false;
let mut discard_local = false;
if args.iter().any(|a| a == "--stop-waiting") {
ensure!(
args.len() == 1,
"--stop-waiting takes nothing else; {USAGE}"
);
return Ok(Self::StopWaiting);
}
let mut rest = args.iter();
while let Some(arg) = rest.next() {
match arg.as_str() {
"--host" => host = Some(rest.next().context(USAGE)?.clone()),
"--restore-keys" => restore_keys = true,
"--discard-local" => discard_local = true,
"--port" => {
let value = rest.next().context(USAGE)?;
port = Some(
value
.parse()
.with_context(|| format!("{value:?} is not a port; {USAGE}"))?,
);
}
flag if flag.starts_with("--") => bail!("{USAGE}"),
word => words.push(word.to_string()),
}
}
if words.is_empty() {
if host.is_some() {
bail!("--host goes with the code shown on the other device; {USAGE}");
}
if discard_local {
bail!("--discard-local goes with the code shown on the other device; {USAGE}");
}
return Ok(Self::Host { port, restore_keys });
}
if port.is_some() || restore_keys {
bail!("--port and --restore-keys are for the device that shows the code; {USAGE}");
}
Ok(Self::Join {
code: words.join(" "),
host,
discard_local,
})
}
}
#[derive(Deserialize)]
struct Founded {
identity: String,
phrase: String,
fingerprint: String,
}
impl Drop for Founded {
fn drop(&mut self) {
self.phrase.zeroize();
}
}
#[derive(Deserialize)]
struct Device {
machine_id: String,
name: String,
}
#[derive(Deserialize)]
struct Status {
state: String,
code: Option<String>,
invite: Option<String>,
retired: u32,
expires_in_secs: u64,
device: Option<Device>,
last_error: Option<String>,
}
impl Drop for Status {
fn drop(&mut self) {
self.code.zeroize();
self.invite.zeroize();
}
}
#[derive(Deserialize)]
struct Started {
#[serde(flatten)]
status: Status,
addresses: Vec<String>,
port: u16,
default_port: bool,
founded: Option<Founded>,
}
#[derive(Deserialize)]
struct Joined {
identity: String,
host: Device,
epochs: usize,
moved: bool,
known_hosts: Vec<String>,
warning: Option<String>,
}
pub(crate) fn cmd_pair(args: &[String]) -> Result<()> {
match PairArgs::parse(args)? {
PairArgs::Host { port, restore_keys } => host(port, restore_keys),
PairArgs::Join {
code,
host,
discard_local: false,
} => join(code, host),
PairArgs::Join {
code,
host,
discard_local: true,
} => discard_local_and_join(code, host),
PairArgs::StopWaiting => {
if stop_waiting()? {
eprintln!("this device no longer waits for its first sync and ingests from now on");
} else {
eprintln!("this device was not waiting for its first sync");
}
Ok(())
}
}
}
pub(crate) fn stop_waiting() -> Result<bool> {
let client = api::client(Duration::from_secs(30))?;
let body: serde_json::Value = api::daemon_ok(
client
.post(format!("{}/v1/pair/stop-waiting", api::base_url()))
.send()
.context("asking the daemon to stop waiting for its first sync")?,
)?
.json()
.context("reading the daemon's answer")?;
Ok(body["cancelled"] == serde_json::Value::Bool(true))
}
fn host(port: Option<u16>, restore_keys: bool) -> Result<()> {
let client = api::client(Duration::from_secs(60))?;
let base = api::base_url();
let started: Started = api::daemon_ok(
client
.post(format!("{base}/v1/pair/start"))
.json(&serde_json::json!({ "port": port, "restore_keys": restore_keys }))
.send()
.context("asking the daemon to open a pairing listener")?,
)?
.json()
.context("reading the pairing listener's details")?;
if let Some(founded) = &started.founded {
println!(
"This device had no sync identity, so it started one ({}).",
founded.identity
);
print!("{}", *show_phrase(&founded.phrase, &founded.fingerprint));
}
let target = join_target(&started.addresses, started.port, started.default_port);
let shown = |status: &Status| {
if restore_keys {
show_restore_code(status, &target)
} else {
show_code(status, &target)
}
};
print!("{}", shown(&started.status)?);
let mut retired = started.status.retired;
let mut last_error = None;
loop {
thread::sleep(POLL);
let status: Status = api::daemon_ok(
client
.get(format!("{base}/v1/pair/status"))
.send()
.context("asking the daemon how pairing is going")?,
)?
.json()
.context("reading the pairing status")?;
if status.last_error.is_some() && status.last_error != last_error {
last_error.clone_from(&status.last_error);
eprintln!(
"a device proved the code but did not join: {}",
status.last_error.as_deref().unwrap_or_default()
);
}
match status.state.as_str() {
"waiting" if status.retired != retired => {
retired = status.retired;
println!("\nThree wrong codes were tried, so that code is retired.");
print!("{}", shown(&status)?);
}
"waiting" => {}
"paired" => {
let device = status
.device
.as_ref()
.context("the daemon named no device")?;
println!("Paired {} ({}).", device.name, device.machine_id);
return Ok(());
}
"handed_over" => {
let device = status
.device
.as_ref()
.context("the daemon named no device")?;
println!("Handed this device's keys to {}.", device.name);
return Ok(());
}
"expired" => bail!("no device joined within 10 minutes; run `sb pair` again"),
_ => bail!("the pairing listener was closed; run `sb pair` again"),
}
}
}
fn join_target(addresses: &[String], port: u16, default_port: bool) -> String {
let host = addresses.first().map_or("<this device>", String::as_str);
if default_port {
host.to_string()
} else if host.contains(':') {
format!("[{host}]:{port}")
} else {
format!("{host}:{port}")
}
}
fn show_restore_code(status: &Status, target: &str) -> Result<String> {
let code = status.code.as_deref().context("the daemon sent no code")?;
let minutes = status.expires_in_secs.div_ceil(60);
Ok(format!(
"\nThis device hands every sync key it holds to a device restoring a backup, and adds \
no device.\nCode, open for {minutes} more minutes:\n\n {code}\n\n\
On the restoring device run:\n\n sb restore <backup-dir> --code {code} --host {target}\n"
))
}
fn show_code(status: &Status, target: &str) -> Result<String> {
let code = status.code.as_deref().context("the daemon sent no code")?;
let invite = status
.invite
.as_deref()
.context("the daemon sent no invite")?;
let qr = QrCode::new(invite.as_bytes())
.context("drawing the pairing QR")?
.render::<Dense1x2>()
.dark_color(Dense1x2::Light)
.light_color(Dense1x2::Dark)
.quiet_zone(true)
.build();
let minutes = status.expires_in_secs.div_ceil(60);
Ok(format!(
"\nPairing code, open for {minutes} more minutes:\n\n {code}\n\n\
On the new device run:\n\n sb pair {code} --host {target}\n\n\
or scan this invite:\n\n{qr}\n"
))
}
fn join(mut code: String, host: Option<String>) -> Result<()> {
let client = api::client(Duration::from_secs(120))?;
let sent = client
.post(format!("{}/v1/pair/join", api::base_url()))
.json(&serde_json::json!({ "code": code, "host": host }))
.send();
code.zeroize();
let joined: Joined = api::daemon_ok(sent.context("asking the daemon to join")?)?
.json()
.context("reading the pairing result")?;
println!("{}", describe_join(&joined));
Ok(())
}
fn discard_local_and_join(code: String, host: Option<String>) -> Result<()> {
let code = Zeroizing::new(code);
discard_preflight(&code, host.as_deref())?;
ensure!(
daemon_answers(),
"the daemon is not running; start it with `sb start`, then run this again"
);
let data_dir = machine::data_dir()?;
eprintln!("stopping the daemon so this device's store can be moved aside");
daemon::control(daemon::Action::Stop)
.context("stopping the daemon; stop it with `sb stop` and run this again")?;
wait_until_down()?;
let moved = move_aside_for_pairing(
&data_dir,
Utc::now().timestamp_micros(),
&[JOIN_PENDING_FILE],
);
if moved.is_ok() || data_dir.join("brain.db").exists() {
restart_daemon();
} else {
eprintln!("the daemon stays stopped, since the data dir is not where it starts from");
}
let aside = moved.context("moving this device's store aside")?;
eprintln!(
"moved this device's store to {}; it is deleted after 90 days, and until then \
POST /v1/maintenance/plaintext-copy with {{\"aside\": \"{}\"}} writes a readable copy",
aside.display(),
aside.file_name().unwrap_or_default().to_string_lossy()
);
let next = |what: &str| {
format!(
"{what}; `sb pair <code>` joins from the empty store, with this code while the other \
device still shows it; the earlier store is at {}, and moving it back in place of \
the empty one with the daemon stopped undoes the discard",
aside.display()
)
};
if !daemon_ready()? {
bail!(next("the daemon did not come up"));
}
join(code.to_string(), host).with_context(|| next("the join failed"))
}
fn discard_preflight(code: &str, host: Option<&str>) -> Result<()> {
let addresses = JoinCode::parse(code)?.addresses(host)?;
ensure!(
!addresses.is_empty(),
"--discard-local needs --host <host>, as `sb pair` shows on the pairing device, so that \
device is checked before anything moves; nothing was moved"
);
reachable(&addresses).context("nothing was moved")
}
fn describe_join(joined: &Joined) -> String {
let mut out = format!(
"Paired with {} ({}) into sync identity {}; this device opens {} key epochs.",
joined.host.name, joined.host.machine_id, joined.identity, joined.epochs
);
if joined.moved {
out.push_str(
"\nThis device left its earlier identity; its memories stay and sync into this one.",
);
}
if joined.known_hosts.is_empty() {
if joined.warning.is_none() {
out.push_str(&format!(
"\n{} runs no sshd this device can see, so it syncs by reaching this device.",
joined.host.name
));
}
} else {
out.push_str(&format!(
"\nPinned {}'s ssh host key in ~/.second-brain/known_hosts for: {}.",
joined.host.name,
joined
.known_hosts
.iter()
.filter_map(|entry| entry.split_whitespace().next())
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect::<Vec<_>>()
.join(", ")
));
}
if let Some(warning) = &joined.warning {
out.push_str(&format!("\nWarning: {warning}"));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn words(line: &str) -> Vec<String> {
line.split_whitespace().map(str::to_string).collect()
}
#[test]
fn arguments_parse_into_hosting_or_joining() {
assert_eq!(
PairArgs::parse(&[]).unwrap(),
PairArgs::Host {
port: None,
restore_keys: false
}
);
assert_eq!(
PairArgs::parse(&words("--port 7300")).unwrap(),
PairArgs::Host {
port: Some(7300),
restore_keys: false
}
);
assert_eq!(
PairArgs::parse(&words("--restore-keys --port 7300")).unwrap(),
PairArgs::Host {
port: Some(7300),
restore_keys: true
}
);
assert_eq!(
PairArgs::parse(&words("acid-able-act-add --host desk")).unwrap(),
PairArgs::Join {
code: "acid-able-act-add".into(),
host: Some("desk".into()),
discard_local: false
}
);
assert_eq!(
PairArgs::parse(&words("acid able act add")).unwrap(),
PairArgs::Join {
code: "acid able act add".into(),
host: None,
discard_local: false
}
);
assert_eq!(
PairArgs::parse(&words("--discard-local acid-able-act-add")).unwrap(),
PairArgs::Join {
code: "acid-able-act-add".into(),
host: None,
discard_local: true
}
);
assert_eq!(
PairArgs::parse(&words("--stop-waiting")).unwrap(),
PairArgs::StopWaiting
);
for bad in [
"--stop-waiting code",
"--port 7300 --stop-waiting",
"--host desk",
"--port",
"--port many",
"code --port 7300",
"--verbose",
"code --host",
"--discard-local",
"code --restore-keys",
"--stop-waiting --restore-keys",
] {
assert!(PairArgs::parse(&words(bad)).is_err(), "{bad}");
}
}
#[test]
fn the_join_command_names_the_port_only_when_it_is_not_the_default() {
let addresses = vec!["192.0.2.4".to_string(), "desk".to_string()];
assert_eq!(join_target(&addresses, 7201, true), "192.0.2.4");
assert_eq!(join_target(&addresses, 40001, false), "192.0.2.4:40001");
assert_eq!(
join_target(&["fe80::1".into()], 40001, false),
"[fe80::1]:40001"
);
}
#[test]
fn the_shown_code_carries_the_join_command_and_a_qr() {
let status = Status {
state: "waiting".into(),
code: Some("acid-able-act-add".into()),
invite: Some("sb-pair:00112233445566778899aabbccddeeff@desk:7201".into()),
retired: 0,
expires_in_secs: 599,
device: None,
last_error: None,
};
let shown = show_code(&status, "desk").unwrap();
assert!(
shown.contains("sb pair acid-able-act-add --host desk"),
"{shown}"
);
assert!(shown.contains("10 more minutes"), "{shown}");
assert!(
shown.contains('\u{2580}') || shown.contains('\u{2584}'),
"{shown}"
);
}
#[test]
fn a_discard_with_a_bad_code_or_no_listener_stops_before_touching_anything() {
assert!(discard_preflight("not a pairing code", None).is_err());
let err = discard_preflight("acid-able-act-add", None).unwrap_err();
assert!(format!("{err:#}").contains("--host"), "{err:#}");
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = closed.local_addr().unwrap().port();
drop(closed);
let err =
discard_preflight("acid-able-act-add", Some(&format!("127.0.0.1:{port}"))).unwrap_err();
assert!(format!("{err:#}").contains("nothing was moved"), "{err:#}");
}
#[test]
fn the_restore_code_names_the_restore_command_and_no_join() {
let status = Status {
state: "waiting".into(),
code: Some("acid-able-act-add".into()),
invite: Some("sb-pair:00112233445566778899aabbccddeeff@desk:7201".into()),
retired: 0,
expires_in_secs: 599,
device: None,
last_error: None,
};
let shown = show_restore_code(&status, "desk").unwrap();
assert!(
shown.contains("sb restore <backup-dir> --code acid-able-act-add --host desk"),
"{shown}"
);
assert!(!shown.contains("sb pair acid"), "{shown}");
}
#[test]
fn a_join_report_names_the_pinned_hosts_and_a_move() {
let joined = Joined {
identity: "f-tag".into(),
host: Device {
machine_id: "m-1".into(),
name: "desk".into(),
},
epochs: 2,
moved: true,
known_hosts: vec![
"desk ssh-ed25519 AAAA".into(),
"192.0.2.2 ssh-ed25519 AAAA".into(),
"desk ssh-rsa BBBB".into(),
],
warning: None,
};
let shown = describe_join(&joined);
assert!(shown.contains("opens 2 key epochs"), "{shown}");
assert!(shown.contains("left its earlier identity"), "{shown}");
assert!(shown.contains("for: 192.0.2.2, desk."), "{shown}");
}
#[test]
fn a_join_whose_host_keys_were_not_pinned_shows_the_warning() {
let joined: Joined = serde_json::from_value(serde_json::json!({
"identity": "f-tag",
"host": {"machine_id": "m-1", "name": "desk"},
"epochs": 1,
"moved": false,
"devices": 1,
"known_hosts": [],
"warning": "the host keys were not pinned, so ssh will ask you to trust desk",
}))
.unwrap();
let shown = describe_join(&joined);
assert!(shown.starts_with("Paired with desk"), "{shown}");
assert!(
shown.contains("Warning: the host keys were not pinned"),
"{shown}"
);
assert!(!shown.contains("runs no sshd"), "{shown}");
let without: Joined = serde_json::from_value(serde_json::json!({
"identity": "f-tag",
"host": {"machine_id": "m-1", "name": "desk"},
"epochs": 1,
"moved": false,
"known_hosts": [],
}))
.unwrap();
assert!(!describe_join(&without).contains("Warning"));
let pinned_but_unacked: Joined = serde_json::from_value(serde_json::json!({
"identity": "f-tag",
"host": {"machine_id": "m-1", "name": "desk"},
"epochs": 1,
"moved": false,
"known_hosts": ["desk ssh-ed25519 AAAA"],
"warning": "the join is done, but desk was not told the join succeeded",
}))
.unwrap();
let shown = describe_join(&pinned_but_unacked);
assert!(shown.contains("Pinned desk's ssh host key"), "{shown}");
assert!(shown.contains("Warning: the join is done"), "{shown}");
}
}