envseal 0.3.13

Write-only secret vault with process-level access control — post-agent secret management
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
//! Cross-platform GUI dialog orchestration — the user-facing
//! security boundary.
//!
//! Five public entry points fan out to per-platform implementations:
//!
//! - `request_passphrase` — vault unlock / change.
//! - `request_secret_value` — capture a new secret value.
//! - `request_approval` — per-secret release authorization (this is
//!   where the [`crate::guard`] signal/policy taxonomy is consumed:
//!   every detector runs, the policy decides, the approval pipeline
//!   acts).
//! - `request_totp_code` — second-factor entry.
//! - `preexec_capture_prompt` — bash/zsh/fish hook key-migration
//!   confirmation.
//!
//! Every entry point is gated by `has_display`; headless
//! environments produce [`crate::error::Error::NoDisplay`] rather
//! than silently falling through to a non-interactive code path.

pub mod linux;
pub mod macos;
pub mod relay;
pub mod windows;

#[cfg(feature = "mock-gui")]
pub mod mock;

use crate::audit;
use crate::error::Error;
use crate::guard;
use crate::security_config::SecurityConfig;
use std::process::Command;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use zeroize::Zeroizing;

#[cfg(target_os = "linux")]
use linux::{
    linux_fido2_pin_entry, linux_passphrase, linux_popup, linux_preexec_prompt, linux_secret_value,
    linux_totp_entry, resolve_linux_dialog, DialogKind,
};
#[cfg(target_os = "macos")]
use macos::{
    macos_fido2_pin_entry, macos_passphrase, macos_popup, macos_preexec_prompt, macos_secret_value,
    macos_totp_entry,
};
#[cfg(target_os = "windows")]
use windows::{
    windows_fido2_pin_entry, windows_passphrase, windows_popup, windows_preexec_prompt,
    windows_secret_value, windows_totp_entry,
};

/// Runtime guard for the `mock-gui` feature (audit C4).
///
/// Aborts the process if mock-gui responses are requested outside a
/// recognized test / fuzz / bench harness. Cargo feature unification
/// means a transitive dependency could enable `mock-gui`; this guard
/// ensures the feature only takes effect when envseal is actually
/// running inside a Cargo harness.
#[cfg(feature = "mock-gui")]
fn assert_mock_gui_safe() {
    if cfg!(test) {
        return;
    }
    for marker in ["CARGO_TARGET_TMPDIR", "CARGO_MANIFEST_DIR"] {
        if std::env::var_os(marker).is_some() {
            return;
        }
    }
    eprintln!(
        "envseal: SECURITY ABORT — `mock-gui` feature reached from outside \
         a recognized Cargo test harness.\n\
         A downstream dependency may have enabled this feature, which \
         bypasses the human-in-the-loop approval boundary."
    );
    std::process::abort();
}

/// Type of approval granted by the user.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Approval {
    /// Allow this single secret release. The next release of the
    /// same secret will prompt again.
    AllowOnce,
    /// Allow this secret release and persist a policy rule so
    /// subsequent releases of the same `(binary, secret, argv)`
    /// triple proceed without a prompt.
    AllowAlways,
    /// Refuse this release. The caller surfaces `Error::UserDenied`.
    Deny,
}

/// User's response to the `__preexec` migration prompt.
///
/// Used by the bash/zsh/fish hook to react when an API key is
/// detected in a typed shell command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PreexecChoice {
    /// Store the value in the vault and emit a `.envseal` suggestion.
    Store,
    /// Skip this one occurrence; ask again next time.
    Skip,
    /// Record this (`env_var`, value) pair so we never re-prompt for it.
    DontAskAgain,
}

/// Pop a 3-button GUI dialog asking whether to migrate a freshly
/// detected API key into the vault. Returns [`PreexecChoice::Skip`]
/// on any platform/dialog failure rather than propagating an error
/// — the hook is best-effort and must never break the user's shell.
#[cfg_attr(feature = "mock-gui", allow(unreachable_code, unused_variables))]
pub fn preexec_capture_prompt(message: &str) -> Result<PreexecChoice, Error> {
    #[cfg(feature = "mock-gui")]
    {
        assert_mock_gui_safe();
        // Fail-closed: tests must set a mock; never fall through to GUI.
        return Ok(mock::get_mock_preexec().unwrap_or(PreexecChoice::Skip));
    }

    if !has_display() {
        return Ok(PreexecChoice::Skip);
    }
    #[cfg(target_os = "linux")]
    {
        linux_preexec_prompt(message)
    }
    #[cfg(target_os = "macos")]
    {
        macos_preexec_prompt(message)
    }
    #[cfg(target_os = "windows")]
    {
        windows_preexec_prompt(message)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        let _ = message;
        Ok(PreexecChoice::Skip)
    }
}

static RATE_LIMITER: Mutex<RateLimiterState> = Mutex::new(RateLimiterState {
    recent_requests: Vec::new(),
    last_request: None,
});

struct RateLimiterState {
    recent_requests: Vec<Instant>,
    last_request: Option<Instant>,
}

/// Request human approval to release a secret to a process.
///
/// This is the load-bearing security boundary. The flow is:
///
/// 1. Rate-limit gate (anti-fatigue / anti-spam).
/// 2. Relay path if `relay_required` — fail closed on relay error.
/// 3. Display gate — return `Error::NoDisplay` if headless.
/// 4. Run every detector via [`guard::assess_all_signals`], evaluate
///    against the default [`guard::Policy`] at the active tier, and
///    block / friction-gate / warn per the policy table. Every
///    signal is audit-logged.
/// 5. Optional challenge gate (config-requested or signal-demanded).
/// 6. Optional approval delay (anti-click-through).
/// 7. Render the platform popup with the accumulated warnings.
///
/// # Errors
/// `Error::UserDenied`, `Error::NoDisplay`,
/// `Error::EnvironmentCompromised` (signal blocked the operation),
/// `Error::RelayRequiredButUnavailable`, plus relay/audit IO errors.
#[cfg_attr(feature = "mock-gui", allow(unreachable_code, unused_variables))]
#[allow(clippy::too_many_lines)]
pub fn request_approval(
    binary_path: &str,
    command: &[String],
    secret_name: &str,
    env_var: &str,
    config: &SecurityConfig,
) -> Result<Approval, Error> {
    // Mock-gui short-circuit when a mock IS set. We do this BEFORE
    // the relay/rate-limit checks so tests can drive the approval
    // path without standing up a relay server. Tests that
    // specifically want the relay-required failure mode (e.g.
    // `relay_required_no_gui_fallback`) simply leave the mock
    // unset and fall through to the relay-gate below.
    #[cfg(feature = "mock-gui")]
    {
        assert_mock_gui_safe();
        if let Some(response) = mock::get_mock_approval() {
            return response;
        }
    }

    let cmd_str = command.join(" ");

    enforce_rate_limit(config)?;

    // If relay is configured as REQUIRED, the relay path must be tried
    // first and any error must be terminal — no fallback to local GUI.
    // The local-display check happens *after* this gate so that a
    // headless host with a paired phone can still authorize.
    if config.relay_required {
        match relay::request_relay_approval(config, binary_path, secret_name, env_var) {
            Ok(relay::RelayDecision::Allow) => return Ok(Approval::AllowOnce),
            Ok(relay::RelayDecision::Deny | relay::RelayDecision::Timeout) => {
                return Err(Error::UserDenied);
            }
            Err(e) => {
                return Err(Error::RelayRequiredButUnavailable(e.to_string()));
            }
        }
    }

    // Fail-closed under mock-gui: if we reach this point with the
    // feature on, no mock was set AND relay wasn't required.
    // Refuse loudly with NoDisplay rather than dropping to the
    // real platform GUI which would hang CI on an undismissable
    // dialog.
    #[cfg(feature = "mock-gui")]
    {
        return Err(Error::NoDisplay);
    }

    if !has_display() {
        return Err(Error::NoDisplay);
    }

    // Run every detector under the unified taxonomy and let the
    // policy decide. This is the single load-bearing consumer of
    // the signal model; doctor-rendering is a passive surface.
    //
    // The policy comes from `SecurityConfig::build_policy()` so
    // user-authored `signal_overrides` and `tier_overrides` from
    // `security.toml` are honored without any approval-pipeline
    // edits — exactly the "scales to 1000s of detectors without
    // touching this function" promise.
    // Build a per-operation context so detectors that care about the
    // target binary or stdin classification can fire. Ambient
    // detectors ignore the context fields they don't read.
    let ctx = guard::DetectorContext::builder()
        .binary_path(binary_path)
        .stdin_kind(guard::detect_stdin_kind())
        .build();
    let signals = guard::assess_all_signals(&ctx);
    let policy = config.build_policy();
    let decision = guard::evaluate(&signals, &policy, config.tier);

    // Audit-log every signal regardless of action — forensics need
    // the full picture, not just the blocking ones.
    for sig in &decision.log_entries {
        audit::log(&audit::AuditEvent::SignalRecorded {
            tier: format!("{:?}", config.tier),
            classification: format!("{} [{}] {}", sig.severity.as_str(), sig.id, sig.label),
        })
        .map_err(|e| Error::AuditLogFailed(e.to_string()))?;
    }

    if let Some(blocking) = decision.blocking_signal.as_ref() {
        return Err(Error::EnvironmentCompromised(format!(
            "{label} ({id}): {detail}{mitigation}",
            label = blocking.label,
            id = blocking.id,
            detail = blocking.detail,
            mitigation = blocking.mitigation,
        )));
    }

    // Challenge gate fires when EITHER the static config requests
    // it OR a signal demanded friction at this tier. Once cleared
    // within a process, we don't re-prompt — `envseal run` with
    // three unauthorized secrets shouldn't make the user solve the
    // numeric challenge three times for what is, from their
    // perspective, a single intent ("run this command with these
    // secrets"). The flag is process-scoped so a second `envseal`
    // invocation rightly re-prompts.
    if (config.challenge_required || decision.needs_friction)
        && !challenge_already_passed_in_process()
    {
        challenge_gate()?;
        mark_challenge_passed_in_process();
    }

    if config.approval_delay_secs > 0 {
        std::thread::sleep(Duration::from_secs(config.approval_delay_secs.into()));
    }

    // Single source of warnings: every detector that fired, rendered
    // through the unified `evaluate(...) -> Decision` pipeline. The
    // ad-hoc `shell_warning` / `check_untrusted_binary` strings that
    // used to be concatenated here are now signals emitted by
    // `guard::assess_target_binary_signals` and surface through the
    // same path as every other detector.
    let mut warnings = String::new();
    for warning in &decision.warnings {
        warnings.push_str(warning);
        warnings.push('\n');
    }

    // Homoglyph defense (audit M/L follow-up): sanitize every
    // user-visible field before it reaches the platform dialog.
    // An attacker who can plant a binary at e.g. `/tmp/wrаngler`
    // (Cyrillic 'а', U+0430) renders identically to `wrangler`
    // and would otherwise let the user approve what they think
    // is the trusted CLI. `sanitize_description` strips control
    // chars, bidi overrides, combining marks, and (when mixed
    // with ASCII Latin) Cyrillic / Greek / Armenian confusables.
    let safe_binary = sanitize_description(binary_path);
    let safe_cmd = sanitize_description(&cmd_str);
    let safe_secret = sanitize_description(secret_name);
    let safe_env = sanitize_description(env_var);
    let safe_warnings = sanitize_description(&warnings);

    #[cfg(target_os = "linux")]
    {
        linux_popup(
            &safe_binary,
            &safe_cmd,
            &safe_secret,
            &safe_env,
            &safe_warnings,
        )
    }
    #[cfg(target_os = "macos")]
    {
        macos_popup(
            &safe_binary,
            &safe_cmd,
            &safe_secret,
            &safe_env,
            &safe_warnings,
        )
    }
    #[cfg(target_os = "windows")]
    {
        windows_popup(
            &safe_binary,
            &safe_cmd,
            &safe_secret,
            &safe_env,
            &safe_warnings,
        )
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        Err(Error::NoDisplay)
    }
}

/// Prompt the user for the vault passphrase. `is_new = true` shows
/// the create-and-confirm flow; `is_new = false` is a single-field
/// unlock prompt. Returns `Error::NoDisplay` in headless sessions.
///
/// Equivalent to [`request_passphrase_with_hint`] with no previous
/// error — kept for SDK back-compat.
pub fn request_passphrase(
    is_new: bool,
    config: &SecurityConfig,
) -> Result<Zeroizing<String>, Error> {
    request_passphrase_with_hint(is_new, None, config)
}

/// Same as [`request_passphrase`] but renders `prev_error` at the top
/// of the dialog when present — used by the unlock-retry loop so the
/// operator sees "Incorrect passphrase, try again." in the SAME
/// dialog instead of having the CLI exit with a cryptic error after
/// a single typo.
#[cfg_attr(feature = "mock-gui", allow(unreachable_code, unused_variables))]
pub fn request_passphrase_with_hint(
    is_new: bool,
    prev_error: Option<&str>,
    _config: &SecurityConfig,
) -> Result<Zeroizing<String>, Error> {
    #[cfg(feature = "mock-gui")]
    {
        assert_mock_gui_safe();
        return mock::get_mock_passphrase().ok_or(Error::NoDisplay);
    }

    if !has_display() {
        return Err(Error::NoDisplay);
    }
    #[cfg(target_os = "linux")]
    {
        linux_passphrase(is_new, prev_error)
    }
    #[cfg(target_os = "macos")]
    {
        macos_passphrase(is_new, prev_error)
    }
    #[cfg(target_os = "windows")]
    {
        windows_passphrase(is_new, prev_error)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        let _ = prev_error;
        Err(Error::NoDisplay)
    }
}

/// Prompt the user to paste a new secret value (`store --gui` and
/// agent-initiated `request-key` flows). Returns `Error::NoDisplay`
/// in headless sessions.
#[cfg_attr(feature = "mock-gui", allow(unreachable_code, unused_variables))]
pub fn request_secret_value(
    key_name: &str,
    description: &str,
    _config: &SecurityConfig,
) -> Result<Zeroizing<String>, Error> {
    #[cfg(feature = "mock-gui")]
    {
        assert_mock_gui_safe();
        return mock::get_mock_secret_value().ok_or(Error::NoDisplay);
    }

    if !has_display() {
        return Err(Error::NoDisplay);
    }
    let safe_desc = sanitize_description(description);
    #[cfg(target_os = "linux")]
    {
        linux_secret_value(key_name, &safe_desc)
    }
    #[cfg(target_os = "macos")]
    {
        macos_secret_value(key_name, &safe_desc)
    }
    #[cfg(target_os = "windows")]
    {
        windows_secret_value(key_name, &safe_desc)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        Err(Error::NoDisplay)
    }
}

/// Prompt the user for the PIN of their FIDO2 authenticator.
///
/// `retries_left` is the device's remaining PIN-attempt counter (per
/// CTAP2 `clientPin/getRetries`), surfaced in the dialog so the user
/// can see how close they are to a permanent lockout before typing.
/// `attempt` is the per-session attempt counter (1-based) so a retry
/// after a wrong PIN is explicit in the dialog title.
///
/// The returned PIN is wrapped in [`Zeroizing`] so it is scrubbed on
/// drop; callers should pass it directly into `ctap-hid-fido2`'s
/// `pin(..)` builder method and never copy it into a non-zeroizing
/// container.
///
/// # Errors
/// - [`Error::NoDisplay`] when no GUI is reachable
/// - [`Error::UserDenied`] when the user dismisses the dialog
#[cfg_attr(feature = "mock-gui", allow(unreachable_code, unused_variables))]
pub fn request_fido2_pin(
    retries_left: u32,
    attempt: u32,
) -> Result<zeroize::Zeroizing<String>, Error> {
    #[cfg(feature = "mock-gui")]
    {
        assert_mock_gui_safe();
        return mock::get_mock_fido2_pin().ok_or(Error::NoDisplay);
    }

    if !has_display() {
        return Err(Error::NoDisplay);
    }
    #[cfg(target_os = "linux")]
    {
        linux_fido2_pin_entry(retries_left, attempt)
    }
    #[cfg(target_os = "macos")]
    {
        macos_fido2_pin_entry(retries_left, attempt)
    }
    #[cfg(target_os = "windows")]
    {
        windows_fido2_pin_entry(retries_left, attempt)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        let _ = (retries_left, attempt);
        Err(Error::NoDisplay)
    }
}

/// Prompt the user for a 6-digit TOTP code on tiers that require a
/// second factor. `attempt` is the 1-based attempt counter shown in
/// the prompt to make retries explicit.
#[cfg_attr(feature = "mock-gui", allow(unreachable_code, unused_variables))]
pub fn request_totp_code(attempt: u32) -> Result<String, Error> {
    #[cfg(feature = "mock-gui")]
    {
        assert_mock_gui_safe();
        return mock::get_mock_totp().ok_or(Error::NoDisplay);
    }

    if !has_display() {
        return Err(Error::NoDisplay);
    }
    #[cfg(target_os = "linux")]
    {
        linux_totp_entry(attempt)
    }
    #[cfg(target_os = "macos")]
    {
        macos_totp_entry(attempt)
    }
    #[cfg(target_os = "windows")]
    {
        windows_totp_entry(attempt)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        Err(Error::NoDisplay)
    }
}

/// Back-compat shim. The canonical home for interpreter / script-
/// runner detection is [`crate::guard::target_binary::is_interpreter`];
/// this re-export is kept so external callers that imported from
/// `crate::gui::is_interpreter` keep working.
#[must_use]
pub fn is_interpreter(binary_path: &str) -> bool {
    crate::guard::is_interpreter(binary_path)
}

/// Show an approval popup and return the user's decision.
///
/// The popup displays the binary path, secret name, and env var name,
/// with buttons for each approval tier.
///
/// Behavior is driven by the granular fields in `SecurityConfig`:
/// - `approval_delay_secs`: delay before popup appears (0 = immediate)
/// - `challenge_required`: if true, shows a 4-digit code gate first
/// - `signal_overrides` / `tier_overrides`: detection→policy overrides
///   (see [`crate::guard::signal`])
/// - `audit_logging`: whether to record events
///
/// For the average AI developer on Standard: popup appears instantly,
/// click Allow, done. Zero friction.
/// Sanitize an agent-provided description for GUI dialogs.
///
/// Strips control characters, bidi override characters, mixed-script
/// homoglyphs, and combining marks. Capped at 256 chars.
pub(crate) fn sanitize_description(description: &str) -> String {
    // Strip control characters and bidi overrides
    let filtered: String = description
        .chars()
        .filter(|c| {
            !c.is_control()
                && !matches!(
                    *c,
                    '\u{202A}'
                        ..='\u{202E}' // LRE, RLE, LRO, RLO, PDF
                        | '\u{200E}' | '\u{200F}' // LRM, RLM
                )
        })
        .collect();

    // Strip combining marks that could be used for visual spoofing.
    let stripped: String = filtered
        .chars()
        .filter(|c| !matches!(*c, '\u{0300}'..='\u{036F}'))
        .collect();

    // Detect mixed-script homoglyphs: if the string contains both
    // Latin-lookalike confusable scripts and basic Latin, strip the
    // confusable characters to prevent visual spoofing.
    let has_latin = stripped.chars().any(|c| c.is_ascii_alphabetic());
    let has_confusable = stripped.chars().any(|c| {
        matches!(
            c as u32,
            0x0400..=0x04FF   // Cyrillic
                | 0x0370..=0x03FF // Greek
                | 0x0530..=0x058F // Armenian
        )
    });
    let sanitized: String = if has_latin && has_confusable {
        stripped
            .chars()
            .filter(|c| {
                !matches!(
                    *c as u32,
                    0x0400..=0x04FF | 0x0370..=0x03FF | 0x0530..=0x058F
                )
            })
            .collect()
    } else {
        stripped
    };

    sanitized.chars().take(256).collect()
}

/// Process-scoped flag: has the challenge gate been cleared once in
/// this `envseal` invocation? Used to suppress re-prompting within a
/// single `inject` / `run` / `pipe` batch when multiple secrets each
/// trigger `request_approval`. Each new process starts at `false`.
static CHALLENGE_PASSED_THIS_PROCESS: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

fn challenge_already_passed_in_process() -> bool {
    CHALLENGE_PASSED_THIS_PROCESS.load(std::sync::atomic::Ordering::Acquire)
}

fn mark_challenge_passed_in_process() {
    CHALLENGE_PASSED_THIS_PROCESS.store(true, std::sync::atomic::Ordering::Release);
}

fn challenge_gate() -> Result<(), Error> {
    let (challenge_text, expected) = guard::generate_gui_challenge();

    #[cfg(target_os = "linux")]
    {
        let (dialog_path, kind) = resolve_linux_dialog()?;

        let result = match kind {
            DialogKind::Zenity => Command::new(&dialog_path)
                .args([
                    "--entry",
                    "--title=envseal — Security Challenge",
                    &format!("--text=LOCKDOWN MODE\n\n{challenge_text}\n\nThis code confirms you are physically present."),
                    "--width=400",
                ])
                .output(),
            DialogKind::Kdialog => Command::new(&dialog_path)
                .args([
                    "--inputbox",
                    &format!("LOCKDOWN: {challenge_text}"),
                    "--title",
                    "envseal — Security Challenge",
                ])
                .output(),
        };

        match result {
            Ok(output) if output.status.success() => {
                let answer = String::from_utf8_lossy(&output.stdout).trim().to_string();
                if guard::verify_gui_challenge(&expected, &answer) {
                    Ok(())
                } else {
                    Err(Error::UserDenied)
                }
            }
            _ => Err(Error::UserDenied),
        }
    }

    #[cfg(target_os = "macos")]
    {
        let script = format!(
            r#"display dialog "LOCKDOWN: {challenge_text}" with title "envseal — Security Challenge" default answer "" buttons {{"Cancel", "OK"}} default button "OK""#
        );
        let binary = guard::verify_gui_binary("osascript")
            .unwrap_or_else(|_| std::path::PathBuf::from("/usr/bin/osascript"));
        let result = Command::new(&binary).args(["-e", &script]).output();
        match result {
            Ok(output) if output.status.success() => {
                let out = String::from_utf8_lossy(&output.stdout);
                if let Some(answer) = out.strip_prefix("text returned:") {
                    if guard::verify_gui_challenge(&expected, answer.trim()) {
                        return Ok(());
                    }
                }
                Err(Error::UserDenied)
            }
            _ => Err(Error::UserDenied),
        }
    }

    #[cfg(target_os = "windows")]
    {
        let script = format!(
            r#"$input = [Microsoft.VisualBasic.Interaction]::InputBox("LOCKDOWN: {challenge_text}", "envseal — Security Challenge"); Write-Output $input"#
        );
        let result = Command::new("powershell")
            .args([
                "-NoProfile",
                "-Command",
                &format!("Add-Type -AssemblyName Microsoft.VisualBasic; {script}"),
            ])
            .output();
        match result {
            Ok(output) if output.status.success() => {
                let answer = String::from_utf8_lossy(&output.stdout).trim().to_string();
                if guard::verify_gui_challenge(&expected, &answer) {
                    Ok(())
                } else {
                    Err(Error::UserDenied)
                }
            }
            _ => Err(Error::UserDenied),
        }
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        Err(Error::NoDisplay)
    }
}

/// Whether a graphical session capable of running the approval dialog
/// is available.
///
/// Returns `false` when:
/// - `ENVSEAL_DISABLE` or `ENVSEAL_NO_GUI` is set (any non-empty value),
/// - on Linux: neither `DISPLAY` nor `WAYLAND_DISPLAY` is exported,
/// - on Windows: the process has no interactive `SESSIONNAME` (Windows
///   service, ssh-without-rdp, scheduled task running as system),
///
/// Without the Windows session check, an SSH'd-in user on Windows
/// hangs forever trying to spawn a `PowerShell.Forms` dialog that has
/// no desktop to render onto. The user reported this exact symptom in
/// 0.3.9 — `envseal store` / `peek` over SSH on Windows blocked
/// indefinitely.
fn has_display() -> bool {
    if std::env::var("ENVSEAL_DISABLE").is_ok_and(|v| !v.is_empty())
        || std::env::var("ENVSEAL_NO_GUI").is_ok_and(|v| !v.is_empty())
    {
        return false;
    }

    #[cfg(target_os = "linux")]
    {
        // H batch 3 (audit, May 2026): the prior implementation
        // returned true on the trivial existence of $DISPLAY or
        // $WAYLAND_DISPLAY. An attacker who controls those env
        // vars (e.g. systemd unit running as the user with
        // `Environment=DISPLAY=:99`) bypassed the headless check
        // even with no X server / Wayland compositor reachable.
        // Now we additionally probe for the Unix-domain socket the
        // server listens on. The socket presence is observable to
        // any process the server would accept connections from;
        // the env-var spoof produces a $DISPLAY whose backing
        // socket doesn't exist.
        let display_ok = std::env::var("DISPLAY")
            .ok()
            .filter(|s| !s.trim().is_empty())
            .map(|d| {
                // DISPLAY is `[host]:N[.S]`; strip everything before
                // the colon and after a trailing dot to get N.
                let after_colon = d.split_once(':').map_or("", |(_, after)| after);
                let n_str = after_colon.split('.').next().unwrap_or(after_colon);
                if n_str.is_empty() {
                    return false;
                }
                std::path::Path::new(&format!("/tmp/.X11-unix/X{n_str}")).exists()
            })
            .unwrap_or(false);
        let wayland_ok = std::env::var("WAYLAND_DISPLAY")
            .ok()
            .filter(|s| !s.trim().is_empty())
            .map(|wd| {
                // WAYLAND_DISPLAY may be relative (just "wayland-0")
                // or absolute. Resolve via XDG_RUNTIME_DIR for the
                // relative form.
                let p = std::path::PathBuf::from(&wd);
                if p.is_absolute() {
                    p.exists()
                } else if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR") {
                    std::path::Path::new(&xdg).join(&wd).exists()
                } else {
                    false
                }
            })
            .unwrap_or(false);
        display_ok || wayland_ok
    }

    #[cfg(target_os = "macos")]
    {
        // H batch 3: the prior implementation returned true
        // unconditionally on macOS, which meant every headless
        // SSH session into a Mac thought it had a display. The
        // robust probe is `CGSessionCopyCurrentDictionary` which
        // requires linking CoreGraphics; until that lands, fall
        // back to checking for a logged-in graphical session via
        // the presence of the WindowServer socket. SECURITYSESSIONID
        // / Aqua launchctl bootstrap are the user-session markers
        // we can read without dynamic loading.
        std::env::var("__CFBundleIdentifier").is_ok()
            || std::env::var("XPC_FLAGS").is_ok_and(|v| !v.is_empty())
            || std::env::var("Apple_PubSub_Socket_Render").is_ok()
    }

    #[cfg(target_os = "windows")]
    {
        // H batch 3: SESSIONNAME alone is spoofable by any
        // process that owns the env (a service that sets
        // SESSIONNAME=Console before launching the binary). The
        // robust probe is `GetProcessWindowStation()` returning
        // non-null AND the station having USER_INTERACTIVE rights.
        // Below we keep the env-var sanity check AND additionally
        // probe via `GetProcessWindowStation`; either failure
        // falls through to NoDisplay.
        if std::env::var("SESSIONNAME")
            .map(|s| s.trim().is_empty())
            .unwrap_or(true)
        {
            return false;
        }
        unsafe {
            use windows_sys::Win32::System::StationsAndDesktops::GetProcessWindowStation;
            !GetProcessWindowStation().is_null()
        }
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        false
    }
}

/// Enforce configurable rate limits on approval popups.
///
/// Two independent limits:
/// - `approval_cooldown_secs`: minimum time between popups
/// - `max_approvals_per_minute`: cap on popup frequency
///
/// When exceeded, requests are auto-denied and logged. This prevents
/// agents from spamming the user with 100 popups hoping they click
/// "Allow" reflexively (approval fatigue attack).
fn enforce_rate_limit(config: &crate::security_config::SecurityConfig) -> Result<(), Error> {
    let mut guard = RATE_LIMITER.lock().map_err(|_| {
        Error::CryptoFailure("rate limiter state corrupted — retry after cooldown".to_string())
    })?;
    let state = &mut *guard;

    let now = Instant::now();

    // Cooldown check
    if config.approval_cooldown_secs > 0 {
        if let Some(last) = state.last_request {
            let elapsed = now.duration_since(last);
            if elapsed.as_secs() < u64::from(config.approval_cooldown_secs) {
                let remaining = u64::from(config.approval_cooldown_secs) - elapsed.as_secs();
                crate::audit::log_required(&crate::audit::AuditEvent::RateLimited {
                    reason: format!("cooldown: {remaining}s remaining"),
                })?;
                return Err(Error::CryptoFailure(format!(
                    "rate limited: approval cooldown ({remaining}s remaining). \
                     this prevents approval fatigue attacks."
                )));
            }
        }
    }

    // Per-minute cap
    if config.max_approvals_per_minute > 0 {
        // Prune requests older than 60 seconds
        let one_minute_ago = now
            .checked_sub(std::time::Duration::from_secs(60))
            .unwrap_or(now);
        state.recent_requests.retain(|&t| t > one_minute_ago);

        if state.recent_requests.len() >= config.max_approvals_per_minute as usize {
            crate::audit::log_required(&crate::audit::AuditEvent::RateLimited {
                reason: format!(
                    "per-minute cap: {} requests in last 60s (max={})",
                    state.recent_requests.len(),
                    config.max_approvals_per_minute
                ),
            })?;
            return Err(Error::CryptoFailure(format!(
                "rate limited: {} approval requests in the last minute (max={}). \
                 this prevents approval fatigue attacks.",
                state.recent_requests.len(),
                config.max_approvals_per_minute
            )));
        }
    }

    // Record this request
    state.last_request = Some(now);
    state.recent_requests.push(now);

    Ok(())
}

// `check_untrusted_binary` and `shell_warning` previously emitted ad-hoc
// warning strings concatenated onto the approval popup body. Both are
// now Signals emitted by `crate::guard::target_binary` (interpreter +
// untrusted-path) and `crate::guard::context::assess_io_context_signals`
// (real-pipe stdin), flowing through the unified
// `evaluate(...) -> Decision` pipeline like every other detector.

#[cfg(test)]
mod sanitize_description_tests {
    use super::sanitize_description;

    #[test]
    fn strips_control_chars() {
        let raw = "hello\x07\x08world";
        let sanitized = sanitize_description(raw);
        assert!(!sanitized.contains('\x07'));
        assert!(!sanitized.contains('\x08'));
        assert!(sanitized.contains("helloworld"));
    }

    #[test]
    fn strips_bidi_overrides() {
        let raw = "\u{202A}spoofed\u{202C}";
        let sanitized = sanitize_description(raw);
        assert!(!sanitized.contains('\u{202A}'));
        assert!(!sanitized.contains('\u{202C}'));
        assert!(sanitized.contains("spoofed"));
    }

    #[test]
    fn strips_combining_marks() {
        let raw = "a\u{0300}b\u{036F}c";
        let sanitized = sanitize_description(raw);
        assert!(!sanitized.contains('\u{0300}'));
        assert!(!sanitized.contains('\u{036F}'));
        assert_eq!(sanitized, "abc");
    }

    #[test]
    fn caps_at_256_chars() {
        let raw: String = (0..500).map(|_| 'x').collect();
        let sanitized = sanitize_description(&raw);
        assert_eq!(sanitized.len(), 256);
    }

    #[test]
    fn preserves_safe_text() {
        let raw = "Normal description: deploy to production";
        let sanitized = sanitize_description(raw);
        assert_eq!(sanitized, raw);
    }
}