tsafe-cli 1.0.21

tsafe CLI — local secret and credential manager (replaces .env files)
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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! `tsafe import` — .env files and password-manager CSV exports.

use std::collections::HashMap;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use colored::Colorize;
use tsafe_core::{audit::AuditEntry, env as tsenv};

use crate::helpers::*;

/// Max directory depth when searching for a missing import file (from cwd).
const DOTENV_SEARCH_MAX_DEPTH: usize = 8;
/// Cap matches so monorepos do not print hundreds of lines.
const DOTENV_SEARCH_MAX_MATCHES: usize = 20;
const EXTENDED_IMPORT_SOURCES: &[&str] = &[
    "bitwarden",
    "1password",
    "lastpass",
    "chrome",
    "edge",
    "firefox",
];

fn is_extended_import_source(from: &str) -> bool {
    EXTENDED_IMPORT_SOURCES.contains(&from)
}

fn should_skip_subdir(dir_name: &OsStr) -> bool {
    let name = dir_name.to_string_lossy();
    matches!(
        name.as_ref(),
        "target"
            | "node_modules"
            | ".git"
            | ".cargo"
            | "vendor"
            | "dist"
            | "build"
            | ".next"
            | ".cache"
            | "venv"
            | ".venv"
            | "__pycache__"
    )
}

/// Files under `root` whose final path component equals `basename` (DFS, bounded).
fn find_same_named_files_under_dir(root: &Path, basename: &OsStr) -> Vec<PathBuf> {
    let mut results = Vec::new();
    let mut stack: Vec<(PathBuf, usize)> = vec![(root.to_path_buf(), 0)];

    while let Some((dir, depth)) = stack.pop() {
        if results.len() >= DOTENV_SEARCH_MAX_MATCHES {
            break;
        }
        let Ok(read_dir) = std::fs::read_dir(&dir) else {
            continue;
        };
        for ent in read_dir.flatten() {
            if results.len() >= DOTENV_SEARCH_MAX_MATCHES {
                break;
            }
            let Ok(ft) = ent.file_type() else {
                continue;
            };
            let p = ent.path();
            if ft.is_dir() {
                if depth >= DOTENV_SEARCH_MAX_DEPTH {
                    continue;
                }
                if should_skip_subdir(ent.file_name().as_os_str()) {
                    continue;
                }
                stack.push((p, depth + 1));
            } else if ft.is_file() && p.file_name() == Some(basename) {
                results.push(p);
            }
        }
    }

    results.sort_by(|a, b| {
        let la = a.components().count();
        let lb = b.components().count();
        la.cmp(&lb)
            .then_with(|| a.to_string_lossy().cmp(&b.to_string_lossy()))
    });
    results
}

fn basename_for_import_search(requested: &Path) -> Option<&OsStr> {
    requested.file_name().or({
        if requested.as_os_str().is_empty() {
            None
        } else {
            Some(requested.as_os_str())
        }
    })
}

fn display_path_for_hint(cwd: &Path, p: &Path) -> String {
    if let Ok(rel) = p.strip_prefix(cwd) {
        let s = rel.to_string_lossy();
        if s.is_empty() {
            return ".".to_string();
        }
        if rel.components().next().is_some() && !s.starts_with('.') {
            format!("./{s}")
        } else {
            s.into_owned()
        }
    } else {
        p.display().to_string()
    }
}

fn dotenv_import_not_found_message(from: &str, requested: &Path, cwd: &Path) -> String {
    let cwd_disp = cwd.display().to_string();
    let mut msg = format!(
        "import source not found: '{from}'\n  \
         Current directory: {cwd_disp}\n\n  \
         Hints:\n  \
         • Pass a path to an existing file, e.g. `tsafe import --from ./apps/web/.env`\n  \
         • Or `cd` into the directory that contains the file, then run import again.\n  \
         • Create the file if you meant to add variables there first.\n"
    );

    if requested.is_relative() {
        if let Some(base) = basename_for_import_search(requested) {
            let hits = find_same_named_files_under_dir(cwd, base);
            if !hits.is_empty() {
                msg.push_str(&format!(
                    "\n  Found {} file(s) named '{}' under this directory (search depth ≤ {}, skipped common build/cache folders):\n",
                    hits.len(),
                    base.to_string_lossy(),
                    DOTENV_SEARCH_MAX_DEPTH
                ));
                for p in &hits {
                    let rel = display_path_for_hint(cwd, p);
                    msg.push_str(&format!("    {rel}\n"));
                }
                if let Some(first) = hits.first() {
                    let arg = display_path_for_hint(cwd, first);
                    msg.push_str(&format!("\n  Try: tsafe import --from '{arg}'\n"));
                }
                if hits.len() >= DOTENV_SEARCH_MAX_MATCHES {
                    msg.push_str(&format!(
                        "  (List capped at {DOTENV_SEARCH_MAX_MATCHES} matches; narrow the path or cd closer to the file.)\n"
                    ));
                }
            } else {
                msg.push_str(&format!(
                    "\n  No files named '{base}' found under this directory within the search depth.\n  \
                     If the file lives elsewhere, use an absolute path.\n",
                    base = base.to_string_lossy()
                ));
            }
        }
    } else {
        msg.push_str(
            "\n  This is an absolute path — tsafe did not search subdirectories (use a correct path or a relative path from cwd to get suggestions).\n",
        );
    }

    msg
}

pub(crate) fn cmd_import(
    profile: &str,
    from: &str,
    file: Option<&str>,
    overwrite: bool,
    skip_duplicates: bool,
    ns: Option<&str>,
    dry_run: bool,
) -> Result<()> {
    let from_lower = from.to_ascii_lowercase();
    if is_extended_import_source(&from_lower) {
        #[cfg(not(feature = "pm-import-extended"))]
        {
            let _ = (file, skip_duplicates);
            anyhow::bail!(
                "extended import source '{from}' is not compiled into this build; use a tsafe build or release channel that includes `pm-import-extended`.\n\
                 Local development builds can rebuild with feature `pm-import-extended`."
            );
        }

        #[cfg(feature = "pm-import-extended")]
        {
            let export_file = file.ok_or_else(|| {
                anyhow::anyhow!("--file <path> is required when --from is '{from}'")
            })?;
            return cmd_import_pw_manager(profile, from, export_file, overwrite, skip_duplicates);
        }
    }
    let path = Path::new(from);
    if !path.exists() {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let text = dotenv_import_not_found_message(from, path, &cwd);
        anyhow::bail!("{text}");
    }
    let imported =
        tsenv::parse_dotenv(path).with_context(|| format!("failed to parse '{from}'"))?;

    if dry_run {
        // In dry-run mode, show what would happen without writing to the vault.
        let vault = open_vault(profile)?;
        if let Some(n) = ns {
            println!(
                "{} [dry-run] Using namespace '{n}' (keys would be stored as '{n}/<KEY>')",
                "i".blue()
            );
        }
        let mut would_import = 0usize;
        let mut would_skip = 0usize;
        let mut keys: Vec<String> = imported.keys().cloned().collect();
        keys.sort();
        for raw_key in &keys {
            let key = match ns {
                Some(n) => format!("{n}/{raw_key}"),
                None => raw_key.clone(),
            };
            if !overwrite && vault.list().contains(&key.as_str()) {
                println!("  {} [skip]   {key} (already exists)", "!".yellow());
                would_skip += 1;
            } else {
                println!("  {} [import] {key}", "".green());
                would_import += 1;
            }
        }
        println!(
            "\n{} Dry-run: would import {would_import} key(s), skip {would_skip} existing",
            "i".blue()
        );
        return Ok(());
    }

    let mut vault = open_vault(profile)?;
    let mut count = 0usize;
    let mut skipped = 0usize;
    if let Some(n) = ns {
        println!(
            "{} Using namespace '{n}' (keys stored as '{n}/<KEY>')",
            "i".blue()
        );
    }
    for (raw_key, value) in &imported {
        let key = match ns {
            Some(n) => format!("{n}/{raw_key}"),
            None => raw_key.clone(),
        };
        if !overwrite && vault.list().contains(&key.as_str()) {
            eprintln!(
                "{} Skipping existing key '{key}' (use --overwrite to replace)",
                "!".yellow()
            );
            skipped += 1;
            continue;
        }
        vault.set(&key, value, HashMap::new())?;
        count += 1;
    }
    audit(profile)
        .append(&AuditEntry::success(profile, "import", None))
        .ok();
    if skipped > 0 {
        println!(
            "{} Imported {count} secret(s), skipped {skipped} existing (profile '{profile}')",
            "".green()
        );
    } else {
        println!(
            "{} Imported {count} secret(s) into profile '{profile}'",
            "".green()
        );
    }
    Ok(())
}

#[cfg(feature = "pm-import-extended")]
fn cmd_import_pw_manager(
    profile: &str,
    source: &str,
    path: &str,
    overwrite: bool,
    skip_duplicates: bool,
) -> Result<()> {
    let p = Path::new(path);
    if !p.exists() {
        let cwd = std::env::current_dir()
            .map(|d| d.display().to_string())
            .unwrap_or_else(|_| "(unknown)".to_string());
        anyhow::bail!(
            "import file not found: '{path}'\n  \
             Current directory: {cwd}\n\n  \
             Hints:\n  \
             • Check the path — use Tab completion or `ls` to confirm the export file exists.\n  \
             • Bitwarden / 1Password / LastPass: export a CSV from the app, then pass `--file /full/path/to/export.csv`.\n  \
             • Chrome / Edge: chrome://settings/passwords → Download file; Firefox: about:logins → export.\n"
        );
    }
    let data = std::fs::read_to_string(path).with_context(|| format!("failed to read '{path}'"))?;

    let mut lines = data.lines();
    let header_line = lines
        .next()
        .ok_or_else(|| anyhow::anyhow!("export file is empty"))?;
    let headers: Vec<&str> = split_csv_line(header_line);

    let col = |names: &[&str]| -> Option<usize> {
        names
            .iter()
            .find_map(|n| headers.iter().position(|h| h.eq_ignore_ascii_case(n)))
    };

    let (name_col, user_col, pass_col, url_col) = match source.to_ascii_lowercase().as_str() {
        "bitwarden" => (
            col(&["name"]).ok_or_else(|| anyhow::anyhow!("missing 'name' column"))?,
            col(&["login_username"]),
            col(&["login_password"]),
            col(&["login_uri"]),
        ),
        "lastpass" => (
            col(&["name"]).ok_or_else(|| anyhow::anyhow!("missing 'name' column"))?,
            col(&["username"]),
            col(&["password"]),
            col(&["url"]),
        ),
        "1password" => (
            col(&["title", "name"]).ok_or_else(|| anyhow::anyhow!("missing 'title' column"))?,
            col(&["username"]),
            col(&["password"]),
            col(&["url", "website url"]),
        ),
        // Chrome and Edge: CSV exported from chrome://settings/passwords or edge://settings/passwords.
        // Columns: name, url, username, password
        "chrome" | "edge" => (
            col(&["name"]).ok_or_else(|| anyhow::anyhow!("missing 'name' column — export from chrome://settings/passwords or edge://settings/passwords"))?,
            col(&["username"]),
            col(&["password"]),
            col(&["url"]),
        ),
        // Firefox: CSV exported from about:logins (Firefox 79+).
        // Columns: url, username, password, httpRealm, formActionOrigin, guid, …
        "firefox" => (
            col(&["url"]).ok_or_else(|| anyhow::anyhow!("missing 'url' column — export from Firefox about:logins"))?,
            col(&["username"]),
            col(&["password"]),
            None, // url is used as the name; no separate url column
        ),
        other => anyhow::bail!("unknown password-manager source '{other}'"),
    };

    let mut vault = open_vault(profile)?;
    let mut imported = 0usize;
    let mut skipped = 0usize;
    let mut duplicate_errors: Vec<String> = Vec::new();
    // Track keys seen within this import batch to detect within-file duplicates.
    let mut seen_in_batch: std::collections::HashSet<String> = std::collections::HashSet::new();

    for (row_num, line) in lines.enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        let cols: Vec<String> = split_csv_line(line)
            .into_iter()
            .map(|s| s.to_string())
            .collect();
        let get = |idx: usize| {
            cols.get(idx)
                .map(|s| s.as_str())
                .unwrap_or("")
                .trim()
                .to_string()
        };

        let name = get(name_col);
        if name.is_empty() {
            eprintln!("{} row {}: empty name, skipping", "!".yellow(), row_num + 2);
            continue;
        }
        let prefix = name
            .chars()
            .map(|c| {
                if c.is_alphanumeric() {
                    c.to_ascii_uppercase()
                } else {
                    '_'
                }
            })
            .collect::<String>();
        let prefix = prefix.trim_matches('_').to_string();

        let mut store = |suffix: &str, value: String| -> Result<()> {
            if value.is_empty() {
                return Ok(());
            }
            let key = format!("{prefix}_{suffix}");
            // Within-file duplicate: same key appears more than once in the CSV.
            if seen_in_batch.contains(&key) {
                if skip_duplicates {
                    eprintln!(
                        "{} row {}: duplicate key '{}' in import file — skipping",
                        "!".yellow(),
                        row_num + 2,
                        key
                    );
                    skipped += 1;
                    return Ok(());
                } else if !overwrite {
                    duplicate_errors.push(format!(
                        "  row {}: key '{}' appears more than once in the import file",
                        row_num + 2,
                        key
                    ));
                    return Ok(());
                }
                // overwrite=true: fall through to overwrite.
            }
            // Vault already has this key (cross-file duplicate).
            if !overwrite && vault.list().contains(&key.as_str()) {
                if skip_duplicates {
                    eprintln!("{} Skipping existing key '{key}'", "!".yellow());
                    skipped += 1;
                    return Ok(());
                }
                eprintln!(
                    "{} Skipping existing key '{key}' (use --overwrite to replace)",
                    "!".yellow()
                );
                skipped += 1;
                return Ok(());
            }
            seen_in_batch.insert(key.clone());
            vault.set(&key, &value, HashMap::new())?;
            audit(profile)
                .append(&AuditEntry::success(profile, "import", Some(&key)))
                .ok();
            imported += 1;
            Ok(())
        };

        if let Some(idx) = user_col {
            store("USERNAME", get(idx))?;
        }
        if let Some(idx) = pass_col {
            store("PASSWORD", get(idx))?;
        }
        if let Some(idx) = url_col {
            store("URL", get(idx))?;
        }
    }

    if !duplicate_errors.is_empty() {
        anyhow::bail!(
            "duplicate keys detected in import file (use --skip-duplicates to skip without error, \
             or --overwrite to overwrite):\n{}",
            duplicate_errors.join("\n")
        );
    }

    println!(
        "{} Imported {} secret(s) from {source} export (skipped {skipped} existing)",
        "".green(),
        imported
    );
    Ok(())
}

#[cfg(any(feature = "pm-import-extended", test))]
fn split_csv_line(line: &str) -> Vec<&str> {
    let mut fields = Vec::new();
    let mut start = 0usize;
    let bytes = line.as_bytes();
    let mut in_quotes = false;
    let mut i = 0usize;
    while i < bytes.len() {
        match bytes[i] {
            b'"' => {
                if in_quotes && i + 1 < bytes.len() && bytes[i + 1] == b'"' {
                    i += 1;
                } else {
                    in_quotes = !in_quotes;
                }
            }
            b',' if !in_quotes => {
                let field = &line[start..i];
                fields.push(unquote(field));
                start = i + 1;
            }
            _ => {}
        }
        i += 1;
    }
    fields.push(unquote(&line[start..]));
    fields
}

#[cfg(any(feature = "pm-import-extended", test))]
fn unquote(s: &str) -> &str {
    let s = s.trim();
    if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
        &s[1..s.len() - 1]
    } else {
        s
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── dotenv search ─────────────────────────────────────────────────────────

    #[test]
    fn find_same_named_files_skips_target_and_node_modules() {
        let dir = tempfile::tempdir().unwrap();
        let good = dir.path().join("app");
        std::fs::create_dir_all(&good).unwrap();
        std::fs::write(good.join(".env"), "A=1\n").unwrap();
        let target = dir.path().join("target");
        std::fs::create_dir_all(target.join("nested")).unwrap();
        std::fs::write(target.join("nested").join(".env"), "B=2\n").unwrap();

        let hits = find_same_named_files_under_dir(dir.path(), OsStr::new(".env"));
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].file_name(), Some(OsStr::new(".env")));
        assert!(hits[0].to_string_lossy().contains("app"));
    }

    #[test]
    fn dotenv_not_found_message_lists_nested_candidates() {
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("packages").join("api");
        std::fs::create_dir_all(&sub).unwrap();
        std::fs::write(sub.join(".env"), "X=1\n").unwrap();

        let msg = dotenv_import_not_found_message(".env", Path::new(".env"), dir.path());
        assert!(msg.contains("packages"));
        assert!(msg.contains("Try: tsafe import --from"));
        assert!(msg.contains("Hints:"));
    }

    #[test]
    fn basename_for_import_search_handles_dotted_filename() {
        let p = Path::new(".env.production");
        assert_eq!(
            basename_for_import_search(p),
            Some(OsStr::new(".env.production"))
        );
    }

    // ── split_csv_line ────────────────────────────────────────────────────────

    #[test]
    fn split_csv_simple_fields() {
        let fields = split_csv_line("name,url,username,password");
        assert_eq!(fields, vec!["name", "url", "username", "password"]);
    }

    #[test]
    fn split_csv_quoted_fields_preserve_content() {
        let fields = split_csv_line(r#""Alice","http://example.com","admin","s3cr3t""#);
        assert_eq!(
            fields,
            vec!["Alice", "http://example.com", "admin", "s3cr3t"]
        );
    }

    #[test]
    fn split_csv_quoted_field_containing_comma() {
        // A quoted field with a comma inside must not split on it.
        let fields = split_csv_line(r#""My Service, LLC",https://myservice.com,user,pass"#);
        assert_eq!(
            fields,
            vec!["My Service, LLC", "https://myservice.com", "user", "pass"]
        );
    }

    #[test]
    fn split_csv_double_quoted_escape_within_field() {
        // The parser skips the second '"' of a '""' pair to stay in quoted mode
        // (preventing an early field termination), but does not unescape the
        // double-quote in the extracted slice. The key property to test is that
        // the comma inside the quoted value is NOT treated as a delimiter.
        let fields = split_csv_line(r#""Say ""hello""",next"#);
        // Field boundary is respected — exactly 2 fields.
        assert_eq!(fields.len(), 2);
        assert_eq!(fields[1], "next");
    }

    #[test]
    fn split_csv_single_field_no_comma() {
        let fields = split_csv_line("onlyone");
        assert_eq!(fields, vec!["onlyone"]);
    }

    #[test]
    fn split_csv_empty_fields() {
        let fields = split_csv_line("a,,c");
        assert_eq!(fields, vec!["a", "", "c"]);
    }

    // ── unquote ───────────────────────────────────────────────────────────────

    #[test]
    fn unquote_removes_surrounding_double_quotes() {
        assert_eq!(unquote(r#""hello""#), "hello");
    }

    #[test]
    fn unquote_leaves_unquoted_string_unchanged() {
        assert_eq!(unquote("hello"), "hello");
    }

    #[test]
    fn unquote_trims_whitespace_before_checking_quotes() {
        assert_eq!(unquote(r#"  "hello"  "#), "hello");
    }

    #[test]
    fn unquote_single_char_not_stripped() {
        // A single `"` is not a matched pair — left as-is after trim.
        assert_eq!(unquote("\""), "\"");
    }

    #[test]
    fn unquote_empty_quoted_string() {
        assert_eq!(unquote(r#""""#), "");
    }
}