second-brain-api 0.13.3

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
use std::sync::Arc;

use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use second_brain_sync::keyring::{Keyring, RecoveryState, RemovalRefused, Retired};
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;

use super::{bad_request, internal_error};
use crate::{AppState, identity_report};

const NO_IDENTITY: &str =
    "this device has no sync identity yet, so a recovery phrase would open nothing";

#[derive(Serialize)]
struct NewPhrase {
    phrase: String,
    fingerprint: String,
}

impl Drop for NewPhrase {
    fn drop(&mut self) {
        self.phrase.zeroize();
    }
}

async fn blocking<T: Serialize + Send + 'static>(
    work: impl FnOnce() -> anyhow::Result<T> + Send + 'static,
) -> Response {
    match tokio::task::spawn_blocking(work).await {
        Ok(Ok(body)) => Json(body).into_response(),
        Ok(Err(e)) => internal_error(e),
        Err(e) => internal_error(e),
    }
}

pub(super) async fn recovery_state(State(state): State<Arc<AppState>>) -> Response {
    blocking(move || -> anyhow::Result<RecoveryState> {
        Keyring::load(&state.sqlite, &state.data_dir)?.recovery_state()
    })
    .await
}

/// The phrase is in this response and nowhere else.
pub(super) async fn new_recovery_phrase(State(state): State<Arc<AppState>>) -> Response {
    let made = tokio::task::spawn_blocking(move || -> anyhow::Result<Option<NewPhrase>> {
        let keyring = Keyring::load(&state.sqlite, &state.data_dir)?;
        if keyring.identity().is_none() {
            return Ok(None);
        }
        let phrase = keyring.add_recovery_phrase(state.clock.wall_micros())?;
        Ok(Some(NewPhrase {
            phrase: String::from(phrase.expose_text().as_str()),
            fingerprint: phrase.fingerprint()?,
        }))
    })
    .await;
    match made {
        Ok(Ok(Some(body))) => Json(body).into_response(),
        Ok(Ok(None)) => (
            StatusCode::CONFLICT,
            Json(serde_json::json!({"error": NO_IDENTITY})),
        )
            .into_response(),
        Ok(Err(e)) => internal_error(e),
        Err(e) => internal_error(e),
    }
}

pub(super) async fn recovery_offered(State(state): State<Arc<AppState>>) -> Response {
    blocking(move || -> anyhow::Result<RecoveryState> {
        state
            .sqlite
            .mark_recovery_offered(state.clock.wall_micros())?;
        Keyring::load(&state.sqlite, &state.data_dir)?.recovery_state()
    })
    .await
}

#[derive(Deserialize)]
pub(super) struct RemoveRequest {
    fingerprint: String,
}

/// Retires a phrase on every device: peers take the retirement from the
/// next handshake, and the store key rotates at the next quiet minute.
pub(super) async fn remove_recovery_phrase(
    State(state): State<Arc<AppState>>,
    Json(req): Json<RemoveRequest>,
) -> Response {
    let retired =
        tokio::task::spawn_blocking(move || -> anyhow::Result<Result<Retired, String>> {
            let keyring = Keyring::load(&state.sqlite, &state.data_dir)?;
            match keyring.retire_recovery(&req.fingerprint, state.clock.wall_micros()) {
                Ok(retired) => {
                    identity_report::report(&state.sqlite, &state.data_dir, &state.health);
                    Ok(Ok(retired))
                }
                Err(e) => match e.downcast_ref::<RemovalRefused>() {
                    Some(refused) => Ok(Err(refused.to_string())),
                    None => Err(e),
                },
            }
        })
        .await;
    match retired {
        Ok(Ok(Ok(body))) => Json(body).into_response(),
        Ok(Ok(Err(message))) => bad_request(message),
        Ok(Err(e)) => internal_error(e),
        Err(e) => internal_error(e),
    }
}