second-brain-sync 0.13.4

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
Documentation
use age::x25519::Recipient;
use anyhow::{Context, Result};
use second_brain_core::keys::{
    Epoch, IdentityKey, IdentityTag, RecoveryPhrase, recovery_fingerprint, wrap_for_recovery,
};
use serde::Serialize;

use super::Keyring;

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RecoveryState {
    pub identity: Option<String>,
    /// Fingerprints of the phrases this device wraps its epochs to.
    pub fingerprints: Vec<String>,
    pub offered: bool,
    /// Fingerprints of the retired phrases.
    pub retired: Vec<String>,
}

impl Keyring<'_> {
    pub fn recovery_state(&self) -> Result<RecoveryState> {
        let (fingerprints, retired) = match &self.identity {
            Some(tag) => (
                self.store
                    .recovery_recipients(tag)?
                    .iter()
                    .map(|r| recovery_fingerprint(&r.to_string()))
                    .collect(),
                self.store.retired_fingerprints()?.into_iter().collect(),
            ),
            None => (Vec::new(), Vec::new()),
        };
        Ok(RecoveryState {
            identity: self.identity.as_ref().map(|t| t.as_str().to_string()),
            fingerprints,
            offered: self.store.recovery_offered()?,
            retired,
        })
    }

    /// Makes a phrase for this identity, lists its fingerprint in this
    /// device's signed row and then wraps every epoch this device holds to
    /// it, so a failed row write leaves no phrase trusted unseen. The phrase
    /// is returned once and never stored.
    pub fn add_recovery_phrase(&self, now_micros: i64) -> Result<RecoveryPhrase> {
        let tag = self
            .identity
            .as_ref()
            .context("this device has no sync identity yet, so there is nothing to recover")?;
        let phrase = RecoveryPhrase::generate()?;
        let recipient = phrase.recipient()?;
        self.update_own_row(|record| {
            record
                .recovery_fingerprints
                .push(recovery_fingerprint(&recipient.to_string()));
        })?;
        let held: Vec<_> = self.held.iter().map(|(epoch, key)| (*epoch, key)).collect();
        wrap_for_recovery(self.store, tag, &held, std::slice::from_ref(&recipient))?;
        self.store.mark_recovery_offered(now_micros)?;
        self.fill_recovery_envelopes()?;
        Ok(phrase)
    }

    /// Wraps every epoch stored for this identity since this keyring was
    /// loaded, by a rotation or a peer, and every epoch of an earlier
    /// identity this device still holds after a restore, to each recovery
    /// recipient that lacks it.
    pub(super) fn fill_recovery_envelopes(&self) -> Result<usize> {
        let Some(tag) = &self.identity else {
            return Ok(0);
        };
        let recipients = self.store.recovery_recipients(tag)?;
        if recipients.is_empty() {
            return Ok(0);
        }
        let fresh = Keyring::load(self.store, self.data_dir)?;
        let held: Vec<_> = fresh
            .held
            .iter()
            .map(|(epoch, key)| (*epoch, key))
            .collect();
        let mut added = wrap_for_recovery(self.store, tag, &held, &recipients)?;
        for (earlier, epoch, key) in self.earlier_epochs(&recipients)? {
            added += wrap_for_recovery(self.store, &earlier, &[(epoch, &key)], &recipients)?;
        }
        Ok(added)
    }

    /// Epochs of other identities wrapped to this device that some of
    /// `recipients` lack; they only decrypt here.
    fn earlier_epochs(
        &self,
        recipients: &[Recipient],
    ) -> Result<Vec<(IdentityTag, Epoch, IdentityKey)>> {
        let own_recipient = self.device.age_recipient().to_string();
        let mut earlier = Vec::new();
        for envelope in self.store.envelopes_for_machine(self.own())? {
            if Some(&envelope.identity_tag) == self.identity.as_ref()
                || envelope.recipient != own_recipient
            {
                continue;
            }
            let mut missing = false;
            for recipient in recipients {
                missing |= self
                    .store
                    .envelope(
                        &envelope.identity_tag,
                        &envelope.epoch,
                        &recipient.to_string(),
                    )?
                    .is_none();
            }
            if !missing {
                continue;
            }
            match envelope.open(self.device.age_identity()) {
                Ok(key) => earlier.push((envelope.identity_tag, envelope.epoch, key)),
                Err(e) => tracing::warn!(
                    "skipping an earlier identity's epoch {} this device cannot open: {e:#}",
                    envelope.epoch.number
                ),
            }
        }
        Ok(earlier)
    }
}