envseal 0.3.12

Write-only secret vault with process-level access control — post-agent secret management
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
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
//! GUI-environment threat assessment.
//!
//! Detects everything that would let an attacker subvert the approval
//! popup: remote sessions (SSH, RDP, VNC), input-injection tools that can
//! click "Approve" without a human, screen recorders that can capture
//! passphrase entry, accessibility automation, and the fundamentally
//! insecure X11 input model.
//!
//! [`assess_gui_security`] aggregates all of these into a single
//! [`GuiSecurityReport`] with a [`GuiThreatLevel`] used by the GUI module
//! to decide whether to allow, degrade, or refuse a popup.

use crate::error::Error;

/// Verify that a GUI dialog binary (`zenity`, `kdialog`) is trustworthy.
///
/// Checks:
/// 1. The binary exists at a system path (not user-writable).
/// 2. The binary is owned by root (Unix).
/// 3. The binary is not group/world writable (Unix).
///
/// Prevents the GUI spoofing attack where an agent puts a fake `zenity`
/// in `PATH` that captures the passphrase.
///
/// # Errors
/// Returns [`Error::BinaryResolution`] if the binary is missing or fails any
/// of the trust checks.
pub fn verify_gui_binary(name: &str) -> Result<std::path::PathBuf, Error> {
    let system_dirs = ["/usr/bin", "/usr/local/bin", "/bin", "/usr/sbin"];

    for dir in &system_dirs {
        let path = std::path::Path::new(dir).join(name);
        if path.exists() {
            verify_not_symlink_to_user_path(&path)?;

            #[cfg(unix)]
            {
                use std::os::unix::fs::MetadataExt;
                let meta = std::fs::metadata(&path).map_err(|e| {
                    Error::BinaryResolution(format!(
                        "cannot stat gui binary {}: {e}",
                        path.display()
                    ))
                })?;

                if meta.uid() != 0 {
                    return Err(Error::BinaryResolution(format!(
                        "gui binary {} is not owned by root (uid={}). \
                         this could be a spoofed binary.",
                        path.display(),
                        meta.uid()
                    )));
                }

                let mode = meta.mode();
                if mode & 0o022 != 0 {
                    return Err(Error::BinaryResolution(format!(
                        "gui binary {} is writable by non-root (mode={mode:04o}). \
                         this could be a tampered binary.",
                        path.display()
                    )));
                }
            }

            return Ok(path);
        }
    }

    Err(Error::BinaryResolution(format!(
        "gui binary '{name}' not found in system paths ({system_dirs:?}). \
         refusing to use PATH-resolved binary to prevent spoofing."
    )))
}

/// Verify a GUI binary path doesn't symlink to a user-writable location.
fn verify_not_symlink_to_user_path(path: &std::path::Path) -> Result<(), Error> {
    let meta = std::fs::symlink_metadata(path)
        .map_err(|e| Error::BinaryResolution(format!("cannot stat {}: {e}", path.display())))?;
    if meta.file_type().is_symlink() {
        let target = std::fs::read_link(path).map_err(|e| {
            Error::BinaryResolution(format!("cannot read symlink {}: {e}", path.display()))
        })?;
        let combined = if target.is_absolute() {
            target
        } else {
            path.parent()
                .map_or_else(|| target.clone(), |p| p.join(&target))
        };
        let normalized = std::fs::canonicalize(&combined).map_err(|e| {
            Error::BinaryResolution(format!(
                "cannot resolve gui binary symlink {} -> {}: {e}",
                path.display(),
                combined.display()
            ))
        })?;
        let norm_str = normalized.to_string_lossy();
        if norm_str.starts_with("/tmp")
            || norm_str.starts_with("/home")
            || norm_str.starts_with("/var/tmp")
        {
            return Err(Error::BinaryResolution(format!(
                "gui binary {} is a symlink to user-writable location {}. \
                 this could be a spoofed binary.",
                path.display(),
                normalized.display()
            )));
        }
    }
    Ok(())
}

/// Check if the current session is on X11 and warn about keylogging risk.
///
/// X11 has zero input isolation — any process connected to the same X
/// server can intercept all keystrokes via `xinput`. Wayland isolates
/// input per-surface and is safe.
#[must_use]
pub fn check_x11_keylog_risk() -> Option<String> {
    #[cfg(target_os = "linux")]
    {
        if let Ok(session_type) = std::env::var("XDG_SESSION_TYPE") {
            if session_type == "x11" {
                return Some(
                    "WARNING: running on X11. any process connected to this X server \
                     can intercept your passphrase keystrokes via xinput. \
                     switch to Wayland for input isolation."
                        .to_string(),
                );
            }
            if session_type == "wayland" {
                return None;
            }
        }

        if std::env::var("WAYLAND_DISPLAY").is_ok() {
            return None;
        }

        if std::env::var("DISPLAY").is_ok() {
            return Some(
                "WARNING: appears to be running on X11 (DISPLAY set, no WAYLAND_DISPLAY). \
                 passphrase keystrokes may be interceptable."
                    .to_string(),
            );
        }

        None
    }

    #[cfg(not(target_os = "linux"))]
    {
        None
    }
}

/// Physical presence status.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum PhysicalPresence {
    /// User is physically at the machine (local display, no SSH).
    Local,
    /// User is accessing via SSH (terminal only — no display).
    Ssh,
    /// User is accessing via X11 forwarding (SSH with display).
    X11Forward,
    /// User is accessing via remote desktop (RDP, VNC, etc.).
    RemoteDesktop(String),
    /// Cannot determine — treat as potentially remote.
    #[default]
    Unknown,
}

/// Detect whether the current session is a physical (local) session
/// or a remote session (SSH, VNC, RDP, X11 forwarding).
///
/// In Lockdown mode, remote sessions are blocked from accessing secrets.
/// This prevents an attacker with SSH/RDP access from approving their own
/// secret requests via the GUI popup.
///
/// **Priority order** (higher = more reliable):
///   1. SSH env vars + ancestor walk (definitive — we ARE in an SSH tree)
///   2. `loginctl` session `Remote=yes/no` (kernel-level, most reliable)
///   3. X server ancestry check (is our display served by `xrdp`/`Xvnc`?)
///   4. Fallback: if `DISPLAY` is set, assume local
#[must_use]
pub fn check_physical_presence() -> PhysicalPresence {
    if std::env::var("SSH_CLIENT").is_ok()
        || std::env::var("SSH_CONNECTION").is_ok()
        || std::env::var("SSH_TTY").is_ok()
        || is_ssh_ancestor()
    {
        if let Ok(display) = std::env::var("DISPLAY") {
            if display.starts_with("localhost:") || display.starts_with("127.0.0.1:") {
                return PhysicalPresence::X11Forward;
            }
        }
        return PhysicalPresence::Ssh;
    }

    #[cfg(target_os = "linux")]
    {
        if let Some(presence) = check_loginctl_session() {
            return presence;
        }

        if let Some(name) = detect_remote_desktop_for_session() {
            return PhysicalPresence::RemoteDesktop(name);
        }
    }

    #[cfg(target_os = "macos")]
    {
        if detect_macos_screen_sharing() {
            return PhysicalPresence::RemoteDesktop("Screen Sharing".to_string());
        }
    }

    #[cfg(target_os = "windows")]
    {
        if detect_windows_rdp() {
            return PhysicalPresence::RemoteDesktop("Remote Desktop".to_string());
        }
    }

    if std::env::var("DISPLAY").is_ok() || std::env::var("WAYLAND_DISPLAY").is_ok() {
        return PhysicalPresence::Local;
    }

    PhysicalPresence::Unknown
}

#[cfg(target_os = "linux")]
fn is_ssh_ancestor() -> bool {
    let mut pid = std::process::id();
    for _ in 0..20 {
        let stat_path = format!("/proc/{pid}/stat");
        if let Ok(stat) = std::fs::read_to_string(&stat_path) {
            let parts: Vec<&str> = stat.split_whitespace().collect();
            if parts.len() < 4 {
                break;
            }
            let comm = parts[1].trim_matches(|c| c == '(' || c == ')');
            if comm == "sshd" || comm == "dropbear" || comm == "mosh-server" {
                return true;
            }
            if let Ok(ppid) = parts[3].parse::<u32>() {
                if ppid == 0 || ppid == 1 {
                    break;
                }
                pid = ppid;
            } else {
                break;
            }
        } else {
            break;
        }
    }
    false
}

#[cfg(not(target_os = "linux"))]
fn is_ssh_ancestor() -> bool {
    false
}

/// Check `loginctl` for the current session's remote status.
#[cfg(target_os = "linux")]
fn check_loginctl_session() -> Option<PhysicalPresence> {
    let session_id = find_loginctl_session_id()?;

    let output = std::process::Command::new("loginctl")
        .args(["show-session", &session_id, "-p", "Remote"])
        .stderr(std::process::Stdio::null())
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let remote_line = String::from_utf8_lossy(&output.stdout);
    let remote_line = remote_line.trim();

    if remote_line == "Remote=yes" {
        let host_output = std::process::Command::new("loginctl")
            .args(["show-session", &session_id, "-p", "RemoteHost"])
            .stderr(std::process::Stdio::null())
            .output()
            .ok();

        let host = host_output.map_or_else(
            || "unknown".to_string(),
            |o| {
                String::from_utf8_lossy(&o.stdout)
                    .trim()
                    .strip_prefix("RemoteHost=")
                    .unwrap_or("unknown")
                    .to_string()
            },
        );

        return Some(PhysicalPresence::RemoteDesktop(format!(
            "remote session from {host}"
        )));
    }

    if remote_line == "Remote=no" {
        return Some(PhysicalPresence::Local);
    }

    None
}

/// Find the current `loginctl` session ID using multiple methods.
///
/// Methods tried in order:
///   1. `XDG_SESSION_ID` env var (set by `pam_systemd`).
///   2. `/proc/self/sessionid` (kernel audit session).
///   3. `loginctl list-sessions` filtered by our UID.
#[cfg(target_os = "linux")]
fn find_loginctl_session_id() -> Option<String> {
    if let Ok(id) = std::env::var("XDG_SESSION_ID") {
        let id = id.trim().to_string();
        if !id.is_empty() {
            return Some(id);
        }
    }

    if let Ok(id) = std::fs::read_to_string("/proc/self/sessionid") {
        let id = id.trim().to_string();
        if !id.is_empty() && id != "4294967295" {
            let check = std::process::Command::new("loginctl")
                .args(["show-session", &id, "-p", "Remote"])
                .stderr(std::process::Stdio::null())
                .output();
            if let Ok(output) = check {
                if output.status.success() && !output.stdout.is_empty() {
                    return Some(id);
                }
            }
        }
    }

    let uid = unsafe { libc::getuid() };
    let output = std::process::Command::new("loginctl")
        .args(["list-sessions", "--no-legend"])
        .stderr(std::process::Stdio::null())
        .output()
        .ok()?;

    if output.status.success() {
        let text = String::from_utf8_lossy(&output.stdout);
        for line in text.lines() {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 {
                if let Ok(line_uid) = parts[1].parse::<u32>() {
                    if line_uid == uid {
                        return Some(parts[0].to_string());
                    }
                }
            }
        }
    }

    None
}

/// Detect whether the current session's display is served by a remote
/// desktop server (`xrdp`, `Xvnc`, `vino-server`, …) by walking the parent
/// chain of the X server PID for `$DISPLAY`.
#[cfg(target_os = "linux")]
fn detect_remote_desktop_for_session() -> Option<String> {
    let display = std::env::var("DISPLAY").ok()?;
    let xserver_pid = find_x_server_pid(&display)?;

    let remote_parents = [
        ("xrdp", "xrdp"),
        ("xrdp-sesman", "xrdp"),
        ("xrdp-chansrv", "xrdp"),
        ("Xvnc", "VNC"),
        ("x11vnc", "VNC"),
        ("vino-server", "GNOME Screen Sharing"),
        ("tigervnc", "TigerVNC"),
        ("gnome-remote-desktop", "GNOME Remote Desktop"),
    ];

    let mut pid = xserver_pid;
    for _ in 0..30 {
        let stat_path = format!("/proc/{pid}/comm");
        if let Ok(comm) = std::fs::read_to_string(&stat_path) {
            let comm = comm.trim();
            for (process_name, label) in &remote_parents {
                if comm == *process_name {
                    return Some((*label).to_string());
                }
            }
        }

        let stat_path = format!("/proc/{pid}/stat");
        if let Ok(stat) = std::fs::read_to_string(&stat_path) {
            let parts: Vec<&str> = stat.split_whitespace().collect();
            if parts.len() < 4 {
                break;
            }
            if let Ok(ppid) = parts[3].parse::<u32>() {
                if ppid == 0 || ppid == 1 || ppid == pid {
                    break;
                }
                pid = ppid;
            } else {
                break;
            }
        } else {
            break;
        }
    }

    None
}

/// Find the PID of the X server serving the given `DISPLAY`.
#[cfg(target_os = "linux")]
fn find_x_server_pid(display: &str) -> Option<u32> {
    let x_server_names = ["Xorg", "X", "Xwayland", "Xephyr", "Xvnc", "Xrdp", "xrdp"];

    if let Ok(entries) = std::fs::read_dir("/proc") {
        for entry in entries.flatten() {
            let path = entry.path();
            let name = entry.file_name();
            let name_str = name.to_string_lossy();

            if !name_str.chars().all(|c| c.is_ascii_digit()) {
                continue;
            }

            let comm_path = path.join("comm");
            if let Ok(comm) = std::fs::read_to_string(&comm_path) {
                let comm = comm.trim();
                if x_server_names.contains(&comm) {
                    if let Ok(cmdline) = std::fs::read_to_string(path.join("cmdline")) {
                        let cmdline = cmdline.replace('\0', " ");
                        if cmdline.contains(display)
                            || cmdline.contains(&display.replace(':', " :"))
                        {
                            return name_str.parse().ok();
                        }
                    }
                }
            }
        }
    }

    None
}

/// Detect macOS Screen Sharing.
#[cfg(target_os = "macos")]
fn detect_macos_screen_sharing() -> bool {
    std::process::Command::new("pgrep")
        .args(["-x", "ScreensharingD"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Detect Windows Remote Desktop session.
#[cfg(target_os = "windows")]
fn detect_windows_rdp() -> bool {
    std::env::var("SESSIONNAME")
        .map(|v| v.starts_with("RDP-"))
        .unwrap_or(false)
}

/// Threats detected during GUI security assessment.
#[derive(Debug, Clone, Default)]
pub struct GuiSecurityReport {
    /// Detected input injection tools (`xdotool`, `xte`, `xdo`, …).
    pub input_injectors: Vec<String>,
    /// Detected screen recording processes.
    pub screen_recorders: Vec<String>,
    /// Detected accessibility automation tools.
    pub accessibility_tools: Vec<String>,
    /// Physical presence status.
    pub presence: PhysicalPresence,
    /// Whether X11 (insecure input) is in use.
    pub x11_session: bool,
    /// Overall threat level: safe, degraded, or hostile.
    pub threat_level: GuiThreatLevel,
}

/// Overall GUI security threat level.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum GuiThreatLevel {
    /// No threats detected — safe for passphrase prompts.
    #[default]
    Safe,
    /// Degraded security — warn user but allow operation.
    /// (e.g., X11 without injectors detected, or screen recorder present)
    Degraded(String),
    /// Hostile environment — block passphrase prompts in Lockdown mode.
    /// (e.g., input injectors running, remote session, or SSH)
    Hostile(String),
}

/// Run a comprehensive GUI security assessment.
///
/// Checks for:
/// 1. Remote session (SSH, RDP, VNC).
/// 2. Input injection tools (`xdotool`, `xte`, `xdo`, `ydotool`, `wtype`).
/// 3. Screen recording software.
/// 4. Accessibility automation.
/// 5. X11 keylogging risk.
///
/// Used before displaying passphrase prompts to determine the appropriate
/// security tier response.
#[must_use]
pub fn assess_gui_security() -> GuiSecurityReport {
    let presence = check_physical_presence();

    #[allow(unused_mut, unused_assignments)]
    let mut x11_session = false;
    #[cfg(target_os = "linux")]
    {
        x11_session = detect_x11_session();
    }

    #[allow(unused_mut, unused_assignments)]
    let mut input_injectors = Vec::new();
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    {
        input_injectors = detect_input_injectors();
    }

    let screen_recorders = detect_screen_recorders();

    #[allow(unused_mut, unused_assignments)]
    let mut accessibility_tools = Vec::new();
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    {
        accessibility_tools = detect_accessibility_automation();
    }

    let mut report = GuiSecurityReport {
        input_injectors,
        screen_recorders,
        accessibility_tools,
        presence,
        x11_session,
        threat_level: GuiThreatLevel::Safe,
    };

    report.threat_level = compute_threat_level(&report);

    report
}

/// Run the full GUI assessment and emit it as a uniform signal stream.
///
/// This is the new shape every detector should produce: each
/// detected condition becomes one [`super::Signal`] with a stable
/// id, category, severity, and mitigation hint. Approval decisions
/// then flow through [`super::evaluate`] against the active
/// [`super::Policy`] and [`crate::security_config::SecurityTier`] —
/// no `if`-ladder per heuristic.
///
/// Returns an empty `Vec` when nothing fired. Composes cleanly with
/// other future signal producers (env, disk, audit, sandbox) by
/// concatenating their outputs.
#[must_use]
pub fn assess_gui_signals(_ctx: &super::DetectorContext) -> Vec<super::Signal> {
    let report = assess_gui_security();
    let mut signals = Vec::new();

    match &report.presence {
        PhysicalPresence::Ssh => signals.push(super::Signal::new(
            super::SignalId::new("gui.presence.ssh"),
            super::Category::GuiPresence,
            super::Severity::Hostile,
            "SSH session detected",
            "no local display available for GUI approval",
            "use the paired-device relay (`security set relay_required true`) or run envseal locally",
        )),
        PhysicalPresence::X11Forward => signals.push(super::Signal::new(
            super::SignalId::new("gui.presence.x11_forward"),
            super::Category::GuiPresence,
            super::Severity::Hostile,
            "X11 forwarding active",
            "passphrase keystrokes interceptable by the remote host",
            "switch to a local session or paired-device relay",
        )),
        PhysicalPresence::RemoteDesktop(name) => signals.push(super::Signal::new(
            super::SignalId::new("gui.presence.remote_desktop"),
            super::Category::GuiPresence,
            super::Severity::Hostile,
            "remote desktop session active",
            format!("controlled remotely via {name}"),
            "use a local session for sensitive operations",
        )),
        PhysicalPresence::Unknown | PhysicalPresence::Local => {}
    }

    for tool in &report.input_injectors {
        signals.push(super::Signal::new(
            super::SignalId::scoped("gui.input_injector", tool),
            super::Category::InputInjection,
            super::Severity::Hostile,
            "input injection tool running",
            format!("`{tool}` can synthesize keystrokes / clicks on this session"),
            "stop the process before approving secret access",
        ));
    }

    for rec in &report.screen_recorders {
        signals.push(super::Signal::new(
            super::SignalId::scoped("gui.screen_recorder", rec),
            super::Category::ScreenRecording,
            super::Severity::Degraded,
            "screen recorder running",
            format!("`{rec}` may capture passphrase entry"),
            "stop screen recording before entering credentials",
        ));
    }

    if report.x11_session {
        signals.push(super::Signal::new(
            super::SignalId::new("gui.session.x11"),
            super::Category::GuiPresence,
            super::Severity::Degraded,
            "X11 session — no input isolation",
            "any process on this display can read keystrokes",
            "switch to Wayland or use the on-screen keyboard for passphrase entry",
        ));
    }

    for tool in &report.accessibility_tools {
        signals.push(super::Signal::new(
            super::SignalId::scoped("gui.accessibility_bridge", tool),
            super::Category::AccessibilityBridge,
            super::Severity::Warn,
            "accessibility automation running",
            format!("`{tool}` could synthesize approval clicks"),
            "review accessibility-tool configuration",
        ));
    }

    signals
}

/// Compute the overall threat level from individual checks.
fn compute_threat_level(report: &GuiSecurityReport) -> GuiThreatLevel {
    match &report.presence {
        PhysicalPresence::Ssh => {
            return GuiThreatLevel::Hostile(
                "SSH session — no local display for GUI approval".to_string(),
            );
        }
        PhysicalPresence::X11Forward => {
            return GuiThreatLevel::Hostile(
                "X11 forwarding — passphrase interceptable by remote host".to_string(),
            );
        }
        PhysicalPresence::RemoteDesktop(name) => {
            return GuiThreatLevel::Hostile(format!(
                "remote desktop ({name}) — GUI can be controlled remotely"
            ));
        }
        PhysicalPresence::Unknown | PhysicalPresence::Local => {}
    }

    if !report.input_injectors.is_empty() {
        return GuiThreatLevel::Hostile(format!(
            "input injection tools detected: {}. these can simulate mouse clicks \
             to auto-approve passphrase prompts.",
            report.input_injectors.join(", ")
        ));
    }

    if !report.screen_recorders.is_empty() {
        return GuiThreatLevel::Degraded(format!(
            "screen recording detected: {}. passphrase entry may be captured.",
            report.screen_recorders.join(", ")
        ));
    }

    if report.x11_session {
        return GuiThreatLevel::Degraded(
            "X11 session — any process can intercept keystrokes. \
             use virtual keyboard for passphrase entry."
                .to_string(),
        );
    }

    if !report.accessibility_tools.is_empty() {
        return GuiThreatLevel::Degraded(format!(
            "accessibility automation detected: {}. these can simulate input events.",
            report.accessibility_tools.join(", ")
        ));
    }

    GuiThreatLevel::Safe
}

/// Detect X11 session (as opposed to Wayland which has input isolation).
#[cfg(target_os = "linux")]
fn detect_x11_session() -> bool {
    if let Ok(session_type) = std::env::var("XDG_SESSION_TYPE") {
        return session_type == "x11";
    }
    std::env::var("DISPLAY").is_ok() && std::env::var("WAYLAND_DISPLAY").is_err()
}

/// Detect running input injection tools.
#[cfg(target_os = "linux")]
fn detect_input_injectors() -> Vec<String> {
    // Process-name detection is the SECOND line of defense — the
    // first is `kernel.yama.ptrace_scope` (Linux) and Wayland's
    // per-surface input isolation. A renamed injector slips through
    // a name match but still has to defeat OS-level isolation,
    // which Lockdown enforces separately.
    //
    // The list covers the active ecosystem of GUI automation tools
    // an attacker would actually reach for, across all three
    // platforms. Adding to this is cheap; missing a tool means a
    // detector that's silently weaker than the docs claim.
    let injection_tools = [
        // X11 (Linux)
        ("xdotool", "xdotool (X11 input simulator)"),
        ("xte", "xte (xautomation toolkit)"),
        ("xdo", "xdo (X11 window/input tool)"),
        ("xmacro", "xmacro (X11 macro recorder)"),
        // uinput / Wayland (Linux)
        ("ydotool", "ydotool (uinput-based input simulator)"),
        ("ydotoold", "ydotool daemon (uinput injector)"),
        ("wtype", "wtype (Wayland keystroke injector)"),
        ("dotool", "dotool (uinput-based, Wayland-compatible)"),
        ("dotoold", "dotool daemon (uinput injector)"),
        ("evemu-event", "evemu (uinput event replay)"),
        ("evemu-play", "evemu (uinput event playback)"),
        // Generic Linux desktop automation
        ("autokey", "autokey (desktop automation)"),
        ("autokey-gtk", "autokey-gtk"),
        ("autokey-qt", "autokey-qt"),
        // Windows
        ("AutoHotkey", "AutoHotkey (input automation)"),
        ("AutoHotkey.exe", "AutoHotkey (input automation)"),
        ("AutoHotkeyU64.exe", "AutoHotkey U64 (input automation)"),
        ("AutoIt3.exe", "AutoIt3 (Windows automation)"),
        ("AutoIt3_x64.exe", "AutoIt3 x64 (Windows automation)"),
        ("nircmd.exe", "NirCmd (Windows command-line automation)"),
        ("nircmdc.exe", "NirCmd console"),
        // macOS
        ("cliclick", "cliclick (macOS click/keystroke automation)"),
    ];

    detect_running_processes(&injection_tools)
}

#[cfg(target_os = "macos")]
fn detect_input_injectors() -> Vec<String> {
    let injection_tools = [
        ("osascript", "osascript (AppleScript automation)"),
        ("cliclick", "cliclick (macOS input simulator)"),
        ("MouseTools", "MouseTools (mouse control)"),
    ];

    detect_running_processes(&injection_tools)
}

#[cfg(target_os = "windows")]
fn detect_input_injectors() -> Vec<String> {
    let injection_tools = [
        ("AutoHotkey.exe", "AutoHotkey (Windows input automation)"),
        ("autoit3.exe", "AutoIt (Windows automation)"),
        ("AutoIt.exe", "AutoIt (Windows automation)"),
        ("macrorecorder.exe", "Macro Recorder"),
        ("pulover.exe", "Pulover's Macro Creator"),
    ];

    detect_running_processes(&injection_tools)
}

/// Detect running screen recording software.
fn detect_screen_recorders() -> Vec<String> {
    #[cfg(target_os = "linux")]
    {
        let recorders = [
            ("obs", "OBS Studio"),
            ("obs-studio", "OBS Studio"),
            ("simplescreenrecorder", "SimpleScreenRecorder"),
            ("kazam", "Kazam"),
            ("peek", "Peek (GIF recorder)"),
            ("recordmydesktop", "RecordMyDesktop"),
            ("ffmpeg", "ffmpeg"),
            ("wf-recorder", "wf-recorder (Wayland)"),
            ("gpu-screen-recorder", "GPU Screen Recorder"),
        ];
        detect_running_processes(&recorders)
    }

    #[cfg(target_os = "macos")]
    {
        let recorders = [
            ("screencapturekit", "ScreenCaptureKit"),
            ("OBS", "OBS Studio"),
        ];
        detect_running_processes(&recorders)
    }

    #[cfg(target_os = "windows")]
    {
        let recorders = [
            ("obs64.exe", "OBS Studio"),
            ("obs32.exe", "OBS Studio"),
            ("ShareX.exe", "ShareX"),
            ("CamtasiaStudio.exe", "Camtasia"),
            ("SnagitCapture.exe", "Snagit"),
            ("Bandicam.exe", "Bandicam"),
            ("Action.exe", "Action!"),
            ("screenrecorder.exe", "Screen Recorder"),
        ];
        detect_running_processes(&recorders)
    }
}

/// Detect accessibility automation tools.
#[cfg(target_os = "linux")]
fn detect_accessibility_automation() -> Vec<String> {
    let a11y_tools = [
        ("at-spi-bus-launcher", "AT-SPI (accessibility bus)"),
        ("dogtail", "Dogtail (a11y testing tool)"),
        ("ldtp", "LDTP (Linux Desktop Testing Project)"),
        ("accerciser", "Accerciser (a11y inspector)"),
    ];

    let mut found = detect_running_processes(&a11y_tools);

    // AT-SPI is the standard Linux accessibility bus and is running
    // in nearly every desktop session — its presence alone is not a
    // signal of an attacker. Clear the result if AT-SPI is the only
    // accessibility tool detected.
    if found.iter().any(|f| f.contains("AT-SPI")) && found.len() <= 1 {
        found.clear();
    }

    found
}

#[cfg(target_os = "macos")]
fn detect_accessibility_automation() -> Vec<String> {
    let a11y_tools = [
        ("ScriptEditor", "Script Editor (macOS automation)"),
        ("Automator", "Automator (macOS workflow automation)"),
        ("Hammerspoon", "Hammerspoon (macOS scripting)"),
    ];

    detect_running_processes(&a11y_tools)
}

#[cfg(target_os = "windows")]
fn detect_accessibility_automation() -> Vec<String> {
    let a11y_tools = [("Narrator.exe", "Narrator (screen reader / a11y bridge)")];

    detect_running_processes(&a11y_tools)
}

/// Scan `/proc` for processes matching known tool names (Linux).
#[cfg(target_os = "linux")]
fn detect_running_processes(tools: &[(&str, &str)]) -> Vec<String> {
    let mut found = Vec::new();

    if let Ok(entries) = std::fs::read_dir("/proc") {
        for entry in entries.flatten() {
            let comm_path = entry.path().join("comm");
            if let Ok(comm) = std::fs::read_to_string(&comm_path) {
                let comm = comm.trim();
                for (name, label) in tools {
                    if comm == *name {
                        found.push((*label).to_string());
                    }
                }
            }
        }
    }

    found.sort();
    found.dedup();
    found
}

/// Scan for processes by name on macOS.
#[cfg(target_os = "macos")]
fn detect_running_processes(tools: &[(&str, &str)]) -> Vec<String> {
    let mut found = Vec::new();
    for (name, label) in tools {
        if let Ok(output) = std::process::Command::new("pgrep")
            .args(["-x", name])
            .output()
        {
            if output.status.success() {
                found.push((*label).to_string());
            }
        }
    }
    found
}

/// Scan for processes by name on Windows using tasklist.
#[cfg(target_os = "windows")]
fn detect_running_processes(tools: &[(&str, &str)]) -> Vec<String> {
    let mut found = Vec::new();
    for (name, label) in tools {
        let filter = format!("IMAGENAME eq {name}");
        if let Ok(output) = std::process::Command::new("tasklist")
            .args(["/FI", &filter, "/NH", "/FO", "CSV"])
            .output()
        {
            if output.status.success() {
                let stdout = String::from_utf8_lossy(&output.stdout);
                if stdout.trim().contains(name) {
                    found.push((*label).to_string());
                }
            }
        }
    }
    found
}

/// Generate a random challenge for GUI anti-automation.
///
/// Returns a `(challenge_text, expected_answer)` pair. The GUI displays the
/// challenge and requires the user to type the expected answer before
/// approving — preventing automated tools from clicking "Approve" without
/// understanding the challenge.
#[must_use]
pub fn generate_gui_challenge() -> (String, String) {
    // Audit L26: OsRng directly (not thread_rng) to avoid the
    // RUSTSEC-2026-0097 seed-pool init unsoundness.
    use rand::Rng;
    let mut rng = rand::rngs::OsRng;
    let code: u32 = rng.gen_range(100_000..1_000_000);
    let code_str = code.to_string();

    (format!("Type {code_str} to confirm"), code_str)
}

/// Verify a GUI challenge response.
#[must_use]
pub fn verify_gui_challenge(expected: &str, actual: &str) -> bool {
    if expected.len() != actual.len() {
        return false;
    }
    let mut diff = 0u8;
    for (a, b) in expected.bytes().zip(actual.bytes()) {
        diff |= a ^ b;
    }
    std::hint::black_box(diff) == 0
}

/// Determine the minimum delay (in seconds) before the approval button
/// becomes clickable, based on security tier.
#[must_use]
pub fn approval_delay_seconds(tier: &str) -> u32 {
    match tier {
        "standard" => 0,
        "hardened" => 2,
        "lockdown" => 5,
        _ => 1,
    }
}