agentmux_srv_core/backend/vault/
plain_export.rs1use std::io::Write as _;
20use std::path::Path;
21
22use zeroize::Zeroizing;
23
24use super::import::Incoming;
25use super::kdbx_names::{self, COMPANIONS, DETAILS};
26use super::transfer::{gather, plain_json, wipe, ExportResult};
27use super::{record, PERSON};
28use crate::backend::storage::store::Store;
29
30const HEADER: [&str; 11] = ["folder", "favorite", "type", "name", "notes", "fields", "reprompt", "login_uri", "login_username", "login_password", "login_totp"];
32
33pub fn export(store: &Store, ids: Option<&[String]>, format: &str, path: &Path) -> Result<ExportResult, String> {
35 let json = match format {
36 "csv" => false,
37 "json" => true,
38 other => return Err(format!("unknown plain export format {other:?}")),
39 };
40 let entries = gather(store, ids)?;
41 let count = entries.len();
42 let bytes = if json { plain_json(&entries) } else { csv_bytes(&entries) };
43 wipe(entries);
44 write_private(path, &bytes?)?;
45 let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
46 record(store, "", "", PERSON, "exported", &file_name, &format!("{count} entries, unencrypted {}", format.to_uppercase()));
47 Ok(ExportResult { count, file_name, links_only: false })
48}
49
50pub(super) fn csv_bytes(entries: &[Incoming]) -> Result<Zeroizing<Vec<u8>>, String> {
52 let mut out = Zeroizing::new(Vec::new());
53 {
54 let mut w = csv::WriterBuilder::new().terminator(csv::Terminator::CRLF).from_writer(&mut *out);
55 w.write_record(HEADER).map_err(|e| e.to_string())?;
56 for e in entries {
57 let row = row(e);
58 let result = w.write_record(row.iter().map(|c| c.as_str()));
59 result.map_err(|e| format!("couldn't write the CSV: {e}"))?;
60 }
61 w.flush().map_err(|e| e.to_string())?;
62 }
63 Ok(out)
64}
65
66fn row(e: &Incoming) -> Vec<Zeroizing<String>> {
68 let part = |name: &str| e.parts.get(name).map(String::as_str).unwrap_or("");
69 let field = |name: &str| e.fields.get(name).map(String::as_str).unwrap_or("");
70 let z = |s: &str| Zeroizing::new(s.to_string());
71 let folder = z(e.tags.first().map(String::as_str).unwrap_or(""));
72 if e.kind == "login" {
73 let mut notes = field("notes").to_string();
74 for (name, value) in &e.parts {
76 if !matches!(name.as_str(), "password" | "totp") && !value.is_empty() {
77 notes = format!("{name}: {value}\n{notes}");
78 }
79 }
80 return vec![folder, z("0"), z("login"), z(&e.label), Zeroizing::new(notes), z(""), z("0"), z(field("site")), z(field("username")), z(part("password")), z(part("totp"))];
81 }
82 vec![folder, z("0"), z("note"), z(&e.label), Zeroizing::new(note_text(e)), z(""), z("0"), z(""), z(""), z(""), z("")]
83}
84
85fn note_text(e: &Incoming) -> String {
88 if e.kind == "note" {
89 return e.parts.get("text").cloned().unwrap_or_default();
90 }
91 let mut lines: Vec<String> = Vec::new();
92 let mut used: Vec<&str> = Vec::new();
93 let mut add = |title: &str, value: &str| {
94 if !value.is_empty() {
95 lines.push(format!("{title}: {value}"));
96 }
97 };
98 if let Some(p) = kdbx_names::primary_for(&e.kind) {
99 add(p.title, e.parts.get(p.part).map(String::as_str).unwrap_or(""));
100 used.push(p.part);
101 }
102 for c in COMPANIONS.iter().filter(|c| c.kind == e.kind) {
103 add(c.title, e.parts.get(c.part).map(String::as_str).unwrap_or(""));
104 used.push(c.part);
105 }
106 for d in DETAILS {
107 add(d.title, e.fields.get(d.name).map(String::as_str).unwrap_or(""));
108 }
109 for (name, value) in &e.parts {
111 if !used.contains(&name.as_str()) {
112 add(name, value);
113 }
114 }
115 let mut text = lines.join("\n");
116 if let Some(notes) = e.fields.get("notes").filter(|n| !n.is_empty()) {
117 if !text.is_empty() {
118 text.push_str("\n\n");
119 }
120 text.push_str(notes);
121 }
122 text
123}
124
125fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
128 let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
129 let tmp = dir.join(format!(".{}.tmp", uuid::Uuid::new_v4().simple()));
130 let mut options = std::fs::OpenOptions::new();
131 options.write(true).create_new(true);
132 #[cfg(unix)]
133 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
134 let written = options.open(&tmp).and_then(|mut f| f.write_all(bytes).and_then(|_| f.sync_all()));
135 if let Err(e) = written {
136 let _ = std::fs::remove_file(&tmp);
138 return Err(format!("couldn't write the file: {e}"));
139 }
140 std::fs::rename(&tmp, path).map_err(|e| {
141 let _ = std::fs::remove_file(&tmp);
142 format!("couldn't save the file there: {e}")
143 })
144}
145
146#[cfg(test)]
147#[path = "plain_export_tests.rs"]
148mod tests;