Skip to main content

agentmux_srv_core/backend/vault/import/
enpass.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Enpass's exports (spec §8.4): its JSON (folders and items whose `template_type` says what they
5//! are and whose `fields` carry the values) and its CSV (a `Title,Field,Value,…` table whose rows
6//! hold a title, then pairs of a field's name and value, then perhaps a note). Written from the
7//! format as Bitwarden's open-source importer reads it, not from an export Enpass made.
8
9use std::collections::HashMap;
10
11use serde_json::Value;
12
13use super::shared::{add_line, expiry, label_of, parse_csv, present, Sink};
14use super::{Imported, ReadError, Source, MAX_ITEMS};
15
16/// Folders nest; a chain longer than this is a loop or a crafted file.
17const MOST_DEPTH: usize = 32;
18/// Per login: how many of its addresses are kept.
19const MOST_URLS: usize = 50;
20
21fn text<'a>(v: &'a Value, key: &str) -> &'a str {
22    v.get(key).and_then(Value::as_str).unwrap_or("")
23}
24
25/// A flag Enpass writes as a number (`1` is set).
26fn flag(v: &Value, key: &str) -> bool {
27    v.get(key).and_then(Value::as_i64).is_some_and(|n| n != 0)
28}
29
30/// Each folder's path from the top (`Work/Servers`), found by walking up its parents.
31fn folder_paths(root: &Value) -> HashMap<String, String> {
32    let list: Vec<&Value> = root.get("folders").and_then(Value::as_array).into_iter().flatten().take(MAX_ITEMS).collect();
33    let by_id: HashMap<&str, &Value> = list.iter().filter_map(|f| Some((f.get("uuid")?.as_str()?, *f))).collect();
34    let mut paths = HashMap::new();
35    for (id, folder) in &by_id {
36        let mut parts = vec![text(folder, "title").trim()];
37        let mut parent = text(folder, "parent_uuid");
38        while !parent.is_empty() && parts.len() < MOST_DEPTH {
39            let Some(up) = by_id.get(parent) else { break };
40            parts.push(text(up, "title").trim());
41            parent = text(up, "parent_uuid");
42        }
43        parts.reverse();
44        let path = parts.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join("/");
45        if !path.is_empty() {
46            paths.insert(id.to_string(), path);
47        }
48    }
49    paths
50}
51
52pub(super) fn read_json(input: &str) -> Result<Imported, ReadError> {
53    let root: Value = serde_json::from_str(input).map_err(|_| ReadError::from("this isn't the JSON an Enpass export holds"))?;
54    let items = root.get("items").and_then(Value::as_array).ok_or("this JSON isn't an Enpass export: it has no items")?;
55    if items.len() > MAX_ITEMS {
56        return Err(format!("this export has more than {MAX_ITEMS} items, more than the Vault imports").into());
57    }
58    if items.is_empty() {
59        return Err("this Enpass export has no items".into());
60    }
61    let folders = folder_paths(&root);
62    let mut sink = Sink::default();
63    for item in items {
64        let tag = item.get("folders").and_then(Value::as_array).and_then(|f| f.first()).and_then(Value::as_str).and_then(|id| folders.get(id)).map(String::as_str).unwrap_or("");
65        item_into(item, tag, &mut sink);
66    }
67    sink.done(Source::Enpass)
68}
69
70/// One field of an item that has a value: (type, label, value). Deleted fields (Enpass keeps their
71/// last value in the file) and section headings are left out.
72fn live_fields(item: &Value) -> Vec<(&str, &str, &str)> {
73    item.get("fields")
74        .and_then(Value::as_array)
75        .into_iter()
76        .flatten()
77        .filter(|f| !flag(f, "deleted"))
78        .map(|f| (text(f, "type"), text(f, "label").trim(), text(f, "value")))
79        .filter(|(ty, _, value)| *ty != "section" && present(value).is_some())
80        .collect()
81}
82
83fn item_into(item: &Value, tag: &str, sink: &mut Sink) {
84    let title = text(item, "title").trim();
85    let label = if title.is_empty() { "Enpass item" } else { title };
86    if flag(item, "trashed") {
87        sink.skip(label, "it is in the trash");
88        return;
89    }
90    let note = text(item, "note");
91    let fields = live_fields(item);
92    let template = text(item, "template_type");
93    if template.starts_with("login.") || template.starts_with("password.") {
94        login_into(sink, label, title.is_empty(), &fields, note, tag);
95    } else if template.starts_with("creditcard.") {
96        card_into(sink, label, &fields, note, tag);
97    } else if !template.starts_with("identity.") && fields.iter().any(|(ty, _, _)| *ty == "password") {
98        login_into(sink, label, title.is_empty(), &fields, note, tag);
99    } else {
100        // Anything else (an identity, a router, a licence…) has no kind of its own: kept whole, sealed.
101        let mut lines = String::new();
102        for (_, name, value) in &fields {
103            add_line(&mut lines, name, value);
104        }
105        let mut all = String::new();
106        add_line(&mut all, "", &lines);
107        add_line(&mut all, "", note);
108        sink.note(label, &all, tag);
109    }
110}
111
112fn login_into(sink: &mut Sink, label: &str, untitled: bool, fields: &[(&str, &str, &str)], note: &str, tag: &str) {
113    let (mut username, mut password, mut totp) = ("", "", "");
114    let mut urls: Vec<&str> = Vec::new();
115    let mut secret = String::new();
116    add_line(&mut secret, "", note);
117    for (ty, name, value) in fields {
118        match *ty {
119            "username" | "email" if username.is_empty() => username = value.trim(),
120            "password" if password.is_empty() => password = *value,
121            "totp" if totp.is_empty() => totp = value.trim(),
122            "url" => {
123                if urls.len() < MOST_URLS {
124                    urls.push(value.trim());
125                }
126            }
127            // The app a sign-in belongs to on a phone has no address a browser could offer it for.
128            ".Android#" => add_line(&mut secret, "app", value),
129            _ => add_line(&mut secret, name, value),
130        }
131    }
132    for url in urls.iter().skip(1) {
133        add_line(&mut secret, "url", url);
134    }
135    let site = urls.first().copied().unwrap_or("");
136    let label = if untitled { label_of("", site, username) } else { label.to_string() };
137    sink.login(&label, username, password, site, totp, &secret, tag);
138}
139
140fn card_into(sink: &mut Sink, label: &str, fields: &[(&str, &str, &str)], note: &str, tag: &str) {
141    let (mut holder, mut number, mut cvc, mut expires) = ("", "", "", None);
142    let mut secret = String::new();
143    add_line(&mut secret, "", note);
144    for (ty, name, value) in fields {
145        match *ty {
146            "ccName" if holder.is_empty() => holder = value.trim(),
147            "ccNumber" if number.is_empty() => number = value.trim(),
148            "ccCvc" if cvc.is_empty() => cvc = value.trim(),
149            "ccExpiry" if expires.is_none() => match expiry(value) {
150                Some(e) => expires = Some(e),
151                None => add_line(&mut secret, name, value),
152            },
153            // The brand follows from the number.
154            "ccType" => {}
155            _ => add_line(&mut secret, name, value),
156        }
157    }
158    sink.card(label, number, expires, cvc, holder, &secret, tag);
159}
160
161/// An Enpass CSV starts `Title,Field,Value`.
162pub(super) fn csv_looks_like(names: &[String]) -> bool {
163    names.len() >= 3 && names[0] == "title" && names[1] == "field" && names[2] == "value"
164}
165
166/// A field's name as Enpass labels it: a leading `*` marks a sensitive one.
167fn plain_name(name: &str) -> &str {
168    name.trim().trim_start_matches('*').trim()
169}
170
171pub(super) fn read_csv(input: &str) -> Result<Imported, ReadError> {
172    let table = parse_csv(input, false)?;
173    let mut sink = Sink::default();
174    for (n, row) in table.rows.iter().enumerate() {
175        let cells: Vec<&str> = row.iter().collect();
176        if cells.len() < 2 || (n == 0 && cells[0].eq_ignore_ascii_case("title")) {
177            continue;
178        }
179        let title = cells[0].trim();
180        let label = if title.is_empty() { "Enpass item" } else { title };
181        // Enpass appends a note as one more column, so a row of an even length ends with one.
182        let note = if cells.len() % 2 == 0 { cells[cells.len() - 1] } else { "" };
183        let pairs_end = if cells.len() % 2 == 0 { cells.len() - 1 } else { cells.len() };
184        let pairs: Vec<(&str, &str)> = (1..pairs_end).step_by(2).filter(|i| i + 1 < pairs_end).map(|i| (cells[i], cells[i + 1])).filter(|(_, v)| present(v).is_some()).collect();
185        let names: Vec<String> = (1..pairs_end).step_by(2).map(|i| plain_name(cells[i]).to_ascii_lowercase()).collect();
186        let has = |n: &str| names.iter().any(|x| x == n);
187        if has("cardholder") && has("number") && has("expiry date") {
188            csv_card(&mut sink, label, &pairs, note);
189        } else if cells.len() > 2 && ["username", "password", "email", "e-mail", "url", "website"].iter().any(|n| has(n)) {
190            csv_login(&mut sink, label, title.is_empty(), &pairs, note);
191        } else {
192            let mut lines = String::new();
193            for (name, value) in &pairs {
194                add_line(&mut lines, plain_name(name), value);
195            }
196            let mut all = String::new();
197            add_line(&mut all, "", &lines);
198            add_line(&mut all, "", note);
199            sink.note(label, &all, "");
200        }
201    }
202    sink.done(Source::Enpass)
203}
204
205fn csv_login(sink: &mut Sink, label: &str, untitled: bool, pairs: &[(&str, &str)], note: &str) {
206    let (mut username, mut password, mut totp) = ("", "", "");
207    let mut urls: Vec<&str> = Vec::new();
208    let mut secret = String::new();
209    add_line(&mut secret, "", note);
210    for (name, value) in pairs {
211        match plain_name(name).to_ascii_lowercase().as_str() {
212            "url" | "website" => {
213                if urls.len() < MOST_URLS {
214                    urls.push(value.trim());
215                }
216            }
217            "username" | "email" | "e-mail" if username.is_empty() => username = value.trim(),
218            "password" if password.is_empty() => password = *value,
219            "totp" | "one-time code" if totp.is_empty() => totp = value.trim(),
220            _ => add_line(&mut secret, plain_name(name), value),
221        }
222    }
223    for url in urls.iter().skip(1) {
224        add_line(&mut secret, "url", url);
225    }
226    let site = urls.first().copied().unwrap_or("");
227    let label = if untitled { label_of("", site, username) } else { label.to_string() };
228    sink.login(&label, username, password, site, totp, &secret, "");
229}
230
231fn csv_card(sink: &mut Sink, label: &str, pairs: &[(&str, &str)], note: &str) {
232    let (mut holder, mut number, mut cvc, mut expires) = ("", "", "", None);
233    let mut secret = String::new();
234    add_line(&mut secret, "", note);
235    for (name, value) in pairs {
236        match plain_name(name).to_ascii_lowercase().as_str() {
237            "cardholder" if holder.is_empty() => holder = value.trim(),
238            "number" if number.is_empty() => number = value.trim(),
239            "cvc" if cvc.is_empty() => cvc = value.trim(),
240            "expiry date" if expires.is_none() => match expiry(value) {
241                Some(e) => expires = Some(e),
242                None => add_line(&mut secret, plain_name(name), value),
243            },
244            "type" => {}
245            _ => add_line(&mut secret, plain_name(name), value),
246        }
247    }
248    sink.card(label, number, expires, cvc, holder, &secret, "");
249}