second-brain-cli 0.11.0

Universal memory layer for AI coding agents: ingest, recall, and sync across Claude Code and Cursor
use std::path::PathBuf;
use std::time::Duration;

use anyhow::{Context, Result};
use reqwest::StatusCode;
use reqwest::blocking::{Client, Response};
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue};
use second_brain_core::{api_token, machine};
use second_brain_sync::protocol::{SyncHeader, VersionError};

/// Only for commands that move sync records: the daemon applies them, so a
/// daemon on other sync versions than this binary must be refused up front.
pub fn sync_client(timeout: Duration) -> Result<Client> {
    let client = client(timeout)?;
    ensure_daemon_sync_version(&client, &base_url())?;
    Ok(client)
}

fn ensure_daemon_sync_version(client: &Client, base: &str) -> Result<()> {
    let resp = client
        .get(format!("{base}/v1/sync/version"))
        .send()
        .context("asking the local daemon for its sync version")?;
    if resp.status() == StatusCode::NOT_FOUND {
        return Err(VersionError::UnversionedDaemon.into());
    }
    let daemon: SyncHeader = daemon_ok(resp)?
        .json()
        .context("reading the local daemon's sync version")?;
    SyncHeader::local().ensure_matches("this sb", &daemon, "the local daemon")?;
    Ok(())
}

/// Surfaces a daemon's sync refusal (409) as its own message, and names the
/// token file this process read when the daemon rejects it (401).
pub fn daemon_ok(resp: Response) -> Result<Response> {
    daemon_ok_against(resp, || Ok(api_token::path(&machine::data_dir()?)))
}

fn daemon_ok_against(
    resp: Response,
    token_path: impl FnOnce() -> Result<PathBuf>,
) -> Result<Response> {
    if resp.status() == StatusCode::UNAUTHORIZED {
        anyhow::bail!(
            "the daemon rejected the API token in {}; run as the user the daemon runs as, \
             or restart the daemon if that file was replaced",
            token_path()?.display()
        );
    }
    if resp.status() == StatusCode::CONFLICT {
        let body = resp.text().context("reading the daemon's sync refusal")?;
        let message = serde_json::from_str::<serde_json::Value>(&body)
            .ok()
            .and_then(|v| v["error"].as_str().map(str::to_string))
            .unwrap_or(body);
        anyhow::bail!("{message}");
    }
    Ok(resp.error_for_status()?)
}

pub fn base_url() -> String {
    std::env::var("SECOND_BRAIN_API").unwrap_or_else(|_| "http://127.0.0.1:7200".to_string())
}

pub fn client(timeout: Duration) -> Result<Client> {
    let token = api_token::read(&machine::data_dir()?)?;
    build(timeout, Some(&token))
}

/// For `GET /health` and `GET /v1/status`, the only routes the daemon serves
/// without a token, so they work before the daemon has created one.
pub fn open_client(timeout: Duration) -> Result<Client> {
    build(timeout, None)
}

fn build(timeout: Duration, token: Option<&str>) -> Result<Client> {
    Client::builder()
        .timeout(timeout)
        .default_headers(default_headers(token)?)
        .build()
        .context("building the daemon API client")
}

fn default_headers(token: Option<&str>) -> Result<HeaderMap> {
    let mut headers = HeaderMap::new();
    if let Some(token) = token {
        let mut auth = HeaderValue::from_str(&format!("Bearer {token}"))
            .context("the daemon API token is not a valid header value")?;
        auth.set_sensitive(true);
        headers.insert(AUTHORIZATION, auth);
    }
    Ok(headers)
}

#[cfg(test)]
mod tests {
    use std::io::{BufRead, BufReader, Write};
    use std::net::TcpListener;

    use second_brain_sync::protocol::SYNC_PROTOCOL_VERSION;

    use super::*;

    #[test]
    fn default_headers_carry_the_bearer_token_as_sensitive() {
        let headers = default_headers(Some("abc123")).unwrap();
        let auth = &headers[AUTHORIZATION];
        assert_eq!(auth, "Bearer abc123");
        assert!(auth.is_sensitive());
    }

    #[test]
    fn open_client_headers_carry_no_token() {
        assert!(!default_headers(None).unwrap().contains_key(AUTHORIZATION));
    }

    #[test]
    fn every_request_sends_the_token() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let mut reader = BufReader::new(stream.try_clone().unwrap());
            let mut head = Vec::new();
            loop {
                let mut line = String::new();
                reader.read_line(&mut line).unwrap();
                if line == "\r\n" || line.is_empty() {
                    break;
                }
                head.push(line.trim_end().to_ascii_lowercase());
            }
            (&stream)
                .write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
                .unwrap();
            head
        });

        let client = build(Duration::from_secs(5), Some("tok")).unwrap();
        client.get(format!("http://{addr}/v1/x")).send().unwrap();
        let head = server.join().unwrap();
        assert!(
            head.iter().any(|l| l == "authorization: bearer tok"),
            "{head:?}"
        );
    }

    fn daemon_answering(status: &'static str, body: String) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let mut reader = BufReader::new(stream.try_clone().unwrap());
            loop {
                let mut line = String::new();
                reader.read_line(&mut line).unwrap();
                if line == "\r\n" || line.is_empty() {
                    break;
                }
            }
            let response = format!(
                "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
            (&stream).write_all(response.as_bytes()).unwrap();
        });
        format!("http://{addr}")
    }

    fn check(status: &'static str, body: String) -> Result<()> {
        let base = daemon_answering(status, body);
        ensure_daemon_sync_version(&build(Duration::from_secs(5), None).unwrap(), &base)
    }

    fn json(header: &SyncHeader) -> String {
        serde_json::to_string(header).unwrap()
    }

    #[test]
    fn a_daemon_refusal_carries_its_reason() {
        let body = r#"{"error":"upgrade this daemon's binary"}"#.to_string();
        let err = check("409 Conflict", body).unwrap_err();
        assert!(
            err.to_string().contains("upgrade this daemon's binary"),
            "{err:#}"
        );
    }

    #[test]
    fn a_daemon_on_this_binarys_versions_passes() {
        check("200 OK", json(&SyncHeader::local())).unwrap();
    }

    #[test]
    fn a_daemon_without_the_version_route_is_refused() {
        let err = check("404 Not Found", String::new()).unwrap_err();
        assert!(err.to_string().contains("protocol 1"), "{err:#}");
        assert!(
            err.to_string().contains("upgrade the local daemon"),
            "{err:#}"
        );
    }

    #[test]
    fn a_daemon_on_another_protocol_is_refused() {
        let daemon = SyncHeader {
            sync_protocol: SYNC_PROTOCOL_VERSION + 1,
            ..SyncHeader::local()
        };
        let err = check("200 OK", json(&daemon)).unwrap_err();
        assert!(err.to_string().contains("upgrade this sb"), "{err:#}");
    }

    #[test]
    fn a_daemon_on_another_schema_is_refused() {
        let local = SyncHeader::local();
        let daemon = SyncHeader {
            schema_version: local.schema_version - 1,
            ..local
        };
        let err = check("200 OK", json(&daemon)).unwrap_err();
        assert!(
            err.to_string().contains("upgrade the local daemon"),
            "{err:#}"
        );
    }

    fn answer(status: &'static str) -> Response {
        let base = daemon_answering(status, String::new());
        build(Duration::from_secs(5), Some("tok"))
            .unwrap()
            .get(format!("{base}/v1/sync/export"))
            .send()
            .unwrap()
    }

    #[test]
    fn a_rejected_token_names_the_token_file() {
        let token_path = || Ok(PathBuf::from("/somewhere/.second-brain/api.token"));
        let err = daemon_ok_against(answer("401 Unauthorized"), token_path).unwrap_err();
        assert!(
            format!("{err:#}").contains("/somewhere/.second-brain/api.token"),
            "{err:#}"
        );
    }

    #[test]
    fn other_statuses_do_not_resolve_the_token_path() {
        let token_path = || -> Result<PathBuf> { panic!("token path resolved for a non-401") };
        assert!(daemon_ok_against(answer("200 OK"), token_path).is_ok());
        let err = daemon_ok_against(answer("500 Internal Server Error"), token_path).unwrap_err();
        assert!(format!("{err:#}").contains("500"), "{err:#}");
    }
}