agentmux_srv_core/backend/vault/import/
onepux.rs1use std::io::Read;
13
14use std::collections::HashSet;
15
16use serde_json::Value;
17
18use super::{Imported, Incoming, ReadError, Source, MAX_ITEMS};
19
20const MAX_DATA_BYTES: u64 = 128 * 1024 * 1024;
23const MOST_TAGS: usize = 40;
25const MOST_URLS: usize = 50;
26const MAX_ZIP_ENTRIES: usize = 100_000;
28
29pub fn looks_like(bytes: &[u8]) -> bool {
30 zip::ZipArchive::new(std::io::Cursor::new(bytes)).is_ok_and(|z| z.file_names().any(|n| n == "export.data"))
31}
32
33pub fn read(bytes: &[u8]) -> Result<Imported, ReadError> {
34 let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|_| ReadError::from("this zip file is damaged or isn't one"))?;
35 if archive.len() > MAX_ZIP_ENTRIES {
36 return Err("this zip has more files than a 1Password export does".into());
37 }
38 let mut data = Vec::new();
39 {
40 let file = archive.by_name("export.data").map_err(|_| ReadError::from("this zip isn't a 1Password export: it has no export.data"))?;
41 file.take(MAX_DATA_BYTES + 1).read_to_end(&mut data).map_err(|_| ReadError::from("couldn't read export.data from the zip"))?;
42 }
43 if data.len() as u64 > MAX_DATA_BYTES {
44 return Err("this export's data is larger than the Vault imports".into());
45 }
46 let root: Value = serde_json::from_slice(&data).map_err(|_| ReadError::from("export.data isn't the JSON a 1Password export holds"))?;
47 drop(data);
48 let mut entries = Vec::new();
49 let mut skipped = Vec::new();
50 let mut count = 0usize;
51 for account in root.get("accounts").and_then(Value::as_array).into_iter().flatten() {
52 for vault in account.get("vaults").and_then(Value::as_array).into_iter().flatten() {
53 let tag = vault.pointer("/attrs/name").and_then(Value::as_str).unwrap_or("");
54 for item in vault.get("items").and_then(Value::as_array).into_iter().flatten() {
55 count += 1;
56 if count > MAX_ITEMS {
57 return Err(format!("this export has more than {MAX_ITEMS} items, more than the Vault imports").into());
58 }
59 item_into(item, tag, &mut entries, &mut skipped);
60 }
61 }
62 }
63 if count == 0 {
64 return Err("this 1Password export has no items".into());
65 }
66 Ok(Imported { source: Source::OnePassword, entries, skipped, plaintext: true })
67}
68
69struct Field {
71 id: String,
72 title: String,
73 value: String,
74 kind: String,
76}
77
78fn text_of(kind: &str, v: &Value) -> Option<String> {
79 let s = match v {
80 Value::String(s) => s.clone(),
81 Value::Number(n) if kind == "monthYear" => {
82 let n = n.as_i64()?;
84 format!("{:02}/{}", n % 100, n / 100)
85 }
86 Value::Number(n) => n.to_string(),
87 Value::Object(_) | Value::Array(_) => {
88 let mut leaves: Vec<(String, String)> = Vec::new();
91 collect_leaves(v, "", 0, &mut leaves);
92 match leaves.len() {
93 0 => return None,
94 1 => leaves.remove(0).1,
95 _ => leaves.into_iter().map(|(k, t)| format!("{k}: {t}")).collect::<Vec<_>>().join("\n"),
96 }
97 }
98 _ => return None,
99 };
100 let s = s.trim().to_string();
101 (!s.is_empty()).then_some(s)
102}
103
104const MAX_LEAVES: usize = 200;
106const MAX_DEPTH: usize = 8;
107
108fn collect_leaves(v: &Value, name: &str, depth: usize, out: &mut Vec<(String, String)>) {
109 if depth > MAX_DEPTH || out.len() >= MAX_LEAVES {
110 return;
111 }
112 match v {
113 Value::String(s) if !s.trim().is_empty() => out.push((name.to_string(), s.clone())),
114 Value::Number(n) => out.push((name.to_string(), n.to_string())),
115 Value::Object(o) => {
116 for (k, x) in o {
117 let path = if name.is_empty() { k.clone() } else { format!("{name}.{k}") };
118 collect_leaves(x, &path, depth + 1, out);
119 }
120 }
121 Value::Array(a) => {
122 for x in a {
123 collect_leaves(x, name, depth + 1, out);
124 }
125 }
126 _ => {}
127 }
128}
129
130fn fields_of(details: &Value) -> Vec<Field> {
131 let mut out = Vec::new();
132 for section in details.get("sections").and_then(Value::as_array).into_iter().flatten() {
133 for f in section.get("fields").and_then(Value::as_array).into_iter().flatten() {
134 let Some(value) = f.get("value").and_then(Value::as_object) else { continue };
135 let Some((kind, inner)) = value.iter().next() else { continue };
137 let Some(text) = text_of(kind, inner) else { continue };
138 out.push(Field {
139 id: f.get("id").and_then(Value::as_str).unwrap_or("").to_string(),
140 title: f.get("title").and_then(Value::as_str).unwrap_or("").to_string(),
141 value: text,
142 kind: kind.clone(),
143 });
144 }
145 }
146 out
147}
148
149fn has_attachment(details: &Value) -> bool {
152 details.get("documentAttributes").is_some_and(|d| !d.is_null())
153 || details
154 .get("sections")
155 .and_then(Value::as_array)
156 .into_iter()
157 .flatten()
158 .flat_map(|s| s.get("fields").and_then(Value::as_array).into_iter().flatten())
159 .any(|f| f.pointer("/value/file").is_some())
160}
161
162fn find<'a>(fields: &'a [Field], ids: &[&str]) -> Option<&'a Field> {
163 fields.iter().find(|f| ids.iter().any(|i| f.id.eq_ignore_ascii_case(i)))
164}
165
166fn main_secret(fields: &[Field], ids: &[&str]) -> Option<String> {
169 find(fields, ids).map(|f| f.value.clone())
170}
171
172fn item_into(item: &Value, tag: &str, entries: &mut Vec<Incoming>, skipped: &mut Vec<(String, String)>) {
173 let overview = item.get("overview").cloned().unwrap_or(Value::Null);
174 let details = item.get("details").cloned().unwrap_or(Value::Null);
175 let title = overview.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()).unwrap_or("(unnamed)").to_string();
176 if item.get("trashed").and_then(Value::as_bool) == Some(true) {
177 skipped.push((title, "it is in 1Password's trash".to_string()));
178 return;
179 }
180 let fields = fields_of(&details);
181 let notes = details.get("notesPlain").and_then(Value::as_str).map(str::trim).unwrap_or("").to_string();
182 let site = overview
183 .get("url")
184 .and_then(Value::as_str)
185 .filter(|u| !u.is_empty())
186 .or_else(|| overview.pointer("/urls/0/url").and_then(Value::as_str))
187 .unwrap_or("")
188 .to_string();
189 let mut made: Vec<Incoming> = Vec::new();
190 let mut used: HashSet<usize> = HashSet::new();
192 let mark = |used: &mut HashSet<usize>, f: &Field| {
193 if let Some(i) = fields.iter().position(|x| std::ptr::eq(x, f)) {
194 used.insert(i);
195 }
196 };
197 match item.get("categoryUuid").and_then(Value::as_str).unwrap_or("") {
198 "001" | "005" => {
199 let login = |designation: &str| -> Option<String> {
200 details
201 .get("loginFields")
202 .and_then(Value::as_array)?
203 .iter()
204 .find(|f| f.get("designation").and_then(Value::as_str) == Some(designation))
205 .and_then(|f| f.get("value").and_then(Value::as_str))
206 .map(|v| if designation == "password" { v } else { v.trim() })
208 .filter(|v| !v.is_empty())
209 .map(str::to_string)
210 };
211 let password = login("password").or_else(|| details.get("password").and_then(Value::as_str).filter(|p| !p.is_empty()).map(str::to_string));
213 match password {
214 Some(pw) => {
215 let mut e = Incoming::new("login", &title).part("password", &pw).field("site", &site).field("username", &login("username").unwrap_or_default());
216 if let Some(t) = fields.iter().find(|f| f.kind == "totp") {
217 e = e.part("totp", &t.value);
218 mark(&mut used, t);
219 }
220 made.push(e);
221 }
222 None => {}
224 }
225 }
226 "002" => match fields.iter().find(|f| f.kind == "creditCardNumber").or_else(|| find(&fields, &["ccnum"])) {
227 Some(number) => {
228 mark(&mut used, number);
229 let mut e = Incoming::new("card", &title).part("number", &number.value);
230 for (part, ids, kind) in [("expiry", &["expiry", "validUntil"][..], "monthYear"), ("cvc", &["cvv"][..], ""), ("name", &["cardholder"][..], "")] {
231 let hit = find(&fields, ids).or_else(|| if kind.is_empty() { None } else { fields.iter().find(|f| f.kind == kind) });
232 if let Some(f) = hit {
233 e = e.part(part, &f.value);
234 mark(&mut used, f);
235 }
236 }
237 made.push(e);
238 }
239 None => {}
240 },
241 "101" => {
242 if let Some(account) = find(&fields, &["accountNo", "accountNumber", "iban"]) {
243 mark(&mut used, account);
244 let mut e = Incoming::new("bank-account", &title).part("account", &account.value);
245 if let Some(r) = find(&fields, &["routingNo", "routing"]) {
246 e = e.part("routing", &r.value);
247 mark(&mut used, r);
248 }
249 if let Some(b) = find(&fields, &["bankName"]) {
250 e = e.field("bank", &b.value);
251 mark(&mut used, b);
252 }
253 made.push(e);
254 }
255 }
256 kind @ ("108" | "106" | "103") => {
257 let (name, ids): (&str, &[&str]) = match kind {
258 "108" => ("ssn", &["number", "ssn"]),
259 "106" => ("passport", &["number", "passportNumber"]),
260 _ => ("drivers-licence", &["number", "licenseNumber"]),
261 };
262 if let Some(v) = main_secret(&fields, ids) {
263 if let Some(f) = fields.iter().find(|f| f.value == v) {
264 mark(&mut used, f);
265 }
266 let mut e = Incoming::new(name, &title).part("value", &v);
267 if let Some(o) = find(&fields, &["fullname", "name", "owner"]) {
268 e = e.field("owner", &o.value);
269 mark(&mut used, o);
270 }
271 made.push(e);
272 }
273 }
274 "112" => {
275 if let Some(v) = main_secret(&fields, &["credential"]) {
276 if let Some(f) = fields.iter().find(|f| f.value == v) {
277 mark(&mut used, f);
278 }
279 made.push(Incoming::new("api-key", &title).part("value", &v).field("service", &site));
280 }
281 }
282 _ => {}
283 }
284 let mut rest = String::new();
287 let mut line = |rest: &mut String, text: String| {
288 if !rest.is_empty() {
289 rest.push('\n');
290 }
291 rest.push_str(&text);
292 };
293 if !notes.is_empty() {
294 line(&mut rest, notes.clone());
295 }
296 let login_made = made.iter().any(|m| m.kind == "login");
298 for f in details.get("loginFields").and_then(Value::as_array).into_iter().flatten() {
299 let value = f.get("value").and_then(Value::as_str).map(str::trim).unwrap_or("");
300 let designation = f.get("designation").and_then(Value::as_str).unwrap_or("");
301 if value.is_empty() || (login_made && (designation == "username" || designation == "password")) {
302 continue;
303 }
304 let name = [f.get("name"), f.get("id")].into_iter().flatten().filter_map(Value::as_str).find(|n| !n.is_empty()).unwrap_or(designation);
305 line(&mut rest, format!("{name}: {value}"));
306 }
307 let site_taken = made.iter().any(|m| m.kind == "login" || m.kind == "api-key");
308 let mut seen: HashSet<&str> = HashSet::new();
310 let mut urls: Vec<&str> = Vec::new();
311 let extra = overview.get("urls").and_then(Value::as_array).into_iter().flatten().filter_map(|u| u.get("url").and_then(Value::as_str));
312 let mut cut = false;
313 for u in std::iter::once(site.as_str()).chain(extra) {
314 if u.is_empty() || !seen.insert(u) {
315 continue;
316 }
317 if urls.len() >= MOST_URLS {
318 cut = true;
319 break;
320 }
321 urls.push(u);
322 }
323 for (i, u) in urls.iter().enumerate() {
324 if i == 0 && site_taken && *u == site {
326 continue;
327 }
328 line(&mut rest, format!("url: {u}"));
329 }
330 if cut {
331 skipped.push((format!("{title} (addresses)"), format!("it has more than {MOST_URLS} addresses: the rest weren't kept")));
332 }
333 for (i, f) in fields.iter().enumerate() {
334 if used.contains(&i) {
335 continue;
336 }
337 if !rest.is_empty() {
338 rest.push('\n');
339 }
340 let name = if f.title.is_empty() { &f.id } else { &f.title };
341 rest.push_str(&format!("{name}: {}", f.value));
342 }
343 if !rest.is_empty() {
344 let name = if made.is_empty() { title.clone() } else { format!("{title} (notes)") };
345 made.push(Incoming::new("note", &name).part("text", &rest));
346 }
347 if has_attachment(&details) {
348 skipped.push((format!("{title} (attached file)"), "the Vault keeps text, not files: the file isn't imported".to_string()));
349 if made.is_empty() {
350 return;
351 }
352 }
353 if made.is_empty() {
354 let why = if matches!(item.get("categoryUuid").and_then(Value::as_str), Some("001" | "005")) { "it has no password" } else { "it holds nothing the Vault can keep" };
355 skipped.push((title, why.to_string()));
356 return;
357 }
358 let mut seen_tags: HashSet<&str> = HashSet::new();
361 let mut own: Vec<&str> = Vec::new();
362 let mut over = false;
363 for t in overview.get("tags").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::trim).filter(|t| !t.is_empty()) {
364 if !seen_tags.insert(t) {
365 continue;
366 }
367 if own.len() >= MOST_TAGS {
368 over = true;
369 break;
370 }
371 own.push(t);
372 }
373 if over {
374 skipped.push((format!("{title} (tags)"), format!("it has more than {MOST_TAGS} tags: the rest weren't kept")));
375 }
376 entries.extend(made.into_iter().map(|m| own.iter().fold(m.tag(tag), |m, t| m.tag(t))));
377}
378
379#[cfg(test)]
380#[path = "onepux_tests.rs"]
381mod tests;