bwx-cli 2.3.0

Unofficial Bitwarden CLI with first-class macOS support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use std::fmt::Write as _;

use super::auth::unlock;
use super::cipher::DecryptedData;
use super::find::{find_entry, Needle};
use super::util::{
    format_rfc3339, load_db, parse_editor, save_db, HELP_NOTES, HELP_PW,
};
use crate::bin_error::{self, ContextExt as _};

/// Stages plaintexts into a single `EncryptBatch` IPC, then exposes
/// per-index reads. Mirrors the decrypt-side `Batcher` in
/// `commands::decrypt`; kept private to crud since that's the only
/// call site that batch-encrypts today.
struct EncryptBatcher {
    items: Vec<bwx::protocol::EncryptItem>,
    results: Vec<bin_error::Result<String>>,
}

impl EncryptBatcher {
    fn new() -> Self {
        Self {
            items: Vec::new(),
            results: Vec::new(),
        }
    }

    fn push(&mut self, plaintext: &str, org_id: Option<&str>) -> usize {
        self.items.push(bwx::protocol::EncryptItem {
            plaintext: plaintext.to_string(),
            org_id: org_id.map(std::string::ToString::to_string),
        });
        self.items.len() - 1
    }

    fn push_opt(
        &mut self,
        plaintext: Option<&str>,
        org_id: Option<&str>,
    ) -> Option<usize> {
        plaintext.map(|p| self.push(p, org_id))
    }

    fn run(&mut self) -> bin_error::Result<()> {
        if !self.items.is_empty() {
            let items = std::mem::take(&mut self.items);
            self.results = crate::actions::encrypt_batch(items)?;
        }
        Ok(())
    }

    /// Read a slot whose encrypt failure should propagate as an error.
    fn take(&self, idx: usize) -> bin_error::Result<String> {
        match &self.results[idx] {
            Ok(s) => Ok(s.clone()),
            Err(e) => Err(crate::bin_error::Error::msg(e.to_string())),
        }
    }

    fn take_opt(
        &self,
        idx: Option<usize>,
    ) -> bin_error::Result<Option<String>> {
        idx.map(|i| self.take(i)).transpose()
    }
}

pub fn add(
    name: &str,
    username: Option<&str>,
    uris: &[(String, Option<bwx::api::UriMatchType>)],
    folder: Option<&str>,
) -> bin_error::Result<()> {
    unlock()?;

    let mut db = load_db()?;
    // unwrap is safe here because the call to unlock above is guaranteed to
    // populate these or error
    let mut access_token = db.access_token.as_ref().unwrap().clone();
    let refresh_token = db.refresh_token.as_ref().unwrap();

    let contents = bwx::edit::edit("", HELP_PW)?;
    let (password, notes) = parse_editor(&contents);

    let mut b = EncryptBatcher::new();
    let name_idx = b.push(name, None);
    let username_idx = b.push_opt(username, None);
    let password_idx = b.push_opt(password.as_deref(), None);
    let notes_idx = b.push_opt(notes.as_deref(), None);
    let uri_idxs: Vec<(usize, Option<bwx::api::UriMatchType>)> = uris
        .iter()
        .map(|(uri, match_type)| (b.push(uri, None), *match_type))
        .collect();
    b.run()?;

    let name = b.take(name_idx)?;
    let username = b.take_opt(username_idx)?;
    let password = b.take_opt(password_idx)?;
    let notes = b.take_opt(notes_idx)?;
    let uris: Vec<_> = uri_idxs
        .into_iter()
        .map(|(idx, match_type)| {
            Ok(bwx::db::Uri {
                uri: b.take(idx)?,
                match_type,
            })
        })
        .collect::<bin_error::Result<_>>()?;

    let mut folder_id = None;
    if let Some(folder_name) = folder {
        let (new_access_token, folders) =
            bwx::actions::list_folders(&access_token, refresh_token)?;
        if let Some(new_access_token) = new_access_token {
            access_token.clone_from(&new_access_token);
            db.access_token = Some(new_access_token);
            save_db(&db)?;
        }

        let items: Vec<_> = folders
            .iter()
            .map(|(_, name)| bwx::protocol::DecryptItem {
                cipherstring: name.clone(),
                entry_key: None,
                org_id: None,
            })
            .collect();
        let names = crate::actions::decrypt_batch(items)?;
        let folders: Vec<(String, String)> = folders
            .into_iter()
            .zip(names)
            .map(|((id, _), name)| Ok((id, name?)))
            .collect::<bin_error::Result<_>>()?;

        for (id, name) in folders {
            if name == folder_name {
                folder_id = Some(id);
            }
        }
        if folder_id.is_none() {
            let (new_access_token, id) = bwx::actions::create_folder(
                &access_token,
                refresh_token,
                &crate::actions::encrypt(folder_name, None)?,
            )?;
            if let Some(new_access_token) = new_access_token {
                access_token.clone_from(&new_access_token);
                db.access_token = Some(new_access_token);
                save_db(&db)?;
            }
            folder_id = Some(id);
        }
    }

    if let (Some(access_token), ()) = bwx::actions::add(
        &access_token,
        refresh_token,
        &name,
        &bwx::db::EntryData::Login {
            username,
            password,
            uris,
            totp: None,
        },
        notes.as_deref(),
        folder_id.as_deref(),
    )? {
        db.access_token = Some(access_token);
        save_db(&db)?;
    }

    crate::actions::sync()?;

    Ok(())
}

pub fn generate(
    name: Option<&str>,
    username: Option<&str>,
    uris: &[(String, Option<bwx::api::UriMatchType>)],
    folder: Option<&str>,
    len: usize,
    ty: bwx::pwgen::Type,
) -> bin_error::Result<()> {
    let password = bwx::pwgen::pwgen(ty, len);
    // pwgen guarantees valid UTF-8 (ASCII alphabet + space-joined
    // diceware words), so this unwrap can't fail.
    let password_str = std::str::from_utf8(password.password()).unwrap();
    println!("{password_str}");

    if let Some(name) = name {
        unlock()?;

        let mut db = load_db()?;
        // unwrap is safe here because the call to unlock above is guaranteed
        // to populate these or error
        let mut access_token = db.access_token.as_ref().unwrap().clone();
        let refresh_token = db.refresh_token.as_ref().unwrap();

        let mut b = EncryptBatcher::new();
        let name_idx = b.push(name, None);
        let username_idx = b.push_opt(username, None);
        let password_idx = b.push(password_str, None);
        let uri_idxs: Vec<(usize, Option<bwx::api::UriMatchType>)> = uris
            .iter()
            .map(|(uri, match_type)| (b.push(uri, None), *match_type))
            .collect();
        b.run()?;

        let name = b.take(name_idx)?;
        let username = b.take_opt(username_idx)?;
        let password = b.take(password_idx)?;
        let uris: Vec<_> = uri_idxs
            .into_iter()
            .map(|(idx, match_type)| {
                Ok(bwx::db::Uri {
                    uri: b.take(idx)?,
                    match_type,
                })
            })
            .collect::<bin_error::Result<_>>()?;

        let mut folder_id = None;
        if let Some(folder_name) = folder {
            let (new_access_token, folders) =
                bwx::actions::list_folders(&access_token, refresh_token)?;
            if let Some(new_access_token) = new_access_token {
                access_token.clone_from(&new_access_token);
                db.access_token = Some(new_access_token);
                save_db(&db)?;
            }

            let folders: Vec<(String, String)> = folders
                .iter()
                .cloned()
                .map(|(id, name)| {
                    Ok((id, crate::actions::decrypt(&name, None, None)?))
                })
                .collect::<bin_error::Result<_>>()?;

            for (id, name) in folders {
                if name == folder_name {
                    folder_id = Some(id);
                }
            }
            if folder_id.is_none() {
                let (new_access_token, id) = bwx::actions::create_folder(
                    &access_token,
                    refresh_token,
                    &crate::actions::encrypt(folder_name, None)?,
                )?;
                if let Some(new_access_token) = new_access_token {
                    access_token.clone_from(&new_access_token);
                    db.access_token = Some(new_access_token);
                    save_db(&db)?;
                }
                folder_id = Some(id);
            }
        }

        if let (Some(access_token), ()) = bwx::actions::add(
            &access_token,
            refresh_token,
            &name,
            &bwx::db::EntryData::Login {
                username,
                password: Some(password),
                uris,
                totp: None,
            },
            None,
            folder_id.as_deref(),
        )? {
            db.access_token = Some(access_token);
            save_db(&db)?;
        }

        crate::actions::sync()?;
    }

    Ok(())
}

pub fn edit(
    name: Needle,
    username: Option<&str>,
    folder: Option<&str>,
    ignore_case: bool,
) -> bin_error::Result<()> {
    unlock()?;

    let mut db = load_db()?;
    let access_token = db.access_token.as_ref().unwrap();
    let refresh_token = db.refresh_token.as_ref().unwrap();

    let desc = format!(
        "{}{}",
        username.map_or_else(String::new, |s| format!("{s}@")),
        name
    );

    let (entry, decrypted) =
        find_entry(&db, name, username, folder, ignore_case)
            .with_context(|| format!("couldn't find entry for '{desc}'"))?;

    let (data, fields, notes, history) = match &decrypted.data {
        DecryptedData::Login { password, .. } => {
            let mut contents =
                format!("{}\n", password.as_deref().unwrap_or(""));
            if let Some(notes) = decrypted.notes {
                write!(contents, "\n{notes}\n").unwrap();
            }

            let contents = bwx::edit::edit(&contents, HELP_PW)?;
            let (password, notes) = parse_editor(&contents);

            let mut b = EncryptBatcher::new();
            let password_idx =
                b.push_opt(password.as_deref(), entry.org_id.as_deref());
            let notes_idx =
                b.push_opt(notes.as_deref(), entry.org_id.as_deref());
            b.run()?;
            let password = b.take_opt(password_idx)?;
            let notes = b.take_opt(notes_idx)?;
            let mut history = entry.history.clone();
            let bwx::db::EntryData::Login {
                username: entry_username,
                password: entry_password,
                uris: entry_uris,
                totp: entry_totp,
            } = &entry.data
            else {
                unreachable!();
            };

            if let Some(prev_password) = entry_password.clone() {
                let new_history_entry = bwx::db::HistoryEntry {
                    last_used_date: format_rfc3339(
                        std::time::SystemTime::now(),
                    ),
                    password: prev_password,
                };
                history.insert(0, new_history_entry);
            }

            let data = bwx::db::EntryData::Login {
                username: entry_username.clone(),
                password,
                uris: entry_uris.clone(),
                totp: entry_totp.clone(),
            };
            (data, entry.fields, notes, history)
        }
        DecryptedData::SecureNote => {
            let data = bwx::db::EntryData::SecureNote {};

            let editor_content = decrypted.notes.map_or_else(
                || "\n".to_string(),
                |notes| format!("{notes}\n"),
            );
            let contents = bwx::edit::edit(&editor_content, HELP_NOTES)?;

            // prepend blank line to be parsed as pw by `parse_editor`
            let (_, notes) = parse_editor(&format!("\n{contents}\n"));

            let notes = notes
                .map(|notes| {
                    crate::actions::encrypt(&notes, entry.org_id.as_deref())
                })
                .transpose()?;

            (data, entry.fields, notes, entry.history)
        }
        _ => {
            return Err(crate::bin_error::err!(
                "modifications are only supported for login and note entries"
            ));
        }
    };

    if let (Some(access_token), ()) = bwx::actions::edit(
        access_token,
        refresh_token,
        &entry.id,
        entry.org_id.as_deref(),
        &entry.name,
        &data,
        &fields,
        notes.as_deref(),
        entry.folder_id.as_deref(),
        &history,
    )? {
        db.access_token = Some(access_token);
        save_db(&db)?;
    }

    crate::actions::sync()?;
    Ok(())
}

pub fn remove(
    name: Needle,
    username: Option<&str>,
    folder: Option<&str>,
    ignore_case: bool,
) -> bin_error::Result<()> {
    unlock()?;

    let mut db = load_db()?;
    let access_token = db.access_token.as_ref().unwrap();
    let refresh_token = db.refresh_token.as_ref().unwrap();

    let desc = format!(
        "{}{}",
        username.map_or_else(String::new, |s| format!("{s}@")),
        name
    );

    let (entry, _) = find_entry(&db, name, username, folder, ignore_case)
        .with_context(|| format!("couldn't find entry for '{desc}'"))?;

    if let (Some(access_token), ()) =
        bwx::actions::remove(access_token, refresh_token, &entry.id)?
    {
        db.access_token = Some(access_token);
        save_db(&db)?;
    }

    crate::actions::sync()?;

    Ok(())
}