Skip to main content

agentmux_srv_core/backend/vault/import/
logins.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The CSV files password managers and browsers export: LastPass, 1Password,
5//! Chrome, Edge, Brave, Firefox, Safari and Apple Passwords all write a table of
6//! logins (spec §8.4), and LastPass also writes its secure notes into it. A CSV no
7//! reader knows is imported with a column mapping the person chooses.
8//!
9//! The columns are found by their names, not their order, since exports differ and
10//! change between versions.
11
12use super::{Imported, Incoming, Mapping, MappingNeeded, ReadError, Source, MAX_ITEMS};
13use std::collections::BTreeMap;
14
15/// A column's lowercase name without spaces, dashes or underscores.
16pub(super) fn norm(name: &str) -> String {
17    name.trim().trim_start_matches('\u{feff}').chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_lowercase()
18}
19
20/// The columns a login table can have, found by their names.
21#[derive(Default)]
22struct Columns {
23    label: Option<usize>,
24    site: Option<usize>,
25    username: Option<usize>,
26    password: Option<usize>,
27    totp: Option<usize>,
28    notes: Option<usize>,
29    folder: Option<usize>,
30    /// LastPass's secure notes are rows whose url is `http://sn`; their fields are in `extra`.
31    extra: Option<usize>,
32}
33
34impl Columns {
35    fn of(headers: &[String]) -> Self {
36        let find = |names: &[&str]| headers.iter().position(|h| names.contains(&norm(h).as_str()));
37        Columns {
38            label: find(&["title", "name"]),
39            site: find(&["url", "website", "loginuri", "weburl", "site"]),
40            username: find(&["username", "loginusername", "user", "login"]),
41            password: find(&["password", "loginpassword"]),
42            totp: find(&["totp", "otp", "otpauth", "onetimepassword", "logintotp"]),
43            notes: find(&["notes", "note"]),
44            folder: find(&["grouping", "folder", "group", "tags"]),
45            extra: find(&["extra"]),
46        }
47    }
48}
49
50/// Which export it is, from its column names.
51fn source_of(headers: &[String]) -> Source {
52    let names: Vec<String> = headers.iter().map(|h| norm(h)).collect();
53    let has = |n: &str| names.iter().any(|x| x == n);
54    if has("grouping") && has("extra") {
55        Source::LastPass
56    } else if has("httprealm") || has("formactionorigin") {
57        Source::Firefox
58    } else if has("otpauth") && has("title") {
59        Source::Safari
60    } else if has("title") && (has("website") || has("url")) && (has("type") || has("archived") || has("favorite") || has("tags")) {
61        Source::OnePassword
62    } else if has("name") && has("url") && has("username") && has("password") {
63        Source::Chrome
64    } else {
65        Source::Csv
66    }
67}
68
69pub(super) fn cell<'a>(row: &'a csv::StringRecord, col: Option<usize>) -> &'a str {
70    col.and_then(|i| row.get(i)).map(str::trim).unwrap_or("")
71}
72
73/// On a login Chrome kept for an Android app: it has no site to be offered on, so it stays in the Vault only.
74pub(super) const ANDROID_APP: &str = "from an Android app: no site to offer it on";
75
76/// A browser export's address as a saved sign-in names its site: the exact origin of a web page's
77/// address (`https://accounts.example.com/signin?x=1` is `https://accounts.example.com`), and none for an
78/// Android app (`android://<hash>@com.example.app/`), whose package is given back for a label. An address
79/// with no web origin is kept as exported.
80pub(super) fn chrome_site(url: &str) -> (String, Option<String>) {
81    let url = url.trim();
82    if let Some(app) = url.strip_prefix("android://") {
83        let package = app.rsplit_once('@').map_or(app, |(_, p)| p).trim_end_matches('/');
84        return (String::new(), Some(if package.is_empty() { "Android app".to_string() } else { package.to_string() }));
85    }
86    (agentmux_common::allowed_origins::target_origin(url).unwrap_or_else(|| url.to_string()), None)
87}
88
89/// A host for a label when a row has no title.
90pub(super) fn host_of(url: &str) -> String {
91    let rest = url.split("://").nth(1).unwrap_or(url);
92    rest.split(['/', '?', '#']).next().unwrap_or("").trim_start_matches("www.").to_string()
93}
94
95pub fn read(text: &str, mapping: Option<&Mapping>) -> Result<Imported, ReadError> {
96    let mut reader = csv::ReaderBuilder::new().flexible(true).from_reader(text.as_bytes());
97    let headers: Vec<String> = reader.headers().map_err(|e| ReadError::from(format!("this isn't a CSV file: {e}")))?.iter().map(str::to_string).collect();
98    if headers.len() < 2 {
99        return Err("this doesn't look like a CSV file of passwords: it has one column".into());
100    }
101    let mut rows = Vec::new();
102    for record in reader.records() {
103        let record = record.map_err(|e| ReadError::from(format!("couldn't read a row of the CSV: {e}")))?;
104        if rows.len() >= MAX_ITEMS {
105            return Err(format!("this file has more than {MAX_ITEMS} rows, more than the Vault imports").into());
106        }
107        rows.push(record);
108    }
109    if let Some(m) = mapping {
110        return mapped(&rows, &headers, m);
111    }
112    let cols = Columns::of(&headers);
113    if cols.password.is_none() || (cols.site.is_none() && cols.label.is_none()) {
114        return Err(ReadError::NeedsMapping(MappingNeeded { columns: headers, rows: rows.len() }));
115    }
116    let source = source_of(&headers);
117    let mut entries = Vec::new();
118    let mut skipped = Vec::new();
119    for row in &rows {
120        // A browser export gives a page's address; a saved sign-in is offered for exactly a site's origin.
121        let (site, android) = if source == Source::Chrome { chrome_site(cell(row, cols.site)) } else { (cell(row, cols.site).to_string(), None) };
122        let site = site.as_str();
123        let title = cell(row, cols.label);
124        let label = if !title.is_empty() {
125            title.to_string()
126        } else if !host_of(site).is_empty() {
127            host_of(site)
128        } else if let Some(app) = android.as_deref() {
129            app.to_string()
130        } else {
131            cell(row, cols.username).to_string()
132        };
133        let label = if label.is_empty() { "(unnamed)".to_string() } else { label };
134        let folder = cell(row, cols.folder);
135        if source == Source::LastPass && site == "http://sn" {
136            match lastpass_note(&label, cell(row, cols.extra)) {
137                Ok(made) => entries.extend(made.into_iter().map(|e| e.tag(folder))),
138                Err(why) => skipped.push((label, why)),
139            }
140            continue;
141        }
142        // A password is kept exactly as exported, spaces and all.
143        let password = cols.password.and_then(|i| row.get(i)).unwrap_or("");
144        // LastPass keeps a login's notes in `extra`.
145        let notes_col = cols.notes.or(if source == Source::LastPass { cols.extra } else { None });
146        if password.is_empty() {
147            // Bitwarden's CSV puts a secure note in a row with no login: its text is the point, so it
148            // is kept (sealed) with where and who it was filed under; a row with nothing but an
149            // address or a name is listed as skipped.
150            let notes = cell(row, notes_col);
151            if notes.is_empty() {
152                skipped.push((label, "it has no password".to_string()));
153            } else {
154                let mut text = String::new();
155                for (name, value) in [("site", site), ("username", cell(row, cols.username))] {
156                    if !value.is_empty() {
157                        text.push_str(&format!("{name}: {value}"));
158                        text.push(char::from(10));
159                    }
160                }
161                text.push_str(notes);
162                entries.push(Incoming::new("note", &label).part("text", &text).tag(folder));
163            }
164            continue;
165        }
166        let mut login = Incoming::new("login", &label).part("password", password).field("site", site).field("username", cell(row, cols.username)).tag(folder);
167        if android.is_some() {
168            login = login.tag(ANDROID_APP);
169        }
170        let totp = cell(row, cols.totp);
171        if !totp.is_empty() {
172            login = login.part("totp", totp);
173        }
174        entries.push(login);
175        // Notes can hold secrets, so they are kept sealed in a note of their own.
176        let notes = cell(row, notes_col);
177        if !notes.is_empty() {
178            entries.push(Incoming::new("note", &format!("{label} (notes)")).part("text", notes).tag(folder));
179        }
180    }
181    Ok(Imported { source, entries, skipped, plaintext: true })
182}
183
184/// Rows read with the person's own column choices.
185fn mapped(rows: &[csv::StringRecord], headers: &[String], m: &Mapping) -> Result<Imported, ReadError> {
186    let kind = super::super::kinds::kind(&m.kind).ok_or_else(|| ReadError::from(format!("unknown kind {:?}", m.kind)))?;
187    if headers.len() <= m.label.max(m.value) || m.site.is_some_and(|i| i >= headers.len()) || m.username.is_some_and(|i| i >= headers.len()) {
188        return Err("a chosen column isn't in the file".into());
189    }
190    if kind.name == "login" && m.site.is_none() && m.username.is_none() {
191        return Err("a login needs a site or a username column as well as its password".into());
192    }
193    let main = kind.parts[0];
194    let mut entries = Vec::new();
195    let mut skipped = Vec::new();
196    for row in rows {
197        let (label, value) = (cell(row, Some(m.label)), cell(row, Some(m.value)));
198        let label = if label.is_empty() { "(unnamed)" } else { label };
199        if value.is_empty() {
200            skipped.push((label.to_string(), format!("its {main} column is empty")));
201            continue;
202        }
203        let mut e = Incoming::new(kind.name, label).part(main, value);
204        if kind.fields.contains(&"site") {
205            e = e.field("site", cell(row, m.site));
206        }
207        if kind.fields.contains(&"username") {
208            e = e.field("username", cell(row, m.username));
209        }
210        entries.push(e);
211    }
212    Ok(Imported { source: Source::Csv, entries, skipped, plaintext: true })
213}
214
215// ── LastPass secure notes ───────────────────────────────────────────────────
216
217/// Every line that starts one of a secure note's fields, whatever its type.
218const LASTPASS_KEYS: &[&str] = &[
219    "NoteType",
220    "Language",
221    "Name on Card",
222    "Type",
223    "Number",
224    "Security Code",
225    "Start Date",
226    "Expiration Date",
227    "Notes",
228    "Bank Name",
229    "Account Type",
230    "Routing Number",
231    "Account Number",
232    "SWIFT Code",
233    "IBAN Number",
234    "Pin",
235    "Branch Address",
236    "Branch Phone",
237    "Name",
238    "Issuing Authority",
239    "Date of Birth",
240    "Sex",
241    "Height",
242    "Issue Date",
243    "Hostname",
244    "Username",
245    "Password",
246    "Port",
247];
248
249/// The `Key:Value` fields of a secure note's `extra`: a line that starts with a
250/// known key begins a field; any other line continues the one before.
251fn lastpass_fields(extra: &str) -> BTreeMap<String, String> {
252    let mut out: BTreeMap<String, String> = BTreeMap::new();
253    let mut current: Option<String> = None;
254    for line in extra.lines() {
255        let key = LASTPASS_KEYS.iter().find(|k| line.strip_prefix(**k).is_some_and(|rest| rest.starts_with(':')));
256        match (key, &current) {
257            (Some(k), _) => {
258                out.insert((*k).to_string(), line[k.len() + 1..].trim().to_string());
259                current = Some((*k).to_string());
260            }
261            (None, Some(k)) => {
262                let v = out.entry(k.clone()).or_default();
263                v.push('\n');
264                v.push_str(line);
265            }
266            (None, None) => {}
267        }
268    }
269    out
270}
271
272/// `January,2030` as `01/2030`.
273fn month_year(s: &str) -> String {
274    const MONTHS: [&str; 12] = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
275    let mut parts = s.split(',');
276    match (parts.next().map(|m| m.trim().to_lowercase()), parts.next().map(str::trim)) {
277        (Some(m), Some(y)) if !y.is_empty() => match MONTHS.iter().position(|x| *x == m) {
278            Some(i) => format!("{:02}/{y}", i + 1),
279            None => s.trim().to_string(),
280        },
281        _ => s.trim().to_string(),
282    }
283}
284
285/// A secure note by its `NoteType`: the kinds the Vault has, else a note holding
286/// every field.
287fn lastpass_note(label: &str, extra: &str) -> Result<Vec<Incoming>, String> {
288    let f = lastpass_fields(extra);
289    let get = |k: &str| f.get(k).map(|v| v.trim()).unwrap_or("");
290    let notes = get("Notes");
291    let mut made: Vec<Incoming> = match get("NoteType") {
292        "Credit Card" if !get("Number").is_empty() => {
293            let mut e = Incoming::new("card", label).part("number", get("Number"));
294            for (part, key) in [("cvc", "Security Code"), ("name", "Name on Card")] {
295                if !get(key).is_empty() {
296                    e = e.part(part, get(key));
297                }
298            }
299            if !get("Expiration Date").is_empty() {
300                e = e.part("expiry", &month_year(get("Expiration Date")));
301            }
302            vec![e]
303        }
304        "Bank Account" if !get("Account Number").is_empty() => {
305            let mut e = Incoming::new("bank-account", label).part("account", get("Account Number")).field("bank", get("Bank Name"));
306            if !get("Routing Number").is_empty() {
307                e = e.part("routing", get("Routing Number"));
308            }
309            vec![e]
310        }
311        "Social Security" if !get("Number").is_empty() => vec![Incoming::new("ssn", label).part("value", get("Number")).field("owner", get("Name"))],
312        "Driver's License" if !get("Number").is_empty() => {
313            vec![Incoming::new("drivers-licence", label).part("value", get("Number")).field("owner", get("Name")).field("expires", &month_year(get("Expiration Date")))]
314        }
315        "Passport" if !get("Number").is_empty() => {
316            vec![Incoming::new("passport", label).part("value", get("Number")).field("owner", get("Name")).field("issuer", get("Issuing Authority")).field("expires", &month_year(get("Expiration Date")))]
317        }
318        _ => {
319            // Every other type (an address, a server, an SSH key, a plain note) is kept
320            // whole, line for line, without the two lines that only name its type.
321            let text = extra.lines().filter(|l| !l.starts_with("NoteType:") && !l.starts_with("Language:")).collect::<Vec<_>>().join("\n");
322            if text.trim().is_empty() {
323                return Err("the secure note is empty".to_string());
324            }
325            return Ok(vec![Incoming::new("note", label).part("text", &text)]);
326        }
327    };
328    if !notes.is_empty() {
329        made.push(Incoming::new("note", &format!("{label} (notes)")).part("text", notes));
330    }
331    Ok(made)
332}