Skip to main content

vault_core/
totp_import.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Reading and writing the export files other authenticator apps produce.
4//!
5//! Phase 22 gave the vault somewhere to keep a third-party TOTP seed. This
6//! module is how a seed gets in and out without being retyped from a phone
7//! screen — Ente Auth, Aegis, 2FAS, andOTP, Bitwarden and Google Authenticator
8//! on the way in; a portable `otpauth://` list, Aegis or 2FAS on the way out.
9//!
10//! # It lives here, and only here
11//!
12//! Six formats parsed twice is six chances to disagree, and a disagreement here
13//! is a seed that imports into the app and not the CLI — or worse, imports with
14//! the wrong `period` and produces six digits the issuer rejects. So this is
15//! Rust only: the CLI calls it directly, the desktop app calls it over IPC
16//! (`totp_import_parse` / `totp_export_build`), and there is no TypeScript twin
17//! to pin. That is the shape `pools.ts` already uses and the one CLAUDE.md's
18//! twin-pair table says to prefer over a golden fixture.
19//!
20//! # Encrypted exports are refused, never decrypted
21//!
22//! Every app here can export encrypted, and each uses its own KDF and envelope.
23//! Implementing six of those would mean this crate holding six password-guessing
24//! paths whose failures are indistinguishable from a corrupt file. [`detect`]
25//! recognises each encrypted shape and returns a message naming the app and
26//! saying to export again without encryption. Refusing with a reason beats
27//! failing to parse with none.
28//!
29//! # Counter-based codes
30//!
31//! `otpauth://hotp/` entries carry their counter through import and export. HOTP
32//! has no clock, so callers request the next code explicitly and advance the
33//! stored counter only after the target service accepts it.
34
35use crate::totp::{self, Params, Stored};
36use base64::Engine;
37use serde::{Deserialize, Serialize};
38use serde_json::Value;
39
40/// An export format this module can read, write, or both.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Format {
44    /// One `otpauth://` URI per line. What Ente Auth's plain-text export is,
45    /// and what KeePassXC, Raivo, Proton Pass and most others accept back.
46    OtpauthList,
47    /// Aegis Authenticator's unencrypted JSON vault.
48    Aegis,
49    /// 2FAS Auth's unencrypted JSON backup.
50    TwoFas,
51    /// andOTP's unencrypted JSON export (also read by FreeOTP+).
52    AndOtp,
53    /// A Bitwarden JSON export — reads `login.totp` off each item.
54    Bitwarden,
55    /// Google Authenticator's `otpauth-migration://offline?data=…` QR payload.
56    GoogleMigration,
57}
58
59impl Format {
60    /// The name a human typed, or that a report prints.
61    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    /// Parses a `--format` value.
73    ///
74    /// `ente` is an alias for `otpauth`, not a format of its own: Ente Auth's
75    /// plain export *is* a list of `otpauth://` URIs, and its import accepts the
76    /// same. The alias exists because somebody with an Ente export will type
77    /// `--format ente`, and being told "unknown format" when the thing works is
78    /// a bad answer.
79    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    /// The formats `--format` accepts on export.
101    ///
102    /// Read-only formats are absent on purpose. Bitwarden's export is a whole
103    /// password vault and writing one containing nothing but TOTP seeds would
104    /// produce a file that imports as a set of empty logins; Google's migration
105    /// payload is a QR code this app cannot draw (see Phase 19's decision about
106    /// the CSP), so writing the URI behind it would be a format nothing reads.
107    pub const EXPORTABLE: [Format; 3] = [Format::OtpauthList, Format::Aegis, Format::TwoFas];
108
109    /// Whether [`build`] can write this format.
110    pub fn is_exportable(self) -> bool {
111        Format::EXPORTABLE.contains(&self)
112    }
113}
114
115/// One seed read out of somebody else's export.
116///
117/// `issuer` and `account` are what the file said. They are *offered* to the
118/// caller — the CLI turns them into a provider name and an account for a new
119/// entry — and never overwrite an existing entry's own names, for the reason in
120/// [`crate::totp`]: renaming an entry is what every `${ref}` addresses it by.
121#[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    /// A note or tag the source app carried, when it had one.
128    pub note: Option<String>,
129}
130
131impl Imported {
132    /// The name an entry made from this should carry.
133    ///
134    /// Issuer first because that is what a user calls the service; the account
135    /// alone is usually an email address, and a vault full of entries named
136    /// `me@example.com` is a vault you cannot search.
137    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/// What a parse produced, including what it refused.
154#[derive(Debug, Clone, Serialize, Deserialize)]
155pub struct ParseReport {
156    pub format: Format,
157    pub items: Vec<Imported>,
158    /// Entries that were recognised and could not be imported, each with a
159    /// reason. Reported rather than dropped: a count that does not add up is
160    /// how somebody discovers six months later that one account never came
161    /// across.
162    pub skipped: Vec<Skipped>,
163}
164
165/// One entry the parser declined, and why.
166#[derive(Debug, Clone, Serialize, Deserialize)]
167pub struct Skipped {
168    /// Whatever the file called it. Never the secret.
169    pub name: String,
170    pub reason: String,
171}
172
173// ── Detection ─────────────────────────────────────────────────────────────────
174
175/// Work out which app wrote this file.
176///
177/// Errors name the app and what to do, rather than saying "unrecognised" — the
178/// encrypted variants are the common case for a user who has just pressed
179/// "export" in an app that defaults to encrypting, and they are all detectable.
180pub 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        // Ente Auth's encrypted export. The decrypted payload is a plain
195        // newline-delimited otpauth:// list, but the envelope needs the export
196        // password. The official Ente CLI owns that decryption step.
197        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        // Aegis. Encrypted vaults keep `header.slots` populated and store `db`
207        // as a base64 string instead of an object.
208        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        // 2FAS.
223        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        // Bitwarden.
238        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        // andOTP: a bare array of objects carrying `secret`.
248        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    // A plain-text list is the last guess, because it is the loosest: any file
262    // with an otpauth:// URI somewhere in it qualifies, so it must not shadow a
263    // format that identifies itself.
264    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
287// ── Parsing ───────────────────────────────────────────────────────────────────
288
289/// Read an export, detecting the format.
290pub fn parse(text: &str) -> Result<ParseReport, String> {
291    let format = detect(text)?;
292    parse_as(text, format)
293}
294
295/// Read an export in a format the caller has already decided.
296pub fn parse_as(text: &str, format: Format) -> Result<ParseReport, String> {
297    let text = text.trim_start_matches('\u{feff}');
298    // Choosing the format skips guessing it, never the refusal of an encrypted export:
299    // without this check `--format aegis` on an encrypted vault says "no db.entries
300    // array" instead of naming the real problem.
301    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
321/// One `otpauth://` URI per line — Ente Auth's plain export, and the format
322/// every other app will take back.
323///
324/// Blank lines and `#` comments are skipped in silence; anything else that is
325/// not a URI is reported. Ente writes an extra `codeDisplay={…}` parameter
326/// holding its own UI state, which the URI parser ignores along with every other
327/// unknown parameter — that is why it is ignored rather than special-cased.
328fn 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                // The line number, never the line: a malformed URI still holds
345                // the secret, and this string reaches stdout.
346                name: format!("line {}", n + 1),
347                reason: e,
348            }),
349        }
350    }
351    (items, skipped)
352}
353
354/// Build a `Stored` from the pieces every JSON format spells slightly
355/// differently, defaulting whatever the file left out.
356fn 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    // One reader for the four parameter fields, shared with the CLI and the
365    // desktop command — see `Params::from_fields`, which clamps every one of
366    // them and forces the shape Steam fixes.
367    let params = Params::from_fields(kind, algo, digits, period, counter);
368    // Goes through the same validator every other entry point uses, so a seed
369    // an export mangled is refused here rather than stored unusable.
370    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        // Aegis names all three kinds in `type`, and writes a `steam` entry with
397        // `type: "steam"` rather than through the `encoder` parameter its URI
398        // export uses.
399        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        // 2FAS keeps the display name at the top level and the issuer inside
437        // `otp`, and real backups have one or the other empty depending on how
438        // the entry was added.
439        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
521/// Read `login.totp` out of a Bitwarden export.
522///
523/// Bitwarden stores either a bare base32 seed or a whole `otpauth://` URI in
524/// that one field, depending on how the entry was created — which is exactly the
525/// pair `parse_seed` already accepts, so both work with no branch here.
526fn 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            // Most items in a password export have no TOTP at all. That is not
541            // a skip worth reporting — it would drown the ones that are.
542            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                // A URI in this field carries its own issuer; the item's name is
550                // the fallback, and is usually the better of the two.
551                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
565// ── Google Authenticator migration payloads ──────────────────────────────────
566
567/// Read `otpauth-migration://offline?data=…`.
568///
569/// The payload is a protobuf, and it is decoded by hand for the same reason
570/// base32 is: pulling in `prost` and a build-time code generator to read one
571/// message with seven scalar fields costs more than the forty lines below, and
572/// those forty lines are what a reader has to check.
573///
574/// A multi-QR export produces several URIs, one per batch. Pass them one per
575/// line and they accumulate; `batch_index` is not checked, because a user who
576/// scanned three of four codes should get three accounts and be told, not get an
577/// error and none.
578fn 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
610/// Percent-decode then base64-decode a migration payload.
611///
612/// Both alphabets are tried: the URI is standard base64 percent-encoded, but
613/// every tool that has ever copied one out of a QR reader writes it URL-safe,
614/// and telling a user their QR code is corrupt because of an alphabet is a poor
615/// answer.
616fn 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        // `+` is base64's 62nd character *and* a form-encoded space. In a
648        // migration URI it is always the former — the payload is base64 and a
649        // space cannot appear in it — so it is left alone here, unlike in the
650        // otpauth label parser where the opposite is true.
651        out.push(bytes[i]);
652        i += 1;
653    }
654    String::from_utf8_lossy(&out).into_owned()
655}
656
657/// A minimal protobuf reader: just enough for `MigrationPayload`.
658struct 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    /// Base-128 varint. Caps the shift so a malformed payload cannot loop or
671    /// overflow — this parses a file somebody else wrote.
672    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    /// Field key, returning `(field number, wire type)`.
692    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    /// Step over a field this reader does not care about.
708    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        // Field 1 is the repeated OtpParameters; 2..=5 are version and batch
731        // bookkeeping we do not need.
732        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
746/// One `OtpParameters` message. `Ok(None)` means "nothing wrong, nothing to
747/// import" — which never happens today but keeps the caller honest if it does.
748fn 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; // 1 = SHA1, and 0 (unspecified) means the same thing.
753    let mut digits_enum = 1u64; // 1 = SIX
754    let mut kind = 2u64; // 2 = TOTP
755    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            // Field 7 is the counter, present only on a counter-based entry.
784            // Dropping it hands the next device a seed starting from zero — a
785            // second factor that fails until the account is resynced.
786            (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    // Google stores raw bytes; everything else in this module speaks base32.
800    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            // 0 (unspecified) and 1 (SHA1) are the same answer. 4 is MD5, which
806            // RFC 6238 does not define and nothing generates; it falls here
807            // rather than being refused, because a wrong algorithm is visible
808            // immediately (the code is rejected) while a lost account is not.
809            _ => totp::Algorithm::Sha1,
810        },
811        digits: if digits_enum == 2 { 8 } else { 6 },
812        // The migration format has no period field at all: Google only ever
813        // exports 30-second entries.
814        period: totp::STEP_SECS,
815        // 1 = HOTP, 2 = TOTP, 0 = unspecified. Google Authenticator has no Steam
816        // support, so there is no third case to read.
817        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
838// ── Building ─────────────────────────────────────────────────────────────────
839
840/// Write the seeds out in a format another app reads.
841///
842/// **Every byte of this is secret material** — the whole point of the file is to
843/// carry seeds to another device. Callers treat it exactly as they treat a
844/// `.vaultbak`: `--out` to a 0600 file, refused to stdout without `--reveal`.
845pub 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            // Aegis spells all three kinds in `type`, and reads `counter` only
882            // for the counter-based one. Writing a period onto an `hotp` entry
883            // is harmless there but says something untrue about the seed, so
884            // each kind writes only the field that governs it.
885            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                // Aegis keys its own entries by uuid; a stable one derived from
899                // the seed means re-importing the same file twice updates rather
900                // than duplicating.
901                "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    // `header.slots: null` is how Aegis marks a vault as unencrypted, and it is
912    // required — an absent header is not the same thing and Aegis refuses it.
913    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                    // 2FAS spells them in upper case, and carries a counter only
939                    // for the counter-based one.
940                    "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        // 2FAS refuses a backup whose schemaVersion it does not know. 4 is the
955        // oldest version every current build still reads.
956        "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
966/// A UUID-shaped string derived from the seed.
967///
968/// Not a real UUID and not claimed to be one — Aegis only needs the field to be
969/// stable and unique per entry. Deriving it from the seed is what makes a second
970/// import of the same file an update rather than a duplicate; a random one would
971/// give the user two of everything on the second try.
972///
973/// It is a hash, so the file does not leak the seed through this field. The file
974/// contains the seed anyway, which is why the whole thing is a materialising
975/// path — but a field that *looked* opaque and was not would be worse.
976fn 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
990// ── Merging an import into a vault ───────────────────────────────────────────
991//
992// The rules live here rather than in the CLI because they decide whether a
993// working second factor survives an import, and a rule like that must not be
994// able to differ between the app and the terminal. `unv totp import` and the
995// desktop app's Import button both call [`plan`] and [`apply`].
996
997/// Normalised key for "is this the same account?".
998///
999/// Provider and account together, case-folded and trimmed. Neither alone is
1000/// enough: two GitHub accounts are two entries, and two services can share an
1001/// email address. Case-folded because exports capitalise inconsistently —
1002/// "GitHub" in one app, "github" in the next — and a case-sensitive match
1003/// silently duplicates every account.
1004fn match_key(provider: &str, account: &str) -> (String, String) {
1005    (
1006        provider.trim().to_lowercase(),
1007        account.trim().to_lowercase(),
1008    )
1009}
1010
1011/// What an import would do to one incoming seed.
1012#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1013#[serde(tag = "action", rename_all = "snake_case")]
1014pub enum Plan {
1015    /// No entry matches provider+account; make one.
1016    Create,
1017    /// An entry matches and carries no seed, or `force` was set.
1018    Update { index: usize },
1019    /// An entry matches and already holds this exact seed. Doing nothing is
1020    /// what makes re-running an import idempotent.
1021    Unchanged { index: usize },
1022    /// An entry matches and holds a **different** seed. Reported, never
1023    /// overwritten without `force`.
1024    Conflict { index: usize },
1025}
1026
1027/// Decide, for each incoming seed, what should happen to it.
1028///
1029/// The rule that matters is [`Plan::Conflict`]. A stored second factor is not
1030/// recoverable from UnENVerse's side once it is gone, and an import is exactly
1031/// the moment a stale export gets pointed at a vault that has since been
1032/// re-enrolled. Silently taking the incoming value there would lock the user out
1033/// of an account at the moment they believe they are backing one up.
1034pub 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
1075/// Write a seed and its parameters onto an entry.
1076///
1077/// Parameters equal to the default are **removed**, not written: a field that
1078/// reads "SHA1" on every entry cannot be told apart from a defaulted one, and
1079/// removing rather than skipping is what makes re-importing a 60-second seed as
1080/// a 30-second one actually clear the old period.
1081pub 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    // The counter is state rather than configuration, so it is written whenever
1114    // the seed is counter-based — including at zero, which is a real position and
1115    // not an absent one. Removing it for the other kinds is what stops a seed
1116    // converted from HOTP to TOTP keeping a number nothing reads.
1117    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
1124/// Build a fresh entry for a seed that matched nothing in the vault.
1125///
1126/// `secretType` is `password`, not `api_key`: a TOTP seed is a login's second
1127/// factor, and the password form is the one with a username field for the
1128/// account to live in. `api_key` is empty because there is no password beside it
1129/// yet — which is why the add/edit form lets an entry carrying a seed skip its
1130/// "value is required" check.
1131pub 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        // Nearly always the login name, and the password form shows a username.
1157        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    /// "Hello!\u{0}\u{0}" — the RFC 4648 example, and a seed short enough to read.
1171    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    /// The first item, where a fixture deliberately carries several kinds.
1179    fn first(items: &[Imported]) -> &Imported {
1180        assert!(!items.is_empty(), "expected at least one item");
1181        &items[0]
1182    }
1183
1184    // ── Detection ───────────────────────────────────────────────────────────
1185
1186    #[test]
1187    fn every_supported_format_is_recognised_from_its_own_bytes() {
1188        // Detection has to be right before anything else can be: guessing wrong
1189        // means parsing an Aegis file as andOTP and reporting "no entries",
1190        // which tells the user nothing about what actually happened.
1191        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        // This is the common case for somebody who just pressed "export" in an
1216        // app that encrypts by default. "Unrecognised file" would send them
1217        // looking for a bug; naming the app and the fix does not.
1218        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        // Ente's encrypted envelope used to fall through to a generic JSON
1232        // error. Someone with the normal Ente backup then had no safe next
1233        // step, even though Ente documents a CLI decryption route.
1234        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        // A file picker hands this whatever the user chose.
1243        for junk in ["", "   ", "\u{feff}", "not json {", "\0\0\0", "[]", "{}"] {
1244            let _ = detect(junk);
1245        }
1246    }
1247
1248    // ── Ente / otpauth lists ────────────────────────────────────────────────
1249
1250    #[test]
1251    fn an_ente_plain_export_imports_including_its_codedisplay_parameter() {
1252        // Ente writes its own UI state into an extra `codeDisplay` parameter.
1253        // The URI parser ignores unknown parameters, which is why this needs no
1254        // special case — but it needs a test, because "ignored" and "chokes on"
1255        // look identical until somebody tries it.
1256        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        // A malformed URI still holds a secret, and this string reaches stdout.
1279        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        // The counter-based line is imported now (Phase 22.2) rather than named
1284        // and skipped; only the mangled secret is still a skip.
1285        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    // ── The JSON formats ────────────────────────────────────────────────────
1296
1297    #[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        // Aegis names all three kinds in `type`, and keeps the counter under
1322        // `info` where the period would be for a time-based entry.
1323        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        // Aegis writes `type: "steam"` in its JSON and `encoder=steam` in its
1331        // URI export. Reading only one of the two spellings imports the seed as
1332        // an ordinary six-digit TOTP, which produces codes Steam rejects with no
1333        // explanation.
1334        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        // And it survives a round trip back out through both writable formats.
1348        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        // The counter is the one number in a seed that is *state*. An export
1362        // that drops it hands the next device a second factor that fails until
1363        // the account is resynced — and the failure looks exactly like a wrong
1364        // seed, which is the wrong thing to be debugging.
1365        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        // Real backups have `otp.issuer` empty for entries added by hand and
1396        // `name` empty for some scanned ones, so both have to be read.
1397        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        // Three now: the `HOTP` service is read rather than skipped.
1412        assert_eq!(r.items.len(), 3);
1413        assert_eq!(r.items[0].issuer.as_deref(), Some("Acme"));
1414        // No `otp.issuer`: the top-level name stands in.
1415        assert_eq!(r.items[1].issuer.as_deref(), Some("Fallback"));
1416        assert_eq!(r.items[1].account.as_deref(), Some("lbl"));
1417        // Omitted parameters mean the defaults.
1418        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        // Bitwarden stores a bare seed or a whole URI in the same field,
1440        // depending on how the item was created.
1441        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        // The item's own name beats the URI's issuer: it is the one the user
1455        // chose, and the URI's half is usually whatever the site sent.
1456        assert_eq!(r.items[1].issuer.as_deref(), Some("Uri"));
1457        // Items with no TOTP are not "skipped" — in a password export they are
1458        // the overwhelming majority and would drown the real report.
1459        assert!(r.skipped.is_empty(), "{:?}", r.skipped);
1460    }
1461
1462    // ── Google Authenticator ────────────────────────────────────────────────
1463
1464    /// Hand-built `MigrationPayload`, so the test does not depend on owning a
1465    /// phone. Field numbers are from Google's `otpauth-migration` schema.
1466    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, &params);
1507        field_varint(&mut payload, 2, 1); // version
1508        field_varint(&mut payload, 3, 1); // batch_size
1509        field_varint(&mut payload, 4, 0); // batch_index
1510
1511        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        // Google stores the secret as raw bytes; everything else in this module
1527        // speaks base32. Getting that conversion wrong produces a seed that is
1528        // the right length and the wrong value — six plausible digits that are
1529        // rejected, with nothing on screen saying why.
1530        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        // The migration format has no period field: Google only exports 30s.
1539        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), // unspecified means SHA-1
1547            (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        // The digit count is an enum, not a number: 1 is SIX and 2 is EIGHT.
1559        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        // Phase 22 named and skipped these. Phase 22.2 reads them: the entry can
1568        // hold a counter, and the counter is the half that has to survive —
1569        // importing an HOTP seed at zero is a second factor that fails until the
1570        // account is resynced, which looks exactly like a wrong seed.
1571        let raw = totp::base32_decode(SEED).unwrap();
1572        let uri = google_payload(&raw, "counter", "Old", 1, 1, 1); // kind 1 = HOTP
1573        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        // A large export is several QR codes. Somebody who scanned three of four
1582        // should get three accounts and be told, not get an error and none.
1583        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        // This parses bytes from a QR code somebody else generated. Every length
1597        // in it is attacker-controlled as far as this function is concerned.
1598        for bad in [
1599            "otpauth-migration://offline?data=",
1600            "otpauth-migration://offline?data=!!!!",
1601            "otpauth-migration://offline?data=CjEKCg", // truncated mid-field
1602            "otpauth-migration://offline?data=%FF%FF%FF%FF",
1603        ] {
1604            let _ = parse(bad);
1605        }
1606        // And a length header claiming more bytes than exist.
1607        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    // ── Building ────────────────────────────────────────────────────────────
1613
1614    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        // The round trip is the property that matters, not the bytes: a file
1650        // that cannot be read back is one the destination app will not read
1651        // either, and the user finds that out on a phone with no other copy.
1652        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        // A random uuid would give the user two of everything the second time
1681        // they imported the same file.
1682        let a = build(&sample(), Format::Aegis).unwrap();
1683        let b = build(&sample(), Format::Aegis).unwrap();
1684        assert_eq!(a, b);
1685        // And it does not carry the seed it is derived from.
1686        assert!(!a.contains(&format!("\"uuid\": \"{SEED}\"")));
1687    }
1688
1689    #[test]
1690    fn aegis_marks_the_vault_unencrypted_the_way_aegis_requires() {
1691        // `header.slots: null` is the marker. An absent header is not the same
1692        // thing, and Aegis refuses the file rather than importing it.
1693        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        // Ente's plain export *is* an otpauth list, and somebody holding one
1714        // will type --format ente. Refusing it would be pedantry.
1715        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        // A vault of forty entries all called me@example.com is a vault you
1728        // cannot search.
1729        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    // ── Merge rules ─────────────────────────────────────────────────────────
1738
1739    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        // The common case: the vault already holds the password for this login
1772        // and the import is adding its second factor beside it. Creating a
1773        // second entry would split one credential across two cards.
1774        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        // Idempotence is what makes an import safe to retry after it half-failed.
1784        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        // The failure this exists to prevent: pointing a stale export at a vault
1794        // that has since been re-enrolled silently replaces a working second
1795        // factor with a dead one, at the moment the user believes they are
1796        // backing it up.
1797        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        // Two accounts at one service are two entries; two services can share an
1812        // email address. Matching on either alone merges credentials that are
1813        // not the same credential.
1814        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        // "GitHub" in one app, "github" in the next. A case-sensitive match
1831        // silently duplicates every account.
1832        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        // A stored seed written with the grouping spaces must not read as a
1846        // conflict against the same seed written without them.
1847        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        // Removing rather than skipping is the point: re-importing a 60-second
1857        // seed as a 30-second one has to actually clear the old period, or the
1858        // entry keeps generating against a period nothing sent it.
1859        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        // A specific project never replaces Universal — every entry carries it.
1892        assert_eq!(e["projectIds"], serde_json::json!(["Universal", "web"]));
1893    }
1894}