Skip to main content

agentmux_srv_core/backend/vault/import/
shared.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the readers of the second wave of services share (Dashlane, Keeper, NordPass, RoboForm,
5//! Zoho Vault, and the others of spec §12 P6): reading a table, and making entries the way the
6//! first wave does. A login's notes and custom fields can hold recovery codes, so they are sealed
7//! in a note of their own; a folder becomes a tag; a row with nothing to keep is listed as
8//! skipped with the reason.
9
10pub(super) use super::logins::{cell, host_of, norm};
11use super::{Imported, Incoming, ReadError, Source, MAX_ITEMS};
12
13/// A CSV file: its header row (empty when the service writes none) and its rows.
14pub(super) struct Table {
15    pub headers: Vec<String>,
16    pub rows: Vec<csv::StringRecord>,
17}
18
19pub(super) fn parse_csv(text: &str, has_header: bool) -> Result<Table, ReadError> {
20    let mut reader = csv::ReaderBuilder::new().flexible(true).has_headers(has_header).from_reader(text.as_bytes());
21    let headers: Vec<String> = if has_header {
22        reader.headers().map_err(|e| ReadError::from(format!("this isn't a CSV file: {e}")))?.iter().map(str::to_string).collect()
23    } else {
24        Vec::new()
25    };
26    let mut rows = Vec::new();
27    for record in reader.records() {
28        let record = record.map_err(|e| ReadError::from(format!("couldn't read a row of the CSV: {e}")))?;
29        if rows.len() >= MAX_ITEMS {
30            return Err(format!("this file has more than {MAX_ITEMS} rows, more than the Vault imports").into());
31        }
32        rows.push(record);
33    }
34    Ok(Table { headers, rows })
35}
36
37impl Table {
38    /// A row's cell in the column with this name, trimmed; empty when the file has no such column.
39    pub fn get<'a>(&self, row: &'a csv::StringRecord, name: &str) -> &'a str {
40        cell(row, self.col(&[name]))
41    }
42
43    /// The first column with one of these names (compared without case, spaces, dashes or underscores).
44    pub fn col(&self, names: &[&str]) -> Option<usize> {
45        self.headers.iter().position(|h| names.contains(&norm(h).as_str()))
46    }
47}
48
49/// A header row's names, normalised, for telling which service wrote the file.
50pub(super) fn header_names(text: &str) -> Vec<String> {
51    let mut reader = csv::ReaderBuilder::new().flexible(true).from_reader(text.as_bytes());
52    reader.headers().map(|h| h.iter().map(norm).collect()).unwrap_or_default()
53}
54
55pub(super) fn present(s: &str) -> Option<&str> {
56    let t = s.trim();
57    (!t.is_empty()).then_some(t)
58}
59
60/// `MM/YYYY` from a month and a year written apart (`1` and `2030`, or `01` and `30`).
61pub(super) fn month_year(month: &str, year: &str) -> Option<String> {
62    let m: u32 = month.trim().parse().ok().filter(|m| (1..=12).contains(m))?;
63    let y: u32 = year.trim().parse().ok()?;
64    let y = if y < 100 { 2000 + y } else { y };
65    (1000..=9999).contains(&y).then(|| format!("{m:02}/{y}"))
66}
67
68/// `MM/YYYY` from an expiry written `01 / 22`, `1/2030` or `03/23`.
69pub(super) fn expiry(s: &str) -> Option<String> {
70    let compact: String = s.chars().filter(|c| !c.is_whitespace()).collect();
71    let (m, y) = compact.split_once('/')?;
72    month_year(m, y)
73}
74
75/// Text to seal: each non-empty value on its own line, as `name: value` (or just the value when
76/// the name is empty).
77pub(super) fn sealed(parts: &[(&str, &str)]) -> String {
78    let mut out = String::new();
79    for (name, value) in parts {
80        add_line(&mut out, name, value);
81    }
82    out
83}
84
85/// Adds one line to text to seal: `name: value`, or just the value when the name is empty. A
86/// value with nothing in it adds nothing.
87pub(super) fn add_line(out: &mut String, name: &str, value: &str) {
88    let Some(v) = present(value) else { return };
89    if !out.is_empty() {
90        out.push('\n');
91    }
92    if name.is_empty() {
93        out.push_str(v);
94    } else {
95        out.push_str(name);
96        out.push_str(": ");
97        out.push_str(v);
98    }
99}
100
101/// A label for a row that has no title: its host, else its username.
102pub(super) fn label_of(title: &str, site: &str, username: &str) -> String {
103    let host = host_of(site);
104    let label = [title.trim(), host.as_str(), username.trim()].into_iter().find(|s| !s.is_empty()).unwrap_or("(unnamed)").to_string();
105    label
106}
107
108/// What a reader collects.
109#[derive(Default)]
110pub(super) struct Sink {
111    pub entries: Vec<Incoming>,
112    pub skipped: Vec<(String, String)>,
113}
114
115impl Sink {
116    pub fn skip(&mut self, label: &str, why: &str) {
117        self.skipped.push((label.to_string(), why.to_string()));
118    }
119
120    /// A login. `secret` is the text to seal beside it (notes, custom fields). A row with no
121    /// password but something to keep is kept as a note, with where and who it was filed under; a
122    /// row with nothing is listed as skipped.
123    pub fn login(&mut self, label: &str, username: &str, password: &str, site: &str, totp: &str, secret: &str, tag: &str) {
124        if password.is_empty() {
125            if secret.trim().is_empty() {
126                self.skip(label, "it has no password");
127                return;
128            }
129            let mut text = String::new();
130            for (name, value) in [("site", site), ("username", username)] {
131                if let Some(v) = present(value) {
132                    text.push_str(&format!("{name}: {v}\n"));
133                }
134            }
135            text.push_str(secret);
136            self.entries.push(Incoming::new("note", label).part("text", &text).tag(tag));
137            return;
138        }
139        // A password is kept exactly as exported, spaces and all.
140        let mut login = Incoming::new("login", label).part("password", password).field("site", site).field("username", username).tag(tag);
141        if let Some(t) = present(totp) {
142            login = login.part("totp", t);
143        }
144        self.entries.push(login);
145        self.notes_of(label, secret, tag);
146    }
147
148    /// The text sealed beside another entry, in a note named for it.
149    pub fn notes_of(&mut self, label: &str, secret: &str, tag: &str) {
150        if !secret.trim().is_empty() {
151            self.entries.push(Incoming::new("note", &format!("{label} (notes)")).part("text", secret).tag(tag));
152        }
153    }
154
155    pub fn note(&mut self, label: &str, text: &str, tag: &str) {
156        if text.trim().is_empty() {
157            self.skip(label, "the note is empty");
158        } else {
159            self.entries.push(Incoming::new("note", label).part("text", text).tag(tag));
160        }
161    }
162
163    pub fn card(&mut self, label: &str, number: &str, expiry: Option<String>, cvc: &str, holder: &str, secret: &str, tag: &str) {
164        let Some(number) = present(number) else {
165            self.skip(label, "the card has no number");
166            return;
167        };
168        let mut e = Incoming::new("card", label).part("number", number);
169        if let Some(x) = expiry {
170            e = e.part("expiry", &x);
171        }
172        for (part, value) in [("cvc", cvc), ("name", holder)] {
173            if let Some(v) = present(value) {
174                e = e.part(part, v);
175            }
176        }
177        self.entries.push(e.tag(tag));
178        self.notes_of(label, secret, tag);
179    }
180
181    pub fn bank(&mut self, label: &str, account: &str, routing: &str, bank: &str, owner: &str, secret: &str, tag: &str) {
182        let Some(account) = present(account) else {
183            self.skip(label, "the account has no number");
184            return;
185        };
186        let mut e = Incoming::new("bank-account", label).part("account", account).field("bank", bank).field("owner", owner);
187        if let Some(r) = present(routing) {
188            e = e.part("routing", r);
189        }
190        self.entries.push(e.tag(tag));
191        self.notes_of(label, secret, tag);
192    }
193
194    /// An identity number of a kind the Vault has (`ssn`, `passport`, `drivers-licence`, …).
195    pub fn id(&mut self, kind: &str, label: &str, value: &str, owner: &str, issuer: &str, expires: &str, tag: &str) {
196        let Some(value) = present(value) else {
197            self.skip(label, "it has no number");
198            return;
199        };
200        let mut e = Incoming::new(kind, label).part("value", value).field("owner", owner);
201        if kind != "ssn" && kind != "tin" && kind != "date-of-birth" {
202            e = e.field("issuer", issuer).field("expires", expires);
203        }
204        self.entries.push(e.tag(tag));
205    }
206
207    pub fn done(self, source: Source) -> Result<Imported, ReadError> {
208        Ok(Imported { source, entries: self.entries, skipped: self.skipped, plaintext: true })
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn expiries_are_written_month_slash_year() {
218        assert_eq!(expiry("01 / 22").as_deref(), Some("01/2022"));
219        assert_eq!(expiry("1/2030").as_deref(), Some("01/2030"));
220        assert_eq!(expiry("13/2030"), None);
221        assert_eq!(expiry("soon"), None);
222        assert_eq!(month_year("3", "2031").as_deref(), Some("03/2031"));
223        assert_eq!(month_year("", ""), None);
224    }
225
226    #[test]
227    fn sealed_text_skips_what_is_empty() {
228        assert_eq!(sealed(&[("", "a note"), ("pin", " "), ("code", "1234")]), "a note\ncode: 1234");
229    }
230}