keepassxc-client 0.1.0

KeePassXC browser native-messaging protocol client (associate, get-logins, set-login, ...)
Documentation
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 gaffa fix <gaffa@mafix.cc>

//! Socket transport to KeePassXC's browser integration server.
//!
//! FRAMING NOTE (verify in Phase-0 spike, see implementation plan §5 Phase 0):
//! On the Unix socket KeePassXC exchanges *raw JSON documents* — the 4-byte
//! native-messaging length prefix belongs to the browser<->keepassxc-proxy stdio
//! hop, not to this socket. We therefore write plain JSON and, when reading,
//! split concatenated documents with serde_json's StreamDeserializer.

use async_trait::async_trait;
use serde_json::Value;
use std::path::PathBuf;

use crate::error::{KxcError, Result};

#[async_trait]
pub trait Transport: Send {
    async fn send_json(&mut self, doc: &Value) -> Result<()>;
    /// Receive the next complete JSON document (may block until one arrives).
    async fn recv_json(&mut self) -> Result<Value>;
}

/// Candidate socket locations, most-likely first. Linux/macOS.
pub fn socket_candidates() -> Vec<PathBuf> {
    let mut v = Vec::new();
    let sock = "org.keepassxc.KeePassXC.BrowserServer";
    if let Ok(dir) = std::env::var("XDG_RUNTIME_DIR") {
        v.push(PathBuf::from(&dir).join(sock));
        // Flatpak layout
        v.push(PathBuf::from(&dir).join("app/org.keepassxc.KeePassXC").join(sock));
        // Legacy name (KeePassXC < 2.6)
        v.push(PathBuf::from(&dir).join("kpxc_server"));
    }
    if let Ok(tmp) = std::env::var("TMPDIR") {
        v.push(PathBuf::from(&tmp).join(sock)); // macOS
    }
    v.push(PathBuf::from("/tmp").join(sock));
    v
}

#[cfg(unix)]
pub mod unix {
    use super::*;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::UnixStream;

    pub struct UnixTransport {
        stream: UnixStream,
        buf: Vec<u8>,
    }

    impl UnixTransport {
        /// Try all candidate paths and connect to the first that works.
        pub async fn connect_auto() -> Result<Self> {
            let candidates = socket_candidates();
            for p in &candidates {
                if let Ok(stream) = UnixStream::connect(p).await {
                    tracing::debug!(path = %p.display(), "connected to KeePassXC socket");
                    return Ok(Self { stream, buf: Vec::with_capacity(8192) });
                }
            }
            let tried = candidates
                .iter()
                .map(|p| p.display().to_string())
                .collect::<Vec<_>>()
                .join(", ");
            Err(KxcError::SocketNotFound(tried))
        }

        pub async fn connect_path(p: &std::path::Path) -> Result<Self> {
            let stream = UnixStream::connect(p).await?;
            Ok(Self { stream, buf: Vec::with_capacity(8192) })
        }

        /// Pop one complete JSON doc from the front of `buf`, if present.
        fn try_take_doc(&mut self) -> Option<Value> {
            let mut iter = serde_json::Deserializer::from_slice(&self.buf).into_iter::<Value>();
            match iter.next() {
                Some(Ok(v)) => {
                    let consumed = iter.byte_offset();
                    self.buf.drain(..consumed);
                    Some(v)
                }
                _ => None,
            }
        }
    }

    #[async_trait]
    impl Transport for UnixTransport {
        async fn send_json(&mut self, doc: &Value) -> Result<()> {
            let bytes = serde_json::to_vec(doc)?;
            self.stream.write_all(&bytes).await?;
            self.stream.flush().await?;
            Ok(())
        }

        async fn recv_json(&mut self) -> Result<Value> {
            loop {
                if let Some(doc) = self.try_take_doc() {
                    return Ok(doc);
                }
                let mut chunk = [0u8; 8192];
                let n = self.stream.read(&mut chunk).await?;
                if n == 0 {
                    return Err(KxcError::ConnectionClosed);
                }
                self.buf.extend_from_slice(&chunk[..n]);
            }
        }
    }
}

/// In-memory transport for unit tests: the test plays the KeePassXC side.
///
/// Because request nonces are random, replies must be *computed from* each
/// request — so the mock takes a responder closure invoked on every send.
pub mod mock {
    use super::*;
    use std::collections::VecDeque;
    use std::sync::{Arc, Mutex};

    type Responder = Box<dyn FnMut(&Value) -> Vec<Value> + Send>;

    #[derive(Clone)]
    pub struct MockTransport {
        pub sent: Arc<Mutex<Vec<Value>>>,
        pub to_receive: Arc<Mutex<VecDeque<Value>>>,
        responder: Arc<Mutex<Option<Responder>>>,
    }

    impl MockTransport {
        pub fn new() -> Self {
            Self {
                sent: Arc::new(Mutex::new(Vec::new())),
                to_receive: Arc::new(Mutex::new(VecDeque::new())),
                responder: Arc::new(Mutex::new(None)),
            }
        }

        /// The responder plays KeePassXC: it sees every outgoing frame and
        /// returns the frames to deliver back (0..n, so it can also inject
        /// signals before the actual response).
        pub fn with_responder(f: impl FnMut(&Value) -> Vec<Value> + Send + 'static) -> Self {
            let t = Self::new();
            *t.responder.lock().unwrap() = Some(Box::new(f));
            t
        }

        pub fn push_incoming(&self, v: Value) {
            self.to_receive.lock().unwrap().push_back(v);
        }
        pub fn last_sent(&self) -> Option<Value> {
            self.sent.lock().unwrap().last().cloned()
        }
    }

    #[async_trait]
    impl Transport for MockTransport {
        async fn send_json(&mut self, doc: &Value) -> Result<()> {
            self.sent.lock().unwrap().push(doc.clone());
            if let Some(r) = self.responder.lock().unwrap().as_mut() {
                let replies = r(doc);
                let mut q = self.to_receive.lock().unwrap();
                for v in replies {
                    q.push_back(v);
                }
            }
            Ok(())
        }
        async fn recv_json(&mut self) -> Result<Value> {
            self.to_receive
                .lock()
                .unwrap()
                .pop_front()
                .ok_or(KxcError::ConnectionClosed)
        }
    }
}

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

    #[test]
    fn candidates_are_nonempty_and_ordered() {
        std::env::set_var("XDG_RUNTIME_DIR", "/run/user/1000");
        let c = socket_candidates();
        assert!(c.len() >= 3);
        assert!(c[0].ends_with("org.keepassxc.KeePassXC.BrowserServer"));
    }
}