hardware-enclave 0.1.3

Hardware-backed key management — macOS Secure Enclave, Windows TPM 2.0, Linux TPM/keyring — plus in-process memory protection
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
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
// Copyright 2026 Jay Gowdy
// SPDX-License-Identifier: MIT

//! Higher-level WSL installation orchestration.
//!
//! Provides the full "detect distros, find homes, inject shell blocks, install
//! dependencies" flow that sshenc, sso-jwt, and other enclave apps share.
#![allow(dead_code, unused_imports, unused_qualifications, unreachable_patterns)]

use super::detect::{detect_distros, WslDistro};
use super::shell_config::{install_block, uninstall_block, ShellBlockConfig};
use std::path::{Path, PathBuf};
#[cfg(target_os = "windows")]
use std::time::Duration;

/// Timeout for downloading a Linux release tarball from GitHub
/// (used by [`LinuxReleaseSpec`]). Generous so a slow GitHub mirror
/// doesn't kill the install, bounded so a wedged route doesn't
/// hang it forever.
#[cfg(target_os = "windows")]
const WSL_DEP_INSTALL_TIMEOUT: Duration = Duration::from_secs(300);

/// Timeout for quick WSL shell commands (chmod, which, ldd, etc.).
#[cfg(target_os = "windows")]
const WSL_QUICK_CMD_TIMEOUT: Duration = Duration::from_secs(15);

pub use super::detect::decode_wsl_output;

/// GitHub-release-driven Linux binary install spec.
///
/// When set on [`WslInstallConfig::auto_install_linux_release`], the
/// installer probes each detected distro's libc (glibc → `_gnu`,
/// musl → `_musl`), `curl`s the matching tarball from a GitHub
/// release URL, and `tar`-extracts the listed binaries straight to
/// `/usr/local/bin/`.
///
/// This replaces the old socat + npiperelay bridge-dependency install.
/// Native `sshenc-agent` (or whichever app) running inside the distro
/// supersedes the SSH-protocol-over-socat hack — the native agent
/// handles SSH protocol locally and crosses the WSL/Windows boundary
/// only for the JSON-RPC TPM bridge, which is a different
/// (deterministic) transport.
#[derive(Debug, Clone)]
pub struct LinuxReleaseSpec {
    /// GitHub repo in `owner/name` form, e.g. `"godaddy/sshenc"`.
    pub repo: String,
    /// Release tag to install, e.g. `"v0.6.36"`. Caller passes this
    /// in rather than reading `CARGO_PKG_VERSION` so consumer apps
    /// can pin to a known-good version on rollback if needed.
    pub tag: String,
    /// Tarball name for glibc-based distros, e.g.
    /// `"sshenc-x86_64-unknown-linux-gnu.tar.gz"`. Resolved to
    /// `https://github.com/{repo}/releases/download/{tag}/{asset_gnu}`.
    pub asset_gnu: String,
    /// Tarball name for musl-based distros, e.g.
    /// `"sshenc-x86_64-unknown-linux-musl.tar.gz"`. Used when the
    /// distro's `ldd --version` output doesn't mention "GNU".
    pub asset_musl: String,
    /// Binaries to install from the extracted tarball, e.g.
    /// `["sshenc", "sshenc-agent", "sshenc-keygen", "gitenc"]`.
    pub binaries: Vec<String>,
}

/// Configuration for WSL installation.
#[derive(Debug, Clone)]
pub struct WslInstallConfig {
    /// Application name (used in markers and messages).
    pub app_name: String,
    /// Shell block content to inject (the script body, without markers).
    pub shell_block: String,
    /// Optional: path to a Linux binary to copy into each distro.
    pub linux_binary_path: Option<PathBuf>,
    /// Target path for the Linux binary inside each distro
    /// (relative to home, e.g., `.local/bin/myapp`).
    pub linux_binary_target: Option<String>,
    /// Optional: download a matching Linux release tarball from
    /// GitHub at install time and extract the named binaries into
    /// `/usr/local/bin/`. Replaces the old socat+npiperelay dance.
    pub auto_install_linux_release: Option<LinuxReleaseSpec>,
    /// Binaries to remove from `/usr/local/bin/` on unconfigure.
    /// Set regardless of release/dev status so a `sshenc uninstall`
    /// from a dev build still removes binaries installed by a prior
    /// release build. Leave empty for apps that don't install to
    /// `/usr/local/bin/` (e.g. apps that only use `linux_binary_target`).
    pub linux_binaries_to_remove: Vec<String>,
}

/// Result of configuring or unconfiguring a single distro.
#[derive(Debug)]
pub struct DistroResult {
    /// Distribution name.
    pub distro_name: String,
    /// Outcome: Ok with a list of actions taken, or Err with an error message.
    pub outcome: Result<Vec<String>, String>,
}

/// Configure all detected WSL distros.
///
/// For each distro:
/// 1. Discovers the home directory via UNC path
/// 2. Copies a Linux binary if configured
/// 3. Injects the managed shell block into `.bashrc`/`.zshrc`
/// 4. Downloads + extracts the matching Linux release tarball into
///    `/usr/local/bin/` if `auto_install_linux_release` is set
///    (replaces the old socat + npiperelay bridge dependency path —
///    keeping a native agent inside the distro is the deterministic
///    transport, the SSH-protocol-over-socat hack is gone).
///
/// Returns one result per distro so the caller can report progress.
pub fn configure_all_distros(config: &WslInstallConfig) -> Vec<DistroResult> {
    let distros = detect_distros();
    distros
        .into_iter()
        .map(|distro| {
            let name = distro.name.clone();
            let outcome = configure_distro(&distro, config);
            DistroResult {
                distro_name: name,
                outcome,
            }
        })
        .collect()
}

/// Remove configuration from all detected WSL distros.
///
/// For each distro:
/// 1. Removes the managed shell block from `.bashrc`/`.zshrc`/`.profile`
/// 2. Removes the Linux binary if `linux_binary_target` is set
///
/// Returns one result per distro.
pub fn unconfigure_all_distros(config: &WslInstallConfig) -> Vec<DistroResult> {
    let distros = detect_distros();
    distros
        .into_iter()
        .map(|distro| {
            let name = distro.name.clone();
            let outcome = unconfigure_distro(&distro, config);
            DistroResult {
                distro_name: name,
                outcome,
            }
        })
        .collect()
}

/// Find the WSL user's home directory path from Windows as a UNC path.
///
/// Tries `\\wsl$\<distro>\<path>` first, then `\\wsl.localhost\<distro>\<path>`.
#[cfg(target_os = "windows")]
pub fn find_wsl_home(distro: &str) -> Option<PathBuf> {
    let linux_home = find_linux_home(distro)?;
    if linux_home.is_empty() {
        return None;
    }

    for prefix in &[r"\\wsl$", r"\\wsl.localhost"] {
        let win_path = format!(r"{}\{}{}", prefix, distro, linux_home.replace('/', r"\"));
        let path = PathBuf::from(&win_path);
        if path.exists() {
            return Some(path);
        }
    }

    None
}

/// Stub on non-Windows: always returns None.
#[cfg(not(target_os = "windows"))]
pub fn find_wsl_home(_distro: &str) -> Option<PathBuf> {
    None
}

/// Get the Linux home path string for a distro (e.g., `/home/user`).
#[cfg(target_os = "windows")]
fn find_linux_home(distro: &str) -> Option<String> {
    crate::internal::wsl::detect::linux_home(distro)
}

/// Configure a single WSL distro.
fn configure_distro(distro: &WslDistro, config: &WslInstallConfig) -> Result<Vec<String>, String> {
    let home_path = distro
        .home_path
        .as_ref()
        .ok_or_else(|| format!("could not find home directory for {}", distro.name))?;

    let mut actions = Vec::new();

    // Copy Linux binary if configured
    #[cfg(target_os = "windows")]
    if let (Some(src), Some(target)) = (&config.linux_binary_path, &config.linux_binary_target) {
        copy_linux_binary(home_path, src, target, &distro.name, &mut actions)?;
    }

    // Inject shell block into config files
    let block_config = ShellBlockConfig::new(&config.app_name, &config.shell_block);
    inject_shell_configs(home_path, &block_config, &mut actions)?;

    // Install Linux release binaries from GitHub (replaces the old
    // socat + npiperelay path).
    #[cfg(target_os = "windows")]
    if let Some(release) = config.auto_install_linux_release.as_ref() {
        install_linux_release(&distro.name, release, &mut actions)?;
    }

    Ok(actions)
}

/// Remove configuration from a single WSL distro.
fn unconfigure_distro(
    distro: &WslDistro,
    config: &WslInstallConfig,
) -> Result<Vec<String>, String> {
    let home_path = distro
        .home_path
        .as_ref()
        .ok_or_else(|| format!("could not find home directory for {}", distro.name))?;

    let mut actions = Vec::new();

    // Remove shell blocks
    let block_config = ShellBlockConfig::new(&config.app_name, &config.shell_block);
    for name in &[".bashrc", ".zshrc", ".profile"] {
        let path = home_path.join(name);
        if path.exists() {
            match uninstall_block(&path, &block_config) {
                Ok(crate::internal::wsl::shell_config::UninstallResult::Removed) => {
                    actions.push(format!("Removed block from {name}"));
                }
                Ok(crate::internal::wsl::shell_config::UninstallResult::NotPresent) => {}
                Err(e) => {
                    return Err(format!("{name}: {e}"));
                }
            }
        }
    }

    // Remove Linux binary if configured
    if let Some(target) = &config.linux_binary_target {
        let binary_path = home_path.join(target);
        if binary_path.exists() {
            std::fs::remove_file(&binary_path).map_err(|e| format!("remove binary: {e}"))?;
            actions.push(format!("Removed ~/{target}"));
        }
    }

    // Remove /usr/local/bin/ binaries installed by auto_install_linux_release.
    #[cfg(target_os = "windows")]
    if !config.linux_binaries_to_remove.is_empty() {
        remove_linux_release_binaries(&distro.name, &config.linux_binaries_to_remove, &mut actions);
    }

    // Clean up the app's runtime directory (~/.sshenc/ or ~/.{app_name}/).
    // This removes the agent socket and pid file; the keys subdirectory
    // is intentionally preserved (it contains user key material).
    #[cfg(target_os = "windows")]
    {
        let app = &config.app_name;
        let runtime_dir = home_path.join(format!(".{app}"));
        if runtime_dir.exists() {
            remove_runtime_files_in_distro(&distro.name, &runtime_dir, app, &mut actions);
        }
    }

    Ok(actions)
}

/// Remove the listed binaries from `/usr/local/bin/` inside a WSL distro.
/// Uses `sudo rm -f` — same privilege escalation path as the install side.
/// Best-effort: failures are reported as warnings, not errors.
#[cfg(target_os = "windows")]
fn remove_linux_release_binaries(
    distro_name: &str,
    binaries: &[String],
    actions: &mut Vec<String>,
) {
    let rm_args: Vec<String> = binaries
        .iter()
        .map(|b| format!("/usr/local/bin/{b}"))
        .collect();
    let script = format!(
        "set -e\nfor b in {}; do sudo rm -f \"$b\" 2>/dev/null || true; done",
        rm_args
            .iter()
            .map(|p| format!("'{p}'"))
            .collect::<Vec<_>>()
            .join(" ")
    );
    let mut cmd = std::process::Command::new("wsl");
    cmd.args(["-d", distro_name, "-e", "bash", "-c", &script]);
    match crate::internal::core::timeout::run_with_timeout(cmd, WSL_QUICK_CMD_TIMEOUT) {
        Ok(crate::internal::core::timeout::TimeoutResult::Completed(output))
            if output.status.success() =>
        {
            actions.push(format!(
                "Removed {} from /usr/local/bin/",
                binaries.join(", ")
            ));
        }
        Ok(crate::internal::core::timeout::TimeoutResult::Completed(output)) => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            actions.push(format!(
                "Warning: could not remove binaries from /usr/local/bin/ ({})",
                stderr.lines().next().unwrap_or("unknown error")
            ));
        }
        Ok(crate::internal::core::timeout::TimeoutResult::TimedOut) => {
            actions.push("Warning: timed out removing binaries from /usr/local/bin/".to_string());
        }
        Err(e) => {
            actions.push(format!(
                "Warning: could not launch wsl to remove binaries: {e}"
            ));
        }
    }
}

/// Remove agent runtime files (socket, pid) from the app's home dir in the
/// distro. Leaves subdirectories (e.g. `keys/`) intact.
#[cfg(target_os = "windows")]
fn remove_runtime_files_in_distro(
    distro_name: &str,
    runtime_dir: &Path,
    app_name: &str,
    actions: &mut Vec<String>,
) {
    let dir = runtime_dir.display().to_string();
    // Kill any running agent, then remove the socket and pid file.
    // `rmdir` at the end removes the directory only if it is now empty
    // (i.e. keys/ is gone too); if not, it is silently left behind.
    let script = format!(
        "set -e\n\
         pkill -TERM -x {app_name}-agent 2>/dev/null || true\n\
         sleep 0.3\n\
         rm -f '{dir}/agent.sock' '{dir}/agent.pid'\n\
         rmdir '{dir}' 2>/dev/null || true"
    );
    let mut cmd = std::process::Command::new("wsl");
    cmd.args(["-d", distro_name, "-e", "bash", "-c", &script]);
    drop(crate::internal::core::timeout::run_with_timeout(
        cmd,
        WSL_QUICK_CMD_TIMEOUT,
    ));
    actions.push(format!("Cleaned up runtime files in ~/.{app_name}/"));
}

/// Inject the managed shell block into shell config files.
fn inject_shell_configs(
    home_path: &Path,
    block_config: &ShellBlockConfig,
    actions: &mut Vec<String>,
) -> Result<(), String> {
    let mut configured = false;

    // .bashrc -- primary target for bash users
    let bashrc = home_path.join(".bashrc");
    if bashrc.exists() {
        match install_block(&bashrc, block_config) {
            Ok(crate::internal::wsl::shell_config::InstallResult::Installed) => {
                actions.push("Updated .bashrc".to_string());
                configured = true;
            }
            Ok(crate::internal::wsl::shell_config::InstallResult::AlreadyPresent) => {
                configured = true;
            }
            Err(e) => return Err(format!(".bashrc: {e}")),
        }
    }

    // .zshrc -- for zsh users
    let zshrc = home_path.join(".zshrc");
    if zshrc.exists() {
        match install_block(&zshrc, block_config) {
            Ok(crate::internal::wsl::shell_config::InstallResult::Installed) => {
                actions.push("Updated .zshrc".to_string());
                configured = true;
            }
            Ok(crate::internal::wsl::shell_config::InstallResult::AlreadyPresent) => {
                configured = true;
            }
            Err(e) => return Err(format!(".zshrc: {e}")),
        }
    }

    // Fallback: .profile or create .bashrc
    if !configured {
        let profile = home_path.join(".profile");
        if profile.exists() {
            match install_block(&profile, block_config) {
                Ok(crate::internal::wsl::shell_config::InstallResult::Installed) => {
                    actions.push("Updated .profile".to_string());
                }
                Ok(crate::internal::wsl::shell_config::InstallResult::AlreadyPresent) => {}
                Err(e) => return Err(format!(".profile: {e}")),
            }
        } else {
            // Create .bashrc as last resort
            match install_block(&bashrc, block_config) {
                Ok(_) => {
                    actions.push("Created .bashrc".to_string());
                }
                Err(e) => return Err(format!("create .bashrc: {e}")),
            }
        }
    }

    Ok(())
}

/// Copy a Linux binary into the distro's home directory.
#[cfg(target_os = "windows")]
fn copy_linux_binary(
    home_path: &Path,
    src: &Path,
    target: &str,
    distro_name: &str,
    actions: &mut Vec<String>,
) -> Result<(), String> {
    let dest = home_path.join(target);
    if let Some(parent) = dest.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("create directory {}: {e}", parent.display()))?;
    }
    std::fs::copy(src, &dest).map_err(|e| format!("copy binary: {e}"))?;

    // Make executable via WSL (bounded timeout so a wedged distro can't hang us).
    if let Some(linux_home) = find_linux_home(distro_name) {
        let linux_path = format!("{linux_home}/{target}");
        let mut cmd = std::process::Command::new("wsl");
        cmd.args(["-d", distro_name, "-e", "chmod", "+x", &linux_path]);
        drop(crate::internal::core::timeout::run_status_with_timeout(
            cmd,
            WSL_QUICK_CMD_TIMEOUT,
        ));
    }

    actions.push(format!("Installed binary to ~/{target}"));
    Ok(())
}

/// Detect whether the distro's libc is glibc (`Ok(true)`) or musl
/// (`Ok(false)`). Done by running `ldd --version` inside the
/// distro and checking the first line — glibc says "GNU libc",
/// musl says "musl libc". Anything else (e.g., Alpine where `ldd`
/// is part of busybox) defaults to musl since that's the only
/// statically-linked tarball that's guaranteed to run there.
#[cfg(target_os = "windows")]
fn distro_is_glibc(distro_name: &str) -> bool {
    let mut wsl = std::process::Command::new("wsl");
    wsl.args(["-d", distro_name, "-e", "ldd", "--version"]);
    match crate::internal::core::timeout::run_with_timeout(wsl, WSL_QUICK_CMD_TIMEOUT) {
        Ok(crate::internal::core::timeout::TimeoutResult::Completed(o)) => {
            let stdout = String::from_utf8_lossy(&o.stdout);
            let stderr = String::from_utf8_lossy(&o.stderr);
            let combined = format!("{stdout}{stderr}");
            // glibc's ldd prints to stdout and includes "GNU libc";
            // musl's ldd writes a usage line to stderr that mentions
            // "musl". Check both streams either way.
            combined.contains("GNU libc") || combined.contains("Free Software Foundation")
        }
        _ => false, // ldd missing → assume musl (statically-linked tarball runs anywhere)
    }
}

/// Download the matching Linux release tarball from GitHub and
/// extract the listed binaries into `/usr/local/bin/` inside the
/// distro. Done with `curl` and `tar`, both of which are present
/// in WSL distros (and on Windows but we run them inside the
/// distro so the artifacts go straight to the right filesystem
/// without crossing the WSL/Windows boundary).
#[cfg(target_os = "windows")]
fn install_linux_release(
    distro_name: &str,
    spec: &LinuxReleaseSpec,
    actions: &mut Vec<String>,
) -> Result<(), String> {
    let asset = if distro_is_glibc(distro_name) {
        &spec.asset_gnu
    } else {
        &spec.asset_musl
    };
    let url = format!(
        "https://github.com/{}/releases/download/{}/{}",
        spec.repo, spec.tag, asset
    );

    // Curl the tarball, untar into a per-PID work dir, atomically
    // replace the binaries under /usr/local/bin/. All in one bash
    // invocation so the installer runs in a single subprocess per
    // distro.
    //
    // Atomic rename rather than `cp` in place: writing over a
    // running ELF returns ETXTBSY on Linux ("text file busy"). The
    // previous mitigation tried `pkill -x sshenc-agent` before
    // `cp`, but in practice it was unreliable — on some distros
    // (`pgrep -x` doesn't match its own running agent on
    // AlmaLinux 9; pkill leaves siblings alive on Debian under
    // some race), so the `cp` still hit ETXTBSY and the user saw
    // a misleading "(network? release missing?)" warning. The
    // rename pattern (`cp src dst.tmp && mv dst.tmp dst`) sidesteps
    // the issue entirely: rename(2) atomically swaps the path
    // entry, leaving any running process with the old inode
    // (which lives until that process exits) and pointing all
    // future invocations at the new file. No kernel text-page
    // conflict, no install failure.
    //
    // Using a fixed `/tmp/sshenc-install-$$` rather than mktemp:
    // mktemp under `wsl bash -c` was observed to silently land in
    // `cd ""` on some distros, at which point `tar` extracted into
    // `$HOME` and collided with existing files.
    // `set -e` is the FIRST statement so every subsequent failure
    // aborts immediately. The previous structure stitched everything
    // together with `&&` and put `set -e` mid-chain, then ended with
    // `; pkill ... || true` — which made bash's exit code always 0
    // regardless of whether curl / tar / cp actually succeeded. The
    // wrapper saw `output.status.success() == true` and reported
    // "Installed" even when nothing had been copied. Multiple v0.6.71
    // installs reported success in 4 distros while leaving the
    // binaries at v0.6.70.
    //
    // The pkill at the end is gated by `||true` so it doesn't trip
    // `set -e` when no agent is running, but the install steps above
    // it can no longer be silently masked.
    let bins = spec.binaries.join(" ");
    let script = format!(
        "set -e\n\
         work=/tmp/sshenc-install-$$\n\
         rm -rf \"$work\"\n\
         mkdir -p \"$work\"\n\
         cd \"$work\"\n\
         trap 'rm -rf \"$work\"' EXIT\n\
         curl -fsSL '{url}' -o release.tar.gz\n\
         tar xzf release.tar.gz\n\
         for b in {bins}; do\n\
           sudo cp \"$b\" \"/usr/local/bin/$b.new\"\n\
           sudo chmod +x \"/usr/local/bin/$b.new\"\n\
           sudo mv \"/usr/local/bin/$b.new\" \"/usr/local/bin/$b\"\n\
         done\n\
         pkill -KILL -x sshenc-agent 2>/dev/null || true\n"
    );
    // `-e bash -c <script>` rather than `-- bash -c <script>`: the
    // `--` form runs the user's login shell as the wrapper, and
    // empirically that wrapper performs a layer of variable
    // expansion against ITS environment before bash -c sees the
    // script. So `foo=bar; echo "$foo"` arrives at bash as
    // `foo=bar; echo ""` and the install silently no-ops on every
    // path that depends on a script-local variable.
    // `-e <prog> <args>` execs `<prog>` directly without the login
    // shell wrapper, so bash -c sees the script intact and `$foo`
    // expands at the bash level as intended. Repro:
    //   wsl -d <distro> -- bash -c 'foo=bar; echo "[$foo]"' -> "[]"
    //   wsl -d <distro> -e bash -c 'foo=bar; echo "[$foo]"' -> "[bar]"
    let mut cmd = std::process::Command::new("wsl");
    cmd.args(["-d", distro_name, "-e", "bash", "-c", &script]);
    match crate::internal::core::timeout::run_with_timeout(cmd, WSL_DEP_INSTALL_TIMEOUT) {
        Ok(crate::internal::core::timeout::TimeoutResult::Completed(output))
            if output.status.success() =>
        {
            actions.push(format!(
                "Installed {} from {} {}",
                spec.binaries.join(", "),
                spec.repo,
                spec.tag
            ));
            Ok(())
        }
        Ok(crate::internal::core::timeout::TimeoutResult::TimedOut) => {
            actions.push(format!(
                "Warning: {} install timed out after {}s",
                spec.repo,
                WSL_DEP_INSTALL_TIMEOUT.as_secs()
            ));
            Ok(())
        }
        Ok(crate::internal::core::timeout::TimeoutResult::Completed(output)) => {
            // Non-zero exit. Surface the actual stderr (last few
            // lines, trimmed) instead of the old "(network? release
            // missing?)" guess that masked the real failure for
            // operators trying to diagnose a stuck distro.
            let stderr = String::from_utf8_lossy(&output.stderr);
            let tail: Vec<&str> = stderr
                .lines()
                .rev()
                .filter(|l| !l.trim().is_empty())
                .take(3)
                .collect();
            let detail: String = tail.into_iter().rev().collect::<Vec<_>>().join(" / ");
            let exit = output
                .status
                .code()
                .map(|c| format!("exit {c}"))
                .unwrap_or_else(|| "signaled".to_string());
            actions.push(format!(
                "Warning: failed to install {} from {} ({}: {})",
                spec.binaries.join(", "),
                url,
                exit,
                if detail.is_empty() {
                    "no stderr"
                } else {
                    detail.as_str()
                }
            ));
            Ok(())
        }
        Err(e) => {
            actions.push(format!(
                "Warning: failed to launch wsl install for {} ({e})",
                spec.binaries.join(", "),
            ));
            Ok(())
        }
    }
}

// `wsl_has_command` was used by the old socat / npiperelay path and
// is no longer needed — `install_linux_release` invokes `curl` + `tar`
// (both ubiquitous in WSL distros) directly via a single bash script.
// Removed rather than dead-coded so the per-distro setup path stays
// transparent.

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic, let_underscore_drop)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn test_dir(name: &str) -> PathBuf {
        let id = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let pid = std::process::id();
        let dir =
            std::env::temp_dir().join(format!("enclaveapp-wsl-install-test-{pid}-{id}-{name}"));
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn test_inject_shell_configs_bashrc() {
        let dir = test_dir("inject-bashrc");
        std::fs::write(dir.join(".bashrc"), "# existing\n").unwrap();

        let config = ShellBlockConfig::new("testapp", "export FOO=bar");
        let mut actions = Vec::new();
        inject_shell_configs(&dir, &config, &mut actions).unwrap();

        assert!(!actions.is_empty());
        let content = std::fs::read_to_string(dir.join(".bashrc")).unwrap();
        assert!(content.contains("BEGIN testapp managed block"));
        assert!(content.contains("export FOO=bar"));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_inject_shell_configs_zshrc() {
        let dir = test_dir("inject-zshrc");
        std::fs::write(dir.join(".zshrc"), "# zsh config\n").unwrap();

        let config = ShellBlockConfig::new("testapp", "export BAR=baz");
        let mut actions = Vec::new();
        inject_shell_configs(&dir, &config, &mut actions).unwrap();

        assert!(actions.iter().any(|a| a.contains(".zshrc")));
        let content = std::fs::read_to_string(dir.join(".zshrc")).unwrap();
        assert!(content.contains("export BAR=baz"));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_inject_shell_configs_both() {
        let dir = test_dir("inject-both");
        std::fs::write(dir.join(".bashrc"), "# bash\n").unwrap();
        std::fs::write(dir.join(".zshrc"), "# zsh\n").unwrap();

        let config = ShellBlockConfig::new("testapp", "export X=1");
        let mut actions = Vec::new();
        inject_shell_configs(&dir, &config, &mut actions).unwrap();

        assert!(actions.iter().any(|a| a.contains(".bashrc")));
        assert!(actions.iter().any(|a| a.contains(".zshrc")));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_inject_shell_configs_fallback_profile() {
        let dir = test_dir("inject-profile");
        // No .bashrc or .zshrc, only .profile
        std::fs::write(dir.join(".profile"), "# profile\n").unwrap();

        let config = ShellBlockConfig::new("testapp", "export Y=2");
        let mut actions = Vec::new();
        inject_shell_configs(&dir, &config, &mut actions).unwrap();

        assert!(actions.iter().any(|a| a.contains(".profile")));
        let content = std::fs::read_to_string(dir.join(".profile")).unwrap();
        assert!(content.contains("export Y=2"));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_inject_shell_configs_creates_bashrc() {
        let dir = test_dir("inject-create");
        // No existing shell configs at all

        let config = ShellBlockConfig::new("testapp", "export Z=3");
        let mut actions = Vec::new();
        inject_shell_configs(&dir, &config, &mut actions).unwrap();

        assert!(actions.iter().any(|a| a.contains(".bashrc")));
        let content = std::fs::read_to_string(dir.join(".bashrc")).unwrap();
        assert!(content.contains("export Z=3"));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_inject_idempotent() {
        let dir = test_dir("inject-idempotent");
        std::fs::write(dir.join(".bashrc"), "# existing\n").unwrap();

        let config = ShellBlockConfig::new("testapp", "export A=1");
        let mut actions1 = Vec::new();
        inject_shell_configs(&dir, &config, &mut actions1).unwrap();
        let content1 = std::fs::read_to_string(dir.join(".bashrc")).unwrap();

        let mut actions2 = Vec::new();
        inject_shell_configs(&dir, &config, &mut actions2).unwrap();
        let content2 = std::fs::read_to_string(dir.join(".bashrc")).unwrap();

        assert_eq!(content1, content2);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_unconfigure_distro_removes_blocks() {
        let dir = test_dir("unconfigure");
        std::fs::write(dir.join(".bashrc"), "# before\n").unwrap();

        let block_config = ShellBlockConfig::new("testapp", "export Q=1");
        install_block(dir.join(".bashrc").as_path(), &block_config).unwrap();

        let distro = WslDistro {
            name: "TestDistro".to_string(),
            home_path: Some(dir.clone()),
        };
        let config = WslInstallConfig {
            app_name: "testapp".to_string(),
            shell_block: "export Q=1".to_string(),
            auto_install_linux_release: None,
            linux_binary_path: None,
            linux_binary_target: None,
            linux_binaries_to_remove: vec![],
        };
        let result = unconfigure_distro(&distro, &config).unwrap();
        assert!(result.iter().any(|a| a.contains("Removed")));

        let content = std::fs::read_to_string(dir.join(".bashrc")).unwrap();
        assert!(!content.contains("BEGIN testapp managed block"));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_decode_wsl_output_utf8() {
        let input = b"Ubuntu\nDebian\n";
        let result = decode_wsl_output(input);
        assert_eq!(result, "Ubuntu\nDebian\n");
    }

    #[test]
    fn test_decode_wsl_output_utf16le_bom() {
        // UTF-16LE with BOM: "Hi\n"
        let mut bytes = vec![0xFF_u8, 0xFE]; // BOM
        for ch in "Hi\n".encode_utf16() {
            bytes.extend_from_slice(&ch.to_le_bytes());
        }
        let result = decode_wsl_output(&bytes);
        assert_eq!(result, "Hi\n");
    }

    #[test]
    fn test_find_wsl_home_non_windows() {
        // On non-Windows, always returns None
        #[cfg(not(target_os = "windows"))]
        assert!(find_wsl_home("Ubuntu").is_none());
    }

    #[test]
    fn test_distro_result_debug() {
        let result = DistroResult {
            distro_name: "Ubuntu".to_string(),
            outcome: Ok(vec!["Updated .bashrc".to_string()]),
        };
        let debug_str = format!("{result:?}");
        assert!(debug_str.contains("Ubuntu"));
    }

    #[test]
    fn test_wsl_install_config_clone() {
        let config = WslInstallConfig {
            app_name: "test".to_string(),
            shell_block: "# test".to_string(),
            auto_install_linux_release: None,
            linux_binary_path: None,
            linux_binary_target: None,
            linux_binaries_to_remove: vec![],
        };
        let cloned = config.clone();
        assert_eq!(cloned.app_name, config.app_name);
        assert_eq!(cloned.shell_block, config.shell_block);
    }

    #[test]
    fn test_decode_wsl_output_real_utf16le_bom() {
        // Simulate real UTF-16LE BOM output: "Ubuntu\r\n"
        let text = "Ubuntu\r\n";
        let mut bytes = vec![0xFF_u8, 0xFE]; // BOM
        for ch in text.encode_utf16() {
            bytes.extend_from_slice(&ch.to_le_bytes());
        }
        let result = decode_wsl_output(&bytes);
        assert_eq!(result, "Ubuntu\r\n");
    }

    #[test]
    fn test_decode_wsl_output_plain_utf8() {
        let input = b"Debian GNU/Linux\n";
        let result = decode_wsl_output(input);
        assert_eq!(result, "Debian GNU/Linux\n");
    }

    #[test]
    fn test_configure_distro_creates_backup_like_file() {
        // Configure a distro with shell configs — the .bashrc should be modified
        let dir = test_dir("configure-backup");
        let bashrc = dir.join(".bashrc");
        std::fs::write(&bashrc, "# original content\nexport PATH=/usr/bin\n").unwrap();
        let original_content = std::fs::read_to_string(&bashrc).unwrap();

        let distro = WslDistro {
            name: "TestDistro".to_string(),
            home_path: Some(dir.clone()),
        };
        let config = WslInstallConfig {
            app_name: "testapp".to_string(),
            shell_block: "export TEST=1".to_string(),
            auto_install_linux_release: None,
            linux_binary_path: None,
            linux_binary_target: None,
            linux_binaries_to_remove: vec![],
        };

        let result = configure_distro(&distro, &config).unwrap();
        assert!(!result.is_empty());

        // .bashrc should now contain the block
        let new_content = std::fs::read_to_string(&bashrc).unwrap();
        assert!(new_content.contains("BEGIN testapp managed block"));
        // Original content should still be present
        assert!(new_content.contains(&original_content.trim_end().to_string()));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_unconfigure_distro_removes_block_but_keeps_content() {
        let dir = test_dir("unconfigure-keep");
        let bashrc = dir.join(".bashrc");
        std::fs::write(&bashrc, "# my config\nexport FOO=bar\n").unwrap();

        let block_config = ShellBlockConfig::new("testapp", "export Q=1");
        install_block(bashrc.as_path(), &block_config).unwrap();

        // Verify block is there
        let content = std::fs::read_to_string(&bashrc).unwrap();
        assert!(content.contains("BEGIN testapp managed block"));

        let distro = WslDistro {
            name: "TestDistro".to_string(),
            home_path: Some(dir.clone()),
        };
        let config = WslInstallConfig {
            app_name: "testapp".to_string(),
            shell_block: "export Q=1".to_string(),
            auto_install_linux_release: None,
            linux_binary_path: None,
            linux_binary_target: None,
            linux_binaries_to_remove: vec![],
        };
        let result = unconfigure_distro(&distro, &config).unwrap();
        assert!(result.iter().any(|a| a.contains("Removed")));

        let final_content = std::fs::read_to_string(&bashrc).unwrap();
        assert!(!final_content.contains("BEGIN testapp managed block"));
        assert!(final_content.contains("# my config"));
        assert!(final_content.contains("export FOO=bar"));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_decode_wsl_output_utf16le_multiple_lines() {
        // UTF-16LE BOM with multiple lines: "Ubuntu\nDebian\n"
        let text = "Ubuntu\nDebian\n";
        let mut bytes = vec![0xFF_u8, 0xFE];
        for ch in text.encode_utf16() {
            bytes.extend_from_slice(&ch.to_le_bytes());
        }
        let result = decode_wsl_output(&bytes);
        assert_eq!(result, "Ubuntu\nDebian\n");
    }

    #[test]
    fn test_decode_wsl_output_empty_utf8() {
        let result = decode_wsl_output(b"");
        assert_eq!(result, "");
    }
}