sefy 0.1.2

An inconspicuous encrypted store for notes, credentials and files
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! What each subcommand does once the vault is open.

use crate::cli::{AddKind, EditArgs, Field, FindArgs, GetArgs, ListArgs};
use crate::output;
use crate::session;
use anyhow::{bail, Context, Result};
use sefy_core::{Credential, NewItem, Payload, Query, Vault};
use std::io::Read;
use std::path::{Path, PathBuf};

/// Creates a vault, refusing to touch a file that already exists.
pub fn init(path: &Path, password_env: Option<&str>) -> Result<()> {
    if path.exists() {
        bail!("{} already exists", path.display());
    }
    let password = session::new_password(password_env)?;
    Vault::create(path, password.as_bytes())?;
    println!("created {}", path.display());
    Ok(())
}

/// Adds an item and saves the vault.
pub fn add(vault: &mut Vault, kind: AddKind) -> Result<()> {
    let (item, description) = match kind {
        AddKind::Note {
            title,
            text,
            editor,
            tag,
        } => {
            let text = match text {
                Some(text) => text,
                None if editor => crate::editor::edit("")?,
                None => read_stdin().context("cannot read the note text from stdin")?,
            };
            (
                NewItem::new(title.clone(), Payload::Note { text }).with_tags(tag),
                title,
            )
        }
        AddKind::Credential {
            title,
            login,
            url,
            totp,
            notes,
            item_password_env,
            tag,
        } => {
            // Only this item's own variable is consulted: falling back to
            // --password-env would silently store the master password as the
            // account's password.
            let password =
                session::secret("Password for this item: ", item_password_env.as_deref())?;
            (
                NewItem::new(
                    title.clone(),
                    Payload::Credential(Credential {
                        login,
                        password,
                        url,
                        totp,
                        notes,
                    }),
                )
                .with_tags(tag),
                title,
            )
        }
        AddKind::File { path, title, tag } => {
            let bytes =
                std::fs::read(&path).with_context(|| format!("cannot read {}", path.display()))?;
            let filename = path
                .file_name()
                .map(|name| name.to_string_lossy().into_owned())
                .unwrap_or_else(|| "file".to_owned());
            let title = title.unwrap_or_else(|| filename.clone());
            (
                NewItem::new(title.clone(), Payload::File { filename, bytes }).with_tags(tag),
                title,
            )
        }
    };

    let id = vault.add(item)?;
    vault.save()?;
    println!("added {description:?} as {id}");
    Ok(())
}

/// Copies a secret to the clipboard, or prints it when asked to.
pub fn get(vault: &Vault, args: GetArgs) -> Result<()> {
    let summary = vault.resolve(&args.reference).map_err(output::explain)?;
    let item = vault.get(summary.id)?;

    let (value, description) = match &item.payload {
        Payload::Note { text } => (text.clone(), "text".to_owned()),
        Payload::Credential(credential) => {
            let value = match args.field {
                Field::Password => Some(credential.password.clone()),
                Field::Login => Some(credential.login.clone()),
                Field::Url => credential.url.clone(),
                Field::Totp => credential.totp.clone(),
            };
            match value {
                Some(value) => (value, args.field.as_str().to_owned()),
                None => bail!("{:?} has no {}", item.summary.title, args.field.as_str()),
            }
        }
        Payload::File { .. } => bail!(
            "{:?} is a file; write it to disk with: sefy extract {}",
            item.summary.title,
            item.summary.id
        ),
    };

    if args.stdout {
        println!("{value}");
        return Ok(());
    }

    if args.clear_after > 0 {
        // Said before the wait, not after: the user needs to know why the
        // command is sitting there.
        println!(
            "copied {description} of {:?} to the clipboard; clearing in {}s",
            item.summary.title, args.clear_after
        );
    } else {
        println!(
            "copied {description} of {:?} to the clipboard",
            item.summary.title
        );
    }
    flush_stdout();

    let hold = output::to_clipboard(&value, args.clear_after)?;
    if hold.cleared {
        println!("clipboard cleared");
    }
    Ok(())
}

/// Makes sure a message is on screen before a wait, not buffered behind it.
fn flush_stdout() {
    use std::io::Write;
    let _ = std::io::stdout().flush();
}

/// Shows an item's fields, keeping its secrets hidden.
pub fn show(vault: &Vault, reference: &str) -> Result<()> {
    let summary = vault.resolve(reference).map_err(output::explain)?;
    let item = vault.get(summary.id)?;

    field("id", &item.summary.id.to_string());
    field("title", &item.summary.title);
    field("kind", item.summary.kind.as_str());
    if !item.summary.tags.is_empty() {
        field("tags", &item.summary.tags.join(", "));
    }

    match &item.payload {
        Payload::Note { text } => {
            println!("---");
            println!("{text}");
        }
        Payload::Credential(credential) => {
            field("login", &credential.login);
            // Never printed here; `sefy get` is the one way a secret leaves.
            field("password", "<hidden — use sefy get>");
            if let Some(url) = &credential.url {
                field("url", url);
            }
            if credential.totp.is_some() {
                field("totp", "<hidden — use sefy get --field totp>");
            }
            if let Some(notes) = &credential.notes {
                field("notes", notes);
            }
        }
        Payload::File { filename, bytes } => {
            field("file", filename);
            field("size", &format!("{} bytes", bytes.len()));
        }
    }
    Ok(())
}

/// Prints one labelled line of `sefy show`, aligned to a fixed column.
///
/// A single place to pad from: hand-spaced labels drift the moment one of them
/// is longer than the rest, and `password` already had. The width leaves a
/// space after the longest label rather than butting against it.
fn field(label: &str, value: &str) {
    const LABEL_WIDTH: usize = "password:".len() + 1;
    println!("{:<LABEL_WIDTH$}{value}", format!("{label}:"));
}

/// Lists items, optionally narrowed by kind and tags.
pub fn ls(vault: &Vault, args: ListArgs) -> Result<()> {
    let mut query = Query::all().tags(args.tag);
    if let Some(kind) = args.kind {
        query = query.kind(kind.into());
    }
    output::table(&vault.search(&query)?);
    Ok(())
}

/// Searches items by text, kind and tags.
pub fn find(vault: &Vault, args: FindArgs) -> Result<()> {
    let mut query = Query::all().tags(args.tag);
    if let Some(text) = args.text {
        query = query.text(text);
    }
    if let Some(kind) = args.kind {
        query = query.kind(kind.into());
    }
    output::table(&vault.search(&query)?);
    Ok(())
}

/// Changes an item's title, contents or tags.
pub fn edit(vault: &mut Vault, args: EditArgs) -> Result<()> {
    let summary = vault.resolve(&args.reference).map_err(output::explain)?;
    let existing = vault.get(summary.id)?;

    let payload = build_edited_payload(&existing.payload, &args)?;
    let tags = if args.clear_tags {
        Some(Vec::new())
    } else if args.tag.is_empty() {
        None
    } else {
        Some(args.tag.clone())
    };

    if args.title.is_none() && payload.is_none() && tags.is_none() {
        bail!("nothing to change; pass --title, --tag, or a field to edit");
    }

    vault.update(summary.id, args.title, payload, tags)?;
    vault.save()?;
    println!("updated {}", summary.id);
    Ok(())
}

/// Applies the edit flags to an item's current payload.
///
/// Returns `None` when no flag touches the payload, so the item keeps what it
/// has. Flags meant for another kind of item are an error rather than a silent
/// no-op.
fn build_edited_payload(existing: &Payload, args: &EditArgs) -> Result<Option<Payload>> {
    let wants_new_password = args.password || args.item_password_env.is_some();
    let wants_credential_field = args.login.is_some()
        || wants_new_password
        || args.url.is_some()
        || args.totp.is_some()
        || args.notes.is_some();

    match existing {
        Payload::Note { text: current } => {
            if wants_credential_field {
                bail!(
                    "this item is a note; --login, --password, --url, --totp and --notes \
                     apply to credentials"
                );
            }
            if args.editor {
                return Ok(Some(Payload::Note {
                    text: crate::editor::edit(current)?,
                }));
            }
            Ok(args.text.clone().map(|text| Payload::Note { text }))
        }
        Payload::Credential(credential) => {
            if args.text.is_some() || args.editor {
                bail!("this item is a credential; --text and --editor apply to notes");
            }
            if !wants_credential_field {
                return Ok(None);
            }

            let mut updated = credential.clone();
            if let Some(login) = args.login.clone() {
                updated.login = login;
            }
            if wants_new_password {
                updated.password = session::secret(
                    "New password for this item: ",
                    args.item_password_env.as_deref(),
                )?;
            }
            if let Some(url) = args.url.clone() {
                updated.url = Some(url);
            }
            if let Some(totp) = args.totp.clone() {
                updated.totp = Some(totp);
            }
            if let Some(notes) = args.notes.clone() {
                updated.notes = Some(notes);
            }
            Ok(Some(Payload::Credential(updated)))
        }
        Payload::File { .. } => {
            if args.text.is_some() || args.editor || wants_credential_field {
                bail!("this item is a file; only --title and tags can be edited");
            }
            Ok(None)
        }
    }
}

/// Removes an item, asking first unless told not to.
pub fn rm(vault: &mut Vault, reference: &str, yes: bool) -> Result<()> {
    let summary = vault.resolve(reference).map_err(output::explain)?;

    if !yes
        && !confirm(&format!(
            "remove {:?} ({})? [y/N] ",
            summary.title, summary.id
        ))?
    {
        println!("kept");
        return Ok(());
    }

    vault.remove(summary.id)?;
    vault.save()?;
    println!("removed {}", summary.id);
    Ok(())
}

/// Writes a stored file back to disk.
pub fn extract(
    vault: &Vault,
    reference: &str,
    output_path: Option<PathBuf>,
    force: bool,
) -> Result<()> {
    let summary = vault.resolve(reference).map_err(output::explain)?;
    let item = vault.get(summary.id)?;

    let Payload::File { filename, bytes } = &item.payload else {
        bail!(
            "{:?} is a {}, not a file",
            item.summary.title,
            item.summary.kind
        );
    };

    let destination = output_path.unwrap_or_else(|| PathBuf::from(filename));
    if destination.exists() && !force {
        bail!(
            "{} already exists; pass --force to overwrite",
            destination.display()
        );
    }

    std::fs::write(&destination, bytes)
        .with_context(|| format!("cannot write {}", destination.display()))?;
    println!("wrote {} ({} bytes)", destination.display(), bytes.len());
    Ok(())
}

/// Lists the tags in use with their item counts.
pub fn tags(vault: &Vault) -> Result<()> {
    let tags = vault.tags()?;
    if tags.is_empty() {
        println!("no tags");
        return Ok(());
    }
    let width = tags
        .iter()
        .map(|(name, _)| name.chars().count())
        .max()
        .unwrap_or(4);
    for (name, count) in tags {
        println!("{name:<width$}  {count}");
    }
    Ok(())
}

/// Writes the vault's contents out as plain JSON.
pub fn export(
    vault: &Vault,
    output_path: Option<PathBuf>,
    acknowledged: bool,
    force: bool,
) -> Result<()> {
    if !acknowledged {
        bail!(
            "export writes every secret in this vault in the clear\n\
             the resulting file protects nothing — encrypt it, or delete it when done\n\
             pass --i-know-this-writes-plaintext to go ahead"
        );
    }

    let json = sefy_core::exchange::to_json(&sefy_core::exchange::export(vault)?)?;

    match output_path {
        Some(path) => {
            if path.exists() && !force {
                bail!(
                    "{} already exists; pass --force to overwrite",
                    path.display()
                );
            }
            std::fs::write(&path, json.as_bytes())
                .with_context(|| format!("cannot write {}", path.display()))?;
            eprintln!("wrote {} in the clear", path.display());
        }
        None => println!("{json}"),
    }
    Ok(())
}

/// Adds the contents of an export to the vault.
pub fn import(vault: &mut Vault, input: Option<PathBuf>) -> Result<()> {
    let json = match input {
        Some(path) => std::fs::read_to_string(&path)
            .with_context(|| format!("cannot read {}", path.display()))?,
        None => read_stdin().context("cannot read the export from stdin")?,
    };

    let export = sefy_core::exchange::from_json(&json)?;
    let count = sefy_core::exchange::import(vault, &export)?;
    println!("imported {count} item{}", if count == 1 { "" } else { "s" });
    Ok(())
}

/// Replaces the master password and rewrites the file under it.
pub fn change_password(vault: &mut Vault, password_env: Option<&str>) -> Result<()> {
    let password = session::new_password(password_env)?;
    vault.change_password(password.as_bytes())?;
    println!("password changed");
    Ok(())
}

/// Reads everything from stdin as text.
fn read_stdin() -> Result<String> {
    let mut text = String::new();
    std::io::stdin().read_to_string(&mut text)?;
    Ok(text.trim_end_matches(['\n', '\r']).to_owned())
}

/// Asks a yes/no question on the terminal.
fn confirm(question: &str) -> Result<bool> {
    use std::io::{IsTerminal, Write};

    if !std::io::stdin().is_terminal() {
        bail!("cannot ask for confirmation: input is not a terminal; pass --yes");
    }

    print!("{question}");
    std::io::stdout().flush()?;

    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer)?;
    Ok(matches!(
        answer.trim().to_ascii_lowercase().as_str(),
        "y" | "yes"
    ))
}