1use std::collections::HashSet;
27use std::sync::Mutex;
28use std::time::Duration;
29
30use serde::{Deserialize, Serialize};
31use tokio::sync::oneshot;
32
33pub const SETTING_ENABLED: &str = "desktop:enabled";
35pub const SETTING_BLOCKLIST: &str = "desktop:blocklist";
37pub const SETTING_ALLOWLIST: &str = "desktop:allowlist";
39pub const SETTING_GRANT_MINUTES: &str = "desktop:grantminutes";
41pub const DEFAULT_GRANT_MINUTES: u64 = 30;
42
43pub const MAX_ACTIONS_PER_GRANT: u32 = 200;
45pub const MIN_ACTION_GAP_MS: u64 = 500;
47pub const ANSWER_WAIT: Duration = Duration::from_secs(10 * 60);
49pub const DRIVING_SHOWN_MS: u64 = 10_000;
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
54#[ts(export, export_to = "../../../frontend/types/rpc/")]
55pub struct DesktopRequest {
56 pub id: String,
57 pub agent: String,
59 pub app: String,
61 pub title: String,
63 #[ts(type = "number")]
64 pub asked_ms: u64,
65 pub block_id: String,
67 #[ts(type = "number")]
69 pub grant_minutes: u64,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
74#[ts(export, export_to = "../../../frontend/types/rpc/")]
75pub struct DesktopGrantView {
76 pub agent: String,
77 pub app: String,
78 pub block_id: String,
79 #[ts(type = "number | null")]
81 pub until_ms: Option<u64>,
82 pub active: bool,
84}
85
86#[derive(Debug, Clone, Default, Serialize, ts_rs::TS)]
88#[ts(export, export_to = "../../../frontend/types/rpc/")]
89pub struct DesktopEvent {
90 pub requests: Vec<DesktopRequest>,
91 pub grants: Vec<DesktopGrantView>,
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(rename_all = "snake_case")]
97pub enum Choice {
98 Timed,
100 Session,
102 Deny,
103}
104
105#[derive(Debug, Clone, Deserialize)]
107pub struct DesktopAnswer {
108 pub id: String,
109 pub choice: Choice,
110}
111
112#[derive(Debug)]
113struct Grant {
114 id: String,
115 agent: String,
116 app: String,
117 block_id: String,
118 until_ms: Option<u64>,
119 actions: u32,
120 last_action_ms: u64,
121}
122
123struct Pending {
124 request: DesktopRequest,
125 waiters: Vec<oneshot::Sender<Choice>>,
126}
127
128#[derive(Debug, PartialEq, Eq)]
130pub enum Check {
131 Allow { grant_id: String },
132 Stopped,
134 Denied,
136 TooFast { wait_ms: u64 },
138 Ask,
140}
141
142#[derive(Default)]
143pub struct Gate {
144 pending: Vec<Pending>,
145 grants: Vec<Grant>,
146 denied: HashSet<(String, String)>,
147 stopped: HashSet<String>,
148}
149
150impl Gate {
151 fn purge(&mut self, now: u64) {
152 self.grants.retain(|g| g.until_ms.map_or(true, |u| u > now));
153 }
154
155 pub fn check(&mut self, agent: &str, block_id: &str, app: &str, now: u64) -> Check {
158 self.purge(now);
159 if self.stopped.remove(agent) {
160 return Check::Stopped;
161 }
162 if self.denied.contains(&(agent.to_string(), app.to_string())) {
163 return Check::Denied;
164 }
165 let Some(pos) = self
166 .grants
167 .iter()
168 .position(|g| g.agent == agent && g.app == app && g.block_id == block_id)
169 else {
170 return Check::Ask;
171 };
172 let g = &mut self.grants[pos];
173 if g.actions >= MAX_ACTIONS_PER_GRANT {
174 self.grants.remove(pos);
175 return Check::Ask;
176 }
177 let since = now.saturating_sub(g.last_action_ms);
178 if g.actions > 0 && since < MIN_ACTION_GAP_MS {
179 return Check::TooFast { wait_ms: MIN_ACTION_GAP_MS - since };
180 }
181 g.actions += 1;
182 g.last_action_ms = now;
183 Check::Allow { grant_id: g.id.clone() }
184 }
185
186 pub fn asking(&self, agent: &str, block_id: &str, app: &str) -> bool {
189 self.pending
190 .iter()
191 .any(|p| p.request.agent == agent && p.request.app == app && p.request.block_id == block_id)
192 }
193
194 pub fn ask(&mut self, request: DesktopRequest) -> oneshot::Receiver<Choice> {
197 let (tx, rx) = oneshot::channel();
198 if let Some(p) = self
199 .pending
200 .iter_mut()
201 .find(|p| p.request.agent == request.agent && p.request.app == request.app && p.request.block_id == request.block_id)
202 {
203 p.waiters.push(tx);
204 } else {
205 self.pending.push(Pending { request, waiters: vec![tx] });
206 }
207 rx
208 }
209
210 pub fn grant(&mut self, agent: &str, block_id: &str, app: &str, minutes: Option<u64>, now: u64) {
213 self.grants.retain(|g| !(g.agent == agent && g.app == app && g.block_id == block_id));
214 self.grants.push(Grant {
215 id: uuid::Uuid::new_v4().to_string(),
216 agent: agent.to_string(),
217 app: app.to_string(),
218 block_id: block_id.to_string(),
219 until_ms: minutes.map(|m| now + m.max(1) * 60_000),
220 actions: 0,
221 last_action_ms: 0,
222 });
223 }
224
225 pub fn answer(&mut self, id: &str, choice: Choice, now: u64, grant_minutes: u64) -> Result<(), String> {
227 let Some(pos) = self.pending.iter().position(|p| p.request.id == id) else {
228 return Err("that request was already answered".into());
229 };
230 let p = self.pending.remove(pos);
231 let r = &p.request;
232 match choice {
233 Choice::Deny => {
234 self.denied.insert((r.agent.clone(), r.app.clone()));
235 }
236 Choice::Timed | Choice::Session => {
237 self.grant(&r.agent, &r.block_id, &r.app, (choice == Choice::Timed).then_some(grant_minutes), now);
238 }
239 }
240 for tx in p.waiters {
241 let _ = tx.send(choice);
242 }
243 Ok(())
244 }
245
246 pub fn abandon(&mut self, id: &str) {
248 self.pending.retain(|p| p.request.id != id);
249 }
250
251 pub fn stop(&mut self, block_id: &str) -> usize {
254 let agents: HashSet<String> = self
255 .grants
256 .iter()
257 .filter(|g| g.block_id == block_id)
258 .map(|g| g.agent.clone())
259 .chain(self.pending.iter().filter(|p| p.request.block_id == block_id).map(|p| p.request.agent.clone()))
260 .collect();
261 let before = self.grants.len();
262 self.grants.retain(|g| g.block_id != block_id);
263 self.pending.retain(|p| p.request.block_id != block_id);
264 let revoked = before - self.grants.len();
265 self.stopped.extend(agents);
266 revoked
267 }
268
269 pub fn has_grant(&mut self, agent: &str, block_id: &str, app: &str, now: u64) -> bool {
271 self.purge(now);
272 self.grants.iter().any(|g| g.agent == agent && g.app == app && g.block_id == block_id)
273 }
274
275 pub fn release(&mut self, agent: &str, block_id: &str, app: &str) -> bool {
277 let before = self.grants.len();
278 self.grants.retain(|g| !(g.agent == agent && g.block_id == block_id && g.app == app));
279 before != self.grants.len()
280 }
281
282 pub fn event(&mut self, now: u64) -> DesktopEvent {
283 self.purge(now);
284 DesktopEvent {
285 requests: self.pending.iter().map(|p| p.request.clone()).collect(),
286 grants: self
287 .grants
288 .iter()
289 .map(|g| DesktopGrantView {
290 agent: g.agent.clone(),
291 app: g.app.clone(),
292 block_id: g.block_id.clone(),
293 until_ms: g.until_ms,
294 active: g.actions > 0 && now.saturating_sub(g.last_action_ms) < DRIVING_SHOWN_MS,
295 })
296 .collect(),
297 }
298 }
299}
300
301static GATE: Mutex<Option<Gate>> = Mutex::new(None);
302
303pub fn with_gate<T>(f: impl FnOnce(&mut Gate) -> T) -> T {
305 let mut guard = GATE.lock().unwrap_or_else(|e| e.into_inner());
306 f(guard.get_or_insert_with(Gate::default))
307}
308
309const DEFAULT_BLOCKED: &[(&str, &str)] = &[
316 ("keepass", "a password manager"),
318 ("keepassxc", "a password manager"),
319 ("1password", "a password manager"),
320 ("bitwarden", "a password manager"),
321 ("lastpass", "a password manager"),
322 ("dashlane", "a password manager"),
323 ("enpass", "a password manager"),
324 ("nordpass", "a password manager"),
325 ("roboform", "a password manager"),
326 ("chrome", "a web browser; use the Browser tool"),
328 ("msedge", "a web browser; use the Browser tool"),
329 ("firefox", "a web browser; use the Browser tool"),
330 ("brave", "a web browser; use the Browser tool"),
331 ("opera", "a web browser; use the Browser tool"),
332 ("vivaldi", "a web browser; use the Browser tool"),
333 ("chromium", "a web browser; use the Browser tool"),
334 ("iexplore", "a web browser; use the Browser tool"),
335 ("safari", "a web browser; use the Browser tool"),
336 ("arc", "a web browser; use the Browser tool"),
337 ("librewolf", "a web browser; use the Browser tool"),
338 ("waterfox", "a web browser; use the Browser tool"),
339 ("consent", "an operating system prompt"),
341 ("credentialuibroker", "an operating system prompt"),
342 ("logonui", "an operating system prompt"),
343 ("sechealthui", "Windows Security"),
344 ("metatrader", "a trading app"),
346 ("terminal64", "a trading app"),
347 ("tradingview", "a trading app"),
348 ("thinkorswim", "a trading app"),
349 ("tws", "a trading app"),
350 ("ledger live", "a crypto wallet"),
351 ("ledgerlive", "a crypto wallet"),
352 ("exodus", "a crypto wallet"),
353 ("electrum", "a crypto wallet"),
354 ("coinbase", "a crypto app"),
355 ("binance", "a crypto app"),
356];
357
358pub fn app_key(exe: &str) -> String {
361 let name = exe.rsplit(['\\', '/']).next().unwrap_or(exe);
362 let name = name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name);
363 name.trim().to_lowercase()
364}
365
366pub fn blocked_reason(app: &str, title: &str, added: &[String], allowed: &[String]) -> Option<String> {
370 let app = app_key(app);
371 let title = title.to_lowercase();
372 let norm = |s: &String| app_key(s);
373 let allowed: HashSet<String> = allowed.iter().map(norm).collect();
374 if app.starts_with("agentmux") {
375 return Some("AgentMux itself; use the UI tool".into());
376 }
377 if let Some((_, why)) = DEFAULT_BLOCKED.iter().find(|(name, _)| *name == app && !allowed.contains(*name)) {
378 return Some((*why).to_string());
379 }
380 if (title.contains("windows security") || title.contains("user account control")) && !allowed.contains("windowssecurity") {
381 return Some("an operating system prompt".into());
382 }
383 for entry in added {
384 let e = norm(entry);
385 if e.is_empty() {
386 continue;
387 }
388 if e == app || title.contains(&e) {
389 return Some(format!("on your blocklist ({entry})"));
390 }
391 }
392 None
393}
394
395pub fn audit(entry: &serde_json::Value) {
402 let Ok(root) = agentmux_common::data_paths::agentmux_root() else {
403 return;
404 };
405 let dir = root.join("tmp/capture-window");
406 if std::fs::create_dir_all(&dir).is_err() {
407 return;
408 }
409 if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("desktop-audit.log")) {
410 use std::io::Write;
411 let _ = f.write_all(format!("{entry}\n").as_bytes());
412 }
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418
419 fn req(id: &str, agent: &str, app: &str, block: &str) -> DesktopRequest {
420 DesktopRequest {
421 id: id.into(),
422 agent: agent.into(),
423 app: app.into(),
424 title: "t".into(),
425 asked_ms: 0,
426 block_id: block.into(),
427 grant_minutes: 30,
428 }
429 }
430
431 fn grant(g: &mut Gate, choice: Choice, now: u64) {
433 let _rx = g.ask(req("r1", "naki", "notepad", "b1"));
434 g.answer("r1", choice, now, 30).unwrap();
435 }
436
437 #[test]
438 fn with_no_grant_the_user_is_asked() {
439 let mut g = Gate::default();
440 assert_eq!(g.check("naki", "b1", "notepad", 1_000), Check::Ask);
441 }
442
443 #[test]
446 fn asking_lasts_until_the_user_answers() {
447 let mut g = Gate::default();
448 assert!(!g.asking("naki", "b1", "notepad"));
449 let _rx = g.ask(req("r1", "naki", "notepad", "b1"));
450 assert!(g.asking("naki", "b1", "notepad"));
451 assert!(!g.asking("naki", "b1", "calc"), "another app is its own prompt");
452 assert!(!g.asking("naki", "b2", "notepad"), "another pane is its own prompt");
453 g.answer("r1", Choice::Deny, 1_000, 30).unwrap();
454 assert!(!g.asking("naki", "b1", "notepad"));
455 }
456
457 #[test]
458 fn a_direct_grant_allows_for_its_minutes_and_replaces_the_one_before() {
459 let mut g = Gate::default();
460 g.grant("naki", "b1", "notepad", Some(5), 0);
461 assert!(matches!(g.check("naki", "b1", "notepad", 1_000), Check::Allow { .. }));
462 g.grant("naki", "b1", "notepad", Some(1), 0);
463 assert_eq!(g.check("naki", "b1", "notepad", 61_000), Check::Ask, "the later grant replaced the longer one");
464 g.grant("naki", "b1", "notepad", None, 0);
465 assert!(matches!(g.check("naki", "b1", "notepad", 999_999_999), Check::Allow { .. }), "no minutes: until the session ends");
466 }
467
468 #[test]
469 fn a_timed_grant_allows_then_expires() {
470 let mut g = Gate::default();
471 grant(&mut g, Choice::Timed, 0);
472 assert!(matches!(g.check("naki", "b1", "notepad", 1_000), Check::Allow { .. }));
473 assert_eq!(g.check("naki", "b1", "notepad", 30 * 60_000 + 1), Check::Ask);
475 }
476
477 #[test]
478 fn a_session_grant_does_not_expire_but_is_tied_to_its_pane() {
479 let mut g = Gate::default();
480 grant(&mut g, Choice::Session, 0);
481 assert!(matches!(g.check("naki", "b1", "notepad", 999_999_999), Check::Allow { .. }));
482 assert_eq!(g.check("naki", "b2", "notepad", 999_999_999 + 1000), Check::Ask);
484 }
485
486 #[test]
487 fn a_grant_is_for_one_agent_and_one_app() {
488 let mut g = Gate::default();
489 grant(&mut g, Choice::Timed, 0);
490 assert_eq!(g.check("other", "b1", "notepad", 1_000), Check::Ask);
491 assert_eq!(g.check("naki", "b1", "calc", 1_000), Check::Ask);
492 }
493
494 #[test]
495 fn a_denial_is_remembered_so_the_agent_cannot_nag() {
496 let mut g = Gate::default();
497 grant(&mut g, Choice::Deny, 0);
498 assert_eq!(g.check("naki", "b1", "notepad", 1_000), Check::Denied);
499 assert_eq!(g.check("naki", "b1", "notepad", 2_000), Check::Denied);
500 }
501
502 #[test]
503 fn actions_are_at_most_two_a_second() {
504 let mut g = Gate::default();
505 grant(&mut g, Choice::Timed, 0);
506 assert!(matches!(g.check("naki", "b1", "notepad", 10_000), Check::Allow { .. }));
507 assert_eq!(g.check("naki", "b1", "notepad", 10_100), Check::TooFast { wait_ms: 400 });
508 assert!(matches!(g.check("naki", "b1", "notepad", 10_500), Check::Allow { .. }));
509 }
510
511 #[test]
512 fn a_grant_ends_after_its_action_limit() {
513 let mut g = Gate::default();
514 grant(&mut g, Choice::Session, 0);
515 let mut t = 10_000;
516 for _ in 0..MAX_ACTIONS_PER_GRANT {
517 assert!(matches!(g.check("naki", "b1", "notepad", t), Check::Allow { .. }));
518 t += MIN_ACTION_GAP_MS;
519 }
520 assert_eq!(g.check("naki", "b1", "notepad", t), Check::Ask);
521 }
522
523 #[test]
524 fn stop_revokes_and_the_next_action_hears_it_once() {
525 let mut g = Gate::default();
526 grant(&mut g, Choice::Session, 0);
527 assert_eq!(g.stop("b1"), 1);
528 assert_eq!(g.check("naki", "b1", "notepad", 1_000), Check::Stopped);
529 assert_eq!(g.check("naki", "b1", "notepad", 2_000), Check::Ask);
531 }
532
533 #[test]
534 fn stop_also_drops_a_prompt_the_agent_was_waiting_on() {
535 let mut g = Gate::default();
536 let _rx = g.ask(req("r1", "naki", "notepad", "b1"));
537 g.stop("b1");
538 assert!(g.event(0).requests.is_empty());
539 assert!(g.answer("r1", Choice::Timed, 0, 30).is_err());
540 }
541
542 #[test]
543 fn has_grant_says_whether_the_agent_may_drive_the_app() {
544 let mut g = Gate::default();
545 assert!(!g.has_grant("naki", "b1", "notepad", 0));
546 grant(&mut g, Choice::Timed, 0);
547 assert!(g.has_grant("naki", "b1", "notepad", 1_000));
548 assert!(!g.has_grant("naki", "b2", "notepad", 1_000));
549 assert!(!g.has_grant("naki", "b1", "notepad", 30 * 60_000 + 1));
550 }
551
552 #[test]
553 fn release_gives_a_grant_back() {
554 let mut g = Gate::default();
555 grant(&mut g, Choice::Session, 0);
556 assert!(g.release("naki", "b1", "notepad"));
557 assert_eq!(g.check("naki", "b1", "notepad", 1_000), Check::Ask);
558 assert!(!g.release("naki", "b1", "notepad"));
559 }
560
561 #[test]
562 fn asking_twice_about_one_app_is_one_prompt_and_both_hear_the_answer() {
563 let mut g = Gate::default();
564 let mut a = g.ask(req("r1", "naki", "notepad", "b1"));
565 let mut b = g.ask(req("r2", "naki", "notepad", "b1"));
566 assert_eq!(g.event(0).requests.len(), 1);
567 g.answer("r1", Choice::Timed, 0, 30).unwrap();
568 assert_eq!(a.try_recv().unwrap(), Choice::Timed);
569 assert_eq!(b.try_recv().unwrap(), Choice::Timed);
570 }
571
572 #[test]
573 fn an_answered_prompt_cannot_be_answered_again() {
574 let mut g = Gate::default();
575 let _rx = g.ask(req("r1", "naki", "notepad", "b1"));
576 g.answer("r1", Choice::Deny, 0, 30).unwrap();
577 assert!(g.answer("r1", Choice::Timed, 0, 30).is_err());
578 }
579
580 #[test]
581 fn the_event_shows_a_grant_as_driving_only_just_after_an_action() {
582 let mut g = Gate::default();
583 grant(&mut g, Choice::Session, 0);
584 assert!(!g.event(1_000).grants[0].active);
585 g.check("naki", "b1", "notepad", 5_000);
586 assert!(g.event(6_000).grants[0].active);
587 assert!(!g.event(5_000 + DRIVING_SHOWN_MS).grants[0].active);
588 }
589
590 #[test]
591 fn app_names_are_compared_without_path_extension_or_case() {
592 assert_eq!(app_key(r"C:\Program Files\KeePass\KeePass.exe"), "keepass");
593 assert_eq!(app_key("/usr/bin/firefox"), "firefox");
594 assert_eq!(app_key("Notepad.EXE"), "notepad");
595 }
596
597 #[test]
598 fn password_managers_browsers_and_agentmux_are_blocked_by_default() {
599 let none: &[String] = &[];
600 assert!(blocked_reason("KeePass.exe", "", none, none).unwrap().contains("password"));
601 assert!(blocked_reason("chrome.exe", "", none, none).unwrap().contains("Browser tool"));
602 assert!(blocked_reason("agentmux-0.59.35.exe", "", none, none).unwrap().contains("UI tool"));
603 assert!(blocked_reason("consent.exe", "", none, none).unwrap().contains("operating system"));
604 assert!(blocked_reason("notepad.exe", "Untitled - Notepad", none, none).is_none());
605 }
606
607 #[test]
608 fn an_operating_system_prompt_is_recognised_by_its_title() {
609 let none: &[String] = &[];
610 assert!(blocked_reason("somehost.exe", "User Account Control", none, none).is_some());
611 }
612
613 #[test]
614 fn the_user_can_add_to_the_blocklist_by_app_or_by_title() {
615 let added = vec!["Photoshop".to_string(), "bank".to_string()];
616 let none: &[String] = &[];
617 assert!(blocked_reason("photoshop.exe", "x", &added, none).unwrap().contains("blocklist"));
618 assert!(blocked_reason("notepad.exe", "My Bank - Notepad", &added, none).is_some());
619 assert!(blocked_reason("notepad.exe", "notes", &added, none).is_none());
620 }
621
622 #[test]
623 fn the_user_can_take_a_default_off_the_list() {
624 let none: &[String] = &[];
625 let allowed = vec!["chrome".to_string()];
626 assert!(blocked_reason("chrome.exe", "", none, &allowed).is_none());
627 let allowed = vec!["agentmux".to_string()];
629 assert!(blocked_reason("agentmux.exe", "", none, &allowed).is_some());
630 }
631}