Skip to main content

agentmux_srv_core/backend/vault/
transfer.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Export to and import from the encrypted `.vault` file
5//! (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md §8).
6//!
7//! A `.vault` file is an age file encrypted to a passphrase (age's scrypt
8//! recipient), whose plaintext is the JSON in `docs/api/VAULT_FILE_FORMAT.md`.
9//! `age -d backup.vault` opens it without AgentMux.
10//!
11//! Only the person exports or imports: these functions are reached through the
12//! host, which picks the file in its native dialog, so no agent chooses a path.
13//! An import is two steps: `inspect` reads and decrypts the file into memory and
14//! describes it with no values; `commit` writes it, in one transaction.
15
16use std::collections::{BTreeMap, HashMap};
17use std::io::{Read, Write};
18use std::path::Path;
19use std::sync::Mutex;
20use std::time::{Duration, Instant};
21
22use age::secrecy::SecretString;
23use ring::rand::{SecureRandom, SystemRandom};
24use serde::{Deserialize, Serialize};
25use zeroize::Zeroizing;
26
27use super::import::{self, Incoming, Mapping, MappingNeeded, ReadError, Source};
28use super::kinds::{self, VaultSection};
29use super::seal::{self, Parts};
30use super::signins;
31use super::source_link::Link;
32use super::{linked, new_id, record, validate, PERSON};
33use crate::backend::storage::store::Store;
34use crate::backend::storage::vault::VaultRow;
35use agentmux_common::time::now_ms;
36
37pub const FORMAT: &str = "agentmux-vault";
38pub const VERSION: u32 = 1;
39
40/// §8.7: a file over this is refused before it is read.
41const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024;
42const MAX_ENTRIES: usize = 100_000;
43/// A passphrase shorter than this isn't accepted for an export.
44pub const MIN_PASSPHRASE: usize = 8;
45/// How long a staged import waits for the person to commit it.
46const STAGED_TTL: Duration = Duration::from_secs(10 * 60);
47/// How many imports wait for a person at once: the oldest makes room for a new one.
48const MAX_STAGED: usize = 4;
49/// [`MAX_STAGED`], and in a test run (where every test shares the one table) enough that another test's imports never
50/// push out the one a test is working on.
51fn stage_limit() -> usize {
52    if cfg!(test) { 256 } else { MAX_STAGED }
53}
54/// Drops the oldest staged imports until there is room for one more under `limit`.
55fn make_room(held: &mut HashMap<String, Staged>, limit: usize) {
56    while held.len() >= limit {
57        let Some(oldest) = held.iter().min_by_key(|(_, s)| s.at).map(|(k, _)| k.clone()) else { break };
58        held.remove(&oldest);
59    }
60}
61const AGE_MAGIC: &[u8] = b"age-encryption.org/v1";
62
63#[derive(Serialize, Deserialize)]
64struct VaultFile {
65    format: String,
66    version: u32,
67    exported_at: i64,
68    #[serde(default)]
69    app_version: String,
70    entries: Vec<Incoming>,
71}
72
73/// [`VaultFile`] borrowing its entries, so writing one out leaves no copy of them to wipe.
74#[derive(Serialize)]
75struct VaultFileRef<'a> {
76    format: &'a str,
77    version: u32,
78    exported_at: i64,
79    app_version: &'a str,
80    entries: &'a [Incoming],
81}
82
83/// The `.vault` file's contents without the encryption, for the plain JSON export.
84pub(super) fn plain_json(entries: &[Incoming]) -> Result<Zeroizing<Vec<u8>>, String> {
85    let file = VaultFileRef { format: FORMAT, version: VERSION, exported_at: now_ms(), app_version: env!("CARGO_PKG_VERSION"), entries };
86    serde_json::to_vec_pretty(&file).map(Zeroizing::new).map_err(|e| e.to_string())
87}
88
89fn passphrase_of(s: &str) -> SecretString {
90    SecretString::from(s.to_string())
91}
92
93// ── Passphrase suggestion ────────────────────────────────────────────────────
94
95/// Eight random words joined by hyphens: 64 bits, slowed down by scrypt.
96pub fn suggest_passphrase() -> Result<String, String> {
97    let mut bytes = [0u8; 8];
98    SystemRandom::new().fill(&mut bytes).map_err(|_| "the system's random source failed".to_string())?;
99    Ok(bytes.iter().map(|b| super::wordlist::WORDS[*b as usize]).collect::<Vec<_>>().join("-"))
100}
101
102// ── Export ───────────────────────────────────────────────────────────────────
103
104/// What an export reported.
105#[derive(Debug, Serialize, ts_rs::TS)]
106#[ts(export, export_to = "../../../frontend/types/rpc/")]
107pub struct ExportResult {
108    pub count: usize,
109    pub file_name: String,
110    /// The file holds linked entries only, and so no value. The dialog says "no value is in the file" only on this
111    /// word, never on what it asked for: a part of the app that does not know the option writes a whole export.
112    pub links_only: bool,
113}
114
115/// Writes the chosen entries (all when `ids` is `None`) to `path`, encrypted to
116/// `passphrase`.
117pub fn export(store: &Store, ids: Option<&[String]>, passphrase: &str, path: &Path) -> Result<ExportResult, String> {
118    export_of(store, ids, passphrase, path, false)
119}
120
121/// [`export`], of the linked entries only (`super::linked`): where each key lives, who reads it and when it last
122/// changed, to show on another machine. No value is in the file: a link holds none, and an entry that holds one is
123/// left out even when `ids` names it.
124pub fn export_links(store: &Store, ids: Option<&[String]>, passphrase: &str, path: &Path) -> Result<ExportResult, String> {
125    export_of(store, ids, passphrase, path, true)
126}
127
128fn export_of(store: &Store, ids: Option<&[String]>, passphrase: &str, path: &Path, links_only: bool) -> Result<ExportResult, String> {
129    if passphrase.chars().count() < MIN_PASSPHRASE {
130        return Err(format!("a passphrase is at least {MIN_PASSPHRASE} characters"));
131    }
132    let entries = if links_only { gather_links(store, ids)? } else { gather(store, ids)? };
133    let count = entries.len();
134    let file = VaultFile { format: FORMAT.into(), version: VERSION, exported_at: now_ms(), app_version: env!("CARGO_PKG_VERSION").into(), entries };
135    let plain = Zeroizing::new(serde_json::to_vec(&file).map_err(|e| e.to_string())?);
136    // `file` holds every value too: wipe them.
137    for mut e in file.entries {
138        for v in e.parts.values_mut() {
139            zeroize::Zeroize::zeroize(v);
140        }
141    }
142    let mut out = Vec::new();
143    let encryptor = age::Encryptor::with_user_passphrase(passphrase_of(passphrase));
144    let mut w = encryptor.wrap_output(&mut out).map_err(|e| format!("couldn't start encrypting: {e}"))?;
145    w.write_all(&plain).map_err(|e| format!("couldn't encrypt: {e}"))?;
146    w.finish().map_err(|e| format!("couldn't finish encrypting: {e}"))?;
147    write_atomically(path, &out)?;
148    let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
149    let what = if links_only { format!("{count} linked entries, no values") } else { format!("{count} entries") };
150    record(store, "", "", PERSON, "exported", &file_name, &what);
151    Ok(ExportResult { count, file_name, links_only })
152}
153
154/// The linked entries among the chosen ones (among all when `ids` is `None`), for a file that holds no value.
155fn gather_links(store: &Store, ids: Option<&[String]>) -> Result<Vec<Incoming>, String> {
156    let rows = store.vault_list().map_err(|e| e.to_string())?;
157    let links: Vec<String> = rows.into_iter().filter(|r| linked::is_linked_row(r) && ids.is_none_or(|ids| ids.contains(&r.id))).map(|r| r.id).collect();
158    if links.is_empty() {
159        return Err("there are no linked entries to export".into());
160    }
161    let entries = gather(store, Some(&links))?;
162    // A link holds no value. One that does is wrong (`verify` finds it), and this file promises none.
163    if let Some(label) = entries.iter().find(|e| !e.parts.is_empty()).map(|e| e.label.clone()) {
164        wipe(entries);
165        return Err(format!("the linked entry {label:?} holds a value, which a link never should: nothing was exported"));
166    }
167    Ok(entries)
168}
169
170/// The chosen entries (all when `ids` is `None`), opened: every part in the clear, for the caller to
171/// put in a file and wipe.
172pub(super) fn gather(store: &Store, ids: Option<&[String]>) -> Result<Vec<Incoming>, String> {
173    let rows = store.vault_list().map_err(|e| e.to_string())?;
174    let rows: Vec<VaultRow> = match ids {
175        Some(ids) => {
176            let wanted: std::collections::HashSet<&str> = ids.iter().map(String::as_str).collect();
177            rows.into_iter().filter(|r| wanted.contains(r.id.as_str())).collect()
178        }
179        None => rows,
180    };
181    if rows.is_empty() {
182        return Err("there is nothing to export".into());
183    }
184    let key = seal::key(false)?;
185    let mut entries = Vec::with_capacity(rows.len());
186    for row in &rows {
187        let parts = seal::open(&key, &row.id, &row.sealed)?;
188        entries.push(Incoming {
189            id: row.id.clone(),
190            kind: row.kind.clone(),
191            label: row.label.clone(),
192            fields: serde_json::from_str(&row.fields).unwrap_or_default(),
193            tags: serde_json::from_str(&row.tags).unwrap_or_default(),
194            parts: parts.0.clone(),
195            created_at: row.created_at,
196            updated_at: row.updated_at,
197        });
198    }
199    Ok(entries)
200}
201
202/// Wipes every part of `entries`.
203pub(super) fn wipe(entries: Vec<Incoming>) {
204    for mut e in entries {
205        for v in e.parts.values_mut() {
206            zeroize::Zeroize::zeroize(v);
207        }
208    }
209}
210
211/// The file appears whole or not at all: written beside it, then renamed.
212pub(super) fn write_atomically(path: &Path, bytes: &[u8]) -> Result<(), String> {
213    let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
214    let tmp = dir.join(format!(".{}.tmp", uuid::Uuid::new_v4().simple()));
215    std::fs::write(&tmp, bytes).map_err(|e| {
216        // A write that stopped part way (a full disk) leaves ciphertext beside the destination.
217        let _ = std::fs::remove_file(&tmp);
218        format!("couldn't write the file: {e}")
219    })?;
220    std::fs::rename(&tmp, path).map_err(|e| {
221        let _ = std::fs::remove_file(&tmp);
222        format!("couldn't save the file there: {e}")
223    })
224}
225
226// ── Import: inspect ──────────────────────────────────────────────────────────
227
228/// What `inspect` couldn't do yet.
229#[derive(Debug)]
230pub enum InspectError {
231    /// The file is encrypted and no passphrase was given.
232    NeedsPassphrase,
233    /// A CSV no reader knows: which column is which is the person's to say.
234    NeedsMapping(MappingNeeded),
235    Other(String),
236}
237
238impl From<String> for InspectError {
239    fn from(s: String) -> Self {
240        InspectError::Other(s)
241    }
242}
243
244struct Staged {
245    file_name: String,
246    entries: Vec<StagedEntry>,
247    at: Instant,
248}
249
250struct StagedEntry {
251    id: String,
252    kind: &'static kinds::Kind,
253    label: String,
254    fields: BTreeMap<String, String>,
255    tags: Vec<String>,
256    parts: Parts,
257    created_at: i64,
258    updated_at: i64,
259    /// The existing entry this one duplicates, if any.
260    duplicate_of: Option<String>,
261    /// A login with a site from a browser's export: it belongs to one browser profile, in that
262    /// profile's sign-in Vault, where the browser offers it from (spec §8).
263    browser_sign_in: bool,
264}
265
266fn staged() -> &'static Mutex<HashMap<String, Staged>> {
267    static STAGED: std::sync::OnceLock<Mutex<HashMap<String, Staged>>> = std::sync::OnceLock::new();
268    STAGED.get_or_init(Mutex::default)
269}
270
271#[derive(Debug, Serialize, ts_rs::TS)]
272#[ts(export, export_to = "../../../frontend/types/rpc/")]
273pub struct PreviewEntry {
274    pub label: String,
275    pub kind: String,
276    pub duplicate: bool,
277    /// A linked entry: it says where a key lives and brings no value.
278    pub linked: bool,
279}
280
281#[derive(Debug, Serialize, ts_rs::TS)]
282#[ts(export, export_to = "../../../frontend/types/rpc/")]
283pub struct PreviewSection {
284    pub section: VaultSection,
285    pub count: usize,
286    /// The first few entries: labels, never values.
287    pub first: Vec<PreviewEntry>,
288}
289
290#[derive(Debug, Serialize, ts_rs::TS)]
291#[ts(export, export_to = "../../../frontend/types/rpc/")]
292pub struct Skipped {
293    pub label: String,
294    pub reason: String,
295}
296
297#[derive(Debug, Serialize, ts_rs::TS)]
298#[ts(export, export_to = "../../../frontend/types/rpc/")]
299pub struct ImportPreview {
300    pub token: String,
301    pub file_name: String,
302    pub total: usize,
303    pub duplicates: usize,
304    /// How many of `duplicates` are linked entries: one is a duplicate by its kind and place, having no value.
305    pub duplicate_links: usize,
306    pub sections: Vec<PreviewSection>,
307    pub skipped: Vec<Skipped>,
308    /// What the file is, found from its contents.
309    pub source: Source,
310    pub source_label: String,
311    /// The file holds every secret in it unencrypted: the person is offered to delete it.
312    pub plaintext_file: bool,
313    /// How many logins a browser's export gave a site: they go to one browser profile's sign-in Vault
314    /// (`commit`'s `profile`), where the browser offers them; none for any other file.
315    pub browser_signins: usize,
316}
317
318/// How many entries of each section the preview lists.
319const PREVIEW_FIRST: usize = 5;
320
321/// What a duplicate is: the same place for a linked entry (it has no value to compare), the same site and
322/// username for a login, the same kind and main value for anything else.
323fn fingerprint(kind: &kinds::Kind, fields: &BTreeMap<String, String>, parts: &Parts) -> Option<String> {
324    if linked::is_linked(fields) {
325        let place = Link::of(fields)?;
326        // Each field on its own: a `#` or a `|` in a location must not make two places one.
327        return serde_json::to_string(&("link", kind.name, &place.kind, &place.location, &place.key, &place.region)).ok();
328    }
329    if kind.name == "login" {
330        let site = fields.get("site")?.trim().trim_end_matches('/').to_lowercase();
331        let user = fields.get("username").map(|u| u.trim().to_lowercase()).unwrap_or_default();
332        return Some(format!("login|{site}|{user}"));
333    }
334    Some(format!("{}|{}", kind.name, parts.get(kind.parts[0])?))
335}
336
337/// Reads `path`, decrypts it with `passphrase`, and stages it for `commit`.
338pub fn inspect(store: &Store, path: &Path, passphrase: Option<&str>) -> Result<ImportPreview, InspectError> {
339    inspect_with(store, path, passphrase, None)
340}
341
342/// [`inspect`], with the person's column choices for a CSV no reader recognises.
343pub fn inspect_with(store: &Store, path: &Path, passphrase: Option<&str>, mapping: Option<&Mapping>) -> Result<ImportPreview, InspectError> {
344    inspect_keyed(store, path, passphrase, mapping, None)
345}
346
347/// [`inspect_with`], and the key file of a KeePass database that has one.
348pub fn inspect_keyed(store: &Store, path: &Path, passphrase: Option<&str>, mapping: Option<&Mapping>, keyfile: Option<&[u8]>) -> Result<ImportPreview, InspectError> {
349    let meta = std::fs::metadata(path).map_err(|e| format!("couldn't read that file: {e}"))?;
350    if !meta.is_file() {
351        return Err("that isn't a file".to_string().into());
352    }
353    if meta.len() > MAX_FILE_BYTES {
354        return Err(format!("that file is over {} MiB, more than the Vault imports", MAX_FILE_BYTES / 1024 / 1024).into());
355    }
356    let mut head = Vec::new();
357    std::fs::File::open(path).and_then(|f| f.take(MAX_FILE_BYTES).read_to_end(&mut head)).map_err(|e| format!("couldn't read that file: {e}"))?;
358    let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
359    // An age file is a Vault export; anything else is another service's plaintext export.
360    let (source, incoming, mut skipped, plaintext_file) = if head.starts_with(AGE_MAGIC) {
361        let plain = decrypt(&head, passphrase)?;
362        let file: VaultFile = serde_json::from_slice(&plain).map_err(|_| "this isn't a Vault file: its contents aren't in the expected shape".to_string())?;
363        drop(plain);
364        if file.format != FORMAT {
365            return Err(format!("this isn't a Vault file (its format is {:?})", file.format).into());
366        }
367        if file.version > VERSION {
368            return Err(format!("this file was made by a newer AgentMux (format version {}); update AgentMux to import it", file.version).into());
369        }
370        (Source::Vault, file.entries, Vec::new(), false)
371    } else {
372        match import::read_keyed(&head, &file_name, mapping, passphrase, keyfile) {
373            Ok(i) => (i.source, i.entries, i.skipped.into_iter().map(|(label, reason)| Skipped { label, reason }).collect(), i.plaintext),
374            Err(ReadError::NeedsMapping(m)) => return Err(InspectError::NeedsMapping(m)),
375            Err(ReadError::NeedsPassphrase) => return Err(InspectError::NeedsPassphrase),
376            Err(ReadError::Other(e)) => return Err(e.into()),
377        }
378    };
379    drop(head);
380    if incoming.len() > MAX_ENTRIES {
381        return Err(format!("this file has more than {MAX_ENTRIES} entries, more than the Vault imports").into());
382    }
383    let existing = existing_fingerprints(store);
384    let mut entries = Vec::new();
385    for e in incoming {
386        let Some(kind) = kinds::kind(&e.kind) else {
387            skipped.push(Skipped { label: e.label, reason: format!("unknown kind {:?}", e.kind) });
388            continue;
389        };
390        let mut parts = Parts(e.parts);
391        parts.0.retain(|_, v| !v.is_empty());
392        let mut fields: BTreeMap<String, String> = e.fields.into_iter().map(|(k, v)| (k, v.trim().to_string())).filter(|(_, v)| !v.is_empty()).collect();
393        // Who a login is shared with is this computer's and the person's to say, never a file's.
394        fields.remove(super::shares::SHARED);
395        let settled = settle_incoming(kind, &mut fields, &mut parts).and_then(|()| validate(kind, &e.label, &fields, &e.tags, &parts));
396        if let Err(why) = settled {
397            skipped.push(Skipped { label: e.label, reason: why });
398            continue;
399        }
400        // A linked entry is the place it names and holds nothing (`validate` saw to both).
401        if !linked::is_linked(&fields) && parts.get(kind.parts[0]).is_none() {
402            skipped.push(Skipped { label: e.label, reason: format!("it has no {}", kind.parts[0]) });
403            continue;
404        }
405        let duplicate_of = fingerprint(kind, &fields, &parts).and_then(|f| existing.get(&f).cloned());
406        let browser_sign_in = source == Source::Chrome && kind.name == "login" && fields.contains_key(signins::SITE);
407        entries.push(StagedEntry {
408            id: e.id,
409            kind,
410            label: e.label.trim().to_string(),
411            fields,
412            tags: e.tags,
413            parts,
414            created_at: e.created_at,
415            updated_at: e.updated_at,
416            duplicate_of,
417            browser_sign_in,
418        });
419    }
420    let sections = preview_sections(&entries);
421    let preview = ImportPreview {
422        token: uuid::Uuid::new_v4().to_string(),
423        file_name: file_name.clone(),
424        total: entries.len(),
425        duplicates: entries.iter().filter(|e| e.duplicate_of.is_some()).count(),
426        duplicate_links: entries.iter().filter(|e| e.duplicate_of.is_some() && linked::is_linked(&e.fields)).count(),
427        sections,
428        skipped,
429        source,
430        source_label: source.label().to_string(),
431        plaintext_file,
432        browser_signins: entries.iter().filter(|e| e.browser_sign_in).count(),
433    };
434    let mut held = staged().lock().unwrap_or_else(|p| p.into_inner());
435    held.retain(|_, s| s.at.elapsed() < STAGED_TTL);
436    make_room(&mut held, stage_limit());
437    held.insert(preview.token.clone(), Staged { file_name, entries, at: Instant::now() });
438    Ok(preview)
439}
440
441/// What the preview lists of each section: how many, and the first few.
442fn preview_sections(entries: &[StagedEntry]) -> Vec<PreviewSection> {
443    let mut sections: Vec<PreviewSection> = Vec::new();
444    for e in entries {
445        let section = e.kind.section;
446        let slot = match sections.iter().position(|s| s.section == section) {
447            Some(i) => i,
448            None => {
449                sections.push(PreviewSection { section, count: 0, first: Vec::new() });
450                sections.len() - 1
451            }
452        };
453        sections[slot].count += 1;
454        if sections[slot].first.len() < PREVIEW_FIRST {
455            sections[slot].first.push(PreviewEntry { label: e.label.clone(), kind: e.kind.name.into(), duplicate: e.duplicate_of.is_some(), linked: linked::is_linked(&e.fields) });
456        }
457    }
458    sections
459}
460
461/// Decrypts an age file with a passphrase; the plaintext is wiped on drop.
462fn decrypt(bytes: &[u8], passphrase: Option<&str>) -> Result<Zeroizing<Vec<u8>>, InspectError> {
463    if !bytes.starts_with(AGE_MAGIC) {
464        return Err("this isn't a Vault file: it isn't an age-encrypted file".to_string().into());
465    }
466    let decryptor = age::Decryptor::new(bytes).map_err(|e| format!("this isn't a readable Vault file: {e}"))?;
467    if !decryptor.is_scrypt() {
468        return Err("this file isn't encrypted to a passphrase, so AgentMux can't open it".to_string().into());
469    }
470    let Some(passphrase) = passphrase.filter(|p| !p.is_empty()) else {
471        return Err(InspectError::NeedsPassphrase);
472    };
473    let mut identity = age::scrypt::Identity::new(passphrase_of(passphrase));
474    // §8.7: a file can't make the import hang on a huge work factor.
475    identity.set_max_work_factor(22);
476    let mut reader = decryptor.decrypt(std::iter::once(&identity as &dyn age::Identity)).map_err(|e| match e {
477        age::DecryptError::DecryptionFailed | age::DecryptError::NoMatchingKeys => "that passphrase didn't open the file".to_string(),
478        age::DecryptError::ExcessiveWork { .. } => "this file's key-stretching is too heavy for AgentMux to open safely".to_string(),
479        other => format!("couldn't decrypt the file: {other}"),
480    })?;
481    let mut plain = Zeroizing::new(Vec::new());
482    reader.by_ref().take(MAX_FILE_BYTES * 2).read_to_end(&mut plain).map_err(|_| "the file is damaged or was changed: it didn't decrypt cleanly".to_string())?;
483    Ok(plain)
484}
485
486/// The fingerprint of each existing entry, mapped to its id. Entries that can't
487/// be opened aren't compared.
488fn existing_fingerprints(store: &Store) -> HashMap<String, String> {
489    let mut out = HashMap::new();
490    let Ok(rows) = store.vault_list() else { return out };
491    if rows.is_empty() {
492        return out;
493    }
494    let Ok(key) = seal::key(false) else { return out };
495    for row in rows {
496        let (Some(kind), Ok(parts)) = (kinds::kind(&row.kind), seal::open(&key, &row.id, &row.sealed)) else { continue };
497        let fields: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
498        if let Some(f) = fingerprint(kind, &fields, &parts) {
499            out.insert(f, row.id);
500        }
501    }
502    out
503}
504
505// ── Import: commit ───────────────────────────────────────────────────────────
506
507/// What to do with an incoming entry that duplicates one already in the Vault.
508#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
509#[serde(rename_all = "snake_case")]
510pub enum Duplicates {
511    Skip,
512    Replace,
513    KeepBoth,
514}
515
516#[derive(Debug, Serialize, ts_rs::TS)]
517#[ts(export, export_to = "../../../frontend/types/rpc/")]
518pub struct ImportResult {
519    pub added: usize,
520    pub replaced: usize,
521    pub skipped: usize,
522}
523
524/// Writes a staged import: all of it or none of it, with every browser sign-in in Personal's.
525pub fn commit(store: &Store, token: &str, duplicates: Duplicates, vault_id: &str) -> Result<ImportResult, String> {
526    commit_for(store, token, duplicates, vault_id, None)
527}
528
529/// [`commit`], with the browser profile the logins a browser's export gave a site belong to.
530///
531/// `profile` (`personal` or `profile:<id>`, Personal when left out) is the browser profile the logins a
532/// browser's export gave a site belong to: they go to that profile's sign-in Vault, not `vault_id`.
533pub fn commit_for(store: &Store, token: &str, duplicates: Duplicates, vault_id: &str, profile: Option<&str>) -> Result<ImportResult, String> {
534    let profile = profile.map(str::trim).filter(|p| !p.is_empty()).unwrap_or(signins::PERSONAL);
535    if !signins::is_profile(profile) {
536        return Err(format!("profile is personal or profile:<id>, not {profile:?}"));
537    }
538    let taken = {
539        let mut held = staged().lock().unwrap_or_else(|p| p.into_inner());
540        held.remove(token)
541    };
542    let Some(staged_import) = taken.filter(|s| s.at.elapsed() < STAGED_TTL) else {
543        return Err("this import has expired: choose the file again".into());
544    };
545    match write_staged(store, &staged_import, duplicates, vault_id, profile) {
546        Ok(result) => Ok(result),
547        Err(e) => {
548            // Nothing was written: the import stays staged, so Import can be pressed again.
549            staged().lock().unwrap_or_else(|p| p.into_inner()).insert(token.to_string(), staged_import);
550            Err(e)
551        }
552    }
553}
554
555/// An incoming entry's expiry date and, for a card, its parts and plain fields, made what the Vault keeps.
556fn settle_incoming(kind: &kinds::Kind, fields: &mut BTreeMap<String, String>, parts: &mut Parts) -> Result<(), String> {
557    super::expiry::settle_imported(kind, fields);
558    super::card::settle(kind.name, fields, parts)
559}
560
561/// Writes `incoming`, all of it or none of it.
562fn write_staged(store: &Store, incoming: &Staged, duplicates: Duplicates, vault_id: &str, profile: &str) -> Result<ImportResult, String> {
563    store.vault_info(vault_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no Vault {vault_id}"))?;
564    let key = seal::key(store.vault_count().map_err(|e| e.to_string())? == 0)?;
565    let now = now_ms();
566    let mut inserts: Vec<VaultRow> = Vec::new();
567    let mut updates: Vec<VaultRow> = Vec::new();
568    let mut skipped = 0;
569    let mut taken: std::collections::HashSet<String> = std::collections::HashSet::new();
570    for e in &incoming.entries {
571        if e.duplicate_of.is_some() && duplicates == Duplicates::Skip {
572            skipped += 1;
573            continue;
574        }
575        let created = if e.created_at > 0 { e.created_at } else { now };
576        let tags = serde_json::to_string(&e.tags).map_err(|err| err.to_string())?;
577        if let (Some(existing), Duplicates::Replace) = (&e.duplicate_of, duplicates) {
578            let current = store.vault_get(existing).map_err(|err| err.to_string())?;
579            let mut fields = e.fields.clone();
580            if e.browser_sign_in {
581                // A sign-in the browser already saved keeps its profile; one the Vault had gets the chosen one.
582                let kept = current.as_ref().and_then(|row| signins::fields_of(row).get(signins::PROFILE).cloned());
583                fields.insert(signins::PROFILE.to_string(), kept.unwrap_or_else(|| profile.to_string()));
584            }
585            if let Some(row) = &current {
586                super::source_link::carry_over(&mut fields, row);
587                // A replaced login keeps who it is shared with.
588                if let Some(shared) = signins::fields_of(row).get(super::shares::SHARED) {
589                    fields.insert(super::shares::SHARED.to_string(), shared.clone());
590                }
591            }
592            updates.push(VaultRow {
593                id: existing.clone(),
594                kind: e.kind.name.into(),
595                label: e.label.clone(),
596                fields: serde_json::to_string(&fields).map_err(|err| err.to_string())?,
597                tags,
598                sealed: seal::seal(&key, existing, &e.parts)?,
599                created_at: created,
600                updated_at: now,
601                last_used_at: 0,
602                // A replaced entry stays in the Vault it is in.
603                vault_id: current.map_or_else(|| vault_id.to_string(), |row| row.vault_id),
604            });
605            continue;
606        }
607        let mut fields = e.fields.clone();
608        let mut entry_vault = vault_id.to_string();
609        if e.browser_sign_in {
610            fields.insert(signins::PROFILE.to_string(), profile.to_string());
611            entry_vault = signins::vault_for(store, profile)?;
612        }
613        let fields = serde_json::to_string(&fields).map_err(|err| err.to_string())?;
614        // The file's own id when it is free, so an agent's reference survives
615        // a round trip; else a new one.
616        let wanted = e.id.trim();
617        let id = if !wanted.is_empty()
618            && wanted.len() <= 48
619            && wanted.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
620            && !taken.contains(wanted)
621            && store.vault_get(wanted).map_err(|err| err.to_string())?.is_none()
622        {
623            wanted.to_string()
624        } else {
625            let base = new_id(store, e.kind.name, &e.label)?;
626            let mut id = base.clone();
627            let mut n = 2;
628            while taken.contains(&id) || store.vault_get(&id).map_err(|err| err.to_string())?.is_some() {
629                id = format!("{base}-{n}");
630                n += 1;
631            }
632            id
633        };
634        taken.insert(id.clone());
635        inserts.push(VaultRow {
636            sealed: seal::seal(&key, &id, &e.parts)?,
637            id,
638            kind: e.kind.name.into(),
639            label: e.label.clone(),
640            fields,
641            tags,
642            created_at: created,
643            updated_at: now,
644            last_used_at: 0,
645            vault_id: entry_vault,
646        });
647    }
648    store.vault_write_many(&inserts, &updates).map_err(|e| e.to_string())?;
649    let result = ImportResult { added: inserts.len(), replaced: updates.len(), skipped };
650    record(store, "", "", PERSON, "imported", &incoming.file_name, &format!("{} added, {} replaced, {} skipped", result.added, result.replaced, result.skipped));
651    Ok(result)
652}
653
654/// Drops a staged import (the person cancelled).
655pub fn cancel(token: &str) {
656    staged().lock().unwrap_or_else(|p| p.into_inner()).remove(token);
657}
658
659#[cfg(test)]
660#[path = "transfer_stage_tests.rs"]
661mod stage_tests;