safehell 0.7.0

Approval-gated SSH broker for AI coding agents
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
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use anyhow::{Context, Result};
use muda::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
use tokio::sync::{mpsc, watch};
use tray_icon::{Icon, TrayIcon, TrayIconBuilder, TrayIconEvent};
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId;

use crate::broker::ApprovalRequest;

const ID_TOGGLE: &str = "toggle_broker";
const ID_AUTOAPPROVE: &str = "toggle_autoapprove";
const ID_AUTOSTART: &str = "toggle_autostart";
const ID_APPROVE: &str = "action_approve";
const ID_DENY: &str = "action_deny";
const ID_UPDATE: &str = "action_update";
const ID_REFRESH_SERVERS: &str = "refresh_global_servers";
const ID_RESTART: &str = "action_restart";
const ID_QUIT: &str = "quit_app";

/// Calculate shortest distance from point `(px, py)` to line segment `(x1, y1) -> (x2, y2)`.
fn dist_to_segment(px: f32, py: f32, x1: f32, y1: f32, x2: f32, y2: f32) -> f32 {
    let dx = x2 - x1;
    let dy = y2 - y1;
    let len_sq = dx * dx + dy * dy;
    if len_sq == 0.0 {
        return ((px - x1) * (px - x1) + (py - y1) * (py - y1)).sqrt();
    }
    let t = (((px - x1) * dx + (py - y1) * dy) / len_sq).clamp(0.0, 1.0);
    let proj_x = x1 + t * dx;
    let proj_y = y1 + t * dy;
    ((px - proj_x) * (px - proj_x) + (py - proj_y) * (py - proj_y)).sqrt()
}

fn is_inside_mark(px: f32, py: f32) -> bool {
    // 1. Shackle (arch and legs)
    let d_arch = if py <= 11.4 && (11.0..=21.0).contains(&px) {
        let dx = px - 16.0;
        let dy = py - 11.4;
        ((dx * dx + dy * dy).sqrt() - 5.0).abs()
    } else {
        f32::MAX
    };
    let d_leg_l = dist_to_segment(px, py, 11.0, 11.4, 11.0, 14.5);
    let d_leg_r = dist_to_segment(px, py, 21.0, 11.4, 21.0, 14.5);
    let in_shackle = d_arch.min(d_leg_l).min(d_leg_r) <= 1.6;

    // 2. Lock Body (5.5 <= x <= 26.5, 14.0 <= y <= 27.0 with rounded corners rx=2.0)
    let in_body_box = (5.5..=26.5).contains(&px) && (14.0..=27.0).contains(&py);
    let in_body = if in_body_box {
        let cx = px.clamp(7.5, 24.5);
        let cy = py.clamp(16.0, 25.0);
        let d_corner = ((px - cx) * (px - cx) + (py - cy) * (py - cy)).sqrt();
        d_corner <= 2.0
    } else {
        false
    };

    // 3. Prompt cutout `>_`
    let d_p1 = dist_to_segment(px, py, 9.6, 17.6, 13.4, 20.5);
    let d_p2 = dist_to_segment(px, py, 13.4, 20.5, 9.6, 23.4);
    let d_p3 = dist_to_segment(px, py, 15.8, 23.6, 22.2, 23.6);
    let in_prompt = d_p1.min(d_p2).min(d_p3) <= 1.25;

    (in_shackle || in_body) && !in_prompt
}

const SUBPIXEL_OFFSETS: [(f32, f32); 4] = [(0.25, 0.25), (0.75, 0.25), (0.25, 0.75), (0.75, 0.75)];

fn pixel_coverage(x: usize, y: usize) -> f32 {
    let x_f = x as f32;
    let y_f = y as f32;
    let hits = SUBPIXEL_OFFSETS
        .iter()
        .filter(|&&(sx, sy)| is_inside_mark(x_f + sx, y_f + sy))
        .count();
    hits as f32 * 0.25
}

/// Create SafeHell brand padlock icon with terminal prompt `>_` cut into it.
pub fn create_brand_icon(r: u8, g: u8, b: u8) -> Icon {
    const SIZE: usize = 32;
    let mut rgba = Vec::with_capacity(SIZE * SIZE * 4);

    for index in 0..(SIZE * SIZE) {
        let x = index % SIZE;
        let y = index / SIZE;
        let coverage = pixel_coverage(x, y);
        let alpha = (coverage * 255.0).round().clamp(0.0, 255.0) as u8;
        rgba.extend_from_slice(&[r, g, b, alpha]);
    }

    Icon::from_rgba(rgba, SIZE as u32, SIZE as u32).expect("valid icon RGBA buffer")
}

fn get_auto_launcher() -> Option<auto_launch::AutoLaunch> {
    let app_name = "SafeHell";
    let exe = std::env::current_exe().ok()?;
    let exe_str = exe.to_string_lossy();
    auto_launch::AutoLaunchBuilder::new()
        .set_app_name(app_name)
        .set_app_path(&exe_str)
        .set_args(&["tray", "--foreground"])
        .build()
        .ok()
}

fn spawn_tray_process(auto_approve: bool) -> Result<std::process::Child> {
    let exe = std::env::current_exe().context("cannot locate safehell executable")?;
    let mut command = Command::new(exe);
    command
        .arg("tray")
        .arg("--foreground")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    if auto_approve {
        command.arg("--yes");
    }

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        command.process_group(0);
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
        const DETACHED_PROCESS: u32 = 0x0000_0008;
        command.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW | DETACHED_PROCESS);
    }

    command
        .spawn()
        .context("cannot start SafeHell tray in the background")
}

fn spawn_restarted_tray(auto_approve: bool) -> Result<()> {
    let _ = spawn_tray_process(auto_approve)?;
    Ok(())
}

struct TrayApp {
    auto_approve: Arc<AtomicBool>,
    running: bool,
    shutdown_tx: Option<watch::Sender<bool>>,
    approval_tx: mpsc::Sender<ApprovalRequest>,
    approval_rx: mpsc::Receiver<ApprovalRequest>,
    pending_approval: Option<ApprovalRequest>,

    icon_running: Icon,
    icon_stopped: Icon,
    icon_waiting: Icon,

    tray_icon: Option<TrayIcon>,
    menu_header: MenuItem,
    menu_toggle: MenuItem,
    menu_autoapprove: CheckMenuItem,
    menu_autostart: CheckMenuItem,
    menu_approval_title: MenuItem,
    menu_approve: MenuItem,
    menu_deny: MenuItem,
    global_servers: Submenu,
    menu_refresh_servers: MenuItem,

    tokio_handle: tokio::runtime::Handle,
}

impl TrayApp {
    fn new(initial_auto_approve: bool, tokio_handle: tokio::runtime::Handle) -> Self {
        let (approval_tx, approval_rx) = mpsc::channel(16);
        let auto_approve = Arc::new(AtomicBool::new(initial_auto_approve));
        let global_servers = Submenu::new("Global Servers", true);
        let menu_refresh_servers =
            MenuItem::with_id(ID_REFRESH_SERVERS, "↻ Refresh Global Servers", true, None);

        let autostart_enabled = get_auto_launcher()
            .and_then(|a| a.is_enabled().ok())
            .unwrap_or(false);

        let menu_header = MenuItem::new("🟢 SafeHell: Running", false, None);
        let menu_toggle = MenuItem::with_id(ID_TOGGLE, "⏹️  Stop Broker", true, None);
        let menu_autoapprove = CheckMenuItem::with_id(
            ID_AUTOAPPROVE,
            "⚡ Auto-Approve Allowed Rules",
            true,
            initial_auto_approve,
            None,
        );
        let menu_autostart = CheckMenuItem::with_id(
            ID_AUTOSTART,
            "🚀 Start at Login",
            true,
            autostart_enabled,
            None,
        );
        let menu_approval_title = MenuItem::new("⚠️ No pending approvals", false, None);
        let menu_approve = MenuItem::with_id(ID_APPROVE, "  ✅ Approve", false, None);
        let menu_deny = MenuItem::with_id(ID_DENY, "  ❌ Deny", false, None);
        let icon_running = create_brand_icon(74, 222, 128);
        let icon_stopped = create_brand_icon(239, 68, 68);
        let icon_waiting = create_brand_icon(245, 158, 11);

        Self {
            auto_approve,
            running: false,
            shutdown_tx: None,
            approval_tx,
            approval_rx,
            pending_approval: None,
            icon_running,
            icon_stopped,
            icon_waiting,
            tray_icon: None,
            menu_header,
            menu_toggle,
            menu_autoapprove,
            menu_autostart,
            menu_approval_title,
            menu_approve,
            menu_deny,
            global_servers,
            menu_refresh_servers,
            tokio_handle,
        }
    }

    fn start_broker(&mut self) {
        if self.running {
            return;
        }
        let (tx, rx) = watch::channel(false);
        self.shutdown_tx = Some(tx);
        self.running = true;

        let auto_approve = Arc::clone(&self.auto_approve);
        let approval_tx = Some(self.approval_tx.clone());

        self.tokio_handle.spawn(async move {
            if let Err(error) =
                crate::broker::serve_with_shutdown(auto_approve, rx, approval_tx).await
            {
                eprintln!("broker error: {error:#}");
            }
        });

        self.menu_header.set_text("🟢 SafeHell: Running");
        self.menu_toggle.set_text("⏹️  Stop Broker");
        self.update_tray_icon();
    }

    fn stop_broker(&mut self) {
        if !self.running {
            return;
        }
        if let Some(tx) = self.shutdown_tx.take() {
            let _ = tx.send(true);
        }
        self.running = false;
        self.clear_pending_approval();

        self.menu_header.set_text("🔴 SafeHell: Stopped");
        self.menu_toggle.set_text("▶️  Start Broker");
        self.update_tray_icon();
    }

    fn toggle_broker(&mut self) {
        if self.running {
            self.stop_broker();
        } else {
            self.start_broker();
        }
    }

    fn update_tray_icon(&self) {
        let Some(tray) = &self.tray_icon else {
            return;
        };
        if self.pending_approval.is_some() {
            let _ = tray.set_icon(Some(self.icon_waiting.clone()));
            let _ = tray.set_tooltip(Some("SafeHell: Approval Required"));
        } else if self.running {
            let _ = tray.set_icon(Some(self.icon_running.clone()));
            let _ = tray.set_tooltip(Some("SafeHell: Running"));
        } else {
            let _ = tray.set_icon(Some(self.icon_stopped.clone()));
            let _ = tray.set_tooltip(Some("SafeHell: Stopped"));
        }
    }

    fn handle_approval_request(&mut self, req: ApprovalRequest) {
        let cmd_preview = if req.command.len() > 28 {
            format!("{}...", &req.command[..25])
        } else {
            req.command.clone()
        };

        self.menu_approval_title
            .set_text(format!("⚠️ Approve {} ({cmd_preview})?", req.alias));
        self.menu_approve.set_enabled(true);
        self.menu_deny.set_enabled(true);

        // Send desktop notification
        let body = if let Some(reason) = &req.reason {
            format!(
                "Server: {}\nCommand: {}\nReason: {}\nExpires in {}s",
                req.alias, req.command, reason, req.timeout_seconds
            )
        } else {
            format!(
                "Server: {}\nCommand: {}\nExpires in {}s",
                req.alias, req.command, req.timeout_seconds
            )
        };

        let _ = notify_rust::Notification::new()
            .summary("SafeHell: Approval Requested")
            .body(&body)
            .show();

        self.pending_approval = Some(req);
        self.update_tray_icon();
    }

    fn resolve_approval(&mut self, approved: bool) {
        if let Some(req) = self.pending_approval.take() {
            let _ = req.responder.try_send(approved);
        }
        self.clear_pending_approval();
    }

    fn refresh_global_servers(&self) {
        while self.global_servers.remove_at(0).is_some() {}
        match crate::config::load_global() {
            Ok(global) if global.servers.is_empty() => {
                let item = MenuItem::new("No global servers configured", false, None);
                let _ = self.global_servers.append(&item);
            }
            Ok(global) => {
                for (alias, server) in global.servers {
                    let item = MenuItem::new(
                        format!(
                            "{alias}  {}@{}:{} ({})",
                            server.username,
                            server.host,
                            server.port,
                            server.auth.label()
                        ),
                        false,
                        None,
                    );
                    let _ = self.global_servers.append(&item);
                }
            }
            Err(error) => {
                let item = MenuItem::new(
                    format!("Unable to load global servers: {error:#}"),
                    false,
                    None,
                );
                let _ = self.global_servers.append(&item);
            }
        }
    }

    fn clear_pending_approval(&mut self) {
        self.pending_approval = None;
        self.menu_approval_title.set_text("⚠️ No pending approvals");
        self.menu_approve.set_enabled(false);
        self.menu_deny.set_enabled(false);
        self.update_tray_icon();
    }

    fn toggle_autoapprove(&mut self) {
        let current = self.auto_approve.load(Ordering::Relaxed);
        let next = !current;
        self.auto_approve.store(next, Ordering::Relaxed);
        self.menu_autoapprove.set_checked(next);

        let status = if next { "Enabled" } else { "Disabled" };
        let _ = notify_rust::Notification::new()
            .summary("SafeHell: Auto-Approve Mode")
            .body(&format!("Auto-approve allowed rules: {status}"))
            .show();
    }

    fn toggle_autostart(&mut self) {
        if let Some(launcher) = get_auto_launcher() {
            let is_enabled = launcher.is_enabled().unwrap_or(false);
            if is_enabled {
                let _ = launcher.disable();
                self.menu_autostart.set_checked(false);
            } else {
                let _ = launcher.enable();
                self.menu_autostart.set_checked(true);
            }
        }
    }

    fn check_update(&self) {
        let _ = notify_rust::Notification::new()
            .summary("SafeHell Update")
            .body("Checking for published updates...")
            .show();
        let auto_approve = self.auto_approve.load(Ordering::Relaxed);

        self.tokio_handle.spawn(async move {
            match crate::update::run(None) {
                Ok(()) => {
                    let _ = notify_rust::Notification::new()
                        .summary("SafeHell Update")
                        .body("SafeHell updated successfully. Restarting...")
                        .show();
                    if spawn_restarted_tray(auto_approve).is_ok() {
                        std::process::exit(0);
                    }
                }
                Err(error) => {
                    let _ = notify_rust::Notification::new()
                        .summary("SafeHell Update")
                        .body(&format!("Update check finished: {error:#}"))
                        .show();
                }
            }
        });
    }

    fn restart_app(&mut self, event_loop: &ActiveEventLoop) {
        self.stop_broker();
        if let Err(error) = spawn_restarted_tray(self.auto_approve.load(Ordering::Relaxed)) {
            let _ = notify_rust::Notification::new()
                .summary("SafeHell Restart Failed")
                .body(&format!("{error:#}"))
                .show();
            return;
        }
        event_loop.exit();
    }
}

impl ApplicationHandler for TrayApp {
    fn resumed(&mut self, _event_loop: &ActiveEventLoop) {
        if self.tray_icon.is_some() {
            return;
        }

        let menu = Menu::new();
        self.refresh_global_servers();
        let menu_update = MenuItem::with_id(ID_UPDATE, "🔄 Check & Apply Update", true, None);
        let menu_restart = MenuItem::with_id(ID_RESTART, "🔁 Restart SafeHell", true, None);
        let menu_quit = MenuItem::with_id(ID_QUIT, "❌ Quit", true, None);

        let _ = menu.append_items(&[
            &self.menu_header,
            &PredefinedMenuItem::separator(),
            &self.menu_approval_title,
            &self.menu_approve,
            &self.menu_deny,
            &PredefinedMenuItem::separator(),
            &self.global_servers,
            &self.menu_refresh_servers,
            &PredefinedMenuItem::separator(),
            &self.menu_toggle,
            &self.menu_autoapprove,
            &self.menu_autostart,
            &PredefinedMenuItem::separator(),
            &menu_update,
            &menu_restart,
            &PredefinedMenuItem::separator(),
            &menu_quit,
        ]);

        let tray = TrayIconBuilder::new()
            .with_menu(Box::new(menu))
            .with_tooltip("SafeHell: Running")
            .with_icon(self.icon_running.clone())
            .build()
            .expect("cannot create system tray icon");

        self.tray_icon = Some(tray);
        self.start_broker();
    }

    fn window_event(
        &mut self,
        _event_loop: &ActiveEventLoop,
        _window_id: WindowId,
        _event: WindowEvent,
    ) {
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        event_loop.set_control_flow(ControlFlow::WaitUntil(
            std::time::Instant::now() + std::time::Duration::from_millis(50),
        ));

        // Poll incoming approval requests from broker
        while let Ok(req) = self.approval_rx.try_recv() {
            self.handle_approval_request(req);
        }

        while let Ok(event) = MenuEvent::receiver().try_recv() {
            match event.id.0.as_str() {
                ID_TOGGLE => self.toggle_broker(),
                ID_AUTOAPPROVE => self.toggle_autoapprove(),
                ID_AUTOSTART => self.toggle_autostart(),
                ID_APPROVE => self.resolve_approval(true),
                ID_DENY => self.resolve_approval(false),
                ID_UPDATE => self.check_update(),
                ID_REFRESH_SERVERS => self.refresh_global_servers(),
                ID_RESTART => self.restart_app(event_loop),
                ID_QUIT => {
                    self.stop_broker();
                    event_loop.exit();
                }
                _ => {}
            }
        }

        while let Ok(_event) = TrayIconEvent::receiver().try_recv() {}
    }
}

pub fn run(auto_approve: bool, foreground: bool) -> Result<()> {
    if !foreground {
        let child = spawn_tray_process(auto_approve)?;
        println!(
            "SafeHell tray started in the background (pid {}).",
            child.id()
        );
        return Ok(());
    }

    let tokio_handle = tokio::runtime::Handle::current();
    let event_loop = EventLoop::new()?;
    let mut app = TrayApp::new(auto_approve, tokio_handle);
    event_loop.run_app(&mut app)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn creates_valid_brand_padlock_icons() {
        let _green = create_brand_icon(74, 222, 128);
        let _red = create_brand_icon(239, 68, 68);
        let _amber = create_brand_icon(245, 158, 11);
    }
}