tsafe-cli 1.0.26

Secrets runtime for developers — inject credentials into processes via exec, never into shell history or .env 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
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
//! Shared helper functions for all CLI command handlers.
//!
//! Vault open strategies, password prompting, clipboard management, tag
//! parsing, and interactive onboarding flows are centralised here so the
//! top-level `main.rs` stays focused on dispatch.

use std::collections::HashMap;
use std::io::{self, BufRead, IsTerminal, Write};

use anyhow::{Context, Result};
use chrono::Utc;
use colored::Colorize;

use tsafe_core::{
    audit::{AuditEntry, AuditLog},
    env as tsenv,
    errors::SafeError,
    events::emit_event,
    keyring_store, profile,
    rbac::RbacProfile,
    vault::Vault,
};

// ── Password prompting ────────────────────────────────────────────────────────

pub fn prompt_password(prompt: &str) -> Result<String> {
    // Non-interactive path: TSAFE_PASSWORD env var (CI / agent / scripted use).
    if let Ok(pw) = std::env::var("TSAFE_PASSWORD") {
        return Ok(pw);
    }
    // No TTY and no env var — fail fast rather than hanging on a read that will
    // never come.  This is the case when a process (agent, pipeline step) calls
    // tsafe without setting TSAFE_PASSWORD.
    use std::io::IsTerminal;
    if !std::io::stdin().is_terminal() {
        anyhow::bail!(
            "no TTY detected and TSAFE_PASSWORD is not set.\n\
             For non-interactive use set TSAFE_PASSWORD in the process environment:\n\
             \n  $env:TSAFE_PASSWORD = \"<vault password>\"   # PowerShell\n\
               export TSAFE_PASSWORD=\"<vault password>\"     # bash\n\
             \nTo create a new vault non-interactively:\n\
             \n  $env:TSAFE_PASSWORD = \"<new password>\"; tsafe init"
        );
    }
    rpassword::prompt_password(prompt).context("failed to read password from terminal")
}

pub fn prompt_password_confirmed() -> Result<String> {
    // When using the env-var path (non-interactive), skip the confirmation prompt;
    // there is no human typing who could mistype.
    if std::env::var("TSAFE_PASSWORD").is_ok() {
        return prompt_password("New vault password: ");
    }
    let pw1 = prompt_password("New vault password: ")?;
    let pw2 = prompt_password("Confirm password:   ")?;
    if pw1 != pw2 {
        anyhow::bail!("passwords do not match");
    }
    Ok(pw1)
}

fn quick_unlock_cooldown_path(profile_name: &str) -> std::path::PathBuf {
    profile::app_state_dir()
        .join("quick-unlock-cooldown")
        .join(format!("{profile_name}.txt"))
}

#[allow(dead_code)] // used in non-biometric builds
fn quick_unlock_retry_blocked(profile_name: &str) -> bool {
    if !profile::get_auto_quick_unlock() {
        return true;
    }
    let path = quick_unlock_cooldown_path(profile_name);
    let Ok(raw) = std::fs::read_to_string(&path) else {
        return false;
    };
    let Ok(until_epoch) = raw.trim().parse::<i64>() else {
        let _ = std::fs::remove_file(path);
        return false;
    };
    let now_epoch = Utc::now().timestamp();
    if now_epoch < until_epoch {
        return true;
    }
    let _ = std::fs::remove_file(path);
    false
}

fn note_quick_unlock_retry_cooldown(profile_name: &str) {
    let seconds = profile::get_quick_unlock_retry_cooldown_secs();
    if seconds == 0 {
        return;
    }
    let path = quick_unlock_cooldown_path(profile_name);
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let until_epoch = Utc::now().timestamp() + seconds as i64;
    let _ = std::fs::write(path, until_epoch.to_string());
}

fn clear_quick_unlock_retry_cooldown(profile_name: &str) {
    let _ = std::fs::remove_file(quick_unlock_cooldown_path(profile_name));
}

#[allow(dead_code)] // used in non-biometric builds
fn try_auto_quick_unlock_password(profile_name: &str) -> Option<String> {
    if quick_unlock_retry_blocked(profile_name) {
        return None;
    }
    match keyring_store::retrieve_password(profile_name) {
        Ok(Some(pw)) => {
            clear_quick_unlock_retry_cooldown(profile_name);
            Some(pw.trim_end_matches(['\n', '\r']).to_string())
        }
        Ok(None) => {
            clear_quick_unlock_retry_cooldown(profile_name);
            None
        }
        Err(_) => {
            note_quick_unlock_retry_cooldown(profile_name);
            None
        }
    }
}

// ── Vault open strategies ─────────────────────────────────────────────────────

pub fn open_vault(profile: &str) -> Result<Vault> {
    open_vault_with_access_profile(profile, RbacProfile::ReadWrite)
}

pub fn open_vault_with_access_profile(profile: &str, access_profile: RbacProfile) -> Result<Vault> {
    profile::validate_profile_name(profile)?;
    let path = profile::vault_path(profile);
    if !path.exists() {
        if !access_profile.allows_write() {
            anyhow::bail!("vault not found: {}", path.display());
        }
        return first_run_create_vault(profile, &path);
    }

    // ── Team vault path: use age identity instead of password ────────────────
    if Vault::is_team_vault(&path) {
        return open_team_vault_with_access_profile(profile, &path, access_profile);
    }

    if let Ok(password) = std::env::var("TSAFE_PASSWORD") {
        return Vault::open_with_access_profile(&path, password.as_bytes(), access_profile)
            .map_err(|e| match e {
                SafeError::DecryptionFailed => {
                    anyhow::anyhow!("wrong password for profile '{profile}' from TSAFE_PASSWORD")
                }
                other => anyhow::anyhow!("{other}"),
            });
    }

    // Try the background agent first (no interactive prompt needed).
    if let Ok(Some(pw)) = tsafe_core::agent::request_password_from_agent(profile) {
        return Vault::open_with_access_profile(&path, pw.as_bytes(), access_profile).map_err(
            |e| match e {
                SafeError::DecryptionFailed => {
                    anyhow::anyhow!("agent provided wrong password for '{profile}'")
                }
                other => anyhow::anyhow!("{other}"),
            },
        );
    }
    // Try the main vault's profile-passwords namespace (master-password bridging).
    if let Some(pw) = get_password_from_main(profile) {
        return Vault::open_with_access_profile(&path, pw.as_bytes(), access_profile).map_err(
            |e| match e {
                SafeError::DecryptionFailed => anyhow::anyhow!(
                    "main vault has a password stored for '{profile}' but it is wrong — \
                     update it with: tsafe -p main set profile-passwords/{profile} <new-password>"
                ),
                other => anyhow::anyhow!("{other}"),
            },
        );
    }
    // ── E4.1: Windows Hello challenge before keyring read ───────────────────
    #[cfg(all(windows, feature = "biometric"))]
    {
        use crate::windows_hello::{request_windows_hello_verification, BiometricChallengeError};
        match request_windows_hello_verification("tsafe vault unlock") {
            Ok(true) | Err(BiometricChallengeError::NoWindowHandle)
            | Err(BiometricChallengeError::NotEnrolled)
            | Err(BiometricChallengeError::NotConfigured) => {
                // Proceed — challenge passed or not available on this device
            }
            Ok(false) => {
                anyhow::bail!("Windows Hello verification denied for '{profile}'")
            }
            Err(BiometricChallengeError::Canceled) => {
                anyhow::bail!("Windows Hello verification canceled for '{profile}'")
            }
            Err(e) => {
                eprintln!("{} Windows Hello challenge failed ({e}) — proceeding without challenge", "warn:".yellow());
            }
        }
    }

    // Try OS credential store (biometric / keyring unlock).
    #[cfg(feature = "biometric")]
    if let Some(pw) = crate::cmd_biometric::retrieve_biometric_password(profile)
        .ok()
        .flatten()
    {
        let pw_str = pw.trim_end_matches(['\n', '\r']).to_string();
        match Vault::open_with_access_profile(&path, pw_str.as_bytes(), access_profile) {
            Ok(v) => {
                clear_quick_unlock_retry_cooldown(profile);
                return Ok(v);
            }
            Err(SafeError::DecryptionFailed) => {
                note_quick_unlock_retry_cooldown(profile);
                // Warn about stale credential per ADR-016, but fall through to
                // the interactive password prompt so the user can still access
                // their vault with the master password and then re-enroll.
                let stale = crate::cmd_biometric::classify_biometric_unlock_error(
                    SafeError::DecryptionFailed,
                );
                eprintln!("{} {stale}", "warn:".yellow());
                eprintln!(
                    "{} After logging in, run: tsafe biometric re-enroll",
                    "hint:".cyan()
                );
                // Fall through to interactive prompt below.
            }
            Err(other) => return Err(anyhow::anyhow!("{other}")),
        }
    }
    #[cfg(not(feature = "biometric"))]
    if let Some(pw) = try_auto_quick_unlock_password(profile) {
        match Vault::open_with_access_profile(&path, pw.as_bytes(), access_profile) {
            Ok(v) => {
                clear_quick_unlock_retry_cooldown(profile);
                return Ok(v);
            }
            Err(SafeError::DecryptionFailed) => {
                note_quick_unlock_retry_cooldown(profile);
                eprintln!(
                    "{} Stored keyring password for '{}' is outdated — falling back to prompt.",
                    "warn:".yellow(),
                    profile
                );
                // Fall through to interactive prompt.
            }
            Err(other) => return Err(anyhow::anyhow!("{other}")),
        }
    }
    let password = prompt_password(&format!("Password for profile '{profile}': "))?;
    let vault =
        Vault::open_with_access_profile(&path, password.as_bytes(), access_profile).map_err(
            |e| match e {
                SafeError::DecryptionFailed => anyhow::anyhow!(
                    "wrong password for profile '{profile}'\n\
                     \n  If you use quick unlock, check its status: tsafe biometric status\
                     \n  To reset the stored password:            tsafe biometric disable && tsafe biometric enable\
                     \n  If you forgot the master password, see:  tsafe explain vault-recovery"
                ),
                other => anyhow::anyhow!("{other}"),
            },
        )?;
    // Only persist to the keyring when the password was typed interactively.
    // If it came from the TSAFE_PASSWORD env var (CI / scripted use) we must not
    // cache it — doing so would let subsequent calls bypass a changed env var.
    if std::env::var("TSAFE_PASSWORD").is_err() {
        tsafe_core::keyring_store::store_password(profile, &password).ok();
    }
    Ok(vault)
}

#[allow(dead_code)] // utility for agent / MCP callers
pub fn open_vault_noninteractive(profile: &str) -> Result<Option<Vault>> {
    open_vault_noninteractive_with_access_profile(profile, RbacProfile::ReadWrite)
}

#[allow(dead_code)] // utility for agent / MCP callers
pub fn open_vault_noninteractive_with_access_profile(
    profile: &str,
    access_profile: RbacProfile,
) -> Result<Option<Vault>> {
    profile::validate_profile_name(profile)?;
    let path = profile::vault_path(profile);
    if !path.exists() {
        return Ok(None);
    }

    if Vault::is_team_vault(&path) {
        return open_team_vault_with_access_profile(profile, &path, access_profile).map(Some);
    }

    if let Ok(password) = std::env::var("TSAFE_PASSWORD") {
        return match Vault::open_with_access_profile(&path, password.as_bytes(), access_profile) {
            Ok(vault) => Ok(Some(vault)),
            Err(SafeError::DecryptionFailed) => Ok(None),
            Err(other) => Err(anyhow::anyhow!("{other}")),
        };
    }

    if let Ok(Some(pw)) = tsafe_core::agent::request_password_from_agent(profile) {
        return match Vault::open_with_access_profile(&path, pw.as_bytes(), access_profile) {
            Ok(vault) => Ok(Some(vault)),
            Err(SafeError::DecryptionFailed) => Ok(None),
            Err(other) => Err(anyhow::anyhow!("{other}")),
        };
    }
    if let Some(pw) = get_password_from_main(profile) {
        return match Vault::open_with_access_profile(&path, pw.as_bytes(), access_profile) {
            Ok(vault) => Ok(Some(vault)),
            Err(SafeError::DecryptionFailed) => Ok(None),
            Err(other) => Err(anyhow::anyhow!("{other}")),
        };
    }
    Ok(None)
}

/// Try to retrieve the vault password for `profile` from the `main` vault's
/// `profile-passwords/<profile>` entry.
///
/// Opens `main` non-interactively only (agent then TSAFE_PASSWORD env var).
/// Returns `None` if:
/// - `profile` is "main" (avoids recursion)
/// - the main vault does not exist
/// - main cannot be opened non-interactively
/// - the key is absent from main
pub fn get_password_from_main(profile: &str) -> Option<String> {
    if profile == "main" {
        return None;
    }
    let main_path = profile::vault_path("main");
    if !main_path.exists() {
        return None;
    }
    // Open main vault non-interactively: agent first, then TSAFE_PASSWORD.
    let main_pw: String =
        if let Ok(Some(pw)) = tsafe_core::agent::request_password_from_agent("main") {
            pw.to_string()
        } else if let Ok(pw) = std::env::var("TSAFE_PASSWORD") {
            pw
        } else {
            return None;
        };
    let main_vault = Vault::open(&main_path, main_pw.as_bytes()).ok()?;
    let key = format!("profile-passwords/{profile}");
    main_vault.get(&key).ok().map(|z| z.to_string())
}

/// Open an existing vault to write `profile-passwords/<child>` during init
/// (no auto-create, no keyring write side effects).
pub fn open_vault_for_backup(target_profile: &str) -> Result<Vault> {
    profile::validate_profile_name(target_profile)?;
    let path = profile::vault_path(target_profile);
    if !path.exists() {
        anyhow::bail!("vault for profile '{target_profile}' does not exist");
    }
    if Vault::is_team_vault(&path) {
        return open_team_vault_with_access_profile(target_profile, &path, RbacProfile::ReadWrite);
    }
    if let Ok(password) = std::env::var("TSAFE_PASSWORD") {
        return Vault::open_with_access_profile(&path, password.as_bytes(), RbacProfile::ReadWrite)
            .map_err(|e| anyhow::anyhow!("{e}"));
    }
    if let Ok(Some(pw)) = tsafe_core::agent::request_password_from_agent(target_profile) {
        return Vault::open_with_access_profile(&path, pw.as_bytes(), RbacProfile::ReadWrite)
            .map_err(|e| anyhow::anyhow!("{e}"));
    }
    if let Some(pw) = get_password_from_main(target_profile) {
        return Vault::open_with_access_profile(&path, pw.as_bytes(), RbacProfile::ReadWrite)
            .map_err(|e| anyhow::anyhow!("{e}"));
    }
    use std::io::IsTerminal;
    if std::io::stdin().is_terminal() && std::env::var("TSAFE_PASSWORD").is_err() {
        let password = prompt_password(&format!(
            "Password for '{target_profile}' vault (to store backup of the new profile's master password): "
        ))?;
        return Vault::open_with_access_profile(&path, password.as_bytes(), RbacProfile::ReadWrite)
            .map_err(|e| match e {
                SafeError::DecryptionFailed => anyhow::anyhow!("wrong password"),
                other => anyhow::anyhow!("{other}"),
            });
    }
    anyhow::bail!(
        "could not open backup vault '{target_profile}' non-interactively — unlock it first \
         (e.g. `tsafe agent unlock --profile {target_profile}`)"
    )
}

/// If `backup_new_profile_passwords_to` is set in config, copy the new vault
/// password into that vault.
pub fn backup_new_profile_password_if_configured(
    created_profile: &str,
    new_password: &str,
) -> Result<()> {
    let Some(target) = profile::get_backup_new_profile_passwords_to() else {
        return Ok(());
    };
    if target == created_profile {
        return Ok(());
    }
    profile::validate_profile_name(&target).map_err(|e| anyhow::anyhow!("{e}"))?;
    if !profile::vault_path(&target).exists() {
        eprintln!(
            "{} Config expects master-password backups in '{}' but that vault does not exist yet — skipping backup.",
            "warn:".yellow().bold(),
            target
        );
        eprintln!("  Create it with: tsafe --profile {target} init");
        return Ok(());
    }
    let mut v = match open_vault_for_backup(&target) {
        Ok(v) => v,
        Err(e) => {
            eprintln!(
                "{} Could not open backup vault '{}' to store the new profile password: {:#}",
                "warn:".yellow().bold(),
                target,
                e
            );
            eprintln!(
                "  After '{target}' is unlocked, add the password with: tsafe --profile {target} set profile-passwords/{created_profile}"
            );
            return Ok(());
        }
    };
    let key = format!("profile-passwords/{created_profile}");
    v.set(&key, new_password, HashMap::new())
        .map_err(|e| anyhow::anyhow!("{e}"))?;
    v.save().map_err(|e| anyhow::anyhow!("{e}"))?;
    audit(&target)
        .append(&AuditEntry::success(&target, "set", Some(&key)))
        .ok();
    println!(
        "{} Also saved master password for '{}' under {} in the '{}' vault \
         (config: backup_new_profile_passwords_to).",
        "".green(),
        created_profile,
        key,
        target
    );
    println!("  Keep that vault strictly protected — it can unlock other profiles via bridging.");
    Ok(())
}

pub fn open_team_vault_with_access_profile(
    profile: &str,
    path: &std::path::Path,
    access_profile: RbacProfile,
) -> Result<Vault> {
    use tsafe_core::{age_crypto, team};

    let identity_path = profile::resolve_age_identity_path(profile);

    if !identity_path.exists() {
        anyhow::bail!(
            "Team vault detected but no age identity found at {}\n\
             Generate one with: tsafe --profile {profile} team keygen\n\
             Or set TSAFE_AGE_IDENTITY to your identity file.",
            identity_path.display()
        );
    }

    let identities = age_crypto::load_identities(&identity_path)
        .map_err(|e| anyhow::anyhow!("failed to load age identity: {e}"))?;

    // Read the vault file to unwrap the DEK.
    let json = std::fs::read_to_string(path)?;
    let file: tsafe_core::vault::VaultFile = serde_json::from_str(&json)?;
    let dek = team::unwrap_dek(&file, &identities).map_err(|e| {
        anyhow::anyhow!("cannot decrypt team vault — your identity may not be a member: {e}")
    })?;

    Vault::open_with_key_with_access_profile(path, dek, access_profile)
        .map_err(|e| anyhow::anyhow!("{e}"))
}

/// Called when the vault for `profile` doesn't exist yet.
///
/// - If `TSAFE_PASSWORD` is set (non-interactive / scripted): auto-create silently.
/// - If on a TTY: ask the user whether to create it now.
/// - If no TTY and no `TSAFE_PASSWORD`: fail fast with a clear message.
pub fn first_run_create_vault(profile: &str, path: &std::path::Path) -> Result<Vault> {
    // Non-interactive path — password is available, just create the vault.
    if std::env::var("TSAFE_PASSWORD").is_ok() {
        let password = prompt_password("")?; // returns env var immediately
        let vault = Vault::create(path, password.as_bytes()).context("failed to create vault")?;
        audit(profile)
            .append(&AuditEntry::success(profile, "init", None))
            .ok();
        emit_event(profile, "init", None);
        eprintln!("{} Vault for profile '{profile}' created.", "".green());
        backup_new_profile_password_if_configured(profile, &password)?;
        return Ok(vault);
    }

    eprintln!("{} No vault found for profile '{profile}'.", "i".blue());

    if !io::stdin().is_terminal() {
        anyhow::bail!("Vault not created. Run `tsafe --profile {profile} init` to set up.");
    }

    use inquire::Confirm;
    let confirmed = Confirm::new("Create it now?")
        .with_default(true)
        .prompt()
        .unwrap_or(false);
    if !confirmed {
        anyhow::bail!("Vault not created. Run `tsafe --profile {profile} init` to set up.");
    }

    let password = prompt_password_confirmed()?;
    let vault = Vault::create(path, password.as_bytes()).context("failed to create vault")?;
    audit(profile)
        .append(&AuditEntry::success(profile, "init", None))
        .ok();
    emit_event(profile, "init", None);
    eprintln!("{} Vault for profile '{profile}' created.", "".green());
    backup_new_profile_password_if_configured(profile, &password)?;
    onboarding_biometric_unlock(profile, &password)?;
    Ok(vault)
}

// ── Small shared utilities ────────────────────────────────────────────────────

/// Return the audit log handle for `profile`.
pub fn audit(profile: &str) -> AuditLog {
    AuditLog::new(&profile::audit_log_path(profile))
}

/// Parse `["env=prod", "team=backend"]` → `[("env","prod"), ("team","backend")]`.
pub fn parse_tag_filters(filters: &[String]) -> Vec<(&str, &str)> {
    filters
        .iter()
        .filter_map(|f| {
            let mut parts = f.splitn(2, '=');
            Some((parts.next()?, parts.next()?))
        })
        .collect()
}

/// Parse tag args into an owned map for `vault.set()`.
pub fn parse_tags_map(tags: &[String]) -> HashMap<String, String> {
    tags.iter()
        .filter_map(|t| {
            let mut p = t.splitn(2, '=');
            Some((p.next()?.to_string(), p.next()?.to_string()))
        })
        .collect()
}

/// Emit a stderr warning if `key` carries an `expires` tag that is past or within 30 days.
pub fn warn_if_expired(key: &str, tags: &HashMap<String, String>) {
    if let Some(exp) = tags.get("expires") {
        if let Ok(date) = chrono::NaiveDate::parse_from_str(exp, "%Y-%m-%d") {
            let today = Utc::now().date_naive();
            if date < today {
                eprintln!(
                    "{} '{}' expired on {} (tag expires={})",
                    "warn:".yellow().bold(),
                    key,
                    exp,
                    exp
                );
            } else {
                let days = (date - today).num_days();
                if days <= 30 {
                    eprintln!(
                        "{} '{}' expires in {} day(s) on {}",
                        "warn:".yellow().bold(),
                        key,
                        days,
                        exp
                    );
                }
            }
        }
    }
}

/// Copy `value` to the system clipboard and spawn a background thread that
/// clears the clipboard after 30 seconds.
pub fn set_clipboard(value: &str) -> Result<()> {
    // Use platform clipboard tool: clip.exe on Windows.
    #[cfg(target_os = "windows")]
    {
        let mut child = std::process::Command::new("clip")
            .stdin(std::process::Stdio::piped())
            .spawn()
            .context("could not launch clip.exe — clipboard unavailable")?;
        if let Some(mut stdin) = child.stdin.take() {
            stdin.write_all(value.as_bytes()).ok();
        }
        child.wait().ok();
    }
    #[cfg(target_os = "macos")]
    {
        let mut child = std::process::Command::new("pbcopy")
            .stdin(std::process::Stdio::piped())
            .spawn()
            .context("could not launch pbcopy — clipboard unavailable")?;
        if let Some(mut stdin) = child.stdin.take() {
            stdin.write_all(value.as_bytes()).ok();
        }
        child.wait().ok();
    }
    #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
    {
        // xclip fallback on Linux.
        let mut child = std::process::Command::new("xclip")
            .args(["-selection", "clipboard"])
            .stdin(std::process::Stdio::piped())
            .spawn()
            .context("could not launch xclip — install xclip or copy manually")?;
        if let Some(mut stdin) = child.stdin.take() {
            stdin.write_all(value.as_bytes()).ok();
        }
        child.wait().ok();
    }

    // Spawn a background thread to clear clipboard after 30 s.
    std::thread::spawn(|| {
        std::thread::sleep(std::time::Duration::from_secs(30));
        #[cfg(target_os = "windows")]
        {
            let _ = std::process::Command::new("cmd")
                .args(["/c", "echo off | clip"])
                .status();
        }
        #[cfg(target_os = "macos")]
        {
            // Direct pipe — no shell wrapper, no injection risk.
            if let Ok(mut child) = std::process::Command::new("pbcopy")
                .stdin(std::process::Stdio::piped())
                .spawn()
            {
                drop(child.stdin.take()); // send EOF → clears clipboard
                let _ = child.wait();
            }
        }
        #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
        {
            // Direct pipe — no shell wrapper.
            if let Ok(mut child) = std::process::Command::new("xclip")
                .args(["-selection", "clipboard"])
                .stdin(std::process::Stdio::piped())
                .spawn()
            {
                drop(child.stdin.take());
                let _ = child.wait();
            }
        }
    });

    Ok(())
}

// ── Onboarding helpers ────────────────────────────────────────────────────────

/// When to show the OS keychain prompt for the **vault master password**
/// (not individual secrets).
#[derive(Clone, Copy)]
pub enum MasterPasswordKeychainPrompt {
    /// After `tsafe init` / first vault — skip if keyring already has this profile.
    NewVault,
    /// After `tsafe rotate` — offer to replace the stored password so quick unlock stays valid.
    AfterRotate,
}

/// Offer saving the vault master password to the OS credential store
/// (Touch ID / Hello / PIN).
pub fn offer_os_keychain_for_master_password(
    profile: &str,
    password: &str,
    ctx: MasterPasswordKeychainPrompt,
) -> Result<()> {
    use std::io::IsTerminal;

    if std::env::var("TSAFE_PASSWORD").is_ok() || !std::io::stdin().is_terminal() {
        return Ok(());
    }
    match ctx {
        MasterPasswordKeychainPrompt::NewVault => {
            if keyring_store::has_password(profile) {
                return Ok(());
            }
        }
        MasterPasswordKeychainPrompt::AfterRotate => {
            if std::env::var("TSAFE_NEW_MASTER_PASSWORD").is_ok() {
                return Ok(());
            }
        }
    }

    let store_ok = keyring_store::probe_credential_store().is_ok();

    println!();
    if store_ok {
        match ctx {
            MasterPasswordKeychainPrompt::NewVault => {
                println!("{}", "Quick unlock — recommended".cyan().bold());
                println!(
                    "  Store your master password in this device's OS credential store so you can unlock \
                     with Touch ID, Face ID, Windows Hello, or your device PIN — without typing it every time."
                );
            }
            MasterPasswordKeychainPrompt::AfterRotate => {
                println!("{}", "Update OS keychain for quick unlock".cyan().bold());
                println!(
                    "  Your vault master password just changed. Save the new password to the OS credential store \
                     so Touch ID / empty-password unlock keeps working? (Any old stored password no longer matches.)"
                );
            }
        }
        println!(
            "  You can change this later with `tsafe biometric disable` or `tsafe biometric enable`."
        );
        println!();

        for attempt in 0..4 {
            if attempt > 0 {
                eprint!("  Please answer Y, n, or l. ");
            }
            eprint!(
                "{} [Y] Set up now   [n] Not now   [l] Later: ",
                "".cyan().bold()
            );
            io::stderr().flush().ok();
            let mut line = String::new();
            let n = io::stdin().lock().read_line(&mut line)?;
            if n == 0 {
                println!();
                println!("  When you're ready: tsafe --profile {profile} biometric enable");
                return Ok(());
            }
            match parse_onboarding_biometric_choice(line.as_str()) {
                Some('y') => {
                    keyring_store::store_password(profile, password)
                        .map_err(|e| anyhow::anyhow!("{e}"))?;
                    println!();
                    println!(
                        "{} Master password saved for quick unlock (profile '{}').",
                        "".green(),
                        profile
                    );
                    println!(
                        "  Leave the password empty when prompted (CLI or TUI) to use OS unlock, \
                         or run `tsafe biometric status`."
                    );
                    return Ok(());
                }
                Some('n') => {
                    println!();
                    println!(
                        "  Understood — you'll enter your master password when unlocking the vault."
                    );
                    println!(
                        "  To enable quick unlock later: tsafe --profile {profile} biometric enable"
                    );
                    return Ok(());
                }
                Some('l') => {
                    println!();
                    println!("  No problem — enable it when you're ready.");
                    println!("  tsafe --profile {profile} biometric enable");
                    return Ok(());
                }
                Some(_) | None => continue,
            }
        }
        println!();
        println!("  To enable quick unlock later: tsafe --profile {profile} biometric enable");
        return Ok(());
    }

    println!("{}", "Quick unlock".cyan().bold());
    println!(
        "  This environment doesn't appear to have a working OS credential store \
         (common over SSH or in CI)."
    );
    println!(
        "  On this machine with a desktop session, run: {}",
        format!("tsafe --profile {profile} biometric enable").cyan()
    );
    println!();
    Ok(())
}

/// After creating a vault on an interactive terminal, offer OS credential / quick unlock setup.
pub fn onboarding_biometric_unlock(profile: &str, password: &str) -> Result<()> {
    offer_os_keychain_for_master_password(profile, password, MasterPasswordKeychainPrompt::NewVault)
}

pub fn parse_onboarding_biometric_choice(line: &str) -> Option<char> {
    let t = line.trim().to_lowercase();
    if t.is_empty() {
        return Some('y');
    }
    match t.chars().next()? {
        'y' => Some('y'),
        'n' => Some('n'),
        'l' => Some('l'),
        _ => None,
    }
}

#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    // ── parse_tag_filters ─────────────────────────────────────────────────────

    #[test]
    fn parse_tag_filters_splits_key_value_pairs() {
        let filters = vec!["env=prod".to_string(), "team=backend".to_string()];
        let result = parse_tag_filters(&filters);
        assert_eq!(result, vec![("env", "prod"), ("team", "backend")]);
    }

    #[test]
    fn parse_tag_filters_skips_entries_without_equals() {
        let filters = vec!["no-equals".to_string(), "key=val".to_string()];
        let result = parse_tag_filters(&filters);
        assert_eq!(result, vec![("key", "val")]);
    }

    #[test]
    fn parse_tag_filters_empty_input_returns_empty() {
        assert!(parse_tag_filters(&[]).is_empty());
    }

    #[test]
    fn parse_tag_filters_value_may_contain_equals() {
        // splitn(2, '=') — the second segment can contain '=' characters.
        let filters = vec!["url=http://example.com?a=b&c=d".to_string()];
        let result = parse_tag_filters(&filters);
        assert_eq!(result, vec![("url", "http://example.com?a=b&c=d")]);
    }

    // ── parse_tags_map ────────────────────────────────────────────────────────

    #[test]
    fn parse_tags_map_produces_correct_map() {
        let tags = vec!["env=prod".to_string(), "team=backend".to_string()];
        let map = parse_tags_map(&tags);
        assert_eq!(map.get("env").map(String::as_str), Some("prod"));
        assert_eq!(map.get("team").map(String::as_str), Some("backend"));
        assert_eq!(map.len(), 2);
    }

    #[test]
    fn parse_tags_map_skips_entries_without_equals() {
        let tags = vec!["not-a-tag".to_string()];
        assert!(parse_tags_map(&tags).is_empty());
    }

    #[test]
    fn parse_tags_map_empty_input_is_empty() {
        assert!(parse_tags_map(&[]).is_empty());
    }

    #[test]
    fn parse_tags_map_value_may_contain_equals() {
        let tags = vec!["url=https://example.com?foo=bar".to_string()];
        let map = parse_tags_map(&tags);
        assert_eq!(
            map.get("url").map(String::as_str),
            Some("https://example.com?foo=bar")
        );
    }

    // ── parse_onboarding_biometric_choice ─────────────────────────────────────

    #[test]
    fn biometric_choice_empty_or_whitespace_means_yes() {
        assert_eq!(parse_onboarding_biometric_choice(""), Some('y'));
        assert_eq!(parse_onboarding_biometric_choice("\n"), Some('y'));
        assert_eq!(parse_onboarding_biometric_choice("   "), Some('y'));
    }

    #[test]
    fn biometric_choice_y_variants_return_yes() {
        assert_eq!(parse_onboarding_biometric_choice("y"), Some('y'));
        assert_eq!(parse_onboarding_biometric_choice("Y"), Some('y'));
        assert_eq!(parse_onboarding_biometric_choice("Y\n"), Some('y'));
    }

    #[test]
    fn biometric_choice_n_variants_return_no() {
        assert_eq!(parse_onboarding_biometric_choice("n"), Some('n'));
        assert_eq!(parse_onboarding_biometric_choice("N"), Some('n'));
        assert_eq!(parse_onboarding_biometric_choice("N\n"), Some('n'));
    }

    #[test]
    fn biometric_choice_l_variants_return_later() {
        assert_eq!(parse_onboarding_biometric_choice("l"), Some('l'));
        assert_eq!(parse_onboarding_biometric_choice("L"), Some('l'));
    }

    #[test]
    fn biometric_choice_unknown_char_returns_none() {
        assert_eq!(parse_onboarding_biometric_choice("x"), None);
        assert_eq!(parse_onboarding_biometric_choice("q"), None);
        assert_eq!(parse_onboarding_biometric_choice("?"), None);
    }

    // ── prompt_password (env-var path) ────────────────────────────────────────

    #[test]
    fn prompt_password_returns_env_var_value() {
        temp_env::with_var("TSAFE_PASSWORD", Some("my-secret-pw"), || {
            let pw = prompt_password("ignored prompt").unwrap();
            assert_eq!(pw, "my-secret-pw");
        });
    }

    #[test]
    fn prompt_password_confirmed_skips_confirm_when_env_var_set() {
        temp_env::with_var("TSAFE_PASSWORD", Some("env-pw"), || {
            let pw = prompt_password_confirmed().unwrap();
            assert_eq!(pw, "env-pw");
        });
    }

    // ── get_password_from_main ────────────────────────────────────────────────

    #[test]
    fn get_password_from_main_returns_none_for_main_profile() {
        // Avoids infinite recursion: "main" profile never looks up itself.
        assert!(get_password_from_main("main").is_none());
    }

    #[test]
    fn open_vault_with_access_profile_returns_read_only_handle() {
        let dir = tempdir().unwrap();
        let vault_dir = dir.path().join("vaults");
        std::fs::create_dir_all(&vault_dir).unwrap();

        temp_env::with_vars(
            [
                ("TSAFE_VAULT_DIR", Some(vault_dir.as_os_str())),
                ("TSAFE_PASSWORD", Some(std::ffi::OsStr::new("test-pw"))),
            ],
            || {
                let vault_path = profile::vault_path("default");
                {
                    let mut vault = Vault::create(&vault_path, b"test-pw").unwrap();
                    vault.set("API_KEY", "secret", HashMap::new()).unwrap();
                    vault.save().unwrap();
                }

                let opened =
                    open_vault_with_access_profile("default", RbacProfile::ReadOnly).unwrap();
                assert_eq!(opened.access_profile(), RbacProfile::ReadOnly);
                assert_eq!(opened.get("API_KEY").unwrap().as_str(), "secret");
            },
        );
    }

    #[test]
    fn open_vault_with_access_profile_read_only_missing_vault_does_not_create() {
        let dir = tempdir().unwrap();
        let vault_dir = dir.path().join("vaults");
        std::fs::create_dir_all(&vault_dir).unwrap();

        temp_env::with_vars(
            [
                ("TSAFE_VAULT_DIR", Some(vault_dir.as_os_str())),
                ("TSAFE_PASSWORD", Some(std::ffi::OsStr::new("test-pw"))),
            ],
            || {
                let missing_path = profile::vault_path("default");
                let err = match open_vault_with_access_profile("default", RbacProfile::ReadOnly) {
                    Ok(_) => panic!("expected missing read-only vault open to fail"),
                    Err(err) => err,
                };
                assert!(err.to_string().contains("vault not found"));
                assert!(!missing_path.exists());
            },
        );
    }
}

/// After first `tsafe init`, scan the working directory for .env files and offer
/// to import them so new users don't have to run `tsafe import` manually.
pub fn onboarding_import_dotenv(profile: &str, password: &str) -> Result<()> {
    let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
    let mut dotenv_files: Vec<std::path::PathBuf> = std::fs::read_dir(&cwd)
        .into_iter()
        .flatten()
        .flatten()
        .filter_map(|e| {
            let name = e.file_name();
            let s = name.to_string_lossy().into_owned();
            if s == ".env" || s.starts_with(".env.") {
                Some(e.path())
            } else {
                None
            }
        })
        .collect();
    dotenv_files.sort();
    if dotenv_files.is_empty() {
        return Ok(());
    }
    println!(
        "\n{} Found .env file(s) in the current directory:",
        "".cyan().bold()
    );
    for f in &dotenv_files {
        println!("  {}", f.display());
    }
    // Non-interactive: TSAFE_PASSWORD set or no TTY — skip the prompt.
    use std::io::IsTerminal as _;
    let non_interactive =
        std::env::var("TSAFE_PASSWORD").is_ok() || !std::io::stdin().is_terminal();
    if non_interactive {
        return Ok(());
    }
    eprint!("Import them into the new vault? [y/N]: ");
    io::stderr().flush().ok();
    let mut resp = String::new();
    io::stdin().lock().read_line(&mut resp)?;
    if !resp.trim().eq_ignore_ascii_case("y") {
        return Ok(());
    }
    // Re-open the vault we just created.
    let vault_path = profile::vault_path(profile);
    let mut vault = Vault::open(&vault_path, password.as_bytes())
        .context("could not reopen vault for onboarding import")?;
    let mut total = 0usize;
    for path in &dotenv_files {
        match tsenv::parse_dotenv(path) {
            Err(e) => eprintln!(
                "{} skipping {}: {e}",
                "warn:".yellow().bold(),
                path.display()
            ),
            Ok(pairs) => {
                let mut n = 0usize;
                for (k, v) in &pairs {
                    if vault.set(k, v, HashMap::new()).is_ok() {
                        audit(profile)
                            .append(&AuditEntry::success(profile, "import", Some(k)))
                            .ok();
                        n += 1;
                    }
                }
                println!("  {} {} secret(s) from {}", "".green(), n, path.display());
                total += n;
            }
        }
    }
    println!(
        "{} Onboarding complete — {total} secret(s) imported",
        "".green().bold()
    );
    Ok(())
}

// ── HTTP ──────────────────────────────────────────────────────────────────────

/// Shared ureq agent with standard tsafe timeout policy.
///
/// 10 s connect / 30 s read+write. Reuse a single instance per operation to
/// share the connection pool across multiple requests (HIBP loop, Vault LIST+GET).
pub fn build_http_agent() -> ureq::Agent {
    ureq::AgentBuilder::new()
        .timeout_connect(std::time::Duration::from_secs(10))
        .timeout_read(std::time::Duration::from_secs(30))
        .timeout_write(std::time::Duration::from_secs(30))
        .build()
}