second-brain-sync 0.13.1

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
Documentation
use anyhow::Result;
use second_brain_core::keys::{
    Epoch, Retirement, SignedRetirement, recovery_fingerprint, valid_fingerprint,
};
use serde::Serialize;

use super::Keyring;
use super::revocation::RemovalRefused;

/// What `sb recovery remove` retired.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Retired {
    pub fingerprint: String,
    /// The epoch minted so no newer key opens with the phrase; None when
    /// this device holds no epoch to rotate from.
    pub epoch: Option<Epoch>,
}

fn refused(message: impl Into<String>) -> anyhow::Error {
    RemovalRefused(message.into()).into()
}

impl Keyring<'_> {
    /// Signs a retirement of the recovery phrase with `fingerprint`, mints
    /// the next epoch without wrapping it to that phrase, and deletes this
    /// device's envelopes for it. Peers apply it from the handshake.
    pub fn retire_recovery(&self, fingerprint: &str, now_micros: i64) -> Result<Retired> {
        let Some(tag) = &self.identity else {
            return Err(refused(
                "this device holds no sync identity, so it has no recovery phrase to remove",
            ));
        };
        let fingerprint = fingerprint.trim().to_ascii_lowercase();
        if !valid_fingerprint(&fingerprint) {
            return Err(refused(format!(
                "{fingerprint:?} is not a recovery phrase fingerprint; `sb recovery` lists them"
            )));
        }
        if self.is_revoked(self.own())? {
            return Err(refused(
                "this device was removed from its sync identity, so it cannot remove a recovery \
                 phrase",
            ));
        }
        if self.store.retired_fingerprints()?.contains(&fingerprint) {
            return Err(refused(format!(
                "recovery phrase {fingerprint} was already removed"
            )));
        }
        if !self.phrase_known(&fingerprint)? {
            return Err(refused(format!(
                "no device of this sync identity lists recovery phrase {fingerprint}; \
                 `sb recovery` lists them"
            )));
        }
        let signed = Retirement {
            identity_tag: tag.as_str().to_string(),
            retirer: self.own().to_string(),
            fingerprint: fingerprint.clone(),
            created_at_micros: now_micros,
        }
        .sign(self.device.signing_key());
        self.store
            .put_retirement(&signed, &self.device.verifying_key())?;
        let epoch = self.apply_retirements(now_micros)?;
        Ok(Retired { fingerprint, epoch })
    }

    /// Listed in the row of a device not revoked, or wrapped to here.
    fn phrase_known(&self, fingerprint: &str) -> Result<bool> {
        let Some(tag) = &self.identity else {
            return Ok(false);
        };
        let listed = self.store.device_records()?.into_iter().any(|row| {
            !row.revoked
                && row.current.record.identity_tag == tag.as_str()
                && row
                    .current
                    .record
                    .recovery_fingerprints
                    .iter()
                    .any(|f| f == fingerprint)
        });
        Ok(listed
            || self
                .store
                .recovery_recipients(tag)?
                .iter()
                .any(|r| recovery_fingerprint(&r.to_string()) == fingerprint))
    }

    /// Takes each retirement signed by a device of this identity, revoked or
    /// not, since a retirement only shrinks who decrypts.
    pub(super) fn accept_retirements(
        &self,
        peer: &str,
        retirements: &[SignedRetirement],
    ) -> Result<()> {
        let Some(tag) = &self.identity else {
            return Ok(());
        };
        for signed in retirements {
            let retirement = &signed.retirement;
            if retirement.identity_tag != tag.as_str() {
                continue;
            }
            let Some((retirer, _)) = self.member_row(&retirement.retirer)? else {
                tracing::debug!(
                    "holding back the retirement of recovery phrase {} from {peer}: its retirer \
                     {} is unknown here",
                    retirement.fingerprint,
                    retirement.retirer
                );
                continue;
            };
            if let Err(e) = self
                .store
                .put_retirement(signed, &retirer.record.signing_public_key()?)
            {
                tracing::warn!("{peer} sent a retirement this device refuses: {e:#}");
            }
        }
        self.store.mark_rotating_retirements(tag)?;
        Ok(())
    }

    /// Mints the next epoch when a held retirement asks for one, then
    /// deletes every envelope to a retired phrase; minting goes first so
    /// the check sees an envelope to it in the newest epoch.
    pub(super) fn apply_retirements(&self, now_micros: i64) -> Result<Option<Epoch>> {
        let Some(tag) = &self.identity else {
            return Ok(None);
        };
        self.store.note_named_retirements(tag)?;
        self.store.mark_rotating_retirements(tag)?;
        let epoch = self.rotate_if_needed(now_micros)?;
        let deleted = self.store.delete_retired_envelopes()?;
        if deleted > 0 {
            tracing::info!("deleted {deleted} envelopes wrapped to a retired recovery phrase");
        }
        Ok(epoch)
    }
}