1use std::collections::HashMap;
11use std::io::Read;
12
13use serde_json::Value;
14
15use super::shared::{add_line, label_of, month_year, parse_csv, present, Sink};
16use super::{Imported, ReadError, Source, MAX_ITEMS};
17
18const MAX_DATA_BYTES: u64 = 64 * 1024 * 1024;
20const MAX_ZIP_ENTRIES: usize = 100_000;
22const MOST_URLS: usize = 50;
24const MOST_DEPTH: usize = 32;
26
27const DATA_JSON: &str = "Proton Pass/data.json";
28const DATA_PGP: &str = "Proton Pass/data.pgp";
29const FILES_DIR: &str = "Proton Pass/files/";
30
31pub(super) const ENCRYPTED: &str = "this Proton Pass export is protected with a passphrase, which AgentMux can't open yet; export it again from Proton Pass without the passphrase (as a zip or as JSON), or as a CSV for the logins";
32
33static NULL: Value = Value::Null;
34
35pub(super) fn zip_looks_like(bytes: &[u8]) -> bool {
36 zip::ZipArchive::new(std::io::Cursor::new(bytes)).is_ok_and(|z| z.file_names().any(|n| n == DATA_JSON || n == DATA_PGP))
37}
38
39pub(super) fn read_zip(bytes: &[u8]) -> Result<Imported, ReadError> {
40 let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|_| ReadError::from("this zip file is damaged or isn't one"))?;
41 if archive.len() > MAX_ZIP_ENTRIES {
42 return Err("this zip has more files than a Proton Pass export does".into());
43 }
44 let attachments = archive.file_names().filter(|n| n.starts_with(FILES_DIR) && !n.ends_with('/')).count();
45 let mut data = Vec::new();
46 match archive.by_name(DATA_JSON) {
47 Ok(file) => {
48 file.take(MAX_DATA_BYTES + 1).read_to_end(&mut data).map_err(|_| ReadError::from("couldn't read data.json from the zip"))?;
49 }
50 Err(_) => return Err(ENCRYPTED.into()),
51 }
52 if data.len() as u64 > MAX_DATA_BYTES {
53 return Err("this export's data is larger than the Vault imports".into());
54 }
55 let text = String::from_utf8(data).map_err(|_| ReadError::from("data.json isn't the text a Proton Pass export holds"))?;
56 let mut imported = read_json(&text)?;
57 if attachments > 0 {
58 imported.skipped.push(("attachments".into(), format!("{attachments} attached file{} can't be imported", if attachments == 1 { "" } else { "s" })));
59 }
60 Ok(imported)
61}
62
63fn text<'a>(v: &'a Value, key: &str) -> &'a str {
65 v.get(key).and_then(Value::as_str).unwrap_or("")
66}
67
68pub(super) fn read_json(text: &str) -> Result<Imported, ReadError> {
69 let root: Value = serde_json::from_str(text).map_err(|_| ReadError::from("this isn't the JSON a Proton Pass export holds"))?;
70 if root.get("encrypted").and_then(Value::as_bool) == Some(true) {
71 return Err(ENCRYPTED.into());
72 }
73 let vaults = root.get("vaults").and_then(Value::as_object).ok_or("this JSON isn't a Proton Pass export: it has no vaults")?;
74 let mut sink = Sink::default();
75 let mut count = 0usize;
76 for vault in vaults.values() {
77 let vault_name = text_of(vault, "name");
78 let folders = folder_paths(vault);
79 for item in vault.get("items").and_then(Value::as_array).into_iter().flatten() {
80 count += 1;
81 if count > MAX_ITEMS {
82 return Err(format!("this export has more than {MAX_ITEMS} items, more than the Vault imports").into());
83 }
84 let folder = item.get("folderId").and_then(Value::as_str).and_then(|id| folders.get(id));
85 let tag = match folder {
86 Some(path) if !vault_name.is_empty() => format!("{vault_name}/{path}"),
87 Some(path) => path.clone(),
88 None => vault_name.to_string(),
89 };
90 item_into(item, &tag, &mut sink);
91 }
92 }
93 if count == 0 {
94 return Err("this Proton Pass export has no items".into());
95 }
96 sink.done(Source::ProtonPass)
97}
98
99fn text_of<'a>(v: &'a Value, key: &str) -> &'a str {
100 text(v, key).trim()
101}
102
103fn folder_paths(vault: &Value) -> HashMap<String, String> {
105 let list: Vec<&Value> = vault.get("folders").and_then(Value::as_array).into_iter().flatten().take(MAX_ITEMS).collect();
106 let by_id: HashMap<&str, &Value> = list.iter().filter_map(|f| Some((f.get("folderId")?.as_str()?, *f))).collect();
107 let mut paths = HashMap::new();
108 for (id, folder) in &by_id {
109 let mut parts = vec![text_of(folder, "name")];
110 let mut parent = folder.get("parentFolderId").and_then(Value::as_str);
111 while let Some(p) = parent {
112 if parts.len() >= MOST_DEPTH {
113 break;
114 }
115 let Some(up) = by_id.get(p) else { break };
116 parts.push(text_of(up, "name"));
117 parent = up.get("parentFolderId").and_then(Value::as_str);
118 }
119 parts.reverse();
120 let path = parts.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join("/");
121 if !path.is_empty() {
122 paths.insert(id.to_string(), path);
123 }
124 }
125 paths
126}
127
128fn extra_value(field: &Value) -> String {
130 let data = field.get("data").unwrap_or(&NULL);
131 match text(field, "type") {
132 "totp" => text(data, "totpUri").to_string(),
133 "timestamp" => match data.get("timestamp") {
134 Some(Value::String(s)) => s.clone(),
135 Some(Value::Number(n)) => n.to_string(),
136 Some(other) if !other.is_null() => other.to_string(),
137 _ => String::new(),
138 },
139 _ => text(data, "content").to_string(),
140 }
141}
142
143fn extra_lines(fields: Option<&Value>) -> String {
145 let mut out = String::new();
146 for field in fields.and_then(Value::as_array).into_iter().flatten() {
147 add_line(&mut out, text_of(field, "fieldName"), &extra_value(field));
148 }
149 out
150}
151
152fn section_lines(sections: Option<&Value>) -> String {
154 let mut out = String::new();
155 for section in sections.and_then(Value::as_array).into_iter().flatten() {
156 let lines = extra_lines(section.get("sectionFields"));
157 if lines.is_empty() {
158 continue;
159 }
160 add_line(&mut out, "", text_of(section, "sectionName"));
161 add_line(&mut out, "", &lines);
162 }
163 out
164}
165
166fn join(parts: &[&str]) -> String {
167 let mut out = String::new();
168 for p in parts {
169 add_line(&mut out, "", p);
170 }
171 out
172}
173
174fn login_urls(content: &Value) -> Vec<String> {
176 let modes: Vec<String> = content
177 .get("autofillUrls")
178 .and_then(Value::as_array)
179 .into_iter()
180 .flatten()
181 .filter_map(|u| present(text(u, "url")).map(str::to_string))
182 .take(MOST_URLS)
183 .collect();
184 if !modes.is_empty() {
185 return modes;
186 }
187 content.get("urls").and_then(Value::as_array).into_iter().flatten().filter_map(|u| u.as_str().and_then(present).map(str::to_string)).take(MOST_URLS).collect()
188}
189
190fn item_into(item: &Value, tag: &str, sink: &mut Sink) {
191 let data = item.get("data").unwrap_or(&NULL);
192 let meta = data.get("metadata").unwrap_or(&NULL);
193 let content = data.get("content").unwrap_or(&NULL);
194 let name = text_of(meta, "name");
195 let note = text(meta, "note");
196 let label = if name.is_empty() { "Proton Pass item" } else { name };
197 if item.get("state").and_then(Value::as_u64) == Some(2) {
198 sink.skip(label, "it is in the trash");
199 return;
200 }
201 let extra = extra_lines(data.get("extraFields"));
202 match text(data, "type") {
203 "login" => login_into(sink, label, content, note, &extra, tag),
204 "alias" => {
205 let mut t = String::new();
206 add_line(&mut t, "alias", text(item, "aliasEmail"));
207 sink.note(label, &join(&[&t, note, &extra]), tag);
208 }
209 "note" => sink.note(label, &join(&[note, &extra]), tag),
210 "creditCard" => card_into(sink, label, content, note, &extra, tag),
211 "identity" => identity_into(sink, label, content, note, &extra, tag),
212 "sshKey" => {
213 let mut t = String::new();
214 for (name, key) in [("private key", "privateKey"), ("public key", "publicKey"), ("fingerprint", "fingerprint")] {
215 add_line(&mut t, name, text(content, key));
216 }
217 sink.note(label, &join(&[&t, note, §ion_lines(content.get("sections")), &extra]), tag);
218 }
219 "wifi" => {
220 let security = match content.get("security").and_then(Value::as_u64) {
221 Some(1) => "WPA",
222 Some(2) => "WPA2",
223 Some(3) => "WPA3",
224 Some(4) => "WEP",
225 _ => "",
226 };
227 let mut t = String::new();
228 add_line(&mut t, "SSID", text(content, "ssid"));
229 add_line(&mut t, "password", text(content, "password"));
230 add_line(&mut t, "security", security);
231 sink.note(label, &join(&[&t, note, §ion_lines(content.get("sections")), &extra]), tag);
232 }
233 "custom" => sink.note(label, &join(&[note, §ion_lines(content.get("sections")), &extra]), tag),
234 _ => {
235 let mut t = String::new();
237 for (key, value) in content.as_object().into_iter().flatten() {
238 match value {
239 Value::String(s) => add_line(&mut t, key, s),
240 Value::Number(n) => add_line(&mut t, key, &n.to_string()),
241 _ => {}
242 }
243 }
244 sink.note(label, &join(&[&t, note, §ion_lines(content.get("sections")), &extra]), tag);
245 }
246 }
247}
248
249fn login_into(sink: &mut Sink, label: &str, content: &Value, note: &str, extra: &str, tag: &str) {
250 let (user, email) = (text_of(content, "itemUsername"), text_of(content, "itemEmail"));
251 let username = if user.is_empty() { email } else { user };
253 let urls = login_urls(content);
254 let mut secret = String::new();
255 add_line(&mut secret, "", note);
256 if !user.is_empty() && !email.is_empty() && user != email {
257 add_line(&mut secret, "email", email);
258 }
259 for url in urls.iter().skip(1) {
260 add_line(&mut secret, "url", url);
261 }
262 add_line(&mut secret, "", extra);
263 let site = urls.first().map(String::as_str).unwrap_or("");
264 let label_for = if label == "Proton Pass item" { label_of("", site, username) } else { label.to_string() };
265 sink.login(&label_for, username, text(content, "password"), site, text(content, "totpUri"), &secret, tag);
266 let passkeys = content.get("passkeys").and_then(Value::as_array).map_or(0, Vec::len);
267 if passkeys > 0 {
268 sink.skip(&format!("{label_for} (passkey)"), "a passkey can't be imported");
269 }
270}
271
272fn card_expiry(s: &str) -> Option<String> {
274 let mut parts = s.trim().split('-');
275 let year = parts.next()?;
276 month_year(parts.next()?, year)
277}
278
279fn card_into(sink: &mut Sink, label: &str, content: &Value, note: &str, extra: &str, tag: &str) {
280 let mut secret = String::new();
281 add_line(&mut secret, "", note);
282 add_line(&mut secret, "PIN", text(content, "pin"));
283 add_line(&mut secret, "", extra);
284 sink.card(label, text(content, "number"), card_expiry(text(content, "expirationDate")), text(content, "verificationNumber"), text(content, "cardholderName"), &secret, tag);
285}
286
287const ID_NUMBERS: [(&str, &str, &str); 3] =
289 [("socialSecurityNumber", "ssn", "Social Security number"), ("passportNumber", "passport", "passport"), ("licenseNumber", "drivers-licence", "driver's licence")];
290
291fn identity_into(sink: &mut Sink, label: &str, content: &Value, note: &str, extra: &str, tag: &str) {
292 let owner = match present(text(content, "fullName")) {
293 Some(n) => n.to_string(),
294 None => [text(content, "firstName"), text(content, "middleName"), text(content, "lastName")].iter().filter_map(|s| present(s)).collect::<Vec<_>>().join(" "),
295 };
296 for (key, kind, what) in ID_NUMBERS {
297 if present(text(content, key)).is_some() {
298 sink.id(kind, &format!("{label} ({what})"), text(content, key), &owner, "", "", tag);
299 }
300 }
301 let mut t = String::new();
303 let mut extras = String::new();
304 for (key, value) in content.as_object().into_iter().flatten() {
305 if ID_NUMBERS.iter().any(|(k, _, _)| k == key) {
306 continue;
307 }
308 match (key.as_str(), value) {
309 ("extraSections", sections) => add_line(&mut extras, "", §ion_lines(Some(sections))),
310 (k, fields) if k.starts_with("extra") => add_line(&mut extras, "", &extra_lines(Some(fields))),
311 (k, Value::String(s)) => add_line(&mut t, k, s),
312 (k, Value::Number(n)) => add_line(&mut t, k, &n.to_string()),
313 _ => {}
314 }
315 }
316 let text = join(&[&t, note, &extras, extra]);
317 if !text.is_empty() {
318 sink.note(label, &text, tag);
319 }
320}
321
322pub(super) fn csv_looks_like(names: &[String]) -> bool {
323 let has = |n: &str| names.iter().any(|x| x == n);
324 has("name") && has("password") && has("note") && has("totp") && has("type") && has("vault")
325}
326
327pub(super) fn read_csv(input: &str) -> Result<Imported, ReadError> {
328 let t = parse_csv(input, true)?;
329 let mut sink = Sink::default();
330 for row in &t.rows {
331 let c = |name: &str| t.get(row, name);
332 let (name, url, vault) = (c("name"), c("url"), c("vault"));
333 let password = t.col(&["password"]).and_then(|i| row.get(i)).unwrap_or("");
334 match c("type").to_ascii_lowercase().as_str() {
335 "" | "login" => {
336 let (user, email) = (c("username"), c("email"));
338 let username = if user.is_empty() { email } else { user };
339 let urls = csv_urls(c("autofillurls"), url);
340 let mut secret = String::new();
341 add_line(&mut secret, "", c("note"));
342 if !user.is_empty() && !email.is_empty() && user != email {
343 add_line(&mut secret, "email", email);
344 }
345 for u in urls.iter().skip(1) {
346 add_line(&mut secret, "url", u);
347 }
348 let site = urls.first().map(String::as_str).unwrap_or("");
349 sink.login(&label_of(name, site, username), username, password, site, c("totp"), &secret, vault);
350 }
351 "alias" => {
352 let mut lines = String::new();
353 add_line(&mut lines, "alias", c("email"));
354 let label = if name.is_empty() { "Proton Pass alias" } else { name };
355 sink.note(label, &join(&[&lines, c("note")]), vault);
356 }
357 "creditcard" => match serde_json::from_str::<Value>(c("note")) {
358 Ok(content) => card_into(&mut sink, if name.is_empty() { "Proton Pass card" } else { name }, &content, text(&content, "note"), "", vault),
359 Err(_) => sink.note(if name.is_empty() { "Proton Pass card" } else { name }, c("note"), vault),
360 },
361 "identity" => match serde_json::from_str::<Value>(c("note")) {
362 Ok(content) => identity_into(&mut sink, if name.is_empty() { "Proton Pass identity" } else { name }, &content, text(&content, "note"), "", vault),
363 Err(_) => sink.note(if name.is_empty() { "Proton Pass identity" } else { name }, c("note"), vault),
364 },
365 _ => sink.note(if name.is_empty() { "Proton Pass note" } else { name }, c("note"), vault),
366 }
367 }
368 sink.done(Source::ProtonPass)
369}
370
371fn csv_urls(structured: &str, plain: &str) -> Vec<String> {
373 if let Ok(Value::Array(list)) = serde_json::from_str::<Value>(structured) {
374 let urls: Vec<String> = list.iter().filter_map(|u| present(text(u, "url")).map(str::to_string)).take(MOST_URLS).collect();
375 if !urls.is_empty() {
376 return urls;
377 }
378 }
379 plain.split(", ").filter_map(|u| present(u).map(str::to_string)).take(MOST_URLS).collect()
380}