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
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
//! `tsafe browser-native-host` — install / remove the native-messaging-host
//! manifest pointing at `tsafe-nativehost`. Per-OS branches:
//!
//! - Windows: Chromium-family HKCU registry keys + a host-specific manifest
//!   under `%LOCALAPPDATA%\tsafe\com.tsafe.host.<hash>.json`; Firefox
//!   filesystem manifest under `%APPDATA%\Mozilla\NativeMessagingHosts\`
//! - macOS: per-browser dirs under `~/Library/Application Support/<browser>/NativeMessagingHosts/`
//! - Linux: per-browser dirs under `~/.config/<browser>/NativeMessagingHosts/`
//!   plus `~/.mozilla/native-messaging-hosts/` for Firefox
//!
//! All paths are per-user; never elevates. Detects installed browsers via
//! application-bundle existence (macOS) or `which`-style PATH lookup
//! (Linux); skips silently for browsers not installed.

use anyhow::{Context, Result};
#[cfg(windows)]
use sha1::{Digest, Sha1};

use tsafe_cli::cli::BrowserNativeHostAction;

pub fn cmd_browser_native_host(action: BrowserNativeHostAction) -> Result<()> {
    #[cfg(windows)]
    {
        match action {
            BrowserNativeHostAction::Register { extension_id } => register_impl(&extension_id),
            BrowserNativeHostAction::Unregister => unregister_impl(),
            BrowserNativeHostAction::Detect => detect_impl_windows(),
        }
    }
    #[cfg(target_os = "macos")]
    {
        match action {
            BrowserNativeHostAction::Register { extension_id } => {
                unix_register_impl(&extension_id, MACOS_PATHS)
            }
            BrowserNativeHostAction::Unregister => unix_unregister_impl(MACOS_PATHS),
            BrowserNativeHostAction::Detect => unix_detect_impl(MACOS_PATHS),
        }
    }
    #[cfg(target_os = "linux")]
    {
        match action {
            BrowserNativeHostAction::Register { extension_id } => {
                unix_register_impl(&extension_id, LINUX_PATHS)
            }
            BrowserNativeHostAction::Unregister => unix_unregister_impl(LINUX_PATHS),
            BrowserNativeHostAction::Detect => unix_detect_impl(LINUX_PATHS),
        }
    }
    #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))]
    {
        let _ = action;
        anyhow::bail!("browser-native-host is only supported on Windows, macOS, and Linux");
    }
}

// ── Windows ────────────────────────────────────────────────────────────────

/// Chromium-family manifests live under %LOCALAPPDATA%\tsafe\ (not in
/// %APPDATA%) because they are per-machine-user and not roamed.  Firefox
/// manifests must go under %APPDATA%\Mozilla\NativeMessagingHosts\ per the
/// Firefox native-messaging specification.
#[cfg(windows)]
fn chromium_manifest_dir() -> Result<std::path::PathBuf> {
    let base = std::env::var_os("LOCALAPPDATA").context(
        "LOCALAPPDATA is unset; expected per-user manifest under %LOCALAPPDATA%\\tsafe\\",
    )?;
    Ok(std::path::Path::new(&base).join("tsafe"))
}

#[cfg(windows)]
fn firefox_manifest_dir() -> Result<std::path::PathBuf> {
    let base = std::env::var_os("APPDATA").context(
        "APPDATA is unset; expected Firefox manifest under %APPDATA%\\Mozilla\\NativeMessagingHosts\\",
    )?;
    Ok(std::path::Path::new(&base)
        .join("Mozilla")
        .join("NativeMessagingHosts"))
}

#[cfg(windows)]
fn sibling_host_exe_path() -> Result<std::path::PathBuf> {
    let tsafe = std::env::current_exe().context("could not resolve path to tsafe.exe")?;
    let dir = tsafe
        .parent()
        .context("tsafe.exe has no parent directory (unexpected)")?;
    Ok(dir.join("tsafe-nativehost.exe"))
}

#[cfg(windows)]
fn host_exe_path() -> Result<std::path::PathBuf> {
    let host = sibling_host_exe_path()?;
    if !host.is_file() {
        anyhow::bail!(
            "tsafe-nativehost.exe not found next to tsafe at {}.\n\
             Use the MSI or place tsafe-nativehost.exe beside tsafe.exe, then retry.",
            host.display()
        );
    }
    Ok(host)
}

/// Chromium-family native messaging manifest: uses `allowed_origins`.
#[cfg(windows)]
#[derive(serde::Serialize, serde::Deserialize)]
struct WindowsManifest {
    name: String,
    description: String,
    path: String,
    #[serde(rename = "type")]
    ty: String,
    allowed_origins: Vec<String>,
}

/// Firefox native messaging manifest: uses `allowed_extensions` instead of
/// `allowed_origins`.  The extension ID must match the `gecko.id` in the
/// extension's `browser_specific_settings` block.
#[cfg(windows)]
#[derive(serde::Serialize, serde::Deserialize)]
struct WindowsFirefoxManifest {
    name: String,
    description: String,
    path: String,
    #[serde(rename = "type")]
    ty: String,
    allowed_extensions: Vec<String>,
}

#[cfg(windows)]
fn manifest_path_for_host(host: &std::path::Path) -> Result<std::path::PathBuf> {
    let dir = chromium_manifest_dir()?;
    let mut hasher = Sha1::new();
    hasher.update(host.to_string_lossy().as_bytes());
    let digest = hasher.finalize();
    let suffix: String = digest[..6].iter().map(|b| format!("{b:02x}")).collect();
    Ok(dir.join(format!("com.tsafe.host.{suffix}.json")))
}

/// A Firefox extension ID is an email-address-like string (e.g.
/// `tsafe@tsafe.dev`) or a UUID in curly braces (e.g.
/// `{7a7a4a92-a2a0-41d1-9fd7-1e92480d612d}`).  Chromium-family IDs are
/// exactly 32 lowercase letters from the range `a–p`.
#[cfg(windows)]
fn is_firefox_extension_id(extension_id: &str) -> bool {
    // UUID-in-braces form
    if extension_id.starts_with('{') && extension_id.ends_with('}') {
        return true;
    }
    // Email-like form: must contain '@' and at least one '.' after the '@'
    if let Some(at_pos) = extension_id.find('@') {
        let domain = &extension_id[at_pos + 1..];
        return domain.contains('.');
    }
    false
}

#[cfg(windows)]
fn is_chromium_extension_id(extension_id: &str) -> bool {
    extension_id.len() == 32 && extension_id.chars().all(|ch| matches!(ch, 'a'..='p'))
}

#[cfg(windows)]
fn register_impl(extension_id: &str) -> Result<()> {
    use std::fs;

    let host = host_exe_path()?;
    let path_str = host
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("native host path is not valid UTF-8"))?
        .to_string();

    if is_firefox_extension_id(extension_id) {
        // Firefox path: write a filesystem manifest to %APPDATA%\Mozilla\NativeMessagingHosts\
        let dir = firefox_manifest_dir()?;
        fs::create_dir_all(&dir)
            .with_context(|| format!("create Firefox manifest directory {}", dir.display()))?;
        let manifest_path = dir.join("com.tsafe.host.json");
        let manifest = WindowsFirefoxManifest {
            name: "com.tsafe.host".to_string(),
            description: "tsafe vault native messaging host".to_string(),
            path: path_str,
            ty: "stdio".to_string(),
            allowed_extensions: vec![extension_id.to_string()],
        };
        let json = serde_json::to_string_pretty(&manifest)?;
        fs::write(&manifest_path, json)
            .with_context(|| format!("write Firefox manifest {}", manifest_path.display()))?;
        eprintln!(
            "Registered native messaging host com.tsafe.host (Firefox) → {}",
            manifest_path.display()
        );
        return Ok(());
    }

    if !is_chromium_extension_id(extension_id) {
        anyhow::bail!(
            "Unrecognised extension ID format: {extension_id:?}\n\
             Chromium-family IDs are 32 characters from a–p (find at chrome://extensions).\n\
             Firefox IDs are email-style (e.g. tsafe@tsafe.dev) or UUID in curly braces."
        );
    }

    // Chromium-family path: write JSON manifest + HKCU registry keys.
    let dir = chromium_manifest_dir()?;
    fs::create_dir_all(&dir).with_context(|| format!("create directory {}", dir.display()))?;
    let manifest_path = manifest_path_for_host(&host)?;
    let requested_origin = windows_allowed_origin(extension_id);
    let existing_origins = read_existing_windows_allowed_origins(&manifest_path)?;
    let merged_origins = merge_windows_allowed_origins(existing_origins, &requested_origin);

    let manifest = WindowsManifest {
        name: "com.tsafe.host".to_string(),
        description: "tsafe vault native messaging host".to_string(),
        path: path_str,
        ty: "stdio".to_string(),
        allowed_origins: merged_origins.clone(),
    };
    let json = serde_json::to_string_pretty(&manifest)?;
    fs::write(&manifest_path, json)
        .with_context(|| format!("write manifest {}", manifest_path.display()))?;

    let manifest_str = manifest_path
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("manifest path is not valid UTF-8"))?;

    write_chromium_registry(manifest_str)?;

    eprintln!(
        "Registered native messaging host com.tsafe.host → {} ({})",
        manifest_path.display(),
        merged_origins.join(", ")
    );
    Ok(())
}

#[cfg(all(test, windows))]
mod windows_tests {
    use super::{
        is_chromium_extension_id, is_firefox_extension_id, merge_windows_allowed_origins,
        windows_allowed_origin,
    };

    #[test]
    fn chromium_extension_ids_are_accepted() {
        assert!(is_chromium_extension_id("abcdefghijklmnopabcdefghijklmnop"));
    }

    #[test]
    fn firefox_email_style_id_is_detected() {
        assert!(is_firefox_extension_id("tsafe@tsafe.dev"));
        assert!(is_firefox_extension_id("tsafe@example.com"));
    }

    #[test]
    fn firefox_uuid_style_id_is_detected() {
        assert!(is_firefox_extension_id(
            "{7a7a4a92-a2a0-41d1-9fd7-1e92480d612d}"
        ));
    }

    #[test]
    fn chromium_id_is_not_firefox() {
        assert!(!is_firefox_extension_id("abcdefghijklmnopabcdefghijklmnop"));
    }

    #[test]
    fn merge_preserves_existing_allowed_origins() {
        let existing = vec![windows_allowed_origin("abcdefghijklmnopabcdefghijklmnop")];
        let merged = merge_windows_allowed_origins(
            existing,
            &windows_allowed_origin("ponmlkjihgfedcbaponmlkjihgfedcba"),
        );
        assert_eq!(
            merged,
            vec![
                windows_allowed_origin("abcdefghijklmnopabcdefghijklmnop"),
                windows_allowed_origin("ponmlkjihgfedcbaponmlkjihgfedcba"),
            ]
        );
    }

    #[test]
    fn merge_dedupes_allowed_origins() {
        let requested = windows_allowed_origin("abcdefghijklmnopabcdefghijklmnop");
        let merged = merge_windows_allowed_origins(vec![requested.clone()], &requested);
        assert_eq!(merged, vec![requested]);
    }
}

#[cfg(windows)]
fn windows_allowed_origin(extension_id: &str) -> String {
    format!("chrome-extension://{extension_id}/")
}

#[cfg(windows)]
fn read_existing_windows_allowed_origins(manifest_path: &std::path::Path) -> Result<Vec<String>> {
    use std::fs;

    if manifest_path.is_file() {
        let raw = fs::read_to_string(manifest_path)
            .with_context(|| format!("read existing manifest {}", manifest_path.display()))?;
        let manifest: WindowsManifest = serde_json::from_str(&raw)
            .with_context(|| format!("parse existing manifest {}", manifest_path.display()))?;
        return Ok(manifest.allowed_origins);
    }

    let legacy_path = chromium_manifest_dir()?.join("com.tsafe.host.json");
    if !legacy_path.is_file() {
        return Ok(Vec::new());
    }

    let raw = fs::read_to_string(&legacy_path)
        .with_context(|| format!("read legacy manifest {}", legacy_path.display()))?;
    let manifest: WindowsManifest = serde_json::from_str(&raw)
        .with_context(|| format!("parse legacy manifest {}", legacy_path.display()))?;
    Ok(manifest.allowed_origins)
}

#[cfg(windows)]
fn read_windows_manifest(manifest_path: &std::path::Path) -> Result<WindowsManifest> {
    let raw = std::fs::read_to_string(manifest_path)
        .with_context(|| format!("read manifest {}", manifest_path.display()))?;
    serde_json::from_str(&raw)
        .with_context(|| format!("parse manifest {}", manifest_path.display()))
}

#[cfg(windows)]
fn merge_windows_allowed_origins(mut existing: Vec<String>, requested_origin: &str) -> Vec<String> {
    if !existing.iter().any(|origin| origin == requested_origin) {
        existing.push(requested_origin.to_string());
    }
    existing.sort();
    existing.dedup();
    existing
}

#[cfg(windows)]
fn write_chromium_registry(manifest_path: &str) -> Result<()> {
    use winreg::enums::*;
    use winreg::RegKey;

    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    for rel in [
        r"Software\Google\Chrome\NativeMessagingHosts\com.tsafe.host",
        r"Software\BraveSoftware\Brave-Browser\NativeMessagingHosts\com.tsafe.host",
        r"Software\Chromium\NativeMessagingHosts\com.tsafe.host",
        r"Software\Microsoft\Edge\NativeMessagingHosts\com.tsafe.host",
    ] {
        let (key, _) = hkcu
            .create_subkey(rel)
            .with_context(|| format!("create registry key HKCU\\{rel}"))?;
        key.set_value("", &manifest_path)
            .with_context(|| format!("set default value for HKCU\\{rel}"))?;
    }
    Ok(())
}

#[cfg(windows)]
fn unregister_impl() -> Result<()> {
    use std::fs;
    use winreg::enums::*;
    use winreg::RegKey;

    let host = sibling_host_exe_path()?;
    let host_path = host
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("native host path is not valid UTF-8"))?
        .to_string();
    let primary_manifest_path = manifest_path_for_host(&host)?;
    let legacy_manifest_path = chromium_manifest_dir()?.join("com.tsafe.host.json");
    let mut owned_manifest_paths: Vec<std::path::PathBuf> = vec![primary_manifest_path.clone()];
    if !legacy_manifest_path.is_file() {
        owned_manifest_paths.push(legacy_manifest_path.clone());
    } else if let Ok(manifest) = read_windows_manifest(&legacy_manifest_path) {
        if manifest.path == host_path {
            owned_manifest_paths.push(legacy_manifest_path.clone());
        }
    }
    let hkcu = RegKey::predef(HKEY_CURRENT_USER);
    for rel in [
        r"Software\Google\Chrome\NativeMessagingHosts\com.tsafe.host",
        r"Software\BraveSoftware\Brave-Browser\NativeMessagingHosts\com.tsafe.host",
        r"Software\Chromium\NativeMessagingHosts\com.tsafe.host",
        r"Software\Microsoft\Edge\NativeMessagingHosts\com.tsafe.host",
    ] {
        match hkcu.open_subkey(rel) {
            Ok(key) => {
                let current_path = key.get_value::<String, _>("").ok();
                let owned_match = current_path.as_ref().is_some_and(|path| {
                    owned_manifest_paths
                        .iter()
                        .filter_map(|candidate| candidate.to_str())
                        .any(|candidate| candidate == path)
                });
                if owned_match {
                    if let Err(e) = hkcu.delete_subkey_all(rel) {
                        if e.kind() != std::io::ErrorKind::NotFound {
                            eprintln!("warning: could not remove HKCU\\{rel}: {e}");
                        }
                    }
                } else if let Some(path) = current_path {
                    eprintln!(
                        "  - leaving HKCU\\{rel} in place because it points at another tsafe manifest: {path}"
                    );
                }
            }
            Err(e) => {
                if e.kind() != std::io::ErrorKind::NotFound {
                    eprintln!("warning: could not inspect HKCU\\{rel}: {e}");
                }
            }
        }
    }

    for manifest_path in owned_manifest_paths {
        if !manifest_path.is_file() {
            continue;
        }
        if let Err(e) = fs::remove_file(&manifest_path) {
            eprintln!(
                "warning: could not remove manifest {}: {e}",
                manifest_path.display()
            );
        }
    }

    // Also remove the Firefox manifest if it points at this host binary.
    if let Ok(ff_dir) = firefox_manifest_dir() {
        let ff_manifest = ff_dir.join("com.tsafe.host.json");
        if ff_manifest.is_file() {
            let owned = std::fs::read_to_string(&ff_manifest)
                .ok()
                .and_then(|raw| serde_json::from_str::<WindowsFirefoxManifest>(&raw).ok())
                .is_some_and(|m| m.path == host_path);
            if owned {
                if let Err(e) = fs::remove_file(&ff_manifest) {
                    eprintln!(
                        "warning: could not remove Firefox manifest {}: {e}",
                        ff_manifest.display()
                    );
                } else {
                    eprintln!("  ✓ removed Firefox manifest {}", ff_manifest.display());
                }
            }
        }
    }

    eprintln!("Unregistered native messaging host com.tsafe.host");
    Ok(())
}

// ── Windows detect ────────────────────────────────────────────────────────

#[cfg(windows)]
fn detect_impl_windows() -> Result<()> {
    // Resolve the native-host binary (same logic as host_exe_path but non-fatal).
    let tsafe = std::env::current_exe().context("could not resolve path to tsafe.exe")?;
    let dir = tsafe
        .parent()
        .context("tsafe.exe has no parent directory")?;
    let host = dir.join("tsafe-nativehost.exe");
    let host_found = host.is_file();

    eprintln!("=== tsafe browser-native-host detect ===");
    eprintln!();
    if host_found {
        eprintln!("  native-host binary : FOUND");
        eprintln!("    {}", host.display());
    } else {
        eprintln!("  native-host binary : NOT FOUND");
        eprintln!("    Expected: {}", host.display());
        eprintln!("    Install via MSI, or place tsafe-nativehost.exe beside tsafe.exe.");
    }
    eprintln!();

    // Chromium manifest directory.
    let chromium_dir_result = chromium_manifest_dir();
    eprintln!("  Chromium manifest directory:");
    match &chromium_dir_result {
        Ok(d) => eprintln!("    {}", d.display()),
        Err(e) => eprintln!("    (could not resolve: {e})"),
    }
    eprintln!();

    // Registry keys that would be written.
    eprintln!("  HKCU registry keys that `register` (Chromium ID) would write:");
    for rel in [
        r"Software\Google\Chrome\NativeMessagingHosts\com.tsafe.host",
        r"Software\BraveSoftware\Brave-Browser\NativeMessagingHosts\com.tsafe.host",
        r"Software\Chromium\NativeMessagingHosts\com.tsafe.host",
        r"Software\Microsoft\Edge\NativeMessagingHosts\com.tsafe.host",
    ] {
        eprintln!("    HKCU\\{rel}");
    }
    eprintln!();

    // Firefox manifest directory.
    let firefox_dir_result = firefox_manifest_dir();
    eprintln!("  Firefox manifest directory:");
    match &firefox_dir_result {
        Ok(d) => {
            let ff_manifest = d.join("com.tsafe.host.json");
            let status = if ff_manifest.is_file() {
                " [already registered]"
            } else {
                ""
            };
            eprintln!("    {}{status}", ff_manifest.display());
        }
        Err(e) => eprintln!("    (could not resolve: {e})"),
    }
    eprintln!();

    if host_found {
        eprintln!("Next step (Chromium-family browsers):");
        eprintln!("  1. Load the extension in Chrome/Edge/Brave.");
        eprintln!("  2. Open chrome://extensions (or edge://extensions), enable Developer mode.");
        eprintln!("  3. Copy the 32-character extension ID shown beneath the extension name.");
        eprintln!("  4. Run:");
        eprintln!("       tsafe browser-native-host register --extension-id <32-char-id>");
        eprintln!();
        eprintln!("Next step (Firefox):");
        eprintln!("  1. Load the extension in Firefox (about:debugging → Load Temporary Add-on).");
        eprintln!("  2. Run:");
        eprintln!("       tsafe browser-native-host register --extension-id tsafe@tsafe.dev");
    } else {
        eprintln!("Fix the missing binary first, then re-run detect, then register.");
    }
    Ok(())
}

// ── Unix shared (macOS + Linux) ────────────────────────────────────────────

/// One per-browser entry: how to detect the browser is installed and where
/// to write the manifest. `app_marker` is a path that exists if the browser
/// is installed (an `.app` bundle on macOS, an executable on Linux).
#[cfg(any(target_os = "macos", target_os = "linux"))]
struct UnixBrowserPath {
    /// Display name for log lines.
    name: &'static str,
    /// Absolute path to a file that exists iff the browser is installed.
    /// macOS: `/Applications/<browser>.app`. Linux: `/usr/bin/<binary>` or
    /// `/snap/bin/<binary>`. Caller iterates these and skips browsers
    /// where the marker is missing.
    app_marker: &'static str,
    /// Manifest dir RELATIVE to $HOME.
    manifest_dir_under_home: &'static str,
    /// Whether this entry uses Firefox-style `allowed_extensions` (true) or
    /// Chromium-style `allowed_origins` (false).
    is_firefox: bool,
}

#[cfg(target_os = "macos")]
const MACOS_PATHS: &[UnixBrowserPath] = &[
    UnixBrowserPath {
        name: "Google Chrome",
        app_marker: "/Applications/Google Chrome.app",
        manifest_dir_under_home: "Library/Application Support/Google/Chrome/NativeMessagingHosts",
        is_firefox: false,
    },
    UnixBrowserPath {
        name: "Brave Browser",
        app_marker: "/Applications/Brave Browser.app",
        manifest_dir_under_home:
            "Library/Application Support/BraveSoftware/Brave-Browser/NativeMessagingHosts",
        is_firefox: false,
    },
    UnixBrowserPath {
        name: "Microsoft Edge",
        app_marker: "/Applications/Microsoft Edge.app",
        manifest_dir_under_home: "Library/Application Support/Microsoft Edge/NativeMessagingHosts",
        is_firefox: false,
    },
    UnixBrowserPath {
        name: "Chromium",
        app_marker: "/Applications/Chromium.app",
        manifest_dir_under_home: "Library/Application Support/Chromium/NativeMessagingHosts",
        is_firefox: false,
    },
    UnixBrowserPath {
        name: "Arc",
        app_marker: "/Applications/Arc.app",
        manifest_dir_under_home: "Library/Application Support/Arc/User Data/NativeMessagingHosts",
        is_firefox: false,
    },
    UnixBrowserPath {
        name: "Firefox",
        app_marker: "/Applications/Firefox.app",
        manifest_dir_under_home: "Library/Application Support/Mozilla/NativeMessagingHosts",
        is_firefox: true,
    },
];

#[cfg(target_os = "linux")]
const LINUX_PATHS: &[UnixBrowserPath] = &[
    UnixBrowserPath {
        name: "Google Chrome",
        app_marker: "/usr/bin/google-chrome",
        manifest_dir_under_home: ".config/google-chrome/NativeMessagingHosts",
        is_firefox: false,
    },
    UnixBrowserPath {
        name: "Chromium",
        app_marker: "/usr/bin/chromium",
        manifest_dir_under_home: ".config/chromium/NativeMessagingHosts",
        is_firefox: false,
    },
    UnixBrowserPath {
        name: "Microsoft Edge",
        app_marker: "/usr/bin/microsoft-edge",
        manifest_dir_under_home: ".config/microsoft-edge/NativeMessagingHosts",
        is_firefox: false,
    },
    UnixBrowserPath {
        name: "Brave Browser",
        app_marker: "/usr/bin/brave-browser",
        manifest_dir_under_home: ".config/BraveSoftware/Brave-Browser/NativeMessagingHosts",
        is_firefox: false,
    },
    UnixBrowserPath {
        name: "Firefox",
        app_marker: "/usr/bin/firefox",
        manifest_dir_under_home: ".mozilla/native-messaging-hosts",
        is_firefox: true,
    },
];

#[cfg(any(target_os = "macos", target_os = "linux"))]
#[derive(serde::Serialize)]
struct UnixManifestChromium {
    name: &'static str,
    description: &'static str,
    path: String,
    #[serde(rename = "type")]
    ty: &'static str,
    allowed_origins: Vec<String>,
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
#[derive(serde::Serialize)]
struct UnixManifestFirefox {
    name: &'static str,
    description: &'static str,
    path: String,
    #[serde(rename = "type")]
    ty: &'static str,
    allowed_extensions: Vec<String>,
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
fn unix_host_exe_path() -> Result<std::path::PathBuf> {
    // Prefer the binary next to `tsafe`, fall back to `~/.cargo/bin/tsafe-nativehost`,
    // then $PATH lookup. Documented chain so the user knows what we resolved.
    let tsafe = std::env::current_exe().context("could not resolve path to tsafe binary")?;
    if let Some(dir) = tsafe.parent() {
        let sibling = dir.join("tsafe-nativehost");
        if sibling.is_file() {
            return Ok(sibling);
        }
    }
    if let Some(home) = directories::UserDirs::new().map(|d| d.home_dir().to_path_buf()) {
        let cargo_bin = home.join(".cargo/bin/tsafe-nativehost");
        if cargo_bin.is_file() {
            return Ok(cargo_bin);
        }
    }
    anyhow::bail!(
        "tsafe-nativehost binary not found next to `tsafe` or in ~/.cargo/bin/.\n\
         Run `cargo install --path crates/tsafe-nativehost --locked --force` (from the tsafe repo)\n\
         or place the binary next to the tsafe executable."
    )
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
fn unix_register_impl(extension_id: &str, paths: &[UnixBrowserPath]) -> Result<()> {
    use std::fs;

    if extension_id.trim().is_empty() {
        anyhow::bail!("--extension-id is required (and must not be empty)");
    }
    let host = unix_host_exe_path()?;
    let host_str = host
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("native host path is not valid UTF-8"))?
        .to_string();
    let home = directories::UserDirs::new()
        .map(|d| d.home_dir().to_path_buf())
        .context("could not resolve $HOME")?;

    let mut wrote_any = false;
    let mut skipped: Vec<&str> = Vec::new();
    for browser in paths {
        let marker = std::path::Path::new(browser.app_marker);
        if !marker.exists() {
            skipped.push(browser.name);
            continue;
        }
        let target_dir = home.join(browser.manifest_dir_under_home);
        fs::create_dir_all(&target_dir)
            .with_context(|| format!("create directory {}", target_dir.display()))?;
        let manifest_path = target_dir.join("com.tsafe.host.json");
        let json = if browser.is_firefox {
            // Firefox expects an addon-id-shaped extension identifier in
            // `allowed_extensions` (e.g. "tsafe@tsafe.dev"). The same
            // --extension-id flag carries it; user is responsible for
            // passing the right form.
            serde_json::to_string_pretty(&UnixManifestFirefox {
                name: "com.tsafe.host",
                description: "tsafe vault native messaging host",
                path: host_str.clone(),
                ty: "stdio",
                allowed_extensions: vec![extension_id.to_string()],
            })?
        } else {
            serde_json::to_string_pretty(&UnixManifestChromium {
                name: "com.tsafe.host",
                description: "tsafe vault native messaging host",
                path: host_str.clone(),
                ty: "stdio",
                allowed_origins: vec![format!("chrome-extension://{extension_id}/")],
            })?
        };
        fs::write(&manifest_path, json)
            .with_context(|| format!("write manifest {}", manifest_path.display()))?;
        eprintln!("{}{}", browser.name, manifest_path.display());
        wrote_any = true;
    }

    if !skipped.is_empty() {
        eprintln!("  - skipped (not installed): {}", skipped.join(", "));
    }
    if !wrote_any {
        anyhow::bail!(
            "no supported browsers detected; nothing to register.\n\
             Checked: {}",
            paths.iter().map(|p| p.name).collect::<Vec<_>>().join(", ")
        );
    }
    eprintln!("\nRegistered native messaging host com.tsafe.host with extension {extension_id}");
    eprintln!("Reload the extension in your browser if it's already loaded.");
    Ok(())
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
fn unix_unregister_impl(paths: &[UnixBrowserPath]) -> Result<()> {
    use std::fs;
    let home = directories::UserDirs::new()
        .map(|d| d.home_dir().to_path_buf())
        .context("could not resolve $HOME")?;
    let mut removed_any = false;
    for browser in paths {
        let manifest_path = home
            .join(browser.manifest_dir_under_home)
            .join("com.tsafe.host.json");
        if manifest_path.is_file() {
            match fs::remove_file(&manifest_path) {
                Ok(()) => {
                    eprintln!("  ✓ removed {}", manifest_path.display());
                    removed_any = true;
                }
                Err(e) => {
                    eprintln!(
                        "  warning: could not remove {}: {e}",
                        manifest_path.display()
                    );
                }
            }
        }
    }
    if !removed_any {
        eprintln!("No tsafe native-host manifests found; nothing to remove.");
    }
    Ok(())
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
fn unix_detect_impl(paths: &[UnixBrowserPath]) -> Result<()> {
    // Resolve the native-host binary using the same chain as unix_host_exe_path
    // but non-fatally, so detect can report even when the binary is absent.
    let tsafe = std::env::current_exe().context("could not resolve path to tsafe binary")?;
    let sibling = tsafe.parent().map(|d| d.join("tsafe-nativehost"));
    let cargo_bin =
        directories::UserDirs::new().map(|d| d.home_dir().join(".cargo/bin/tsafe-nativehost"));

    let host_found_at: Option<std::path::PathBuf> = sibling
        .filter(|p| p.is_file())
        .or_else(|| cargo_bin.filter(|p| p.is_file()));

    let home = directories::UserDirs::new()
        .map(|d| d.home_dir().to_path_buf())
        .context("could not resolve $HOME")?;

    eprintln!("=== tsafe browser-native-host detect ===");
    eprintln!();
    match &host_found_at {
        Some(p) => {
            eprintln!("  native-host binary : FOUND");
            eprintln!("    {}", p.display());
        }
        None => {
            eprintln!("  native-host binary : NOT FOUND");
            if let Some(ref s) = sibling {
                eprintln!("    Checked sibling  : {}", s.display());
            }
            if let Some(ref c) = cargo_bin {
                eprintln!("    Checked cargo/bin: {}", c.display());
            }
            eprintln!("    Install via: cargo install --path crates/tsafe-nativehost --locked");
        }
    }
    eprintln!();

    eprintln!("  Manifest paths that `register` would write (installed browsers only):");
    let mut detected_any = false;
    let mut not_installed: Vec<&str> = Vec::new();
    for browser in paths {
        let marker = std::path::Path::new(browser.app_marker);
        if marker.exists() {
            let manifest_path = home
                .join(browser.manifest_dir_under_home)
                .join("com.tsafe.host.json");
            let current_status = if manifest_path.is_file() {
                " [already registered]"
            } else {
                ""
            };
            eprintln!(
                "    {}{}{}",
                browser.name,
                manifest_path.display(),
                current_status
            );
            detected_any = true;
        } else {
            not_installed.push(browser.name);
        }
    }
    if !not_installed.is_empty() {
        eprintln!("  Not installed (skipped): {}", not_installed.join(", "));
    }
    if !detected_any {
        eprintln!("  (no supported browsers detected)");
    }
    eprintln!();

    if host_found_at.is_some() && detected_any {
        eprintln!("Next step:");
        eprintln!("  1. Load the extension in your browser.");
        eprintln!("  2. Find the extension ID:");
        eprintln!("     Chrome/Edge/Brave: chrome://extensions (Developer mode)");
        eprintln!("     Firefox: the addon ID from your manifest.json (tsafe@tsafe.dev)");
        eprintln!("  3. Run:");
        eprintln!("       tsafe browser-native-host register --extension-id <id>");
    } else if host_found_at.is_none() {
        eprintln!("Fix the missing binary first, then re-run detect, then register.");
    } else {
        eprintln!("Install a supported browser first, then re-run detect.");
    }
    Ok(())
}