Skip to main content

keepassxc_client/
protocol.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// Copyright (c) 2026 gaffa fix <gaffa@mafix.cc>
3
4//! Wire types for the KeePassXC-Browser protocol.
5//!
6//! Reference: keepassxreboot/keepassxc-browser, `keepassxc-protocol.md`.
7//! Two envelope shapes exist on the socket:
8//!   1. plaintext  — only `change-public-keys`
9//!   2. encrypted  — everything else: `{"action", "message"(b64 ct), "nonce", "clientID"}`
10//! KeePassXC also emits unsolicited *signals* (`database-locked`, `database-unlocked`).
11
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15/// Outgoing plaintext key-exchange envelope.
16#[derive(Debug, Serialize)]
17pub struct ChangePublicKeysRequest {
18    pub action: String, // "change-public-keys"
19    #[serde(rename = "publicKey")]
20    pub public_key: String,
21    pub nonce: String,
22    #[serde(rename = "clientID")]
23    pub client_id: String,
24}
25
26/// Outgoing encrypted envelope.
27#[derive(Debug, Serialize)]
28pub struct EncryptedEnvelope {
29    pub action: String,
30    pub message: String, // base64(ciphertext)
31    pub nonce: String,   // base64(24B)
32    #[serde(rename = "clientID")]
33    pub client_id: String,
34    /// KeePassXC >= 2.6 accepts this to suppress some popups for triggered requests.
35    #[serde(rename = "triggerUnlock", skip_serializing_if = "Option::is_none")]
36    pub trigger_unlock: Option<String>,
37}
38
39/// Any incoming frame, before we know what it is.
40#[derive(Debug, Clone, Deserialize)]
41pub struct IncomingFrame {
42    pub action: Option<String>,
43    #[serde(rename = "publicKey")]
44    pub public_key: Option<String>,
45    pub message: Option<String>,
46    pub nonce: Option<String>,
47    #[serde(rename = "clientID")]
48    pub client_id: Option<String>,
49    pub error: Option<String>,
50    #[serde(rename = "errorCode")]
51    pub error_code: Option<Value>, // KeePassXC sends this as string or number depending on path
52    pub success: Option<String>,
53    pub version: Option<String>,
54}
55
56impl IncomingFrame {
57    pub fn is_signal(&self) -> bool {
58        matches!(
59            self.action.as_deref(),
60            Some("database-locked") | Some("database-unlocked")
61        )
62    }
63
64    pub fn error_code_i64(&self) -> Option<i64> {
65        match &self.error_code {
66            Some(Value::Number(n)) => n.as_i64(),
67            Some(Value::String(s)) => s.parse().ok(),
68            _ => None,
69        }
70    }
71}
72
73/// Signals KeePassXC pushes without being asked.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum Signal {
76    DatabaseLocked,
77    DatabaseUnlocked,
78}
79
80/// One login entry as returned by `get-logins`.
81#[derive(Debug, Clone, Deserialize)]
82pub struct LoginEntry {
83    pub uuid: String,
84    #[serde(default)]
85    pub name: String,
86    #[serde(default)]
87    pub login: String,
88    #[serde(default)]
89    pub password: String,
90    #[serde(default)]
91    pub group: Option<String>,
92    /// TOTP if KeePassXC is configured to expose it in get-logins results.
93    #[serde(default)]
94    pub totp: Option<String>,
95    /// Custom string fields prefixed KPH: in KeePassXC.
96    #[serde(default, rename = "stringFields")]
97    pub string_fields: Vec<Value>,
98}
99
100/// Decrypted body of a `get-logins` response.
101#[derive(Debug, Deserialize)]
102pub struct GetLoginsResponse {
103    #[serde(default)]
104    pub count: Option<Value>,
105    #[serde(default)]
106    pub entries: Vec<LoginEntry>,
107}
108
109/// Decrypted body of an `associate` response.
110#[derive(Debug, Deserialize)]
111pub struct AssociateResponse {
112    pub id: String,
113    #[serde(default)]
114    pub hash: Option<String>,
115}
116
117/// A group node from `get-database-groups` (recursive).
118#[derive(Debug, Clone, Deserialize)]
119pub struct Group {
120    pub name: String,
121    pub uuid: String,
122    #[serde(default)]
123    pub children: Vec<Group>,
124}
125
126#[derive(Debug, Deserialize)]
127pub struct GetDatabaseGroupsResponse {
128    #[serde(rename = "defaultGroup", default)]
129    pub default_group: Option<String>,
130    pub groups: GroupsWrapper,
131}
132
133#[derive(Debug, Deserialize)]
134pub struct GroupsWrapper {
135    pub groups: Vec<Group>,
136}
137
138impl Group {
139    /// Depth-first flatten to (path, uuid) pairs, e.g. ("/Work/Servers", "abc...").
140    pub fn flatten(&self, parent: &str, out: &mut Vec<(String, String)>) {
141        let path = format!("{}/{}", parent, self.name);
142        out.push((path.clone(), self.uuid.clone()));
143        for c in &self.children {
144            c.flatten(&path, out);
145        }
146    }
147}
148
149/// Association credentials passed in `keys` of most requests.
150#[derive(Debug, Clone, Serialize)]
151pub struct AssociationKey {
152    pub id: String,
153    pub key: String, // idKey public, base64
154}