second-brain-core 0.13.1

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
Documentation
use age::x25519::Recipient;
use anyhow::{Result, ensure};

use super::{
    DeviceKeys, DeviceRecord, Epoch, IdentityKey, IdentityTag, recovery_fingerprint, wrap,
};
use crate::sqlite_store::SqliteStore;

#[non_exhaustive]
pub struct Founded {
    pub tag: IdentityTag,
    pub epoch: Epoch,
    pub key: IdentityKey,
}

/// Starts a new identity with this device as its only member: epoch 1 of a
/// fresh identity key, wrapped to this device and to each recovery
/// recipient, and this device's self-signed row listing their fingerprints.
/// Floor bookkeeping for devices of any other identity is dropped. The new
/// identity holds no revocation, so epoch 1 has no cause.
///
/// The row is written last, so a founding cut short before it leaves only
/// an unused epoch and can be retried.
pub fn found_identity(
    store: &SqliteStore,
    device: &DeviceKeys,
    name: &str,
    recovery: &[Recipient],
    now_micros: i64,
) -> Result<Founded> {
    let own = store.machine_id().to_string();
    ensure!(
        store.device_record(&own)?.is_none(),
        "device {own} already has a row; a new identity needs a fresh machine id"
    );
    let key = IdentityKey::generate()?;
    let tag = IdentityTag::founded(&key.key_id(), &device.verifying_key());
    let epoch = Epoch {
        number: 1,
        key_id: key.key_id(),
    };
    let retired = store.retired_fingerprints()?;
    let recovery: Vec<&Recipient> = recovery
        .iter()
        .filter(|r| !retired.contains(&recovery_fingerprint(&r.to_string())))
        .collect();
    let mut envelopes = vec![wrap(
        &key,
        1,
        &tag,
        &device.age_recipient(),
        Some(own.clone()),
    )?];
    for recipient in &recovery {
        envelopes.push(wrap(&key, 1, &tag, recipient, None)?);
    }
    let row = DeviceRecord {
        machine_id: own.clone(),
        identity_tag: tag.as_str().to_string(),
        version: 1,
        name: name.to_string(),
        age_recipient: device.age_recipient().to_string(),
        ssh_public_key: device.ssh_public_key(),
        signing_public_key: device.verifying_key().to_bytes(),
        recovery_fingerprints: recovery
            .iter()
            .map(|r| recovery_fingerprint(&r.to_string()))
            .collect(),
        ssh_login: None,
        ssh_port: None,
        ssh_host_key: None,
    }
    .sign(&own, device.signing_key());
    store.put_keys_durably(&tag, &[epoch], &envelopes, now_micros)?;
    store.reset_floor_for_new_identity(&tag)?;
    store.insert_first_device_record(&row, &own, &device.verifying_key())?;
    Ok(Founded { tag, epoch, key })
}

#[cfg(test)]
mod tests {
    use super::*;

    const NOW: i64 = 1_793_600_000_000_000;

    #[test]
    fn founding_needs_a_machine_without_a_row() {
        let store = SqliteStore::in_memory("local".to_string()).unwrap();
        let device = DeviceKeys::generate().unwrap();
        let founded = found_identity(&store, &device, "local", &[], NOW).unwrap();
        assert_eq!(founded.epoch.number, 1);
        assert_eq!(
            founded.tag,
            IdentityTag::founded(&founded.key.key_id(), &device.verifying_key())
        );
        assert!(store.key_epochs(&founded.tag).unwrap()[0].cause.is_none());
        let row = store.device_record("local").unwrap().unwrap();
        assert_eq!(row.current.record.identity_tag, founded.tag.as_str());
        let Err(err) = found_identity(&store, &device, "local", &[], NOW) else {
            panic!("a second founding on one machine id must fail");
        };
        assert!(format!("{err:#}").contains("fresh machine id"), "{err:#}");
    }

    #[test]
    fn a_founding_cut_short_before_its_row_can_be_retried() {
        let store = SqliteStore::in_memory("local".to_string()).unwrap();
        let device = DeviceKeys::generate().unwrap();
        let orphan = IdentityKey::generate().unwrap();
        let orphan_tag = IdentityTag::founded(&orphan.key_id(), &device.verifying_key());
        let envelope = wrap(
            &orphan,
            1,
            &orphan_tag,
            &device.age_recipient(),
            Some("local".into()),
        )
        .unwrap();
        store
            .put_keys_durably(&orphan_tag, &[envelope.epoch], &[envelope], NOW)
            .unwrap();

        let founded = found_identity(&store, &device, "local", &[], NOW).unwrap();
        assert_ne!(founded.tag, orphan_tag);
        let row = store.device_record("local").unwrap().unwrap();
        assert_eq!(row.current.record.identity_tag, founded.tag.as_str());
    }
}