Skip to main content

second_brain_sync/keyring/
recovery.rs

1use age::x25519::Recipient;
2use anyhow::{Context, Result};
3use second_brain_core::keys::{
4    Epoch, IdentityKey, IdentityTag, RecoveryPhrase, recovery_fingerprint, wrap_for_recovery,
5};
6use serde::Serialize;
7
8use super::Keyring;
9
10#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
11pub struct RecoveryState {
12    pub identity: Option<String>,
13    /// Fingerprints of the phrases this device wraps its epochs to.
14    pub fingerprints: Vec<String>,
15    pub offered: bool,
16    /// Fingerprints of the retired phrases.
17    pub retired: Vec<String>,
18}
19
20impl Keyring<'_> {
21    pub fn recovery_state(&self) -> Result<RecoveryState> {
22        let (fingerprints, retired) = match &self.identity {
23            Some(tag) => (
24                self.store
25                    .recovery_recipients(tag)?
26                    .iter()
27                    .map(|r| recovery_fingerprint(&r.to_string()))
28                    .collect(),
29                self.store.retired_fingerprints()?.into_iter().collect(),
30            ),
31            None => (Vec::new(), Vec::new()),
32        };
33        Ok(RecoveryState {
34            identity: self.identity.as_ref().map(|t| t.as_str().to_string()),
35            fingerprints,
36            offered: self.store.recovery_offered()?,
37            retired,
38        })
39    }
40
41    /// Makes a phrase for this identity, lists its fingerprint in this
42    /// device's signed row and then wraps every epoch this device holds to
43    /// it, so a failed row write leaves no phrase trusted unseen. The phrase
44    /// is returned once and never stored.
45    pub fn add_recovery_phrase(&self, now_micros: i64) -> Result<RecoveryPhrase> {
46        let tag = self
47            .identity
48            .as_ref()
49            .context("this device has no sync identity yet, so there is nothing to recover")?;
50        let phrase = RecoveryPhrase::generate()?;
51        let recipient = phrase.recipient()?;
52        self.update_own_row(|record| {
53            record
54                .recovery_fingerprints
55                .push(recovery_fingerprint(&recipient.to_string()));
56        })?;
57        let held: Vec<_> = self.held.iter().map(|(epoch, key)| (*epoch, key)).collect();
58        wrap_for_recovery(self.store, tag, &held, std::slice::from_ref(&recipient))?;
59        self.store.mark_recovery_offered(now_micros)?;
60        self.fill_recovery_envelopes()?;
61        Ok(phrase)
62    }
63
64    /// Wraps every epoch stored for this identity since this keyring was
65    /// loaded, by a rotation or a peer, and every epoch of an earlier
66    /// identity this device still holds after a restore, to each recovery
67    /// recipient that lacks it.
68    pub(super) fn fill_recovery_envelopes(&self) -> Result<usize> {
69        let Some(tag) = &self.identity else {
70            return Ok(0);
71        };
72        let recipients = self.store.recovery_recipients(tag)?;
73        if recipients.is_empty() {
74            return Ok(0);
75        }
76        let fresh = Keyring::load(self.store, self.data_dir)?;
77        let held: Vec<_> = fresh
78            .held
79            .iter()
80            .map(|(epoch, key)| (*epoch, key))
81            .collect();
82        let mut added = wrap_for_recovery(self.store, tag, &held, &recipients)?;
83        for (earlier, epoch, key) in self.earlier_epochs(&recipients)? {
84            added += wrap_for_recovery(self.store, &earlier, &[(epoch, &key)], &recipients)?;
85        }
86        Ok(added)
87    }
88
89    /// Epochs of other identities wrapped to this device that some of
90    /// `recipients` lack; they only decrypt here.
91    fn earlier_epochs(
92        &self,
93        recipients: &[Recipient],
94    ) -> Result<Vec<(IdentityTag, Epoch, IdentityKey)>> {
95        let own_recipient = self.device.age_recipient().to_string();
96        let mut earlier = Vec::new();
97        for envelope in self.store.envelopes_for_machine(self.own())? {
98            if Some(&envelope.identity_tag) == self.identity.as_ref()
99                || envelope.recipient != own_recipient
100            {
101                continue;
102            }
103            let mut missing = false;
104            for recipient in recipients {
105                missing |= self
106                    .store
107                    .envelope(
108                        &envelope.identity_tag,
109                        &envelope.epoch,
110                        &recipient.to_string(),
111                    )?
112                    .is_none();
113            }
114            if !missing {
115                continue;
116            }
117            match envelope.open(self.device.age_identity()) {
118                Ok(key) => earlier.push((envelope.identity_tag, envelope.epoch, key)),
119                Err(e) => tracing::warn!(
120                    "skipping an earlier identity's epoch {} this device cannot open: {e:#}",
121                    envelope.epoch.number
122                ),
123            }
124        }
125        Ok(earlier)
126    }
127}