1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
//! Conversion types for various CSV formats.

pub mod bitwarden;
pub mod chrome;
pub mod dashlane;
pub mod firefox;
pub mod macos;
pub mod one_password;

use async_trait::async_trait;
use secrecy::SecretString;
use std::collections::{HashMap, HashSet};
use url::Url;
use vcard4::Vcard;

use crate::{
    crypto::AccessKey,
    storage::search::SearchIndex,
    vault::{
        secret::{
            IdentityKind, Secret, SecretId, SecretMeta, SecretRow, UserData,
        },
        Gatekeeper, Vault,
    },
    UtcDateTime,
};

use crate::migrate::Convert;

/// Default label for CSV records when a title is not available.
pub const UNTITLED: &str = "Untitled";

/// Generic CSV entry type.
pub enum GenericCsvEntry {
    /// Password Eentry.
    Password(GenericPasswordRecord),
    /// Note entry.
    Note(GenericNoteRecord),
    /// Identity entry.
    Id(GenericIdRecord),
    /// Payment entry.
    Payment(GenericPaymentRecord),
    /// Contact entry.
    Contact(Box<GenericContactRecord>),
}

impl GenericCsvEntry {
    /// Get the label for the record.
    fn label(&self) -> &str {
        match self {
            Self::Password(record) => &record.label,
            Self::Note(record) => &record.label,
            Self::Id(record) => &record.label,
            Self::Payment(record) => record.label(),
            Self::Contact(record) => &record.label,
        }
    }

    /// Get the tags for the record.
    fn tags(&mut self) -> &mut Option<HashSet<String>> {
        match self {
            Self::Password(record) => &mut record.tags,
            Self::Note(record) => &mut record.tags,
            Self::Id(record) => &mut record.tags,
            Self::Payment(record) => record.tags(),
            Self::Contact(record) => &mut record.tags,
        }
    }

    /// Get the note for the record.
    fn note(&mut self) -> &mut Option<String> {
        match self {
            Self::Password(record) => &mut record.note,
            Self::Note(record) => &mut record.note,
            Self::Id(record) => &mut record.note,
            Self::Payment(record) => record.note(),
            Self::Contact(record) => &mut record.note,
        }
    }
}

impl From<GenericCsvEntry> for Secret {
    fn from(value: GenericCsvEntry) -> Self {
        match value {
            GenericCsvEntry::Password(record) => Secret::Account {
                account: record.username,
                password: SecretString::new(record.password),
                url: record.url,
                user_data: if let Some(notes) = record.note {
                    UserData::new_comment(notes)
                } else {
                    Default::default()
                },
            },
            GenericCsvEntry::Note(record) => Secret::Note {
                text: SecretString::new(record.text),
                user_data: if let Some(notes) = record.note {
                    UserData::new_comment(notes)
                } else {
                    Default::default()
                },
            },
            GenericCsvEntry::Id(record) => Secret::Identity {
                id_kind: record.id_kind,
                number: SecretString::new(record.number),
                issue_place: record.issue_place,
                issue_date: record.issue_date,
                expiry_date: record.expiration_date,
                user_data: if let Some(notes) = record.note {
                    UserData::new_comment(notes)
                } else {
                    Default::default()
                },
            },
            GenericCsvEntry::Payment(record) => match record {
                GenericPaymentRecord::Card {
                    number,
                    code,
                    expiration,
                    note,
                    ..
                } => {
                    // TODO: handle country?
                    Secret::Card {
                        number: SecretString::new(number),
                        cvv: SecretString::new(code),
                        expiry: expiration,
                        name: None,
                        atm_pin: None,
                        user_data: if let Some(notes) = note {
                            UserData::new_comment(notes)
                        } else {
                            Default::default()
                        },
                    }
                }
                GenericPaymentRecord::BankAccount {
                    account_number,
                    routing_number,
                    note,
                    ..
                } => {
                    // TODO: handle country and account_holder
                    Secret::Bank {
                        number: SecretString::new(account_number),
                        routing: SecretString::new(routing_number),
                        bic: None,
                        iban: None,
                        swift: None,
                        user_data: if let Some(notes) = note {
                            UserData::new_comment(notes)
                        } else {
                            Default::default()
                        },
                    }
                }
            },
            GenericCsvEntry::Contact(record) => Secret::Contact {
                vcard: Box::new(record.vcard),
                user_data: if let Some(notes) = record.note {
                    UserData::new_comment(notes)
                } else {
                    Default::default()
                },
            },
        }
    }
}

/// Generic password record.
pub struct GenericPasswordRecord {
    /// The label of the entry.
    pub label: String,
    /// The URL of the entry.
    pub url: Option<Url>,
    /// The username for the entry.
    pub username: String,
    /// The password for the entry.
    pub password: String,
    /// OTP auth information for the entry.
    pub otp_auth: Option<String>,
    /// Collection of tags.
    pub tags: Option<HashSet<String>>,
    /// Optional note.
    pub note: Option<String>,
}

/// Generic note record.
pub struct GenericNoteRecord {
    /// The label of the entry.
    pub label: String,
    /// The text for the note entry.
    pub text: String,
    /// Collection of tags.
    pub tags: Option<HashSet<String>>,
    /// Optional note.
    pub note: Option<String>,
}

/// Generic contact record.
pub struct GenericContactRecord {
    /// The label of the entry.
    pub label: String,
    /// The vcard for the entry.
    pub vcard: Vcard,
    /// Collection of tags.
    pub tags: Option<HashSet<String>>,
    /// Optional note.
    pub note: Option<String>,
}

/// Generic identification record.
pub struct GenericIdRecord {
    /// The label of the entry.
    pub label: String,
    /// The kind of identification.
    pub id_kind: IdentityKind,
    /// The number for the entry.
    pub number: String,
    /// The issue place for the entry.
    pub issue_place: Option<String>,
    /// The issue date for the entry.
    pub issue_date: Option<UtcDateTime>,
    /// The expiration date for the entry.
    pub expiration_date: Option<UtcDateTime>,
    /// Collection of tags.
    pub tags: Option<HashSet<String>>,
    /// Optional note.
    pub note: Option<String>,
}

/// Generic payment record.
pub enum GenericPaymentRecord {
    /// Card payment information.
    Card {
        /// The label of the entry.
        label: String,
        /// The card number.
        number: String,
        /// The CVV code.
        code: String,
        /// An expiration date.
        expiration: Option<UtcDateTime>,
        /// The country for the entry.
        country: String,
        /// A note for the entry.
        note: Option<String>,
        /// Collection of tags.
        tags: Option<HashSet<String>>,
    },
    /// Bank account payment information.
    BankAccount {
        /// The label of the entry.
        label: String,
        /// The account holder of the entry.
        account_holder: String,
        /// The account number of the entry.
        account_number: String,
        /// The routing number of the entry.
        routing_number: String,
        /// The country for the entry.
        country: String,
        /// A note for the entry.
        note: Option<String>,
        /// Collection of tags.
        tags: Option<HashSet<String>>,
    },
}

impl GenericPaymentRecord {
    /// Get the label for the record.
    fn label(&self) -> &str {
        match self {
            Self::Card { label, .. } => label,
            Self::BankAccount { label, .. } => label,
        }
    }

    /// Get the tags for the record.
    fn tags(&mut self) -> &mut Option<HashSet<String>> {
        match self {
            Self::Card { tags, .. } => tags,
            Self::BankAccount { tags, .. } => tags,
        }
    }

    /// Get the note for the record.
    fn note(&mut self) -> &mut Option<String> {
        match self {
            Self::Card { note, .. } => note,
            Self::BankAccount { note, .. } => note,
        }
    }
}

/// Convert from generic password records.
pub struct GenericCsvConvert;

#[async_trait]
impl Convert for GenericCsvConvert {
    type Input = Vec<GenericCsvEntry>;

    async fn convert(
        &self,
        source: Self::Input,
        vault: Vault,
        key: &AccessKey,
    ) -> crate::Result<Vault> {
        let mut index = SearchIndex::new();
        let mut keeper = Gatekeeper::new(vault);
        keeper.unlock(key).await?;

        let mut duplicates: HashMap<String, usize> = HashMap::new();

        for mut entry in source {
            // Handle duplicate labels by incrementing a counter
            let mut label = entry.label().to_owned();

            let rename_label = {
                if index
                    .find_by_label(keeper.vault().id(), &label, None)
                    .is_some()
                {
                    duplicates
                        .entry(label.clone())
                        .and_modify(|counter| *counter += 1)
                        .or_insert(1);
                    let counter = duplicates.get(&label).unwrap();
                    Some(format!("{} {}", label, counter))
                } else {
                    None
                }
            };

            if let Some(renamed) = rename_label {
                label = renamed;
            }

            let tags = entry.tags().take();
            let note = entry.note().take();
            let mut secret: Secret = entry.into();
            secret.user_data_mut().set_comment(note);
            let mut meta = SecretMeta::new(label, secret.kind());
            if let Some(tags) = tags {
                meta.set_tags(tags);
            }

            let id = SecretId::new_v4();
            let index_doc = index.prepare(keeper.id(), &id, &meta, &secret);
            let secret_data = SecretRow::new(id, meta, secret);
            keeper.create_secret(&secret_data).await?;
            index.commit(index_doc);
        }

        keeper.lock();
        Ok(keeper.into())
    }
}