1use crate::totp::{self, Params, Stored};
36use base64::Engine;
37use serde::{Deserialize, Serialize};
38use serde_json::Value;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Format {
44 OtpauthList,
47 Aegis,
49 TwoFas,
51 AndOtp,
53 Bitwarden,
55 GoogleMigration,
57}
58
59impl Format {
60 pub fn as_str(self) -> &'static str {
62 match self {
63 Format::OtpauthList => "otpauth",
64 Format::Aegis => "aegis",
65 Format::TwoFas => "2fas",
66 Format::AndOtp => "andotp",
67 Format::Bitwarden => "bitwarden",
68 Format::GoogleMigration => "google",
69 }
70 }
71
72 pub fn parse(raw: &str) -> Option<Self> {
80 match raw
81 .trim()
82 .to_ascii_lowercase()
83 .replace(['-', '_'], "")
84 .as_str()
85 {
86 "otpauth" | "uri" | "uris" | "txt" | "text" | "ente" | "keepassxc" | "raivo" => {
87 Some(Format::OtpauthList)
88 }
89 "aegis" => Some(Format::Aegis),
90 "2fas" | "twofas" => Some(Format::TwoFas),
91 "andotp" | "freeotp" | "freeotpplus" => Some(Format::AndOtp),
92 "bitwarden" => Some(Format::Bitwarden),
93 "google" | "googleauthenticator" | "gauth" | "migration" => {
94 Some(Format::GoogleMigration)
95 }
96 _ => None,
97 }
98 }
99
100 pub const EXPORTABLE: [Format; 3] = [Format::OtpauthList, Format::Aegis, Format::TwoFas];
108
109 pub fn is_exportable(self) -> bool {
111 Format::EXPORTABLE.contains(&self)
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122pub struct Imported {
123 pub issuer: Option<String>,
124 pub account: Option<String>,
125 #[serde(flatten)]
126 pub stored: Stored,
127 pub note: Option<String>,
129}
130
131impl Imported {
132 pub fn suggested_provider(&self) -> String {
138 self.issuer
139 .as_deref()
140 .map(str::trim)
141 .filter(|s| !s.is_empty())
142 .or_else(|| {
143 self.account
144 .as_deref()
145 .map(str::trim)
146 .filter(|s| !s.is_empty())
147 })
148 .unwrap_or("Unnamed")
149 .to_string()
150 }
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
155pub struct ParseReport {
156 pub format: Format,
157 pub items: Vec<Imported>,
158 pub skipped: Vec<Skipped>,
163}
164
165#[derive(Debug, Clone, Serialize, Deserialize)]
167pub struct Skipped {
168 pub name: String,
170 pub reason: String,
171}
172
173pub fn detect(text: &str) -> Result<Format, String> {
181 let trimmed = text.trim_start_matches('\u{feff}').trim();
182 if trimmed.is_empty() {
183 return Err("the file is empty".into());
184 }
185
186 if trimmed.len() >= 18 && trimmed[..18].eq_ignore_ascii_case("otpauth-migration:") {
187 return Ok(Format::GoogleMigration);
188 }
189 if trimmed.len() >= 8 && trimmed[..8].eq_ignore_ascii_case("otpauth:") {
190 return Ok(Format::OtpauthList);
191 }
192
193 if let Ok(v) = serde_json::from_str::<Value>(trimmed) {
194 if v.get("kdfParams").is_some()
198 && v.get("encryptedData").is_some()
199 && v.get("encryptionNonce").is_some()
200 {
201 return Err(encrypted_msg(
202 "Ente Auth",
203 "Decrypt it with the Ente CLI into a plain-text otpauth:// list",
204 ));
205 }
206 if v.get("db").is_some() && v.get("header").is_some() {
209 let encrypted = v
210 .pointer("/header/slots")
211 .map(|s| !s.is_null())
212 .unwrap_or(false)
213 || v.get("db").map(|d| d.is_string()).unwrap_or(false);
214 if encrypted {
215 return Err(encrypted_msg(
216 "Aegis",
217 "Export again with encryption turned off",
218 ));
219 }
220 return Ok(Format::Aegis);
221 }
222 if v.get("services").is_some() || v.get("servicesEncrypted").is_some() {
224 let encrypted = v
225 .get("servicesEncrypted")
226 .and_then(|s| s.as_str())
227 .map(|s| !s.is_empty())
228 .unwrap_or(false);
229 if encrypted {
230 return Err(encrypted_msg(
231 "2FAS",
232 "Export again without a password set on the backup",
233 ));
234 }
235 return Ok(Format::TwoFas);
236 }
237 if v.get("items").is_some() {
239 if v.get("encrypted").and_then(|e| e.as_bool()) == Some(true) {
240 return Err(encrypted_msg(
241 "Bitwarden",
242 "Export again as an unencrypted .json",
243 ));
244 }
245 return Ok(Format::Bitwarden);
246 }
247 if v.as_array()
249 .map(|a| a.iter().any(|e| e.get("secret").is_some()))
250 .unwrap_or(false)
251 {
252 return Ok(Format::AndOtp);
253 }
254 return Err(
255 "recognised the file as JSON but not as an authenticator export \
256 (expected Aegis, 2FAS, andOTP or Bitwarden)"
257 .into(),
258 );
259 }
260
261 if text.lines().any(|l| {
265 let l = l.trim();
266 l.len() >= 8 && l[..8].eq_ignore_ascii_case("otpauth:")
267 }) {
268 return Ok(Format::OtpauthList);
269 }
270
271 Err(
272 "could not tell which authenticator app wrote this file. Supported: \
273 Ente Auth and any otpauth:// list, Aegis, 2FAS, andOTP, Bitwarden, \
274 Google Authenticator"
275 .into(),
276 )
277}
278
279fn encrypted_msg(app: &str, advice: &str) -> String {
280 format!(
281 "this is an *encrypted* {app} export. UnENVerse will not try to decrypt \
282 another app's vault — {advice}, import it here, then delete the \
283 plaintext file."
284 )
285}
286
287pub fn parse(text: &str) -> Result<ParseReport, String> {
291 let format = detect(text)?;
292 parse_as(text, format)
293}
294
295pub fn parse_as(text: &str, format: Format) -> Result<ParseReport, String> {
297 let text = text.trim_start_matches('\u{feff}');
298 if let Err(e) = detect(text) {
302 if e.contains("*encrypted*") {
303 return Err(e);
304 }
305 }
306 let (items, skipped) = match format {
307 Format::OtpauthList => parse_uri_list(text),
308 Format::Aegis => parse_aegis(text)?,
309 Format::TwoFas => parse_2fas(text)?,
310 Format::AndOtp => parse_andotp(text)?,
311 Format::Bitwarden => parse_bitwarden(text)?,
312 Format::GoogleMigration => parse_google(text)?,
313 };
314 Ok(ParseReport {
315 format,
316 items,
317 skipped,
318 })
319}
320
321fn parse_uri_list(text: &str) -> (Vec<Imported>, Vec<Skipped>) {
329 let mut items = Vec::new();
330 let mut skipped = Vec::new();
331 for (n, raw) in text.lines().enumerate() {
332 let line = raw.trim();
333 if line.is_empty() || line.starts_with('#') || line.starts_with("//") {
334 continue;
335 }
336 match totp::parse_otpauth(line) {
337 Ok(stored) => items.push(Imported {
338 issuer: stored.issuer.clone(),
339 account: stored.account.clone(),
340 stored,
341 note: None,
342 }),
343 Err(e) => skipped.push(Skipped {
344 name: format!("line {}", n + 1),
347 reason: e,
348 }),
349 }
350 }
351 (items, skipped)
352}
353
354fn stored_from(
357 secret: &str,
358 kind: Option<&str>,
359 algo: Option<&str>,
360 digits: Option<u64>,
361 period: Option<u64>,
362 counter: Option<u64>,
363) -> Result<Stored, String> {
364 let params = Params::from_fields(kind, algo, digits, period, counter);
368 let mut stored = totp::parse_seed(secret)?;
371 stored.params = params;
372 Ok(stored)
373}
374
375fn nonempty(v: Option<&str>) -> Option<String> {
376 v.map(str::trim)
377 .filter(|s| !s.is_empty())
378 .map(str::to_string)
379}
380
381fn parse_aegis(text: &str) -> Result<(Vec<Imported>, Vec<Skipped>), String> {
382 let v: Value = serde_json::from_str(text).map_err(|e| format!("not valid JSON: {e}"))?;
383 let entries = v
384 .pointer("/db/entries")
385 .and_then(|e| e.as_array())
386 .ok_or("this Aegis file has no db.entries array")?;
387 let mut items = Vec::new();
388 let mut skipped = Vec::new();
389 for e in entries {
390 let name = nonempty(e.get("name").and_then(|x| x.as_str()));
391 let issuer = nonempty(e.get("issuer").and_then(|x| x.as_str()));
392 let label = issuer
393 .clone()
394 .or_else(|| name.clone())
395 .unwrap_or_else(|| "unnamed".into());
396 let kind = e.get("type").and_then(|x| x.as_str()).unwrap_or("totp");
400 let secret = e
401 .pointer("/info/secret")
402 .and_then(|x| x.as_str())
403 .unwrap_or("");
404 match stored_from(
405 secret,
406 Some(kind),
407 e.pointer("/info/algo").and_then(|x| x.as_str()),
408 e.pointer("/info/digits").and_then(|x| x.as_u64()),
409 e.pointer("/info/period").and_then(|x| x.as_u64()),
410 e.pointer("/info/counter").and_then(|x| x.as_u64()),
411 ) {
412 Ok(stored) => items.push(Imported {
413 issuer,
414 account: name,
415 stored,
416 note: nonempty(e.get("note").and_then(|x| x.as_str())),
417 }),
418 Err(reason) => skipped.push(Skipped {
419 name: label,
420 reason,
421 }),
422 }
423 }
424 Ok((items, skipped))
425}
426
427fn parse_2fas(text: &str) -> Result<(Vec<Imported>, Vec<Skipped>), String> {
428 let v: Value = serde_json::from_str(text).map_err(|e| format!("not valid JSON: {e}"))?;
429 let services = v
430 .get("services")
431 .and_then(|s| s.as_array())
432 .ok_or("this 2FAS file has no services array")?;
433 let mut items = Vec::new();
434 let mut skipped = Vec::new();
435 for s in services {
436 let issuer = nonempty(s.pointer("/otp/issuer").and_then(|x| x.as_str()))
440 .or_else(|| nonempty(s.get("name").and_then(|x| x.as_str())));
441 let account = nonempty(s.pointer("/otp/account").and_then(|x| x.as_str()))
442 .or_else(|| nonempty(s.pointer("/otp/label").and_then(|x| x.as_str())));
443 let label = issuer
444 .clone()
445 .or_else(|| account.clone())
446 .unwrap_or_else(|| "unnamed".into());
447 let kind = s
448 .pointer("/otp/tokenType")
449 .and_then(|x| x.as_str())
450 .unwrap_or("TOTP");
451 match stored_from(
452 s.get("secret").and_then(|x| x.as_str()).unwrap_or(""),
453 Some(kind),
454 s.pointer("/otp/algorithm").and_then(|x| x.as_str()),
455 s.pointer("/otp/digits").and_then(|x| x.as_u64()),
456 s.pointer("/otp/period").and_then(|x| x.as_u64()),
457 s.pointer("/otp/counter").and_then(|x| x.as_u64()),
458 ) {
459 Ok(stored) => items.push(Imported {
460 issuer,
461 account,
462 stored,
463 note: None,
464 }),
465 Err(reason) => skipped.push(Skipped {
466 name: label,
467 reason,
468 }),
469 }
470 }
471 Ok((items, skipped))
472}
473
474fn parse_andotp(text: &str) -> Result<(Vec<Imported>, Vec<Skipped>), String> {
475 let v: Value = serde_json::from_str(text).map_err(|e| format!("not valid JSON: {e}"))?;
476 let arr = v
477 .as_array()
478 .ok_or("an andOTP export is a JSON array of entries")?;
479 let mut items = Vec::new();
480 let mut skipped = Vec::new();
481 for e in arr {
482 let issuer = nonempty(e.get("issuer").and_then(|x| x.as_str()));
483 let account = nonempty(e.get("label").and_then(|x| x.as_str()));
484 let label = issuer
485 .clone()
486 .or_else(|| account.clone())
487 .unwrap_or_else(|| "unnamed".into());
488 let kind = e.get("type").and_then(|x| x.as_str()).unwrap_or("TOTP");
489 match stored_from(
490 e.get("secret").and_then(|x| x.as_str()).unwrap_or(""),
491 Some(kind),
492 e.get("algorithm").and_then(|x| x.as_str()),
493 e.get("digits").and_then(|x| x.as_u64()),
494 e.get("period").and_then(|x| x.as_u64()),
495 e.get("counter").and_then(|x| x.as_u64()),
496 ) {
497 Ok(stored) => items.push(Imported {
498 issuer,
499 account,
500 stored,
501 note: e
502 .get("tags")
503 .and_then(|t| t.as_array())
504 .map(|t| {
505 t.iter()
506 .filter_map(|x| x.as_str())
507 .collect::<Vec<_>>()
508 .join(", ")
509 })
510 .filter(|s| !s.is_empty()),
511 }),
512 Err(reason) => skipped.push(Skipped {
513 name: label,
514 reason,
515 }),
516 }
517 }
518 Ok((items, skipped))
519}
520
521fn parse_bitwarden(text: &str) -> Result<(Vec<Imported>, Vec<Skipped>), String> {
527 let v: Value = serde_json::from_str(text).map_err(|e| format!("not valid JSON: {e}"))?;
528 let items_json = v
529 .get("items")
530 .and_then(|i| i.as_array())
531 .ok_or("this Bitwarden file has no items array")?;
532 let mut items = Vec::new();
533 let mut skipped = Vec::new();
534 for it in items_json {
535 let raw = it
536 .pointer("/login/totp")
537 .and_then(|x| x.as_str())
538 .unwrap_or("");
539 if raw.trim().is_empty() {
540 continue;
543 }
544 let name = nonempty(it.get("name").and_then(|x| x.as_str()));
545 let account = nonempty(it.pointer("/login/username").and_then(|x| x.as_str()));
546 let label = name.clone().unwrap_or_else(|| "unnamed".into());
547 match totp::parse_seed(raw) {
548 Ok(stored) => items.push(Imported {
549 issuer: name.or_else(|| stored.issuer.clone()),
552 account: account.or_else(|| stored.account.clone()),
553 stored,
554 note: None,
555 }),
556 Err(reason) => skipped.push(Skipped {
557 name: label,
558 reason,
559 }),
560 }
561 }
562 Ok((items, skipped))
563}
564
565fn parse_google(text: &str) -> Result<(Vec<Imported>, Vec<Skipped>), String> {
579 let mut items = Vec::new();
580 let mut skipped = Vec::new();
581 let mut any = false;
582 for (n, raw) in text.lines().enumerate() {
583 let line = raw.trim();
584 if line.is_empty() || line.starts_with('#') {
585 continue;
586 }
587 if line.len() < 18 || !line[..18].eq_ignore_ascii_case("otpauth-migration:") {
588 skipped.push(Skipped {
589 name: format!("line {}", n + 1),
590 reason: "not an otpauth-migration:// URI".into(),
591 });
592 continue;
593 }
594 any = true;
595 let data = line
596 .split_once("data=")
597 .map(|(_, d)| d.split('&').next().unwrap_or(d))
598 .ok_or("the migration URI carries no data= parameter")?;
599 let decoded = decode_migration_b64(data)?;
600 let (mut got, mut bad) = decode_migration_payload(&decoded)?;
601 items.append(&mut got);
602 skipped.append(&mut bad);
603 }
604 if !any {
605 return Err("no otpauth-migration:// URI in this file".into());
606 }
607 Ok((items, skipped))
608}
609
610fn decode_migration_b64(data: &str) -> Result<Vec<u8>, String> {
617 let pct = percent_decode(data);
618 let cleaned: String = pct.chars().filter(|c| !c.is_whitespace()).collect();
619 use base64::engine::general_purpose as b64;
620 [
621 b64::STANDARD.decode(&cleaned),
622 b64::STANDARD_NO_PAD.decode(&cleaned),
623 b64::URL_SAFE.decode(&cleaned),
624 b64::URL_SAFE_NO_PAD.decode(&cleaned),
625 ]
626 .into_iter()
627 .flatten()
628 .next()
629 .ok_or_else(|| "the migration payload is not valid base64".to_string())
630}
631
632fn percent_decode(s: &str) -> String {
633 let bytes = s.as_bytes();
634 let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
635 let mut i = 0;
636 while i < bytes.len() {
637 if bytes[i] == b'%' && i + 2 < bytes.len() {
638 if let Some(b) = std::str::from_utf8(&bytes[i + 1..i + 3])
639 .ok()
640 .and_then(|h| u8::from_str_radix(h, 16).ok())
641 {
642 out.push(b);
643 i += 3;
644 continue;
645 }
646 }
647 out.push(bytes[i]);
652 i += 1;
653 }
654 String::from_utf8_lossy(&out).into_owned()
655}
656
657struct Pb<'a> {
659 b: &'a [u8],
660 i: usize,
661}
662
663impl<'a> Pb<'a> {
664 fn new(b: &'a [u8]) -> Self {
665 Pb { b, i: 0 }
666 }
667 fn done(&self) -> bool {
668 self.i >= self.b.len()
669 }
670 fn varint(&mut self) -> Result<u64, String> {
673 let mut out: u64 = 0;
674 let mut shift = 0;
675 loop {
676 if self.i >= self.b.len() {
677 return Err("truncated migration payload".into());
678 }
679 let byte = self.b[self.i];
680 self.i += 1;
681 out |= u64::from(byte & 0x7f) << shift;
682 if byte & 0x80 == 0 {
683 return Ok(out);
684 }
685 shift += 7;
686 if shift > 63 {
687 return Err("malformed varint in migration payload".into());
688 }
689 }
690 }
691 fn key(&mut self) -> Result<(u64, u8), String> {
693 let k = self.varint()?;
694 Ok((k >> 3, (k & 0x07) as u8))
695 }
696 fn bytes(&mut self) -> Result<&'a [u8], String> {
697 let len = self.varint()? as usize;
698 let end = self
699 .i
700 .checked_add(len)
701 .filter(|e| *e <= self.b.len())
702 .ok_or("truncated length-delimited field")?;
703 let out = &self.b[self.i..end];
704 self.i = end;
705 Ok(out)
706 }
707 fn skip(&mut self, wire: u8) -> Result<(), String> {
709 match wire {
710 0 => {
711 self.varint()?;
712 }
713 1 => self.i = self.i.saturating_add(8).min(self.b.len()),
714 2 => {
715 self.bytes()?;
716 }
717 5 => self.i = self.i.saturating_add(4).min(self.b.len()),
718 _ => return Err(format!("unsupported protobuf wire type {wire}")),
719 }
720 Ok(())
721 }
722}
723
724fn decode_migration_payload(bytes: &[u8]) -> Result<(Vec<Imported>, Vec<Skipped>), String> {
725 let mut items = Vec::new();
726 let mut skipped = Vec::new();
727 let mut p = Pb::new(bytes);
728 while !p.done() {
729 let (field, wire) = p.key()?;
730 if field == 1 && wire == 2 {
733 let inner = p.bytes()?;
734 match decode_otp_parameters(inner) {
735 Ok(Some(item)) => items.push(item),
736 Ok(None) => {}
737 Err(s) => skipped.push(s),
738 }
739 } else {
740 p.skip(wire)?;
741 }
742 }
743 Ok((items, skipped))
744}
745
746fn decode_otp_parameters(bytes: &[u8]) -> Result<Option<Imported>, Skipped> {
749 let mut secret_raw: Vec<u8> = Vec::new();
750 let mut name = String::new();
751 let mut issuer = String::new();
752 let mut algo = 1u64; let mut digits_enum = 1u64; let mut kind = 2u64; let mut counter = 0u64;
756
757 let mut p = Pb::new(bytes);
758 let named = |n: &str, i: &str| {
759 if !i.is_empty() {
760 i.to_string()
761 } else if !n.is_empty() {
762 n.to_string()
763 } else {
764 "unnamed".to_string()
765 }
766 };
767 while !p.done() {
768 let (field, wire) = p.key().map_err(|e| Skipped {
769 name: named(&name, &issuer),
770 reason: e,
771 })?;
772 let fail = |e: String| Skipped {
773 name: named(&name, &issuer),
774 reason: e,
775 };
776 match (field, wire) {
777 (1, 2) => secret_raw = p.bytes().map_err(fail)?.to_vec(),
778 (2, 2) => name = String::from_utf8_lossy(p.bytes().map_err(fail)?).into_owned(),
779 (3, 2) => issuer = String::from_utf8_lossy(p.bytes().map_err(fail)?).into_owned(),
780 (4, 0) => algo = p.varint().map_err(fail)?,
781 (5, 0) => digits_enum = p.varint().map_err(fail)?,
782 (6, 0) => kind = p.varint().map_err(fail)?,
783 (7, 0) => counter = p.varint().map_err(fail)?,
787 _ => p.skip(wire).map_err(fail)?,
788 }
789 }
790
791 let label = named(&name, &issuer);
792 if secret_raw.is_empty() {
793 return Err(Skipped {
794 name: label,
795 reason: "the migration entry carries no secret".into(),
796 });
797 }
798
799 let secret = totp::base32_encode(&secret_raw);
801 let params = Params {
802 algorithm: match algo {
803 2 => totp::Algorithm::Sha256,
804 3 => totp::Algorithm::Sha512,
805 _ => totp::Algorithm::Sha1,
810 },
811 digits: if digits_enum == 2 { 8 } else { 6 },
812 period: totp::STEP_SECS,
815 kind: if kind == 1 {
818 totp::Kind::Hotp
819 } else {
820 totp::Kind::Totp
821 },
822 counter: if kind == 1 { counter } else { 0 },
823 };
824 let stored = Stored {
825 secret,
826 params,
827 issuer: (!issuer.is_empty()).then(|| issuer.clone()),
828 account: (!name.is_empty()).then(|| name.clone()),
829 };
830 Ok(Some(Imported {
831 issuer: stored.issuer.clone(),
832 account: stored.account.clone(),
833 stored,
834 note: None,
835 }))
836}
837
838pub fn build(items: &[Imported], format: Format) -> Result<String, String> {
846 if !format.is_exportable() {
847 return Err(format!(
848 "'{}' can be imported but not written. Export with {} instead.",
849 format.as_str(),
850 Format::EXPORTABLE
851 .iter()
852 .map(|f| f.as_str())
853 .collect::<Vec<_>>()
854 .join(", ")
855 ));
856 }
857 Ok(match format {
858 Format::OtpauthList => build_uri_list(items),
859 Format::Aegis => build_aegis(items),
860 Format::TwoFas => build_2fas(items),
861 _ => unreachable!("is_exportable covers every arm above"),
862 })
863}
864
865fn build_uri_list(items: &[Imported]) -> String {
866 let mut out = String::new();
867 for it in items {
868 out.push_str(&it.stored.to_uri(
869 it.issuer.as_deref().unwrap_or(""),
870 it.account.as_deref().unwrap_or(""),
871 ));
872 out.push('\n');
873 }
874 out
875}
876
877fn build_aegis(items: &[Imported]) -> String {
878 let entries: Vec<Value> = items
879 .iter()
880 .map(|it| {
881 let mut info = serde_json::json!({
886 "secret": it.stored.secret,
887 "algo": it.stored.params.algorithm.as_str(),
888 "digits": it.stored.params.digits,
889 });
890 match it.stored.params.kind {
891 totp::Kind::Hotp => info["counter"] = Value::from(it.stored.params.counter),
892 totp::Kind::Totp | totp::Kind::Steam => {
893 info["period"] = Value::from(it.stored.params.period)
894 }
895 }
896 serde_json::json!({
897 "type": it.stored.params.kind.as_str(),
898 "uuid": stable_uuid(&it.stored.secret),
902 "name": it.account.clone().unwrap_or_default(),
903 "issuer": it.issuer.clone().unwrap_or_default(),
904 "note": it.note.clone().unwrap_or_default(),
905 "favorite": false,
906 "icon": Value::Null,
907 "info": info
908 })
909 })
910 .collect();
911 let doc = serde_json::json!({
914 "version": 1,
915 "header": { "slots": Value::Null, "params": Value::Null },
916 "db": { "version": 3, "entries": entries }
917 });
918 serde_json::to_string_pretty(&doc).unwrap_or_default()
919}
920
921fn build_2fas(items: &[Imported]) -> String {
922 let services: Vec<Value> = items
923 .iter()
924 .map(|it| {
925 let issuer = it.issuer.clone().unwrap_or_default();
926 let account = it.account.clone().unwrap_or_default();
927 serde_json::json!({
928 "name": if issuer.is_empty() { account.clone() } else { issuer.clone() },
929 "secret": it.stored.secret,
930 "updatedAt": 0,
931 "otp": {
932 "label": if account.is_empty() { issuer.clone() } else { account.clone() },
933 "account": account,
934 "issuer": issuer,
935 "digits": it.stored.params.digits,
936 "period": it.stored.params.period,
937 "algorithm": it.stored.params.algorithm.as_str(),
938 "tokenType": it.stored.params.kind.as_str().to_uppercase(),
941 "counter": match it.stored.params.kind {
942 totp::Kind::Hotp => Value::from(it.stored.params.counter),
943 _ => Value::Null,
944 },
945 "source": "Manual",
946 },
947 "order": { "position": 0 },
948 "icon": { "selected": "Label", "label": { "text": "", "backgroundColor": "Blue" } },
949 })
950 })
951 .collect();
952 let doc = serde_json::json!({
953 "services": services,
954 "schemaVersion": 4,
957 "appVersionCode": 0,
958 "appVersionName": "UnENVerse",
959 "appOrigin": "android",
960 "servicesEncrypted": Value::Null,
961 "reference": Value::Null,
962 });
963 serde_json::to_string_pretty(&doc).unwrap_or_default()
964}
965
966fn stable_uuid(secret: &str) -> String {
977 use sha2::{Digest, Sha256};
978 let h = Sha256::digest(format!("unenverse-aegis-uuid:{secret}").as_bytes());
979 let hex: String = h.iter().take(16).map(|b| format!("{b:02x}")).collect();
980 format!(
981 "{}-{}-{}-{}-{}",
982 &hex[0..8],
983 &hex[8..12],
984 &hex[12..16],
985 &hex[16..20],
986 &hex[20..32]
987 )
988}
989
990fn match_key(provider: &str, account: &str) -> (String, String) {
1005 (
1006 provider.trim().to_lowercase(),
1007 account.trim().to_lowercase(),
1008 )
1009}
1010
1011#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1013#[serde(tag = "action", rename_all = "snake_case")]
1014pub enum Plan {
1015 Create,
1017 Update { index: usize },
1019 Unchanged { index: usize },
1022 Conflict { index: usize },
1025}
1026
1027pub fn plan(entries: &[Value], items: &[Imported], force: bool) -> Vec<Plan> {
1035 let existing: std::collections::HashMap<(String, String), usize> = entries
1036 .iter()
1037 .enumerate()
1038 .map(|(i, e)| {
1039 (
1040 match_key(
1041 e.get("provider").and_then(|v| v.as_str()).unwrap_or(""),
1042 e.get("account_name").and_then(|v| v.as_str()).unwrap_or(""),
1043 ),
1044 i,
1045 )
1046 })
1047 .collect();
1048
1049 items
1050 .iter()
1051 .map(|item| {
1052 let key = match_key(
1053 &item.suggested_provider(),
1054 item.account.as_deref().unwrap_or(""),
1055 );
1056 let Some(&index) = existing.get(&key) else {
1057 return Plan::Create;
1058 };
1059 let current = entries[index]
1060 .get("totp_secret")
1061 .and_then(|v| v.as_str())
1062 .map(totp::normalize_b32)
1063 .unwrap_or_default();
1064 if current == item.stored.secret {
1065 Plan::Unchanged { index }
1066 } else if current.is_empty() || force {
1067 Plan::Update { index }
1068 } else {
1069 Plan::Conflict { index }
1070 }
1071 })
1072 .collect()
1073}
1074
1075pub fn write_fields(entry: &mut Value, stored: &Stored) {
1082 let defaults = Params::default();
1083 entry["totp_secret"] = Value::String(stored.secret.clone());
1084 let Some(o) = entry.as_object_mut() else {
1085 return;
1086 };
1087 if stored.params.algorithm == defaults.algorithm {
1088 o.remove("totp_algorithm");
1089 } else {
1090 o.insert(
1091 "totp_algorithm".into(),
1092 Value::String(stored.params.algorithm.as_str().into()),
1093 );
1094 }
1095 if stored.params.digits == defaults.digits {
1096 o.remove("totp_digits");
1097 } else {
1098 o.insert("totp_digits".into(), Value::from(stored.params.digits));
1099 }
1100 if stored.params.period == defaults.period {
1101 o.remove("totp_period");
1102 } else {
1103 o.insert("totp_period".into(), Value::from(stored.params.period));
1104 }
1105 if stored.params.kind == defaults.kind {
1106 o.remove("totp_kind");
1107 } else {
1108 o.insert(
1109 "totp_kind".into(),
1110 Value::String(stored.params.kind.as_str().into()),
1111 );
1112 }
1113 if stored.params.kind == totp::Kind::Hotp {
1118 o.insert("totp_counter".into(), Value::from(stored.params.counter));
1119 } else {
1120 o.remove("totp_counter");
1121 }
1122}
1123
1124pub fn new_entry(
1132 item: &Imported,
1133 id: &str,
1134 now: &str,
1135 project: Option<&str>,
1136 category: Option<&str>,
1137) -> Value {
1138 let account = item.account.clone().unwrap_or_default();
1139 let mut projects = vec![Value::String("Universal".into())];
1140 if let Some(p) = project.filter(|p| *p != "Universal") {
1141 projects.push(Value::String(p.into()));
1142 }
1143 let mut e = serde_json::json!({
1144 "id": id,
1145 "provider": item.suggested_provider(),
1146 "api_key": "",
1147 "secretType": "password",
1148 "price_type": "free",
1149 "categories": category.map(|c| vec![Value::String(c.into())]).unwrap_or_default(),
1150 "projectIds": projects,
1151 "scopes": [],
1152 "created_at": now,
1153 });
1154 if !account.is_empty() {
1155 e["account_name"] = Value::String(account.clone());
1156 e["username"] = Value::String(account);
1158 }
1159 if let Some(note) = &item.note {
1160 e["description"] = Value::String(note.clone());
1161 }
1162 write_fields(&mut e, &item.stored);
1163 e
1164}
1165
1166#[cfg(test)]
1167mod tests {
1168 use super::*;
1169
1170 const SEED: &str = "JBSWY3DPEHPK3PXP";
1172
1173 fn one(items: &[Imported]) -> &Imported {
1174 assert_eq!(items.len(), 1, "expected exactly one item: {items:?}");
1175 &items[0]
1176 }
1177
1178 fn first(items: &[Imported]) -> &Imported {
1180 assert!(!items.is_empty(), "expected at least one item");
1181 &items[0]
1182 }
1183
1184 #[test]
1187 fn every_supported_format_is_recognised_from_its_own_bytes() {
1188 let cases: [(&str, Format); 6] = [
1192 (
1193 "otpauth://totp/Acme:me?secret=JBSWY3DPEHPK3PXP",
1194 Format::OtpauthList,
1195 ),
1196 (
1197 "otpauth-migration://offline?data=CjEKCkhlbGxvIePop-8SEmpvaG5AZXhhbXBsZS5jb20aBUFjbWUgIAEoATACEAEYASAA",
1198 Format::GoogleMigration,
1199 ),
1200 (
1201 r#"{"version":1,"header":{"slots":null,"params":null},"db":{"version":3,"entries":[]}}"#,
1202 Format::Aegis,
1203 ),
1204 (r#"{"services":[],"schemaVersion":4}"#, Format::TwoFas),
1205 (r#"[{"secret":"JBSWY3DPEHPK3PXP","label":"a"}]"#, Format::AndOtp),
1206 (r#"{"encrypted":false,"items":[]}"#, Format::Bitwarden),
1207 ];
1208 for (text, want) in cases {
1209 assert_eq!(detect(text).unwrap(), want, "detecting {want:?}");
1210 }
1211 }
1212
1213 #[test]
1214 fn an_encrypted_export_is_refused_by_name_rather_than_failing_to_parse() {
1215 let aegis = r#"{"version":1,"header":{"slots":[{"type":1}],"params":{}},"db":"AAAA"}"#;
1219 let err = detect(aegis).expect_err("encrypted Aegis must be refused");
1220 assert!(err.contains("Aegis"), "{err}");
1221 assert!(err.contains("encrypt"), "{err}");
1222
1223 let twofas = r#"{"services":[],"servicesEncrypted":"deadbeef","schemaVersion":4}"#;
1224 let err = detect(twofas).expect_err("encrypted 2FAS must be refused");
1225 assert!(err.contains("2FAS"), "{err}");
1226
1227 let bw = r#"{"encrypted":true,"items":[]}"#;
1228 let err = detect(bw).expect_err("encrypted Bitwarden must be refused");
1229 assert!(err.contains("Bitwarden"), "{err}");
1230
1231 let ente = r#"{"version":1,"kdfParams":{"memLimit":4096,"opsLimit":3,"salt":"x"},"encryptedData":"x","encryptionNonce":"x"}"#;
1235 let err = detect(ente).expect_err("encrypted Ente Auth must be refused");
1236 assert!(err.contains("Ente Auth"), "{err}");
1237 assert!(err.contains("Ente CLI"), "{err}");
1238 }
1239
1240 #[test]
1241 fn detection_never_panics_on_junk() {
1242 for junk in ["", " ", "\u{feff}", "not json {", "\0\0\0", "[]", "{}"] {
1244 let _ = detect(junk);
1245 }
1246 }
1247
1248 #[test]
1251 fn an_ente_plain_export_imports_including_its_codedisplay_parameter() {
1252 let text = concat!(
1257 "otpauth://totp/Acme:me%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=Acme",
1258 "&algorithm=SHA1&digits=6&period=30",
1259 "&codeDisplay=%7B%22pinned%22%3Afalse%2C%22trashed%22%3Afalse%7D\n",
1260 "\n",
1261 "# a comment Ente does not write, but a hand-edited file might\n",
1262 "otpauth://totp/Other?secret=MZXW6YTBOI&digits=8&period=60&algorithm=SHA512\n",
1263 );
1264 let r = parse(text).unwrap();
1265 assert_eq!(r.format, Format::OtpauthList);
1266 assert_eq!(r.items.len(), 2);
1267 assert!(r.skipped.is_empty(), "{:?}", r.skipped);
1268 assert_eq!(r.items[0].stored.secret, SEED);
1269 assert_eq!(r.items[0].issuer.as_deref(), Some("Acme"));
1270 assert_eq!(r.items[0].account.as_deref(), Some("me@example.com"));
1271 assert_eq!(r.items[1].stored.params.digits, 8);
1272 assert_eq!(r.items[1].stored.params.period, 60);
1273 assert_eq!(r.items[1].stored.params.algorithm, totp::Algorithm::Sha512);
1274 }
1275
1276 #[test]
1277 fn a_bad_line_is_reported_by_line_number_and_never_by_content() {
1278 let text = "otpauth://totp/Ok?secret=JBSWY3DPEHPK3PXP\n\
1280 otpauth://totp/Bad?secret=NOTBASE32!!!\n\
1281 otpauth://hotp/Counter?secret=JBSWY3DPEHPK3PXP&counter=1\n";
1282 let r = parse(text).unwrap();
1283 assert_eq!(r.items.len(), 2);
1286 assert_eq!(r.items[1].stored.params.kind, totp::Kind::Hotp);
1287 assert_eq!(r.items[1].stored.params.counter, 1);
1288 assert_eq!(r.skipped.len(), 1);
1289 for s in &r.skipped {
1290 assert!(s.name.starts_with("line "), "{s:?}");
1291 assert!(!s.reason.contains("NOTBASE32"), "{s:?}");
1292 }
1293 }
1294
1295 #[test]
1298 fn an_aegis_vault_imports_with_its_parameters_and_note() {
1299 let text = r#"{
1300 "version": 1,
1301 "header": { "slots": null, "params": null },
1302 "db": { "version": 3, "entries": [
1303 { "type": "totp", "uuid": "x", "name": "me@example.com", "issuer": "Acme",
1304 "note": "work laptop", "favorite": false, "icon": null,
1305 "info": { "secret": "JBSWY3DPEHPK3PXP", "algo": "SHA256", "digits": 8, "period": 60 } },
1306 { "type": "hotp", "uuid": "y", "name": "counter", "issuer": "Old",
1307 "info": { "secret": "JBSWY3DPEHPK3PXP", "algo": "SHA1", "digits": 6, "counter": 3 } }
1308 ] }
1309 }"#;
1310 let r = parse(text).unwrap();
1311 assert_eq!(r.format, Format::Aegis);
1312 assert_eq!(r.items.len(), 2);
1313 let it = first(&r.items);
1314 assert_eq!(it.stored.secret, SEED);
1315 assert_eq!(it.stored.params.algorithm, totp::Algorithm::Sha256);
1316 assert_eq!(it.stored.params.digits, 8);
1317 assert_eq!(it.stored.params.period, 60);
1318 assert_eq!(it.issuer.as_deref(), Some("Acme"));
1319 assert_eq!(it.account.as_deref(), Some("me@example.com"));
1320 assert_eq!(it.note.as_deref(), Some("work laptop"));
1321 assert_eq!(r.items[1].stored.params.kind, totp::Kind::Hotp);
1324 assert_eq!(r.items[1].stored.params.counter, 3);
1325 assert!(r.skipped.is_empty(), "{:?}", r.skipped);
1326 }
1327
1328 #[test]
1329 fn an_aegis_steam_entry_keeps_steams_shape() {
1330 let text = r#"{
1335 "version": 1,
1336 "header": { "slots": null, "params": null },
1337 "db": { "version": 3, "entries": [
1338 { "type": "steam", "uuid": "s", "name": "me", "issuer": "Steam",
1339 "info": { "secret": "JBSWY3DPEHPK3PXP", "algo": "SHA1", "digits": 5, "period": 30 } }
1340 ] }
1341 }"#;
1342 let r = parse(text).unwrap();
1343 let it = one(&r.items);
1344 assert_eq!(it.stored.params.kind, totp::Kind::Steam);
1345 assert_eq!(it.stored.params.digits, totp::STEAM_DIGITS);
1346
1347 for fmt in [Format::Aegis, Format::OtpauthList] {
1349 let written = build(&r.items, fmt).expect("steam is exportable");
1350 let back = parse(&written).expect("what we wrote, we read");
1351 assert_eq!(
1352 back.items[0].stored.params.kind,
1353 totp::Kind::Steam,
1354 "{fmt:?} lost the Steam encoder"
1355 );
1356 }
1357 }
1358
1359 #[test]
1360 fn a_counter_survives_a_round_trip_through_every_writable_format() {
1361 let items = vec![Imported {
1366 issuer: Some("Acme".into()),
1367 account: Some("me".into()),
1368 stored: Stored {
1369 secret: SEED.into(),
1370 params: Params {
1371 kind: totp::Kind::Hotp,
1372 counter: 41,
1373 ..Params::default()
1374 },
1375 issuer: Some("Acme".into()),
1376 account: Some("me".into()),
1377 },
1378 note: None,
1379 }];
1380 for fmt in Format::EXPORTABLE {
1381 let written = build(&items, fmt).expect("writable");
1382 let back = parse(&written).unwrap_or_else(|e| panic!("{fmt:?}: {e}"));
1383 assert_eq!(back.items.len(), 1, "{fmt:?}");
1384 assert_eq!(
1385 back.items[0].stored.params.kind,
1386 totp::Kind::Hotp,
1387 "{fmt:?}"
1388 );
1389 assert_eq!(back.items[0].stored.params.counter, 41, "{fmt:?}");
1390 }
1391 }
1392
1393 #[test]
1394 fn a_2fas_backup_imports_from_either_place_it_keeps_the_name() {
1395 let text = r#"{
1398 "services": [
1399 { "name": "Acme", "secret": "JBSWY3DPEHPK3PXP",
1400 "otp": { "label": "me", "account": "me", "issuer": "Acme",
1401 "digits": 6, "period": 30, "algorithm": "SHA1", "tokenType": "TOTP" } },
1402 { "name": "Fallback", "secret": "MZXW6YTBOI",
1403 "otp": { "label": "lbl", "tokenType": "TOTP" } },
1404 { "name": "Counter", "secret": "JBSWY3DPEHPK3PXP",
1405 "otp": { "label": "c", "tokenType": "HOTP" } }
1406 ],
1407 "schemaVersion": 4
1408 }"#;
1409 let r = parse(text).unwrap();
1410 assert_eq!(r.format, Format::TwoFas);
1411 assert_eq!(r.items.len(), 3);
1413 assert_eq!(r.items[0].issuer.as_deref(), Some("Acme"));
1414 assert_eq!(r.items[1].issuer.as_deref(), Some("Fallback"));
1416 assert_eq!(r.items[1].account.as_deref(), Some("lbl"));
1417 assert!(r.items[1].stored.params.is_default());
1419 assert_eq!(r.items[2].stored.params.kind, totp::Kind::Hotp);
1420 assert!(r.skipped.is_empty(), "{:?}", r.skipped);
1421 }
1422
1423 #[test]
1424 fn an_andotp_export_imports_with_its_tags_as_the_note() {
1425 let text = r#"[
1426 { "secret": "JBSWY3DPEHPK3PXP", "issuer": "Acme", "label": "me",
1427 "digits": 6, "type": "TOTP", "algorithm": "SHA1", "period": 30,
1428 "tags": ["work", "critical"] }
1429 ]"#;
1430 let r = parse(text).unwrap();
1431 assert_eq!(r.format, Format::AndOtp);
1432 let it = one(&r.items);
1433 assert_eq!(it.stored.secret, SEED);
1434 assert_eq!(it.note.as_deref(), Some("work, critical"));
1435 }
1436
1437 #[test]
1438 fn a_bitwarden_export_reads_login_totp_in_both_spellings() {
1439 let text = r#"{ "encrypted": false, "items": [
1442 { "type": 1, "name": "Plain", "login": { "username": "u1", "totp": "JBSWY3DPEHPK3PXP" } },
1443 { "type": 1, "name": "Uri", "login": { "username": "u2",
1444 "totp": "otpauth://totp/Ignored:x?secret=MZXW6YTBOI&digits=8" } },
1445 { "type": 1, "name": "NoTotp", "login": { "username": "u3", "password": "p" } },
1446 { "type": 2, "name": "SecureNote" }
1447 ] }"#;
1448 let r = parse(text).unwrap();
1449 assert_eq!(r.format, Format::Bitwarden);
1450 assert_eq!(r.items.len(), 2);
1451 assert_eq!(r.items[0].stored.secret, SEED);
1452 assert_eq!(r.items[0].account.as_deref(), Some("u1"));
1453 assert_eq!(r.items[1].stored.params.digits, 8);
1454 assert_eq!(r.items[1].issuer.as_deref(), Some("Uri"));
1457 assert!(r.skipped.is_empty(), "{:?}", r.skipped);
1460 }
1461
1462 fn google_payload(
1467 secret: &[u8],
1468 name: &str,
1469 issuer: &str,
1470 algo: u8,
1471 digits: u8,
1472 kind: u8,
1473 ) -> String {
1474 fn varint(out: &mut Vec<u8>, mut v: u64) {
1475 loop {
1476 let mut b = (v & 0x7f) as u8;
1477 v >>= 7;
1478 if v != 0 {
1479 b |= 0x80;
1480 }
1481 out.push(b);
1482 if v == 0 {
1483 break;
1484 }
1485 }
1486 }
1487 fn field_bytes(out: &mut Vec<u8>, num: u64, data: &[u8]) {
1488 varint(out, (num << 3) | 2);
1489 varint(out, data.len() as u64);
1490 out.extend_from_slice(data);
1491 }
1492 fn field_varint(out: &mut Vec<u8>, num: u64, v: u64) {
1493 varint(out, num << 3);
1494 varint(out, v);
1495 }
1496
1497 let mut params = Vec::new();
1498 field_bytes(&mut params, 1, secret);
1499 field_bytes(&mut params, 2, name.as_bytes());
1500 field_bytes(&mut params, 3, issuer.as_bytes());
1501 field_varint(&mut params, 4, u64::from(algo));
1502 field_varint(&mut params, 5, u64::from(digits));
1503 field_varint(&mut params, 6, u64::from(kind));
1504
1505 let mut payload = Vec::new();
1506 field_bytes(&mut payload, 1, ¶ms);
1507 field_varint(&mut payload, 2, 1); field_varint(&mut payload, 3, 1); field_varint(&mut payload, 4, 0); let b64 = base64::engine::general_purpose::STANDARD.encode(&payload);
1512 let pct: String = b64
1513 .chars()
1514 .map(|c| match c {
1515 '+' => "%2B".to_string(),
1516 '/' => "%2F".to_string(),
1517 '=' => "%3D".to_string(),
1518 c => c.to_string(),
1519 })
1520 .collect();
1521 format!("otpauth-migration://offline?data={pct}")
1522 }
1523
1524 #[test]
1525 fn a_google_migration_payload_decodes_to_the_same_seed_google_encoded() {
1526 let raw = totp::base32_decode(SEED).unwrap();
1531 let uri = google_payload(&raw, "me@example.com", "Acme", 1, 1, 2);
1532 let r = parse(&uri).unwrap();
1533 assert_eq!(r.format, Format::GoogleMigration);
1534 let it = one(&r.items);
1535 assert_eq!(it.stored.secret, SEED);
1536 assert_eq!(it.issuer.as_deref(), Some("Acme"));
1537 assert_eq!(it.account.as_deref(), Some("me@example.com"));
1538 assert!(it.stored.params.is_default());
1540 }
1541
1542 #[test]
1543 fn the_migration_enums_map_to_the_right_algorithm_and_digit_count() {
1544 let raw = totp::base32_decode(SEED).unwrap();
1545 for (algo_enum, want) in [
1546 (0u8, totp::Algorithm::Sha1), (1, totp::Algorithm::Sha1),
1548 (2, totp::Algorithm::Sha256),
1549 (3, totp::Algorithm::Sha512),
1550 ] {
1551 let uri = google_payload(&raw, "n", "i", algo_enum, 1, 2);
1552 assert_eq!(
1553 parse(&uri).unwrap().items[0].stored.params.algorithm,
1554 want,
1555 "algorithm enum {algo_enum}"
1556 );
1557 }
1558 let six = google_payload(&raw, "n", "i", 1, 1, 2);
1560 let eight = google_payload(&raw, "n", "i", 1, 2, 2);
1561 assert_eq!(parse(&six).unwrap().items[0].stored.params.digits, 6);
1562 assert_eq!(parse(&eight).unwrap().items[0].stored.params.digits, 8);
1563 }
1564
1565 #[test]
1566 fn a_counter_based_migration_entry_is_imported_with_its_counter() {
1567 let raw = totp::base32_decode(SEED).unwrap();
1572 let uri = google_payload(&raw, "counter", "Old", 1, 1, 1); let r = parse(&uri).unwrap();
1574 assert_eq!(r.items.len(), 1);
1575 assert!(r.skipped.is_empty(), "{:?}", r.skipped);
1576 assert_eq!(r.items[0].stored.params.kind, totp::Kind::Hotp);
1577 }
1578
1579 #[test]
1580 fn several_migration_uris_accumulate_rather_than_conflicting() {
1581 let raw = totp::base32_decode(SEED).unwrap();
1584 let text = format!(
1585 "{}\n{}\n",
1586 google_payload(&raw, "a", "One", 1, 1, 2),
1587 google_payload(&raw, "b", "Two", 1, 1, 2)
1588 );
1589 let r = parse(&text).unwrap();
1590 assert_eq!(r.items.len(), 2);
1591 assert_eq!(r.items[1].issuer.as_deref(), Some("Two"));
1592 }
1593
1594 #[test]
1595 fn a_truncated_or_junk_migration_payload_errors_rather_than_panicking() {
1596 for bad in [
1599 "otpauth-migration://offline?data=",
1600 "otpauth-migration://offline?data=!!!!",
1601 "otpauth-migration://offline?data=CjEKCg", "otpauth-migration://offline?data=%FF%FF%FF%FF",
1603 ] {
1604 let _ = parse(bad);
1605 }
1606 let payload = base64::engine::general_purpose::STANDARD.encode([0x0a, 0x7f, 0x01]);
1608 let r = parse(&format!("otpauth-migration://offline?data={payload}"));
1609 assert!(r.is_err(), "a lying length prefix must not be accepted");
1610 }
1611
1612 fn sample() -> Vec<Imported> {
1615 vec![
1616 Imported {
1617 issuer: Some("Acme".into()),
1618 account: Some("me@example.com".into()),
1619 stored: Stored {
1620 secret: SEED.into(),
1621 params: Params::default(),
1622 issuer: None,
1623 account: None,
1624 },
1625 note: Some("work".into()),
1626 },
1627 Imported {
1628 issuer: Some("Other".into()),
1629 account: None,
1630 stored: Stored {
1631 secret: "MZXW6YTBOI".into(),
1632 params: Params {
1633 kind: totp::Kind::Totp,
1634 counter: 0,
1635 algorithm: totp::Algorithm::Sha512,
1636 digits: 8,
1637 period: 45,
1638 },
1639 issuer: None,
1640 account: None,
1641 },
1642 note: None,
1643 },
1644 ]
1645 }
1646
1647 #[test]
1648 fn every_exportable_format_reads_back_through_this_modules_own_parser() {
1649 for format in Format::EXPORTABLE {
1653 let text = build(&sample(), format).unwrap();
1654 let back = parse(&text)
1655 .unwrap_or_else(|e| panic!("{} did not read back: {e}", format.as_str()));
1656 assert_eq!(
1657 back.format, format,
1658 "detected the wrong format for {format:?}"
1659 );
1660 assert_eq!(back.items.len(), 2, "{format:?}");
1661 for (a, b) in sample().iter().zip(back.items.iter()) {
1662 assert_eq!(a.stored.secret, b.stored.secret, "{format:?}");
1663 assert_eq!(a.stored.params, b.stored.params, "{format:?}");
1664 assert_eq!(a.issuer, b.issuer, "{format:?}");
1665 }
1666 }
1667 }
1668
1669 #[test]
1670 fn a_read_only_format_is_refused_by_name_with_the_alternatives() {
1671 for format in [Format::Bitwarden, Format::GoogleMigration, Format::AndOtp] {
1672 let err = build(&sample(), format).expect_err("must refuse");
1673 assert!(err.contains(format.as_str()), "{err}");
1674 assert!(err.contains("otpauth"), "{err}");
1675 }
1676 }
1677
1678 #[test]
1679 fn the_aegis_uuid_is_stable_across_builds_so_a_re_import_updates() {
1680 let a = build(&sample(), Format::Aegis).unwrap();
1683 let b = build(&sample(), Format::Aegis).unwrap();
1684 assert_eq!(a, b);
1685 assert!(!a.contains(&format!("\"uuid\": \"{SEED}\"")));
1687 }
1688
1689 #[test]
1690 fn aegis_marks_the_vault_unencrypted_the_way_aegis_requires() {
1691 let v: Value = serde_json::from_str(&build(&sample(), Format::Aegis).unwrap()).unwrap();
1694 assert!(v.pointer("/header/slots").unwrap().is_null());
1695 assert_eq!(
1696 v.pointer("/db/entries").unwrap().as_array().unwrap().len(),
1697 2
1698 );
1699 }
1700
1701 #[test]
1702 fn format_names_round_trip_and_ente_is_an_alias_for_the_uri_list() {
1703 for f in [
1704 Format::OtpauthList,
1705 Format::Aegis,
1706 Format::TwoFas,
1707 Format::AndOtp,
1708 Format::Bitwarden,
1709 Format::GoogleMigration,
1710 ] {
1711 assert_eq!(Format::parse(f.as_str()), Some(f), "{f:?}");
1712 }
1713 assert_eq!(Format::parse("ente"), Some(Format::OtpauthList));
1716 assert_eq!(Format::parse("Ente"), Some(Format::OtpauthList));
1717 assert_eq!(Format::parse("2FAS"), Some(Format::TwoFas));
1718 assert_eq!(
1719 Format::parse("google-authenticator"),
1720 Some(Format::GoogleMigration)
1721 );
1722 assert_eq!(Format::parse("nonsense"), None);
1723 }
1724
1725 #[test]
1726 fn suggested_provider_prefers_the_issuer_over_an_email_address() {
1727 let mut it = sample().remove(0);
1730 assert_eq!(it.suggested_provider(), "Acme");
1731 it.issuer = None;
1732 assert_eq!(it.suggested_provider(), "me@example.com");
1733 it.account = Some(" ".into());
1734 assert_eq!(it.suggested_provider(), "Unnamed");
1735 }
1736
1737 fn entry(provider: &str, account: &str, seed: Option<&str>) -> Value {
1740 let mut e = serde_json::json!({
1741 "id": provider, "provider": provider, "api_key": "",
1742 "account_name": account, "categories": [], "projectIds": ["Universal"], "scopes": []
1743 });
1744 if let Some(s) = seed {
1745 e["totp_secret"] = Value::String(s.into());
1746 }
1747 e
1748 }
1749
1750 fn incoming(issuer: &str, account: &str, seed: &str) -> Imported {
1751 Imported {
1752 issuer: Some(issuer.into()),
1753 account: Some(account.into()),
1754 stored: totp::parse_seed(seed).expect("fixture seed parses"),
1755 note: None,
1756 }
1757 }
1758
1759 const OTHER: &str = "MZXW6YTBOI";
1760
1761 #[test]
1762 fn an_unmatched_account_is_created() {
1763 assert_eq!(
1764 plan(&[], &[incoming("Acme", "me", SEED)], false),
1765 [Plan::Create]
1766 );
1767 }
1768
1769 #[test]
1770 fn an_entry_with_no_seed_yet_is_updated_rather_than_duplicated() {
1771 let vault = [entry("Acme", "me", None)];
1775 assert_eq!(
1776 plan(&vault, &[incoming("Acme", "me", SEED)], false),
1777 [Plan::Update { index: 0 }]
1778 );
1779 }
1780
1781 #[test]
1782 fn re_running_the_same_import_changes_nothing() {
1783 let vault = [entry("Acme", "me", Some(SEED))];
1785 assert_eq!(
1786 plan(&vault, &[incoming("Acme", "me", SEED)], false),
1787 [Plan::Unchanged { index: 0 }]
1788 );
1789 }
1790
1791 #[test]
1792 fn a_different_stored_seed_is_a_conflict_and_not_an_overwrite() {
1793 let vault = [entry("Acme", "me", Some(SEED))];
1798 assert_eq!(
1799 plan(&vault, &[incoming("Acme", "me", OTHER)], false),
1800 [Plan::Conflict { index: 0 }]
1801 );
1802 assert_eq!(
1803 plan(&vault, &[incoming("Acme", "me", OTHER)], true),
1804 [Plan::Update { index: 0 }],
1805 "--force is how you say you meant it"
1806 );
1807 }
1808
1809 #[test]
1810 fn matching_needs_both_the_provider_and_the_account() {
1811 let vault = [entry("Acme", "me", Some(SEED)), entry("Other", "me", None)];
1815 assert_eq!(
1816 plan(
1817 &vault,
1818 &[
1819 incoming("Acme", "someone-else", OTHER),
1820 incoming("Other", "me", OTHER),
1821 ],
1822 false
1823 ),
1824 [Plan::Create, Plan::Update { index: 1 }]
1825 );
1826 }
1827
1828 #[test]
1829 fn matching_ignores_case_and_surrounding_space() {
1830 let vault = [entry("GitHub", "Me@Example.com", None)];
1833 assert_eq!(
1834 plan(
1835 &vault,
1836 &[incoming(" github ", "me@example.com", SEED)],
1837 false
1838 ),
1839 [Plan::Update { index: 0 }]
1840 );
1841 }
1842
1843 #[test]
1844 fn a_seed_spelled_differently_is_still_the_same_seed() {
1845 let vault = [entry("Acme", "me", Some("jbsw y3dp ehpk 3pxp"))];
1848 assert_eq!(
1849 plan(&vault, &[incoming("Acme", "me", SEED)], false),
1850 [Plan::Unchanged { index: 0 }]
1851 );
1852 }
1853
1854 #[test]
1855 fn write_fields_clears_a_parameter_that_returned_to_its_default() {
1856 let mut e = serde_json::json!({ "provider": "A", "totp_period": 60, "totp_digits": 8 });
1860 write_fields(
1861 &mut e,
1862 &Stored {
1863 secret: SEED.into(),
1864 params: Params::default(),
1865 issuer: None,
1866 account: None,
1867 },
1868 );
1869 assert_eq!(e["totp_secret"], SEED);
1870 assert!(e.get("totp_period").is_none(), "{e}");
1871 assert!(e.get("totp_digits").is_none(), "{e}");
1872 }
1873
1874 #[test]
1875 fn a_new_entry_carries_the_account_into_username_and_stays_in_universal() {
1876 let it = incoming("Acme", "me@example.com", SEED);
1877 let e = new_entry(
1878 &it,
1879 "id-1",
1880 "2026-09-10T00:00:00Z",
1881 Some("web"),
1882 Some("2fa"),
1883 );
1884 assert_eq!(e["provider"], "Acme");
1885 assert_eq!(e["secretType"], "password");
1886 assert_eq!(e["api_key"], "");
1887 assert_eq!(e["account_name"], "me@example.com");
1888 assert_eq!(e["username"], "me@example.com");
1889 assert_eq!(e["totp_secret"], SEED);
1890 assert_eq!(e["categories"], serde_json::json!(["2fa"]));
1891 assert_eq!(e["projectIds"], serde_json::json!(["Universal", "web"]));
1893 }
1894}