agentmux_srv_core/backend/vault/import/
bitwarden.rs1use serde::Deserialize;
10
11use super::bitwarden_encrypted;
12use super::{Imported, Incoming, ReadError, Source, MAX_ITEMS};
13
14fn list<'de, D, T>(d: D) -> Result<Vec<T>, D::Error>
16where
17 D: serde::Deserializer<'de>,
18 T: Deserialize<'de>,
19{
20 Ok(Option::<Vec<T>>::deserialize(d)?.unwrap_or_default())
21}
22
23#[derive(Deserialize)]
24struct Export {
25 #[serde(default)]
26 encrypted: bool,
27 #[serde(default, deserialize_with = "list")]
28 folders: Vec<Folder>,
29 #[serde(default, deserialize_with = "list")]
30 items: Vec<Item>,
31}
32
33#[derive(Deserialize)]
34struct Folder {
35 id: Option<String>,
36 name: Option<String>,
37}
38
39#[derive(Deserialize, Default)]
40#[serde(rename_all = "camelCase")]
41struct Item {
42 #[serde(rename = "type")]
43 kind: Option<u8>,
44 name: Option<String>,
45 notes: Option<String>,
46 folder_id: Option<String>,
47 login: Option<Login>,
48 card: Option<Card>,
49 identity: Option<Identity>,
50 #[serde(default, deserialize_with = "list")]
51 fields: Vec<Custom>,
52}
53
54#[derive(Deserialize, Default)]
55struct Login {
56 username: Option<String>,
57 password: Option<String>,
58 totp: Option<String>,
59 #[serde(default, deserialize_with = "list")]
60 uris: Vec<Uri>,
61}
62
63#[derive(Deserialize)]
64struct Uri {
65 uri: Option<String>,
66}
67
68#[derive(Deserialize, Default)]
69#[serde(rename_all = "camelCase")]
70struct Card {
71 cardholder_name: Option<String>,
72 number: Option<String>,
73 exp_month: Option<String>,
74 exp_year: Option<String>,
75 code: Option<String>,
76}
77
78#[derive(Deserialize, Default)]
79#[serde(rename_all = "camelCase")]
80struct Identity {
81 ssn: Option<String>,
82 passport_number: Option<String>,
83 license_number: Option<String>,
84 first_name: Option<String>,
85 last_name: Option<String>,
86}
87
88#[derive(Deserialize)]
89struct Custom {
90 name: Option<String>,
91 value: Option<String>,
92}
93
94fn present(v: &Option<String>) -> Option<&str> {
95 v.as_deref().map(str::trim).filter(|s| !s.is_empty())
96}
97
98fn expiry(month: &Option<String>, year: &Option<String>) -> Option<String> {
100 let (m, y) = (present(month)?, present(year)?);
101 let m: u32 = m.parse().ok().filter(|m| (1..=12).contains(m))?;
102 Some(format!("{m:02}/{y}"))
103}
104
105pub fn read(text: &str, passphrase: Option<&str>) -> Result<Imported, ReadError> {
107 let export: Export = serde_json::from_str(text).map_err(|_| ReadError::from("this looks like JSON but isn't a Bitwarden export"))?;
108 if export.encrypted {
109 let protected: bitwarden_encrypted::Protected = serde_json::from_str(text).map_err(|_| ReadError::from("this looks like a Bitwarden export but isn't one"))?;
110 if !protected.password_protected {
111 return Err("this Bitwarden export is encrypted with the account's own key, which only Bitwarden can open: export it again unencrypted, or password-protected".into());
112 }
113 let inside = bitwarden_encrypted::open(&protected, passphrase.unwrap_or(""))?;
116 let imported = read_plain(&inside).map(|i| Imported { plaintext: false, ..i });
117 drop(inside);
118 return imported;
119 }
120 read_plain(text)
121}
122
123fn read_plain(text: &str) -> Result<Imported, ReadError> {
124 let export: Export = serde_json::from_str(text).map_err(|_| ReadError::from("this looks like JSON but isn't a Bitwarden export"))?;
125 if export.encrypted {
126 return Err("this Bitwarden export is encrypted inside an encrypted export, which isn't a file Bitwarden writes".into());
127 }
128 if export.items.is_empty() && export.folders.is_empty() {
129 return Err("this JSON has no items: it isn't a Bitwarden export".into());
130 }
131 if export.items.len() > MAX_ITEMS {
132 return Err(format!("this file has more than {MAX_ITEMS} items, more than the Vault imports").into());
133 }
134 let folder_name = |id: &Option<String>| -> Option<String> {
135 let id = id.as_deref()?;
136 export.folders.iter().find(|f| f.id.as_deref() == Some(id)).and_then(|f| f.name.clone())
137 };
138 let mut entries: Vec<Incoming> = Vec::new();
139 let mut skipped: Vec<(String, String)> = Vec::new();
140 for item in &export.items {
141 let label = present(&item.name).unwrap_or("(unnamed)").to_string();
142 let tag = folder_name(&item.folder_id).unwrap_or_default();
143 let mut made: Vec<Incoming> = Vec::new();
144 match item.kind {
145 Some(1) => {
146 let l = item.login.as_ref();
147 let password = l.and_then(|l| l.password.as_deref()).filter(|p| !p.is_empty());
149 match password {
150 Some(password) => {
151 let mut e = Incoming::new("login", &label).part("password", password);
152 if let Some(totp) = l.and_then(|l| present(&l.totp)) {
153 e = e.part("totp", totp);
154 }
155 if let Some(l) = l {
156 e = e.field("username", present(&l.username).unwrap_or("")).field("site", l.uris.iter().find_map(|u| present(&u.uri)).unwrap_or(""));
157 }
158 made.push(e);
159 }
160 None => skipped.push((label.clone(), "it has no password".to_string())),
161 }
162 }
163 Some(2) => match present(&item.notes) {
164 Some(text) => made.push(Incoming::new("note", &label).part("text", text)),
165 None => skipped.push((label.clone(), "the note is empty".to_string())),
166 },
167 Some(3) => {
168 let c = item.card.as_ref();
169 match c.and_then(|c| present(&c.number)) {
170 Some(number) => {
171 let c = c.unwrap();
172 let mut e = Incoming::new("card", &label).part("number", number);
173 if let Some(x) = expiry(&c.exp_month, &c.exp_year) {
174 e = e.part("expiry", &x);
175 }
176 if let Some(cvc) = present(&c.code) {
177 e = e.part("cvc", cvc);
178 }
179 if let Some(n) = present(&c.cardholder_name) {
180 e = e.part("name", n);
181 }
182 made.push(e);
183 }
184 None => skipped.push((label.clone(), "the card has no number".to_string())),
185 }
186 }
187 Some(4) => {
188 let id = item.identity.as_ref();
189 let owner = id.map(|i| [present(&i.first_name), present(&i.last_name)].into_iter().flatten().collect::<Vec<_>>().join(" ")).unwrap_or_default();
190 for (kind, what, value) in [
191 ("ssn", "Social Security number", id.and_then(|i| present(&i.ssn))),
192 ("passport", "passport", id.and_then(|i| present(&i.passport_number))),
193 ("drivers-licence", "driver's licence", id.and_then(|i| present(&i.license_number))),
194 ] {
195 if let Some(v) = value {
196 made.push(Incoming::new(kind, &format!("{label} ({what})")).part("value", v).field("owner", &owner));
197 }
198 }
199 if made.is_empty() {
200 skipped.push((label.clone(), "the identity holds no Social Security, passport or licence number".to_string()));
201 }
202 }
203 other => skipped.push((label.clone(), format!("an item of type {other:?} (a key or other item) can't be imported"))),
204 }
205 let mut extra = String::new();
208 if item.kind != Some(2) {
209 if let Some(n) = present(&item.notes) {
210 extra.push_str(n);
211 }
212 }
213 for f in &item.fields {
214 if let (Some(n), Some(v)) = (present(&f.name), present(&f.value)) {
215 if !extra.is_empty() {
216 extra.push('\n');
217 }
218 extra.push_str(&format!("{n}: {v}"));
219 }
220 }
221 if !made.is_empty() && !extra.is_empty() {
222 made.push(Incoming::new("note", &format!("{label} (notes)")).part("text", &extra));
223 }
224 for e in made {
225 entries.push(e.tag(&tag));
226 }
227 }
228 Ok(Imported { source: Source::Bitwarden, entries, skipped, plaintext: true })
229}