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>

//! Wire types for the KeePassXC-Browser protocol.
//!
//! Reference: keepassxreboot/keepassxc-browser, `keepassxc-protocol.md`.
//! Two envelope shapes exist on the socket:
//!   1. plaintext  — only `change-public-keys`
//!   2. encrypted  — everything else: `{"action", "message"(b64 ct), "nonce", "clientID"}`
//! KeePassXC also emits unsolicited *signals* (`database-locked`, `database-unlocked`).

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Outgoing plaintext key-exchange envelope.
#[derive(Debug, Serialize)]
pub struct ChangePublicKeysRequest {
    pub action: String, // "change-public-keys"
    #[serde(rename = "publicKey")]
    pub public_key: String,
    pub nonce: String,
    #[serde(rename = "clientID")]
    pub client_id: String,
}

/// Outgoing encrypted envelope.
#[derive(Debug, Serialize)]
pub struct EncryptedEnvelope {
    pub action: String,
    pub message: String, // base64(ciphertext)
    pub nonce: String,   // base64(24B)
    #[serde(rename = "clientID")]
    pub client_id: String,
    /// KeePassXC >= 2.6 accepts this to suppress some popups for triggered requests.
    #[serde(rename = "triggerUnlock", skip_serializing_if = "Option::is_none")]
    pub trigger_unlock: Option<String>,
}

/// Any incoming frame, before we know what it is.
#[derive(Debug, Clone, Deserialize)]
pub struct IncomingFrame {
    pub action: Option<String>,
    #[serde(rename = "publicKey")]
    pub public_key: Option<String>,
    pub message: Option<String>,
    pub nonce: Option<String>,
    #[serde(rename = "clientID")]
    pub client_id: Option<String>,
    pub error: Option<String>,
    #[serde(rename = "errorCode")]
    pub error_code: Option<Value>, // KeePassXC sends this as string or number depending on path
    pub success: Option<String>,
    pub version: Option<String>,
}

impl IncomingFrame {
    pub fn is_signal(&self) -> bool {
        matches!(
            self.action.as_deref(),
            Some("database-locked") | Some("database-unlocked")
        )
    }

    pub fn error_code_i64(&self) -> Option<i64> {
        match &self.error_code {
            Some(Value::Number(n)) => n.as_i64(),
            Some(Value::String(s)) => s.parse().ok(),
            _ => None,
        }
    }
}

/// Signals KeePassXC pushes without being asked.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Signal {
    DatabaseLocked,
    DatabaseUnlocked,
}

/// One login entry as returned by `get-logins`.
#[derive(Debug, Clone, Deserialize)]
pub struct LoginEntry {
    pub uuid: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub login: String,
    #[serde(default)]
    pub password: String,
    #[serde(default)]
    pub group: Option<String>,
    /// TOTP if KeePassXC is configured to expose it in get-logins results.
    #[serde(default)]
    pub totp: Option<String>,
    /// Custom string fields prefixed KPH: in KeePassXC.
    #[serde(default, rename = "stringFields")]
    pub string_fields: Vec<Value>,
}

/// Decrypted body of a `get-logins` response.
#[derive(Debug, Deserialize)]
pub struct GetLoginsResponse {
    #[serde(default)]
    pub count: Option<Value>,
    #[serde(default)]
    pub entries: Vec<LoginEntry>,
}

/// Decrypted body of an `associate` response.
#[derive(Debug, Deserialize)]
pub struct AssociateResponse {
    pub id: String,
    #[serde(default)]
    pub hash: Option<String>,
}

/// A group node from `get-database-groups` (recursive).
#[derive(Debug, Clone, Deserialize)]
pub struct Group {
    pub name: String,
    pub uuid: String,
    #[serde(default)]
    pub children: Vec<Group>,
}

#[derive(Debug, Deserialize)]
pub struct GetDatabaseGroupsResponse {
    #[serde(rename = "defaultGroup", default)]
    pub default_group: Option<String>,
    pub groups: GroupsWrapper,
}

#[derive(Debug, Deserialize)]
pub struct GroupsWrapper {
    pub groups: Vec<Group>,
}

impl Group {
    /// Depth-first flatten to (path, uuid) pairs, e.g. ("/Work/Servers", "abc...").
    pub fn flatten(&self, parent: &str, out: &mut Vec<(String, String)>) {
        let path = format!("{}/{}", parent, self.name);
        out.push((path.clone(), self.uuid.clone()));
        for c in &self.children {
            c.flatten(&path, out);
        }
    }
}

/// Association credentials passed in `keys` of most requests.
#[derive(Debug, Clone, Serialize)]
pub struct AssociationKey {
    pub id: String,
    pub key: String, // idKey public, base64
}