Skip to main content

agentmux_srv_core/backend/vault/import/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Readers for the files other password managers export
5//! (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md §8.4).
6//!
7//! Each reader turns a file's bytes into [`Incoming`] entries (the same shape a
8//! `.vault` file holds) and says what it couldn't bring in and why. They're
9//! attack surface (§8.7): they run on files a person was given, so each caps
10//! what it reads and takes no value as trusted. Nothing here touches the Vault:
11//! `transfer::inspect` stages what they return, and the person previews it.
12//!
13//! Everything here is a plaintext export (the encrypted sources, KeePass and
14//! password-protected exports, come with their own passwords); `Imported`
15//! says so, and the pane then offers to delete the file.
16
17pub mod bitwarden;
18pub mod bitwarden_encrypted;
19pub mod dashlane;
20pub mod enpass;
21pub mod env;
22pub mod kdbx;
23pub mod keeper;
24pub use kdbx::{MAX_ARGON_ITERATIONS, MAX_ARGON_MEMORY, MAX_ARGON_PARALLELISM, MAX_KEY_FILE};
25pub mod logins;
26pub mod nordpass;
27pub mod onepux;
28pub mod proton;
29pub mod roboform;
30pub mod shared;
31pub mod sticky;
32pub mod zoho;
33
34use std::collections::BTreeMap;
35
36use serde::{Deserialize, Serialize};
37
38/// Where an import came from, for the preview.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
40#[serde(rename_all = "kebab-case")]
41#[ts(export, export_to = "../../../frontend/types/rpc/")]
42pub enum Source {
43    Vault,
44    LastPass,
45    OnePassword,
46    Bitwarden,
47    Chrome,
48    Firefox,
49    Safari,
50    KeePass,
51    Env,
52    Csv,
53    Dashlane,
54    Keeper,
55    NordPass,
56    RoboForm,
57    ZohoVault,
58    ProtonPass,
59    Enpass,
60    StickyPassword,
61}
62
63impl Source {
64    pub fn label(self) -> &'static str {
65        match self {
66            Source::Vault => "an AgentMux Vault file",
67            Source::LastPass => "LastPass",
68            Source::OnePassword => "1Password",
69            Source::Bitwarden => "Bitwarden",
70            Source::Chrome => "a browser's password export (Chrome, Edge, Brave)",
71            Source::Firefox => "Firefox",
72            Source::Safari => "Safari or Apple Passwords",
73            Source::KeePass => "a KeePass database",
74            Source::Env => "a .env file",
75            Source::Csv => "a CSV file",
76            Source::Dashlane => "Dashlane",
77            Source::Keeper => "Keeper",
78            Source::NordPass => "NordPass",
79            Source::RoboForm => "RoboForm",
80            Source::ZohoVault => "Zoho Vault",
81            Source::ProtonPass => "Proton Pass",
82            Source::Enpass => "Enpass",
83            Source::StickyPassword => "Sticky Password",
84        }
85    }
86}
87
88/// An entry as a file holds it, before it is checked against its kind.
89#[derive(Debug, Default, Clone, Serialize, Deserialize)]
90pub struct Incoming {
91    #[serde(default)]
92    pub id: String,
93    pub kind: String,
94    pub label: String,
95    #[serde(default)]
96    pub fields: BTreeMap<String, String>,
97    #[serde(default)]
98    pub tags: Vec<String>,
99    #[serde(default)]
100    pub parts: BTreeMap<String, String>,
101    #[serde(default)]
102    pub created_at: i64,
103    #[serde(default)]
104    pub updated_at: i64,
105}
106
107impl Incoming {
108    pub fn new(kind: &str, label: &str) -> Self {
109        Self { kind: kind.into(), label: label.trim().into(), ..Self::default() }
110    }
111
112    pub fn part(mut self, name: &str, value: &str) -> Self {
113        self.parts.insert(name.into(), value.to_string());
114        self
115    }
116
117    pub fn field(mut self, name: &str, value: &str) -> Self {
118        let v = value.trim();
119        if !v.is_empty() {
120            self.fields.insert(name.into(), v.to_string());
121        }
122        self
123    }
124
125    pub fn tag(mut self, tag: &str) -> Self {
126        let t = tag.trim();
127        if !t.is_empty() && !self.tags.iter().any(|x| x == t) {
128            self.tags.push(t.to_string());
129        }
130        self
131    }
132}
133
134/// What a reader found.
135pub struct Imported {
136    pub source: Source,
137    pub entries: Vec<Incoming>,
138    /// (label, why) for what couldn't come in.
139    pub skipped: Vec<(String, String)>,
140    /// The file held every secret unencrypted (a CSV or JSON export): the person is
141    /// offered to delete it. A KeePass database is encrypted, so it isn't one.
142    pub plaintext: bool,
143}
144
145/// Which column of a CSV is what, chosen by the person for a file no reader knows.
146#[derive(Debug, Clone, Deserialize)]
147pub struct Mapping {
148    /// The kind of entry every row becomes: `login`, `api-key`, `note`, ….
149    pub kind: String,
150    pub label: usize,
151    /// The main value: a login's password, a key, a note's text.
152    pub value: usize,
153    #[serde(default)]
154    pub site: Option<usize>,
155    #[serde(default)]
156    pub username: Option<usize>,
157}
158
159/// A CSV no reader recognised: its columns, for the person to say which is which.
160#[derive(Debug, Clone, Serialize, ts_rs::TS)]
161#[ts(export, export_to = "../../../frontend/types/rpc/")]
162pub struct MappingNeeded {
163    pub columns: Vec<String>,
164    pub rows: usize,
165}
166
167pub enum ReadError {
168    NeedsMapping(MappingNeeded),
169    /// An encrypted database: its master password is needed.
170    NeedsPassphrase,
171    Other(String),
172}
173
174impl From<String> for ReadError {
175    fn from(s: String) -> Self {
176        ReadError::Other(s)
177    }
178}
179
180impl From<&str> for ReadError {
181    fn from(s: &str) -> Self {
182        ReadError::Other(s.to_string())
183    }
184}
185
186/// The most rows or items one file may hold (§8.7).
187pub const MAX_ITEMS: usize = 100_000;
188
189/// Reads an export that needs no password, finding out what it is from its contents.
190pub fn read(bytes: &[u8], file_name: &str, mapping: Option<&Mapping>) -> Result<Imported, ReadError> {
191    read_with(bytes, file_name, mapping, None)
192}
193
194/// [`read`], with the password an encrypted database (KeePass) needs.
195pub fn read_with(bytes: &[u8], file_name: &str, mapping: Option<&Mapping>, passphrase: Option<&str>) -> Result<Imported, ReadError> {
196    read_keyed(bytes, file_name, mapping, passphrase, None)
197}
198
199/// [`read_with`], and the key file a KeePass database may need as well as, or instead of, its password.
200pub fn read_keyed(bytes: &[u8], file_name: &str, mapping: Option<&Mapping>, passphrase: Option<&str>, keyfile: Option<&[u8]>) -> Result<Imported, ReadError> {
201    if bytes.starts_with(&kdbx::MAGIC) {
202        return kdbx::read(bytes, passphrase.unwrap_or(""), keyfile);
203    }
204    if bytes.starts_with(b"PK\x03\x04") {
205        if onepux::looks_like(bytes) {
206            return onepux::read(bytes);
207        }
208        if proton::zip_looks_like(bytes) {
209            return proton::read_zip(bytes);
210        }
211        return Err("this is a zip file that isn't a 1Password or Proton Pass export; export a CSV or JSON from that app instead".into());
212    }
213    let text = std::str::from_utf8(bytes).map_err(|_| "this isn't a text file AgentMux knows how to read: its export formats are CSV, JSON and .env".to_string())?;
214    let text = text.trim_start_matches('\u{feff}');
215    let trimmed = text.trim_start();
216    if trimmed.starts_with('{') {
217        if let Some(own) = read_own_json(text) {
218            return own;
219        }
220        match json_source(text) {
221            JsonSource::ProtonPass => return proton::read_json(text),
222            JsonSource::Enpass => return enpass::read_json(text),
223            JsonSource::Bitwarden => return bitwarden::read(text, passphrase),
224        }
225    }
226    if trimmed.starts_with("-----BEGIN PGP MESSAGE-----") {
227        return Err(proton::ENCRYPTED.into());
228    }
229    if sticky::looks_like(text) {
230        return sticky::read(text);
231    }
232    if file_name.to_ascii_lowercase().ends_with(".env") || env::looks_like_env(text) {
233        return env::read(text);
234    }
235    if mapping.is_none() {
236        if let Some(read) = read_service_csv(text) {
237            return read;
238        }
239    }
240    match logins::read(text, mapping) {
241        // A table with no header row and no column the generic reader knows: Keeper writes those.
242        Err(ReadError::NeedsMapping(needed)) if mapping.is_none() => keeper::read(text).unwrap_or(Err(ReadError::NeedsMapping(needed))),
243        other => other,
244    }
245}
246
247/// A CSV that one of the second-wave services wrote, found by its column names; `None` for any other.
248fn read_service_csv(text: &str) -> Option<Result<Imported, ReadError>> {
249    let names = shared::header_names(text);
250    if nordpass::looks_like(&names) {
251        return Some(nordpass::read(text));
252    }
253    if roboform::looks_like(&names) {
254        return Some(roboform::read(text));
255    }
256    if zoho::looks_like(&names) {
257        return Some(zoho::read(text));
258    }
259    if proton::csv_looks_like(&names) {
260        return Some(proton::read_csv(text));
261    }
262    if enpass::csv_looks_like(&names) {
263        return Some(enpass::read_csv(text));
264    }
265    dashlane::read(text)
266}
267
268/// Whose JSON this is, when it isn't AgentMux's own: found from what it holds, without reading the entries.
269enum JsonSource {
270    ProtonPass,
271    Enpass,
272    Bitwarden,
273}
274
275fn json_source(text: &str) -> JsonSource {
276    /// An item, as far as Enpass's `template_type` (which Bitwarden's items don't have) shows.
277    #[derive(Deserialize)]
278    struct Peek {
279        template_type: Option<String>,
280    }
281    #[derive(Deserialize)]
282    struct Probe {
283        vaults: Option<serde::de::IgnoredAny>,
284        items: Option<Vec<Peek>>,
285    }
286    match serde_json::from_str::<Probe>(text) {
287        Ok(p) if p.vaults.is_some() => JsonSource::ProtonPass,
288        Ok(p) if p.items.as_ref().is_some_and(|items| items.iter().any(|i| i.template_type.is_some())) => JsonSource::Enpass,
289        _ => JsonSource::Bitwarden,
290    }
291}
292
293/// AgentMux's own plain JSON export (a `.vault` file's contents, unencrypted), or `None` when the
294/// text is some other JSON.
295fn read_own_json(text: &str) -> Option<Result<Imported, ReadError>> {
296    /// Just enough to tell whose JSON it is, without reading the entries.
297    #[derive(Deserialize)]
298    struct Probe {
299        format: Option<String>,
300    }
301    #[derive(Deserialize)]
302    struct File {
303        #[serde(default)]
304        version: u32,
305        entries: Vec<Incoming>,
306    }
307    let probe: Probe = serde_json::from_str(text).ok()?;
308    if probe.format.as_deref() != Some(super::transfer::FORMAT) {
309        return None;
310    }
311    let file: File = match serde_json::from_str(text) {
312        Ok(f) => f,
313        Err(_) => return Some(Err("this isn't a Vault export: its contents aren't in the expected shape".into())),
314    };
315    if file.version > super::transfer::VERSION {
316        return Some(Err(format!("this file was made by a newer AgentMux (format version {}); update AgentMux to import it", file.version).into()));
317    }
318    if file.entries.len() > MAX_ITEMS {
319        return Some(Err(format!("this file has more than {MAX_ITEMS} entries, more than the Vault imports").into()));
320    }
321    Some(Ok(Imported { source: Source::Vault, entries: file.entries, skipped: Vec::new(), plaintext: true }))
322}
323
324#[cfg(test)]
325mod tests;
326#[cfg(test)]
327mod fuzz_tests;
328#[cfg(test)]
329mod second_wave_tests;
330#[cfg(test)]
331mod third_wave_tests;