use std::io::IsTerminal;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use zeroize::{Zeroize, Zeroizing};
use crate::api;
const USAGE: &str = "usage: sb recovery [new | remove <fingerprint>]";
#[derive(Debug, Deserialize)]
pub(crate) struct RecoveryState {
pub(crate) identity: Option<String>,
pub(crate) fingerprints: Vec<String>,
pub(crate) offered: bool,
#[serde(default)]
pub(crate) retired: Vec<String>,
}
#[derive(Deserialize)]
struct NewPhrase {
phrase: String,
fingerprint: String,
}
impl Drop for NewPhrase {
fn drop(&mut self) {
self.phrase.zeroize();
}
}
pub(crate) fn cmd_recovery(args: &[String]) -> Result<()> {
match args.iter().map(String::as_str).collect::<Vec<_>>()[..] {
[] => {
let state = fetch_state()?;
println!("{}", describe(&state));
Ok(())
}
["new"] => {
let phrase = make_phrase()?;
print!("{}", *show_phrase(&phrase.phrase, &phrase.fingerprint));
Ok(())
}
["remove", fingerprint] => {
println!("{}", describe_retired(&retire(fingerprint)?));
Ok(())
}
_ => bail!("{USAGE}"),
}
}
fn describe(state: &RecoveryState) -> String {
let trusted = match (&state.identity, state.fingerprints.as_slice()) {
(None, _) => {
return "this device has no sync identity yet, so there is nothing to recover".into();
}
(Some(_), []) => "no recovery phrase: losing every device loses the memory; \
make one with `sb recovery new`"
.to_string(),
(Some(_), prints) => format!(
"recovery phrases this device wraps its keys to: {}",
prints.join(", ")
),
};
if state.retired.is_empty() {
trusted
} else {
format!(
"{trusted}\nretired recovery phrases, which open no newer key: {}",
state.retired.join(", ")
)
}
}
#[derive(Debug, Deserialize)]
struct Retired {
fingerprint: String,
epoch: Option<RetiredEpoch>,
}
#[derive(Debug, Deserialize)]
struct RetiredEpoch {
number: u32,
}
fn describe_retired(retired: &Retired) -> String {
let epoch = match &retired.epoch {
Some(epoch) => format!(" under key epoch {}", epoch.number),
None => String::new(),
};
format!(
"retired recovery phrase {}: every device deletes its keys for it at its next sync and \
moves its store to a new key{epoch}; make a new phrase with `sb recovery new` if this \
was the only one",
retired.fingerprint
)
}
fn retire(fingerprint: &str) -> Result<Retired> {
let client = api::client(Duration::from_secs(60))?;
api::daemon_ok(
client
.post(format!("{}/v1/keys/recovery/remove", api::base_url()))
.json(&serde_json::json!({ "fingerprint": fingerprint }))
.send()
.context("asking the daemon to retire the recovery phrase")?,
)?
.json()
.context("reading the retired recovery phrase")
}
pub(crate) fn show_phrase(phrase: &str, fingerprint: &str) -> Zeroizing<String> {
Zeroizing::new(format!(
"\nRecovery phrase (fingerprint {fingerprint}), shown only this once:\n\n {phrase}\n\n\
Write it down and keep it away from your devices. With a copy of any device's data dir \
it restores your memory through `sb restore` after every device is lost. It only \
decrypts and grants no access to your devices.\n"
))
}
fn fetch_state() -> Result<RecoveryState> {
let client = api::client(Duration::from_secs(30))?;
api::daemon_ok(
client
.get(format!("{}/v1/keys/recovery", api::base_url()))
.send()
.context("asking the daemon about recovery phrases")?,
)?
.json()
.context("reading the daemon's recovery state")
}
fn make_phrase() -> Result<NewPhrase> {
let client = api::client(Duration::from_secs(60))?;
api::daemon_ok(
client
.post(format!("{}/v1/keys/recovery", api::base_url()))
.json(&serde_json::json!({}))
.send()
.context("asking the daemon for a recovery phrase")?,
)?
.json()
.context("reading the recovery phrase")
}
fn mark_offered() -> Result<()> {
let client = api::client(Duration::from_secs(30))?;
api::daemon_ok(
client
.post(format!("{}/v1/keys/recovery/offered", api::base_url()))
.json(&serde_json::json!({}))
.send()
.context("recording the recovery phrase offer")?,
)?;
Ok(())
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Offer {
Skip,
Ask,
Hint,
}
pub(crate) fn offer_for(state: &RecoveryState, interactive: bool) -> Offer {
if state.identity.is_none() || !state.fingerprints.is_empty() || state.offered {
Offer::Skip
} else if interactive {
Offer::Ask
} else {
Offer::Hint
}
}
pub(crate) fn accepted(answer: &str) -> bool {
matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
}
pub(crate) const HINT: &str =
" this sync identity has no recovery phrase; make one with `sb recovery new`";
pub(crate) fn offer_once() -> Result<()> {
let state = fetch_state()?;
let interactive = std::io::stdin().is_terminal() && std::io::stderr().is_terminal();
match offer_for(&state, interactive) {
Offer::Skip => return Ok(()),
Offer::Hint => {
eprintln!("{HINT}");
return Ok(());
}
Offer::Ask => {
eprint!(
" no recovery phrase yet: without one, losing every device loses the memory.\n \
make one now? [y/N] "
);
let mut answer = String::new();
std::io::stdin()
.read_line(&mut answer)
.context("reading the answer")?;
if accepted(&answer) {
let phrase = make_phrase()?;
eprint!("{}", *show_phrase(&phrase.phrase, &phrase.fingerprint));
return Ok(());
}
}
}
mark_offered()
}
#[cfg(test)]
mod tests {
use super::*;
fn state(identity: bool, prints: &[&str], offered: bool) -> RecoveryState {
RecoveryState {
identity: identity.then(|| "m-tag".to_string()),
fingerprints: prints.iter().map(|p| p.to_string()).collect(),
offered,
retired: Vec::new(),
}
}
#[test]
fn the_offer_is_made_once_to_an_identity_without_a_phrase() {
for (state, interactive, expected) in [
(state(true, &[], false), true, Offer::Ask),
(state(true, &[], false), false, Offer::Hint),
(state(true, &[], true), true, Offer::Skip),
(state(true, &["ab"], false), true, Offer::Skip),
(state(false, &[], false), true, Offer::Skip),
] {
assert_eq!(offer_for(&state, interactive), expected, "{state:?}");
}
}
#[test]
fn only_yes_accepts() {
for (answer, expected) in [("y\n", true), ("YES", true), ("\n", false), ("no", false)] {
assert_eq!(accepted(answer), expected, "{answer:?}");
}
}
#[test]
fn retired_phrases_are_listed_apart_from_trusted_ones() {
let mut with_retired = state(true, &["ab"], true);
with_retired.retired = vec!["cd".to_string()];
let text = describe(&with_retired);
assert!(text.contains("wraps its keys to: ab\n"), "{text}");
assert!(text.contains("retired recovery phrases, which open no newer key: cd"));
let mut only_retired = state(true, &[], true);
only_retired.retired = vec!["cd".to_string()];
assert!(describe(&only_retired).contains("sb recovery new"));
}
#[test]
fn a_retirement_names_its_epoch_when_one_was_minted() {
let minted: Retired =
serde_json::from_str(r#"{"fingerprint":"ab","epoch":{"number":3,"key_id":"x"}}"#)
.unwrap();
assert!(describe_retired(&minted).contains("ab"));
assert!(describe_retired(&minted).contains("epoch 3"));
let none: Retired = serde_json::from_str(r#"{"fingerprint":"ab","epoch":null}"#).unwrap();
assert!(!describe_retired(&none).contains("epoch"));
}
#[test]
fn the_state_names_the_fix_when_there_is_no_phrase() {
assert!(describe(&state(true, &[], false)).contains("sb recovery new"));
assert!(describe(&state(true, &["ab", "cd"], true)).contains("ab, cd"));
assert!(describe(&state(false, &[], false)).contains("no sync identity"));
}
}